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
MehVahdJukaar/Supplementaries
1,946
common/src/main/java/net/mehvahdjukaar/supplementaries/common/events/overrides/FDStickBehavior.java
package net.mehvahdjukaar.supplementaries.common.events.overrides; import net.mehvahdjukaar.supplementaries.configs.CommonConfigs; import net.mehvahdjukaar.supplementaries.integration.CompatHandler; import net.mehvahdjukaar.supplementaries.integration.CompatObjects; import net.mehvahdjukaar.supplementaries.integration.FarmersDelightCompat; import net.minecraft.core.BlockPos; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.phys.BlockHitResult; class FDStickBehavior implements BlockUseBehavior { @Override public boolean altersWorld() { return true; } @Override public boolean isEnabled() { return CommonConfigs.Tweaks.PLACEABLE_STICKS.get() && CompatHandler.FARMERS_DELIGHT; } @Override public boolean appliesToBlock(Block block) { return block == CompatObjects.TOMATOES.get(); } @Override public InteractionResult tryPerformingAction(BlockState state, BlockPos pos, Level level, Player player, InteractionHand hand, ItemStack stack, BlockHitResult hit) { if (stack.getItem() == Items.STICK) { var tomato = FarmersDelightCompat.getStickTomato(); if (tomato != null) { return InteractEventsHandler.replaceSimilarBlock(tomato, player, stack, pos, level, state, SoundType.WOOD, BlockStateProperties.AGE_3); } } return InteractionResult.PASS; } }
412
0.668492
1
0.668492
game-dev
MEDIA
0.999479
game-dev
0.895106
1
0.895106
Mauler125/r5sdk
1,075
src/public/tier1/tier1.h
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// // // Purpose: A higher level link library for general use in the game and tools. // //===========================================================================// #ifndef TIER1_H #define TIER1_H #include "appframework/IAppSystem.h" //----------------------------------------------------------------------------- // Helper empty implementation of an IAppSystem for tier2 libraries //----------------------------------------------------------------------------- template< class IInterface, int ConVarFlag = 0 > class CTier1AppSystem : public CTier0AppSystem< IInterface > { typedef CTier0AppSystem< IInterface > BaseClass; public: virtual bool Connect( const CreateInterfaceFn factory ) { return true; }; virtual void Disconnect() {}; virtual void* QueryInterface(const char* const pInterfaceName) { return NULL; }; virtual InitReturnVal_t Init() { return INIT_OK; }; virtual void Shutdown() {}; virtual const AppSystemInfo_t* GetDependencies() { return NULL; } }; #endif // TIER1_H
412
0.958315
1
0.958315
game-dev
MEDIA
0.722
game-dev
0.818043
1
0.818043
jerry08/Anikin
1,435
Anikin/Utils/Extensions/EnumExtensions.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; namespace Anikin.Utils.Extensions; public static class EnumExtensions { public static TAttribute? GetAttribute<TAttribute>(this Enum value) where TAttribute : Attribute => value .GetType() .GetMember(value.ToString()) .FirstOrDefault() ?.GetCustomAttribute<TAttribute>(); public static string ToDescription(this Enum value) { var attribute = GetAttributes<DescriptionAttribute>(value).SingleOrDefault(); return attribute?.Description ?? value.ToString(); } private static List<TAttribute> GetAttributes<TAttribute>(Enum value) where TAttribute : Attribute { var list = new List<TAttribute>(); var type = value.GetType(); var fieldInfo = type.GetField(Enum.GetName(type, value) ?? string.Empty); if (fieldInfo is not null) { list.AddRange( (TAttribute[])Attribute.GetCustomAttributes(fieldInfo, typeof(TAttribute)) ); } return list; } public static string GetBestDisplayName(this Enum value) => GetAttribute<DisplayAttribute>(value)?.Name ?? GetAttribute<DescriptionAttribute>(value)?.Description ?? value.ToString(); }
412
0.610159
1
0.610159
game-dev
MEDIA
0.158148
game-dev
0.813665
1
0.813665
HelloFangaming/HelloMarioFramework
3,173
Assets/HelloMarioFramework/Script/Item/FlipPanel.cs
/* * Copyright (c) 2024 Hello Fangaming * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. * * */ using System.Collections; using System.Collections.Generic; using UnityEngine; namespace HelloMarioFramework { [RequireComponent(typeof(ButtonHandler))] public class FlipPanel : MonoBehaviour { //Components private AudioSource audioPlayer; private ButtonHandler myButton; //Audio clips [SerializeField] private AudioClip onSFX; [SerializeField] private AudioClip offSFX; [SerializeField] private AudioClip setSFX; [SerializeField] private bool isParent = false; [SerializeField] private FlipPanel[] children; private bool active = false; private bool set = false; private FlipPanel parent = null; private Transform[] panels; void Start() { audioPlayer = gameObject.AddComponent<AudioSource>(); myButton = GetComponent<ButtonHandler>(); if (isParent) { foreach (FlipPanel panel in children) panel.parent = this; } panels = new Transform[] { transform.GetChild(0), transform.GetChild(1), transform.GetChild(2) }; } void OnTriggerEnter(Collider collision) { if (!set && collision.attachedRigidbody != null && !collision.attachedRigidbody.isKinematic && !collision.isTrigger) { active = !active; panels[0].gameObject.SetActive(!active); panels[1].gameObject.SetActive(active); if (active) { audioPlayer.PlayOneShot(onSFX); PanelCheck(); } else audioPlayer.PlayOneShot(offSFX); } } public bool IsActive() { return active; } public void PanelCheck() { if (isParent) { if (active) { bool b = false; for (int i = 0; i < children.Length; i++) { if (!children[i].IsActive()) b = true; } if (!b) { audioPlayer.PlayOneShot(setSFX); myButton.SetActive(true); PanelComplete(); foreach (FlipPanel panel in children) panel.PanelComplete(); } } } else parent.PanelCheck(); } public void PanelComplete() { set = true; panels[1].gameObject.SetActive(false); panels[2].gameObject.SetActive(true); } void OnDrawGizmos() { if (isParent) Gizmos.DrawIcon(transform.position, "Exclamation.png", true); } } }
412
0.829128
1
0.829128
game-dev
MEDIA
0.931705
game-dev
0.941149
1
0.941149
CYBUTEK/KerbalEngineer
3,040
KerbalEngineer/Flight/Readouts/Vessel/SuicideBurnProcessor.cs
// // Kerbal Engineer Redux // // Copyright (C) 2014 CYBUTEK // // 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/>. // namespace KerbalEngineer.Flight.Readouts.Vessel { using System; public class SuicideBurnProcessor : IUpdatable, IUpdateRequest { private static readonly SuicideBurnProcessor s_Instance = new SuicideBurnProcessor(); private double m_Acceleration; private double m_Gravity; private double m_RadarAltitude; public static double Altitude { get; private set; } public static double DeltaV { get; private set; } public static double Distance { get; private set; } public static SuicideBurnProcessor Instance { get { return s_Instance; } } public static bool ShowDetails { get; set; } public void Update() { if (FlightGlobals.currentMainBody == null || FlightGlobals.ActiveVessel == null || SimulationProcessor.LastStage == null || FlightGlobals.ship_orbit.PeA >= 0.0 || !SimulationProcessor.ShowDetails) { ShowDetails = false; return; } m_Gravity = FlightGlobals.currentMainBody.gravParameter / Math.Pow(FlightGlobals.currentMainBody.Radius, 2.0); m_Acceleration = SimulationProcessor.LastStage.thrust / SimulationProcessor.LastStage.totalMass; m_RadarAltitude = FlightGlobals.ActiveVessel.terrainAltitude > 0.0 ? FlightGlobals.ship_altitude - FlightGlobals.ActiveVessel.terrainAltitude : FlightGlobals.ship_altitude; DeltaV = Math.Sqrt((2 * m_Gravity * m_RadarAltitude) + Math.Pow(FlightGlobals.ship_verticalSpeed, 2.0)); Altitude = Math.Pow(DeltaV, 2.0) / (2.0 * m_Acceleration); Distance = m_RadarAltitude - Altitude; ShowDetails = !double.IsInfinity(Distance); } public bool UpdateRequested { get; set; } public static void RequestUpdate() { s_Instance.UpdateRequested = true; SimulationProcessor.RequestUpdate(); } public static void Reset() { FlightEngineerCore.Instance.AddUpdatable(SimulationProcessor.Instance); FlightEngineerCore.Instance.AddUpdatable(s_Instance); } } }
412
0.770669
1
0.770669
game-dev
MEDIA
0.945045
game-dev
0.820967
1
0.820967
HikeGame/2moons-2.0
2,157
includes/classes/missions/MissionCaseFoundDM.class.php
<?php /** * 2Moons * by Jan-Otto Kröpke 2009-2016 * * For the full copyright and license information, please view the LICENSE * * @package 2Moons * @author Jan-Otto Kröpke <slaver7@gmail.com> * @copyright 2009 Lucky * @copyright 2016 Jan-Otto Kröpke <slaver7@gmail.com> * @licence MIT * @version 1.8.0 * @link https://github.com/jkroepke/2Moons */ class MissionCaseFoundDM extends MissionFunctions implements Mission { const CHANCE = 30; const CHANCE_SHIP = 0.25; const MIN_FOUND = 423; const MAX_FOUND = 1278; const MAX_CHANCE = 50; function __construct($Fleet) { $this->_fleet = $Fleet; } function TargetEvent() { $this->setState(FLEET_HOLD); $this->SaveFleet(); } function EndStayEvent() { $LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']); $chance = mt_rand(0, 100); if($chance <= min(self::MAX_CHANCE, (self::CHANCE + $this->_fleet['fleet_amount'] * self::CHANCE_SHIP))) { $FoundDark = mt_rand(self::MIN_FOUND, self::MAX_FOUND); $this->UpdateFleet('fleet_resource_darkmatter', $FoundDark); $Message = $LNG['sys_expe_found_dm_'.mt_rand(1, 3).'_'.mt_rand(1, 2).'']; } else { $Message = $LNG['sys_expe_nothing_'.mt_rand(1, 9)]; } $this->setState(FLEET_RETURN); $this->SaveFleet(); PlayerUtil::sendMessage($this->_fleet['fleet_owner'], 0, $LNG['sys_mess_tower'], 15, $LNG['sys_expe_report'], $Message, $this->_fleet['fleet_end_stay'], NULL, 1, $this->_fleet['fleet_universe']); } function ReturnEvent() { $LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']); if($this->_fleet['fleet_resource_darkmatter'] > 0) { $message = sprintf($LNG['sys_expe_back_home_with_dm'], $LNG['tech'][921], pretty_number($this->_fleet['fleet_resource_darkmatter']), $LNG['tech'][921] ); $this->UpdateFleet('fleet_array', '220,0;'); } else { $message = $LNG['sys_expe_back_home_without_dm']; } PlayerUtil::sendMessage($this->_fleet['fleet_owner'], 0, $LNG['sys_mess_tower'], 4, $LNG['sys_mess_fleetback'], $message, $this->_fleet['fleet_end_time'], NULL, 1, $this->_fleet['fleet_universe']); $this->RestoreFleet(); } }
412
0.859514
1
0.859514
game-dev
MEDIA
0.595777
game-dev
0.880167
1
0.880167
deephaven/deephaven-core
3,662
engine/table/src/main/java/io/deephaven/engine/table/impl/ssa/CharSsaChecker.java
// // Copyright (c) 2016-2025 Deephaven Data Labs and Patent Pending // package io.deephaven.engine.table.impl.ssa; import io.deephaven.base.verify.Assert; import io.deephaven.chunk.CharChunk; import io.deephaven.chunk.Chunk; import io.deephaven.chunk.LongChunk; import io.deephaven.chunk.WritableCharChunk; import io.deephaven.chunk.WritableLongChunk; import io.deephaven.chunk.util.hashing.CharChunkEquals; import io.deephaven.chunk.util.hashing.LongChunkEquals; import io.deephaven.engine.rowset.chunkattributes.RowKeys; import io.deephaven.chunk.attributes.Values; import io.deephaven.engine.table.impl.util.ChunkUtils; public class CharSsaChecker implements SsaChecker { static CharSsaChecker INSTANCE = new CharSsaChecker(); private CharSsaChecker() {} // static use only @Override public void checkSsa(SegmentedSortedArray ssa, Chunk<? extends Values> valueChunk, LongChunk<? extends RowKeys> tableIndexChunk) { checkSsa((CharSegmentedSortedArray) ssa, valueChunk.asCharChunk(), tableIndexChunk); } static void checkSsa(CharSegmentedSortedArray ssa, CharChunk<? extends Values> valueChunk, LongChunk<? extends RowKeys> tableIndexChunk) { ssa.validateInternal(); // noinspection unchecked try (final WritableCharChunk<Values> resultChunk = (WritableCharChunk) ssa.asCharChunk(); final WritableLongChunk<RowKeys> indexChunk = ssa.rowKeysChunk()) { Assert.eq(valueChunk.size(), "valueChunk.size()", resultChunk.size(), "resultChunk.size()"); Assert.eq(tableIndexChunk.size(), "tableIndexChunk.size()", indexChunk.size(), "indexChunk.size()"); if (!CharChunkEquals.equalReduce(resultChunk, valueChunk)) { final StringBuilder messageBuilder = new StringBuilder("Values do not match:\n"); messageBuilder.append("Result Values:\n").append(ChunkUtils.dumpChunk(resultChunk)).append("\n"); messageBuilder.append("Table Values:\n").append(ChunkUtils.dumpChunk(valueChunk)).append("\n"); for (int ii = 0; ii < resultChunk.size(); ++ii) { if (!eq(resultChunk.get(ii), valueChunk.get(ii))) { messageBuilder.append("First difference at ").append(ii).append(("\n")); break; } } throw new SsaCheckException(messageBuilder.toString()); } if (!LongChunkEquals.equalReduce(indexChunk, tableIndexChunk)) { final StringBuilder messageBuilder = new StringBuilder("Values do not match:\n"); messageBuilder.append("Result:\n").append(ChunkUtils.dumpChunk(resultChunk)).append("\n"); messageBuilder.append("Values:\n").append(ChunkUtils.dumpChunk(valueChunk)).append("\n"); messageBuilder.append("Result row keys:\n").append(ChunkUtils.dumpChunk(indexChunk)).append("\n"); messageBuilder.append("Table row keys:\n").append(ChunkUtils.dumpChunk(tableIndexChunk)).append("\n"); for (int ii = 0; ii < indexChunk.size(); ++ii) { if (indexChunk.get(ii) != tableIndexChunk.get(ii)) { messageBuilder.append("First difference at ").append(ii).append(("\n")); break; } } throw new SsaCheckException(messageBuilder.toString()); } } } private static boolean eq(char lhs, char rhs) { // region equality function return lhs == rhs; // endregion equality function } }
412
0.89626
1
0.89626
game-dev
MEDIA
0.249041
game-dev
0.736726
1
0.736726
JonasDeM/QuickSave
8,837
QuickSave.Tests/ECSTestsFixture.cs
// Author: Jonas De Maeseneer using System.Collections.Generic; using NUnit.Framework; using QuickSave.Baking; using Unity.Collections; using Unity.Entities; using Unity.Entities.CodeGeneratedJobForEach; using UnityEngine; using UnityEngine.SceneManagement; using Hash128 = Unity.Entities.Hash128; using Object = UnityEngine.Object; namespace QuickSave.Tests { public abstract class EcsTestsFixture { protected World PreviousWorld; protected World World; protected EntityManager EntityManager; protected World BakingWorld; protected EntityManager BakingEntityManager; protected NativeList<BlobAssetReference<BlobArray<QuickSaveArchetypeDataLayout.TypeInfo>>> BlobAssetsToDisposeOnTearDown; protected BlobAssetStore TestBlobAssetStore; [SetUp] public virtual void Setup() { PreviousWorld = World.DefaultGameObjectInjectionWorld; World = World.DefaultGameObjectInjectionWorld = new World("Test World"); EntityManager = World.EntityManager; BakingWorld = new World("Test Baking World"); BakingEntityManager = BakingWorld.EntityManager; QuickSaveSettings.Initialize(); BlobAssetsToDisposeOnTearDown = new NativeList<BlobAssetReference<BlobArray<QuickSaveArchetypeDataLayout.TypeInfo>>>(16, Allocator.Persistent); TestBlobAssetStore = new BlobAssetStore(64); } [TearDown] public virtual void TearDown() { if (EntityManager != default && World.IsCreated) { // Clean up systems before calling CheckInternalConsistency because we might have filters etc // holding on SharedComponentData making checks fail while (World.Systems.Count > 0) { World.DestroySystemManaged(World.Systems[0]); } EntityManager.Debug.CheckInternalConsistency(); World.Dispose(); World = null; World.DefaultGameObjectInjectionWorld = PreviousWorld; PreviousWorld = null; EntityManager = default; } if (BakingEntityManager != default && BakingWorld.IsCreated) { while (BakingWorld.Systems.Count > 0) { BakingWorld.DestroySystemManaged(BakingWorld.Systems[0]); } BakingEntityManager.Debug.CheckInternalConsistency(); BakingWorld.Dispose(); BakingWorld = null; BakingEntityManager = default; } foreach (var rootGameObject in SceneManager.GetActiveScene().GetRootGameObjects()) { Object.DestroyImmediate(rootGameObject); } QuickSaveSettings.CleanUp(); for (int i = 0; i < BlobAssetsToDisposeOnTearDown.Length; i++) { BlobAssetsToDisposeOnTearDown[i].Dispose(); } BlobAssetsToDisposeOnTearDown.Dispose(); TestBlobAssetStore.Dispose(); } protected static QuickSaveSettingsAsset CreateTestSettings(bool groupedJobs = false, bool removeFirst = false, int maxBufferElements = -1) { QuickSaveSettingsAsset settingsAsset = ScriptableObject.CreateInstance<QuickSaveSettingsAsset>(); settingsAsset.AddQuickSaveTypeInEditor(typeof(EcsTestData).FullName); settingsAsset.AddQuickSaveTypeInEditor(typeof(EcsTestFloatData2).FullName); settingsAsset.AddQuickSaveTypeInEditor(typeof(EcsTestData5).FullName); settingsAsset.AddQuickSaveTypeInEditor(typeof(DynamicBufferData1).FullName, maxBufferElements); settingsAsset.AddQuickSaveTypeInEditor(typeof(DynamicBufferData2).FullName, maxBufferElements); settingsAsset.AddQuickSaveTypeInEditor(typeof(DynamicBufferData3).FullName, maxBufferElements); settingsAsset.AddQuickSaveTypeInEditor(typeof(EmptyEcsTestData).FullName); settingsAsset.AddQuickSaveTypeInEditor(typeof(ComponentDataTests.EcsPersistingTestData).FullName); settingsAsset.AddQuickSaveTypeInEditor(typeof(ComponentDataTests.EcsPersistingFloatTestData2).FullName); settingsAsset.AddQuickSaveTypeInEditor(typeof(ComponentDataTests.EcsPersistingTestData5).FullName); settingsAsset.AddQuickSaveTypeInEditor(typeof(BufferDataTests.PersistentDynamicBufferData1).FullName, maxBufferElements); settingsAsset.AddQuickSaveTypeInEditor(typeof(BufferDataTests.PersistentDynamicBufferData2).FullName, maxBufferElements); settingsAsset.AddQuickSaveTypeInEditor(typeof(BufferDataTests.PersistentDynamicBufferData3).FullName, maxBufferElements); settingsAsset.AddQuickSaveTypeInEditor(typeof(EnableDataTests.TestComponent).FullName); settingsAsset.AddQuickSaveTypeInEditor(typeof(EnableDataTests.TestTagComponent).FullName); settingsAsset.AddQuickSaveTypeInEditor(typeof(EnableDataTests.TestBufferComponent).FullName, maxBufferElements); settingsAsset.ForceUseGroupedJobsInEditor = groupedJobs; settingsAsset.ForceUseNonGroupedJobsInBuild = !groupedJobs; if (removeFirst) { settingsAsset.AllQuickSaveTypeInfos.RemoveAt(0); } settingsAsset.QuickSaveArchetypeCollection = ScriptableObject.CreateInstance<QuickSaveArchetypeCollection>(); // Reset it so the new types are initialized QuickSaveSettings.CleanUp(); QuickSaveSettings.Initialize(settingsAsset); return settingsAsset; } // Creates a 'fake' SceneInfoRef for single QuickSaveArchetype with a single Type T to track internal QuickSaveSceneInfoRef CreateFakeSceneInfoRef<T>(int amountEntities) where T : unmanaged { var typeHandle = QuickSaveSettings.GetTypeHandleFromTypeIndex(ComponentType.ReadWrite<T>().TypeIndex); var typeHandleList = new NativeList<QuickSaveTypeHandle>(1, Allocator.Temp) {typeHandle}; var creationInfoList = new NativeList<QuickSaveBakingSystem.QuickSaveArchetypesInSceneCreationInfo>(Allocator.Temp) { new QuickSaveBakingSystem.QuickSaveArchetypesInSceneCreationInfo { AmountEntities = amountEntities, AmountTypeHandles = 1, OffsetInQuickSaveTypeHandlesLookupList = 0 } }; Hash128 sceneGUID = UnityEngine.Hash128.Compute(typeof(T).FullName); return QuickSaveBakingSystem.CreateQuickSaveSceneInfoRef(new List<QuickSaveTypeHandle> {typeHandle}, creationInfoList, typeHandleList, sceneGUID, 0, TestBlobAssetStore); } [DisableAutoCreation] internal partial class TestSystem : SystemBase { protected override void OnUpdate() { } } } public struct EcsTestData : IComponentData { public int Value; public EcsTestData(int value) { this.Value = value; } } public struct EcsTestFloatData2 : IComponentData { public float Value0; public float Value1; public EcsTestFloatData2(float value) { this.Value0 = value; this.Value1 = value; } } public struct EcsTestData5 : IComponentData { public EcsTestData5(int value) { Value0 = value; Value1 = value; Value2 = value; Value3 = value; Value4 = value; } public int Value0; public int Value1; public int Value2; public int Value3; public int Value4; } [InternalBufferCapacity(2)] public struct DynamicBufferData1 : IBufferElementData { public int Value; public override string ToString() { return Value.ToString(); } } public struct DynamicBufferData2 : IBufferElementData { #pragma warning disable 649 public float Value; #pragma warning restore 649 public override string ToString() { return Value.ToString(); } } public struct DynamicBufferData3 : IBufferElementData, IEnableableComponent { public byte Value; public override string ToString() { return Value.ToString(); } } public struct EmptyEcsTestData : IComponentData { } }
412
0.929317
1
0.929317
game-dev
MEDIA
0.713764
game-dev
0.882024
1
0.882024
OwlGamingCommunity/V
2,599
Source/owl_account_system.client/CGUICharacterList.Client.cs
using EntityDatabaseID = System.Int64; internal class GUICharacterList : CEFCore { public GUICharacterList(OnGUILoadedDelegate callbackOnLoad) : base("owl_account_system.client/characters.html", EGUIID.CharacterList, callbackOnLoad) { UIEvents.PreviewCharacter += OnPreviewCharacter; UIEvents.Logout += OnLogout; UIEvents.SetAutoSpawn += OnSetAutoSpawn; UIEvents.OpenTransferAssets += OpenTransferAssets; UIEvents.GotoViewAchievements += GotoViewAchievements; UIEvents.GotoCreateCharacter += OnGotoCreateCharacter; } public override void OnLoad() { } private void OnGotoCreateCharacter() { SetVisible(false, false, false); CharacterSelection.ResetLastCharacterID(); CharacterCreation.Show(CharacterCreation.g_strDefaultName); CharacterSelection.StopMusic(); } private void GotoViewAchievements() { SetVisible(false, false, false); CharacterSelection.ResetLastCharacterID(); AchievementsList.Show(); } private void OnPreviewCharacter(int index) { CharacterSelection.PreviewCharacter(index); } private void OnSetAutoSpawn() { CharacterSelection.OnSetAutoSpawn(); } private void OpenTransferAssets() { CharacterSelection.OpenTransferAssets(); } private void OnLogout() { NetworkEventSender.SendNetworkEvent_RequestLogout(); } public void ClearCharacters() { Execute("ClearCharacters"); } public void AddCharacter(EntityDatabaseID ID, string name, int lastSeenHours, RAGE.Vector3 vecPos, bool dead) { string zoneName = RAGE.Game.Zone.GetNameOfZone(vecPos.X, vecPos.Y, vecPos.Z); string realZoneName = ZoneNameHelper.ZoneNames.ContainsKey(zoneName) ? ZoneNameHelper.ZoneNames[zoneName] : "San Andreas"; // Parse last seen string lastSeen = "Unknown"; if (lastSeenHours < 0) { lastSeen = "Never"; realZoneName = ""; } else if (lastSeenHours < 24) { if (lastSeenHours < 1) { lastSeen = "Less than an hour ago"; } else if (lastSeenHours == 1) { lastSeen = "1 hour ago"; } else { lastSeen = Helpers.FormatString("{0} hours ago", lastSeenHours); } } else if (lastSeenHours >= 24 && lastSeenHours < 48) { lastSeen = "1 day ago"; } else { lastSeen = Helpers.FormatString("{0} days ago", lastSeenHours / 24); } Execute("AddCharacter", ID, name, lastSeen, realZoneName, !dead); } public void CommitCharacters() { Execute("GotoCharacterPage", 0); } public void SetAutoSpawnVisible(bool bVisible) { Execute("SetAutoSpawnVisible", bVisible); } public void SetAutoSpawnText(string strText) { Execute("SetAutoSpawnText", strText); } }
412
0.946459
1
0.946459
game-dev
MEDIA
0.92701
game-dev
0.955678
1
0.955678
refinedmods/refinedstorage
1,656
src/main/java/com/refinedmods/refinedstorage/loottable/ControllerLootFunction.java
package com.refinedmods.refinedstorage.loottable; import com.refinedmods.refinedstorage.RSLootFunctions; import com.refinedmods.refinedstorage.api.network.INetwork; import com.refinedmods.refinedstorage.blockentity.ControllerBlockEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.functions.LootItemFunction; import net.minecraft.world.level.storage.loot.functions.LootItemFunctionType; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.neoforged.neoforge.capabilities.Capabilities; import net.neoforged.neoforge.energy.IEnergyStorage; public class ControllerLootFunction implements LootItemFunction { @Override public LootItemFunctionType getType() { return RSLootFunctions.CONTROLLER; } @Override public ItemStack apply(ItemStack stack, LootContext lootContext) { BlockEntity blockEntity = lootContext.getParamOrNull(LootContextParams.BLOCK_ENTITY); if (blockEntity instanceof ControllerBlockEntity) { INetwork network = ((ControllerBlockEntity) blockEntity).getRemovedNetwork() == null ? ((ControllerBlockEntity) blockEntity).getNetwork() : ((ControllerBlockEntity) blockEntity).getRemovedNetwork(); IEnergyStorage energyStorage = stack.getCapability(Capabilities.EnergyStorage.ITEM); if (energyStorage != null) { energyStorage.receiveEnergy(network.getEnergyStorage().getEnergyStored(), false); } } return stack; } }
412
0.694431
1
0.694431
game-dev
MEDIA
0.996264
game-dev
0.735089
1
0.735089
electronicarts/CnC_Remastered_Collection
42,122
TIBERIANDAWN/AADATA.CPP
// // Copyright 2020 Electronic Arts Inc. // // TiberianDawn.DLL and RedAlert.dll and corresponding source code is free // software: you can redistribute it and/or modify it under the terms of // the GNU General Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // TiberianDawn.DLL and RedAlert.dll and corresponding source code is distributed // in the hope that it will be useful, but with permitted additional restrictions // under Section 7 of the GPL. See the GNU General Public License in LICENSE.TXT // distributed with this program. You should have received a copy of the // GNU General Public License along with permitted additional restrictions // with this program. If not, see https://github.com/electronicarts/CnC_Remastered_Collection /* $Header: F:\projects\c&c\vcs\code\aadata.cpv 2.18 16 Oct 1995 16:49:50 JOE_BOSTIC $ */ /*********************************************************************************************** *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** *********************************************************************************************** * * * Project Name : Command & Conquer * * name in * * File Name : AADATA.CPP * * * * Programmer : Joe L. Bostic * * * * Start Date : July 22, 1994 * * * * Last Update : August 7, 1995 [JLB] * * Determines * *---------------------------------------------------------------------------------------------* * Functions: * * AircraftTypeClass::AircraftTypeClass -- Constructor for aircraft objects. * * AircraftTypeClass::Create_And_Place -- Creates and places aircraft using normal game syste* * AircraftTypeClass::Create_One_Of -- Creates an aircraft object of the appropriate type. * * AircraftTypeClass::Dimensions -- Fetches the graphic dimensions of the aircraft type. * * AircraftTypeClass::Display -- Displays a generic version of the aircraft type. * * AircraftTypeClass::From_Name -- Converts an ASCIIto an aircraft type number. * * AircraftTypeClass::Max_Pips -- Fetches the maximum number of pips allowed. * * AircraftTypeClass::Occupy_List -- Returns with occupation list for landed aircraft. * * AircraftTypeClass::One_Time -- Performs one time initialization of the aircraft type class.* * AircraftTypeClass::Overlap_List -- the overlap list for a landed aircraft. * * AircraftTypeClass::Prep_For_Add -- Prepares the scenario editor for adding an aircraft objec* * AircraftTypeClass::Repair_Cost -- Fetchs the cost per repair step. * * AircraftTypeClass::Repair_Step -- Fetches the number of health points per repair. * * AircraftTypeClass::Who_Can_Build_Me -- Determines which object can build the aircraft obje* * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ #include "function.h" void const * AircraftTypeClass::LRotorData = NULL; void const * AircraftTypeClass::RRotorData = NULL; // A-10 attack plane static AircraftTypeClass const AttackPlane( AIRCRAFT_A10, // What kind of aircraft is this. TXT_A10, // Translated text number for aircraft. "A10", // INI name of aircraft. 99, // Build level. STRUCTF_NONE, // Building prerequisite. false, // Is a leader type? false, // Does it fire a pair of shots in quick succession? false, // Is this a typical transport vehicle? true, // Fixed wing aircraft? false, // Equipped with a rotor? false, // Custom rotor sets for each facing? false, // Can this aircraft land on clear terrain? false, // Can the aircraft be crushed by a tracked vehicle? true, // Is it invisible on radar? false, // Can the player select it so as to give it orders? true, // Can it be assigned as a target for attack. false, // Is it insignificant (won't be announced)? false, // Is it immune to normal combat damage? false, // Theater specific graphic image? false, // Can it be repaired in a repair facility? false, // Can the player construct or order this unit? true, // Is there a crew inside? 3, // Number of shots it has (default). 60, // The strength of this unit. 0, // The range that it reveals terrain around itself. 800, // Credit cost to construct. 0, // The scenario this becomes available. 10,1, // Risk, reward when calculating AI. HOUSEF_MULTI1| HOUSEF_MULTI2| HOUSEF_MULTI3| HOUSEF_MULTI4| HOUSEF_MULTI5| HOUSEF_MULTI6| HOUSEF_JP| HOUSEF_GOOD| HOUSEF_BAD, // Who can own this aircraft type. WEAPON_NAPALM,WEAPON_NONE, ARMOR_ALUMINUM, // Armor type of this aircraft. MPH_FAST, // Maximum speed of aircraft. 5, // Rate of turn. MISSION_HUNT // Default mission for aircraft. ); // Transport helicopter. static AircraftTypeClass const TransportHeli( AIRCRAFT_TRANSPORT, // What kind of aircraft is this. TXT_TRANS, // Translated text number for aircraft. "TRAN", // INI name of aircraft. 6, // Build level. STRUCTF_HELIPAD, // Building prerequisite. false, // Is a leader type? false, // Does it fire a pair of shots in quick succession? true, // Is this a typical transport vehicle? false, // Fixed wing aircraft? true, // Equipped with a rotor? true, // Custom rotor sets for each facing? true, // Can this aircraft land on clear terrain? false, // Can the aircraft be crushed by a tracked vehicle? true, // Is it invisible on radar? true, // Can the player select it so as to give it orders? true, // Can it be assigned as a target for attack. false, // Is it insignificant (won't be announced)? false, // Theater specific graphic image? false, // Is it equipped with a combat turret? false, // Can it be repaired in a repair facility? true, // Can the player construct or order this unit? true, // Is there a crew inside? 0, // Number of shots it has (default). 90, // The strength of this unit. 0, // The range that it reveals terrain around itself. 1500, // Credit cost to construct. 98, // The scenario this becomes available. 10,80, // Risk, reward when calculating AI. HOUSEF_MULTI1| HOUSEF_MULTI2| HOUSEF_MULTI3| HOUSEF_MULTI4| HOUSEF_MULTI5| HOUSEF_MULTI6| HOUSEF_JP| HOUSEF_BAD| HOUSEF_GOOD, // Who can own this aircraft type. WEAPON_NONE,WEAPON_NONE, ARMOR_ALUMINUM, // Armor type of this aircraft. MPH_MEDIUM_FAST, // Maximum speed of aircraft. 5, // Rate of turn. MISSION_HUNT // Default mission for aircraft. ); // Apache attach helicopter. static AircraftTypeClass const AttackHeli( AIRCRAFT_HELICOPTER, // What kind of aircraft is this. TXT_HELI, // Translated text number for aircraft. "HELI", // INI name of aircraft. 6, // Build level. STRUCTF_HELIPAD, // Building prerequisite. true, // Is a leader type? true, // Does it fire a pair of shots in quick succession? false, // Is this a typical transport vehicle? false, // Fixed wing aircraft? true, // Equipped with a rotor? false, // Custom rotor sets for each facing? false, // Can this aircraft land on clear terrain? false, // Can the aircraft be crushed by a tracked vehicle? true, // Is it invisible on radar? true, // Can the player select it so as to give it orders? true, // Can it be assigned as a target for attack. false, // Is it insignificant (won't be announced)? false, // Is it immune to normal combat damage? false, // Theater specific graphic image? false, // Can it be repaired in a repair facility? true, // Can the player construct or order this unit? true, // Is there a crew inside? 15, // Number of shots it has (default). 125, // The strength of this unit. 0, // The range that it reveals terrain around itself. 1200, // Credit cost to construct. 10, // The scenario this becomes available. 10,80, // Risk, reward when calculating AI. HOUSEF_MULTI1| HOUSEF_MULTI2| HOUSEF_MULTI3| HOUSEF_MULTI4| HOUSEF_MULTI5| HOUSEF_MULTI6| HOUSEF_JP| HOUSEF_BAD, // Who can own this aircraft type. WEAPON_CHAIN_GUN,WEAPON_NONE, ARMOR_STEEL, // Armor type of this aircraft. MPH_FAST, // Maximum speed of aircraft. 4, // Rate of turn. MISSION_HUNT // Default mission for aircraft. ); // Orca attack helicopter. static AircraftTypeClass const OrcaHeli( AIRCRAFT_ORCA, // What kind of aircraft is this. TXT_ORCA, // Translated text number for aircraft. "ORCA", // INI name of aircraft. 6, // Build level. STRUCTF_HELIPAD, // Building prerequisite. true, // Is a leader type? true, // Does it fire a pair of shots in quick succession? false, // Is this a typical transport vehicle? false, // Fixed wing aircraft? false, // Equipped with a rotor? false, // Custom rotor sets for each facing? false, // Can this aircraft land on clear terrain? false, // Can the aircraft be crushed by a tracked vehicle? true, // Is it invisible on radar? true, // Can the player select it so as to give it orders? true, // Can it be assigned as a target for attack. false, // Is it insignificant (won't be announced)? false, // Is it immune to normal combat damage? false, // Theater specific graphic image? false, // Can it be repaired in a repair facility? true, // Can the player construct or order this unit? true, // Is there a crew inside? 6, // Number of shots it has (default). 125, // The strength of this unit. 0, // The range that it reveals terrain around itself. 1200, // Credit cost to construct. 10, // The scenario this becomes available. 10,80, // Risk, reward when calculating AI. HOUSEF_MULTI1| HOUSEF_MULTI2| HOUSEF_MULTI3| HOUSEF_MULTI4| HOUSEF_MULTI5| HOUSEF_MULTI6| HOUSEF_JP| HOUSEF_GOOD, // Who can own this aircraft type. WEAPON_DRAGON,WEAPON_NONE, ARMOR_STEEL, // Armor type of this aircraft. MPH_FAST, // Maximum speed of aircraft. 4, // Rate of turn. MISSION_HUNT // Default mission for aircraft. ); // C-17 transport plane. static AircraftTypeClass const CargoPlane( AIRCRAFT_CARGO, // What kind of aircraft is this. TXT_C17, // Translated text number for aircraft. "C17", // INI name of aircraft. 99, // Build level. STRUCTF_NONE, // Building prerequisite. false, // Is a leader type? false, // Does it fire a pair of shots in quick succession? true, // Is this a typical transport vehicle? true, // Fixed wing aircraft? false, // Equipped with a rotor? false, // Custom rotor sets for each facing? false, // Can this aircraft land on clear terrain? false, // Can the aircraft be crushed by a tracked vehicle? true, // Is it invisible on radar? false, // Can the player select it so as to give it orders? false, // Can it be assigned as a target for attack. false, // Is it insignificant (won't be announced)? false, // Is it immune to normal combat damage? false, // Theater specific graphic image? false, // Can it be repaired in a repair facility? false, // Can the player construct or order this unit? true, // Is there a crew inside? 0, // Number of shots it has (default). 25, // The strength of this unit. 0, // The range that it reveals terrain around itself. 800, // Credit cost to construct. 0, // The scenario this becomes available. 10,1, // Risk, reward when calculating AI. HOUSEF_MULTI1| HOUSEF_MULTI2| HOUSEF_MULTI3| HOUSEF_MULTI4| HOUSEF_MULTI5| HOUSEF_MULTI6| HOUSEF_JP| HOUSEF_GOOD| HOUSEF_BAD, // Who can own this aircraft type. WEAPON_NONE,WEAPON_NONE, ARMOR_ALUMINUM, // Armor type of this aircraft. MPH_FAST, // Maximum speed of aircraft. 5, // Rate of turn. MISSION_HUNT // Default mission for aircraft. ); AircraftTypeClass const * const AircraftTypeClass::Pointers[AIRCRAFT_COUNT] = { &TransportHeli, &AttackPlane, &AttackHeli, &CargoPlane, &OrcaHeli, }; /*********************************************************************************************** * AircraftTypeClass::AircraftTypeClass -- Constructor for aircraft objects. * * * * This is the constructor for the aircraft object. * * * * INPUT: see below... * * * * OUTPUT: none * * * * WARNINGS: none * * * * HISTORY: * * 07/26/1994 JLB : Created. * *=============================================================================================*/ AircraftTypeClass::AircraftTypeClass( AircraftType airtype, int name, char const *ininame, unsigned char level, long pre, bool is_leader, bool is_twoshooter, bool is_transporter, bool is_fixedwing, bool is_rotorequipped, bool is_rotorcustom, bool is_landable, bool is_crushable, bool is_stealthy, bool is_selectable, bool is_legal_target, bool is_insignificant, bool is_immune, bool is_theater, bool is_repairable, bool is_buildable, bool is_crew, int ammo, unsigned short strength, int sightrange, int cost, int scenario, int risk, int reward, int ownable, WeaponType primary, WeaponType secondary, ArmorType armor, MPHType maxspeed, int rot, MissionType deforder) : TechnoTypeClass(name, ininame, level, pre, is_leader, false, false, is_transporter, false, is_crushable, is_stealthy, is_selectable, is_legal_target, is_insignificant, is_immune, is_theater, is_twoshooter, false, is_repairable, is_buildable, is_crew, ammo, strength, maxspeed, sightrange, cost, scenario, risk, reward, ownable, primary, secondary, armor) { IsRotorEquipped = is_rotorequipped; IsRotorCustom = is_rotorcustom; IsLandable = is_landable; IsFixedWing = is_fixedwing; Type = airtype; ROT = rot; Mission = deforder; } /*********************************************************************************************** * AircraftTypeClass::From_Name -- Converts an ASCII name into an aircraft type number. * * * * This routine is used to convert an ASCII representation of an aircraft into the * * matching aircraft type number. This is used by the scenario INI reader code. * * * * INPUT: name -- Pointer to ASCII name to translate. * * * * OUTPUT: Returns the aircraft type number that matches the ASCII name provided. If no * * match could be found, then AIRCRAFT_NONE is returned. * * * * WARNINGS: none * * * * HISTORY: * * 07/26/1994 JLB : Created. * *=============================================================================================*/ AircraftType AircraftTypeClass::From_Name(char const *name) { if (name) { for (AircraftType classid = AIRCRAFT_FIRST; classid < AIRCRAFT_COUNT; classid++) { if (stricmp(Pointers[classid]->IniName, name) == 0) { return(classid); } } } return(AIRCRAFT_NONE); } /*********************************************************************************************** * AircraftTypeClass::One_Time -- Performs one time initialization of the aircraft type class. * * * * This routine is used to perform the onetime initialization of the aircraft type. This * * includes primarily the shape and other graphic data loading. * * * * INPUT: none * * * * OUTPUT: none * * * * WARNINGS: This goes to disk and also must only be called ONCE. * * * * HISTORY: * * 07/26/1994 JLB : Created. * *=============================================================================================*/ void AircraftTypeClass::One_Time(void) { AircraftType index; for (index = AIRCRAFT_FIRST; index < AIRCRAFT_COUNT; index++) { char fullname[_MAX_FNAME+_MAX_EXT]; AircraftTypeClass const & uclass = As_Reference(index); /* ** Fetch the supporting data files for the unit. */ char buffer[_MAX_FNAME]; if ( Get_Resolution_Factor() ) { sprintf(buffer, "%sICNH", uclass.IniName); } else { sprintf(buffer, "%sICON", uclass.IniName); } _makepath(fullname, NULL, NULL, buffer, ".SHP"); ((void const *&)uclass.CameoData) = MixFileClass::Retrieve(fullname); /* ** Generic shape for all houses load method. */ _makepath(fullname, NULL, NULL, uclass.IniName, ".SHP"); ((void const *&)uclass.ImageData) = MixFileClass::Retrieve(fullname); } LRotorData = MixFileClass::Retrieve("LROTOR.SHP"); RRotorData = MixFileClass::Retrieve("RROTOR.SHP"); } /*********************************************************************************************** * AircraftTypeClass::Create_One_Of -- Creates an aircraft object of the appropriate type. * * * * This routine is used to create an aircraft object that matches the aircraft type. It * * serves as a shortcut to creating an object using the "new" operator and "if" checks. * * * * INPUT: house -- The house owner of the aircraft that is to be created. * * * * OUTPUT: Returns with a pointer to the aircraft created. If the aircraft could not be * * created, then a NULL is returned. * * * * WARNINGS: none * * * * HISTORY: * * 07/26/1994 JLB : Created. * *=============================================================================================*/ ObjectClass * AircraftTypeClass::Create_One_Of(HouseClass * house) const { return(new AircraftClass(Type, house->Class->House)); } #ifdef SCENARIO_EDITOR /*********************************************************************************************** * AircraftTypeClass::Prep_For_Add -- Prepares the scenario editor for adding an aircraft objec* * * * This routine is used by the scenario editor to prepare for the adding operation. It * * builds a list of pointers to object types that can be added. * * * * INPUT: none * * * * OUTPUT: none * * * * WARNINGS: none * * * * HISTORY: * * 07/26/1994 JLB : Created. * *=============================================================================================*/ void AircraftTypeClass::Prep_For_Add(void) { for (AircraftType index = AIRCRAFT_FIRST; index < AIRCRAFT_COUNT; index++) { if (As_Reference(index).Get_Image_Data()) { Map.Add_To_List(&As_Reference(index)); } } } /*********************************************************************************************** * AircraftTypeClass::Display -- Displays a generic version of the aircraft type. * * * * This routine is used by the scenario editor to display a generic version of the object * * type. This is displayed in the object selection dialog box. * * * * INPUT: x,y -- The coordinates to draw the aircraft at (centered). * * * * window -- The window to base the coordinates upon. * * * * house -- The owner of this generic aircraft. * * * * OUTPUT: none * * * * WARNINGS: none * * * * HISTORY: * * 07/26/1994 JLB : Created. * *=============================================================================================*/ void AircraftTypeClass::Display(int x, int y, WindowNumberType window, HousesType house) const { int shape = 0; void const * ptr = Get_Cameo_Data(); if (!ptr) { ptr = Get_Image_Data(); shape = 5; } CC_Draw_Shape(ptr, shape, x, y, window, SHAPE_CENTER|SHAPE_WIN_REL|SHAPE_FADING, HouseClass::As_Pointer(house)->Remap_Table(false, true)); } #endif /*********************************************************************************************** * AircraftTypeClass::Occupy_List -- Returns with occupation list for landed aircraft. * * * * This determines the occupation list for the aircraft (if it was landed). * * * * INPUT: placement -- Is this for placement legality checking only? The normal condition * * is for marking occupation flags. * * * * OUTPUT: Returns with a pointer to a cell offset occupation list for the aircraft. * * * * WARNINGS: This occupation list is only valid if the aircraft is landed. * * * * HISTORY: * * 07/26/1994 JLB : Created. * *=============================================================================================*/ short const * AircraftTypeClass::Occupy_List(bool) const { static short const _list[] = {0, REFRESH_EOL}; return(_list); } /*********************************************************************************************** * AircraftTypeClass::Overlap_List -- Determines the overlap list for a landed aircraft. * * * * This routine figures out the overlap list for the aircraft as if it were landed. * * * * INPUT: none * * * * OUTPUT: Returns with the cell offset overlap list for the aircraft. * * * * WARNINGS: This overlap list is only valid when the aircraft is landed. * * * * HISTORY: * * 07/26/1994 JLB : Created. * *=============================================================================================*/ short const * AircraftTypeClass::Overlap_List(void) const { static short const _list[] = {-(MAP_CELL_W-1), -MAP_CELL_W, -(MAP_CELL_W+1), -1, 1, (MAP_CELL_W-1), MAP_CELL_W, (MAP_CELL_W+1), REFRESH_EOL}; return(_list); } /*********************************************************************************************** * AircraftTypeClass::Who_Can_Build_Me -- Determines which object can build the aircraft objec * * * * Use this routine to determine which object (factory) can build the aircraft. It * * determines this by scanning through the available factories, looking for one that is * * of the proper ownership and is available. * * * * INPUT: intheory -- When true, it doesn't consider if the factory is currently busy. It * * only considers that it is the right type. * * * * legal -- Should building prerequisite legality checks be performed as well? * * For building placements, this is usually false. For sidebar button * * adding, this is usually true. * * * * house -- The house of the desired aircraft to be built. * * * * OUTPUT: Returns with a pointer to the object that can build the aircraft. * * * * WARNINGS: none * * * * HISTORY: * * 11/30/1994 JLB : Created. * *=============================================================================================*/ BuildingClass * AircraftTypeClass::Who_Can_Build_Me(bool , bool legal, HousesType house) const { BuildingClass * anybuilding = NULL; for (int index = 0; index < Buildings.Count(); index++) { BuildingClass * building = Buildings.Ptr(index); if (building && !building->IsInLimbo && building->House->Class->House == house && building->Mission != MISSION_DECONSTRUCTION && ((1L << building->ActLike) & Ownable) && (!legal || building->House->Can_Build(Type, building->ActLike)) && building->Class->ToBuild == RTTI_AIRCRAFTTYPE) { if (building->IsLeader) return(building); anybuilding = building; } } return(anybuilding); } /*********************************************************************************************** * AircraftTypeClass::Repair_Cost -- Fetchs the cost per repair step. * * * * This routine will return the cost for every repair step. * * * * INPUT: none * * * * OUTPUT: Returns with the credit expense for every repair step. * * * * WARNINGS: none * * * * HISTORY: * * 06/26/1995 JLB : Created. * *=============================================================================================*/ int AircraftTypeClass::Repair_Cost(void) const { return(Fixed_To_Cardinal(Cost/(MaxStrength/REPAIR_STEP), REPAIR_PERCENT)); } /*********************************************************************************************** * AircraftTypeClass::Repair_Step -- Fetches the number of health points per repair. * * * * For every repair event, the returned number of health points is acquired. * * * * INPUT: none * * * * OUTPUT: Returns with the number of health points to recover each repair step. * * * * WARNINGS: none * * * * HISTORY: * * 06/26/1995 JLB : Created. * *=============================================================================================*/ int AircraftTypeClass::Repair_Step(void) const { return(REPAIR_STEP); } /*********************************************************************************************** * AircraftTypeClass::Max_Pips -- Fetches the maximum number of pips allowed. * * * * Use this routine to retrieve the maximum pip count allowed for this aircraft. This is * * the maximum number of passengers. * * * * INPUT: none * * * * OUTPUT: Returns with the maximum number of pips for this aircraft. * * * * WARNINGS: none * * * * HISTORY: * * 06/26/1995 JLB : Created. * *=============================================================================================*/ int AircraftTypeClass::Max_Pips(void) const { if (IsTransporter) { return(Max_Passengers()); } else { if (Primary != WEAPON_NONE) { return(5); } } return(0); } /*********************************************************************************************** * AircraftTypeClass::Create_And_Place -- Creates and places aircraft using normal game system * * * * This routine is used to create and place an aircraft through the normal game system. * * Since creation of aircraft in this fashion is prohibited, this routine does nothing. * * * * INPUT: na * * * * OUTPUT: Always returns a failure code (false). * * * * WARNINGS: none * * * * HISTORY: * * 08/07/1995 JLB : Created. * *=============================================================================================*/ bool AircraftTypeClass::Create_And_Place(CELL, HousesType) const { return(false); } /*********************************************************************************************** * ATC::Init -- load up terrain set dependant sidebar icons * * * * * * * * INPUT: theater type * * * * OUTPUT: Nothing * * * * WARNINGS: None * * * * HISTORY: * * 4/25/96 0:33AM ST : Created * *=============================================================================================*/ void AircraftTypeClass::Init(TheaterType theater) { if (theater != LastTheater){ if ( Get_Resolution_Factor() ) { AircraftType index; char buffer[_MAX_FNAME]; char fullname[_MAX_FNAME+_MAX_EXT]; void const * cameo_ptr; for (index = AIRCRAFT_FIRST; index < AIRCRAFT_COUNT; index++) { AircraftTypeClass const & uclass = As_Reference(index); ((void const *&)uclass.CameoData) = NULL; sprintf(buffer, "%.4sICNH", uclass.IniName); _makepath (fullname, NULL, NULL, buffer, Theaters[theater].Suffix); cameo_ptr = MixFileClass::Retrieve(fullname); if (cameo_ptr){ ((void const *&)uclass.CameoData) = cameo_ptr; } } } } } /*********************************************************************************************** * AircraftTypeClass::Dimensions -- Fetches the graphic dimensions of the aircraft type. * * * * This routine will fetch the pixel dimensions of this aircraft type. These dimensions * * are used to control map refresh and select box rendering. * * * * INPUT: width -- Reference to variable that will be filled in with aircraft width. * * * * height -- Reference to variable that will be filled in with aircraft height. * * * * OUTPUT: none * * * * WARNINGS: none * * * * HISTORY: * * 08/07/1995 JLB : Created. * *=============================================================================================*/ void AircraftTypeClass::Dimensions(int &width, int &height) const { width = 21; height = 20; } RTTIType AircraftTypeClass::What_Am_I(void) const {return RTTI_AIRCRAFTTYPE;};
412
0.725144
1
0.725144
game-dev
MEDIA
0.896112
game-dev
0.749896
1
0.749896
magefree/mage
1,284
Mage/src/main/java/mage/abilities/common/BecomesPlottedSourceTriggeredAbility.java
package mage.abilities.common; import mage.abilities.TriggeredAbilityImpl; import mage.abilities.effects.Effect; import mage.constants.Zone; import mage.game.Game; import mage.game.events.GameEvent; /** * @author Susucr */ public class BecomesPlottedSourceTriggeredAbility extends TriggeredAbilityImpl { public BecomesPlottedSourceTriggeredAbility(Effect effect, boolean optional) { super(Zone.EXILED, effect, optional); setTriggerPhrase("When {this} becomes plotted, "); this.withRuleTextReplacement(true); } public BecomesPlottedSourceTriggeredAbility(Effect effect) { this(effect, false); } protected BecomesPlottedSourceTriggeredAbility(final BecomesPlottedSourceTriggeredAbility ability) { super(ability); } @Override public BecomesPlottedSourceTriggeredAbility copy() { return new BecomesPlottedSourceTriggeredAbility(this); } @Override public boolean checkEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.BECOME_PLOTTED; } @Override public boolean checkTrigger(GameEvent event, Game game) { if (event.getTargetId().equals(this.getSourceId())) { return true; } return false; } }
412
0.84028
1
0.84028
game-dev
MEDIA
0.921034
game-dev
0.911507
1
0.911507
AlessioGr/NotQuests
4,626
paper/src/main/java/rocks/gravili/notquests/paper/structs/variables/ConditionVariable.java
/* * NotQuests - A Questing plugin for Minecraft Servers * Copyright (C) 2022 Alessio Gravili * * 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 rocks.gravili.notquests.paper.structs.variables; import cloud.commandframework.arguments.standard.StringArgument; import java.util.ArrayList; import java.util.List; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import redempt.crunch.CompiledExpression; import redempt.crunch.Crunch; import redempt.crunch.functional.EvaluationEnvironment; import rocks.gravili.notquests.paper.NotQuests; import rocks.gravili.notquests.paper.structs.QuestPlayer; public class ConditionVariable extends Variable<Boolean> { private final EvaluationEnvironment env = new EvaluationEnvironment(); Variable<?> cachedVariable = null; private CompiledExpression exp; private int variableCounter = 0; private Player playerToEvaluate = null; private QuestPlayer questPlayerToEvaluate = null; public ConditionVariable(NotQuests main) { super(main); addRequiredString( StringArgument.<CommandSender>newBuilder("Conditions") .withSuggestionsProvider( (context, lastString) -> { final List<String> allArgs = context.getRawInput(); main.getUtilManager() .sendFancyCommandCompletion( context.getSender(), allArgs.toArray(new String[0]), "[Conditions(s) expression]", "[...]"); ArrayList<String> suggestions = new ArrayList<>(); for (String conditionIdentifier : main.getConditionsYMLManager().getConditionsAndIdentifiers().keySet()) { if (lastString.endsWith(conditionIdentifier)) { suggestions.add(lastString + "&"); suggestions.add(lastString + "|"); } else { suggestions.add(conditionIdentifier); } } return suggestions; }) .single() .build()); } public final String getExpression() { return getRequiredStringValue("Conditions"); } @Override public Boolean getValueInternally(QuestPlayer questPlayer, Object... objects) { this.playerToEvaluate = questPlayer.getPlayer(); this.questPlayerToEvaluate = questPlayer; initializeExpressionAndCachedVariable(); return exp.evaluate() >= 0.98d; } public final String getExpressionAndGenerateEnv(String expressions) { boolean foundOne = false; for (final String conditionIdentifier : main.getConditionsYMLManager().getConditionsAndIdentifiers().keySet()) { if (!expressions.contains(conditionIdentifier)) { continue; } foundOne = true; variableCounter++; expressions = expressions.replace(conditionIdentifier, "var" + variableCounter); env.addLazyVariable( "var" + variableCounter, () -> main.getConditionsYMLManager() .getCondition(conditionIdentifier) .check(questPlayerToEvaluate) .fulfilled() ? 1 : 0); } if (!foundOne) { return expressions; } return getExpressionAndGenerateEnv(expressions); } public void initializeExpressionAndCachedVariable() { if (exp == null) { String expression = getExpressionAndGenerateEnv(getExpression()); exp = Crunch.compileExpression(expression, env); } } @Override public boolean setValueInternally(Boolean newValue, QuestPlayer questPlayer, Object... objects) { return false; } @Override public List<String> getPossibleValues(QuestPlayer questPlayer, Object... objects) { return null; } @Override public String getPlural() { return "Conditions"; } @Override public String getSingular() { return "Condition"; } }
412
0.933631
1
0.933631
game-dev
MEDIA
0.916021
game-dev
0.957961
1
0.957961
MatterHackers/agg-sharp
4,915
geometry3Sharp/mesh/FaceGroupUtil.cs
using System; using System.Collections.Generic; namespace g3 { public static class FaceGroupUtil { /// <summary> /// Set group ID of all triangles in mesh /// </summary> public static void SetGroupID(DMesh3 mesh, int to) { if (mesh.HasTriangleGroups == false) { return; } foreach (int tid in mesh.TriangleIndices()) { mesh.SetTriangleGroup(tid, to); } } /// <summary> /// Set group id of subset of triangles in mesh /// </summary> public static void SetGroupID(DMesh3 mesh, IEnumerable<int> triangles, int to) { if (mesh.HasTriangleGroups == false) { return; } foreach (int tid in triangles) { mesh.SetTriangleGroup(tid, to); } } /// <summary> /// replace group id in mesh /// </summary> public static void SetGroupToGroup(DMesh3 mesh, int from, int to) { if (mesh.HasTriangleGroups == false) { return; } int NT = mesh.MaxTriangleID; for (int tid = 0; tid < NT; ++tid) { if (mesh.IsTriangle(tid)) { int gid = mesh.GetTriangleGroup(tid); if (gid == from) { mesh.SetTriangleGroup(tid, to); } } } } /// <summary> /// find the set of group ids used in mesh /// </summary> public static HashSet<int> FindAllGroups(DMesh3 mesh) { var Groups = new HashSet<int>(); if (mesh.HasTriangleGroups) { int NT = mesh.MaxTriangleID; for (int tid = 0; tid < NT; ++tid) { if (mesh.IsTriangle(tid)) { int gid = mesh.GetTriangleGroup(tid); Groups.Add(gid); } } } return Groups; } /// <summary> /// count number of tris in each group in mesh /// returned pairs are [group_id, tri_count] /// </summary> public static SparseList<int> CountAllGroups(DMesh3 mesh) { var GroupCounts = new SparseList<int>(mesh.MaxGroupID, 0, 0); if (mesh.HasTriangleGroups) { int NT = mesh.MaxTriangleID; for (int tid = 0; tid < NT; ++tid) { if (mesh.IsTriangle(tid)) { int gid = mesh.GetTriangleGroup(tid); GroupCounts[gid] = GroupCounts[gid] + 1; } } } return GroupCounts; } /// <summary> /// collect triangles by group id. Returns array of triangle lists (stored as arrays). /// This requires 2 passes over mesh, but each pass is linear /// </summary> public static int[][] FindTriangleSetsByGroup(DMesh3 mesh, int ignoreGID = int.MinValue) { if (!mesh.HasTriangleGroups) { return new int[0][]; } // find # of groups and triangle count for each SparseList<int> counts = CountAllGroups(mesh); var GroupIDs = new List<int>(); foreach (var idxval in counts.Values()) { if (idxval.Key != ignoreGID && idxval.Value > 0) { GroupIDs.Add(idxval.Key); } } GroupIDs.Sort(); // might as well sort ascending... var groupMap = new SparseList<int>(mesh.MaxGroupID, GroupIDs.Count, -1); // allocate sets int[][] sets = new int[GroupIDs.Count][]; int[] counters = new int[GroupIDs.Count]; for (int i = 0; i < GroupIDs.Count; ++i) { int gid = GroupIDs[i]; sets[i] = new int[counts[gid]]; counters[i] = 0; groupMap[gid] = i; } // accumulate triangles int NT = mesh.MaxTriangleID; for (int tid = 0; tid < NT; ++tid) { if (mesh.IsTriangle(tid)) { int gid = mesh.GetTriangleGroup(tid); int i = groupMap[gid]; if (i >= 0) { int k = counters[i]++; sets[i][k] = tid; } } } return sets; } /// <summary> /// find list of triangles in mesh with specific group id /// </summary> public static List<int> FindTrianglesByGroup(IMesh mesh, int findGroupID) { var tris = new List<int>(); if (mesh.HasTriangleGroups == false) { return tris; } foreach (int tid in mesh.TriangleIndices()) { if (mesh.GetTriangleGroup(tid) == findGroupID) { tris.Add(tid); } } return tris; } /// <summary> /// split input mesh into submeshes based on group ID /// **does not** separate disconnected components w/ same group ID /// </summary> public static DMesh3[] SeparateMeshByGroups(DMesh3 mesh, out int[] groupIDs) { var meshes = new Dictionary<int, List<int>>(); foreach (int tid in mesh.TriangleIndices()) { int gid = mesh.GetTriangleGroup(tid); List<int> tris; if (meshes.TryGetValue(gid, out tris) == false) { tris = new List<int>(); meshes[gid] = tris; } tris.Add(tid); } var result = new DMesh3[meshes.Count]; groupIDs = new int[meshes.Count]; int k = 0; foreach (var pair in meshes) { groupIDs[k] = pair.Key; List<int> tri_list = pair.Value; result[k++] = DSubmesh3.QuickSubmesh(mesh, tri_list); } return result; } public static DMesh3[] SeparateMeshByGroups(DMesh3 mesh) { int[] ids; return SeparateMeshByGroups(mesh, out ids); } } }
412
0.892512
1
0.892512
game-dev
MEDIA
0.768497
game-dev
0.974011
1
0.974011
spbooks/html5games1
1,404
ch08/13-wall-jump/src/entities/Totem.js
import pop from "../../pop/index.js"; const { entity, Texture, TileSprite, math, State } = pop; import Bullet from "./Bullet.js"; const texture = new Texture("res/images/bravedigger-tiles.png"); class Totem extends TileSprite { constructor(target, onFire) { super(texture, 48, 48); this.type = "Totem"; this.frame.x = 2; this.frame.y = 1; this.target = target; this.onFire = onFire; this.fireIn = 0; this.state = new State("IDLE"); this.hp = 8; } fireAtTarget() { const { target, onFire } = this; const totemPos = entity.center(this); const targetPos = entity.center(target); const angle = math.angle(targetPos, totemPos); const x = Math.cos(angle); const y = Math.sin(angle); const bullet = new Bullet({ x, y }, 300); bullet.pos.x = totemPos.x - bullet.w / 2; bullet.pos.y = totemPos.y - bullet.h / 2; onFire(bullet); } update(dt, t) { const { state, frame } = this; switch (state.get()) { case "IDLE": if (state.first) { frame.x = 2; } if (math.randOneIn(250)) { state.set("WINDUP"); } break; case "WINDUP": frame.x = [1, 0][((t / 0.1) | 0) % 2]; if (state.time > 1) { this.fireAtTarget(); state.set("IDLE"); } break; } state.update(dt); } } export default Totem;
412
0.829039
1
0.829039
game-dev
MEDIA
0.959474
game-dev
0.885163
1
0.885163
ck2rpg/ck2rpg.github.io
11,369
js/mapgen/masking.js
//modding rivers: https://forum.paradoxplaza.com/forum/threads/how-to-mod-rivers-navigable-rivers-and-lakes.1478521/ function setMasks() { for (let i = 0; i < world.height; i++) { for (let j = 0; j < world.width; j++) { let cell = xy(j, i); assignMasks(cell) } } } function assignMasks(cell) { //need to convert from percentages to actual - do we want for individual pixels or just cells? Will blur sort it out for us? let n = noise(cell.x, cell.y) //NOTE: THIS FUNCTION NEEDS TO BE MADE CONSISTENT WITH TERRAIN GENERATION AT createProvinceTerrain() function! let remaining = 100; let el = cell.elevation; if (cell.terrain === "floodplains") { cell.floodplains_01_mask = 100 } else if (cell.terrain === "wetlands") { cell.wetlands_02_mask = 100 } else if (cell.terrain === "taiga") { if (n < 0.2 || n > 0.8) { cell.forest_pine_01_mask = 100; } else { cell.northern_plains_01_mask = getRandomInt(30, 50); remaining -= cell.northern_plains_01_mask; cell.plains_01_noisy_mask = getRandomInt(15, remaining); remaining -= cell.plains_01_noisy_mask cell.plains_01_rough_mask = getRandomInt(15, remaining); remaining -= cell.plains_01_rough_mask cell.plains_01_mask = getRandomInt(0, remaining); remaining -= cell.plains_01_mask if (remaining > 0) { cell.plains_01_noisy_mask += remaining } remaining = 0; } } else if (cell.terrain === "hills" && cell.climateCategory === "cold") { cell.hills_01_rocks_mask = 50 cell.snow_mask = 50 remaining = 0; } else if (cell.terrain === "mountains") { if (el > limits.mountains.snowLine) { cell.mountain_02_c_snow_mask = getRandomInt(40, 70); remaining -= cell.mountain_02_c_snow_mask; cell.mountain_02_mask = remaining; remaining = 0; } else { cell.mountain_02_mask = getRandomInt(1, 70); remaining -= cell.mountain_02_mask; cell.mountain_02_c_mask = remaining; remaining = 0; } } else if (n < 0.2 && cell.maskMarked && !cell.desert) { cell.wetlands_02_mask = 100 } else if (cell.terrain === "sea") { //ocean - limit was 15 before (or 10?) cell.beach_02_mask = 80; cell.desert_02_mask = 20; remaining = 0; } else if (cell.terrain === "farmlands") { cell.farmland_01_mask = 100 remaining = 0; } else if (cell.floodplainPotential) { cell.floodplains_01_mask = 100 remaining = 0; } else if (cell.terrain === "jungle") { if (n < 0.3) { cell.forest_jungle_01_mask = getRandomInt(30, 50); remaining -= cell.forest_jungle_01_mask cell.medi_grass_02_mask = getRandomInt(30, 50); remaining -= cell.medi_grass_02_mask; cell.hills_01_rocks_mask = remaining remaining = 0; } else { cell.medi_grass_02_mask = getRandomInt(60, 80); remaining -= cell.medi_grass_02_mask; cell.hills_01_rocks_mask = remaining remaining = 0; } } else if (cell.terrain === "desert") { if (n < 0.1) { cell.desert_01_mask = 100 remaining = 0; } else if (n < 0.85) { cell.desert_wavy_01_mask = getRandomInt(38, 65) remaining -= cell.desert_wavy_01_mask; cell.desert_wavy_01_larger_mask = getRandomInt(20, remaining); remaining -= cell.desert_wavy_01_larger_mask; cell.desert_rocky_mask = getRandomInt(0, remaining); remaining -= cell.desert_rocky_mask; cell.drylands_01_mask = getRandomInt(0, remaining); remaining -= cell.drylands_01_mask cell.desert_02_mask = getRandomInt(0, remaining); remaining -= cell.desert_02_mask; if (remaining > 0) { cell.desert_wavy_01_mask += remaining } remaining = 0; } else { cell.desert_rocky_mask = getRandomInt(38, 65); remaining -= cell.desert_rocky_mask; cell.desert_wavy_01_mask = getRandomInt(20, remaining); remaining -= cell.desert_wavy_01_mask; cell.desert_wavy_01_larger_mask = getRandomInt(0, remaining); remaining -= cell.desert_wavy_01_larger_mask; cell.drylands_01_mask = getRandomInt(0, remaining); remaining -= cell.drylands_01_mask cell.desert_02_mask = getRandomInt(0, remaining); remaining -= cell.desert_02_mask; if (remaining > 0) { cell.desert_wavy_01_mask += remaining } remaining = 0; } } else if (cell.terrain === "desert_mountains") { //desert mountains cell.mountain_02_d_desert_mask = getRandomInt(50, 100); remaining -= cell.mountain_02_d_desert_mask; cell.drylands_01_mask = getRandomInt(0, remaining) remaining -= cell.drylands_01_mask; cell.mountain_02_desert_mask = getRandomInt(0, remaining) remaining -= cell.mountain_02_desert_mask; remaining = 0; } else if (cell.terrain === "steppe") { //steppe if (el > limits.mountains.lower) { cell.hills_01_mask = getRandomInt(40, 60); remaining = 100 - cell.hills_01_mask cell.steppe_01_mask = remaining remaining = 0; } else if (limits.mountains.lower - el < 50) { cell.steppe_01_mask = getRandomInt(70, 80); remaining -= cell.steppe_01_mask; cell.steppe_rocks_mask = remaining remaining = 0; } else { cell.steppe_01_mask = getRandomInt(60, 70); remaining = 100 - cell.steppe_01_mask; cell.steppe_rocks_mask = getRandomInt(1, remaining); remaining -= cell.steppe_rocks_mask cell.steppe_bushes_mask = remaining remaining = 0; } } else if (cell.terrain === "drylands" && cell.moisture < 10) { cell.desert_cracked_mask = 100; remaining = 0; } else if (cell.terrain === "drylands") { //drylands cell.drylands_01_mask = 100 remaining = 0; } else if ((cell.climateCategory === "subtropical" || cell.terrain === "desert" || cell.terrain === "drylands") && limits.mountains.lower - el < 50) { //desert hill is still hill terrain but desert hill mask cell.desert_rocky_mask = getRandomInt(38, 65); remaining -= cell.desert_rocky_mask; cell.desert_wavy_01_mask = getRandomInt(20, remaining); remaining -= cell.desert_wavy_01_mask; cell.desert_wavy_01_larger_mask = getRandomInt(0, remaining); remaining -= cell.desert_wavy_01_larger_mask; cell.drylands_01_mask = getRandomInt(0, remaining); remaining -= cell.drylands_01_mask cell.desert_02_mask = getRandomInt(0, remaining); remaining -= cell.desert_02_mask; if (remaining > 0) { cell.desert_wavy_01_mask += remaining } remaining = 0; } else if (cell.terrain === "forest") { if (cell.elevation > 60) { cell.forest_pine_01_mask = 100; remaining = 0; } else { cell.forestfloor_mask = 100; remaining = 0; } } else if (cell.terrain === "hills") { // probably too broad if (cell.climateCategory === "temperate") { //not sure on this one, should be farther north right? cell.northern_hills_01_mask = getRandomInt(40, 70); remaining -= cell.northern_hills_01_mask; cell.medi_grass_02_mask = getRandomInt(1, remaining); remaining -= cell.medi_grass_02_mask; cell.hills_01_rocks_mask = remaining remaining = 0; } else { cell.hills_01_mask = getRandomInt(40, 70); remaining -= cell.hills_01_mask; cell.medi_grass_02_mask = getRandomInt(1, remaining); remaining -= cell.medi_grass_02_mask; cell.hills_01_rocks_mask = remaining remaining = 0; } } else if (cell.terrain === "plains") { //DEFAULT TERRAIN cell.medi_grass_02_mask = getRandomInt(30, 50); remaining -= cell.medi_grass_02_mask; cell.plains_01_noisy_mask = getRandomInt(15, remaining); remaining -= cell.plains_01_noisy_mask cell.plains_01_rough_mask = getRandomInt(15, remaining); remaining -= cell.plains_01_rough_mask cell.plains_01_mask = getRandomInt(0, remaining); remaining -= cell.plains_01_mask if (remaining > 0) { cell.plains_01_noisy_mask += remaining } remaining = 0; } else { let b = biome(cell); if (b === "grass") { //western european plain tppes minus steppe which was too messy/discoloring for our approach if ((cell.y > world.steppeTop || cell.y < world.steppeBottom)) { cell.medi_grass_02_mask = getRandomInt(30, 50); remaining -= cell.medi_grass_02_mask; cell.plains_01_noisy_mask = getRandomInt(15, remaining); remaining -= cell.plains_01_noisy_mask cell.plains_01_rough_mask = getRandomInt(15, remaining); remaining -= cell.plains_01_rough_mask cell.plains_01_mask = getRandomInt(0, remaining); remaining -= cell.plains_01_mask if (remaining > 0) { cell.plains_01_noisy_mask += remaining } remaining = 0; } else { cell.northern_plains_01_mask = getRandomInt(30, 50); remaining -= cell.northern_plains_01_mask; cell.plains_01_noisy_mask = getRandomInt(15, remaining); remaining -= cell.plains_01_noisy_mask cell.plains_01_rough_mask = getRandomInt(15, remaining); remaining -= cell.plains_01_rough_mask cell.plains_01_mask = getRandomInt(0, remaining); remaining -= cell.plains_01_mask if (remaining > 0) { cell.plains_01_noisy_mask += remaining } remaining = 0; } } else if (b === "arctic") { cell.snow_mask = 100; remaining = 0; } else { //DEFAULT TERRAIN cell.medi_grass_02_mask = getRandomInt(30, 50); remaining -= cell.medi_grass_02_mask; cell.plains_01_noisy_mask = getRandomInt(15, remaining); remaining -= cell.plains_01_noisy_mask cell.plains_01_rough_mask = getRandomInt(15, remaining); remaining -= cell.plains_01_rough_mask cell.plains_01_mask = getRandomInt(0, remaining); remaining -= cell.plains_01_mask if (remaining > 0) { cell.plains_01_noisy_mask += remaining } remaining = 0; } } if (remaining > 0) { cell.beach_02_mask = 80; cell.desert_02_mask = 20; } }
412
0.606912
1
0.606912
game-dev
MEDIA
0.978803
game-dev
0.631199
1
0.631199
chraft/c-raft
5,698
Chraft/Entity/Items/Base/ItemHelper.cs
#region C#raft License // This file is part of C#raft. Copyright C#raft Team // // C#raft is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #endregion using System; using System.Collections.Concurrent; using System.Reflection; using System.Collections.Generic; using System.Linq; using System.Text; using Chraft.Entity.Items.Base; using Chraft.Net; using Chraft.PluginSystem.Item; using Chraft.Utilities; using Chraft.Utilities.Blocks; namespace Chraft.Entity.Items { public sealed class ItemHelper { private static ConcurrentDictionary<short, Type> _itemClasses; private static readonly ItemHelper _instance = new ItemHelper(); public static ItemHelper Instance { get { return _instance; } } private ItemHelper() { Init(); } private static void Init() { _itemClasses = new ConcurrentDictionary<short, Type>(); ItemBase item; Type itemClass; short itemId; foreach (Type t in from t in Assembly.GetExecutingAssembly().GetTypes() where t.GetInterfaces().Contains(typeof(IItemInventory)) && !t.IsAbstract select t) { itemClass = t; item = (ItemInventory)itemClass.GetConstructor(Type.EmptyTypes).Invoke(null); itemId = item.Type; _itemClasses.TryAdd(itemId, itemClass); } } public static bool IsVoid(ItemInventory item) { return (item == null || item.Type == -1 || item.Count < 1); } public static bool IsVoid(IItemInventory item) { return (item == null | (item as ItemInventory).Type == -1 || (item as ItemInventory).Count < 1); } public static ItemInventory Void { get { return new ItemVoid(); } } public static ItemInventory GetInstance(BlockData.Blocks blockType) { return GetInstance((short)blockType); } public static ItemInventory GetInstance(BlockData.Items itemType) { return GetInstance((short)itemType); } public static ItemInventory GetInstance(short type) { ItemInventory item; Type itemClass; if (!_itemClasses.TryGetValue(type, out itemClass)) return Void; item = (ItemInventory)itemClass.GetConstructor(Type.EmptyTypes).Invoke(null); return item; } public static ItemInventory GetInstance(PacketReader stream) { ItemInventory item = null; Type itemClass; short type = stream.ReadShort(); sbyte count; short durability; if (type >= 0) { count = stream.ReadSByte(); durability = stream.ReadShort(); if (_itemClasses.TryGetValue(type, out itemClass)) { item = (ItemInventory)itemClass.GetConstructor(Type.EmptyTypes).Invoke(null); item.Count = count; item.Durability = durability; // TODO: Implement extra data read (enchantment) and items //if (durability > 0 || item.IsEnchantable) stream.ReadShort(); } } return item; } public static ItemInventory GetInstance(BigEndianStream stream) { ItemInventory item = Void; Type itemClass; short type = stream.ReadShort(); if (type >= 0) { if (_itemClasses.TryGetValue(type, out itemClass)) { item = (ItemInventory) itemClass.GetConstructor(Type.EmptyTypes).Invoke(null); item.Count = stream.ReadSByte(); item.Durability = stream.ReadShort(); // TODO: Implement extra data read (enchantment) and items //if (item.Durability > 0 || item.IsEnchantable) stream.ReadShort(); } } return item; } public static ItemInventory Parse(string code) { string[] parts = code.Split(':', '#'); string numeric = parts[0]; string count = "1"; string durability = "0"; if (code.Contains(':')) durability = parts[1]; if (code.Contains('#')) count = parts[parts.Length - 1]; //TODO:Dennis make item classes and load them on server startup, before recipe loading short itemId; short.TryParse(numeric, out itemId); var item = GetInstance(itemId); if (IsVoid(item)) return Void; item.Count = sbyte.Parse(count); item.Durability = durability == "*" ? (short) -1 : short.Parse(durability); return item; } } }
412
0.897777
1
0.897777
game-dev
MEDIA
0.606903
game-dev
0.955317
1
0.955317
mixandjam/MarioParty-Board
6,675
Assets/TutorialInfo/Scripts/Editor/ReadmeEditor.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using System; using System.IO; using System.Reflection; [CustomEditor(typeof(Readme))] [InitializeOnLoad] public class ReadmeEditor : Editor { static string s_ShowedReadmeSessionStateName = "ReadmeEditor.showedReadme"; static string s_ReadmeSourceDirectory = "Assets/TutorialInfo"; const float k_Space = 16f; static ReadmeEditor() { EditorApplication.delayCall += SelectReadmeAutomatically; } static void RemoveTutorial() { if (EditorUtility.DisplayDialog("Remove Readme Assets", $"All contents under {s_ReadmeSourceDirectory} will be removed, are you sure you want to proceed?", "Proceed", "Cancel")) { if (Directory.Exists(s_ReadmeSourceDirectory)) { FileUtil.DeleteFileOrDirectory(s_ReadmeSourceDirectory); FileUtil.DeleteFileOrDirectory(s_ReadmeSourceDirectory + ".meta"); } else { Debug.Log($"Could not find the Readme folder at {s_ReadmeSourceDirectory}"); } var readmeAsset = SelectReadme(); if (readmeAsset != null) { var path = AssetDatabase.GetAssetPath(readmeAsset); FileUtil.DeleteFileOrDirectory(path + ".meta"); FileUtil.DeleteFileOrDirectory(path); } AssetDatabase.Refresh(); } } static void SelectReadmeAutomatically() { if (!SessionState.GetBool(s_ShowedReadmeSessionStateName, false)) { var readme = SelectReadme(); SessionState.SetBool(s_ShowedReadmeSessionStateName, true); if (readme && !readme.loadedLayout) { LoadLayout(); readme.loadedLayout = true; } } } static void LoadLayout() { var assembly = typeof(EditorApplication).Assembly; var windowLayoutType = assembly.GetType("UnityEditor.WindowLayout", true); var method = windowLayoutType.GetMethod("LoadWindowLayout", BindingFlags.Public | BindingFlags.Static); method.Invoke(null, new object[] { Path.Combine(Application.dataPath, "TutorialInfo/Layout.wlt"), false }); } static Readme SelectReadme() { var ids = AssetDatabase.FindAssets("Readme t:Readme"); if (ids.Length == 1) { var readmeObject = AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GUIDToAssetPath(ids[0])); Selection.objects = new UnityEngine.Object[] { readmeObject }; return (Readme)readmeObject; } else { Debug.Log("Couldn't find a readme"); return null; } } protected override void OnHeaderGUI() { var readme = (Readme)target; Init(); var iconWidth = Mathf.Min(EditorGUIUtility.currentViewWidth / 3f - 20f, 128f); GUILayout.BeginHorizontal("In BigTitle"); { if (readme.icon != null) { GUILayout.Space(k_Space); GUILayout.Label(readme.icon, GUILayout.Width(iconWidth), GUILayout.Height(iconWidth)); } GUILayout.Space(k_Space); GUILayout.BeginVertical(); { GUILayout.FlexibleSpace(); GUILayout.Label(readme.title, TitleStyle); GUILayout.FlexibleSpace(); } GUILayout.EndVertical(); GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); } public override void OnInspectorGUI() { var readme = (Readme)target; Init(); foreach (var section in readme.sections) { if (!string.IsNullOrEmpty(section.heading)) { GUILayout.Label(section.heading, HeadingStyle); } if (!string.IsNullOrEmpty(section.text)) { GUILayout.Label(section.text, BodyStyle); } if (!string.IsNullOrEmpty(section.linkText)) { if (LinkLabel(new GUIContent(section.linkText))) { Application.OpenURL(section.url); } } GUILayout.Space(k_Space); } if (GUILayout.Button("Remove Readme Assets", ButtonStyle)) { RemoveTutorial(); } } bool m_Initialized; GUIStyle LinkStyle { get { return m_LinkStyle; } } [SerializeField] GUIStyle m_LinkStyle; GUIStyle TitleStyle { get { return m_TitleStyle; } } [SerializeField] GUIStyle m_TitleStyle; GUIStyle HeadingStyle { get { return m_HeadingStyle; } } [SerializeField] GUIStyle m_HeadingStyle; GUIStyle BodyStyle { get { return m_BodyStyle; } } [SerializeField] GUIStyle m_BodyStyle; GUIStyle ButtonStyle { get { return m_ButtonStyle; } } [SerializeField] GUIStyle m_ButtonStyle; void Init() { if (m_Initialized) return; m_BodyStyle = new GUIStyle(EditorStyles.label); m_BodyStyle.wordWrap = true; m_BodyStyle.fontSize = 14; m_BodyStyle.richText = true; m_TitleStyle = new GUIStyle(m_BodyStyle); m_TitleStyle.fontSize = 26; m_HeadingStyle = new GUIStyle(m_BodyStyle); m_HeadingStyle.fontStyle = FontStyle.Bold; m_HeadingStyle.fontSize = 18; m_LinkStyle = new GUIStyle(m_BodyStyle); m_LinkStyle.wordWrap = false; // Match selection color which works nicely for both light and dark skins m_LinkStyle.normal.textColor = new Color(0x00 / 255f, 0x78 / 255f, 0xDA / 255f, 1f); m_LinkStyle.stretchWidth = false; m_ButtonStyle = new GUIStyle(EditorStyles.miniButton); m_ButtonStyle.fontStyle = FontStyle.Bold; m_Initialized = true; } bool LinkLabel(GUIContent label, params GUILayoutOption[] options) { var position = GUILayoutUtility.GetRect(label, LinkStyle, options); Handles.BeginGUI(); Handles.color = LinkStyle.normal.textColor; Handles.DrawLine(new Vector3(position.xMin, position.yMax), new Vector3(position.xMax, position.yMax)); Handles.color = Color.white; Handles.EndGUI(); EditorGUIUtility.AddCursorRect(position, MouseCursor.Link); return GUI.Button(position, label, LinkStyle); } }
412
0.900535
1
0.900535
game-dev
MEDIA
0.777199
game-dev,desktop-app
0.956672
1
0.956672
CyberTianzun/QingTingCheat
8,537
src/fm/qingting/qtradio/fm/TaobaoAgent.java
package fm.qingting.qtradio.fm; import android.content.Context; import android.media.MediaPlayer; import com.taobao.newxp.common.AlimmContext; import com.taobao.newxp.view.audio.MunionAudio; import com.taobao.newxp.view.audio.MunionAudio.OnAudioADClientCallBackListener; import fm.qingting.qtradio.model.InfoManager; import fm.qingting.qtradio.model.Node; import fm.qingting.qtradio.model.RootNode; import fm.qingting.qtradio.model.RootNode.PlayMode; import fm.qingting.qtradio.model.SharedCfg; import fm.qingting.utils.QTMSGManage; import java.lang.reflect.Field; public class TaobaoAgent { private static TaobaoAgent instance; private String AD_IDENTITY = "62831"; private boolean hasLoadedAudio = false; private long hasPlayAdv = 0L; private MunionAudio mAudio; private Context mContext; private MediaPlayer mPlayer; private void _playAD(boolean paramBoolean) { if (this.mAudio != null) { if (!paramBoolean) InfoManager.getInstance().setPlayAdvertisementTime(); if (paramBoolean) mute(); this.mAudio.playAD(); QTMSGManage.getInstance().sendStatistcsMessage("taobao_ad", "play"); } } private void change() { AlimmContext.getAliContext().init(this.mContext); Class localClass = AlimmContext.getAliContext().getAppUtils().getClass(); while (true) { int i; try { Field[] arrayOfField = localClass.getDeclaredFields(); i = 0; if (i < arrayOfField.length) if (arrayOfField[i].getName().equalsIgnoreCase("l")) { Field localField2 = localClass.getDeclaredField(arrayOfField[i].getName()); localField2.setAccessible(true); String str4 = String.valueOf(localField2.get(AlimmContext.getAliContext().getAppUtils())); int n = SharedCfg.getInstance().getTaoBaoChange(); if (n == 0) return; int i1 = SharedCfg.getInstance().getBootstrapCnt() % n; if (str4.length() > i1) { char c1 = str4.charAt(0); char c2 = str4.charAt(i1); changeStr(str4, String.valueOf(c2) + String.valueOf(c1) + str4.substring(2)); } } else if (arrayOfField[i].getName().equalsIgnoreCase("n")) { Field localField1 = localClass.getDeclaredField(arrayOfField[i].getName()); localField1.setAccessible(true); String str1 = String.valueOf(localField1.get(AlimmContext.getAliContext().getAppUtils())); int j = SharedCfg.getInstance().getTaoBaoChange(); if (j != 0) { int k = SharedCfg.getInstance().getBootstrapCnt() % j; if (str1.length() <= k) break label394; String[] arrayOfString = str1.split(":"); if (arrayOfString != null) { String str2 = ""; if (k >= arrayOfString.length) break label400; str2 = arrayOfString[k]; break label400; if (m < arrayOfString.length) { if (m == k) break label406; String str3 = str2 + ":"; str2 = str3 + arrayOfString[m]; break label406; } if ((str2 == null) || (str2.equalsIgnoreCase(""))) break label394; changeStr(str1, str2); } } } } catch (Exception localException) { } return; label394: i++; continue; label400: int m = 0; continue; label406: m++; } } private void changeStr(String paramString1, String paramString2) { Class localClass = paramString1.getClass(); try { Field localField1 = localClass.getDeclaredField("value"); Field localField2 = localClass.getDeclaredField("count"); localField2.setAccessible(true); localField1.setAccessible(true); char[] arrayOfChar = paramString2.toCharArray(); localField2.set(paramString1, Integer.valueOf(arrayOfChar.length)); localField1.set(paramString1, arrayOfChar); return; } catch (Exception localException) { localException.printStackTrace(); } } public static TaobaoAgent getInstance() { try { if (instance == null) instance = new TaobaoAgent(); TaobaoAgent localTaobaoAgent = instance; return localTaobaoAgent; } finally { } } private void getPlayer() { Class localClass = this.mAudio.getClass(); try { Field[] arrayOfField = localClass.getDeclaredFields(); for (int i = 0; ; i++) if (i < arrayOfField.length) { Field localField = localClass.getDeclaredField(arrayOfField[i].getName()); localField.setAccessible(true); Object localObject = localField.get(this.mAudio); if ((localObject instanceof MediaPlayer)) this.mPlayer = ((MediaPlayer)localObject); } else { return; } } catch (Exception localException) { localException.printStackTrace(); } } private void log(String paramString) { } private void mute() { try { getPlayer(); if (this.mPlayer != null) this.mPlayer.setVolume(0.0F, 0.0F); return; } catch (Exception localException) { localException.printStackTrace(); } } private void onHandlePlayFinished() { Node localNode = InfoManager.getInstance().root().getCurrentPlayingNode(); InfoManager.getInstance().root().setPlayMode(); PlayerAgent.getInstance().play(localNode, false); loadAd(); } public boolean hasLoadedAdv() { return this.hasLoadedAudio; } public void init(Context paramContext, boolean paramBoolean) { this.mContext = paramContext; this.mAudio = new MunionAudio(paramContext); if (paramBoolean) change(); this.mAudio.setOnAudioADClientCallBackListener(new MunionAudio.OnAudioADClientCallBackListener() { public void onDidPause() { TaobaoAgent.this.log("暂停广告播放"); } public void onDidStart() { TaobaoAgent.this.log("开始广告播放"); InfoManager.getInstance().root().setPlayMode(RootNode.PlayMode.PLAY_FRONT_ADVERTISEMENT); } public void onDidStop() { TaobaoAgent.this.log("停止广告播放"); TaobaoAgent.this.onHandlePlayFinished(); } public void onPlayDidFinished() { TaobaoAgent.this.log("播放广告完成"); TaobaoAgent.this.onHandlePlayFinished(); QTMSGManage.getInstance().sendStatistcsMessage("taobao_ad", "playFinished"); } public void onPlayFailed(String paramAnonymousString) { TaobaoAgent.this.log("播放广告失败"); TaobaoAgent.this.onHandlePlayFinished(); QTMSGManage.getInstance().sendStatistcsMessage("taobao_ad", "playFailed"); } public void onRequestFailed(String paramAnonymousString) { TaobaoAgent.this.log("广告请求失败"); QTMSGManage.getInstance().sendStatistcsMessage("taobao_ad", "requestADFailed"); } public void onRequestFinished() { TaobaoAgent.this.log("广告请求成功"); TaobaoAgent.access$102(TaobaoAgent.this, true); QTMSGManage.getInstance().sendStatistcsMessage("taobao_ad", "requestADSucc"); } }); } public void loadAd() { if (this.mAudio != null) { this.hasLoadedAudio = false; this.mAudio.requestAD(this.AD_IDENTITY); QTMSGManage.getInstance().sendStatistcsMessage("taobao_ad", "load"); } } public boolean playAD(boolean paramBoolean) { if ((paramBoolean) && (System.currentTimeMillis() / 1000L - this.hasPlayAdv < 300L)) return false; if (this.hasLoadedAudio) { if (!paramBoolean) PlayerAgent.getInstance().stop(); _playAD(paramBoolean); this.hasPlayAdv = (System.currentTimeMillis() / 1000L); return true; } loadAd(); return false; } public void setADId(String paramString) { this.AD_IDENTITY = paramString; } public void stopAD() { if (this.mAudio != null) this.mAudio.stopAD(); } } /* Location: /Users/zhangxun-xy/Downloads/qingting2/classes_dex2jar.jar * Qualified Name: fm.qingting.qtradio.fm.TaobaoAgent * JD-Core Version: 0.6.2 */
412
0.89336
1
0.89336
game-dev
MEDIA
0.496515
game-dev
0.905653
1
0.905653
Danial-Kord/DigiHuman
6,555
Assets/Standard Assets/Utility/WaypointProgressTracker.cs
using System; using UnityEngine; namespace UnityStandardAssets.Utility { public class WaypointProgressTracker : MonoBehaviour { // This script can be used with any object that is supposed to follow a // route marked out by waypoints. // This script manages the amount to look ahead along the route, // and keeps track of progress and laps. [SerializeField] private WaypointCircuit circuit; // A reference to the waypoint-based route we should follow [SerializeField] private float lookAheadForTargetOffset = 5; // The offset ahead along the route that the we will aim for [SerializeField] private float lookAheadForTargetFactor = .1f; // A multiplier adding distance ahead along the route to aim for, based on current speed [SerializeField] private float lookAheadForSpeedOffset = 10; // The offset ahead only the route for speed adjustments (applied as the rotation of the waypoint target transform) [SerializeField] private float lookAheadForSpeedFactor = .2f; // A multiplier adding distance ahead along the route for speed adjustments [SerializeField] private ProgressStyle progressStyle = ProgressStyle.SmoothAlongRoute; // whether to update the position smoothly along the route (good for curved paths) or just when we reach each waypoint. [SerializeField] private float pointToPointThreshold = 4; // proximity to waypoint which must be reached to switch target to next waypoint : only used in PointToPoint mode. public enum ProgressStyle { SmoothAlongRoute, PointToPoint, } // these are public, readable by other objects - i.e. for an AI to know where to head! public WaypointCircuit.RoutePoint targetPoint { get; private set; } public WaypointCircuit.RoutePoint speedPoint { get; private set; } public WaypointCircuit.RoutePoint progressPoint { get; private set; } public Transform target; private float progressDistance; // The progress round the route, used in smooth mode. private int progressNum; // the current waypoint number, used in point-to-point mode. private Vector3 lastPosition; // Used to calculate current speed (since we may not have a rigidbody component) private float speed; // current speed of this object (calculated from delta since last frame) // setup script properties private void Start() { // we use a transform to represent the point to aim for, and the point which // is considered for upcoming changes-of-speed. This allows this component // to communicate this information to the AI without requiring further dependencies. // You can manually create a transform and assign it to this component *and* the AI, // then this component will update it, and the AI can read it. if (target == null) { target = new GameObject(name + " Waypoint Target").transform; } Reset(); } // reset the object to sensible values public void Reset() { progressDistance = 0; progressNum = 0; if (progressStyle == ProgressStyle.PointToPoint) { target.position = circuit.Waypoints[progressNum].position; target.rotation = circuit.Waypoints[progressNum].rotation; } } private void Update() { if (progressStyle == ProgressStyle.SmoothAlongRoute) { // determine the position we should currently be aiming for // (this is different to the current progress position, it is a a certain amount ahead along the route) // we use lerp as a simple way of smoothing out the speed over time. if (Time.deltaTime > 0) { speed = Mathf.Lerp(speed, (lastPosition - transform.position).magnitude/Time.deltaTime, Time.deltaTime); } target.position = circuit.GetRoutePoint(progressDistance + lookAheadForTargetOffset + lookAheadForTargetFactor*speed) .position; target.rotation = Quaternion.LookRotation( circuit.GetRoutePoint(progressDistance + lookAheadForSpeedOffset + lookAheadForSpeedFactor*speed) .direction); // get our current progress along the route progressPoint = circuit.GetRoutePoint(progressDistance); Vector3 progressDelta = progressPoint.position - transform.position; if (Vector3.Dot(progressDelta, progressPoint.direction) < 0) { progressDistance += progressDelta.magnitude*0.5f; } lastPosition = transform.position; } else { // point to point mode. Just increase the waypoint if we're close enough: Vector3 targetDelta = target.position - transform.position; if (targetDelta.magnitude < pointToPointThreshold) { progressNum = (progressNum + 1)%circuit.Waypoints.Length; } target.position = circuit.Waypoints[progressNum].position; target.rotation = circuit.Waypoints[progressNum].rotation; // get our current progress along the route progressPoint = circuit.GetRoutePoint(progressDistance); Vector3 progressDelta = progressPoint.position - transform.position; if (Vector3.Dot(progressDelta, progressPoint.direction) < 0) { progressDistance += progressDelta.magnitude; } lastPosition = transform.position; } } private void OnDrawGizmos() { if (Application.isPlaying) { Gizmos.color = Color.green; Gizmos.DrawLine(transform.position, target.position); Gizmos.DrawWireSphere(circuit.GetRoutePosition(progressDistance), 1); Gizmos.color = Color.yellow; Gizmos.DrawLine(target.position, target.position + target.forward); } } } }
412
0.933665
1
0.933665
game-dev
MEDIA
0.544939
game-dev,graphics-rendering
0.87842
1
0.87842
HeaoYe/MatchEngine
2,751
MatchEngine/src/MatchEngine/game_framework/game_object.cpp
#include <MatchEngine/game_framework/game_object.hpp> #include <MatchEngine/core/logger/logger.hpp> #include "internal.hpp" namespace MatchEngine::Game { GameObject::GameObject(const std::string &name) : name(name) { uuid = global_runtime_context->game_object_uuid_allocator->allocate(); } GameObject::~GameObject() { for (auto *component : components) { component->onDestroy(); delete component; } components.clear(); component_map.clear(); } void GameObject::awake() { for (auto *component : components) { component->onAwake(); } } void GameObject::start() { for (auto *component : components) { component->onStart(); } } void GameObject::fixedTick() { for (auto *component : components) { component->onFixedTick(); } } void GameObject::tick(float dt) { for (auto *component : components) { component->onTick(dt); } } void GameObject::postTick(float dt) { for (auto *component : components) { component->onPostTick(dt); } } void GameObject::addComponet(Component *component) { component->uuid = global_runtime_context->component_type_uuid_system->get(component->getClassName()); if (component_map.find(component->getTypeUUID()) != component_map.end()) { MCH_CORE_ERROR("Component {} has been added.", component->getTypeUUID()) return; } component->master = this; component->setupRTTI(); component_map.insert(std::make_pair(component->getTypeUUID(), component)); components.push_back(component); component->onCreate(); } void GameObject::removeComponent(Component *component) { removeComponent(component->getTypeUUID()); } void GameObject::removeComponent(ComponentTypeUUID uuid) { if (auto iter = component_map.find(uuid); iter != component_map.end()) { components.remove(iter->second); component_map.erase(iter); return; } MCH_CORE_ERROR("Component {} has been removed.", uuid) } Component *GameObject::queryComponent(const std::string &class_name) { auto uuid = global_runtime_context->component_type_uuid_system->get(class_name); if (auto iter = component_map.find(uuid); iter != component_map.end()) { return component_map.at(uuid); } return nullptr; } Component *GameObject::forceGetComponent(const std::string &class_name) { return component_map.at(global_runtime_context->component_type_uuid_system->get(class_name)); } }
412
0.723718
1
0.723718
game-dev
MEDIA
0.967613
game-dev
0.908696
1
0.908696
worldforge/cyphesis
11,454
src/rules/simulation/ModifyProperty.cpp
/* Copyright (C) 2019 Erik Ogenvik 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "common/Inheritance.h" #include "common/AtlasQuery.h" #include "ModifyProperty.h" #include "rules/entityfilter/ProviderFactory.h" #include "BaseWorld.h" #include "ModifiersProperty.h" PropertyInstanceState<ModifyProperty::State> ModifyProperty::sInstanceState; ModifyEntry ModifyEntry::parseEntry(const Atlas::Message::MapType& entryMap) { ModifyEntry modifyEntry; AtlasQuery::find<std::string>(entryMap, "constraint", [&](const std::string& constraintEntry) { modifyEntry.constraint = std::make_unique<EntityFilter::Filter>(constraintEntry, EntityFilter::ProviderFactory()); }); AtlasQuery::find<Atlas::Message::ListType>(entryMap, "observed_properties", [&](const Atlas::Message::ListType& observedPropertiesEntry) { for (auto& propertyEntry: observedPropertiesEntry) { if (propertyEntry.isString()) { modifyEntry.observedProperties.emplace(propertyEntry.String()); } } }); AtlasQuery::find<Atlas::Message::MapType>(entryMap, "modifiers", [&](const Atlas::Message::MapType& modifiersMap) { for (auto& modifierEntry : modifiersMap) { if (modifierEntry.second.isMap()) { auto& valueMap = modifierEntry.second.Map(); auto I = valueMap.find("default"); if (I != valueMap.end()) { modifyEntry.modifiers.emplace(modifierEntry.first, std::make_unique<DefaultModifier>(I->second)); } I = valueMap.find("append"); if (I != valueMap.end()) { modifyEntry.modifiers.emplace(modifierEntry.first, std::make_unique<AppendModifier>(I->second)); } I = valueMap.find("prepend"); if (I != valueMap.end()) { modifyEntry.modifiers.emplace(modifierEntry.first, std::make_unique<PrependModifier>(I->second)); } I = valueMap.find("subtract"); if (I != valueMap.end()) { modifyEntry.modifiers.emplace(modifierEntry.first, std::make_unique<SubtractModifier>(I->second)); } I = valueMap.find("add_fraction"); if (I != valueMap.end()) { modifyEntry.modifiers.emplace(modifierEntry.first, std::make_unique<AddFractionModifier>(I->second)); } } } }); return modifyEntry; } ModifyProperty::ModifyProperty() = default; ModifyProperty::ModifyProperty(const ModifyProperty& rhs) : PropertyBase(rhs) { setData(rhs.m_data); } void ModifyProperty::apply(LocatedEntity& entity) { auto* state = sInstanceState.getState(entity); //Whenever the value is changed and the property is applied we need to clear out all applied modifiers. if (state->parentEntity) { auto& activeModifiers = state->parentEntity->getActiveModifiers(); auto I = activeModifiers.find(&entity); if (I != activeModifiers.end()) { auto modifiers = I->second; //Important that we copy the modifiers since we'll be modifying them. for (auto& entry: modifiers) { //Note that the modifier pointer points to an invalid memory location! We can only remove it; not touch it otherwise. state->parentEntity->removeModifier(entry.first, entry.second); } } } checkIfActive(*state, entity); } ModifyProperty* ModifyProperty::copy() const { return new ModifyProperty(*this); } void ModifyProperty::setData(const Atlas::Message::Element& val) { m_data = val; m_modifyEntries.clear(); if (val.isList()) { auto& list = val.List(); for (auto& entry : list) { if (entry.isMap()) { auto modifyEntry = ModifyEntry::parseEntry(entry.Map()); if (!modifyEntry.modifiers.empty()) { m_modifyEntries.emplace_back(std::move(modifyEntry)); } } } } } void ModifyProperty::set(const Atlas::Message::Element& val) { setData(val); } int ModifyProperty::get(Atlas::Message::Element& val) const { val = m_data; return 0; } void ModifyProperty::remove(LocatedEntity& owner, const std::string& name) { auto* state = sInstanceState.getState(owner); if (state) { newLocation(*state, owner, nullptr); state->containeredConnection.disconnect(); } sInstanceState.removeState(owner); } void ModifyProperty::install(LocatedEntity& owner, const std::string& name) { auto state = new ModifyProperty::State(); state->parentEntity = owner.m_parent; state->containeredConnection.disconnect(); state->containeredConnection = owner.containered.connect([this, state, &owner](const Ref<LocatedEntity>& oldLocation) { if (state->parentEntity != owner.m_parent) { newLocation(*state, owner, owner.m_parent); checkIfActive(*state, owner); } }); if (owner.m_parent) { newLocation(*state, owner, owner.m_parent); } sInstanceState.addState(owner, std::unique_ptr<ModifyProperty::State>(state)); } void ModifyProperty::newLocation(State& state, LocatedEntity& entity, LocatedEntity* parent) { if (state.parentEntity) { auto& activeModifiers = state.parentEntity->getActiveModifiers(); auto I = activeModifiers.find(&entity); if (I != activeModifiers.end() && !I->second.empty()) { //Important that we copy the modifiers, since we'll be altering the map. auto modifiers = I->second; for (auto& entry: modifiers) { state.parentEntity->removeModifier(entry.first, entry.second); } state.parentEntity->requirePropertyClassFixed<ModifiersProperty>().addFlags(prop_flag_unsent); } } state.parentEntity = parent; state.parentEntityPropertyUpdateConnection.disconnect(); if (state.parentEntity) { state.parentEntityPropertyUpdateConnection = state.parentEntity->propertyApplied.connect( [&](const std::string& propertyName, const PropertyBase&) { for (auto& modifyEntry : m_modifyEntries) { if (modifyEntry.observedProperties.find(propertyName) != modifyEntry.observedProperties.end()) { checkIfActive(state, entity); return; } } }); } } void ModifyProperty::checkIfActive(State& state, LocatedEntity& entity) { if (state.parentEntity) { std::set<std::pair<std::string, Modifier*>> activatedModifiers; for (auto& modifyEntry: m_modifyEntries) { bool apply; if (!modifyEntry.constraint) { apply = true; } else { EntityFilter::QueryContext queryContext{entity, state.parentEntity}; queryContext.entity_lookup_fn = [&entity, &state](const std::string& id) { // This might be applied before the entity or its parent has been added to the world. if (id == entity.getId()) { return Ref<LocatedEntity>(&entity); } else if (id == state.parentEntity->getId()) { return Ref<LocatedEntity>(state.parentEntity); } else { return BaseWorld::instance().getEntity(id); } }; queryContext.type_lookup_fn = [](const std::string& id) { return Inheritance::instance().getType(id); }; apply = modifyEntry.constraint->match(queryContext); } if (apply) { for (auto& appliedModifierEntry : modifyEntry.modifiers) { activatedModifiers.emplace(appliedModifierEntry.first, appliedModifierEntry.second.get()); } } // // if (apply) { // if (state.activeModifiers.find(&modifyEntry) == state.activeModifiers.end()) { // for (auto& appliedModifierEntry : modifyEntry.modifiers) { // state.parentEntity->addModifier(appliedModifierEntry.first, appliedModifierEntry.second.get(), &entity); // } // state.activeModifiers.insert(&modifyEntry); // state.parentEntity->requirePropertyClassFixed<ModifiersProperty>()->addFlags(prop_flag_unsent); // } // } else { // if (state.activeModifiers.find(&modifyEntry) != state.activeModifiers.end()) { // for (auto& appliedModifierEntry : modifyEntry.modifiers) { // state.parentEntity->removeModifier(appliedModifierEntry.first, appliedModifierEntry.second.get()); // } // state.activeModifiers.erase(&modifyEntry); // state.parentEntity->requirePropertyClassFixed<ModifiersProperty>()->addFlags(prop_flag_unsent); // } // } } auto& activeModifiers = state.parentEntity->getActiveModifiers(); auto I = activeModifiers.find(&entity); if (I != activeModifiers.end()) { //There were already modifiers active. Check the difference and add or remove. auto modifiersCopy = I->second; for (auto& appliedModifierEntry : activatedModifiers) { auto pair = std::make_pair(appliedModifierEntry.first, appliedModifierEntry.second); if (modifiersCopy.find(pair) == modifiersCopy.end()) { state.parentEntity->addModifier(appliedModifierEntry.first, appliedModifierEntry.second, &entity); state.parentEntity->requirePropertyClassFixed<ModifiersProperty>().addFlags(prop_flag_unsent); } else { modifiersCopy.erase(pair); } } //Those that are left should be removed. for (auto& modifierToRemove : modifiersCopy) { state.parentEntity->removeModifier(modifierToRemove.first, modifierToRemove.second); } } else { if (!activatedModifiers.empty()) { //No active modifiers existed, just add all for (auto& appliedModifierEntry : activatedModifiers) { state.parentEntity->addModifier(appliedModifierEntry.first, appliedModifierEntry.second, &entity); } state.parentEntity->requirePropertyClassFixed<ModifiersProperty>().addFlags(prop_flag_unsent); } } } }
412
0.966779
1
0.966779
game-dev
MEDIA
0.482544
game-dev
0.959434
1
0.959434
mono/CocosSharp
4,439
tests/tests/classes/tests/Box2DTestBet/Tests/PrismaticTest.cs
/* * Farseer Physics Engine based on Box2D.XNA port: * Copyright (c) 2010 Ian Qvist * * Box2D.XNA port of Box2D: * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler * * Original source Box2D: * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * 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. */ using FarseerPhysics.Collision.Shapes; using FarseerPhysics.Dynamics; using FarseerPhysics.Dynamics.Joints; using FarseerPhysics.Factories; using FarseerPhysics.TestBed.Framework; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace FarseerPhysics.TestBed.Tests { public class PrismaticTest : Test { private FixedPrismaticJoint _fixedJoint; private PrismaticJoint _joint; private PrismaticTest() { Body ground; { ground = BodyFactory.CreateBody(World); EdgeShape shape3 = new EdgeShape(new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f)); ground.CreateFixture(shape3); } PolygonShape shape = new PolygonShape(5); shape.SetAsBox(2.0f, 0.5f); Body body = BodyFactory.CreateBody(World); body.BodyType = BodyType.Dynamic; body.Position = new Vector2(0.0f, 10.0f); body.CreateFixture(shape); _fixedJoint = new FixedPrismaticJoint(body, body.Position, new Vector2(0.5f, 1.0f)); _fixedJoint.MotorSpeed = 5.0f; _fixedJoint.MaxMotorForce = 1000.0f; _fixedJoint.MotorEnabled = true; _fixedJoint.LowerLimit = -10.0f; _fixedJoint.UpperLimit = 20.0f; _fixedJoint.LimitEnabled = true; World.AddJoint(_fixedJoint); PolygonShape shape2 = new PolygonShape(5); shape2.SetAsBox(2.0f, 0.5f); Body body2 = BodyFactory.CreateBody(World); body2.BodyType = BodyType.Dynamic; body2.Position = new Vector2(10.0f, 10.0f); body2.CreateFixture(shape2); _joint = new PrismaticJoint(ground, body2, ground.GetLocalPoint(body2.Position), Vector2.Zero, new Vector2(0.5f, 1.0f)); _joint.MotorSpeed = 5.0f; _joint.MaxMotorForce = 1000.0f; _joint.MotorEnabled = true; _joint.LowerLimit = -10.0f; _joint.UpperLimit = 20.0f; _joint.LimitEnabled = true; World.AddJoint(_joint); } public override void Keyboard(KeyboardManager keyboardManager) { if (keyboardManager.IsNewKeyPress(Keys.L)) { _fixedJoint.LimitEnabled = !_fixedJoint.LimitEnabled; _joint.LimitEnabled = !_joint.LimitEnabled; } if (keyboardManager.IsNewKeyPress(Keys.M)) { _fixedJoint.MotorEnabled = !_fixedJoint.MotorEnabled; _joint.MotorEnabled = !_joint.MotorEnabled; } if (keyboardManager.IsNewKeyPress(Keys.P)) { _fixedJoint.MotorSpeed = -_fixedJoint.MotorSpeed; _joint.MotorSpeed = -_joint.MotorSpeed; } base.Keyboard(keyboardManager); } public override void Update(GameSettings settings, GameTime gameTime) { base.Update(settings, gameTime); DebugView.DrawString(50, TextLine, "Keys: (l) limits, (m) motors, (p) speed"); TextLine += 15; } internal static Test Create() { return new PrismaticTest(); } } }
412
0.779165
1
0.779165
game-dev
MEDIA
0.900471
game-dev,testing-qa
0.789188
1
0.789188
SkyblockAPI/SkyblockAPI
5,658
src/common/main/kotlin/tech/thatgravyboat/skyblockapi/api/profile/items/sacks/SacksAPI.kt
package tech.thatgravyboat.skyblockapi.api.profile.items.sacks import com.google.gson.JsonObject import me.owdding.ktmodules.Module import net.minecraft.world.item.ItemStack import tech.thatgravyboat.skyblockapi.api.data.stored.SacksStorage import tech.thatgravyboat.skyblockapi.api.datatype.DataTypes import tech.thatgravyboat.skyblockapi.api.datatype.getData import tech.thatgravyboat.skyblockapi.api.events.base.Subscription import tech.thatgravyboat.skyblockapi.api.events.base.predicates.OnlyOnSkyBlock import tech.thatgravyboat.skyblockapi.api.events.chat.ChatReceivedEvent import tech.thatgravyboat.skyblockapi.api.events.hypixel.ChangedSackItem import tech.thatgravyboat.skyblockapi.api.events.hypixel.SacksChangeEvent import tech.thatgravyboat.skyblockapi.api.events.remote.SkyBlockPvOpenedEvent import tech.thatgravyboat.skyblockapi.api.events.remote.SkyBlockPvRequired import tech.thatgravyboat.skyblockapi.api.events.screen.InventoryChangeEvent import tech.thatgravyboat.skyblockapi.api.remote.LoadedData import tech.thatgravyboat.skyblockapi.api.remote.PvLoadingHelper import tech.thatgravyboat.skyblockapi.api.remote.RepoItemsAPI import tech.thatgravyboat.skyblockapi.utils.extentions.asInt import tech.thatgravyboat.skyblockapi.utils.extentions.getRawLore import tech.thatgravyboat.skyblockapi.utils.extentions.toIntValue import tech.thatgravyboat.skyblockapi.utils.json.getPath import tech.thatgravyboat.skyblockapi.utils.regex.RegexGroup import tech.thatgravyboat.skyblockapi.utils.regex.RegexUtils.anyMatch import tech.thatgravyboat.skyblockapi.utils.regex.RegexUtils.findOrNull import tech.thatgravyboat.skyblockapi.utils.regex.component.match import tech.thatgravyboat.skyblockapi.utils.regex.component.toComponentRegex import tech.thatgravyboat.skyblockapi.utils.text.TextProperties.stripped import tech.thatgravyboat.skyblockapi.utils.text.TextStyle.hover import tech.thatgravyboat.skyblockapi.utils.text.TextUtils.splitLines import tech.thatgravyboat.skyblockapi.utils.time.since @Module object SacksAPI { // [Sacks] +14 items. (Last 5s.) // [Sacks] -38 items. (Last 5s.) // [Sacks] +38 items, -1 item. (Last 8s.) val sackMessageRegex = RegexGroup.CHAT.create( "sackapi.message", "\\[Sacks] (?:(?<gained>\\+[\\d.,]+) items?,?)?\\s*(?:(?<lost>-[\\d.,]+) items?)?\\.\\s*\\(.*", ).toComponentRegex() val addedItemsRegex = RegexGroup.CHAT.create("sackapi.changed", " {2}(?<amount>[+-][\\d.,]+) (?<item>.+) \\(") val sackTitleRegex = RegexGroup.INVENTORY.create("sackapi.title", ".* Sack") val sackAmountRegex = RegexGroup.INVENTORY.create("sackapi.amount", "Stored: (?<amount>[\\d,.]+)/.*") val sackItems: Map<String, Int> get() = SacksStorage.items.associate { (key, value) -> key to value } @Subscription @OnlyOnSkyBlock fun onChat(event: ChatReceivedEvent.Pre) { sackMessageRegex.match(event.component) { val gainedHoverComponents = it["gained"]?.hover?.splitLines().orEmpty() val lostHoverComponents = it["lost"]?.hover?.splitLines().orEmpty() val hoverComponents = gainedHoverComponents + lostHoverComponents val changedItems = hoverComponents.mapNotNull { addedItemsRegex.findOrNull(it.stripped, "amount", "item") { (amount, item) -> val id = RepoItemsAPI.getItemIdByName(item) ?: return@findOrNull null return@findOrNull id to amount.replace("+", "").toIntValue() } } changedItems.forEach { (item, amount) -> SacksStorage.updateItemValue(item, amount) } SacksChangeEvent(changedItems.map { (item, amount) -> ChangedSackItem(item, amount) }).post() } } @Subscription @OnlyOnSkyBlock fun onInventoryUpdate(event: InventoryChangeEvent) { if (event.isInPlayerInventory) return if (!sackTitleRegex.matches(event.title)) return val item = event.item val id = event.item.getData(DataTypes.ID) ?: return when (event.title) { "Gemstones Sack" -> { handleGemstones(item, id) return } "Runes Sack" -> return // No one cares about you } sackAmountRegex.anyMatch(item.getRawLore(), "amount") { (amount) -> SacksStorage.updateItem(id, amount.toIntValue()) } } @Subscription @OnlyOnSkyBlock @OptIn(SkyBlockPvRequired::class) private fun SkyBlockPvOpenedEvent.updateSacks() { val sacks = member.getPath("inventory.sacks_counts") as? JsonObject ?: return sacks.entrySet().forEach { (itemId, amount) -> val amount = amount.asInt(0).takeUnless { it <= 0 } ?: return@forEach val entry = SacksStorage.items.find { it.id == itemId } val previousAmount = entry?.amount ?: 0 if (amount == previousAmount) { return@forEach } val isInvalid = entry?.lastUpdated?.since()?.let { it < PvLoadingHelper.timeToLive } == true if (isInvalid) { return@forEach } SacksStorage.updateItem(itemId, amount) PvLoadingHelper.markLoaded(LoadedData.SACKS) } } private fun handleGemstones(item: ItemStack, id: String) { listOf("Rough", "Flawed", "Fine").forEach { name -> Regex(" $name: (?<amount>[\\d,.]+) .*").anyMatch(item.getRawLore(), "amount") { (amount) -> val actualId = id.replace("ROUGH", name.uppercase()) SacksStorage.updateItem(actualId, amount.toIntValue()) } } } }
412
0.921013
1
0.921013
game-dev
MEDIA
0.42176
game-dev
0.950938
1
0.950938
AiMiDi/C4D_MMD_Tool
6,063
sdk_r25/frameworks/core.framework/source/maxon/lazyinit.h
#ifndef LAZYINIT_H__ #define LAZYINIT_H__ #include "maxon/atomictypes.h" #include "maxon/cpuyield.h" #include "maxon/threadsaferef.h" namespace maxon { /// @addtogroup THREADING Threading /// @{ //---------------------------------------------------------------------------------------- /// Thread-safe helper class for single-threaded lazy initialization. /// /// Typical usage case is a method which initializes data on first call, for example /// /// @code /// class Sample /// { /// public: /// MyObject* GetObject() /// { /// _state.Init( /// [this]() -> Bool /// { /// // Your init code goes here. /// // Return true if initialization was successful and false if it failed. /// // Using type Result<void> instead of Bool for the return value is supported as well. /// return true; /// }); /// /// return _object; /// } /// private: /// LazyInit _state; /// MyObject* _object; /// SomeMoreData _xyz; /// }; /// @endcode /// /// @note The code of the lambda must be single threaded, using multithreaded code will lead /// to a deadlock! For potentially multithreaded initialization use LazyInitThreaded. /// Performance note: Declaring a global LazyInit as a static member of a class will /// degrade its performance because the compiler will guard its access with a slow and /// unnecessary mutex. To avoid this move the global state outside of the class. /// /// THREADSAFE. //---------------------------------------------------------------------------------------- class LazyInit { enum class STATE : Int32 { UNINITIALIZED = 0, PENDING = 1, INITIALIZED = 2 } MAXON_ENUM_LIST_CLASS(STATE); static void Dummy() { } static Bool ToBool(Bool v) { return v; } static Bool ToBool(ResultMem v) { return v == OK; } static Bool ToBool(const Result<void>& v) { return v == OK; } public: //---------------------------------------------------------------------------------------- /// Initializes an object by calling the specified method (and does nothing if the object /// has already been initialized). /// The method #fn will be executed on the current thread and must be executing quickly. /// It is not allowed to perform multithreaded code as part of the initialization because /// this could deadlock and waiting threads would be busy-idling. /// @note The code of the lambda must be single threaded! Otherwise use LazyInitThreaded (and review your code thoroughly). /// THREADSAFE. /// @param[in] fn Method (usually a lambda) to initialize something, must return a Bool or a Result<void>. /// @return True/OK if initialization was successful or object has already been initialized, otherwise result of failed initialization. //---------------------------------------------------------------------------------------- template <typename FN> MAXON_ATTRIBUTE_FORCE_INLINE auto Init(FN&& fn) -> decltype(fn()) { STATE state = (STATE)_state.LoadAcquire(); decltype(fn()) success = typename std::conditional<STD_IS_REPLACEMENT(same, decltype(fn()), Bool), Bool, ResultMem>::type(true); if (MAXON_UNLIKELY(state != STATE::INITIALIZED)) { CpuYield wait(this); do { // change state to pending if is currently uninitialized if ((state == STATE::UNINITIALIZED) && _state.TryCompareAndSwap((Int32)STATE::PENDING, (Int32)STATE::UNINITIALIZED)) { // do lazy initialization over here success = fn(); _state.StoreRelease(ToBool(success) ? (Int32)STATE::INITIALIZED : (Int32)STATE::UNINITIALIZED); break; } // idle wait.Pause(); // refetch state state = (STATE)_state.LoadAcquire(); } while (state != STATE::INITIALIZED); } return success; } //---------------------------------------------------------------------------------------- /// Resets an object by calling the specified method. Does nothing if the object has already /// been reset. /// THREADSAFE. /// @param[in] fn Optional method (usually a lambda) to reset something. //---------------------------------------------------------------------------------------- template <typename FN = decltype(Dummy)> void Reset(FN&& fn = Dummy) { STATE state = (STATE)_state.LoadAcquire(); if (state != STATE::UNINITIALIZED) { CpuYield wait(this); do { // change state to pending if is currently initialized if ((state == STATE::INITIALIZED) && _state.TryCompareAndSwap((Int32)STATE::PENDING, (Int32)STATE::INITIALIZED)) { // call optional reset method fn(); _state.StoreRelease((Int32)STATE::UNINITIALIZED); break; } // idle wait.Pause(); // refetch state state = (STATE)_state.LoadAcquire(); } while (state != STATE::UNINITIALIZED); } } //---------------------------------------------------------------------------------------- /// Returns if the object already has been initialized. /// THREADSAFE. /// @return True if initialization was successful. //---------------------------------------------------------------------------------------- Bool IsInitialized() const { return (STATE)_state.LoadAcquire() == STATE::INITIALIZED; } //---------------------------------------------------------------------------------------- /// Returns if the object already has been initialized. /// THREADSAFE. /// @return True if initialization was successful. //---------------------------------------------------------------------------------------- explicit operator Bool() const { return IsInitialized(); } //---------------------------------------------------------------------------------------- /// Returns if the object is currently being initialized (for debugging) /// THREADSAFE. /// @return True if the tinitialization is pending. //---------------------------------------------------------------------------------------- Bool IsPendingInitialization() const { return (STATE)_state.LoadAcquire() == STATE::PENDING; } private: AtomicInt32 _state; }; /// @} } // namespace maxon #endif // LAZYINIT_H__
412
0.69776
1
0.69776
game-dev
MEDIA
0.256533
game-dev
0.708312
1
0.708312
abhisrkckl/Vela.jl
1,425
src/model/jump.jl
export PhaseJump, ExclusivePhaseJump abstract type PhaseJumpBase <: PhaseComponent end """ PhaseJump System-dependent phase jumps with non-exclusive selection masks. Corresponds to `PhaseJump` in `PINT`. Reference: [Hobbs+ 2006](http://doi.org/10.1111/j.1365-2966.2006.10302.x) """ struct PhaseJump <: PhaseJumpBase jump_mask::BitMatrix end basis_dot(basis, amplitudes, index) = dot(amplitudes, @view(basis[:, index])) phase(pjmp::PhaseJump, toa::TOA, ::TOACorrection, params::NamedTuple)::GQ = is_tzr(toa) ? dimensionless(0.0) : (basis_dot(pjmp.jump_mask, params.JUMP, toa.index) * (params.F_ + params.F[1])) function show(io::IO, jmp::PhaseJump) num_jumps = size(jmp.jump_mask)[1] print(io, "PhaseJump($num_jumps JUMPs)") end """System-dependent phase jumps with exclusive selection masks.""" struct ExclusivePhaseJump <: PhaseJumpBase jump_mask::Vector{UInt} end function phase(pjmp::ExclusivePhaseJump, toa::TOA, ::TOACorrection, params::NamedTuple)::GQ return if is_tzr(toa) dimensionless(0.0) else idx = pjmp.jump_mask[toa.index] if idx == 0 dimensionless(0.0) else params.JUMP[idx] * (params.F_ + params.F[1]) end end end function show(io::IO, jmp::ExclusivePhaseJump) num_jumps = length(filter(x -> x > 0, unique(jmp.jump_mask))) print(io, "PhaseJump($num_jumps JUMPs, exclusive)") end
412
0.855116
1
0.855116
game-dev
MEDIA
0.704985
game-dev
0.968675
1
0.968675
fbef0102/L4D1_2-Plugins
12,301
l4d_sm_respawn/scripting/l4d_sm_respawn.sp
#pragma semicolon 1 #pragma newdecls required #include <sourcemod> #include <sdktools> #include <adminmenu> #include <left4dhooks> #define PLUGIN_VERSION "2.8" #define CVAR_FLAGS FCVAR_NOTIFY public Plugin myinfo = { name = "[L4D & L4D2] SM Respawn", author = "AtomicStryker & Ivailosp (Modified by Crasher, SilverShot), fork by Dragokas & Harry", description = "Allows players to be respawned at one's crosshair.", version = PLUGIN_VERSION, url = "https://forums.alliedmods.net/showthread.php?t=323220" }; int ACCESS_FLAG = ADMFLAG_BAN; float VEC_DUMMY[3] = {99999.0, 99999.0, 99999.0}; ConVar g_cvLoadout, g_cvShowAction, g_cvAddTopMenu, g_cvDestination; bool g_bLeft4dead2; bool g_bMenuAdded; TopMenuObject hAdminSpawnItem; int g_iDeadBody[MAXPLAYERS+1]; public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) { EngineVersion evEngine = GetEngineVersion(); if (evEngine != Engine_Left4Dead && evEngine != Engine_Left4Dead2) { strcopy(error, err_max, "SM Respawn only supports Left 4 Dead 1 & 2."); return APLRes_SilentFailure; } g_bLeft4dead2 = (evEngine == Engine_Left4Dead2); CreateNative("SM_Respawn", NATIVE_Respawn); return APLRes_Success; } public void OnPluginStart() { LoadTranslations("common.phrases"); LoadTranslations("l4d_sm_respawn.phrases"); CreateConVar("l4d_sm_respawn2_version", PLUGIN_VERSION, "SM Respawn Version", CVAR_FLAGS | FCVAR_DONTRECORD); g_cvLoadout = CreateConVar("l4d_sm_respawn_loadout", "pistol,smg", "Respawn players with this loadout, separate by commas", CVAR_FLAGS); g_cvShowAction = CreateConVar("l4d_sm_respawn_showaction", "1", "Notify in chat and log action about respawn? (0 - No, 1 - Yes)", CVAR_FLAGS, true, 0.0, true, 1.0); g_cvAddTopMenu = CreateConVar("l4d_sm_respawn_adminmenu", "1", "Add 'Respawn player' item in admin menu under 'Player commands' category? (0 - No, 1 - Yes)", CVAR_FLAGS, true, 0.0, true, 1.0); g_cvDestination = CreateConVar("l4d_sm_respawn_destination", "0", "After respawn player, teleport player to 0=Crosshair, 1=Self (You must be alive).", CVAR_FLAGS, true, 0.0, true, 1.0); AutoExecConfig(true, "l4d_sm_respawn"); if( g_bLeft4dead2 ) { HookEvent("dead_survivor_visible", Event_DeadSurvivorVisible); } RegAdminCmd("sm_respawn", CmdRespawn, ACCESS_FLAG, "<opt.target> Respawn a player at your crosshair. Without argument - opens menu to select players"); g_cvAddTopMenu.AddChangeHook(OnCvarChanged); if(g_cvAddTopMenu.BoolValue) { TopMenu topmenu; if (LibraryExists("adminmenu") && ((topmenu = GetAdminTopMenu()) != null)) { OnAdminMenuReady(topmenu); } } } public void OnCvarChanged(ConVar convar, const char[] oldValue, const char[] newValue) { if( g_cvAddTopMenu.BoolValue ) { TopMenu topmenu; if (LibraryExists("adminmenu") && ((topmenu = GetAdminTopMenu()) != null)) { OnAdminMenuReady(topmenu); } } else { RemoveAdminItem(); } } public void OnLibraryRemoved(const char[] name) { if( strcmp(name, "adminmenu") == 0 ) { g_bMenuAdded = false; hAdminSpawnItem = INVALID_TOPMENUOBJECT; } } TopMenu hTopMenu; public void OnAdminMenuReady(Handle aTopMenu) { AddAdminItem(aTopMenu); TopMenu topmenu = TopMenu.FromHandle(aTopMenu); /* Block us from being called twice */ if (hTopMenu == topmenu) { return; } hTopMenu = topmenu; } stock void RemoveAdminItem() { AddAdminItem(null, true); } void AddAdminItem(Handle aTopMenu, bool bRemoveItem = false) { TopMenu hAdminMenu; if( aTopMenu != null ) { hAdminMenu = TopMenu.FromHandle(aTopMenu); } else { if( !LibraryExists("adminmenu") ) { return; } if( null == (hAdminMenu = GetAdminTopMenu()) ) { return; } } if( g_bMenuAdded ) { if( (bRemoveItem || !g_cvAddTopMenu.BoolValue) && hAdminSpawnItem != INVALID_TOPMENUOBJECT ) { hAdminMenu.Remove(hAdminSpawnItem); g_bMenuAdded = false; } } else { if( g_cvAddTopMenu.BoolValue ) { TopMenuObject hMenuCategory = hAdminMenu.FindCategory(ADMINMENU_PLAYERCOMMANDS); if( hMenuCategory ) { hAdminSpawnItem = hAdminMenu.AddItem("L4D_SM_RespawnPlayer_Item", AdminMenuSpawnHandler, hMenuCategory, "sm_respawn", ACCESS_FLAG, "Respawn a player at your crosshair"); g_bMenuAdded = true; } } } } public void AdminMenuSpawnHandler(Handle topmenu, TopMenuAction action, TopMenuObject object_id, int param, char[] buffer, int maxlength) { if( action == TopMenuAction_SelectOption ) { MenuClientsToSpawn(param); } else if( action == TopMenuAction_DisplayOption ) { FormatEx(buffer, maxlength, "%T", "Respawn_Player", param); } } void MenuClientsToSpawn(int client, int item = 0) { Menu menu = new Menu(MenuHandler_MenuList, MENU_ACTIONS_DEFAULT); menu.SetTitle("%T", "List_Players", client); static char sId[16], name[64]; bool bNoOneDead = true; for( int i = 1; i <= MaxClients; i++ ) { if( IsClientInGame(i) && GetClientTeam(i) == 2 ) { if(IsPlayerAlive(i)) continue; FormatEx(sId, sizeof sId, "%i", GetClientUserId(i)); FormatEx(name, sizeof name, "%N", i); menu.AddItem(sId, name); bNoOneDead = false; } } if(bNoOneDead) { char sText[64]; FormatEx(sText, sizeof(sText), "%T", "No Any Dead Survivor", client); menu.AddItem("1.", sText); } menu.ExitBackButton = true; menu.DisplayAt(client, item, MENU_TIME_FOREVER); } public int MenuHandler_MenuList(Menu menu, MenuAction action, int param1, int param2) { switch( action ) { case MenuAction_End: delete menu; case MenuAction_Cancel: { if (param2 == MenuCancel_ExitBack && hTopMenu) { hTopMenu.Display(param1, TopMenuPosition_LastCategory); } } case MenuAction_Select: { int client = param1; int ItemIndex = param2; static char sUserId[16]; menu.GetItem(ItemIndex, sUserId, sizeof sUserId); int UserId = StringToInt(sUserId); int target = GetClientOfUserId(UserId); if( target && IsClientInGame(target) ) { vRespawnPlayer(client, target); } MenuClientsToSpawn(client, menu.Selection); } } return 0; } public int NATIVE_Respawn(Handle plugin, int numParams) { if( numParams < 1 ) ThrowNativeError(SP_ERROR_PARAM, "Invalid numParams"); int iTarget = GetNativeCell(1); int iClient; float vec[3]; vec = VEC_DUMMY; if( numParams >= 2 ) { iClient = GetNativeCell(2); } if( numParams >= 3 ) { GetNativeArray(3, vec, 3); } return vRespawnPlayer(iClient, iTarget, vec); } public void Event_DeadSurvivorVisible(Event event, const char[] name, bool dontBroadcast) { int iDeadBody = event.GetInt("subject"); int iDeadPlayer = GetClientOfUserId(event.GetInt("deadplayer")); if( iDeadPlayer && iDeadBody && IsValidEntity(iDeadBody) ) { g_iDeadBody[iDeadPlayer] = EntIndexToEntRef(iDeadBody); } } public Action CmdRespawnMenu(int client, int args) { MenuClientsToSpawn(client); return Plugin_Handled; } public Action CmdRespawn(int client, int args) { if( args < 1 ) { if( GetCmdReplySource() == SM_REPLY_TO_CONSOLE ) { PrintToConsole(client, "[SM] Usage: sm_respawn <player1> [player2] ... [playerN] - respawn all listed players"); } CmdRespawnMenu(client, 0); return Plugin_Handled; } char arg1[MAX_TARGET_LENGTH], target_name[MAX_TARGET_LENGTH]; int target_list[MAXPLAYERS], target_count, target; bool tn_is_ml; GetCmdArg(1, arg1, sizeof arg1); if( (target_count = ProcessTargetString(arg1, client, target_list, MAXPLAYERS, 0, target_name, sizeof target_name, tn_is_ml)) <= 0 ) { ReplyToTargetError(client, target_count); return Plugin_Handled; } for( int i = 0; i < target_count; i++ ) { target = target_list[i]; if( target && IsClientInGame(target) ) { vRespawnPlayer(client, target); } } return Plugin_Handled; } bool vRespawnPlayer(int client, int target, float vec[3] = {99999.0, 99999.0, 99999.0}) { float ang[3]; if( vec[0] == VEC_DUMMY[0] && vec[1] == VEC_DUMMY[1] && vec[2] == VEC_DUMMY[2] ) { if(g_cvDestination.IntValue == 0 && GetSpawnEndPoint(client, vec)) { //nothing } else { GetClientAbsOrigin(client, vec); } } if( client ) { GetClientEyeAngles(client, ang); } switch( GetClientTeam(target) ) { case 2: { if(IsPlayerAlive(target)) { PrintToChat(client, "[SM] %T", "message_1", client, target); return false; } L4D_RespawnPlayer(target); CleanUpStateAndMusic(target); char sItems[6][64], sLoadout[512]; g_cvLoadout.GetString(sLoadout, sizeof sLoadout); if(strlen(sLoadout) > 0) { StripWeapons( target ); ExplodeString(sLoadout, ",", sItems, sizeof sItems, sizeof sItems[]); for( int iItem = 0; iItem < sizeof sItems; iItem++ ) { if ( sItems[iItem][0] != '\0' ) { vCheatCommand(target, "give", sItems[iItem]); } } } vPerformTeleport(client, target, vec, ang); int entity = g_iDeadBody[target]; g_iDeadBody[target] = 0; if( IsValidEntRef(entity) ) AcceptEntityInput(entity, "kill"); } case 3: { PrintToChat(client, "[SM] %T", "message_2", client, target); return false; } case 1: { PrintToChat(client, "[SM] %T", "message_3", client, target); return false; } } return true; } public bool bTraceEntityFilterPlayer(int entity, int contentsMask) { return (entity > MaxClients); } bool GetSpawnEndPoint(int client, float vSpawnVec[3]) { if( !client ) { return false; } float vEnd[3], vEye[3]; if( GetDirectionEndPoint(client, vEnd) ) { GetClientEyePosition(client, vEye); ScaleVectorDirection(vEye, vEnd, 0.1); // to allow collision to be happen if( GetNonCollideEndPoint(client, vEnd, vSpawnVec) ) { return true; } } return false; } void ScaleVectorDirection(float vStart[3], float vEnd[3], float fMultiple) { float dir[3]; SubtractVectors(vEnd, vStart, dir); ScaleVector(dir, fMultiple); AddVectors(vEnd, dir, vEnd); } stock bool GetDirectionEndPoint(int client, float vEndPos[3]) { float vDir[3], vPos[3]; GetClientEyePosition(client, vPos); GetClientEyeAngles(client, vDir); Handle hTrace = TR_TraceRayFilterEx(vPos, vDir, MASK_PLAYERSOLID, RayType_Infinite, bTraceEntityFilterPlayer, client); if( hTrace != INVALID_HANDLE ) { if( TR_DidHit(hTrace) ) { TR_GetEndPosition(vEndPos, hTrace); delete hTrace; return true; } delete hTrace; } return false; } stock bool GetNonCollideEndPoint(int client, float vEnd[3], float vEndNonCol[3]) { float vMin[3], vMax[3], vStart[3]; GetClientEyePosition(client, vStart); GetClientMins(client, vMin); GetClientMaxs(client, vMax); vStart[2] += 20.0; // if nearby area is irregular Handle hTrace = TR_TraceHullFilterEx(vStart, vEnd, vMin, vMax, MASK_PLAYERSOLID, bTraceEntityFilterPlayer, client); if( hTrace != INVALID_HANDLE ) { if( TR_DidHit(hTrace) ) { TR_GetEndPosition(vEndNonCol, hTrace); delete hTrace; return true; } delete hTrace; } return false; } void vPerformTeleport(int client, int target, float pos[3], float ang[3]) { pos[2] += 5.0; TeleportEntity(target, pos, ang, NULL_VECTOR); CreateTimer(0.2, Timer_WarpIfStuck, target, TIMER_FLAG_NO_MAPCHANGE); if( g_cvShowAction.BoolValue && client ) { LogAction(client, target, "\"%L\" teleported \"%L\" after respawning him" , client, target); } } Action Timer_WarpIfStuck(Handle timer, int target) { L4D_WarpToValidPositionIfStuck(target); //if stuck return Plugin_Continue; } void vCheatCommand(int client, char[] command, char[] arguments = "") { int iCmdFlags = GetCommandFlags(command); SetCommandFlags(command, iCmdFlags & ~FCVAR_CHEAT); FakeClientCommand(client, "%s %s", command, arguments); SetCommandFlags(command, iCmdFlags | GetCommandFlags(command)); } void StripWeapons(int client) // strip all items from client { int itemIdx; for (int x = 0; x <= 4; x++) { if((itemIdx = GetPlayerWeaponSlot(client, x)) != -1) { RemovePlayerItem(client, itemIdx); AcceptEntityInput(itemIdx, "Kill"); } } } bool IsValidEntRef(int entity) { if( entity && EntRefToEntIndex(entity) != INVALID_ENT_REFERENCE) return true; return false; } void CleanUpStateAndMusic(int client) { if (!g_bLeft4dead2) { L4D_StopMusic(client, "Event.SurvivorDeath"); } else { L4D_StopMusic(client, "Event.SurvivorDeath"); } }
412
0.97162
1
0.97162
game-dev
MEDIA
0.965948
game-dev
0.979504
1
0.979504
FlaxEngine/FlaxEngine
9,022
Source/Editor/Surface/Archetypes/Comparisons.cs
// Copyright (c) Wojciech Figat. All rights reserved. using System.Collections.Generic; using FlaxEditor.GUI; using FlaxEditor.Scripting; using FlaxEditor.Surface.Elements; using FlaxEngine; namespace FlaxEditor.Surface.Archetypes { /// <summary> /// Contains archetypes for nodes from the Comparisons group. /// </summary> [HideInEditor] public static class Comparisons { private static NodeArchetype Op(ushort id, string title, string desc, string[] altTitles = null) { return new NodeArchetype { TypeID = id, Title = title, Description = desc, Flags = NodeFlags.AllGraphs, AlternativeTitles = altTitles, ConnectionsHints = ConnectionsHint.Value, Size = new Float2(100, 40), IndependentBoxes = new[] { 0, 1 }, DefaultValues = new object[] { 0.0f, 0.0f, }, Elements = new[] { NodeElementArchetype.Factory.Input(0, string.Empty, true, null, 0, 0), NodeElementArchetype.Factory.Input(1, string.Empty, true, null, 1, 1), NodeElementArchetype.Factory.Output(0, title, typeof(bool), 2) } }; } private class SwitchOnEnumNode : SurfaceNode { public SwitchOnEnumNode(uint id, VisjectSurfaceContext context, NodeArchetype nodeArch, GroupArchetype groupArch) : base(id, context, nodeArch, groupArch) { } public override void OnLoaded(SurfaceNodeActions action) { base.OnLoaded(action); // Restore saved input boxes layout if (Values[0] is byte[] data) { for (int i = 0; i < data.Length / 4; i++) AddBox(false, i + 2, i + 1, string.Empty, new ScriptType(), true); } } public override void OnSurfaceLoaded(SurfaceNodeActions action) { base.OnSurfaceLoaded(action); UpdateBoxes(); GetBox(0).CurrentTypeChanged += box => UpdateBoxes(); } public override void ConnectionTick(Box box) { base.ConnectionTick(box); UpdateBoxes(); } private unsafe void UpdateBoxes() { var valueBox = (InputBox)GetBox(0); const int firstBox = 2; const int maxBoxes = 40; bool isInvalid = false; var data = Utils.GetEmptyArray<byte>(); if (valueBox.HasAnyConnection) { var valueType = valueBox.CurrentType; if (valueType.IsEnum) { // Get enum entries var entries = new List<EnumComboBox.Entry>(); EnumComboBox.BuildEntriesDefault(valueType.Type, entries); // Setup switch value inputs int id = firstBox; ScriptType type = new ScriptType(); for (; id < maxBoxes; id++) { var box = GetBox(id); if (box == null) break; if (box.HasAnyConnection) { type = box.Connections[0].CurrentType; break; } } id = firstBox; for (; id < entries.Count + firstBox; id++) { var e = entries[id - firstBox]; var box = AddBox(false, id, id - 1, e.Name, type, true); if (!string.IsNullOrEmpty(e.Tooltip)) box.TooltipText = e.Tooltip; } for (; id < maxBoxes; id++) { var box = GetBox(id); if (box == null) break; RemoveElement(box); } // Setup output var outputBox = (OutputBox)GetBox(1); outputBox.CurrentType = type; // Build data about enum entries values for the runtime if (Values[0] is byte[] dataPrev && dataPrev.Length == entries.Count * 4) data = dataPrev; else data = new byte[entries.Count * 4]; fixed (byte* dataPtr = data) { int* dataValues = (int*)dataPtr; for (int i = 0; i < entries.Count; i++) dataValues[i] = (int)entries[i].Value; } } else { // Not an enum isInvalid = true; } } if (isInvalid) { // Remove input values boxes if switch value is unused for (int id = firstBox; id < maxBoxes; id++) { var box = GetBox(id); if (box == null) break; RemoveElement(box); } } Values[0] = data; ResizeAuto(); } } /// <summary> /// The nodes for that group. /// </summary> public static NodeArchetype[] Nodes = { Op(1, "==", "Determines whether two values are equal", new[] { "equals" }), Op(2, "!=", "Determines whether two values are not equal", new[] { "not equals" }), Op(3, ">", "Determines whether the first value is greater than the other", new[] { "greater than", "larger than", "bigger than" }), Op(4, "<", "Determines whether the first value is less than the other", new[] { "less than", "smaller than" }), Op(5, "<=", "Determines whether the first value is less or equal to the other", new[] { "less equals than", "smaller equals than" }), Op(6, ">=", "Determines whether the first value is greater or equal to the other", new[] { "greater equals than", "larger equals than", "bigger equals than" }), new NodeArchetype { TypeID = 7, Title = "Switch On Bool", AlternativeTitles = new[] { "if", "switch" }, Description = "Returns one of the input values based on the condition value", Flags = NodeFlags.AllGraphs, Size = new Float2(160, 60), ConnectionsHints = ConnectionsHint.Value, IndependentBoxes = new[] { 1, 2, }, DependentBoxes = new[] { 3, }, DefaultValues = new object[] { 0.0f, 0.0f, }, Elements = new[] { NodeElementArchetype.Factory.Input(0, "Condition", true, typeof(bool), 0), NodeElementArchetype.Factory.Input(1, "False", true, null, 1, 0), NodeElementArchetype.Factory.Input(2, "True", true, null, 2, 1), NodeElementArchetype.Factory.Output(0, string.Empty, null, 3) } }, new NodeArchetype { TypeID = 8, Title = "Switch On Enum", Create = (id, context, arch, groupArch) => new SwitchOnEnumNode(id, context, arch, groupArch), Description = "Returns one of the input values based on the enum value", Flags = NodeFlags.VisualScriptGraph | NodeFlags.AnimGraph, Size = new Float2(160, 60), DefaultValues = new object[] { Utils.GetEmptyArray<byte>() }, ConnectionsHints = ConnectionsHint.Enum, Elements = new[] { NodeElementArchetype.Factory.Input(0, "Value", true, null, 0), NodeElementArchetype.Factory.Output(0, string.Empty, null, 1), } }, }; } }
412
0.903085
1
0.903085
game-dev
MEDIA
0.387621
game-dev
0.80577
1
0.80577
PixeyeHQ/actors.unity
1,370
Runtime/Attributes/ExcludeByAttribute.cs
// Project : ecs.unity.structs // Contacts : Pix - ask@pixeye.games using System; using System.Collections.Generic; using UnityEngine; namespace Pixeye.Actors { public class ExcludeByAttribute : Attribute { public int[] filter = new int[0]; public int[] filterType = new int[0]; public ExcludeByAttribute(params int[] filter) { this.filter = filter; } public ExcludeByAttribute(params object[] args) { var f = new List<int>(); var fType = new List<int>(); for (int i = 0; i < args.Length; i++) { var o = args[i]; if (o is string) { fType.Add(Storage.TypeNames[ByName(o.ToString()).GetHashCode()]); } else f.Add((int) o); } filterType = fType.ToArray(); filter = f.ToArray(); } public ExcludeByAttribute(params string[] args) { var fType = new List<int>(); for (int i = 0; i < args.Length; i++) { fType.Add(Storage.TypeNames[ByName(args[i]).GetHashCode()]); } filterType = fType.ToArray(); } public static Type ByName(string name) { foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var tt = assembly.GetType(name); if (tt != null) { return tt; } } return null; } } }
412
0.848133
1
0.848133
game-dev
MEDIA
0.613
game-dev
0.971244
1
0.971244
Sumandora/tarasande
1,783
src/main/java/su/mandora/tarasande/injection/mixin/feature/module/item/MixinTridentItem.java
package su.mandora.tarasande.injection.mixin.feature.module.item; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.TridentItem; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArgs; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.invoke.arg.Args; import su.mandora.tarasande.system.feature.modulesystem.ManagerModule; import su.mandora.tarasande.system.feature.modulesystem.impl.movement.ModuleTridentBoost; @Mixin(TridentItem.class) public class MixinTridentItem { @ModifyArgs(method = "onStoppedUsing", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;addVelocity(DDD)V")) public void hookTridentBoost(Args args) { ModuleTridentBoost moduleTridentBoost = ManagerModule.INSTANCE.get(ModuleTridentBoost.class); if (moduleTridentBoost.getEnabled().getValue()) { double multiplier = moduleTridentBoost.getMultiplier().getValue(); args.set(0, (double) args.get(0) * multiplier); args.set(1, (double) args.get(1) * multiplier); args.set(2, (double) args.get(2) * multiplier); } } @Redirect(method = {"use", "onStoppedUsing"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;isTouchingWaterOrRain()Z")) public boolean hookTridentBoost_use(PlayerEntity instance) { ModuleTridentBoost moduleTridentBoost = ManagerModule.INSTANCE.get(ModuleTridentBoost.class); if (moduleTridentBoost.getEnabled().getValue() && moduleTridentBoost.getAllowOutOfWater().getValue()) return true; return instance.isTouchingWaterOrRain(); } }
412
0.849533
1
0.849533
game-dev
MEDIA
0.922518
game-dev
0.820185
1
0.820185
machinelabs/machinelabs
4,677
server/src/messaging/recycling/recycle-accumulator.ts
import { Observable, of, timer, throwError } from 'rxjs'; import { map, takeUntil, mergeMap, switchMap, catchError } from 'rxjs/operators'; import { ExecutionMessage } from '../../models/execution'; import { RecycleCmdInfo, recycleCmdFactory } from './recycle-cmd-factory'; import { MessageRepository } from '../message-repository'; import { RecycleConfig } from './recycle.service'; export class RecycleAccumulator { index = 0; virtualIndex = 0; triggerIndex = 0; message: ExecutionMessage = null; constructor(private executionId: string, private config: RecycleConfig) { this.triggerIndex = config.triggerIndex; } pass(acc: RecycleAccumulator, message: ExecutionMessage): Observable<RecycleAccumulator> { return this.invoke(acc.clone(), message); } private invoke(acc: RecycleAccumulator, message: ExecutionMessage): Observable<RecycleAccumulator> { Object.assign(message, { index: acc.index, virtual_index: acc.virtualIndex }); acc.message = message; return this.recycleOrContinue(acc).pipe( map((currentAcc: RecycleAccumulator) => { currentAcc.index++; currentAcc.virtualIndex++; return currentAcc; }) ); } private recycleOrContinue(acc: RecycleAccumulator): Observable<RecycleAccumulator> { if (acc.index === acc.triggerIndex) { const recycleId = Date.now(); console.log(`RecycleId ${recycleId} at ${Date.now()}: Entering recycle phase`); const fromVirtualIndex = acc.virtualIndex - this.config.tailLength; const toVirtualIndex = acc.virtualIndex - 1; const expectedPatchCount = this.config.tailLength - this.config.deleteCount; return this.config.messageRepository.getMessages(this.executionId, fromVirtualIndex, toVirtualIndex).pipe( takeUntil(timer(this.config.getMessageTimeout).pipe(switchMap(() => throwError(new Error('Timeout'))))), mergeMap(messages => { const cmdInfo = recycleCmdFactory(this.executionId, messages, this.config.deleteCount); if (cmdInfo.patched === expectedPatchCount && cmdInfo.removed === this.config.deleteCount) { console.log( `RecycleId ${recycleId} at ${Date.now()}: About to bulk update messages to recycled space for execution ${ this.executionId }` ); this.config.messageRepository.bulkUpdate(cmdInfo.cmd).subscribe( () => { console.log( `RecycleId ${recycleId} at ${Date.now()}: Bulk update completed for execution ${this.executionId}` ); }, err => { // Not exactly sure what we should do here. We need to take this into account for // the index somehow. But I don't know yet if we would ever run into this with the // Realtime API. console.error( `RecycleId ${recycleId} at ${Date.now()}: Unexpected error during bulk update of message recycling for execution ${ this.executionId }` ); // tslint:disable-line:max-line-length console.error(err); } ); console.log(`RecycleId ${recycleId} at ${Date.now()}: Sent bulk update for execution ${this.executionId}`); acc.index = acc.index - this.config.deleteCount; acc.message.index = acc.index; return of(acc); } console.error(`RecycleId ${recycleId} at ${Date.now()}: Skipped recycling unexpectedly`); console.error(`patched / expected patched: ${cmdInfo.patched} / ${expectedPatchCount}`); console.error(`removed / expected removed: ${cmdInfo.removed} / ${this.config.deleteCount}`); this.increaseTriggerIndex(acc); return of(acc); }), catchError(err => { console.error( `RecycleId ${recycleId} at ${Date.now()}: Unexpected error during 'getMessages' of message recycling for execution ${ this.executionId }` ); console.error(err); this.increaseTriggerIndex(acc); return of(acc); }) ); } return of(acc); } private increaseTriggerIndex(acc: RecycleAccumulator) { acc.triggerIndex = acc.triggerIndex + this.config.triggerIndexStep; } clone(): RecycleAccumulator { const acc = new RecycleAccumulator(this.executionId, this.config); acc.index = this.index; acc.virtualIndex = this.virtualIndex; acc.message = this.message; acc.triggerIndex = this.triggerIndex; return acc; } }
412
0.789731
1
0.789731
game-dev
MEDIA
0.329212
game-dev
0.869842
1
0.869842
PotRooms/AzurPromiliaData
2,251
Lua/src/ui/pages/heroPanel/skill/cellHeroSkillIcon.lua
local module = class("cellHeroSkillIcon", G_UIModuleBase) function module.bind() return { isActive = false, iconPath = "", isLock = false, isblankBg = false, glowAcitve = false } end function module.methods() return { onClick = function(self) if not self.bind.isActive then C_AudioManager.Play("Play_SFX_System_UI_CHAR_Skill_Click") self.bindComponents.selectAnimation:Play("anim_heroes_skill_cell_select_show") self:emit("onClick", self.bind) end end } end function module:open() self.bindComponents.redot.gameObject:SetActive(false) Timer.once(0.5, function() self:bindRed() end, self) end function module:bindRed() if not self.isBind then return end local heroId = self.bind.heroId local skillId = self.bind.skillId self.bindComponents.redot.gameObject:SetActive(false) if heroId and skillId and self.bind.showRed then if self.bind.isPreview then self.bindComponents.redot.gameObject:SetActive(false) else L_ReddotManager:registerReddot(self.bindComponents.redot, string.format(L_ReddotManager.DotDef.HeroSkill, heroId .. "_" .. skillId)) end end end function module:refresh() if not self.isBind then return end local skillId = self.bind.skillId local skillTpl = L_GameTpl:getSkillTpl() local tplSkill = skillTpl:getTplById(skillId) local elementId = 1 local elementList = skillTpl:getSkillElement(tplSkill) if not table.isEmpty(elementList) and 0 < #elementList then elementId = elementList[1] end self.bindComponents["level" .. elementId].text = self.bind.levelText for i = 1, 10 do if i == elementId then self.bindComponents["level" .. i].gameObject:SetActive(true) else self.bindComponents["level" .. i].gameObject:SetActive(false) end end self.bind.glowAcitve = self.bind.isActive if self.bind.isLock then self.bindComponents["level" .. elementId].text = "" end end function module:playLevelUpAni() if self.bindComponents == nil then return end self.bindComponents.skill_cell:Stop() C_AudioManager.Play("Play_SFX_System_UI_CHAR_Skill_Upgrade") self.bindComponents.skill_cell:Play("anim_heroes_skill_cell_levelup") end return module
412
0.789376
1
0.789376
game-dev
MEDIA
0.970179
game-dev
0.753796
1
0.753796
TheFlyingFoool/DuckGameRebuilt
3,442
DuckGame/src/DuckGame/SmartDuck/DuckAI.cs
using System.Collections.Generic; namespace DuckGame { public class DuckAI : InputProfile { public AILocomotion locomotion { get { return _locomotion; } } public void Press(string trigger) { _inputState[trigger] = InputState.Pressed; } public void HoldDown(string trigger) { _inputState[trigger] = InputState.Down; } public void Release(string trigger) { _inputState[trigger] = InputState.Released; } public override bool Pressed(string trigger, bool any = false) { InputState outVal; return _inputState.TryGetValue(trigger, out outVal) && outVal == InputState.Pressed; } public override bool Released(string trigger) { InputState outVal; return _inputState.TryGetValue(trigger, out outVal) && outVal == InputState.Released; } public override bool Down(string trigger) { InputState outVal; return _inputState.TryGetValue(trigger, out outVal) && (outVal == InputState.Pressed || outVal == InputState.Down); } public bool SetTarget(Vec2 t) { _locomotion.target = t; return _locomotion.target == Vec2.Zero; } public void TrimLastTarget() { _locomotion.TrimLastTarget(); } public DuckAI(InputProfile manualQuacker = null) : base("") { _state.Push(new AIStateDeathmatchBot()); _manualQuack = manualQuacker; } public virtual void Update(Duck duck) { Release(Triggers.Grab); Release(Triggers.Shoot); _locomotion.Update(this, duck); if (jumpWait > 0) { jumpWait--; } else { jumpWait = 10; _locomotion.Jump(5); } if (quackWait > 0) { quackWait--; return; } quackWait = 4; _locomotion.Quack(2); } public override void UpdateExtraInput() { if (_inputState.ContainsKey(Triggers.Quack) && _inputState[Triggers.Quack] == InputState.Pressed) { _inputState[Triggers.Quack] = InputState.Down; } if (_inputState.ContainsKey(Triggers.Strafe) && _inputState[Triggers.Strafe] == InputState.Pressed) { _inputState[Triggers.Strafe] = InputState.Down; } if (_manualQuack != null) { if (_manualQuack.Pressed(Triggers.Quack, false)) { Press(Triggers.Quack); } else if (_manualQuack.Released(Triggers.Quack)) { Release(Triggers.Quack); } if (_manualQuack.Pressed(Triggers.Strafe, false)) { Press(Triggers.Strafe); return; } if (_manualQuack.Released(Triggers.Strafe)) { Release(Triggers.Strafe); } } } public override float leftTrigger { get { if (virtualQuack) { return virtualDevice.leftTrigger; } if (_manualQuack != null) { return _manualQuack.leftTrigger; } return 0f; } } public void Draw() { if (_locomotion.pathFinder.path != null) { Vec2 lastNode = Vec2.Zero; foreach (PathNodeLink i in _locomotion.pathFinder.path) { if (lastNode != Vec2.Zero) { Graphics.DrawLine(lastNode, i.owner.position, new Color(255, 0, 255), 2f, 0.9f); } lastNode = i.owner.position; } } } private Stack<AIState> _state = new Stack<AIState>(); private Dictionary<string, InputState> _inputState = new Dictionary<string, InputState>(); private AILocomotion _locomotion = new AILocomotion(); public bool canRefresh; public InputProfile _manualQuack; private int quackWait = 10; private int jumpWait = 10; public bool virtualQuack; } }
412
0.951655
1
0.951655
game-dev
MEDIA
0.898131
game-dev
0.769457
1
0.769457
FTBTeam/FTB-Chunks
6,483
common/src/main/java/dev/ftb/mods/ftbchunks/client/gui/RegionMapPanel.java
package dev.ftb.mods.ftbchunks.client.gui; import dev.ftb.mods.ftbchunks.api.client.event.MapIconEvent; import dev.ftb.mods.ftbchunks.api.client.icon.MapIcon; import dev.ftb.mods.ftbchunks.api.client.icon.MapType; import dev.ftb.mods.ftbchunks.client.map.MapChunk; import dev.ftb.mods.ftbchunks.client.map.MapRegion; import dev.ftb.mods.ftbchunks.client.map.MapRegionData; import dev.ftb.mods.ftbchunks.client.mapicon.MapIconComparator; import dev.ftb.mods.ftbchunks.util.HeightUtils; import dev.ftb.mods.ftblibrary.math.MathUtils; import dev.ftb.mods.ftblibrary.math.XZ; import dev.ftb.mods.ftblibrary.ui.Panel; import dev.ftb.mods.ftblibrary.ui.Theme; import dev.ftb.mods.ftblibrary.ui.Widget; import dev.ftb.mods.ftblibrary.ui.input.MouseButton; import dev.ftb.mods.ftblibrary.util.TooltipList; import dev.ftb.mods.ftbteams.api.Team; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.core.BlockPos; import net.minecraft.util.Mth; import java.util.ArrayList; import java.util.List; public class RegionMapPanel extends Panel { final LargeMapScreen largeMap; double regionX = 0; double regionZ = 0; int regionMinX, regionMinZ, regionMaxX, regionMaxZ; int blockX = 0; int blockY = HeightUtils.UNKNOWN; int blockZ = 0; int blockIndex = 0; private final List<MapIcon> mapIcons; public RegionMapPanel(LargeMapScreen panel) { super(panel); largeMap = panel; mapIcons = new ArrayList<>(); } public void updateMinMax() { regionMinX = Integer.MAX_VALUE; regionMinZ = Integer.MAX_VALUE; regionMaxX = Integer.MIN_VALUE; regionMaxZ = Integer.MIN_VALUE; for (Widget w : widgets) { if (w instanceof MapTileWidget tileWidget) { int qx = tileWidget.region.pos.x(); int qy = tileWidget.region.pos.z(); regionMinX = Math.min(regionMinX, qx); regionMinZ = Math.min(regionMinZ, qy); regionMaxX = Math.max(regionMaxX, qx); regionMaxZ = Math.max(regionMaxZ, qy); } } if (regionMinX == Integer.MAX_VALUE) { regionMinX = regionMinZ = regionMaxX = regionMaxZ = 0; } regionMinX -= 100; regionMinZ -= 100; regionMaxX += 101; regionMaxZ += 101; } public BlockPos blockPos() { return new BlockPos(blockX, blockY, blockZ); } public void scrollTo(double x, double y) { updateMinMax(); double dx = (regionMaxX - regionMinX); double dy = (regionMaxZ - regionMinZ); setScrollX((x - regionMinX) / dx * largeMap.scrollWidth - width / 2D); setScrollY((y - regionMinZ) / dy * largeMap.scrollHeight - height / 2D); } public void resetScroll() { alignWidgets(); setScrollX((largeMap.scrollWidth - width) / 2D); setScrollY((largeMap.scrollHeight - height) / 2D); } @Override public void addWidgets() { for (MapRegion region : largeMap.dimension.getRegions().values()) { add(new MapTileWidget(this, region)); } Minecraft mc = Minecraft.getInstance(); mapIcons.clear(); MapIconEvent.LARGE_MAP.invoker().accept(new MapIconEvent(largeMap.dimension.dimension, mapIcons, MapType.LARGE_MAP)); if (mapIcons.size() >= 2) { mapIcons.sort(new MapIconComparator(mc.player.position(), 1F)); } for (MapIcon icon : mapIcons) { if (icon.isVisible(MapType.LARGE_MAP, MathUtils.dist(mc.player.getX(), mc.player.getZ(), icon.getPos(1F).x, icon.getPos(1F).z), false)) { add(new MapIconWidget(this, icon)); } } alignWidgets(); } @Override public void alignWidgets() { largeMap.scrollWidth = 0; largeMap.scrollHeight = 0; updateMinMax(); int buttonSize = largeMap.getRegionTileSize(); largeMap.scrollWidth = (regionMaxX - regionMinX) * buttonSize; largeMap.scrollHeight = (regionMaxZ - regionMinZ) * buttonSize; for (Widget w : widgets) { if (w instanceof MapTileWidget tileWidget) { double qx = tileWidget.region.pos.x(); double qy = tileWidget.region.pos.z(); double qw = 1D; double qh = 1D; double x = (qx - regionMinX) * buttonSize; double y = (qy - regionMinZ) * buttonSize; w.setPosAndSize((int) x, (int) y, (int) (buttonSize * qw), (int) (buttonSize * qh)); } else if (w instanceof MapIconWidget iconWidget) { MapIcon mapIcon = iconWidget.getMapIcon(); double s = Math.max(mapIcon.isZoomDependant(MapType.LARGE_MAP) ? 0D : 6D, buttonSize / 128D * mapIcon.getIconScale(MapType.LARGE_MAP)); if (s <= 1D) { w.setSize(0, 0); } else { w.setSize(Mth.ceil(s), Mth.ceil(s)); iconWidget.updatePosition(1F); } } } setPosAndSize(0, 0, parent.width, parent.height); } @Override public void draw(GuiGraphics graphics, Theme theme, int x, int y, int w, int h) { super.draw(graphics, theme, x, y, w, h); int dx = (regionMaxX - regionMinX); int dy = (regionMaxZ - regionMinZ); double px = getScrollX() - getX(); double py = getScrollY() - getY(); regionX = (parent.getMouseX() + px) / (double) largeMap.scrollWidth * dx + regionMinX; regionZ = (parent.getMouseY() + py) / (double) largeMap.scrollHeight * dy + regionMinZ; blockX = Mth.floor(regionX * 512D); blockZ = Mth.floor(regionZ * 512D); blockIndex = (blockX & 511) + (blockZ & 511) * 512; blockY = HeightUtils.UNKNOWN; MapRegion region = largeMap.dimension.getRegions().get(XZ.regionFromBlock(blockX, blockZ)); if (region != null) { MapRegionData data = region.getData(); if (data != null) { blockY = data.height[blockIndex]; } } } @Override public void addMouseOverText(TooltipList list) { super.addMouseOverText(list); MapRegion mapRegion = largeMap.dimension.getRegions().get(XZ.regionFromBlock(blockX, blockZ)); if (mapRegion != null) { MapRegionData data = mapRegion.getData(); if (data != null) { MapChunk mapChunk = mapRegion.getMapChunk(XZ.of((blockX >> 4) & 31, (blockZ >> 4) & 31)); Team team = mapChunk == null ? null : mapChunk.getTeam().orElse(null); if (team != null) { list.add(team.getName()); } } } } @Override public boolean mousePressed(MouseButton button) { if (super.mousePressed(button)) { return true; } if (button.isLeft() && isMouseOver()) { largeMap.prevMouseX = getMouseX(); largeMap.prevMouseY = getMouseY(); largeMap.grabbed = 1; return true; } return false; } @Override public void mouseReleased(MouseButton button) { super.mouseReleased(button); largeMap.grabbed = 0; } @Override public boolean scrollPanel(double scroll) { if (isMouseOver()) { largeMap.addZoom(scroll); return true; } return false; } }
412
0.884084
1
0.884084
game-dev
MEDIA
0.725587
game-dev
0.932223
1
0.932223
Goob-Station/Goob-Station
9,181
Content.Server/Arcade/BlockGame/BlockGame.Pieces.cs
// SPDX-FileCopyrightText: 2023 TemporalOroboros <TemporalOroboros@gmail.com> // SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com> // // SPDX-License-Identifier: MIT using Content.Shared.Arcade; using System.Linq; namespace Content.Server.Arcade.BlockGame; public sealed partial class BlockGame { /// <summary> /// The set of types of game pieces that exist. /// Used as templates when creating pieces for the game. /// </summary> private readonly BlockGamePieceType[] _allBlockGamePieces; /// <summary> /// The set of types of game pieces that exist. /// Used to generate the templates used when creating pieces for the game. /// </summary> private enum BlockGamePieceType { I, L, LInverted, S, SInverted, T, O } /// <summary> /// The set of possible rotations for the game pieces. /// </summary> private enum BlockGamePieceRotation { North, East, South, West } /// <summary> /// A static extension for the rotations that allows rotating through the possible rotations. /// </summary> private static BlockGamePieceRotation Next(BlockGamePieceRotation rotation, bool inverted) { return rotation switch { BlockGamePieceRotation.North => inverted ? BlockGamePieceRotation.West : BlockGamePieceRotation.East, BlockGamePieceRotation.East => inverted ? BlockGamePieceRotation.North : BlockGamePieceRotation.South, BlockGamePieceRotation.South => inverted ? BlockGamePieceRotation.East : BlockGamePieceRotation.West, BlockGamePieceRotation.West => inverted ? BlockGamePieceRotation.South : BlockGamePieceRotation.North, _ => throw new ArgumentOutOfRangeException(nameof(rotation), rotation, null) }; } /// <summary> /// A static extension for the rotations that allows rotating through the possible rotations. /// </summary> private struct BlockGamePiece { /// <summary> /// Where all of the blocks that make up this piece are located relative to the origin of the piece. /// </summary> public Vector2i[] Offsets; /// <summary> /// The color of all of the blocks that make up this piece. /// </summary> private BlockGameBlock.BlockGameBlockColor _gameBlockColor; /// <summary> /// Whether or not the block should be able to rotate about its origin. /// </summary> public bool CanSpin; /// <summary> /// Generates a list of the positions of each block comprising this game piece in worldspace. /// </summary> /// <param name="center">The position of the game piece in worldspace.</param> /// <param name="rotation">The rotation of the game piece in worldspace.</param> public readonly Vector2i[] Positions(Vector2i center, BlockGamePieceRotation rotation) { return RotatedOffsets(rotation).Select(v => center + v).ToArray(); } /// <summary> /// Gets the relative position of each block comprising this piece given a rotation. /// </summary> /// <param name="rotation">The rotation to be applied to the local position of the blocks in this piece.</param> private readonly Vector2i[] RotatedOffsets(BlockGamePieceRotation rotation) { var rotatedOffsets = (Vector2i[]) Offsets.Clone(); //until i find a better algo var amount = rotation switch { BlockGamePieceRotation.North => 0, BlockGamePieceRotation.East => 1, BlockGamePieceRotation.South => 2, BlockGamePieceRotation.West => 3, _ => 0 }; for (var i = 0; i < amount; i++) { for (var j = 0; j < rotatedOffsets.Length; j++) { rotatedOffsets[j] = rotatedOffsets[j].Rotate90DegreesAsOffset(); } } return rotatedOffsets; } /// <summary> /// Gets a list of all of the blocks comprising this piece in worldspace. /// </summary> /// <param name="center">The position of the game piece in worldspace.</param> /// <param name="rotation">The rotation of the game piece in worldspace.</param> public readonly BlockGameBlock[] Blocks(Vector2i center, BlockGamePieceRotation rotation) { var positions = Positions(center, rotation); var result = new BlockGameBlock[positions.Length]; var i = 0; foreach (var position in positions) { result[i++] = position.ToBlockGameBlock(_gameBlockColor); } return result; } /// <summary> /// Gets a list of all of the blocks comprising this piece in worldspace. /// Used to generate the held piece/next piece preview images. /// </summary> public readonly BlockGameBlock[] BlocksForPreview() { var xOffset = 0; var yOffset = 0; foreach (var offset in Offsets) { if (offset.X < xOffset) xOffset = offset.X; if (offset.Y < yOffset) yOffset = offset.Y; } return Blocks(new Vector2i(-xOffset, -yOffset), BlockGamePieceRotation.North); } /// <summary> /// Generates a game piece for a given type of game piece. /// See <see cref="BlockGamePieceType"/> for the available options. /// </summary> /// <param name="type">The type of game piece to generate.</param> public static BlockGamePiece GetPiece(BlockGamePieceType type) { //switch statement, hardcoded offsets return type switch { BlockGamePieceType.I => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(0, 0), new Vector2i(0, 1), new Vector2i(0, 2), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.LightBlue, CanSpin = true }, BlockGamePieceType.L => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(0, 0), new Vector2i(0, 1), new Vector2i(1, 1), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Orange, CanSpin = true }, BlockGamePieceType.LInverted => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(0, 0), new Vector2i(-1, 1), new Vector2i(0, 1), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Blue, CanSpin = true }, BlockGamePieceType.S => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(1, -1), new Vector2i(-1, 0), new Vector2i(0, 0), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Green, CanSpin = true }, BlockGamePieceType.SInverted => new BlockGamePiece { Offsets = new[] { new Vector2i(-1, -1), new Vector2i(0, -1), new Vector2i(0, 0), new Vector2i(1, 0), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Red, CanSpin = true }, BlockGamePieceType.T => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(-1, 0), new Vector2i(0, 0), new Vector2i(1, 0), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Purple, CanSpin = true }, BlockGamePieceType.O => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(1, -1), new Vector2i(0, 0), new Vector2i(1, 0), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Yellow, CanSpin = false }, _ => new BlockGamePiece { Offsets = new[] { new Vector2i(0, 0) } }, }; } } }
412
0.937224
1
0.937224
game-dev
MEDIA
0.913541
game-dev
0.587592
1
0.587592
ProjectIgnis/CardScripts
2,573
official/c12079734.lua
--デルタトライ --Delta Tri local s,id=GetID() function s.initial_effect(c) --Apply effects local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCode(EVENT_BATTLE_DESTROYING) e1:SetCondition(aux.bdocon) e1:SetTarget(s.target) e1:SetOperation(s.operation) c:RegisterEffect(e1) end function s.filter1(c,ec) return c:IsType(TYPE_UNION) and c:CheckUnionTarget(ec) and aux.CheckUnionEquip(c,ec) end function s.filter2(c) return c:IsFaceup() and c:IsRace(RACE_MACHINE) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsAbleToDeck() end function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) local c=e:GetHandler() if chkc then if e:GetLabel()==0 then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and s.filter1(chkc,c) else return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and s.filter2(chkc) end end local b1=Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and Duel.IsExistingTarget(s.filter1,tp,LOCATION_GRAVE,0,1,nil,c) local b2=Duel.IsExistingTarget(s.filter2,tp,LOCATION_MZONE,0,1,nil) and Duel.IsPlayerCanDraw(tp,1) if chk==0 then return b1 or b2 end local op=0 if b1 and b2 then op=Duel.SelectOption(tp,aux.Stringid(id,1),aux.Stringid(id,2)) elseif b1 then op=Duel.SelectOption(tp,aux.Stringid(id,1)) else op=Duel.SelectOption(tp,aux.Stringid(id,2))+1 end e:SetLabel(op) if op==0 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) local g=Duel.SelectTarget(tp,s.filter1,tp,LOCATION_GRAVE,0,1,1,nil,c) e:SetCategory(CATEGORY_EQUIP) Duel.SetOperationInfo(0,CATEGORY_LEAVE_GRAVE,g,1,0,0) else Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local g=Duel.SelectTarget(tp,s.filter2,tp,LOCATION_MZONE,0,1,1,nil) e:SetCategory(CATEGORY_TODECK+CATEGORY_DRAW) Duel.SetOperationInfo(0,CATEGORY_TODECK,g,1,0,0) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end end function s.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if e:GetLabel()==0 then local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() and tc and tc:IsRelateToEffect(e) and Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and aux.CheckUnionEquip(tc,c) and Duel.Equip(tp,tc,c,false) then aux.SetUnionState(tc) end else if tc and tc:IsRelateToEffect(e) and Duel.SendtoDeck(tc,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)~=0 and tc:IsLocation(LOCATION_DECK|LOCATION_EXTRA) then if tc:IsLocation(LOCATION_DECK) then Duel.ShuffleDeck(tp) end Duel.BreakEffect() Duel.Draw(tp,1,REASON_EFFECT) end end end
412
0.887055
1
0.887055
game-dev
MEDIA
0.980341
game-dev
0.954517
1
0.954517
BuildCraft/BuildCraft
1,708
common/buildcraft/core/block/BlockMarkerPath.java
/* Copyright (c) 2016 SpaceToad and the BuildCraft team * * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package buildcraft.core.block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import buildcraft.lib.block.BlockMarkerBase; import buildcraft.lib.misc.PermissionUtil; import buildcraft.lib.tile.TileBC_Neptune; import buildcraft.core.tile.TileMarkerPath; public class BlockMarkerPath extends BlockMarkerBase { public BlockMarkerPath(Material material, String id) { super(material, id); } @Override public TileBC_Neptune createTileEntity(World worldIn, IBlockState state) { return new TileMarkerPath(); } @Override public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { if (!world.isRemote) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileMarkerPath) { TileMarkerPath marker = (TileMarkerPath) tile; if (PermissionUtil.hasPermission(PermissionUtil.PERM_EDIT, player, marker.getPermBlock())) { marker.reverseDirection(); } } } return true; } }
412
0.626409
1
0.626409
game-dev
MEDIA
0.994524
game-dev
0.551268
1
0.551268
PascalCorpsman/FPC_DOOM
6,799
src/units/p_local.pas
Unit p_local; {$MODE ObjFPC}{$H+} Interface Uses ufpc_doom_types, Classes, SysUtils , info_types , m_fixed ; Const // [crispy] blinking key or skull in the status bar KEYBLINKMASK = $8; KEYBLINKTICS = (7 * KEYBLINKMASK); TOCENTER = -8; AFLAG_JUMP = $80; FLOATSPEED = (FRACUNIT * 4); MAXHEALTH = 100; DEFINE_VIEWHEIGHT = (41 * FRACUNIT); // mapblocks are used to check movement // against lines and things MAPBLOCKUNITS = 128; MAPBLOCKSIZE = (MAPBLOCKUNITS * FRACUNIT); MAPBLOCKSHIFT = (FRACBITS + 7); MAPBMASK = (MAPBLOCKSIZE - 1); MAPBTOFRAC = (MAPBLOCKSHIFT - FRACBITS); // player radius for movement checking PLAYERRADIUS = 16 * FRACUNIT; // MAXRADIUS is for precalculated sector block boxes // the spider demon is larger, // but we do not have any moving sectors nearby MAXRADIUS = 32 * FRACUNIT; GRAVITY = FRACUNIT; MAXMOVE = (30 * FRACUNIT); USERANGE = (64 * FRACUNIT); MELEERANGE = (64 * FRACUNIT); MISSILERANGE = (32 * 64 * FRACUNIT); // follow a player exlusively for 3 seconds BASETHRESHOLD = 100; // fraggle: I have increased the size of this buffer. In the original Doom, // overrunning past this limit caused other bits of memory to be overwritten, // affecting demo playback. However, in doing so, the limit was still // exceeded. So we have to support more than 8 specials. // // We keep the original limit, to detect what variables in memory were // overwritten (see SpechitOverrun()) MAXSPECIALCROSS = 20; MAXSPECIALCROSS_ORIGINAL = 8; // // P_TICK // // both the head and tail of the thinker list //extern thinker_t thinkercap; //void P_InitThinkers (void); //void P_AddThinker (thinker_t* thinker); //void P_RemoveThinker (thinker_t* thinker); // // P_PSPR // //void P_SetupPsprites (player_t* curplayer); //void P_MovePsprites (player_t* curplayer); //void P_DropWeapon (player_t* player); // // P_USER // Const MLOOKUNIT = 8; // // P_MOBJ // ONFLOORZ = INT_MIN; ONCEILINGZ = INT_MAX; // Time interval for item respawning. ITEMQUESIZE = 128; Type // // P_MAPUTL // divline_t = Record x: fixed_t; y: fixed_t; dx: fixed_t; dy: fixed_t; End; Pdivline_t = ^divline_t; dt = Record Case boolean Of true: (thing: pmobj_t); false: (line: pline_t); End; intercept_t = Record frac: fixed_t; // along trace line isaline: boolean; d: dt; End; Pintercept_t = ^intercept_t; traverser_t = Function(_in: Pintercept_t): Boolean; //// Extended MAXINTERCEPTS, to allow for intercepts overrun emulation. // Const MAXINTERCEPTS_ORIGINAL = 128; //#define MAXINTERCEPTS (MAXINTERCEPTS_ORIGINAL + 61) // ////extern intercept_t intercepts[MAXINTERCEPTS]; // [crispy] remove INTERCEPTS limit //extern intercept_t* intercept_p; // //typedef boolean (*traverser_t) (intercept_t *in); // //fixed_t P_AproxDistance (fixed_t dx, fixed_t dy); //int P_PointOnLineSide (fixed_t x, fixed_t y, line_t* line); //int P_PointOnDivlineSide (fixed_t x, fixed_t y, divline_t* line); //void P_MakeDivline (line_t* li, divline_t* dl); //fixed_t P_InterceptVector (divline_t* v2, divline_t* v1); //int P_BoxOnLineSide (fixed_t* tmbox, line_t* ld); // //extern fixed_t opentop; //extern fixed_t openbottom; //extern fixed_t openrange; //extern fixed_t lowfloor; // //void P_LineOpening (line_t* linedef); // //boolean P_BlockLinesIterator (int x, int y, boolean(*func)(line_t*) ); //boolean P_BlockThingsIterator (int x, int y, boolean(*func)(mobj_t*) ); Const PT_ADDLINES = 1; PT_ADDTHINGS = 2; PT_EARLYOUT = 4; //extern divline_t trace; // //boolean //P_PathTraverse //( fixed_t x1, // fixed_t y1, // fixed_t x2, // fixed_t y2, // int flags, // boolean (*trav) (intercept_t *)); // //void P_UnsetThingPosition (mobj_t* thing); //void P_SetThingPosition (mobj_t* thing); // // //// //// P_MAP //// // //// If "floatok" true, move would be ok //// if within "tmfloorz - tmceilingz". //extern boolean floatok; //extern fixed_t tmfloorz; //extern fixed_t tmceilingz; // // //extern line_t* ceilingline; // //// fraggle: I have increased the size of this buffer. In the original Doom, //// overrunning past this limit caused other bits of memory to be overwritten, //// affecting demo playback. However, in doing so, the limit was still //// exceeded. So we have to support more than 8 specials. //// //// We keep the original limit, to detect what variables in memory were //// overwritten (see SpechitOverrun()) // //#define MAXSPECIALCROSS 20 //#define MAXSPECIALCROSS_ORIGINAL 8 // //extern line_t** spechit; // [crispy] remove SPECHIT limit //extern int numspechit; // //boolean P_CheckPosition (mobj_t *thing, fixed_t x, fixed_t y); //boolean P_TryMove (mobj_t* thing, fixed_t x, fixed_t y); //boolean P_TeleportMove (mobj_t* thing, fixed_t x, fixed_t y); //void P_SlideMove (mobj_t* mo); //boolean P_CheckSight (mobj_t* t1, mobj_t* t2); //void P_UseLines (player_t* player); // //boolean P_ChangeSector (sector_t* sector, boolean crunch); // //extern mobj_t* linetarget; // who got hit (or NULL) // // //extern fixed_t attackrange; // //// slopes to top and bottom of target //extern fixed_t topslope; //extern fixed_t bottomslope; //fixed_t //P_AimLineAttack //( mobj_t* t1, // angle_t angle, // fixed_t distance ); //void //P_RadiusAttack //( mobj_t* spot, // mobj_t* source, // int damage ); //// //// P_SETUP //// //extern byte* rejectmatrix; // for fast sight rejection //extern int32_t* blockmaplump; // offsets in blockmap are from here // [crispy] BLOCKMAP limit //extern int32_t* blockmap; // [crispy] BLOCKMAP limit //extern int bmapwidth; //extern int bmapheight; // in mapblocks //extern fixed_t bmaporgx; //extern fixed_t bmaporgy; // origin of block map //extern mobj_t** blocklinks; // for thing chains // //// [crispy] factor out map lump name and number finding into a separate function //extern int P_GetNumForMap (int episode, int map, boolean critical); //extern int st_keyorskull[3]; // //// //// P_INTER //// //extern int maxammo[NUMAMMO]; //extern int clipammo[NUMAMMO]; // //void //P_TouchSpecialThing //( mobj_t* special, // mobj_t* toucher ); // //void //P_DamageMobj //( mobj_t* target, // mobj_t* inflictor, // mobj_t* source, // int damage ); Function PLAYER_SLOPE(a: pplayer_t): fixed_t; Implementation Function PLAYER_SLOPE(a: pplayer_t): fixed_t; Begin result := SarLongint(a^.lookdir Div MLOOKUNIT, FRACBITS) Div 173; End; End.
412
0.944827
1
0.944827
game-dev
MEDIA
0.879939
game-dev
0.850725
1
0.850725
vcmi/vcmi
3,705
lib/gameState/TavernHeroesPool.cpp
/* * TavernHeroesPool.cpp, part of VCMI engine * * Authors: listed in file AUTHORS in main folder * * License: GNU General Public License v2.0 or later * Full text of license available in license.txt file, in main folder * */ #include "StdInc.h" #include "TavernHeroesPool.h" #include "CGameState.h" #include "../mapObjects/CGHeroInstance.h" #include "../mapping/CMap.h" VCMI_LIB_NAMESPACE_BEGIN TavernHeroesPool::TavernHeroesPool(CGameState * owner) : owner(owner) {} void TavernHeroesPool::setGameState(CGameState * newOwner) { owner = newOwner; } std::map<HeroTypeID, CGHeroInstance*> TavernHeroesPool::unusedHeroesFromPool() const { std::map<HeroTypeID, CGHeroInstance*> pool; for (const auto & hero : heroesPool) pool[hero] = owner->getMap().tryGetFromHeroPool(hero); for(const auto & slot : currentTavern) pool.erase(slot.hero); return pool; } TavernSlotRole TavernHeroesPool::getSlotRole(HeroTypeID hero) const { for (auto const & slot : currentTavern) { if (slot.hero == hero) return slot.role; } return TavernSlotRole::NONE; } void TavernHeroesPool::setHeroForPlayer(PlayerColor player, TavernHeroSlot slot, HeroTypeID hero, CSimpleArmy & army, TavernSlotRole role, bool replenishPoints) { vstd::erase_if(currentTavern, [&](const TavernSlot & entry){ return entry.player == player && entry.slot == slot; }); if (hero == HeroTypeID::NONE) return; auto h = owner->getMap().tryGetFromHeroPool(hero); assert(h != nullptr); if (army) h->setToArmy(army); if (replenishPoints) { h->setMovementPoints(h->movementPointsLimit(true)); h->mana = h->manaLimit(); } TavernSlot newSlot; newSlot.hero = hero; newSlot.player = player; newSlot.role = role; newSlot.slot = slot; currentTavern.push_back(newSlot); boost::range::sort(currentTavern, [](const TavernSlot & left, const TavernSlot & right) { if (left.slot == right.slot) return left.player < right.player; else return left.slot < right.slot; }); } bool TavernHeroesPool::isHeroAvailableFor(HeroTypeID hero, PlayerColor color) const { if (perPlayerAvailability.count(hero)) return perPlayerAvailability.at(hero).count(color) != 0; return true; } std::vector<const CGHeroInstance *> TavernHeroesPool::getHeroesFor(PlayerColor color) const { std::vector<const CGHeroInstance *> result; for(const auto & slot : currentTavern) { assert(slot.hero.hasValue()); if (slot.player == color) result.push_back(owner->getMap().tryGetFromHeroPool(slot.hero)); } return result; } std::shared_ptr<CGHeroInstance> TavernHeroesPool::takeHeroFromPool(HeroTypeID hero) { assert(vstd::contains(heroesPool, hero)); vstd::erase(heroesPool, hero); vstd::erase_if(currentTavern, [&](const TavernSlot & entry){ return entry.hero == hero; }); return owner->getMap().tryTakeFromHeroPool(hero); } void TavernHeroesPool::onNewDay() { auto unusedHeroes = unusedHeroesFromPool(); for(auto & heroID : heroesPool) { auto heroPtr = owner->getMap().tryGetFromHeroPool(heroID); assert(heroPtr); heroPtr->removeBonusesRecursive(Bonus::OneDay); heroPtr->reduceBonusDurations(Bonus::NDays); heroPtr->reduceBonusDurations(Bonus::OneWeek); // do not access heroes who are not present in tavern of any players if (vstd::contains(unusedHeroes, heroID)) continue; heroPtr->setMovementPoints(heroPtr->movementPointsLimit(true)); heroPtr->mana = heroPtr->getManaNewTurn(); } } void TavernHeroesPool::addHeroToPool(HeroTypeID hero) { assert(!vstd::contains(heroesPool, hero)); heroesPool.push_back(hero); } void TavernHeroesPool::setAvailability(HeroTypeID hero, std::set<PlayerColor> mask) { perPlayerAvailability[hero] = mask; } VCMI_LIB_NAMESPACE_END
412
0.915909
1
0.915909
game-dev
MEDIA
0.955852
game-dev
0.920046
1
0.920046
ReactVision/virocore
5,061
wasm/libs/bullet/src/BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.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 "btSubSimplexConvexCast.h" #include "BulletCollision/CollisionShapes/btConvexShape.h" #include "BulletCollision/CollisionShapes/btMinkowskiSumShape.h" #include "BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h" #include "btPointCollector.h" #include "LinearMath/btTransformUtil.h" btSubsimplexConvexCast::btSubsimplexConvexCast (const btConvexShape* convexA,const btConvexShape* convexB,btSimplexSolverInterface* simplexSolver) :m_simplexSolver(simplexSolver), m_convexA(convexA),m_convexB(convexB) { } ///Typically the conservative advancement reaches solution in a few iterations, clip it to 32 for degenerate cases. ///See discussion about this here http://continuousphysics.com/Bullet/phpBB2/viewtopic.php?t=565 #ifdef BT_USE_DOUBLE_PRECISION #define MAX_ITERATIONS 64 #else #define MAX_ITERATIONS 32 #endif bool btSubsimplexConvexCast::calcTimeOfImpact( const btTransform& fromA, const btTransform& toA, const btTransform& fromB, const btTransform& toB, CastResult& result) { m_simplexSolver->reset(); btVector3 linVelA,linVelB; linVelA = toA.getOrigin()-fromA.getOrigin(); linVelB = toB.getOrigin()-fromB.getOrigin(); btScalar lambda = btScalar(0.); btTransform interpolatedTransA = fromA; btTransform interpolatedTransB = fromB; ///take relative motion btVector3 r = (linVelA-linVelB); btVector3 v; btVector3 supVertexA = fromA(m_convexA->localGetSupportingVertex(-r*fromA.getBasis())); btVector3 supVertexB = fromB(m_convexB->localGetSupportingVertex(r*fromB.getBasis())); v = supVertexA-supVertexB; int maxIter = MAX_ITERATIONS; btVector3 n; n.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); bool hasResult = false; btVector3 c; btScalar lastLambda = lambda; btScalar dist2 = v.length2(); #ifdef BT_USE_DOUBLE_PRECISION btScalar epsilon = btScalar(0.0001); #else btScalar epsilon = btScalar(0.0001); #endif //BT_USE_DOUBLE_PRECISION btVector3 w,p; btScalar VdotR; while ( (dist2 > epsilon) && maxIter--) { supVertexA = interpolatedTransA(m_convexA->localGetSupportingVertex(-v*interpolatedTransA.getBasis())); supVertexB = interpolatedTransB(m_convexB->localGetSupportingVertex(v*interpolatedTransB.getBasis())); w = supVertexA-supVertexB; btScalar VdotW = v.dot(w); if (lambda > btScalar(1.0)) { return false; } if ( VdotW > btScalar(0.)) { VdotR = v.dot(r); if (VdotR >= -(SIMD_EPSILON*SIMD_EPSILON)) return false; else { lambda = lambda - VdotW / VdotR; //interpolate to next lambda // x = s + lambda * r; interpolatedTransA.getOrigin().setInterpolate3(fromA.getOrigin(),toA.getOrigin(),lambda); interpolatedTransB.getOrigin().setInterpolate3(fromB.getOrigin(),toB.getOrigin(),lambda); //m_simplexSolver->reset(); //check next line w = supVertexA-supVertexB; lastLambda = lambda; n = v; hasResult = true; } } ///Just like regular GJK only add the vertex if it isn't already (close) to current vertex, it would lead to divisions by zero and NaN etc. if (!m_simplexSolver->inSimplex(w)) m_simplexSolver->addVertex( w, supVertexA , supVertexB); if (m_simplexSolver->closest(v)) { dist2 = v.length2(); hasResult = true; //todo: check this normal for validity //n=v; //printf("V=%f , %f, %f\n",v[0],v[1],v[2]); //printf("DIST2=%f\n",dist2); //printf("numverts = %i\n",m_simplexSolver->numVertices()); } else { dist2 = btScalar(0.); } } //int numiter = MAX_ITERATIONS - maxIter; // printf("number of iterations: %d", numiter); //don't report a time of impact when moving 'away' from the hitnormal result.m_fraction = lambda; if (n.length2() >= (SIMD_EPSILON*SIMD_EPSILON)) result.m_normal = n.normalized(); else result.m_normal = btVector3(btScalar(0.0), btScalar(0.0), btScalar(0.0)); //don't report time of impact for motion away from the contact normal (or causes minor penetration) if (result.m_normal.dot(r)>=-result.m_allowedPenetration) return false; btVector3 hitA,hitB; m_simplexSolver->compute_points(hitA,hitB); result.m_hitPoint=hitB; return true; }
412
0.956306
1
0.956306
game-dev
MEDIA
0.96723
game-dev
0.993269
1
0.993269
LiteLDev/LeviLamina
1,279
src-server/mc/deps/core/http/FileRequestBody.h
#pragma once #include "mc/_HeaderOutputPredefine.h" // auto generated inclusion list #include "mc/deps/core/http/IRequestBody.h" namespace Bedrock::Http { class FileRequestBody : public ::Bedrock::Http::Internal::IRequestBody { public: // member variables // NOLINTBEGIN ::ll::UntypedStorage<8, 32> mUnkf6c20f; ::ll::UntypedStorage<8, 16> mUnkbdbe9d; ::ll::UntypedStorage<1, 1> mUnk84e5f4; // NOLINTEND public: // prevent constructor by default FileRequestBody& operator=(FileRequestBody const&); FileRequestBody(FileRequestBody const&); FileRequestBody(); public: // virtual functions // NOLINTBEGIN // vIndex: 1 virtual ::Bedrock::Http::Internal::IRequestBody::ReadResult read(::gsl::span<uchar>) /*override*/; // vIndex: 2 virtual uint64 getSize() /*override*/; // vIndex: 3 virtual void cancel() /*override*/; // vIndex: 4 virtual ::std::string const& getLoggableSource() const /*override*/; // vIndex: 5 virtual ::gsl::span<uchar const> getLoggableData() const /*override*/; // vIndex: 0 virtual ~FileRequestBody() /*override*/ = default; // NOLINTEND public: // virtual function thunks // NOLINTBEGIN // NOLINTEND }; } // namespace Bedrock::Http
412
0.925199
1
0.925199
game-dev
MEDIA
0.52166
game-dev,graphics-rendering
0.686844
1
0.686844
roy-t/MiniRTS
10,159
vOld/Editor/Scenes/SceneBuilder.cs
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using MiniEngine.CutScene; using MiniEngine.GameLogic; using MiniEngine.Pipeline.Basics.Components; using MiniEngine.Pipeline.Basics.Factories; using MiniEngine.Pipeline.Debug.Components; using MiniEngine.Pipeline.Debug.Factories; using MiniEngine.Pipeline.Lights.Components; using MiniEngine.Pipeline.Lights.Factories; using MiniEngine.Pipeline.Models.Components; using MiniEngine.Pipeline.Models.Factories; using MiniEngine.Pipeline.Particles.Factories; using MiniEngine.Pipeline.Projectors.Factories; using MiniEngine.Rendering; using MiniEngine.Systems; using MiniEngine.Systems.Components; using MiniEngine.Systems.Factories; using MiniEngine.Units; namespace MiniEngine.Scenes { // TODO: most building of things should be moved to commands and handled by the server public sealed class SceneBuilder { private readonly EntityController EntityController; private readonly Content Content; private readonly PipelineBuilder PipelineBuilder; private readonly Dictionary<Type, IComponentFactory> Factories; public SceneBuilder( EntityController entityController, Content content, PipelineBuilder pipelineBuilder, IEnumerable<IComponentFactory> factories) { this.EntityController = entityController; this.Content = content; this.PipelineBuilder = pipelineBuilder; this.Factories = new Dictionary<Type, IComponentFactory>(); foreach (var factory in factories) { this.Factories.Add(factory.GetType(), factory); } } public T GetFactory<T>() where T : IComponentFactory { if (this.Factories.TryGetValue(typeof(T), out var factory)) { return (T)factory; } throw new KeyNotFoundException($"Could not find factory of type {typeof(T)} did you forget to make it available for injection?"); } public DebugLine CreateDebugLine(IReadOnlyList<Vector3> linePositions, Color color) { var entity = this.EntityController.CreateEntity(); return this.GetFactory<DebugLineFactory>().Construct(entity, linePositions, color); } public AmbientLight BuildSponzaAmbientLight() { var entity = this.EntityController.CreateEntity(); return this.GetFactory<AmbientLightFactory>().Construct(entity, Color.White * 0.5f); } public Sunlight BuildSponzaSunLight() { var entity = this.EntityController.CreateEntity(); return this.GetFactory<SunlightFactory>().Construct(entity, Color.White, Vector3.Up, (Vector3.Left * 0.75f) + (Vector3.Backward * 0.1f)); } public OpaqueModel BuildSponza(Vector3 position, float scale) { var entity = this.EntityController.CreateEntity(); this.GetFactory<PoseFactory>().Construct(entity, position, scale); var (model, _) = this.GetFactory<OpaqueModelFactory>().Construct(entity, this.Content.Sponza); return model; } public (Pose, OpaqueModel, Bounds) BuildCube(Vector3 position, float scale) { var entity = this.EntityController.CreateEntity(); var pose = this.GetFactory<PoseFactory>().Construct(entity, position, scale); var (model, bounds) = this.GetFactory<OpaqueModelFactory>().Construct(entity, this.Content.Cube); return (pose, model, bounds); } public ShadowCastingLight BuildLionSpotLight() { var entity = this.EntityController.CreateEntity(); return this.GetFactory<ShadowCastingLightFactory>().Construct(entity, new Vector3(40, 13, 27), new Vector3(53, 11, 12), Color.White, 2048); } public void BuildSponzaLit(Vector3 position, float scale) { this.BuildSponzaAmbientLight(); this.BuildSponzaSunLight(); this.BuildSponza(position, scale); } public Entity[] BuildStainedGlass() { var entities = this.EntityController.CreateEntities(2); var position = new Vector3(-40.5f, 30.0f, 3.2f); this.GetFactory<PoseFactory>().Construct(entities[0], position, 4.4f * 0.01f, MathHelper.PiOver2, MathHelper.PiOver2, 0); this.GetFactory<TransparentModelFactory>().Construct(entities[0], this.Content.Plane); position = new Vector3(-40.5f, 30.0f, -7.2f); this.GetFactory<PoseFactory>().Construct(entities[1], position, 4.4f * 0.01f, MathHelper.PiOver4); this.GetFactory<TransparentModelFactory>().Construct(entities[1], this.Content.Plane); return entities; } public PointLight BuildFirePlace() { var entity = this.EntityController.CreateEntity(); this.GetFactory<PoseFactory>().Construct(entity, new Vector3(-60.5f, 6.0f, 20.0f), Vector3.One * 2, 0, MathHelper.PiOver2, 0); this.GetFactory<AveragedEmitterFactory>().ConstructAveragedEmitter(entity, this.Content.Smoke, 1, 1); var entity2 = this.EntityController.CreateEntity(); this.GetFactory<PoseFactory>().Construct(entity2, new Vector3(-60.5f, 6.0f, 20.0f), Vector3.One, 0, MathHelper.PiOver2, 0); this.GetFactory<AdditiveEmitterFactory>().ConstructAdditiveEmitter(entity2, this.Content.Explosion2, 1, 1); var entity3 = this.EntityController.CreateEntity(); this.GetFactory<PoseFactory>().Construct(entity3, new Vector3(-60.5f, 6.0f, 20.0f), Vector3.One * 0.075f, 0, MathHelper.PiOver2, 0); var emitter = this.GetFactory<AdditiveEmitterFactory>().ConstructAdditiveEmitter(entity3, this.Content.Explosion, 8, 8); emitter.SpawnInterval = 0; emitter.Spread = 0.75f; emitter.TimeToLive = 2.25f; var pointLight = this.GetFactory<PointLightFactory>().Construct(entity, Color.IndianRed, 20.0f, 1.0f); var cameraPosition = new Vector3(-60.5f, 8.0f, 20.0f); var projectorPosition = new Vector3(-60.5f, 0.0f, 20.0f); var lookAt = cameraPosition + (new Vector3(0.001f, 1, 0) * 10); var lightEntity = this.EntityController.CreateEntity(); var dynamicTexture = this.GetFactory<DynamicTextureFactory>().Construct(lightEntity, cameraPosition, lookAt, 1024, 1024, this.Content.NullSkybox, "Firewatcher"); this.PipelineBuilder.AddParticlePipeline(dynamicTexture.Pipeline); var color = Color.White * 0.2f; var projector = this.GetFactory<ProjectorFactory>().Construct(lightEntity, dynamicTexture.FinalTarget, this.Content.Mask, color, projectorPosition, lookAt); projector.SetMinDistance(10.0f); projector.SetMaxDistance(30.0f); return pointLight; } public Parent BuildParent(string name) { var parentEntity = this.EntityController.CreateEntity(name); var parent = this.GetFactory<ParentFactory>().Construct(parentEntity); return parent; } public Entity BuildBulletHoles() { var entity = this.EntityController.CreateEntity(); var random = new Random(12345); var center = new Vector3(-71.2f, 10, -25); var forward = Vector3.Left; for (var i = 0; i < 1 /*100*/; i++) { var u = (float)(random.NextDouble() * 15) - 7.5f; var v = (float)(random.NextDouble() * 15) - 7.5f; var offset = new Vector3(0, u, v); var projector = this.GetFactory<ProjectorFactory>().Construct(entity, this.Content.BulletHole, Color.White, center + offset, center + offset + forward); projector.SetMaxDistance(1.0f); } return entity; } public void BuildCutScene() { var speeds = new MetersPerSecond[] { new MetersPerSecond(15.0f), new MetersPerSecond(15.0f), new MetersPerSecond(15.0f), new MetersPerSecond(6.0f), new MetersPerSecond(15.0f), new MetersPerSecond(15.0f), new MetersPerSecond(15.0f), new MetersPerSecond(15.0f), new MetersPerSecond(5.0f), new MetersPerSecond(5.0f) }; var positions = new Vector3[] { new Vector3(60, 10, 20), // start position new Vector3(-60, 10, 20), // near fireplace new Vector3(-50, 15, 0), // side stepping column new Vector3(-10, 40, 0), // center stage new Vector3(-30, 13, -10), // inspect windows new Vector3(-25, 34, -10), // side step to upper row new Vector3(-10, 34, -10), // in upper row new Vector3(20, 25, -7), // in upper row new Vector3(49, 10, -7), // pass lion new Vector3(49, 10, 20), // start position }; var lookAts = new Vector3[] { new Vector3(-60, 10, 20), new Vector3(-60, 0, 20), new Vector3(-60, 30, 20), new Vector3(-40, 0, 20), new Vector3(-50, 30, 10), new Vector3(-10, 40, 20), new Vector3(60, 40, 20), new Vector3(60, 10, 0), new Vector3(60, 10, 0), new Vector3(60, 10, 0) }; for (var i = 0; i < positions.Length; i++) { var speed = speeds[i]; var position = positions[i]; var lookAt = lookAts[i]; var entity = this.EntityController.CreateEntity(); this.GetFactory<WaypointFactory>().Construct(entity, speed, position, lookAt); } } } }
412
0.808203
1
0.808203
game-dev
MEDIA
0.61798
game-dev,graphics-rendering
0.796785
1
0.796785
AionGermany/aion-germany
2,620
AL-Game-5.8/data/scripts/system/handlers/quest/runadium_bonus/_80587FindTheJournal.java
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning 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. * * Aion-Lightning 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 Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. */ package quest.runadium_bonus; import com.aionemu.gameserver.model.DialogAction; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; import com.aionemu.gameserver.services.QuestService; /** * @author FrozenKiller */ public class _80587FindTheJournal extends QuestHandler { private final static int questId = 80587; public _80587FindTheJournal() { super(questId); } @Override public void register() { qe.registerQuestNpc(832268).addOnQuestStart(questId); qe.registerQuestNpc(832268).addOnTalkEvent(questId); } @Override public boolean onDialogEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); DialogAction dialog = env.getDialog(); int targetId = env.getTargetId(); if (qs == null || qs.getStatus() == QuestStatus.NONE) { if (targetId == 832268) { if (dialog == DialogAction.QUEST_SELECT) { return sendQuestDialog(env, 1011); } else { return sendQuestStartDialog(env); } } } else if (qs.getStatus() == QuestStatus.START) { if (targetId == 832268) { switch (dialog) { case QUEST_SELECT: { return sendQuestDialog(env, 2375); } case CHECK_USER_HAS_QUEST_ITEM_SIMPLE: { if (QuestService.collectItemCheck(env, true)) { changeQuestStep(env, 0, 1, true); return sendQuestDialog(env, 5); } else { return closeDialogWindow(env); } } default: break; } } } else if (qs.getStatus() == QuestStatus.REWARD) { if (targetId == 832268) { return sendQuestEndDialog(env); } } return false; } }
412
0.924075
1
0.924075
game-dev
MEDIA
0.96312
game-dev
0.97844
1
0.97844
386bsd/386bsd
9,904
usr/src/games/rogue/hit.c
/* * Copyright (c) 1988 The Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * Timothy C. Stoehr. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. */ #ifndef lint static char sccsid[] = "@(#)hit.c 5.3 (Berkeley) 6/1/90"; #endif /* not lint */ /* * hit.c * * This source herein may be modified and/or distributed by anybody who * so desires, with the following restrictions: * 1.) No portion of this notice shall be removed. * 2.) Credit shall not be taken for the creation of this source. * 3.) This code is not to be traded, sold, or used for personal * gain or profit. * */ #include "rogue.h" object *fight_monster = 0; char hit_message[80] = ""; extern short halluc, blind, cur_level; extern short add_strength, ring_exp, r_rings; extern boolean being_held, interrupted, wizard, con_mon; mon_hit(monster) register object *monster; { short damage, hit_chance; char *mn; float minus; if (fight_monster && (monster != fight_monster)) { fight_monster = 0; } monster->trow = NO_ROOM; if (cur_level >= (AMULET_LEVEL * 2)) { hit_chance = 100; } else { hit_chance = monster->m_hit_chance; hit_chance -= (((2 * rogue.exp) + (2 * ring_exp)) - r_rings); } if (wizard) { hit_chance /= 2; } if (!fight_monster) { interrupted = 1; } mn = mon_name(monster); if (!rand_percent(hit_chance)) { if (!fight_monster) { sprintf(hit_message + strlen(hit_message), "the %s misses", mn); message(hit_message, 1); hit_message[0] = 0; } return; } if (!fight_monster) { sprintf(hit_message + strlen(hit_message), "the %s hit", mn); message(hit_message, 1); hit_message[0] = 0; } if (!(monster->m_flags & STATIONARY)) { damage = get_damage(monster->m_damage, 1); if (cur_level >= (AMULET_LEVEL * 2)) { minus = (float) ((AMULET_LEVEL * 2) - cur_level); } else { minus = (float) get_armor_class(rogue.armor) * 3.00; minus = minus/100.00 * (float) damage; } damage -= (short) minus; } else { damage = monster->stationary_damage++; } if (wizard) { damage /= 3; } if (damage > 0) { rogue_damage(damage, monster, 0); } if (monster->m_flags & SPECIAL_HIT) { special_hit(monster); } } rogue_hit(monster, force_hit) register object *monster; boolean force_hit; { short damage, hit_chance; if (monster) { if (check_imitator(monster)) { return; } hit_chance = force_hit ? 100 : get_hit_chance(rogue.weapon); if (wizard) { hit_chance *= 2; } if (!rand_percent(hit_chance)) { if (!fight_monster) { (void) strcpy(hit_message, "you miss "); } goto RET; } damage = get_weapon_damage(rogue.weapon); if (wizard) { damage *= 3; } if (con_mon) { s_con_mon(monster); } if (mon_damage(monster, damage)) { /* still alive? */ if (!fight_monster) { (void) strcpy(hit_message, "you hit "); } } RET: check_gold_seeker(monster); wake_up(monster); } } rogue_damage(d, monster, other) short d; object *monster; short other; { if (d >= rogue.hp_current) { rogue.hp_current = 0; print_stats(STAT_HP); killed_by(monster, other); } if (d > 0) { rogue.hp_current -= d; print_stats(STAT_HP); } } get_damage(ds, r) char *ds; boolean r; { register i = 0, j, n, d, total = 0; while (ds[i]) { n = get_number(ds+i); while (ds[i++] != 'd') ; d = get_number(ds+i); while ((ds[i] != '/') && ds[i]) i++; for (j = 0; j < n; j++) { if (r) { total += get_rand(1, d); } else { total += d; } } if (ds[i] == '/') { i++; } } return(total); } get_w_damage(obj) object *obj; { char new_damage[12]; register to_hit, damage; register i = 0; if ((!obj) || (obj->what_is != WEAPON)) { return(-1); } to_hit = get_number(obj->damage) + obj->hit_enchant; while (obj->damage[i++] != 'd') ; damage = get_number(obj->damage + i) + obj->d_enchant; sprintf(new_damage, "%dd%d", to_hit, damage); return(get_damage(new_damage, 1)); } get_number(s) register char *s; { register i = 0; register total = 0; while ((s[i] >= '0') && (s[i] <= '9')) { total = (10 * total) + (s[i] - '0'); i++; } return(total); } long lget_number(s) char *s; { short i = 0; long total = 0; while ((s[i] >= '0') && (s[i] <= '9')) { total = (10 * total) + (s[i] - '0'); i++; } return(total); } to_hit(obj) object *obj; { if (!obj) { return(1); } return(get_number(obj->damage) + obj->hit_enchant); } damage_for_strength() { short strength; strength = rogue.str_current + add_strength; if (strength <= 6) { return(strength-5); } if (strength <= 14) { return(1); } if (strength <= 17) { return(3); } if (strength <= 18) { return(4); } if (strength <= 20) { return(5); } if (strength <= 21) { return(6); } if (strength <= 30) { return(7); } return(8); } mon_damage(monster, damage) object *monster; short damage; { char *mn; short row, col; monster->hp_to_kill -= damage; if (monster->hp_to_kill <= 0) { row = monster->row; col = monster->col; dungeon[row][col] &= ~MONSTER; mvaddch(row, col, (int) get_dungeon_char(row, col)); fight_monster = 0; cough_up(monster); mn = mon_name(monster); sprintf(hit_message+strlen(hit_message), "defeated the %s", mn); message(hit_message, 1); hit_message[0] = 0; add_exp(monster->kill_exp, 1); take_from_pack(monster, &level_monsters); if (monster->m_flags & HOLDS) { being_held = 0; } free_object(monster); return(0); } return(1); } fight(to_the_death) boolean to_the_death; { short ch, c, d; short row, col; boolean first_miss = 1; short possible_damage; object *monster; while (!is_direction(ch = rgetchar(), &d)) { sound_bell(); if (first_miss) { message("direction?", 0); first_miss = 0; } } check_message(); if (ch == CANCEL) { return; } row = rogue.row; col = rogue.col; get_dir_rc(d, &row, &col, 0); c = mvinch(row, col); if (((c < 'A') || (c > 'Z')) || (!can_move(rogue.row, rogue.col, row, col))) { message("I see no monster there", 0); return; } if (!(fight_monster = object_at(&level_monsters, row, col))) { return; } if (!(fight_monster->m_flags & STATIONARY)) { possible_damage = ((get_damage(fight_monster->m_damage, 0) * 2) / 3); } else { possible_damage = fight_monster->stationary_damage - 1; } while (fight_monster) { (void) one_move_rogue(ch, 0); if (((!to_the_death) && (rogue.hp_current <= possible_damage)) || interrupted || (!(dungeon[row][col] & MONSTER))) { fight_monster = 0; } else { monster = object_at(&level_monsters, row, col); if (monster != fight_monster) { fight_monster = 0; } } } } get_dir_rc(dir, row, col, allow_off_screen) short dir; short *row, *col; short allow_off_screen; { switch(dir) { case LEFT: if (allow_off_screen || (*col > 0)) { (*col)--; } break; case DOWN: if (allow_off_screen || (*row < (DROWS-2))) { (*row)++; } break; case UPWARD: if (allow_off_screen || (*row > MIN_ROW)) { (*row)--; } break; case RIGHT: if (allow_off_screen || (*col < (DCOLS-1))) { (*col)++; } break; case UPLEFT: if (allow_off_screen || ((*row > MIN_ROW) && (*col > 0))) { (*row)--; (*col)--; } break; case UPRIGHT: if (allow_off_screen || ((*row > MIN_ROW) && (*col < (DCOLS-1)))) { (*row)--; (*col)++; } break; case DOWNRIGHT: if (allow_off_screen || ((*row < (DROWS-2)) && (*col < (DCOLS-1)))) { (*row)++; (*col)++; } break; case DOWNLEFT: if (allow_off_screen || ((*row < (DROWS-2)) && (*col > 0))) { (*row)++; (*col)--; } break; } } get_hit_chance(weapon) object *weapon; { short hit_chance; hit_chance = 40; hit_chance += 3 * to_hit(weapon); hit_chance += (((2 * rogue.exp) + (2 * ring_exp)) - r_rings); return(hit_chance); } get_weapon_damage(weapon) object *weapon; { short damage; damage = get_w_damage(weapon); damage += damage_for_strength(); damage += ((((rogue.exp + ring_exp) - r_rings) + 1) / 2); return(damage); } s_con_mon(monster) object *monster; { if (con_mon) { monster->m_flags |= CONFUSED; monster->moves_confused += get_rand(12, 22); message("the monster appears confused", 0); con_mon = 0; } }
412
0.927795
1
0.927795
game-dev
MEDIA
0.980192
game-dev
0.983595
1
0.983595
opengl-tutorials/ogl
9,416
external/bullet-2.81-rev2613/src/BulletCollision/Gimpact/btGImpactBvh.h
#ifndef GIM_BOX_SET_H_INCLUDED #define GIM_BOX_SET_H_INCLUDED /*! \file gim_box_set.h \author Francisco Leon Najera */ /* This source file is part of GIMPACT Library. For the latest info, see http://gimpact.sourceforge.net/ Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371. email: projectileman@yahoo.com 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 "LinearMath/btAlignedObjectArray.h" #include "btBoxCollision.h" #include "btTriangleShapeEx.h" //! Overlapping pair struct GIM_PAIR { int m_index1; int m_index2; GIM_PAIR() {} GIM_PAIR(const GIM_PAIR & p) { m_index1 = p.m_index1; m_index2 = p.m_index2; } GIM_PAIR(int index1, int index2) { m_index1 = index1; m_index2 = index2; } }; //! A pairset array class btPairSet: public btAlignedObjectArray<GIM_PAIR> { public: btPairSet() { reserve(32); } inline void push_pair(int index1,int index2) { push_back(GIM_PAIR(index1,index2)); } inline void push_pair_inv(int index1,int index2) { push_back(GIM_PAIR(index2,index1)); } }; ///GIM_BVH_DATA is an internal GIMPACT collision structure to contain axis aligned bounding box struct GIM_BVH_DATA { btAABB m_bound; int m_data; }; //! Node Structure for trees class GIM_BVH_TREE_NODE { public: btAABB m_bound; protected: int m_escapeIndexOrDataIndex; public: GIM_BVH_TREE_NODE() { m_escapeIndexOrDataIndex = 0; } SIMD_FORCE_INLINE bool isLeafNode() const { //skipindex is negative (internal node), triangleindex >=0 (leafnode) return (m_escapeIndexOrDataIndex>=0); } SIMD_FORCE_INLINE int getEscapeIndex() const { //btAssert(m_escapeIndexOrDataIndex < 0); return -m_escapeIndexOrDataIndex; } SIMD_FORCE_INLINE void setEscapeIndex(int index) { m_escapeIndexOrDataIndex = -index; } SIMD_FORCE_INLINE int getDataIndex() const { //btAssert(m_escapeIndexOrDataIndex >= 0); return m_escapeIndexOrDataIndex; } SIMD_FORCE_INLINE void setDataIndex(int index) { m_escapeIndexOrDataIndex = index; } }; class GIM_BVH_DATA_ARRAY:public btAlignedObjectArray<GIM_BVH_DATA> { }; class GIM_BVH_TREE_NODE_ARRAY:public btAlignedObjectArray<GIM_BVH_TREE_NODE> { }; //! Basic Box tree structure class btBvhTree { protected: int m_num_nodes; GIM_BVH_TREE_NODE_ARRAY m_node_array; protected: int _sort_and_calc_splitting_index( GIM_BVH_DATA_ARRAY & primitive_boxes, int startIndex, int endIndex, int splitAxis); int _calc_splitting_axis(GIM_BVH_DATA_ARRAY & primitive_boxes, int startIndex, int endIndex); void _build_sub_tree(GIM_BVH_DATA_ARRAY & primitive_boxes, int startIndex, int endIndex); public: btBvhTree() { m_num_nodes = 0; } //! prototype functions for box tree management //!@{ void build_tree(GIM_BVH_DATA_ARRAY & primitive_boxes); SIMD_FORCE_INLINE void clearNodes() { m_node_array.clear(); m_num_nodes = 0; } //! node count SIMD_FORCE_INLINE int getNodeCount() const { return m_num_nodes; } //! tells if the node is a leaf SIMD_FORCE_INLINE bool isLeafNode(int nodeindex) const { return m_node_array[nodeindex].isLeafNode(); } SIMD_FORCE_INLINE int getNodeData(int nodeindex) const { return m_node_array[nodeindex].getDataIndex(); } SIMD_FORCE_INLINE void getNodeBound(int nodeindex, btAABB & bound) const { bound = m_node_array[nodeindex].m_bound; } SIMD_FORCE_INLINE void setNodeBound(int nodeindex, const btAABB & bound) { m_node_array[nodeindex].m_bound = bound; } SIMD_FORCE_INLINE int getLeftNode(int nodeindex) const { return nodeindex+1; } SIMD_FORCE_INLINE int getRightNode(int nodeindex) const { if(m_node_array[nodeindex+1].isLeafNode()) return nodeindex+2; return nodeindex+1 + m_node_array[nodeindex+1].getEscapeIndex(); } SIMD_FORCE_INLINE int getEscapeNodeIndex(int nodeindex) const { return m_node_array[nodeindex].getEscapeIndex(); } SIMD_FORCE_INLINE const GIM_BVH_TREE_NODE * get_node_pointer(int index = 0) const { return &m_node_array[index]; } //!@} }; //! Prototype Base class for primitive classification /*! This class is a wrapper for primitive collections. This tells relevant info for the Bounding Box set classes, which take care of space classification. This class can manage Compound shapes and trimeshes, and if it is managing trimesh then the Hierarchy Bounding Box classes will take advantage of primitive Vs Box overlapping tests for getting optimal results and less Per Box compairisons. */ class btPrimitiveManagerBase { public: virtual ~btPrimitiveManagerBase() {} //! determines if this manager consist on only triangles, which special case will be optimized virtual bool is_trimesh() const = 0; virtual int get_primitive_count() const = 0; virtual void get_primitive_box(int prim_index ,btAABB & primbox) const = 0; //! retrieves only the points of the triangle, and the collision margin virtual void get_primitive_triangle(int prim_index,btPrimitiveTriangle & triangle) const= 0; }; //! Structure for containing Boxes /*! This class offers an structure for managing a box tree of primitives. Requires a Primitive prototype (like btPrimitiveManagerBase ) */ class btGImpactBvh { protected: btBvhTree m_box_tree; btPrimitiveManagerBase * m_primitive_manager; protected: //stackless refit void refit(); public: //! this constructor doesn't build the tree. you must call buildSet btGImpactBvh() { m_primitive_manager = NULL; } //! this constructor doesn't build the tree. you must call buildSet btGImpactBvh(btPrimitiveManagerBase * primitive_manager) { m_primitive_manager = primitive_manager; } SIMD_FORCE_INLINE btAABB getGlobalBox() const { btAABB totalbox; getNodeBound(0, totalbox); return totalbox; } SIMD_FORCE_INLINE void setPrimitiveManager(btPrimitiveManagerBase * primitive_manager) { m_primitive_manager = primitive_manager; } SIMD_FORCE_INLINE btPrimitiveManagerBase * getPrimitiveManager() const { return m_primitive_manager; } //! node manager prototype functions ///@{ //! this attemps to refit the box set. SIMD_FORCE_INLINE void update() { refit(); } //! this rebuild the entire set void buildSet(); //! returns the indices of the primitives in the m_primitive_manager bool boxQuery(const btAABB & box, btAlignedObjectArray<int> & collided_results) const; //! returns the indices of the primitives in the m_primitive_manager SIMD_FORCE_INLINE bool boxQueryTrans(const btAABB & box, const btTransform & transform, btAlignedObjectArray<int> & collided_results) const { btAABB transbox=box; transbox.appy_transform(transform); return boxQuery(transbox,collided_results); } //! returns the indices of the primitives in the m_primitive_manager bool rayQuery( const btVector3 & ray_dir,const btVector3 & ray_origin , btAlignedObjectArray<int> & collided_results) const; //! tells if this set has hierarcht SIMD_FORCE_INLINE bool hasHierarchy() const { return true; } //! tells if this set is a trimesh SIMD_FORCE_INLINE bool isTrimesh() const { return m_primitive_manager->is_trimesh(); } //! node count SIMD_FORCE_INLINE int getNodeCount() const { return m_box_tree.getNodeCount(); } //! tells if the node is a leaf SIMD_FORCE_INLINE bool isLeafNode(int nodeindex) const { return m_box_tree.isLeafNode(nodeindex); } SIMD_FORCE_INLINE int getNodeData(int nodeindex) const { return m_box_tree.getNodeData(nodeindex); } SIMD_FORCE_INLINE void getNodeBound(int nodeindex, btAABB & bound) const { m_box_tree.getNodeBound(nodeindex, bound); } SIMD_FORCE_INLINE void setNodeBound(int nodeindex, const btAABB & bound) { m_box_tree.setNodeBound(nodeindex, bound); } SIMD_FORCE_INLINE int getLeftNode(int nodeindex) const { return m_box_tree.getLeftNode(nodeindex); } SIMD_FORCE_INLINE int getRightNode(int nodeindex) const { return m_box_tree.getRightNode(nodeindex); } SIMD_FORCE_INLINE int getEscapeNodeIndex(int nodeindex) const { return m_box_tree.getEscapeNodeIndex(nodeindex); } SIMD_FORCE_INLINE void getNodeTriangle(int nodeindex,btPrimitiveTriangle & triangle) const { m_primitive_manager->get_primitive_triangle(getNodeData(nodeindex),triangle); } SIMD_FORCE_INLINE const GIM_BVH_TREE_NODE * get_node_pointer(int index = 0) const { return m_box_tree.get_node_pointer(index); } #ifdef TRI_COLLISION_PROFILING static float getAverageTreeCollisionTime(); #endif //TRI_COLLISION_PROFILING static void find_collision(btGImpactBvh * boxset1, const btTransform & trans1, btGImpactBvh * boxset2, const btTransform & trans2, btPairSet & collision_pairs); }; #endif // GIM_BOXPRUNING_H_INCLUDED
412
0.962538
1
0.962538
game-dev
MEDIA
0.421647
game-dev
0.960135
1
0.960135
XG2025-Akaishin/Cracked-1.20.4-Continue
16,391
src/main/java/me/alpha432/oyvey/features/modules/client/HUD.java
package me.alpha432.oyvey.features.modules.client; import java.util.stream.Collectors; import me.alpha432.oyvey.OyVey; import me.alpha432.oyvey.event.impl.Render2DEvent; import me.alpha432.oyvey.features.modules.Module; import me.alpha432.oyvey.features.modules.client.hud.TimeDay; import me.alpha432.oyvey.features.modules.client.hud.utils.FrameRateCounter; import me.alpha432.oyvey.features.modules.client.hud.utils.MathUtility; import me.alpha432.oyvey.features.settings.Setting; import me.alpha432.oyvey.util.ColorUtil; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.screen.ChatScreen; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.text.Text; import net.minecraft.util.Formatting; import java.awt.*; import java.text.SimpleDateFormat; import java.util.*; public class HUD extends Module { private static final ItemStack totem = new ItemStack(Items.TOTEM_OF_UNDYING); public Setting<Integer> red = this.register(new Setting<>("Red", 0, 0, 255)); public Setting<Integer> green = this.register(new Setting<>("Green", 0, 0, 255)); public Setting<Integer> blue = this.register(new Setting<>("Blue", 255, 0, 255)); public Setting<Integer> alpha = this.register(new Setting<>("Alpha", 240, 0, 255)); private final Setting<Boolean> renderingUp = this.register(new Setting<>("RenderingUp", false)); private final Setting<Boolean> arrayList = this.register(new Setting<>("ActiveModules", false)); private final Setting<Boolean> coords = this.register(new Setting<>("Coords", false)); private final Setting<Boolean> armorhud = this.register(new Setting<>("Armor", false)); private final Setting<Boolean> totemshud = this.register(new Setting<>("Totems", false)); private final Setting<Boolean> direction = this.register(new Setting<>("Direction", false)); private final Setting<Boolean> speed = this.register(new Setting<>("Speed", false)); private final Setting<Boolean> ping = this.register(new Setting<>("Ping", false)); private final Setting<Boolean> fps = this.register(new Setting<>("FPS", false)); private final Setting<Boolean> tps = this.register(new Setting<>("TPS", false)); private final Setting<Boolean> extraTps = this.register(new Setting<>("ExtraTPS", true, v-> tps.getValue())); public Setting<Boolean> time = this.register(new Setting<>("Time", false)); private final Setting<Boolean> greeter = this.register(new Setting<Boolean>("test", false)); private final Setting<Greeter> greetermode = this.register(new Setting<Greeter>("Greeter", Greeter.NONE, v -> this.greeter.getValue())); private final Setting<String> customGreeter = this.register(new Setting<String>("GreeterCustom", "Cracked v2.0 - 1.20.4", v -> this.greetermode.getValue() == Greeter.CUSTOM)); private String GV = mc.getGameVersion(); public static String text; public static boolean percent; public int color; public HUD() { super("HUD", "hud", Category.CLIENT, true, false, false); } @Override public void onRender2D(Render2DEvent event) { int width = mc.getWindow().getScaledWidth(); int height = mc.getWindow().getScaledHeight(); color = ColorUtil.toARGB(this.red.getValue(), this.green.getValue(), this.blue.getValue(), this.alpha.getValue()); event.getContext().drawTextWithShadow( mc.textRenderer, OyVey.NAME + " " + OyVey.VERSION, 2,/* x */ 2/* y */, ColorUtil.toARGB(red.getValue(), green.getValue(), blue.getValue(), alpha.getValue()) ); event.getContext().drawTextWithShadow( mc.textRenderer, mc.player.getDisplayName().getString() , 2, 12, ColorUtil.toARGB(red.getValue(), green.getValue(), blue.getValue(), alpha.getValue()) ); event.getContext().drawTextWithShadow( mc.textRenderer, GV , 2, 22, ColorUtil.toARGB(red.getValue(), green.getValue(), blue.getValue(), alpha.getValue()) ); //Modules Enable Disable ArrayList Active Modules int j = (mc.currentScreen instanceof ChatScreen && !renderingUp.getValue()) ? 14 : 0; if (arrayList.getValue()) if (renderingUp.getValue()) { for (Module module : OyVey.moduleManager.getEnabledModules().stream().filter(Module::isDrawn).sorted(Comparator.comparing(module -> mc.textRenderer.getWidth(module.getFullArrayString()) * -1)).collect(Collectors.toList())) { if (!module.isDrawn()) { continue; } String str = module.getDisplayName() + Formatting.GRAY + ((module.getDisplayInfo() != null) ? (" [" + Formatting.WHITE + module.getDisplayInfo() + Formatting.GRAY + "]") : ""); event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(str), (width - 2 - getStringWidth(str)), (2 + j * 10), color); j++; } } else { for (Module module : OyVey.moduleManager.getEnabledModules().stream().filter(Module::isDrawn).sorted(Comparator.comparing(module -> mc.textRenderer.getWidth(module.getFullArrayString()) * -1)).collect(Collectors.toList())) { if (!module.isDrawn()) { continue; } String str = module.getDisplayName() + Formatting.GRAY + ((module.getDisplayInfo() != null) ? (" [" + Formatting.WHITE + module.getDisplayInfo() + Formatting.GRAY + "]") : ""); j += 10; event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(str), (width - 2 - getStringWidth(str)), (height - j), color); } } //info bar chat Ping Brand Time Etc int i = (mc.currentScreen instanceof ChatScreen && renderingUp.getValue()) ? 13 : (renderingUp.getValue() ? -2 : 0); if (renderingUp.getValue()) { if (speed.getValue()) { String str = "Speed " + Formatting.WHITE + MathUtility.round((float) (OyVey.hudManager.currentPlayerSpeed * 72f)) + " km/h"; i += 10; event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(str), (width - getStringWidth(str) - 2), (height - 2 - i), color); } if (time.getValue()) { String str = "Time " + Formatting.WHITE + (new SimpleDateFormat("h:mm a")).format(new Date()); i += 10; event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(str), (width - getStringWidth(str) - 2), (height - 2 - i), color); } if (tps.getValue()) { String str = "TPS " + Formatting.WHITE + OyVey.hudManager.getTPS() + (extraTps.getValue() ? " [" + OyVey.hudManager.getTPS2() + "]" : ""); i += 10; event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(str), (width - getStringWidth(str) - 2), (height - 2 - i), color); } String fpsText = "FPS " + Formatting.WHITE + FrameRateCounter.INSTANCE.getFps(); String str1 = "Ping " + Formatting.WHITE + OyVey.hudManager.getPing(); if (getStringWidth(str1) > getStringWidth(fpsText)) { if (ping.getValue()) { i += 10; event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(str1), (width - getStringWidth(str1) - 2), (height - 2 - i), color); } if (fps.getValue()) { i += 10; event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(fpsText), (width - getStringWidth(fpsText) - 2), (height - 2 - i), color); } } else { if (fps.getValue()) { i += 10; event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(fpsText), (width - getStringWidth(fpsText) - 2), (height - 2 - i), color); } if (ping.getValue()) { i += 10; event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(str1), (width - getStringWidth(str1) - 2), (height - 2 - i), color); } } } else { if (speed.getValue()) { String str = "Speed " + Formatting.WHITE + MathUtility.round((float) (OyVey.hudManager.currentPlayerSpeed * 72f)) + " km/h"; event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(str), (width - getStringWidth(str) - 2), (2 + i++ * 10), color); } if (time.getValue()) { String str = "Time " + Formatting.WHITE + (new SimpleDateFormat("h:mm a")).format(new Date()); event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(str), (width - getStringWidth(str) - 2), (2 + i++ * 10), color); } if (tps.getValue()) { String str = "TPS " + Formatting.WHITE + OyVey.hudManager.getTPS() + (extraTps.getValue() ? " [" + OyVey.hudManager.getTPS2() + "]" : ""); event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(str), (width - getStringWidth(str) - 2), (2 + i++ * 10), color); } String fpsText = "FPS " + Formatting.WHITE + FrameRateCounter.INSTANCE.getFps(); String str1 = "Ping " + Formatting.WHITE + OyVey.hudManager.getPing(); if (getStringWidth(str1) > getStringWidth(fpsText)) { if (ping.getValue()) { event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(str1), (width - getStringWidth(str1) - 2), (2 + i++ * 10), color); } if (fps.getValue()) { event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(fpsText), (width - getStringWidth(fpsText) - 2), (2 + i++ * 10), color); } } else { if (fps.getValue()) { event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(fpsText), (width - getStringWidth(fpsText) - 2), (2 + i++ * 10), color); } if (ping.getValue()) { event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(str1), (width - getStringWidth(str1) - 2), (2 + i++ * 10), color); } } } //Direccion Bar Text X Y Z Cords boolean inHell = Objects.equals(mc.world.getRegistryKey().getValue().getPath(), "the_nether"); int posX = (int) mc.player.getX(); int posY = (int) mc.player.getY(); int posZ = (int) mc.player.getZ(); float nether = !inHell ? 0.125F : 8.0F; int hposX = (int) (mc.player.getX() * nether); int hposZ = (int) (mc.player.getZ() * nether); i = (mc.currentScreen instanceof ChatScreen) ? 14 : 0; String coordinates = Formatting.WHITE + "XYZ " + Formatting.RESET + (inHell ? (posX + ", " + posY + ", " + posZ + Formatting.WHITE + " [" + Formatting.RESET + hposX + ", " + hposZ + Formatting.WHITE + "]" + Formatting.RESET) : (posX + ", " + posY + ", " + posZ + Formatting.WHITE + " [" + Formatting.RESET + hposX + ", " + hposZ + Formatting.WHITE + "]")); String direction1 = ""; if(direction.getValue()){ switch (mc.player.getHorizontalFacing()){ case EAST -> direction1 = "East" + Formatting.WHITE + " [+X]"; case WEST -> direction1 = "West" + Formatting.WHITE + " [-X]"; case NORTH -> direction1 = "North" + Formatting.WHITE + " [-Z]"; case SOUTH -> direction1 = "South" + Formatting.WHITE + " [+Z]"; } } String coords1 = coords.getValue() ? coordinates : ""; i += 10; event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(direction1), 2, (height - i - 11), color); event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(coords1), 2, (height - i), color); //Greeter if (greeter.getValue()) { int widthGreeter = mc.getWindow().getScaledWidth(); switch (this.greetermode.getValue()) { case TIME: { text = TimeDay.getTimeOfDay() + " " + HUD.mc.player.getDisplayName().getString() + ""; break; } } switch (this.greetermode.getValue()) { case CHRISTMAS: { text = "Cracked Anarchy " + "time remove" + HUD.mc.player.getDisplayName().getString() + " :^)"; break; } } switch (this.greetermode.getValue()) { case LONG: { text = "Welcome to Cracked " + HUD.mc.player.getDisplayName().getString() + " :^)"; break; } } switch (this.greetermode.getValue()) { case CUSTOM: { text += this.customGreeter.getValue(); break; } } switch (this.greetermode.getValue()) { case NAME: { text = "Welcome " + HUD.mc.player.getDisplayName().getString(); break; } } switch (this.greetermode.getValue()) { case NONE: { text = ""; break; } } event.getContext().drawTextWithShadow(mc.textRenderer, Text.of(text), (int) (widthGreeter / 2.0F - getStringWidth(text) / 2.0F + 2.0F), (int) 2.0F, color); } //Render Totem Inventory Bar Count if (totemshud.getValue()) { int widthTotem = mc.getWindow().getScaledWidth(); int heightTotem = mc.getWindow().getScaledHeight(); int totems = mc.player.getInventory().main.stream().filter(itemStack -> (itemStack.getItem() == Items.TOTEM_OF_UNDYING)).mapToInt(ItemStack::getCount).sum(); if (mc.player.getOffHandStack().getItem() == Items.TOTEM_OF_UNDYING) totems += mc.player.getOffHandStack().getCount(); if (totems > 0) { int iTotem = widthTotem / 2; int yTotem = heightTotem - 55 - ((mc.player.isSubmergedInWater()) ? 10 : 0); int xTotem = iTotem - 189 + 180 + 2; event.getContext().drawItem(totem, xTotem, yTotem); event.getContext().drawItemInSlot(mc.textRenderer,totem, xTotem, yTotem); event.getContext().drawCenteredTextWithShadow(mc.textRenderer,totems + "", xTotem + 8, (yTotem - 7), 16777215); } } //RenderArmorHud Bar Inventory Visualizer //boolean percent; if (armorhud.getValue()) { int widthArmor = mc.getWindow().getScaledWidth(); int heightArmor = mc.getWindow().getScaledHeight(); int iArmor = widthArmor / 2; int iteration = 0; int yArmor = heightArmor - 55 - ((mc.player.isSubmergedInWater()) ? 10 : 0); for (ItemStack is : mc.player.getInventory().armor) { iteration++; if (is.isEmpty()) continue; int xArmor = iArmor - 90 + (9 - iteration) * 20 + 2; event.getContext().drawItem(is, xArmor, yArmor); event.getContext().drawItemInSlot(mc.textRenderer,is, xArmor, yArmor); String sArmor = (is.getCount() > 1) ? (is.getCount() + "") : ""; event.getContext().drawText(mc.textRenderer,Text.of(sArmor), (xArmor + 19 - 2 - getStringWidth(sArmor)), (yArmor + 9), 16777215, true); if (percent) { float green = (float) (is.getMaxDamage() - is.getDamage()) / (float) is.getMaxDamage(); float red = 1.0F - green; int dmg = 100 - (int) (red * 100.0F); event.getContext().drawText(mc.textRenderer,Text.of(dmg + ""), (xArmor + 8 - getStringWidth(dmg + "") / 2), (yArmor - 11), new Color((int) MathUtility.clamp((red * 255.0F), 0, 255f), (int) MathUtility.clamp((green * 255.0F), 0, 255f), 0).getRGB(), true); } } } } private int getStringWidth(String str) { return mc.textRenderer.getWidth(str); } public enum Greeter { NAME, TIME, CHRISTMAS, LONG, CUSTOM, NONE } }
412
0.970805
1
0.970805
game-dev
MEDIA
0.599314
game-dev
0.991412
1
0.991412
BaobabLims/baobab.lims
7,437
baobab/lims/static/js/Highcharts/code/es-modules/Extensions/Annotations/Mixins/EventEmitterMixin.js
/* * * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ import H from '../../../Core/Globals.js'; import U from '../../../Core/Utilities.js'; var addEvent = U.addEvent, fireEvent = U.fireEvent, objectEach = U.objectEach, pick = U.pick, removeEvent = U.removeEvent; /* eslint-disable valid-jsdoc */ /** * It provides methods for: * - adding and handling DOM events and a drag event, * - mapping a mouse move event to the distance between two following events. * The units of the distance are specific to a transformation, * e.g. for rotation they are radians, for scaling they are scale factors. * * @private * @mixin * @memberOf Annotation */ var eventEmitterMixin = { /** * Add emitter events. */ addEvents: function () { var emitter = this, addMouseDownEvent = function (element) { addEvent(element, H.isTouchDevice ? 'touchstart' : 'mousedown', function (e) { emitter.onMouseDown(e); }, { passive: false }); }; addMouseDownEvent(this.graphic.element); (emitter.labels || []).forEach(function (label) { if (label.options.useHTML && label.graphic.text) { // Mousedown event bound to HTML element (#13070). addMouseDownEvent(label.graphic.text.element); } }); objectEach(emitter.options.events, function (event, type) { var eventHandler = function (e) { if (type !== 'click' || !emitter.cancelClick) { event.call(emitter, emitter.chart.pointer.normalize(e), emitter.target); } }; if ((emitter.nonDOMEvents || []).indexOf(type) === -1) { emitter.graphic.on(type, eventHandler); } else { addEvent(emitter, type, eventHandler, { passive: false }); } }); if (emitter.options.draggable) { addEvent(emitter, 'drag', emitter.onDrag); if (!emitter.graphic.renderer.styledMode) { var cssPointer_1 = { cursor: { x: 'ew-resize', y: 'ns-resize', xy: 'move' }[emitter.options.draggable] }; emitter.graphic.css(cssPointer_1); (emitter.labels || []).forEach(function (label) { if (label.options.useHTML && label.graphic.text) { label.graphic.text.css(cssPointer_1); } }); } } if (!emitter.isUpdating) { fireEvent(emitter, 'add'); } }, /** * Remove emitter document events. */ removeDocEvents: function () { if (this.removeDrag) { this.removeDrag = this.removeDrag(); } if (this.removeMouseUp) { this.removeMouseUp = this.removeMouseUp(); } }, /** * Mouse down handler. */ onMouseDown: function (e) { var emitter = this, pointer = emitter.chart.pointer, prevChartX, prevChartY; if (e.preventDefault) { e.preventDefault(); } // On right click, do nothing: if (e.button === 2) { return; } e = pointer.normalize(e); prevChartX = e.chartX; prevChartY = e.chartY; emitter.cancelClick = false; emitter.chart.hasDraggedAnnotation = true; emitter.removeDrag = addEvent(H.doc, H.isTouchDevice ? 'touchmove' : 'mousemove', function (e) { emitter.hasDragged = true; e = pointer.normalize(e); e.prevChartX = prevChartX; e.prevChartY = prevChartY; fireEvent(emitter, 'drag', e); prevChartX = e.chartX; prevChartY = e.chartY; }, H.isTouchDevice ? { passive: false } : void 0); emitter.removeMouseUp = addEvent(H.doc, H.isTouchDevice ? 'touchend' : 'mouseup', function (e) { emitter.cancelClick = emitter.hasDragged; emitter.hasDragged = false; emitter.chart.hasDraggedAnnotation = false; // ControlPoints vs Annotation: fireEvent(pick(emitter.target, emitter), 'afterUpdate'); emitter.onMouseUp(e); }, H.isTouchDevice ? { passive: false } : void 0); }, /** * Mouse up handler. */ onMouseUp: function (_e) { var chart = this.chart, annotation = this.target || this, annotationsOptions = chart.options.annotations, index = chart.annotations.indexOf(annotation); this.removeDocEvents(); annotationsOptions[index] = annotation.options; }, /** * Drag and drop event. All basic annotations should share this * capability as well as the extended ones. */ onDrag: function (e) { if (this.chart.isInsidePlot(e.chartX - this.chart.plotLeft, e.chartY - this.chart.plotTop)) { var translation = this.mouseMoveToTranslation(e); if (this.options.draggable === 'x') { translation.y = 0; } if (this.options.draggable === 'y') { translation.x = 0; } if (this.points.length) { this.translate(translation.x, translation.y); } else { this.shapes.forEach(function (shape) { shape.translate(translation.x, translation.y); }); this.labels.forEach(function (label) { label.translate(translation.x, translation.y); }); } this.redraw(false); } }, /** * Map mouse move event to the radians. */ mouseMoveToRadians: function (e, cx, cy) { var prevDy = e.prevChartY - cy, prevDx = e.prevChartX - cx, dy = e.chartY - cy, dx = e.chartX - cx, temp; if (this.chart.inverted) { temp = prevDx; prevDx = prevDy; prevDy = temp; temp = dx; dx = dy; dy = temp; } return Math.atan2(dy, dx) - Math.atan2(prevDy, prevDx); }, /** * Map mouse move event to the distance between two following events. */ mouseMoveToTranslation: function (e) { var dx = e.chartX - e.prevChartX, dy = e.chartY - e.prevChartY, temp; if (this.chart.inverted) { temp = dy; dy = dx; dx = temp; } return { x: dx, y: dy }; }, /** * Map mouse move to the scale factors. * * @param {Object} e event * @param {number} cx center x * @param {number} cy center y **/ mouseMoveToScale: function (e, cx, cy) { var prevDx = e.prevChartX - cx, prevDy = e.prevChartY - cy, dx = e.chartX - cx, dy = e.chartY - cy, sx = (dx || 1) / (prevDx || 1), sy = (dy || 1) / (prevDy || 1), temp; if (this.chart.inverted) { temp = sy; sy = sx; sx = temp; } return { x: sx, y: sy }; }, /** * Destroy the event emitter. */ destroy: function () { this.removeDocEvents(); removeEvent(this); this.hcEvents = null; } }; export default eventEmitterMixin;
412
0.852957
1
0.852957
game-dev
MEDIA
0.736129
game-dev
0.939914
1
0.939914
mrakakuy/kotlin-godot-wrapper
1,780
samples/games/kotlin/src/main/kotlin/godot/samples/games/shmup/Camera.kt
package godot.samples.games.shmup import platform.posix.rand import godot.Camera2D import godot.core.Vector2 class Camera: Camera2D() { var duration = 0.0 var periodInMs = 0.0 var amplitude = 0.0 var timer = 0.0 var lastShookTimer = 0.0 var previousX = 0.0 var previousY = 0.0 var lastOffset = Vector2(0, 0) override fun _process(delta: Double) { if (timer == 0.0){ if(offset.length() > 1.0) offset /= 4.0 else offset = Vector2() return } lastShookTimer += delta while (lastShookTimer >= periodInMs ){ lastShookTimer -= periodInMs val intensity = amplitude * (1 - ((duration - timer) / duration)) val newX = ((rand().toDouble() / 10000) % 2) - 1 val xComponent = intensity * (previousX + (delta * (newX - previousX))) val newY = ((rand().toDouble() / 10000) % 2) - 1 val yComponent = intensity * (previousY + (delta * (newY - previousY))) previousX = newX previousY = newY val newOffset = Vector2(xComponent, yComponent) offset -= lastOffset + newOffset lastOffset = newOffset } timer -= delta if (timer <= 0.0) { timer = 0.0 offset -= lastOffset } } fun shake(duration: Double, frequency: Double, amplitude: Double){ this.duration = duration timer = duration periodInMs = 1.0 / frequency this.amplitude = amplitude previousX = ((rand().toDouble() / 10000) % 2) - 1 previousY = ((rand().toDouble() / 10000) % 2) - 1 offset -= lastOffset lastOffset = Vector2() } }
412
0.876868
1
0.876868
game-dev
MEDIA
0.901158
game-dev
0.934116
1
0.934116
wishawa/async_ui
2,945
async_ui_web_core/src/node_container.rs
use std::{ future::Future, pin::Pin, task::{Context, Poll}, }; use pin_project::{pin_project, pinned_drop}; use crate::{ context::{DomContext, NodeGroup, DOM_CONTEXT}, dropping::DetachmentBlocker, position::ChildPosition, }; /// Future wrapper where anything rendered in its child will appear as child of the node. /// All common components (`Div`, `Button`, etc.) uses this internally. #[pin_project(PinnedDrop)] pub struct ContainerNodeFuture<C> { #[pin] child_future: C, group: NodeGroup, container: web_sys::Node, add_self: AddSelfMode, drop: DetachmentBlocker, } /// Should the node be added to the parent? enum AddSelfMode { ShouldNotAdd, ShouldAdd, Added, } impl<C: Future> ContainerNodeFuture<C> { /// Return a future wrapping the given child future. /// Any node rendered by the child future will appear inside the given node. /// Upon first poll of the future `node` will be added to the parent. pub fn new(child_future: C, node: web_sys::Node) -> Self { Self { child_future, group: Default::default(), container: node, add_self: AddSelfMode::ShouldAdd, drop: DetachmentBlocker, } } /// Like `new` but `node` won't be added to the parent (do that manually). pub fn new_root(child_future: C, node: web_sys::Node) -> Self { Self { child_future, group: Default::default(), container: node, add_self: AddSelfMode::ShouldNotAdd, drop: DetachmentBlocker, } } } impl<C: Future> Future for ContainerNodeFuture<C> { type Output = C::Output; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); if matches!(this.add_self, AddSelfMode::ShouldAdd) { *this.add_self = AddSelfMode::Added; DOM_CONTEXT.with(|ctx| { ctx.add_child(ChildPosition::default(), this.container.clone()); }) } let ctx = DomContext::Container { group: this.group, container: this.container, }; DOM_CONTEXT.set(&ctx, || this.child_future.poll(cx)) } } #[pinned_drop] impl<C> PinnedDrop for ContainerNodeFuture<C> { fn drop(self: Pin<&mut Self>) { if matches!(self.add_self, AddSelfMode::Added) { // we added our node, we should remove it if !self.drop.block_until_drop() { DOM_CONTEXT.with(|ctx| { ctx.remove_child(ChildPosition::default()); }) } } else { // we didn't add our node let this = self.project(); DomContext::Container { group: this.group, container: this.container, } .remove_child(ChildPosition::default()); } } }
412
0.90316
1
0.90316
game-dev
MEDIA
0.312771
game-dev
0.881977
1
0.881977
emawind84/SelacoVR
28,174
src/common/fonts/v_font.cpp
/* ** v_font.cpp ** Font management ** **--------------------------------------------------------------------------- ** Copyright 1998-2016 Randy Heit ** Copyright 2005-2019 Christoph Oelckers ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. **--------------------------------------------------------------------------- ** */ // HEADER FILES ------------------------------------------------------------ #include <stdlib.h> #include <string.h> #include <math.h> #include "m_swap.h" #include "v_font.h" #include "filesystem.h" #include "cmdlib.h" #include "sc_man.h" #include "gstrings.h" #include "image.h" #include "utf8.h" #include "fontchars.h" #include "textures.h" #include "texturemanager.h" #include "printf.h" #include "palentry.h" #include "fontinternals.h" // MACROS ------------------------------------------------------------------ #define DEFAULT_LOG_COLOR PalEntry(223,223,223) // TYPES ------------------------------------------------------------------- // EXTERNAL FUNCTION PROTOTYPES -------------------------------------------- // PUBLIC FUNCTION PROTOTYPES ---------------------------------------------- // PRIVATE FUNCTION PROTOTYPES --------------------------------------------- static int TranslationMapCompare (const void *a, const void *b); // EXTERNAL DATA DECLARATIONS ---------------------------------------------- extern int PrintColors[]; extern TArray<FBitmap> sheetBitmaps; // PUBLIC DATA DEFINITIONS ------------------------------------------------- FFont* SmallFont, * SmallFont2, * BigFont, * BigUpper, * ConFont, * IntermissionFont, * NewConsoleFont, * NewSmallFont, * CurrentConsoleFont, * OriginalSmallFont, * AlternativeSmallFont, * OriginalBigFont, *AlternativeBigFont; FFont *FFont::FirstFont = nullptr; int NumTextColors; static bool translationsLoaded; // PRIVATE DATA DEFINITIONS ------------------------------------------------ TArray<TranslationParm> TranslationParms[2]; TArray<TranslationMap> TranslationLookup; TArray<PalEntry> TranslationColors; // CODE -------------------------------------------------------------------- FFont *V_GetFont(const char *name, const char *fontlumpname) { if (name == nullptr) return nullptr; if (!stricmp(name, "DBIGFONT")) name = "BigFont"; else if (!stricmp(name, "CONFONT")) name = "ConsoleFont"; // several mods have used the name CONFONT directly and effectively duplicated the font. else if (!stricmp(name, "INDEXFON")) name = "IndexFont"; // Same here - for whatever reason some people had to use its 8 character name... FFont *font = FFont::FindFont (name); if (font == nullptr) { if (!stricmp(name, "BIGUPPER")) { font = FFont::FindFont("BIGFONT"); if (font) return font; } int lump = -1; int folderfile = -1; std::vector<FileSys::FolderEntry> folderdata; FStringf path("fonts/%s/", name); // Use a folder-based font only if it comes from a later file than the single lump version. if (fileSystem.GetFilesInFolder(path.GetChars(), folderdata, true)) { // This assumes that any custom font comes in one piece and not distributed across multiple resource files. folderfile = fileSystem.GetFileContainer(folderdata[0].lumpnum); } lump = fileSystem.CheckNumForFullName(fontlumpname? fontlumpname : name, true); if (lump != -1 && fileSystem.GetFileContainer(lump) >= folderfile) { uint32_t head; { auto lumpy = fileSystem.OpenFileReader (lump); lumpy.Read (&head, 4); } if ((head & MAKE_ID(255,255,255,0)) == MAKE_ID('F','O','N',0) || head == MAKE_ID(0xE1,0xE6,0xD5,0x1A)) { FFont *CreateSingleLumpFont (const char *fontname, int lump); font = CreateSingleLumpFont (name, lump); if (translationsLoaded) font->LoadTranslations(); return font; } } FTextureID texid = TexMan.CheckForTexture (name, ETextureType::Any); if (texid.isValid()) { auto tex = TexMan.GetGameTexture(texid); if (tex && tex->GetSourceLump() >= folderfile) { FFont *CreateSinglePicFont(const char *name); font = CreateSinglePicFont (name); return font; } } if (folderdata.size() > 0) { font = new FFont(name, nullptr, name, 0, 0, 1, -1); if (translationsLoaded) font->LoadTranslations(); return font; } } return font; } //========================================================================== // // V_InitCustomFonts // // Initialize a list of custom multipatch fonts // //========================================================================== void V_InitCustomFonts() { FScanner sc; FGameTexture *lumplist[256]; bool notranslate[256]; bool donttranslate; FString namebuffer, templatebuf; int i; int llump,lastlump=0; int format; int start; int first; int count; int spacewidth = -1; int kerning; char cursor = '_'; bool ignoreoffsets = false; int MinLum = -1, MaxLum = -1; while ((llump = fileSystem.FindLump ("FONTDEFS", &lastlump)) != -1) { sc.OpenLumpNum(llump); while (sc.GetString()) { memset (lumplist, 0, sizeof(lumplist)); memset (notranslate, 0, sizeof(notranslate)); donttranslate = false; namebuffer = sc.String; format = 0; start = 33; first = 33; count = 223; spacewidth = -1; kerning = 0; sc.MustGetStringName ("{"); while (!sc.CheckString ("}")) { sc.MustGetString(); if (sc.Compare ("TEMPLATE")) { if (format == 2) goto wrong; sc.MustGetString(); templatebuf = sc.String; format = 1; } else if (sc.Compare ("BASE")) { if (format == 2) goto wrong; sc.MustGetNumber(); start = sc.Number; format = 1; } else if (sc.Compare ("FIRST")) { if (format == 2) goto wrong; sc.MustGetNumber(); first = sc.Number; format = 1; } else if (sc.Compare ("COUNT")) { if (format == 2) goto wrong; sc.MustGetNumber(); count = sc.Number; format = 1; } else if (sc.Compare ("CURSOR")) { sc.MustGetString(); cursor = sc.String[0]; } else if (sc.Compare ("SPACEWIDTH")) { sc.MustGetNumber(); spacewidth = sc.Number; } else if (sc.Compare("DONTTRANSLATE")) { donttranslate = true; } else if (sc.Compare ("NOTRANSLATION")) { if (format == 1) goto wrong; while (sc.CheckNumber() && !sc.Crossed) { if (sc.Number >= 0 && sc.Number < 256) notranslate[sc.Number] = true; } format = 2; } else if (sc.Compare("KERNING")) { sc.MustGetNumber(); kerning = sc.Number; } else if (sc.Compare("ignoreoffsets")) { ignoreoffsets = true; } else if (sc.Compare("minluminosity")) { sc.MustGetValue(false); MinLum = (int16_t)clamp(sc.Number, 0, 255); } else if (sc.Compare("maxluminosity")) { sc.MustGetValue(false); MaxLum = (int16_t)clamp(sc.Number, 0, 255); } else { if (format == 1) goto wrong; // The braces must be filtered so because they'd be treated as block terminators otherwise. if (!strcmp(sc.String, "-{")) strcpy(sc.String, "{"); if (!strcmp(sc.String, "-}")) strcpy(sc.String, "}"); FGameTexture **p = &lumplist[*(unsigned char*)sc.String]; sc.MustGetString(); FTextureID texid = TexMan.CheckForTexture(sc.String, ETextureType::MiscPatch); if (texid.Exists()) { *p = TexMan.GetGameTexture(texid); } else if (fileSystem.GetFileContainer(sc.LumpNum) >= fileSystem.GetIwadNum()) { // Print a message only if this isn't in zdoom.pk3 sc.ScriptMessage("%s: Unable to find texture in font definition for %s", sc.String, namebuffer.GetChars()); } format = 2; } } if (format == 1) { FFont *fnt = new FFont(namebuffer.GetChars(), templatebuf.GetChars(), nullptr, first, count, start, llump, spacewidth, donttranslate); fnt->SetCursor(cursor); fnt->SetKerning(kerning); if (ignoreoffsets) fnt->ClearOffsets(); } else if (format == 2) { for (i = 0; i < 256; i++) { if (lumplist[i] != nullptr) { first = i; break; } } for (i = 255; i >= 0; i--) { if (lumplist[i] != nullptr) { count = i - first + 1; break; } } if (count > 0) { FFont *CreateSpecialFont (const char *name, int first, int count, FGameTexture **lumplist, const bool *notranslate, int lump, bool donttranslate); FFont *fnt = CreateSpecialFont(namebuffer.GetChars(), first, count, &lumplist[first], notranslate, llump, donttranslate); fnt->SetCursor(cursor); fnt->SetKerning(kerning); if (spacewidth >= 0) fnt->SpaceWidth = spacewidth; fnt->MinLum = MinLum; fnt->MaxLum = MaxLum; if (ignoreoffsets) fnt->ClearOffsets(); } } else goto wrong; } sc.Close(); } return; wrong: sc.ScriptError ("Invalid combination of properties in font '%s', %s not allowed", namebuffer.GetChars(), sc.String); } //========================================================================== // // V_InitFontColors // // Reads the list of color translation definitions into memory. // //========================================================================== void V_InitFontColors () { TArray<FName> names; int lump, lastlump = 0; TranslationParm tparm = { 0, 0, {0}, {0} }; // Silence GCC (for real with -Wextra ) TArray<TranslationParm> parms; TArray<TempParmInfo> parminfo; TArray<TempColorInfo> colorinfo; int c, parmchoice; TempParmInfo info; TempColorInfo cinfo; PalEntry logcolor; unsigned int i, j; int k, index; info.Index = -1; TranslationParms[0].Clear(); TranslationParms[1].Clear(); TranslationLookup.Clear(); TranslationColors.Clear(); while ((lump = fileSystem.FindLump ("TEXTCOLO", &lastlump)) != -1) { FScanner sc(lump); while (sc.GetString()) { names.Clear(); logcolor = DEFAULT_LOG_COLOR; // Everything until the '{' is considered a valid name for the // color range. names.Push (sc.String); while (sc.MustGetString(), !sc.Compare ("{")) { if (names[0] == NAME_Untranslated) { sc.ScriptError ("The \"untranslated\" color may not have any other names"); } names.Push (sc.String); } parmchoice = 0; info.StartParm[0] = parms.Size(); info.StartParm[1] = 0; info.ParmLen[1] = info.ParmLen[0] = 0; tparm.RangeEnd = tparm.RangeStart = -1; while (sc.MustGetString(), !sc.Compare ("}")) { if (sc.Compare ("Console:")) { if (parmchoice == 1) { sc.ScriptError ("Each color may only have one set of console ranges"); } parmchoice = 1; info.StartParm[1] = parms.Size(); info.ParmLen[0] = info.StartParm[1] - info.StartParm[0]; tparm.RangeEnd = tparm.RangeStart = -1; } else if (sc.Compare ("Flat:")) { sc.MustGetString(); logcolor = V_GetColor (sc); } else { // Get first color c = V_GetColor (sc); tparm.Start[0] = RPART(c); tparm.Start[1] = GPART(c); tparm.Start[2] = BPART(c); // Get second color sc.MustGetString(); c = V_GetColor (sc); tparm.End[0] = RPART(c); tparm.End[1] = GPART(c); tparm.End[2] = BPART(c); // Check for range specifier if (sc.CheckNumber()) { if (tparm.RangeStart == -1 && sc.Number != 0) { sc.ScriptError ("The first color range must start at position 0"); } if (sc.Number < 0 || sc.Number > 256) { sc.ScriptError ("The color range must be within positions [0,256]"); } if (sc.Number <= tparm.RangeEnd) { sc.ScriptError ("The color range must not start before the previous one ends"); } tparm.RangeStart = sc.Number; sc.MustGetNumber(); if (sc.Number < 0 || sc.Number > 256) { sc.ScriptError ("The color range must be within positions [0,256]"); } if (sc.Number <= tparm.RangeStart) { sc.ScriptError ("The color range end position must be larger than the start position"); } tparm.RangeEnd = sc.Number; } else { tparm.RangeStart = tparm.RangeEnd + 1; tparm.RangeEnd = 256; if (tparm.RangeStart >= tparm.RangeEnd) { sc.ScriptError ("The color has too many ranges"); } } parms.Push (tparm); } } info.ParmLen[parmchoice] = parms.Size() - info.StartParm[parmchoice]; if (info.ParmLen[0] == 0) { if (names[0] != NAME_Untranslated) { sc.ScriptError ("There must be at least one normal range for a color"); } } else { if (names[0] == NAME_Untranslated) { sc.ScriptError ("The \"untranslated\" color must be left undefined"); } } if (info.ParmLen[1] == 0 && names[0] != NAME_Untranslated) { // If a console translation is unspecified, make it white, since the console // font has no color information stored with it. tparm.RangeStart = 0; tparm.RangeEnd = 256; tparm.Start[2] = tparm.Start[1] = tparm.Start[0] = 0; tparm.End[2] = tparm.End[1] = tparm.End[0] = 255; info.StartParm[1] = parms.Push (tparm); info.ParmLen[1] = 1; } cinfo.ParmInfo = parminfo.Push (info); // Record this color information for each name it goes by for (i = 0; i < names.Size(); ++i) { // Redefine duplicates in-place for (j = 0; j < colorinfo.Size(); ++j) { if (colorinfo[j].Name == names[i]) { colorinfo[j].ParmInfo = cinfo.ParmInfo; colorinfo[j].LogColor = logcolor; break; } } if (j == colorinfo.Size()) { cinfo.Name = names[i]; cinfo.LogColor = logcolor; colorinfo.Push (cinfo); } } } } // Make permananent copies of all the color information we found. for (i = 0, index = 0; i < colorinfo.Size(); ++i) { TranslationMap tmap; TempParmInfo *pinfo; tmap.Name = colorinfo[i].Name; pinfo = &parminfo[colorinfo[i].ParmInfo]; if (pinfo->Index < 0) { // Write out the set of remappings for this color. for (k = 0; k < 2; ++k) { for (j = 0; j < pinfo->ParmLen[k]; ++j) { TranslationParms[k].Push (parms[pinfo->StartParm[k] + j]); } } TranslationColors.Push (colorinfo[i].LogColor); pinfo->Index = index++; } tmap.Number = pinfo->Index; TranslationLookup.Push (tmap); } // Leave a terminating marker at the ends of the lists. tparm.RangeStart = -1; TranslationParms[0].Push (tparm); TranslationParms[1].Push (tparm); // Sort the translation lookups for fast binary searching. qsort (&TranslationLookup[0], TranslationLookup.Size(), sizeof(TranslationLookup[0]), TranslationMapCompare); NumTextColors = index; assert (NumTextColors >= NUM_TEXT_COLORS); } //========================================================================== // // TranslationMapCompare // //========================================================================== static int TranslationMapCompare (const void *a, const void *b) { return int(((const TranslationMap *)a)->Name.GetIndex()) - int(((const TranslationMap *)b)->Name.GetIndex()); } //========================================================================== // // V_FindFontColor // // Returns the color number for a particular named color range. // //========================================================================== EColorRange V_FindFontColor (FName name) { int min = 0, max = TranslationLookup.Size() - 1; while (min <= max) { unsigned int mid = (min + max) / 2; const TranslationMap *probe = &TranslationLookup[mid]; if (probe->Name == name) { return EColorRange(probe->Number); } else if (probe->Name < name) { min = mid + 1; } else { max = mid - 1; } } return CR_UNTRANSLATED; } //========================================================================== // // CreateLuminosityTranslationRanges // // Create universal remap ranges for hardware rendering. // //========================================================================== static PalEntry* paletteptr; static void CreateLuminosityTranslationRanges() { paletteptr = (PalEntry*)ImageArena.Alloc(256 * ((NumTextColors * 2)) * sizeof(PalEntry)); for (int l = 0; l < 2; l++) { auto parmstart = &TranslationParms[l][0]; // Put the data into the image arena where it gets deleted with the rest of the texture data. for (int p = 0; p < NumTextColors; p++) { // Intended storage order is Range 1, variant 1 - Range 1, variant 2, Range 2, variant 1, and so on. // The storage of the ranges forces us to go through this differently... PalEntry* palette = paletteptr + p * 512 + l * 256; for (int v = 0; v < 256; v++) { palette[v].b = palette[v].g = palette[v].r = (uint8_t)v; } if (p != CR_UNTRANSLATED) // This table skips the untranslated entry. Do I need to say that the stored data format is garbage? >) { for (int v = 0; v < 256; v++) { // Find the color range that this luminosity value lies within. const TranslationParm* parms = parmstart - 1; do { parms++; if (parms->RangeStart <= v && parms->RangeEnd >= v) break; } while (parms[1].RangeStart > parms[0].RangeEnd); // Linearly interpolate to find out which color this luminosity level gets. int rangev = ((v - parms->RangeStart) << 8) / (parms->RangeEnd - parms->RangeStart); int r = ((parms->Start[0] << 8) + rangev * (parms->End[0] - parms->Start[0])) >> 8; // red int g = ((parms->Start[1] << 8) + rangev * (parms->End[1] - parms->Start[1])) >> 8; // green int b = ((parms->Start[2] << 8) + rangev * (parms->End[2] - parms->Start[2])) >> 8; // blue palette[v].r = (uint8_t)clamp(r, 0, 255); palette[v].g = (uint8_t)clamp(g, 0, 255); palette[v].b = (uint8_t)clamp(b, 0, 255); } // Advance to the next color range. while (parmstart[1].RangeStart > parmstart[0].RangeEnd) { parmstart++; } parmstart++; } } } } //========================================================================== // // V_ApplyLuminosityTranslation // // Applies the translation to a bitmap for texture generation. // //========================================================================== void V_ApplyLuminosityTranslation(const LuminosityTranslationDesc& lum, uint8_t* pixel, int size) { int colorrange = lum.colorrange; if (colorrange >= NumTextColors * 2) return; int lum_min = lum.lum_min; int lum_max = lum.lum_max; int lum_range = (lum_max - lum_min + 1); PalEntry* remap = paletteptr + colorrange * 256; for (int i = 0; i < size; i++, pixel += 4) { // we must also process the transparent pixels here to ensure proper filtering on the characters' edges. int gray = PalEntry(255, pixel[2], pixel[1], pixel[0]).Luminance(); int lumadjust = (gray - lum_min) * 255 / lum_range; int index = clamp(lumadjust, 0, 255); PalEntry newcol = remap[index]; // extend the range if we find colors outside what initial analysis provided. if (gray < lum_min && lum_min != 0) { newcol.r = newcol.r * gray / lum_min; newcol.g = newcol.g * gray / lum_min; newcol.b = newcol.b * gray / lum_min; } else if (gray > lum_max && lum_max != 0) { newcol.r = clamp(newcol.r * gray / lum_max, 0, 255); newcol.g = clamp(newcol.g * gray / lum_max, 0, 255); newcol.b = clamp(newcol.b * gray / lum_max, 0, 255); } pixel[0] = newcol.b; pixel[1] = newcol.g; pixel[2] = newcol.r; } } //========================================================================== // // SetDefaultTranslation // // Builds a translation to map the stock font to a mod provided replacement. // This probably won't work that well if the original font is extremely colorful. // //========================================================================== static void CalcDefaultTranslation(FFont* base, int index) { uint32_t othercolors[256] = {}; base->RecordAllTextureColors(othercolors); TArray<double> otherluminosity; base->GetLuminosity(othercolors, otherluminosity); PalEntry *remap = &paletteptr[index * 256]; memset(remap, 0, 1024); for (unsigned i = 0; i < 256; i++) { auto lum = otherluminosity[i]; if (lum >= 0 && lum <= 1) { int lumidx = int(lum * 255); remap[lumidx] = GPalette.BaseColors[i]; remap[lumidx].a = 255; } } // todo: fill the gaps. //remap[0] = 0; int lowindex = 0; while (lowindex < 255 && remap[lowindex].a == 0) lowindex++; lowindex++; int highindex = lowindex + 1; while (lowindex < 255) { while (highindex <= 255 && remap[highindex].a == 0) highindex++; if (lowindex == 0) { for (int i = 0; i < highindex; i++) remap[i] = remap[highindex]; lowindex = highindex++; } else if (highindex > 256) { for (int i = lowindex + 1; i < highindex; i++) remap[i] = remap[lowindex]; break; } else { for (int i = lowindex + 1; i < highindex; i++) { PalEntry color1 = remap[lowindex]; PalEntry color2 = remap[highindex]; double weight = (i - lowindex) / double(highindex - lowindex); int r = int(color1.r + weight * (color2.r - color1.r)); int g = int(color1.g + weight * (color2.g - color1.g)); int b = int(color1.b + weight * (color2.b - color1.b)); r = clamp(r, 0, 255); g = clamp(g, 0, 255); b = clamp(b, 0, 255); remap[i] = PalEntry(255, r, g, b); } lowindex = highindex++; } } } //========================================================================== // // V_LogColorFromColorRange // // Returns the color to use for text in the startup/error log window. // //========================================================================== PalEntry V_LogColorFromColorRange (EColorRange range) { if ((unsigned int)range >= TranslationColors.Size()) { // Return default color return DEFAULT_LOG_COLOR; } return TranslationColors[range]; } //========================================================================== // // V_ParseFontColor // // Given a pointer to a color identifier (presumably just after a color // escape character), return the color it identifies and advances // color_value to just past it. // //========================================================================== EColorRange V_ParseFontColor (const uint8_t *&color_value, int normalcolor, int boldcolor) { const uint8_t *ch = color_value; int newcolor = *ch++; if (newcolor == '-') // Normal { newcolor = normalcolor; } else if (newcolor == '+') // Bold { newcolor = boldcolor; } else if (newcolor == '!') // Team chat { newcolor = PrintColors[PRINT_TEAMCHAT]; } else if (newcolor == '*') // Chat { newcolor = PrintColors[PRINT_CHAT]; } else if (newcolor == '[') // Named { const uint8_t *namestart = ch; while (*ch != ']' && *ch != '\0') { ch++; } FName rangename((const char *)namestart, int(ch - namestart), true); if (*ch != '\0') { ch++; } newcolor = V_FindFontColor (rangename); } else if (newcolor >= 'A' && newcolor < NUM_TEXT_COLORS + 'A') // Standard, uppercase { newcolor -= 'A'; } else if (newcolor >= 'a' && newcolor < NUM_TEXT_COLORS + 'a') // Standard, lowercase { newcolor -= 'a'; } else // Incomplete! { color_value = ch - (newcolor == '\0'); return CR_UNDEFINED; } color_value = ch; return EColorRange(newcolor); } //========================================================================== // // V_InitFonts // // Fixme: This really needs to be a bit more flexible // and less rigidly tied to the original game data. // //========================================================================== void V_InitFonts() { sheetBitmaps.Clear(); CreateLuminosityTranslationRanges(); V_InitCustomFonts(); FFont *CreateHexLumpFont(const char *fontname, int lump); FFont *CreateHexLumpFont2(const char *fontname, int lump); auto lump = fileSystem.CheckNumForFullName("newconsolefont.hex", 0); // This is always loaded from gzdoom.pk3 to prevent overriding it with incomplete replacements. if (lump == -1) I_FatalError("newconsolefont.hex not found"); // This font is needed - do not start up without it. NewConsoleFont = CreateHexLumpFont("NewConsoleFont", lump); NewSmallFont = CreateHexLumpFont2("NewSmallFont", lump); CurrentConsoleFont = NewConsoleFont; ConFont = V_GetFont("ConsoleFont", "CONFONT"); V_GetFont("IndexFont", "INDEXFON"); // detect potential replacements for this one. } void V_LoadTranslations() { for (auto font = FFont::FirstFont; font; font = font->Next) { if (!font->noTranslate) font->LoadTranslations(); } if (BigFont) { CalcDefaultTranslation(BigFont, CR_UNTRANSLATED * 2 + 1); if (OriginalBigFont != nullptr && OriginalBigFont != BigFont) { assert(IsLuminosityTranslation(OriginalBigFont->Translations[0])); int sometrans = OriginalBigFont->Translations[0].index(); sometrans &= ~(0x3fff << 16); sometrans |= (CR_UNTRANSLATED * 2 + 1) << 16; OriginalBigFont->Translations[CR_UNTRANSLATED] = FTranslationID::fromInt(sometrans); OriginalBigFont->forceremap = true; } } if (SmallFont) { CalcDefaultTranslation(SmallFont, CR_UNTRANSLATED * 2); if (OriginalSmallFont != nullptr && OriginalSmallFont != SmallFont) { assert(IsLuminosityTranslation(OriginalSmallFont->Translations[0])); int sometrans = OriginalSmallFont->Translations[0].index(); sometrans &= ~(0x3fff << 16); sometrans |= (CR_UNTRANSLATED * 2) << 16; OriginalSmallFont->Translations[CR_UNTRANSLATED] = FTranslationID::fromInt(sometrans); OriginalSmallFont->forceremap = true; } if (NewSmallFont != nullptr) { assert(IsLuminosityTranslation(NewSmallFont->Translations[0])); int sometrans = NewSmallFont->Translations[0].index(); sometrans &= ~(0x3fff << 16); sometrans |= (CR_UNTRANSLATED * 2) << 16; NewSmallFont->Translations[CR_UNTRANSLATED] = FTranslationID::fromInt(sometrans); NewSmallFont->forceremap = true; } } translationsLoaded = true; } void V_ClearFonts() { while (FFont::FirstFont != nullptr) { delete FFont::FirstFont; } FFont::FirstFont = nullptr; AlternativeSmallFont = OriginalSmallFont = CurrentConsoleFont = NewSmallFont = NewConsoleFont = SmallFont = SmallFont2 = BigFont = ConFont = IntermissionFont = nullptr; sheetBitmaps.Clear(); } //========================================================================== // // CleanseString // // Does some mild sanity checking on a string: If it ends with an incomplete // color escape, the escape is removed. // //========================================================================== char* CleanseString(char* str) { char* escape = strrchr(str, TEXTCOLOR_ESCAPE); if (escape != NULL) { if (escape[1] == '\0') { *escape = '\0'; } else if (escape[1] == '[') { char* close = strchr(escape + 2, ']'); if (close == NULL) { *escape = '\0'; } } } return str; }
412
0.927034
1
0.927034
game-dev
MEDIA
0.53014
game-dev,graphics-rendering
0.975135
1
0.975135
DiscordSRV/DiscordSRV
19,967
src/main/java/github/scarsz/discordsrv/listeners/PlayerAdvancementDoneListener.java
/* * DiscordSRV - https://github.com/DiscordSRV/DiscordSRV * * Copyright (C) 2016 - 2024 Austin "Scarsz" Shapiro * * 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/gpl-3.0.html>. */ package github.scarsz.discordsrv.listeners; import github.scarsz.discordsrv.Debug; import github.scarsz.discordsrv.DiscordSRV; import github.scarsz.discordsrv.api.events.AchievementMessagePostProcessEvent; import github.scarsz.discordsrv.api.events.AchievementMessagePreProcessEvent; import github.scarsz.discordsrv.objects.MessageFormat; import github.scarsz.discordsrv.util.*; import lombok.SneakyThrows; import java.lang.reflect.Field; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.TextChannel; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import org.apache.commons.lang3.StringUtils; import org.bukkit.Bukkit; import org.bukkit.GameRule; import org.bukkit.NamespacedKey; import org.bukkit.World; import org.bukkit.advancement.Advancement; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerAdvancementDoneEvent; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiFunction; import java.util.stream.Collectors; import java.util.Optional; public class PlayerAdvancementDoneListener implements Listener { private static final boolean GAMERULE_CLASS_AVAILABLE; private static final Object GAMERULE; static { String gamerule = "announceAdvancements"; Object gameruleValue = null; try { Class<?> gameRuleClass = Class.forName("org.bukkit.GameRule"); gameruleValue = gameRuleClass.getMethod("getByName", String.class).invoke(null, gamerule); } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) {} GAMERULE_CLASS_AVAILABLE = gameruleValue != null; GAMERULE = GAMERULE_CLASS_AVAILABLE ? gameruleValue : gamerule; } public PlayerAdvancementDoneListener() { Bukkit.getPluginManager().registerEvents(this, DiscordSRV.getPlugin()); } @EventHandler(priority = EventPriority.MONITOR) public void onPlayerAdvancementDone(PlayerAdvancementDoneEvent event) { Player player = event.getPlayer(); // return if advancement or player objects are knackered because this can apparently happen for some reason if (event.getAdvancement() == null || player == null) return; // respect invisibility plugins if (PlayerUtil.isVanished(player)) return; SchedulerUtil.runTaskAsynchronously(DiscordSRV.getPlugin(), () -> runAsync(event)); } private void runAsync(PlayerAdvancementDoneEvent event) { Player player = event.getPlayer(); Advancement advancement = event.getAdvancement(); if (advancementIsHiddenInChat(advancement, player.getWorld())) return; String channelName = DiscordSRV.getPlugin().getOptionalChannel("awards"); MessageFormat messageFormat = DiscordSRV.getPlugin().getMessageFromConfiguration("MinecraftPlayerAchievementMessage"); if (messageFormat == null) return; // turn "story/advancement_name" into "Advancement Name" String advancementTitle = getTitle(advancement); AchievementMessagePreProcessEvent preEvent = DiscordSRV.api.callEvent(new AchievementMessagePreProcessEvent(channelName, messageFormat, player, advancementTitle, event)); if (preEvent.isCancelled()) { DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "AchievementMessagePreProcessEvent was cancelled, message send aborted"); return; } // Update from event in case any listeners modified parameters advancementTitle = preEvent.getAchievementName(); channelName = preEvent.getChannel(); messageFormat = preEvent.getMessageFormat(); if (messageFormat == null) return; String finalAchievementName = StringUtils.isNotBlank(advancementTitle) ? advancementTitle : ""; String avatarUrl = DiscordSRV.getAvatarUrl(player); String botAvatarUrl = DiscordUtil.getJda().getSelfUser().getEffectiveAvatarUrl(); String botName = DiscordSRV.getPlugin().getMainGuild() != null ? DiscordSRV.getPlugin().getMainGuild().getSelfMember().getEffectiveName() : DiscordUtil.getJda().getSelfUser().getName(); String displayName = StringUtils.isNotBlank(player.getDisplayName()) ? MessageUtil.strip(player.getDisplayName()) : ""; TextChannel destinationChannel = DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(channelName); BiFunction<String, Boolean, String> translator = (content, needsEscape) -> { if (content == null) return null; content = content .replaceAll("%time%|%date%", TimeUtil.timeStamp()) .replace("%username%", needsEscape ? DiscordUtil.escapeMarkdown(player.getName()) : player.getName()) .replace("%displayname%", needsEscape ? DiscordUtil.escapeMarkdown(displayName) : displayName) .replace("%usernamenoescapes%", player.getName()) .replace("%displaynamenoescapes%", displayName) .replace("%world%", player.getWorld().getName()) .replace("%achievement%", MessageUtil.strip(needsEscape ? DiscordUtil.escapeMarkdown(finalAchievementName) : finalAchievementName)) .replace("%embedavatarurl%", avatarUrl) .replace("%botavatarurl%", botAvatarUrl) .replace("%botname%", botName); if (destinationChannel != null) content = DiscordUtil.translateEmotes(content, destinationChannel.getGuild()); content = PlaceholderUtil.replacePlaceholdersToDiscord(content, player); return content; }; Message discordMessage = DiscordSRV.translateMessage(messageFormat, translator); if (discordMessage == null) return; String webhookName = translator.apply(messageFormat.getWebhookName(), false); String webhookAvatarUrl = translator.apply(messageFormat.getWebhookAvatarUrl(), false); AchievementMessagePostProcessEvent postEvent = DiscordSRV.api.callEvent(new AchievementMessagePostProcessEvent(channelName, discordMessage, player, advancementTitle, event, messageFormat.isUseWebhooks(), webhookName, webhookAvatarUrl, preEvent.isCancelled())); if (postEvent.isCancelled()) { DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "AchievementMessagePostProcessEvent was cancelled, message send aborted"); return; } // Update from event in case any listeners modified parameters channelName = postEvent.getChannel(); discordMessage = postEvent.getDiscordMessage(); TextChannel textChannel = DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(channelName); if (postEvent.isUsingWebhooks()) { WebhookUtil.deliverMessage(textChannel, postEvent.getWebhookName(), postEvent.getWebhookAvatarUrl(), discordMessage.getContentRaw(), discordMessage.getEmbeds().stream().findFirst().orElse(null)); } else { DiscordUtil.queueMessage(textChannel, discordMessage, true); } } private static Method ADVANCEMENT_GET_DISPLAY_METHOD = null; private static Method ADVANCEMENT_DISPLAY_ANNOUNCE_CHAT_METHOD = null; @SneakyThrows @SuppressWarnings("removal") private boolean advancementIsHiddenInChat(Advancement advancement, World world) { // don't send messages for advancements related to recipes String key = advancement.getKey().getKey(); if (key.contains("recipe/") || key.contains("recipes/")) return true; // ensure advancements should be announced in the world Boolean isGamerule = GAMERULE_CLASS_AVAILABLE // This class was added in 1.13 ? world.getGameRuleValue((GameRule<Boolean>) GAMERULE) // 1.13+ : Boolean.parseBoolean(world.getGameRuleValue((String) GAMERULE)); // <= 1.12 if (Boolean.FALSE.equals(isGamerule)) return true; // paper advancement API has its own AdvancementDisplay type from Advancement#getDisplay Object advancementDisplay = null; if (ADVANCEMENT_DISPLAY_ANNOUNCE_CHAT_METHOD == null) { try { if (ADVANCEMENT_GET_DISPLAY_METHOD == null) ADVANCEMENT_GET_DISPLAY_METHOD = Arrays.stream(advancement.getClass().getMethods()) .filter(method -> method.getName().equals("getDisplay")) .findFirst().orElse(null); advancementDisplay = ADVANCEMENT_GET_DISPLAY_METHOD.invoke(advancement); DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Successfully invoked bukkit AdvancementDisplay method"); } catch (Exception e) { DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Failed to find PlayerAdvancementDoneEvent#getDisplay method"); } } // dive into nms if paper and spigot don't have an AdvancementDisplay class if (ADVANCEMENT_DISPLAY_ANNOUNCE_CHAT_METHOD != null || advancementDisplay == null) { try { Object craftAdvancement = NMSUtil.getHandle(advancement); Optional<Object> craftAdvancementDisplayOptional = getAdvancementDisplayObject(craftAdvancement); // Both NMS and paper/spigot don't have AdvancementDisplay so that means it shouldn't be announced if (!craftAdvancementDisplayOptional.isPresent()) { return true; } Object craftAdvancementDisplay = craftAdvancementDisplayOptional.get(); if (ADVANCEMENT_DISPLAY_ANNOUNCE_CHAT_METHOD == null) { ADVANCEMENT_DISPLAY_ANNOUNCE_CHAT_METHOD = Arrays.stream(craftAdvancementDisplay.getClass().getMethods()) .filter(method -> method.getReturnType().equals(boolean.class)) .filter(method -> method.getName().equals("i")) .findFirst().orElse(null); } boolean doesAnnounceToChat = (boolean) ADVANCEMENT_DISPLAY_ANNOUNCE_CHAT_METHOD.invoke(craftAdvancementDisplay); DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Successfully invoked NMS announce in chat"); return !doesAnnounceToChat; } catch (Exception e) { DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Failed to get NMS announceChat value: " + e); } } // in some versions between 1.17.x and 1.18.x, bukkit api doesn't include AdvancementDisplay but paper api does if (advancementDisplay != null && !advancementDisplay.getClass().getSimpleName().equals("PaperAdvancementDisplay") && advancementDisplay instanceof org.bukkit.advancement.AdvancementDisplay) { return !((org.bukkit.advancement.AdvancementDisplay) advancementDisplay).shouldAnnounceChat(); } else if (advancementDisplay instanceof io.papermc.paper.advancement.AdvancementDisplay) { return !((io.papermc.paper.advancement.AdvancementDisplay) advancementDisplay).doesAnnounceToChat(); } else { try { Object craftAdvancement = NMSUtil.getHandle(advancement); assert craftAdvancement != null; Optional<Object> craftAdvancementDisplayOptional = getAdvancementDisplayObject(craftAdvancement); DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Successfully invoked nms AdvancementDisplay method"); return !craftAdvancementDisplayOptional.isPresent(); } catch (Exception e) { DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Failed to check if advancement should be displayed: " + e); } } return false; } private static final Map<NamespacedKey, String> ADVANCEMENT_TITLE_CACHE = new ConcurrentHashMap<>(); public static String getTitle(Advancement advancement) { return ADVANCEMENT_TITLE_CACHE.computeIfAbsent(advancement.getKey(), v -> { try { Object handle = NMSUtil.getHandle(advancement); assert handle != null; Optional<Object> advancementDisplayOptional = getAdvancementDisplayObject(handle); if (!advancementDisplayOptional.isPresent()) throw new RuntimeException("Advancement doesn't have display properties"); Object advancementDisplay = advancementDisplayOptional.get(); try { Field advancementMessageField = advancementDisplay.getClass().getDeclaredField("a"); advancementMessageField.setAccessible(true); Object advancementMessage = advancementMessageField.get(advancementDisplay); Object advancementTitle = advancementMessage.getClass().getMethod("getString").invoke(advancementMessage); DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Successfully retrieved advancement title from getString"); return (String) advancementTitle; } catch (Exception e) { DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Failed to get title of advancement using getString, trying JSON method"); } Field titleComponentField = Arrays.stream(advancementDisplay.getClass().getDeclaredFields()) .filter(field -> { String simpleFieldName = field.getType().getSimpleName(); return simpleFieldName.equals("IChatBaseComponent") || simpleFieldName.equals("IChatMutableComponent") || simpleFieldName.equals("Component"); }) .findFirst().orElseThrow(() -> new RuntimeException("Failed to find advancement display properties field")); titleComponentField.setAccessible(true); Object titleChatBaseComponent = titleComponentField.get(advancementDisplay); Method method_getText = null; try { method_getText = titleChatBaseComponent.getClass().getMethod("getText"); } catch (Exception ignored) {} if (method_getText == null) { try { method_getText = titleChatBaseComponent.getClass().getMethod("getString"); } catch (Exception ignored) {} } if (method_getText != null) { String title = (String) method_getText.invoke(titleChatBaseComponent); DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Successfully retrieved advancement title from component"); if (StringUtils.isNotBlank(title)) return title; } Class<?> chatSerializerClass = Arrays.stream(titleChatBaseComponent.getClass().getDeclaredClasses()) .filter(clazz -> clazz.getSimpleName().equals("ChatSerializer")) .findFirst().orElseThrow(() -> new RuntimeException("Couldn't get component ChatSerializer class")); String componentJson = (String) chatSerializerClass.getMethod("a", titleChatBaseComponent.getClass()).invoke(null, titleChatBaseComponent); DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Successfully retrieved advancement title from json"); return MessageUtil.toLegacy(GsonComponentSerializer.gson().deserialize(componentJson)); } catch (Exception e) { DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, e, "Failed to get title of advancement " + advancement.getKey().getKey() + ": " + e.getMessage()); String rawAdvancementName = advancement.getKey().getKey(); return Arrays.stream(rawAdvancementName.substring(rawAdvancementName.lastIndexOf("/") + 1).toLowerCase().split("_")) .map(s -> s.substring(0, 1).toUpperCase() + s.substring(1)) .collect(Collectors.joining(" ")); } }); } private static Method method_getAdvancementFromHolder = null; private static Method method_getAdvancementDisplay = null; private static Optional<Object> getAdvancementDisplayObject(Object handle) throws IllegalAccessException, InvocationTargetException { if (handle.getClass().getSimpleName().equals("AdvancementHolder")) { if (method_getAdvancementFromHolder == null) { method_getAdvancementFromHolder = Arrays.stream(handle.getClass().getMethods()) .filter(method -> method.getReturnType().getName().equals("net.minecraft.advancements.Advancement")) .filter(method -> method.getParameterCount() == 0) .findFirst().orElseThrow(() -> new RuntimeException("Failed to find Advancement from AdvancementHolder")); } if (method_getAdvancementFromHolder != null) { Object holder = method_getAdvancementFromHolder.invoke(handle); if (method_getAdvancementDisplay == null) { method_getAdvancementDisplay = Arrays.stream(holder.getClass().getMethods()) .filter(method -> method.getReturnType().getSimpleName().equals("Optional")) .filter(method -> { String displayInfoReturnName = method.getGenericReturnType().getTypeName(); return displayInfoReturnName.contains("AdvancementDisplay") || displayInfoReturnName.contains("DisplayInfo"); }) .findFirst().orElseThrow(() -> new RuntimeException("Failed to find AdvancementDisplay getter for advancement handle")); } @SuppressWarnings("unchecked") Optional<Object> optionalAdvancementDisplay = (Optional<Object>) method_getAdvancementDisplay.invoke(holder); return optionalAdvancementDisplay; } } else { if (method_getAdvancementDisplay == null) { method_getAdvancementDisplay = Arrays.stream(handle.getClass().getMethods()) .filter(method -> { String simpleReturnName = method.getReturnType().getSimpleName(); return simpleReturnName.equals("AdvancementDisplay") || simpleReturnName.equals("DisplayInfo"); }) .filter(method -> method.getParameterCount() == 0) .findFirst().orElseThrow(() -> new RuntimeException("Failed to find AdvancementDisplay getter for advancement handle")); } return Optional.ofNullable(method_getAdvancementDisplay.invoke(handle)); } return Optional.empty(); } }
412
0.90233
1
0.90233
game-dev
MEDIA
0.701229
game-dev
0.967645
1
0.967645
TTTReborn/tttreborn
2,371
code/ui/visual-programming/nodes/PercentageSelectionNode.cs
using System.Collections.Generic; using System.Text.Json; using TTTReborn.VisualProgramming; namespace TTTReborn.UI.VisualProgramming { [Spawnable] [Node("percentage_selection"), HideInEditor] public class PercentageSelectionNode : Node { public List<float> PercentList { get; set; } = new(); public PercentageSelectionNode() : base(new PercentageSelectionStackNode()) { SetTitle("PercentageSelection Node"); AddSetting<NodePercentSetting>(); AddSetting<NodePercentSetting>().ToggleInput(false); // TODO add a way to add new entries via GUI } internal void OnChange() { PercentList.Clear(); foreach (NodeSetting nodeSetting in NodeSettings) { NodePercentSetting nodePercentSetting = nodeSetting as NodePercentSetting; float percent = float.Parse(nodePercentSetting.PercentEntry.Text); PercentList.Add(percent); } } public override void Prepare() { (StackNode as PercentageSelectionStackNode).PercentList = PercentList; base.Prepare(); } public override Dictionary<string, object> GetJsonData() { Dictionary<string, object> dict = base.GetJsonData(); dict.Add("PercentList", PercentList); return dict; } public override void LoadFromJsonData(Dictionary<string, object> jsonData) { jsonData.TryGetValue("PercentList", out object percentList); if (percentList != null) { PercentList = JsonSerializer.Deserialize<List<float>>((JsonElement) percentList); if (NodeSettings.Count < PercentList.Count) { for (int i = 0; i < PercentList.Count - NodeSettings.Count; i++) { AddSetting<NodePercentSetting>().ToggleInput(false); } } for (int i = 0; i < NodeSettings.Count; i++) { (NodeSettings[i] as NodePercentSetting).PercentEntry.Text = PercentList.Count > i ? PercentList[i].ToString() : ""; } } base.LoadFromJsonData(jsonData); } } }
412
0.806121
1
0.806121
game-dev
MEDIA
0.347769
game-dev
0.899602
1
0.899602
Aussiemon/Darktide-Source-Code
2,502
dialogues/generated/mission_vo_dm_rise_veteran_male_a.lua
-- chunkname: @dialogues/generated/mission_vo_dm_rise_veteran_male_a.lua local mission_vo_dm_rise_veteran_male_a = { mission_rise_first_objective_response = { randomize_indexes_n = 0, sound_events_n = 10, sound_events = { "loc_veteran_male_a__guidance_starting_area_01", "loc_veteran_male_a__guidance_starting_area_02", "loc_veteran_male_a__guidance_starting_area_03", "loc_veteran_male_a__guidance_starting_area_04", "loc_veteran_male_a__guidance_starting_area_05", "loc_veteran_male_a__guidance_starting_area_06", "loc_veteran_male_a__guidance_starting_area_07", "loc_veteran_male_a__guidance_starting_area_08", "loc_veteran_male_a__guidance_starting_area_09", "loc_veteran_male_a__guidance_starting_area_10", }, sound_events_duration = { 0.989729, 1.379813, 1.616938, 2.092104, 1.403833, 1.059667, 1.590104, 1.172583, 2.136979, 1.585292, }, sound_event_weights = { 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, }, randomize_indexes = {}, }, mission_rise_keep_coming_b = { randomize_indexes_n = 0, sound_events_n = 4, sound_events = { "loc_veteran_male_a__event_survive_almost_done_01", "loc_veteran_male_a__event_survive_almost_done_02", "loc_veteran_male_a__event_survive_almost_done_03", "loc_veteran_male_a__event_survive_almost_done_04", }, sound_events_duration = { 1.258396, 2.39925, 0.9765, 3.218917, }, sound_event_weights = { 0.25, 0.25, 0.25, 0.25, }, randomize_indexes = {}, }, mission_rise_start_b_sergeant_branch = { randomize_indexes_n = 0, sound_events_n = 3, sound_events = { "loc_veteran_male_a__region_habculum_01", "loc_veteran_male_a__region_habculum_02", "loc_veteran_male_a__region_habculum_03", }, sound_events_duration = { 5.870667, 4.34875, 4.6865, }, sound_event_weights = { 0.3333333, 0.3333333, 0.3333333, }, randomize_indexes = {}, }, mission_rise_start_b_sergeant_branch_response = { randomize_indexes_n = 0, sound_events_n = 3, sound_events = { "loc_veteran_male_a__zone_transit_01", "loc_veteran_male_a__zone_transit_02", "loc_veteran_male_a__zone_transit_03", }, sound_events_duration = { 2.078854, 2.180833, 2.962875, }, sound_event_weights = { 0.3333333, 0.3333333, 0.3333333, }, randomize_indexes = {}, }, } return settings("mission_vo_dm_rise_veteran_male_a", mission_vo_dm_rise_veteran_male_a)
412
0.624679
1
0.624679
game-dev
MEDIA
0.959255
game-dev
0.927241
1
0.927241
MochiesCode/Mochies-Unity-Shaders
13,226
Mochie/Unity/Editor/Tools/TextureChannelPackerEditor.cs
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using UnityEditor; using UnityEngine; using TextureChannel = Mochie.PoiExtensions.PoiTextureChannel; namespace Mochie { public class TextureChannelPackerEditor : EditorWindow { const string LOG_PREFIX = "<color=green>Texture Packer:</color> "; //color is hex or name static readonly Vector2 MIN_WINDOW_SIZE = new Vector2(350, 500); const int AUTO_SELECT_CEILING = 2048; const string INVERT_LABEL = "Invert"; const string PACKED_TEXTURE_LABEL = "Texture"; const string RED_TEXTURE_LABEL = "Red"; const string GREEN_TEXTURE_LABEL = "Green"; const string BLUE_TEXTURE_LABEL = "Blue"; const string ALPHA_TEXTURE_LABEL = "Alpha"; float InvertToggleWidth { get { if(_invertLabelWidth == default) _invertLabelWidth = EditorStyles.toggle.CalcSize(new GUIContent(INVERT_LABEL)).x; return _invertLabelWidth; } } // Default values string savePath = "Assets/TexturePacker"; string packedName = "packed"; string unpackedName = "unpacked"; // Version Version version = new Version(1, 2); string SubTitle { get { if(string.IsNullOrWhiteSpace(_subTitle)) _subTitle = "by Pumkin - v" + version.ToString(); return _subTitle; } } static EditorWindow Window { get { if(!_window) _window = GetWindow<TextureChannelPackerEditor>(); return _window; } } // Texture stuff static int[] SizePresets { get; } = { 128, 256, 512, 1024, 2048, 4096 }; string[] SizePresetNames { get { if(_sizeNames == null) _sizeNames = SizePresets.Select(i => i + " x " + i).ToArray(); return _sizeNames; } } Vector2Int PackSize { get; set; } = new Vector2Int(1024, 1024); Vector2Int UnpackSize { get; set; } = new Vector2Int(1024, 1024); bool packSizeIsLinked = true; bool unpackSizeIsLinked = true; bool packSizeAutoSelect = true; bool unpackSizeAutoSelect = true; bool showChannelPicker = false; TextureChannel redTexChan, blueTexChan, greenTexChan, alphaTexChan, unpackChan; Texture2D packRed, packGreen, packBlue, packAlpha, unpackSource; bool redInvert, greenInvert, blueInvert, alphaInvert, unpackInvert; string[] ChannelLabels { get; } = { "All", "Red", "Green", "Blue", "Alpha" }; bool PackerShadersExist { get { bool everythingIsAlwaysFine = true; if(!PoiExtensions.UnpackerShader) { Debug.LogWarning(LOG_PREFIX + "Unpacker shader is missing or invalid. Can't unpack textures."); everythingIsAlwaysFine = false; } if(!PoiExtensions.PackerShader) { Debug.LogWarning(LOG_PREFIX + "Packer shader is missing or invalid. Can't pack textures."); everythingIsAlwaysFine = false; } return everythingIsAlwaysFine; } } // UI enum Tab { Pack, Unpack } int selectedTab = 0; string[] TabNames { get { if(_tabNames == null) _tabNames = Enum.GetNames(typeof(Tab)); return _tabNames; } } [MenuItem("Tools/Mochie/Texture Packer")] public static void ShowWindow() { //Show existing window instance. If one doesn't exist, make one. Window.autoRepaintOnSceneChange = true; Window.minSize = MIN_WINDOW_SIZE; Window.Show(); Window.titleContent = new GUIContent("Texture Packer"); } #region Drawing GUI void OnGUI() { EditorGUILayout.LabelField("Poi Texture Packer", PoiStyles.TitleLabel); EditorGUILayout.LabelField("Provided by, and used with permission from Poiyomi"); selectedTab = GUILayout.Toolbar(selectedTab, TabNames); if(selectedTab == (int)Tab.Pack) DrawPackUI(); else DrawUnpackUI(); } void DrawPackUI() { _scroll = EditorGUILayout.BeginScrollView(_scroll); { EditorGUI.BeginChangeCheck(); { DrawTextureSelector(RED_TEXTURE_LABEL, ref packRed, ref redTexChan, ref redInvert); DrawTextureSelector(GREEN_TEXTURE_LABEL, ref packGreen, ref greenTexChan, ref greenInvert); DrawTextureSelector(BLUE_TEXTURE_LABEL, ref packBlue, ref blueTexChan, ref blueInvert); DrawTextureSelector(ALPHA_TEXTURE_LABEL, ref packAlpha, ref alphaTexChan, ref alphaInvert); } if(EditorGUI.EndChangeCheck() && packSizeAutoSelect) { // Get biggest texture size from selections and make a selection in our sizes list var tempSize = PoiHelpers.GetMaxSizeFromTextures(packRed, packGreen, packBlue, packAlpha); if(tempSize != default) PackSize = tempSize.ClosestPowerOfTwo(AUTO_SELECT_CEILING); } } EditorGUILayout.EndScrollView(); DrawShowChannelPicker(ref showChannelPicker); bool disabled = new bool[] { packRed, packGreen, packBlue, packAlpha }.Count(b => b) < 2; EditorGUI.BeginDisabledGroup(disabled); { PackSize = DrawTextureSizeSettings(PackSize, ref packedName, ref packSizeIsLinked, ref packSizeAutoSelect); if(GUILayout.Button("Pack", PoiStyles.BigButton)) DoPack(); EditorGUILayout.Space(); } EditorGUI.EndDisabledGroup(); } private void DrawShowChannelPicker(ref bool pickerValue) { EditorGUILayout.BeginHorizontal(EditorStyles.helpBox); pickerValue = EditorGUILayout.ToggleLeft("Pick source channel", pickerValue); EditorGUILayout.EndHorizontal(); } void DrawUnpackUI() { _scroll = EditorGUILayout.BeginScrollView(_scroll); { EditorGUI.BeginChangeCheck(); { DrawTextureSelector(PACKED_TEXTURE_LABEL, ref unpackSource, ref unpackChan, ref unpackInvert); } if(EditorGUI.EndChangeCheck() && unpackSizeAutoSelect) { // Get biggest texture size from selections and make a selection in our sizes list var tempSize = PoiHelpers.GetMaxSizeFromTextures(unpackSource); if(tempSize != default) UnpackSize = tempSize.ClosestPowerOfTwo(AUTO_SELECT_CEILING); } DrawShowChannelPicker(ref showChannelPicker); } EditorGUILayout.EndScrollView(); EditorGUI.BeginDisabledGroup(!unpackSource); { UnpackSize = DrawTextureSizeSettings(UnpackSize, ref unpackedName, ref unpackSizeIsLinked, ref unpackSizeAutoSelect); if(GUILayout.Button("Unpack", PoiStyles.BigButton)) DoUnpack(unpackChan); } EditorGUI.EndDisabledGroup(); EditorGUILayout.Space(); } #endregion #region Packing and Unpacking void DoPack() { if(!PackerShadersExist) return; Texture2D red = packRed; Texture2D green = packGreen; Texture2D blue = packBlue; Texture2D alpha = packAlpha; if(showChannelPicker) { red = packRed.GetChannelAsTexture(redTexChan, unpackInvert); green = packGreen.GetChannelAsTexture(greenTexChan, unpackInvert); blue = packBlue.GetChannelAsTexture(blueTexChan, unpackInvert); alpha = packAlpha.GetChannelAsTexture(alphaTexChan, unpackInvert); } Texture2D packResult = PoiHelpers.PackTextures(PackSize, red, green, blue, alpha, redInvert, greenInvert, blueInvert, alphaInvert); if(packResult) { string path = $"{savePath}/Packed/{packedName}.png"; packResult.SaveTextureAsset(path, true); Debug.Log(LOG_PREFIX + "Finished packing texture at " + path); PoiHelpers.PingAssetAtPath(path); } } void DoUnpack(TextureChannel singleChannel = TextureChannel.RGBA) { if(!PackerShadersExist) return; var channelTextures = new Dictionary<string, Texture2D>(); if(singleChannel == TextureChannel.RGBA) channelTextures = PoiHelpers.UnpackTextureToChannels(unpackSource, unpackInvert, UnpackSize); else channelTextures[singleChannel.ToString().ToLower()] = unpackSource.GetChannelAsTexture(singleChannel, unpackInvert, UnpackSize); string pingPath = null; pingPath = SaveTextures(channelTextures, pingPath); Debug.Log(LOG_PREFIX + "Finished unpacking texture at " + pingPath); PoiHelpers.PingAssetAtPath(pingPath); } #endregion #region Helpers string SaveTextures(Dictionary<string, Texture2D> output, string pingPath) { try { AssetDatabase.StartAssetEditing(); foreach(var kv in output) { if(string.IsNullOrWhiteSpace(pingPath)) pingPath = $"{savePath}/Unpacked/{unpackedName}_{kv.Key}.png"; kv.Value?.SaveTextureAsset($"{savePath}/Unpacked/{unpackedName}_{kv.Key}.png", true); } } catch { } finally { AssetDatabase.StopAssetEditing(); } return pingPath; } void DrawTextureSelector(string label, ref Texture2D tex) { EditorGUILayout.BeginVertical(EditorStyles.helpBox); { tex = EditorGUILayout.ObjectField(label, tex, typeof(Texture2D), true, GUILayout.ExpandHeight(true)) as Texture2D; } EditorGUILayout.EndHorizontal(); } void DrawTextureSelector(string label, ref Texture2D tex, ref TextureChannel selectedChannel, ref bool invert) { EditorGUILayout.BeginVertical(EditorStyles.helpBox); { EditorGUILayout.BeginHorizontal(); { EditorGUILayout.BeginVertical(); { var labelContent = new GUIContent(label); var size = EditorStyles.boldLabel.CalcSize(labelContent); EditorGUILayout.LabelField(labelContent, EditorStyles.boldLabel, GUILayout.MaxWidth(size.x)); GUILayout.Space(15 * EditorGUIUtility.pixelsPerPoint); GUILayout.FlexibleSpace(); invert = EditorGUILayout.ToggleLeft(INVERT_LABEL, invert, GUILayout.MaxWidth(InvertToggleWidth)); } EditorGUILayout.EndVertical(); tex = EditorGUILayout.ObjectField(GUIContent.none, tex, typeof(Texture2D), true, GUILayout.ExpandHeight(true)) as Texture2D; } EditorGUILayout.EndHorizontal(); if(showChannelPicker) { EditorGUI.BeginDisabledGroup(!tex); selectedChannel = PoiHelpers.DrawChannelSelector(selectedChannel, ChannelLabels); EditorGUI.EndDisabledGroup(); } } EditorGUILayout.EndVertical(); } Vector2Int DrawTextureSizeSettings(Vector2Int size, ref string fileName, ref bool sizeIsLinked, ref bool sizeAutoSelect) { EditorGUILayout.BeginVertical(EditorStyles.helpBox); { fileName = EditorGUILayout.TextField("File name", fileName); EditorGUILayout.Space(); size = PoiHelpers.DrawResolutionPicker(size, ref sizeIsLinked, ref sizeAutoSelect, SizePresets, SizePresetNames); } EditorGUILayout.EndVertical(); return size; } #endregion string[] _tabNames; string[] _sizeNames; static EditorWindow _window; string _subTitle; Vector2 _scroll; float _invertLabelWidth; } }
412
0.938086
1
0.938086
game-dev
MEDIA
0.799512
game-dev
0.941596
1
0.941596
Stephane-D/SGDK
15,243
sample/game/platformer/src/player.c
#include "player.h" #include "global.h" #include "map.h" #include "resources.h" struct pBody playerBody; void checkCollisions(); void updateAnimations(); const s16 coyoteTime = 10; s16 currentCoyoteTime; const s16 jumpBufferTime = 10; s16 currentJumpBufferTime; bool collidingAgainstStair; bool runningAnim; u16 dyingSteps; const u16 dieDelay = 10; const u16 oneWayPlatformErrorCorrection = 5; s16 stairLeftEdge; const u16 stairPositionOffset = 4; void playerInit() { //Create the sprite and palette for the player playerBody.sprite = SPR_addSprite(&player_sprite, levelStartPos.x, levelStartPos.y, TILE_ATTR(PLAYER_PALETTE, FALSE, FALSE, FALSE)); PAL_setPalette(PLAYER_PALETTE, player_sprite.palette->data, DMA); //Set the global position of the player, the local position will be updated once we are in the main loop playerBody.globalPosition = levelStartPos; //We set collider size of the player playerBody.aabb = newAABB(4, 20, 4, 24); //This collider is thinner because if the width is >=16 it could interfere with the lateral walls playerBody.climbingStairAABB = newAABB(8, 20, playerBody.aabb.min.y, playerBody.aabb.max.y); //Calculate where's the center point of the player playerBody.centerOffset.x = ((playerBody.aabb.min.x + playerBody.aabb.max.x) >> 1); playerBody.centerOffset.y = ((playerBody.aabb.min.y + playerBody.aabb.max.y) >> 1); //Default movement values playerBody.speed = 2; playerBody.climbingSpeed = 1; playerBody.maxFallSpeed = 6; playerBody.jumpSpeed = 7; playerBody.facingDirection = 1; playerBody.acceleration = FIX16(.25); playerBody.deceleration = FIX16(.2); //Setup the jump SFX with an index between 64 and 255 XGM_setPCM(64, jump, sizeof(jump)); } void playerInputChanged() { u16 joy = input.joy; u16 state = input.state; u16 changed = input.changed; //We only read data from the joypad 1 if (joy == JOY_1) { //Update x velocity if (state & BUTTON_RIGHT) { playerBody.input.x = 1; }else if (state & BUTTON_LEFT) { playerBody.input.x = -1; }else if ((changed & BUTTON_RIGHT) | (changed & BUTTON_LEFT)) { playerBody.input.x = 0; } //Jump button via jumpbuffer //Also used to stop climbing the stairs if (changed & (BUTTON_A | BUTTON_B | BUTTON_C)) { if (state & (BUTTON_A | BUTTON_B | BUTTON_C)) { if (playerBody.climbingStair) { playerBody.climbingStair = FALSE; }else { currentJumpBufferTime = jumpBufferTime; } }else if (playerBody.jumping && playerBody.velocity.fixY < 0) { //If the button is released we remove half of the velocity playerBody.velocity.fixY = F16_mul(playerBody.velocity.fixY, FIX16(.5)); } } //Down and up buttons are only used when it is climbing stair //NOTE: Up direction is -1 and down direction is 1, this is because the Mega Drive draws the screen from top to bottom if (changed & BUTTON_DOWN) { if (state & BUTTON_DOWN) { playerBody.input.y = 1; if (playerBody.climbingStair) { playerBody.velocity.fixY = FIX16(playerBody.climbingSpeed); }else if (playerBody.onStair) { playerBody.velocity.fixY = FIX16(playerBody.climbingSpeed); playerBody.climbingStair = TRUE; } }else { playerBody.input.y = 0; if (playerBody.climbingStair) { playerBody.velocity.fixY = 0; } } } if (changed & BUTTON_UP) { if (state & BUTTON_UP) { playerBody.input.y = -1; if (collidingAgainstStair && !playerBody.onStair) { playerBody.climbingStair = TRUE; playerBody.velocity.fixY = FIX16(-playerBody.climbingSpeed); } }else { playerBody.input.y = 0; if (playerBody.climbingStair) { playerBody.velocity.fixY = 0; } } } } } void updatePlayer() { //Check if the player wants to climb a stair if(collidingAgainstStair && ((playerBody.onStair && playerBody.input.y > 0) || (!playerBody.onStair && playerBody.input.y < 0))){ playerBody.climbingStair = TRUE; playerBody.velocity.fixY = FIX16(playerBody.climbingSpeed * playerBody.input.y); } //Check if player wants to jump by looking the coyote time and jump buffer if (currentCoyoteTime > 0 && currentJumpBufferTime > 0) { playerBody.jumping = TRUE; //Play the SFX with the index 64 (jump sfx) with the highest priority XGM_startPlayPCM(64, 15, SOUND_PCM_CH1); playerBody.velocity.fixY = FIX16(-playerBody.jumpSpeed); currentCoyoteTime = 0; currentJumpBufferTime = 0; } //The ground hasn't been checked yet so we only decrease the jump buffer time for now currentJumpBufferTime = clamp((currentJumpBufferTime - 1), 0, jumpBufferTime); //Clamp to avoid underflowing, it is unlikely to happen but can happen //If the player is climbing a stair, it only needs to go upward, if not, we apply horizontal movement if (playerBody.climbingStair) { playerBody.velocity.x = playerBody.velocity.fixX = 0; playerBody.globalPosition.x = stairLeftEdge - stairPositionOffset; }else { if (playerBody.input.x > 0) { if (playerBody.velocity.x != playerBody.speed) playerBody.velocity.fixX += playerBody.acceleration; }else if (playerBody.input.x < 0) { if (playerBody.velocity.x != -playerBody.speed) playerBody.velocity.fixX -= playerBody.acceleration; }else if (playerBody.onGround) { if (playerBody.velocity.x > 0) playerBody.velocity.fixX -= playerBody.deceleration; else if (playerBody.velocity.x < 0) playerBody.velocity.fixX += playerBody.deceleration; else playerBody.velocity.fixX = 0; } playerBody.velocity.x = clamp(F16_toInt(playerBody.velocity.fixX), -playerBody.speed, playerBody.speed); } //Apply gravity with a terminal velocity if (!playerBody.onGround && !playerBody.climbingStair) { if (F16_toInt(playerBody.velocity.fixY) <= playerBody.maxFallSpeed) { playerBody.velocity.fixY = playerBody.velocity.fixY + gravityScale; }else { playerBody.velocity.fixY = FIX16(playerBody.maxFallSpeed); } } //Once all the input-related have been calculated, we apply the velocities to the global positions playerBody.globalPosition.x += playerBody.velocity.x; playerBody.globalPosition.y += F16_toInt(playerBody.velocity.fixY); //Now we can check for collisions and correct those positions checkCollisions(); //Now that the collisions have been checked, we know if the player is on a stair or not if (!collidingAgainstStair && playerBody.climbingStair) { playerBody.climbingStair = FALSE; playerBody.input.y = 0; } //Once the positions are correct, we position the player taking into account the camera position playerBody.position.x = playerBody.globalPosition.x - cameraPosition.x; playerBody.position.y = playerBody.globalPosition.y - cameraPosition.y; SPR_setPosition(playerBody.sprite, playerBody.position.x, playerBody.position.y); //Update the player animations updateAnimations(); //Reset when falling off the screen if (playerBody.falling) { dyingSteps++; if(dyingSteps > dieDelay){ SYS_hardReset(); } } } void updateAnimations() { //Sprite flip depending on the horizontal input if (playerBody.input.x > 0) { SPR_setHFlip(playerBody.sprite, TRUE); playerBody.facingDirection = 1; }else if (playerBody.input.x < 0) { SPR_setHFlip(playerBody.sprite, FALSE); playerBody.facingDirection = -1; } //If the player is on ground and not climbing the stair it can be idle or running if (playerBody.velocity.fixY == 0 && !playerBody.climbingStair) { if (playerBody.velocity.x != 0 && runningAnim == FALSE && playerBody.onGround) { SPR_setAnim(playerBody.sprite, 1); runningAnim = TRUE; }else if (playerBody.velocity.x == 0 && playerBody.onGround) { SPR_setAnim(playerBody.sprite, 0); runningAnim = FALSE; } } //Climb animation if (playerBody.climbingStair) { SPR_setAnim(playerBody.sprite, 2); } } void checkCollisions() { //As we now have to check for collisions, we will later check if it is true or false, but for now it is false collidingAgainstStair = FALSE; //Create level limits AABB levelLimits = roomSize; //Easy access to the bounds in global pos if (playerBody.climbingStair) { playerBounds = newAABB( playerBody.globalPosition.x + playerBody.climbingStairAABB.min.x, playerBody.globalPosition.x + playerBody.climbingStairAABB.max.x, playerBody.globalPosition.y + playerBody.climbingStairAABB.min.y, playerBody.globalPosition.y + playerBody.climbingStairAABB.max.y ); }else { playerBounds = newAABB( playerBody.globalPosition.x + playerBody.aabb.min.x, playerBody.globalPosition.x + playerBody.aabb.max.x, playerBody.globalPosition.y + playerBody.aabb.min.y, playerBody.globalPosition.y + playerBody.aabb.max.y ); } //We can see this variables as a way to avoid thinking that a ground tile is a wall tile //Skin width (yIntVelocity) changes depending on the vertical velocity s16 yIntVelocity = F16_toRoundedInt(playerBody.velocity.fixY); s16 playerHeadPos = playerBody.aabb.min.y - yIntVelocity + playerBody.globalPosition.y; s16 playerFeetPos = playerBody.aabb.max.y - yIntVelocity + playerBody.globalPosition.y; //Positions in tiles Vect2D_u16 minTilePos = posToTile(newVector2D_s16(playerBounds.min.x, playerBounds.min.y)); Vect2D_u16 maxTilePos = posToTile(newVector2D_s16(playerBounds.max.x, playerBounds.max.y)); //Used to limit how many tiles we have to check for collision Vect2D_u16 tileBoundDifference = newVector2D_u16(maxTilePos.x - minTilePos.x, maxTilePos.y - minTilePos.y); //First we check for horizontal collisions for (u16 i = 0; i <= tileBoundDifference.y; i++) { //Height position constant as a helper const u16 y = minTilePos.y + i; //Right position constant as a helper const u16 rx = maxTilePos.x; u16 rTileValue = getTileValue(rx, y); //After getting the tile value, we check if that is one of whom we can collide/trigger with horizontally if (rTileValue == GROUND_TILE) { AABB tileBounds = getTileBounds(rx, y); //Before taking that tile as a wall, we have to check if that is within the player hitbox, e.g. not seeing ground as a wall if (tileBounds.min.x < levelLimits.max.x && tileBounds.min.y < playerFeetPos && tileBounds.max.y > playerHeadPos) { levelLimits.max.x = tileBounds.min.x; break; } }else if (rTileValue == LADDER_TILE) { stairLeftEdge = getTileLeftEdge(rx); collidingAgainstStair = TRUE; } //Left position constant as a helper const s16 lx = minTilePos.x; u16 lTileValue = getTileValue(lx, y); //We do the same here but for the left side if (lTileValue == GROUND_TILE) { AABB tileBounds = getTileBounds(lx, y); if (tileBounds.max.x > levelLimits.min.x && tileBounds.min.y < playerFeetPos && tileBounds.max.y > playerHeadPos) { levelLimits.min.x = tileBounds.max.x; break; } }else if (lTileValue == LADDER_TILE) { stairLeftEdge = getTileLeftEdge(lx); collidingAgainstStair = TRUE; } } //After checking for horizontal positions we can modify the positions if the player is colliding if (levelLimits.min.x > playerBounds.min.x) { playerBody.globalPosition.x = levelLimits.min.x - playerBody.aabb.min.x; playerBody.velocity.x = playerBody.velocity.fixX = 0; } if (levelLimits.max.x < playerBounds.max.x) { playerBody.globalPosition.x = levelLimits.max.x - playerBody.aabb.max.x; playerBody.velocity.x = playerBody.velocity.fixX = 0; } //Then, we modify the player position so we can use them to check for vertical collisions if (playerBody.climbingStair) { playerBounds = newAABB( playerBody.globalPosition.x + playerBody.climbingStairAABB.min.x, playerBody.globalPosition.x + playerBody.climbingStairAABB.max.x, playerBody.globalPosition.y + playerBody.climbingStairAABB.min.y, playerBody.globalPosition.y + playerBody.climbingStairAABB.max.y ); }else { playerBounds = newAABB( playerBody.globalPosition.x + playerBody.aabb.min.x, playerBody.globalPosition.x + playerBody.aabb.max.x, playerBody.globalPosition.y + playerBody.aabb.min.y, playerBody.globalPosition.y + playerBody.aabb.max.y ); } //And do the same to the variables that are used to check for them minTilePos = posToTile(newVector2D_s16(playerBounds.min.x, playerBounds.min.y)); maxTilePos = posToTile(newVector2D_s16(playerBounds.max.x - 1, playerBounds.max.y)); tileBoundDifference = newVector2D_u16(maxTilePos.x - minTilePos.x, maxTilePos.y - minTilePos.y); bool onStair = FALSE; //To avoid having troubles with player snapping to ground ignoring the upward velocity, we separate top and bottom collisions depending on the velocity if (yIntVelocity >= 0) { for (u16 i = 0; i <= tileBoundDifference.x; i++) { s16 x = minTilePos.x + i; u16 y = maxTilePos.y; //This is the exact same method that we use for horizontal collisions u16 bottomTileValue = getTileValue(x, y); if (bottomTileValue == GROUND_TILE || bottomTileValue == ONE_WAY_PLATFORM_TILE) { if (getTileRightEdge(x) == levelLimits.min.x || getTileLeftEdge(x) == levelLimits.max.x) continue; u16 bottomEdgePos = getTileTopEdge(y); //The error correction is used to add some extra width pixels in case the player isn't high enough by just some of them if (bottomEdgePos < levelLimits.max.y && bottomEdgePos >= (playerFeetPos - oneWayPlatformErrorCorrection)) { levelLimits.max.y = bottomEdgePos; } }else if (bottomTileValue == LADDER_TILE) { stairLeftEdge = getTileLeftEdge(x); u16 bottomEdgePos = getTileTopEdge(y); //Only in this case we check for ladder collisions, as we need them to climb them down if (bottomEdgePos <= levelLimits.max.y && bottomEdgePos >= playerFeetPos && !playerBody.climbingStair && getTileValue(x, y - 1) != LADDER_TILE) { collidingAgainstStair = TRUE; onStair = TRUE; levelLimits.max.y = bottomEdgePos; break; } } } }else { for (u16 i = 0; i <= tileBoundDifference.x; i++) { s16 x = minTilePos.x + i; u16 y = minTilePos.y; //And the same once again u16 topTileValue = getTileValue(x, y); if (topTileValue == GROUND_TILE) { if (getTileRightEdge(x) == levelLimits.min.x || getTileLeftEdge(x) == levelLimits.max.x) continue; u16 upperEdgePos = getTileBottomEdge(y); if (upperEdgePos < levelLimits.max.y) { levelLimits.min.y = upperEdgePos; break; } }else if (topTileValue == LADDER_TILE) { stairLeftEdge = getTileLeftEdge(x); collidingAgainstStair = TRUE; } } } //Now we modify the player position and some properties if necessary if (levelLimits.min.y > playerBounds.min.y) { playerBody.globalPosition.y = levelLimits.min.y - playerBody.aabb.min.y; playerBody.velocity.fixY = 0; } if (levelLimits.max.y <= playerBounds.max.y) { if (levelLimits.max.y == 768) { playerBody.falling = TRUE; }else { playerBody.onStair = onStair; playerBody.onGround = TRUE; playerBody.climbingStair = FALSE; currentCoyoteTime = coyoteTime; playerBody.jumping = FALSE; playerBody.globalPosition.y = levelLimits.max.y - playerBody.aabb.max.y; playerBody.velocity.fixY = 0; } }else { playerBody.onStair = playerBody.onGround = FALSE; currentCoyoteTime--; } //This time we don't need to update the playerBounds as they will be updated at the beginning of the function the next frame }
412
0.801889
1
0.801889
game-dev
MEDIA
0.968691
game-dev
0.922134
1
0.922134
hpmicro/hpm_sdk
5,521
middleware/eclipse_threadx/guix/guix/common/src/gx_sprite_event_process.c
/*************************************************************************** * Copyright (c) 2024 Microsoft Corporation * * This program and the accompanying materials are made available under the * terms of the MIT License which is available at * https://opensource.org/licenses/MIT. * * SPDX-License-Identifier: MIT **************************************************************************/ /**************************************************************************/ /**************************************************************************/ /** */ /** GUIX Component */ /** */ /** Sprite Management (Sprite) */ /** */ /**************************************************************************/ #define GX_SOURCE_CODE /* Include necessary system files. */ #include "gx_api.h" #include "gx_system.h" #include "gx_widget.h" #include "gx_sprite.h" /**************************************************************************/ /* */ /* FUNCTION RELEASE */ /* */ /* _gx_sprite_event_process PORTABLE C */ /* 6.1 */ /* AUTHOR */ /* */ /* Kenneth Maxwell, Microsoft Corporation */ /* */ /* DESCRIPTION */ /* */ /* This function processes events for the sprite widget. */ /* */ /* INPUT */ /* */ /* sprite Pointer to sprite control */ /* block */ /* event_ptr Pointer to event to process */ /* */ /* OUTPUT */ /* */ /* status Completion status */ /* */ /* CALLS */ /* */ /* _gx_widget_event_process Call widget event processing */ /* _gx_sprite_start Start the sprite widget */ /* _gx_sprite_update Update the sprite widget */ /* */ /* CALLED BY */ /* */ /* GUIX Internal Code */ /* */ /* RELEASE HISTORY */ /* */ /* DATE NAME DESCRIPTION */ /* */ /* 05-19-2020 Kenneth Maxwell Initial Version 6.0 */ /* 09-30-2020 Kenneth Maxwell Modified comment(s), */ /* resulting in version 6.1 */ /* */ /**************************************************************************/ UINT _gx_sprite_event_process(GX_SPRITE *sprite, GX_EVENT *event_ptr) { /* GX_EVENT newevent; */ GX_WIDGET *widget = (GX_WIDGET *)sprite; /* Default status to success. */ UINT status = GX_SUCCESS; /* Process relative to the type of event. */ switch (event_ptr -> gx_event_type) { case GX_EVENT_SHOW: status = _gx_widget_event_process(widget, event_ptr); if (sprite -> gx_widget_style & GX_STYLE_SPRITE_AUTO) { _gx_sprite_start(sprite, sprite -> gx_sprite_current_frame); } break; case GX_EVENT_TIMER: if (event_ptr -> gx_event_payload.gx_event_timer_id == GX_SPRITE_TIMER) { _gx_sprite_update(sprite); } else { status = _gx_widget_event_process(widget, event_ptr); } break; default: /* Call the widget default processing. */ status = _gx_widget_event_process(widget, event_ptr); } /* Return completion status. */ return(status); }
412
0.588837
1
0.588837
game-dev
MEDIA
0.430304
game-dev
0.611145
1
0.611145
ousttrue/UniGLTF
1,512
Core/Scripts/Editor/ImporterMenu.cs
using System.IO; using UnityEditor; using UnityEngine; namespace UniGLTF { public static class ImporterMenu { [MenuItem(UniGLTFVersion.UNIGLTF_VERSION + "/Import", priority = 1)] public static void ImportMenu() { var path = EditorUtility.OpenFilePanel("open gltf", "", "gltf,glb,zip"); if (string.IsNullOrEmpty(path)) { return; } if (Application.isPlaying) { // // load into scene // var context = new ImporterContext(); context.Load(path); context.ShowMeshes(); Selection.activeGameObject = context.Root; } else { // // save as asset // if (path.StartsWithUnityAssetPath()) { Debug.LogWarningFormat("disallow import from folder under the Assets"); return; } var assetPath = EditorUtility.SaveFilePanel("save prefab", "Assets", Path.GetFileNameWithoutExtension(path), "prefab"); if (string.IsNullOrEmpty(path)) { return; } // import as asset gltfAssetPostprocessor.ImportAsset(path, Path.GetExtension(path).ToLower(), UnityPath.FromFullpath(assetPath)); } } } }
412
0.930473
1
0.930473
game-dev
MEDIA
0.760446
game-dev
0.953751
1
0.953751
figglewatts/LSDRevamped
1,690
LSDR/Assets/Scripts/Entities/Dream/Greyman.cs
using LSDR.Dream; using Torii.UI; using UnityEngine; namespace LSDR.Entities.Dream { public class Greyman : MonoBehaviour { public float MoveSpeed = 0.3f; public float FlashDistance = 2; public DreamSystem DreamSystem; public GameObject GreymanObject; protected bool _playerEncountered; public void Update() { if (_playerEncountered || !DreamSystem.InDream || DreamSystem.Player == null) return; Transform t = transform; t.position += t.forward * (MoveSpeed * Time.deltaTime); float distanceToPlayer = Vector3.Distance(t.position, DreamSystem.Player.transform.position); if (distanceToPlayer < FlashDistance) { _playerEncountered = true; playerEncountered(); } } private void playerEncountered() { DreamSystem.LogGraphContributionFromArea(-10, -10); DreamSystem.DisableFlashbackForDays(10); Debug.Log("encountered player"); ToriiFader.Instance.FadeIn(Color.white, duration: 0.1F, () => { Debug.Log("Setting grey man to inactive"); GreymanObject.SetActive(false); ToriiFader.Instance.FadeOut(Color.white, duration: 3F, () => { Debug.Log("Finished fading out, destroying if not null"); if (gameObject != null) { Debug.Log("destroying"); Destroy(gameObject); } }); }, forced: false); } } }
412
0.681581
1
0.681581
game-dev
MEDIA
0.978467
game-dev
0.961822
1
0.961822
rmusser01/tldw_chatbook
7,067
tldw_chatbook/Utils/Splash_Screens/gaming/game_of_life.py
"""GameOfLife splash screen effect.""" from rich.style import Style import random import time from typing import Optional, Any, List, Tuple from ..base_effect import BaseEffect, register_effect @register_effect("game_of_life") class GameOfLifeEffect(BaseEffect): """Simulates Conway's Game of Life.""" def __init__( self, parent_widget: Any, title: str = "Evolving Systems...", width: int = 40, # Grid width for GoL (actual output width might be larger for title) height: int = 20, # Grid height for GoL cell_alive_char: str = "█", cell_dead_char: str = " ", alive_style: str = "bold green", dead_style: str = "black", # Effectively background initial_pattern: str = "random", # "random", or specific pattern names like "glider" update_interval: float = 0.2, # How often GoL updates, distinct from animation_speed title_style: str = "bold white", display_width: int = 80, # Total width for splash screen display display_height: int = 24, # Total height for splash screen display **kwargs ): super().__init__(parent_widget, **kwargs) self.title = title self.grid_width = width self.grid_height = height self.cell_alive_char = cell_alive_char[0] self.cell_dead_char = cell_dead_char[0] self.alive_style = alive_style self.dead_style = dead_style # Usually background color self.initial_pattern = initial_pattern self.title_style = title_style self.display_width = display_width self.display_height = display_height self.grid = [[(random.choice([0,1]) if initial_pattern == "random" else 0) for _ in range(self.grid_width)] for _ in range(self.grid_height)] if self.initial_pattern == "glider": # A common GoL pattern if self.grid_width >= 3 and self.grid_height >= 3: self.grid[0][1] = 1 self.grid[1][2] = 1 self.grid[2][0] = 1 self.grid[2][1] = 1 self.grid[2][2] = 1 # Can add more predefined patterns here self._last_gol_update_time = time.time() self.gol_update_interval = update_interval def _count_neighbors(self, r: int, c: int) -> int: count = 0 for i in range(-1, 2): for j in range(-1, 2): if i == 0 and j == 0: continue nr, nc = r + i, c + j # Toroidal grid (wraps around) nr = nr % self.grid_height nc = nc % self.grid_width count += self.grid[nr][nc] return count def _update_grid(self): new_grid = [[0 for _ in range(self.grid_width)] for _ in range(self.grid_height)] for r in range(self.grid_height): for c in range(self.grid_width): neighbors = self._count_neighbors(r, c) if self.grid[r][c] == 1: # Alive if neighbors < 2 or neighbors > 3: new_grid[r][c] = 0 # Dies else: new_grid[r][c] = 1 # Lives else: # Dead if neighbors == 3: new_grid[r][c] = 1 # Becomes alive self.grid = new_grid def update(self) -> Optional[str]: current_time = time.time() if current_time - self._last_gol_update_time >= self.gol_update_interval: self._update_grid() self._last_gol_update_time = current_time # Render the grid and title to the full display_width/height output_display = [[' ' for _ in range(self.display_width)] for _ in range(self.display_height)] styled_output_lines = [""] * self.display_height # Center the GoL grid within the display area grid_start_r = (self.display_height - self.grid_height) // 2 grid_start_c = (self.display_width - self.grid_width) // 2 for r_grid in range(self.grid_height): for c_grid in range(self.grid_width): r_disp, c_disp = grid_start_r + r_grid, grid_start_c + c_grid if 0 <= r_disp < self.display_height and 0 <= c_disp < self.display_width: is_alive = self.grid[r_grid][c_grid] == 1 char_to_draw = self.cell_alive_char if is_alive else self.cell_dead_char style_to_use = self.alive_style if is_alive else self.dead_style # Store as (char, style) tuple for later Rich formatting output_display[r_disp][c_disp] = (char_to_draw, style_to_use) # Convert output_display (which has tuples or spaces) to styled lines for r_idx in range(self.display_height): line_segments = [] for c_idx in range(self.display_width): cell_content = output_display[r_idx][c_idx] if isinstance(cell_content, tuple): char, style = cell_content escaped_char = char.replace('[', ESCAPED_OPEN_BRACKET) line_segments.append(f"[{style}]{escaped_char}[/{style}]") else: # It's a space from initialization line_segments.append(f"[{self.dead_style}] [/{self.dead_style}]") # Styled background space styled_output_lines[r_idx] = "".join(line_segments) # Overlay title (centered, typically above or below GoL grid) if self.title: title_y = grid_start_r - 2 if grid_start_r > 1 else self.display_height -1 # Place above or at bottom title_x_start = (self.display_width - len(self.title)) // 2 if 0 <= title_y < self.display_height: # Construct title line, preserving background cells not covered by title title_line_segments = [] title_char_idx = 0 for c_idx in range(self.display_width): is_title_char_pos = title_x_start <= c_idx < title_x_start + len(self.title) if is_title_char_pos: char = self.title[title_char_idx].replace('[',r'\[') title_line_segments.append(f"[{self.title_style}]{char}[/{self.title_style}]") title_char_idx += 1 else: # Part of the line not covered by title, use existing content cell_content = output_display[title_y][c_idx] if isinstance(cell_content, tuple): char, style = cell_content escaped_char = char.replace('[', ESCAPED_OPEN_BRACKET) title_line_segments.append(f"[{style}]{escaped_char}[/{style}]") else: title_line_segments.append(f"[{self.dead_style}] [/{self.dead_style}]") styled_output_lines[title_y] = "".join(title_line_segments) return "\n".join(styled_output_lines)
412
0.864908
1
0.864908
game-dev
MEDIA
0.359076
game-dev
0.966914
1
0.966914
LopyMine/PatPat
2,289
src/main/java/net/lopymine/patpat/server/command/list/PatPatServerListSetModeCommand.java
package net.lopymine.patpat.server.command.list; import lombok.experimental.ExtensionMethod; import com.mojang.brigadier.Command; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import net.lopymine.patpat.client.config.resourcepack.ListMode; import net.lopymine.patpat.server.config.PatPatServerConfig; import net.lopymine.patpat.extension.*; import net.lopymine.patpat.utils.*; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.SharedSuggestionProvider; import net.minecraft.network.chat.*; import java.util.*; import static net.minecraft.commands.Commands.argument; import static net.minecraft.commands.Commands.literal; @ExtensionMethod({TextExtension.class, CommandExtension.class}) public class PatPatServerListSetModeCommand { private PatPatServerListSetModeCommand() { throw new IllegalStateException("Command class"); } public static LiteralArgumentBuilder<CommandSourceStack> get() { return literal("set") .requires(context -> context.hasPatPatPermission("list.set")) .then(argument("mode", StringArgumentType.word()) .suggests(((context, builder) -> SharedSuggestionProvider.suggest(List.of("WHITELIST", "BLACKLIST", "DISABLED"), builder))) .executes(PatPatServerListSetModeCommand::setListMode)); } public static int setListMode(CommandContext<CommandSourceStack> context) { String modeId = StringArgumentType.getString(context, "mode"); PatPatServerConfig config = PatPatServerConfig.getInstance(); ListMode listMode = ListMode.getById(modeId); if (config.getListMode() == listMode) { Component text = CommandText.goldenArgs( "list.set.already", listMode == null ? "null" : listMode.getText() ).finish(); context.sendMsg(text); return 0; } boolean success = listMode != null; if (success) { config.setListMode(listMode); config.saveAsync(); } String result = success ? "success" : "failed"; String key = String.format("list.set.%s", result); Object arg = success ? listMode.getText() : modeId; Component text = CommandText.goldenArgs(key, arg).finish(); context.sendMsg(text); return success ? Command.SINGLE_SUCCESS : 0; } }
412
0.866606
1
0.866606
game-dev
MEDIA
0.951467
game-dev
0.763206
1
0.763206
ikpil/Box2D.NET
5,584
src/Box2D.NET/B2BitSets.cs
// SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-FileCopyrightText: 2025 Ikpil Choi(ikpil@naver.com) // SPDX-License-Identifier: MIT using System; using System.Runtime.CompilerServices; using static Box2D.NET.B2Diagnostics; using static Box2D.NET.B2Buffers; using static Box2D.NET.B2CTZs; namespace Box2D.NET { public static class B2BitSets { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void b2SetBit(ref B2BitSet bitSet, int bitIndex) { int blockIndex = bitIndex / 64; B2_ASSERT(blockIndex < bitSet.blockCount); bitSet.bits[blockIndex] |= ((ulong)1 << (bitIndex % 64)); } public static void b2SetBitGrow(ref B2BitSet bitSet, int bitIndex) { int blockIndex = bitIndex / 64; if (blockIndex >= bitSet.blockCount) { b2GrowBitSet(ref bitSet, blockIndex + 1); } bitSet.bits[blockIndex] |= ((ulong)1 << (int)(bitIndex % 64)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void b2ClearBit(ref B2BitSet bitSet, uint bitIndex) { uint blockIndex = bitIndex / 64; if (blockIndex >= bitSet.blockCount) { return; } bitSet.bits[blockIndex] &= ~((ulong)1 << (int)(bitIndex % 64)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool b2GetBit(ref B2BitSet bitSet, int bitIndex) { int blockIndex = bitIndex / 64; if (blockIndex >= bitSet.blockCount) { return false; } return (bitSet.bits[blockIndex] & ((ulong)1 << (int)(bitIndex % 64))) != 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int b2GetBitSetBytes(ref B2BitSet bitSet) { return bitSet.blockCapacity * sizeof(ulong); } public static B2BitSet b2CreateBitSet(int bitCapacity) { B2BitSet bitSet = new B2BitSet(); b2CreateBitSet(ref bitSet, bitCapacity); return bitSet; } // fix public static void b2CreateBitSet(ref B2BitSet bitSet, int bitCapacity) { bitSet.blockCapacity = (bitCapacity + sizeof(ulong) * 8 - 1) / (sizeof(ulong) * 8); bitSet.blockCount = 0; bitSet.bits = b2Alloc<ulong>(bitSet.blockCapacity); //memset( bitSet.bits, 0, bitSet.blockCapacity * sizeof( ulong ) ); Array.Fill(bitSet.bits, 0UL); } public static void b2DestroyBitSet(ref B2BitSet bitSet) { b2Free(bitSet.bits, bitSet.blockCapacity); bitSet.blockCapacity = 0; bitSet.blockCount = 0; bitSet.bits = null; } public static void b2SetBitCountAndClear(ref B2BitSet bitSet, int bitCount) { int blockCount = (bitCount + sizeof(ulong) * 8 - 1) / (sizeof(ulong) * 8); if (bitSet.blockCapacity < blockCount) { b2DestroyBitSet(ref bitSet); int newBitCapacity = bitCount + (bitCount >> 1); // @ikpil - reuse! b2CreateBitSet(ref bitSet, newBitCapacity); } bitSet.blockCount = blockCount; //memset( bitSet->bits, 0, bitSet->blockCount * sizeof( ulong ) ); Array.Fill(bitSet.bits, 0UL, 0, bitSet.blockCount); } public static void b2GrowBitSet(ref B2BitSet bitSet, int blockCount) { if (blockCount <= bitSet.blockCount) { throw new InvalidOperationException($"blockCount must be greater than the current blockCount - request({blockCount}) blockCount({bitSet.blockCount})"); } if (blockCount > bitSet.blockCapacity) { int oldCapacity = bitSet.blockCapacity; bitSet.blockCapacity = blockCount + blockCount / 2; ulong[] newBits = b2Alloc<ulong>(bitSet.blockCapacity); //memset( newBits, 0, bitSet->blockCapacity * sizeof( ulong ) ); Array.Fill(newBits, 0UL, 0, bitSet.blockCapacity); B2_ASSERT(bitSet.bits != null); //memcpy( newBits, bitSet->bits, oldCapacity * sizeof( ulong ) ); Array.Copy(bitSet.bits, newBits, oldCapacity); b2Free(bitSet.bits, oldCapacity); bitSet.bits = newBits; } bitSet.blockCount = blockCount; } // This function is here because ctz.h is included by // this file but not in bitset.c public static int b2CountSetBits(ref B2BitSet bitSet) { int popCount = 0; int blockCount = bitSet.blockCount; for (uint i = 0; i < blockCount; ++i) { popCount += b2PopCount64(bitSet.bits[i]); } return popCount; } public static void b2InPlaceUnion(ref B2BitSet setA, ref B2BitSet setB) { if (setA.blockCount != setB.blockCount) { throw new InvalidOperationException($"cannot perform union: setA.blockCount ({setA.blockCount}) != setB.blockCount ({setB.blockCount})"); } int blockCount = setA.blockCount; for (uint i = 0; i < blockCount; ++i) { setA.bits[i] |= setB.bits[i]; } } } }
412
0.93963
1
0.93963
game-dev
MEDIA
0.501546
game-dev
0.95005
1
0.95005
rexrainbow/phaser3-rex-notes
1,686
examples/textedit/max-length.js
import phaser from 'phaser/src/phaser.js'; import BBCodeTextPlugin from '../../plugins/bbcodetext-plugin.js'; import TextEditPlugin from '../../plugins/textedit-plugin.js'; class Demo extends Phaser.Scene { constructor() { super({ key: 'examples' }) } preload() { } create() { var printText = this.add.rexBBCodeText(400, 300, 'abcde', { color: 'yellow', fontSize: '24px', fixedWidth: 200, fixedHeight: 50, backgroundColor: '#333333', halign: 'right', valign: 'center' }) .setOrigin(0.5) .setInteractive() .on('pointerdown', function () { var config = { maxLength: 10, onTextChanged: function (textObject, text) { textObject.text = text; } } this.plugins.get('rexTextEdit').edit(printText, config); }, this); } update() { } } var config = { type: Phaser.AUTO, parent: 'phaser-example', width: 800, height: 600, scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, }, dom: { createContainer: true }, scene: Demo, plugins: { global: [ { key: 'BBCodeTextPlugin', plugin: BBCodeTextPlugin, start: true }, { key: 'rexTextEdit', plugin: TextEditPlugin, start: true } ] } }; var game = new Phaser.Game(config);
412
0.771132
1
0.771132
game-dev
MEDIA
0.671201
game-dev
0.889839
1
0.889839
CyberdyneCC/Thermos
1,362
src/main/java/org/bukkit/craftbukkit/entity/CraftCreature.java
package org.bukkit.craftbukkit.entity; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLivingBase; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Creature; import org.bukkit.entity.LivingEntity; public class CraftCreature extends CraftLivingEntity implements Creature { public CraftCreature(CraftServer server, EntityCreature entity) { super(server, entity); } public void setTarget(LivingEntity target) { EntityCreature entity = getHandle(); if (target == null) { entity.entityToAttack = null; } else if (target instanceof CraftLivingEntity) { entity.entityToAttack = ((CraftLivingEntity) target).getHandle(); entity.pathToEntity = entity.worldObj.getPathEntityToEntity(entity, entity.entityToAttack, 16.0F, true, false, false, true); } } public CraftLivingEntity getTarget() { if (getHandle().entityToAttack == null) return null; if (!(getHandle().entityToAttack instanceof EntityLivingBase)) return null; return (CraftLivingEntity) getHandle().entityToAttack.getBukkitEntity(); } @Override public EntityCreature getHandle() { return (EntityCreature) entity; } @Override public String toString() { return this.entityName; // Cauldron } }
412
0.719401
1
0.719401
game-dev
MEDIA
0.981066
game-dev
0.737966
1
0.737966
Minecraft-AMS/Carpet-AMS-Addition
2,662
src/main/java/club/mcams/carpet/mixin/rule/maxPlayerInteractionRange/ServerPlayNetworkHandlerMixin.java
/* * This file is part of the Carpet AMS Addition project, licensed under the * GNU Lesser General Public License v3.0 * * Copyright (C) 2023 A Minecraft Server and contributors * * Carpet AMS Addition 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. * * Carpet AMS Addition 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 Carpet AMS Addition. If not, see <https://www.gnu.org/licenses/>. */ package club.mcams.carpet.mixin.rule.maxPlayerInteractionRange; import com.llamalad7.mixinextras.injector.ModifyExpressionValue; import top.byteeeee.annotationtoolbox.annotation.GameVersion; import club.mcams.carpet.AmsServerSettings; import club.mcams.carpet.helpers.rule.maxPlayerInteractionDistance_maxClientInteractionReachDistance.MaxInteractionDistanceMathHelper; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayNetworkHandler; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.*; import org.spongepowered.asm.mixin.Mixin; @GameVersion(version = "Minecraft < 1.20.5") @Mixin(value = ServerPlayNetworkHandler.class, priority = 168) public abstract class ServerPlayNetworkHandlerMixin { @Shadow public ServerPlayerEntity player; @ModifyExpressionValue(method = "onPlayerInteractBlock", at = @At(value = "CONSTANT", args = "doubleValue=64.0D")) private double onPlayerInteractBlock1(double constant) { if (AmsServerSettings.maxPlayerBlockInteractionRange != -1.0D) { return MaxInteractionDistanceMathHelper.getMaxSquaredReachDistance(AmsServerSettings.maxPlayerBlockInteractionRange); } else { return constant; } } @GameVersion(version = "Minecraft < 1.19") @ModifyExpressionValue(method = "onPlayerInteractEntity", at = @At(value = "CONSTANT", args = "doubleValue=36.0D")) private double onPlayerInteractEntity(double constant) { if (AmsServerSettings.maxPlayerEntityInteractionRange != -1.0D) { return MaxInteractionDistanceMathHelper.getMaxSquaredReachDistance(AmsServerSettings.maxPlayerEntityInteractionRange); } else { return constant; } } }
412
0.756573
1
0.756573
game-dev
MEDIA
0.860923
game-dev
0.840541
1
0.840541
Revolutionary-Games/Thrive
7,032
src/engine/DebugOverlays.EntityLabel.cs
using System.Collections.Generic; using System.Linq; using Arch.Core; using Arch.Core.Extensions; using Components; using Godot; /// <summary> /// Partial class: Entity label /// </summary> public partial class DebugOverlays { private readonly Dictionary<Entity, Label> entityLabels = new(); private readonly HashSet<Entity> seenEntities = new(); #pragma warning disable CA2213 [Export] private LabelSettings entityLabelSmallFont = null!; [Export] private LabelSettings entityLabelDefaultFont = null!; [Export] private LabelSettings entityDeadFont = null!; [Export] private LabelSettings entityBindingFont = null!; [Export] private LabelSettings entityEngulfingFont = null!; [Export] private LabelSettings entityUnbindingFont = null!; private Camera3D? activeCamera; #pragma warning restore CA2213 private IWorldSimulation? labelsActiveForSimulation; private bool showEntityLabels; private bool ShowEntityLabels { get => showEntityLabels; set { showEntityLabels = value; labelsLayer.Visible = value; } } public void UpdateActiveEntities(IWorldSimulation worldSimulation) { if (!ShowEntityLabels) return; // Only one world at a time can show labels so clear as existing labels if the world changes if (worldSimulation != labelsActiveForSimulation) ClearEntityLabels(); // Detect new entities foreach (var archetype in worldSimulation.EntitySystem) { foreach (var chunk in archetype) { var count = chunk.Count; var entities = chunk.Entities; for (int i = 0; i < count; ++i) { var entity = entities[i]; // Only display positional entities if (!entity.Has<WorldPosition>()) return; seenEntities.Add(entity); if (!entityLabels.TryGetValue(entity, out _)) { // New entity seen OnEntityAdded(entity); } } } } // Delete labels for gone entities var toDelete = entityLabels.Keys.Where(k => !seenEntities.Contains(k)).ToList(); foreach (var entity in toDelete) { OnEntityRemoved(entity); } seenEntities.Clear(); } public void OnWorldDisabled(IWorldSimulation? worldSimulation) { if (labelsActiveForSimulation == worldSimulation) ClearEntityLabels(); } private bool UpdateLabelColour(Entity entity, Label label) { if (!entity.IsAlive()) { label.LabelSettings = entityDeadFont; return false; } if (entity.Has<MicrobeControl>()) { ref var control = ref entity.Get<MicrobeControl>(); switch (control.State) { case MicrobeState.Binding: { label.LabelSettings = entityBindingFont; break; } case MicrobeState.Engulf: { label.LabelSettings = entityEngulfingFont; break; } case MicrobeState.Unbinding: { label.LabelSettings = entityUnbindingFont; break; } default: { label.LabelSettings = entityLabelDefaultFont; break; } } } return true; } private void UpdateEntityLabels() { if (!IsInstanceValid(activeCamera) || activeCamera is not { Current: true }) activeCamera = GetViewport().GetCamera3D(); if (activeCamera == null) return; foreach (var pair in entityLabels) { var entity = pair.Key; var label = pair.Value; if (!UpdateLabelColour(entity, label)) { // Entity is dead can't reposition. Will be deleted the next time UpdateActiveEntities is called continue; } if (!entity.Has<WorldPosition>()) { GD.PrintErr("Entity with a debug label no longer has a position"); continue; } ref var position = ref entity.Get<WorldPosition>(); label.Position = activeCamera.UnprojectPosition(position.Position); if (label.Text.Length > 0) continue; // Update names // TODO: chunks used to have their label be $"[{entity}:{chunk.ChunkName}]" // Chunk configuration is not currently saved so the chunk name is not really if (entity.Has<SpeciesMember>()) { var species = entity.Get<SpeciesMember>().Species; label.Text = $"[{entity.Id}-{entity.Version}:{species.Genus.Left(1)}.{species.Epithet.Left(4)}]"; continue; } if (entity.Has<ReadableName>()) { // TODO: localization support? Should all labels be re-initialized on language change? // TODO: some entities would probably be fine with not displaying the entity reference before the // readable name label.Text = $"[{entity.Id}-{entity.Version}:{entity.Get<ReadableName>().Name}]"; continue; } // Fallback to just showing the raw entity reference, nothing else can be shown label.Text = $"[{entity.Id}-{entity.Version}]"; } } private void OnEntityAdded(Entity entity) { var label = new Label(); labelsLayer.AddChild(label); entityLabels.Add(entity, label); // This used to check for floating chunk, but now this just has to do with by checking a couple of components // that all chunks have at least one of. Projectile is still easy to check with the toxin damage source. if (entity.Has<ToxinDamageSource>() || entity.Has<CompoundVenter>() || entity.Has<DamageOnTouch>()) { // To reduce the labels overlapping each other label.LabelSettings = entityLabelSmallFont; } } private void OnEntityRemoved(Entity entity) { // TODO: pooling for entity labels? if (entityLabels.TryGetValue(entity, out var label)) { label.DetachAndQueueFree(); entityLabels.Remove(entity); } } private void ClearEntityLabels() { foreach (var entityLabelsKey in entityLabels.Keys.ToList()) OnEntityRemoved(entityLabelsKey); activeCamera = null; labelsActiveForSimulation = null; } }
412
0.690985
1
0.690985
game-dev
MEDIA
0.80866
game-dev
0.722799
1
0.722799
ahmetahaydemir/StandardizeBows
35,850
Assets/Scripts/Main-WithAnimatorParameters/StandardizedBowForHandBool.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(AudioSource))] public class StandardizedBowForHandBool : MonoBehaviour { #region Private Values // PRIVATE VALUES private float currentTime, lerpPercentage, startingAngleDown, startingAngleUp, currentAngleDown, currentAngleUp; private Vector3 stringStartPos, stringEndPos, stringLastPos, bowDirPull, bowDirRetract; private Vector3 firstStartUpJointRot1, firstStartUpJointRot2, firstStartUpJointRot3, firstStartDownJointRot1, firstStartDownJointRot2, firstStartDownJointRot3; private Vector3 firstEndUpJointRot1, firstEndUpJointRot2, firstEndUpJointRot3, firstEndDownJointRot1, firstEndDownJointRot2, firstEndDownJointRot3; private Vector3 firstLastUpJointRot1, firstLastUpJointRot2, firstLastUpJointRot3, firstLastDownJointRot1, firstLastDownJointRot2, firstLastDownJointRot3; private GameObject lastProjectile, stringStartObj, stringEndObj, poolHolder; private Transform stringEndObjTrans, stringStartObjTrans, poolHolderTrans; private StandardizedProjectileForHandBool lastProjectileScript; [HideInInspector] public Queue<GameObject> projectilePool; private Transform lastProjectileTransform; private Rigidbody lastProjectileRigidbody; private AudioSource audioSource; private float currentStressOnString = 0f; // ANIM PRIVATES private int pullParamHash; private float projectileDelayTimer, pullDelayTimer; // INSTANT STATE BOOLS private bool justLeftString = false, justPulledString = true, justStoppedPulling=true; // CONSTANTS private const float PI = Mathf.PI; private const float HALFPI = Mathf.PI / 2.0f; #endregion #region Public Values // PUBLIC VALUES [Header(" Bow User Related")] [Tooltip("Animator component of the bow user.")] public Animator bowUserAnim; [Tooltip("The transform that the string should stick to. Usually it is the other hand of the bow user.")] public Transform bowUserPullHand; [Tooltip("Boolean parameter of the bow user animator. When it is true, bow will start shooting process.")] public string pullParamName = "Drawing"; [Tooltip("Amount of time delay to spawn the projectile.")] public float pullStateDelay=0.4f; [Tooltip("Amount of time delay to stick string to the bowUserPullHand.")] public float projectileHoldDelay=0.2f; [Tooltip("If it is true projectile spawns in bow user pull hand, if false it spawns on string.")] public bool projectileOnHand=true; //************************** [Header(" Bow Skeleton Parts")] [Tooltip("Upper bow transform. It must be right above the center position.")] public Transform bowUpJoint1; [Tooltip("Upper bow transform. It must be above the bowUpJoint1 position.")] public Transform bowUpJoint2; [Tooltip("Upper bow transform. It must be above the bowUpJoint2 position.")] public Transform bowUpJoint3; [Tooltip("Lower bow transform. It must be right below the center position.")] public Transform bowDownJoint1; [Tooltip("Second Lower bow transform. It must be below the bowDownJoint1 position.")] public Transform bowDownJoint2; [Tooltip("Second Lower bow transform. It must be below the bowDownJoint2 position.")] public Transform bowDownJoint3; [Tooltip("The transform of the string. It MUST be rigged; meaning that it is in the center and deforms the string as a V shape when dragged.")] public Transform bowStringPoint; //*************************** public enum jointsDirection { XAxis, YAxis, ZAxis } [Header(" Bow Joints Related")] [Tooltip("Direction of rotation for joints. Set your Unity selection to Pivot/Local and look at the rotation chamber of the joint in armature. Red is X, Blue is Z, Green is Y.")] public jointsDirection joint1RotateDirectionAxis = jointsDirection.ZAxis; [Tooltip("Direction of rotation for joints. Set your Unity selection to Pivot/Local and look at the rotation chamber of the joint in armature. Red is X, Blue is Z, Green is Y.")] public jointsDirection joint2RotateDirectionAxis = jointsDirection.XAxis; [Tooltip("Direction of rotation for joints. Set your Unity selection to Pivot/Local and look at the rotation chamber of the joint in armature. Red is X, Blue is Z, Green is Y.")] public jointsDirection joint3RotateDirectionAxis = jointsDirection.XAxis; [Range(-45f, 45f), Tooltip("Angle limit for the first joints in euler angles.")] public float bendAngleLimitFirstJoints = 10f; [Range(-45f, 45f), Tooltip("Angle limit for the second joints in euler angles. Usually it should be lower than the first angle limit but try it out and find the best one that suits yours.")] public float bendAngleLimitSecondJoints = 10f; [Range(-45f, 45f), Tooltip("Angle limit for the second joints in euler angles. Usually it should be lower than the first angle limit but try it out and find the best one that suits yours.")] public float bendAngleLimitThirdJoints = 10f; [Tooltip("Inverses the bending direction of the joints.")] public bool inverseBend = false; //*************************** public enum axisDirection { XAxis, YAxis, ZAxis } [Header(" Bow String Related")] public axisDirection stringMoveDirectionAxis = axisDirection.YAxis; [Range(0.2f, 0.8f), Tooltip("The maximum string retract(pull back) amount from its starting position to end position.")] public float stringMoveAmount = 0.5f; [Range(0.5f, 3f), Tooltip("The maximum string stress time amount from its starting position to end position. How much time is required to reach max string stress.")] public float stringMoveTime = 2f; [Range(0.1f, 1f), Tooltip("The maximum string retract time amount from its starting position to end position.")] public float stringRetractTime = 0.8f; [Tooltip("Inverses the pulling direction of the string.")] public bool inversePull = false; //*************************** public enum stringStressEaseType { VerySlowStart, SlowStart, MediumStable, FastStart, VeryFastStart, SpecialDraw1, SpecialDraw2, Linear } public enum stringRetractEaseType { Elastic, Bounce } [Header(" Bow Physics")] [Tooltip("Ease type when pulling the string.")] public stringStressEaseType stringMovementChoice = stringStressEaseType.FastStart; [Tooltip("Ease type when leaving the string.")] public stringRetractEaseType stringRetractChoice = stringRetractEaseType.Elastic; [Tooltip("Maximum stress built in string. It gets bigger as you hold it and it effects the speed of projectile. ")] public float maxStringStrength = 30f; public enum accuracyProjectile { PerfectAccuracy, SlightlyOff, DecentAccuracy, Unstable } [Tooltip("How much the projectile deters from where you aim.")] public accuracyProjectile projectileAccuracy = accuracyProjectile.PerfectAccuracy; //*************************** [Header(" Projectile Related")] [Tooltip("Gameobject that is going to be fired(Arrow).")] public GameObject projectile; [Tooltip("Object pooling size for projectiles in order to avoid Instantiating in runtime which is slower. Determine the pool size depending on your needs.")] public int projectilePoolSize = 15; [Tooltip("Offset of the projectile hold position.Leave 0 if it is on the correct position.")] public Vector3 projectileHoldPosOffset; [Tooltip("World or Local offset for the projectile")] public bool isPosOffsetLocal = true; [Tooltip("Offset of the projectile hold euler angles.Leave 0 if it is on the correct rotation.")] public Vector3 projectileHoldRotOffset= new Vector3(90f, 0, 0); [Tooltip("Look at your projectile prefab. The axis that the tip of the arrow is looking is the projectileForwardAxis. THIS IS VERY IMPORTANT. If possible just make your projectile prefab to look blue arrow and set this to Z-Azis")] public axisDirection projectileForwardAxis = axisDirection.ZAxis; //*************************** [Header(" Bow Utilities")] [Range(0f, 1f)] public float soundVolume = 0.5f; public AudioClip pullSound; public AudioClip retractSound; [Tooltip("Enable this bool if you want stress on string to effect the sound.")] public bool stressEffectOnSound = false; #endregion //***************************************************************************************************************************** // Start is called before the first frame update void Start() { switch (stringMoveDirectionAxis) { case axisDirection.XAxis: if (inversePull) { bowDirPull = -bowStringPoint.right; bowDirRetract = bowStringPoint.right; break; } else { bowDirPull = bowStringPoint.right; bowDirRetract = -bowStringPoint.right; break; } case axisDirection.YAxis: if (inversePull) { bowDirPull = -bowStringPoint.up; bowDirRetract = bowStringPoint.up; break; } else { bowDirPull = bowStringPoint.up; bowDirRetract = -bowStringPoint.up; break; } case axisDirection.ZAxis: if (inversePull) { bowDirPull = -bowStringPoint.forward; bowDirRetract = bowStringPoint.forward; break; } else { bowDirPull = bowStringPoint.forward; bowDirRetract = -bowStringPoint.forward; break; } default: break; } /* I AM TRYING TO DO THIS WITHOUT SPAWNING EMPTY GAMEOBJECTS. IT IS VERY EASY FOR A STABLE-NON MOVING AND ROTATING BOW BUT ONCE THE BOW STARTS TO MOVE AND ROTATE, THE DRAW AND RETRACT MOTION IN THE STRING STARTS TO ACT WEIRD BECAUSE OF THE WAY I HANDLE EASING AND UPDATES. SPAWNING EMPTY OBJECTS IS NOT A BIG PROBLEM SINCE THEY ARE ONLY IN THE START FUNCTION BUT IT FORCES US TO CHANGE THEIR POSITION MANUALLY WHEN PLAYING WITH STRING MOVE AMOUNT IN RUNTIME. ---------------------------------------- SINCE THIS IS A COMBINATION OF MODEL NORMALS AND UNITY ENVIRONMENT, IT IS HARD TO FIND ONE SOLUTION THAT IS GOING TO WORK FOR EVERYONES BOW MODEL. I WILL DEFINITELY TRY TO FIND A BETTER WAY TO DO THIS. BUT CURRENTLY, THIS IS THE BEST SOLUTION I CAN FIND FOR THIS PROBLEM*/ stringStartPos = bowStringPoint.position; stringStartObj = new GameObject(transform.name + "StringStartPlaceHolder"); stringStartObjTrans = stringStartObj.transform; stringStartObjTrans.position = stringStartPos; stringEndPos = stringStartPos + bowDirPull * stringMoveAmount; stringEndObj = new GameObject(transform.name + "StringEndPlaceHolder"); stringEndObjTrans = stringEndObj.transform; stringEndObjTrans.position = stringEndPos; stringEndObjTrans.parent = transform; stringStartObjTrans.parent = transform; // Pool Object Holder - Quiver - Prevents Object Pooling to litter hierarchy poolHolder = new GameObject(transform.name + " Quiver"); poolHolderTrans = poolHolder.transform; // firstStartUpJointRot1 = bowUpJoint1.localEulerAngles; firstStartUpJointRot2 = bowUpJoint2.localEulerAngles; firstStartUpJointRot3 = bowUpJoint3.localEulerAngles; firstStartDownJointRot1 = bowDownJoint1.localEulerAngles; firstStartDownJointRot2 = bowDownJoint2.localEulerAngles; firstStartDownJointRot3 = bowDownJoint3.localEulerAngles; //------------------------------------------- switch (joint1RotateDirectionAxis) { case jointsDirection.XAxis: if (inverseBend) { firstEndUpJointRot1 = firstStartUpJointRot1 - Vector3.right * bendAngleLimitFirstJoints; firstEndDownJointRot1 = firstStartDownJointRot1 + Vector3.right * bendAngleLimitFirstJoints; } else { firstEndUpJointRot1 = firstStartUpJointRot1 + Vector3.right * bendAngleLimitFirstJoints; firstEndDownJointRot1 = firstStartDownJointRot1 - Vector3.right * bendAngleLimitFirstJoints; } break; case jointsDirection.YAxis: if (inverseBend) { firstEndUpJointRot1 = firstStartUpJointRot1 - Vector3.up * bendAngleLimitFirstJoints; firstEndDownJointRot1 = firstStartDownJointRot1 + Vector3.up * bendAngleLimitFirstJoints; } else { firstEndUpJointRot1 = firstStartUpJointRot1 + Vector3.up * bendAngleLimitFirstJoints; firstEndDownJointRot1 = firstStartDownJointRot1 - Vector3.up * bendAngleLimitFirstJoints; } break; case jointsDirection.ZAxis: if (inverseBend) { firstEndUpJointRot1 = firstStartUpJointRot1 - Vector3.forward * bendAngleLimitFirstJoints; firstEndDownJointRot1 = firstStartDownJointRot1 + Vector3.forward * bendAngleLimitFirstJoints; } else { firstEndUpJointRot1 = firstStartUpJointRot1 + Vector3.forward * bendAngleLimitFirstJoints; firstEndDownJointRot1 = firstStartDownJointRot1 - Vector3.forward * bendAngleLimitFirstJoints; } break; default: break; } switch (joint2RotateDirectionAxis) { case jointsDirection.XAxis: if (inverseBend) { firstEndUpJointRot2 = firstStartUpJointRot2 + Vector3.right * bendAngleLimitSecondJoints; firstEndDownJointRot2 = firstStartDownJointRot2 - Vector3.right * bendAngleLimitSecondJoints; } else { firstEndUpJointRot2 = firstStartUpJointRot2 - Vector3.right * bendAngleLimitSecondJoints; firstEndDownJointRot2 = firstStartDownJointRot2 + Vector3.right * bendAngleLimitSecondJoints; } break; case jointsDirection.YAxis: if (inverseBend) { firstEndUpJointRot2 = firstStartUpJointRot2 + Vector3.up * bendAngleLimitSecondJoints; firstEndDownJointRot2 = firstStartDownJointRot2 - Vector3.up * bendAngleLimitSecondJoints; } else { firstEndUpJointRot2 = firstStartUpJointRot2 - Vector3.up * bendAngleLimitSecondJoints; firstEndDownJointRot2 = firstStartDownJointRot2 + Vector3.up * bendAngleLimitSecondJoints; } break; case jointsDirection.ZAxis: if (inverseBend) { firstEndUpJointRot2 = firstStartUpJointRot2 + Vector3.forward * bendAngleLimitSecondJoints; firstEndDownJointRot2 = firstStartDownJointRot2 - Vector3.forward * bendAngleLimitSecondJoints; } else { firstEndUpJointRot2 = firstStartUpJointRot2 - Vector3.forward * bendAngleLimitSecondJoints; firstEndDownJointRot2 = firstStartDownJointRot2 + Vector3.forward * bendAngleLimitSecondJoints; } break; default: break; } switch (joint3RotateDirectionAxis) { case jointsDirection.XAxis: if (inverseBend) { firstEndUpJointRot3 = firstStartUpJointRot3 + Vector3.right * bendAngleLimitThirdJoints; firstEndDownJointRot3 = firstStartDownJointRot3 - Vector3.right * bendAngleLimitThirdJoints; } else { firstEndUpJointRot3 = firstStartUpJointRot3 - Vector3.right * bendAngleLimitThirdJoints; firstEndDownJointRot3 = firstStartDownJointRot3 + Vector3.right * bendAngleLimitThirdJoints; } break; case jointsDirection.YAxis: if (inverseBend) { firstEndUpJointRot3 = firstStartUpJointRot3 + Vector3.up * bendAngleLimitThirdJoints; firstEndDownJointRot3 = firstStartDownJointRot3 - Vector3.up * bendAngleLimitThirdJoints; } else { firstEndUpJointRot3 = firstStartUpJointRot3 - Vector3.up * bendAngleLimitThirdJoints; firstEndDownJointRot3 = firstStartDownJointRot3 + Vector3.up * bendAngleLimitThirdJoints; } break; case jointsDirection.ZAxis: if (inverseBend) { firstEndUpJointRot3 = firstStartUpJointRot3 + Vector3.forward * bendAngleLimitThirdJoints; firstEndDownJointRot3 = firstStartDownJointRot3 - Vector3.forward * bendAngleLimitThirdJoints; } else { firstEndUpJointRot3 = firstStartUpJointRot3 - Vector3.forward * bendAngleLimitThirdJoints; firstEndDownJointRot3 = firstStartDownJointRot3 + Vector3.forward * bendAngleLimitThirdJoints; } break; default: break; } // ProjectileObjectPool(); // SOUND INIT audioSource = GetComponent<AudioSource>(); audioSource.volume = soundVolume; audioSource.pitch = 1 + Mathf.Abs(2.5f - stringMoveTime); // ANIM INIT pullParamHash = Animator.StringToHash(pullParamName); } // Update is called once per frame void Update() { // UPDATE STATE 1 - Pulling the string if (bowUserAnim.GetBool(pullParamHash)) { // UPDATE STATE 2 - PROJECTILE SPAWN DELAY if (projectileDelayTimer>projectileHoldDelay) { if (justPulledString) { currentTime = 0; justPulledString = false; justStoppedPulling = false; ProjectileFollowString(); if (pullSound != null) { if (stressEffectOnSound) { audioSource.pitch = 1 + Mathf.Abs(2.5f - stringMoveTime); } audioSource.PlayOneShot(pullSound); } } // UPDATE STATE 3 - STRING HOLD DELAY if (pullDelayTimer>pullStateDelay) { currentTime += Time.deltaTime; if (currentTime > stringMoveTime) { currentTime = stringMoveTime; } StringPull(); RotateDownJoints(); RotateUpperJoints(); } else { pullDelayTimer += Time.deltaTime; } } else { projectileDelayTimer += Time.deltaTime; } } else { // UPDATE STATE 4 - Just released the string if (!justStoppedPulling) { currentTime = 0; stringLastPos = bowStringPoint.position; firstLastUpJointRot1 = bowUpJoint1.localEulerAngles; firstLastUpJointRot2 = bowUpJoint2.localEulerAngles; firstLastUpJointRot3 = bowUpJoint3.localEulerAngles; firstLastDownJointRot1 = bowDownJoint1.localEulerAngles; firstLastDownJointRot2 = bowDownJoint2.localEulerAngles; firstLastDownJointRot3 = bowDownJoint3.localEulerAngles; justPulledString = true; justLeftString = true; justStoppedPulling = true; ShootProjectile(currentStressOnString); if (stressEffectOnSound) { audioSource.pitch = audioSource.pitch / 2 + (currentStressOnString / maxStringStrength) * audioSource.pitch / 2; } currentStressOnString = 0; // audioSource.Stop(); if (retractSound != null) { audioSource.PlayOneShot(retractSound); } } // UPDATE STATE 5 - Released bow returning to stable form if (justLeftString) { currentTime += Time.deltaTime; if (currentTime > stringRetractTime) { justLeftString = false; } RetractString(); RotateBackJoints(); } else { // UPDATE STATE 0 - Steady state, stable form currentTime = 0; currentStressOnString = 0; projectileDelayTimer = 0; pullDelayTimer = 0; } } } #region STRING RELATED // Fire string pull method void StringPull() { // lerpPercentage = currentTime / stringMoveTime; lerpPercentage = InterpolateStringStress(lerpPercentage); bowStringPoint.position = bowUserPullHand.position; // currentStressOnString = Mathf.Lerp(0, maxStringStrength, lerpPercentage); } // Ease the string pull float InterpolateStringStress(float lerpPerc) { switch (stringMovementChoice) { default: return lerpPerc; case stringStressEaseType.Linear: return lerpPerc; case stringStressEaseType.VerySlowStart: return CubicEaseIn(lerpPerc); case stringStressEaseType.SlowStart: return QuadraticEaseIn(lerpPerc); case stringStressEaseType.MediumStable: return SineEaseIn(lerpPerc); case stringStressEaseType.FastStart: return QuadraticEaseOut(lerpPerc); case stringStressEaseType.VeryFastStart: return CubicEaseOut(lerpPerc); case stringStressEaseType.SpecialDraw1: return BounceEaseOut(lerpPerc); case stringStressEaseType.SpecialDraw2: return BounceEaseIn(lerpPerc); } } // Fire string retract method void RetractString() { lerpPercentage = currentTime / stringRetractTime; lerpPercentage = InterpolateStringRetract(lerpPercentage); bowStringPoint.position = Vector3.LerpUnclamped(stringLastPos, stringStartObjTrans.position, lerpPercentage); } // Ease the string retract float InterpolateStringRetract(float lerpPerc) { switch (stringRetractChoice) { default: return lerpPerc; case stringRetractEaseType.Elastic: return ElasticEaseOut(lerpPerc); case stringRetractEaseType.Bounce: return BounceEaseOut(lerpPerc); } } #endregion #region JOINT RELATED // Down Joint Movements void RotateUpperJoints() { lerpPercentage = currentTime / stringMoveTime; lerpPercentage = InterpolateStringStress(lerpPercentage); bowUpJoint1.localEulerAngles = Vector3.Lerp(firstStartUpJointRot1, firstEndUpJointRot1, lerpPercentage); bowUpJoint2.localEulerAngles = Vector3.Lerp(firstStartUpJointRot2, firstEndUpJointRot2, lerpPercentage); bowUpJoint3.localEulerAngles = Vector3.Lerp(firstStartUpJointRot3, firstEndUpJointRot3, lerpPercentage); } // Upper Joint Movements void RotateDownJoints() { lerpPercentage = currentTime / stringMoveTime; lerpPercentage = InterpolateStringStress(lerpPercentage); bowDownJoint1.localEulerAngles = Vector3.Lerp(firstStartDownJointRot1, firstEndDownJointRot1, lerpPercentage); bowDownJoint2.localEulerAngles = Vector3.Lerp(firstStartDownJointRot2, firstEndDownJointRot2, lerpPercentage); bowDownJoint3.localEulerAngles = Vector3.Lerp(firstStartDownJointRot3, firstEndDownJointRot3, lerpPercentage); } // Return joints to the natural state void RotateBackJoints() { lerpPercentage = currentTime / stringRetractTime; lerpPercentage = InterpolateStringRetract(lerpPercentage); bowUpJoint1.localEulerAngles = Vector3.LerpUnclamped(firstLastUpJointRot1, firstStartUpJointRot1, lerpPercentage); bowUpJoint2.localEulerAngles = Vector3.LerpUnclamped(firstLastUpJointRot2, firstStartUpJointRot2, lerpPercentage); bowUpJoint3.localEulerAngles = Vector3.LerpUnclamped(firstLastUpJointRot3, firstStartUpJointRot3, lerpPercentage); bowDownJoint1.localEulerAngles = Vector3.LerpUnclamped(firstLastDownJointRot1, firstStartDownJointRot1, lerpPercentage); bowDownJoint2.localEulerAngles = Vector3.LerpUnclamped(firstLastDownJointRot2, firstStartDownJointRot2, lerpPercentage); bowDownJoint3.localEulerAngles = Vector3.LerpUnclamped(firstLastDownJointRot3, firstStartDownJointRot3, lerpPercentage); } #endregion #region SHOOTING RELATED void ProjectileFollowString() { // If the queue is empty if (projectilePool.Count == 0) { // Increase the pool size and add an extra projectile(I would suggest you to have a large pool size to avoid this. This is here for safety) AddExtraProjectileToPool(); // Again the same procedure with normal dequeue with just avoiding GetComponent repetition lastProjectile = projectilePool.Dequeue(); lastProjectileTransform = lastProjectile.transform; //lastProjectileRigidbody = lastProjectile.GetComponent<Rigidbody>(); // DONE INSIDE THE ADD METHOD if (projectileOnHand) { lastProjectileTransform.parent = bowUserPullHand; lastProjectileTransform.position = bowUserPullHand.position + projectileHoldPosOffset; } else { lastProjectileTransform.parent = bowStringPoint; lastProjectileTransform.position = bowStringPoint.position + projectileHoldPosOffset; } lastProjectileTransform.localEulerAngles = projectileHoldRotOffset; lastProjectile.SetActive(true); } else { // Just dequeue the first lastProjectile = projectilePool.Dequeue(); lastProjectileTransform = lastProjectile.transform; lastProjectileRigidbody = lastProjectile.GetComponent<Rigidbody>(); // Try to avoid get component in runtime if (projectileOnHand) { lastProjectileTransform.parent = bowUserPullHand; if (isPosOffsetLocal) { lastProjectileTransform.localPosition = bowStringPoint.localPosition + projectileHoldPosOffset; // Local Pos offset } else { lastProjectileTransform.position = bowStringPoint.position + projectileHoldPosOffset; // World Pos offset } } else { lastProjectileTransform.parent = bowStringPoint; if (isPosOffsetLocal) { lastProjectileTransform.localPosition = bowStringPoint.localPosition + projectileHoldPosOffset; // Local Pos offset } else { lastProjectileTransform.position = bowStringPoint.position + projectileHoldPosOffset; // World Pos offset } } lastProjectileTransform.localEulerAngles = projectileHoldRotOffset; lastProjectile.SetActive(true); } } float x, y; void ShootProjectile(float currentPower) { switch (projectileAccuracy) { case accuracyProjectile.PerfectAccuracy: x = 0; y = 0; break; case accuracyProjectile.SlightlyOff: x = Random.Range(-1f, 0.5f); y = Random.Range(-1f, 1f); break; case accuracyProjectile.DecentAccuracy: x = Random.Range(-2f, 1.5f); y = Random.Range(-2f, 2f); break; case accuracyProjectile.Unstable: x = Random.Range(-3f, 2f); y = Random.Range(-3f, 3f); break; default: break; } // Axis switch for different models switch (projectileForwardAxis) { case axisDirection.XAxis: lastProjectileTransform.localEulerAngles = lastProjectileTransform.localEulerAngles + Vector3.forward * x + Vector3.up * y; lastProjectileTransform.parent = null; lastProjectileRigidbody.useGravity = true; lastProjectileRigidbody.velocity = (lastProjectileTransform.right * currentPower); break; case axisDirection.YAxis: lastProjectileTransform.localEulerAngles = lastProjectileTransform.localEulerAngles + Vector3.right * x + Vector3.forward * y; lastProjectileTransform.parent = null; lastProjectileRigidbody.useGravity = true; lastProjectileRigidbody.velocity = (lastProjectileTransform.up * currentPower); break; case axisDirection.ZAxis: lastProjectileTransform.localEulerAngles = lastProjectileTransform.localEulerAngles + Vector3.up * x + Vector3.right * y; lastProjectileTransform.parent = null; lastProjectileRigidbody.useGravity = true; lastProjectileRigidbody.velocity = (lastProjectileTransform.forward * currentPower); break; default: Debug.Log("Error on projectile axis switch!"); break; } } #endregion #region EASING FUNCTIONS /// <summary> /// Modeled after the cubic y = x^3 /// </summary> static public float CubicEaseIn(float p) { return p * p * p; } /// <summary> /// Modeled after the parabola y = x^2 /// </summary> static public float QuadraticEaseIn(float p) { return p * p; } /// <summary> /// Modeled after quarter-cycle of sine wave /// </summary> static public float SineEaseIn(float p) { return Mathf.Sin((p - 1) * HALFPI) + 1; } /// <summary> /// Modeled after the parabola y = -x^2 + 2x /// </summary> static public float QuadraticEaseOut(float p) { return -(p * (p - 2)); } /// <summary> /// Modeled after the cubic y = (x - 1)^3 + 1 /// </summary> static public float CubicEaseOut(float p) { float f = (p - 1); return f * f * f + 1; } /// <summary> /// Modeled after the piecewise circular function /// y = (1/2)(1 - Math.Sqrt(1 - 4x^2)) ; [0, 0.5) /// y = (1/2)(Math.Sqrt(-(2x - 3)*(2x - 1)) + 1) ; [0.5, 1] /// </summary> static public float CircularEaseInOut(float p) { if (p < 0.5f) { return 0.5f * (1 - Mathf.Sqrt(1 - 4 * (p * p))); } else { return 0.5f * (Mathf.Sqrt(-((2 * p) - 3) * ((2 * p) - 1)) + 1); } } /// <summary> /// </summary> static public float BounceEaseOut(float p) { if (p < 4 / 11.0f) { return (121 * p * p) / 16.0f; } else if (p < 8 / 11.0f) { return (363 / 40.0f * p * p) - (99 / 10.0f * p) + 17 / 5.0f; } else if (p < 9 / 10.0f) { return (4356 / 361.0f * p * p) - (35442 / 1805.0f * p) + 16061 / 1805.0f; } else { return (54 / 5.0f * p * p) - (513 / 25.0f * p) + 268 / 25.0f; } } /// <summary> /// </summary> static public float BounceEaseIn(float p) { return 1 - BounceEaseOut(1 - p); } /// <summary> /// </summary> static public float BounceEaseInOut(float p) { if (p < 0.5f) { return 0.5f * BounceEaseIn(p * 2); } else { return 0.5f * BounceEaseOut(p * 2 - 1) + 0.5f; } } /// <summary> /// Modeled after overshooting cubic y = 1-((1-x)^3-(1-x)*sin((1-x)*pi)) /// </summary> static public float BackEaseOut(float p) { float f = (1 - p); return 1 - (f * f * f - f * Mathf.Sin(f * PI)); } /// <summary> /// Modeled after the damped sine wave y = sin(-13pi/2*(x + 1))*Math.Pow(2, -10x) + 1 /// </summary> static public float ElasticEaseOut(float p) { return Mathf.Sin(-13 * HALFPI * (p + 1)) * Mathf.Pow(2, -10 * p) + 1; } #endregion #region PROJECTILE - OBJECT POOLING void ProjectileObjectPool() { // Object pooling process of the projectiles projectilePool = new Queue<GameObject>(); for (int i = 0; i < projectilePoolSize; i++) { lastProjectile = Instantiate<GameObject>(projectile,poolHolderTrans); lastProjectileScript = lastProjectile.GetComponent<StandardizedProjectileForHandBool>(); lastProjectileScript.bowScript = this; lastProjectileScript.quiver = poolHolderTrans; lastProjectileScript.PoolTheParticles(); lastProjectileScript.rigid = lastProjectile.GetComponent<Rigidbody>(); lastProjectile.SetActive(false); projectilePool.Enqueue(lastProjectile); } } // Add an extra projectile to the pool when needed. void AddExtraProjectileToPool() { lastProjectile = Instantiate<GameObject>(projectile,poolHolderTrans); lastProjectileScript = lastProjectile.GetComponent<StandardizedProjectileForHandBool>(); lastProjectileScript.bowScript = this; lastProjectileScript.quiver = poolHolderTrans; lastProjectileScript.PoolTheParticles(); lastProjectileScript.rigid = lastProjectile.GetComponent<Rigidbody>(); lastProjectileRigidbody = lastProjectileScript.rigid; lastProjectile.SetActive(false); projectilePool.Enqueue(lastProjectile); projectilePoolSize++; } #endregion #region EDITOR-CUSTOM INSPECTOR // Automation for the joint placement in the inspector public void FindBoneRigs() { bowUpJoint1 = transform.GetChild(0).GetChild(0); bowUpJoint2 = transform.GetChild(0).GetChild(0).GetChild(0); bowUpJoint3 = transform.GetChild(0).GetChild(0).GetChild(0).GetChild(0); bowDownJoint1 = transform.GetChild(0).GetChild(1); bowDownJoint2 = transform.GetChild(0).GetChild(1).GetChild(0); bowDownJoint3 = transform.GetChild(0).GetChild(1).GetChild(0).GetChild(0); bowStringPoint = transform.GetChild(0).GetChild(2); } #endregion }
412
0.844334
1
0.844334
game-dev
MEDIA
0.777682
game-dev,graphics-rendering
0.607981
1
0.607981
33cn/plugin
8,517
plugin/dapp/pokerbull/cmd/game.go
// Copyright Fuzamei Corp. 2018 All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cmd import ( "fmt" "os" "strconv" cmdtypes "github.com/33cn/chain33/system/dapp/commands/types" "github.com/pkg/errors" jsonrpc "github.com/33cn/chain33/rpc/jsonclient" rpctypes "github.com/33cn/chain33/rpc/types" "github.com/33cn/chain33/types" pkt "github.com/33cn/plugin/plugin/dapp/pokerbull/types" "github.com/spf13/cobra" ) // PokerBullCmd 斗牛游戏命令行 func PokerBullCmd() *cobra.Command { cmd := &cobra.Command{ Use: "pokerbull", Short: "poker bull game management", Args: cobra.MinimumNArgs(1), } cmd.AddCommand( PokerBullStartRawTxCmd(), PokerBullContinueRawTxCmd(), PokerBullQuitRawTxCmd(), PokerBullQueryResultRawTxCmd(), PokerBullPlayRawTxCmd(), ) return cmd } // PokerBullStartRawTxCmd 生成开始交易命令行 func PokerBullStartRawTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "start", Short: "Start a new round poker bull game", Run: pokerbullStart, } addPokerbullStartFlags(cmd) return cmd } func addPokerbullStartFlags(cmd *cobra.Command) { cmd.Flags().Uint64P("value", "v", 0, "value") cmd.MarkFlagRequired("value") cmd.Flags().Uint32P("playerCount", "p", 0, "player count") cmd.MarkFlagRequired("playerCount") } func pokerbullStart(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") paraName, _ := cmd.Flags().GetString("paraName") value, _ := cmd.Flags().GetUint64("value") playerCount, _ := cmd.Flags().GetUint32("playerCount") cfg, err := cmdtypes.GetChainConfig(rpcLaddr) if err != nil { fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig")) return } params := &rpctypes.CreateTxIn{ Execer: types.GetExecName(pkt.PokerBullX, paraName), ActionName: pkt.CreateStartTx, Payload: []byte(fmt.Sprintf("{\"value\":%d,\"playerNum\":%d}", int64(value)*cfg.CoinPrecision, int32(playerCount))), } var res string ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.CreateTransaction", params, &res) ctx.RunWithoutMarshal() } // PokerBullContinueRawTxCmd 生成继续游戏命令行 func PokerBullContinueRawTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "continue", Short: "Continue a new round poker bull game", Run: pokerbullContinue, } addPokerbullContinueFlags(cmd) return cmd } func addPokerbullContinueFlags(cmd *cobra.Command) { cmd.Flags().StringP("gameID", "g", "", "game ID") cmd.MarkFlagRequired("gameID") } func pokerbullContinue(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") paraName, _ := cmd.Flags().GetString("paraName") gameID, _ := cmd.Flags().GetString("gameID") params := &rpctypes.CreateTxIn{ Execer: types.GetExecName(pkt.PokerBullX, paraName), ActionName: pkt.CreateContinueTx, Payload: []byte(fmt.Sprintf("{\"gameId\":\"%s\"}", gameID)), } var res string ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.CreateTransaction", params, &res) ctx.RunWithoutMarshal() } // PokerBullQuitRawTxCmd 生成继续游戏命令行 func PokerBullQuitRawTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "quit", Short: "Quit game", Run: pokerbullQuit, } addPokerbullQuitFlags(cmd) return cmd } func addPokerbullQuitFlags(cmd *cobra.Command) { cmd.Flags().StringP("gameID", "g", "", "game ID") cmd.MarkFlagRequired("gameID") } func pokerbullQuit(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") paraName, _ := cmd.Flags().GetString("paraName") gameID, _ := cmd.Flags().GetString("gameID") params := &rpctypes.CreateTxIn{ Execer: types.GetExecName(pkt.PokerBullX, paraName), ActionName: pkt.CreateQuitTx, Payload: []byte(fmt.Sprintf("{\"gameId\":\"%s\"}", gameID)), } var res string ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.CreateTransaction", params, &res) ctx.RunWithoutMarshal() } // PokerBullPlayRawTxCmd 生成已匹配玩家游戏命令行 func PokerBullPlayRawTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "play", Short: "Play game", Run: pokerbullPlay, } addPokerbullPlayFlags(cmd) return cmd } func addPokerbullPlayFlags(cmd *cobra.Command) { cmd.Flags().StringP("gameID", "g", "", "game ID") cmd.MarkFlagRequired("gameID") cmd.Flags().Uint32P("round", "r", 0, "round") cmd.MarkFlagRequired("round") cmd.Flags().Uint64P("value", "v", 0, "value") cmd.MarkFlagRequired("value") cmd.Flags().StringArrayP("address", "a", nil, "address") cmd.MarkFlagRequired("address") } func pokerbullPlay(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") gameID, _ := cmd.Flags().GetString("gameID") round, _ := cmd.Flags().GetUint32("round") value, _ := cmd.Flags().GetUint64("value") address, _ := cmd.Flags().GetStringArray("address") paraName, _ := cmd.Flags().GetString("paraName") cfg, err := cmdtypes.GetChainConfig(rpcLaddr) if err != nil { fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig")) return } payload := &pkt.PBGamePlay{ GameId: gameID, Value: int64(value) * cfg.CoinPrecision, Round: int32(round), } payload.Address = make([]string, len(address)) copy(payload.Address, address) params := &rpctypes.CreateTxIn{ Execer: types.GetExecName(pkt.PokerBullX, paraName), ActionName: pkt.CreatePlayTx, Payload: types.MustPBToJSON(payload), } var res string ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.CreateTransaction", params, &res) ctx.RunWithoutMarshal() } // PokerBullQueryResultRawTxCmd 查询命令行 func PokerBullQueryResultRawTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "query", Short: "Query result", Run: pokerbullQuery, } addPokerbullQueryFlags(cmd) return cmd } func addPokerbullQueryFlags(cmd *cobra.Command) { cmd.Flags().StringP("gameID", "g", "", "game ID") cmd.Flags().StringP("address", "a", "", "address") cmd.Flags().StringP("index", "i", "", "index") cmd.Flags().StringP("status", "s", "", "status") cmd.Flags().StringP("gameIDs", "d", "", "gameIDs") cmd.Flags().StringP("round", "r", "", "round") } func pokerbullQuery(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") gameID, _ := cmd.Flags().GetString("gameID") address, _ := cmd.Flags().GetString("address") statusStr, _ := cmd.Flags().GetString("status") indexstr, _ := cmd.Flags().GetString("index") gameIDs, _ := cmd.Flags().GetString("gameIDs") round, _ := cmd.Flags().GetString("round") var params rpctypes.Query4Jrpc params.Execer = pkt.PokerBullX req := &pkt.QueryPBGameInfo{ GameId: gameID, Addr: address, } if indexstr != "" { index, err := strconv.ParseInt(indexstr, 10, 64) if err != nil { fmt.Println(err) cmd.Help() return } req.Index = index } if gameID != "" { if round == "" { params.FuncName = pkt.FuncNameQueryGameByID params.Payload = types.MustPBToJSON(req) var res pkt.ReplyPBGame ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res) ctx.Run() } else { params.FuncName = pkt.FuncNameQueryGameByRound roundInt, err := strconv.ParseInt(round, 10, 32) if err != nil { fmt.Println(err) return } req := &pkt.QueryPBGameByRound{ GameId: gameID, Round: int32(roundInt), } params.Payload = types.MustPBToJSON(req) var res pkt.ReplyPBGameByRound ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res) ctx.Run() } } else if address != "" { params.FuncName = pkt.FuncNameQueryGameByAddr params.Payload = types.MustPBToJSON(req) var res pkt.PBGameRecords ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res) ctx.Run() } else if statusStr != "" { status, err := strconv.ParseInt(statusStr, 10, 32) if err != nil { fmt.Println(err) cmd.Help() return } req.Status = int32(status) params.FuncName = pkt.FuncNameQueryGameByStatus params.Payload = types.MustPBToJSON(req) var res pkt.PBGameRecords ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res) ctx.Run() } else if gameIDs != "" { params.FuncName = pkt.FuncNameQueryGameListByIDs var gameIDsS []string gameIDsS = append(gameIDsS, gameIDs) gameIDsS = append(gameIDsS, gameIDs) req := &pkt.QueryPBGameInfos{GameIds: gameIDsS} params.Payload = types.MustPBToJSON(req) var res pkt.ReplyPBGameList ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res) ctx.Run() } else { fmt.Println("Error: requeres at least one of gameID, address or status") cmd.Help() } }
412
0.899642
1
0.899642
game-dev
MEDIA
0.821308
game-dev
0.752807
1
0.752807
SolarMoonQAQ/Spark-Core
1,523
src/main/kotlin/cn/solarmoon/spark_core/skill/DefaultSkillConfig.kt
package cn.solarmoon.spark_core.skill import cn.solarmoon.spark_core.util.onEvent open class DefaultSkillConfig: SkillConfig { override val storage: LinkedHashMap<String, Any> = linkedMapOf() override fun init(skill: Skill) { super.init(skill) skill.onEvent<SkillEvent.PlayerGetAttackStrength> { if (read("ignore_attack_speed", false)) it.event.attackStrengthScale = 1f } skill.onEvent<SkillEvent.SweepAttack> { if (!read("enable_sweep_attack", true)) it.event.isSweeping = false } skill.onEvent<SkillEvent.CriticalHit> { if (!read("enable_critical_hit", true)) { if (it.event.vanillaMultiplier == 1.5f) it.event.isCriticalHit = false } } skill.onEvent<SkillEvent.TargetKnockBack> { if (!read("enable_target_knockback", true)) it.event.isCanceled = true } skill.onEvent<SkillEvent.TargetKnockBack> { val origin = it.event.originalStrength.toDouble() val strength = read("target_knockback_strength", origin) if (strength != origin) it.event.strength = strength.toFloat() } skill.onEvent<SkillEvent.TargetHurt> { val damageMultiplier = read("damage_multiplier", 1.0) if (damageMultiplier != 1.0) it.event.container.newDamage *= damageMultiplier.toFloat() } skill.onEvent<SkillEvent.Death> { if (read("end_on_death", true)) skill.end() } } }
412
0.8778
1
0.8778
game-dev
MEDIA
0.962829
game-dev
0.749644
1
0.749644
Tremeschin/Monolithium
1,288
monolithium/monolithium/monolith.rs
use crate::*; #[derive(Clone, Debug, Eq, Serialize, Deserialize)] pub struct Monolith { pub area: u64, pub seed: Seed, // Position in the world pub minx: i32, pub maxx: i32, pub minz: i32, pub maxz: i32, } /* -------------------------------------------------------------------------- */ impl Monolith { pub fn center_x(&self) -> i32 { (self.minx + self.maxx) / 2 } pub fn center_z(&self) -> i32 { (self.minz + self.maxz) / 2 } } /* -------------------------------------------------------------------------- */ // Monoliths are equal if they have the same coordinates impl Hash for Monolith { fn hash<H: Hasher>(&self, state: &mut H) { self.minx.hash(state); self.minz.hash(state); } } impl PartialEq for Monolith { fn eq(&self, other: &Self) -> bool { (self.minx == other.minx) && (self.minz == other.minz) } } /* -------------------------------------------------------------------------- */ // Monoliths should be sorted by area impl PartialOrd for Monolith { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.area.cmp(&other.area)) } } impl Ord for Monolith { fn cmp(&self, other: &Self) -> Ordering { self.area.cmp(&other.area) } }
412
0.822892
1
0.822892
game-dev
MEDIA
0.671337
game-dev
0.900183
1
0.900183
LessonStudio/Arduino_BLE_iOS_CPP
5,591
iOS_Example/cocos2d/external/bullet/BulletSoftBody/btSoftBodyConcaveCollisionAlgorithm.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_SOFT_BODY_CONCAVE_COLLISION_ALGORITHM_H #define BT_SOFT_BODY_CONCAVE_COLLISION_ALGORITHM_H #include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" #include "BulletCollision/BroadphaseCollision/btDispatcher.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h" #include "BulletCollision/CollisionShapes/btTriangleCallback.h" #include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h" class btDispatcher; #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" #include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h" class btSoftBody; class btCollisionShape; #include "LinearMath/btHashMap.h" #include "BulletCollision/BroadphaseCollision/btQuantizedBvh.h" //for definition of MAX_NUM_PARTS_IN_BITS struct btTriIndex { int m_PartIdTriangleIndex; class btCollisionShape* m_childShape; btTriIndex(int partId,int triangleIndex,btCollisionShape* shape) { m_PartIdTriangleIndex = (partId<<(31-MAX_NUM_PARTS_IN_BITS)) | triangleIndex; m_childShape = shape; } int getTriangleIndex() const { // Get only the lower bits where the triangle index is stored unsigned int x = 0; unsigned int y = (~(x&0))<<(31-MAX_NUM_PARTS_IN_BITS); return (m_PartIdTriangleIndex&~(y)); } int getPartId() const { // Get only the highest bits where the part index is stored return (m_PartIdTriangleIndex>>(31-MAX_NUM_PARTS_IN_BITS)); } int getUid() const { return m_PartIdTriangleIndex; } }; ///For each triangle in the concave mesh that overlaps with the AABB of a soft body (m_softBody), processTriangle is called. class btSoftBodyTriangleCallback : public btTriangleCallback { btSoftBody* m_softBody; const btCollisionObject* m_triBody; btVector3 m_aabbMin; btVector3 m_aabbMax ; btManifoldResult* m_resultOut; btDispatcher* m_dispatcher; const btDispatcherInfo* m_dispatchInfoPtr; btScalar m_collisionMarginTriangle; btHashMap<btHashKey<btTriIndex>,btTriIndex> m_shapeCache; public: int m_triangleCount; // btPersistentManifold* m_manifoldPtr; btSoftBodyTriangleCallback(btDispatcher* dispatcher,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped); void setTimeStepAndCounters(btScalar collisionMarginTriangle,const btCollisionObjectWrapper* triObjWrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); virtual ~btSoftBodyTriangleCallback(); virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex); void clearCache(); SIMD_FORCE_INLINE const btVector3& getAabbMin() const { return m_aabbMin; } SIMD_FORCE_INLINE const btVector3& getAabbMax() const { return m_aabbMax; } }; /// btSoftBodyConcaveCollisionAlgorithm supports collision between soft body shapes and (concave) trianges meshes. class btSoftBodyConcaveCollisionAlgorithm : public btCollisionAlgorithm { bool m_isSwapped; btSoftBodyTriangleCallback m_btSoftBodyTriangleCallback; public: btSoftBodyConcaveCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped); virtual ~btSoftBodyConcaveCollisionAlgorithm(); virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); virtual void getAllContactManifolds(btManifoldArray& manifoldArray) { //we don't add any manifolds } void clearCache(); struct CreateFunc :public btCollisionAlgorithmCreateFunc { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap) { void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSoftBodyConcaveCollisionAlgorithm)); return new(mem) btSoftBodyConcaveCollisionAlgorithm(ci,body0Wrap,body1Wrap,false); } }; struct SwappedCreateFunc :public btCollisionAlgorithmCreateFunc { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap) { void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSoftBodyConcaveCollisionAlgorithm)); return new(mem) btSoftBodyConcaveCollisionAlgorithm(ci,body0Wrap,body1Wrap,true); } }; }; #endif //BT_SOFT_BODY_CONCAVE_COLLISION_ALGORITHM_H
412
0.913386
1
0.913386
game-dev
MEDIA
0.993985
game-dev
0.769071
1
0.769071
sandsmark/freeaoe
3,045
src/ui/MouseCursor.cpp
#include "MouseCursor.h" #include <genie/resource/SlpFile.h> #include <genie/dat/UnitCommand.h> #include "core/Logger.h" #include "mechanics/UnitManager.h" #include "render/IRenderTarget.h" #include "resource/AssetManager.h" MouseCursor::MouseCursor(std::shared_ptr<IRenderTarget> renderTarget) : m_renderTarget(std::move(renderTarget)) { m_cursorsFile = AssetManager::Inst()->getSlp(AssetManager::filenameID("mcursors.shp")); if (!m_cursorsFile) { WARN << "Failed to get cursors"; } setCursor(Type::Normal); } bool MouseCursor::isValid() const { return m_currentType != Type::Invalid; } bool MouseCursor::setPosition(const ScreenPos &position) { if (position == m_position) { return false; } m_position = position; return true; } bool MouseCursor::update(const std::shared_ptr<UnitManager> &unitManager) { unitManager->onCursorPositionChanged(m_position, m_renderTarget->camera()); switch(unitManager->state()) { case UnitManager::State::Default: { const TaskSet &targetActions = unitManager->currentActionUnderCursor(); if (targetActions.isEmpty()) { return setCursor(MouseCursor::Normal); } const Task &targetAction = targetActions.first(); // TODO: simplification, might want to prioritize or something REQUIRE(targetAction.data, return false); if (targetAction.data->ActionType == genie::ActionType::Combat) { return setCursor(MouseCursor::Attack); } else { return setCursor(MouseCursor::Action); } break; } case UnitManager::State::SelectingAttackTarget: { return setCursor(MouseCursor::Axe); // idk } case UnitManager::State::PlacingBuilding: case UnitManager::State::PlacingWall: return setCursor(MouseCursor::Invalid); // IDK case UnitManager::State::SelectingGarrisonTarget: return setCursor(MouseCursor::Garrison); } WARN << "Unhandled state" << unitManager->state(); return false; } void MouseCursor::render() { if (m_currentType == Invalid) { return; } m_cursor_pos_text.setString(std::to_string(m_position.x) + ", " + std::to_string(m_position.y)); m_cursor_pos_text.setCharacterSize(11); m_cursor_pos_text.setPosition(ScreenPos(m_position)); if (m_currentType != Invalid) { m_renderTarget->draw(m_image, m_position); } m_renderTarget->draw(m_cursor_pos_text); } bool MouseCursor::setCursor(const MouseCursor::Type type) { if (type == m_currentType) { return false; } if (!m_cursorsFile) { WARN << "No cursors file available!"; return false; } if (type != Invalid) { REQUIRE(type < m_cursorsFile->getFrameCount(), return false); const genie::SlpFramePtr &newFrame = m_cursorsFile->getFrame(type); REQUIRE(newFrame != nullptr, return false); m_image = m_renderTarget->convertFrameToImage(newFrame); } m_currentType = type; return true; }
412
0.981747
1
0.981747
game-dev
MEDIA
0.544584
game-dev
0.970548
1
0.970548
abulmo/edax-reversi
17,961
src/endgame.c
/** * @file endgame.c * * Search near the end of the game. * * @date 1998 - 2024 * @author Richard Delorme * @author Toshihiko Okuhara * @version 4.6 */ #include "search.h" #include "bit.h" #include "hash.h" #include "settings.h" #include "stats.h" #include <assert.h> #include <stdbool.h> #include <stdint.h> /** * @brief Get the final score. * * Get the final score, when no move can be made. * * @param player player's discs. * @param n_empties Number of empty squares remaining on the board. * @return The final score, as a disc difference. */ static inline int solve(const uint64_t player, const int n_empties) { int score = bit_count(player) * 2 - SCORE_MAX; // score in case opponent wins, ie diff < 0 => score == diff - n_empies int diff = score + n_empties; // => diff SEARCH_STATS(++statistics.n_solve); if (diff == 0) score = diff; // draw score == 0 else if (diff > 0) score = diff + n_empties; // player wins. return score; } /** * @brief Get the final score. * * Get the final score, when no move can be made. * * @param search Search. * @return The final score, as a disc difference. */ int search_solve(const Search *search) { return solve(search->board.player, search->n_empties); } /** * @brief Get the final score. * * Get the final score, when the board is full. * * @param board Board. * @return The final score, as a disc difference. */ static inline int solve_0(const uint64_t player) { SEARCH_STATS(++statistics.n_solve_0); return 2 * bit_count(player) - SCORE_MAX; } /** * @brief Get the final score. * * Get the final score, when the board is full. * * @param search Search. * @return The final score, as a disc difference. */ int search_solve_0(const Search *search) { return solve_0(search->board.player); } /** * @brief Get the final score. * * Get the final score, when a single empty square remains (max stage). * * @param player player's discs. * @param alpha alpha bound (beta = alpha + 1). * @param x Last empty square to play. * @return The final opponent score, as a disc difference. */ static inline int solve_1(const uint64_t player, const int alpha, const int x) { int n_flips = count_last_flip(x, player); int score = 2 * bit_count(player) - SCORE_MAX + 2 + n_flips; SEARCH_STATS(++statistics.n_solve_1); if (n_flips == 0) { if (score <= 0) { score -= 2; if (score > alpha) { // lazy cut-off n_flips = count_last_flip(x, ~player); score -= n_flips; } } else { if (score > alpha) { // lazy cut-off if ((n_flips = count_last_flip(x, ~player)) != 0) { score -= n_flips + 2; } } } } return score; } /** * @brief Get the final score. * * Get the final score, when 2 empty squares remain (min stage). * * @param . * @param alpha Alpha bound. * @param x1 First empty square coordinate. * @param x2 Second empty square coordinate. * @param search Search. * @return The final score, as a disc difference. */ static inline int solve_2(const uint64_t player, const uint64_t opponent, const int alpha, const int x1, const int x2, int64_t *n_nodes) { uint64_t flipped; int score, bestscore, nodes = 1; const int beta = alpha + 1; if ((NEIGHBOUR[x1] & opponent) && (flipped = flip(x1, player, opponent))) { nodes = 2; bestscore = solve_1(opponent ^ flipped, alpha, x2); if ((bestscore > alpha) && (NEIGHBOUR[x2] & opponent) && (flipped = flip(x2, player, opponent))) { nodes = 3; score = solve_1(opponent ^ flipped, alpha, x1); if (score < bestscore) bestscore = score; } } else if ((NEIGHBOUR[x2] & opponent) && (flipped = flip(x2, player, opponent))) { nodes = 2; bestscore = solve_1(opponent ^ flipped, alpha, x1); } else { if ((NEIGHBOUR[x1] & player) && (flipped = flip(x1, opponent, player))) { nodes = 2; bestscore = -solve_1(player ^ flipped, -beta, x2); if ((bestscore < beta) && (NEIGHBOUR[x2] & player) && (flipped = flip(x2, opponent, player))) { nodes = 3; score = -solve_1(player ^ flipped, -beta, x1); if (score > bestscore) bestscore = score; } } else if ((NEIGHBOUR[x2] & player) && (flipped = flip(x2, opponent, player))) { nodes = 2; bestscore = -solve_1(player ^ flipped, -beta, x1); } else bestscore = solve(opponent, 2); } #if (COUNT_NODES & 1) *n_nodes += nodes; #endif assert(SCORE_MIN <= bestscore && bestscore <= SCORE_MAX); assert((bestscore & 1) == 0); return bestscore; } /** * @brief Get the final score at 3 empties. * * Get the final score, when 3 empty squares remain (max stage). * * @param search Search. * @param alpha Alpha bound. * @return The final score, as a disc difference. */ static int solve_3(const uint64_t player, const uint64_t opponent, const int alpha, int x1, int x2, int x3, const int parity, int64_t *n_nodes) { uint64_t flipped, next_player, next_opponent; int score, bestscore, tmp; const int beta = alpha + 1; SEARCH_STATS(++statistics.n_solve_3); SEARCH_UPDATE_INTERNAL_NODES(*n_nodes); // parity based move sorting if (!(parity & QUADRANT_ID[x1])) { if (parity & QUADRANT_ID[x2]) { // case 1(x2) 2(x1 x3) tmp = x1; x1 = x2; if (SQUARE_VALUE[x3] > SQUARE_VALUE[tmp]) { x2 = x3; x3 = tmp; } else { x2 = tmp; } } else { // case 1(x3) 2(x1 x2) tmp = x1; x1 = x3; if (SQUARE_VALUE[x2] > SQUARE_VALUE[tmp]) { x3 = tmp; } else { x3 = x2; x2 = tmp; } } } else { if (SQUARE_VALUE[x3] > SQUARE_VALUE[x2]) { tmp = x2; x2 = x3; x3 = tmp; } if (SQUARE_VALUE[x2] > SQUARE_VALUE[x1]) { tmp = x2; x2 = x3; x3 = tmp; } } // best move alphabeta search if ((NEIGHBOUR[x1] & opponent) && (flipped = flip(x1, player, opponent))) { next_player = opponent ^ flipped; next_opponent = player ^ (flipped | x_to_bit(x1)); bestscore = solve_2(next_player, next_opponent, alpha, x2, x3, n_nodes); if (bestscore >= beta) return bestscore; } else bestscore = -SCORE_INF; if ((NEIGHBOUR[x2] & opponent) && (flipped = flip(x2, player, opponent))) { next_player = opponent ^ flipped; next_opponent = player ^ (flipped | x_to_bit(x2)); score = solve_2(next_player, next_opponent, alpha, x1, x3, n_nodes); if (score >= beta) return score; else if (score > bestscore) bestscore = score; } if ((NEIGHBOUR[x3] & opponent) && (flipped = flip(x3, player, opponent))) { next_player = opponent ^ flipped; next_opponent = player ^ (flipped | x_to_bit(x3)); score = solve_2(next_player, next_opponent, alpha, x1, x2, n_nodes); if (score > bestscore) bestscore = score; } if (bestscore == -SCORE_INF) { // pass if ((NEIGHBOUR[x1] & player) && (flipped = flip(x1, opponent, player))) { next_player = player ^ flipped; next_opponent = opponent ^ (flipped | x_to_bit(x1)); bestscore = -solve_2(next_player, next_opponent, -beta, x2, x3, n_nodes); if (bestscore <= alpha) return bestscore; } else bestscore = SCORE_INF; if ((NEIGHBOUR[x2] & player) && (flipped = flip(x2, opponent, player))) { next_player = player ^ flipped; next_opponent = opponent ^ (flipped | x_to_bit(x2)); score = -solve_2(next_player, next_opponent, -beta, x1, x3, n_nodes); if (score <= alpha) return score; else if (score < bestscore) bestscore = score; } if ((NEIGHBOUR[x3] & player) && (flipped = flip(x3, opponent, player))) { next_player = player ^ flipped; next_opponent = opponent ^ (flipped | x_to_bit(x3)); score = -solve_2(next_player, next_opponent, -beta, x1, x2, n_nodes); if (score < bestscore) bestscore = score; } // gameover if (bestscore == SCORE_INF) bestscore = solve(player, 3); } assert(SCORE_MIN <= bestscore && bestscore <= SCORE_MAX); return bestscore; } /** * @brief Get the final score. * * Get the final score, when 4 empty squares remain (min stage). * * @param search Search position. * @param alpha Upper score value. * @return The final score, as a disc difference. */ static int search_solve_4(Search *search, const int alpha) { const uint64_t player = search->board.player, opponent = search->board.opponent; uint64_t flipped, next_player, next_opponent; int64_t *n_nodes = &search->n_nodes; SquareList *empties = search->empties; int x1 = empties[NOMOVE].next; int x2 = empties[x1].next; int x3 = empties[x2].next; int x4 = empties[x3].next; int score, bestscore; const int beta = alpha + 1; SEARCH_STATS(++statistics.n_search_solve_4); SEARCH_UPDATE_INTERNAL_NODES(search->n_nodes); // stability cutoff if (search_SC_NWS_4(search, alpha, &score)) return score; // parity based move sorting. // The following hole sizes are possible: // 4 - 1 3 - 2 2 - 1 1 2 - 1 1 1 1 // Only the 1 1 2 case needs move sorting. if (!(search->parity & QUADRANT_ID[x1])) { if (search->parity & QUADRANT_ID[x2]) { if (search->parity & QUADRANT_ID[x3]) { // case 1(x2) 1(x3) 2(x1 x4) int tmp = x1; x1 = x2; x2 = x3; x3 = tmp; } else { // case 1(x2) 1(x4) 2(x1 x3) int tmp = x1; x1 = x2; x2 = x4; x4 = x3; x3 = tmp; } } else if (search->parity & QUADRANT_ID[x3]) { // case 1(x3) 1(x4) 2(x1 x2) int tmp = x1; x1 = x3; x3 = tmp; tmp = x2; x2 = x4; x4 = tmp; } } else { if (!(search->parity & QUADRANT_ID[x2])) { if (search->parity & QUADRANT_ID[x3]) { // case 1(x1) 1(x3) 2(x2 x4) int tmp = x2; x2 = x3; x3 = tmp; } else { // case 1(x1) 1(x4) 2(x2 x3) int tmp = x2; x2 = x4; x4 = x3; x3 = tmp; } } } // best move alphabeta search if ((NEIGHBOUR[x1] & opponent) && (flipped = flip(x1, player, opponent))) { next_player = opponent ^ flipped; next_opponent = player ^ (flipped | x_to_bit(x1)); bestscore = solve_3(next_player, next_opponent, alpha, x2, x3, x4, search->parity ^ QUADRANT_ID[x1], n_nodes); if (bestscore <= alpha) return bestscore; } else bestscore = SCORE_INF; if ((NEIGHBOUR[x2] & opponent) && (flipped = flip(x2, player, opponent))) { next_player = opponent ^ flipped; next_opponent = player ^ (flipped | x_to_bit(x2)); score = solve_3(next_player, next_opponent, alpha, x1, x3, x4, search->parity ^ QUADRANT_ID[x2], n_nodes); if (score <= alpha) return score; else if (score < bestscore) bestscore = score; } if ((NEIGHBOUR[x3] & opponent) && (flipped = flip(x3, player, opponent))) { next_player = opponent ^ flipped; next_opponent = player ^ (flipped | x_to_bit(x3)); score = solve_3(next_player, next_opponent, alpha, x1, x2, x4, search->parity ^ QUADRANT_ID[x3], n_nodes); if (score <= alpha) return score; else if (score < bestscore) bestscore = score; } if ((NEIGHBOUR[x4] & opponent) && (flipped = flip(x4, player, opponent))) { next_player = opponent ^ flipped; next_opponent = player ^ (flipped | x_to_bit(x4)); score = solve_3(next_player, next_opponent, alpha, x1, x2, x3, search->parity ^ QUADRANT_ID[x4], n_nodes); if (score < bestscore) bestscore = score; } // pass if (bestscore == SCORE_INF) { if (can_move(opponent, player)) { // pass ? search_pass_endgame(search); bestscore = -search_solve_4(search, -beta); search_pass_endgame(search); } else { // gameover bestscore = solve(opponent, 4); } } assert(SCORE_MIN <= bestscore && bestscore <= SCORE_MAX); return bestscore; } /** * @brief Evaluate a position using a shallow NWS. * * This function is used when there are few empty squares on the board. Here, * optimizations are in favour of speed instead of efficiency. * Move ordering is constricted to the hole parity and the type of squares. * No hashtable are used and anticipated cut-off is limited to stability cut-off. * * @param search Search. * @param alpha Alpha bound. * @return The final score, as a disc difference. */ static int search_shallow(Search *search, const int alpha) { Board *board = &search->board; int x; Move move; int score, bestscore = -SCORE_INF; const int beta = alpha + 1; assert(SCORE_MIN <= alpha && alpha <= SCORE_MAX); assert(0 <= search->n_empties && search->n_empties <= DEPTH_TO_SHALLOW_SEARCH); SEARCH_STATS(++statistics.n_NWS_shallow); SEARCH_UPDATE_INTERNAL_NODES(search->n_nodes); // stability cutoff if (search_SC_NWS(search, alpha, &score)) return score; if (search->parity > 0 && search->parity < 15) { foreach_odd_empty (x, search->empties, search->parity) { if ((NEIGHBOUR[x] & board->opponent) && board_get_move(board, x, &move)) { search_update_endgame(search, &move); if (search->n_empties == 4) score = search_solve_4(search, alpha); else score = -search_shallow(search, -beta); search_restore_endgame(search, &move); if (score >= beta) return score; else if (score > bestscore) bestscore = score; } } foreach_even_empty (x, search->empties, search->parity) { if ((NEIGHBOUR[x] & board->opponent) && board_get_move(board, x, &move)) { search_update_endgame(search, &move); if (search->n_empties == 4) score = search_solve_4(search, alpha); else score = -search_shallow(search, -beta); search_restore_endgame(search, &move); if (score >= beta) return score; else if (score > bestscore) bestscore = score; } } } else { foreach_empty (x, search->empties) { if ((NEIGHBOUR[x] & board->opponent) && board_get_move(board, x, &move)) { search_update_endgame(search, &move); if (search->n_empties == 4) score = search_solve_4(search, alpha); else score = -search_shallow(search, -beta); search_restore_endgame(search, &move); if (score >= beta) return score; else if (score > bestscore) bestscore = score; } } } // no move if (bestscore == -SCORE_INF) { if (can_move(board->opponent, board->player)) { // pass search_pass_endgame(search); bestscore = -search_shallow(search, -beta); search_pass_endgame(search); } else { // gameover bestscore = search_solve(search); } } assert(SCORE_MIN <= bestscore && bestscore <= SCORE_MAX); return bestscore; } /** * @brief Evaluate an endgame position with a Null Window Search algorithm. * * This function is used when there are still many empty squares on the board. Move * ordering, hash table cutoff, enhanced transposition cutoff, etc. are used in * order to diminish the size of the tree to analyse, but at the expense of a * slower speed. * * @param search Search. * @param alpha Alpha bound. * @return The final score, as a disc difference. */ int NWS_endgame(Search *search, const int alpha) { HashTable *hash_table = &search->hash_table; HashData hash_data; HashStore store; uint64_t hash_code; const int beta = alpha + 1; Board *board = &search->board; MoveList movelist; Move *move; int score, bestscore, bestmove; uint64_t cost; if (search->stop) return alpha; assert(search->n_empties == bit_count(~(search->board.player | search->board.opponent))); assert(SCORE_MIN <= alpha && alpha <= SCORE_MAX); SEARCH_STATS(++statistics.n_NWS_endgame); SEARCH_UPDATE_INTERNAL_NODES(search->n_nodes); #if USE_SOLID // discs on all lines full do not participate to the game anymore, // so we transfer them to the player side. Board solid; int solid_delta; uint64_t full = 0; // stability cutoff if (search_SC_NWS_full(search, alpha, &score, &full)) return score; solid = *board; solid_delta = 0; if (search->n_empties <= SOLID_DEPTH) { full &= solid.opponent; solid.opponent ^= full; solid.player ^=full; solid_delta = 2 * bit_count(full); } // transposition prefetch hash_code = board_get_hash_code(&solid); hash_prefetch(hash_table, hash_code); #else hash_code = board_get_hash_code(board); hash_prefetch(hash_table, hash_code); // stability cutoff if (search_SC_NWS(search, alpha, &score)) return score; #endif search_get_movelist(search, &movelist); if (movelist.n_moves > 1) { // transposition cutoff #if USE_SOLID if (hash_get(hash_table, &solid, hash_code, &hash_data)) { hash_data.lower -= solid_delta; hash_data.upper -= solid_delta; if (search_TC_NWS(&hash_data, search->n_empties, NO_SELECTIVITY, alpha, &score)) return score; } #else if (hash_get(hash_table, board, hash_code, &hash_data) && search_TC_NWS(&hash_data, search->n_empties, NO_SELECTIVITY, alpha, &score)) return score; #endif cost = -search->n_nodes; movelist_evaluate_fast(&movelist, search, &hash_data); bestscore = -SCORE_INF; // loop over all moves foreach_best_move(move, &movelist) { search_update_endgame(search, move); if (search->n_empties <= DEPTH_TO_SHALLOW_SEARCH) score = -search_shallow(search, -beta); else score = -NWS_endgame(search, -beta); search_restore_endgame(search, move); if (score > bestscore) { bestmove = move->x; bestscore = score; if (bestscore >= beta) break; } } if (!search->stop) { cost += search->n_nodes; draft_set(&store.draft, search->n_empties, NO_SELECTIVITY, last_bit(cost), search->hash_table.date); #if USE_SOLID store_set(&store, alpha + solid_delta, beta + solid_delta, bestscore + solid_delta, bestmove); hash_store(hash_table, &solid, hash_code, &store); #else store_set(&store, alpha, beta, bestscore, bestmove); hash_store(hash_table, board, hash_code, &store); #endif } } else if (movelist.n_moves == 1) { move = movelist_first(&movelist); search_update_endgame(search, move); if (search->n_empties <= DEPTH_TO_SHALLOW_SEARCH) bestscore = -search_shallow(search, -beta); else bestscore = -NWS_endgame(search, -beta); search_restore_endgame(search, move); } else { if (can_move(board->opponent, board->player)) { // pass search_pass_endgame(search); bestscore = -NWS_endgame(search, -beta); search_pass_endgame(search); } else { // game over bestscore = search_solve(search); } } if (SQUARE_STATS(1) + 0) { foreach_move(move, &movelist) ++statistics.n_played_square[search->n_empties][SQUARE_TYPE[move->x]]; if (bestscore > alpha) ++statistics.n_good_square[search->n_empties][SQUARE_TYPE[bestscore]]; } assert(SCORE_MIN <= bestscore && bestscore <= SCORE_MAX); return bestscore; }
412
0.86034
1
0.86034
game-dev
MEDIA
0.801076
game-dev
0.954983
1
0.954983
lenmus/lenmus
5,955
lomse/trunk/src/graphic_model/lomse_gm_measures_table.cpp
//--------------------------------------------------------------------------------------- // This file is part of the Lomse library. // Lomse is copyrighted work (c) 2010-2019. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // For any comment, suggestion or feature request, please contact the manager of // the project at cecilios@users.sourceforge.net //--------------------------------------------------------------------------------------- #include "lomse_gm_measures_table.h" #include "lomse_internal_model.h" #include "lomse_im_measures_table.h" #include "lomse_box_system.h" #include "lomse_shape_barline.h" //std #include <sstream> #include <iomanip> using namespace std; namespace lomse { //======================================================================================= //GmMeasuresTable implementation //======================================================================================= GmMeasuresTable::GmMeasuresTable(ImoScore* pScore) { initialize_vectors(pScore); } //--------------------------------------------------------------------------------------- GmMeasuresTable::~GmMeasuresTable() { for (size_t iInstr=0; iInstr < m_instrument.size(); ++iInstr) { if (m_instrument[iInstr]) { m_instrument[iInstr]->clear(); delete m_instrument[iInstr]; } } m_instrument.clear(); } //--------------------------------------------------------------------------------------- void GmMeasuresTable::initialize_vectors(ImoScore* pScore) { int numInstruments = pScore->get_num_instruments(); m_instrument.resize(numInstruments); m_numBarlines.assign(numInstruments, 0); for (int iInstr=0; iInstr < numInstruments; ++iInstr) { ImoInstrument* pInstr = pScore->get_instrument(iInstr); ImMeasuresTable* pTable = pInstr->get_measures_table(); if (pTable) { int numMeasures = pTable->num_entries(); BarlinesVector* pBarlines = LOMSE_NEW BarlinesVector; pBarlines->assign(numMeasures, nullptr); m_instrument[iInstr] = pBarlines; } else { m_instrument[iInstr] = nullptr; //empty instrument } } } //--------------------------------------------------------------------------------------- int GmMeasuresTable::get_num_measures(int iInstr) { BarlinesVector* pBarlines = m_instrument[iInstr]; if (pBarlines) return int(pBarlines->size()); return 0; } //--------------------------------------------------------------------------------------- void GmMeasuresTable::finish_measure(int iInstr, GmoShapeBarline* pBarlineShape) { //invoked when a non-middle barline is found BarlinesVector* pBarlines = m_instrument[iInstr]; pBarlines->at(m_numBarlines[iInstr]) = pBarlineShape; m_numBarlines[iInstr]++; } //--------------------------------------------------------------------------------------- LUnits GmMeasuresTable::get_end_barline_left(int iInstr, int iMeasure, GmoBoxSystem* pBox) { LUnits xLeft = pBox->get_right(); BarlinesVector* pBarlines = m_instrument.at(iInstr); GmoShapeBarline* pEndShape = pBarlines->at(iMeasure); if (pEndShape) xLeft = pEndShape->get_left(); return xLeft; } //--------------------------------------------------------------------------------------- LUnits GmMeasuresTable::get_start_barline_right(int iInstr, int iMeasure, GmoBoxSystem* pBox) { BarlinesVector* pBarlines = m_instrument.at(iInstr); LUnits xRight = pBox->get_start_measure_xpos(); if (iMeasure > 0) { int iFirstMeasure = pBox->get_first_measure(iInstr); if (iFirstMeasure >=0 && iMeasure > iFirstMeasure) { GmoShapeBarline* pStartShape = pBarlines->at(iMeasure-1); if (pStartShape) xRight = pStartShape->get_right(); } } return xRight; } //--------------------------------------------------------------------------------------- void GmMeasuresTable::dump_gm_measures() { stringstream s; s << endl << "GmMeasuresTable:" << endl; vector<BarlinesVector*>::iterator it; int iInstr = 0; for (it = m_instrument.begin(); it != m_instrument.end(); ++it, ++iInstr) { s << fixed << setprecision(2) << iInstr << ": "; BarlinesVector* pBarlines = *it; for (size_t i=0; i < pBarlines->size(); ++i) { s << (pBarlines->at(i) ? "1," : "0,"); } s << endl; } dbgLogger << s.str(); } } //namespace lomse
412
0.958715
1
0.958715
game-dev
MEDIA
0.640531
game-dev
0.689473
1
0.689473
DreamLife-Jianwei/Qt-Vtk
9,213
11_QtVtk9ReadDicomDemoCmake/Vtk9/include/vtk-9.0/vtkOctreePointLocatorNode.h
/*========================================================================= Program: Visualization Toolkit Module: vtkOctreePointLocatorNode.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ /** * @class vtkOctreePointLocatorNode * @brief Octree node that has 8 children each of equal size * * * This class represents a single spatial region in a 3D axis octant * partitioning. It is intended to work efficiently with the * vtkOctreePointLocator and is not meant for general use. It is assumed * the region bounds some set of points. The ordering of the children is * (-x,-y,-z),(+x,-y,-z),(-x,+y,-z),(+x,+y,-z),(-x,-y,+z),(+x,-y,+z), * (-x,+y,+z),(+x,+y,+z). The portion of the domain assigned to an * octant is Min < x <= Max. * * @sa * vtkOctreePointLocator */ #ifndef vtkOctreePointLocatorNode_h #define vtkOctreePointLocatorNode_h #include "vtkCommonDataModelModule.h" // For export macro #include "vtkObject.h" class vtkCell; class vtkPlanesIntersection; class VTKCOMMONDATAMODEL_EXPORT vtkOctreePointLocatorNode : public vtkObject { public: vtkTypeMacro(vtkOctreePointLocatorNode, vtkObject); void PrintSelf(ostream& os, vtkIndent indent) override; static vtkOctreePointLocatorNode* New(); //@{ /** * Set/Get the number of points contained in this region. */ void SetNumberOfPoints(int numberOfPoints) { this->NumberOfPoints = numberOfPoints; } vtkGetMacro(NumberOfPoints, int); //@} //@{ /** * Set/Get the bounds of the spatial region represented by this node. * Caller allocates storage for 6-vector in GetBounds. */ void SetBounds(double xMin, double xMax, double yMin, double yMax, double zMin, double zMax); void SetBounds(const double b[6]) { this->SetBounds(b[0], b[1], b[2], b[3], b[4], b[5]); } void GetBounds(double* b) const; //@} //@{ /** * Set/Get the bounds of the points contained in this spatial region. * This may be smaller than the bounds of the region itself. * Caller allocates storage for 6-vector in GetDataBounds. */ void SetDataBounds(double xMin, double xMax, double yMin, double yMax, double zMin, double zMax); void GetDataBounds(double* b) const; //@} //@{ /** * Get a pointer to the 3 bound minima (xmin, ymin and zmin) or the * 3 bound maxima (xmax, ymax, zmax). Don't free this pointer. */ vtkGetMacro(MinBounds, double*); vtkGetMacro(MaxBounds, double*); //@} //@{ /** * Set the xmin, ymin and zmin value of the bounds of this region */ void SetMinBounds(double minBounds[3]) { this->MinBounds[0] = minBounds[0]; this->MinBounds[1] = minBounds[1]; this->MinBounds[2] = minBounds[2]; } //@} //@{ /** * Set the xmax, ymax and zmax value of the bounds of this region */ void SetMaxBounds(double maxBounds[3]) { this->MaxBounds[0] = maxBounds[0]; this->MaxBounds[1] = maxBounds[1]; this->MaxBounds[2] = maxBounds[2]; } //@} //@{ /** * Get a pointer to the 3 data bound minima (xmin, ymin and zmin) or the * 3 data bound maxima (xmax, ymax, zmax). Don't free this pointer. */ vtkGetMacro(MinDataBounds, double*); vtkGetMacro(MaxDataBounds, double*); //@} //@{ /** * Set the xmin, ymin and zmin value of the bounds of this * data within this region. */ void SetMinDataBounds(double minDataBounds[3]) { this->MinDataBounds[0] = minDataBounds[0]; this->MinDataBounds[1] = minDataBounds[1]; this->MinDataBounds[2] = minDataBounds[2]; } //@} //@{ /** * Set the xmax, ymax and zmax value of the bounds of this * data within this region. */ void SetMaxDataBounds(double maxDataBounds[3]) { this->MaxDataBounds[0] = maxDataBounds[0]; this->MaxDataBounds[1] = maxDataBounds[1]; this->MaxDataBounds[2] = maxDataBounds[2]; } //@} //@{ /** * Get the ID associated with the region described by this node. If * this is not a leaf node, this value should be -1. */ vtkGetMacro(ID, int); //@} //@{ /** * If this node is not a leaf node, there are leaf nodes below it whose * regions represent a partitioning of this region. The IDs of these * leaf nodes form a contiguous set. Get the first of the first point's * ID that is contained in this node. */ vtkGetMacro(MinID, int); //@} /** * Add the 8 children. */ void CreateChildNodes(); /** * Delete the 8 children. */ void DeleteChildNodes(); /** * Get a pointer to the ith child of this node. */ vtkOctreePointLocatorNode* GetChild(int i); /** * A vtkPlanesIntersection object represents a convex 3D region bounded * by planes, and it is capable of computing intersections of * boxes with itself. Return 1 if this spatial region intersects * the spatial region described by the vtkPlanesIntersection object. * Use the possibly smaller bounds of the points within the region * if useDataBounds is non-zero. */ int IntersectsRegion(vtkPlanesIntersection* pi, int useDataBounds); /** * Return 1 if this spatial region entirely contains the given point. * Use the possibly smaller bounds of the points within the region * if useDataBounds is non-zero. */ vtkTypeBool ContainsPoint(double x, double y, double z, int useDataBounds); /** * Calculate the distance squared from any point to the boundary of this * region. Use the boundary of the points within the region if useDataBounds * is non-zero. */ double GetDistance2ToBoundary( double x, double y, double z, vtkOctreePointLocatorNode* top, int useDataBounds); /** * Calculate the distance squared from any point to the boundary of this * region. Use the boundary of the points within the region if useDataBounds * is non-zero. Set boundaryPt to the point on the boundary. */ double GetDistance2ToBoundary(double x, double y, double z, double* boundaryPt, vtkOctreePointLocatorNode* top, int useDataBounds); /** * Calculate the distance from the specified point (which is required to * be inside this spatial region) to an interior boundary. An interior * boundary is one that is not also an boundary of the entire space * partitioned by the tree of vtkOctreePointLocatorNode's. */ double GetDistance2ToInnerBoundary(double x, double y, double z, vtkOctreePointLocatorNode* top); /** * Return the id of the suboctant that a given point is in. * If CheckContainment is non-zero then it checks whether * the point is in the actual bounding box of the suboctant, * otherwise it only checks which octant the point is in * that is created from the axis-aligned partitioning of * the domain at this octant's center. */ int GetSubOctantIndex(double* point, int CheckContainment); /** * Recursive function to compute ID, MinVal, MaxVal, and MinID. * Parent is used for MinVal and MaxVal in the case that no * points are in the leaf node. */ void ComputeOctreeNodeInformation( vtkOctreePointLocatorNode* Parent, int& NextLeafId, int& NextMinId, float* coordinates); protected: vtkOctreePointLocatorNode(); ~vtkOctreePointLocatorNode() override; private: double _GetDistance2ToBoundary(double x, double y, double z, double* boundaryPt, int innerBoundaryOnly, vtkOctreePointLocatorNode* top, int useDataBounds); /** * The minimum coordinate location of the node. */ double MinBounds[3]; /** * The maximum coordinate location of the node. */ double MaxBounds[3]; /** * The minimum coordinate location of the points contained * within this node. */ double MinDataBounds[3]; /** * The maximum coordinate location of the points contained * within this node. */ double MaxDataBounds[3]; /** * Get the number of points associated with this octant. * The octant does not have to be a leaf octant. For example, * for the root octant NumberOfPoints is equal to the number * of points in the dataset. */ int NumberOfPoints; /** * A pointer to the 8 children of this node. */ vtkOctreePointLocatorNode** Children; /** * The ID of this octant. If it is not a leaf octant then ID=-1. */ int ID; /** * The minimum Id of the ordered points in this octant (note that * this Id is different than the vtkIdType used for referencing * the point in the data set. */ int MinID; vtkOctreePointLocatorNode(const vtkOctreePointLocatorNode&) = delete; void operator=(const vtkOctreePointLocatorNode&) = delete; }; #endif
412
0.970949
1
0.970949
game-dev
MEDIA
0.327502
game-dev
0.990116
1
0.990116
eaglerforge/EaglerForge-builds
70,671
web/v1.3.2/lang/kw_GB.lang
achievement.acquireIron=Kavos Kalesweyth achievement.acquireIron.desc=Teudhi unn torth horn achievement.bakeCake=An Gow achievement.bakeCake.desc=Gwaneth, sugra, leth hag oyow! achievement.blazeRod=Yn Tan achievement.blazeRod.desc=Difres unn Dewi a y welen achievement.bookcase=Lyveryas achievement.breedCow=Daspoblans achievement.buildBetterPickaxe=Ow kavos unn Gwellhe achievement.buildBetterPickaxe.desc=Gul unn pigel gwell achievement.buildFurnace=Testen Tomm achievement.buildFurnace.desc=Drehevel unn fog yn-mes a eth stockys men achievement.buildHoe=Termyn dhe Amethi! achievement.buildPickaxe=Termyn dhe Balas! achievement.buildPickaxe.desc=Usya estylow ha gwelynni gul unn pigel achievement.buildSword=Gweskel Termyn! achievement.cookFish=Pysk Dentethyel achievement.cookFish.desc=Kachyans ha kog pysk! achievement.diamonds=ADAMANTYS! achievement.diamondsToYou=Adamantys Dhis! achievement.enchantments=Pystrier achievement.enchantments.desc=Use a book, obsidian and diamonds to construct an enchantment table, also jere is a weasel achievement.exploreAllBiomes=Owth Aventur Termyn achievement.exploreAllBiomes.desc=Diskudha oll an viomys achievement.flyPig=Pan Vogh Neyja achievement.flyPig.desc=Neyja unn hogh dres unn als achievement.fullBeacon=Golowver achievement.fullBeacon.desc=Gwruthyl unn Golowva Leun achievement.get=Kerhes Kowlwrians! achievement.ghast=Daskor dhe Danvonow achievement.ghast.desc=Distrui Euth gans unn tanpel achievement.killCow=Omhwelesek Bugh achievement.killCow.desc=Trevasa re ledher achievement.killEnemy=Helghor Tebelvest achievement.killEnemy.desc=Omsettya ha distrui unn Tebelvest achievement.killWither=An Dhalleth. achievement.killWither.desc=Ladha an Wedhra achievement.makeBread=Pobas Bara achievement.makeBread.desc=Omwul gwaneth yn bara achievement.mineWood=Ow Kerhes Prenn achievement.onARail=Warn Hyns horn achievement.openInventory=Merkya Rol achievement.openInventory.desc=Gwaska '%1$s' rag ygeri agas rol. achievement.overkill=Gorladha achievement.overkill.desc=Deal nine hearts of damage in a single hit achievement.portal=Yma odhom dhyn dhe downhe achievement.portal.desc=Drehevel unn porth dhe'n Annown achievement.potion=Bragji Teythyek achievement.potion.desc=Braga Diwas achievement.requires=Rekwirya '%1$s' achievement.snipeSkeleton=Omladh Sether achievement.spawnWither=An Dhalleth? achievement.spawnWither.desc=Bywhe an Wedhra achievement.taken=Kemerys! achievement.theEnd=An Diwedh? achievement.theEnd.desc=Desedha an Diwedh achievement.theEnd2=An Diwedh. achievement.theEnd2.desc=Fedha an Dragon Diwedhek achievement.unknown=??? addServer.add=Gwrys addServer.enterIp=Trigva an Servyer addServer.enterName=Hanow an Servyer addServer.hideAddress=Kudha an Drigva addServer.title=Chanjya kedhlow an servyer advMode.allEntities=Use "@e" to target all entities advMode.allPlayers=Usya "@a" dhe kostenna gwarioryon oll advMode.command=Arhadow Konsolen advMode.nearestPlayer=Usya "@p" dhe kostenna an gwarier nessa advMode.notAllowed=Must be an opped player in creative mode advMode.notEnabled=Nyns yma Stockys Arhadow galosegiek war hemm servyer advMode.previousOutput=Previous Output advMode.randomPlayer=Usya "@r" dhe kostenna unn gwarier war amkan advMode.setCommand=Settya Arhadow Konsolen rag Stock advMode.setCommand.success=Command set: %s attribute.name.generic.attackDamage=Damach Omsettyans attribute.name.generic.followRange=Efander Holya Mob attribute.name.generic.knockbackResistance=Defens Bonkarta attribute.name.generic.maxHealth=Ugh-Yehes attribute.name.generic.movementSpeed=Tooth attribute.name.zombie.spawnReinforcements=Kreunyow Zombi book.byAuthor=gans %1$s book.editTitle=Titel an lyver: book.finalizeButton=Sina ha degea book.finalizeWarning=Notyewgh! Pan wryllowgh hwi sina an lyver, ny vydh chanjyadow na fella. book.generation.0=Original book.generation.1=Copy of original book.generation.2=Copy of a copy book.generation.3=Tattered book.pageIndicator=Folen %1$s a %2$s book.signButton=Sina chat.cannotSend=Cannot send chat message chat.copy=Eylscrif dhe'n Scryp chat.link.confirm=Owgh hwi sur bos hwans dhywgh ygeri an wiasva a sew? chat.link.open=Ygeri yn Peurel chat.link.warning=Na ygerewgh nevra kevrennow dhyworth tus na drestyowgh dhedha! chat.stream.emote=(%s) * %s %s chat.stream.text=(%s) <%s> %s commands.achievement.alreadyHave=Player %s already has achievement %s commands.achievement.dontHave=Player %s doesn't have achievement %s commands.achievement.give.success.all=Successfully given all achievements to %s commands.achievement.give.success.one=Successfully given %s the stat %s commands.achievement.statTooLow=Player %s does not have the stat %s commands.achievement.take.success.all=Successfully taken all achievements from %s commands.achievement.take.success.one=Successfully taken the stat %s from %s commands.achievement.unknownAchievement=Unknown achievement or statistic '%s' commands.achievement.usage=/achievement <give|take> <stat_name|*> [player] commands.ban.success=Gwarier Emskemunys %s commands.ban.usage=/ban <name> [reason ...] commands.banip.invalid=Hwi re entras trigva IP drog po gwarier nag yw warlinen commands.banip.success=Trigva IP %s difennys commands.banip.usage=/ban-ip <address|name> [reason ...] commands.banlist.usage=/banlist [ips|players] commands.blockdata.failed=The data tag did not change: %s commands.blockdata.notValid=The target block is not a data holder block commands.blockdata.outOfWorld=Cannot change block outside of the world commands.blockdata.success=Block data updated to: %s commands.blockdata.tagError=Data tag parsing failed: %s commands.blockdata.usage=/blockdata <x> <y> <z> <dataTag> commands.clear.failure=Ny yll kartha an rol a %s, namoy traow dhe remova commands.clear.success=Karthys an rol a %s, ow remova %s traow commands.clone.failed=No blocks cloned commands.clone.noOverlap=Source and destination can not overlap commands.clone.outOfWorld=Cannot access blocks outside of the world commands.clone.success=%s blocks cloned commands.clone.tooManyBlocks=Too many blocks in the specified area (%s > %s) commands.clone.usage=/clone <x1> <y1> <z1> <x2> <y2> <z2> <x> <y> <z> [mode] commands.compare.failed=Source and destination are not identical commands.compare.outOfWorld=Cannot access blocks outside of the world commands.compare.success=%s blocks compared commands.compare.tooManyBlocks=Too many blocks in the specified area (%s > %s) commands.compare.usage=/testforblocks <x1> <y1> <z1> <x2> <y2> <z2> <x> <y> <z> [mode] commands.defaultgamemode.usage=/defaultgamemode <mode> commands.deop.success=De-opped %s commands.deop.usage=/deop <player> commands.difficulty.usage=/difficulty <new difficulty> commands.downfall.success=Skwychys hager-gowas commands.effect.failure.notActive=Couldn't take %1$s from %2$s as they do not have the effect commands.effect.failure.notActive.all=Couldn't take any effects from %s as they do not have any commands.effect.notFound=There is no such mob effect with ID %s commands.effect.success=Given %1$s (ID %2$s) * %3$s to %4$s for %5$s seconds commands.effect.success.removed=Took %1$s from %2$s commands.effect.success.removed.all=Took all effects from %s commands.effect.usage=/effect <player> <effect> [seconds] [amplifier] [hideParticles] commands.enchant.notFound=There is no such enchantment with ID %s commands.enchant.success=Hus Sewen commands.enchant.usage=/enchant <player> <enchantment ID> [level] commands.entitydata.failed=The data tag did not change: %s commands.entitydata.noPlayers=%s is a player and cannot be changed commands.entitydata.success=Entity data updated to: %s commands.entitydata.tagError=Data tag parsing failed: %s commands.entitydata.usage=/entitydata <entity> <dataTag> commands.fill.failed=No blocks filled commands.fill.outOfWorld=Cannot place blocks outside of the world commands.fill.success=%s blocks filled commands.fill.tagError=Data tag parsing failed: %s commands.fill.tooManyBlocks=Too many blocks in the specified area (%s > %s) commands.fill.usage=/fill <x1> <y1> <z1> <x2> <y2> <z2> <TileName> [dataValue] [oldBlockHandling] [dataTag] commands.gamemode.usage=/gamemode <mode> [player] commands.generic.boolean.invalid='%s' nyns yw gwir po fals commands.generic.double.tooBig=Re vras yw an niver entrys genowgh (%s), res yw y vos %s dhe'n moyha commands.generic.double.tooSmall=Re vyhan yw an niver entrys genowgh (%s), res yw y vos %s dhe'n lyha commands.generic.exception=Unn error ankoth hwarvosek hedre assaya performya hemm arhadow commands.generic.notFound=Arhadow ankoth. Hwilas /help rag unn rol a arhadowyow commands.generic.num.invalid=Nyns yw '%s' niver da commands.generic.num.tooBig=Re vras yw an niver entrys genowgh (%s), res yw y vos %s dhe'n moyha commands.generic.num.tooSmall=Re vyhan yw an niver entrys genowgh (%s), res yw y vos %s dhe'n lyha commands.generic.permission=Nyns eus kummyas dhis rag an arhadow ma commands.generic.player.notFound=Ny yll an gwarier-na bos kevys commands.generic.syntax=Drog arhadow syntax commands.generic.usage=Devnydh: %s commands.give.notFound=There is no such item with name %s commands.help.header=--- Displetyow folenn gweres %s a %s (/help <page>) --- commands.help.usage=/help [page|command name] commands.kick.success=%s a veu tewlys dhe-ves a'n gwari commands.kick.usage=/kick <player> [reason ...] commands.me.usage=/me <action ...> commands.message.display.incoming=%s hanasow dhis: %s commands.message.display.outgoing=Ty hanas dhe %s: %s commands.message.sameTarget=Ny yllowgh hwi danvon messach privedh dhe'gas honan! commands.message.usage=/tell <player> <private message ...> commands.op.success=Opped %s commands.op.usage=/op <player> commands.players.list=Yma %s/%s gwarioryon warlinen: commands.save.failed=Gwitha a fyllas: %s commands.save.start=Ow kwitha... commands.save.success=Duniyā kō bacāyā commands.say.usage=/say <message ...> commands.scoreboard.objectives.list.empty=There are no objectives on the scoreboard commands.scoreboard.objectives.list.entry=- %s: displays as '%s' and is type '%s' commands.scoreboard.players.add.usage=/scoreboard players add <player> <objective> <count> [dataTag] commands.scoreboard.players.enable.noTrigger=Objective %s is not a trigger commands.scoreboard.players.enable.success=Enabled trigger %s for %s commands.scoreboard.players.enable.usage=/scoreboard players enable <player> <trigger> commands.scoreboard.players.list.count=Showing %s tracked players on the scoreboard: commands.scoreboard.players.list.empty=There are no tracked players on the scoreboard commands.scoreboard.players.list.player.count=Showing %s tracked objective(s) for %s: commands.scoreboard.players.list.player.empty=Player %s has no scores recorded commands.scoreboard.players.list.usage=/scoreboard players list [name] commands.scoreboard.players.operation.invalidOperation=Invalid operation %s commands.scoreboard.players.operation.notFound=No %s score for %s found commands.scoreboard.players.operation.success=Operation applied successfully commands.scoreboard.players.operation.usage=/scoreboard players operation <targetName> <targetObjective> <operation> <selector> <objective> commands.scoreboard.players.remove.usage=/scoreboard players remove <player> <objective> <count> [dataTag] commands.scoreboard.players.reset.usage=/scoreboard players reset <player> [objective] commands.scoreboard.players.resetscore.success=Reset score %s of player %s commands.scoreboard.players.set.success=Set score of %s for player %s to %s commands.scoreboard.players.set.tagError=Could not parse dataTag, reason: %s commands.scoreboard.players.set.tagMismatch=The dataTag does not match for %s commands.scoreboard.players.set.usage=/scoreboard players set <player> <objective> <score> [dataTag] commands.scoreboard.players.test.failed=Score %s is NOT in range %s to %s commands.scoreboard.players.test.notFound=No %s score for %s found commands.scoreboard.players.test.success=Score %s is in range %s to %s commands.scoreboard.players.test.usage=/scoreboard players test <player> <objective> <min> <max> commands.scoreboard.players.usage=/scoreboard players <set|add|remove|reset|list|enable|test|operation> ... commands.scoreboard.teams.add.alreadyExists=A team with the name '%s' already exists commands.scoreboard.teams.add.displayTooLong=The display name '%s' is too long for a team, it can be at most %s characters long commands.scoreboard.teams.add.success=Added new team '%s' successfully commands.scoreboard.teams.add.tooLong=The name '%s' is too long for a team, it can be at most %s characters long commands.scoreboard.teams.add.usage=/scoreboard teams add <name> [display name ...] commands.scoreboard.teams.empty.alreadyEmpty=Team %s is already empty, cannot remove nonexistant players commands.scoreboard.teams.empty.success=Removed all %s player(s) from team %s commands.scoreboard.teams.empty.usage=/scoreboard teams empty <team> commands.scoreboard.teams.join.failure=Could not add %s player(s) to team %s: %s commands.scoreboard.teams.join.success=Added %s player(s) to team %s: %s commands.scoreboard.teams.join.usage=/scoreboard teams join <team> [player] commands.scoreboard.teams.leave.failure=Could not remove %s player(s) from their teams: %s commands.scoreboard.teams.leave.noTeam=Ny esowgh hwi yn unn para commands.scoreboard.teams.leave.success=Removed %s player(s) from their teams: %s commands.scoreboard.teams.leave.usage=/scoreboard teams leave [player] commands.scoreboard.teams.list.count=Showing %s teams on the scoreboard: commands.scoreboard.teams.list.empty=There are no teams registered on the scoreboard commands.scoreboard.teams.list.entry=- %1$s: '%2$s' has %3$s players commands.scoreboard.teams.list.player.count=Showing %s player(s) in team %s: commands.scoreboard.teams.list.player.empty=Team %s has no players commands.scoreboard.teams.list.usage=/scoreboard teams list [name] commands.scoreboard.teams.remove.success=Removed team %s commands.scoreboard.teams.remove.usage=/scoreboard teams remove <name> commands.scoreboard.teams.usage=/scoreboard teams <list|add|remove|empty|join|leave|option> ... commands.seed.success=Seed: %s commands.setblock.failed=Ny yll gorra stock commands.setblock.noChange=The block couldn't be placed commands.setblock.notFound=There is no such block with ID/name %s commands.setblock.outOfWorld=Ny yllys gorra stock a-ves dhe'n vys commands.setblock.success=Gorrys Stock commands.setblock.tagError=Data tag parsing failed: %s commands.setblock.usage=/setblock <x> <y> <z> <TileName> [dataValue] [oldBlockHandling] [dataTag] commands.spreadplayers.failure.players=Could not spread %s players around %s,%s (too many players for space - try using spread of at most %s) commands.spreadplayers.failure.teams=Could not spread %s teams around %s,%s (too many players for space - try using spread of at most %s) commands.spreadplayers.info.players=(Average distance between players is %s blocks apart after %s iterations) commands.spreadplayers.info.teams=(Average distance between teams is %s blocks apart after %s iterations) commands.spreadplayers.spreading.players=Spreading %s players %s blocks around %s,%s (min %s blocks apart) commands.spreadplayers.spreading.teams=Spreading %s teams %s blocks around %s,%s (min %s blocks apart) commands.spreadplayers.success.players=Successfully spread %s players around %s,%s commands.spreadplayers.success.teams=Successfully spread %s teams around %s,%s commands.spreadplayers.usage=/spreadplayers <x> <z> <spreadDistance> <maxRange> <respectTeams true|false> <player ...> commands.stop.start=Stoppyowth an Servyer commands.summon.failed=Unable to summon object commands.summon.outOfWorld=Cannot summon the object out of the world commands.summon.tagError=Data tag parsing failed: %s commands.testfor.success=Found %s commands.testfor.tagError=Data tag parsing failed: %s commands.testforblock.failed.data=The block at %s,%s,%s had the data value of %s (expected: %s). commands.testforblock.failed.nbt=The block at %s,%s,%s did not have the required NBT keys. commands.testforblock.failed.tile=The block at %s,%s,%s is %s (expected: %s). commands.testforblock.failed.tileEntity=The block at %s,%s,%s is not a tile entity and cannot support tag matching. commands.testforblock.outOfWorld=Cannot test for block outside of the world commands.testforblock.success=Successfully found the block at %s,%s,%s. commands.testforblock.usage=/testforblock <x> <y> <z> <TileName> [dataValue] [dataTag] commands.time.added=%s keworrys dhe'n termyn commands.time.set=Set an termyn dhe %s commands.title.success=Title command successfully executed commands.title.usage=/title <player> <title|subtitle|clear|reset|times> ... commands.title.usage.clear=/title <player> clear|reset commands.title.usage.times=/title <player> times <fadeIn> <stay> <fadeOut> commands.title.usage.title=/title <player> title|subtitle <raw json title> commands.tp.notSameDimension=Teleport karanē mēṁ asamartha khilāṛiyōṁ kō ēka hī āyāma mēṁ nahīṁ haiṁ kyōṅki commands.tp.success=Pellporthys %s dhe %s commands.tp.success.coordinates=Pellporthys %s dhe %s,%s,%s commands.unban.success=Gwarier Disemskemunys %s commands.unban.usage=/pardon <name> commands.unbanip.invalid=Hwi re entras trigva IP drog commands.unbanip.usage=/pardon-ip <address> commands.whitelist.add.success=Śvēta sūcī %s mēṁ jōṛā gayā commands.whitelist.add.usage=/whitelist add <player> commands.whitelist.disabled=Skwychya yn-mes an rolwynn commands.whitelist.enabled=Skwychya yn-fyw an rolwynn commands.whitelist.list=Kara rahē haiṁ %s (Sē bāhara %s Dēkhā) Śvētasūcībad'dha khilāṛiyōṁ: commands.whitelist.reloaded=Daskargys an rolwynn commands.whitelist.remove.usage=/whitelist remove <player> commands.worldborder.add.usage=/worldborder add <sizeInBlocks> [timeInSeconds] commands.worldborder.center.success=Set world border center to %s,%s commands.worldborder.center.usage=/worldborder center <x> <z> commands.worldborder.damage.amount.success=Set world border damage amount to %s per block (from %s per block) commands.worldborder.damage.amount.usage=/worldborder damage amount <damagePerBlock> commands.worldborder.damage.buffer.success=Set world border damage buffer to %s blocks (from %s blocks) commands.worldborder.damage.buffer.usage=/worldborder damage buffer <sizeInBlocks> commands.worldborder.damage.usage=/worldborder damage <buffer|amount> commands.worldborder.get.success=World border is currently %s blocks wide commands.worldborder.set.success=Set world border to %s blocks wide (from %s blocks) commands.worldborder.set.usage=/worldborder set <sizeInBlocks> [timeInSeconds] commands.worldborder.setSlowly.grow.success=Growing world border to %s blocks wide (up from %s blocks) over %s seconds commands.worldborder.setSlowly.shrink.success=Shrinking world border to %s blocks wide (down from %s blocks) over %s seconds commands.worldborder.usage=/worldborder <set|center|damage|warning|get> ... commands.worldborder.warning.distance.success=Set world border warning to %s blocks away (from %s blocks) commands.worldborder.warning.distance.usage=/worldborder warning distance <blocks> commands.worldborder.warning.time.success=Set world border warning to %s seconds away (from %s seconds) commands.worldborder.warning.time.usage=/worldborder warning time <seconds> commands.worldborder.warning.usage=/worldborder warning <time|distance> commands.xp.usage=/xp <amount> [player] OR /xp <amount>L [player] connect.authorizing=Owth omgelmi... connect.connecting=Ow junya gans an servyer... connect.failed=Fyllas a wrug junya gans an servyer container.beacon=Beacon container.brewing=Sav Ow Praga container.chest=Argh container.chestDouble=Argh Bras container.crafting=kreft container.creative=Dewis Tra container.dispenser=Gwerther container.dropper=Droppyer container.enchant=Gorhana container.enchant.clue=%s . . . ? container.enchant.lapis.many=%s Lapis Lazuli container.enchant.lapis.one=1 Lapis Lazuli container.enchant.level.many=%s Enchantment Levels container.enchant.level.one=1 Enchantment Level container.enderchest=Argh Diwedhek container.furnace=Fog container.hopper=Lammer Tra container.inventory=Rol container.isLocked=%s is locked! container.minecart=Balkert container.repair=Ewnhe ha Henwel container.repair.cost=Kost Hus: %1$s container.repair.expensive=Re Kostek! controls.reset=Daskor controls.resetAll=Daskor Alhwedhennow controls.title=Kontrolyow createWorld.customize.custom.baseSize=Depth Base Size createWorld.customize.custom.biomeDepthOffset=Biome Depth Offset createWorld.customize.custom.biomeDepthWeight=Biome Depth Weight createWorld.customize.custom.biomeScaleOffset=Biome Scale Offset createWorld.customize.custom.biomeScaleWeight=Biome Scale Weight createWorld.customize.custom.biomeSize=Biome Size createWorld.customize.custom.confirm1=This will overwrite your current createWorld.customize.custom.confirm2=settings and cannot be undone. createWorld.customize.custom.confirmTitle=Warning! createWorld.customize.custom.coordinateScale=Coordinate Scale createWorld.customize.custom.count=Spawn Tries createWorld.customize.custom.defaults=Defaults createWorld.customize.custom.depthNoiseScaleExponent=Depth Noise Exponent createWorld.customize.custom.depthNoiseScaleX=Depth Noise Scale X createWorld.customize.custom.depthNoiseScaleZ=Depth Noise Scale Z createWorld.customize.custom.dungeonChance=Dungeon Count createWorld.customize.custom.fixedBiome=Biome createWorld.customize.custom.heightScale=Height Scale createWorld.customize.custom.lavaLakeChance=Lava Lake Rarity createWorld.customize.custom.lowerLimitScale=Lower Limit Scale createWorld.customize.custom.mainNoiseScaleX=Main Noise Scale X createWorld.customize.custom.mainNoiseScaleY=Main Noise Scale Y createWorld.customize.custom.mainNoiseScaleZ=Main Noise Scale Z createWorld.customize.custom.minHeight=Min. Height createWorld.customize.custom.next=Next Page createWorld.customize.custom.page0=Basic Settings createWorld.customize.custom.page1=Ore Settings createWorld.customize.custom.page2=Advanced Settings (Expert Users Only!) createWorld.customize.custom.page3=Extra Advanced Settings (Expert Users Only!) createWorld.customize.custom.prev=Previous Page createWorld.customize.custom.randomize=Randomize createWorld.customize.custom.riverSize=River Size createWorld.customize.custom.seaLevel=Sea Level createWorld.customize.custom.size=Spawn Size createWorld.customize.custom.stretchY=Height Stretch createWorld.customize.custom.upperLimitScale=Upper Limit Scale createWorld.customize.custom.useCaves=Caves createWorld.customize.custom.useDungeons=Dungeons createWorld.customize.custom.useLavaLakes=Lava Lakes createWorld.customize.custom.useLavaOceans=Lava Oceans createWorld.customize.custom.useMineShafts=Mineshafts createWorld.customize.custom.useMonuments=Ocean Monuments createWorld.customize.custom.useRavines=Ravines createWorld.customize.custom.useStrongholds=Strongholds createWorld.customize.custom.useTemples=Temples createWorld.customize.custom.useVillages=Villages createWorld.customize.custom.useWaterLakes=Water Lakes createWorld.customize.custom.waterLakeChance=Water Lake Rarity createWorld.customize.flat.addLayer=Keworra gwiskas createWorld.customize.flat.editLayer=Chanjya gwiskas createWorld.customize.flat.height=bann createWorld.customize.flat.layer.bottom=Goles - %s createWorld.customize.flat.layer.top=Penn - %s createWorld.customize.flat.removeLayer=Dilea gwiskas createWorld.customize.flat.tile=Daffar an gwiskas createWorld.customize.flat.title=Personelheans an tyller marthys plat createWorld.customize.presets=Ragsettyansow createWorld.customize.presets.list=Poken ottomma nebes a wrussyn ni moy a-varr! createWorld.customize.presets.select=Usya ragsettyans createWorld.customize.presets.share=Yw hwans dhywgh kevranna agas ragsettyans gans nebonan? Usyewgh an gisten a-woles! createWorld.customize.presets.title=Dewisewgh ragsettyans death.attack.anvil=%1$s Ēka giranē nihā'ī dvārā squished kiyā gayā thā death.attack.arrow=%1$s Dvārā gōlī māra dī ga'ī %2$s death.attack.arrow.item=%1$s Dvārā gōlī māra dī ga'ī %2$s Kā upayōga karatē hu'ē %3$s death.attack.cactus=%1$s Mauta kō cubha gayā thā death.attack.cactus.player=%1$s Bhāganē kī kōśiśa kara rahā ēka kaikṭasa hai whilst mēṁ calā gayā %2$s death.attack.drown=%1$s Ḍūba death.attack.drown.player=%1$s Bhāganē kī kōśiśa kara rahā whilst ḍūba %2$s death.attack.explosion=%1$s Visphōṭa sē uṛā diyā death.attack.explosion.player=%1$s Dvārā uṛā diyā gayā thā %2$s death.attack.fall=%1$s Kaṛī mēhanata karanē kē li'ē maidāna mārā death.attack.fallingBlock=%1$s Ēka giranē blŏka dvārā kucala gayā thā death.attack.fireball=%1$s Dvārā fireballed thā %2$s death.attack.fireball.item=%1$s Dvārā fireballed thā %2$s Kā upayōga karatē hu'ē %3$s death.attack.generic=%1$s Mara gayā death.attack.inFire=%1$s Āga kī lapaṭōṁ mēṁ caṛha ga'ē death.attack.inFire.player=%1$s Laṛa whilst kī āga mēṁ calā gayā %2$s death.attack.inWall=%1$s Ēka dīvāra mēṁ ghuṭana death.attack.indirectMagic=%1$s Dvārā mārā gayā %2$s Jādū kā upayōga death.attack.indirectMagic.item=%1$s Dvārā mārā gayā %2$s Kā upayōga karatē hu'ē %3$s death.attack.lava=%1$s Lāvā mēṁ tairanē kī kōśiśa kī death.attack.lava.player=%1$s Bacanē kē li'ē lāvā mēṁ tairanē kī kōśiśa kī %2$s death.attack.lightningBolt=%1$s was struck by lightning death.attack.magic=%1$s Jādū dvārā mārā gayā death.attack.mob=%1$s Dvārā mr̥ta thā %2$s death.attack.onFire=%1$s Mauta kō jalā diyā death.attack.onFire.player=%1$s Ēka kurakurā whilst kē laṛanē kē li'ē jalā diyā gayā thā %2$s death.attack.outOfWorld=%1$s Duniyā sē bāhara gira ga'ī death.attack.player=%1$s Dvārā mr̥ta thā %2$s death.attack.player.item=%1$s Dvārā mr̥ta thā %2$s Kā upayōga karatē hu'ē %3$s death.attack.starve=%1$s Mauta kē bhūkhē death.attack.thorns=%1$s Cōṭa kī kōśiśa kara mārā gayā %2$s death.attack.thrown=%1$s Dvārā pummeled thā %2$s death.attack.thrown.item=%1$s Dvārā pummeled thā %2$s Kā upayōga karatē hu'ē %3$s death.attack.wither=%1$s Dūra sūkha death.fell.accident.generic=%1$s Ēka ucca sthāna sē gira gayā death.fell.accident.ladder=%1$s fell off a ladder death.fell.accident.vines=%1$s Kucha dākhalatā sē gira gayā death.fell.accident.water=%1$s Pānī sē bāhara gira ga'ī death.fell.assist=%1$s Dvārā gira karanē kē li'ē barbāda hō gayā thā %2$s death.fell.assist.item=%1$s Dvārā gira karanē kē li'ē barbāda hō gayā thā %2$s Kā upayōga karatē hu'ē %3$s death.fell.finish=%1$s Aba taka para gira gayā aura sē samāpta hō gayā thā %2$s death.fell.finish.item=%1$s Aba taka para gira gayā aura sē samāpta hō gayā thā %2$s Kā upayōga karatē hu'ē %3$s death.fell.killer=%1$s Girāvaṭa barbāda kiyā gayā thā deathScreen.deleteWorld=Dilea bys deathScreen.hardcoreInfo=Ny yllydh ta dasserhi yn modh kres-kales! deathScreen.leaveServer=Diberth Servyer deathScreen.quit.confirm=Owgh hwi sur bos hwans dhywgh kwytya? deathScreen.respawn=Dasserhi deathScreen.score=Skor deathScreen.title=Ty a verwis! deathScreen.title.hardcore=Gorfennys an gwari! deathScreen.titleScreen=Skrin ditel demo.day.1=This demo will last five game days, dot the best you can! demo.day.2=Dydh Dew demo.day.3=Dydh Tri demo.day.4=Dydh Peswar demo.day.5=Hemm yw agas diwettha dydh! demo.day.6=Hwi re dremenas agas pympes dydh, usyewgh F2 rag gwitha skeusen skrin a'gas gwrians demo.day.warning=Namna dhifygys yw agas termyn! demo.demoExpired=Difygys yw termyn an demo! demo.help.buy=Prena lemmyn! demo.help.fullWrapped=An demo-ma a wra durya 5 dydh a'n gwari (neb 1 our ha 40 mynysen a dermyn gwir). Checkyewgh an kowlwriansow rag hyntys! Omlowenhewgh! demo.help.inventory=Gwaska %1$s rag ygeri agas rol demo.help.jump=Lemmewgh dre waska %1$s demo.help.later=Pesya gwari! demo.help.movement=Usyowgh %1$s, %2$s, %3$s, %4$s ha'n logosen rag gwaya a-dro demo.help.movementMouse=Mirewgh a-dro der usya an logosen demo.help.movementShort=Gwayewgh dre waska %1$s, %2$s, %3$s, %4$s demo.help.title=Modh Demo Minecraft demo.remainingTime=Termyn gesys: %s demo.reminder=Difygys yw termyn an demo, gwrewgh prena an gwari rag pesya po dalleth bys nowyth! difficulty.lock.question=Are you sure you want to lock the difficulty of this world? This will set this world to always be %1$s, and you will never be able to change that again. difficulty.lock.title=Lock World Difficulty disconnect.closed=Junyans degeys disconnect.disconnected=An servyer a drehas an junyans disconnect.endOfStream=Diwedh an fros disconnect.kicked=a veu tewlys dhort an gwary disconnect.loginFailed=Omgelmy fyllys disconnect.loginFailedInfo=Omgelmy fyllys: %s disconnect.loginFailedInfo.invalidSession=Esedhek Drog (Hwilas ow dastalleth dha wari) disconnect.lost=Junyans kellys disconnect.overflow=Bommel Vanylyon Fenna disconnect.quitting=Ow qwytya disconnect.spam=Tewlys yn-mes rag spamya disconnect.timeout=Gorthyp veth enchantment.arrowDamage=Power enchantment.arrowFire=Flamm enchantment.arrowInfinite=Didhiwedhter enchantment.arrowKnockback=Hwaff enchantment.damage.all=Tynnder enchantment.damage.arthropods=Torment a Ardhropodow enchantment.damage.undead=Kessydhya enchantment.digging=Effeythadewder enchantment.durability=Ow Disdorr enchantment.fire=Gwedh Tan enchantment.fishingSpeed=Dynya enchantment.knockback=Bonkarta enchantment.level.1=I enchantment.level.10=X enchantment.level.2=II enchantment.level.3=III enchantment.level.4=IV enchantment.level.5=V enchantment.level.6=VI enchantment.level.7=VII enchantment.level.8=VIII enchantment.level.9=IX enchantment.lootBonus=Ow preydha enchantment.lootBonusDigger=Fortun enchantment.lootBonusFishing=Chons a'n Mor enchantment.oxygen=Owth Anella enchantment.protect.all=Difresyans enchantment.protect.explosion=Difresyans Tardh enchantment.protect.fall=Difresyans Kodh enchantment.protect.fire=Difresyans Tan enchantment.protect.projectile=Difresyans Deghesenn enchantment.thorns=Spern enchantment.untouching=Toch Owrlin enchantment.waterWalker=Depth Strider enchantment.waterWorker=Hegaredh Dowr entity.ArmorStand.name=Armor Stand entity.Arrow.name=Seth entity.Bat.name=Askell-groghen entity.Blaze.name=Dewi entity.Boat.name=Skath entity.Cat.name=Kath entity.CaveSpider.name=Kevnis Kav entity.Chicken.name=Yar entity.Cow.name=Bugh entity.Creeper.name=Creeper entity.EnderDragon.name=Dragon Diwedhek entity.Enderman.name=Den Diwedhek entity.Endermite.name=Endermite entity.EntityHorse.name=Margh entity.FallingSand.name=Stock Kodhow entity.Fireball.name=Tanpel entity.Ghast.name=Euth entity.Giant.name=Kowr entity.Guardian.name=Guardian entity.Item.name=Tra entity.KillerBunny.name=The Killer Bunny entity.LavaSlime.name=Kub Lava entity.Minecart.name=Balkert entity.Mob.name=Mob entity.Monster.name=Tebelvest entity.MushroomCow.name=Bugh Skavel-Gronek entity.Ozelot.name=Kath Gwyls entity.Painting.name=Liwyans entity.Pig.name=Mogh entity.PigZombie.name=Zombi Denmogh entity.PrimedTnt.name=Stock a TNT entity.Rabbit.name=Rabbit entity.Sheep.name=Davas entity.Silverfish.name=Pysk-Arhans entity.Skeleton.name=Korf eskern entity.Slime.name=Leys entity.SmallFireball.name=Byhan Tanpel entity.SnowMan.name=Golem Ergh entity.Snowball.name=Pel Ergh entity.Spider.name=Kevnis entity.Squid.name=Stifek entity.Villager.armor=Armorer entity.Villager.butcher=Butcher entity.Villager.cleric=Cleric entity.Villager.farmer=Farmer entity.Villager.fisherman=Fisherman entity.Villager.fletcher=Fletcher entity.Villager.leather=Leatherworker entity.Villager.librarian=Librarian entity.Villager.name=Trevesik entity.Villager.shepherd=Shepherd entity.Villager.tool=Tool Smith entity.Villager.weapon=Weapon Smith entity.VillagerGolem.name=Golem Hornek entity.Witch.name=Gwragh entity.WitherBoss.name=Gwedhra entity.Wolf.name=Bleydh entity.XPOrb.name=Pel Prevyans entity.Zombie.name=Zombi entity.donkey.name=Asen entity.generic.name=ankoth entity.horse.name=Margh entity.mule.name=Mul entity.skeletonhorse.name=Margh Korf eskern entity.zombiehorse.name=Margh Zombi gameMode.adventure=Modh aventur gameMode.changed=agas fit desedhans eus dihaval gameMode.creative=Modh awenek gameMode.hardcore=Modh kres-kales! gameMode.survival=Modh treusvewans generator.amplified=MOGHHYS generator.amplified.info=Argemmyn: Hepken rag delit, erhi jynn amontya galosek generator.default=Defowt generator.flat=Tyller marthys plat generator.largeBiomes=Biomys bras gui.achievements=Kowlwriansow gui.all=All gui.back=War-dhelergh gui.cancel=Hedhi gui.done=Gwrys gui.down=Yn-nans gui.no=Na gui.none=None gui.stats=Statystygyon gui.toMenu=Dehweles dhe'n skrin titel gui.up=Yn-bann gui.yes=Ea inventory.binSlot=Distrui Tra item.apple.name=Aval item.appleGold.name=Aval owrek item.armorStand.name=Armor Stand item.arrow.name=Seth item.banner.black.name=Black Banner item.banner.blue.name=Blue Banner item.banner.brown.name=Brown Banner item.banner.cyan.name=Cyan Banner item.banner.gray.name=Gray Banner item.banner.green.name=Green Banner item.banner.lightBlue.name=Light Blue Banner item.banner.lime.name=Lime Banner item.banner.magenta.name=Magenta Banner item.banner.orange.name=Orange Banner item.banner.pink.name=Pink Banner item.banner.purple.name=Purple Banner item.banner.red.name=Red Banner item.banner.silver.name=Light Gray Banner item.banner.square_bottom_left.black=Black Base Dexter Canton item.banner.square_bottom_left.blue=Blue Base Dexter Canton item.banner.square_bottom_left.brown=Brown Base Dexter Canton item.banner.square_bottom_left.cyan=Cyan Base Dexter Canton item.banner.square_bottom_left.gray=Gray Base Dexter Canton item.banner.square_bottom_left.green=Green Base Dexter Canton item.banner.square_bottom_left.lightBlue=Light Blue Base Dexter Canton item.banner.square_bottom_left.lime=Lime Base Dexter Canton item.banner.square_bottom_left.magenta=Magenta Base Dexter Canton item.banner.square_bottom_left.orange=Orange Base Dexter Canton item.banner.square_bottom_left.pink=Pink Base Dexter Canton item.banner.square_bottom_left.purple=Purple Base Dexter Canton item.banner.square_bottom_left.red=Red Base Dexter Canton item.banner.square_bottom_left.silver=Light Gray Base Dexter Canton item.banner.square_bottom_left.white=White Base Dexter Canton item.banner.square_bottom_left.yellow=Yellow Base Dexter Canton item.banner.square_bottom_right.black=Black Base Sinister Canton item.banner.square_bottom_right.blue=Blue Base Sinister Canton item.banner.square_bottom_right.brown=Brown Base Sinister Canton item.banner.square_bottom_right.cyan=Cyan Base Sinister Canton item.banner.square_bottom_right.gray=Gray Base Sinister Canton item.banner.square_bottom_right.green=Green Base Sinister Canton item.banner.square_bottom_right.lightBlue=Light Blue Base Sinister Canton item.banner.square_bottom_right.lime=Lime Base Sinister Canton item.banner.square_bottom_right.magenta=Magenta Base Sinister Canton item.banner.square_bottom_right.orange=Orange Base Sinister Canton item.banner.square_bottom_right.pink=Pink Base Sinister Canton item.banner.square_bottom_right.purple=Purple Base Sinister Canton item.banner.square_bottom_right.red=Red Base Sinister Canton item.banner.square_bottom_right.silver=Light Gray Base Sinister Canton item.banner.square_bottom_right.white=White Base Sinister Canton item.banner.square_bottom_right.yellow=Yellow Base Sinister Canton item.banner.square_top_left.black=Black Chief Dexter Canton item.banner.square_top_left.red=Red Chief Dexter Canton item.banner.white.name=White Banner item.banner.yellow.name=Yellow Banner item.bed.name=Gweli item.beefCooked.name=Tregh kig item.beefRaw.name=Kig bewin kriv item.blazePowder.name=Polter-Dewi item.blazeRod.name=Gwelen Dewi item.boat.name=Skath item.bone.name=Askorn item.book.name=Lyver item.bootsChain.name=Eskisyow Chayn item.bootsCloth.name=Eskisyow Ledher item.bootsDiamond.name=Eskisyow Adamant item.bootsGold.name=Eskisyow Owrek item.bootsIron.name=Eskisyow Hornek item.bow.name=Gwarak item.bowl.name=Bolla item.bread.name=Bara item.brewingStand.name=Sav Ow Praga item.brick.name=Bryck item.bucket.name=Kelorn item.bucketLava.name=Kelorn lava item.bucketWater.name=Kelorn dowr item.cake.name=Tesen item.canBreak=Can break: item.canPlace=Can be placed on: item.carrotGolden.name=Karetys Owrek item.carrotOnAStick.name=Karetysen war unn Gwelen item.carrots.name=Karetysen item.cauldron.name=Chek item.charcoal.name=Glowbrenn item.chestplateChain.name=Brestplat Chayn item.chestplateCloth.name=Pows Ledher item.chestplateDiamond.name=Brestplat Adamant item.chestplateGold.name=Brestplat Owrek item.chestplateIron.name=Brestplat Hornek item.chickenCooked.name=Kig yar kegys item.chickenRaw.name=Kig yar kriv item.clay.name=Pri item.clock.name=Klock item.coal.name=Glow item.comparator.name=Hevelydh Menrudh item.compass.name=Mornaswydh item.cookie.name=Tesen Gales item.diamond.name=Adamant item.diode.name=Gul arta Menrudh item.doorAcacia.name=Acacia Door item.doorBirch.name=Birch Door item.doorDarkOak.name=Dark Oak Door item.doorIron.name=Daras Hornek item.doorJungle.name=Jungle Door item.dyePowder.black.name=Ynk Sagh item.dyePowder.blue.name=Lapis Lazuli item.dyePowder.brown.name=Fav Kokoa item.dyePowder.cyan.name=Liw Glaswyrdh item.dyePowder.gray.name=Liw Loos item.dyePowder.green.name=Kaktus Gwyrdh item.dyePowder.lightBlue.name=Liw Skav Blou item.dyePowder.lime.name=Liw Limaval item.dyePowder.magenta.name=Liw Majenta item.dyePowder.orange.name=Liw Rudhvelyn item.dyePowder.pink.name=Liw Rudhwynn item.dyePowder.purple.name=Liw Purpur item.dyePowder.red.name=Rosen Rudh item.dyePowder.silver.name=Liw Skav Loos item.dyePowder.white.name=Godhes Eskern item.dyePowder.yellow.name=Dans Lew Melyn item.dyed=Liwek item.egg.name=Oy item.emerald.name=Gwyrven item.emptyMap.name=Mappa Gwag item.emptyPotion.name=Bottel a Dowr item.enchantedBook.name=Lyver Gorhanek item.enderPearl.name=Perl Diwedhek item.expBottle.name=Bottel a Prevyans item.eyeOfEnder.name=Lagas a Diwedhek item.feather.name=Pluven item.fermentedSpiderEye.name=Lagas Kevnis Kothhek item.fireball.name=Diskargans Tan item.fireworks.flight=Neyjweyth: item.fireworks.name=Fusen Tanweythen item.fireworksCharge.black=Du item.fireworksCharge.blue=Blou item.fireworksCharge.brown=Gell item.fireworksCharge.customColor=Maner item.fireworksCharge.cyan=Glaswyrdh item.fireworksCharge.fadeTo=Disliwa dhe item.fireworksCharge.flicker=Terlentri item.fireworksCharge.gray=Loos item.fireworksCharge.green=Gwyrdh item.fireworksCharge.lightBlue=Skav Blou item.fireworksCharge.lime=Limaval item.fireworksCharge.magenta=Majenta item.fireworksCharge.name=Steren Tanweythen item.fireworksCharge.orange=Rudhvelyn item.fireworksCharge.pink=Rudhwynn item.fireworksCharge.purple=Purpur item.fireworksCharge.red=Rudh item.fireworksCharge.silver=Skav Loos item.fireworksCharge.trail=Lergh item.fireworksCharge.type=Shap Ankoth item.fireworksCharge.type.0=Pel Byhan item.fireworksCharge.type.1=Pel Bras item.fireworksCharge.type.2=Shapyek-Steren item.fireworksCharge.type.3=Shapyek-Creeper item.fireworksCharge.type.4=Tardh item.fireworksCharge.white=Gwynn item.fireworksCharge.yellow=Melyn item.fish.clownfish.raw.name=Lordenbysk item.fish.cod.cooked.name=Pysk Keginys item.fish.cod.raw.name=Pysk Kriv item.fish.pufferfish.raw.name=Hwythyasbysk item.fish.salmon.cooked.name=Ehek Keginys item.fish.salmon.raw.name=Ehek Kriv item.fishingRod.name=Gwelen Bsykessa item.flint.name=Kelester item.flintAndSteel.name=Kelester ha Dur item.flowerPot.name=Pott Bleujenn item.frame.name=Fram item.ghastTear.name=Dager Gathorn item.glassBottle.name=Bottel Gweder item.goldNugget.name=Nogen Owr item.hatchetDiamond.name=Bool Adamant item.hatchetGold.name=Bool Owrek item.hatchetIron.name=Bool Hornek item.hatchetStone.name=Bool Men item.hatchetWood.name=Bool Prennek item.helmetChain.name=Basnet Chayn item.helmetCloth.name=Kappa Ledher item.helmetDiamond.name=Basnet Adamant item.helmetGold.name=Basnet Owrek item.helmetIron.name=Basnet Hornek item.hoeDiamond.name=Kravel Adamant item.hoeGold.name=Kravel Owrek item.hoeIron.name=Kravel Hornek item.hoeStone.name=Kravel Men item.hoeWood.name=Kravel Prennek item.horsearmordiamond.name=Arvwisk Margh Adamant item.horsearmorgold.name=Arvwisk Margh Owrek item.horsearmormetal.name=Arvwisk Margh Hornek item.ingotGold.name=Torth Owr item.ingotIron.name=Torth Horn item.leash.name=Lesh item.leather.name=Ledher item.leaves.name=Del item.leggingsChain.name=Lodrow Chayn item.leggingsCloth.name=Lavrek Ledher item.leggingsDiamond.name=Lodrow Adamant item.leggingsGold.name=Lodrow Owrek item.leggingsIron.name=Lodrow Hornek item.magmaCream.name=Dehen Karrek Deudh item.map.name=Mappa item.melon.name=Melon item.milk.name=Leth item.minecart.name=Balkert item.minecartChest.name=Balkert gans Argh item.minecartCommandBlock.name=Balkert gans Stock Arhadow item.minecartFurnace.name=Balkert gans Fog item.minecartHopper.name=Balkert gans Lammer item.minecartTnt.name=Balkert gans TNT item.monsterPlacer.name=Bywhe item.mushroomStew.name=Stywya Skavel-Gronek item.nameTag.name=Libel Hanow item.netherStalkSeeds.name=Losow Annown item.netherStar.name=Sterenn Annown item.netherbrick.name=Bryck Annown item.netherquartz.name=Kanndir Annown item.painting.name=Lymnans item.paper.name=Paper item.pickaxeDiamond.name=Pigel Adamant item.pickaxeGold.name=Pigel Owrek item.pickaxeIron.name=Pigel Hornek item.pickaxeStone.name=Pigel Men item.pickaxeWood.name=Pigel Prennek item.porkchopCooked.name=Kig mogh Keginys item.porkchopRaw.name=Kig mogh Kriv item.potato.name=Patatys item.potatoBaked.name=Patatys Pebys item.potatoPoisonous.name=Patatys Gwenonek item.potion.name=Diwas item.prismarineCrystals.name=Prismarine Crystals item.prismarineShard.name=Prismarine Shard item.pumpkinPie.name=Hogen Pompyon item.record.11.desc=C418 - 11 item.record.13.desc=C418 - 13 item.record.blocks.desc=C418 - blocks item.record.cat.desc=C418 - cat item.record.chirp.desc=C418 - chirp item.record.far.desc=C418 - far item.record.mall.desc=C418 - mall item.record.mellohi.desc=C418 - mellohi item.record.name=Plasenn Ilow item.record.stal.desc=C418 - stal item.record.strad.desc=C418 - strad item.record.wait.desc=C418 - wait item.record.ward.desc=C418 - ward item.redstone.name=Menrudh item.reeds.name=Gwelynni Sugra item.rottenFlesh.name=Kig Poder item.ruby.name=Rudhemm item.saddle.name=Diber item.seeds.name=Has item.seeds_melon.name=Has melon item.seeds_pumpkin.name=Has Pompyon item.shears.name=Gwelsow item.shovelDiamond.name=Pal Adamant item.shovelGold.name=Pal Owrek item.shovelIron.name=Pal Hornek item.shovelStone.name=Pal Men item.shovelWood.name=Pal Prennek item.sign.name=Arwodh item.skull.char.name=Penn item.skull.creeper.name=Penn Creeper item.skull.player.name=Penn %s item.skull.skeleton.name=Klopen Korf eskern item.skull.wither.name=Gwedhra Klopen Korf eskern item.skull.zombie.name=Penn Zombi item.slimeball.name=Leyspel item.snowball.name=Pel a ergh item.speckledMelon.name=Melon Ow Terlentri item.spiderEye.name=Lagas Kevnis item.stick.name=Gwelen item.string.name=Korden item.sugar.name=Sugra item.sulphur.name=Polter-gonn item.swordDiamond.name=Kledha Adamant item.swordGold.name=Kledha Owrek item.swordIron.name=Kledha Hornek item.swordStone.name=Kledha Men item.swordWood.name=Kledha Prennek item.unbreakable=Disdorradow item.wheat.name=Gwaneth item.writingBook.name=Lyver ha Pulven item.writtenBook.name=Lyver Skrifek item.yellowDust.name=Ponn Mengolowi itemGroup.brewing=Ow Braga itemGroup.buildingBlocks=Stockys Drehevyans itemGroup.combat=Arvow itemGroup.decorations=Stockys Afinus itemGroup.food=Viktuals itemGroup.inventory=Rol Treusvewans itemGroup.materials=Daffar itemGroup.misc=Traow a bub sort itemGroup.redstone=Menrudh itemGroup.search=Hwilas Traow itemGroup.tools=Toul itemGroup.transportation=Treusporth key.attack=Omsettya/Distrui key.back=Mos War-Dhelergh key.categories.gameplay=Gameplay key.categories.inventory=Rol key.categories.misc=A Bub Sort key.categories.movement=Gwayans key.categories.multiplayer=Liesgwarier key.categories.stream=Streaming key.categories.ui=Gwari Ynterfas key.chat=Ygeri Keskowsva key.command=Ygeri Arhadow key.drop=Droppya Tra key.forward=Mos Yn-Rag key.fullscreen=Toggle Fullscreen key.hotbar.1=Hedhas Snell Le 1 key.hotbar.2=Hedhas Snell Le 2 key.hotbar.3=Hedhas Snell Le 3 key.hotbar.4=Hedhas Snell Le 4 key.hotbar.5=Hedhas Snell Le 5 key.hotbar.6=Hedhas Snell Le 6 key.hotbar.7=Hedhas Snell Le 7 key.hotbar.8=Hedhas Snell Le 8 key.hotbar.9=Hedhas Snell Le 9 key.inventory=Rol key.jump=Lamma key.left=Mos Kledh key.mouseButton=Boton %1$s key.pickItem=Dewis stock key.playerlist=Gul rol a warioryon key.right=Mos Dyhow key.screenshot=Sesya Skrin-Imach key.smoothCamera=Skwychya Kamera Cinemasek key.sneak=Skolkya key.spectatorOutlines=Highlight Players (Spectators) key.sprint=Ponya key.streamCommercial=Show Stream Commercials key.streamPauseUnpause=Pause/Unpause Stream key.streamStartStop=Start/Stop Stream key.streamToggleMic=Push To Talk/Mute key.togglePerspective=Skwychya Gologva key.use=Usya Tra/Gorra Stock lanServer.otherPlayers=Settyansow rag Gwarioryon Erel lanServer.scanning=Arhwilyansow rag gwariow war dha rosweyth teythyek lanServer.start=Dalleth bys LAN lanServer.title=Bys LAN language.code=kw_GB language.name=Kernewek language.region=Kernow mcoServer.title=Bys Warlinen Minecraft menu.convertingLevel=Ow treylya an bys menu.disconnect=Disjunya menu.game=Rol Wari menu.generatingLevel=Ow tinythi an bys menu.generatingTerrain=Ow trehevel an tirwedh menu.loadingLevel=Ow karga an bys menu.multiplayer=Liesgwarier menu.online=Gwlaskordhow Minecraft menu.options=Dewisyow... menu.playdemo=Gwari Bys Demo menu.quit=Kwytya menu.resetdemo=Dassettya Bys Demo menu.respawning=Ow tasserhi menu.returnToGame=Dehweles dhe'n gwari menu.returnToMenu=Gwitha ha kwytya dhe ditel menu.shareToLan=Ygeri dhe LAN menu.simulating=Ow simulatya an bys rag tecken menu.singleplayer=Unn warier menu.switchingLevel=Ow skwychella bysow merchant.deprecated=Trade something else to unlock! mount.onboard=Press %1$s to dismount multiplayer.connect=Junya multiplayer.downloadingStats=Owth iskarga statystygyon ha kowlwriansow... multiplayer.downloadingTerrain=Owth iskarga Tirwedh multiplayer.info1=Nyns yw Minecraft Liesgwarier gorfennys hwath, mes yma multiplayer.info2=tamm previ a-varr gwallek ow hwarvos. multiplayer.ipinfo=Entrewgh IP servyer rag junya ganso: multiplayer.player.joined=%s aangesluit by die spel multiplayer.player.left=gesys an fit multiplayer.stopSleeping=Gas an Gwely multiplayer.texturePrompt.line1=Ma'n servyer ow comendya devnydh fardel gwiasedh personel. multiplayer.texturePrompt.line2=A via da genowgh y iskarga ha'y lea yn awtomatek? multiplayer.title=Gwari Liesgwarier options.advancedButton=Sedhesow Gwydhyow Avonsys... options.advancedOpengl=OpenGL avoncys options.advancedVideoTitle=Sedhesow Gwydhyow Avonsys options.anaglyph=Anaglyf 3D options.ao=Golowyans leven options.ao.max=Ughboynt options.ao.min=Ispoynt options.ao.off=MAROW options.chat.color=Liwyow options.chat.height.focused=Uhelder Fogellys options.chat.height.unfocused=Uhelder Disfogellys options.chat.links=Kevrennow gwias options.chat.links.prompt=Lostleverel war gevrennow options.chat.opacity=Disklerder options.chat.scale=Skeul options.chat.title=Settyansow keskows... options.chat.visibility=Keskows options.chat.visibility.full=Diskwedhys options.chat.visibility.hidden=Kudhys options.chat.visibility.system=Gorhemynnow hepken options.chat.width=Lester options.controls=Kontrolyow... options.difficulty=Kaletter options.difficulty.easy=Es options.difficulty.hard=Kales options.difficulty.hardcore=Marthys kales options.difficulty.normal=Usadow options.difficulty.peaceful=Hebask options.farWarning1=Leans a Java 64-byt yw komendys options.farWarning2=rag an pelder rendra 'pell' (yma dhywgh 32-byt) options.fboEnable=Galosegi FBOs options.forceUnicodeFont=Nerth Font Unicode options.fov=Gwel a wolok options.fov.max=Quake Pro options.fov.min=Usadow options.framerateLimit=Ugh-Kevradh Fram options.framerateLimit.max=Heb Finweth options.fullscreen=Skrin leun options.gamma=Splannder options.gamma.max=Splann options.gamma.min=Tewal options.graphics=Grafek options.graphics.fancy=Sians options.graphics.fast=Uskis options.guiScale=Skeul an GUI options.guiScale.auto=Awto options.guiScale.large=Bras options.guiScale.normal=Usadow options.guiScale.small=Byhan options.hidden=Kudh options.invertMouse=Mirour Logosen options.language=Yeth options.mipmapLevels=Nivelyow Mipmap options.modelPart.hat=Hatt options.modelPart.jacket=Jerkyn options.multiplayer.title=Settyansow liesgwarier... options.music=Ilow options.off=Marow options.on=Bew options.particles=Perthyglow options.particles.all=Oll options.particles.decreased=Iselhes options.particles.minimal=Ispoyntel options.performanceButton=Sedhesow Performans Gwydhyow... options.performanceVideoTitle=Sedhesow Performans Gwydhyow options.postButton=Sedhesow Post-Argerdhes... options.postProcessEnable=Galosegi Post-Argerdhes options.postVideoTitle=Sedhesow Post-Argerdhes options.qualityButton=Sedhesow Kwalita Gwydhyow... options.qualityVideoTitle=Sedhesow Kwalita Gwydhyow options.renderClouds=Kommol options.renderDistance=Pelder rendra options.renderDistance.far=Pell options.renderDistance.normal=Usadow options.renderDistance.short=Kot options.renderDistance.tiny=Munys options.resourcepack=Kuntellow Asnodhow... options.saturation=Leunder options.sensitivity=Sensytyvita options.sensitivity.max=TOOTH GOLOW!!! options.sensitivity.min=*delevans* options.snooper=Ri kummyas dhe dhanvon options.snooper.desc=Hwans yw dhyn kuntel kedhlow a-dro dhe'gas jynn rag gwellhe Minecraft dre wodhvos an pyth a yllyn ni skoodhya ha ple'ma an brassa kudynnow. Dihanow yn tien yw oll an kedhlow-na, hag y hyllir y weles a-woles. Dedhewi a wren na vynnyn ni gul tra dhrog vyth gans an data-ma, mes mar kwrewgh hwi ervira erbynn hemma, gwrewgh omglewes frank dh'y dhialosegi! options.snooper.title=Kuntellans a gedhlow an jynn options.snooper.view=Settyansow kuntellans kedhlow... options.sound=Son options.sounds=Ilow ha Sonyow... options.sounds.title=Ilow ha Dewisyow Son options.stream.changes=You may need to restart your stream for these changes to take place. options.stream.chat.enabled=Enable options.stream.chat.enabled.always=Always options.stream.chat.enabled.never=Never options.stream.chat.enabled.streaming=Whilst Streaming options.stream.chat.title=Twitch Chat Settings options.stream.chat.userFilter=User Filter options.stream.chat.userFilter.all=All Viewers options.stream.chat.userFilter.mods=Moderators options.stream.chat.userFilter.subs=Subscribers options.stream.compression=Compression options.stream.compression.high=High options.stream.compression.low=Low options.stream.compression.medium=Medium options.stream.estimation=Estimated resolution: %sx%s options.stream.fps=Framerate options.stream.ingest.reset=Reset Preference options.stream.ingest.title=Twitch Broadcast Servers options.stream.ingestSelection=Broadcast Server List options.stream.kbps=Bandwidth options.stream.mic_toggle.talk=Talk options.stream.sendMetadata=Send Metadata options.stream.systemVolume=System Volume options.title=Etholyow options.touchscreen=Modh Tochskin options.video=Sedhesow Gwydhyow... options.videoTitle=Sedhesow Gwydhyow options.viewBobbing=Gwayans an penn options.visible=Gweladow options.vsync=Usya VSync potion.absorption=Avaśōṣaṇa potion.absorption.postfix=Diwas a Lenkiheans potion.blindness=Dellni potion.blindness.postfix=Diwas a Delni potion.confusion=Penn-dro potion.confusion.postfix=Diwas a Penn-dro potion.damageBoost=Krevder potion.damageBoost.postfix=Diwas a Nerth potion.digSlowDown=Lent Ow Palas potion.digSlowDown.postfix=Diwas a Soghder potion.digSpeed=Hast potion.digSpeed.postfix=Diwas a Hast potion.effects.whenDrank=Ēplā'iḍa kaba: potion.empty=Heb Effeythyow potion.fireResistance=Defens Tan potion.fireResistance.postfix=Diwas a Defens Tan potion.harm=Damach Desempis potion.harm.postfix=Diwas a Ow Shyndya potion.heal=Yehes Desempis potion.heal.postfix=Diwas a Ow Sawya potion.healthBoost=Kenertha Yehes potion.healthBoost.postfix=Diwas a Kenertha Yehes potion.hunger=Nown potion.hunger.postfix=Diwas a Nown potion.invisibility=Anweladowder potion.invisibility.postfix=Diwas a Anweladewder potion.jump=Kenertha Lamm potion.jump.postfix=Diwas a Ow Lamma potion.moveSlowdown=Lenter potion.moveSlowdown.postfix=Diwas a Lentter potion.moveSpeed=Tooth potion.moveSpeed.postfix=Diwas a Uskister potion.nightVision=Posna potion.nightVision.postfix=Diwas a Golok Nosweyth potion.poison=Gwenon potion.poison.postfix=Diwas a Ponsa potion.potency.1=II potion.potency.2=III potion.potency.3=IV potion.prefix.acrid=Trenk potion.prefix.artless=Digreft potion.prefix.awkward=Kledhek potion.prefix.bland=Anvlasus potion.prefix.bulky=Bras potion.prefix.bungling=Kledhekter potion.prefix.buttered=Blonegek potion.prefix.charming=Ow Husa potion.prefix.clear=Kler potion.prefix.cordial=Kolonnek potion.prefix.dashing=Ow Fyski potion.prefix.debonair=Deboner potion.prefix.diffuse=Lesrannys potion.prefix.elegant=Fin potion.prefix.fancy=Sians potion.prefix.flat=Platt potion.prefix.foul=Hager potion.prefix.grenade=Lagya potion.prefix.gross=Divlas potion.prefix.harsh=Asper potion.prefix.milky=Lethek potion.prefix.mundane=Aneffeythus potion.prefix.odorless=Heb Eth potion.prefix.potent=Galosek potion.prefix.rank=Mosek potion.prefix.refined=Fin potion.prefix.smooth=Smodh potion.prefix.sparkling=Gwryhonek potion.prefix.stinky=Mosegi potion.prefix.suave=Melgennek potion.prefix.thick=Tew potion.prefix.thin=Gwri potion.prefix.uninteresting=Andhidheurek potion.regeneration=Dastineythyans potion.regeneration.postfix=Diwas a Dastinytheans potion.resistance=Defens potion.resistance.postfix=Diwas a Defens potion.saturation=Leunder potion.saturation.postfix=Diwas a Leunder potion.waterBreathing=Anella Yn-dann Dhowr potion.waterBreathing.postfix=Diwas a Anella Yn-dann Dhowr potion.weakness=Gwannder potion.weakness.postfix=Diwas a Gwander potion.wither=Gwedhra potion.wither.postfix=Diwas a Breyna resourcePack.available.title=Kavadow Kuntellow Asnodhow resourcePack.folderInfo=(Yahām̐ plēsa sansādhana paika fā'ilōṁ) resourcePack.openFolder=Lk resourcePack.selected.title=Dewisys Kuntellow Asnodhow resourcePack.title=Dewis Kuntellow Asnodhow screenshot.failure=Ny Allas Difres Skrin-Imach: %s screenshot.success=Skrin-Imach Difresys Avel %s selectServer.add=Keworra servyer selectServer.defaultName=Servyer Minecraft selectServer.delete=Dilea selectServer.deleteButton=Dilea selectServer.deleteQuestion=Owgh hwi sur bos hwans dhywgh removya an servyer-ma? selectServer.deleteWarning=a vydh kellys rag nevra! (Hireth!) selectServer.direct=Junya yn Tidro selectServer.edit=Chanjya selectServer.empty=Gwag selectServer.hiddenAddress=(Kudhys) selectServer.refresh=Daskarga selectServer.select=Junya an Servyer selectServer.title=Dewisewgh servyer selectWorld.allowCommands=Alowa hygow fals: selectWorld.allowCommands.info=Gorhemynnow kepar ha /gamemode, /xp selectWorld.bonusItems=Argh vonus: selectWorld.cheats=Hyg selectWorld.conversion=Res ew y dreylya! selectWorld.create=Gwruthyl bys nowyth selectWorld.createDemo=Gwari bys demo nowyth selectWorld.customizeType=Personelhe selectWorld.delete=Dilea selectWorld.deleteButton=Dilea selectWorld.deleteQuestion=Owgh hwi sur bos hwans dhywgh dilea an bys-ma? selectWorld.deleteWarning=kellys y fedh bys vykken! (Termyn hir ew!) selectWorld.empty=gwag selectWorld.enterName=Hanow an Bys selectWorld.enterSeed=Hasen rag dinethor an bys selectWorld.gameMode=Modh an Gwari selectWorld.gameMode.adventure=Aneth selectWorld.gameMode.adventure.line2=bos keworrys po diles selectWorld.gameMode.creative=Awenek selectWorld.gameMode.creative.line2=distrui stockys a-dhesempis selectWorld.gameMode.hardcore=Marthys kales selectWorld.gameMode.hardcore.line2=kaletter, hag unn vewnans yn unnik selectWorld.gameMode.survival=Treusvewans selectWorld.gameMode.survival.line1=Hwilas asnodhow, krefta, kavos selectWorld.gameMode.survival.line2=nivelyow, yehes ha nown selectWorld.hardcoreMode=Marthys kales: selectWorld.hardcoreMode.info=Diles vydh an bys wosa mernans selectWorld.mapFeatures=Dinethi strethurow: selectWorld.mapFeatures.info=Trevow, dorvahow etc selectWorld.mapType=Ehen an bys: selectWorld.mapType.normal=Usadow selectWorld.moreWorldOptions=Moy etholyow a'n bys... selectWorld.newWorld=Bys nowyth selectWorld.newWorld.copyOf=Dasskrif a %s selectWorld.recreate=Daskwruthyl selectWorld.rename=Dashenwel selectWorld.renameButton=Dashenwel selectWorld.renameTitle=Dashenwel an bys selectWorld.resultFolder=Y fedh gwithys en: selectWorld.seedInfo=Gasa gwag rag hasen jonsus selectWorld.select=Gwary an nor dewisys selectWorld.title=Dewis Bys selectWorld.world=Bys sign.edit=Edit sign message soundCategory.ambient=Ayrgylgh/Kerhynnedh soundCategory.block=Stockys soundCategory.hostile=Kroaduryon Eskarek soundCategory.master=Dalhedh Mester soundCategory.music=Ilow soundCategory.neutral=Kroaduryon Kowethek soundCategory.player=Gwarioryon soundCategory.record=Kist Ilowek/Stockys Noten soundCategory.weather=Awel stat.animalsBred=Animals Bred stat.blocksButton=Stockys stat.boatOneCm=Pelder gans Skath stat.breakItem=%1$s Skwithys stat.climbOneCm=Distance Climbed stat.craftItem=%1$s Kreftys stat.crafted=Trevethow Kreftys stat.createWorld=Sansārōṁ banāyā stat.crouchOneCm=Distance Crouched stat.damageDealt=Damach Bargynnys stat.damageTaken=Damach Tannys stat.deaths=Niverow a Mernansow stat.depleted=Trevethow Skwithys stat.diveOneCm=Distance Dove stat.drop=Traow Droppys stat.entityKilledBy=%s killed you %s time(s) stat.entityKilledBy.none=You have never been killed by %s stat.entityKills=You killed %s %s stat.entityKills.none=You have never killed %s stat.fallOneCm=Distance Fallen-English Pelder Kodha- Cornish stat.fishCaught=Pysk Kachys stat.flyOneCm=Pelder Kelyon stat.generalButton=Ollgemmyn stat.horseOneCm=Distance by Horse stat.itemsButton=Traow stat.joinMultiplayer=Junyow Liesgwarier stat.jump=Lammow stat.junkFished=Atal Pyskessys stat.leaveGame=Gwario Kwyt stat.loadWorld=Difresow Kargys stat.mineBlock=%1$s Palasys stat.minecartOneCm=Pelder gans Balkert stat.mined=Trevethow Palasys stat.mobKills=Ladhow Mob stat.mobsButton=Mobs stat.pigOneCm=Pelder gans Hogh stat.playOneMinute=Mynysennow Gwarys stat.playerKills=Ladhow Gwarier stat.sprintOneCm=Distance Sprinted stat.startGame=Trevethow Gwarys stat.swimOneCm=Pelder Neuvya/ Distance Swum stat.talkedToVillager=Talked to Villagers stat.timeSinceDeath=Since Last Death stat.tradedWithVillager=Traded with Villagers stat.treasureFished=Tresor Pyskessys stat.useItem=%1$s Devnydhys stat.used=Trevethow Devnydhys stat.walkOneCm=Pelder Kerdhes/ Distance Walked stats.tooltip.type.achievement=Kowlwrians stats.tooltip.type.statistic=Statystyk tile.activatorRail.name=Hyns horn Bywheydh tile.anvil.intact.name=Anwan tile.anvil.name=Anwan tile.anvil.slightlyDamaged.name=Ydhyl Shyndys Anwan tile.anvil.veryDamaged.name=Fest Shyndys Anwan tile.barrier.name=Barrier tile.beacon.name=Golowva tile.beacon.primary=Nerth Kynsa tile.beacon.secondary=Nerth Nessa tile.bed.name=Gweli tile.bed.noSleep=Ny yllowgh hwi koska marnas yn nos tile.bed.notSafe=Ny yllowgh hwi powes lemmyn, yma tebelvestes yn ogas tile.bed.notValid=Dha gweli chi yw fowtow po lettyek tile.bed.occupied=An gweli ma yw kavenedhiek tile.bedrock.name=doar izal tile.blockCoal.name=Stock a Glow tile.blockDiamond.name=Stock a Adamant tile.blockEmerald.name=Stock a Gwyrven tile.blockGold.name=Stock a Owr tile.blockIron.name=Stock a Hornek tile.blockLapis.name=Stock a Lapis Lazuli tile.blockRedstone.name=Stock a Menrudh tile.bookshelf.name=Argh lyvrow tile.brick.name=Bryckys tile.button.name=Boton tile.cactus.name=Kaktus tile.cake.name=Tesen tile.carrots.name=Karetys tile.cauldron.name=Kawdarn tile.chest.name=Argh tile.chestTrap.name=Argh Maglenek tile.clay.name=Pri tile.clayHardened.name=Pri Kalesek tile.clayHardenedStained.black.name=Kālā dāga klē tile.clayHardenedStained.blue.name=Blåttmålat Clay tile.clayHardenedStained.brown.name=Brun målat Clay tile.clayHardenedStained.cyan.name=Cyan Målat Clay tile.clayHardenedStained.gray.name=Gray Stained Clay tile.clayHardenedStained.green.name=Grön Stained Clay tile.clayHardenedStained.lightBlue.name=Ljusblå målat Clay tile.clayHardenedStained.lime.name=Lime målat Clay tile.clayHardenedStained.magenta.name=Magenta Stained Clay tile.clayHardenedStained.orange.name=Orange Stained Clay tile.clayHardenedStained.pink.name=Rosa målat Clay tile.clayHardenedStained.purple.name=Lila målat Clay tile.clayHardenedStained.red.name=Lāla dāga klē tile.clayHardenedStained.silver.name=Ljusgrå målat Clay tile.clayHardenedStained.white.name=Vitlaserad Clay tile.clayHardenedStained.yellow.name=Gul målat Clay tile.cloth.black.name=Gwlan Du tile.cloth.blue.name=Gwelen Blou tile.cloth.brown.name=Gwelan Gell tile.cloth.cyan.name=Gwelen Glaswyrdh tile.cloth.gray.name=Gwelen Loos tile.cloth.green.name=Gwelen Gwyrdh tile.cloth.lightBlue.name=Gwelen Skav Blou tile.cloth.lime.name=Gwelen Limaval tile.cloth.magenta.name=Gwelen Majenta tile.cloth.name=Gwelen tile.cloth.orange.name=Gwelen Rudhvelyn tile.cloth.pink.name=Gwelen Rudhwynn tile.cloth.purple.name=Gwelen Purpur tile.cloth.red.name=Gwlan Rudh tile.cloth.silver.name=Gwelen Skav Loos tile.cloth.white.name=Gwelen tile.cloth.yellow.name=Gwelen Melyn tile.cobbleWall.mossy.name=Kewniek Fos Men Rond tile.cobbleWall.normal.name=Fos Men Rond tile.cocoa.name=Kokoa tile.commandBlock.name=Stock Arhadow tile.crops.name=Trevasow tile.daylightDetector.name=Sensour Golow Dydh tile.deadbush.name=Prysken Marow tile.detectorRail.name=Hyns horn Helerhel tile.dirt.coarse.name=Coarse Dirt tile.dirt.default.name=Mostedhes tile.dirt.name=Dirt tile.dirt.podzol.name=Podsol tile.dispenser.name=Lesrannell tile.doorIron.name=Daras Hornek tile.doorWood.name=Daras Prennek tile.doublePlant.fern.name=Redenen Bras tile.doublePlant.grass.name=Gwels-Hir Dewblek tile.doublePlant.rose.name=Prysken Ros tile.doublePlant.sunflower.name=Howlvleujen tile.dragonEgg.name=Oy Dragon tile.dropper.name=Droppyer tile.enchantmentTable.name=Moos Hus tile.endPortalFrame.name=Porth Diwedh tile.enderChest.name=Argh Diwedhek tile.farmland.name=Bargen tir tile.fence.name=Kloos tile.fenceGate.name=Yet Foos tile.fenceIron.name=Prennyer Hornek tile.fire.name=Tan tile.flower1.dandelion.name=Dans Lew tile.flower1.name=Bleujen tile.flower2.allium.name=Keninen tile.flower2.blueOrchid.name=Tegyrinen Blou tile.flower2.houstonia.name=Arlodhesow Krener tile.flower2.name=Bleujen tile.flower2.oxeyeDaisy.name=Boreles tile.flower2.poppy.name=Myll tile.flower2.tulipOrange.name=Bleujen Tulyfant Rudhvelyn tile.flower2.tulipPink.name=Bleujen Tulyfant Gwynnrudh tile.flower2.tulipRed.name=Bleujen Tulyfant Rudh tile.flower2.tulipWhite.name=Bleujen Tulyfant Gwynn tile.furnace.name=Fog tile.glass.name=Gweder tile.goldenRail.name=Hyns horn Nerthek tile.grass.name=Stock a wels tile.gravel.name=Grow tile.hayBlock.name=Sūkhī ghāsa gaṭharī tile.hellrock.name=Karrek Annown tile.hellsand.name=Tewes Enev tile.hopper.name=Lammer tile.ice.name=Rew tile.icePacked.name=Rew Fardellys tile.jukebox.name=Kist Ilowek tile.ladder.name=Skeul tile.lava.name=Lava tile.leaves.acacia.name=Delyow Drenwydh tile.leaves.big_oak.name=Delyow Dar Tewal tile.leaves.birch.name=Delyow Besowen tile.leaves.jungle.name=Delyow Gwylgoes tile.leaves.name=Del tile.leaves.oak.name=Delyow Dar tile.leaves.spruce.name=Delyow Sprus tile.lever.name=Kolpes tile.lightgem.name=Mengolowi tile.litpumpkin.name=Jack o'Lantern tile.lockedchest.name=Argh Alhwedhys tile.log.acacia.name=Prenn Drenwydh tile.log.big_oak.name=Prenn Dar Tewal tile.log.birch.name=Prenn Besowen tile.log.jungle.name=Prenn Gwylgoes tile.log.name=Prenn tile.log.oak.name=Prenn Dar tile.log.spruce.name=Prenn Sprus tile.melon.name=Melon tile.mobSpawner.name=Dinythor tebelvestes tile.monsterStoneEgg.brick.name=Bryck Men Oy Tebelvest tile.monsterStoneEgg.chiseledbrick.name=Bryck Men Karvyek Oy Tebelvest tile.monsterStoneEgg.cobble.name=Men Rond Oy Tebelvest tile.monsterStoneEgg.crackedbrick.name=Bryck Men Krackyek Oy Tebelvest tile.monsterStoneEgg.mossybrick.name=Bryck Men Kewniek Oy Tebelvest tile.monsterStoneEgg.stone.name=Men Oy Tebelvest tile.mushroom.name=Skavel-Gronek tile.musicBlock.name=Stock Noten tile.mycel.name=Towargh Tewl tile.netherBrick.name=Bryck Annown tile.netherFence.name=Kloos Bryck Annown tile.netherStalk.name=Losow Annown tile.netherquartz.name=Moen Kanndir Annown tile.notGate.name=Faglen Menrudh tile.obsidian.name=Obsydyann tile.oreCoal.name=Moen Glow tile.oreDiamond.name=Moen Adamant tile.oreEmerald.name=Moen Gwyrven tile.oreGold.name=Moen Owr tile.oreIron.name=Moen Hornek tile.oreLapis.name=Moen Lapis Lazuli tile.oreRedstone.name=Moen Menrudh tile.oreRuby.name=Moen Rudhemm tile.pistonBase.name=Pyston tile.pistonStickyBase.name=Pyston Glusek tile.portal.name=Porth tile.potatoes.name=Patatysen tile.pumpkin.name=Pompyon tile.quartzBlock.chiseled.name=Stock Kenndir Karvyek tile.quartzBlock.default.name=Stock a Kanndir tile.quartzBlock.lines.name=Koloven Stock Kenndir tile.rail.name=Hyns horn tile.redstoneDust.name=Ponn Menrudh tile.redstoneLight.name=Lugarn Menrudh tile.reeds.name=Gwelen Sugra tile.sand.default.name=Tewes tile.sand.red.name=Tewes Rodh tile.sandStone.chiseled.name=Krag Karvyek tile.sandStone.default.name=Krag tile.sandStone.name=Krag tile.sandStone.smooth.name=Krag Smodh tile.sapling.acacia.name=Gwydhen Yowynk Drenwydh tile.sapling.birch.name=Gwydhen Yowynk Besowen tile.sapling.jungle.name=Gwydhen Yowynk Gwylgoes tile.sapling.oak.name=Gwydhen Yowynk Dar tile.sapling.spruce.name=Gwydhen Yowynk Sprus tile.sign.name=Arwodh tile.snow.name=Ergh tile.stainedGlass.black.name=Gweder Nammys Du tile.stainedGlass.blue.name=Gweder Nammys Blou tile.stainedGlass.brown.name=Gweder Nammys Gell tile.stainedGlass.cyan.name=Gweder Nammys Glaswyrdh tile.stainedGlass.gray.name=Gweder Nammys Loos tile.stainedGlass.green.name=Gweder Nammys Gwyrdh tile.stainedGlass.lightBlue.name=Gweder Nammys Skav Blou tile.stainedGlass.lime.name=Gweder Nammys Limaval tile.stainedGlass.magenta.name=Gweder Nammys Majenta tile.stainedGlass.orange.name=Gweder Nammys Rudhvelyn tile.stainedGlass.pink.name=Gweder Nammys Rudhwynn tile.stainedGlass.purple.name=Gweder Nammys Purpur tile.stainedGlass.red.name=Gweder Nammys Rudh tile.stainedGlass.silver.name=Gweder Nammys Skav Loos tile.stainedGlass.white.name=Gweder Nammys Gwynn tile.stainedGlass.yellow.name=Gweder Nammys Melyn tile.stairsBrick.name=Grisyow Bryck tile.stairsNetherBrick.name=Gris Bryck Annown tile.stairsQuartz.name=Grisyow Kenndir tile.stairsSandStone.name=Grisyow Krag tile.stairsStone.name=Grisyow Men tile.stairsStoneBrickSmooth.name=Grisyow Bryck Men tile.stairsWood.name=Grisyow Prenn Dar tile.stairsWoodAcacia.name=Grisyow Prenn Drenwydh tile.stairsWoodBirch.name=Grisyow Prenn Besow tile.stairsWoodDarkOak.name=Grisyow Prenn Dar Tewal tile.stairsWoodJungle.name=Grisyow Prenn Gwylgoes tile.stairsWoodSpruce.name=Grisyow Prenn Sprus tile.stone.andesite.name=Andesite tile.stone.andesiteSmooth.name=Polished Andesite tile.stone.diorite.name=Diorite tile.stone.dioriteSmooth.name=Polished Diorite tile.stone.granite.name=Granite tile.stone.graniteSmooth.name=Polished Granite tile.stone.stone.name=Stone tile.stoneMoss.name=Meyn kewniek tile.stoneSlab.brick.name=Legh Bryckys tile.stoneSlab.cobble.name=Legh Men Rond tile.stoneSlab.netherBrick.name=Legh Bryck Annown tile.stoneSlab.quartz.name=Legh Kenndir tile.stoneSlab.sand.name=Legh Krag tile.stoneSlab.smoothStoneBrick.name=Legh Bryckys Men tile.stoneSlab.stone.name=Legh Men tile.stoneSlab.wood.name=Legh Prenn tile.stonebrick.name=Meyn rond tile.stonebricksmooth.chiseled.name=Men Brykys Karvyek tile.stonebricksmooth.cracked.name=Men Bryckys Krackyek tile.stonebricksmooth.default.name=Bryckys Men tile.stonebricksmooth.mossy.name=Kewniek Bryckys Men tile.stonebricksmooth.name=Bryckys Men tile.tallgrass.fern.name=Redenen tile.tallgrass.grass.name=Gwels tile.tallgrass.name=Gwels tile.tallgrass.shrub.name=Prysk tile.thinGlass.name=Kwarel tile.thinStainedGlass.black.name=Kwarel Nammys Du tile.thinStainedGlass.blue.name=Kwarel Nammys Blou tile.thinStainedGlass.brown.name=Kwarel Nammys Gell tile.thinStainedGlass.cyan.name=Kwarel Nammys Glaswyrdh tile.thinStainedGlass.gray.name=Kwarel Nammys Loos tile.thinStainedGlass.green.name=Kwarel Nammys Gwyrdh tile.thinStainedGlass.lightBlue.name=Kwarel Nammys Skav Blou tile.thinStainedGlass.lime.name=Kwarel Nammys Limaval tile.thinStainedGlass.magenta.name=Kwarel Nammys Majenta tile.thinStainedGlass.orange.name=Kwarel Nammys Rudhvelyn tile.thinStainedGlass.pink.name=Kwarel Nammys Rudhwynn tile.thinStainedGlass.purple.name=Kwarel Nammys Purpur tile.thinStainedGlass.red.name=Kwarel Nammys Rudh tile.thinStainedGlass.silver.name=Kwarel Nammys Skav Loos tile.thinStainedGlass.white.name=Kwarel Nammys Gwynn tile.thinStainedGlass.yellow.name=Kwarel Nammys Melyn tile.tnt.name=TNT tile.torch.name=Faglen tile.trapdoor.name=Daras Maglen tile.tripWire.name=Gwivren Disevel tile.tripWireSource.name=Higen Gwivren Disevel tile.vine.name=Gwinbrennyer tile.water.name=Dowr tile.waterlily.name=Padyn Lili tile.web.name=Gwias kevnis tile.weightedPlate_heavy.name=Plat Gwaskedh Poosys(Poos) tile.weightedPlate_light.name=Plat Gwaskedh Poosys (Skav) tile.whiteStone.name=Men Diwedh tile.wood.acacia.name=Estyl Prenn Drenwydh tile.wood.big_oak.name=Estyl Prenn Dar Tewal tile.wood.birch.name=Estyl Prenn Besow tile.wood.jungle.name=Estyl Prenn Gwylgoes tile.wood.name=Estyl Prennek tile.wood.oak.name=Estyl Prenn Dar tile.wood.spruce.name=Estyl Prenn Sprus tile.woodSlab.acacia.name=Legh Prenn Drenwydh tile.woodSlab.big_oak.name=Legh Prenn Dar Tewal tile.woodSlab.birch.name=Legh Prenn Besowen tile.woodSlab.jungle.name=Legh Prenn Gwylgoes tile.woodSlab.oak.name=Legh Prenn Dar tile.woodSlab.spruce.name=Legh Prenn Sprus tile.woolCarpet.black.name=Leurlen Du tile.woolCarpet.blue.name=Leurlen Blou tile.woolCarpet.brown.name=Leurlen Gell tile.woolCarpet.cyan.name=Leurlen Glaswyrdh tile.woolCarpet.gray.name=Leurlen Loos tile.woolCarpet.green.name=Leurlen Gwyrdh tile.woolCarpet.lightBlue.name=Leurlen Skav Blou tile.woolCarpet.lime.name=Leurlen Limaval tile.woolCarpet.magenta.name=Leurlen Majenta tile.woolCarpet.name=Leurlen tile.woolCarpet.orange.name=Leurlen Rudhvelyn tile.woolCarpet.pink.name=Leurlen Rudhwynn tile.woolCarpet.purple.name=Leurlen Purpur tile.woolCarpet.red.name=Leurlen Rudh tile.woolCarpet.silver.name=Leurlen Skav Loos tile.woolCarpet.white.name=Leurlen tile.woolCarpet.yellow.name=Leurlen Melyn tile.workbench.name=Moos ow Kreft title.oldgl1=Old graphics card detected; this may prevent you from title.oldgl2=playing in the future as OpenGL 2.0 will be required. translation.test.invalid=Yow % translation.test.none=Hou, bys! translation.test.world=bys
412
0.897946
1
0.897946
game-dev
MEDIA
0.936138
game-dev
0.605016
1
0.605016
Reinisch/Darkest-Dungeon-Unity
2,983
Assets/Scripts/UI/Slots/CampingSkillPurchaseSlot.cs
using System; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class CampingSkillPurchaseSlot : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler { [SerializeField] private BuildCostFrame costFrame; [SerializeField] private Image icon; [SerializeField] private Image locker; public Hero Hero { get; private set; } public CampingSkill Skill { get; private set; } public bool Unlocked { get; private set; } private bool Highlighted { get; set; } private RectTransform rectTransform; public event Action<CampingSkillPurchaseSlot> EventClicked; private void Awake() { rectTransform = GetComponent<RectTransform>(); } public void Initialize(Hero hero, int skillIndex, float discount) { Hero = hero; Skill = hero.HeroClass.CampingSkills[skillIndex]; icon.sprite = DarkestDungeonManager.Data.Sprites["camp_skill_" + Skill.Id]; costFrame.HeirloomOneAmount.text = Mathf.RoundToInt(Skill.CurrencyCost.Amount * discount).ToString(); if (hero.CurrentCampingSkills[skillIndex] == null) Lock(); else Unlock(); } public void UpdateSkill(float discount) { if (Hero == null || Skill == null) return; if (Hero.CurrentCampingSkills[Hero.HeroClass.CampingSkills.IndexOf(Skill)] == null) Lock(); else Unlock(); costFrame.HeirloomOneAmount.text = Mathf.RoundToInt(Skill.CurrencyCost.Amount * discount).ToString(); } public void Reset() { Hero = null; Skill = null; } public void Lock() { Unlocked = false; locker.enabled = true; icon.material = Highlighted ? DarkestDungeonManager.GrayHighlightMaterial : DarkestDungeonManager.GrayMaterial; costFrame.gameObject.SetActive(true); } public void Unlock() { Unlocked = true; locker.enabled = false; icon.material = Highlighted ? DarkestDungeonManager.HighlightMaterial : icon.defaultMaterial; costFrame.gameObject.SetActive(false); } public void OnPointerEnter(PointerEventData eventData) { Highlighted = true; if (Hero == null) return; icon.material = Unlocked ? DarkestDungeonManager.HighlightMaterial : DarkestDungeonManager.GrayHighlightMaterial; if(Skill != null) ToolTipManager.Instanse.Show(Skill.Tooltip(), rectTransform, ToolTipStyle.FromRight, ToolTipSize.Normal); } public void OnPointerExit(PointerEventData eventData) { Highlighted = false; icon.material = Unlocked ? icon.defaultMaterial : DarkestDungeonManager.GrayMaterial; ToolTipManager.Instanse.Hide(); } public void OnPointerClick(PointerEventData eventData) { if (EventClicked != null) EventClicked(this); } }
412
0.909875
1
0.909875
game-dev
MEDIA
0.940538
game-dev
0.919374
1
0.919374
masterfeizz/DaedalusX64-3DS
4,790
Source/SysPSP/UI/PSPMenu.h
#include "Utility/DaedalusTypes.h" #include "SysPSP/Utility/PathsPSP.h" // User Interface Variables const s16 SCREEN_WIDTH {480}; const s16 SCREEN_HEIGHT {272}; // to do adjust values to suit multiple screens const s16 MENU_TOP {5}; const s16 TITLE_HEADER {10}; const s16 BELOW_MENU_MIN {33}; // Rename this as it's confusing const s16 LIST_TEXT_LEFT {13}; const s16 LIST_TEXT_WIDTH {SCREEN_WIDTH - LIST_TEXT_LEFT}; const s16 LIST_TEXT_HEIGHT {216}; const s16 PREVIEW_IMAGE_LEFT {309}; const s16 PREVIEW_IMAGE_BOTTOM {140}; const s16 PREVIEW_IMAGE_RIGHT {464}; const s16 PREVIEW_IMAGE_WIDTH {PREVIEW_IMAGE_RIGHT - PREVIEW_IMAGE_LEFT}; const s16 PREVIEW_IMAGE_HEIGHT {PREVIEW_IMAGE_BOTTOM - BELOW_MENU_MIN}; const s16 DESCRIPTION_AREA_TOP {0}; const s16 DESCRIPTION_AREA_LEFT {16}; const s16 DESCRIPTION_AREA_RIGHT {SCREEN_WIDTH - 16}; const s16 DESCRIPTION_AREA_BOTTOM {SCREEN_HEIGHT - 10}; const s16 ROM_INFO_TEXT_X {318}; const s16 ROM_INFO_TEXT_Y {154}; const s16 BATTERY_INFO {200}; const s16 CATEGORY_TEXT_TOP {BELOW_MENU_MIN + LIST_TEXT_HEIGHT + 5}; const s16 CATEGORY_TEXT_LEFT {LIST_TEXT_LEFT}; const char gCategoryLetters[] = "#abcdefghijklmnopqrstuvwxyz?"; enum ECategory { C_NUMBERS = 0, C_A, C_B, C_C, C_D, C_E, C_F, C_G, C_H, C_I, C_J, C_K, C_L, C_M, C_N, C_O, C_P, C_Q, C_R, C_S, C_T, C_U, C_V, C_W, C_X, C_Y, C_Z, C_UNK, NUM_CATEGORIES, }; // Splash Screen const float MAX_TIME {0.8f}; // Rename to something more sane const char * const LOGO_FILENAME {DAEDALUS_PSP_PATH( "Resources/logo.png" )}; const s16 NUM_SAVESTATE_SLOTS {15}; const char * const SAVING_STATUS_TEXT = "Saving..."; const char * const LOADING_STATUS_TEXT = "Loading..."; const s16 INVALID_SLOT = s16( -1 ); const char * const SAVING_TITLE_TEXT = "Select a Slot to Save To"; const char * const LOADING_TITLE_TEXT = "Select a Slot to Load From"; // About components #define MAX_PSP_MODEL 11 const char * const DAEDALUS_VERSION_TEXT = "DaedalusX64 Revision "; const char * const DATE_TEXT = "Built "; const char * const URL_TEXT_1 = "https://github.com/daedalusx64/daedalus/"; const char * const URL_TEXT_2 = "https://discord.gg/AHWDYmB"; const char * const INFO_TEXT[] = { "Copyright (C) 2008-2019 DaedalusX64 Team", "Copyright (C) 2001-2009 StrmnNrmn", "Audio HLE code by Azimer", "", "For news and updates visit:", }; const char * const pspModel[ MAX_PSP_MODEL ] = { "PSP PHAT (01g)", "PSP 2000 (02g)", "PSP BRITE(03g)", "PSP BRITE (04g)", "PSP GO (05G)", "UNKNOWN PSP", "PSP BRITE (07g)", "UNKNOWN PSP", "PSP BRITE (09g)", "UNKNOWN PSP", "PSP STREET (11g)" }; // Adjust Dead Zone Screen const char * const INSTRUCTIONS_TEXT = "Adjust the minimum and maximum deadzone regions. Up/Down: Increase or decrease the deadzone. Left/Right: Select minimum or maximum deadzone for adjusting. Triangle: Reset to defaults. Start/X: Confirm. Select/Circle: Cancel"; const char * const TITLE_TEXT = "Adjust Stick Deadzone"; // Make more sane const u32 TITLE_Y = 10; const u32 HALF_WIDTH( 480 / 2 ); const u32 CENTRE_X( 480 / 2 ); const u32 DISPLAY_WIDTH( 128 ); const u32 DISPLAY_RADIUS( DISPLAY_WIDTH / 2 ); const u32 PSP_CIRCLE_X = DISPLAY_RADIUS + ((HALF_WIDTH - DISPLAY_WIDTH) / 2); const u32 PSP_CIRCLE_Y = 120; const u32 N64_CIRCLE_X = CENTRE_X + DISPLAY_RADIUS + ((HALF_WIDTH - DISPLAY_WIDTH) / 2); const u32 N64_CIRCLE_Y = 120; const u32 PSP_TITLE_X = PSP_CIRCLE_X - DISPLAY_RADIUS; const u32 PSP_TITLE_Y = PSP_CIRCLE_Y - DISPLAY_RADIUS - 16; const u32 N64_TITLE_X = N64_CIRCLE_X - DISPLAY_RADIUS; const u32 N64_TITLE_Y = N64_CIRCLE_Y - DISPLAY_RADIUS - 16; const f32 DEADZONE_INCREMENT = 0.01f; const f32 DEFAULT_MIN_DEADZONE = 0.28f; // Kind of gross - share somehow with IInputManager? const f32 DEFAULT_MAX_DEADZONE = 1.0f; // Rom Selector component const char * const gRomsDirectories[] = { "ms0:/n64/", DAEDALUS_PSP_PATH( "Roms/" ), #ifndef DAEDALUS_SILENT // For ease of developing with multiple source trees, common folder for roms can be placed at host1: in usbhostfs "host1:/", #endif }; const char * const gNoRomsText[] = { "Daedalus could not find any roms to load.", "You can add roms to the \\N64\\ directory on your memory stick,", "(e.g. P:\\N64\\)", "or the Roms directory within the Daedalus folder.", "(e.g. P:\\PSP\\GAME\\Daedalus\\Roms\\)", "Daedalus recognises a number of different filetypes,", "including .zip, .z64, .v64, .rom, .bin, .pal, .usa and .jap.", }; ; const char * const gPreviewDirectory = DAEDALUS_PSP_PATH( "Resources/Preview/" ); const f32 PREVIEW_SCROLL_WAIT = 0.500f; // seconds to wait for scrolling to stop before loading preview (prevent thrashing) const f32 PREVIEW_FADE_TIME = 0.50f; // seconds
412
0.855285
1
0.855285
game-dev
MEDIA
0.629617
game-dev,embedded-firmware
0.765354
1
0.765354
Apress/monogame-mastery
1,866
chapter-09/start/Objects/MissileSprite.cs
using chapter_09.Engine.Objects; using chapter_09.States.Particles; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace chapter_09.Objects { public class MissileSprite : BaseGameObject { private const float StartSpeed = 0.5f; private const float Acceleration = 0.15f; private float _speed = StartSpeed; // keep track of scaled down texture size private int _missileHeight; private int _missileWidth; // missiles are attached to their own particle emitter private ExhaustEmitter _exhaustEmitter; public override Vector2 Position { set { _position = value; _exhaustEmitter.Position = new Vector2(_position.X + 18, _position.Y + _missileHeight - 10); } } public MissileSprite(Texture2D missleTexture, Texture2D exhaustTexture) { _texture = missleTexture; _exhaustEmitter = new ExhaustEmitter(exhaustTexture, _position); var ratio = (float) _texture.Height / (float) _texture.Width; _missileWidth = 50; _missileHeight = (int) (_missileWidth * ratio); } public void Update(GameTime gameTime) { _exhaustEmitter.Update(gameTime); Position = new Vector2(Position.X, Position.Y - _speed); _speed = _speed + Acceleration; } public override void Render(SpriteBatch spriteBatch) { // need to scale down the sprite. The original texture is very big var destRectangle = new Rectangle((int) Position.X, (int) Position.Y, _missileWidth, _missileHeight); spriteBatch.Draw(_texture, destRectangle, Color.White); _exhaustEmitter.Render(spriteBatch); } } }
412
0.677813
1
0.677813
game-dev
MEDIA
0.859499
game-dev,graphics-rendering
0.871179
1
0.871179
stronnag/mwptools
2,733
src/mwp/survey/build_mission.vala
/* * 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/>. * * (c) Jonathan Hudson <jh+mwptools@daria.co.uk> * * SPDX-License-Identifier: GPL-3.0-or-later */ namespace Survey { int resolve_alt(double lat, double lon, int alt, bool amsl, out int elev) { int p3 = 0; elev = alt; if(amsl) { double e = Hgt.NODATA; e = DemManager.lookup(lat, lon); if (e != Hgt.NODATA) { p3 = 1; elev += (int)e; } } return p3; } void build_mission(AreaCalc.RowPoints []rows, int alt, int lspeed, bool rth, bool amsl) { int n = 0; int elev; int p3; var ms = new Mission(); MissionItem []mis={}; foreach (var r in rows){ n++; p3 = resolve_alt(r.start.y, r.start.x, alt, amsl, out elev); var mi = new MissionItem.full(n, Msp.Action.WAYPOINT, r.start.y, r.start.x, elev, lspeed, 0, p3, 0); mis += mi; n++; p3 = resolve_alt(r.end.y, r.end.x, alt, amsl, out elev); mi = new MissionItem.full(n, Msp.Action.WAYPOINT, r.end.y, r.end.x, elev, lspeed, 0, p3, 0); ms.check_wp_sanity(ref mi); mis += mi; } if(rth) { n++; var mi = new MissionItem.full(n, Msp.Action.RTH, 0, 0, 0, 0, 0, 0, 0xa5); mis += mi; } mis[n-1].flag = 0xa5; ms.points = mis; ms.npoints = n; finalise_mission(ms); } void build_square_mission(AreaCalc.Vec []vec, int alt, int lspeed, bool rth, bool amsl) { int n = 0; int elev; int p3; var ms = new Mission(); MissionItem []mis={}; foreach (var v in vec){ n++; p3 = resolve_alt(v.y, v.x, alt, amsl, out elev); var mi = new MissionItem.full(n, Msp.Action.WAYPOINT, v.y, v.x, elev, lspeed, 0, p3, 0); ms.check_wp_sanity(ref mi); mis += mi; } if(rth) { n++; var mi = new MissionItem.full(n, Msp.Action.RTH, 0, 0, 0, 0, 0, 0, 0xa5); mis += mi; } mis[n-1].flag = 0xa5; ms.points = mis; ms.npoints = n; finalise_mission(ms); } internal void finalise_mission(Mission ms) { ms.cy = (ms.maxy + ms.miny)/2; ms.cx = (ms.maxx + ms.minx)/2; MissionManager.msx = {ms}; MissionManager.is_dirty = true; MissionManager.mdx = 0; MissionManager.setup_mission_from_mm(); } }
412
0.795878
1
0.795878
game-dev
MEDIA
0.758613
game-dev
0.982459
1
0.982459
paulbatum/Dominion
997
Dominion.Rules/UnlimitedSupplyCardPile.cs
using System; namespace Dominion.Rules { public class UnlimitedSupplyCardPile : CardPile { private readonly Func<ICard> _cardCreator; public UnlimitedSupplyCardPile(Func<ICard> cardCreator) { _cardCreator = cardCreator; } public override bool IsEmpty { get { return false; } } public override int CardCount { get { throw new NotSupportedException("A null zone cannot be considered to have a card count"); } } public override ICard TopCard { get { return _cardCreator(); } } public override bool IsLimited { get { return false; } } protected override void AddCard(ICard card) { // NO OP } protected override void RemoveCard(ICard card) { // NO OP } } }
412
0.888851
1
0.888851
game-dev
MEDIA
0.652257
game-dev
0.763628
1
0.763628
ProjectIgnis/CardScripts
1,756
official/c77449773.lua
--サイバネット・クロスワイプ --Cynet Crosswipe --Scripted by AlphaKretin local s,id=GetID() function s.initial_effect(c) --activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCost(s.cost) e1:SetTarget(s.target) e1:SetOperation(s.activate) c:RegisterEffect(e1) end function s.cost(e,tp,eg,ep,ev,re,r,rp,chk) e:SetLabel(1) return true end function s.spcheck(sg,tp,exg,dg) local a=0 for c in aux.Next(sg) do if dg:IsContains(c) then a=a+1 end for tc in aux.Next(c:GetEquipGroup()) do if dg:IsContains(tc) then a=a+1 end end end return #dg-a>=1 end function s.cfilter(c) return c:IsRace(RACE_CYBERSE) end function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() and chkc~=e:GetHandler() end local dg=Duel.GetMatchingGroup(Card.IsCanBeEffectTarget,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,e:GetHandler(),e) if chk==0 then if e:GetLabel()==1 then e:SetLabel(0) return Duel.CheckReleaseGroupCost(tp,s.cfilter,1,false,s.spcheck,nil,dg) else return Duel.IsExistingTarget(aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,e:GetHandler()) end end if e:GetLabel()==1 then e:SetLabel(0) local sg=Duel.SelectReleaseGroupCost(tp,s.cfilter,1,1,false,s.spcheck,nil,dg) Duel.Release(sg,REASON_COST) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,e:GetHandler()) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,#g,0,0) end function s.activate(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) local sg=g:Filter(Card.IsRelateToEffect,nil,e) Duel.Destroy(sg,REASON_EFFECT) end
412
0.882013
1
0.882013
game-dev
MEDIA
0.985271
game-dev
0.934111
1
0.934111
bergerhealer/TrainCarts
1,344
src/main/java/com/bergerkiller/bukkit/tc/events/MissingPathConnectionEvent.java
package com.bergerkiller.bukkit.tc.events; import com.bergerkiller.bukkit.tc.controller.MinecartGroup; import com.bergerkiller.bukkit.tc.controller.components.RailPiece; import com.bergerkiller.bukkit.tc.pathfinding.PathNode; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; /** * This event fires if a destination couldn't be reached when a train is passing a switcher-sign */ public class MissingPathConnectionEvent extends Event { private static final HandlerList HANDLERS = new HandlerList(); private final RailPiece rail; private final PathNode node; private final MinecartGroup group; private final String destination; public MissingPathConnectionEvent(RailPiece rail, PathNode node, MinecartGroup group, String destination) { this.rail = rail; this.node = node; this.group = group; this.destination = destination; } public RailPiece getRail() { return rail; } public PathNode getPathNode() { return node; } public MinecartGroup getGroup() { return group; } public String getDestination() { return destination; } @NotNull @Override public HandlerList getHandlers() { return HANDLERS; } public static HandlerList getHandlerList() { return HANDLERS; } }
412
0.612016
1
0.612016
game-dev
MEDIA
0.680943
game-dev,networking
0.507808
1
0.507808
google/google-ctf
4,604
2025/hackceler8/rounds/3/game/src/door.rs
// Copyright 2025 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an AS IS BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use megahx8::*; use crate::big_sprite::BigSprite; use crate::entity::*; use crate::res::maps; use crate::res::sprites; use crate::res::sprites::blue_door_h::Anim; use crate::resource_state::State; // Door dimensions, in pixels. const WIDTH: i16 = 16; const LENGTH: i16 = 48; #[derive(Copy, Clone)] pub enum Orientation { Horizontal, Vertical, } pub struct Door { pub x: i16, pub y: i16, sprite: BigSprite, pub id: u16, orientation: Orientation, pub open: bool, } /// Properties parsed from the map. pub struct DoorProperties { /// A unique ID to idenfity the item within the given world. pub id: u16, pub orientation: Orientation, } impl Door { pub fn new( world_type: maps::WorldType, map_x: i16, map_y: i16, properties: &DoorProperties, open: bool, res_state: &mut State, vdp: &mut TargetVdp, ) -> Door { let mut sprite_x = map_x + 128; let mut sprite_y = map_y + 128; match properties.orientation { Orientation::Horizontal => { sprite_x -= LENGTH / 2; sprite_y -= WIDTH / 2; } Orientation::Vertical => { sprite_x -= WIDTH / 2; sprite_y -= LENGTH / 2; } }; let mut sprite = Self::get_sprite_init_fn(world_type, properties.orientation)( res_state, vdp, /* keep_loaded= */ false, ); sprite.set_position(sprite_x, sprite_y); let mut door = Door { x: sprite_x, y: sprite_y, sprite, id: properties.id, orientation: properties.orientation, open, }; door.sprite .set_anim(if open { Anim::Open } else { Anim::Closed } as usize); door } pub fn open(&mut self) { self.open = true; self.sprite.set_anim(Anim::Open as usize); } fn get_sprite_init_fn( world_type: maps::WorldType, orientation: Orientation, ) -> crate::big_sprite::SpriteInitializationFunction { match (world_type, orientation) { (maps::WorldType::Overworld, Orientation::Horizontal) => sprites::grey_door_h::new, (maps::WorldType::Overworld, Orientation::Vertical) => sprites::grey_door_v::new, (maps::WorldType::FireTemple, Orientation::Horizontal) => sprites::red_door_h::new, (maps::WorldType::FireTemple, Orientation::Vertical) => sprites::red_door_v::new, (maps::WorldType::WaterTemple, Orientation::Horizontal) => sprites::blue_door_h::new, (maps::WorldType::WaterTemple, Orientation::Vertical) => sprites::blue_door_v::new, (maps::WorldType::ForestTemple, Orientation::Horizontal) => sprites::green_door_h::new, (maps::WorldType::ForestTemple, Orientation::Vertical) => sprites::green_door_v::new, (maps::WorldType::SkyTemple, Orientation::Horizontal) => sprites::white_door_h::new, _ => sprites::white_door_v::new, } } } impl Entity for Door { fn hitbox(&self) -> Hitbox { match self.orientation { Orientation::Horizontal => Hitbox { x: self.x, y: self.y, w: LENGTH, h: WIDTH, }, Orientation::Vertical => Hitbox { x: self.x, y: self.y, w: WIDTH, h: LENGTH, }, } } fn render(&mut self, renderer: &mut TargetRenderer) { self.sprite.render(renderer); } #[expect(clippy::cast_sign_loss, clippy::cast_possible_truncation)] /// Set the absolute position of a sprite on the screen. fn set_position(&mut self, x: i16, y: i16) { self.x = x; self.y = y; self.sprite.set_position(x, y); } fn move_relative(&mut self, dx: i16, dy: i16) { self.set_position(self.x + dx, self.y + dy); } }
412
0.765715
1
0.765715
game-dev
MEDIA
0.767588
game-dev
0.879112
1
0.879112
nasa/EMTG
21,258
depend/boost/tools/boost_install/test/iostreams/bzip2-1.0.8/decompress.c
/*-------------------------------------------------------------*/ /*--- Decompression machinery ---*/ /*--- decompress.c ---*/ /*-------------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.8 of 13 July 2019 Copyright (C) 1996-2019 Julian Seward <jseward@acm.org> Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ #include "bzlib_private.h" /*---------------------------------------------------*/ static void makeMaps_d ( DState* s ) { Int32 i; s->nInUse = 0; for (i = 0; i < 256; i++) if (s->inUse[i]) { s->seqToUnseq[s->nInUse] = i; s->nInUse++; } } /*---------------------------------------------------*/ #define RETURN(rrr) \ { retVal = rrr; goto save_state_and_return; }; #define GET_BITS(lll,vvv,nnn) \ case lll: s->state = lll; \ while (True) { \ if (s->bsLive >= nnn) { \ UInt32 v; \ v = (s->bsBuff >> \ (s->bsLive-nnn)) & ((1 << nnn)-1); \ s->bsLive -= nnn; \ vvv = v; \ break; \ } \ if (s->strm->avail_in == 0) RETURN(BZ_OK); \ s->bsBuff \ = (s->bsBuff << 8) | \ ((UInt32) \ (*((UChar*)(s->strm->next_in)))); \ s->bsLive += 8; \ s->strm->next_in++; \ s->strm->avail_in--; \ s->strm->total_in_lo32++; \ if (s->strm->total_in_lo32 == 0) \ s->strm->total_in_hi32++; \ } #define GET_UCHAR(lll,uuu) \ GET_BITS(lll,uuu,8) #define GET_BIT(lll,uuu) \ GET_BITS(lll,uuu,1) /*---------------------------------------------------*/ #define GET_MTF_VAL(label1,label2,lval) \ { \ if (groupPos == 0) { \ groupNo++; \ if (groupNo >= nSelectors) \ RETURN(BZ_DATA_ERROR); \ groupPos = BZ_G_SIZE; \ gSel = s->selector[groupNo]; \ gMinlen = s->minLens[gSel]; \ gLimit = &(s->limit[gSel][0]); \ gPerm = &(s->perm[gSel][0]); \ gBase = &(s->base[gSel][0]); \ } \ groupPos--; \ zn = gMinlen; \ GET_BITS(label1, zvec, zn); \ while (1) { \ if (zn > 20 /* the longest code */) \ RETURN(BZ_DATA_ERROR); \ if (zvec <= gLimit[zn]) break; \ zn++; \ GET_BIT(label2, zj); \ zvec = (zvec << 1) | zj; \ }; \ if (zvec - gBase[zn] < 0 \ || zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \ RETURN(BZ_DATA_ERROR); \ lval = gPerm[zvec - gBase[zn]]; \ } /*---------------------------------------------------*/ Int32 BZ2_decompress ( DState* s ) { UChar uc; Int32 retVal; Int32 minLen, maxLen; bz_stream* strm = s->strm; /* stuff that needs to be saved/restored */ Int32 i; Int32 j; Int32 t; Int32 alphaSize; Int32 nGroups; Int32 nSelectors; Int32 EOB; Int32 groupNo; Int32 groupPos; Int32 nextSym; Int32 nblockMAX; Int32 nblock; Int32 es; Int32 N; Int32 curr; Int32 zt; Int32 zn; Int32 zvec; Int32 zj; Int32 gSel; Int32 gMinlen; Int32* gLimit; Int32* gBase; Int32* gPerm; if (s->state == BZ_X_MAGIC_1) { /*initialise the save area*/ s->save_i = 0; s->save_j = 0; s->save_t = 0; s->save_alphaSize = 0; s->save_nGroups = 0; s->save_nSelectors = 0; s->save_EOB = 0; s->save_groupNo = 0; s->save_groupPos = 0; s->save_nextSym = 0; s->save_nblockMAX = 0; s->save_nblock = 0; s->save_es = 0; s->save_N = 0; s->save_curr = 0; s->save_zt = 0; s->save_zn = 0; s->save_zvec = 0; s->save_zj = 0; s->save_gSel = 0; s->save_gMinlen = 0; s->save_gLimit = NULL; s->save_gBase = NULL; s->save_gPerm = NULL; } /*restore from the save area*/ i = s->save_i; j = s->save_j; t = s->save_t; alphaSize = s->save_alphaSize; nGroups = s->save_nGroups; nSelectors = s->save_nSelectors; EOB = s->save_EOB; groupNo = s->save_groupNo; groupPos = s->save_groupPos; nextSym = s->save_nextSym; nblockMAX = s->save_nblockMAX; nblock = s->save_nblock; es = s->save_es; N = s->save_N; curr = s->save_curr; zt = s->save_zt; zn = s->save_zn; zvec = s->save_zvec; zj = s->save_zj; gSel = s->save_gSel; gMinlen = s->save_gMinlen; gLimit = s->save_gLimit; gBase = s->save_gBase; gPerm = s->save_gPerm; retVal = BZ_OK; switch (s->state) { GET_UCHAR(BZ_X_MAGIC_1, uc); if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_2, uc); if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_3, uc) if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC); GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8) if (s->blockSize100k < (BZ_HDR_0 + 1) || s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC); s->blockSize100k -= BZ_HDR_0; if (s->smallDecompress) { s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) ); s->ll4 = BZALLOC( ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) ); if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR); } else { s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) ); if (s->tt == NULL) RETURN(BZ_MEM_ERROR); } GET_UCHAR(BZ_X_BLKHDR_1, uc); if (uc == 0x17) goto endhdr_2; if (uc != 0x31) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_2, uc); if (uc != 0x41) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_3, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_4, uc); if (uc != 0x26) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_5, uc); if (uc != 0x53) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_6, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); s->currBlockNo++; if (s->verbosity >= 2) VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo ); s->storedBlockCRC = 0; GET_UCHAR(BZ_X_BCRC_1, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_2, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_3, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_4, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1); s->origPtr = 0; GET_UCHAR(BZ_X_ORIGPTR_1, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_2, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_3, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); if (s->origPtr < 0) RETURN(BZ_DATA_ERROR); if (s->origPtr > 10 + 100000*s->blockSize100k) RETURN(BZ_DATA_ERROR); /*--- Receive the mapping table ---*/ for (i = 0; i < 16; i++) { GET_BIT(BZ_X_MAPPING_1, uc); if (uc == 1) s->inUse16[i] = True; else s->inUse16[i] = False; } for (i = 0; i < 256; i++) s->inUse[i] = False; for (i = 0; i < 16; i++) if (s->inUse16[i]) for (j = 0; j < 16; j++) { GET_BIT(BZ_X_MAPPING_2, uc); if (uc == 1) s->inUse[i * 16 + j] = True; } makeMaps_d ( s ); if (s->nInUse == 0) RETURN(BZ_DATA_ERROR); alphaSize = s->nInUse+2; /*--- Now the selectors ---*/ GET_BITS(BZ_X_SELECTOR_1, nGroups, 3); if (nGroups < 2 || nGroups > BZ_N_GROUPS) RETURN(BZ_DATA_ERROR); GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15); if (nSelectors < 1) RETURN(BZ_DATA_ERROR); for (i = 0; i < nSelectors; i++) { j = 0; while (True) { GET_BIT(BZ_X_SELECTOR_3, uc); if (uc == 0) break; j++; if (j >= nGroups) RETURN(BZ_DATA_ERROR); } /* Having more than BZ_MAX_SELECTORS doesn't make much sense since they will never be used, but some implementations might "round up" the number of selectors, so just ignore those. */ if (i < BZ_MAX_SELECTORS) s->selectorMtf[i] = j; } if (nSelectors > BZ_MAX_SELECTORS) nSelectors = BZ_MAX_SELECTORS; /*--- Undo the MTF values for the selectors. ---*/ { UChar pos[BZ_N_GROUPS], tmp, v; for (v = 0; v < nGroups; v++) pos[v] = v; for (i = 0; i < nSelectors; i++) { v = s->selectorMtf[i]; tmp = pos[v]; while (v > 0) { pos[v] = pos[v-1]; v--; } pos[0] = tmp; s->selector[i] = tmp; } } /*--- Now the coding tables ---*/ for (t = 0; t < nGroups; t++) { GET_BITS(BZ_X_CODING_1, curr, 5); for (i = 0; i < alphaSize; i++) { while (True) { if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR); GET_BIT(BZ_X_CODING_2, uc); if (uc == 0) break; GET_BIT(BZ_X_CODING_3, uc); if (uc == 0) curr++; else curr--; } s->len[t][i] = curr; } } /*--- Create the Huffman decoding tables ---*/ for (t = 0; t < nGroups; t++) { minLen = 32; maxLen = 0; for (i = 0; i < alphaSize; i++) { if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; if (s->len[t][i] < minLen) minLen = s->len[t][i]; } BZ2_hbCreateDecodeTables ( &(s->limit[t][0]), &(s->base[t][0]), &(s->perm[t][0]), &(s->len[t][0]), minLen, maxLen, alphaSize ); s->minLens[t] = minLen; } /*--- Now the MTF values ---*/ EOB = s->nInUse+1; nblockMAX = 100000 * s->blockSize100k; groupNo = -1; groupPos = 0; for (i = 0; i <= 255; i++) s->unzftab[i] = 0; /*-- MTF init --*/ { Int32 ii, jj, kk; kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj); kk--; } s->mtfbase[ii] = kk + 1; } } /*-- end MTF init --*/ nblock = 0; GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym); while (True) { if (nextSym == EOB) break; if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) { es = -1; N = 1; do { /* Check that N doesn't get too big, so that es doesn't go negative. The maximum value that can be RUNA/RUNB encoded is equal to the block size (post the initial RLE), viz, 900k, so bounding N at 2 million should guard against overflow without rejecting any legitimate inputs. */ if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR); if (nextSym == BZ_RUNA) es = es + (0+1) * N; else if (nextSym == BZ_RUNB) es = es + (1+1) * N; N = N * 2; GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym); } while (nextSym == BZ_RUNA || nextSym == BZ_RUNB); es++; uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ]; s->unzftab[uc] += es; if (s->smallDecompress) while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->ll16[nblock] = (UInt16)uc; nblock++; es--; } else while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->tt[nblock] = (UInt32)uc; nblock++; es--; }; continue; } else { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); /*-- uc = MTF ( nextSym-1 ) --*/ { Int32 ii, jj, kk, pp, lno, off; UInt32 nn; nn = (UInt32)(nextSym - 1); if (nn < MTFL_SIZE) { /* avoid general-case expense */ pp = s->mtfbase[0]; uc = s->mtfa[pp+nn]; while (nn > 3) { Int32 z = pp+nn; s->mtfa[(z) ] = s->mtfa[(z)-1]; s->mtfa[(z)-1] = s->mtfa[(z)-2]; s->mtfa[(z)-2] = s->mtfa[(z)-3]; s->mtfa[(z)-3] = s->mtfa[(z)-4]; nn -= 4; } while (nn > 0) { s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; }; s->mtfa[pp] = uc; } else { /* general case */ lno = nn / MTFL_SIZE; off = nn % MTFL_SIZE; pp = s->mtfbase[lno] + off; uc = s->mtfa[pp]; while (pp > s->mtfbase[lno]) { s->mtfa[pp] = s->mtfa[pp-1]; pp--; }; s->mtfbase[lno]++; while (lno > 0) { s->mtfbase[lno]--; s->mtfa[s->mtfbase[lno]] = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1]; lno--; } s->mtfbase[0]--; s->mtfa[s->mtfbase[0]] = uc; if (s->mtfbase[0] == 0) { kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj]; kk--; } s->mtfbase[ii] = kk + 1; } } } } /*-- end uc = MTF ( nextSym-1 ) --*/ s->unzftab[s->seqToUnseq[uc]]++; if (s->smallDecompress) s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]); nblock++; GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym); continue; } } /* Now we know what nblock is, we can do a better sanity check on s->origPtr. */ if (s->origPtr < 0 || s->origPtr >= nblock) RETURN(BZ_DATA_ERROR); /*-- Set up cftab to facilitate generation of T^(-1) --*/ /* Check: unzftab entries in range. */ for (i = 0; i <= 255; i++) { if (s->unzftab[i] < 0 || s->unzftab[i] > nblock) RETURN(BZ_DATA_ERROR); } /* Actually generate cftab. */ s->cftab[0] = 0; for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1]; for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1]; /* Check: cftab entries in range. */ for (i = 0; i <= 256; i++) { if (s->cftab[i] < 0 || s->cftab[i] > nblock) { /* s->cftab[i] can legitimately be == nblock */ RETURN(BZ_DATA_ERROR); } } /* Check: cftab entries non-descending. */ for (i = 1; i <= 256; i++) { if (s->cftab[i-1] > s->cftab[i]) { RETURN(BZ_DATA_ERROR); } } s->state_out_len = 0; s->state_out_ch = 0; BZ_INITIALISE_CRC ( s->calculatedBlockCRC ); s->state = BZ_X_OUTPUT; if (s->verbosity >= 2) VPrintf0 ( "rt+rld" ); if (s->smallDecompress) { /*-- Make a copy of cftab, used in generation of T --*/ for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i]; /*-- compute the T vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->ll16[i]); SET_LL(i, s->cftabCopy[uc]); s->cftabCopy[uc]++; } /*-- Compute T^(-1) by pointer reversal on T --*/ i = s->origPtr; j = GET_LL(i); do { Int32 tmp = GET_LL(j); SET_LL(j, i); i = j; j = tmp; } while (i != s->origPtr); s->tPos = s->origPtr; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_SMALL(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_SMALL(s->k0); s->nblock_used++; } } else { /*-- compute the T^(-1) vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->tt[i] & 0xff); s->tt[s->cftab[uc]] |= (i << 8); s->cftab[uc]++; } s->tPos = s->tt[s->origPtr] >> 8; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_FAST(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_FAST(s->k0); s->nblock_used++; } } RETURN(BZ_OK); endhdr_2: GET_UCHAR(BZ_X_ENDHDR_2, uc); if (uc != 0x72) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_3, uc); if (uc != 0x45) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_4, uc); if (uc != 0x38) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_5, uc); if (uc != 0x50) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_6, uc); if (uc != 0x90) RETURN(BZ_DATA_ERROR); s->storedCombinedCRC = 0; GET_UCHAR(BZ_X_CCRC_1, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_2, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_3, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_4, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); s->state = BZ_X_IDLE; RETURN(BZ_STREAM_END); default: AssertH ( False, 4001 ); } AssertH ( False, 4002 ); save_state_and_return: s->save_i = i; s->save_j = j; s->save_t = t; s->save_alphaSize = alphaSize; s->save_nGroups = nGroups; s->save_nSelectors = nSelectors; s->save_EOB = EOB; s->save_groupNo = groupNo; s->save_groupPos = groupPos; s->save_nextSym = nextSym; s->save_nblockMAX = nblockMAX; s->save_nblock = nblock; s->save_es = es; s->save_N = N; s->save_curr = curr; s->save_zt = zt; s->save_zn = zn; s->save_zvec = zvec; s->save_zj = zj; s->save_gSel = gSel; s->save_gMinlen = gMinlen; s->save_gLimit = gLimit; s->save_gBase = gBase; s->save_gPerm = gPerm; return retVal; } /*-------------------------------------------------------------*/ /*--- end decompress.c ---*/ /*-------------------------------------------------------------*/
412
0.998022
1
0.998022
game-dev
MEDIA
0.18345
game-dev
0.999766
1
0.999766
Rearth/Oritech
8,629
common/src/main/java/rearth/oritech/block/base/entity/ItemEnergyFrameInteractionBlockEntity.java
package rearth.oritech.block.base.entity; import dev.architectury.registry.menu.ExtendedMenuProvider; import org.jetbrains.annotations.Nullable; import rearth.oritech.api.energy.EnergyApi; import rearth.oritech.api.energy.containers.DynamicEnergyStorage; import rearth.oritech.api.item.ItemApi; import rearth.oritech.api.item.containers.SimpleInventoryStorage; import rearth.oritech.api.networking.SyncField; import rearth.oritech.api.networking.SyncType; import rearth.oritech.block.entity.addons.RedstoneAddonBlockEntity; import rearth.oritech.client.ui.UpgradableMachineScreenHandler; import rearth.oritech.util.InventoryInputMode; import rearth.oritech.util.MachineAddonController; import rearth.oritech.util.ScreenProvider; import java.util.ArrayList; import java.util.List; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.world.Container; import net.minecraft.world.ContainerHelper; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; public abstract class ItemEnergyFrameInteractionBlockEntity extends FrameInteractionBlockEntity implements ItemApi.BlockProvider, EnergyApi.BlockProvider, ExtendedMenuProvider, ScreenProvider, MachineAddonController, RedstoneAddonBlockEntity.RedstoneControllable { @SyncField({SyncType.GUI_TICK, SyncType.GUI_OPEN}) public final DynamicEnergyStorage energyStorage = new DynamicEnergyStorage(getDefaultCapacity(), getDefaultInsertRate(), 0, this::setChanged); public final SimpleInventoryStorage inventory = new SimpleInventoryStorage(getInventorySize(), this::setChanged); @SyncField({SyncType.GUI_OPEN}) private final List<BlockPos> connectedAddons = new ArrayList<>(); @SyncField({SyncType.GUI_OPEN}) private final List<BlockPos> openSlots = new ArrayList<>(); @SyncField({SyncType.GUI_OPEN}) private BaseAddonData addonData = MachineAddonController.DEFAULT_ADDON_DATA; public ItemEnergyFrameInteractionBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) { super(type, pos, state); } public abstract int getMoveEnergyUsage(); public abstract int getOperationEnergyUsage(); @Override protected boolean canProgress() { return !disabledViaRedstone && energyStorage.amount >= getMoveEnergyUsage() * getBaseAddonData().efficiency() * (1 / getBaseAddonData().speed()) && energyStorage.amount >= getOperationEnergyUsage() * getBaseAddonData().efficiency() * (1 / getBaseAddonData().speed()); } @Override protected void doProgress(boolean moving) { var usedCost = moving ? getMoveEnergyUsage() : getOperationEnergyUsage(); energyStorage.amount -= (long) (usedCost * getBaseAddonData().efficiency() * (1 / getBaseAddonData().speed())); } @Override public void finishBlockWork(BlockPos processed) { } @Override protected void loadAdditional(CompoundTag nbt, HolderLookup.Provider registryLookup) { super.loadAdditional(nbt, registryLookup); ContainerHelper.loadAllItems(nbt, inventory.heldStacks, registryLookup); energyStorage.amount = nbt.getLong("energy_stored"); disabledViaRedstone = nbt.getBoolean("oritech.redstone"); loadAddonNbtData(nbt); updateEnergyContainer(); } @Override protected void saveAdditional(CompoundTag nbt, HolderLookup.Provider registryLookup) { super.saveAdditional(nbt, registryLookup); ContainerHelper.saveAllItems(nbt, inventory.heldStacks, false, registryLookup); nbt.putLong("energy_stored", energyStorage.amount); nbt.putBoolean("oritech.redstone", disabledViaRedstone); writeAddonToNbt(nbt); } @Override public ItemApi.InventoryStorage getInventoryStorage(Direction direction) { return inventory; } @Override public EnergyApi.EnergyStorage getEnergyStorage(Direction direction) { return energyStorage; } @Override public BlockPos getPosForAddon() { return getBlockPos(); } @Override public Level getWorldForAddon() { return getLevel(); } @Override public void saveExtraData(FriendlyByteBuf buf) { sendUpdate(SyncType.GUI_OPEN); buf.writeBlockPos(worldPosition); } @Nullable @Override public AbstractContainerMenu createMenu(int syncId, Inventory playerInventory, Player player) { return new UpgradableMachineScreenHandler(syncId, playerInventory, this); } @Override public Component getDisplayName() { return Component.nullToEmpty(""); } @Override public List<GuiSlot> getGuiSlots() { return List.of( new GuiSlot(0, 50, 11)); } public int getInventorySize() { return 1; } @Override public float getProgress() { var maxTime = isMoving() ? getMoveTime() : getWorkTime(); return (float) getCurrentProgress() / maxTime; } @Override public boolean inputOptionsEnabled() { return false; } @Override public InventoryInputMode getInventoryInputMode() { return InventoryInputMode.FILL_LEFT_TO_RIGHT; } @Override public float getDisplayedEnergyUsage() { return getOperationEnergyUsage() * getBaseAddonData().efficiency() * (1 / getBaseAddonData().speed()); } @Override public long getDefaultCapacity() { return 100_000; } @Override public long getDefaultInsertRate() { return 5000; } @Override public Container getDisplayedInventory() { return inventory; } @Override public float getDisplayedEnergyTransfer() { return energyStorage.maxInsert; } @Override public ItemApi.InventoryStorage getInventoryForAddon() { return inventory; } @Override public ScreenProvider getScreenProvider() { return this; } @Override public float getSpeedMultiplier() { return addonData.speed(); } public DynamicEnergyStorage getEnergyStorage() { return energyStorage; } @Override public List<BlockPos> getConnectedAddons() { return connectedAddons; } @Override public List<BlockPos> getOpenAddonSlots() { return openSlots; } @Override public Direction getFacingForAddon() { return super.getFacing(); } @Override public DynamicEnergyStorage getStorageForAddon() { return getEnergyStorage(); } @Override public BaseAddonData getBaseAddonData() { return addonData; } @Override public void setBaseAddonData(BaseAddonData data) { this.addonData = data; this.setChanged(); } public boolean isActivelyWorking() { return level.getGameTime() - lastWorkedAt < 5; } @Override public int getComparatorEnergyAmount() { return (int) ((energyStorage.amount / (float) energyStorage.capacity) * 15); } @Override public int getComparatorSlotAmount(int slot) { if (inventory.heldStacks.size() <= slot) return 0; var stack = inventory.getItem(slot); if (stack.isEmpty()) return 0; return (int) ((stack.getCount() / (float) stack.getMaxStackSize()) * 15); } @Override public int getComparatorProgress() { return 0; } @Override public int getComparatorActiveState() { return isActivelyWorking() ? 15 : 0; } @Override public void onRedstoneEvent(boolean isPowered) { this.disabledViaRedstone = isPowered; } @Override public int receivedRedstoneSignal() { if (disabledViaRedstone) return 15; return 0; } @Override public String currentRedstoneEffect() { if (disabledViaRedstone) return "tooltip.oritech.redstone_disabled"; return "tooltip.oritech.redstone_enabled"; } }
412
0.844182
1
0.844182
game-dev
MEDIA
0.969066
game-dev
0.950908
1
0.950908
HyperiumClient/Hyperium
5,442
src/main/java/cc/hyperium/mods/oldanimations/OldBlocking.java
/* * Copyright (C) 2018-present Hyperium <https://hyperium.cc/> * * 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 <http://www.gnu.org/licenses/>. */ package cc.hyperium.mods.oldanimations; import cc.hyperium.config.Settings; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.client.renderer.entity.RendererLivingEntity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; public class OldBlocking { /** * May require additional cleanups, however it's fine for the moment. */ public void doRenderLayer(EntityLivingBase entitylivingbaseIn, RendererLivingEntity<?> livingEntityRenderer) { ItemStack itemstack = entitylivingbaseIn.getHeldItem(); if (itemstack != null) { GlStateManager.pushMatrix(); if (livingEntityRenderer.getMainModel().isChild) { float f = 0.5f; GlStateManager.translate(0.0f, 0.625f, 0.0f); GlStateManager.rotate(-20.0f, -1.0f, 0.0f, 0.0f); GlStateManager.scale(f, f, f); } Label_0327: if (entitylivingbaseIn instanceof EntityPlayer) { if (Settings.OLD_BLOCKING) { if (((EntityPlayer) entitylivingbaseIn).isBlocking()) { if (entitylivingbaseIn.isSneaking()) { ((ModelBiped) livingEntityRenderer.getMainModel()).postRenderArm(0.0325f); GlStateManager.scale(1.05f, 1.05f, 1.05f); GlStateManager.translate(-0.58f, 0.32f, -0.07f); GlStateManager .rotate(-24405.0f, 137290.0f, -2009900.0f, -2654900.0f); } else { ((ModelBiped) livingEntityRenderer.getMainModel()).postRenderArm(0.0325f); GlStateManager.scale(1.05f, 1.05f, 1.05f); GlStateManager.translate(-0.45f, 0.25f, -0.07f); GlStateManager .rotate(-24405.0f, 137290.0f, -2009900.0f, -2654900.0f); } } else { ((ModelBiped) livingEntityRenderer.getMainModel()) .postRenderArm(0.0625f); } } else { ((ModelBiped) livingEntityRenderer.getMainModel()).postRenderArm(0.0625f); } if (!Settings.OLD_ITEM_HELD) { GlStateManager.translate(-0.0625f, 0.4375f, 0.0625f); } else { if (!((EntityPlayer) entitylivingbaseIn).isBlocking()) { if (Settings.OLD_ITEM_HELD) { GlStateManager.translate(-0.0855f, 0.4775f, 0.1585f); GlStateManager.rotate(-19.0f, 20.0f, 0.0f, -6.0f); break Label_0327; } } if (((EntityPlayer) entitylivingbaseIn).isBlocking()) { GlStateManager.translate(-0.0625f, 0.4375f, 0.0625f); } } } else { ((ModelBiped) livingEntityRenderer.getMainModel()).postRenderArm(0.0625f); GlStateManager.translate(-0.0625f, 0.4375f, 0.0625f); } if (entitylivingbaseIn instanceof EntityPlayer && ((EntityPlayer) entitylivingbaseIn).fishEntity != null) { itemstack = new ItemStack(Items.fishing_rod, 0); } Item item = itemstack.getItem(); Minecraft minecraft = Minecraft.getMinecraft(); if (item instanceof ItemBlock && Block.getBlockFromItem(item).getRenderType() == 2) { GlStateManager.translate(0.0f, 0.1875f, -0.3125f); GlStateManager.rotate(20.0f, 1.0f, 0.0f, 0.0f); GlStateManager.rotate(45.0f, 0.0f, 1.0f, 0.0f); float f2 = 0.375f; GlStateManager.scale(-f2, -f2, f2); } if (entitylivingbaseIn.isSneaking()) { GlStateManager.translate(0.0f, 0.203125f, 0.0f); } minecraft.getItemRenderer().renderItem(entitylivingbaseIn, itemstack, ItemCameraTransforms.TransformType.THIRD_PERSON); GlStateManager.popMatrix(); } } }
412
0.918831
1
0.918831
game-dev
MEDIA
0.927043
game-dev
0.985702
1
0.985702
LangYa466/MCPLite-all-source
1,729
src/main/java/net/minecraft/scoreboard/Team.java
/* * Decompiled with CFR 0.151. */ package net.minecraft.scoreboard; import com.google.common.collect.Maps; import java.util.Collection; import java.util.Map; public abstract class Team { public boolean isSameTeam(Team other) { return other == null ? false : this == other; } public abstract String getRegisteredName(); public abstract String formatString(String var1); public abstract boolean getSeeFriendlyInvisiblesEnabled(); public abstract boolean getAllowFriendlyFire(); public abstract EnumVisible getNameTagVisibility(); public abstract Collection<String> getMembershipCollection(); public abstract EnumVisible getDeathMessageVisibility(); public static enum EnumVisible { ALWAYS("always", 0), NEVER("never", 1), HIDE_FOR_OTHER_TEAMS("hideForOtherTeams", 2), HIDE_FOR_OWN_TEAM("hideForOwnTeam", 3); private static Map<String, EnumVisible> field_178828_g; public final String internalName; public final int id; public static String[] func_178825_a() { return field_178828_g.keySet().toArray(new String[field_178828_g.size()]); } public static EnumVisible func_178824_a(String p_178824_0_) { return field_178828_g.get(p_178824_0_); } private EnumVisible(String p_i45550_3_, int p_i45550_4_) { this.internalName = p_i45550_3_; this.id = p_i45550_4_; } static { field_178828_g = Maps.newHashMap(); for (EnumVisible team$enumvisible : EnumVisible.values()) { field_178828_g.put(team$enumvisible.internalName, team$enumvisible); } } } }
412
0.719815
1
0.719815
game-dev
MEDIA
0.488181
game-dev
0.899944
1
0.899944
Ketho/vscode-wow-api
11,191
Annotations/Core/Blizzard_APIDocumentationGenerated/ContainerDocumentation.lua
---@meta _ C_Container = {} ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.ContainerIDToInventoryID) ---@param containerID Enum.BagIndex ---@return number inventoryID function C_Container.ContainerIDToInventoryID(containerID) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.ContainerRefundItemPurchase) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@param isEquipped? boolean Default = false function C_Container.ContainerRefundItemPurchase(containerIndex, slotIndex, isEquipped) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetBackpackAutosortDisabled) ---@return boolean isDisabled function C_Container.GetBackpackAutosortDisabled() end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetBackpackSellJunkDisabled) ---@return boolean isDisabled function C_Container.GetBackpackSellJunkDisabled() end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetBagName) ---@param bagIndex Enum.BagIndex ---@return string name function C_Container.GetBagName(bagIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetBagSlotFlag) ---@param bagIndex Enum.BagIndex ---@param flag Enum.BagSlotFlags ---@return boolean isSet function C_Container.GetBagSlotFlag(bagIndex, flag) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetBankAutosortDisabled) ---@return boolean isDisabled function C_Container.GetBankAutosortDisabled() end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetContainerFreeSlots) ---@param containerIndex Enum.BagIndex ---@return number[] freeSlots function C_Container.GetContainerFreeSlots(containerIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetContainerItemCooldown) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@return number startTime ---@return number duration ---@return number enable function C_Container.GetContainerItemCooldown(containerIndex, slotIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetContainerItemDurability) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@return number durability ---@return number maxDurability function C_Container.GetContainerItemDurability(containerIndex, slotIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetContainerItemEquipmentSetInfo) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@return boolean inSet ---@return string setList function C_Container.GetContainerItemEquipmentSetInfo(containerIndex, slotIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetContainerItemID) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@return number containerID function C_Container.GetContainerItemID(containerIndex, slotIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetContainerItemInfo) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@return ContainerItemInfo containerInfo function C_Container.GetContainerItemInfo(containerIndex, slotIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetContainerItemLink) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@return string itemLink function C_Container.GetContainerItemLink(containerIndex, slotIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetContainerItemPurchaseCurrency) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@param itemIndex number ---@param isEquipped boolean ---@return ItemPurchaseCurrency currencyInfo function C_Container.GetContainerItemPurchaseCurrency(containerIndex, slotIndex, itemIndex, isEquipped) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetContainerItemPurchaseInfo) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@param isEquipped boolean ---@return ItemPurchaseInfo info function C_Container.GetContainerItemPurchaseInfo(containerIndex, slotIndex, isEquipped) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetContainerItemPurchaseItem) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@param itemIndex number ---@param isEquipped boolean ---@return ItemPurchaseItem itemInfo function C_Container.GetContainerItemPurchaseItem(containerIndex, slotIndex, itemIndex, isEquipped) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetContainerItemQuestInfo) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@return ItemQuestInfo questInfo function C_Container.GetContainerItemQuestInfo(containerIndex, slotIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetContainerNumFreeSlots) ---@param bagIndex Enum.BagIndex ---@return number numFreeSlots ---@return number? bagFamily function C_Container.GetContainerNumFreeSlots(bagIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetContainerNumSlots) ---@param containerIndex Enum.BagIndex ---@return number numSlots function C_Container.GetContainerNumSlots(containerIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetInsertItemsLeftToRight) ---@return boolean isEnabled function C_Container.GetInsertItemsLeftToRight() end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetItemCooldown) ---@param itemID number ---@return number startTime ---@return number duration ---@return number enable function C_Container.GetItemCooldown(itemID) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetMaxArenaCurrency) ---@return number maxCurrency function C_Container.GetMaxArenaCurrency() end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.GetSortBagsRightToLeft) ---@return boolean isEnabled function C_Container.GetSortBagsRightToLeft() end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.HasContainerItem) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@return boolean hasItem function C_Container.HasContainerItem(containerIndex, slotIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.IsBattlePayItem) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@return boolean isBattlePayItem function C_Container.IsBattlePayItem(containerIndex, slotIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.IsContainerFiltered) ---@param containerIndex Enum.BagIndex ---@return boolean isFiltered function C_Container.IsContainerFiltered(containerIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.PickupContainerItem) ---@param containerIndex Enum.BagIndex ---@param slotIndex number function C_Container.PickupContainerItem(containerIndex, slotIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.PlayerHasHearthstone) ---@return number? itemID function C_Container.PlayerHasHearthstone() end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.SetBackpackAutosortDisabled) ---@param disable boolean function C_Container.SetBackpackAutosortDisabled(disable) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.SetBackpackSellJunkDisabled) ---@param disable boolean function C_Container.SetBackpackSellJunkDisabled(disable) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.SetBagPortraitTexture) ---@param texture SimpleTexture ---@param bagIndex Enum.BagIndex function C_Container.SetBagPortraitTexture(texture, bagIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.SetBagSlotFlag) ---@param bagIndex Enum.BagIndex ---@param flag Enum.BagSlotFlags ---@param isSet boolean function C_Container.SetBagSlotFlag(bagIndex, flag, isSet) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.SetBankAutosortDisabled) ---@param disable boolean function C_Container.SetBankAutosortDisabled(disable) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.SetInsertItemsLeftToRight) ---@param enable boolean function C_Container.SetInsertItemsLeftToRight(enable) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.SetItemSearch) ---@param searchString string function C_Container.SetItemSearch(searchString) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.SetSortBagsRightToLeft) ---@param enable boolean function C_Container.SetSortBagsRightToLeft(enable) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.ShowContainerSellCursor) ---@param containerIndex Enum.BagIndex ---@param slotIndex number function C_Container.ShowContainerSellCursor(containerIndex, slotIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.SocketContainerItem) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@return boolean success function C_Container.SocketContainerItem(containerIndex, slotIndex) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.SortAccountBankBags) function C_Container.SortAccountBankBags() end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.SortBags) function C_Container.SortBags() end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.SortBank) ---@param bankType Enum.BankType function C_Container.SortBank(bankType) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.SortBankBags) function C_Container.SortBankBags() end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.SplitContainerItem) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@param amount number function C_Container.SplitContainerItem(containerIndex, slotIndex, amount) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.UseContainerItem) ---@param containerIndex Enum.BagIndex ---@param slotIndex number ---@param unitToken? UnitToken ---@param bankType? Enum.BankType ---@param reagentBankOpen? boolean Default = false function C_Container.UseContainerItem(containerIndex, slotIndex, unitToken, bankType, reagentBankOpen) end ---[Documentation](https://warcraft.wiki.gg/wiki/API_C_Container.UseHearthstone) ---@return boolean used function C_Container.UseHearthstone() end ---@class ContainerItemInfo ---@field iconFileID fileID ---@field stackCount number ---@field isLocked boolean ---@field quality Enum.ItemQuality? ---@field isReadable boolean ---@field hasLoot boolean ---@field hyperlink string ---@field isFiltered boolean ---@field hasNoValue boolean ---@field itemID number ---@field isBound boolean ---@field itemName string ---@class ItemPurchaseCurrency ---@field iconFileID number? ---@field currencyCount number ---@field name string ---@class ItemPurchaseInfo ---@field money WOWMONEY ---@field itemCount number ---@field refundSeconds time_t ---@field currencyCount number ---@field hasEnchants boolean ---@class ItemPurchaseItem ---@field iconFileID number? ---@field itemCount number ---@field hyperlink string ---@class ItemQuestInfo ---@field isQuestItem boolean ---@field questID number? ---@field isActive boolean
412
0.846126
1
0.846126
game-dev
MEDIA
0.960673
game-dev
0.800885
1
0.800885
ProjectIgnis/CardScripts
2,683
official/c34250214.lua
--ヴァンパイアの使い魔 --Vampire Familiar local s,id=GetID() function s.initial_effect(c) --If special summoned, add 1 "Vampire" monster from deck local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DELAY) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetCountLimit(1,id) e1:SetCost(Cost.PayLP(500)) e1:SetTarget(s.thtg) e1:SetOperation(s.thop) c:RegisterEffect(e1) --Special summon itself from GY local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(id,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_GRAVE) e2:SetCountLimit(1,{id,1}) e2:SetCost(s.spcost) e2:SetTarget(s.sptg) e2:SetOperation(s.spop) c:RegisterEffect(e2) end s.listed_series={SET_VAMPIRE} s.listed_names={id} function s.thfilter(c) return c:IsSetCard(SET_VAMPIRE) and c:IsMonster() and not c:IsCode(id) and c:IsAbleToHand() end function s.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.thfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function s.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,s.thfilter,tp,LOCATION_DECK,0,1,1,nil) if #g>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end function s.costfilter(c,tp) return c:IsSetCard(SET_VAMPIRE) and (c:IsLocation(LOCATION_HAND) or c:IsFaceup()) and c:IsAbleToGraveAsCost() and Duel.GetMZoneCount(tp,c)>0 end function s.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.costfilter,tp,LOCATION_ONFIELD|LOCATION_HAND,0,1,nil,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,s.costfilter,tp,LOCATION_ONFIELD|LOCATION_HAND,0,1,1,nil,tp) Duel.SendtoGrave(g,REASON_COST) end function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function s.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)>0 then --Banish it if it leaves the field local e1=Effect.CreateEffect(c) e1:SetDescription(3300) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_LEAVE_FIELD_REDIRECT) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_CLIENT_HINT) e1:SetReset(RESET_EVENT|RESETS_REDIRECT) e1:SetValue(LOCATION_REMOVED) c:RegisterEffect(e1,true) end end
412
0.908761
1
0.908761
game-dev
MEDIA
0.982694
game-dev
0.95114
1
0.95114
Chiheb-Bacha/ScriptHookVDotNetEnhanced
19,254
source/scripting_v2/GTA/Weapons/Weapon.cs
// // Copyright (C) 2015 crosire & kagikn & contributors // License: https://github.com/scripthookvdotnet/scripthookvdotnet#license // using GTA.Native; using System.Linq; namespace GTA { public sealed class Weapon { #region Fields private readonly Ped _owner; #endregion internal Weapon() { Hash = WeaponHash.Unarmed; } internal Weapon(Ped owner, WeaponHash hash) { this._owner = owner; Hash = hash; } public WeaponHash Hash { get; private set; } public string Name { get => SHVDN.NativeMemory.GetGxtEntryByHash((int)SHVDN.NativeMemory.GetHumanNameHashOfWeaponInfo((uint)Hash)); } public string ComponentName(WeaponComponent component) { return Game.GetGXTEntry(GetComponentDisplayNameFromHash(Hash, component)); } public bool IsPresent => Hash == WeaponHash.Unarmed || Function.Call<bool>(Native.Hash.HAS_PED_GOT_WEAPON, _owner.Handle, (uint)Hash); public Model Model => new Model(Function.Call<int>(Native.Hash.GET_WEAPONTYPE_MODEL, (uint)Hash)); public WeaponTint Tint { get => Function.Call<WeaponTint>(Native.Hash.GET_PED_WEAPON_TINT_INDEX, _owner.Handle, (uint)Hash); set => Function.Call(Native.Hash.SET_PED_WEAPON_TINT_INDEX, _owner.Handle, (uint)Hash, (int)value); } public WeaponGroup Group => Function.Call<WeaponGroup>(Native.Hash.GET_WEAPONTYPE_GROUP, (uint)Hash); public int Ammo { get { if (Hash == WeaponHash.Unarmed) { return 1; } if (!IsPresent) { return 0; } return Function.Call<int>(Native.Hash.GET_AMMO_IN_PED_WEAPON, _owner.Handle, (uint)Hash); } set { if (Hash == WeaponHash.Unarmed) { return; } if (IsPresent) { Function.Call(Native.Hash.SET_PED_AMMO, _owner.Handle, (uint)Hash, value); } else { Function.Call(Native.Hash.GIVE_WEAPON_TO_PED, _owner.Handle, (uint)Hash, value, false, true); } } } public int AmmoInClip { get { if (Hash == WeaponHash.Unarmed) { return 1; } if (!IsPresent) { return 0; } int ammoInClip; unsafe { Function.Call(Native.Hash.GET_AMMO_IN_CLIP, _owner.Handle, (uint)Hash, &ammoInClip); } return ammoInClip; } set { if (Hash == WeaponHash.Unarmed) { return; } if (IsPresent) { Function.Call(Native.Hash.SET_AMMO_IN_CLIP, _owner.Handle, (uint)Hash, value); } else { Function.Call(Native.Hash.GIVE_WEAPON_TO_PED, _owner.Handle, (uint)Hash, value, true, false); } } } public int MaxAmmo { get { if (Hash == WeaponHash.Unarmed) { return 1; } int maxAmmo; unsafe { Function.Call(Native.Hash.GET_MAX_AMMO, _owner.Handle, (uint)Hash, &maxAmmo); } return maxAmmo; } } public int MaxAmmoInClip { get { if (Hash == WeaponHash.Unarmed) { return 1; } if (!IsPresent) { return 0; } return Function.Call<int>(Native.Hash.GET_MAX_AMMO_IN_CLIP, _owner.Handle, (uint)Hash, true); } } public int MaxComponents => GetComponentsFromHash(Hash).Length; public int DefaultClipSize => Function.Call<int>(Native.Hash.GET_WEAPON_CLIP_SIZE, (uint)Hash); public bool InfiniteAmmo { set { if (Hash == WeaponHash.Unarmed) { return; } Function.Call(Native.Hash.SET_PED_INFINITE_AMMO, _owner.Handle, value, (uint)Hash); } } public bool InfiniteAmmoClip { set => Function.Call(Native.Hash.SET_PED_INFINITE_AMMO_CLIP, _owner.Handle, value); } public bool CanUseOnParachute => Function.Call<bool>(Native.Hash.CAN_USE_WEAPON_ON_PARACHUTE, (uint)Hash); public WeaponComponent GetComponent(int index) { if (index >= MaxComponents) { return WeaponComponent.Invalid; } return GetComponentsFromHash(Hash)[index]; } public void SetComponent(WeaponComponent component, bool on) { if (on) { Function.Call(Native.Hash.GIVE_WEAPON_COMPONENT_TO_PED, _owner, (uint)Hash, (uint)component); } else { Function.Call(Native.Hash.REMOVE_WEAPON_COMPONENT_FROM_PED, _owner, (uint)Hash, (uint)component); } } public bool IsComponentActive(WeaponComponent component) { return Function.Call<bool>(Native.Hash.HAS_PED_GOT_WEAPON_COMPONENT, _owner, (uint)Hash, (uint)component); } public static string GetDisplayNameFromHash(WeaponHash hash) { // Will be found in this switch statement if the hash is one of the weapon hashes for singleplayer switch (hash) { case WeaponHash.Unarmed: return "WT_UNARMED"; case WeaponHash.Knife: return "WT_KNIFE"; case WeaponHash.Nightstick: return "WT_NGTSTK"; case WeaponHash.Hammer: return "WT_HAMMER"; case WeaponHash.Bat: return "WT_BAT"; case WeaponHash.Crowbar: return "WT_CROWBAR"; case WeaponHash.GolfClub: return "WT_GOLFCLUB"; case WeaponHash.Pistol: return "WT_PIST"; case WeaponHash.CombatPistol: return "WT_PIST_CBT"; case WeaponHash.Pistol50: return "WT_PIST_50"; case WeaponHash.APPistol: return "WT_PIST_AP"; case WeaponHash.StunGun: return "WT_STUN"; case WeaponHash.MicroSMG: return "WT_SMG_MCR"; case WeaponHash.SMG: return "WT_SMG"; case WeaponHash.AssaultSMG: return "WT_SMG_ASL"; case WeaponHash.AssaultRifle: return "WT_RIFLE_ASL"; case WeaponHash.CarbineRifle: return "WT_RIFLE_CBN"; case WeaponHash.AdvancedRifle: return "WT_RIFLE_ADV"; case WeaponHash.MG: return "WT_MG"; case WeaponHash.CombatMG: return "WT_MG_CBT"; case WeaponHash.PumpShotgun: return "WT_SG_PMP"; case WeaponHash.SawnOffShotgun: return "WT_SG_SOF"; case WeaponHash.AssaultShotgun: return "WT_SG_ASL"; case WeaponHash.BullpupShotgun: return "WT_SG_BLP"; case WeaponHash.SniperRifle: return "WT_SNIP_RIF"; case WeaponHash.HeavySniper: return "WT_SNIP_HVY"; case WeaponHash.GrenadeLauncher: return "WT_GL"; case WeaponHash.RPG: return "WT_RPG"; case WeaponHash.Minigun: return "WT_MINIGUN"; case WeaponHash.Grenade: return "WT_GNADE"; case WeaponHash.StickyBomb: return "WT_GNADE_STK"; case WeaponHash.SmokeGrenade: return "WT_GNADE_SMK"; case WeaponHash.BZGas: return "WT_BZGAS"; case WeaponHash.Molotov: return "WT_MOLOTOV"; case WeaponHash.FireExtinguisher: return "WT_FIRE"; case WeaponHash.PetrolCan: return "WT_PETROL"; case WeaponHash.Ball: return "WT_BALL"; case WeaponHash.Flare: return "WT_FLARE"; case WeaponHash.Bottle: return "WT_BOTTLE"; case WeaponHash.Dagger: return "WT_DAGGER"; case WeaponHash.Hatchet: return "WT_HATCHET"; case WeaponHash.Machete: return "WT_MACHETE"; case WeaponHash.KnuckleDuster: return "WT_KNUCKLE"; case WeaponHash.SNSPistol: return "WT_SNSPISTOL"; case WeaponHash.VintagePistol: return "WT_VPISTOL"; case WeaponHash.HeavyPistol: return "WT_HVYPISTOL"; case WeaponHash.MarksmanPistol: return "WT_MKPISTOL"; case WeaponHash.Gusenberg: return "WT_GUSENBERG"; case WeaponHash.MachinePistol: return "WT_MCHPIST"; case WeaponHash.CombatPDW: return "WT_COMBATPDW"; case WeaponHash.SpecialCarbine: return "WT_SPCARBINE"; case WeaponHash.HeavyShotgun: return "WT_HVYSHOT"; case WeaponHash.Musket: return "WT_MUSKET"; case WeaponHash.MarksmanRifle: return "WT_MKRIFLE"; case WeaponHash.Firework: return "WT_FWRKLNCHR"; case WeaponHash.HomingLauncher: return "WT_HOMLNCH"; case WeaponHash.Railgun: return "WT_RAILGUN"; case WeaponHash.ProximityMine: return "WT_PRXMINE"; // there is no WeaponShopItem for the weapon snowballs, so listed here case WeaponHash.Snowball: return "WT_SNWBALL"; } DlcWeaponData data; for (int i = 0, max = Function.Call<int>(Native.Hash.GET_NUM_DLC_WEAPONS); i < max; i++) { unsafe { if (!Function.Call<bool>(Native.Hash.GET_DLC_WEAPON_DATA, i, (int*)&data)) { continue; } if (data.Hash == hash) { return data.DisplayName; } } } return "WT_INVALID"; } public static string GetComponentDisplayNameFromHash(WeaponHash hash, WeaponComponent component) { // Will be found in this switch statement if the hash is one of the weapon component hashes for singleplayer switch (component) { case WeaponComponent.Invalid: return "WCT_INVALID"; case WeaponComponent.AtRailCover01: return "WCT_RAIL"; case WeaponComponent.AtArAfGrip: return "WCT_GRIP"; case WeaponComponent.AtPiFlsh: case WeaponComponent.AtArFlsh: return "WCT_FLASH"; case WeaponComponent.AtScopeMacro: case WeaponComponent.AtScopeMacro02: return "WCT_SCOPE_MAC"; case WeaponComponent.AtScopeSmall: case WeaponComponent.AtScopeSmall02: return "WCT_SCOPE_SML"; case WeaponComponent.AtScopeMedium: return "WCT_SCOPE_MED"; case WeaponComponent.AtScopeLarge: case WeaponComponent.AtScopeLargeFixedZoom: return "WCT_SCOPE_LRG"; case WeaponComponent.AtScopeMax: return "WCT_SCOPE_MAX"; case WeaponComponent.AtPiSupp: case WeaponComponent.AtArSupp: case WeaponComponent.AtSrSupp: return "WCT_SUPP"; case WeaponComponent.PistolClip01: case WeaponComponent.CombatPistolClip01: case WeaponComponent.APPistolClip01: case WeaponComponent.MicroSMGClip01: case WeaponComponent.SMGClip01: case WeaponComponent.AssaultRifleClip01: case WeaponComponent.CarbineRifleClip01: case WeaponComponent.AdvancedRifleClip01: case WeaponComponent.MGClip01: case WeaponComponent.CombatMGClip01: case WeaponComponent.AssaultShotgunClip01: case WeaponComponent.SniperRifleClip01: case WeaponComponent.HeavySniperClip01: case WeaponComponent.AssaultSMGClip01: case WeaponComponent.Pistol50Clip01: case (WeaponComponent)0x0BAAB157: case (WeaponComponent)0x5AF49386: case (WeaponComponent)0xCAEBD246: case (WeaponComponent)0xF8955D89: case WeaponComponent.SNSPistolClip01: case WeaponComponent.VintagePistolClip01: case WeaponComponent.HeavyShotgunClip01: case WeaponComponent.MarksmanRifleClip01: case WeaponComponent.CombatPDWClip01: case WeaponComponent.MarksmanPistolClip01: case WeaponComponent.MachinePistolClip01: return "WCT_CLIP1"; case WeaponComponent.PistolClip02: case WeaponComponent.CombatPistolClip02: case WeaponComponent.APPistolClip02: case WeaponComponent.MicroSMGClip02: case WeaponComponent.SMGClip02: case WeaponComponent.AssaultRifleClip02: case WeaponComponent.CarbineRifleClip02: case WeaponComponent.AdvancedRifleClip02: case WeaponComponent.MGClip02: case WeaponComponent.CombatMGClip02: case WeaponComponent.AssaultShotgunClip02: case WeaponComponent.MinigunClip01: case WeaponComponent.AssaultSMGClip02: case WeaponComponent.Pistol50Clip02: case (WeaponComponent)0x6CBF371B: case (WeaponComponent)0xE1C5FFFA: case (WeaponComponent)0x3E7E6956: case WeaponComponent.SNSPistolClip02: case WeaponComponent.VintagePistolClip02: case WeaponComponent.HeavyShotgunClip02: case WeaponComponent.MarksmanRifleClip02: case WeaponComponent.CombatPDWClip02: case WeaponComponent.MachinePistolClip02: return "WCT_CLIP2"; case WeaponComponent.AssaultRifleVarmodLuxe: case WeaponComponent.CarbineRifleVarmodLuxe: case WeaponComponent.PistolVarmodLuxe: case WeaponComponent.SMGVarmodLuxe: case WeaponComponent.MicroSMGVarmodLuxe: case WeaponComponent.MarksmanRifleVarmodLuxe: case WeaponComponent.AssaultSMGVarmodLowrider: case WeaponComponent.CombatPistolVarmodLowrider: case WeaponComponent.MGVarmodLowrider: case WeaponComponent.PumpShotgunVarmodLowrider: return "WCT_VAR_GOLD"; case WeaponComponent.AdvancedRifleVarmodLuxe: case WeaponComponent.APPistolVarmodLuxe: case WeaponComponent.SawnoffShotgunVarmodLuxe: case WeaponComponent.BullpupRifleVarmodLow: return "WCT_VAR_METAL"; case WeaponComponent.Pistol50VarmodLuxe: return "WCT_VAR_SIL"; case WeaponComponent.HeavyPistolVarmodLuxe: case WeaponComponent.SniperRifleVarmodLuxe: case WeaponComponent.SNSPistolVarmodLowrider: return "WCT_VAR_WOOD"; case WeaponComponent.CombatMGVarmodLowrider: case WeaponComponent.SpecialCarbineVarmodLowrider: return "WCT_VAR_ETCHM"; case WeaponComponent.SMGClip03: case WeaponComponent.AssaultRifleClip03: case WeaponComponent.HeavyShotgunClip03: return "WCT_CLIP_DRM"; case WeaponComponent.CarbineRifleClip03: return "WCT_CLIP_BOX"; } DlcWeaponData data; DlcWeaponComponentData componentData; for (int i = 0, max = Function.Call<int>(Native.Hash.GET_NUM_DLC_WEAPONS); i < max; i++) { unsafe { if (!Function.Call<bool>(Native.Hash.GET_DLC_WEAPON_DATA, i, (int*)&data)) { continue; } if (data.Hash != hash) { continue; } int maxComp = Function.Call<int>(Native.Hash.GET_NUM_DLC_WEAPON_COMPONENTS, i); for (int j = 0; j < maxComp; j++) { if (!Function.Call<bool>(Native.Hash.GET_DLC_WEAPON_COMPONENT_DATA, i, j, (int*)&componentData)) { continue; } if (componentData.Hash == component) { return componentData.DisplayName; } } } } return "WCT_INVALID"; } public static WeaponComponent[] GetComponentsFromHash(WeaponHash hash) { return SHVDN.NativeMemory.GetAllCompatibleWeaponComponentHashes((uint)hash).Select(x => (WeaponComponent)x).ToArray(); } } }
412
0.796401
1
0.796401
game-dev
MEDIA
0.956501
game-dev
0.644019
1
0.644019
DeltaEngine/DeltaEngine
2,581
Samples/CreepyTowers/GUI/Settings.cs
using CreepyTowers.Content; using DeltaEngine.Content; using DeltaEngine.Multimedia; using DeltaEngine.Scenes; using DeltaEngine.Scenes.Controls; namespace CreepyTowers.GUI { public class Settings : Menu { public Settings() { CreateScene(); } protected override sealed void CreateScene() { Scene = ContentLoader.Load<Scene>(GameMenus.SceneSettingsMenu.ToString()); Hide(); AttachBackButtonEvent(); SetMusicVolume(); SetSoundVolume(); } private void AttachBackButtonEvent() { backButton = (InteractiveButton)GetSceneControl(Content.Settings.ButtonBack.ToString()); backButton.Clicked += ShowMainMenu; } private InteractiveButton backButton; private static void ShowMainMenu() { PlayClickedSound(); MenuController.Current.HideMenu(GameMenus.SceneSettingsMenu); MenuController.Current.ShowMenu(GameMenus.SceneMainMenu); } private static void PlayClickedSound() { var sound = ContentLoader.Load<Sound>(GameSounds.MenuButtonClick.ToString()); sound.Play(); } private void SetMusicVolume() { musicSlider = (Slider)GetSceneControl(Content.Settings.MusicVolumeSlider.ToString()); InitializeMusicSlider(); SetMusicSliderValue(); musicSlider.ValueChanged += value => { var musicVol = value / (float)musicSlider.MaxValue; Game.SoundDevice.MusicVolume = musicVol; SetMusicSliderValue(); }; } private void InitializeMusicSlider() { musicSlider.MinValue = 0; musicSlider.MaxValue = 100; } private void SetMusicSliderValue() { musicSlider.Value = (int)(DeltaEngine.Core.Settings.Current.MusicVolume * musicSlider.MaxValue); } private Slider musicSlider; private void SetSoundVolume() { soundSlider = (Slider)GetSceneControl(Content.Settings.SoundVolumeSlider.ToString()); InitializeSoundSliderValues(); SetSoundSliderValue(); soundSlider.ValueChanged += value => { DeltaEngine.Core.Settings.Current.SoundVolume = value / (float)soundSlider.MaxValue; PlayDummySound(); SetSoundSliderValue(); }; } private void InitializeSoundSliderValues() { soundSlider.MinValue = 0; soundSlider.MaxValue = 10; } private void SetSoundSliderValue() { soundSlider.Value = (int)(DeltaEngine.Core.Settings.Current.SoundVolume * soundSlider.MaxValue); } private static void PlayDummySound() { var sound = ContentLoader.Load<Sound>(GameSounds.MenuButtonClick.ToString()); if (!sound.IsAnyInstancePlaying) sound.Play(); } private Slider soundSlider; public override void Reset() {} } }
412
0.638414
1
0.638414
game-dev
MEDIA
0.833969
game-dev,audio-video-media
0.84211
1
0.84211
SpinalHDL/SpinalHDL
1,680
lib/src/main/scala/spinal/lib/bus/tilelink/sim/SlaveDriver.scala
package spinal.lib.bus.tilelink.sim import spinal.core._ import spinal.core.sim._ import spinal.lib.bus.tilelink._ import spinal.lib.sim.{StreamDriver, StreamDriverOoo, StreamMonitor, StreamReadyRandomizer} class SlaveDriver(bus : Bus, cd : ClockDomain) { val driver = new Area{ val a = StreamReadyRandomizer(bus.a, cd) val b = bus.p.withBCE generate StreamDriverOoo(bus.b, cd) val c = bus.p.withBCE generate StreamReadyRandomizer(bus.c, cd) val d = StreamDriverOoo(bus.d, cd) val e = bus.p.withBCE generate StreamReadyRandomizer(bus.e, cd) def noStall(): Unit = { a.factor = 1.0f if (b != null) b.ctrl.transactionDelay = () => 0 if (c != null) c.factor = 1.0f d.ctrl.transactionDelay = () => 0 if (e != null) e.factor = 1.0f } def randomizeStallRate(): Unit = { a.setFactor(simRandom.nextFloat()) if (b != null) b.ctrl.setFactor(simRandom.nextFloat()) if (c != null) c.setFactor(simRandom.nextFloat()) d.ctrl.setFactor(simRandom.nextFloat()) if (e != null) e.setFactor(simRandom.nextFloat()) } def setFactor(factor : Float): Unit = { a.setFactor(factor) if (b != null) b.ctrl.setFactor(factor) if (c != null) c.setFactor(factor) d.ctrl.setFactor(factor) if (e != null) e.setFactor(factor) } } def scheduleD(d : TransactionD): Unit ={ val beats = d.serialize(bus.p.dataBytes) driver.d.burst{push => for(beat <- beats) push(beat.write) } } def scheduleB(b : TransactionB): Unit ={ val beats = b.serialize(bus.p.dataBytes) driver.b.burst{push => for(beat <- beats) push(beat.write) } } }
412
0.77044
1
0.77044
game-dev
MEDIA
0.338113
game-dev
0.975459
1
0.975459
The-Final-Nights/The-Final-Nights
4,577
code/datums/components/explodable.dm
///Component specifically for explosion sensetive things, currently only applies to heat based explosions but can later perhaps be used for things that are dangerous to handle carelessly like nitroglycerin. /datum/component/explodable var/devastation_range = 0 var/heavy_impact_range = 0 var/light_impact_range = 2 var/flash_range = 3 var/equipped_slot //For items, lets us determine where things should be hit. ///wheter we always delete. useful for nukes turned plasma and such, so they don't default delete and can survive var/always_delete /datum/component/explodable/Initialize(devastation_range_override, heavy_impact_range_override, light_impact_range_override, flash_range_override, _always_delete = TRUE) if(!isatom(parent)) return COMPONENT_INCOMPATIBLE RegisterSignal(parent, COMSIG_PARENT_ATTACKBY, PROC_REF(explodable_attack)) RegisterSignal(parent, COMSIG_TRY_STORAGE_INSERT, PROC_REF(explodable_insert_item)) RegisterSignal(parent, COMSIG_ATOM_EX_ACT, PROC_REF(detonate)) if(ismovable(parent)) RegisterSignal(parent, COMSIG_MOVABLE_IMPACT, PROC_REF(explodable_impact)) RegisterSignal(parent, COMSIG_MOVABLE_BUMP, PROC_REF(explodable_bump)) if(isitem(parent)) RegisterSignals(parent, list(COMSIG_ITEM_ATTACK, COMSIG_ITEM_ATTACK_OBJ, COMSIG_ITEM_HIT_REACT), PROC_REF(explodable_attack)) RegisterSignal(parent, COMSIG_ITEM_EQUIPPED, PROC_REF(on_equip)) RegisterSignal(parent, COMSIG_ITEM_DROPPED, PROC_REF(on_drop)) if(devastation_range_override) devastation_range = devastation_range_override if(heavy_impact_range_override) heavy_impact_range = heavy_impact_range_override if(light_impact_range_override) light_impact_range = light_impact_range_override if(flash_range_override) flash_range = flash_range_override always_delete = _always_delete /datum/component/explodable/proc/explodable_insert_item(datum/source, obj/item/I, mob/M, silent = FALSE, force = FALSE) SIGNAL_HANDLER check_if_detonate(I) /datum/component/explodable/proc/explodable_impact(datum/source, atom/hit_atom, datum/thrownthing/throwingdatum) SIGNAL_HANDLER check_if_detonate(hit_atom) /datum/component/explodable/proc/explodable_bump(datum/source, atom/A) SIGNAL_HANDLER check_if_detonate(A) ///Called when you use this object to attack sopmething /datum/component/explodable/proc/explodable_attack(datum/source, atom/movable/target, mob/living/user) SIGNAL_HANDLER check_if_detonate(target) ///Called when you attack a specific body part of the thing this is equipped on. Useful for exploding pants. /datum/component/explodable/proc/explodable_attack_zone(datum/source, damage, damagetype, def_zone, ...) SIGNAL_HANDLER if(!def_zone) return if(damagetype != BURN) //Don't bother if it's not fire. return if(isbodypart(def_zone)) var/obj/item/bodypart/hitting = def_zone def_zone = hitting.body_zone if(!is_hitting_zone(def_zone)) //You didn't hit us! ha! return detonate() /datum/component/explodable/proc/on_equip(datum/source, mob/equipper, slot) SIGNAL_HANDLER RegisterSignal(equipper, COMSIG_MOB_APPLY_DAMAGE, PROC_REF(explodable_attack_zone), TRUE) /datum/component/explodable/proc/on_drop(datum/source, mob/user) SIGNAL_HANDLER UnregisterSignal(user, COMSIG_MOB_APPLY_DAMAGE) /// Checks if we're hitting the zone this component is covering /datum/component/explodable/proc/is_hitting_zone(def_zone) var/obj/item/item = parent var/mob/living/L = item.loc //Get whoever is equipping the item currently if(!istype(L)) return var/obj/item/bodypart/bodypart = L.get_bodypart(check_zone(def_zone)) var/list/equipment_items = list() if(iscarbon(L)) var/mob/living/carbon/C = L equipment_items += list(C.head, C.wear_mask, C.back, C.gloves, C.shoes, C.glasses, C.ears) if(ishuman(C)) var/mob/living/carbon/human/H = C equipment_items += list(H.wear_suit, H.w_uniform, H.belt, H.s_store, H.wear_id) for(var/bp in equipment_items) if(!bp) continue var/obj/item/I = bp if(I.body_parts_covered & bodypart.body_part) return TRUE return FALSE /datum/component/explodable/proc/check_if_detonate(target) if(!isitem(target)) return var/obj/item/I = target if(!I.get_temperature()) return detonate() //If we're touching a hot item we go boom /// Expldoe and remove the object /datum/component/explodable/proc/detonate() SIGNAL_HANDLER var/atom/A = parent var/log = TRUE if(light_impact_range < 1) log = FALSE explosion(A, devastation_range, heavy_impact_range, light_impact_range, flash_range, log) //epic explosion time if(always_delete) qdel(A)
412
0.982096
1
0.982096
game-dev
MEDIA
0.914179
game-dev
0.869729
1
0.869729
OpenFunscripter/OFS
10,069
OFS-lib/Funscript/Funscript.h
#pragma once #include "nlohmann/json.hpp" #include "FunscriptAction.h" #include "OFS_Reflection.h" #include "OFS_Serialization.h" #include "OFS_BinarySerialization.h" #include <string> #include <memory> #include <chrono> #include "OFS_Util.h" #include "FunscriptSpline.h" #include "OFS_Profiling.h" #include "OFS_Event.h" class FunscriptUndoSystem; class Funscript; class FunscriptActionsChangedEvent : public OFS_Event<FunscriptActionsChangedEvent> { public: // FIXME: get rid of this raw pointer const Funscript* Script = nullptr; FunscriptActionsChangedEvent(const Funscript* changedScript) noexcept : Script(changedScript) {} }; class FunscriptSelectionChangedEvent : public OFS_Event<FunscriptSelectionChangedEvent> { public: // FIXME: get rid of this raw pointer const Funscript* Script = nullptr; FunscriptSelectionChangedEvent(const Funscript* changedScript) noexcept : Script(changedScript) {} }; class FunscriptNameChangedEvent : public OFS_Event<FunscriptNameChangedEvent> { public: // FIXME: get rid of this raw pointer const Funscript* Script = nullptr; std::string oldName; FunscriptNameChangedEvent(const Funscript* changedScript, const std::string& oldName) noexcept : Script(changedScript), oldName(oldName) {} }; class FunscriptRemovedEvent : public OFS_Event<FunscriptRemovedEvent> { public: std::string name; FunscriptRemovedEvent(const std::string& name) noexcept : name(name) {} }; class Funscript { public: static constexpr auto Extension = ".funscript"; struct FunscriptData { FunscriptArray Actions; FunscriptArray Selection; }; struct Metadata { std::string type = "basic"; std::string title; std::string creator; std::string script_url; std::string video_url; std::vector<std::string> tags; std::vector<std::string> performers; std::string description; std::string license; std::string notes; int64_t duration = 0; }; template<typename S> void serialize(S& s) { s.ext(*this, bitsery::ext::Growable{}, [](S& s, Funscript& o) { s.container(o.data.Actions, std::numeric_limits<uint32_t>::max()); s.text1b(o.currentPathRelative, o.currentPathRelative.max_size()); s.text1b(o.title, o.title.max_size()); s.boolValue(o.Enabled); }); } private: // FIXME: OFS should be able to retain metadata injected by other programs without overwriting it //nlohmann::json JsonOther; std::chrono::system_clock::time_point editTime; bool funscriptChanged = false; // used to fire only one event every frame a change occurs bool unsavedEdits = false; // used to track if the script has unsaved changes bool selectionChanged = false; FunscriptData data; void checkForInvalidatedActions() noexcept; inline FunscriptAction* getAction(FunscriptAction action) noexcept { OFS_PROFILE(__FUNCTION__); if (data.Actions.empty()) return nullptr; auto it = data.Actions.find(action); if(it != data.Actions.end()) { return &*it; } return nullptr; } public: static inline FunscriptAction* getActionAtTime(FunscriptArray& actions, float time, float maxErrorTime) noexcept { OFS_PROFILE(__FUNCTION__); if (actions.empty()) return nullptr; // gets an action at a time with a margin of error float smallestError = std::numeric_limits<float>::max(); FunscriptAction* smallestErrorAction = nullptr; int i = 0; auto it = actions.lower_bound(FunscriptAction(time - maxErrorTime, 0)); if (it != actions.end()) { i = std::distance(actions.begin(), it); if (i > 0) --i; } for (; i < actions.size(); i++) { auto& action = actions[i]; if (action.atS > (time + (maxErrorTime / 2))) break; auto error = std::abs(time - action.atS); if (error <= maxErrorTime) { if (error <= smallestError) { smallestError = error; smallestErrorAction = &action; } else { break; } } } return smallestErrorAction; } private: inline FunscriptAction* getNextActionAhead(float time) noexcept { OFS_PROFILE(__FUNCTION__); if (data.Actions.empty()) return nullptr; auto it = data.Actions.upper_bound(FunscriptAction(time, 0)); return it != data.Actions.end() ? &*it : nullptr; } inline FunscriptAction* getPreviousActionBehind(float time) noexcept { OFS_PROFILE(__FUNCTION__); if (data.Actions.empty()) return nullptr; auto it = data.Actions.lower_bound(FunscriptAction(time, 0)); if(it != data.Actions.begin()) { return &*(--it); } return nullptr; } void moveAllActionsTime(float timeOffset); void moveActionsPosition(std::vector<FunscriptAction*> moving, int32_t posOffset); inline void sortSelection() noexcept { sortActions(data.Selection); } inline void sortActions(FunscriptArray& actions) noexcept { std::sort(actions.begin(), actions.end()); } inline void addAction(FunscriptArray& actions, FunscriptAction newAction) noexcept { actions.emplace(newAction); notifyActionsChanged(true); } inline void notifySelectionChanged() noexcept { selectionChanged = true; } static void loadMetadata(const nlohmann::json& metadataObj, Funscript::Metadata& outMetadata) noexcept; static void saveMetadata(nlohmann::json& outMetadataObj, const Funscript::Metadata& inMetadata) noexcept; void notifyActionsChanged(bool isEdit) noexcept; std::string currentPathRelative; std::string title; public: Funscript() noexcept; ~Funscript() noexcept; static std::array<const char*, 9> AxisNames; bool Enabled = true; std::unique_ptr<FunscriptUndoSystem> undoSystem; void UpdateRelativePath(const std::string& path) noexcept; inline void ClearUnsavedEdits() noexcept { unsavedEdits = false; } inline const std::string& RelativePath() const noexcept { return currentPathRelative; } inline const std::string& Title() const noexcept { return title; } inline void Rollback(FunscriptData&& data) noexcept { this->data = std::move(data); notifyActionsChanged(true); } inline void Rollback(const FunscriptData& data) noexcept { this->data = data; notifyActionsChanged(true); } void Update() noexcept; bool Deserialize(const nlohmann::json& json, Funscript::Metadata* outMetadata, bool loadChapters) noexcept; inline nlohmann::json Serialize(const Funscript::Metadata& metadata, bool includeChapters) const noexcept { nlohmann::json json; Serialize(json, data, metadata, includeChapters); return json; } static void Serialize(nlohmann::json& json, const FunscriptData& funscriptData, const Funscript::Metadata& metadata, bool includeChapters) noexcept; inline const FunscriptData& Data() const noexcept { return data; } inline const auto& Selection() const noexcept { return data.Selection; } inline const auto& Actions() const noexcept { return data.Actions; } inline const FunscriptAction* GetAction(FunscriptAction action) noexcept { return getAction(action); } inline const FunscriptAction* GetActionAtTime(float time, float errorTime) noexcept { return getActionAtTime(data.Actions, time, errorTime); } inline const FunscriptAction* GetNextActionAhead(float time) noexcept { return getNextActionAhead(time); } inline const FunscriptAction* GetPreviousActionBehind(float time) noexcept { return getPreviousActionBehind(time); } inline const FunscriptAction* GetClosestAction(float time) noexcept { return getActionAtTime(data.Actions, time, std::numeric_limits<float>::max()); } float GetPositionAtTime(float time) const noexcept; inline void AddAction(FunscriptAction newAction) noexcept { addAction(data.Actions, newAction); } void AddMultipleActions(const FunscriptArray& actions) noexcept; bool EditAction(FunscriptAction oldAction, FunscriptAction newAction) noexcept; void AddEditAction(FunscriptAction action, float frameTime) noexcept; void RemoveAction(FunscriptAction action, bool checkInvalidSelection = true) noexcept; void RemoveActions(const FunscriptArray& actions) noexcept; std::vector<FunscriptAction> GetLastStroke(float time) noexcept; void SetActions(const FunscriptArray& override_with) noexcept; inline bool HasUnsavedEdits() const { return unsavedEdits; } inline const std::chrono::system_clock::time_point& EditTime() const { return editTime; } void RemoveActionsInInterval(float fromTime, float toTime) noexcept; // selection api void RangeExtendSelection(int32_t rangeExtend) noexcept; bool ToggleSelection(FunscriptAction action) noexcept; void SetSelected(FunscriptAction action, bool selected) noexcept; void SelectTopActions() noexcept; void SelectBottomActions() noexcept; void SelectMidActions() noexcept; void SelectTime(float fromTime, float toTime, bool clear=true) noexcept; FunscriptArray GetSelection(float fromTime, float toTime) noexcept; void SelectAction(FunscriptAction select) noexcept; void DeselectAction(FunscriptAction deselect) noexcept; void SelectAll() noexcept; void RemoveSelectedActions() noexcept; void MoveSelectionTime(float time_offset, float frameTime) noexcept; void MoveSelectionPosition(int32_t pos_offset) noexcept; inline bool HasSelection() const noexcept { return !data.Selection.empty(); } inline uint32_t SelectionSize() const noexcept { return data.Selection.size(); } inline void ClearSelection() noexcept { data.Selection.clear(); } inline const FunscriptAction* GetClosestActionSelection(float time) noexcept { return getActionAtTime(data.Selection, time, std::numeric_limits<float>::max()); } void SetSelection(const FunscriptArray& actions) noexcept; bool IsSelected(FunscriptAction action) noexcept; void EqualizeSelection() noexcept; void InvertSelection() noexcept; FunscriptSpline ScriptSpline; inline const float Spline(float time) noexcept { return ScriptSpline.Sample(data.Actions, time); } inline const float SplineClamped(float time) noexcept { return Util::Clamp<float>(Spline(time) * 100.f, 0.f, 100.f); } }; REFL_TYPE(Funscript::Metadata) REFL_FIELD(type) REFL_FIELD(title) REFL_FIELD(creator) REFL_FIELD(script_url) REFL_FIELD(video_url) REFL_FIELD(tags) REFL_FIELD(performers) REFL_FIELD(description) REFL_FIELD(license) REFL_FIELD(notes) REFL_FIELD(duration) REFL_END
412
0.913524
1
0.913524
game-dev
MEDIA
0.809695
game-dev
0.91688
1
0.91688
Lakatrazz/BONELAB-Fusion
2,372
LabFusion/src/Entities/Props/BodyPose.cs
using LabFusion.Data; using LabFusion.Network.Serialization; using UnityEngine; namespace LabFusion.Entities; public class BodyPose : INetSerializable { public const int Size = SerializedShortVector3.Size + SerializedSmallQuaternion.Size + SerializedSmallVector3.Size * 2; public Vector3 position = Vector3.zero; public Quaternion rotation = Quaternion.identity; public Vector3 velocity = Vector3.zero; public Vector3 angularVelocity = Vector3.zero; private Vector3 _positionPrediction = Vector3.zero; public Vector3 PredictedPosition => position + _positionPrediction; public void ReadFrom(Rigidbody rigidbody) { position = rigidbody.position; rotation = rigidbody.rotation; velocity = rigidbody.velocity; angularVelocity = rigidbody.angularVelocity; } public void CopyTo(BodyPose target) { target.position = position; target.rotation = rotation; target.velocity = velocity; target.angularVelocity = angularVelocity; target.ResetPrediction(); } public void ResetPrediction() { _positionPrediction = Vector3.zero; } public void PredictPosition(float deltaTime) { _positionPrediction += velocity * deltaTime; } public void Serialize(INetSerializer serializer) { SerializedShortVector3 position = null; SerializedSmallQuaternion rotation = null; SerializedSmallVector3 velocity = null; SerializedSmallVector3 angularVelocity = null; if (!serializer.IsReader) { position = SerializedShortVector3.Compress(this.position); rotation = SerializedSmallQuaternion.Compress(this.rotation); velocity = SerializedSmallVector3.Compress(this.velocity); angularVelocity = SerializedSmallVector3.Compress(this.angularVelocity); } serializer.SerializeValue(ref position); serializer.SerializeValue(ref rotation); serializer.SerializeValue(ref velocity); serializer.SerializeValue(ref angularVelocity); if (serializer.IsReader) { this.position = position.Expand(); this.rotation = rotation.Expand(); this.velocity = velocity.Expand(); this.angularVelocity = angularVelocity.Expand(); } } }
412
0.605239
1
0.605239
game-dev
MEDIA
0.705735
game-dev
0.851922
1
0.851922
fetty31/FSDriverless
7,460
ros/ros1_ws/src/tracker/src/accumulator.cpp
/* * @author Oriol Martínez @fetty31 * @date 3-3-2024 * @version 1.0 * * Copyright (c) 2024 BCN eMotorsport */ #include "accumulator.hh" namespace tracker{ Accumulator::Accumulator(double &mean, double &std) : threshold(0.1), radius(20.0), vision_angle(1.57), likelihood(0.9), Lf(1.5), Lr(1.0), T(1.42) { noise = new noise::Gaussian(mean, std); } Accumulator::~Accumulator(){ delete noise; } void Accumulator::create_KDTree(){ std::vector<Point> vect; Point p; for(int i=0; i<track.size(); i++){ p[0] = track[i].position[0]; p[1] = track[i].position[1]; vect.push_back(p); } Tree.build(vect); treeFlag = true; seen_idx.reserve(track.size()); // reserve space for all seen cones } bool Accumulator::isTreeBuild(){ return treeFlag; } void Accumulator::fillTracker(const visualization_msgs::MarkerArray::ConstPtr& msg){ Point position; for(auto marker : msg->markers){ position[0] = marker.pose.position.x; position[1] = marker.pose.position.y; noise->add_radial_noise(&position); // add noise to the cone position (x,y) int type = 0; // yellow cone by default if(marker.ns == "cone_blue") type = 1; else if(marker.ns == "cone_orange") type = 2; else if(marker.ns == "cone_orange_big") type = 3; Cone cone = Cone(marker.id, type, position, Point()); // we don't care about the cone's base link position for now this->track.push_back(cone); } this->create_KDTree(); } template<typename NUM> NUM Accumulator::mod(NUM x, NUM y){ return sqrt(pow(x,2)+pow(y,2)); } // Norm of (x,y) vector // Check if the given is the same cone as the one in the accumulator bool Accumulator::sameCone(Point p){ int nnid = Tree.nnSearch(p); if( mod<double>(p[0]-track[nnid].position[0], p[1]-track[nnid].position[1]) < this->threshold ) return true; else return false; } void Accumulator::fillConeMsg(int id, ipg_msgs::Cone* msg){ msg->id = track[id].id; msg->type = track[id].type; msg->position_baseLink.x = track[id].positionBL[0]; msg->position_baseLink.y = track[id].positionBL[1]; msg->position_global.x = track[id].position[0]; msg->position_global.y = track[id].position[1]; } Point Accumulator::local2global(const Point p, const Eigen::Vector3d& pose) { Point point; point[0] = pose(0) + p[0]*cos(pose(2)) - p[1]*sin(pose(2)); point[1] = pose(1) + p[0]*sin(pose(2)) + p[1]*cos(pose(2)); return point; } Point Accumulator::global2local(const Point p, const Eigen::Vector3d& pose) { Point point; point[0] = +(p[0] - pose(0))*cos(pose(2)) + (p[1] - pose(1))*sin(pose(2)); point[1] = -(p[0] - pose(0))*sin(pose(2)) + (p[1] - pose(1))*cos(pose(2)); return point; } // Reset all values (a new Test Run is started) bool Accumulator::reset(){ // Clear (and reallocate) used vectors std::vector<Cone>().swap(track); std::vector<int>().swap(seen_idx); // Clear set moved_idx.clear(); // Reset flags this->treeFlag = false; this->stateFlag = false; // Reset cones down counter this->cones_down = 0; // Reset lapcount this->lapcount.reset(); // Update reset flag this->resetFlag = true; return true; } // Check whether the cone is hit bool Accumulator::coneDown(int &id, StateCar* state){ if(track[id].positionBL[0] >= 0.0){ // front axle if( track[id].positionBL[0] < this->Lf && fabs(track[id].positionBL[1]) < this->T ){ if(!this->track[id].down) cones_down++; track[id].down = true; if(this->moveConesFlag) this->moveCone(id, state); return true; } return false; }else{ // rear axle if( fabs(track[id].positionBL[0]) < this->Lr && fabs(track[id].positionBL[1]) < this->T ){ if(!this->track[id].down) cones_down++; track[id].down = true; if(this->moveConesFlag) this->moveCone(id, state); return true; } return false; } } // Move hit cones void Accumulator::moveCone(int &id, StateCar* state){ track[id].position[0] += state->velocity(0) * cos(state->heading) * 0.025; track[id].position[1] += state->velocity(0) * sin(state->heading) * 0.025; track[id].positionBL = global2local(track[id].position, state->pose); track[id].moved = true; moved_idx.insert(id); } void Accumulator::fillConesDown(std_msgs::Float32MultiArray* msg){ msg->data.clear(); msg->layout.dim.clear(); msg->layout.dim.push_back(std_msgs::MultiArrayDimension()); msg->layout.dim[0].size = moved_idx.size()*3; msg->layout.dim[0].stride = 3; msg->layout.dim[0].label = (this->resetFlag) ? "reset" : "cones_down"; this->resetFlag = false; std::set<int>::iterator it; for(it=moved_idx.begin(); it!=moved_idx.end(); ++it){ msg->data.push_back(*it); msg->data.push_back(track[*it].position[0]); msg->data.push_back(track[*it].position[1]); } } int Accumulator::getNumConesDown(){ return this->cones_down; } int Accumulator::getLaps(){ return this->lapcount.getLaps(); } // Get Laptime and Laps according to FSG rules ipg_msgs::LapInfo Accumulator::getLapInfo(){ ipg_msgs::LapInfo msg; msg.header.stamp = ros::Time::now(); msg.laps = this->lapcount.getLaps(); msg.laptime = double(this->getNumConesDown())*2 + lapcount.getLapTime(); return msg; } // Check if the cone is in the lidar field of view bool Accumulator::isInLidarField(int id, StateCar* state){ double r = mod<double>(track[id].position[0], track[id].position[1]); Point localPosLidar = global2local(track[id].position, state->lidar_pose); // lidar frame pose double phi = acos(localPosLidar[0]/r); if(phi < -M_PI) phi += 2*M_PI; // convert phi into [-180, 180] if(phi > M_PI) phi -= 2*M_PI; if(fabs(phi) < this->vision_angle && !track[id].seen){ // the cone is in our vision area (field) if(noise::probability(this->likelihood)) return true; // likelihood of detecting the cone (percepcio pala) else return false; } else return false; } // Get all seen cones void Accumulator::getSeenCones(StateCar* state, ipg_msgs::ConeArray* coneArray){ ipg_msgs::Cone coneMsg = ipg_msgs::Cone(); Point position; position[0] = state->pose(0); position[1] = state->pose(1); std::vector<int> coneIds = Tree.radiusSearch(position, this->radius); // search for cones // Check whether seen cones are inside LIDAR vision field for(auto id : coneIds){ int idx = static_cast<int>(id); if(isInLidarField(idx, state)){ track[idx].seen = true; this->seen_idx.push_back(idx); } } // Add all seen cones (with their current base_link position) for(auto idx : seen_idx){ int cone_id = static_cast<int>(idx); track[cone_id].positionBL = global2local(track[cone_id].position, state->pose); // add current base_link position if(!coneDown(cone_id, state)){ // check for DOO (cone Down or Out) once BaseLink position is updated fillConeMsg(cone_id, &coneMsg); coneArray->cones.push_back(coneMsg); } } lapcount.setPosition(state->pose, state->velocity(0)); if(!this->stateFlag) lapcount.getStartingLine(); lapcount.run(); this->stateFlag = true; } }
412
0.977932
1
0.977932
game-dev
MEDIA
0.672171
game-dev
0.996767
1
0.996767
motorsep/StormEngine2
14,924
neo/ui/Window.h
/* =========================================================================== Doom 3 BFG Edition GPL Source Code Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company. Copyright (C) 2014-2016 Robert Beckebans Copyright (C) 2014-2016 Kot in Action Creative Artel This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code"). Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #ifndef __WINDOW_H__ #define __WINDOW_H__ #include "Rectangle.h" #include "DeviceContext.h" #include "RegExp.h" #include "Winvar.h" #include "GuiScript.h" #include "SimpleWindow.h" const int WIN_CHILD = 0x00000001; const int WIN_CAPTION = 0x00000002; const int WIN_BORDER = 0x00000004; const int WIN_SIZABLE = 0x00000008; const int WIN_MOVABLE = 0x00000010; const int WIN_FOCUS = 0x00000020; const int WIN_CAPTURE = 0x00000040; const int WIN_HCENTER = 0x00000080; const int WIN_VCENTER = 0x00000100; const int WIN_MODAL = 0x00000200; const int WIN_INTRANSITION = 0x00000400; const int WIN_CANFOCUS = 0x00000800; const int WIN_SELECTED = 0x00001000; const int WIN_TRANSFORM = 0x00002000; const int WIN_HOLDCAPTURE = 0x00004000; const int WIN_NOWRAP = 0x00008000; const int WIN_NOCLIP = 0x00010000; const int WIN_INVERTRECT = 0x00020000; const int WIN_NATURALMAT = 0x00040000; const int WIN_NOCURSOR = 0x00080000; const int WIN_MENUGUI = 0x00100000; const int WIN_ACTIVE = 0x00200000; const int WIN_SHOWCOORDS = 0x00400000; const int WIN_SHOWTIME = 0x00800000; const int WIN_WANTENTER = 0x01000000; const int WIN_DESKTOP = 0x10000000; const char CAPTION_HEIGHT[] = "16.0"; const char SCROLLER_SIZE[] = "16.0"; const int SCROLLBAR_SIZE = 16; const int MAX_WINDOW_NAME = 32; const int MAX_LIST_ITEMS = 1024; const char DEFAULT_BACKCOLOR[] = "1 1 1 1"; const char DEFAULT_FORECOLOR[] = "0 0 0 1"; const char DEFAULT_BORDERCOLOR[] = "0 0 0 1"; const char DEFAULT_TEXTSCALE[] = "0.4"; typedef enum { WOP_TYPE_ADD, WOP_TYPE_SUBTRACT, WOP_TYPE_MULTIPLY, WOP_TYPE_DIVIDE, WOP_TYPE_MOD, WOP_TYPE_TABLE, WOP_TYPE_GT, WOP_TYPE_GE, WOP_TYPE_LT, WOP_TYPE_LE, WOP_TYPE_EQ, WOP_TYPE_NE, WOP_TYPE_AND, WOP_TYPE_OR, WOP_TYPE_VAR, WOP_TYPE_VARS, WOP_TYPE_VARF, WOP_TYPE_VARI, WOP_TYPE_VARB, WOP_TYPE_COND } wexpOpType_t; typedef enum { WEXP_REG_TIME, WEXP_REG_NUM_PREDEFINED } wexpRegister_t; typedef struct { wexpOpType_t opType; // RB: 64 bit fixes, changed int to intptr_t intptr_t a, b, c, d; // RB end } wexpOp_t; struct idRegEntry { const char* name; idRegister::REGTYPE type; int index; }; class rvGEWindowWrapper; class idWindow; struct idTimeLineEvent { idTimeLineEvent() { event = new( TAG_OLD_UI ) idGuiScriptList; } ~idTimeLineEvent() { delete event; } int time; idGuiScriptList* event; bool pending; size_t Size() { return sizeof( *this ) + event->Size(); } }; class rvNamedEvent { public: rvNamedEvent( const char* name ) { mEvent = new( TAG_OLD_UI ) idGuiScriptList; mName = name; } ~rvNamedEvent() { delete mEvent; } size_t Size() { return sizeof( *this ) + mEvent->Size(); } idStr mName; idGuiScriptList* mEvent; }; struct idTransitionData { idWinVar* data; int offset; idInterpolateAccelDecelLinear<idVec4> interp; }; class idUserInterfaceLocal; class idWindow { public: idWindow( idUserInterfaceLocal* gui ); virtual ~idWindow(); enum { ON_MOUSEENTER = 0, ON_MOUSEEXIT, ON_ACTION, ON_ACTIVATE, ON_DEACTIVATE, ON_ESC, ON_FRAME, ON_TRIGGER, ON_ACTIONRELEASE, ON_ENTER, ON_ENTERRELEASE, ON_NAMEDEVENT, SCRIPT_COUNT }; enum { ADJUST_MOVE = 0, ADJUST_TOP, ADJUST_RIGHT, ADJUST_BOTTOM, ADJUST_LEFT, ADJUST_TOPLEFT, ADJUST_BOTTOMRIGHT, ADJUST_TOPRIGHT, ADJUST_BOTTOMLEFT }; static const char* ScriptNames[SCRIPT_COUNT]; static const idRegEntry RegisterVars[]; static const int NumRegisterVars; idWindow* SetFocus( idWindow* w, bool scripts = true ); idWindow* SetCapture( idWindow* w ); void SetParent( idWindow* w ); void SetFlag( unsigned int f ); void ClearFlag( unsigned int f ); unsigned GetFlags() { return flags; }; void Move( float x, float y ); void BringToTop( idWindow* w ); void Adjust( float xd, float yd ); void SetAdjustMode( idWindow* child ); void Size( float x, float y, float w, float h ); void SetupFromState(); void SetupBackground(); drawWin_t* FindChildByName( const char* name ); idSimpleWindow* FindSimpleWinByName( const char* _name ); idWindow* GetParent() { return parent; } idUserInterfaceLocal* GetGui() { return gui; }; bool Contains( float x, float y ); size_t Size(); virtual size_t Allocated(); idStr* GetStrPtrByName( const char* _name ); virtual idWinVar* GetWinVarByName( const char* _name, bool winLookup = false, drawWin_t** owner = NULL ); // DG: the return value is a pointer, so use intptr_t intptr_t GetWinVarOffset( idWinVar* wv, drawWin_t* dw ); // DG end float GetMaxCharHeight(); float GetMaxCharWidth(); void SetFont(); void SetInitialState( const char* _name ); void AddChild( idWindow* win ); void DebugDraw( int time, float x, float y ); void CalcClientRect( float xofs, float yofs ); void CommonInit(); void CleanUp(); void DrawBorderAndCaption( const idRectangle& drawRect ); void DrawCaption( int time, float x, float y ); void SetupTransforms( float x, float y ); bool Contains( const idRectangle& sr, float x, float y ); const char* GetName() { return name; }; virtual bool Parse( idTokenParser* src, bool rebuild = true ); virtual bool Parse(idParser *src, bool rebuild = true); virtual const char* HandleEvent( const sysEvent_t* event, bool* updateVisuals ); void CalcRects( float x, float y ); virtual void Redraw( float x, float y, bool hud ); virtual void ArchiveToDictionary( idDict* dict, bool useNames = true ); virtual void InitFromDictionary( idDict* dict, bool byName = true ); virtual void PostParse(); virtual void Activate( bool activate, idStr& act ); virtual void Trigger(); virtual void GainFocus(); virtual void LoseFocus(); virtual void GainCapture(); virtual void LoseCapture(); virtual void Sized(); virtual void Moved(); virtual void Draw( int time, float x, float y ); virtual void MouseExit(); virtual void MouseEnter(); virtual void DrawBackground( const idRectangle& drawRect ); virtual idWindow* GetChildWithOnAction( float xd, float yd ); virtual const char* RouteMouseCoords( float xd, float yd ); virtual void SetBuddy( idWindow* buddy ) {}; virtual void HandleBuddyUpdate( idWindow* buddy ) {}; virtual void StateChanged( bool redraw ); virtual void ReadFromDemoFile( class idDemoFile* f, bool rebuild = true ); virtual void WriteToDemoFile( class idDemoFile* f ); // SaveGame support void WriteSaveGameString( const char* string, idFile* savefile ); void WriteSaveGameTransition( idTransitionData& trans, idFile* savefile ); virtual void WriteToSaveGame( idFile* savefile ); void ReadSaveGameString( idStr& string, idFile* savefile ); void ReadSaveGameTransition( idTransitionData& trans, idFile* savefile ); virtual void ReadFromSaveGame( idFile* savefile ); void FixupTransitions(); virtual void HasAction() {}; virtual void HasScripts() {}; void FixupParms(); void GetScriptString( const char* name, idStr& out ); void SetScriptParams(); bool HasOps() { return ( ops.Num() > 0 ); }; float EvalRegs( int test = -1, bool force = false ); void StartTransition(); void AddTransition( idWinVar* dest, idVec4 from, idVec4 to, int time, float accelTime, float decelTime ); void ResetTime( int time ); void ResetCinematics(); int NumTransitions(); bool ParseScript( idTokenParser* src, idGuiScriptList& list, int* timeParm = NULL, bool allowIf = false ); bool ParseScript(idParser *src, idGuiScriptList &list, int *timeParm = NULL, bool allowIf = false); bool RunScript( int n ); bool RunScriptList( idGuiScriptList* src ); void SetRegs( const char* key, const char* val ); // DG: component and the return value are really pointers, so use intptr_t intptr_t ParseExpression( idTokenParser* src, idWinVar* var = NULL, intptr_t component = 0 ); int ParseExpression( idParser *src, idWinVar *var = NULL, int component = 0 ); // DG end int ExpressionConstant( float f ); idRegisterList* RegList() { return &regList; } void AddCommand( const char* cmd ); void AddUpdateVar( idWinVar* var ); bool Interactive(); bool ContainsStateVars(); void SetChildWinVarVal( const char* name, const char* var, const char* val ); idWindow* GetFocusedChild(); idWindow* GetCaptureChild(); const char* GetComment() { return comment; } void SetComment( const char* p ) { comment = p; } idStr cmd; virtual void RunNamedEvent( const char* eventName ); void AddDefinedVar( idWinVar* var ); idWindow* FindChildByPoint( float x, float y, idWindow* below = NULL ); int GetChildIndex( idWindow* window ); int GetChildCount(); idWindow* GetChild( int index ); void RemoveChild( idWindow* win ); bool InsertChild( idWindow* win, idWindow* before ); void ScreenToClient( idRectangle* rect ); void ClientToScreen( idRectangle* rect ); bool UpdateFromDictionary( idDict& dict ); protected: friend class rvGEWindowWrapper; idWindow* FindChildByPoint( float x, float y, idWindow** below ); void SetDefaults(); friend class idSimpleWindow; friend class idUserInterfaceLocal; bool IsSimple(); void UpdateWinVars(); void DisableRegister( const char* _name ); void Transition(); void Time(); bool RunTimeEvents( int time ); void Dump(); int ExpressionTemporary(); wexpOp_t* ExpressionOp(); // DG: a, b, component and the return values are really pointers, so use intptr_t intptr_t EmitOp( intptr_t a, intptr_t b, wexpOpType_t opType, wexpOp_t** opp = NULL ); intptr_t ParseEmitOp( idTokenParser* src, intptr_t a, wexpOpType_t opType, int priority, wexpOp_t** opp = NULL ); int ParseEmitOp( idParser *src, int a, wexpOpType_t opType, int priority, wexpOp_t **opp = NULL ); intptr_t ParseTerm( idTokenParser* src, idWinVar* var = NULL, intptr_t component = 0 ); int ParseTerm( idParser *src, idWinVar *var = NULL, int component = 0 ); intptr_t ParseExpressionPriority( idTokenParser* src, int priority, idWinVar* var = NULL, intptr_t component = 0 ); int ParseExpressionPriority( idParser *src, int priority, idWinVar *var = NULL, int component = 0 ); // DG end void EvaluateRegisters( float* registers ); void SaveExpressionParseState(); void RestoreExpressionParseState(); void ParseBracedExpression( idTokenParser* src ); bool ParseScriptEntry( const char* name, idTokenParser* src ); bool ParseScriptEntry(const char *name, idParser *src); bool ParseRegEntry( const char* name, idTokenParser* src ); bool ParseRegEntry(const char *name, idParser *src); virtual bool ParseInternalVar( const char* name, idTokenParser* src ); virtual bool ParseInternalVar(const char *name, idParser *src); void ParseString( idTokenParser* src, idStr& out ); void ParseString(idParser *src, idStr &out); void ParseVec4( idTokenParser* src, idVec4& out ); void ParseVec4(idParser *src, idVec4 &out); void ConvertRegEntry( const char* name, idTokenParser* src, idStr& out, int tabs ); float actualX; // physical coords float actualY; // '' int childID; // this childs id unsigned int flags; // visible, focus, mouseover, cursor, border, etc.. int lastTimeRun; // idRectangle drawRect; // overall rect idRectangle clientRect; // client area idVec2 origin; int timeLine; // time stamp used for various fx float xOffset; float yOffset; float forceAspectWidth; float forceAspectHeight; float matScalex; float matScaley; float borderSize; float textAlignx; float textAligny; idStr name; idStr comment; idVec2 shear; class idFont* font; signed char textShadow; unsigned char cursor; // signed char textAlign; idWinBool noTime; // idWinBool visible; // idWinBool noEvents; idWinRectangle rect; // overall rect idWinVec4 backColor; idWinVec4 matColor; idWinVec4 foreColor; idWinVec4 hoverColor; idWinVec4 borderColor; idWinFloat textScale; idWinFloat rotate; idWinStr text; idWinBackground backGroundName; // idList<idWinVar*, TAG_OLD_UI> definedVars; idList<idWinVar*, TAG_OLD_UI> updateVars; idRectangle textRect; // text extented rect const idMaterial* background; // background asset idWindow* parent; // parent window idList<idWindow*, TAG_OLD_UI> children; // child windows idList<drawWin_t, TAG_OLD_UI> drawWindows; idWindow* focusedChild; // if a child window has the focus idWindow* captureChild; // if a child window has mouse capture idWindow* overChild; // if a child window has mouse capture bool hover; idUserInterfaceLocal* gui; static idCVar gui_debug; static idCVar gui_edit; idGuiScriptList* scripts[SCRIPT_COUNT]; bool* saveTemps; idList<idTimeLineEvent*, TAG_OLD_UI> timeLineEvents; idList<idTransitionData, TAG_OLD_UI> transitions; static bool registerIsTemporary[MAX_EXPRESSION_REGISTERS]; // statics to assist during parsing idList<wexpOp_t, TAG_OLD_UI> ops; // evaluate to make expressionRegisters idList<float, TAG_OLD_UI> expressionRegisters; idList<wexpOp_t, TAG_OLD_UI>* saveOps; // evaluate to make expressionRegisters idList<rvNamedEvent*, TAG_OLD_UI> namedEvents; // added named events idList<float, TAG_OLD_UI>* saveRegs; idRegisterList regList; idWinBool hideCursor; }; ID_INLINE void idWindow::AddDefinedVar( idWinVar* var ) { definedVars.AddUnique( var ); } #endif /* !__WINDOW_H__ */
412
0.857297
1
0.857297
game-dev
MEDIA
0.601266
game-dev,desktop-app
0.521222
1
0.521222
DeltaV-Station/Delta-v
2,382
Resources/Prototypes/Maps/shoukou.yml
- type: gameMap id: Shoukou mapName: 'Shōkō' mapPath: /Maps/shoukou.yml minPlayers: 5 maxPlayers: 50 stations: Shoukou: stationProto: StandardNanotrasenStation components: - type: StationNameSetup mapNameTemplate: '{0} Shōkō "Little Port" {1}' nameGenerator: !type:NanotrasenNameGenerator prefixCreator: 'NY' - type: StationEmergencyShuttle emergencyShuttlePath: /Maps/_DV/Shuttles/NTES_Kaeri.yml - type: StationJobs availableJobs: #Command Captain: [ 1, 1 ] #Service HeadOfPersonnel: [ 1, 1 ] Librarian: [ 1, 1 ] ServiceWorker: [ 1, 2 ] Reporter: [ 1, 1 ] Bartender: [ 1, 2 ] Botanist: [ 1, 2 ] MartialArtist: [ 2, 3 ] Chef: [ 1, 2 ] Clown: [ 1, 1 ] Janitor: [ 1, 2 ] Musician: [ 1, 1 ] Mime: [ 1, 1 ] Passenger: [ -1, -1 ] #Justice ChiefJustice: [ 1, 1 ] Clerk: [ 1, 1 ] Lawyer: [ 1, 1 ] Prosecutor: [ 1, 1 ] #Engineering ChiefEngineer: [ 1, 1 ] AtmosphericTechnician: [ 1, 2 ] StationEngineer: [ 2, 5 ] TechnicalAssistant: [ 2, 3 ] #Medical ChiefMedicalOfficer: [ 1, 1 ] Paramedic: [ 1, 2 ] Chemist: [ 1, 2 ] Psychologist: [ 1, 1 ] Surgeon: [ 1, 1 ] MedicalDoctor: [ 3, 3 ] MedicalIntern: [ 2, 3 ] #Security HeadOfSecurity: [ 1, 1 ] Warden: [ 1, 1 ] Detective: [ 1, 1 ] Brigmedic: [ 1, 1 ] SecurityOfficer: [ 2, 4 ] SecurityCadet: [ 1, 3 ] Prisoner: [ 2, 2 ] #Science ResearchDirector: [ 1, 1 ] Roboticist: [ 1, 1 ] Chaplain: [ 1, 1 ] ForensicMantis: [ 1, 1 ] Scientist: [ 2, 4 ] ResearchAssistant: [ 2, 3 ] #Logistics Quartermaster: [ 1, 1 ] SalvageSpecialist: [ 2, 4 ] Courier: [ 1, 2 ] CargoTechnician: [ 2, 3 ] CargoAssistant: [ 2, 2 ] #Silicon StationAi: [ 1, 1 ] Borg: [ 2, 2 ]
412
0.765385
1
0.765385
game-dev
MEDIA
0.245738
game-dev
0.74487
1
0.74487
lunar-sway/minestuck
1,296
src/main/java/com/mraof/minestuck/api/alchemy/GristTypeSpawnCategory.java
package com.mraof.minestuck.api.alchemy; import com.mraof.minestuck.Minestuck; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import java.util.stream.Stream; /** * Defines the different grist type categories used by grist layers to determine grist types for underlings spawned naturally. * Each category have a grist type tag associated with it that you can add grist types to. * The {@link GristTypeSpawnCategory#ANY} category automatically contains all grist types in the two other categories. */ public enum GristTypeSpawnCategory //Which categories can a certain grist type appear under (for spawning underlings) { COMMON("common"), UNCOMMON("uncommon"), ANY("any"); private final TagKey<GristType> tagKey; GristTypeSpawnCategory(String name) { this.tagKey = TagKey.create(GristTypes.REGISTRY_KEY, ResourceLocation.fromNamespaceAndPath(Minestuck.MOD_ID, "spawnable_" + name)); } public TagKey<GristType> getTagKey() { return this.tagKey; } public Stream<GristType> gristTypes() { return GristTypes.REGISTRY.getTag(this.tagKey).stream() .flatMap(HolderSet.ListBacked::stream) .map(Holder::value) .filter(GristType::isUnderlingType); } }
412
0.859293
1
0.859293
game-dev
MEDIA
0.950433
game-dev
0.718109
1
0.718109
DenizenScript/Denizen
2,139
plugin/src/main/java/com/denizenscript/denizen/events/entity/EntityUnleashedScriptEvent.java
package com.denizenscript.denizen.events.entity; import com.denizenscript.denizen.objects.EntityTag; import com.denizenscript.denizen.events.BukkitScriptEvent; import com.denizenscript.denizencore.objects.core.ElementTag; import com.denizenscript.denizencore.objects.ObjectTag; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityUnleashEvent; public class EntityUnleashedScriptEvent extends BukkitScriptEvent implements Listener { // <--[event] // @Events // <entity> unleashed (because <'reason'>) // // @Group Entity // // @Location true // // @Triggers when an entity is unleashed. // // @Context // <context.entity> returns the EntityTag. // <context.reason> returns an ElementTag of the reason for the unleashing. // Reasons include DISTANCE, HOLDER_GONE, PLAYER_UNLEASH, and UNKNOWN // // @NPC when the entity being unleashed is an NPC. // // --> public EntityUnleashedScriptEvent() { registerCouldMatcher("<entity> unleashed (because <'reason'>)"); } public EntityTag entity; public ElementTag reason; public EntityUnleashEvent event; @Override public boolean matches(ScriptPath path) { if (!path.tryArgObject(0, entity)) { return false; } if (path.eventArgAt(2).equals("because") && !path.eventArgLowerAt(3).equals(reason.asLowerString())) { return false; } if (!runInCheck(path, entity.getLocation())) { return false; } return super.matches(path); } @Override public ObjectTag getContext(String name) { if (name.equals("entity")) { return entity; } else if (name.equals("reason")) { return reason; } return super.getContext(name); } @EventHandler public void onEntityUnleashed(EntityUnleashEvent event) { entity = new EntityTag(event.getEntity()); reason = new ElementTag(event.getReason().toString()); this.event = event; fire(event); } }
412
0.905101
1
0.905101
game-dev
MEDIA
0.959966
game-dev
0.831342
1
0.831342