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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GenisysPro/GenisysPro | 1,845 | src/pocketmine/level/generator/object/TallGrass.php | <?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace pocketmine\level\generator\object;
use pocketmine\block\Block;
use pocketmine\level\ChunkManager;
use pocketmine\math\Vector3 as Vector3;
use pocketmine\utils\Random;
class TallGrass {
/**
* @param ChunkManager $level
* @param Vector3 $pos
* @param Random $random
* @param int $count
* @param int $radius
*/
public static function growGrass(ChunkManager $level, Vector3 $pos, Random $random, $count = 15, $radius = 10){
$arr = [
[Block::DANDELION, 0],
[Block::POPPY, 0],
[Block::TALL_GRASS, 1],
[Block::TALL_GRASS, 1],
[Block::TALL_GRASS, 1],
[Block::TALL_GRASS, 1]
];
$arrC = count($arr) - 1;
for($c = 0; $c < $count; ++$c){
$x = $random->nextRange($pos->x - $radius, $pos->x + $radius);
$z = $random->nextRange($pos->z - $radius, $pos->z + $radius);
if($level->getBlockIdAt($x, $pos->y + 1, $z) === Block::AIR and $level->getBlockIdAt($x, $pos->y, $z) === Block::GRASS){
$t = $arr[$random->nextRange(0, $arrC)];
$level->setBlockIdAt($x, $pos->y + 1, $z, $t[0]);
$level->setBlockDataAt($x, $pos->y + 1, $z, $t[1]);
}
}
}
} | 412 | 0.955962 | 1 | 0.955962 | game-dev | MEDIA | 0.907098 | game-dev | 0.990449 | 1 | 0.990449 |
TelepathicGrunt/Bumblezone | 13,483 | common/src/main/java/com/telepathicgrunt/the_bumblezone/blocks/blockentities/CrystallineFlowerBlockEntity.java | package com.telepathicgrunt.the_bumblezone.blocks.blockentities;
import com.telepathicgrunt.the_bumblezone.blocks.CrystallineFlower;
import com.telepathicgrunt.the_bumblezone.configs.BzGeneralConfigs;
import com.telepathicgrunt.the_bumblezone.items.datacomponents.CrystallineFlowerData;
import com.telepathicgrunt.the_bumblezone.modinit.BzBlockEntities;
import com.telepathicgrunt.the_bumblezone.modinit.BzBlocks;
import com.telepathicgrunt.the_bumblezone.modinit.BzDataComponents;
import com.telepathicgrunt.the_bumblezone.modinit.BzItems;
import com.telepathicgrunt.the_bumblezone.utils.GeneralUtils;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.component.DataComponentMap;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ClientGamePacketListener;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import java.util.UUID;
public class CrystallineFlowerBlockEntity extends BlockEntity {
public static final String TIER_TAG = "tier";
public static final String XP_TAG = "xp";
public static final String UUID_TAG = "guid";
private int xpTier = 1;
private int currentXp = 0;
private UUID uuid = java.util.UUID.randomUUID();
public static final String BOOK_SLOT_ITEMS = "bookItems";
public static final String CONSUME_SLOT_ITEMS = "consumeItems";
private ItemStack bookSlotItems = ItemStack.EMPTY;
private ItemStack consumeSlotItems = ItemStack.EMPTY;
protected CrystallineFlowerBlockEntity(BlockEntityType<?> blockEntityType, BlockPos blockPos, BlockState blockState) {
super(blockEntityType, blockPos, blockState);
}
public CrystallineFlowerBlockEntity(BlockPos blockPos, BlockState blockState) {
this(BzBlockEntities.CRYSTALLINE_FLOWER.get(), blockPos, blockState);
}
public int getXpTier() {
return this.xpTier;
}
public void setXpTier(int xpTier) {
this.xpTier = xpTier;
}
public int getCurrentXp() {
return this.currentXp;
}
public void setCurrentXp(int currentXp) {
this.currentXp = currentXp;
}
public UUID getUUID() {
return this.uuid;
}
public void setGUID(UUID uuid) {
this.uuid = uuid;
}
public ItemStack getBookSlotItems() {
return this.bookSlotItems;
}
public void setBookSlotItems(ItemStack bookSlotItems) {
this.bookSlotItems = bookSlotItems;
}
public ItemStack getConsumeSlotItems() {
return this.consumeSlotItems;
}
public void setConsumeSlotItems(ItemStack consumeSlotItems) {
this.consumeSlotItems = consumeSlotItems;
setPillar(0);
}
public void syncPillar() {
setPillar(0);
}
@Override
public void loadAdditional(CompoundTag compoundTag, HolderLookup.Provider provider) {
super.loadAdditional(compoundTag, provider);
this.xpTier = compoundTag.getInt(TIER_TAG);
this.currentXp = Math.min(compoundTag.getInt(XP_TAG), getMaxXpForTier(this.xpTier));
if (compoundTag.contains(UUID_TAG)) {
if (compoundTag.getTagType(UUID_TAG) == Tag.TAG_STRING) {
this.uuid = UUID.fromString(compoundTag.getString(UUID_TAG));
}
else {
this.uuid = compoundTag.getUUID(UUID_TAG);
}
if (this.uuid.compareTo(CrystallineFlowerData.DEFAULT_UUID) == 0) {
this.uuid = java.util.UUID.randomUUID();
}
}
else {
this.uuid = java.util.UUID.randomUUID();
}
if (compoundTag.contains(BOOK_SLOT_ITEMS)) {
this.bookSlotItems = ItemStack.parse(provider, compoundTag.getCompound(BOOK_SLOT_ITEMS)).orElse(ItemStack.EMPTY);
}
else {
this.bookSlotItems = ItemStack.EMPTY;
}
if (compoundTag.contains(CONSUME_SLOT_ITEMS)) {
this.consumeSlotItems = ItemStack.parse(provider, compoundTag.getCompound(CONSUME_SLOT_ITEMS)).orElse(ItemStack.EMPTY);
}
else {
this.consumeSlotItems = ItemStack.EMPTY;
}
}
@Override
protected void saveAdditional(CompoundTag compoundTag, HolderLookup.Provider provider) {
super.saveAdditional(compoundTag, provider);
saveFieldsToTag(compoundTag, provider);
}
private void saveFieldsToTag(CompoundTag compoundTag, HolderLookup.Provider provider) {
compoundTag.putInt(TIER_TAG, this.xpTier);
compoundTag.putInt(XP_TAG, this.currentXp);
compoundTag.putUUID(UUID_TAG, this.uuid);
if (!this.bookSlotItems.isEmpty()) {
compoundTag.put(BOOK_SLOT_ITEMS, this.bookSlotItems.save(provider));
}
if (!this.consumeSlotItems.isEmpty()) {
compoundTag.put(CONSUME_SLOT_ITEMS, this.consumeSlotItems.save(provider));
}
}
@Override
public void saveToItem(ItemStack stack, HolderLookup.Provider provider) {
CompoundTag compoundTag = new CompoundTag();
this.saveAdditional(compoundTag, provider);
BlockItem.setBlockEntityData(stack, this.getType(), compoundTag);
}
@Override
public Packet<ClientGamePacketListener> getUpdatePacket() {
return ClientboundBlockEntityDataPacket.create(this);
}
@Override
public CompoundTag getUpdateTag(HolderLookup.Provider provider) {
CompoundTag tag = new CompoundTag();
saveFieldsToTag(tag, provider);
return tag;
}
public void addXpAndTier(int xpChange) {
currentXp += xpChange;
int tierChange = 0;
while (currentXp >= getMaxXpForTier(xpTier) && !isMaxTier()) {
currentXp -= getMaxXpForTier(xpTier);
tierChange++;
xpTier++;
}
while (currentXp < 0 && !isMinTier()) {
currentXp += getMaxXpForTier(xpTier);
tierChange--;
xpTier--;
}
if (isMaxTier()) {
currentXp = 0;
}
if (currentXp >= getMaxXpForTier(xpTier)) {
currentXp = getMaxXpForTier(xpTier);
}
else if (currentXp < 0) {
currentXp = 0;
}
this.setChanged();
setPillar(tierChange);
}
public void increaseTier(int tierIncrease) {
int tierChange = Math.min(7 - xpTier, tierIncrease);
if (!isMaxTier()) {
xpTier += tierIncrease;
}
else {
currentXp = getMaxXpForTier(xpTier);
}
if (currentXp >= getMaxXpForTier(xpTier) && !isMaxTier()) {
currentXp = getMaxXpForTier(xpTier) - 1;
}
this.setChanged();
setPillar(tierChange);
}
public void decreaseTier(int tierDecrease) {
int tierChange = Math.min(xpTier - 1, tierDecrease);
if (!isMinTier()) {
xpTier -= tierDecrease;
}
if (currentXp >= getMaxXpForTier(xpTier) && !isMaxTier()) {
currentXp = getMaxXpForTier(xpTier) - 1;
}
this.setChanged();
setPillar(-tierChange);
}
public void setPillar(int tierChange) {
if (this.level != null) {
int bottomHeight = CrystallineFlower.flowerHeightBelow(this.level, this.getBlockPos());
BlockPos operatingPos = this.getBlockPos().below(bottomHeight);
int topHeight = CrystallineFlower.flowerHeightAbove(this.level, operatingPos);
BlockEntity blockEntity = level.getBlockEntity(operatingPos);
if (blockEntity instanceof CrystallineFlowerBlockEntity crystallineFlowerBlockEntity) {
if (tierChange != 0) {
if (bottomHeight != 0) {
BlockEntity targetBlockEntity = level.getBlockEntity(this.getBlockPos().below(bottomHeight));
if (targetBlockEntity instanceof CrystallineFlowerBlockEntity) {
targetBlockEntity.loadWithComponents(crystallineFlowerBlockEntity.getUpdateTag(level.registryAccess()), level.registryAccess());
}
}
boolean upward = tierChange > 0;
for (int i = 0; i < (upward ? this.xpTier : topHeight + 1); i++) {
boolean placePlant = upward || i < this.xpTier;
level.setBlock(
operatingPos.above(i),
placePlant ? BzBlocks.CRYSTALLINE_FLOWER.get().defaultBlockState() : Blocks.AIR.defaultBlockState(),
2);
if (this.level instanceof ServerLevel serverLevel && !placePlant) {
for (int itemsToDrop = 0; itemsToDrop < 2 + (i / 1.5); itemsToDrop++) {
ItemStack stack = BzItems.HONEY_CRYSTAL_SHARDS.get().getDefaultInstance();
stack.setCount(1);
GeneralUtils.spawnItemEntity(
serverLevel,
operatingPos.above(i),
stack,
0.05D,
0.2D);
}
}
}
operatingPos = operatingPos.above(upward ? this.xpTier - 1 : topHeight + tierChange);
level.setBlock(
operatingPos,
BzBlocks.CRYSTALLINE_FLOWER.get().defaultBlockState().setValue(CrystallineFlower.FLOWER, true),
2);
BlockEntity blockEntity2 = level.getBlockEntity(operatingPos);
if (blockEntity2 instanceof CrystallineFlowerBlockEntity crystallineFlowerBlockEntity2) {
crystallineFlowerBlockEntity2.loadWithComponents(crystallineFlowerBlockEntity.getUpdateTag(level.registryAccess()), level.registryAccess());
blockEntity2.setChanged();
}
}
for (int i = 0; i <= topHeight; i++) {
BlockPos updatePos = operatingPos.above(i);
BlockState state = level.getBlockState(updatePos);
level.updateNeighborsAt(updatePos, state.getBlock());
if (i != 0) {
BlockEntity blockEntity2 = level.getBlockEntity(updatePos);
if (blockEntity2 instanceof CrystallineFlowerBlockEntity crystallineFlowerBlockEntity2) {
crystallineFlowerBlockEntity2.loadWithComponents(crystallineFlowerBlockEntity.getUpdateTag(level.registryAccess()), level.registryAccess());
}
}
}
}
}
}
public boolean isMaxXP() {
return currentXp == getMaxXpForTier(xpTier);
}
public boolean isMinXP() {
return currentXp == 0;
}
public boolean isMaxTier() {
return xpTier == 7;
}
public boolean isMinTier() {
return xpTier == 0;
}
public int getMaxXpForTier(int tier) {
return Math.max(1, (90 + (tier * tier * 15)) + BzGeneralConfigs.crystallineFlowerExtraXpNeededForTiers);
}
public int getXpForNextTiers(int nextTiersToCalculate) {
int totalXpNeeded = 0;
for (int i = 0; i < nextTiersToCalculate; i++) {
if (i == 0) {
totalXpNeeded += getMaxXpForTier(xpTier) - currentXp;
}
else if (xpTier + i <= 7) {
totalXpNeeded += getMaxXpForTier(xpTier + i);
}
}
return totalXpNeeded;
}
@Override
protected void applyImplicitComponents(BlockEntity.DataComponentInput dataComponentInput) {
super.applyImplicitComponents(dataComponentInput);
CrystallineFlowerData crystallineFlowerData = dataComponentInput.getOrDefault(BzDataComponents.CRYSTALLINE_FLOWER_DATA.get(), new CrystallineFlowerData());
this.xpTier = crystallineFlowerData.tier();
this.currentXp = crystallineFlowerData.experience();
if (crystallineFlowerData.uuid().compareTo(CrystallineFlowerData.DEFAULT_UUID) != 0) {
this.uuid = crystallineFlowerData.uuid();
}
}
@Override
protected void collectImplicitComponents(DataComponentMap.Builder builder) {
super.collectImplicitComponents(builder);
CrystallineFlowerData crystallineFlowerData = new CrystallineFlowerData(this.xpTier, this.currentXp, this.uuid);
builder.set(BzDataComponents.CRYSTALLINE_FLOWER_DATA.get(), crystallineFlowerData);
}
@Override
public void removeComponentsFromTag(CompoundTag compoundTag) {
compoundTag.remove(TIER_TAG);
compoundTag.remove(XP_TAG);
compoundTag.remove(UUID_TAG);
super.removeComponentsFromTag(compoundTag);
}
}
| 412 | 0.93755 | 1 | 0.93755 | game-dev | MEDIA | 0.997718 | game-dev | 0.89959 | 1 | 0.89959 |
ill-inc/biomes-game | 2,894 | src/client/game/helpers/place_effect.ts | import type { Scenes } from "@/client/game/renderers/scenes";
import { addToScenes } from "@/client/game/renderers/scenes";
import type {
ClientResourcePaths,
ClientResources,
} from "@/client/game/resources/types";
import { ParticleSystem } from "@/client/game/resources/particles";
import { blockPlaceParticleMaterials } from "@/client/game/util/particles_systems";
import { voxelShard } from "@/shared/game/shard";
import { add } from "@/shared/math/linear";
import type { ReadonlyVec3 } from "@/shared/math/types";
import type { Key } from "@/shared/resources/types";
import type { Texture } from "three";
const PLACE_EFFECT_TRIGGER_RESOURCE: Key<ClientResourcePaths> =
"/terrain/combined_mesh";
export class PlaceEffect {
// The terrain mesh version which should trigger this effect, in order
// to sync the effect on when the terrain mesh is actually modified.
private playOnTerrainMeshVersion: number;
done = false;
private particleSystem: ParticleSystem | undefined;
constructor(
resources: ClientResources,
// The voxel position in the world that was placed.
public readonly placePos: ReadonlyVec3,
public readonly placeWorldTime: number,
private readonly face: number
) {
// Relying on the assumption that the current cached terrain
// mesh cannot yet be up-to-date and reflect changes associated
// don't trigger the effect until the terrain is updated.
this.playOnTerrainMeshVersion =
resources.cachedVersion(
PLACE_EFFECT_TRIGGER_RESOURCE,
voxelShard(...placePos)
) + 1;
}
dispose() {
if (this.particleSystem) {
this.particleSystem.materials.dispose();
}
this.done = true;
}
tick(resources: ClientResources, time: number, texture: Texture) {
if (this.done) {
return;
}
if (this.particleSystem) {
const skyParams = resources.get("/scene/sky_params");
this.particleSystem.tickToTime(time, skyParams.sunDirection.toArray());
if (this.particleSystem.allAnimationsComplete()) {
this.dispose();
}
} else if (this.shouldTriggerPlaceEffect(resources)) {
this.particleSystem = new ParticleSystem(
blockPlaceParticleMaterials(texture, this.face).withClonedMaterial(),
time
);
this.particleSystem.three.position.fromArray(
add(this.placePos, [0.5, 0.5, 0.5])
);
}
}
private shouldTriggerPlaceEffect(resources: ClientResources) {
if (this.particleSystem || this.done) {
return false;
}
const cachedTerrainVersion = resources.cachedVersion(
PLACE_EFFECT_TRIGGER_RESOURCE,
voxelShard(...this.placePos)
);
return cachedTerrainVersion >= this.playOnTerrainMeshVersion;
}
addToScenes(scenes: Scenes) {
if (this.done || !this.particleSystem) {
return;
}
addToScenes(scenes, this.particleSystem.three);
}
}
| 412 | 0.937718 | 1 | 0.937718 | game-dev | MEDIA | 0.769705 | game-dev,graphics-rendering | 0.948711 | 1 | 0.948711 |
EmptyBottleInc/DFU-Tanguy-Multiplayer | 2,643 | Assets/Scripts/Game/MagicAndEffects/Effects/Restoration/FortifyStrength.cs | // Project: Daggerfall Unity
// Copyright: Copyright (C) 2009-2022 Daggerfall Workshop
// Web Site: http://www.dfworkshop.net
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/Interkarma/daggerfall-unity
// Original Author: Gavin Clayton (interkarma@dfworkshop.net)
// Contributors:
//
// Notes:
//
using DaggerfallConnect;
using DaggerfallConnect.Arena2;
namespace DaggerfallWorkshop.Game.MagicAndEffects.MagicEffects
{
/// <summary>
/// Fortify Attribute - Strength
/// </summary>
public class FortifyStrength : FortifyEffect
{
public static readonly string EffectKey = "Fortify-Strength";
public override void SetProperties()
{
properties.Key = EffectKey;
properties.ClassicKey = MakeClassicKey(9, 0);
properties.SupportDuration = true;
properties.SupportMagnitude = true;
properties.AllowedTargets = EntityEffectBroker.TargetFlags_All;
properties.AllowedElements = EntityEffectBroker.ElementFlags_MagicOnly;
properties.AllowedCraftingStations = MagicCraftingStations.SpellMaker | MagicCraftingStations.PotionMaker;
properties.MagicSkill = DFCareer.MagicSkills.Restoration;
properties.DurationCosts = MakeEffectCosts(28, 100);
properties.MagnitudeCosts = MakeEffectCosts(40, 120);
fortifyStat = DFCareer.Stats.Strength;
}
public override string GroupName => TextManager.Instance.GetLocalizedText("fortifyAttribute");
public override string SubGroupName => TextManager.Instance.GetLocalizedText("strength");
public override TextFile.Token[] SpellMakerDescription => DaggerfallUnity.Instance.TextProvider.GetRSCTokens(1532);
public override TextFile.Token[] SpellBookDescription => DaggerfallUnity.Instance.TextProvider.GetRSCTokens(1232);
public override void SetPotionProperties()
{
// Magnitude 1-1 + 14-14 per 1 levels
EffectSettings orcStrengthSettings = SetEffectMagnitude(DefaultEffectSettings(), 1, 1, 14, 14, 1);
PotionRecipe orcStrength = new PotionRecipe(
"orcStrength",
50,
orcStrengthSettings,
(int)Items.CreatureIngredients1.Orcs_blood,
(int)Items.MetalIngredients.Iron,
(int)Items.MiscellaneousIngredients1.Pure_water);
// Assign recipe
orcStrength.TextureRecord = 13;
AssignPotionRecipes(orcStrength);
}
}
}
| 412 | 0.870605 | 1 | 0.870605 | game-dev | MEDIA | 0.981855 | game-dev | 0.885684 | 1 | 0.885684 |
Lotus-AU/LotusContinued | 3,425 | src/GameModes/GameModeManager.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Lotus.API.Odyssey;
using Lotus.API.Reactive;
using Lotus.Victory;
using VentLib.Options;
using VentLib.Options.UI;
using Lotus.Options;
using Lotus.Extensions;
using Lotus.GameModes.Standard;
using Lotus.GameModes.Colorwars;
using Lotus.GameModes.CTF;
namespace Lotus.GameModes;
// As we move to the future we're going to try to use instances for managers rather than making everything static
public class GameModeManager
{
private static readonly StandardLogger log = LoggerFactory.GetLogger<StandardLogger>(typeof(GameModeManager));
private const string GameModeManagerStartHook = nameof(GameModeManager);
internal readonly List<IGameMode> GameModes = new();
public IGameMode CurrentGameMode
{
get => currentGameMode!;
set
{
currentGameMode?.InternalDeactivate();
currentGameMode = value;
currentGameMode?.InternalActivate();
}
}
private IGameMode? currentGameMode;
internal GameOption gamemodeOption = null!;
public GameModeManager()
{
Hooks.GameStateHooks.GameStartHook.Bind(GameModeManagerStartHook, _ => CurrentGameMode.SetupWinConditions(Game.GetWinDelegate()));
}
public void SetGameMode(int id)
{
if (currentGameMode?.GetType() == GameModes[id].GetType()) return;
CurrentGameMode = GameModes[id];
log.High($"Setting GameMode {CurrentGameMode.Name}", "GameMode");
}
public IEnumerable<IGameMode> GetGameModes() => GameModes;
public IGameMode GetGameMode(int id) => GameModes[id];
public IGameMode? GetGameMode(Type type) => GameModes.FirstOrDefault(t => t.GetType() == type);
internal void AddGamemodes() => GameModes.AddRange([
new StandardGameMode(),
new ColorwarsGamemode(),
new CTFGamemode()
]);
public void Setup()
{
GameOptionBuilder builder = new();
for (int i = 0; i < GameModes.Count; i++)
{
IGameMode gameMode = GameModes[i];
var index = i;
builder.Value(v => v.Text(gameMode.Name).Value(index).Build());
}
gamemodeOption = builder.KeyName("GameMode", GamemodeTranslations.GamemodeText).IsHeader(true).BindInt(SetGameMode).Build();
OptionManager.GetManager(file: "other.txt", managerFlags: OptionManagerFlags.SyncOverRpc).Register(gamemodeOption, OptionLoadMode.LoadOrCreate);
if (currentGameMode == null) SetGameMode(0);
GameModes.ForEach(gm => AddGamemodeSettingToOptions(gm.MainTab().GetOptions()));
}
public void StartGame(WinDelegate winDelegate)
{
CurrentGameMode.CoroutineManager.Start();
CurrentGameMode.SetupWinConditions(winDelegate);
}
internal void AddGamemodeSettingToOptions(List<GameOption> options)
{
// Add gamemode switcher at top
options.Insert(0, gamemodeOption);
options.Insert(0, new GameOptionTitleBuilder()
.Title(GamemodeTranslations.GamemodeSelection)
.Build());
// Add Admin Options
options.InsertRange(2, GeneralOptions.AdminOptions.AllOptions);
// Add Miscellaneous Options
options.AddRange(GeneralOptions.MiscellaneousOptions.AllOptions);
// Add Debug Options
options.AddRange(GeneralOptions.DebugOptions.AllOptions);
}
} | 412 | 0.762312 | 1 | 0.762312 | game-dev | MEDIA | 0.778808 | game-dev | 0.781447 | 1 | 0.781447 |
pnp/pnpframework | 2,129 | src/lib/PnP.Framework/Provisioning/Model/SharePoint/Publishing/PageLayout.cs | ο»Ώusing System;
namespace PnP.Framework.Provisioning.Model
{
/// <summary>
/// Defines an available Page Layout for the current Publishing site
/// </summary>
public partial class PageLayout : BaseModel, IEquatable<PageLayout>
{
#region Public Members
/// <summary>
/// Defines the path of the Page Layout for the current Publishing site
/// </summary>
public String Path { get; set; }
/// <summary>
/// Defines whether the Page Layout is the default for the current Publishing site
/// </summary>
public Boolean IsDefault { get; set; }
#endregion
#region Comparison code
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Returns HashCode</returns>
public override int GetHashCode()
{
return (String.Format("{0}|{1}|",
(this.Path != null ? this.Path.GetHashCode() : 0),
this.IsDefault.GetHashCode()
).GetHashCode());
}
/// <summary>
/// Compares object with PageLayout
/// </summary>
/// <param name="obj">Object that represents PageLayout</param>
/// <returns>true if the current object is equal to the PageLayout</returns>
public override bool Equals(object obj)
{
if (!(obj is PageLayout))
{
return (false);
}
return (Equals((PageLayout)obj));
}
/// <summary>
/// Compares PageLayout object based on Path and IsDefault properties.
/// </summary>
/// <param name="other">PageLayout object</param>
/// <returns>true if the PageLayout object is equal to the current object; otherwise, false.</returns>
public bool Equals(PageLayout other)
{
if (other == null)
{
return (false);
}
return (
this.Path == other.Path &&
this.IsDefault == other.IsDefault
);
}
#endregion
}
}
| 412 | 0.864473 | 1 | 0.864473 | game-dev | MEDIA | 0.337753 | game-dev | 0.803546 | 1 | 0.803546 |
NationalSecurityAgency/ghidra | 17,898 | Ghidra/Features/Decompiler/src/decompile/cpp/xml.y | /* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
%define api.prefix {xml}
%{
#include "xml.hh"
// CharData mode look for '<' '&' or "]]>"
// Name mode look for non-name char
// CData mode looking for "]]>"
// Entity mode looking for ending ';'
// AttValue mode looking for endquote or '&'
// Comment mode looking for "--"
#include <iostream>
#include <string>
namespace ghidra {
string Attributes::bogus_uri("http://unused.uri");
/// \brief The XML character scanner
///
/// Tokenize a byte stream suitably for the main XML parser. The scanner expects an ASCII or UTF-8
/// encoding. Characters is XML tag and attribute names are restricted to ASCII "letters", but
/// extended UTF-8 characters can be used in any other character data: attribute values, content, comments.
class XmlScan {
public:
/// \brief Modes of the scanner
enum mode { CharDataMode, CDataMode, AttValueSingleMode,
AttValueDoubleMode, CommentMode, CharRefMode,
NameMode, SNameMode, SingleMode };
/// \brief Additional tokens returned by the scanner, in addition to byte values 00-ff
enum token { CharDataToken = 258,
CDataToken = 259,
AttValueToken = 260,
CommentToken =261,
CharRefToken = 262,
NameToken = 263,
SNameToken = 264,
ElementBraceToken = 265,
CommandBraceToken = 266 };
private:
mode curmode; ///< The current scanning mode
istream &s; ///< The stream being scanned
string *lvalue; ///< Current string being built
int4 lookahead[4]; ///< Lookahead into the byte stream
int4 pos; ///< Current position in the lookahead buffer
bool endofstream; ///< Has end of stream been reached
void clearlvalue(void); ///< Clear the current token string
/// \brief Get the next byte in the stream
///
/// Maintain a lookahead of 4 bytes at all times so that we can check for special
/// XML character sequences without consuming.
/// \return the next byte value as an integer
int4 getxmlchar(void) {
char c;
int4 ret=lookahead[pos];
if (!endofstream) {
s.get(c);
if (s.eof()||(c=='\0')) {
endofstream = true;
lookahead[pos] = '\n';
}
else
lookahead[pos] = c;
}
else
lookahead[pos] = -1;
pos = (pos+1)&3;
return ret;
}
int4 next(int4 i) { return lookahead[(pos+i)&3]; } ///< Peek at the next (i-th) byte without consuming
bool isLetter(int4 val) { return (((val>=0x41)&&(val<=0x5a))||((val>=0x61)&&(val<=0x7a))); } ///< Is the given byte a \e letter
bool isInitialNameChar(int4 val); ///< Is the given byte/character the valid start of an XML name
bool isNameChar(int4 val); ///< Is the given byte/character valid for an XML name
bool isChar(int4 val); ///< Is the given byte/character valid as an XML character
int4 scanSingle(void); ///< Scan for the next token in Single Character mode
int4 scanCharData(void); ///< Scan for the next token is Character Data mode
int4 scanCData(void); ///< Scan for the next token in CDATA mode
int4 scanAttValue(int4 quote); ///< Scan for the next token in Attribute Value mode
int4 scanCharRef(void); ///< Scan for the next token in Character Reference mode
int4 scanComment(void); ///< Scan for the next token in Comment mode
int4 scanName(void); ///< Scan a Name or return single non-name character
int4 scanSName(void); ///< Scan Name, allow white space before
public:
XmlScan(istream &t); ///< Construct scanner given a stream
~XmlScan(void); ///< Destructor
void setmode(mode m) { curmode = m; } ///< Set the scanning mode
int4 nexttoken(void); ///< Get the next token
string *lval(void) { string *ret = lvalue; lvalue = (string *)0; return ret; } ///< Return the last \e lvalue string
};
/// \brief A parsed name/value pair
struct NameValue {
string *name; ///< The name
string *value; ///< The value
};
extern int xmllex(void); ///< Interface to the scanner
extern int xmlerror(const char *str); ///< Interface for registering an error in parsing
extern void print_content(const string &str); ///< Send character data to the ContentHandler
extern int4 convertEntityRef(const string &ref); ///< Convert an XML entity to its equivalent character
extern int4 convertCharRef(const string &ref); ///< Convert an XML character reference to its equivalent character
static XmlScan *global_scan; ///< Global reference to the scanner
static ContentHandler *handler; ///< Global reference to the content handler
%}
%union {
int4 i;
string *str;
Attributes *attr;
NameValue *pair;
}
%expect 8
%token <str> CHARDATA CDATA ATTVALUE COMMENT CHARREF NAME SNAME ELEMBRACE COMMBRACE
%type <str> AttValue attsinglemid attdoublemid ETag CDSect CharRef EntityRef
%type <i> Reference
%type <attr> EmptyElemTag STag stagstart
%type <pair> SAttribute
%destructor { } <i>
%destructor { delete $$; } <*>
%%
document: element Misc;
| prolog element Misc;
whitespace: ' '
| '\n'
| '\r'
| '\t';
S: whitespace
| S whitespace ;
attsinglemid: '\'' { $$ = new string; global_scan->setmode(XmlScan::AttValueSingleMode); }
| attsinglemid ATTVALUE { $$ = $1; *$$ += *$2; delete $2; global_scan->setmode(XmlScan::AttValueSingleMode); }
| attsinglemid Reference { $$ = $1; *$$ += $2; global_scan->setmode(XmlScan::AttValueSingleMode); };
attdoublemid: '"' { $$ = new string; global_scan->setmode(XmlScan::AttValueDoubleMode); }
| attdoublemid ATTVALUE { $$ = $1; *$$ += *$2; delete $2; global_scan->setmode(XmlScan::AttValueDoubleMode); }
| attdoublemid Reference { $$ = $1; *$$ += $2; global_scan->setmode(XmlScan::AttValueDoubleMode); };
AttValue: attsinglemid '\'' { $$ = $1; }
| attdoublemid '"' { $$ = $1; };
elemstart: ELEMBRACE { global_scan->setmode(XmlScan::NameMode); delete $1; };
commentstart: COMMBRACE '!' '-' '-' { global_scan->setmode(XmlScan::CommentMode); delete $1; } ;
Comment: commentstart COMMENT '-' '-' '>' { delete $2; } ;
PI: COMMBRACE '?' { delete $1; yyerror("Processing instructions are not supported"); YYERROR; };
CDSect: CDStart CDATA CDEnd { $$ = $2; } ;
CDStart: COMMBRACE '!' '[' 'C' 'D' 'A' 'T' 'A' '[' { global_scan->setmode(XmlScan::CDataMode); delete $1; } ;
CDEnd: ']' ']' '>' ;
doctypepro: doctypedecl
| doctypepro Misc;
prologpre: XMLDecl
| Misc
| prologpre Misc;
prolog: prologpre doctypepro
| prologpre ;
doctypedecl: COMMBRACE '!' 'D' 'O' 'C' 'T' 'Y' 'P' 'E' { delete $1; yyerror("DTD's not supported"); YYERROR; };
Eq: '='
| S '='
| Eq S ;
Misc: Comment
| PI
| S ;
VersionInfo: S 'v' 'e' 'r' 's' 'i' 'o' 'n' Eq AttValue { handler->setVersion(*$10); delete $10; };
EncodingDecl: S 'e' 'n' 'c' 'o' 'd' 'i' 'n' 'g' Eq AttValue { handler->setEncoding(*$11); delete $11; };
xmldeclstart: COMMBRACE '?' 'x' 'm' 'l' VersionInfo
XMLDecl: xmldeclstart '?' '>'
| xmldeclstart S '?' '>'
| xmldeclstart EncodingDecl '?' '>'
| xmldeclstart EncodingDecl S '?' '>' ;
element: EmptyElemTag { handler->endElement($1->getelemURI(),$1->getelemName(),$1->getelemName()); delete $1; }
| STag content ETag { handler->endElement($1->getelemURI(),$1->getelemName(),$1->getelemName()); delete $1; delete $3; } ;
STag: stagstart '>' { handler->startElement($1->getelemURI(),$1->getelemName(),$1->getelemName(),*$1); $$ = $1; }
| stagstart S '>' { handler->startElement($1->getelemURI(),$1->getelemName(),$1->getelemName(),*$1); $$ = $1; };
EmptyElemTag: stagstart '/' '>' { handler->startElement($1->getelemURI(),$1->getelemName(),$1->getelemName(),*$1); $$ = $1; }
| stagstart S '/' '>' { handler->startElement($1->getelemURI(),$1->getelemName(),$1->getelemName(),*$1); $$ = $1; };
stagstart: elemstart NAME { $$ = new Attributes($2); global_scan->setmode(XmlScan::SNameMode); }
| stagstart SAttribute { $$ = $1; $$->add_attribute( $2->name, $2->value); delete $2; global_scan->setmode(XmlScan::SNameMode); };
SAttribute: SNAME Eq AttValue { $$ = new NameValue; $$->name = $1; $$->value = $3; };
etagbrace: COMMBRACE '/' { global_scan->setmode(XmlScan::NameMode); delete $1; };
ETag: etagbrace NAME '>' { $$ = $2; }
| etagbrace NAME S '>' { $$ = $2; };
content: { global_scan->setmode(XmlScan::CharDataMode); }
| content CHARDATA { print_content( *$2 ); delete $2; global_scan->setmode(XmlScan::CharDataMode); }
| content element { global_scan->setmode(XmlScan::CharDataMode); }
| content Reference { string *tmp=new string(); *tmp += $2; print_content(*tmp); delete tmp; global_scan->setmode(XmlScan::CharDataMode); }
| content CDSect { print_content( *$2 ); delete $2; global_scan->setmode(XmlScan::CharDataMode); }
| content PI { global_scan->setmode(XmlScan::CharDataMode); }
| content Comment { global_scan->setmode(XmlScan::CharDataMode); };
Reference: EntityRef { $$ = convertEntityRef(*$1); delete $1; }
| CharRef { $$ = convertCharRef(*$1); delete $1; };
refstart: '&' { global_scan->setmode(XmlScan::NameMode); } ;
charrefstart: refstart '#' { global_scan->setmode(XmlScan::CharRefMode); };
CharRef: charrefstart CHARREF ';' { $$ = $2; };
EntityRef: refstart NAME ';' { $$ = $2; };
%%
XmlScan::XmlScan(istream &t) : s(t)
{
curmode = SingleMode;
lvalue = (string *)0;
pos = 0;
endofstream = false;
getxmlchar(); getxmlchar(); getxmlchar(); getxmlchar(); // Fill lookahead buffer
}
XmlScan::~XmlScan(void)
{
clearlvalue();
}
void XmlScan::clearlvalue(void)
{
if (lvalue != (string *)0)
delete lvalue;
}
int4 XmlScan::scanSingle(void)
{
int4 res = getxmlchar();
if (res == '<') {
if (isInitialNameChar(next(0))) return ElementBraceToken;
return CommandBraceToken;
}
return res;
}
int4 XmlScan::scanCharData(void)
{
clearlvalue();
lvalue = new string();
while(next(0) != -1) { // look for '<' '&' or ']]>'
if (next(0) == '<') break;
if (next(0) == '&') break;
if (next(0) == ']')
if (next(1)== ']')
if (next(2)=='>')
break;
*lvalue += getxmlchar();
}
if (lvalue->size()==0)
return scanSingle();
return CharDataToken;
}
int4 XmlScan::scanCData(void)
{
clearlvalue();
lvalue = new string();
while(next(0) != -1) { // Look for "]]>" and non-Char
if (next(0)==']')
if (next(1)==']')
if (next(2)=='>')
break;
if (!isChar(next(0))) break;
*lvalue += getxmlchar();
}
return CDataToken; // CData can be empty
}
int4 XmlScan::scanCharRef(void)
{
int4 v;
clearlvalue();
lvalue = new string();
if (next(0) == 'x') {
*lvalue += getxmlchar();
while(next(0) != -1) {
v = next(0);
if (v < '0') break;
if ((v>'9')&&(v<'A')) break;
if ((v>'F')&&(v<'a')) break;
if (v>'f') break;
*lvalue += getxmlchar();
}
if (lvalue->size()==1)
return 'x'; // Must be at least 1 hex digit
}
else {
while(next(0) != -1) {
v = next(0);
if (v<'0') break;
if (v>'9') break;
*lvalue += getxmlchar();
}
if (lvalue->size()==0)
return scanSingle();
}
return CharRefToken;
}
int4 XmlScan::scanAttValue(int4 quote)
{
clearlvalue();
lvalue = new string();
while(next(0) != -1) {
if (next(0) == quote) break;
if (next(0) == '<') break;
if (next(0) == '&') break;
*lvalue += getxmlchar();
}
if (lvalue->size() == 0)
return scanSingle();
return AttValueToken;
}
int4 XmlScan::scanComment(void)
{
clearlvalue();
lvalue = new string();
while(next(0) != -1) {
if (next(0)=='-')
if (next(1)=='-')
break;
if (!isChar(next(0))) break;
*lvalue += getxmlchar();
}
return CommentToken;
}
int4 XmlScan::scanName(void)
{
clearlvalue();
lvalue = new string();
if (!isInitialNameChar(next(0)))
return scanSingle();
*lvalue += getxmlchar();
while(next(0) != -1) {
if (!isNameChar(next(0))) break;
*lvalue += getxmlchar();
}
return NameToken;
}
int4 XmlScan::scanSName(void)
{
int4 whitecount = 0;
while((next(0)==' ')||(next(0)=='\n')||(next(0)=='\r')||(next(0)=='\t')) {
whitecount += 1;
getxmlchar();
}
clearlvalue();
lvalue = new string();
if (!isInitialNameChar(next(0))) { // First non-whitespace is not Name char
if (whitecount > 0)
return ' ';
return scanSingle();
}
*lvalue += getxmlchar();
while(next(0) != -1) {
if (!isNameChar(next(0))) break;
*lvalue += getxmlchar();
}
if (whitecount>0)
return SNameToken;
return NameToken;
}
bool XmlScan::isInitialNameChar(int4 val)
{
if (isLetter(val)) return true;
if ((val=='_')||(val==':')) return true;
return false;
}
bool XmlScan::isNameChar(int4 val)
{
if (isLetter(val)) return true;
if ((val>='0')&&(val<='9')) return true;
if ((val=='.')||(val=='-')||(val=='_')||(val==':')) return true;
return false;
}
bool XmlScan::isChar(int4 val)
{
if (val>=0x20) return true;
if ((val == 0xd)||(val==0xa)||(val==0x9)) return true;
return false;
}
int4 XmlScan::nexttoken(void)
{
mode mymode = curmode;
curmode = SingleMode;
switch(mymode) {
case CharDataMode:
return scanCharData();
case CDataMode:
return scanCData();
case AttValueSingleMode:
return scanAttValue('\'');
case AttValueDoubleMode:
return scanAttValue('"');
case CommentMode:
return scanComment();
case CharRefMode:
return scanCharRef();
case NameMode:
return scanName();
case SNameMode:
return scanSName();
case SingleMode:
return scanSingle();
}
return -1;
}
void print_content(const string &str)
{
uint4 i;
for(i=0;i<str.size();++i) {
if (str[i]==' ') continue;
if (str[i]=='\n') continue;
if (str[i]=='\r') continue;
if (str[i]=='\t') continue;
break;
}
if (i==str.size())
handler->ignorableWhitespace(str.c_str(),0,str.size());
else
handler->characters(str.c_str(),0,str.size());
}
int4 convertEntityRef(const string &ref)
{
if (ref == "lt") return '<';
if (ref == "amp") return '&';
if (ref == "gt") return '>';
if (ref == "quot") return '"';
if (ref == "apos") return '\'';
return -1;
}
int4 convertCharRef(const string &ref)
{
uint4 i;
int4 mult,val,cur;
if (ref[0]=='x') {
i = 1;
mult = 16;
}
else {
i = 0;
mult = 10;
}
val = 0;
for(;i<ref.size();++i) {
if (ref[i]<='9') cur = ref[i]-'0';
else if (ref[i]<='F') cur = 10+ref[i]-'A';
else cur=10+ref[i]-'a';
val *= mult;
val += cur;
}
return val;
}
int xmllex(void)
{
int res = global_scan->nexttoken();
if (res>255)
yylval.str = global_scan->lval();
return res;
}
int xmlerror(const char *str)
{
handler->setError(str);
return 0;
}
int4 xml_parse(istream &i,ContentHandler *hand,int4 dbg)
{
#if YYDEBUG
yydebug = dbg;
#endif
global_scan = new XmlScan(i);
handler = hand;
handler->startDocument();
int4 res = yyparse();
if (res == 0)
handler->endDocument();
delete global_scan;
return res;
}
void TreeHandler::startElement(const string &namespaceURI,const string &localName,
const string &qualifiedName,const Attributes &atts)
{
Element *newel = new Element(cur);
cur->addChild(newel);
cur = newel;
newel->setName(localName);
for(int4 i=0;i<atts.getLength();++i)
newel->addAttribute(atts.getLocalName(i),atts.getValue(i));
}
void TreeHandler::endElement(const string &namespaceURI,const string &localName,
const string &qualifiedName)
{
cur = cur->getParent();
}
void TreeHandler::characters(const char *text,int4 start,int4 length)
{
cur->addContent(text,start,length);
}
Element::~Element(void)
{
List::iterator iter;
for(iter=children.begin();iter!=children.end();++iter)
delete *iter;
}
const string &Element::getAttributeValue(const string &nm) const
{
for(uint4 i=0;i<attr.size();++i)
if (attr[i] == nm)
return value[i];
throw DecoderError("Unknown attribute: "+nm);
}
DocumentStorage::~DocumentStorage(void)
{
for(int4 i=0;i<doclist.size();++i) {
if (doclist[i] != (Document *)0)
delete doclist[i];
}
}
Document *DocumentStorage::parseDocument(istream &s)
{
doclist.push_back((Document *)0);
doclist.back() = xml_tree(s);
return doclist.back();
}
Document *DocumentStorage::openDocument(const string &filename)
{
ifstream s(filename.c_str());
if (!s)
throw DecoderError("Unable to open xml document "+filename);
Document *res = parseDocument(s);
s.close();
return res;
}
void DocumentStorage::registerTag(const Element *el)
{
tagmap[el->getName()] = el;
}
const Element *DocumentStorage::getTag(const string &nm) const
{
map<string,const Element *>::const_iterator iter;
iter = tagmap.find(nm);
if (iter != tagmap.end())
return (*iter).second;
return (const Element *)0;
}
Document *xml_tree(istream &i)
{
Document *doc = new Document();
TreeHandler handle(doc);
if (0!=xml_parse(i,&handle)) {
delete doc;
throw DecoderError(handle.getError());
}
return doc;
}
void xml_escape(ostream &s,const char *str)
{
while(*str!='\0') {
if (*str < '?') {
if (*str=='<') s << "<";
else if (*str=='>') s << ">";
else if (*str=='&') s << "&";
else if (*str=='"') s << """;
else if (*str=='\'') s << "'";
else s << *str;
}
else
s << *str;
str++;
}
}
} // End namespace ghidra
| 412 | 0.955382 | 1 | 0.955382 | game-dev | MEDIA | 0.346986 | game-dev | 0.802344 | 1 | 0.802344 |
risingPhil/PokeMe64 | 2,632 | include/widget/DistributionPokemonMenuItemWidget.h | #ifndef _DISTRIBUTIONPOKEMONMENUITEMWIDGET_H
#define _DISTRIBUTIONPOKEMONMENUITEMWIDGET_H
#include "widget/PokemonPartyIconWidget.h"
#include "widget/MenuItemWidget.h"
typedef struct DistributionPokemonMenuItemStyle
{
/**
* width and height for the MenuItemWidget
*/
Dimensions size;
struct {
/**
* (optional) background sprite
*/
sprite_t* sprite;
/*
* RenderSettings that influence how the backgroundSprite is
* being rendered
*/
SpriteRenderSettings spriteSettings;
} background;
struct {
PokemonPartyIconWidgetStyle style;
Rectangle bounds;
} icon;
/**
* These are the text settings for when the MenuItemWidget is NOT focused by the user
*/
TextRenderSettings titleNotFocused;
/**
* These are the text render settings for when the MenuItemWidget is focused by the user
*/
TextRenderSettings titleFocused;
/**
* Offset to indicate how far from the left we need to start rendering the title text
*/
uint16_t leftMargin;
/**
* Offset to indicate how far from the top we need to start rendering the title text
*/
uint16_t topMargin;
} DistributionPokemonMenuItemStyle;
typedef struct DistributionPokemonMenuItemData : public MenuItemData
{
PokemonPartyIconWidgetData iconData;
} DistributionPokemonMenuItemData;
/**
* @brief This is a custom MenuItem widget to display distribution event pokemon in a vertical list menu.
*/
class DistributionPokemonMenuItem : public IWidget
{
public:
DistributionPokemonMenuItem();
virtual ~DistributionPokemonMenuItem();
const DistributionPokemonMenuItemData& getData() const;
void setData(const DistributionPokemonMenuItemData& data);
void setStyle(const DistributionPokemonMenuItemStyle& style);
bool isFocused() const override;
void setFocused(bool isFocused) override;
bool isVisible() const override;
void setVisible(bool visible) override;
Rectangle getBounds() const override;
void setBounds(const Rectangle& bounds) override;
Dimensions getSize() const override;
bool handleUserInput(const joypad_inputs_t& userInput) override;
void render(RDPQGraphics& gfx, const Rectangle& parentBounds) override;
protected:
/**
* Executes the onConfirmAction callback (if any)
*/
bool execute();
private:
PokemonPartyIconWidget partyIconWidget_;
DistributionPokemonMenuItemStyle style_;
DistributionPokemonMenuItemData data_;
bool focused_;
bool visible_;
bool aButtonPressed_;
};
#endif | 412 | 0.926324 | 1 | 0.926324 | game-dev | MEDIA | 0.865777 | game-dev | 0.794389 | 1 | 0.794389 |
dma-educational-resources/eft-dma-radar | 17,359 | arena-dma-radar/UI/Misc/GuiMisc.cs | ο»Ώusing arena_dma_radar;
using arena_dma_radar.UI.ESP;
using arena_dma_radar.UI.Misc;
using arena_dma_radar.Arena.ArenaPlayer;
using eft_dma_shared.Common.Maps;
using eft_dma_shared.Common.Misc;
using eft_dma_shared.Common.Misc.Data;
using eft_dma_shared.Common.Unity;
namespace arena_dma_radar.UI.Misc
{
/// <summary>
/// Contains long/short names for player gear.
/// </summary>
public sealed class GearItem
{
public string Long { get; init; }
public string Short { get; init; }
}
/// <summary>
/// Represents a PMC in the PMC History log.
/// </summary>
public sealed class PlayerHistoryEntry
{
private readonly Player _player;
private DateTime _lastSeen;
/// <summary>
/// The Player Object that this entry is bound to.
/// </summary>
public Player Player => _player;
public string Name => _player.Name;
public string ID => _player.AccountID;
public string Acct
{
get
{
if (_player is ArenaObservedPlayer observed)
return observed.Profile?.Acct;
return "--";
}
}
public string Type => $"{_player.Type.GetDescription()}";
public string KD
{
get
{
if (_player is ArenaObservedPlayer observed && observed.Profile?.Overall_KD is float kd)
return kd.ToString("n2");
return "--";
}
}
public string Hours
{
get
{
if (_player is ArenaObservedPlayer observed && observed.Profile?.Hours is int hours)
return hours.ToString();
return "--";
}
}
/// <summary>
/// When this player was last seen
/// </summary>
public DateTime LastSeen
{
get => _lastSeen;
private set => _lastSeen = value;
}
/// <summary>
/// Formatted LastSeen for display in UI
/// </summary>
public string LastSeenFormatted
{
get
{
var timeSpan = DateTime.Now - _lastSeen;
if (timeSpan.TotalMinutes < 1)
return "Just now";
else if (timeSpan.TotalMinutes < 60)
return $"{(int)timeSpan.TotalMinutes}m ago";
else if (timeSpan.TotalHours < 24)
return $"{(int)timeSpan.TotalHours}h ago";
else if (timeSpan.TotalDays < 7)
return $"{(int)timeSpan.TotalDays}d ago";
else
return _lastSeen.ToString("MM/dd/yyyy");
}
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="player">Player Object to bind to.</param>
public PlayerHistoryEntry(Player player)
{
ArgumentNullException.ThrowIfNull(player, nameof(player));
_player = player;
_lastSeen = DateTime.Now;
}
/// <summary>
/// Updates the LastSeen timestamp to current time
/// </summary>
public void UpdateLastSeen()
{
LastSeen = DateTime.Now;
}
/// <summary>
/// Updates the LastSeen timestamp to a specific time
/// </summary>
/// <param name="timestamp">The timestamp when the player was seen</param>
public void UpdateLastSeen(DateTime timestamp)
{
LastSeen = timestamp;
}
}
/// <summary>
/// JSON Wrapper for Player Watchlist.
/// </summary>
public sealed class PlayerWatchlistEntry
{
/// <summary>
/// Player's Account ID as obtained from Player History.
/// </summary>
[JsonPropertyName("acctID")]
public string AccountID { get; set; } = string.Empty;
/// <summary>
/// Reason for adding player to Watchlist (ex: Cheater, streamer name,etc.)
/// </summary>
[JsonPropertyName("reason")]
public string Reason { get; set; } = string.Empty;
/// <summary>
/// The streaming platform (Twitch, YouTube, etc.)
/// </summary>
[JsonPropertyName("platform")]
public StreamingPlatform StreamingPlatform { get; set; } = StreamingPlatform.None;
/// <summary>
/// The platform username
/// </summary>
[JsonPropertyName("username")]
public string Username { get; set; } = string.Empty;
}
public sealed class ScreenEntry
{
private readonly int _screenNumber;
/// <summary>
/// Screen Index Number.
/// </summary>
public int ScreenNumber => _screenNumber;
public ScreenEntry(int screenNumber)
{
_screenNumber = screenNumber;
}
public override string ToString() => $"Screen {_screenNumber}";
}
public sealed class BonesListItem
{
public string Name { get; }
public Bones Bone { get; }
public BonesListItem(Bones bone)
{
Name = bone.GetDescription();
Bone = bone;
}
public override string ToString() => Name;
}
public sealed class QuestListItem : INotifyPropertyChanged
{
public string Name { get; }
public string Id { get; }
private bool _isSelected;
public bool IsSelected
{
get => _isSelected;
set
{
if (_isSelected != value)
{
_isSelected = value;
OnPropertyChanged(nameof(IsSelected));
}
}
}
public QuestListItem(string id, bool isSelected)
{
Id = id;
if (EftDataManager.TaskData.TryGetValue(id, out var task))
{
Name = task.Name ?? id;
}
else
Name = id;
IsSelected = isSelected;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string prop) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
public sealed class HotkeyDisplayModel
{
public string Action { get; set; }
public string Key { get; set; }
public string Type { get; set; }
public string Display => $"{Action} ({Key})";
}
/// <summary>
/// Wrapper class for displaying container info in the UI.
/// </summary>
public sealed class ContainerListItem : INotifyPropertyChanged
{
public string Name { get; }
public string Id { get; }
public List<string> GroupedIds { get; set; } = new();
private bool _isSelected;
public bool IsSelected
{
get => _isSelected;
set
{
if (_isSelected != value)
{
_isSelected = value;
OnPropertyChanged(nameof(IsSelected));
}
}
}
public ContainerListItem(TarkovMarketItem container)
{
Name = container.ShortName;
Id = container.BsgId;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string prop) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
public static class SkiaResourceTracker
{
private static DateTime _lastMainWindowPurge = DateTime.UtcNow;
private static DateTime _lastESPPurge = DateTime.UtcNow;
private static int _mainWindowFrameCount = 0;
private static int _espFrameCount = 0;
public static void TrackMainWindowFrame()
{
_mainWindowFrameCount++;
var now = DateTime.UtcNow;
var timeSincePurge = (now - _lastMainWindowPurge).TotalSeconds;
if (timeSincePurge >= 5.0 && _mainWindowFrameCount % 300 == 0)
{
_lastMainWindowPurge = now;
MainWindow.Window?.PurgeSKResources();
}
}
public static void TrackESPFrame()
{
_espFrameCount++;
var now = DateTime.UtcNow;
var timeSincePurge = (now - _lastESPPurge).TotalSeconds;
if (timeSincePurge >= 10.0 && _espFrameCount % 600 == 0)
{
_lastESPPurge = now;
//ESPForm.Window?.PurgeSKResources();
}
}
}
public enum LootPriceMode : int
{
/// <summary>
/// Optimal Flea Price.
/// </summary>
FleaMarket = 0,
/// <summary>
/// Highest Trader Price.
/// </summary>
Trader = 1
}
public enum ApplicationMode
{
Normal,
SafeMode
}
/// <summary>
/// Defines how entity types are rendered on the map
/// </summary>
public enum EntityRenderMode
{
[Description("None")]
None,
[Description("Dot")]
Dot,
[Description("Cross")]
Cross,
[Description("Plus")]
Plus,
[Description("Square")]
Square,
[Description("Diamond")]
Diamond
}
/// <summary>
/// Enum representing different streaming platforms
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum StreamingPlatform
{
/// <summary>
/// No streaming platform
/// </summary>
None,
/// <summary>
/// Twitch.tv streaming platform
/// </summary>
Twitch,
/// <summary>
/// YouTube streaming platform
/// </summary>
YouTube
}
/// <summary>
/// Serializable RectF Structure.
/// </summary>
public struct RectFSer
{
[JsonPropertyName("left")] public float Left { get; set; }
[JsonPropertyName("top")] public float Top { get; set; }
[JsonPropertyName("right")] public float Right { get; set; }
[JsonPropertyName("bottom")] public float Bottom { get; set; }
public RectFSer(float left, float top, float right, float bottom)
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
}
public struct PointFSer
{
[JsonPropertyName("x")]
public float X { get; set; }
[JsonPropertyName("y")]
public float Y { get; set; }
public PointFSer() { }
public PointFSer(float x, float y)
{
X = x;
Y = y;
}
}
public static class GuiExtensions
{
#region GUI Extensions
/// <summary>
/// Convert Unity Position (X,Y,Z) to an unzoomed Map Position..
/// </summary>
/// <param name="vector">Unity Vector3</param>
/// <param name="map">Current Map</param>
/// <returns>Unzoomed 2D Map Position.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 ToMapPos(this System.Numerics.Vector3 vector, LoneMapConfig map) =>
new()
{
X = (map.X * map.SvgScale) + (vector.X * (map.Scale * map.SvgScale)),
Y = (map.Y * map.SvgScale) - (vector.Z * (map.Scale * map.SvgScale))
};
/// <summary>
/// Convert an Unzoomed Map Position to a Zoomed Map Position ready for 2D Drawing.
/// </summary>
/// <param name="mapPos">Unzoomed Map Position.</param>
/// <param name="mapParams">Current Map Parameters.</param>
/// <returns>Zoomed 2D Map Position.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static SKPoint ToZoomedPos(this Vector2 mapPos, LoneMapParams mapParams) =>
new SKPoint()
{
X = (mapPos.X - mapParams.Bounds.Left) * mapParams.XScale,
Y = (mapPos.Y - mapParams.Bounds.Top) * mapParams.YScale
};
/// <summary>
/// Gets a drawable 'Up Arrow'. IDisposable. Applies UI Scaling internally.
/// </summary>
public static SKPath GetUpArrow(this SKPoint point, float size = 6, float offsetX = 0, float offsetY = 0)
{
float x = point.X + offsetX;
float y = point.Y + offsetY;
size *= MainWindow.UIScale;
var path = new SKPath();
path.MoveTo(x, y);
path.LineTo(x - size, y + size);
path.LineTo(x + size, y + size);
path.Close();
return path;
}
/// <summary>
/// Gets a drawable 'Down Arrow'. IDisposable. Applies UI Scaling internally.
/// </summary>
public static SKPath GetDownArrow(this SKPoint point, float size = 6, float offsetX = 0, float offsetY = 0)
{
float x = point.X + offsetX;
float y = point.Y + offsetY;
size *= MainWindow.UIScale;
var path = new SKPath();
path.MoveTo(x, y);
path.LineTo(x - size, y - size);
path.LineTo(x + size, y - size);
path.Close();
return path;
}
/// <summary>
/// Draws a Mine/Explosive Marker on this zoomed location.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void DrawMineMarker(this SKPoint zoomedMapPos, SKCanvas canvas)
{
float length = 3.5f * MainWindow.UIScale;
canvas.DrawLine(new SKPoint(zoomedMapPos.X - length, zoomedMapPos.Y + length), new SKPoint(zoomedMapPos.X + length, zoomedMapPos.Y - length), SKPaints.PaintExplosives);
canvas.DrawLine(new SKPoint(zoomedMapPos.X - length, zoomedMapPos.Y - length), new SKPoint(zoomedMapPos.X + length, zoomedMapPos.Y + length), SKPaints.PaintExplosives);
}
/// <summary>
/// Draws Mouseover Text (with backer) on this zoomed location.
/// </summary>
public static void DrawMouseoverText(this SKPoint zoomedMapPos, SKCanvas canvas, IEnumerable<string> lines)
{
float maxLength = 0;
foreach (var line in lines)
{
var length = SKPaints.TextMouseover.MeasureText(line);
if (length > maxLength)
maxLength = length;
}
var backer = new SKRect()
{
Bottom = zoomedMapPos.Y + ((lines.Count() * 12f) - 2) * MainWindow.UIScale,
Left = zoomedMapPos.X + (9 * MainWindow.UIScale),
Top = zoomedMapPos.Y - (9 * MainWindow.UIScale),
Right = zoomedMapPos.X + (9 * MainWindow.UIScale) + maxLength + (6 * MainWindow.UIScale)
};
canvas.DrawRect(backer, SKPaints.PaintTransparentBacker); // Draw tooltip backer
zoomedMapPos.Offset(11 * MainWindow.UIScale, 3 * MainWindow.UIScale);
foreach (var line in lines) // Draw tooltip text
{
if (string.IsNullOrEmpty(line?.Trim()))
continue;
canvas.DrawText(line, zoomedMapPos, SKPaints.TextMouseover); // draw line text
zoomedMapPos.Offset(0, 12f * MainWindow.UIScale);
}
}
/// <summary>
/// Draw ESP text with optional distance display for entities or static objects like mines
/// </summary>
public static void DrawESPText(this SKPoint screenPos, SKCanvas canvas, IESPEntity entity, LocalPlayer localPlayer, bool printDist, SKPaint paint, params string[] lines)
{
if (printDist && lines.Length > 0)
{
if (entity != null)
{
var dist = Vector3.Distance(entity.Position, localPlayer.Position);
lines[0] += $" {(int)dist}m"; ;
}
}
foreach (var x in lines)
{
if (string.IsNullOrEmpty(x?.Trim()))
continue;
canvas.DrawText(x, screenPos, paint);
screenPos.Y += paint.TextSize;
}
}
/// <summary>
/// Overload for static objects like mines where we calculate the distance with a provided value
/// </summary>
public static void DrawESPText(this SKPoint screenPos, SKCanvas canvas, IESPEntity entity, LocalPlayer localPlayer, bool printDist, SKPaint paint, string label, float distance)
{
if (string.IsNullOrEmpty(label))
return;
string textWithDist = label;
if (printDist)
{
string distStr;
if (distance < 10f)
{
distStr = $" {distance.ToString("n1")}m";
}
else
{
distStr = $" {(int)distance}m";
}
textWithDist += distStr;
}
canvas.DrawText(textWithDist, screenPos, paint);
}
#endregion
}
}
| 412 | 0.931162 | 1 | 0.931162 | game-dev | MEDIA | 0.644736 | game-dev | 0.942864 | 1 | 0.942864 |
thedarkcolour/ForestryCE | 7,411 | src/main/java/forestry/factory/tiles/TileStill.java | /*******************************************************************************
* Copyright (c) 2011-2014 SirSengir.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Various Contributors including, but not limited to:
* SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges
******************************************************************************/
package forestry.factory.tiles;
import com.google.common.base.Preconditions;
import forestry.api.core.ForestryError;
import forestry.api.core.IErrorLogic;
import forestry.api.recipes.IStillRecipe;
import forestry.core.config.Constants;
import forestry.core.fluids.FilteredTank;
import forestry.core.fluids.FluidHelper;
import forestry.core.fluids.FluidRecipeFilter;
import forestry.core.fluids.TankManager;
import forestry.core.render.TankRenderInfo;
import forestry.core.tiles.ILiquidTankTile;
import forestry.core.tiles.TilePowered;
import forestry.core.utils.RecipeUtils;
import forestry.factory.features.FactoryTiles;
import forestry.factory.gui.ContainerStill;
import forestry.factory.inventory.InventoryStill;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.WorldlyContainer;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ForgeCapabilities;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidHandler;
import javax.annotation.Nullable;
import java.util.Objects;
public class TileStill extends TilePowered implements WorldlyContainer, ILiquidTankTile {
private static final int ENERGY_PER_RECIPE_TIME = 200;
private final FilteredTank resourceTank;
private final FilteredTank productTank;
private final TankManager tankManager;
@Nullable
private IStillRecipe currentRecipe = null;
private FluidStack bufferedLiquid = FluidStack.EMPTY;
public TileStill(BlockPos pos, BlockState state) {
super(FactoryTiles.STILL.tileType(), pos, state, 1100, 80000);
setInternalInventory(new InventoryStill(this));
this.resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, true, true).setFilter(FluidRecipeFilter.STILL_INPUT);
this.productTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, false, true).setFilter(FluidRecipeFilter.STILL_OUTPUT);
this.tankManager = new TankManager(this, this.resourceTank, this.productTank);
}
@Override
public void saveAdditional(CompoundTag compoundNBT) {
super.saveAdditional(compoundNBT);
this.tankManager.write(compoundNBT);
if (!this.bufferedLiquid.isEmpty()) {
CompoundTag buffer = new CompoundTag();
this.bufferedLiquid.writeToNBT(buffer);
compoundNBT.put("Buffer", buffer);
}
}
@Override
public void load(CompoundTag compoundNBT) {
super.load(compoundNBT);
this.tankManager.read(compoundNBT);
if (compoundNBT.contains("Buffer")) {
CompoundTag buffer = compoundNBT.getCompound("Buffer");
this.bufferedLiquid = FluidStack.loadFluidStackFromNBT(buffer);
}
}
@Override
public void writeData(FriendlyByteBuf data) {
super.writeData(data);
this.tankManager.writeData(data);
}
@Override
public void readData(FriendlyByteBuf data) {
super.readData(data);
this.tankManager.readData(data);
}
@Override
public void serverTick(Level level, BlockPos pos, BlockState state) {
super.serverTick(level, pos, state);
if (updateOnInterval(20)) {
FluidHelper.drainContainers(this.tankManager, this, InventoryStill.SLOT_CAN);
FluidStack fluidStack = this.productTank.getFluid();
if (!fluidStack.isEmpty()) {
FluidHelper.fillContainers(this.tankManager, this, InventoryStill.SLOT_RESOURCE, InventoryStill.SLOT_PRODUCT, fluidStack.getFluid(), true);
}
}
}
@Override
public boolean workCycle() {
Preconditions.checkNotNull(this.currentRecipe);
int cycles = this.currentRecipe.getCyclesPerUnit();
FluidStack output = this.currentRecipe.getOutput();
FluidStack product = new FluidStack(output, output.getAmount() * cycles);
this.productTank.fillInternal(product, IFluidHandler.FluidAction.EXECUTE);
this.bufferedLiquid = FluidStack.EMPTY;
return true;
}
private void checkRecipe() {
FluidStack recipeLiquid = !this.bufferedLiquid.isEmpty() ? this.bufferedLiquid : this.resourceTank.getFluid();
if (this.currentRecipe == null || !this.currentRecipe.matches(recipeLiquid)) {
Level level = Objects.requireNonNull(this.level);
this.currentRecipe = RecipeUtils.getStillRecipe(level.getRecipeManager(), recipeLiquid);
int recipeTime = this.currentRecipe == null ? 0 : this.currentRecipe.getCyclesPerUnit();
setEnergyPerWorkCycle(ENERGY_PER_RECIPE_TIME * recipeTime);
setTicksPerWorkCycle(recipeTime);
}
}
@Override
public boolean hasWork() {
checkRecipe();
boolean hasRecipe = this.currentRecipe != null;
boolean hasTankSpace = true;
boolean hasLiquidResource = true;
if (hasRecipe) {
FluidStack fluidStack = this.currentRecipe.getOutput();
hasTankSpace = this.productTank.fillInternal(fluidStack, IFluidHandler.FluidAction.SIMULATE) == fluidStack.getAmount();
if (this.bufferedLiquid.isEmpty()) {
int cycles = this.currentRecipe.getCyclesPerUnit();
FluidStack input = this.currentRecipe.getInput();
int drainAmount = cycles * input.getAmount();
FluidStack drained = this.resourceTank.drain(drainAmount, IFluidHandler.FluidAction.SIMULATE);
hasLiquidResource = !drained.isEmpty() && drained.getAmount() == drainAmount;
if (hasLiquidResource) {
this.bufferedLiquid = new FluidStack(input, drainAmount);
this.resourceTank.drain(drainAmount, IFluidHandler.FluidAction.EXECUTE);
}
}
}
IErrorLogic errorLogic = getErrorLogic();
errorLogic.setCondition(!hasRecipe, ForestryError.NO_RECIPE);
errorLogic.setCondition(!hasTankSpace, ForestryError.NO_SPACE_TANK);
errorLogic.setCondition(!hasLiquidResource, ForestryError.NO_RESOURCE_LIQUID);
return hasRecipe && hasLiquidResource && hasTankSpace;
}
@Override
public TankRenderInfo getResourceTankInfo() {
return new TankRenderInfo(this.resourceTank);
}
@Override
public TankRenderInfo getProductTankInfo() {
return new TankRenderInfo(this.productTank);
}
@Override
public TankManager getTankManager() {
return this.tankManager;
}
@Override
public <T> LazyOptional<T> getCapability(Capability<T> capability, @Nullable Direction facing) {
if (capability == ForgeCapabilities.FLUID_HANDLER) {
return LazyOptional.of(() -> this.tankManager).cast();
}
return super.getCapability(capability, facing);
}
@Override
public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) {
return new ContainerStill(windowId, player.getInventory(), this);
}
}
| 412 | 0.910033 | 1 | 0.910033 | game-dev | MEDIA | 0.995634 | game-dev | 0.973424 | 1 | 0.973424 |
joekoolade/JOE | 14,724 | rvm/src/org/jikesrvm/compilers/opt/regalloc/CompoundInterval.java | /*
* This file is part of the Jikes RVM project (http://jikesrvm.org).
*
* This file is licensed to You under the Eclipse Public License (EPL);
* You may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership.
*/
package org.jikesrvm.compilers.opt.regalloc;
import java.util.Iterator;
import java.util.SortedSet;
import org.jikesrvm.VM;
import org.jikesrvm.compilers.opt.ir.BasicBlock;
import org.jikesrvm.compilers.opt.ir.Instruction;
import org.jikesrvm.compilers.opt.ir.Register;
/**
* Implements a live interval with holes; i.e. an ordered set of basic live
* intervals. There is exactly one instance of this class for each
* Register.
* <p>
* The order that this set imposes is inconsistent with equals.
* <p>
* This class is designed for use by a single thread.
*/
class CompoundInterval extends IncreasingStartIntervalSet {
/** Support for Set serialization */
static final long serialVersionUID = 7423553044815762071L;
/**
* Is this compound interval fully contained in infrequent code?
*/
private boolean _infrequent = true;
final void setFrequent() {
_infrequent = false;
}
final boolean isInfrequent() {
return _infrequent;
}
/**
* The register this compound interval represents or {@code null}
* if this interval is not associated with a register (i.e. if it
* represents a spill location).
*/
private final Register reg;
/**
* A spill location assigned for this interval.
*/
private SpillLocationInterval spillInterval;
SpillLocationInterval getSpillInterval() {
return spillInterval;
}
/**
* @return the register this interval represents
*/
Register getRegister() {
return reg;
}
/**
* Creates a new compound interval of a single Basic interval.
*
* @param dfnBegin interval's begin
* @param dfnEnd interval's end
* @param register the register for the compound interval
*/
CompoundInterval(int dfnBegin, int dfnEnd, Register register) {
BasicInterval newInterval = new MappedBasicInterval(dfnBegin, dfnEnd, this);
add(newInterval);
reg = register;
}
/**
* Creates a new compound interval of a single Basic interval.
*
* @param i interval providing start and end for the new interval
* @param register the register for the compound interval
*/
CompoundInterval(BasicInterval i, Register register) {
BasicInterval newInterval = new MappedBasicInterval(i.getBegin(), i.getEnd(), this);
add(newInterval);
reg = register;
}
/**
* Dangerous constructor: use with care.
* <p>
* Creates a compound interval with a register but doesn't actually
* add any intervals to the compound interval.
*
* @param r a register
*/
protected CompoundInterval(Register r) {
reg = r;
}
/**
* Copies the ranges from this interval into a new interval associated
* with a register.
*
* @param r the register for the new interval
* @return the new interval
*/
CompoundInterval copy(Register r) {
CompoundInterval result = new CompoundInterval(r);
for (Iterator<BasicInterval> i = iterator(); i.hasNext();) {
BasicInterval b = i.next();
result.add(b);
}
return result;
}
/**
* Copies the basic intervals up to and including stop into a new interval.
* The new interval is associated with the given register.
*
* @param r the register for the new interval
* @param stop the interval to stop at
* @return the new interval
*/
CompoundInterval copy(Register r, BasicInterval stop) {
CompoundInterval result = new CompoundInterval(r);
for (Iterator<BasicInterval> i = iterator(); i.hasNext();) {
BasicInterval b = i.next();
result.add(b);
if (b.sameRange(stop)) return result;
}
return result;
}
/**
* Add a new live range to this compound interval.
* @param regAllocState depth-first numbers for for instructions
* @param live the new live range
* @param bb the basic block for live
*
* @return the new basic interval if one was created; null otherwise
*/
BasicInterval addRange(RegisterAllocatorState regAllocState, LiveIntervalElement live, BasicBlock bb) {
if (shouldConcatenate(regAllocState, live, bb)) {
// concatenate with the last basic interval
BasicInterval last = last();
last.setEnd(regAllocState.getDfnEnd(live, bb));
return null;
} else {
// create a new basic interval and append it to the list.
BasicInterval newInterval = new MappedBasicInterval(regAllocState.getDfnBegin(live, bb), regAllocState.getDfnEnd(live, bb), this);
add(newInterval);
return newInterval;
}
}
/**
* Should we simply merge the live interval <code>live</code> into a
* previous BasicInterval?
* @param regAllocState depth-first numbers for for instructions
* @param live the live interval being queried
* @param bb the basic block in which live resides.
*
* @return {@code true} if the interval should be concatenated, {@code false}
* if it should'nt
*/
private boolean shouldConcatenate(RegisterAllocatorState regAllocState, LiveIntervalElement live, BasicBlock bb) {
BasicInterval last = last();
// Make sure the new live range starts after the last basic interval
if (VM.VerifyAssertions) {
VM._assert(last.getEnd() <= regAllocState.getDfnBegin(live, bb));
}
int dfnBegin = regAllocState.getDfnBegin(live, bb);
if (live.getBegin() != null) {
if (live.getBegin() == bb.firstRealInstruction()) {
// live starts the basic block. Now make sure it is contiguous
// with the last interval.
return last.getEnd() + 1 >= dfnBegin;
} else {
// live does not start the basic block. Merge with last iff
// last and live share an instruction. This happens when a
// register is def'ed and use'd in the same instruction.
return last.getEnd() == dfnBegin;
}
} else {
// live.getBegin == null.
// Merge if it is contiguous with the last interval.
int dBegin = regAllocState.getDFN(bb.firstInstruction());
return last.getEnd() + 1 >= dBegin;
}
}
/**
* Assign this compound interval to a free spill location.
*
* @param spillManager governing spill location manager
* @param regAllocState current state of the register allocator
*/
void spill(SpillLocationManager spillManager, RegisterAllocatorState regAllocState) {
spillInterval = spillManager.findOrCreateSpillLocation(this);
regAllocState.setSpill(reg, spillInterval.getOffset());
regAllocState.clearOneToOne(reg);
if (LinearScan.VERBOSE_DEBUG) {
System.out.println("Assigned " + reg + " to location " + spillInterval.getOffset());
}
}
boolean isSpilled(RegisterAllocatorState regAllocState) {
return (regAllocState.getSpill(getRegister()) != 0);
}
/**
* Assign this compound interval to a physical register.
*
* @param r the register to assign to
*/
void assign(Register r) {
getRegister().allocateToRegister(r);
}
/**
* @param regAllocState current state of the register allocator
* @return {@code true} if this interval has been assigned to
* a physical register
*/
boolean isAssigned(RegisterAllocatorState regAllocState) {
return (regAllocState.getMapping(getRegister()) != null);
}
/**
* @param regAllocState current state of the register allocator
* @return the physical register this interval is assigned to, {@code null}
* if none assigned
*/
Register getAssignment(RegisterAllocatorState regAllocState) {
return regAllocState.getMapping(getRegister());
}
/**
* Merges this interval with another, non-intersecting interval.
* <p>
* Precondition: BasicInterval stop is an interval in i. This version
* will only merge basic intervals up to and including stop into this.
*
* @param i a non-intersecting interval for merging
* @param stop a interval to stop at
*/
void addNonIntersectingInterval(CompoundInterval i, BasicInterval stop) {
SortedSet<BasicInterval> headSet = i.headSetInclusive(stop);
addAll(headSet);
}
/**
* Computes the headSet() [from java.util.SortedSet] but includes all
* elements less than upperBound <em>inclusive</em>.
*
* @param upperBound the interval acting as upper bound
* @return the head set
* @see SortedSet#headSet(Object)
*/
SortedSet<BasicInterval> headSetInclusive(BasicInterval upperBound) {
BasicInterval newUpperBound = new BasicInterval(upperBound.getBegin() + 1, upperBound.getEnd());
return headSet(newUpperBound);
}
/**
* Computes the headSet() [from java.util.SortedSet] but includes all
* elements less than upperBound <em>inclusive</em>.
*
* @param upperBound the instruction number acting as upper bound
* @return the head set
* @see SortedSet#headSet(Object)
*/
SortedSet<BasicInterval> headSetInclusive(int upperBound) {
BasicInterval newUpperBound = new BasicInterval(upperBound + 1, upperBound + 1);
return headSet(newUpperBound);
}
/**
* Computes the tailSet() [from java.util.SortedSet] but includes all
* elements greater than lowerBound <em>inclusive</em>.
*
* @param lowerBound the instruction number acting as lower bound
* @return the tail set
* @see SortedSet#tailSet(Object)
*/
SortedSet<BasicInterval> tailSetInclusive(int lowerBound) {
BasicInterval newLowerBound = new BasicInterval(lowerBound - 1, lowerBound - 1);
return tailSet(newLowerBound);
}
/**
* Removes some basic intervals from this compound interval, and returns
* the intervals actually removed.
* <p>
* PRECONDITION: All basic intervals in the other interval that have the
* same begin as an interval in this compound interval must have the same
* end. For example, for a compound interval {@code [(1,2)(2,3)]},
* the other interval would be allowed to contain {@code (1,2)} and/or
* {@code (2,2)} but not {@code (1,3)}.
* <p>
* A violation of the precondition that would have an effect will trigger
* an assertion failure in assertion-enabled builds.
*
* @param other interval to check for intervals that we want to remove
* from this
* @return the basic intervals that were removed
*/
CompoundInterval removeIntervalsAndCache(CompoundInterval other) {
CompoundInterval result = new CompoundInterval(other.getRegister());
Iterator<BasicInterval> myIterator = iterator();
Iterator<BasicInterval> otherIterator = other.iterator();
BasicInterval current = myIterator.hasNext() ? myIterator.next() : null;
BasicInterval otherCurrent = otherIterator.hasNext() ? otherIterator.next() : null;
while (otherCurrent != null && current != null) {
if (current.startsBefore(otherCurrent)) {
current = myIterator.hasNext() ? myIterator.next() : null;
} else if (otherCurrent.startsBefore(current)) {
otherCurrent = otherIterator.hasNext() ? otherIterator.next() : null;
} else {
if (VM.VerifyAssertions) VM._assert(current.sameRange(otherCurrent));
otherCurrent = otherIterator.hasNext() ? otherIterator.next() : null;
BasicInterval next = myIterator.hasNext() ? myIterator.next() : null;
// add the interval to the cache
result.add(current);
current = next;
}
}
removeAll(result);
return result;
}
/**
* @return the lowest DFN in this compound interval at this time
*/
int getLowerBound() {
BasicInterval b = first();
return b.getBegin();
}
/**
* @return the highest DFN in this compound interval at this time
*/
int getUpperBound() {
BasicInterval b = last();
return b.getEnd();
}
boolean intersects(CompoundInterval i) {
if (isEmpty()) return false;
if (i.isEmpty()) return false;
// Walk over the basic intervals of this interval and i.
// Restrict the walking to intervals that might intersect.
int lower = Math.max(getLowerBound(), i.getLowerBound());
int upper = Math.min(getUpperBound(), i.getUpperBound());
// we may have to move one interval lower on each side.
BasicInterval b = getBasicInterval(lower);
int myLower = (b == null) ? lower : b.getBegin();
if (myLower > upper) return false;
b = i.getBasicInterval(lower);
int otherLower = (b == null) ? lower : b.getBegin();
if (otherLower > upper) return false;
SortedSet<BasicInterval> myTailSet = tailSetInclusive(myLower);
SortedSet<BasicInterval> otherTailSet = i.tailSetInclusive(otherLower);
Iterator<BasicInterval> myIterator = myTailSet.iterator();
Iterator<BasicInterval> otherIterator = otherTailSet.iterator();
BasicInterval current = myIterator.hasNext() ? myIterator.next() : null;
BasicInterval currentI = otherIterator.hasNext() ? otherIterator.next() : null;
while (current != null && currentI != null) {
if (current.getBegin() > upper) break;
if (currentI.getBegin() > upper) break;
if (current.intersects(currentI)) return true;
if (current.startsBefore(currentI)) {
current = myIterator.hasNext() ? myIterator.next() : null;
} else {
currentI = otherIterator.hasNext() ? otherIterator.next() : null;
}
}
return false;
}
/**
* @param dfnNumbers depth-first numbers for for instructions
* @param s The instruction in question
* @return the first basic interval that contains a given
* instruction, {@code null} if there is no such interval
*/
BasicInterval getBasicInterval(RegisterAllocatorState dfnNumbers, Instruction s) {
return getBasicInterval(dfnNumbers.getDFN(s));
}
/**
* @param n The DFN of the instruction in question
* @return the first basic interval that contains a given
* instruction, {@code null} if there is no such interval
*/
BasicInterval getBasicInterval(int n) {
SortedSet<BasicInterval> headSet = headSetInclusive(n);
if (!headSet.isEmpty()) {
BasicInterval last = headSet.last();
return last.contains(n) ? last : null;
} else {
return null;
}
}
@Override
public String toString() {
StringBuilder str = new StringBuilder("[");
str.append(getRegister());
str.append("]:");
for (Iterator<BasicInterval> i = iterator(); i.hasNext();) {
BasicInterval b = i.next();
str.append(b);
}
return str.toString();
}
}
| 412 | 0.895429 | 1 | 0.895429 | game-dev | MEDIA | 0.477865 | game-dev | 0.799017 | 1 | 0.799017 |
pganalyze/pg_query_go | 36,760 | parser/include/pg_query_fingerprint_conds.c | case T_Alias:
// Intentionally ignoring for fingerprinting
break;
case T_RangeVar:
_fingerprintString(ctx, "RangeVar");
_fingerprintRangeVar(ctx, obj, parent, field_name, depth);
break;
case T_TableFunc:
_fingerprintString(ctx, "TableFunc");
_fingerprintTableFunc(ctx, obj, parent, field_name, depth);
break;
case T_IntoClause:
_fingerprintString(ctx, "IntoClause");
_fingerprintIntoClause(ctx, obj, parent, field_name, depth);
break;
case T_Var:
_fingerprintString(ctx, "Var");
_fingerprintVar(ctx, obj, parent, field_name, depth);
break;
case T_Const:
_fingerprintString(ctx, "Const");
_fingerprintConst(ctx, obj, parent, field_name, depth);
break;
case T_Param:
_fingerprintString(ctx, "Param");
_fingerprintParam(ctx, obj, parent, field_name, depth);
break;
case T_Aggref:
_fingerprintString(ctx, "Aggref");
_fingerprintAggref(ctx, obj, parent, field_name, depth);
break;
case T_GroupingFunc:
_fingerprintString(ctx, "GroupingFunc");
_fingerprintGroupingFunc(ctx, obj, parent, field_name, depth);
break;
case T_WindowFunc:
_fingerprintString(ctx, "WindowFunc");
_fingerprintWindowFunc(ctx, obj, parent, field_name, depth);
break;
case T_WindowFuncRunCondition:
_fingerprintString(ctx, "WindowFuncRunCondition");
_fingerprintWindowFuncRunCondition(ctx, obj, parent, field_name, depth);
break;
case T_MergeSupportFunc:
_fingerprintString(ctx, "MergeSupportFunc");
_fingerprintMergeSupportFunc(ctx, obj, parent, field_name, depth);
break;
case T_SubscriptingRef:
_fingerprintString(ctx, "SubscriptingRef");
_fingerprintSubscriptingRef(ctx, obj, parent, field_name, depth);
break;
case T_FuncExpr:
_fingerprintString(ctx, "FuncExpr");
_fingerprintFuncExpr(ctx, obj, parent, field_name, depth);
break;
case T_NamedArgExpr:
_fingerprintString(ctx, "NamedArgExpr");
_fingerprintNamedArgExpr(ctx, obj, parent, field_name, depth);
break;
case T_OpExpr:
_fingerprintString(ctx, "OpExpr");
_fingerprintOpExpr(ctx, obj, parent, field_name, depth);
break;
case T_ScalarArrayOpExpr:
_fingerprintString(ctx, "ScalarArrayOpExpr");
_fingerprintScalarArrayOpExpr(ctx, obj, parent, field_name, depth);
break;
case T_BoolExpr:
_fingerprintString(ctx, "BoolExpr");
_fingerprintBoolExpr(ctx, obj, parent, field_name, depth);
break;
case T_SubLink:
_fingerprintString(ctx, "SubLink");
_fingerprintSubLink(ctx, obj, parent, field_name, depth);
break;
case T_SubPlan:
_fingerprintString(ctx, "SubPlan");
_fingerprintSubPlan(ctx, obj, parent, field_name, depth);
break;
case T_AlternativeSubPlan:
_fingerprintString(ctx, "AlternativeSubPlan");
_fingerprintAlternativeSubPlan(ctx, obj, parent, field_name, depth);
break;
case T_FieldSelect:
_fingerprintString(ctx, "FieldSelect");
_fingerprintFieldSelect(ctx, obj, parent, field_name, depth);
break;
case T_FieldStore:
_fingerprintString(ctx, "FieldStore");
_fingerprintFieldStore(ctx, obj, parent, field_name, depth);
break;
case T_RelabelType:
_fingerprintString(ctx, "RelabelType");
_fingerprintRelabelType(ctx, obj, parent, field_name, depth);
break;
case T_CoerceViaIO:
_fingerprintString(ctx, "CoerceViaIO");
_fingerprintCoerceViaIO(ctx, obj, parent, field_name, depth);
break;
case T_ArrayCoerceExpr:
_fingerprintString(ctx, "ArrayCoerceExpr");
_fingerprintArrayCoerceExpr(ctx, obj, parent, field_name, depth);
break;
case T_ConvertRowtypeExpr:
_fingerprintString(ctx, "ConvertRowtypeExpr");
_fingerprintConvertRowtypeExpr(ctx, obj, parent, field_name, depth);
break;
case T_CollateExpr:
_fingerprintString(ctx, "CollateExpr");
_fingerprintCollateExpr(ctx, obj, parent, field_name, depth);
break;
case T_CaseExpr:
_fingerprintString(ctx, "CaseExpr");
_fingerprintCaseExpr(ctx, obj, parent, field_name, depth);
break;
case T_CaseWhen:
_fingerprintString(ctx, "CaseWhen");
_fingerprintCaseWhen(ctx, obj, parent, field_name, depth);
break;
case T_CaseTestExpr:
_fingerprintString(ctx, "CaseTestExpr");
_fingerprintCaseTestExpr(ctx, obj, parent, field_name, depth);
break;
case T_ArrayExpr:
_fingerprintString(ctx, "ArrayExpr");
_fingerprintArrayExpr(ctx, obj, parent, field_name, depth);
break;
case T_RowExpr:
_fingerprintString(ctx, "RowExpr");
_fingerprintRowExpr(ctx, obj, parent, field_name, depth);
break;
case T_RowCompareExpr:
_fingerprintString(ctx, "RowCompareExpr");
_fingerprintRowCompareExpr(ctx, obj, parent, field_name, depth);
break;
case T_CoalesceExpr:
_fingerprintString(ctx, "CoalesceExpr");
_fingerprintCoalesceExpr(ctx, obj, parent, field_name, depth);
break;
case T_MinMaxExpr:
_fingerprintString(ctx, "MinMaxExpr");
_fingerprintMinMaxExpr(ctx, obj, parent, field_name, depth);
break;
case T_SQLValueFunction:
_fingerprintString(ctx, "SQLValueFunction");
_fingerprintSQLValueFunction(ctx, obj, parent, field_name, depth);
break;
case T_XmlExpr:
_fingerprintString(ctx, "XmlExpr");
_fingerprintXmlExpr(ctx, obj, parent, field_name, depth);
break;
case T_JsonFormat:
_fingerprintString(ctx, "JsonFormat");
_fingerprintJsonFormat(ctx, obj, parent, field_name, depth);
break;
case T_JsonReturning:
_fingerprintString(ctx, "JsonReturning");
_fingerprintJsonReturning(ctx, obj, parent, field_name, depth);
break;
case T_JsonValueExpr:
_fingerprintString(ctx, "JsonValueExpr");
_fingerprintJsonValueExpr(ctx, obj, parent, field_name, depth);
break;
case T_JsonConstructorExpr:
_fingerprintString(ctx, "JsonConstructorExpr");
_fingerprintJsonConstructorExpr(ctx, obj, parent, field_name, depth);
break;
case T_JsonIsPredicate:
_fingerprintString(ctx, "JsonIsPredicate");
_fingerprintJsonIsPredicate(ctx, obj, parent, field_name, depth);
break;
case T_JsonBehavior:
_fingerprintString(ctx, "JsonBehavior");
_fingerprintJsonBehavior(ctx, obj, parent, field_name, depth);
break;
case T_JsonExpr:
_fingerprintString(ctx, "JsonExpr");
_fingerprintJsonExpr(ctx, obj, parent, field_name, depth);
break;
case T_JsonTablePath:
_fingerprintString(ctx, "JsonTablePath");
_fingerprintJsonTablePath(ctx, obj, parent, field_name, depth);
break;
case T_JsonTablePathScan:
_fingerprintString(ctx, "JsonTablePathScan");
_fingerprintJsonTablePathScan(ctx, obj, parent, field_name, depth);
break;
case T_JsonTableSiblingJoin:
_fingerprintString(ctx, "JsonTableSiblingJoin");
_fingerprintJsonTableSiblingJoin(ctx, obj, parent, field_name, depth);
break;
case T_NullTest:
_fingerprintString(ctx, "NullTest");
_fingerprintNullTest(ctx, obj, parent, field_name, depth);
break;
case T_BooleanTest:
_fingerprintString(ctx, "BooleanTest");
_fingerprintBooleanTest(ctx, obj, parent, field_name, depth);
break;
case T_MergeAction:
_fingerprintString(ctx, "MergeAction");
_fingerprintMergeAction(ctx, obj, parent, field_name, depth);
break;
case T_CoerceToDomain:
_fingerprintString(ctx, "CoerceToDomain");
_fingerprintCoerceToDomain(ctx, obj, parent, field_name, depth);
break;
case T_CoerceToDomainValue:
_fingerprintString(ctx, "CoerceToDomainValue");
_fingerprintCoerceToDomainValue(ctx, obj, parent, field_name, depth);
break;
case T_SetToDefault:
// Intentionally ignoring for fingerprinting
break;
case T_CurrentOfExpr:
_fingerprintString(ctx, "CurrentOfExpr");
_fingerprintCurrentOfExpr(ctx, obj, parent, field_name, depth);
break;
case T_NextValueExpr:
_fingerprintString(ctx, "NextValueExpr");
_fingerprintNextValueExpr(ctx, obj, parent, field_name, depth);
break;
case T_InferenceElem:
_fingerprintString(ctx, "InferenceElem");
_fingerprintInferenceElem(ctx, obj, parent, field_name, depth);
break;
case T_TargetEntry:
_fingerprintString(ctx, "TargetEntry");
_fingerprintTargetEntry(ctx, obj, parent, field_name, depth);
break;
case T_RangeTblRef:
_fingerprintString(ctx, "RangeTblRef");
_fingerprintRangeTblRef(ctx, obj, parent, field_name, depth);
break;
case T_JoinExpr:
_fingerprintString(ctx, "JoinExpr");
_fingerprintJoinExpr(ctx, obj, parent, field_name, depth);
break;
case T_FromExpr:
_fingerprintString(ctx, "FromExpr");
_fingerprintFromExpr(ctx, obj, parent, field_name, depth);
break;
case T_OnConflictExpr:
_fingerprintString(ctx, "OnConflictExpr");
_fingerprintOnConflictExpr(ctx, obj, parent, field_name, depth);
break;
case T_Query:
_fingerprintString(ctx, "Query");
_fingerprintQuery(ctx, obj, parent, field_name, depth);
break;
case T_TypeName:
_fingerprintString(ctx, "TypeName");
_fingerprintTypeName(ctx, obj, parent, field_name, depth);
break;
case T_ColumnRef:
_fingerprintString(ctx, "ColumnRef");
_fingerprintColumnRef(ctx, obj, parent, field_name, depth);
break;
case T_ParamRef:
// Intentionally ignoring for fingerprinting
break;
case T_A_Expr:
_fingerprintString(ctx, "A_Expr");
_fingerprintA_Expr(ctx, obj, parent, field_name, depth);
break;
case T_TypeCast:
if (!IsA(castNode(TypeCast, (void*) obj)->arg, A_Const) && !IsA(castNode(TypeCast, (void*) obj)->arg, ParamRef))
{
_fingerprintString(ctx, "TypeCast");
_fingerprintTypeCast(ctx, obj, parent, field_name, depth);
}
break;
case T_CollateClause:
_fingerprintString(ctx, "CollateClause");
_fingerprintCollateClause(ctx, obj, parent, field_name, depth);
break;
case T_RoleSpec:
_fingerprintString(ctx, "RoleSpec");
_fingerprintRoleSpec(ctx, obj, parent, field_name, depth);
break;
case T_FuncCall:
_fingerprintString(ctx, "FuncCall");
_fingerprintFuncCall(ctx, obj, parent, field_name, depth);
break;
case T_A_Star:
_fingerprintString(ctx, "A_Star");
_fingerprintA_Star(ctx, obj, parent, field_name, depth);
break;
case T_A_Indices:
_fingerprintString(ctx, "A_Indices");
_fingerprintA_Indices(ctx, obj, parent, field_name, depth);
break;
case T_A_Indirection:
_fingerprintString(ctx, "A_Indirection");
_fingerprintA_Indirection(ctx, obj, parent, field_name, depth);
break;
case T_A_ArrayExpr:
_fingerprintString(ctx, "A_ArrayExpr");
_fingerprintA_ArrayExpr(ctx, obj, parent, field_name, depth);
break;
case T_ResTarget:
_fingerprintString(ctx, "ResTarget");
_fingerprintResTarget(ctx, obj, parent, field_name, depth);
break;
case T_MultiAssignRef:
_fingerprintString(ctx, "MultiAssignRef");
_fingerprintMultiAssignRef(ctx, obj, parent, field_name, depth);
break;
case T_SortBy:
_fingerprintString(ctx, "SortBy");
_fingerprintSortBy(ctx, obj, parent, field_name, depth);
break;
case T_WindowDef:
_fingerprintString(ctx, "WindowDef");
_fingerprintWindowDef(ctx, obj, parent, field_name, depth);
break;
case T_RangeSubselect:
_fingerprintString(ctx, "RangeSubselect");
_fingerprintRangeSubselect(ctx, obj, parent, field_name, depth);
break;
case T_RangeFunction:
_fingerprintString(ctx, "RangeFunction");
_fingerprintRangeFunction(ctx, obj, parent, field_name, depth);
break;
case T_RangeTableFunc:
_fingerprintString(ctx, "RangeTableFunc");
_fingerprintRangeTableFunc(ctx, obj, parent, field_name, depth);
break;
case T_RangeTableFuncCol:
_fingerprintString(ctx, "RangeTableFuncCol");
_fingerprintRangeTableFuncCol(ctx, obj, parent, field_name, depth);
break;
case T_RangeTableSample:
_fingerprintString(ctx, "RangeTableSample");
_fingerprintRangeTableSample(ctx, obj, parent, field_name, depth);
break;
case T_ColumnDef:
_fingerprintString(ctx, "ColumnDef");
_fingerprintColumnDef(ctx, obj, parent, field_name, depth);
break;
case T_TableLikeClause:
_fingerprintString(ctx, "TableLikeClause");
_fingerprintTableLikeClause(ctx, obj, parent, field_name, depth);
break;
case T_IndexElem:
_fingerprintString(ctx, "IndexElem");
_fingerprintIndexElem(ctx, obj, parent, field_name, depth);
break;
case T_DefElem:
_fingerprintString(ctx, "DefElem");
_fingerprintDefElem(ctx, obj, parent, field_name, depth);
break;
case T_LockingClause:
_fingerprintString(ctx, "LockingClause");
_fingerprintLockingClause(ctx, obj, parent, field_name, depth);
break;
case T_XmlSerialize:
_fingerprintString(ctx, "XmlSerialize");
_fingerprintXmlSerialize(ctx, obj, parent, field_name, depth);
break;
case T_PartitionElem:
_fingerprintString(ctx, "PartitionElem");
_fingerprintPartitionElem(ctx, obj, parent, field_name, depth);
break;
case T_PartitionSpec:
_fingerprintString(ctx, "PartitionSpec");
_fingerprintPartitionSpec(ctx, obj, parent, field_name, depth);
break;
case T_PartitionBoundSpec:
_fingerprintString(ctx, "PartitionBoundSpec");
_fingerprintPartitionBoundSpec(ctx, obj, parent, field_name, depth);
break;
case T_PartitionRangeDatum:
_fingerprintString(ctx, "PartitionRangeDatum");
_fingerprintPartitionRangeDatum(ctx, obj, parent, field_name, depth);
break;
case T_SinglePartitionSpec:
_fingerprintString(ctx, "SinglePartitionSpec");
_fingerprintSinglePartitionSpec(ctx, obj, parent, field_name, depth);
break;
case T_PartitionCmd:
_fingerprintString(ctx, "PartitionCmd");
_fingerprintPartitionCmd(ctx, obj, parent, field_name, depth);
break;
case T_RangeTblEntry:
_fingerprintString(ctx, "RangeTblEntry");
_fingerprintRangeTblEntry(ctx, obj, parent, field_name, depth);
break;
case T_RTEPermissionInfo:
_fingerprintString(ctx, "RTEPermissionInfo");
_fingerprintRTEPermissionInfo(ctx, obj, parent, field_name, depth);
break;
case T_RangeTblFunction:
_fingerprintString(ctx, "RangeTblFunction");
_fingerprintRangeTblFunction(ctx, obj, parent, field_name, depth);
break;
case T_TableSampleClause:
_fingerprintString(ctx, "TableSampleClause");
_fingerprintTableSampleClause(ctx, obj, parent, field_name, depth);
break;
case T_WithCheckOption:
_fingerprintString(ctx, "WithCheckOption");
_fingerprintWithCheckOption(ctx, obj, parent, field_name, depth);
break;
case T_SortGroupClause:
_fingerprintString(ctx, "SortGroupClause");
_fingerprintSortGroupClause(ctx, obj, parent, field_name, depth);
break;
case T_GroupingSet:
_fingerprintString(ctx, "GroupingSet");
_fingerprintGroupingSet(ctx, obj, parent, field_name, depth);
break;
case T_WindowClause:
_fingerprintString(ctx, "WindowClause");
_fingerprintWindowClause(ctx, obj, parent, field_name, depth);
break;
case T_RowMarkClause:
_fingerprintString(ctx, "RowMarkClause");
_fingerprintRowMarkClause(ctx, obj, parent, field_name, depth);
break;
case T_WithClause:
_fingerprintString(ctx, "WithClause");
_fingerprintWithClause(ctx, obj, parent, field_name, depth);
break;
case T_InferClause:
_fingerprintString(ctx, "InferClause");
_fingerprintInferClause(ctx, obj, parent, field_name, depth);
break;
case T_OnConflictClause:
_fingerprintString(ctx, "OnConflictClause");
_fingerprintOnConflictClause(ctx, obj, parent, field_name, depth);
break;
case T_CTESearchClause:
_fingerprintString(ctx, "CTESearchClause");
_fingerprintCTESearchClause(ctx, obj, parent, field_name, depth);
break;
case T_CTECycleClause:
_fingerprintString(ctx, "CTECycleClause");
_fingerprintCTECycleClause(ctx, obj, parent, field_name, depth);
break;
case T_CommonTableExpr:
_fingerprintString(ctx, "CommonTableExpr");
_fingerprintCommonTableExpr(ctx, obj, parent, field_name, depth);
break;
case T_MergeWhenClause:
_fingerprintString(ctx, "MergeWhenClause");
_fingerprintMergeWhenClause(ctx, obj, parent, field_name, depth);
break;
case T_TriggerTransition:
_fingerprintString(ctx, "TriggerTransition");
_fingerprintTriggerTransition(ctx, obj, parent, field_name, depth);
break;
case T_JsonOutput:
_fingerprintString(ctx, "JsonOutput");
_fingerprintJsonOutput(ctx, obj, parent, field_name, depth);
break;
case T_JsonArgument:
_fingerprintString(ctx, "JsonArgument");
_fingerprintJsonArgument(ctx, obj, parent, field_name, depth);
break;
case T_JsonFuncExpr:
_fingerprintString(ctx, "JsonFuncExpr");
_fingerprintJsonFuncExpr(ctx, obj, parent, field_name, depth);
break;
case T_JsonTablePathSpec:
_fingerprintString(ctx, "JsonTablePathSpec");
_fingerprintJsonTablePathSpec(ctx, obj, parent, field_name, depth);
break;
case T_JsonTable:
_fingerprintString(ctx, "JsonTable");
_fingerprintJsonTable(ctx, obj, parent, field_name, depth);
break;
case T_JsonTableColumn:
_fingerprintString(ctx, "JsonTableColumn");
_fingerprintJsonTableColumn(ctx, obj, parent, field_name, depth);
break;
case T_JsonKeyValue:
_fingerprintString(ctx, "JsonKeyValue");
_fingerprintJsonKeyValue(ctx, obj, parent, field_name, depth);
break;
case T_JsonParseExpr:
_fingerprintString(ctx, "JsonParseExpr");
_fingerprintJsonParseExpr(ctx, obj, parent, field_name, depth);
break;
case T_JsonScalarExpr:
_fingerprintString(ctx, "JsonScalarExpr");
_fingerprintJsonScalarExpr(ctx, obj, parent, field_name, depth);
break;
case T_JsonSerializeExpr:
_fingerprintString(ctx, "JsonSerializeExpr");
_fingerprintJsonSerializeExpr(ctx, obj, parent, field_name, depth);
break;
case T_JsonObjectConstructor:
_fingerprintString(ctx, "JsonObjectConstructor");
_fingerprintJsonObjectConstructor(ctx, obj, parent, field_name, depth);
break;
case T_JsonArrayConstructor:
_fingerprintString(ctx, "JsonArrayConstructor");
_fingerprintJsonArrayConstructor(ctx, obj, parent, field_name, depth);
break;
case T_JsonArrayQueryConstructor:
_fingerprintString(ctx, "JsonArrayQueryConstructor");
_fingerprintJsonArrayQueryConstructor(ctx, obj, parent, field_name, depth);
break;
case T_JsonAggConstructor:
_fingerprintString(ctx, "JsonAggConstructor");
_fingerprintJsonAggConstructor(ctx, obj, parent, field_name, depth);
break;
case T_JsonObjectAgg:
_fingerprintString(ctx, "JsonObjectAgg");
_fingerprintJsonObjectAgg(ctx, obj, parent, field_name, depth);
break;
case T_JsonArrayAgg:
_fingerprintString(ctx, "JsonArrayAgg");
_fingerprintJsonArrayAgg(ctx, obj, parent, field_name, depth);
break;
case T_RawStmt:
_fingerprintString(ctx, "RawStmt");
_fingerprintRawStmt(ctx, obj, parent, field_name, depth);
break;
case T_InsertStmt:
_fingerprintString(ctx, "InsertStmt");
_fingerprintInsertStmt(ctx, obj, parent, field_name, depth);
break;
case T_DeleteStmt:
_fingerprintString(ctx, "DeleteStmt");
_fingerprintDeleteStmt(ctx, obj, parent, field_name, depth);
break;
case T_UpdateStmt:
_fingerprintString(ctx, "UpdateStmt");
_fingerprintUpdateStmt(ctx, obj, parent, field_name, depth);
break;
case T_MergeStmt:
_fingerprintString(ctx, "MergeStmt");
_fingerprintMergeStmt(ctx, obj, parent, field_name, depth);
break;
case T_SelectStmt:
_fingerprintString(ctx, "SelectStmt");
_fingerprintSelectStmt(ctx, obj, parent, field_name, depth);
break;
case T_SetOperationStmt:
_fingerprintString(ctx, "SetOperationStmt");
_fingerprintSetOperationStmt(ctx, obj, parent, field_name, depth);
break;
case T_ReturnStmt:
_fingerprintString(ctx, "ReturnStmt");
_fingerprintReturnStmt(ctx, obj, parent, field_name, depth);
break;
case T_PLAssignStmt:
_fingerprintString(ctx, "PLAssignStmt");
_fingerprintPLAssignStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateSchemaStmt:
_fingerprintString(ctx, "CreateSchemaStmt");
_fingerprintCreateSchemaStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterTableStmt:
_fingerprintString(ctx, "AlterTableStmt");
_fingerprintAlterTableStmt(ctx, obj, parent, field_name, depth);
break;
case T_ReplicaIdentityStmt:
_fingerprintString(ctx, "ReplicaIdentityStmt");
_fingerprintReplicaIdentityStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterTableCmd:
_fingerprintString(ctx, "AlterTableCmd");
_fingerprintAlterTableCmd(ctx, obj, parent, field_name, depth);
break;
case T_AlterCollationStmt:
_fingerprintString(ctx, "AlterCollationStmt");
_fingerprintAlterCollationStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterDomainStmt:
_fingerprintString(ctx, "AlterDomainStmt");
_fingerprintAlterDomainStmt(ctx, obj, parent, field_name, depth);
break;
case T_GrantStmt:
_fingerprintString(ctx, "GrantStmt");
_fingerprintGrantStmt(ctx, obj, parent, field_name, depth);
break;
case T_ObjectWithArgs:
_fingerprintString(ctx, "ObjectWithArgs");
_fingerprintObjectWithArgs(ctx, obj, parent, field_name, depth);
break;
case T_AccessPriv:
_fingerprintString(ctx, "AccessPriv");
_fingerprintAccessPriv(ctx, obj, parent, field_name, depth);
break;
case T_GrantRoleStmt:
_fingerprintString(ctx, "GrantRoleStmt");
_fingerprintGrantRoleStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterDefaultPrivilegesStmt:
_fingerprintString(ctx, "AlterDefaultPrivilegesStmt");
_fingerprintAlterDefaultPrivilegesStmt(ctx, obj, parent, field_name, depth);
break;
case T_CopyStmt:
_fingerprintString(ctx, "CopyStmt");
_fingerprintCopyStmt(ctx, obj, parent, field_name, depth);
break;
case T_VariableSetStmt:
_fingerprintString(ctx, "VariableSetStmt");
_fingerprintVariableSetStmt(ctx, obj, parent, field_name, depth);
break;
case T_VariableShowStmt:
_fingerprintString(ctx, "VariableShowStmt");
_fingerprintVariableShowStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateStmt:
_fingerprintString(ctx, "CreateStmt");
_fingerprintCreateStmt(ctx, obj, parent, field_name, depth);
break;
case T_Constraint:
_fingerprintString(ctx, "Constraint");
_fingerprintConstraint(ctx, obj, parent, field_name, depth);
break;
case T_CreateTableSpaceStmt:
_fingerprintString(ctx, "CreateTableSpaceStmt");
_fingerprintCreateTableSpaceStmt(ctx, obj, parent, field_name, depth);
break;
case T_DropTableSpaceStmt:
_fingerprintString(ctx, "DropTableSpaceStmt");
_fingerprintDropTableSpaceStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterTableSpaceOptionsStmt:
_fingerprintString(ctx, "AlterTableSpaceOptionsStmt");
_fingerprintAlterTableSpaceOptionsStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterTableMoveAllStmt:
_fingerprintString(ctx, "AlterTableMoveAllStmt");
_fingerprintAlterTableMoveAllStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateExtensionStmt:
_fingerprintString(ctx, "CreateExtensionStmt");
_fingerprintCreateExtensionStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterExtensionStmt:
_fingerprintString(ctx, "AlterExtensionStmt");
_fingerprintAlterExtensionStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterExtensionContentsStmt:
_fingerprintString(ctx, "AlterExtensionContentsStmt");
_fingerprintAlterExtensionContentsStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateFdwStmt:
_fingerprintString(ctx, "CreateFdwStmt");
_fingerprintCreateFdwStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterFdwStmt:
_fingerprintString(ctx, "AlterFdwStmt");
_fingerprintAlterFdwStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateForeignServerStmt:
_fingerprintString(ctx, "CreateForeignServerStmt");
_fingerprintCreateForeignServerStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterForeignServerStmt:
_fingerprintString(ctx, "AlterForeignServerStmt");
_fingerprintAlterForeignServerStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateForeignTableStmt:
_fingerprintString(ctx, "CreateForeignTableStmt");
_fingerprintCreateForeignTableStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateUserMappingStmt:
_fingerprintString(ctx, "CreateUserMappingStmt");
_fingerprintCreateUserMappingStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterUserMappingStmt:
_fingerprintString(ctx, "AlterUserMappingStmt");
_fingerprintAlterUserMappingStmt(ctx, obj, parent, field_name, depth);
break;
case T_DropUserMappingStmt:
_fingerprintString(ctx, "DropUserMappingStmt");
_fingerprintDropUserMappingStmt(ctx, obj, parent, field_name, depth);
break;
case T_ImportForeignSchemaStmt:
_fingerprintString(ctx, "ImportForeignSchemaStmt");
_fingerprintImportForeignSchemaStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreatePolicyStmt:
_fingerprintString(ctx, "CreatePolicyStmt");
_fingerprintCreatePolicyStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterPolicyStmt:
_fingerprintString(ctx, "AlterPolicyStmt");
_fingerprintAlterPolicyStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateAmStmt:
_fingerprintString(ctx, "CreateAmStmt");
_fingerprintCreateAmStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateTrigStmt:
_fingerprintString(ctx, "CreateTrigStmt");
_fingerprintCreateTrigStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateEventTrigStmt:
_fingerprintString(ctx, "CreateEventTrigStmt");
_fingerprintCreateEventTrigStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterEventTrigStmt:
_fingerprintString(ctx, "AlterEventTrigStmt");
_fingerprintAlterEventTrigStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreatePLangStmt:
_fingerprintString(ctx, "CreatePLangStmt");
_fingerprintCreatePLangStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateRoleStmt:
_fingerprintString(ctx, "CreateRoleStmt");
_fingerprintCreateRoleStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterRoleStmt:
_fingerprintString(ctx, "AlterRoleStmt");
_fingerprintAlterRoleStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterRoleSetStmt:
_fingerprintString(ctx, "AlterRoleSetStmt");
_fingerprintAlterRoleSetStmt(ctx, obj, parent, field_name, depth);
break;
case T_DropRoleStmt:
_fingerprintString(ctx, "DropRoleStmt");
_fingerprintDropRoleStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateSeqStmt:
_fingerprintString(ctx, "CreateSeqStmt");
_fingerprintCreateSeqStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterSeqStmt:
_fingerprintString(ctx, "AlterSeqStmt");
_fingerprintAlterSeqStmt(ctx, obj, parent, field_name, depth);
break;
case T_DefineStmt:
_fingerprintString(ctx, "DefineStmt");
_fingerprintDefineStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateDomainStmt:
_fingerprintString(ctx, "CreateDomainStmt");
_fingerprintCreateDomainStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateOpClassStmt:
_fingerprintString(ctx, "CreateOpClassStmt");
_fingerprintCreateOpClassStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateOpClassItem:
_fingerprintString(ctx, "CreateOpClassItem");
_fingerprintCreateOpClassItem(ctx, obj, parent, field_name, depth);
break;
case T_CreateOpFamilyStmt:
_fingerprintString(ctx, "CreateOpFamilyStmt");
_fingerprintCreateOpFamilyStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterOpFamilyStmt:
_fingerprintString(ctx, "AlterOpFamilyStmt");
_fingerprintAlterOpFamilyStmt(ctx, obj, parent, field_name, depth);
break;
case T_DropStmt:
_fingerprintString(ctx, "DropStmt");
_fingerprintDropStmt(ctx, obj, parent, field_name, depth);
break;
case T_TruncateStmt:
_fingerprintString(ctx, "TruncateStmt");
_fingerprintTruncateStmt(ctx, obj, parent, field_name, depth);
break;
case T_CommentStmt:
_fingerprintString(ctx, "CommentStmt");
_fingerprintCommentStmt(ctx, obj, parent, field_name, depth);
break;
case T_SecLabelStmt:
_fingerprintString(ctx, "SecLabelStmt");
_fingerprintSecLabelStmt(ctx, obj, parent, field_name, depth);
break;
case T_DeclareCursorStmt:
_fingerprintString(ctx, "DeclareCursorStmt");
_fingerprintDeclareCursorStmt(ctx, obj, parent, field_name, depth);
break;
case T_ClosePortalStmt:
_fingerprintString(ctx, "ClosePortalStmt");
_fingerprintClosePortalStmt(ctx, obj, parent, field_name, depth);
break;
case T_FetchStmt:
_fingerprintString(ctx, "FetchStmt");
_fingerprintFetchStmt(ctx, obj, parent, field_name, depth);
break;
case T_IndexStmt:
_fingerprintString(ctx, "IndexStmt");
_fingerprintIndexStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateStatsStmt:
_fingerprintString(ctx, "CreateStatsStmt");
_fingerprintCreateStatsStmt(ctx, obj, parent, field_name, depth);
break;
case T_StatsElem:
_fingerprintString(ctx, "StatsElem");
_fingerprintStatsElem(ctx, obj, parent, field_name, depth);
break;
case T_AlterStatsStmt:
_fingerprintString(ctx, "AlterStatsStmt");
_fingerprintAlterStatsStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateFunctionStmt:
_fingerprintString(ctx, "CreateFunctionStmt");
_fingerprintCreateFunctionStmt(ctx, obj, parent, field_name, depth);
break;
case T_FunctionParameter:
_fingerprintString(ctx, "FunctionParameter");
_fingerprintFunctionParameter(ctx, obj, parent, field_name, depth);
break;
case T_AlterFunctionStmt:
_fingerprintString(ctx, "AlterFunctionStmt");
_fingerprintAlterFunctionStmt(ctx, obj, parent, field_name, depth);
break;
case T_DoStmt:
_fingerprintString(ctx, "DoStmt");
_fingerprintDoStmt(ctx, obj, parent, field_name, depth);
break;
case T_InlineCodeBlock:
_fingerprintString(ctx, "InlineCodeBlock");
_fingerprintInlineCodeBlock(ctx, obj, parent, field_name, depth);
break;
case T_CallStmt:
_fingerprintString(ctx, "CallStmt");
_fingerprintCallStmt(ctx, obj, parent, field_name, depth);
break;
case T_CallContext:
_fingerprintString(ctx, "CallContext");
_fingerprintCallContext(ctx, obj, parent, field_name, depth);
break;
case T_RenameStmt:
_fingerprintString(ctx, "RenameStmt");
_fingerprintRenameStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterObjectDependsStmt:
_fingerprintString(ctx, "AlterObjectDependsStmt");
_fingerprintAlterObjectDependsStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterObjectSchemaStmt:
_fingerprintString(ctx, "AlterObjectSchemaStmt");
_fingerprintAlterObjectSchemaStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterOwnerStmt:
_fingerprintString(ctx, "AlterOwnerStmt");
_fingerprintAlterOwnerStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterOperatorStmt:
_fingerprintString(ctx, "AlterOperatorStmt");
_fingerprintAlterOperatorStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterTypeStmt:
_fingerprintString(ctx, "AlterTypeStmt");
_fingerprintAlterTypeStmt(ctx, obj, parent, field_name, depth);
break;
case T_RuleStmt:
_fingerprintString(ctx, "RuleStmt");
_fingerprintRuleStmt(ctx, obj, parent, field_name, depth);
break;
case T_NotifyStmt:
_fingerprintString(ctx, "NotifyStmt");
_fingerprintNotifyStmt(ctx, obj, parent, field_name, depth);
break;
case T_ListenStmt:
_fingerprintString(ctx, "ListenStmt");
_fingerprintListenStmt(ctx, obj, parent, field_name, depth);
break;
case T_UnlistenStmt:
_fingerprintString(ctx, "UnlistenStmt");
_fingerprintUnlistenStmt(ctx, obj, parent, field_name, depth);
break;
case T_TransactionStmt:
_fingerprintString(ctx, "TransactionStmt");
_fingerprintTransactionStmt(ctx, obj, parent, field_name, depth);
break;
case T_CompositeTypeStmt:
_fingerprintString(ctx, "CompositeTypeStmt");
_fingerprintCompositeTypeStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateEnumStmt:
_fingerprintString(ctx, "CreateEnumStmt");
_fingerprintCreateEnumStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateRangeStmt:
_fingerprintString(ctx, "CreateRangeStmt");
_fingerprintCreateRangeStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterEnumStmt:
_fingerprintString(ctx, "AlterEnumStmt");
_fingerprintAlterEnumStmt(ctx, obj, parent, field_name, depth);
break;
case T_ViewStmt:
_fingerprintString(ctx, "ViewStmt");
_fingerprintViewStmt(ctx, obj, parent, field_name, depth);
break;
case T_LoadStmt:
_fingerprintString(ctx, "LoadStmt");
_fingerprintLoadStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreatedbStmt:
_fingerprintString(ctx, "CreatedbStmt");
_fingerprintCreatedbStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterDatabaseStmt:
_fingerprintString(ctx, "AlterDatabaseStmt");
_fingerprintAlterDatabaseStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterDatabaseRefreshCollStmt:
_fingerprintString(ctx, "AlterDatabaseRefreshCollStmt");
_fingerprintAlterDatabaseRefreshCollStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterDatabaseSetStmt:
_fingerprintString(ctx, "AlterDatabaseSetStmt");
_fingerprintAlterDatabaseSetStmt(ctx, obj, parent, field_name, depth);
break;
case T_DropdbStmt:
_fingerprintString(ctx, "DropdbStmt");
_fingerprintDropdbStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterSystemStmt:
_fingerprintString(ctx, "AlterSystemStmt");
_fingerprintAlterSystemStmt(ctx, obj, parent, field_name, depth);
break;
case T_ClusterStmt:
_fingerprintString(ctx, "ClusterStmt");
_fingerprintClusterStmt(ctx, obj, parent, field_name, depth);
break;
case T_VacuumStmt:
_fingerprintString(ctx, "VacuumStmt");
_fingerprintVacuumStmt(ctx, obj, parent, field_name, depth);
break;
case T_VacuumRelation:
_fingerprintString(ctx, "VacuumRelation");
_fingerprintVacuumRelation(ctx, obj, parent, field_name, depth);
break;
case T_ExplainStmt:
_fingerprintString(ctx, "ExplainStmt");
_fingerprintExplainStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateTableAsStmt:
_fingerprintString(ctx, "CreateTableAsStmt");
_fingerprintCreateTableAsStmt(ctx, obj, parent, field_name, depth);
break;
case T_RefreshMatViewStmt:
_fingerprintString(ctx, "RefreshMatViewStmt");
_fingerprintRefreshMatViewStmt(ctx, obj, parent, field_name, depth);
break;
case T_CheckPointStmt:
_fingerprintString(ctx, "CheckPointStmt");
_fingerprintCheckPointStmt(ctx, obj, parent, field_name, depth);
break;
case T_DiscardStmt:
_fingerprintString(ctx, "DiscardStmt");
_fingerprintDiscardStmt(ctx, obj, parent, field_name, depth);
break;
case T_LockStmt:
_fingerprintString(ctx, "LockStmt");
_fingerprintLockStmt(ctx, obj, parent, field_name, depth);
break;
case T_ConstraintsSetStmt:
_fingerprintString(ctx, "ConstraintsSetStmt");
_fingerprintConstraintsSetStmt(ctx, obj, parent, field_name, depth);
break;
case T_ReindexStmt:
_fingerprintString(ctx, "ReindexStmt");
_fingerprintReindexStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateConversionStmt:
_fingerprintString(ctx, "CreateConversionStmt");
_fingerprintCreateConversionStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateCastStmt:
_fingerprintString(ctx, "CreateCastStmt");
_fingerprintCreateCastStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateTransformStmt:
_fingerprintString(ctx, "CreateTransformStmt");
_fingerprintCreateTransformStmt(ctx, obj, parent, field_name, depth);
break;
case T_PrepareStmt:
_fingerprintString(ctx, "PrepareStmt");
_fingerprintPrepareStmt(ctx, obj, parent, field_name, depth);
break;
case T_ExecuteStmt:
_fingerprintString(ctx, "ExecuteStmt");
_fingerprintExecuteStmt(ctx, obj, parent, field_name, depth);
break;
case T_DeallocateStmt:
_fingerprintString(ctx, "DeallocateStmt");
_fingerprintDeallocateStmt(ctx, obj, parent, field_name, depth);
break;
case T_DropOwnedStmt:
_fingerprintString(ctx, "DropOwnedStmt");
_fingerprintDropOwnedStmt(ctx, obj, parent, field_name, depth);
break;
case T_ReassignOwnedStmt:
_fingerprintString(ctx, "ReassignOwnedStmt");
_fingerprintReassignOwnedStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterTSDictionaryStmt:
_fingerprintString(ctx, "AlterTSDictionaryStmt");
_fingerprintAlterTSDictionaryStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterTSConfigurationStmt:
_fingerprintString(ctx, "AlterTSConfigurationStmt");
_fingerprintAlterTSConfigurationStmt(ctx, obj, parent, field_name, depth);
break;
case T_PublicationTable:
_fingerprintString(ctx, "PublicationTable");
_fingerprintPublicationTable(ctx, obj, parent, field_name, depth);
break;
case T_PublicationObjSpec:
_fingerprintString(ctx, "PublicationObjSpec");
_fingerprintPublicationObjSpec(ctx, obj, parent, field_name, depth);
break;
case T_CreatePublicationStmt:
_fingerprintString(ctx, "CreatePublicationStmt");
_fingerprintCreatePublicationStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterPublicationStmt:
_fingerprintString(ctx, "AlterPublicationStmt");
_fingerprintAlterPublicationStmt(ctx, obj, parent, field_name, depth);
break;
case T_CreateSubscriptionStmt:
_fingerprintString(ctx, "CreateSubscriptionStmt");
_fingerprintCreateSubscriptionStmt(ctx, obj, parent, field_name, depth);
break;
case T_AlterSubscriptionStmt:
_fingerprintString(ctx, "AlterSubscriptionStmt");
_fingerprintAlterSubscriptionStmt(ctx, obj, parent, field_name, depth);
break;
case T_DropSubscriptionStmt:
_fingerprintString(ctx, "DropSubscriptionStmt");
_fingerprintDropSubscriptionStmt(ctx, obj, parent, field_name, depth);
break;
| 412 | 0.874662 | 1 | 0.874662 | game-dev | MEDIA | 0.345796 | game-dev | 0.862752 | 1 | 0.862752 |
OpenRakis/Spice86 | 2,454 | src/Spice86.Core/LinkedListExtensions.cs | ο»Ώnamespace Spice86.Core;
public static class LinkedListExtensions
{
/// <summary>
/// Replaces an existing linked list node with zero or more new nodes.
/// </summary>
/// <typeparam name="T">Type of list item.</typeparam>
/// <param name="list">Linked list instance.</param>
/// <param name="originalItem">Item to replace.</param>
/// <param name="newItems">Values to insert in place of the original item.</param>
public static void Replace<T>(this LinkedList<T> list, T originalItem, T[] newItems)
{
if (list == null) {
throw new ArgumentNullException(nameof(list));
}
if (newItems == null) {
throw new ArgumentNullException(nameof(newItems));
}
LinkedListNode<T>? originalNode = list.Find(originalItem);
if (originalNode == null) {
throw new ArgumentException("Original item not found.");
}
if (originalNode.Previous == null)
{
list.RemoveFirst();
for (int i = newItems.Length - 1; i >= 0; i--) {
list.AddFirst(newItems[i]);
}
}
else
{
LinkedListNode<T> previous = originalNode.Previous;
list.Remove(originalNode);
for (int i = newItems.Length - 1; i >= 0; i--) {
list.AddAfter(previous, newItems[i]);
}
}
}
/// <summary>
/// Replaces an existing linked list node with a new node.
/// </summary>
/// <typeparam name="T">Type of list item.</typeparam>
/// <param name="list">Linked list instance.</param>
/// <param name="originalItem">Item to replace.</param>
/// <param name="newItem">New item to replace the original with.</param>
public static void Replace<T>(this LinkedList<T> list, T originalItem, T newItem) {
if (list == null) {
throw new ArgumentNullException(nameof(list));
}
LinkedListNode<T>? originalNode = list.Find(originalItem);
if (originalNode == null) {
throw new ArgumentException("Original item not found.");
}
if (originalNode.Previous == null)
{
list.RemoveFirst();
list.AddFirst(newItem);
}
else
{
LinkedListNode<T> previous = originalNode.Previous;
list.Remove(originalNode);
list.AddAfter(previous, newItem);
}
}
}
| 412 | 0.682544 | 1 | 0.682544 | game-dev | MEDIA | 0.358715 | game-dev | 0.882311 | 1 | 0.882311 |
HearthSim/HSTracker | 1,134 | HSTracker/Hearthstone/CounterSystem/NumericCounter.swift | //
// NumericCounter.swift
// HSTracker
//
// Created by Francisco Moraes on 10/22/24.
// Copyright Β© 2024 Benjamin Michotte. All rights reserved.
//
import Foundation
// Assuming BaseCounter is already translated as shown earlier
class NumericCounter: BaseCounter {
private var _counter: Int = 0
var counter: Int {
get {
return _counter
}
set {
if _counter != newValue {
_counter = newValue
onCounterChanged()
onPropertyChanged()
}
}
}
required init(controlledByPlayer: Bool, game: Game) {
super.init(controlledByPlayer: controlledByPlayer, game: game)
self.counter = 0
}
override func valueToShow() -> String {
return String(counter)
}
var lastEntityToCount: Entity?
func discountIfCantPlay(tag: GameTag, value: Int, entity: Entity) -> Bool {
if lastEntityToCount == nil || entity.id != lastEntityToCount?.id || tag != .cant_play || value <= 0 {
return false
}
counter -= 1
return true
}
}
| 412 | 0.882952 | 1 | 0.882952 | game-dev | MEDIA | 0.895063 | game-dev | 0.868135 | 1 | 0.868135 |
Wurst-Imperium/Wurst7 | 2,599 | src/main/java/net/wurstclient/mixin/ChatScreenMixin.java | /*
* Copyright (c) 2014-2025 Wurst-Imperium and contributors.
*
* This source code is subject to the terms of the GNU General Public
* License, version 3. If a copy of the GPL was not distributed with this
* file, You can obtain one at: https://www.gnu.org/licenses/gpl-3.0.txt
*/
package net.wurstclient.mixin;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import net.minecraft.client.gui.screen.ChatScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.text.Text;
import net.wurstclient.WurstClient;
import net.wurstclient.event.EventManager;
import net.wurstclient.events.ChatOutputListener.ChatOutputEvent;
@Mixin(ChatScreen.class)
public abstract class ChatScreenMixin extends Screen
{
@Shadow
protected TextFieldWidget chatField;
private ChatScreenMixin(WurstClient wurst, Text title)
{
super(title);
}
@Inject(at = @At("TAIL"), method = "init()V")
protected void onInit(CallbackInfo ci)
{
if(WurstClient.INSTANCE.getHax().infiniChatHack.isEnabled())
chatField.setMaxLength(Integer.MAX_VALUE);
}
@Inject(at = @At("HEAD"),
method = "sendMessage(Ljava/lang/String;Z)V",
cancellable = true)
public void onSendMessage(String message, boolean addToHistory,
CallbackInfo ci)
{
// Ignore empty messages just like vanilla
if((message = normalize(message)).isEmpty())
return;
// Create and fire the chat output event
ChatOutputEvent event = new ChatOutputEvent(message);
EventManager.fire(event);
// If the event hasn't been modified or cancelled,
// let the vanilla method handle the message
boolean cancelled = event.isCancelled();
if(!cancelled && !event.isModified())
return;
// Otherwise, cancel the vanilla method and handle the message here
ci.cancel();
// Add the message to history, even if it was cancelled
// Otherwise the up/down arrows won't work correctly
String newMessage = event.getMessage();
if(addToHistory)
client.inGameHud.getChatHud().addToMessageHistory(newMessage);
// If the event isn't cancelled, send the modified message
if(!cancelled)
if(newMessage.startsWith("/"))
client.player.networkHandler
.sendChatCommand(newMessage.substring(1));
else
client.player.networkHandler.sendChatMessage(newMessage);
}
@Shadow
public abstract String normalize(String chatText);
}
| 412 | 0.796783 | 1 | 0.796783 | game-dev | MEDIA | 0.699335 | game-dev | 0.929596 | 1 | 0.929596 |
HomoMC/Beast | 1,949 | patches/server/0115-perf-avoid-double-I-O-operation-on-player-file.patch | From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Softik Lord <dimap9986@gmail.com>
Date: Thu, 14 Jul 2022 06:08:45 +0500
Subject: [PATCH] perf: avoid double I/O operation on player file
Credits to Akarin: https://github.com/Akarin-project/Akarin/blob/279a2b23ffd5b71f067638b8170f3f81aa0a4298/patches/server/0007-Avoid-double-I-O-operation-on-load-player-file.patch
diff --git a/src/main/java/net/minecraft/server/WorldNBTStorage.java b/src/main/java/net/minecraft/server/WorldNBTStorage.java
index 691d511bf7ed8f9787146bd0d7c078f2a56d256f..8b113eac32c732d15cd5b146153c08cbf0e25fd6 100644
--- a/src/main/java/net/minecraft/server/WorldNBTStorage.java
+++ b/src/main/java/net/minecraft/server/WorldNBTStorage.java
@@ -168,7 +168,8 @@ public class WorldNBTStorage implements IDataManager, IPlayerFileData {
File file = new File(this.playerDir, entityhuman.bn() + ".dat");
// Spigot Start
boolean usingWrongFile = false;
- if ( org.bukkit.Bukkit.getOnlineMode() && !file.exists() ) // Paper - Check online mode first
+ boolean normalFile = file.exists() && file.isFile(); // Reaper - Ensures normal file
+ if ( org.bukkit.Bukkit.getOnlineMode() && !normalFile ) // Paper - Check online mode first // Reaper - Ensures normal file
{
file = new File( this.playerDir, UUID.nameUUIDFromBytes( ( "OfflinePlayer:" + entityhuman.getName() ).getBytes( "UTF-8" ) ).toString() + ".dat");
if ( file.exists() )
@@ -179,7 +180,7 @@ public class WorldNBTStorage implements IDataManager, IPlayerFileData {
}
// Spigot End
- if (file.exists() && file.isFile()) {
+ if (normalFile) { // Reaper - Avoid double I/O operation
nbttagcompound = NBTCompressedStreamTools.a((InputStream) (new FileInputStream(file)));
}
// Spigot Start
| 412 | 0.881339 | 1 | 0.881339 | game-dev | MEDIA | 0.931165 | game-dev | 0.763626 | 1 | 0.763626 |
magefree/mage | 2,218 | Mage.Sets/src/mage/cards/d/DeathsPresence.java | package mage.cards.d;
import mage.abilities.Ability;
import mage.abilities.common.DiesCreatureTriggeredAbility;
import mage.abilities.dynamicvalue.DynamicValue;
import mage.abilities.effects.Effect;
import mage.abilities.effects.common.counter.AddCountersTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.counters.CounterType;
import mage.filter.StaticFilters;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.target.TargetPermanent;
import java.util.UUID;
/**
*
* @author LevelX2
*/
public final class DeathsPresence extends CardImpl {
public DeathsPresence(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{5}{G}");
// Whenever a creature you control dies, put X +1/+1 counters on target creature you control, where X is the power of the creature that died.
Ability ability = new DiesCreatureTriggeredAbility(
new AddCountersTargetEffect(CounterType.P1P1.createInstance(), DeathsPresenceDiedPermanentPowerCount.instance),
false, StaticFilters.FILTER_CONTROLLED_CREATURE);
ability.addTarget(new TargetPermanent(StaticFilters.FILTER_PERMANENT_CREATURE_CONTROLLED));
this.addAbility(ability);
}
private DeathsPresence(final DeathsPresence card) {
super(card);
}
@Override
public DeathsPresence copy() {
return new DeathsPresence(this);
}
}
enum DeathsPresenceDiedPermanentPowerCount implements DynamicValue {
instance;
@Override
public int calculate(Game game, Ability sourceAbility, Effect effect) {
Permanent targetPermanent = (Permanent) effect.getValue("creatureDied");
if (targetPermanent != null) {
return targetPermanent.getPower().getValue();
}
return 0;
}
@Override
public DeathsPresenceDiedPermanentPowerCount copy() {
return DeathsPresenceDiedPermanentPowerCount.instance;
}
@Override
public String toString() {
return "X";
}
@Override
public String getMessage() {
return "the power of the creature that died";
}
}
| 412 | 0.985042 | 1 | 0.985042 | game-dev | MEDIA | 0.971641 | game-dev | 0.985503 | 1 | 0.985503 |
microsoft/Extensible-Storage-Engine | 65,795 | test/ese/src/blue/src/esetest/esetest/bounce/loadnarrow.cxx | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// Generated by generate_ese_stubs.pl
#include "ese_common.hxx"
#include "esetest_bounce.hxx"
#include <stdlib.h> // for rand()
#include <strsafe.h>
#include <windows.h>
// Do NOT edit this file! It can (and will) be overwritten.
JET_ERR
BounceJetCreateInstance(
JET_INSTANCE *pinstance,
const char * szInstanceName
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetCreateInstance ) ( JET_INSTANCE *pinstance, const char * szInstanceName );
static PFN_JetCreateInstance pfnJetCreateInstance = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetCreateInstance )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetCreateInstance = ( PFN_JetCreateInstance ) ( GetProcAddress( hEseDll, "JetCreateInstance" ) );
}
if ( NULL == hEseDll || NULL == pfnJetCreateInstance )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetCreateInstance", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetCreateInstance)( pinstance, szInstanceName );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetCreateInstance2(
JET_INSTANCE *pinstance,
const char * szInstanceName,
const char * szDisplayName,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetCreateInstance2 ) (
JET_INSTANCE *pinstance,
const char * szInstanceName,
const char * szDisplayName,
JET_GRBIT grbit );
static PFN_JetCreateInstance2 pfnJetCreateInstance2 = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetCreateInstance2 )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetCreateInstance2 = ( PFN_JetCreateInstance2 ) ( GetProcAddress( hEseDll, "JetCreateInstance2" ) );
}
if ( NULL == hEseDll || NULL == pfnJetCreateInstance2 )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetCreateInstance2", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetCreateInstance2)( pinstance, szInstanceName, szDisplayName, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetSetSystemParameter(
JET_INSTANCE *pinstance,
JET_SESID sesid,
unsigned long paramid,
__in_opt JET_API_PTR lParam,
__in_opt JET_PCSTR szParam
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetSetSystemParameter ) (
JET_INSTANCE *pinstance,
JET_SESID sesid,
unsigned long paramid,
__in_opt JET_API_PTR lParam,
__in_opt JET_PCSTR szParam );
static PFN_JetSetSystemParameter pfnJetSetSystemParameter = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetSetSystemParameter )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetSetSystemParameter = ( PFN_JetSetSystemParameter ) ( GetProcAddress( hEseDll, "JetSetSystemParameter" ) );
}
if ( NULL == hEseDll || NULL == pfnJetSetSystemParameter )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetSetSystemParameter", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetSetSystemParameter)( pinstance, sesid, paramid, lParam, szParam );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetBeginSession(
JET_INSTANCE instance,
JET_SESID *psesid,
__in_opt JET_PCSTR szUserName,
__in_opt JET_PCSTR szPassword
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetBeginSession ) (
JET_INSTANCE instance,
JET_SESID *psesid,
__in_opt JET_PCSTR szUserName,
__in_opt JET_PCSTR szPassword );
static PFN_JetBeginSession pfnJetBeginSession = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetBeginSession )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetBeginSession = ( PFN_JetBeginSession ) ( GetProcAddress( hEseDll, "JetBeginSession" ) );
}
if ( NULL == hEseDll || NULL == pfnJetBeginSession )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetBeginSession", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetBeginSession)( instance, psesid, szUserName, szPassword );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetCreateDatabase(
JET_SESID sesid,
const char *szFilename,
const char *szConnect,
JET_DBID *pdbid,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetCreateDatabase ) (
JET_SESID sesid,
const char *szFilename,
const char *szConnect,
JET_DBID *pdbid,
JET_GRBIT grbit );
static PFN_JetCreateDatabase pfnJetCreateDatabase = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetCreateDatabase )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetCreateDatabase = ( PFN_JetCreateDatabase ) ( GetProcAddress( hEseDll, "JetCreateDatabase" ) );
}
if ( NULL == hEseDll || NULL == pfnJetCreateDatabase )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetCreateDatabase", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetCreateDatabase)( sesid, szFilename, szConnect, pdbid, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetCreateDatabase2(
JET_SESID sesid,
const char *szFilename,
const unsigned long cpgDatabaseSizeMax,
JET_DBID *pdbid,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetCreateDatabase2 ) (
JET_SESID sesid,
const char *szFilename,
const unsigned long cpgDatabaseSizeMax,
JET_DBID *pdbid,
JET_GRBIT grbit );
static PFN_JetCreateDatabase2 pfnJetCreateDatabase2 = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetCreateDatabase2 )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetCreateDatabase2 = ( PFN_JetCreateDatabase2 ) ( GetProcAddress( hEseDll, "JetCreateDatabase2" ) );
}
if ( NULL == hEseDll || NULL == pfnJetCreateDatabase2 )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetCreateDatabase2", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetCreateDatabase2)( sesid, szFilename, cpgDatabaseSizeMax, pdbid, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetCreateDatabaseWithStreaming(
JET_SESID sesid,
const char *szDbFileName,
const char *szSLVFileName,
const char *szSLVRootName,
const unsigned long cpgDatabaseSizeMax,
JET_DBID *pdbid,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetCreateDatabaseWithStreaming ) (
JET_SESID sesid,
const char *szDbFileName,
const char *szSLVFileName,
const char *szSLVRootName,
const unsigned long cpgDatabaseSizeMax,
JET_DBID *pdbid,
JET_GRBIT grbit );
static PFN_JetCreateDatabaseWithStreaming pfnJetCreateDatabaseWithStreaming = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetCreateDatabaseWithStreaming )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetCreateDatabaseWithStreaming = ( PFN_JetCreateDatabaseWithStreaming ) ( GetProcAddress( hEseDll, "JetCreateDatabaseWithStreaming" ) );
}
if ( NULL == hEseDll || NULL == pfnJetCreateDatabaseWithStreaming )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetCreateDatabaseWithStreaming", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetCreateDatabaseWithStreaming)( sesid, szDbFileName, szSLVFileName, szSLVRootName, cpgDatabaseSizeMax, pdbid, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetAttachDatabase(
JET_SESID sesid,
const char *szFilename,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetAttachDatabase ) (
JET_SESID sesid,
const char *szFilename,
JET_GRBIT grbit );
static PFN_JetAttachDatabase pfnJetAttachDatabase = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetAttachDatabase )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetAttachDatabase = ( PFN_JetAttachDatabase ) ( GetProcAddress( hEseDll, "JetAttachDatabase" ) );
}
if ( NULL == hEseDll || NULL == pfnJetAttachDatabase )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetAttachDatabase", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetAttachDatabase)( sesid, szFilename, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetAttachDatabase2(
JET_SESID sesid,
const char *szFilename,
const unsigned long cpgDatabaseSizeMax,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetAttachDatabase2 ) (
JET_SESID sesid,
const char *szFilename,
const unsigned long cpgDatabaseSizeMax,
JET_GRBIT grbit );
static PFN_JetAttachDatabase2 pfnJetAttachDatabase2 = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetAttachDatabase2 )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetAttachDatabase2 = ( PFN_JetAttachDatabase2 ) ( GetProcAddress( hEseDll, "JetAttachDatabase2" ) );
}
if ( NULL == hEseDll || NULL == pfnJetAttachDatabase2 )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetAttachDatabase2", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetAttachDatabase2)( sesid, szFilename, cpgDatabaseSizeMax, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetAttachDatabase3(
JET_SESID sesid,
const char *szFilename,
const JET_SETDBPARAM* const rgsetdbparam,
const unsigned long csetdbparam,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetAttachDatabase3 ) (
JET_SESID sesid,
const char *szFilename,
const JET_SETDBPARAM* const rgsetdbparam,
const unsigned long csetdbparam,
JET_GRBIT grbit );
static PFN_JetAttachDatabase3 pfnJetAttachDatabase3 = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetAttachDatabase3 )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetAttachDatabase3 = ( PFN_JetAttachDatabase3 ) ( GetProcAddress( hEseDll, "JetAttachDatabase3" ) );
}
if ( NULL == hEseDll || NULL == pfnJetAttachDatabase3 )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetAttachDatabase3", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetAttachDatabase3)( sesid, szFilename, rgsetdbparam, csetdbparam, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetAttachDatabaseWithStreaming(
JET_SESID sesid,
const char *szDbFileName,
const char *szSLVFileName,
const char *szSLVRootName,
const unsigned long cpgDatabaseSizeMax,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetAttachDatabaseWithStreaming ) (
JET_SESID sesid,
const char *szDbFileName,
const char *szSLVFileName,
const char *szSLVRootName,
const unsigned long cpgDatabaseSizeMax,
JET_GRBIT grbit );
static PFN_JetAttachDatabaseWithStreaming pfnJetAttachDatabaseWithStreaming = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetAttachDatabaseWithStreaming )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetAttachDatabaseWithStreaming = ( PFN_JetAttachDatabaseWithStreaming ) ( GetProcAddress( hEseDll, "JetAttachDatabaseWithStreaming" ) );
}
if ( NULL == hEseDll || NULL == pfnJetAttachDatabaseWithStreaming )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetAttachDatabaseWithStreaming", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetAttachDatabaseWithStreaming)( sesid, szDbFileName, szSLVFileName, szSLVRootName, cpgDatabaseSizeMax, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetDetachDatabase(
JET_SESID sesid,
const char *szFilename
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetDetachDatabase ) (
JET_SESID sesid,
const char *szFilename );
static PFN_JetDetachDatabase pfnJetDetachDatabase = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetDetachDatabase )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetDetachDatabase = ( PFN_JetDetachDatabase ) ( GetProcAddress( hEseDll, "JetDetachDatabase" ) );
}
if ( NULL == hEseDll || NULL == pfnJetDetachDatabase )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetDetachDatabase", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetDetachDatabase)( sesid, szFilename );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetDetachDatabase2(
JET_SESID sesid,
const char *szFilename,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetDetachDatabase2 ) (
JET_SESID sesid,
const char *szFilename,
JET_GRBIT grbit );
static PFN_JetDetachDatabase2 pfnJetDetachDatabase2 = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetDetachDatabase2 )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetDetachDatabase2 = ( PFN_JetDetachDatabase2 ) ( GetProcAddress( hEseDll, "JetDetachDatabase2" ) );
}
if ( NULL == hEseDll || NULL == pfnJetDetachDatabase2 )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetDetachDatabase2", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetDetachDatabase2)( sesid, szFilename, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetCreateTable(
JET_SESID sesid,
JET_DBID dbid,
const char *szTableName,
unsigned long lPages,
unsigned long lDensity,
JET_TABLEID *ptableid
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetCreateTable ) (
JET_SESID sesid,
JET_DBID dbid,
const char *szTableName,
unsigned long lPages,
unsigned long lDensity,
JET_TABLEID *ptableid );
static PFN_JetCreateTable pfnJetCreateTable = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetCreateTable )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetCreateTable = ( PFN_JetCreateTable ) ( GetProcAddress( hEseDll, "JetCreateTable" ) );
}
if ( NULL == hEseDll || NULL == pfnJetCreateTable )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetCreateTable", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetCreateTable)( sesid, dbid, szTableName, lPages, lDensity, ptableid );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetDeleteTable(
JET_SESID sesid,
JET_DBID dbid,
const char *szTableName
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetDeleteTable ) (
JET_SESID sesid,
JET_DBID dbid,
const char *szTableName );
static PFN_JetDeleteTable pfnJetDeleteTable = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetDeleteTable )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetDeleteTable = ( PFN_JetDeleteTable ) ( GetProcAddress( hEseDll, "JetDeleteTable" ) );
}
if ( NULL == hEseDll || NULL == pfnJetDeleteTable )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetDeleteTable", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetDeleteTable)( sesid, dbid, szTableName );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetRenameTable(
JET_SESID sesid,
JET_DBID dbid,
const char *szName,
const char *szNameNew
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetRenameTable ) (
JET_SESID sesid,
JET_DBID dbid,
const char *szName,
const char *szNameNew );
static PFN_JetRenameTable pfnJetRenameTable = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetRenameTable )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetRenameTable = ( PFN_JetRenameTable ) ( GetProcAddress( hEseDll, "JetRenameTable" ) );
}
if ( NULL == hEseDll || NULL == pfnJetRenameTable )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetRenameTable", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetRenameTable)( sesid, dbid, szName, szNameNew );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetDeleteColumn(
JET_SESID sesid,
JET_TABLEID tableid,
const char *szColumnName
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetDeleteColumn ) (
JET_SESID sesid,
JET_TABLEID tableid,
const char *szColumnName );
static PFN_JetDeleteColumn pfnJetDeleteColumn = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetDeleteColumn )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetDeleteColumn = ( PFN_JetDeleteColumn ) ( GetProcAddress( hEseDll, "JetDeleteColumn" ) );
}
if ( NULL == hEseDll || NULL == pfnJetDeleteColumn )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetDeleteColumn", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetDeleteColumn)( sesid, tableid, szColumnName );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetDeleteColumn2(
JET_SESID sesid,
JET_TABLEID tableid,
const char *szColumnName,
const JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetDeleteColumn2 ) (
JET_SESID sesid,
JET_TABLEID tableid,
const char *szColumnName,
const JET_GRBIT grbit );
static PFN_JetDeleteColumn2 pfnJetDeleteColumn2 = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetDeleteColumn2 )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetDeleteColumn2 = ( PFN_JetDeleteColumn2 ) ( GetProcAddress( hEseDll, "JetDeleteColumn2" ) );
}
if ( NULL == hEseDll || NULL == pfnJetDeleteColumn2 )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetDeleteColumn2", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetDeleteColumn2)( sesid, tableid, szColumnName, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetRenameColumn(
JET_SESID sesid,
JET_TABLEID tableid,
_In_ JET_PCSTR szName,
_In_ JET_PCSTR szNameNew,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetRenameColumn ) (
JET_SESID sesid,
JET_TABLEID tableid,
_In_ JET_PCSTR szName,
_In_ JET_PCSTR szNameNew,
JET_GRBIT grbit );
static PFN_JetRenameColumn pfnJetRenameColumn = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetRenameColumn )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetRenameColumn = ( PFN_JetRenameColumn ) ( GetProcAddress( hEseDll, "JetRenameColumn" ) );
}
if ( NULL == hEseDll || NULL == pfnJetRenameColumn )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetRenameColumn", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetRenameColumn)( sesid, tableid, szName, szNameNew, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetSetColumnDefaultValue(
JET_SESID sesid,
JET_DBID dbid,
_In_ JET_PCSTR szTableName,
_In_ JET_PCSTR szColumnName,
__in_bcount(cbData) const void *pvData,
const unsigned long cbData,
const JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetSetColumnDefaultValue ) (
JET_SESID sesid,
JET_DBID dbid,
_In_ JET_PCSTR szTableName,
_In_ JET_PCSTR szColumnName,
__in_bcount(cbData) const void *pvData,
const unsigned long cbData,
const JET_GRBIT grbit );
static PFN_JetSetColumnDefaultValue pfnJetSetColumnDefaultValue = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetSetColumnDefaultValue )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetSetColumnDefaultValue = ( PFN_JetSetColumnDefaultValue ) ( GetProcAddress( hEseDll, "JetSetColumnDefaultValue" ) );
}
if ( NULL == hEseDll || NULL == pfnJetSetColumnDefaultValue )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetSetColumnDefaultValue", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetSetColumnDefaultValue)( sesid, dbid, szTableName, szColumnName, pvData, cbData, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetDeleteIndex(
JET_SESID sesid,
JET_TABLEID tableid,
_In_ JET_PCSTR szIndexName
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetDeleteIndex ) (
JET_SESID sesid,
JET_TABLEID tableid,
_In_ JET_PCSTR szIndexName );
static PFN_JetDeleteIndex pfnJetDeleteIndex = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetDeleteIndex )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetDeleteIndex = ( PFN_JetDeleteIndex ) ( GetProcAddress( hEseDll, "JetDeleteIndex" ) );
}
if ( NULL == hEseDll || NULL == pfnJetDeleteIndex )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetDeleteIndex", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetDeleteIndex)( sesid, tableid, szIndexName );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetGetDatabaseFileInfo(
const char *szDatabaseName,
void *pvResult,
unsigned long cbMax,
unsigned long InfoLevel
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetGetDatabaseFileInfo ) (
const char *szDatabaseName,
void *pvResult,
unsigned long cbMax,
unsigned long InfoLevel );
static PFN_JetGetDatabaseFileInfo pfnJetGetDatabaseFileInfo = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetGetDatabaseFileInfo )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetGetDatabaseFileInfo = ( PFN_JetGetDatabaseFileInfo ) ( GetProcAddress( hEseDll, "JetGetDatabaseFileInfo" ) );
}
if ( NULL == hEseDll || NULL == pfnJetGetDatabaseFileInfo )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetGetDatabaseFileInfo", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetGetDatabaseFileInfo)( szDatabaseName, pvResult, cbMax, InfoLevel );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetOpenDatabase(
JET_SESID sesid,
const char *szFilename,
const char *szConnect,
JET_DBID *pdbid,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetOpenDatabase ) (
JET_SESID sesid,
const char *szFilename,
const char *szConnect,
JET_DBID *pdbid,
JET_GRBIT grbit );
static PFN_JetOpenDatabase pfnJetOpenDatabase = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetOpenDatabase )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetOpenDatabase = ( PFN_JetOpenDatabase ) ( GetProcAddress( hEseDll, "JetOpenDatabase" ) );
}
if ( NULL == hEseDll || NULL == pfnJetOpenDatabase )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetOpenDatabase", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetOpenDatabase)( sesid, szFilename, szConnect, pdbid, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetOpenTable(
JET_SESID sesid,
JET_DBID dbid,
const char *szTableName,
const void *pvParameters,
unsigned long cbParameters,
JET_GRBIT grbit,
JET_TABLEID *ptableid
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetOpenTable ) (
JET_SESID sesid,
JET_DBID dbid,
const char *szTableName,
const void *pvParameters,
unsigned long cbParameters,
JET_GRBIT grbit,
JET_TABLEID *ptableid );
static PFN_JetOpenTable pfnJetOpenTable = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetOpenTable )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetOpenTable = ( PFN_JetOpenTable ) ( GetProcAddress( hEseDll, "JetOpenTable" ) );
}
if ( NULL == hEseDll || NULL == pfnJetOpenTable )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetOpenTable", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetOpenTable)( sesid, dbid, szTableName, pvParameters, cbParameters, grbit, ptableid );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetSetCurrentIndex(
JET_SESID sesid,
JET_TABLEID tableid,
const char *szIndexName
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetSetCurrentIndex ) (
JET_SESID sesid,
JET_TABLEID tableid,
const char *szIndexName );
static PFN_JetSetCurrentIndex pfnJetSetCurrentIndex = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetSetCurrentIndex )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetSetCurrentIndex = ( PFN_JetSetCurrentIndex ) ( GetProcAddress( hEseDll, "JetSetCurrentIndex" ) );
}
if ( NULL == hEseDll || NULL == pfnJetSetCurrentIndex )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetSetCurrentIndex", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetSetCurrentIndex)( sesid, tableid, szIndexName );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetSetCurrentIndex2(
JET_SESID sesid,
JET_TABLEID tableid,
const char *szIndexName,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetSetCurrentIndex2 ) (
JET_SESID sesid,
JET_TABLEID tableid,
const char *szIndexName,
JET_GRBIT grbit );
static PFN_JetSetCurrentIndex2 pfnJetSetCurrentIndex2 = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetSetCurrentIndex2 )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetSetCurrentIndex2 = ( PFN_JetSetCurrentIndex2 ) ( GetProcAddress( hEseDll, "JetSetCurrentIndex2" ) );
}
if ( NULL == hEseDll || NULL == pfnJetSetCurrentIndex2 )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetSetCurrentIndex2", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetSetCurrentIndex2)( sesid, tableid, szIndexName, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetSetCurrentIndex3(
JET_SESID sesid,
JET_TABLEID tableid,
const char *szIndexName,
JET_GRBIT grbit,
unsigned long itagSequence
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetSetCurrentIndex3 ) (
JET_SESID sesid,
JET_TABLEID tableid,
const char *szIndexName,
JET_GRBIT grbit,
unsigned long itagSequence );
static PFN_JetSetCurrentIndex3 pfnJetSetCurrentIndex3 = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetSetCurrentIndex3 )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetSetCurrentIndex3 = ( PFN_JetSetCurrentIndex3 ) ( GetProcAddress( hEseDll, "JetSetCurrentIndex3" ) );
}
if ( NULL == hEseDll || NULL == pfnJetSetCurrentIndex3 )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetSetCurrentIndex3", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetSetCurrentIndex3)( sesid, tableid, szIndexName, grbit, itagSequence );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetSetCurrentIndex4(
JET_SESID sesid,
JET_TABLEID tableid,
const char *szIndexName,
JET_INDEXID *pindexid,
JET_GRBIT grbit,
unsigned long itagSequence
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetSetCurrentIndex4 ) (
JET_SESID sesid,
JET_TABLEID tableid,
const char *szIndexName,
JET_INDEXID *pindexid,
JET_GRBIT grbit,
unsigned long itagSequence );
static PFN_JetSetCurrentIndex4 pfnJetSetCurrentIndex4 = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetSetCurrentIndex4 )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetSetCurrentIndex4 = ( PFN_JetSetCurrentIndex4 ) ( GetProcAddress( hEseDll, "JetSetCurrentIndex4" ) );
}
if ( NULL == hEseDll || NULL == pfnJetSetCurrentIndex4 )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetSetCurrentIndex4", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetSetCurrentIndex4)( sesid, tableid, szIndexName, pindexid, grbit, itagSequence );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetCompact(
JET_SESID sesid,
const char *szDatabaseSrc,
const char *szDatabaseDest,
JET_PFNSTATUS pfnStatus,
JET_CONVERT *pconvert,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetCompact ) (
JET_SESID sesid,
const char *szDatabaseSrc,
const char *szDatabaseDest,
JET_PFNSTATUS pfnStatus,
JET_CONVERT *pconvert,
JET_GRBIT grbit );
static PFN_JetCompact pfnJetCompact = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetCompact )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetCompact = ( PFN_JetCompact ) ( GetProcAddress( hEseDll, "JetCompact" ) );
}
if ( NULL == hEseDll || NULL == pfnJetCompact )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetCompact", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetCompact)( sesid, szDatabaseSrc, szDatabaseDest, pfnStatus, pconvert, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetDefragment(
JET_SESID sesid,
JET_DBID dbid,
const char *szTableName,
unsigned long *pcPasses,
unsigned long *pcSeconds,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetDefragment ) (
JET_SESID sesid,
JET_DBID dbid,
const char *szTableName,
unsigned long *pcPasses,
unsigned long *pcSeconds,
JET_GRBIT grbit );
static PFN_JetDefragment pfnJetDefragment = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetDefragment )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetDefragment = ( PFN_JetDefragment ) ( GetProcAddress( hEseDll, "JetDefragment" ) );
}
if ( NULL == hEseDll || NULL == pfnJetDefragment )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetDefragment", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetDefragment)( sesid, dbid, szTableName, pcPasses, pcSeconds, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetDefragment2(
JET_SESID sesid,
JET_DBID dbid,
const char *szTableName,
unsigned long *pcPasses,
unsigned long *pcSeconds,
JET_CALLBACK callback,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetDefragment2 ) (
JET_SESID sesid,
JET_DBID dbid,
const char *szTableName,
unsigned long *pcPasses,
unsigned long *pcSeconds,
JET_CALLBACK callback,
JET_GRBIT grbit );
static PFN_JetDefragment2 pfnJetDefragment2 = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetDefragment2 )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetDefragment2 = ( PFN_JetDefragment2 ) ( GetProcAddress( hEseDll, "JetDefragment2" ) );
}
if ( NULL == hEseDll || NULL == pfnJetDefragment2 )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetDefragment2", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetDefragment2)( sesid, dbid, szTableName, pcPasses, pcSeconds, callback, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetDefragment3(
JET_SESID vsesid,
const char *szDatabaseName,
const char *szTableName,
unsigned long *pcPasses,
unsigned long *pcSeconds,
JET_CALLBACK callback,
void *pvContext,
JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetDefragment3 ) (
JET_SESID vsesid,
const char *szDatabaseName,
const char *szTableName,
unsigned long *pcPasses,
unsigned long *pcSeconds,
JET_CALLBACK callback,
void *pvContext,
JET_GRBIT grbit );
static PFN_JetDefragment3 pfnJetDefragment3 = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetDefragment3 )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetDefragment3 = ( PFN_JetDefragment3 ) ( GetProcAddress( hEseDll, "JetDefragment3" ) );
}
if ( NULL == hEseDll || NULL == pfnJetDefragment3 )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetDefragment3", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetDefragment3)( vsesid, szDatabaseName, szTableName, pcPasses, pcSeconds, callback, pvContext, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetUpgradeDatabase(
JET_SESID sesid,
const char *szDbFileName,
const char *szSLVFileName,
const JET_GRBIT grbit
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetUpgradeDatabase ) (
JET_SESID sesid,
const char *szDbFileName,
const char *szSLVFileName,
const JET_GRBIT grbit );
static PFN_JetUpgradeDatabase pfnJetUpgradeDatabase = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetUpgradeDatabase )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetUpgradeDatabase = ( PFN_JetUpgradeDatabase ) ( GetProcAddress( hEseDll, "JetUpgradeDatabase" ) );
}
if ( NULL == hEseDll || NULL == pfnJetUpgradeDatabase )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetUpgradeDatabase", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetUpgradeDatabase)( sesid, szDbFileName, szSLVFileName, grbit );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetBackup(
const char *szBackupPath,
JET_GRBIT grbit,
JET_PFNSTATUS pfnStatus
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetBackup ) ( const char *szBackupPath, JET_GRBIT grbit, JET_PFNSTATUS pfnStatus );
static PFN_JetBackup pfnJetBackup = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetBackup )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetBackup = ( PFN_JetBackup ) ( GetProcAddress( hEseDll, "JetBackup" ) );
}
if ( NULL == hEseDll || NULL == pfnJetBackup )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetBackup", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetBackup)( szBackupPath, grbit, pfnStatus );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetBackupInstance(
JET_INSTANCE instance,
const char *szBackupPath,
JET_GRBIT grbit,
JET_PFNSTATUS pfnStatus
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetBackupInstance ) (
JET_INSTANCE instance,
const char *szBackupPath,
JET_GRBIT grbit,
JET_PFNSTATUS pfnStatus );
static PFN_JetBackupInstance pfnJetBackupInstance = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetBackupInstance )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetBackupInstance = ( PFN_JetBackupInstance ) ( GetProcAddress( hEseDll, "JetBackupInstance" ) );
}
if ( NULL == hEseDll || NULL == pfnJetBackupInstance )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetBackupInstance", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetBackupInstance)( instance, szBackupPath, grbit, pfnStatus );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetRestore(
_In_ JET_PCSTR sz,
JET_PFNSTATUS pfn
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetRestore ) (
_In_ JET_PCSTR sz,
JET_PFNSTATUS pfn );
static PFN_JetRestore pfnJetRestore = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetRestore )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetRestore = ( PFN_JetRestore ) ( GetProcAddress( hEseDll, "JetRestore" ) );
}
if ( NULL == hEseDll || NULL == pfnJetRestore )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetRestore", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetRestore)( sz, pfn );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetRestore2(
JET_PCSTR sz,
JET_PCSTR szDest,
JET_PFNSTATUS pfn
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetRestore2 ) (
JET_PCSTR sz,
JET_PCSTR szDest,
JET_PFNSTATUS pfn );
static PFN_JetRestore2 pfnJetRestore2 = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetRestore2 )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetRestore2 = ( PFN_JetRestore2 ) ( GetProcAddress( hEseDll, "JetRestore2" ) );
}
if ( NULL == hEseDll || NULL == pfnJetRestore2 )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetRestore2", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetRestore2)( sz, szDest, pfn );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetRestoreInstance(
JET_INSTANCE instance,
const char *sz,
const char *szDest,
JET_PFNSTATUS pfn
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetRestoreInstance ) (
JET_INSTANCE instance,
const char *sz,
const char *szDest,
JET_PFNSTATUS pfn );
static PFN_JetRestoreInstance pfnJetRestoreInstance = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetRestoreInstance )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetRestoreInstance = ( PFN_JetRestoreInstance ) ( GetProcAddress( hEseDll, "JetRestoreInstance" ) );
}
if ( NULL == hEseDll || NULL == pfnJetRestoreInstance )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetRestoreInstance", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetRestoreInstance)( instance, sz, szDest, pfn );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetOpenFile(
const char *szFileName,
JET_HANDLE *phfFile,
unsigned long *pulFileSizeLow,
unsigned long *pulFileSizeHigh
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetOpenFile ) ( const char *szFileName,
JET_HANDLE *phfFile,
unsigned long *pulFileSizeLow,
unsigned long *pulFileSizeHigh );
static PFN_JetOpenFile pfnJetOpenFile = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetOpenFile )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetOpenFile = ( PFN_JetOpenFile ) ( GetProcAddress( hEseDll, "JetOpenFile" ) );
}
if ( NULL == hEseDll || NULL == pfnJetOpenFile )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetOpenFile", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetOpenFile)( szFileName, phfFile, pulFileSizeLow, pulFileSizeHigh );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetOpenFileInstance(
JET_INSTANCE instance,
const char *szFileName,
JET_HANDLE *phfFile,
unsigned long *pulFileSizeLow,
unsigned long *pulFileSizeHigh
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetOpenFileInstance ) ( JET_INSTANCE instance,
const char *szFileName,
JET_HANDLE *phfFile,
unsigned long *pulFileSizeLow,
unsigned long *pulFileSizeHigh );
static PFN_JetOpenFileInstance pfnJetOpenFileInstance = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetOpenFileInstance )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetOpenFileInstance = ( PFN_JetOpenFileInstance ) ( GetProcAddress( hEseDll, "JetOpenFileInstance" ) );
}
if ( NULL == hEseDll || NULL == pfnJetOpenFileInstance )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetOpenFileInstance", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetOpenFileInstance)( instance, szFileName, phfFile, pulFileSizeLow, pulFileSizeHigh );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetOpenFileSectionInstance(
JET_INSTANCE instance,
_In_ JET_PSTR szFile,
JET_HANDLE * phFile,
long iSection,
long cSections,
unsigned long * pulSectionSizeLow,
long * plSectionSizeHigh
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetOpenFileSectionInstance ) (
JET_INSTANCE instance,
_In_ JET_PSTR szFile,
JET_HANDLE * phFile,
long iSection,
long cSections,
unsigned long * pulSectionSizeLow,
long * plSectionSizeHigh );
static PFN_JetOpenFileSectionInstance pfnJetOpenFileSectionInstance = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetOpenFileSectionInstance )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetOpenFileSectionInstance = ( PFN_JetOpenFileSectionInstance ) ( GetProcAddress( hEseDll, "JetOpenFileSectionInstance" ) );
}
if ( NULL == hEseDll || NULL == pfnJetOpenFileSectionInstance )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetOpenFileSectionInstance", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetOpenFileSectionInstance)( instance, szFile, phFile, iSection, cSections, pulSectionSizeLow, plSectionSizeHigh );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
JET_ERR
BounceJetGetLogFileInfo(
char *szLog,
__out_bcount(cbMax) void *pvResult,
const unsigned long cbMax,
const unsigned long InfoLevel
)
{
JET_ERR err = JET_errSuccess;
typedef JET_ERR ( __stdcall *PFN_JetGetLogFileInfo ) ( char *szLog,
__out_bcount(cbMax) void *pvResult,
const unsigned long cbMax,
const unsigned long InfoLevel );
static PFN_JetGetLogFileInfo pfnJetGetLogFileInfo = NULL;
// Get the procedure address if this is the first time calling this function.
if ( NULL == pfnJetGetLogFileInfo )
{
// Do not bother with synchronization of GetProcAddress() -- sloppy, but a leak isn't a big deal.
const HMODULE hEseDll = HmodEsetestEseDll();
if ( NULL != hEseDll )
{
pfnJetGetLogFileInfo = ( PFN_JetGetLogFileInfo ) ( GetProcAddress( hEseDll, "JetGetLogFileInfo" ) );
}
if ( NULL == hEseDll || NULL == pfnJetGetLogFileInfo )
{
tprintf( "%s(): Failed to either fetch hEseDll (=%p) GetProcAddress( hEseDll, %s ), Gle = %d " CRLF,
__FUNCTION__, hEseDll, "JetGetLogFileInfo", GetLastError() );
err = JET_errTestError;
goto Cleanup;
}
}
err = (*pfnJetGetLogFileInfo)( szLog, pvResult, cbMax, InfoLevel );
goto Cleanup; // Need to have the explicit goto in case the function hasn't referenced 'Cleanup' yet.
Cleanup:
return err;
}
//---------------------------------------------------
bool FEsetestAlwaysNarrow()
{
return true;
}
//---------------------------------------------------
| 412 | 0.664065 | 1 | 0.664065 | game-dev | MEDIA | 0.521809 | game-dev | 0.901681 | 1 | 0.901681 |
dingxiaowei/GFFrameWork | 1,587 | Assets/Code/Game/ILRuntime/Binding/Analysis/UnityEngine_Application_Binding.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.Reflection;
using ILRuntime.CLR.Utils;
namespace ILRuntime.Runtime.Generated
{
unsafe class UnityEngine_Application_Binding
{
public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
{
BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodBase method;
Type[] args;
Type type = typeof(UnityEngine.Application);
args = new Type[]{typeof(System.Int32)};
method = type.GetMethod("set_targetFrameRate", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, set_targetFrameRate_0);
}
static StackObject* set_targetFrameRate_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Int32 @value = ptr_of_this_method->Value;
UnityEngine.Application.targetFrameRate = value;
return __ret;
}
}
}
| 412 | 0.760512 | 1 | 0.760512 | game-dev | MEDIA | 0.252843 | game-dev | 0.687179 | 1 | 0.687179 |
AstroTechies/unrealmodding | 10,025 | unreal_asset/unreal_asset_properties/src/str_property.rs | //! String properties
use crate::property_prelude::*;
/// Text history type
#[derive(
FNameContainer,
Debug,
Copy,
Clone,
Default,
PartialEq,
Eq,
IntoPrimitive,
TryFromPrimitive,
Hash,
)]
#[repr(i8)]
pub enum TextHistoryType {
/// None
#[default]
None = -1,
/// Base
Base = 0,
/// Named format
NamedFormat,
/// Ordered format
OrderedFormat,
/// Argument format
ArgumentFormat,
/// As number
AsNumber,
/// As percentage
AsPercent,
/// As currency
AsCurrency,
/// As date
AsDate,
/// As time
AsTime,
/// As datetime
AsDateTime,
/// Transform
Transform,
/// String table entry
StringTableEntry,
/// Text generator
TextGenerator,
/// Uncertain, Back 4 Blood specific serialization
RawText,
}
/// String property
#[derive(FNameContainer, Debug, Clone, PartialEq, Eq, Hash)]
pub struct StrProperty {
/// Name
pub name: FName,
/// Property ancestry
pub ancestry: Ancestry,
/// Property guid
pub property_guid: Option<Guid>,
/// Property duplication index
pub duplication_index: i32,
/// FString value
pub value: Option<String>,
}
impl_property_data_trait!(StrProperty);
/// Text property
#[derive(FNameContainer, Debug, Clone, PartialEq, Eq, Hash)]
pub struct TextProperty {
/// Name
pub name: FName,
/// Property ancestry
pub ancestry: Ancestry,
/// Property guid
pub property_guid: Option<Guid>,
/// Property duplication index
pub duplication_index: i32,
/// Culture invariant string
pub culture_invariant_string: Option<String>,
/// Namespace
pub namespace: Option<String>,
/// String table id
pub table_id: Option<FName>,
/// Flags
pub flags: u32,
/// History type
pub history_type: TextHistoryType,
/// FString value
pub value: Option<String>,
}
impl_property_data_trait!(TextProperty);
/// Name property
#[derive(FNameContainer, Debug, Clone, PartialEq, Eq, Hash)]
pub struct NameProperty {
/// Name
pub name: FName,
/// Property ancestry
pub ancestry: Ancestry,
/// Property guid
pub property_guid: Option<Guid>,
/// Property duplication index
pub duplication_index: i32,
/// FName value
pub value: FName,
}
impl_property_data_trait!(NameProperty);
impl StrProperty {
/// Read a `StrProperty` from an asset
pub fn new<Reader: ArchiveReader<impl PackageIndexTrait>>(
asset: &mut Reader,
name: FName,
ancestry: Ancestry,
include_header: bool,
duplication_index: i32,
) -> Result<Self, Error> {
let property_guid = optional_guid!(asset, include_header);
Ok(StrProperty {
name,
ancestry,
property_guid,
duplication_index,
value: asset.read_fstring()?,
})
}
}
impl PropertyTrait for StrProperty {
fn write<Writer: ArchiveWriter<impl PackageIndexTrait>>(
&self,
asset: &mut Writer,
include_header: bool,
) -> Result<usize, Error> {
optional_guid_write!(self, asset, include_header);
let begin = asset.position();
asset.write_fstring(self.value.as_deref())?;
Ok((asset.position() - begin) as usize)
}
}
impl TextProperty {
/// Read a `TextProperty` from an asset
pub fn new<Reader: ArchiveReader<impl PackageIndexTrait>>(
asset: &mut Reader,
name: FName,
ancestry: Ancestry,
include_header: bool,
duplication_index: i32,
) -> Result<Self, Error> {
let property_guid = optional_guid!(asset, include_header);
let mut culture_invariant_string = None;
let mut namespace = None;
let mut value = None;
if asset.get_object_version() < ObjectVersion::VER_UE4_FTEXT_HISTORY {
culture_invariant_string = asset.read_fstring()?;
if asset.get_object_version()
>= ObjectVersion::VER_UE4_ADDED_NAMESPACE_AND_KEY_DATA_TO_FTEXT
{
namespace = asset.read_fstring()?;
value = asset.read_fstring()?;
} else {
namespace = None;
value = asset.read_fstring()?;
}
}
let flags = asset.read_u32::<LE>()?;
let mut history_type = TextHistoryType::Base;
let mut table_id = None;
if asset.get_object_version() >= ObjectVersion::VER_UE4_FTEXT_HISTORY {
history_type = TextHistoryType::try_from(asset.read_i8()?)?;
match history_type {
TextHistoryType::None => {
value = None;
let version: CustomVersion = asset.get_custom_version::<FEditorObjectVersion>();
if version.version
>= FEditorObjectVersion::CultureInvariantTextSerializationKeyStability
as i32
{
let has_culture_invariant_string = asset.read_i32::<LE>()? == 1;
if has_culture_invariant_string {
culture_invariant_string = asset.read_fstring()?;
}
}
}
TextHistoryType::Base => {
namespace = asset.read_fstring()?;
value = asset.read_fstring()?;
culture_invariant_string = asset.read_fstring()?;
}
TextHistoryType::StringTableEntry => {
table_id = Some(asset.read_fname()?);
value = asset.read_fstring()?;
}
_ => {
return Err(Error::unimplemented(format!(
"Unimplemented reader for {history_type:?}"
)));
}
}
}
Ok(TextProperty {
name,
ancestry,
property_guid,
duplication_index,
culture_invariant_string,
namespace,
table_id,
flags,
history_type,
value,
})
}
}
impl PropertyTrait for TextProperty {
fn write<Writer: ArchiveWriter<impl PackageIndexTrait>>(
&self,
asset: &mut Writer,
include_header: bool,
) -> Result<usize, Error> {
optional_guid_write!(self, asset, include_header);
let begin = asset.position();
if asset.get_object_version() < ObjectVersion::VER_UE4_FTEXT_HISTORY {
asset.write_fstring(self.culture_invariant_string.as_deref())?;
if asset.get_object_version()
>= ObjectVersion::VER_UE4_ADDED_NAMESPACE_AND_KEY_DATA_TO_FTEXT
{
asset.write_fstring(self.namespace.as_deref())?;
asset.write_fstring(self.value.as_deref())?;
} else {
asset.write_fstring(self.value.as_deref())?;
}
}
asset.write_u32::<LE>(self.flags)?;
if asset.get_object_version() >= ObjectVersion::VER_UE4_FTEXT_HISTORY {
let history_type = self.history_type;
asset.write_i8(history_type.into())?;
match history_type {
TextHistoryType::None => {
if asset.get_custom_version::<FEditorObjectVersion>().version
>= FEditorObjectVersion::CultureInvariantTextSerializationKeyStability
as i32
{
let is_empty = match &self.culture_invariant_string {
Some(e) => e.is_empty(),
None => true,
};
match is_empty {
true => asset.write_i32::<LE>(0)?,
false => {
asset.write_i32::<LE>(1)?;
asset.write_fstring(self.culture_invariant_string.as_deref())?;
}
}
}
Ok(())
}
TextHistoryType::Base => {
asset.write_fstring(self.namespace.as_deref())?;
asset.write_fstring(self.value.as_deref())?;
asset.write_fstring(self.culture_invariant_string.as_deref())?;
Ok(())
}
TextHistoryType::StringTableEntry => {
asset.write_fname(self.table_id.as_ref().ok_or_else(|| {
PropertyError::property_field_none("table_id", "FName")
})?)?;
asset.write_fstring(self.value.as_deref())?;
Ok(())
}
_ => Err(Error::unimplemented(format!(
"Unimplemented writer for {}",
history_type as i8
))),
}?;
}
Ok((asset.position() - begin) as usize)
}
}
impl NameProperty {
/// Read a `NameProperty` from an asset
pub fn new<Reader: ArchiveReader<impl PackageIndexTrait>>(
asset: &mut Reader,
name: FName,
ancestry: Ancestry,
include_header: bool,
duplication_index: i32,
) -> Result<Self, Error> {
let property_guid = optional_guid!(asset, include_header);
let value = asset.read_fname()?;
Ok(NameProperty {
name,
ancestry,
property_guid,
duplication_index,
value,
})
}
}
impl PropertyTrait for NameProperty {
fn write<Writer: ArchiveWriter<impl PackageIndexTrait>>(
&self,
asset: &mut Writer,
include_header: bool,
) -> Result<usize, Error> {
optional_guid_write!(self, asset, include_header);
asset.write_fname(&self.value)?;
Ok(size_of::<i32>() * 2)
}
}
| 412 | 0.889608 | 1 | 0.889608 | game-dev | MEDIA | 0.340693 | game-dev | 0.933997 | 1 | 0.933997 |
GValiente/butano | 7,236 | games/butano-fighter/src/bf_game_scoreboard.cpp | /*
* Copyright (c) 2020-2025 Gustavo Valiente gustavo.valiente@protonmail.com
* zlib License, see LICENSE file.
*/
#include "bf_game_scoreboard.h"
#include "bn_string.h"
#include "bn_display.h"
#include "bn_sprite_builder.h"
#include "bn_sprite_text_generator.h"
#include "bn_sprite_items_experience_bar.h"
#include "bn_sprite_items_experience_frame_back.h"
#include "bn_sprite_items_experience_frame_front.h"
#include "bn_sprite_items_hero_bomb_icon.h"
#include "bf_game_hero.h"
namespace bf::game
{
namespace
{
constexpr int level_text_x = 19 - (bn::display::width() / 2);
constexpr int level_text_y = (bn::display::height() / 2) - 12;
constexpr int experience_bar_x = (bn::display::width() / 2) - 22;
constexpr int experience_bar_y = (bn::display::height() / 2) - 16;
constexpr int experience_text_x = experience_bar_x - 8;
constexpr int experience_text_y = (bn::display::height() / 2) - 32;
void _set_visible(bool visible, bn::ivector<bn::sprite_ptr>& sprites)
{
for(bn::sprite_ptr& sprite : sprites)
{
sprite.set_visible(visible);
}
}
}
scoreboard::scoreboard(bn::sprite_text_generator& text_generator) :
_text_generator(text_generator),
_bombs_affine_mat(bn::sprite_affine_mat_ptr::create())
{
_text_generator.set_center_alignment();
_text_generator.generate(level_text_x, level_text_y - 12, "LVL", _level_label_sprites);
_text_generator.generate(experience_text_x, experience_text_y - 12, "EXP", _experience_label_sprites);
{
bn::sprite_builder builder(bn::sprite_items::experience_frame_back);
builder.set_position(bn::fixed_point(experience_bar_x - 8, experience_bar_y));
builder.set_bg_priority(_text_generator.bg_priority());
builder.set_z_order(_text_generator.z_order());
_experience_bar_sprites.push_back(builder.release_build());
}
{
bn::sprite_builder builder(bn::sprite_items::experience_bar);
builder.set_position(_experience_bar_sprites[0].position());
builder.set_bg_priority(_text_generator.bg_priority());
builder.set_horizontal_scale(0.5);
builder.set_z_order(_text_generator.z_order());
_experience_bar_sprites.push_back(builder.release_build());
}
{
bn::sprite_builder builder(bn::sprite_items::experience_frame_front);
builder.set_position(bn::fixed_point(experience_bar_x - 2, experience_bar_y));
builder.set_bg_priority(_text_generator.bg_priority());
builder.set_z_order(_text_generator.z_order());
builder.set_horizontal_flip(true);
_experience_bar_sprites.push_back(builder.build());
builder.set_position(bn::fixed_point(experience_bar_x - 13, experience_bar_y));
builder.set_horizontal_flip(false);
_experience_bar_sprites.push_back(builder.release_build());
}
_experience_bar_palette_action.emplace(_experience_bar_sprites[1].palette(), 2, 1);
}
void scoreboard::set_visible(bool visible)
{
_set_visible(visible, _level_label_sprites);
_set_visible(visible, _level_number_sprites);
_set_visible(visible, _experience_label_sprites);
_set_visible(visible, _experience_number_sprites);
_set_visible(visible, _experience_bar_sprites);
_set_visible(visible, _bomb_sprites);
}
void scoreboard::update(const hero& hero)
{
int level = hero.level();
int experience = hero.experience();
int bombs_count = hero.bombs_count();
bool visible = _level_label_sprites.front().visible();
_experience_bar_palette_action->update();
if(_bombs_affine_mat_scale_action)
{
_bombs_affine_mat_scale_action->update();
if(_bombs_affine_mat_scale_action->done())
{
_bombs_affine_mat_scale_action.reset();
if(_bomb_sprites.size() > _last_bombs_count)
{
_bomb_sprites.shrink(_last_bombs_count);
}
else
{
for(bn::sprite_ptr& bomb_sprite : _bomb_sprites)
{
bomb_sprite.remove_affine_mat();
}
}
}
}
if(level != _last_level)
{
_last_level = level;
_last_experience = -1;
bn::string<4> text;
if(level < constants::hero_bullet_levels - 1)
{
text = bn::to_string<4>(level + 1);
}
else
{
text = "MAX";
}
_level_number_sprites.clear();
_text_generator.set_center_alignment();
_text_generator.generate(level_text_x, level_text_y, text, _level_number_sprites);
_set_visible(visible, _level_number_sprites);
}
if(experience != _last_experience)
{
_last_experience = experience;
bn::sprite_ptr& experience_bar_sprite = _experience_bar_sprites[1];
bn::fixed next_level_experience_ratio = hero.next_level_experience_ratio();
if(next_level_experience_ratio < 1)
{
next_level_experience_ratio *= bn::fixed(0.935);
}
if(next_level_experience_ratio == 0)
{
experience_bar_sprite.set_visible(false);
}
else
{
experience_bar_sprite.set_horizontal_scale(next_level_experience_ratio);
experience_bar_sprite.set_visible(true);
}
bn::string<8> text = bn::to_string<8>(experience);
_experience_number_sprites.clear();
_text_generator.set_center_alignment();
_text_generator.generate(experience_text_x, experience_text_y, text, _experience_number_sprites);
_set_visible(visible, _experience_number_sprites);
}
if(bombs_count != _last_bombs_count)
{
int last_bombs_count = _last_bombs_count;
_last_bombs_count = bombs_count;
_bomb_sprites.clear();
for(int index = 0, limit = bn::max(bombs_count, last_bombs_count); index < limit; ++index)
{
bn::sprite_builder builder(bn::sprite_items::hero_bomb_icon);
builder.set_x((bn::display::width() / 2) - ((index + 1) * 16) + 1);
builder.set_y(16 - (bn::display::height() / 2));
builder.set_bg_priority(_text_generator.bg_priority());
builder.set_z_order(_text_generator.z_order());
builder.set_visible(visible);
_bomb_sprites.push_back(builder.release_build());
}
if(bombs_count > last_bombs_count)
{
if(last_bombs_count != -1)
{
_bombs_affine_mat.set_scale(0.01);
_bombs_affine_mat_scale_action.emplace(_bombs_affine_mat, 16, 1);
for(int index = last_bombs_count; index < bombs_count; ++index)
{
_bomb_sprites[index].set_affine_mat(_bombs_affine_mat);
}
}
}
else
{
_bombs_affine_mat.set_scale(1);
_bombs_affine_mat_scale_action.emplace(_bombs_affine_mat, 16, bn::fixed(0.01));
for(int index = bombs_count; index < last_bombs_count; ++index)
{
_bomb_sprites[index].set_affine_mat(_bombs_affine_mat);
}
}
}
}
}
| 412 | 0.510411 | 1 | 0.510411 | game-dev | MEDIA | 0.97357 | game-dev | 0.900393 | 1 | 0.900393 |
OpenOLAT/OpenOLAT | 2,604 | src/main/java/org/olat/modules/forms/ui/component/ResponsiveBarChartComponent.java | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.modules.forms.ui.component;
import java.util.ArrayList;
import java.util.List;
import org.olat.core.gui.components.ComponentRenderer;
import org.olat.core.gui.components.chart.BarSeries;
import org.olat.core.gui.components.chart.DefaultD3Component;
/**
*
* Initial date: 28.05.2018<br>
* @author uhensler, urs.hensler@frentix.com, http://www.frentix.com
*
*/
public class ResponsiveBarChartComponent extends DefaultD3Component {
private static final ComponentRenderer renderer = new ResponsiveBarChartRenderer();
private List<BarSeries> seriesList = new ArrayList<>();
private String defaultBarClass = "bar_default";
private String yLegend;
private String xLegend;
private Double yMin;
private Double yMax;
public ResponsiveBarChartComponent(String name) {
super(name);
}
public String getDefaultBarClass() {
return defaultBarClass;
}
public void setDefaultBarClass(String defaultBarClass) {
this.defaultBarClass = defaultBarClass;
}
public String getYLegend() {
return yLegend;
}
public void setYLegend(String yLegend) {
this.yLegend = yLegend;
}
public String getXLegend() {
return xLegend;
}
public void setXLegend(String xLegend) {
this.xLegend = xLegend;
}
public List<BarSeries> getSeries() {
return seriesList;
}
public Double getYMin() {
return yMin;
}
public void setYMin(Double yMin) {
this.yMin = yMin;
}
public Double getYMax() {
return yMax;
}
public void setYMax(Double yMax) {
this.yMax = yMax;
}
public void addSeries(BarSeries... series) {
if(series != null && series.length > 0 && series[0] != null) {
for(BarSeries s:series) {
seriesList.add(s);
}
}
}
@Override
public ComponentRenderer getHTMLRendererSingleton() {
return renderer;
}
}
| 412 | 0.585446 | 1 | 0.585446 | game-dev | MEDIA | 0.774703 | game-dev | 0.76815 | 1 | 0.76815 |
freeorion/freeorion | 11,794 | default/scripting/buildings/EXPERIMENTOR_OUTPOST.focs.py | from buildings.buildings_macros import CAN_ADD_STARLANE_TO_SOURCE
from focs._effects import (
AddStarlanes,
AnyEmpire,
ContainedBy,
Contains,
CreateShip,
Destroy,
DirectDistanceBetween,
EffectsGroup,
GalaxyMaxAIAggression,
GalaxyPlanetDensity,
GalaxySize,
GameRule,
GenerateSitRepMessage,
HasDesign,
HasSpecies,
InSystem,
IsAnyObject,
IsSource,
LocalCandidate,
MaxOf,
MinimumNumberOf,
Monster,
NumberOf,
Object,
OwnedBy,
Planet,
Random,
RemoveStarlanes,
SetDefense,
SetDetection,
SetMaxDefense,
SetMaxShield,
SetMaxTroops,
SetShield,
SetStealth,
Ship,
Source,
System,
Turn,
Unowned,
Value,
Victory,
WithinStarlaneJumps,
)
from macros.misc import PLANET_DEFENSE_FACTOR, PLANET_SHIELD_FACTOR
try:
from focs._buildings import *
except ModuleNotFoundError:
pass
# the highest current MaxAIAggression is 5, so this would range from 0.2 to 1.2
EXPERIMENTOR_MONSTER_FREQ_FACTOR: float = (1 + GalaxyMaxAIAggression) / 5.0
EXPERIMENTOR_SPAWN_BASE_TURN: int = GameRule(type=int, name="RULE_EXPERIMENTORS_SPAWN_BASE_TURN")
EXPERIMENTOR_SPAWN_AI_AGGRESSION_CHECK: bool = GalaxyMaxAIAggression <= 2
# the following intermediate value is turn 200 for Manaical Max AI Aggression, and 50 turns later for each aggression tier less,
# for AI aggressions above Typical, otherwise adding 1000 turns
EXPERIMENTOR_SPAWN_CALC_A: int = (
EXPERIMENTOR_SPAWN_BASE_TURN + 50 * (5 - GalaxyMaxAIAggression) + 1000 * EXPERIMENTOR_SPAWN_AI_AGGRESSION_CHECK
)
# the following modifies Experimentor spawn start by a factor of 0.1 up for low planet density, and 0.1 down for high planet density
# for galaxy sizes above 200 increases it somewhat as the galaxy size grows
EXPERIMENTOR_SPAWN_START_TURN = (
EXPERIMENTOR_SPAWN_CALC_A * (1.2 - GalaxyPlanetDensity / 10) * (MaxOf(float, 1, GalaxySize / 200)) ** 0.4
)
# of the 5 closest systems to which a lane could be added, pick one
EXPERIMENTOR_ADD_STARLANE = AddStarlanes(
endpoint=NumberOf(
number=1,
condition=MinimumNumberOf(
number=5,
sortkey=DirectDistanceBetween(Source.ID, LocalCandidate.ID),
condition=System & ~Contains(IsSource),
)
& CAN_ADD_STARLANE_TO_SOURCE,
),
)
BuildingType( # type: ignore[reportUnboundVariable]
name="BLD_EXPERIMENTOR_OUTPOST",
description="BLD_EXPERIMENTOR_OUTPOST_DESC",
buildcost=1,
buildtime=1,
location=IsAnyObject,
effectsgroups=[
EffectsGroup(
scope=IsSource | (Object(id=Source.PlanetID) & Planet()),
effects=[SetStealth(value=Value + 60)],
),
EffectsGroup(
scope=(Object(id=Source.SystemID) | (InSystem(id=Source.SystemID) & Planet() & ~IsSource)),
effects=[SetStealth(value=Value + 40)],
),
EffectsGroup(
scope=Object(id=Source.PlanetID),
effects=[
SetMaxShield(value=Value + (60000 * PLANET_SHIELD_FACTOR)),
SetMaxDefense(value=Value + (EXPERIMENTOR_SPAWN_START_TURN * PLANET_DEFENSE_FACTOR)),
SetMaxTroops(value=Value + 300),
SetDetection(value=Value + 100),
],
),
EffectsGroup(
scope=Object(id=Source.PlanetID),
activation=(~ContainedBy(Contains(Ship & OwnedBy(affiliation=AnyEmpire)))),
effects=[
# Regeneration
SetDefense(value=Value + (10 * PLANET_DEFENSE_FACTOR)),
SetShield(value=Value + (50 * PLANET_SHIELD_FACTOR)),
],
),
EffectsGroup(
scope=(IsSource & OwnedBy(affiliation=AnyEmpire) & HasSpecies(name=["SP_EXPERIMENTOR"])),
effects=[
Victory(reason="VICTORY_EXPERIMENTOR_CAPTURE"),
EXPERIMENTOR_ADD_STARLANE,
EXPERIMENTOR_ADD_STARLANE,
EXPERIMENTOR_ADD_STARLANE,
EXPERIMENTOR_ADD_STARLANE,
EXPERIMENTOR_ADD_STARLANE,
Destroy,
],
),
EffectsGroup(
scope=IsSource & ~OwnedBy(affiliation=AnyEmpire),
activation=(
# always remove lanes before spawn start turn
Turn(high=EXPERIMENTOR_SPAWN_START_TURN)
| ~ContainedBy(Contains(Monster & Unowned & ~HasDesign(name="SM_EXP_OUTPOST")))
),
effects=[RemoveStarlanes(endpoint=WithinStarlaneJumps(jumps=1, condition=IsSource))],
),
EffectsGroup(
scope=IsSource,
activation=(
Turn(low=(EXPERIMENTOR_SPAWN_START_TURN), high=(EXPERIMENTOR_SPAWN_START_TURN + 35))
& Random(probability=(0.2 * EXPERIMENTOR_MONSTER_FREQ_FACTOR))
),
effects=[
CreateShip(designname="SM_BLACK_KRAKEN", empire=Source.Owner),
CreateShip(designname="SM_BLACK_KRAKEN", empire=Source.Owner),
GenerateSitRepMessage(
message="EFFECT_EXPERIMENT_MONSTERS_LAUNCH",
label="EFFECT_EXPERIMENT_MONSTERS_LAUNCH_LABEL",
icon="icons/specials_huge/ancient_ruins.png",
parameters={
"system": Source.SystemID,
"predefinedshipdesign": "SM_BLACK_KRAKEN",
"species": "SP_EXPERIMENTOR",
"rawtext": "2",
},
),
EXPERIMENTOR_ADD_STARLANE,
],
),
EffectsGroup(
scope=IsSource,
activation=(
Turn(low=(EXPERIMENTOR_SPAWN_START_TURN + 36))
& Random(probability=(0.1 * EXPERIMENTOR_MONSTER_FREQ_FACTOR))
),
effects=[
CreateShip(designname="SM_BLACK_KRAKEN", empire=Source.Owner),
CreateShip(designname="SM_BLACK_KRAKEN", empire=Source.Owner),
GenerateSitRepMessage(
message="EFFECT_EXPERIMENT_MONSTERS_LAUNCH",
label="EFFECT_EXPERIMENT_MONSTERS_LAUNCH_LABEL",
icon="icons/specials_huge/ancient_ruins.png",
parameters={
"system": Source.SystemID,
"predefinedshipdesign": "SM_BLACK_KRAKEN",
"species": "SP_EXPERIMENTOR",
"rawtext": "2",
},
),
EXPERIMENTOR_ADD_STARLANE,
],
),
EffectsGroup(
scope=IsSource,
activation=(
Turn(low=EXPERIMENTOR_SPAWN_START_TURN + 36, high=EXPERIMENTOR_SPAWN_START_TURN + 70)
& Random(probability=0.2 * EXPERIMENTOR_MONSTER_FREQ_FACTOR)
),
effects=[
CreateShip(designname="SM_BLOATED_JUGGERNAUT", empire=Source.Owner),
CreateShip(designname="SM_BLOATED_JUGGERNAUT", empire=Source.Owner),
GenerateSitRepMessage(
message="EFFECT_EXPERIMENT_MONSTERS_LAUNCH",
label="EFFECT_EXPERIMENT_MONSTERS_LAUNCH_LABEL",
icon="icons/specials_huge/ancient_ruins.png",
parameters={
"system": Source.SystemID,
"predefinedshipdesign": "SM_BLOATED_JUGGERNAUT",
"species": "SP_EXPERIMENTOR",
"rawtext": "2",
},
),
EXPERIMENTOR_ADD_STARLANE,
],
),
EffectsGroup(
scope=IsSource,
activation=(
Turn(low=EXPERIMENTOR_SPAWN_START_TURN + 71)
& Random(probability=0.1 * EXPERIMENTOR_MONSTER_FREQ_FACTOR)
),
effects=[
CreateShip(designname="SM_BLOATED_JUGGERNAUT", empire=Source.Owner),
CreateShip(designname="SM_BLOATED_JUGGERNAUT", empire=Source.Owner),
GenerateSitRepMessage(
message="EFFECT_EXPERIMENT_MONSTERS_LAUNCH",
label="EFFECT_EXPERIMENT_MONSTERS_LAUNCH_LABEL",
icon="icons/specials_huge/ancient_ruins.png",
parameters={
"system": Source.SystemID,
"predefinedshipdesign": "SM_BLOATED_JUGGERNAUT",
"species": "SP_EXPERIMENTOR",
"rawtext": "2",
},
),
EXPERIMENTOR_ADD_STARLANE,
],
),
EffectsGroup(
scope=IsSource,
activation=(
Turn(low=(EXPERIMENTOR_SPAWN_START_TURN + 71), high=(EXPERIMENTOR_SPAWN_START_TURN + 130))
& Random(probability=(0.2 * EXPERIMENTOR_MONSTER_FREQ_FACTOR))
),
effects=[
CreateShip(designname="SM_PSIONIC_SNOWFLAKE", empire=Source.Owner),
CreateShip(designname="SM_PSIONIC_SNOWFLAKE", empire=Source.Owner),
GenerateSitRepMessage(
message="EFFECT_EXPERIMENT_MONSTERS_LAUNCH",
label="EFFECT_EXPERIMENT_MONSTERS_LAUNCH_LABEL",
icon="icons/specials_huge/ancient_ruins.png",
parameters={
"system": Source.SystemID,
"predefinedshipdesign": "SM_PSIONIC_SNOWFLAKE",
"species": "SP_EXPERIMENTOR",
"rawtext": "2",
},
),
EXPERIMENTOR_ADD_STARLANE,
],
),
EffectsGroup(
scope=IsSource,
activation=(
Turn(low=EXPERIMENTOR_SPAWN_START_TURN + 131)
& Random(probability=0.1 * EXPERIMENTOR_MONSTER_FREQ_FACTOR)
),
effects=[
CreateShip(designname="SM_PSIONIC_SNOWFLAKE", empire=Source.Owner),
CreateShip(designname="SM_PSIONIC_SNOWFLAKE", empire=Source.Owner),
GenerateSitRepMessage(
message="EFFECT_EXPERIMENT_MONSTERS_LAUNCH",
label="EFFECT_EXPERIMENT_MONSTERS_LAUNCH_LABEL",
icon="icons/specials_huge/ancient_ruins.png",
parameters={
"system": Source.SystemID,
"predefinedshipdesign": "SM_PSIONIC_SNOWFLAKE",
"species": "SP_EXPERIMENTOR",
"rawtext": "2",
},
),
EXPERIMENTOR_ADD_STARLANE,
],
),
EffectsGroup(
scope=IsSource,
activation=(
Turn(low=(EXPERIMENTOR_SPAWN_START_TURN + 131))
& Random(probability=(0.2 * EXPERIMENTOR_MONSTER_FREQ_FACTOR))
),
effects=[
CreateShip(designname="SM_COSMIC_DRAGON", empire=Source.Owner),
GenerateSitRepMessage(
message="EFFECT_EXPERIMENT_MONSTERS_LAUNCH",
label="EFFECT_EXPERIMENT_MONSTERS_LAUNCH_LABEL",
icon="icons/specials_huge/ancient_ruins.png",
parameters={
"system": Source.SystemID,
"predefinedshipdesign": "SM_COSMIC_DRAGON",
"species": "SP_EXPERIMENTOR",
"rawtext": "1",
},
),
EXPERIMENTOR_ADD_STARLANE,
],
),
],
icon="",
)
| 412 | 0.79797 | 1 | 0.79797 | game-dev | MEDIA | 0.992272 | game-dev | 0.760994 | 1 | 0.760994 |
mastercomfig/tf2-patches-old | 20,061 | src/public/shaderlib/cshader.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef CSHADER_H
#define CSHADER_H
#ifdef _WIN32
#pragma once
#endif
// uncomment this if you want to build for nv3x
//#define NV3X 1
// This is what all shaders include.
// CBaseShader will become CShader in this file.
#include "materialsystem/ishaderapi.h"
#include "utlvector.h"
#include "materialsystem/imaterialvar.h"
#include "materialsystem/imaterial.h"
#include "BaseShader.h"
#include "materialsystem/itexture.h"
// Included for convenience because they are used in a bunch of shaders
#include "materialsystem/imesh.h"
#include "materialsystem/imaterialsystemhardwareconfig.h"
#include "materialsystem/materialsystem_config.h"
#include "shaderlib/ShaderDLL.h"
// make "local variable is initialized but not referenced" warnings errors for combo checking macros
#pragma warning ( error : 4189 )
//-----------------------------------------------------------------------------
// Global interfaces
//-----------------------------------------------------------------------------
extern IMaterialSystemHardwareConfig *g_pHardwareConfig;
extern const MaterialSystem_Config_t *g_pConfig;
extern bool g_shaderConfigDumpEnable;
// Helper method
bool IsUsingGraphics();
#define SOFTWARE_VERTEX_SHADER(name) \
static void SoftwareVertexShader_ ## name( CMeshBuilder &meshBuilder, IMaterialVar **params, IShaderDynamicAPI* pShaderAPI )
#define FORWARD_DECLARE_SOFTWARE_VERTEX_SHADER(name)\
static void SoftwareVertexShader_ ## name( CMeshBuilder &meshBuilder, IMaterialVar **params, IShaderDynamicAPI* pShaderAPI );
#define USE_SOFTWARE_VERTEX_SHADER(name) \
m_SoftwareVertexShader = SoftwareVertexShader_ ## name
#define SHADER_INIT_PARAMS() \
virtual void OnInitShaderParams( IMaterialVar **params, const char *pMaterialName )
#define SHADER_FALLBACK \
virtual char const* GetFallbackShader( IMaterialVar** params ) const
// Typesafe flag setting
inline void CShader_SetFlags( IMaterialVar **params, MaterialVarFlags_t _flag )
{
params[FLAGS]->SetIntValue( params[FLAGS]->GetIntValue() | (_flag) );
}
inline bool CShader_IsFlagSet( IMaterialVar **params, MaterialVarFlags_t _flag )
{
return ((params[FLAGS]->GetIntValue() & (_flag) ) != 0);
}
#define SET_FLAGS( _flag ) CShader_SetFlags( params, _flag )
#define CLEAR_FLAGS( _flag ) params[FLAGS]->SetIntValue( params[FLAGS]->GetIntValue() & ~(_flag) )
#define IS_FLAG_SET( _flag ) CShader_IsFlagSet( params, _flag )
#define IS_FLAG_DEFINED( _flag ) ((params[FLAGS_DEFINED]->GetIntValue() & (_flag) ) != 0)
#define IS_PARAM_DEFINED( _param ) ( ( ( _param >= 0 ) && ( params[_param]->IsDefined() ) ) )
#define SET_PARAM_STRING_IF_NOT_DEFINED( nParamIndex, kDefaultValue ) \
if ( ( nParamIndex != -1 ) && ( !params[nParamIndex]->IsDefined() ) ) \
{ \
params[nParamIndex]->SetStringValue( kDefaultValue ); \
}
#define SET_PARAM_INT_IF_NOT_DEFINED( nParamIndex, kDefaultValue ) \
if ( ( nParamIndex != -1 ) && ( !params[nParamIndex]->IsDefined() ) ) \
{ \
params[nParamIndex]->SetIntValue( kDefaultValue ); \
}
#define SET_PARAM_FLOAT_IF_NOT_DEFINED( nParamIndex, kDefaultValue ) \
if ( ( nParamIndex != -1 ) && ( !params[nParamIndex]->IsDefined() ) ) \
{ \
params[nParamIndex]->SetFloatValue( kDefaultValue ); \
}
#define SET_PARAM_VEC_IF_NOT_DEFINED( nParamIndex, kDefaultValue, nSize ) \
if ( ( nParamIndex != -1 ) && ( !params[nParamIndex]->IsDefined() ) ) \
{ \
params[nParamIndex]->SetVecValue( kDefaultValue, nSize ); \
}
// Typesafe flag setting
inline void CShader_SetFlags2( IMaterialVar **params, MaterialVarFlags2_t _flag )
{
params[FLAGS2]->SetIntValue( params[FLAGS2]->GetIntValue() | (_flag) );
}
inline bool CShader_IsFlag2Set( IMaterialVar **params, MaterialVarFlags2_t _flag )
{
return ((params[FLAGS2]->GetIntValue() & (_flag) ) != 0);
}
#define SET_FLAGS2( _flag ) CShader_SetFlags2( params, _flag )
#define CLEAR_FLAGS2( _flag ) params[FLAGS2]->SetIntValue( params[FLAGS2]->GetIntValue() & ~(_flag) )
#define IS_FLAG2_SET( _flag ) CShader_IsFlag2Set( params, _flag )
#define IS_FLAG2_DEFINED( _flag ) ((params[FLAGS_DEFINED2]->GetIntValue() & (_flag) ) != 0)
#define __BEGIN_SHADER_INTERNAL(_baseclass, name, help, flags) \
namespace name \
{\
typedef _baseclass CBaseClass;\
static const char *s_HelpString = help; \
static const char *s_Name = #name; \
static int s_nFlags = flags; \
class CShaderParam;\
static CUtlVector<CShaderParam *> s_ShaderParams;\
static CShaderParam *s_pShaderParamOverrides[NUM_SHADER_MATERIAL_VARS];\
class CShaderParam\
{\
public:\
CShaderParam( ShaderMaterialVars_t var, ShaderParamType_t type, const char *pDefaultParam, const char *pHelp, int nFlags )\
{\
m_Info.m_pName = "override";\
m_Info.m_Type = type;\
m_Info.m_pDefaultValue = pDefaultParam;\
m_Info.m_pHelp = pHelp;\
m_Info.m_nFlags = nFlags;\
AssertMsg( !s_pShaderParamOverrides[var], ( "Shader parameter override duplicately defined!" ) );\
s_pShaderParamOverrides[var] = this;\
m_Index = var;\
}\
CShaderParam( const char *pName, ShaderParamType_t type, const char *pDefaultParam, const char *pHelp, int nFlags )\
{\
m_Info.m_pName = pName;\
m_Info.m_Type = type;\
m_Info.m_pDefaultValue = pDefaultParam;\
m_Info.m_pHelp = pHelp;\
m_Info.m_nFlags = nFlags;\
m_Index = NUM_SHADER_MATERIAL_VARS + s_ShaderParams.Count();\
s_ShaderParams.AddToTail( this );\
}\
operator int() \
{\
return m_Index;\
}\
const char *GetName()\
{\
return m_Info.m_pName;\
}\
ShaderParamType_t GetType()\
{\
return m_Info.m_Type;\
}\
const char *GetDefault()\
{\
return m_Info.m_pDefaultValue;\
}\
int GetFlags() const\
{\
return m_Info.m_nFlags;\
}\
const char *GetHelp()\
{\
return m_Info.m_pHelp;\
}\
private:\
ShaderParamInfo_t m_Info; \
int m_Index;\
};\
#define BEGIN_SHADER(name,help) __BEGIN_SHADER_INTERNAL( CBaseShader, name, help, 0 )
#define BEGIN_SHADER_FLAGS(name,help,flags) __BEGIN_SHADER_INTERNAL( CBaseShader, name, help, flags )
#define BEGIN_SHADER_PARAMS
#define SHADER_PARAM( param, paramtype, paramdefault, paramhelp ) \
static CShaderParam param( "$" #param, paramtype, paramdefault, paramhelp, 0 );
#define SHADER_PARAM_FLAGS( param, paramtype, paramdefault, paramhelp, flags ) \
static CShaderParam param( "$" #param, paramtype, paramdefault, paramhelp, flags );
#define SHADER_PARAM_OVERRIDE( param, paramtype, paramdefault, paramhelp, flags ) \
static CShaderParam param( (ShaderMaterialVars_t) ::param, paramtype, paramdefault, paramhelp, flags );
// regarding the macro above: the "::" was added to the first argument in order to disambiguate it for GCC.
// for example, in cloak.cpp, this usage appears:
// SHADER_PARAM_OVERRIDE( COLOR, SHADER_PARAM_TYPE_COLOR, "{255 255 255}", "unused", SHADER_PARAM_NOT_EDITABLE )
// which in turn tries to ask the compiler to instantiate an object like so:
// static CShaderParam COLOR( (ShaderMaterialVars_t)COLOR, SHADER_PARAM_TYPE_COLOR, "{255 255 255}", "unused", SHADER_PARAM_NOT_EDITABLE )
// and GCC thinks that the reference to COLOR in the arg list is actually a reference to the object we're in the middle of making.
// and you get --> error: invalid cast from type βCloak_DX90::CShaderParamβ to type βShaderMaterialVars_tβ
// Resolved: add the "::" so compiler knows that reference is to the enum, not to the name of the object being made.
#define END_SHADER_PARAMS \
class CShader : public CBaseClass\
{\
public:
#define END_SHADER }; \
static CShader s_ShaderInstance;\
} // namespace
#define SHADER_INIT \
char const* GetName() const \
{ \
return s_Name; \
} \
int GetFlags() const \
{ \
return s_nFlags; \
} \
int GetNumParams() const \
{\
return CBaseClass::GetNumParams() + s_ShaderParams.Count();\
}\
char const* GetParamName( int param ) const \
{\
int nBaseClassParamCount = CBaseClass::GetNumParams(); \
if (param < nBaseClassParamCount) \
return CBaseClass::GetParamName(param); \
else \
return s_ShaderParams[param - nBaseClassParamCount]->GetName(); \
}\
char const* GetParamHelp( int param ) const \
{\
int nBaseClassParamCount = CBaseClass::GetNumParams(); \
if (param < nBaseClassParamCount) \
{ \
if ( !s_pShaderParamOverrides[param] ) \
return CBaseClass::GetParamHelp( param ); \
else \
return s_pShaderParamOverrides[param]->GetHelp(); \
} \
else \
return s_ShaderParams[param - nBaseClassParamCount]->GetHelp(); \
}\
ShaderParamType_t GetParamType( int param ) const \
{\
int nBaseClassParamCount = CBaseClass::GetNumParams(); \
if (param < nBaseClassParamCount) \
return CBaseClass::GetParamType( param ); \
else \
return s_ShaderParams[param - nBaseClassParamCount]->GetType(); \
}\
char const* GetParamDefault( int param ) const \
{\
int nBaseClassParamCount = CBaseClass::GetNumParams(); \
if (param < nBaseClassParamCount) \
{ \
if ( !s_pShaderParamOverrides[param] ) \
return CBaseClass::GetParamDefault( param ); \
else \
return s_pShaderParamOverrides[param]->GetDefault(); \
} \
else \
return s_ShaderParams[param - nBaseClassParamCount]->GetDefault(); \
}\
int GetParamFlags( int param ) const \
{\
int nBaseClassParamCount = CBaseClass::GetNumParams(); \
if (param < nBaseClassParamCount) \
{ \
if ( !s_pShaderParamOverrides[param] ) \
return CBaseClass::GetParamFlags( param ); \
else \
return s_pShaderParamOverrides[param]->GetFlags(); \
} \
else \
return s_ShaderParams[param - nBaseClassParamCount]->GetFlags(); \
}\
void OnInitShaderInstance( IMaterialVar **params, IShaderInit *pShaderInit, const char *pMaterialName )
#define SHADER_DRAW \
void OnDrawElements( IMaterialVar **params, IShaderShadow* pShaderShadow, IShaderDynamicAPI* pShaderAPI, VertexCompressionType_t vertexCompression, CBasePerMaterialContextData **pContextDataPtr )
#define SHADOW_STATE if (pShaderShadow)
#define DYNAMIC_STATE if (pShaderAPI)
#define ShaderWarning if (pShaderShadow) Warning
//-----------------------------------------------------------------------------
// Used to easily define a shader which *always* falls back
//-----------------------------------------------------------------------------
#define DEFINE_FALLBACK_SHADER( _shadername, _fallbackshadername ) \
BEGIN_SHADER( _shadername, "" ) \
BEGIN_SHADER_PARAMS \
END_SHADER_PARAMS \
SHADER_FALLBACK { return #_fallbackshadername; } \
SHADER_INIT {} \
SHADER_DRAW {} \
END_SHADER
//-----------------------------------------------------------------------------
// Used to easily define a shader which inherits from another shader
//-----------------------------------------------------------------------------
// FIXME: There's a compiler bug preventing this from working.
// Maybe it'll work under VC7!
/*
//#define BEGIN_INHERITED_SHADER( name, _baseclass, help ) \
// namespace _baseclass \
// {\
// __BEGIN_SHADER_INTERNAL( _baseclass::CShader, name, help )
*/
//#define END_INHERITED_SHADER END_SHADER }
//#define CHAIN_SHADER_INIT_PARAMS() CBaseClass::OnInitShaderParams( params, pMaterialName )
//#define CHAIN_SHADER_FALLBACK() CBaseClass::GetFallbackShader( params )
//#define CHAIN_SHADER_INIT() CBaseClass::OnInitShaderInstance( params, pShaderInit, pMaterialName )
//#define CHAIN_SHADER_DRAW() CBaseClass::OnDrawElements( params, pShaderShadow, pShaderAPI )
// A dumbed-down version which does what I need now which works
// This version doesn't allow you to do chain *anything* down to the base class
#define BEGIN_INHERITED_SHADER_FLAGS( _name, _base, _help, _flags ) \
namespace _base\
{\
namespace _name\
{\
static const char *s_Name = #_name; \
static const char *s_HelpString = _help;\
static int s_nFlags = _flags;\
class CShader : public _base::CShader\
{\
public:\
char const* GetName() const \
{ \
return s_Name; \
} \
int GetFlags() const \
{ \
return s_nFlags; \
}
#define BEGIN_INHERITED_SHADER( _name, _base, _help ) BEGIN_INHERITED_SHADER_FLAGS( _name, _base, _help, 0 )
#define END_INHERITED_SHADER END_SHADER }
// psh ## shader is used here to generate a warning if you don't ever call SET_DYNAMIC_PIXEL_SHADER
#define DECLARE_DYNAMIC_PIXEL_SHADER( shader ) \
int declaredynpixshader_ ## shader ## _missingcurlybraces = 0; \
NOTE_UNUSED( declaredynpixshader_ ## shader ## _missingcurlybraces ); \
shader ## _Dynamic_Index _pshIndex; \
int psh ## shader = 0
// vsh ## shader is used here to generate a warning if you don't ever call SET_DYNAMIC_VERTEX_SHADER
#define DECLARE_DYNAMIC_VERTEX_SHADER( shader ) \
int declaredynvertshader_ ## shader ## _missingcurlybraces = 0; \
NOTE_UNUSED( declaredynvertshader_ ## shader ## _missingcurlybraces ); \
shader ## _Dynamic_Index _vshIndex; \
int vsh ## shader = 0
// psh ## shader is used here to generate a warning if you don't ever call SET_STATIC_PIXEL_SHADER
#define DECLARE_STATIC_PIXEL_SHADER( shader ) \
int declarestaticpixshader_ ## shader ## _missingcurlybraces = 0; \
NOTE_UNUSED( declarestaticpixshader_ ## shader ## _missingcurlybraces ); \
shader ## _Static_Index _pshIndex; \
int psh ## shader = 0
// vsh ## shader is used here to generate a warning if you don't ever call SET_STATIC_VERTEX_SHADER
#define DECLARE_STATIC_VERTEX_SHADER( shader ) \
int declarestaticvertshader_ ## shader ## _missingcurlybraces = 0; \
NOTE_UNUSED( declarestaticvertshader_ ## shader ## _missingcurlybraces ); \
shader ## _Static_Index _vshIndex; \
int vsh ## shader = 0
// psh_forgot_to_set_dynamic_ ## var is used to make sure that you set all
// all combos. If you don't, you will get an undefined variable used error
// in the SET_DYNAMIC_PIXEL_SHADER block.
#define SET_DYNAMIC_PIXEL_SHADER_COMBO( var, val ) \
int dynpixshadercombo_ ## var ## _missingcurlybraces = 0; \
NOTE_UNUSED( dynpixshadercombo_ ## var ## _missingcurlybraces ); \
_pshIndex.Set ## var( ( val ) ); if(g_shaderConfigDumpEnable){printf("\n PS dyn var %s = %d (%s)", #var, (int) val, #val );}; \
int psh_forgot_to_set_dynamic_ ## var = 0
// vsh_forgot_to_set_dynamic_ ## var is used to make sure that you set all
// all combos. If you don't, you will get an undefined variable used error
// in the SET_DYNAMIC_VERTEX_SHADER block.
#define SET_DYNAMIC_VERTEX_SHADER_COMBO( var, val ) \
int dynvertshadercombo_ ## var ## _missingcurlybraces = 0; \
NOTE_UNUSED( dynvertshadercombo_ ## var ## _missingcurlybraces ); \
_vshIndex.Set ## var( ( val ) ); if(g_shaderConfigDumpEnable){printf("\n VS dyn var %s = %d (%s)", #var, (int) val, #val );}; \
int vsh_forgot_to_set_dynamic_ ## var = 0
// psh_forgot_to_set_static_ ## var is used to make sure that you set all
// all combos. If you don't, you will get an undefined variable used error
// in the SET_STATIC_PIXEL_SHADER block.
#define SET_STATIC_PIXEL_SHADER_COMBO( var, val ) \
int staticpixshadercombo_ ## var ## _missingcurlybraces = 0; \
NOTE_UNUSED( staticpixshadercombo_ ## var ## _missingcurlybraces ); \
_pshIndex.Set ## var( ( val ) ); if(g_shaderConfigDumpEnable){printf("\n PS stat var %s = %d (%s)", #var, (int) val, #val );}; \
int psh_forgot_to_set_static_ ## var = 0
// vsh_forgot_to_set_static_ ## var is used to make sure that you set all
// all combos. If you don't, you will get an undefined variable used error
// in the SET_STATIC_VERTEX_SHADER block.
#define SET_STATIC_VERTEX_SHADER_COMBO( var, val ) \
int staticvertshadercombo_ ## var ## _missingcurlybraces = 0; \
NOTE_UNUSED( staticvertshadercombo_ ## var ## _missingcurlybraces ); \
_vshIndex.Set ## var( ( val ) ); if(g_shaderConfigDumpEnable){printf("\n VS stat var %s = %d (%s)", #var, (int) val, #val );}; \
int vsh_forgot_to_set_static_ ## var = 0
// psh_testAllCombos adds up all of the psh_forgot_to_set_dynamic_ ## var's from
// SET_DYNAMIC_PIXEL_SHADER_COMBO so that an error is generated if they aren't set.
// psh_testAllCombos is set to itself to avoid an unused variable warning.
// psh ## shader being set to itself ensures that DECLARE_DYNAMIC_PIXEL_SHADER
// was called for this particular shader.
#define SET_DYNAMIC_PIXEL_SHADER( shader ) \
int dynamicpixshader_ ## shader ## _missingcurlybraces = 0; \
NOTE_UNUSED( dynamicpixshader_ ## shader ## _missingcurlybraces ); \
int psh_testAllCombos = shaderDynamicTest_ ## shader; \
NOTE_UNUSED( psh_testAllCombos ); \
NOTE_UNUSED( psh ## shader ); \
pShaderAPI->SetPixelShaderIndex( _pshIndex.GetIndex() )
#define SET_DYNAMIC_PIXEL_SHADER_CMD( cmdstream, shader ) \
int dynamicpixshader_ ## shader ## _missingcurlybraces = 0; \
NOTE_UNUSED( dynamicpixshader_ ## shader ## _missingcurlybraces ); \
int psh_testAllCombos = shaderDynamicTest_ ## shader; \
NOTE_UNUSED( psh_testAllCombos ); \
NOTE_UNUSED( psh ## shader ); \
cmdstream.SetPixelShaderIndex( _pshIndex.GetIndex() )
// vsh_testAllCombos adds up all of the vsh_forgot_to_set_dynamic_ ## var's from
// SET_DYNAMIC_VERTEX_SHADER_COMBO so that an error is generated if they aren't set.
// vsh_testAllCombos is set to itself to avoid an unused variable warning.
// vsh ## shader being set to itself ensures that DECLARE_DYNAMIC_VERTEX_SHADER
// was called for this particular shader.
#define SET_DYNAMIC_VERTEX_SHADER( shader ) \
int dynamicvertshader_ ## shader ## _missingcurlybraces = 0; \
NOTE_UNUSED( dynamicvertshader_ ## shader ## _missingcurlybraces ); \
int vsh_testAllCombos = shaderDynamicTest_ ## shader; \
NOTE_UNUSED( vsh_testAllCombos ); \
NOTE_UNUSED( vsh ## shader ); \
pShaderAPI->SetVertexShaderIndex( _vshIndex.GetIndex() )
#define SET_DYNAMIC_VERTEX_SHADER_CMD( cmdstream, shader ) \
int dynamicvertshader_ ## shader ## _missingcurlybraces = 0; \
NOTE_UNUSED( dynamicvertshader_ ## shader ## _missingcurlybraces ); \
int vsh_testAllCombos = shaderDynamicTest_ ## shader; \
NOTE_UNUSED( vsh_testAllCombos ); \
NOTE_UNUSED( vsh ## shader ); \
cmdstream.SetVertexShaderIndex( _vshIndex.GetIndex() )
// psh_testAllCombos adds up all of the psh_forgot_to_set_static_ ## var's from
// SET_STATIC_PIXEL_SHADER_COMBO so that an error is generated if they aren't set.
// psh_testAllCombos is set to itself to avoid an unused variable warning.
// psh ## shader being set to itself ensures that DECLARE_STATIC_PIXEL_SHADER
// was called for this particular shader.
#define SET_STATIC_PIXEL_SHADER( shader ) \
int staticpixshader_ ## shader ## _missingcurlybraces = 0; \
NOTE_UNUSED( staticpixshader_ ## shader ## _missingcurlybraces ); \
int psh_testAllCombos = shaderStaticTest_ ## shader; \
NOTE_UNUSED( psh_testAllCombos ); \
NOTE_UNUSED( psh ## shader ); \
pShaderShadow->SetPixelShader( #shader, _pshIndex.GetIndex() )
// vsh_testAllCombos adds up all of the vsh_forgot_to_set_static_ ## var's from
// SET_STATIC_VERTEX_SHADER_COMBO so that an error is generated if they aren't set.
// vsh_testAllCombos is set to itself to avoid an unused variable warning.
// vsh ## shader being set to itself ensures that DECLARE_STATIC_VERTEX_SHADER
// was called for this particular shader.
#define SET_STATIC_VERTEX_SHADER( shader ) \
int staticvertshader_ ## shader ## _missingcurlybraces = 0; \
NOTE_UNUSED( staticvertshader_ ## shader ## _missingcurlybraces ); \
int vsh_testAllCombos = shaderStaticTest_ ## shader; \
NOTE_UNUSED( vsh_testAllCombos ); \
NOTE_UNUSED( vsh ## shader ); \
pShaderShadow->SetVertexShader( #shader, _vshIndex.GetIndex() )
#endif // CSHADER_H
| 412 | 0.878083 | 1 | 0.878083 | game-dev | MEDIA | 0.53091 | game-dev | 0.767273 | 1 | 0.767273 |
FrozenBlock/WilderWild | 9,599 | src/main/java/net/frozenblock/wilderwild/datagen/advancement/WWAdvancementProvider.java | /*
* Copyright 2025 FrozenBlock
* This file is part of Wilder Wild.
*
* This program is free software; you can modify it under
* the terms of version 1 of the FrozenBlock Modding Oasis License
* as published by FrozenBlock Modding Oasis.
*
* 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
* FrozenBlock Modding Oasis License for more details.
*
* You should have received a copy of the FrozenBlock Modding Oasis License
* along with this program; if not, see <https://github.com/FrozenBlock/Licenses>.
*/
package net.frozenblock.wilderwild.datagen.advancement;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput;
import net.fabricmc.fabric.api.datagen.v1.provider.FabricAdvancementProvider;
import net.frozenblock.wilderwild.WWConstants;
import net.frozenblock.wilderwild.advancement.FragileIceFallOntoAndBreakTrigger;
import net.frozenblock.wilderwild.advancement.GeyserPushMobTrigger;
import net.frozenblock.wilderwild.advancement.MobBottleTrigger;
import net.frozenblock.wilderwild.advancement.TermiteEatTrigger;
import net.frozenblock.wilderwild.block.state.properties.GeyserType;
import net.frozenblock.wilderwild.registry.WWBlocks;
import net.frozenblock.wilderwild.registry.WWEntityTypes;
import net.frozenblock.wilderwild.registry.WWItems;
import net.minecraft.advancements.Advancement;
import net.minecraft.advancements.AdvancementHolder;
import net.minecraft.advancements.AdvancementType;
import net.minecraft.advancements.critereon.BlockPredicate;
import net.minecraft.advancements.critereon.EntityFlagsPredicate;
import net.minecraft.advancements.critereon.EntityPredicate;
import net.minecraft.advancements.critereon.EntityTypePredicate;
import net.minecraft.advancements.critereon.FilledBucketTrigger;
import net.minecraft.advancements.critereon.InventoryChangeTrigger;
import net.minecraft.advancements.critereon.ItemPredicate;
import net.minecraft.advancements.critereon.MinMaxBounds;
import net.minecraft.advancements.critereon.MovementPredicate;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderSet;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.tags.BlockTags;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.item.Items;
public final class WWAdvancementProvider extends FabricAdvancementProvider {
public WWAdvancementProvider(FabricDataOutput output, CompletableFuture<HolderLookup.Provider> registries) {
super(output, registries);
}
@Override
public void generateAdvancement(HolderLookup.Provider registries, Consumer<AdvancementHolder> writer) {
AdvancementHolder adventure = Advancement.Builder.advancement().build(WWConstants.vanillaId("adventure/root"));
AdvancementHolder husbandry = Advancement.Builder.advancement().build(WWConstants.vanillaId("husbandry/root"));
HolderLookup.RegistryLookup<EntityType<?>> entityTypeRegistryLookup = registries.lookupOrThrow(Registries.ENTITY_TYPE);
Advancement.Builder.advancement()
.parent(husbandry)
.display(
WWItems.CRAB_BUCKET,
Component.translatable("wilderwild.advancements.husbandry.crab_in_a_bucket.title"),
Component.translatable("wilderwild.advancements.husbandry.crab_in_a_bucket.description"),
null,
AdvancementType.TASK,
true,
true,
false
)
.addCriterion("crab_bucket", FilledBucketTrigger.TriggerInstance.filledBucket(ItemPredicate.Builder.item().of(WWItems.CRAB_BUCKET)))
.save(writer, WWConstants.string("husbandry/crab_in_a_bucket"));
Advancement.Builder.advancement()
.parent(husbandry)
.display(
WWItems.FIREFLY_BOTTLE,
Component.translatable("wilderwild.advancements.husbandry.firefly_in_a_bottle.title"),
Component.translatable("wilderwild.advancements.husbandry.firefly_in_a_bottle.description"),
null,
AdvancementType.TASK,
true,
true,
false
)
.addCriterion("firefly_bottled", MobBottleTrigger.TriggerInstance.mobBottle(ItemPredicate.Builder.item().of(WWItems.FIREFLY_BOTTLE)))
.save(writer, WWConstants.string("husbandry/firefly_in_a_bottle"));
Advancement.Builder.advancement()
.parent(husbandry)
.display(
WWItems.BUTTERFLY_BOTTLE,
Component.translatable("wilderwild.advancements.husbandry.butterfly_in_a_bottle.title"),
Component.translatable("wilderwild.advancements.husbandry.butterfly_in_a_bottle.description"),
null,
AdvancementType.TASK,
true,
true,
false
)
.addCriterion("butterfly_bottled", MobBottleTrigger.TriggerInstance.mobBottle(ItemPredicate.Builder.item().of(WWItems.BUTTERFLY_BOTTLE)))
.save(writer, WWConstants.string("husbandry/butterfly_in_a_bottle"));
Advancement.Builder.advancement()
.parent(husbandry)
.display(
WWItems.JELLYFISH_BUCKET,
Component.translatable("wilderwild.advancements.husbandry.jellyfish_in_a_bucket.title"),
Component.translatable("wilderwild.advancements.husbandry.jellyfish_in_a_bucket.description"),
null,
AdvancementType.TASK,
true,
true,
false
)
.addCriterion("jellyfish_bucket", FilledBucketTrigger.TriggerInstance.filledBucket(ItemPredicate.Builder.item().of(WWItems.JELLYFISH_BUCKET)))
.save(writer, WWConstants.string("husbandry/jellyfish_in_a_bucket"));
Advancement.Builder.advancement()
.parent(adventure)
.display(
WWBlocks.TERMITE_MOUND,
Component.translatable("wilderwild.advancements.adventure.use_termite_on_tree.title"),
Component.translatable("wilderwild.advancements.adventure.use_termite_on_tree.description"),
null,
AdvancementType.TASK,
true,
true,
false
)
.addCriterion("termite_ate_block", TermiteEatTrigger.TriggerInstance.termiteEat(BlockPredicate.Builder.block().of(BlockTags.OVERWORLD_NATURAL_LOGS), true))
.save(writer, WWConstants.string("adventure/use_termite_on_tree"));
AdvancementHolder geyserPushedFlightlessBird = Advancement.Builder.advancement()
.parent(adventure)
.display(
WWBlocks.GEYSER,
Component.translatable("wilderwild.advancements.adventure.geyser_pushed_flightless_bird.title"),
Component.translatable("wilderwild.advancements.adventure.geyser_pushed_flightless_bird.description"),
null,
AdvancementType.TASK,
true,
true,
false
)
.addCriterion("geyser_pushed_mob", GeyserPushMobTrigger.TriggerInstance.geyserPushMob(
Optional.of(
EntityPredicate.Builder.entity()
.entityType(
new EntityTypePredicate(
HolderSet.direct(
EntityType.CHICKEN.builtInRegistryHolder(),
WWEntityTypes.OSTRICH.builtInRegistryHolder(),
WWEntityTypes.PENGUIN.builtInRegistryHolder()
)
)
)
.moving(
new MovementPredicate(
MinMaxBounds.Doubles.ANY,
MinMaxBounds.Doubles.atLeast(0.5D),
MinMaxBounds.Doubles.ANY,
MinMaxBounds.Doubles.ANY,
MinMaxBounds.Doubles.ANY,
MinMaxBounds.Doubles.ANY,
MinMaxBounds.Doubles.ANY
)
)
.build()
),
true,
GeyserType.AIR
)
)
.save(writer, WWConstants.string("adventure/geyser_pushed_flightless_bird"));
Advancement.Builder.advancement()
.parent(geyserPushedFlightlessBird)
.display(
Items.COOKED_BEEF,
Component.translatable("wilderwild.advancements.adventure.geyser_sets_cow_on_fire.title"),
Component.translatable("wilderwild.advancements.adventure.geyser_sets_cow_on_fire.description"),
null,
AdvancementType.TASK,
true,
true,
false
)
.addCriterion("geyser_pushed_mob", GeyserPushMobTrigger.TriggerInstance.geyserPushMob(
Optional.of(
EntityPredicate.Builder.entity()
.entityType(
new EntityTypePredicate(
HolderSet.direct(
EntityType.COW.builtInRegistryHolder(),
EntityType.MOOSHROOM.builtInRegistryHolder(),
WWEntityTypes.MOOBLOOM.builtInRegistryHolder()
)
)
)
.flags(EntityFlagsPredicate.Builder.flags().setOnFire(true))
.build()
),
true,
GeyserType.LAVA
)
)
.save(writer, WWConstants.string("adventure/geyser_sets_cow_on_fire"));
Advancement.Builder.advancement()
.parent(Advancement.Builder.advancement().build(WWConstants.vanillaId("adventure/walk_on_powder_snow_with_leather_boots")))
.display(
WWBlocks.FRAGILE_ICE,
Component.translatable("wilderwild.advancements.adventure.fall_onto_and_break_fragile_ice.title"),
Component.translatable("wilderwild.advancements.adventure.fall_onto_and_break_fragile_ice.description"),
null,
AdvancementType.TASK,
true,
true,
false
)
.addCriterion("fall_onto_and_break_fragile_ice", FragileIceFallOntoAndBreakTrigger.TriggerInstance.fragileIceBreak())
.save(writer, WWConstants.string("adventure/fall_onto_and_break_fragile_ice"));
Advancement.Builder.advancement()
.parent(adventure)
.display(
WWBlocks.NULL_BLOCK,
Component.translatable("wilderwild.advancements.adventure.obtain_null_block.title"),
Component.translatable("wilderwild.advancements.adventure.obtain_null_block.description"),
null,
AdvancementType.TASK,
true,
true,
true
)
.addCriterion("obtain_null_block", InventoryChangeTrigger.TriggerInstance.hasItems(WWBlocks.NULL_BLOCK))
.save(writer, WWConstants.string("adventure/obtain_null_block"));
}
}
| 412 | 0.814086 | 1 | 0.814086 | game-dev | MEDIA | 0.961109 | game-dev | 0.882159 | 1 | 0.882159 |
SmashPhil/Vehicle-Framework | 1,461 | Source/Vehicles/Utility/Helpers/Combat/CombatTargetFinder.cs | ο»Ώusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RimWorld;
using Verse;
using Verse.AI;
namespace Vehicles
{
public static class CombatTargetFinder
{
public static Thing FindAttackTarget(VehiclePawn vehicle, TargetScanFlags scanFlags, Func<Thing, bool> validator = null,
float minDistance = 0f, float maxDistance = float.MaxValue, IntVec3? locus = null,
float maxTravelRadiusFromLocus = float.MaxValue, bool onlyRanged = false)
{
// TODO - Use VehicleRegionTraverser for reachability search
Thing attackTarget = GenClosest.ClosestThingReachable(vehicle.Position, vehicle.Map,
ThingRequest.ForGroup(ThingRequestGroup.AttackTarget), PathEndMode.Touch,
TraverseParms.For(vehicle, Danger.Deadly, TraverseMode.ByPawn), maxDistance: maxDistance,
validator: (Thing target) => (validator == null || validator(target)) && !ShouldIgnoreNonCombatant(vehicle, target, scanFlags),
searchRegionsMax: maxDistance > 800 ? -1 : 40);
return attackTarget;
}
private static bool ShouldIgnoreNonCombatant(VehiclePawn vehicle, Thing thing, TargetScanFlags scanFlags)
{
if (thing is not Pawn pawn)
{
return false;
}
if (pawn.IsCombatant())
{
return false;
}
if (scanFlags.HasFlag(TargetScanFlags.IgnoreNonCombatants))
{
return true;
}
return !GenSight.LineOfSightToThing(vehicle.Position, pawn, vehicle.Map);
}
}
}
| 412 | 0.962279 | 1 | 0.962279 | game-dev | MEDIA | 0.99282 | game-dev | 0.947155 | 1 | 0.947155 |
aaa719717747/TrueSyncExample | 12,037 | Assets/TrueSync/Physics/Farseer/Factories/BodyFactory.cs | ο»Ώusing System;
using System.Collections.Generic;
namespace TrueSync.Physics2D
{
public static class BodyFactory
{
public static Body CreateBody(World world, object userData = null)
{
Body body = new Body(world, null, 0, userData);
return body;
}
// TS - public static Body CreateBody(World world, Vector2 position, FP rotation = 0, object userData = null)
public static Body CreateBody(World world, TSVector2 position, FP rotation, object userData = null)
{
Body body = new Body(world, position, rotation, userData);
return body;
}
public static Body CreateEdge(World world, TSVector2 start, TSVector2 end, object userData = null)
{
Body body = CreateBody(world);
FixtureFactory.AttachEdge(start, end, body, userData);
return body;
}
public static Body CreateChainShape(World world, Vertices vertices, object userData = null)
{
return CreateChainShape(world, vertices, TSVector2.zero, userData);
}
public static Body CreateChainShape(World world, Vertices vertices, TSVector2 position, object userData = null)
{
Body body = CreateBody(world, position);
FixtureFactory.AttachChainShape(vertices, body, userData);
return body;
}
public static Body CreateLoopShape(World world, Vertices vertices, object userData = null)
{
return CreateLoopShape(world, vertices, TSVector2.zero, userData);
}
public static Body CreateLoopShape(World world, Vertices vertices, TSVector2 position, object userData = null)
{
Body body = CreateBody(world, position);
FixtureFactory.AttachLoopShape(vertices, body, userData);
return body;
}
public static Body CreateRectangle(World world, FP width, FP height, FP density, object userData = null)
{
return CreateRectangle(world, width, height, density, TSVector2.zero, userData);
}
public static Body CreateRectangle(World world, FP width, FP height, FP density, TSVector2 position, object userData = null)
{
if (width <= 0)
throw new ArgumentOutOfRangeException("width", "Width must be more than 0 meters");
if (height <= 0)
throw new ArgumentOutOfRangeException("height", "Height must be more than 0 meters");
Body newBody = CreateBody(world, position);
newBody.UserData = userData;
Vertices rectangleVertices = PolygonTools.CreateRectangle(width / 2, height / 2);
PolygonShape rectangleShape = new PolygonShape(rectangleVertices, density);
newBody.CreateFixture(rectangleShape);
return newBody;
}
public static Body CreateCircle(World world, FP radius, FP density, object userData = null)
{
return CreateCircle(world, radius, density, TSVector2.zero, userData);
}
public static Body CreateCircle(World world, FP radius, FP density, TSVector2 position, object userData = null)
{
Body body = CreateBody(world, position);
FixtureFactory.AttachCircle(radius, density, body, userData);
return body;
}
public static Body CreateEllipse(World world, FP xRadius, FP yRadius, int edges, FP density, object userData = null)
{
return CreateEllipse(world, xRadius, yRadius, edges, density, TSVector2.zero, userData);
}
public static Body CreateEllipse(World world, FP xRadius, FP yRadius, int edges, FP density,
TSVector2 position, object userData = null)
{
Body body = CreateBody(world, position);
FixtureFactory.AttachEllipse(xRadius, yRadius, edges, density, body, userData);
return body;
}
public static Body CreatePolygon(World world, Vertices vertices, FP density, object userData)
{
return CreatePolygon(world, vertices, density, TSVector2.zero, userData);
}
public static Body CreatePolygon(World world, Vertices vertices, FP density, TSVector2 position, object userData)
{
Body body = CreateBody(world, position);
FixtureFactory.AttachPolygon(vertices, density, body, userData);
return body;
}
public static Body CreateCompoundPolygon(World world, List<Vertices> list, FP density, object userData = null)
{
return CreateCompoundPolygon(world, list, density, TSVector2.zero, userData);
}
public static Body CreateCompoundPolygon(World world, List<Vertices> list, FP density, TSVector2 position, object userData = null)
{
//We create a single body
Body polygonBody = CreateBody(world, position);
FixtureFactory.AttachCompoundPolygon(list, density, polygonBody, userData);
return polygonBody;
}
public static Body CreateGear(World world, FP radius, int numberOfTeeth, FP tipPercentage, FP toothHeight, FP density, object userData = null)
{
Vertices gearPolygon = PolygonTools.CreateGear(radius, numberOfTeeth, tipPercentage, toothHeight);
//Gears can in some cases be convex
if (!gearPolygon.IsConvex())
{
//Decompose the gear:
List<Vertices> list = Triangulate.ConvexPartition(gearPolygon, TriangulationAlgorithm.Earclip, true, FP.EN3);
return CreateCompoundPolygon(world, list, density, userData);
}
return CreatePolygon(world, gearPolygon, density, userData);
}
/// <summary>
/// Creates a capsule.
/// Note: Automatically decomposes the capsule if it contains too many vertices (controlled by Settings.MaxPolygonVertices)
/// </summary>
/// <returns></returns>
public static Body CreateCapsule(World world, FP height, FP topRadius, int topEdges, FP bottomRadius, int bottomEdges, FP density, TSVector2 position, object userData = null)
{
Vertices verts = PolygonTools.CreateCapsule(height, topRadius, topEdges, bottomRadius, bottomEdges);
Body body;
//There are too many vertices in the capsule. We decompose it.
if (verts.Count >= Settings.MaxPolygonVertices)
{
List<Vertices> vertList = Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Earclip, true, FP.EN3);
body = CreateCompoundPolygon(world, vertList, density, userData);
body.Position = position;
return body;
}
body = CreatePolygon(world, verts, density, userData);
body.Position = position;
return body;
}
public static Body CreateCapsule(World world, FP height, FP endRadius, FP density,
object userData = null)
{
//Create the middle rectangle
Vertices rectangle = PolygonTools.CreateRectangle(endRadius, height / 2);
List<Vertices> list = new List<Vertices>();
list.Add(rectangle);
Body body = CreateCompoundPolygon(world, list, density, userData);
body.UserData = userData;
//Create the two circles
CircleShape topCircle = new CircleShape(endRadius, density);
topCircle.Position = new TSVector2(0, height / 2);
body.CreateFixture(topCircle);
CircleShape bottomCircle = new CircleShape(endRadius, density);
bottomCircle.Position = new TSVector2(0, -(height / 2));
body.CreateFixture(bottomCircle);
return body;
}
/// <summary>
/// Creates a rounded rectangle.
/// Note: Automatically decomposes the capsule if it contains too many vertices (controlled by Settings.MaxPolygonVertices)
/// </summary>
/// <param name="world">The world.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="xRadius">The x radius.</param>
/// <param name="yRadius">The y radius.</param>
/// <param name="segments">The segments.</param>
/// <param name="density">The density.</param>
/// <param name="position">The position.</param>
/// <returns></returns>
public static Body CreateRoundedRectangle(World world, FP width, FP height, FP xRadius, FP yRadius, int segments, FP density, TSVector2 position, object userData = null)
{
Vertices verts = PolygonTools.CreateRoundedRectangle(width, height, xRadius, yRadius, segments);
//There are too many vertices in the capsule. We decompose it.
if (verts.Count >= Settings.MaxPolygonVertices)
{
List<Vertices> vertList = Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Earclip, true, FP.EN3);
Body body = CreateCompoundPolygon(world, vertList, density, userData);
body.Position = position;
return body;
}
return CreatePolygon(world, verts, density, null);
}
public static Body CreateRoundedRectangle(World world, FP width, FP height, FP xRadius, FP yRadius, int segments, FP density, object userData = null)
{
return CreateRoundedRectangle(world, width, height, xRadius, yRadius, segments, density, TSVector2.zero, userData);
}
public static BreakableBody CreateBreakableBody(World world, Vertices vertices, FP density)
{
return CreateBreakableBody(world, vertices, density, TSVector2.zero);
}
public static BreakableBody CreateBreakableBody(World world, IEnumerable<Shape> shapes)
{
return CreateBreakableBody(world, shapes, TSVector2.zero);
}
/// <summary>
/// Creates a breakable body. You would want to remove collinear points before using this.
/// </summary>
/// <param name="world">The world.</param>
/// <param name="vertices">The vertices.</param>
/// <param name="density">The density.</param>
/// <param name="position">The position.</param>
/// <returns></returns>
public static BreakableBody CreateBreakableBody(World world, Vertices vertices, FP density, TSVector2 position)
{
List<Vertices> triangles = Triangulate.ConvexPartition(vertices, TriangulationAlgorithm.Earclip, true, FP.EN3);
BreakableBody breakableBody = new BreakableBody(triangles, world, density);
breakableBody.MainBody.Position = position;
world.AddBreakableBody(breakableBody);
return breakableBody;
}
public static BreakableBody CreateBreakableBody(World world, IEnumerable<Shape> shapes, TSVector2 position)
{
BreakableBody breakableBody = new BreakableBody(shapes, world);
breakableBody.MainBody.Position = position;
world.AddBreakableBody(breakableBody);
return breakableBody;
}
public static Body CreateLineArc(World world, FP radians, int sides, FP radius, TSVector2 position, FP angle, bool closed)
{
Body body = CreateBody(world);
FixtureFactory.AttachLineArc(radians, sides, radius, position, angle, closed, body);
return body;
}
public static Body CreateSolidArc(World world, FP density, FP radians, int sides, FP radius, TSVector2 position, FP angle)
{
Body body = CreateBody(world);
FixtureFactory.AttachSolidArc(density, radians, sides, radius, position, angle, body);
return body;
}
}
} | 412 | 0.65324 | 1 | 0.65324 | game-dev | MEDIA | 0.832271 | game-dev | 0.657104 | 1 | 0.657104 |
Grimrukh/soulstruct | 6,805 | src/soulstruct/eldenring/params/paramdef/EQUIP_PARAM_ACCESSORY_ST.py | from __future__ import annotations
__all__ = ["EQUIP_PARAM_ACCESSORY_ST"]
from soulstruct.base.params.param_row import *
from soulstruct.eldenring.game_types import *
from soulstruct.eldenring.params.enums import *
from soulstruct.utilities.binary import *
class EQUIP_PARAM_ACCESSORY_ST(ParamRow):
DisableParamNT: bool = ParamField(
uint8, "disableParam_NT:1", BOOL_CIRCLECROSS_TYPE, bit_count=1, default=False,
tooltip="TOOLTIP-TODO",
)
_BitPad0: int = ParamBitPad(uint8, "disableParamReserve1:7", bit_count=7)
_Pad0: bytes = ParamPad(3, "disableParamReserve2[3]")
SpecialEffect: int = ParamField(
int32, "refId", game_type=SpecialEffectParam, default=-1,
tooltip="Special effect applied when accessory is equipped.",
)
SFXVariation: int = ParamField(
int32, "sfxVariationId", default=-1,
tooltip="SFX variation ID combined with the value specified in TAE animation data. Always -1; likely works "
"with unused Behavior parameter below.",
)
Weight: float = ParamField(
float32, "weight", default=1.0,
tooltip="Weight of accessory. Always set to zero in vanilla Dark Souls, but likely works just like other "
"equipment.",
)
Behavior: int = ParamField(
int32, "behaviorId", game_type=BehaviorParam, default=0,
tooltip="Behavior of accessory 'skill'. Always zero in the vanilla game.",
)
BasicCost: int = ParamField(
int32, "basicPrice", default=0,
tooltip="Unknown purpose, and unused.",
)
FramptSellValue: int = ParamField(
int32, "sellValue", default=0,
tooltip="Amount of souls received when fed to Frampt. (Set to -1 to prevent it from being sold.",
)
SortIndex: int = ParamField(
int32, "sortId", default=0,
tooltip="Index for automatic inventory sorting.",
)
QWCID: int = ParamField(
int32, "qwcId", default=-1,
tooltip="Unused world tendency remnant.",
)
EquipmentModel: int = ParamField(
uint16, "equipModelId", game_type=EquipmentModel, default=0,
tooltip="Always zero. (Talismans have no model, presumably.)",
)
MenuIcon: int = ParamField(
uint16, "iconId", game_type=Icon, default=0,
tooltip="Icon ID of talisman in menu.",
)
ShopLevel: int = ParamField(
int16, "shopLv", default=0,
tooltip="Internal description: 'Level that can be solved in the shop.' Unknown and unused (talismans have no "
"level).",
)
AchievementContributionID: int = ParamField(
int16, "trophySGradeId", default=-1,
tooltip="Index of talisman as it contributes to certain multi-item achievements (none for talismans).",
)
AchievementUnlockID: int = ParamField(
int16, "trophySeqId", default=-1,
tooltip="Achievement unlocked when talisman is acquired (Covenant of Artorias).",
)
EquipmentModelCategory: int = ParamField(
uint8, "equipModelCategory", EQUIP_MODEL_CATEGORY, default=0,
tooltip="Always zero.",
)
EquipmentModelGender: int = ParamField(
uint8, "equipModelGender", EQUIP_MODEL_GENDER, default=0,
tooltip="Always zero.",
)
AccessoryCategory: int = ParamField(
uint8, "accessoryCategory", ACCESSORY_CATEGORY, default=0,
tooltip="Always zero.",
)
ReferenceType: int = ParamField(
uint8, "refCategory", BEHAVIOR_REF_TYPE, default=0,
tooltip="Always set to Special Effects. No idea what happens if you set it to Attacks for a talisman...",
)
SpecialEffectCategory: int = ParamField(
uint8, "spEffectCategory", BEHAVIOR_CATEGORY, default=0,
tooltip="Determines what type of special effects affect the stats of this equipment. Unused for talismans.",
)
SortGroupId: int = ParamField(
uint8, "sortGroupId", default=255,
tooltip="TOOLTIP-TODO",
)
VagrantItemLot: int = ParamField(
int32, "vagrantItemLotId", game_type=ItemLotParam, default=0,
tooltip="TODO",
)
VagrantBonusEnemyDropItemLot: int = ParamField(
int32, "vagrantBonusEneDropItemLotId", game_type=ItemLotParam, default=0,
tooltip="TODO",
)
VagrantItemEnemyDropItemLot: int = ParamField(
int32, "vagrantItemEneDropItemLotId", game_type=ItemLotParam, default=0,
tooltip="TODO",
)
CanBeStored: bool = ParamField(
uint8, "isDeposit:1", EQUIP_BOOL, bit_count=1, default=False,
tooltip="If True, this talisman can be stored in storage. Always True for talismans.",
)
BreaksWhenUnequipped: bool = ParamField(
uint8, "isEquipOutBrake:1", EQUIP_BOOL, bit_count=1, default=False,
tooltip="If True, this talisman will break when it is unequipped.",
)
DisableMultiplayerShare: bool = ParamField(
uint8, "disableMultiDropShare:1", EQUIP_BOOL, bit_count=1, default=False,
tooltip="If True, this talisman cannot be given to other players by dropping it. Always False in vanilla.",
)
IsDiscard: bool = ParamField(
uint8, "isDiscard:1", EQUIP_BOOL, bit_count=1, default=False,
tooltip="TOOLTIP-TODO",
)
IsDrop: bool = ParamField(
uint8, "isDrop:1", EQUIP_BOOL, bit_count=1, default=False,
tooltip="TOOLTIP-TODO",
)
ShowLogCondType: bool = ParamField(
uint8, "showLogCondType:1", EQUIP_BOOL, bit_count=1, default=True,
tooltip="TOOLTIP-TODO",
)
ShowDialogCondType: int = ParamField(
uint8, "showDialogCondType:2", GET_DIALOG_CONDITION_TYPE, bit_count=2, default=2,
tooltip="TOOLTIP-TODO",
)
Rarity: int = ParamField(
uint8, "rarity", default=0,
tooltip="TOOLTIP-TODO",
)
_Pad1: bytes = ParamPad(2, "pad2[2]")
SaleValue: int = ParamField(
int32, "saleValue", default=-1,
tooltip="TOOLTIP-TODO",
)
AccessoryGroup: int = ParamField(
int16, "accessoryGroup", default=-1,
tooltip="TOOLTIP-TODO",
)
_Pad2: bytes = ParamPad(1, "pad3[1]")
CompTrophySedId: int = ParamField(
int8, "compTrophySedId", default=-1,
tooltip="TOOLTIP-TODO",
)
ResidentSpEffectId1: int = ParamField(
int32, "residentSpEffectId1", default=0,
tooltip="TOOLTIP-TODO",
)
ResidentSpEffectId2: int = ParamField(
int32, "residentSpEffectId2", default=0,
tooltip="TOOLTIP-TODO",
)
ResidentSpEffectId3: int = ParamField(
int32, "residentSpEffectId3", default=0,
tooltip="TOOLTIP-TODO",
)
ResidentSpEffectId4: int = ParamField(
int32, "residentSpEffectId4", default=0,
tooltip="TOOLTIP-TODO",
)
_Pad3: bytes = ParamPad(4, "pad1[4]")
| 412 | 0.863909 | 1 | 0.863909 | game-dev | MEDIA | 0.818916 | game-dev | 0.730895 | 1 | 0.730895 |
neilmewada/CrystalEngine | 29,844 | Engine/Source/Engine/Private/Asset/AssetRegistry.cpp | #include "Engine.h"
namespace CE
{
AssetRegistry* AssetRegistry::singleton = nullptr;
static bool SortAssetData(AssetData* lhs, AssetData* rhs)
{
return String::NaturalCompare(lhs->bundleName.GetLastComponent(), rhs->bundleName.GetLastComponent());
}
AssetRegistry::AssetRegistry()
{
}
AssetRegistry::~AssetRegistry()
{
#if PAL_TRAIT_BUILD_EDITOR
fileWatcher.RemoveWatcher(fileWatchID);
#endif
for (auto assetData : allAssetDatas)
{
delete assetData;
}
allAssetDatas.Clear();
cachedAssetsByPath.Clear();
}
void AssetRegistry::Shutdown()
{
Bundle::PopBundleResolver(this);
}
AssetRegistry* AssetRegistry::Get()
{
return AssetManager::GetRegistry();
}
void AssetRegistry::Refresh()
{
}
AssetData* AssetRegistry::GetPrimaryAssetByPath(const Name& path)
{
LockGuard guard{ cacheMutex };
return cachedPrimaryAssetByPath[path];
}
Array<AssetData*> AssetRegistry::GetAssetsByPath(const Name& path)
{
LockGuard guard{ cacheMutex };
return cachedAssetsByPath[path];
}
AssetData* AssetRegistry::GetAssetBySourcePath(const Name& sourcePath)
{
LockGuard guard{ cacheMutex };
if (cachedAssetBySourcePath.KeyExists(sourcePath))
return cachedAssetBySourcePath[sourcePath];
return nullptr;
}
Array<AssetData*> AssetRegistry::GetPrimaryAssetsInSubPath(const Name& parentPath)
{
LockGuard guard{ cacheMutex };
return cachedPrimaryAssetsByParentPath[parentPath];
}
const Array<AssetData*>& AssetRegistry::GetAllAssetsOfType(TypeId typeId)
{
LockGuard guard{ cacheMutex };
static Array<AssetData*> empty;
if (!cachedAssetsByType.KeyExists(typeId))
return empty;
return cachedAssetsByType[typeId];
}
Array<String> AssetRegistry::GetSubDirectoriesAtPath(const Name& path)
{
LockGuard guard{ cacheMutex };
Array<String> result{};
auto directoryNode = cachedDirectoryTree.GetNode(path);
if (directoryNode == nullptr)
return result;
for (const auto subDirectory : directoryNode->children)
{
result.Add(subDirectory->name.GetString());
}
return result;
}
PathTreeNode* AssetRegistry::GetDirectoryNode(const Name& path)
{
LockGuard guard{ cacheMutex };
return cachedDirectoryTree.GetNode(path);
}
Name AssetRegistry::ResolveBundlePath(const Uuid& bundleUuid)
{
LockGuard guard{ cacheMutex };
if (!cachedPrimaryAssetByBundleUuid.KeyExists(bundleUuid))
return Name();
AssetData* assetData = cachedPrimaryAssetByBundleUuid[bundleUuid];
if (assetData == nullptr)
return Name();
return assetData->bundlePath;
}
void AssetRegistry::AddRegistryListener(IAssetRegistryListener* listener)
{
listeners.Add(listener);
}
void AssetRegistry::RemoveRegistryListener(IAssetRegistryListener* listener)
{
listeners.Remove(listener);
}
void AssetRegistry::OnAssetImported(const IO::Path& bundleAbsolutePath, const Name& sourcePath)
{
LockGuard guard{ cacheMutex };
LoadBundleArgs args{
.loadTemporary = true,
.loadFully = false,
.forceReload = false,
.destroyOutdatedObjects = false
};
Ref<Bundle> load = Bundle::LoadBundleAbsolute(nullptr, bundleAbsolutePath, args);
if (load == nullptr)
return;
auto projectAssetsPath = gProjectPath / "Game/Assets";
String relativePathStr = "";
String parentRelativePathStr = "";
auto engineInstallDir = EngineDirectories::GetEngineInstallDirectory();
auto engineAssetsPath = engineInstallDir / "Engine/Assets";
auto editorAssetsPath = engineInstallDir / "Editor/Assets";
if (IO::Path::IsSubDirectory(bundleAbsolutePath, projectAssetsPath))
{
relativePathStr = IO::Path::GetRelative(bundleAbsolutePath, gProjectPath).RemoveExtension().GetString().Replace({'\\'}, '/');
if (!relativePathStr.StartsWith("/"))
relativePathStr = "/" + relativePathStr;
parentRelativePathStr = IO::Path::GetRelative(bundleAbsolutePath, gProjectPath).GetParentPath().GetString().Replace({ '\\' }, '/');
if (!parentRelativePathStr.StartsWith("/"))
parentRelativePathStr = "/" + parentRelativePathStr;
}
else if (IO::Path::IsSubDirectory(bundleAbsolutePath, engineAssetsPath) || IO::Path::IsSubDirectory(bundleAbsolutePath, editorAssetsPath))
{
relativePathStr = IO::Path::GetRelative(bundleAbsolutePath, engineInstallDir).RemoveExtension().GetString().Replace({ '\\' }, '/');
if (!relativePathStr.StartsWith("/"))
relativePathStr = "/" + relativePathStr;
parentRelativePathStr = IO::Path::GetRelative(bundleAbsolutePath, engineInstallDir).GetParentPath().GetString().Replace({ '\\' }, '/');
if (!parentRelativePathStr.StartsWith("/"))
parentRelativePathStr = "/" + parentRelativePathStr;
}
AssetData* assetData = nullptr;
bool newEntry = false;
int originalIndex = cachedPrimaryAssetsByParentPath[parentRelativePathStr]
.IndexOf([&](AssetData* data) -> bool { return data->bundleName == load->GetName(); });
if (originalIndex >= 0)
{
assetData = cachedPrimaryAssetsByParentPath[parentRelativePathStr].At(originalIndex);
}
if (assetData == nullptr)
{
assetData = new AssetData();
newEntry = true;
}
//String sourceAssetRelativePath = sourcePath.GetString();
Bundle::ObjectData primaryObjectData = load->GetPrimaryObjectData();
Name primaryName = primaryObjectData.name;
Name primaryTypeName = primaryObjectData.typeName;
assetData->bundleName = load->GetName();
assetData->bundlePath = load->GetBundlePath();
assetData->assetName = primaryName;
assetData->assetClassTypeName = primaryTypeName;
assetData->bundleUuid = load->GetUuid();
assetData->assetUuid = primaryObjectData.uuid;
#if PAL_TRAIT_BUILD_EDITOR
// Source asset path relative in project
//assetData->sourceAssetPath = sourceAssetRelativePath;
if (load->sourceAssetRelativePath.IsValid())
{
assetData->sourceAssetPath = load->GetBundlePath().GetParentPath() + "/" + load->sourceAssetRelativePath.GetString();
}
#endif
if (newEntry && relativePathStr.NotEmpty())
{
AddAssetEntry(relativePathStr, assetData);
}
load->BeginDestroy();
load = nullptr;
for (IAssetRegistryListener* listener : listeners)
{
if (listener != nullptr)
{
listener->OnAssetImported(assetData->bundlePath, sourcePath);
listener->OnAssetPathTreeUpdated(cachedPathTree);
}
}
}
void AssetRegistry::OnAssetUpdated(const Name& bundlePath)
{
for (IAssetRegistryListener* listener : listeners)
{
if (listener != nullptr)
{
listener->OnAssetImported(bundlePath, {});
listener->OnAssetPathTreeUpdated(cachedPathTree);
}
}
}
void AssetRegistry::OnDirectoryCreated(const IO::Path& absolutePath)
{
LockGuard guard{ cacheMutex };
auto projectAssetsPath = gProjectPath / "Game/Assets";
String relativePathStr = "";
if (IO::Path::IsSubDirectory(absolutePath, projectAssetsPath))
{
relativePathStr = IO::Path::GetRelative(absolutePath, gProjectPath).RemoveExtension().GetString().Replace({ '\\' }, '/');
if (!relativePathStr.StartsWith("/"))
relativePathStr = "/" + relativePathStr;
}
else
{
return;
}
PathTreeNode* pathNode = cachedPathTree.AddPath(relativePathStr);
PathTreeNode* directoryNode = cachedDirectoryTree.AddPath(relativePathStr);
if (pathNode != nullptr && pathNode->parent != nullptr)
{
pathNode->parent->SortChildren();
}
if (directoryNode != nullptr && directoryNode->parent != nullptr)
{
directoryNode->parent->SortChildren();
}
for (IAssetRegistryListener* listener : listeners)
{
if (listener != nullptr)
{
listener->OnAssetPathTreeUpdated(cachedPathTree);
}
}
}
void AssetRegistry::OnDirectoryRenamed(const Name& originalPath, const Name& newName)
{
LockGuard guard{ cacheMutex };
PathTreeNode* pathNode = cachedPathTree.GetNode(originalPath);
Name newFullPath{};
if (pathNode != nullptr)
{
Name oldFullPath = pathNode->GetFullPath();
pathNode->name = newName;
newFullPath = pathNode->GetFullPath();
if (pathNode->parent != nullptr)
{
pathNode->parent->SortChildren();
}
std::function<void(PathTreeNode*,Name,Name)> visitor = [&](PathTreeNode* node, Name curNewPath, Name curOldPath)
{
if (node->nodeType == PathTreeNodeType::Directory && cachedPrimaryAssetsByParentPath.KeyExists(curOldPath))
{
cachedPrimaryAssetsByParentPath[curNewPath] = cachedPrimaryAssetsByParentPath[curOldPath];
cachedPrimaryAssetsByParentPath.Remove(curOldPath);
}
else if (node->nodeType == PathTreeNodeType::Asset)
{
Uuid bundleUuid = {};
if (cachedPrimaryAssetByPath.KeyExists(curOldPath))
{
cachedPrimaryAssetByPath[curNewPath] = cachedPrimaryAssetByPath[curOldPath];
bundleUuid = cachedPrimaryAssetByPath[curNewPath]->bundleUuid;
cachedPrimaryAssetByPath.Remove(curOldPath);
}
if (cachedAssetsByPath.KeyExists(curOldPath))
{
cachedAssetsByPath[curNewPath] = cachedAssetsByPath[curOldPath];
const auto& assetDatas = cachedAssetsByPath[curNewPath];
for (AssetData* assetData : assetDatas)
{
assetData->bundlePath = curNewPath;
if (assetData->sourceAssetPath.IsValid())
{
Name newSourcePath = curNewPath.GetParentPath() + "/" + assetData->sourceAssetPath.GetLastComponent();
assetData->sourceAssetPath = newSourcePath;
String::IsAlphabet('a');
}
}
cachedAssetsByPath.Remove(curOldPath);
}
AssetManager* assetManager = AssetManager::Get();
{
LockGuard lock{ assetManager->loadedAssetsMutex };
if (assetManager->loadedAssetsByPath.KeyExists(curOldPath))
{
assetManager->loadedAssetsByPath[curNewPath] = assetManager->loadedAssetsByPath[curOldPath];
assetManager->loadedAssetsByPath.Remove(curOldPath);
assetManager->loadedAssetsByPath[curNewPath]->absoluteBundlePath = Bundle::GetAbsoluteBundlePath(curNewPath);
assetManager->loadedAssetsByPath[curNewPath]->bundlePath = curNewPath;
}
}
{
LockGuard guard{ Bundle::bundleRegistryMutex };
if (Bundle::loadedBundlesByUuid.KeyExists(bundleUuid))
{
if (Ref<Bundle> loadedBundle = Bundle::loadedBundlesByUuid[bundleUuid].Lock())
{
loadedBundle->absoluteBundlePath = Bundle::GetAbsoluteBundlePath(curNewPath);
loadedBundle->bundlePath = curNewPath;
}
}
}
}
for (PathTreeNode* child : node->children)
{
visitor(child, curNewPath.GetString() + "/" + child->name.GetString(),
curOldPath.GetString() + "/" + child->name.GetString());
}
};
IO::Path projectPath = gProjectPath;
IO::Path stampDirectory = gProjectPath / ("Temp/AssetCache" + oldFullPath.GetString());
if (stampDirectory.Exists())
{
IO::Path newStampDirectory = gProjectPath / ("Temp/AssetCache" + newFullPath.GetString());
if (newStampDirectory.Exists())
{
IO::Path::RemoveRecursively(newStampDirectory);
}
IO::Path::Rename(stampDirectory, newStampDirectory);
}
visitor(pathNode, newFullPath, oldFullPath);
}
PathTreeNode* directoryNode = cachedDirectoryTree.GetNode(originalPath);
if (directoryNode != nullptr)
{
directoryNode->name = newName;
if (directoryNode->parent != nullptr)
{
directoryNode->parent->SortChildren();
}
}
for (IAssetRegistryListener* listener : listeners)
{
if (listener != nullptr)
{
if (newFullPath.IsValid())
{
listener->OnDirectoryRenamed(originalPath, newFullPath);
}
listener->OnAssetPathTreeUpdated(cachedPathTree);
}
}
}
void AssetRegistry::OnDirectoryDeleted(const Name& directoryPath)
{
LockGuard guard{ cacheMutex };
PathTreeNode* pathNode = cachedPathTree.GetNode(directoryPath);
if (pathNode == nullptr || pathNode->nodeType != PathTreeNodeType::Directory)
return;
std::function<void(PathTreeNode*)> visitor = [&](PathTreeNode* node)
{
if (!node)
return;
Name curPath = node->GetFullPath();
for (int i = (int)node->children.GetSize() - 1; i >= 0; --i)
{
visitor(node->children[i]);
}
if (node->nodeType == PathTreeNodeType::Directory)
{
cachedPrimaryAssetsByParentPath.Remove(curPath);
}
else if (node->nodeType == PathTreeNodeType::Asset)
{
DeleteAssetEntry(curPath);
}
};
visitor(pathNode);
cachedPathTree.RemovePath(directoryPath);
cachedDirectoryTree.RemovePath(directoryPath);
for (IAssetRegistryListener* listener : listeners)
{
if (listener != nullptr)
{
listener->OnAssetPathTreeUpdated(cachedPathTree);
}
}
}
void AssetRegistry::OnAssetRenamed(const Name& originalPath, const IO::Path& newAbsolutePath, const Name& newName)
{
LockGuard guard{ cacheMutex };
PathTreeNode* pathNode = cachedPathTree.GetNode(originalPath);
if (pathNode == nullptr || pathNode->nodeType != PathTreeNodeType::Asset)
return;
Name oldName = pathNode->name;
pathNode->name = newName;
Name newPath = pathNode->GetFullPath();
Ref<Bundle> bundle = nullptr;
AssetManager* assetManager = AssetManager::Get();
bool bundleLoaded = false;
{
LockGuard lock{ assetManager->loadedAssetsMutex };
if (assetManager->loadedAssetsByPath.KeyExists(originalPath))
{
bundleLoaded = true;
Ref<Bundle> oldBundle = assetManager->loadedAssetsByPath[originalPath];
assetManager->loadedAssetsByPath[newPath] = oldBundle;
assetManager->loadedAssetsByPath.Remove(originalPath);
bundle = assetManager->loadedAssetsByPath[newPath];
}
else
{
bundle = Bundle::LoadBundleAbsolute(this, newAbsolutePath, LoadBundleArgs{
.loadFully = true,
.forceReload = false,
.destroyOutdatedObjects = true
});
}
}
if (cachedAssetsByPath.KeyExists(originalPath))
{
cachedAssetsByPath[newPath] = cachedAssetsByPath[originalPath];
cachedAssetsByPath.Remove(originalPath);
for (AssetData* assetData : cachedAssetsByPath[newPath])
{
assetData->bundleName = newName;
assetData->bundlePath = newPath;
}
}
if (cachedPrimaryAssetByPath.KeyExists(originalPath))
{
cachedPrimaryAssetByPath[newPath] = cachedPrimaryAssetByPath[originalPath];
cachedPrimaryAssetByPath.Remove(originalPath);
cachedPrimaryAssetByPath[newPath]->bundleName = newName;
cachedPrimaryAssetByPath[newPath]->bundlePath = newPath;
}
if (bundle == nullptr)
return;
if (!bundleLoaded)
{
DetachSubobject(bundle.Get());
}
bundle->SetName(newName);
Bundle::SaveToDisk(bundle, nullptr, newAbsolutePath);
Uuid bundleUuid = bundle->GetUuid();
// Do NOT BeginDestroy() the bundle, because it might be used somewhere else!
bundle = nullptr;
for (IAssetRegistryListener* listener : listeners)
{
if (listener != nullptr)
{
listener->OnAssetRenamed(bundleUuid, oldName, newName, newPath);
listener->OnAssetPathTreeUpdated(cachedPathTree);
}
}
}
void AssetRegistry::OnDirectoryAndAssetsDeleted(const Array<Name>& paths)
{
LockGuard guard{ cacheMutex };
// TODO: Special consideration when deleting assets:
// What if they are loaded in memory and referenced by something?
// TODO: Implement asset hot-reloading & safe-deleting
for (const auto& path : paths)
{
PathTreeNode* directoryNode = cachedDirectoryTree.GetNode(path);
if (directoryNode != nullptr)
{
OnDirectoryDeleted(path);
}
PathTreeNode* pathNode = cachedPathTree.GetNode(path);
if (pathNode != nullptr && pathNode->nodeType == PathTreeNodeType::Asset)
{
DeleteAssetEntry(path);
}
cachedDirectoryTree.RemovePath(path);
cachedPathTree.RemovePath(path);
}
for (IAssetRegistryListener* listener : listeners)
{
if (listener != nullptr)
{
listener->OnAssetPathTreeUpdated(cachedPathTree);
}
}
}
void AssetRegistry::InitializeCache()
{
if (cacheInitialized)
return;
Bundle::PushBundleResolver(this);
// Clear the path tree
cachedPathTree.RemoveAll();
cachedDirectoryTree.RemoveAll();
cachedPathTree.AddPath("/Game/Assets"); cachedDirectoryTree.AddPath("/Game/Assets");
cachedPathTree.AddPath("/Engine"); cachedDirectoryTree.AddPath("/Engine");
#if PAL_TRAIT_BUILD_EDITOR
//pathTree.AddPath("/Editor"); directoryTree.AddPath("/Editor");
#endif
// Game assets
if (gProjectPath.Exists() && (gProjectPath / "Game/Assets").Exists())
{
auto projectAssetsPath = gProjectPath / "Game/Assets";
projectAssetsPath.RecursivelyIterateChildren([&](const IO::Path& item)
{
auto relativePath = IO::Path::GetRelative(item, gProjectPath);
auto relativePathStr = relativePath.RemoveExtension().GetString().Replace({'\\'}, '/');
if (!relativePathStr.StartsWith("/"))
relativePathStr = "/" + relativePathStr;
String parentRelativePathStr = relativePath.GetParentPath().GetString().Replace({ '\\' }, '/');
if (!parentRelativePathStr.StartsWith("/"))
parentRelativePathStr = "/" + parentRelativePathStr;
if (item.IsDirectory()) // Folder
{
if (!relativePathStr.IsEmpty())
{
cachedPathTree.AddPath(relativePathStr);
cachedDirectoryTree.AddPath(relativePathStr);
}
}
else if (item.GetExtension() == ".casset") // Product asset file
{
LoadBundleArgs args{
.loadFully = false,
.forceReload = false,
.destroyOutdatedObjects = false
};
Ref<Bundle> load = Bundle::LoadBundleAbsolute(nullptr, item, args);
if (load != nullptr)
{
AssetData* assetData = new AssetData();
auto primaryObjectData = load->GetPrimaryObjectData();
//if (!load->GetPrimaryObjectName().IsValid())
// load->LoadFully();
Name primaryName = primaryObjectData.name;
Name primaryTypeName = primaryObjectData.typeName;
assetData->bundleName = load->GetName();
assetData->bundlePath = load->GetBundlePath();
assetData->assetName = primaryName;
assetData->assetClassTypeName = primaryTypeName;
assetData->bundleUuid = load->GetUuid();
assetData->assetUuid = primaryObjectData.uuid;
#if PAL_TRAIT_BUILD_EDITOR
// Source asset path relative to project assets directory
if (load->sourceAssetRelativePath.IsValid())
{
assetData->sourceAssetPath = load->GetBundlePath().GetParentPath() + "/" + load->sourceAssetRelativePath.GetString();
}
#endif
load->BeginDestroy();
load = nullptr;
AddAssetEntry(relativePathStr, assetData);
}
else
{
CE_LOG(Error, All, "Failed to load asset metadata: {}", item);
}
}
});
#if PAL_TRAIT_BUILD_EDITOR
fileWatchID = fileWatcher.AddWatcher(projectAssetsPath, this, true);
fileWatcher.Watch();
#endif
}
auto engineDir = gProjectPath;
if (!gProjectPath.Exists() || !(gProjectPath / "Engine/Assets").Exists())
{
engineDir = PlatformDirectories::GetEngineRootDir();
}
// Engine assets
if (engineDir.Exists() && (engineDir / "Engine/Assets").Exists())
{
auto projectAssetsPath = engineDir / "Engine/Assets";
projectAssetsPath.RecursivelyIterateChildren([&](const IO::Path& item)
{
auto relativePath = IO::Path::GetRelative(item, engineDir);
auto relativePathStr = relativePath.RemoveExtension().GetString().Replace({ '\\' }, '/');
if (!relativePathStr.StartsWith("/"))
relativePathStr = "/" + relativePathStr;
String parentRelativePathStr = relativePath.GetParentPath().GetString().Replace({ '\\' }, '/');
if (!parentRelativePathStr.StartsWith("/"))
parentRelativePathStr = "/" + parentRelativePathStr;
if (item.IsDirectory()) // Folder
{
if (!relativePathStr.IsEmpty())
{
cachedPathTree.AddPath(relativePathStr);
cachedDirectoryTree.AddPath(relativePathStr);
}
}
else if (item.GetExtension() == ".casset") // Product asset file
{
LoadBundleArgs args{
.loadFully = false
};
Ref<Bundle> load = Bundle::LoadBundleAbsolute(nullptr, item, args);
if (load != nullptr)
{
AssetData* assetData = new AssetData();
auto primaryObjectData = load->GetPrimaryObjectData();
Name primaryName = primaryObjectData.name;
Name primaryTypeName = primaryObjectData.typeName;
assetData->bundleName = load->GetName();
assetData->bundlePath = load->GetBundlePath();
assetData->assetName = primaryName;
assetData->assetClassTypeName = primaryTypeName;
assetData->bundleUuid = load->GetUuid();
assetData->assetUuid = primaryObjectData.uuid;
#if PAL_TRAIT_BUILD_EDITOR
// Source asset path relative to project assets directory
//assetData->sourceAssetPath = load->GetPrimarySourceAssetRelativePath();
#endif
load->BeginDestroy();
load = nullptr;
AddAssetEntry(relativePathStr, assetData);
}
else
{
CE_LOG(Error, All, "Failed to load asset metadata: {}", item);
}
}
});
}
auto launchDir = PlatformDirectories::GetLaunchDir();
// Editor assets
if ((launchDir / "Editor/Assets").Exists())
{
auto editorAssetsPath = launchDir / "Editor/Assets";
editorAssetsPath.RecursivelyIterateChildren([&](const IO::Path& item)
{
auto relativePath = IO::Path::GetRelative(item, launchDir);
auto relativePathStr = relativePath.RemoveExtension().GetString().Replace({ '\\' }, '/');
if (!relativePathStr.StartsWith("/"))
relativePathStr = "/" + relativePathStr;
String parentRelativePathStr = relativePath.GetParentPath().GetString().Replace({ '\\' }, '/');
if (!parentRelativePathStr.StartsWith("/"))
parentRelativePathStr = "/" + parentRelativePathStr;
if (item.IsDirectory()) // Folder
{
if (!relativePathStr.IsEmpty())
{
cachedPathTree.AddPath(relativePathStr);
cachedDirectoryTree.AddPath(relativePathStr);
}
}
else if (item.GetExtension() == ".casset") // Product asset file
{
LoadBundleArgs args{
.loadFully = false
};
Ref<Bundle> load = Bundle::LoadBundleAbsolute(nullptr, item, args);
if (load != nullptr)
{
AssetData* assetData = new AssetData();
auto primaryObjectData = load->GetPrimaryObjectData();
Name primaryName = primaryObjectData.name;
Name primaryTypeName = primaryObjectData.typeName;
assetData->bundleName = load->GetName();
assetData->bundlePath = load->GetBundlePath();
assetData->assetName = primaryName;
assetData->assetClassTypeName = primaryTypeName;
assetData->bundleUuid = load->GetUuid();
assetData->assetUuid = primaryObjectData.uuid;
#if PAL_TRAIT_BUILD_EDITOR
// Source asset path relative to project assets directory
// TODO:
//assetData->sourceAssetPath = load->GetPrimarySourceAssetRelativePath();
#endif
load->BeginDestroy();
load = nullptr;
AddAssetEntry(relativePathStr, assetData);
}
else
{
CE_LOG(Error, All, "Failed to load asset metadata: {}", item);
}
}
}
);
}
// We don't want to sort the root directories: /Game, /Engine, /Editor
for (PathTreeNode* child : cachedDirectoryTree.GetRootNode()->children)
{
child->SortChildrenRecursively();
}
for (PathTreeNode* child : cachedPathTree.GetRootNode()->children)
{
child->SortChildrenRecursively();
}
cacheInitialized = true;
}
void AssetRegistry::AddAssetEntry(const Name& bundleName, AssetData* assetData)
{
LockGuard guard{ cacheMutex };
if (assetData == nullptr)
return;
allAssetDatas.Add(assetData);
cachedPathTree.AddPath(bundleName, PathTreeNodeType::Asset, assetData);
cachedAssetsByPath[bundleName].Add(assetData);
cachedPrimaryAssetByPath[bundleName] = assetData;
cachedPrimaryAssetByBundleUuid[assetData->bundleUuid] = assetData;
String parentPathStr = IO::Path(bundleName.GetString()).GetParentPath().GetString().Replace({ '\\' }, '/');
Name parentPath = parentPathStr;
cachedPrimaryAssetsByParentPath[parentPath].Add(assetData);
cachedPrimaryAssetsByParentPath[parentPath].Sort(SortAssetData);
ClassType* assetClass = ClassType::FindClass(assetData->assetClassTypeName);
while (assetClass != nullptr)
{
cachedAssetsByType[assetClass->GetTypeId()].InsertSorted(assetData, SortAssetData);
if (assetClass->GetSuperClassCount() == 0)
break;
assetClass = assetClass->GetSuperClass(0);
}
if (assetData->sourceAssetPath.IsValid())
{
cachedAssetBySourcePath[assetData->sourceAssetPath] = assetData;
}
}
void AssetRegistry::DeleteAssetEntry(const Name& bundlePath)
{
LockGuard guard{ cacheMutex };
if (!cachedAssetsByPath.KeyExists(bundlePath))
return;
Uuid bundleUuid = {};
if (cachedPrimaryAssetByPath.KeyExists(bundlePath) && cachedPrimaryAssetByPath[bundlePath] != nullptr)
{
bundleUuid = cachedPrimaryAssetByPath[bundlePath]->bundleUuid;
}
for (IAssetRegistryListener* listener : listeners)
{
if (listener != nullptr)
{
listener->OnAssetDeleted(bundlePath);
if (Bundle::IsBundleLoaded(bundleUuid))
{
}
}
}
Name sourceAssetPath = {};
{
const Array<AssetData*>& assetDataList = cachedAssetsByPath[bundlePath];
String parentPathStr = IO::Path(bundlePath.GetString()).GetParentPath().GetString().Replace({ '\\' }, '/');
Name parentPath = parentPathStr;
for (AssetData* assetData : assetDataList)
{
if (assetData != nullptr)
{
if (!sourceAssetPath.IsValid())
{
sourceAssetPath = assetData->sourceAssetPath;
}
ClassType* assetClass = ClassType::FindClass(assetData->assetClassTypeName);
while (assetClass != nullptr)
{
cachedAssetsByType.Remove(assetClass->GetTypeId());
if (assetClass->GetSuperClassCount() == 0)
break;
assetClass = assetClass->GetSuperClass(0);
}
cachedPrimaryAssetByBundleUuid.Remove(assetData->bundleUuid);
cachedPrimaryAssetsByParentPath[parentPath].Remove(assetData);
allAssetDatas.Remove(assetData);
Name sourcePath = assetData->sourceAssetPath;
if (cachedAssetBySourcePath.KeyExists(sourcePath))
{
cachedAssetBySourcePath.Remove(sourcePath);
}
delete assetData;
}
}
}
IO::Path projectPath = gProjectPath;
IO::Path stampPath = gProjectPath / ("Temp/AssetCache" + bundlePath.GetString() + ".stamp");
if (stampPath.Exists())
{
IO::Path::Remove(stampPath);
}
if (sourceAssetPath.IsValid())
{
IO::Path sourceAssetAbsolutePath = projectPath / sourceAssetPath.GetString().GetSubstring(1);
if (sourceAssetAbsolutePath.Exists() && !sourceAssetAbsolutePath.IsDirectory())
{
IO::Path::Remove(sourceAssetAbsolutePath);
}
}
cachedAssetsByPath.Remove(bundlePath);
AssetManager* assetManager = AssetManager::Get();
Ref<Bundle> bundle = nullptr;
{
LockGuard lock{ assetManager->loadedAssetsMutex };
if (assetManager->loadedAssetsByPath.KeyExists(bundlePath))
{
bundle = assetManager->loadedAssetsByPath[bundlePath];
}
}
if (bundle != nullptr)
{
Uuid bundleUuid = bundle->GetUuid();
assetManager->UnloadAsset(bundle);
}
cachedPathTree.RemovePath(bundlePath);
cachedPrimaryAssetByPath.Remove(bundlePath);
/*for (IAssetRegistryListener* listener : listeners)
{
if (listener != nullptr)
{
listener->OnAssetPathTreeUpdated(cachedPathTree);
}
}*/
}
void AssetRegistry::HandleFileAction(IO::WatchID watchId, IO::Path directory, const String& fileName, IO::FileAction fileAction, const String& oldFileName)
{
sourceChangesMutex.Lock();
// Watch for new/modified source assets
IO::Path relative = IO::Path::GetRelative(directory, gProjectPath / "Game/Assets").GetString().Replace({ '\\' }, '/');
u64 length = 0;
auto filePath = directory / fileName;
bool isDirectory = filePath.IsDirectory();
bool isFile = !isDirectory;
if (filePath.Exists() && !isDirectory)
{
FileStream stream = FileStream(directory / fileName, Stream::Permissions::ReadOnly);
stream.SetBinaryMode(true);
length = stream.GetLength();
stream.Close();
}
if (isFile && (length > 0 || fileAction == IO::FileAction::Delete || fileAction == IO::FileAction::Moved || fileAction == IO::FileAction::Add))
{
if (length > 0 && (fileAction == IO::FileAction::Modified || fileAction == IO::FileAction::Add))
{
if (sourceChanges.IsEmpty() ||
//sourceChanges.Top().fileAction != IO::FileAction::Modified ||
sourceChanges.Top().currentPath != filePath)
{
SourceAssetChange change{};
change.fileAction = IO::FileAction::Modified;
change.fileSize = length;
change.currentPath = filePath;
change.oldPath = "";
sourceChanges.Add(change);
}
}
else if (fileAction == IO::FileAction::Delete)
{
SourceAssetChange change{};
change.fileAction = IO::FileAction::Delete;
change.currentPath = filePath;
change.fileSize = length;
sourceChanges.Add(change);
}
else if (fileAction == IO::FileAction::Moved)
{
SourceAssetChange change{};
change.fileAction = IO::FileAction::Moved;
change.currentPath = filePath;
change.oldPath = directory / oldFileName;
change.fileSize = length;
sourceChanges.Add(change);
}
}
sourceChangesMutex.Unlock();
// FIX: Added delay to prevent skipping file Modified calls
Thread::SleepFor(1);
}
} // namespace CE
| 412 | 0.96011 | 1 | 0.96011 | game-dev | MEDIA | 0.753843 | game-dev | 0.963936 | 1 | 0.963936 |
project-topaz/topaz | 1,024 | scripts/zones/Waughroon_Shrine/Zone.lua | -----------------------------------
--
-- Zone: Waughroon_Shrine (144)
--
-----------------------------------
local ID = require("scripts/zones/Waughroon_Shrine/IDs")
require("scripts/globals/conquest")
require("scripts/globals/quests")
-----------------------------------
function onInitialize(zone)
end
function onZoneIn(player, prevZone)
local cs = -1
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-361.434, 101.798, -259.996, 0)
end
if (player:getQuestStatus(OUTLANDS, tpz.quest.id.outlands.A_THIEF_IN_NORG) == QUEST_ACCEPTED and player:getCharVar("aThiefinNorgCS") == 4) then
cs = 2
end
return cs
end
function onConquestUpdate(zone, updatetype)
tpz.conq.onConquestUpdate(zone, updatetype)
end
function onRegionEnter(player, region)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if (csid == 2) then
player:setCharVar("aThiefinNorgCS", 5)
end
end
| 412 | 0.925788 | 1 | 0.925788 | game-dev | MEDIA | 0.994214 | game-dev | 0.946952 | 1 | 0.946952 |
28msec/zorba | 4,175 | src/store/naive/dataguide.h | /*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ZORBA_SIMPLE_STORE_DATAGUIDE
#define ZORBA_SIMPLE_STORE_DATAGUIDE
#include "store/api/item.h"
//#define DATAGUIDE
namespace zorba
{
namespace simplestore
{
class ElementGuideNode;
class GuideNode
{
friend class AttributeGuideNode;
friend class ElementGuideNode;
protected:
ElementGuideNode * theParent;
store::Item_t theName;
bool theIsUnique;
public:
GuideNode(ElementGuideNode* parent, store::Item_t& name)
:
theParent(parent),
theIsUnique(true)
{
theName.transfer(name);
}
virtual ~GuideNode() {}
virtual store::StoreConsts::NodeKind getNodeKind() const = 0;
ElementGuideNode* getParent() const { return theParent; }
store::Item* getName() const { return theName.getp(); }
bool getUnique() const { return theIsUnique; }
void setUnique(bool v) { theIsUnique = v; }
virtual ulong numChildren() const { return 0; }
virtual ulong numAttributes() const { return 0; }
void deleteTree();
virtual void getPathInfo(
std::vector<const store::Item*>& ctxPath,
std::vector<const store::Item*>& relPath,
bool attrPath,
bool& found,
bool& unique) = 0;
virtual std::string show(ulong depth) const = 0;
};
/*******************************************************************************
********************************************************************************/
class AttributeGuideNode : public GuideNode
{
friend class GuideNode;
friend class ElementGuideNode;
public:
AttributeGuideNode(ElementGuideNode* parent, store::Item_t& name)
:
GuideNode(parent, name)
{
}
store::StoreConsts::NodeKind getNodeKind() const
{
return store::StoreConsts::attributeNode;
}
void getPathInfo(
std::vector<const store::Item*>& ctxPath,
std::vector<const store::Item*>& relPath,
bool attrPath,
bool& found,
bool& unique);
std::string show(ulong depth) const { return "attr"; }
};
/*******************************************************************************
********************************************************************************/
class ElementGuideNode : public GuideNode
{
friend class GuideNode;
protected:
std::vector<ElementGuideNode*> theChildren;
std::vector<AttributeGuideNode*> theAttributes;
public:
ElementGuideNode(ElementGuideNode* parent, store::Item_t& name)
:
GuideNode(parent, name)
{
if (parent)
parent->theChildren.push_back(this);
}
store::StoreConsts::NodeKind getNodeKind() const
{
return store::StoreConsts::elementNode;
}
ulong numChildren() const { return (ulong)theChildren.size(); }
ulong numAttributes() const { return (ulong)theAttributes.size(); }
void getPathInfo(
std::vector<const store::Item*>& ctxPath,
std::vector<const store::Item*>& relPath,
bool attrPath,
bool& found,
bool& unique);
GuideNode* findPath(
std::vector<const store::Item*>& path,
bool attrPath,
bool& unique);
ElementGuideNode* findChild(const store::Item* name);
AttributeGuideNode* findAttr(const store::Item* name);
std::string show(ulong depth) const;
};
}
}
#endif
/* vim:set et sw=2 ts=2: */
| 412 | 0.889322 | 1 | 0.889322 | game-dev | MEDIA | 0.64961 | game-dev,desktop-app | 0.572217 | 1 | 0.572217 |
sonicretro/SonLVL | 2,891 | INI Files/Sonic 3K Git INIs/DEZ/GravityTube.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using SonicRetro.SonLVL.API;
namespace S3KObjectDefinitions.DEZ
{
class GravityTube : ObjectDefinition
{
private PropertySpec[] properties;
private ReadOnlyCollection<byte> subtypes;
private Sprite[] sprite;
public override string Name
{
get { return "Gravity Tube"; }
}
public override bool Debug
{
get { return true; }
}
public override Sprite Image
{
get { return sprite[0]; }
}
public override PropertySpec[] CustomProperties
{
get { return properties; }
}
public override ReadOnlyCollection<byte> Subtypes
{
get { return subtypes; }
}
public override string SubtypeName(byte subtype)
{
return null;
}
public override Sprite SubtypeImage(byte subtype)
{
return sprite[0];
}
public override Sprite GetSprite(ObjectEntry obj)
{
return sprite[(obj.XFlip ? 1 : 0) | (obj.YFlip ? 2 : 0)];
}
public override Sprite GetDebugOverlay(ObjectEntry obj)
{
if ((obj.SubType & 0x3F) == 0) return null;
var bounds = GetBounds(obj);
var bitmap = new BitmapBits(bounds.Width, bounds.Height);
bitmap.DrawRectangle(LevelData.ColorWhite, 0, 0, bounds.Width - 1, bounds.Height - 1);
return new Sprite(bitmap, -bounds.Width / 2, -bounds.Height / 2);
}
public override Rectangle GetBounds(ObjectEntry obj)
{
if ((obj.SubType & 0x3F) == 0) return base.GetBounds(obj);
var length = (obj.SubType & 0x3F) << 4;
if (obj.SubType >= 0x80)
return new Rectangle(obj.X - 32, obj.Y - (length / 2), 64, length);
var height = (obj.SubType & 0x40) == 0 ? 64 : 192;
return new Rectangle(obj.X - (length / 2), obj.Y - (height / 2), length, height);
}
public override void Init(ObjectData data)
{
properties = new PropertySpec[2];
subtypes = new ReadOnlyCollection<byte>(new byte[0]);
sprite = BuildFlippedSprites(ObjectHelper.UnknownObject);
properties[0] = new PropertySpec("Direction", typeof(int), "Extended",
"The object's orientation.", null, new Dictionary<string, int>
{
{ "Horizontal", 0 },
{ "Horizontal (wide)", 0x40 },
{ "Vertical", 0x80 }
},
(obj) => (obj.SubType & 0x80) != 0 ? 0x80 : (obj.SubType & 0xC0),
(obj, value) => obj.SubType = (byte)((obj.SubType & 0x3F) | ((int)value & 0xC0)));
properties[1] = new PropertySpec("Length", typeof(int), "Extended",
"The range of the object, in pixels.", null,
(obj) => (obj.SubType & 0x3F) << 4,
(obj, value) => obj.SubType = (byte)((obj.SubType & 0xC0) | (((int)value >> 4) & 0x3F)));
}
private Sprite[] BuildFlippedSprites(Sprite sprite)
{
var flipX = new Sprite(sprite, true, false);
var flipY = new Sprite(sprite, false, true);
var flipXY = new Sprite(sprite, true, true);
return new[] { sprite, flipX, flipY, flipXY };
}
}
}
| 412 | 0.816522 | 1 | 0.816522 | game-dev | MEDIA | 0.860778 | game-dev | 0.953545 | 1 | 0.953545 |
signumsoftware/framework | 1,498 | Signum/Entities/Patterns/ImmutableEntity.cs | using System.Runtime.CompilerServices;
namespace Signum.Entities;
public abstract class ImmutableEntity : Entity
{
[Ignore]
bool allowTemporaly = false;
public bool AllowChange
{
get { return tempDisabled.Value || allowTemporaly || IsNew; }
set { allowTemporaly = value; Notify(() => AllowChange); }
}
protected override bool Set<T>(ref T variable, T value, [CallerMemberName]string? automaticPropertyName = null)
{
if (AllowChange)
return base.Set(ref variable, value, automaticPropertyName!);
else
return base.SetIfNew(ref variable, value, automaticPropertyName!);
}
protected internal override void PreSaving(PreSavingContext ctx)
{
if (AllowChange)
base.PreSaving(ctx);
else
if (Modified == ModifiedState.SelfModified)
throw new InvalidOperationException($"Attempt to save a not new modified ImmutableEntity ({this.GetType().TypeName()})");
}
public IDisposable AllowChanges()
{
bool old = this.AllowChange;
this.AllowChange = true;
return new Disposable(() => this.AllowChange = old);
}
static readonly Variable<bool> tempDisabled = Statics.ThreadVariable<bool>("immutableTempDisabled");
public static IDisposable? Disable()
{
if (tempDisabled.Value) return null;
tempDisabled.Value = true;
return new Disposable(() => tempDisabled.Value = false);
}
}
| 412 | 0.912807 | 1 | 0.912807 | game-dev | MEDIA | 0.246809 | game-dev | 0.839638 | 1 | 0.839638 |
MohistMC/Youer | 2,617 | patches/net/minecraft/network/protocol/game/ClientboundCommandsPacket.java.patch | --- a/net/minecraft/network/protocol/game/ClientboundCommandsPacket.java
+++ b/net/minecraft/network/protocol/game/ClientboundCommandsPacket.java
@@ -5,12 +_,13 @@
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
-import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import com.mojang.brigadier.tree.ArgumentCommandNode;
import com.mojang.brigadier.tree.CommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;
import com.mojang.brigadier.tree.RootCommandNode;
+import io.netty.buffer.Unpooled;
+import io.papermc.paper.configuration.GlobalConfiguration;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.ints.IntSets;
@@ -33,6 +_,7 @@
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.PacketType;
import net.minecraft.resources.ResourceLocation;
+import org.spigotmc.SpigotConfig;
public class ClientboundCommandsPacket implements Packet<ClientGamePacketListener> {
public static final StreamCodec<FriendlyByteBuf, ClientboundCommandsPacket> STREAM_CODEC = Packet.codec(
@@ -242,8 +_,21 @@
private static <A extends ArgumentType<?>, T extends ArgumentTypeInfo.Template<A>> void serializeCap(
FriendlyByteBuf p_237663_, ArgumentTypeInfo<A, T> p_237664_, ArgumentTypeInfo.Template<A> p_237665_
) {
+ // Youer start
+ ResourceLocation key = BuiltInRegistries.COMMAND_ARGUMENT_TYPE.getKey(p_237664_);
+ if ((!GlobalConfiguration.get().proxies.velocity.enabled && !SpigotConfig.bungee) || ((key != null) && (key.getNamespace().equals("minecraft") || key.getNamespace().equals("brigadier")))) {
+ p_237663_.writeVarInt(BuiltInRegistries.COMMAND_ARGUMENT_TYPE.getId(p_237664_));
+ p_237664_.serializeToNetwork((T) p_237665_, p_237663_);
+ return;
+ }
+ p_237663_.writeVarInt(-256);
p_237663_.writeVarInt(BuiltInRegistries.COMMAND_ARGUMENT_TYPE.getId(p_237664_));
- p_237664_.serializeToNetwork((T)p_237665_, p_237663_);
+ FriendlyByteBuf payload = new FriendlyByteBuf(Unpooled.buffer());
+ p_237664_.serializeToNetwork((T) p_237665_, payload);
+ p_237663_.writeVarInt(payload.readableBytes());
+ p_237663_.writeBytes(payload);
+ payload.release();
+ // Youer end
}
}
| 412 | 0.803129 | 1 | 0.803129 | game-dev | MEDIA | 0.96168 | game-dev,networking | 0.866021 | 1 | 0.866021 |
Automattic/wp-calypso | 1,952 | client/state/data-layer/wpcom/sites/scan/threats/fix-all-threats.js | import i18n from 'i18n-calypso';
import { JETPACK_SCAN_THREATS_FIX_ALL } from 'calypso/state/action-types';
import { registerHandlers } from 'calypso/state/data-layer/handler-registry';
import { http } from 'calypso/state/data-layer/wpcom-http/actions';
import { dispatchRequest } from 'calypso/state/data-layer/wpcom-http/utils';
import {
updateThreat,
updateThreatCompleted,
getFixThreatsStatus,
} from 'calypso/state/jetpack-scan/threats/actions';
import { errorNotice, successNotice, infoNotice } from 'calypso/state/notices/actions';
export const request = ( action ) => {
const notice = successNotice( i18n.translate( 'Fixing all threatsβ¦' ), { duration: 30000 } );
const {
notice: { noticeId },
} = notice;
return [
notice,
http(
{
apiNamespace: 'wpcom/v2',
method: 'POST',
path: `/sites/${ action.siteId }/alerts/fix`,
body: { threat_ids: action.threatIds },
},
{ ...action, noticeId }
),
...action.threatIds.map( ( threatId ) => updateThreat( action.siteId, threatId ) ),
];
};
// We don't have a wait to only execute this path if all request succeeded.
export const success = ( action ) => [
infoNotice(
i18n.translate(
"We're hard at work fixing these threats in the background. Please check back shortly."
),
{
duration: 4000,
id: action.noticeId,
}
),
getFixThreatsStatus( action.siteId, action.threatIds ),
];
// Not sure if this is even going to happen. Maybe if all of them fail.
export const failure = ( action ) => [
errorNotice( i18n.translate( 'Error fixing threats. Please contact support.' ), {
duration: 10000,
id: action.noticeId,
} ),
...action.threatIds.map( ( threatId ) => updateThreatCompleted( action.siteId, threatId ) ),
];
registerHandlers( 'state/data-layer/wpcom/sites/scan/threats/fix-all-threats.js', {
[ JETPACK_SCAN_THREATS_FIX_ALL ]: [
dispatchRequest( {
fetch: request,
onSuccess: success,
onError: failure,
} ),
],
} );
| 412 | 0.848068 | 1 | 0.848068 | game-dev | MEDIA | 0.241478 | game-dev | 0.79877 | 1 | 0.79877 |
CommandAPI/CommandAPI | 2,610 | commandapi-platforms/commandapi-bukkit/commandapi-bukkit-core/src/main/java/dev/jorel/commandapi/arguments/MathOperationArgument.java | /*******************************************************************************
* Copyright 2018, 2020 Jorel Ali (Skepter) - MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/
package dev.jorel.commandapi.arguments;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import dev.jorel.commandapi.CommandAPIBukkit;
import dev.jorel.commandapi.executors.CommandArguments;
import dev.jorel.commandapi.wrappers.MathOperation;
/**
* An argument that represents Minecraft scoreboard math operations
*
* @since 3.0
*/
public class MathOperationArgument extends SafeOverrideableArgument<MathOperation, MathOperation> {
/**
* A MathOperation argument. Represents a math operation (e.g. addition, subtraction etc.)
* @param nodeName the name of the node for this argument
*/
public MathOperationArgument(String nodeName) {
super(nodeName, CommandAPIBukkit.get().getNMS()._ArgumentMathOperation(), MathOperation::toString);
}
@Override
public Class<MathOperation> getPrimitiveType() {
return MathOperation.class;
}
@Override
public CommandAPIArgumentType getArgumentType() {
return CommandAPIArgumentType.MATH_OPERATION;
}
@Override
public <CommandSourceStack> MathOperation parseArgument(CommandContext<CommandSourceStack> cmdCtx, String key, CommandArguments previousArgs) throws CommandSyntaxException {
return CommandAPIBukkit.<CommandSourceStack>get().getNMS().getMathOperation(cmdCtx, key);
}
}
| 412 | 0.67107 | 1 | 0.67107 | game-dev | MEDIA | 0.53363 | game-dev | 0.886052 | 1 | 0.886052 |
EphemeralSpace/ephemeral-space | 1,861 | Content.Client/Mech/Ui/MechBoundUserInterface.cs | using Content.Client.UserInterface.Fragments;
using Content.Shared.Mech;
using Content.Shared.Mech.Components;
using JetBrains.Annotations;
using Robust.Client.GameObjects;
using Robust.Client.UserInterface;
namespace Content.Client.Mech.Ui;
[UsedImplicitly]
public sealed class MechBoundUserInterface : BoundUserInterface
{
[ViewVariables]
private MechMenu? _menu;
public MechBoundUserInterface(EntityUid owner, Enum uiKey) : base(owner, uiKey)
{
}
protected override void Open()
{
base.Open();
_menu = this.CreateWindowCenteredLeft<MechMenu>();
_menu.SetEntity(Owner);
_menu.OnRemoveButtonPressed += uid =>
{
SendMessage(new MechEquipmentRemoveMessage(EntMan.GetNetEntity(uid)));
};
}
protected override void UpdateState(BoundUserInterfaceState state)
{
base.UpdateState(state);
if (state is not MechBoundUiState msg)
return;
UpdateEquipmentControls(msg);
_menu?.UpdateMechStats();
_menu?.UpdateEquipmentView();
}
public void UpdateEquipmentControls(MechBoundUiState state)
{
if (!EntMan.TryGetComponent<MechComponent>(Owner, out var mechComp))
return;
foreach (var ent in mechComp.EquipmentContainer.ContainedEntities)
{
var ui = GetEquipmentUi(ent);
if (ui == null)
continue;
foreach (var (attached, estate) in state.EquipmentStates)
{
if (ent == EntMan.GetEntity(attached))
ui.UpdateState(estate);
}
}
}
public UIFragment? GetEquipmentUi(EntityUid? uid)
{
var component = EntMan.GetComponentOrNull<UIFragmentComponent>(uid);
component?.Ui?.Setup(this, uid);
return component?.Ui;
}
}
| 412 | 0.782792 | 1 | 0.782792 | game-dev | MEDIA | 0.757399 | game-dev | 0.705603 | 1 | 0.705603 |
molstar/molstar | 4,105 | src/mol-geo/primitive/pyramid.ts | /**
* Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author Alexander Rose <alexander.rose@weirdbyte.de>
*/
import { Vec3 } from '../../mol-math/linear-algebra';
import { Primitive, PrimitiveBuilder, createPrimitive } from './primitive';
import { polygon } from './polygon';
import { Cage } from './cage';
const on = Vec3.create(0, 0, -0.5), op = Vec3.create(0, 0, 0.5);
const a = Vec3(), b = Vec3(), c = Vec3(), d = Vec3();
/**
* Create a pyramid with a polygonal base
*/
export function Pyramid(points: ArrayLike<number>): Primitive {
const sideCount = points.length / 3;
const baseCount = sideCount === 3 ? 1 : sideCount === 4 ? 2 : sideCount;
const triangleCount = baseCount + sideCount;
const vertexCount = sideCount === 4 ? (sideCount * 3 + 4) : triangleCount * 3;
const builder = PrimitiveBuilder(triangleCount, vertexCount);
// create sides
for (let i = 0; i < sideCount; ++i) {
const ni = (i + 1) % sideCount;
Vec3.set(a, points[i * 3], points[i * 3 + 1], -0.5);
Vec3.set(b, points[ni * 3], points[ni * 3 + 1], -0.5);
builder.add(a, b, op);
}
// create base
if (sideCount === 3) {
Vec3.set(a, points[0], points[1], -0.5);
Vec3.set(b, points[3], points[4], -0.5);
Vec3.set(c, points[6], points[7], -0.5);
builder.add(c, b, a);
} else if (sideCount === 4) {
Vec3.set(a, points[0], points[1], -0.5);
Vec3.set(b, points[3], points[4], -0.5);
Vec3.set(c, points[6], points[7], -0.5);
Vec3.set(d, points[9], points[10], -0.5);
builder.addQuad(d, c, b, a);
} else {
for (let i = 0; i < sideCount; ++i) {
const ni = (i + 1) % sideCount;
Vec3.set(a, points[i * 3], points[i * 3 + 1], -0.5);
Vec3.set(b, points[ni * 3], points[ni * 3 + 1], -0.5);
builder.add(on, b, a);
}
}
return builder.getPrimitive();
}
let triangularPyramid: Primitive;
export function TriangularPyramid() {
if (!triangularPyramid) triangularPyramid = Pyramid(polygon(3, true));
return triangularPyramid;
}
let octagonalPyramid: Primitive;
export function OctagonalPyramid() {
if (!octagonalPyramid) octagonalPyramid = Pyramid(polygon(8, true));
return octagonalPyramid;
}
let perforatedOctagonalPyramid: Primitive;
export function PerforatedOctagonalPyramid() {
if (!perforatedOctagonalPyramid) {
const points = polygon(8, true);
const vertices = new Float32Array(8 * 3 + 6);
for (let i = 0; i < 8; ++i) {
vertices[i * 3] = points[i * 3];
vertices[i * 3 + 1] = points[i * 3 + 1];
vertices[i * 3 + 2] = -0.5;
}
vertices[8 * 3] = 0;
vertices[8 * 3 + 1] = 0;
vertices[8 * 3 + 2] = -0.5;
vertices[8 * 3 + 3] = 0;
vertices[8 * 3 + 4] = 0;
vertices[8 * 3 + 5] = 0.5;
const indices: ReadonlyArray<number> = [
0, 1, 8, 1, 2, 8, 4, 5, 8, 5, 6, 8,
2, 3, 9, 3, 4, 9, 6, 7, 9, 7, 0, 9
];
perforatedOctagonalPyramid = createPrimitive(vertices, indices);
}
return perforatedOctagonalPyramid;
}
//
/**
* Create a prism cage
*/
export function PyramidCage(points: ArrayLike<number>): Cage {
const sideCount = points.length / 3;
// const count = 4 * sideCount
const vertices: number[] = [];
const edges: number[] = [];
let offset = 1;
vertices.push(op[0], op[1], op[2]);
// vertices and side edges
for (let i = 0; i < sideCount; ++i) {
vertices.push(points[i * 3], points[i * 3 + 1], -0.5);
edges.push(0, offset);
offset += 1;
}
// bases edges
for (let i = 0; i < sideCount; ++i) {
const ni = (i + 1) % sideCount;
edges.push(i + 1, ni + 1);
}
return { vertices, edges };
}
let octagonalPyramidCage: Cage;
export function OctagonalPyramidCage() {
if (!octagonalPyramidCage) octagonalPyramidCage = PyramidCage(polygon(8, true));
return octagonalPyramidCage;
} | 412 | 0.686504 | 1 | 0.686504 | game-dev | MEDIA | 0.417766 | game-dev,graphics-rendering | 0.932453 | 1 | 0.932453 |
shanecoughlan/OpenGEM | 5,540 | source/OpenGEM-7-RC3-SDK/OpenGEM-7-SDK/VIDEO AND SOUND DRIVERS AND SOURCE CODE/SOURCE AND BINARY CODE - Obscure Drivers/Wang Professional Computer/entry.a86 | ;************************************************************************
;* Copyright 1999, Caldera Thin Clients, Inc. *
;* This software is licenced under the GNU Public License. *
;* Please see LICENSE.TXT for further information. *
;* *
;* Historical Copyright *
;* *
;* *
;* *
;* Copyright (c) 1987, Digital Research, Inc. All Rights Reserved. *
;* The Software Code contained in this listing is proprietary to *
;* Digital Research, Inc., Monterey, California and is covered by U.S. *
;* and other copyright protection. Unauthorized copying, adaptation, *
;* distribution, use or display is prohibited and may be subject to *
;* civil and criminal penalties. Disclosure to others is prohibited. *
;* For the terms and conditions of software code use refer to the *
;* appropriate Digital Research License Agreement. *
;* *
;************************************************************************
;
include externs.a86
W_0 equ word ptr 0
W_1 equ word ptr 2
W_2 equ word ptr 4
W_3 equ word ptr 6
W_4 equ word ptr 8
W_5 equ word ptr 10
W_6 equ word ptr 12
W_7 equ word ptr 14
W_8 equ word ptr 16
W_9 equ word ptr 18
W_10 equ word ptr 20
W_11 equ word ptr 22
;
dseg
extrn DEV_TAB:word
cseg
extrn SCREEN:near
;
public entry
entry:
push si
pushf ;save state on old stack
pop si
pushf ; dx = old flag state
cli
if GSX
mov ax, seg ptsin_ptr
else
or ax,ax ;if ax contains 0, it is OW call,
jnz not_OW ;else ax contains data segment
mov ax,seg ptsin_ptr
Not_OW:
endif
mov cx,sp
mov bx,ss
mov ss,ax
mov sp, offset FLIP_Y ;set up local stack
push cx ; save sp
push bx ; save ss
push si
popf ; get orriginal flag state
mov es,ax ;ax is our dseg
mov di,offset contrl_ptr ;point to array pointer storage
mov si,dx
mov cx,10
rep movsw ;store 5 long array pointers
mov ds,ax ;set ds to data seg
mov di,offset CONTRL ;point es:di to our control array
push ds
lds si,contrl_ptr ;point ds:si to app control array
mov cx,CONTRL_SIZE
rep movsw ;copy control array in to our dseg
pop ds
mov si,offset CONTRL
mov W_2[si],0 ;init intout count and ptsout count
mov W_4[si],0
mov cx,W_1[si] ;length of ptsin
shl cx,1 ;two words per point
cmp cx,PTSIN_SIZE
jb ptsok
cmp cx,2998
jb ptsok1
mov W_1[si],1499
ptsok1:
mov cx,256
ptsok: mov di,offset PTSIN
push ds
lds si,ptsin_ptr
rep movsw ;copy ptsin array to our dseg
pop ds
mov si,offset CONTRL
mov cx,W_3[si] ;length of intin
cmp cx,2
ja chk_intin_max
mov cx,2
jmps intok
chk_intin_max:
cmp cx,INTIN_SIZE
jb intok
mov cx,INTIN_SIZE
mov W_3[si], cx
intok: mov di,offset INTIN
push ds
lds si,intin_ptr
rep movsw ;mov intin array to our dseg
pop ds
if GSX
;
; GSX has the Y origin at the bottom; GEM has it at the top. So flip all
; Y-coordinates here (GEM does it in the VDI).
;
mov si, offset PTSIN+2
mov bx, DEV_TAB+2
inc bx
mov cx, word ptr CONTRL+2 ;Number of points
or cx, cx
jz noflip
cmp cx, PTSIN_SIZE/2 ;If there are more than fit in the
jc flipit ;array, limit it.
mov cx, PTSIN_SIZE/2
flipit: mov ax, bx
sub ax, [si]
cmp ax, bx
jc flip1 ;If that sent the coordinates over
mov ax, bx ;the edge, clip to edge
dec ax
flip1:
mov [si], ax
add si, 4
loop flipit
noflip:
endif
;; points_out is not present in SDPSC9
;; mov si, offset ptsout ; jn, justified text fix
;; mov points_out, si ; jn, justified text fix
mov FLIP_Y,0 ;set the flip y flag
mov bez_flag,-1
mov al, cs:slot
or al, al
jz noslot
mov dh, al
mov dl, 10h ; Video card control register
mov al, cs:ctlbyte
and al, 0Ch
or al, 1
out dx, al ; Video card paged in
mov cs:ctlbyte, al
noslot:
;
call SCREEN ;go to 'C' part of driver
;
mov al, cs:slot
or al, al
jz noslot2
mov dh, al
mov dl, 10h ; Video card control register
mov al, cs:ctlbyte
and al, 0Ch
out dx, al ; Video card paged out
mov cs:ctlbyte, al
noslot2:
mov si,offset CONTRL
les di,contrl_ptr
mov bx,W_8[si]
mov es:W_8[di],bx ;contrl[8]
mov bx,W_7[si]
mov es:W_7[di],bx ;contrl[7]
mov bx,W_4[si]
mov es:W_4[di],bx ;contrl[4] = intout size
mov cx,W_2[si]
mov es:W_2[di],cx ;contrl[2] = ptsout size
and cx,cx
jz ret_intout
shl cx,1 ;two words per point
les di,ptsout_ptr
mov si,offset PTSOUT ; jn, justified text fix
;; mov si, points_out ; jn, justified text fix
rep movsw
ret_intout:
and bx,bx
jz ret_done
mov cx,bx
les di,intout_ptr
mov si,offset INTOUT
rep movsw
ret_done:
mov ax,FLIP_Y ; return the flip flag 0 ok 1 = no
cli
pop cx ;get the old ss
pop bx ;get the old sp
mov ss,cx
mov sp,bx
popf
pop si ;get orriginal si back
retf
;
public SLOT, CTLBYTE
slot db 0
ctlbyte db 0
;
;************************************************************************
;* data area *
;************************************************************************
;
DATA dseg PUBLIC word
DGROUP GROUP DATA
public FLIP_Y
public XFM_MODE
public contrl_ptr
public ptsin_ptr
public intin_ptr
public ptsout_ptr
public intout_ptr
;; extrn points_out:word ; jn, justified text fix
extrn CONTRL:word,INTOUT:word,INTIN:word,PTSIN:word,PTSOUT:word
extrn bez_flag:word
;
contrl_ptr rd 1
intin_ptr rd 1
ptsin_ptr rd 1
intout_ptr rd 1
ptsout_ptr rd 1
stack rs 256
FLIP_Y dw 0
XFM_MODE dw 0
;
end entry
| 412 | 0.973521 | 1 | 0.973521 | game-dev | MEDIA | 0.605237 | game-dev | 0.972854 | 1 | 0.972854 |
RoboMaster/RoboRTS | 5,476 | roborts_decision/example_behavior/chase_behavior.h | #ifndef ROBORTS_DECISION_CHASE_BEHAVIOR_H
#define ROBORTS_DECISION_CHASE_BEHAVIOR_H
#include "io/io.h"
#include "../blackboard/blackboard.h"
#include "../executor/chassis_executor.h"
#include "../behavior_tree/behavior_state.h"
#include "../proto/decision.pb.h"
#include "line_iterator.h"
namespace roborts_decision {
class ChaseBehavior {
public:
ChaseBehavior(ChassisExecutor* &chassis_executor,
Blackboard* &blackboard,
const std::string & proto_file_path) : chassis_executor_(chassis_executor),
blackboard_(blackboard) {
chase_goal_.header.frame_id = "map";
chase_goal_.pose.orientation.x = 0;
chase_goal_.pose.orientation.y = 0;
chase_goal_.pose.orientation.z = 0;
chase_goal_.pose.orientation.w = 1;
chase_goal_.pose.position.x = 0;
chase_goal_.pose.position.y = 0;
chase_goal_.pose.position.z = 0;
chase_buffer_.resize(2);
chase_count_ = 0;
cancel_goal_ = true;
}
void Run() {
auto executor_state = Update();
auto robot_map_pose = blackboard_->GetRobotMapPose();
if (executor_state != BehaviorState::RUNNING) {
chase_buffer_[chase_count_++ % 2] = blackboard_->GetEnemy();
chase_count_ = chase_count_ % 2;
auto dx = chase_buffer_[(chase_count_ + 2 - 1) % 2].pose.position.x - robot_map_pose.pose.position.x;
auto dy = chase_buffer_[(chase_count_ + 2 - 1) % 2].pose.position.y - robot_map_pose.pose.position.y;
auto yaw = std::atan2(dy, dx);
if (std::sqrt(std::pow(dx, 2) + std::pow(dy, 2)) >= 1.0 && std::sqrt(std::pow(dx, 2) + std::pow(dy, 2)) <= 2.0) {
if (cancel_goal_) {
chassis_executor_->Cancel();
cancel_goal_ = false;
}
return;
} else {
auto orientation = tf::createQuaternionMsgFromYaw(yaw);
geometry_msgs::PoseStamped reduce_goal;
reduce_goal.pose.orientation = robot_map_pose.pose.orientation;
reduce_goal.header.frame_id = "map";
reduce_goal.header.stamp = ros::Time::now();
reduce_goal.pose.position.x = chase_buffer_[(chase_count_ + 2 - 1) % 2].pose.position.x - 1.2 * cos(yaw);
reduce_goal.pose.position.y = chase_buffer_[(chase_count_ + 2 - 1) % 2].pose.position.y - 1.2 * sin(yaw);
auto enemy_x = reduce_goal.pose.position.x;
auto enemy_y = reduce_goal.pose.position.y;
reduce_goal.pose.position.z = 1;
unsigned int goal_cell_x, goal_cell_y;
// if necessary add mutex lock
//blackboard_->GetCostMap2D()->GetMutex()->lock();
auto get_enemy_cell = blackboard_->GetCostMap2D()->World2Map(enemy_x,
enemy_y,
goal_cell_x,
goal_cell_y);
//blackboard_->GetCostMap2D()->GetMutex()->unlock();
if (!get_enemy_cell) {
return;
}
auto robot_x = robot_map_pose.pose.position.x;
auto robot_y = robot_map_pose.pose.position.y;
unsigned int robot_cell_x, robot_cell_y;
double goal_x, goal_y;
blackboard_->GetCostMap2D()->World2Map(robot_x,
robot_y,
robot_cell_x,
robot_cell_y);
if (blackboard_->GetCostMap2D()->GetCost(goal_cell_x, goal_cell_y) >= 253) {
bool find_goal = false;
for(FastLineIterator line( goal_cell_x, goal_cell_y, robot_cell_x, robot_cell_x); line.IsValid(); line.Advance()) {
auto point_cost = blackboard_->GetCostMap2D()->GetCost((unsigned int) (line.GetX()), (unsigned int) (line.GetY())); //current point's cost
if(point_cost >= 253){
continue;
} else {
find_goal = true;
blackboard_->GetCostMap2D()->Map2World((unsigned int) (line.GetX()),
(unsigned int) (line.GetY()),
goal_x,
goal_y);
reduce_goal.pose.position.x = goal_x;
reduce_goal.pose.position.y = goal_y;
break;
}
}
if (find_goal) {
cancel_goal_ = true;
chassis_executor_->Execute(reduce_goal);
} else {
if (cancel_goal_) {
chassis_executor_->Cancel();
cancel_goal_ = false;
}
return;
}
} else {
cancel_goal_ = true;
chassis_executor_->Execute(reduce_goal);
}
}
}
}
void Cancel() {
chassis_executor_->Cancel();
}
BehaviorState Update() {
return chassis_executor_->Update();
}
void SetGoal(geometry_msgs::PoseStamped chase_goal) {
chase_goal_ = chase_goal;
}
~ChaseBehavior() = default;
private:
//! executor
ChassisExecutor* const chassis_executor_;
//! perception information
Blackboard* const blackboard_;
//! chase goal
geometry_msgs::PoseStamped chase_goal_;
//! chase buffer
std::vector<geometry_msgs::PoseStamped> chase_buffer_;
unsigned int chase_count_;
//! cancel flag
bool cancel_goal_;
};
}
#endif //ROBORTS_DECISION_CHASE_BEHAVIOR_H
| 412 | 0.673337 | 1 | 0.673337 | game-dev | MEDIA | 0.947709 | game-dev | 0.814652 | 1 | 0.814652 |
dviglo/dviglo | 8,152 | source/dviglo/scene/spline_path.cpp | // Copyright (c) 2008-2023 the Urho3D project
// Copyright (c) the Dviglo project
// License: MIT
#include "../core/context.h"
#include "../io/log.h"
#include "scene.h"
#include "spline_path.h"
namespace dviglo
{
extern const char* interpolationModeNames[];
extern const char* LOGIC_CATEGORY;
static const StringVector controlPointsStructureElementNames =
{
"Control Point Count",
" NodeID"
};
SplinePath::SplinePath() :
spline_(BEZIER_CURVE),
speed_(1.f),
elapsedTime_(0.f),
traveled_(0.f),
length_(0.f),
dirty_(false),
controlledIdAttr_(0)
{
UpdateNodeIds();
}
void SplinePath::register_object()
{
DV_CONTEXT->RegisterFactory<SplinePath>(LOGIC_CATEGORY);
DV_ENUM_ACCESSOR_ATTRIBUTE("Interpolation Mode", GetInterpolationMode, SetInterpolationMode,
interpolationModeNames, BEZIER_CURVE, AM_FILE);
DV_ATTRIBUTE("Speed", speed_, 1.f, AM_FILE);
DV_ATTRIBUTE("Traveled", traveled_, 0.f, AM_FILE | AM_NOEDIT);
DV_ATTRIBUTE("Elapsed Time", elapsedTime_, 0.f, AM_FILE | AM_NOEDIT);
DV_ACCESSOR_ATTRIBUTE("Controlled", GetControlledIdAttr, SetControlledIdAttr, 0, AM_FILE | AM_NODEID);
DV_ACCESSOR_ATTRIBUTE("Control Points", GetControlPointIdsAttr, SetControlPointIdsAttr,
Variant::emptyVariantVector, AM_FILE | AM_NODEIDVECTOR)
.SetMetadata(AttributeMetadata::P_VECTOR_STRUCT_ELEMENTS, controlPointsStructureElementNames);
}
void SplinePath::apply_attributes()
{
if (!dirty_)
return;
// Remove all old instance nodes before searching for new. Can not call RemoveAllInstances() as that would modify
// the ID list on its own
for (unsigned i = 0; i < controlPoints_.Size(); ++i)
{
Node* node = controlPoints_[i];
if (node)
node->RemoveListener(this);
}
controlPoints_.Clear();
spline_.Clear();
Scene* scene = GetScene();
if (scene)
{
// The first index stores the number of IDs redundantly. This is for editing
for (unsigned i = 1; i < controlPointIdsAttr_.Size(); ++i)
{
Node* node = scene->GetNode(controlPointIdsAttr_[i].GetU32());
if (node)
{
WeakPtr<Node> controlPoint(node);
node->AddListener(this);
controlPoints_.Push(controlPoint);
spline_.AddKnot(node->GetWorldPosition());
}
}
Node* node = scene->GetNode(controlledIdAttr_);
if (node)
{
WeakPtr<Node> controlled(node);
controlledNode_ = controlled;
}
}
CalculateLength();
dirty_ = false;
}
void SplinePath::draw_debug_geometry(DebugRenderer* debug, bool /*depthTest*/)
{
if (debug && node_ && IsEnabledEffective())
{
if (spline_.GetKnots().Size() > 1)
{
Vector3 a = spline_.GetPoint(0.f).GetVector3();
for (auto i = 1; i <= 100; ++i)
{
Vector3 b = spline_.GetPoint(i / 100.f).GetVector3();
debug->AddLine(a, b, Color::GREEN);
a = b;
}
}
for (Vector<WeakPtr<Node>>::ConstIterator i = controlPoints_.Begin(); i != controlPoints_.End(); ++i)
debug->AddNode(*i);
if (controlledNode_)
debug->AddNode(controlledNode_);
}
}
void SplinePath::AddControlPoint(Node* point, unsigned index)
{
if (!point)
return;
WeakPtr<Node> controlPoint(point);
point->AddListener(this);
controlPoints_.Insert(index, controlPoint);
spline_.AddKnot(point->GetWorldPosition(), index);
UpdateNodeIds();
CalculateLength();
}
void SplinePath::RemoveControlPoint(Node* point)
{
if (!point)
return;
WeakPtr<Node> controlPoint(point);
point->RemoveListener(this);
for (unsigned i = 0; i < controlPoints_.Size(); ++i)
{
if (controlPoints_[i] == controlPoint)
{
controlPoints_.Erase(i);
spline_.RemoveKnot(i);
break;
}
}
UpdateNodeIds();
CalculateLength();
}
void SplinePath::ClearControlPoints()
{
for (unsigned i = 0; i < controlPoints_.Size(); ++i)
{
Node* node = controlPoints_[i];
if (node)
node->RemoveListener(this);
}
controlPoints_.Clear();
spline_.Clear();
UpdateNodeIds();
CalculateLength();
}
void SplinePath::SetControlledNode(Node* controlled)
{
if (controlled)
controlledNode_ = WeakPtr<Node>(controlled);
}
void SplinePath::SetInterpolationMode(InterpolationMode interpolationMode)
{
spline_.SetInterpolationMode(interpolationMode);
CalculateLength();
}
void SplinePath::SetPosition(float factor)
{
float t = factor;
if (t < 0.f)
t = 0.0f;
else if (t > 1.0f)
t = 1.0f;
traveled_ = t;
}
Vector3 SplinePath::GetPoint(float factor) const
{
return spline_.GetPoint(factor).GetVector3();
}
void SplinePath::Move(float timeStep)
{
if (traveled_ >= 1.0f || length_ <= 0.0f || controlledNode_.Null())
return;
elapsedTime_ += timeStep;
// Calculate where we should be on the spline based on length, speed and time. If that is less than the set traveled_ don't move till caught up.
float distanceCovered = elapsedTime_ * speed_;
traveled_ = distanceCovered / length_;
controlledNode_->SetWorldPosition(GetPoint(traveled_));
}
void SplinePath::Reset()
{
traveled_ = 0.f;
elapsedTime_ = 0.f;
}
void SplinePath::SetControlPointIdsAttr(const VariantVector& value)
{
// Just remember the node IDs. They need to go through the SceneResolver, and we actually find the nodes during
// apply_attributes()
if (value.Size())
{
controlPointIdsAttr_.Clear();
unsigned index = 0;
unsigned numInstances = value[index++].GetU32();
// Prevent crash on entering negative value in the editor
if (numInstances > M_MAX_INT)
numInstances = 0;
controlPointIdsAttr_.Push(numInstances);
while (numInstances--)
{
// If vector contains less IDs than should, fill the rest with zeros
if (index < value.Size())
controlPointIdsAttr_.Push(value[index++].GetU32());
else
controlPointIdsAttr_.Push(0);
}
dirty_ = true;
}
else
{
controlPointIdsAttr_.Clear();
controlPointIdsAttr_.Push(0);
dirty_ = true;
}
}
void SplinePath::SetControlledIdAttr(unsigned value)
{
if (value > 0 && value < M_MAX_UNSIGNED)
controlledIdAttr_ = value;
dirty_ = true;
}
void SplinePath::OnMarkedDirty(Node* point)
{
if (!point)
return;
WeakPtr<Node> controlPoint(point);
for (unsigned i = 0; i < controlPoints_.Size(); ++i)
{
if (controlPoints_[i] == controlPoint)
{
spline_.SetKnot(point->GetWorldPosition(), i);
break;
}
}
CalculateLength();
}
void SplinePath::OnNodeSetEnabled(Node* point)
{
if (!point)
return;
WeakPtr<Node> controlPoint(point);
for (unsigned i = 0; i < controlPoints_.Size(); ++i)
{
if (controlPoints_[i] == controlPoint)
{
if (point->IsEnabled())
spline_.AddKnot(point->GetWorldPosition(), i);
else
spline_.RemoveKnot(i);
break;
}
}
CalculateLength();
}
void SplinePath::UpdateNodeIds()
{
unsigned numInstances = controlPoints_.Size();
controlPointIdsAttr_.Clear();
controlPointIdsAttr_.Push(numInstances);
for (unsigned i = 0; i < numInstances; ++i)
{
Node* node = controlPoints_[i];
controlPointIdsAttr_.Push(node ? node->GetID() : 0);
}
}
void SplinePath::CalculateLength()
{
if (spline_.GetKnots().Size() <= 0)
return;
length_ = 0.f;
Vector3 a = spline_.GetKnot(0).GetVector3();
for (auto i = 0; i <= 1000; ++i)
{
Vector3 b = spline_.GetPoint(i / 1000.f).GetVector3();
length_ += Abs((a - b).Length());
a = b;
}
}
}
| 412 | 0.978064 | 1 | 0.978064 | game-dev | MEDIA | 0.398084 | game-dev | 0.9837 | 1 | 0.9837 |
pixel-quest/pixel-games | 23,305 | games/classics_v1/classics_v1.lua | --[[
ΠΠ°Π·Π²Π°Π½ΠΈΠ΅: ΠΠ»Π°ΡΡΠΈΠΊΠΈ
ΠΠ²ΡΠΎΡ: Avondale, Π΄ΠΈΡΠΊΠΎΡΠ΄ - avonda
ΠΠΏΠΈΡΠ°Π½ΠΈΠ΅ ΠΌΠ΅Ρ
Π°Π½ΠΈΠΊΠΈ:
ΠΠ΄Π΅ΠΈ ΠΏΠΎ Π΄ΠΎΡΠ°Π±ΠΎΡΠΊΠ΅:
]]
math.randomseed(os.time())
require("avonlib")
local CLog = require("log")
local CInspect = require("inspect")
local CHelp = require("help")
local CJson = require("json")
local CTime = require("time")
local CAudio = require("audio")
local CColors = require("colors")
local tGame = {
Cols = 24,
Rows = 15,
Buttons = {},
}
local tConfig = {}
-- ΡΡΠ΅ΠΉΡΡ ΠΈΠ»ΠΈ ΡΡΠ°ΠΏΡ ΠΈΠ³ΡΡ
local GAMESTATE_SETUP = 1
local GAMESTATE_GAME = 2
local GAMESTATE_POSTGAME = 3
local GAMESTATE_FINISH = 4
local bGamePaused = false
local iGameState = GAMESTATE_SETUP
local iPrevTickTime = 0
local bAnyButtonClick = false
local tGameStats = {
StageLeftDuration = 0,
StageTotalDuration = 0,
CurrentStars = 0,
TotalStars = 0,
CurrentLives = 0,
TotalLives = 0,
Players = { -- ΠΌΠ°ΠΊΡΠΈΠΌΡΠΌ 6 ΠΈΠ³ΡΠΎΠΊΠΎΠ²
{ Score = 0, Lives = 0, Color = CColors.NONE },
{ Score = 0, Lives = 0, Color = CColors.NONE },
{ Score = 0, Lives = 0, Color = CColors.NONE },
{ Score = 0, Lives = 0, Color = CColors.NONE },
{ Score = 0, Lives = 0, Color = CColors.NONE },
{ Score = 0, Lives = 0, Color = CColors.NONE },
},
TargetScore = 0,
StageNum = 0,
TotalStages = 0,
TargetColor = CColors.NONE,
ScoreboardVariant = 6,
}
local tGameResults = {
Won = false,
AfterDelay = false,
PlayersCount = 0,
Score = 0,
Color = CColors.NONE,
}
local tFloor = {}
local tButtons = {}
local tFloorStruct = {
iColor = CColors.NONE,
iBright = CColors.BRIGHT0,
bClick = false,
bDefect = false,
iWeight = 0,
bAnimated = false,
}
local tButtonStruct = {
iColor = CColors.NONE,
iBright = CColors.BRIGHT0,
bClick = false,
bDefect = false,
}
local tArenaPlayerReady = {}
local tPlayerColors = {}
tPlayerColors[1] = CColors.GREEN
tPlayerColors[2] = CColors.YELLOW
tPlayerColors[3] = CColors.MAGENTA
tPlayerColors[4] = CColors.CYAN
tPlayerColors[5] = CColors.BLUE
tPlayerColors[6] = CColors.RED
function StartGame(gameJson, gameConfigJson)
tGame = CJson.decode(gameJson)
tConfig = CJson.decode(gameConfigJson)
for iX = 1, tGame.Cols do
tFloor[iX] = {}
for iY = 1, tGame.Rows do
tFloor[iX][iY] = CHelp.ShallowCopy(tFloorStruct)
end
end
for _, iId in pairs(tGame.Buttons) do
tButtons[iId] = CHelp.ShallowCopy(tButtonStruct)
end
iPrevTickTime = CTime.unix()
if AL.RoomHasNFZ(tGame) then
AL.LoadNFZInfo()
end
tGame.iMinX = 1
tGame.iMinY = 1
tGame.iMaxX = tGame.Cols
tGame.iMaxY = tGame.Rows
if AL.NFZ.bLoaded then
tGame.iMinX = AL.NFZ.iMinX
tGame.iMinY = AL.NFZ.iMinY
tGame.iMaxX = AL.NFZ.iMaxX
tGame.iMaxY = AL.NFZ.iMaxY
end
tGame.CenterX = math.floor((tGame.iMaxX-tGame.iMinX+1)/2)
tGame.CenterY = math.ceil((tGame.iMaxY-tGame.iMinY+1)/2)
tGame.StartPositionSizeX = 3
if tGame.ArenaMode then
local iX = math.floor(tGame.Cols/2) - (tGame.StartPositionSizeX*2)
for iPlayerID = 1, #tGame.StartPositions do
tGame.StartPositions[iPlayerID].Color = tonumber(tGame.StartPositions[iPlayerID].Color)
tGameStats.Players[iPlayerID].Color = tGame.StartPositions[iPlayerID].Color
end
else
tGame.StartPositions = {}
for iPlayerID = 1, tConfig.PlayerCount do
tGame.StartPositions[iPlayerID] = {}
tGame.StartPositions[iPlayerID].Color = tPlayerColors[iPlayerID]
tGameStats.Players[iPlayerID].Color = tPlayerColors[iPlayerID]
tGame.StartPositions[iPlayerID].Y = math.floor((tGame.iMaxY-tGame.iMinY+1)/3)
if iPlayerID % 2 ~= 0 then
tGame.StartPositions[iPlayerID].X = tGame.CenterX - (tGame.StartPositionSizeX+1)*math.ceil(iPlayerID/2)
else
tGame.StartPositions[iPlayerID].X = tGame.CenterX-1 + (tGame.StartPositionSizeX+1)*math.ceil(iPlayerID/2)
end
if tGame.StartPositions[iPlayerID].X < tGame.iMinX or tGame.StartPositions[iPlayerID].X+tGame.StartPositionSizeX > tGame.iMaxX then
CLog.print(tGame.StartPositions[iPlayerID].X)
tGame.StartPositions[iPlayerID] = nil
tGameStats.Players[iPlayerID].Color = CColors.NONE
tConfig.PlayerCount = iPlayerID-1
break;
end
end
end
tGameResults.PlayersCount = tConfig.PlayerCount
CGameMode.InitGameMode()
tGameStats.TargetScore = 1
CAudio.PlayVoicesSyncFromScratch("classics/classics-game.mp3")
if tGame.ArenaMode then
CAudio.PlayVoicesSync("press-zone-for-start.mp3")
else
CAudio.PlayVoicesSync("press-center-for-start.mp3")
end
--CAudio.PlaySync("voices/press-button-for-start.mp3")
AL.NewTimer((CAudio.GetVoicesDuration("classics/classics-game.mp3"))*1000, function()
CGameMode.bCanStart = true
end)
end
function NextTick()
if iGameState == GAMESTATE_SETUP then
GameSetupTick()
end
if iGameState == GAMESTATE_GAME then
GameTick()
end
if iGameState == GAMESTATE_POSTGAME then
PostGameTick()
if not tGameResults.AfterDelay then
tGameResults.AfterDelay = true
return tGameResults
end
end
if iGameState == GAMESTATE_FINISH then
tGameResults.AfterDelay = false
return tGameResults
end
AL.CountTimers((CTime.unix() - iPrevTickTime) * 1000)
iPrevTickTime = CTime.unix()
end
function GameSetupTick()
SetGlobalColorBright(CColors.NONE, tConfig.Bright) -- ΠΊΡΠ°ΡΠΈΠΌ Π²ΡΡ ΠΏΠΎΠ»Π΅ Π² ΠΎΠ΄ΠΈΠ½ ΡΠ²Π΅Ρ
CPaint.PlayerZones()
--SetAllButtonColorBright(CColors.GREEN, tConfig.Bright)
if tGame.ArenaMode then
bAnyButtonClick = false
for iPos, tPos in ipairs(tGame.StartPositions) do
if iPos <= #tGame.StartPositions then
local iCenterX = tPos.X + math.floor(tGame.StartPositionSizeX/3)-1
local iCenterY = tPos.Y + math.floor(tGame.StartPositionSizeY/3)
local bArenaClick = false
for iX = iCenterX, iCenterX+2 do
for iY = iCenterY, iCenterY+1 do
tFloor[iX][iY].iColor = CColors.MAGENTA
if tArenaPlayerReady[iPos] then
tFloor[iX][iY].iBright = tConfig.Bright+2
end
if tFloor[iX][iY].bClick then
bArenaClick = true
end
end
end
if bArenaClick then
bAnyButtonClick = true
tArenaPlayerReady[iPos] = true
else
tArenaPlayerReady[iPos] = false
end
end
end
elseif not CGameMode.bCountDownStarted and CGameMode.bCanStart then
for iX = tGame.CenterX, tGame.CenterX + 1 do
for iY = tGame.CenterY-1, tGame.CenterY do
tFloor[iX][iY].iColor = CColors.BLUE
tFloor[iX][iY].iBright = tConfig.Bright
if tFloor[iX][iY].bClick then bAnyButtonClick = true; end
end
end
end
if bAnyButtonClick and not CGameMode.bCountDownStarted then
CGameMode.CountDownNextRound()
end
end
function GameTick()
SetGlobalColorBright(CColors.NONE, tConfig.Bright) -- ΠΊΡΠ°ΡΠΈΠΌ Π²ΡΡ ΠΏΠΎΠ»Π΅ Π² ΠΎΠ΄ΠΈΠ½ ΡΠ²Π΅Ρ
CPaint.PlayerZones()
CPaint.Blocks()
end
function PostGameTick()
end
function RangeFloor(setPixel, setButton)
for iX = 1, tGame.Cols do
for iY = 1, tGame.Rows do
setPixel(iX , iY, tFloor[iX][iY].iColor, tFloor[iX][iY].iBright)
end
end
for i, tButton in pairs(tButtons) do
setButton(i, tButton.iColor, tButton.iBright)
end
end
function SwitchStage()
CGameMode.EndGame()
end
--GAMEMODE
CGameMode = {}
CGameMode.iCountdown = -1
CGameMode.iWinnerID = -1
CGameMode.bGameStarted = false
CGameMode.tPlayerSeeds = {}
CGameMode.tPlayerMapTotalCoinCount = {}
CGameMode.tPlayerMapTotalCoinCollected = {}
CGameMode.iDefaultSeed = 1
CGameMode.bCountDownStarted = false
CGameMode.bCanStart = false
CGameMode.InitGameMode = function()
if tGame.Direction == "right" then
CGameMode.iFinishPosition = tGame.StartPositionSizeX
elseif tGame.Direction == "left" then
CGameMode.iFinishPosition = 1
end
end
CGameMode.CountDownNextRound = function()
CGameMode.bGameStarted = false
CGameMode.iDefaultSeed = math.random(1,99999)
CGameMode.iCountdown = tConfig.GameCountdown
tGameStats.StageLeftDuration = CGameMode.iCountdown
CGameMode.bCountDownStarted = true
AL.NewTimer(1000, function()
CAudio.ResetSync()
tGameStats.StageLeftDuration = CGameMode.iCountdown
if tGame.ArenaMode and not bAnyButtonClick then
CGameMode.bCountDownStarted = false
return nil
end
if CGameMode.iCountdown <= 0 then
CGameMode.iCountdown = -1
CGameMode.Start()
CAudio.PlayVoicesSync(CAudio.START_GAME)
return nil
else
CAudio.PlayLeftAudio(CGameMode.iCountdown)
CGameMode.iCountdown = CGameMode.iCountdown - 1
return 1000
end
end)
end
CGameMode.Start = function()
iGameState = GAMESTATE_GAME
CAudio.PlayRandomBackground()
tGameStats.StageLeftDuration = tConfig.GameLength
CGameMode.bGameStarted = true
CGameMode.LoadMapsForPlayers()
if tGameStats.StageLeftDuration > 1 then
AL.NewTimer(1000, function()
tGameStats.StageLeftDuration = tGameStats.StageLeftDuration - 1
if tGameStats.StageLeftDuration <= 0 and CGameMode.EndGame() then
return nil
end
if tGameStats.StageLeftDuration < 10 then
CAudio.PlayLeftAudio(tGameStats.StageLeftDuration)
end
return 1000
end)
end
end
CGameMode.LoadMapsForPlayers = function()
for iPlayerID = 1, #tGame.StartPositions do
CGameMode.tPlayerSeeds[iPlayerID] = CGameMode.iDefaultSeed
CMaps.LoadMapForPlayer(iPlayerID)
CBlock.AnimateVisibility(iPlayerID)
end
end
CGameMode.PlayerRoundScoreAdd = function(iPlayerID, iScore)
tGameStats.Players[iPlayerID].Score = tGameStats.Players[iPlayerID].Score + iScore
if tGameStats.Players[iPlayerID].Score > tGameStats.TargetScore then
tGameStats.TargetScore = tGameStats.Players[iPlayerID].Score
end
CAudio.PlaySystemAsync(CAudio.CLICK);
end
CGameMode.PlayerScorePenalty = function(iPlayerID, iPenalty)
if tGameStats.Players[iPlayerID].Score > 0 then
tGameStats.Players[iPlayerID].Score = tGameStats.Players[iPlayerID].Score - iPenalty
end
CAudio.PlaySystemAsync(CAudio.MISCLICK);
end
CGameMode.PlayerFinished = function(iPlayerID)
CAudio.PlaySystemAsync(CAudio.STAGE_DONE)
CBlock.ClearPlayerZone(iPlayerID)
CMaps.LoadMapForPlayer(iPlayerID)
CBlock.AnimateVisibility(iPlayerID)
end
CGameMode.EndGame = function()
local iMaxScore = -999
for i = 1, #tGame.StartPositions do
if tGameStats.Players[i].Score > iMaxScore then
CGameMode.iWinnerID = i
iMaxScore = tGameStats.Players[i].Score
elseif tGameStats.Players[i].Score == iMaxScore then
CAudio.PlayVoicesSyncFromScratch("draw_overtime.mp3")
tGameStats.StageLeftDuration = 15
return false
end
end
CAudio.StopBackground()
iGameState = GAMESTATE_POSTGAME
CAudio.PlaySyncColorSound(tGame.StartPositions[CGameMode.iWinnerID].Color)
CAudio.PlayVoicesSync(CAudio.VICTORY)
tGameResults.Won = true
tGameResults.Color = tGame.StartPositions[CGameMode.iWinnerID].Color
AL.NewTimer(tConfig.WinDurationMS, function()
iGameState = GAMESTATE_FINISH
end)
SetGlobalColorBright(tGameStats.Players[CGameMode.iWinnerID].Color, tConfig.Bright)
return true
end
--//
--MAPS
CMaps = {}
CMaps.LoadMapForPlayer = function(iPlayerID)
local tMap, fSeed = CMaps.GenerateRandomMapFromSeed(CGameMode.tPlayerSeeds[iPlayerID])
CGameMode.tPlayerSeeds[iPlayerID] = fSeed
CGameMode.tPlayerMapTotalCoinCount[iPlayerID] = 0
CGameMode.tPlayerMapTotalCoinCollected[iPlayerID] = 0
local iMapX = 0
local iMapY = 0
for iY = tGame.StartPositions[iPlayerID].Y, tGame.StartPositionSizeY-1 + tGame.StartPositions[iPlayerID].Y do
iMapY = iMapY + 1
for iX = tGame.StartPositions[iPlayerID].X, tGame.StartPositionSizeX-1 + tGame.StartPositions[iPlayerID].X do
iMapX = iMapX + 1
local iBlockType = CBlock.BLOCK_TYPE_GROUND
if not tFloor[iX][iY].bDefect and tMap[iMapY] ~= nil and tMap[iMapY][iMapX] ~= nil then
iBlockType = tMap[iMapY][iMapX]
end
if iBlockType == CBlock.BLOCK_TYPE_COIN then
CGameMode.tPlayerMapTotalCoinCount[iPlayerID] = CGameMode.tPlayerMapTotalCoinCount[iPlayerID] + 1
end
CBlock.NewBlock(iX, iY, iBlockType, iPlayerID)
end
iMapX = 0
end
end
CMaps.GenerateRandomMapFromSeed = function(fSeed)
local tMap = {}
local iPrevZoneCoinCount = 1
for iY = 1, tGame.StartPositionSizeY do
tMap[iY] = {}
local iCoinCount = 0
local iMaxCoinCount = 0
iMaxCoinCount, fSeed = CRandom.IntFromSeed(1, 3, fSeed)
if iMaxCoinCount > 2 then iMaxCoinCount = 2 end
for iX = 1, tGame.StartPositionSizeX do
local iBlockType = CBlock.BLOCK_TYPE_GROUND
if iCoinCount < iMaxCoinCount then
iBlockType, fSeed = CRandom.IntFromSeed(1, 3, fSeed)
if iBlockType == CBlock.BLOCK_TYPE_GROUND then
if (tGame.StartPositionSizeX - iX) - (iMaxCoinCount - iCoinCount) < 0 then
iBlockType = CBlock.BLOCK_TYPE_COIN
end
end
if iBlockType == CBlock.BLOCK_TYPE_COIN then
iCoinCount = iCoinCount + 1
end
end
tMap[iY][iX] = iBlockType
end
end
return tMap, fSeed
end
--//
--BLOCK
CBlock = {}
CBlock.tBlocks = {}
CBlock.tBlockStructure = {
iBlockType = 0,
bCollected = false,
iPlayerID = 0,
iBright = 0,
bVisible = false,
}
CBlock.BLOCK_TYPE_GROUND = 1
CBlock.BLOCK_TYPE_COIN = 2
CBlock.tBLOCK_TYPE_TO_COLOR = {}
CBlock.tBLOCK_TYPE_TO_COLOR[CBlock.BLOCK_TYPE_GROUND] = CColors.WHITE
CBlock.tBLOCK_TYPE_TO_COLOR[CBlock.BLOCK_TYPE_COIN] = CColors.BLUE
CBlock.NewBlock = function(iX, iY, iBlockType, iPlayerID)
if CBlock.tBlocks[iX] == nil then CBlock.tBlocks[iX] = {} end
CBlock.tBlocks[iX][iY] = CHelp.ShallowCopy(CBlock.tBlockStructure)
CBlock.tBlocks[iX][iY].iBlockType = iBlockType
CBlock.tBlocks[iX][iY].iPlayerID = iPlayerID
CBlock.tBlocks[iX][iY].iBright = tConfig.Bright
CBlock.tBlocks[iX][iY].bVisible = false
end
CBlock.RegisterBlockClick = function(iX, iY)
if CBlock.tBlocks[iX][iY].bVisible == false then return; end
local iPlayerID = CBlock.tBlocks[iX][iY].iPlayerID
if CBlock.tBlocks[iX][iY].iBlockType == CBlock.BLOCK_TYPE_COIN and CBlock.tBlocks[iX][iY].bCollected == false then
CBlock.tBlocks[iX][iY].bCollected = true
CGameMode.PlayerRoundScoreAdd(iPlayerID, 1)
CGameMode.tPlayerMapTotalCoinCollected[iPlayerID] = CGameMode.tPlayerMapTotalCoinCollected[iPlayerID] + 1
if CGameMode.tPlayerMapTotalCoinCollected[iPlayerID] == CGameMode.tPlayerMapTotalCoinCount[iPlayerID] then
CGameMode.PlayerFinished(iPlayerID)
end
elseif CBlock.tBlocks[iX][iY].iBlockType == CBlock.BLOCK_TYPE_GROUND and CBlock.tBlocks[iX][iY].bCollected == false and tConfig.EnableMissPenalty then
CBlock.tBlocks[iX][iY].bCollected = true
CGameMode.PlayerScorePenalty(iPlayerID, 1)
CPaint.AnimatePixelFlicker(iX, iY, 3, CBlock.tBLOCK_TYPE_TO_COLOR[CBlock.tBlocks[iX][iY].iBlockType])
end
end
CBlock.AnimateVisibility = function(iPlayerID)
local iY = tGame.StartPositions[iPlayerID].Y
AL.NewTimer(CPaint.ANIMATION_DELAY*2, function()
for iX = tGame.StartPositions[iPlayerID].X, tGame.StartPositions[iPlayerID].X + tGame.StartPositionSizeX do
if CBlock.tBlocks[iX] and CBlock.tBlocks[iX][iY] then
CBlock.tBlocks[iX][iY].bVisible = true
end
end
if iY < tGame.StartPositions[iPlayerID].Y + tGame.StartPositionSizeY then
iY = iY + 1
return CPaint.ANIMATION_DELAY*2
end
return nil
end)
end
CBlock.ClearPlayerZone = function(iPlayerID)
for iY = tGame.StartPositions[iPlayerID].Y, tGame.StartPositionSizeY-1 + tGame.StartPositions[iPlayerID].Y do
for iX = tGame.StartPositions[iPlayerID].X, tGame.StartPositionSizeX-1 + tGame.StartPositions[iPlayerID].X do
CBlock.tBlocks[iX][iY] = nil
end
end
end
--//
--RANDOM
CRandom = {}
CRandom.fA = 45.0001
CRandom.fB = 1337.0000
CRandom.fM = 99.9999
CRandom.IntFromSeed = function(iMin, iMax, fSeed) -- Π²ΠΎΠ·Π²ΡΠ°ΡΠ°Π΅Ρ iRand, fSeed
local iRand, fSeed = CRandom.NextFromSeed(fSeed)
return math.floor(iRand * (iMax-iMin) + iMin), fSeed
end
CRandom.NextFromSeed = function(fSeed)
fSeed = (CRandom.fA * fSeed + CRandom.fB) % CRandom.fM
return fSeed % 1, fSeed
end
--//
--PAINT
CPaint = {}
CPaint.ANIMATION_DELAY = 75
CPaint.Blocks = function()
for iX = 1, tGame.Cols do
if CBlock.tBlocks[iX] then
for iY = 1, tGame.Rows do
if not tFloor[iX][iY].bAnimated and CBlock.tBlocks[iX][iY] and CBlock.tBlocks[iX][iY].bVisible then
if CBlock.tBlocks[iX] and CBlock.tBlocks[iX][iY] then
tFloor[iX][iY].iColor = CBlock.tBLOCK_TYPE_TO_COLOR[CBlock.tBlocks[iX][iY].iBlockType]
tFloor[iX][iY].iBright = CBlock.tBlocks[iX][iY].iBright
if CBlock.tBlocks[iX][iY].iBlockType == CBlock.BLOCK_TYPE_COIN then
tFloor[iX][iY].iColor = tGameStats.Players[CBlock.tBlocks[iX][iY].iPlayerID].Color
if CBlock.tBlocks[iX][iY].bCollected then
tFloor[iX][iY].iBright = 1
end
end
end
end
end
end
end
end
CPaint.PlayerZones = function()
for i = 1, #tGame.StartPositions do
CPaint.PlayerZone(i, tConfig.Bright)
end
end
CPaint.PlayerZone = function(iPlayerID, iBright)
for iX = tGame.StartPositions[iPlayerID].X, tGame.StartPositionSizeX + tGame.StartPositions[iPlayerID].X-1 do
for iY = tGame.StartPositions[iPlayerID].Y, tGame.StartPositionSizeY + tGame.StartPositions[iPlayerID].Y-1 do
if not tFloor[iX][iY].bAnimated then
tFloor[iX][iY].iColor = tGame.StartPositions[iPlayerID].Color
tFloor[iX][iY].iBright = iBright-1
end
end
end
end
CPaint.AnimatePixelFlicker = function(iX, iY, iFlickerCount, iColor)
if tFloor[iX][iY].bAnimated then return; end
tFloor[iX][iY].bAnimated = true
local iCount = 0
AL.NewTimer(CPaint.ANIMATION_DELAY, function()
if not tFloor[iX][iY].bAnimated then return; end
if tFloor[iX][iY].iColor == iColor then
tFloor[iX][iY].iBright = tConfig.Bright + 1
tFloor[iX][iY].iColor = CColors.RED
iCount = iCount + 1
else
tFloor[iX][iY].iBright = tConfig.Bright
tFloor[iX][iY].iColor = iColor
iCount = iCount + 1
end
if iCount <= iFlickerCount then
return CPaint.ANIMATION_DELAY*3
end
tFloor[iX][iY].iBright = tConfig.Bright
tFloor[iX][iY].iColor = iColor
tFloor[iX][iY].bAnimated = false
return nil
end)
end
--//
--UTIL ΠΏΡΠΎΡΠΈΠ΅ ΡΡΠΈΠ»ΠΈΡΡ
function CheckPositionClick(tStart, iSizeX, iSizeY)
for iX = tStart.X, tStart.X + iSizeX - 1 do
for iY = tStart.Y, tStart.Y + iSizeY - 1 do
if tFloor[iX] and tFloor[iX][iY] then
if tFloor[iX][iY].bClick then
return true
end
end
end
end
return false
end
function SetPositionColorBright(tStart, iSize, iColor, iBright)
for i = 0, iSize * iSize - 1 do
local iX = tStart.X + i % iSize
local iY = tStart.Y + math.floor(i / iSize)
if not (iX < 1 or iX > tGame.Cols or iY < 1 or iY > tGame.Rows) then
tFloor[iX][iY].iColor = iColor
tFloor[iX][iY].iBright = iBright
end
end
end
function SetGlobalColorBright(iColor, iBright)
for iX = 1, tGame.Cols do
for iY = 1, tGame.Rows do
if not tFloor[iX][iY].bAnimated then
tFloor[iX][iY].iColor = iColor
tFloor[iX][iY].iBright = iBright
end
end
end
for i, tButton in pairs(tButtons) do
tButtons[i].iColor = iColor
tButtons[i].iBright = iBright
end
end
function SetAllButtonColorBright(iColor, iBright)
for i, tButton in pairs(tButtons) do
if not tButtons[i].bDefect then
tButtons[i].iColor = iColor
tButtons[i].iBright = iBright
end
end
end
--//
--//
function GetStats()
return tGameStats
end
function PauseGame()
bGamePaused = true
end
function ResumeGame()
bGamePaused = false
iPrevTickTime = CTime.unix()
end
function PixelClick(click)
if tFloor[click.X] and tFloor[click.X][click.Y] then
if bGamePaused then
tFloor[click.X][click.Y].bClick = false
return;
end
tFloor[click.X][click.Y].bClick = click.Click
tFloor[click.X][click.Y].iWeight = click.Weight
if click.Click and iGameState == GAMESTATE_GAME and CGameMode.bGameStarted then
if CBlock.tBlocks[click.X] and CBlock.tBlocks[click.X][click.Y] then
CBlock.RegisterBlockClick(click.X, click.Y)
end
end
end
end
function DefectPixel(defect)
if tFloor[defect.X] and tFloor[defect.X][defect.Y] then
tFloor[defect.X][defect.Y].bDefect = defect.Defect
if defect.Defect and CBlock.tBlocks[defect.X] and CBlock.tBlocks[defect.X][defect.Y] and CBlock.tBlocks[defect.X][defect.Y].iBlockType == CBlock.BLOCK_TYPE_COIN then
CBlock.RegisterBlockClick(defect.X, defect.Y)
end
end
end
function ButtonClick(click)
if tButtons[click.Button] == nil or bGamePaused or tButtons[click.Button].bDefect then return end
tButtons[click.Button].bClick = click.Click
if iGameState == GAMESTATE_SETUP and click.Click == true then
bAnyButtonClick = true
end
end
function DefectButton(defect)
if tButtons[defect.Button] == nil then return end
tButtons[defect.Button].bDefect = defect.Defect
end | 412 | 0.620927 | 1 | 0.620927 | game-dev | MEDIA | 0.762621 | game-dev | 0.813437 | 1 | 0.813437 |
ChuanqiXu9/clangd-for-modules | 4,076 | clang/test/CodeGenCXX/predefined-expr-cxx14.cpp | // RUN: %clang_cc1 -std=c++14 %s -triple %itanium_abi_triple -fblocks -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -x c++ -std=c++14 -triple %itanium_abi_triple -fblocks -emit-pch -o %t %s
// RUN: %clang_cc1 -x c++ -triple %itanium_abi_triple -std=c++14 -fblocks -include-pch %t %s -emit-llvm -o - | FileCheck %s
#ifndef HEADER
#define HEADER
// CHECK-DAG: @__func__._ZN13ClassTemplateIiE21classTemplateFunctionERi = private unnamed_addr constant [22 x i8] c"classTemplateFunction\00"
// CHECK-DAG: @__PRETTY_FUNCTION__._ZN13ClassTemplateIiE21classTemplateFunctionERi = private unnamed_addr constant [69 x i8] c"const auto &ClassTemplate<int>::classTemplateFunction(T &) [T = int]\00"
// CHECK-DAG: @__func__._ZN24ClassInTopLevelNamespace16functionTemplateIiEERDaRT_ = private unnamed_addr constant [17 x i8] c"functionTemplate\00"
// CHECK-DAG: @__PRETTY_FUNCTION__._ZN24ClassInTopLevelNamespace16functionTemplateIiEERDaRT_ = private unnamed_addr constant [64 x i8] c"auto &ClassInTopLevelNamespace::functionTemplate(T &) [T = int]\00"
// CHECK-DAG: @__func__._ZN24ClassInTopLevelNamespace16variadicFunctionEPiz = private unnamed_addr constant [17 x i8] c"variadicFunction\00"
// CHECK-DAG: @__PRETTY_FUNCTION__._ZN24ClassInTopLevelNamespace16variadicFunctionEPiz = private unnamed_addr constant [70 x i8] c"decltype(auto) ClassInTopLevelNamespace::variadicFunction(int *, ...)\00"
// CHECK-DAG: @__func__._ZN24ClassInTopLevelNamespace25topLevelNamespaceFunctionEv = private unnamed_addr constant [26 x i8] c"topLevelNamespaceFunction\00"
// CHECK-DAG: @__PRETTY_FUNCTION__._ZN24ClassInTopLevelNamespace25topLevelNamespaceFunctionEv = private unnamed_addr constant [60 x i8] c"auto *ClassInTopLevelNamespace::topLevelNamespaceFunction()\00"
// CHECK-DAG: @__func__.___ZN16ClassBlockConstrD2Ev_block_invoke = private unnamed_addr constant [31 x i8] c"~ClassBlockConstr_block_invoke\00"
// CHECK-DAG: @__func__.___ZN16ClassBlockConstrC2Ev_block_invoke = private unnamed_addr constant [30 x i8] c"ClassBlockConstr_block_invoke\00"
// CHECK-DAG: private unnamed_addr constant [32 x i8] c"const char *ConstexprPrettyFn()\00"
int printf(const char * _Format, ...);
class ClassInTopLevelNamespace {
public:
auto *topLevelNamespaceFunction() {
printf("__func__ %s\n", __func__);
printf("__FUNCTION__ %s\n", __FUNCTION__);
printf("__PRETTY_FUNCTION__ %s\n\n", __PRETTY_FUNCTION__);
return static_cast<int *>(nullptr);
}
decltype(auto) variadicFunction(int *a, ...) {
printf("__func__ %s\n", __func__);
printf("__FUNCTION__ %s\n", __FUNCTION__);
printf("__PRETTY_FUNCTION__ %s\n\n", __PRETTY_FUNCTION__);
return a;
}
template<typename T>
auto &functionTemplate(T &t) {
printf("__func__ %s\n", __func__);
printf("__FUNCTION__ %s\n", __FUNCTION__);
printf("__PRETTY_FUNCTION__ %s\n\n", __PRETTY_FUNCTION__);
return t;
}
};
template<typename T>
class ClassTemplate {
public:
const auto &classTemplateFunction(T &t) {
printf("__func__ %s\n", __func__);
printf("__FUNCTION__ %s\n", __FUNCTION__);
printf("__PRETTY_FUNCTION__ %s\n\n", __PRETTY_FUNCTION__);
return t;
}
};
struct ClassBlockConstr {
const char *s;
ClassBlockConstr() {
const char * (^b)() = ^() {
return __func__;
};
s = b();
}
~ClassBlockConstr() {
const char * (^b)() = ^() {
return __func__;
};
s = b();
}
};
template <class T>
class FuncTemplate {
const char *Func;
public:
FuncTemplate() : Func(__func__) {}
const char *getFunc() const { return Func; }
};
constexpr const char* ConstexprPrettyFn() {
return __PRETTY_FUNCTION__;
}
const char* ConstexprPrettyVar = ConstexprPrettyFn();
int
main() {
int a;
ClassInTopLevelNamespace topLevelNamespace;
ClassBlockConstr classBlockConstr;
topLevelNamespace.topLevelNamespaceFunction();
topLevelNamespace.variadicFunction(&a);
topLevelNamespace.functionTemplate(a);
ClassTemplate<int> t;
t.classTemplateFunction(a);
return 0;
}
#else
void Foo() {
FuncTemplate<int> FTi;
(void)FTi.getFunc();
}
#endif
| 412 | 0.82687 | 1 | 0.82687 | game-dev | MEDIA | 0.140371 | game-dev | 0.538108 | 1 | 0.538108 |
DevDungeon/Cookbook | 3,577 | python/panda3D/events.py | from direct.showbase.ShowBase import ShowBase
from direct.showbase.DirectObject import DirectObject
from direct.interval.IntervalGlobal import Sequence, Func, Wait
from panda3d.core import CollisionTraverser, CollisionHandlerEvent
from panda3d.core import CollisionNode, CollisionSphere
from panda3d.core import VBase4
class World(DirectObject):
def __init__( self ):
# Initialize the traverser.
base.cTrav = CollisionTraverser()
# Initialize the handler.
self.collHandEvent = CollisionHandlerEvent()
self.collHandEvent.addInPattern('into-%in')
self.collHandEvent.addOutPattern('outof-%in')
# Make a variable to store the unique collision string count.
self.collCount = 0
# Load a model. Reparent it to the camera so we can move it.
s = loader.loadModel('smiley')
s.reparentTo(camera)
s.setPos(0, 25, 0)
# Setup a collision solid for this model.
sColl = self.initCollisionSphere(s, True)
# Add this object to the traverser.
base.cTrav.addCollider(sColl[0], self.collHandEvent)
# Accept the events sent by the collisions.
self.accept('into-' + sColl[1], self.collide3)
self.accept('outof-' + sColl[1], self.collide4)
print(sColl[1])
# Load another model.
t = loader.loadModel('smiley')
t.reparentTo(render)
t.setPos(5, 25, 0)
# Setup a collision solid for this model.
tColl = self.initCollisionSphere(t, True)
# Add this object to the traverser.
base.cTrav.addCollider(tColl[0], self.collHandEvent)
# Accept the events sent by the collisions.
self.accept('into-' + tColl[1], self.collide)
self.accept('outof-' + tColl[1], self.collide2)
print(tColl[1])
print("WERT")
def collide(self, collEntry):
print("WERT: object has collided into another object")
Sequence(Func(collEntry.getFromNodePath().getParent().setColor,
VBase4(1, 0, 0, 1)),
Wait(0.2),
Func(collEntry.getFromNodePath().getParent().setColor,
VBase4(0, 1, 0, 1)),
Wait(0.2),
Func(collEntry.getFromNodePath().getParent().setColor,
VBase4(1, 1, 1, 1))).start()
def collide2(self, collEntry):
print("WERT.: object is no longer colliding with another object")
def collide3(self, collEntry):
print("WERT2: object has collided into another object")
def collide4(self, collEntry):
print("WERT2: object is no longer colliding with another object")
def initCollisionSphere(self, obj, show=False):
# Get the size of the object for the collision sphere.
bounds = obj.getChild(0).getBounds()
center = bounds.getCenter()
radius = bounds.getRadius() * 1.1
# Create a collision sphere and name it something understandable.
collSphereStr = 'CollisionHull' + str(self.collCount) + "_" + obj.getName()
self.collCount += 1
cNode = CollisionNode(collSphereStr)
cNode.addSolid(CollisionSphere(center, radius))
cNodepath = obj.attachNewNode(cNode)
if show:
cNodepath.show()
# Return a tuple with the collision node and its corrsponding string so
# that the bitmask can be set.
return (cNodepath, collSphereStr)
ShowBase()
# Run the world. Move around with the mouse to create collisions.
w = World()
run() | 412 | 0.789756 | 1 | 0.789756 | game-dev | MEDIA | 0.449193 | game-dev | 0.921473 | 1 | 0.921473 |
Dimbreath/AzurLaneData | 9,080 | en-US/mod/experiment/world/model/worldmapop.lua | slot0 = class("WorldMapOp", import("...BaseEntity"))
slot0.Fields = {
terrainUpdates = "table",
fleetUpdates = "table",
drops = "table",
callbacksWhenApplied = "table",
destMapId = "number",
salvageUpdates = "table",
hiddenAttachments = "table",
path = "table",
duration = "number",
depth = "number",
updateAttachmentCells = "table",
childOps = "table",
arg1 = "number",
anim = "string",
arg2 = "number",
effect = "table",
applied = "boolean",
op = "number",
id = "number",
trap = "number",
routine = "function",
updateCarryItems = "table",
entranceId = "number",
pos = "table",
hiddenCells = "table",
stepOps = "table",
locations = "table",
staminaUpdate = "table",
attachment = "table",
shipUpdates = "table",
fleetAttachUpdates = "table",
sign = "table",
destGridId = "number"
}
function slot0.Apply(slot0)
slot0.applied = true
slot1 = getProxy(WorldProxy)
slot3 = nowWorld:GetActiveMap()
if slot0.op == WorldConst.OpReqMoveFleet then
slot2:IncRound()
elseif slot0.op == WorldConst.OpReqRound then
slot2:IncRound()
elseif slot0.op == WorldConst.OpReqEvent then
slot4 = slot3:GetFleet(slot0.id)
slot5 = slot0.effect
slot7 = slot5.effect_paramater
if slot5.effect_type == WorldMapAttachment.EffectEventTeleport or slot6 == WorldMapAttachment.EffectEventTeleportBack then
slot1:NetUpdateActiveMap(slot0.entranceId, slot0.destMapId, slot0.destGridId)
elseif slot6 == WorldMapAttachment.EffectEventShipBuff then
slot8 = slot7[1]
_.each(slot4:GetShips(true), function (slot0)
slot0:AddBuff(uv0, 1)
end)
elseif slot6 == WorldMapAttachment.EffectEventAchieveCarry then
_.each(slot7, function (slot0)
slot1 = WorldCarryItem.New()
slot1:Setup(slot0)
uv0:AddCarry(slot1)
end)
elseif slot6 == WorldMapAttachment.EffectEventConsumeCarry then
_.each(slot7[1] or {}, function (slot0)
uv0:RemoveCarry(slot0)
end)
elseif slot6 == WorldMapAttachment.EffectEventConsumeItem then
slot2:GetInventoryProxy():RemoveItem(slot7[1], slot7[2])
elseif slot6 == WorldMapAttachment.EffectEventDropTreasure then
slot2.treasureCount = slot2.treasureCount + 1
elseif slot6 == WorldMapAttachment.EffectEventFOV then
slot3:EventEffectOpenFOV(slot5)
elseif slot6 == WorldMapAttachment.EffectEventProgress then
slot2:UpdateProgress(math.max(slot2:GetProgress(), slot7[1]))
elseif slot6 == WorldMapAttachment.EffectEventDeleteTask then
for slot12, slot13 in ipairs(slot7) do
slot2:GetTaskProxy():deleteTask(slot13)
end
elseif slot6 == WorldMapAttachment.EffectEventGlobalBuff then
slot2:AddGlobalBuff(slot7[1], slot7[2])
elseif slot6 == WorldMapAttachment.EffectEventMapClearFlag then
slot3:UpdateClearFlag(slot7[1] == 1)
elseif slot6 == WorldMapAttachment.EffectEventBrokenClean then
for slot11, slot12 in ipairs(slot2:GetShips()) do
if slot12:IsBroken() then
slot12:RemoveBuff(WorldConst.BrokenBuffId)
end
end
elseif slot6 == WorldMapAttachment.EffectEventCatSalvage then
-- Nothing
elseif slot6 == WorldMapAttachment.EffectEventAddWorldBossFreeCount and getProxy(ActivityProxy):getActivityByType(ActivityConst.ACTIVITY_TYPE_WORLD_WORLDBOSS) and not slot9:isEnd() then
slot9.data3 = slot9.data3 + 1
print("add extra active boss cnt", slot9.data3)
slot8:updateActivity(slot9)
end
if #slot5.sound_effects > 0 then
pg.CriMgr.GetInstance():PlaySoundEffect_V3("event:" .. slot5.sound_effects)
end
elseif slot0.op == WorldConst.OpReqDiscover then
_.each(slot0.locations, function (slot0)
uv0:GetCell(slot0.row, slot0.column):UpdateDiscovered(true)
end)
_.each(slot0.hiddenAttachments, function (slot0)
slot0:UpdateLurk(false)
end)
elseif slot0.op == WorldConst.OpReqTransport then
slot1:NetUpdateActiveMap(slot0.entranceId, slot0.destMapId, slot0.destGridId)
if slot2:TreasureMap2ItemId(slot0.destMapId, slot0.entranceId) then
slot2:GetInventoryProxy():RemoveItem(slot4, 1)
end
elseif slot0.op == WorldConst.OpReqSub then
slot2:ResetSubmarine()
slot2:UpdateSubmarineSupport(true)
slot4 = slot2:GetActiveMap()
elseif slot0.op == WorldConst.OpReqPressingMap then
slot4 = slot0.arg1
slot2:FlagMapPressingAward(slot4)
slot2:GetAtlas():AddPressingMap(slot4)
if not slot2:GetMap(slot4).visionFlag and nowWorld:IsMapVisioned(slot4) then
slot6:UpdateVisionFlag(true)
end
elseif slot0.op == WorldConst.OpReqJumpOut then
slot5 = slot2:GetInventoryProxy()
_.each(pg.world_chapter_template_reset[slot3.gid].reset_item, function (slot0)
uv0:RemoveItem(slot0)
end)
slot1:NetUpdateActiveMap(slot0.entranceId, slot0.destMapId, slot0.destGridId)
slot3 = slot2:GetActiveMap()
elseif slot0.op == WorldConst.OpReqEnterPort then
-- Nothing
elseif slot0.op == WorldConst.OpReqCatSalvage then
slot3:GetFleet(slot0.id):UpdateCatSalvage(0, nil, 0)
elseif slot0.op == WorldConst.OpReqSkipBattle then
slot3:WriteBack(true, {
statistics = {},
hpDropInfo = {}
})
elseif slot0.op == WorldConst.OpActionFleetMove then
slot4 = slot0.path[#slot0.path]
slot3:UpdateFleetLocation(slot0.id, slot4.row, slot4.column)
slot2.stepCount = slot2.stepCount + #slot0.path
elseif slot0.op == WorldConst.OpActionMoveStep then
slot0:ApplyAttachmentUpdate()
_.each(slot0.hiddenCells, function (slot0)
slot0:UpdateDiscovered(true)
end)
slot4 = slot3:GetFleet(slot0.id)
if slot3:GetCell(slot4.row, slot4.column):GetEventAttachment() and slot6:IsTriggered() then
slot6.triggered = false
end
if slot0.updateCarryItems and #slot0.updateCarryItems > 0 then
for slot11, slot12 in ipairs(slot4:GetCarries()) do
slot12:UpdateOffset(slot0.updateCarryItems[slot11].offsetRow, slot0.updateCarryItems[slot11].offsetColumn)
end
WPool:ReturnArray(slot0.updateCarryItems)
slot0.updateCarryItems = nil
end
slot3:UpdateFleetLocation(slot0.id, slot0.pos.row, slot0.pos.column)
_.each(slot0.hiddenAttachments, function (slot0)
slot0:UpdateLurk(false)
end)
elseif slot0.op == WorldConst.OpActionAttachmentMove then
slot4 = slot0.attachment:Clone()
slot5 = slot0.path[#slot0.path]
slot3:GetCell(slot0.attachment.row, slot0.attachment.column):RemoveAttachment(slot0.attachment)
slot4.row = slot5.row
slot4.column = slot5.column
slot3:GetCell(slot5.row, slot5.column):AddAttachment(slot4)
elseif slot0.op == WorldConst.OpActionEventOp then
if slot0.effect.effect_type == WorldMapAttachment.EffectEventFOV then
slot3:EventEffectOpenFOV(slot4)
end
slot0.attachment:UpdateDataOp(slot0.attachment.dataop - 1)
elseif slot0.op == WorldConst.OpActionTaskGoto and slot0.effect.effect_type == WorldMapAttachment.EffectEventFOV then
slot3:EventEffectOpenFOV(slot4)
end
if slot0.childOps then
_.each(slot0.childOps, function (slot0)
if not slot0.applied then
slot0:Apply()
end
end)
end
if slot0.stepOps then
_.each(slot0.stepOps, function (slot0)
if not slot0.applied then
slot0:Apply()
end
end)
end
slot0:ApplyAttachmentUpdate()
slot0:ApplyNetUpdate()
if slot0.callbacksWhenApplied then
_.each(slot0.callbacksWhenApplied, function (slot0)
slot0()
end)
end
end
function slot0.ApplyAttachmentUpdate(slot0)
if slot0.updateAttachmentCells then
slot7 = slot0.updateAttachmentCells
getProxy(WorldProxy):UpdateMapAttachmentCells(nowWorld:GetActiveMap().id, slot7)
for slot7, slot8 in pairs(slot0.updateAttachmentCells) do
slot9 = slot3:GetCell(slot8.pos.row, slot8.pos.column)
_.each(slot8.attachmentList, function (slot0)
if not uv0:ContainsAttachment(slot0) then
WPool:Return(slot0)
end
end)
end
slot0.updateAttachmentCells = nil
end
end
function slot0.ApplyNetUpdate(slot0)
slot1 = getProxy(WorldProxy)
slot3 = nowWorld:GetActiveMap()
if slot0.staminaUpdate then
slot2.staminaMgr:ChangeStamina(slot0.staminaUpdate[1], slot0.staminaUpdate[2])
slot0.staminaUpdate = nil
end
if slot0.shipUpdates and #slot0.shipUpdates > 0 then
slot1:ApplyShipUpdate(slot0.shipUpdates)
WPool:ReturnArray(slot0.shipUpdates)
slot0.shipUpdates = nil
end
if slot0.fleetAttachUpdates and #slot0.fleetAttachUpdates > 0 then
slot1:ApplyFleetAttachUpdate(slot3.id, slot0.fleetAttachUpdates)
WPool:ReturnArray(slot0.fleetAttachUpdates)
slot0.fleetAttachUpdates = nil
end
if slot0.fleetUpdates and #slot0.fleetUpdates > 0 then
slot1:ApplyFleetUpdate(slot3.id, slot0.fleetUpdates)
WPool:ReturnArray(slot0.fleetUpdates)
slot0.fleetUpdates = nil
end
if slot0.terrainUpdates and #slot0.terrainUpdates > 0 then
slot1:ApplyTerrainUpdate(slot3.id, slot0.terrainUpdates)
WPool:ReturnArray(slot0.terrainUpdates)
slot0.terrainUpdates = nil
end
if slot0.salvageUpdates and #slot0.salvageUpdates > 0 then
slot1:ApplySalvageUpdate(slot0.salvageUpdates)
WPool:ReturnArray(slot0.salvageUpdates)
slot0.salvageUpdates = nil
end
end
function slot0.AddCallbackWhenApplied(slot0, slot1)
if not slot0.callbacksWhenApplied then
slot0.callbacksWhenApplied = {}
end
table.insert(slot0.callbacksWhenApplied, slot1)
end
return slot0
| 412 | 0.647196 | 1 | 0.647196 | game-dev | MEDIA | 0.931091 | game-dev | 0.912448 | 1 | 0.912448 |
s0bvi/goldsvet-opensource | 42,403 | casino/app/Games/PantherMoonPTM/SlotSettings.php | <?php
namespace VanguardLTE\Games\PantherMoonPTM
{
class SlotSettings
{
public $playerId = null;
public $splitScreen = null;
public $reelStrip1 = null;
public $reelStrip2 = null;
public $reelStrip3 = null;
public $reelStrip4 = null;
public $reelStrip5 = null;
public $reelStrip6 = null;
public $reelStripBonus1 = null;
public $reelStripBonus2 = null;
public $reelStripBonus3 = null;
public $reelStripBonus4 = null;
public $reelStripBonus5 = null;
public $reelStripBonus6 = null;
public $slotId = '';
public $slotDBId = '';
public $Line = null;
public $scaleMode = null;
public $numFloat = null;
public $gameLine = null;
public $Bet = null;
public $isBonusStart = null;
public $Balance = null;
public $SymbolGame = null;
public $GambleType = null;
public $lastEvent = null;
public $Jackpots = [];
public $keyController = null;
public $slotViewState = null;
public $hideButtons = null;
public $slotReelsConfig = null;
public $slotFreeCount = null;
public $slotFreeMpl = null;
public $slotWildMpl = null;
public $slotExitUrl = null;
public $slotBonus = null;
public $slotBonusType = null;
public $slotScatterType = null;
public $slotGamble = null;
public $Paytable = [];
public $slotSounds = [];
private $jpgs = null;
private $Bank = null;
private $Percent = null;
private $WinLine = null;
private $WinGamble = null;
private $Bonus = null;
private $shop_id = null;
public $licenseDK = null;
public $currency = null;
public $user = null;
public $game = null;
public $shop = null;
public $jpgPercentZero = false;
public $count_balance = null;
public function __construct($sid, $playerId)
{
$this->slotId = $sid;
$this->playerId = $playerId;
$user = \VanguardLTE\User::lockForUpdate()->find($this->playerId);
$this->user = $user;
$this->shop_id = $user->shop_id;
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $this->shop_id])->lockForUpdate()->get();
$game = \VanguardLTE\Game::where([
'name' => $this->slotId,
'shop_id' => $this->shop_id
])->lockForUpdate()->first();
$this->shop = \VanguardLTE\Shop::find($this->shop_id);
$this->game = $game;
$this->MaxWin = $this->shop->max_win;
$this->increaseRTP = 1;
$this->CurrentDenom = $this->game->denomination;
$this->scaleMode = 0;
$this->numFloat = 0;
$this->Paytable['SYM_0'] = [
0,
0,
10,
250,
2500,
10000
];
$this->Paytable['SYM_1'] = [
0,
0,
2,
25,
125,
750
];
$this->Paytable['SYM_2'] = [
0,
0,
2,
25,
125,
750
];
$this->Paytable['SYM_3'] = [
0,
0,
0,
20,
100,
500
];
$this->Paytable['SYM_4'] = [
0,
0,
0,
15,
75,
250
];
$this->Paytable['SYM_5'] = [
0,
0,
0,
15,
75,
250
];
$this->Paytable['SYM_6'] = [
0,
0,
0,
10,
40,
150
];
$this->Paytable['SYM_7'] = [
0,
0,
0,
10,
40,
150
];
$this->Paytable['SYM_8'] = [
0,
0,
0,
5,
30,
125
];
$this->Paytable['SYM_9'] = [
0,
0,
0,
5,
25,
100
];
$this->Paytable['SYM_10'] = [
0,
0,
0,
5,
25,
100
];
$this->Paytable['SYM_11'] = [
0,
0,
2,
5,
25,
100
];
$this->Paytable['SYM_12'] = [
0,
0,
2,
5,
20,
500
];
$reel = new GameReel();
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $reelStrip )
{
if( count($reel->reelsStrip[$reelStrip]) )
{
$this->$reelStrip = $reel->reelsStrip[$reelStrip];
}
}
foreach( [
'reelStripBonus1',
'reelStripBonus2',
'reelStripBonus3',
'reelStripBonus4',
'reelStripBonus5',
'reelStripBonus6'
] as $reelStrip )
{
if( count($reel->reelsStripBonus[$reelStrip]) )
{
$this->$reelStrip = $reel->reelsStripBonus[$reelStrip];
}
}
$this->keyController = [
'13' => 'uiButtonSpin,uiButtonSkip',
'49' => 'uiButtonInfo',
'50' => 'uiButtonCollect',
'51' => 'uiButtonExit2',
'52' => 'uiButtonLinesMinus',
'53' => 'uiButtonLinesPlus',
'54' => 'uiButtonBetMinus',
'55' => 'uiButtonBetPlus',
'56' => 'uiButtonGamble',
'57' => 'uiButtonRed',
'48' => 'uiButtonBlack',
'189' => 'uiButtonAuto',
'187' => 'uiButtonSpin'
];
$this->slotReelsConfig = [
[
425,
142,
3
],
[
669,
142,
3
],
[
913,
142,
3
],
[
1157,
142,
3
],
[
1401,
142,
3
]
];
$this->slotBonusType = 1;
$this->slotScatterType = 0;
$this->splitScreen = false;
$this->slotBonus = true;
$this->slotGamble = true;
$this->slotFastStop = 1;
$this->slotExitUrl = '/';
$this->slotWildMpl = 2;
$this->GambleType = 1;
$this->slotFreeCount = 15;
$this->slotFreeMpl = 3;
$this->slotViewState = ($game->slotViewState == '' ? 'Normal' : $game->slotViewState);
$this->hideButtons = [];
$this->jpgs = \VanguardLTE\JPG::where('shop_id', $this->shop_id)->lockForUpdate()->get();
$this->Line = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
];
$this->gameLine = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
];
$this->Bet = explode(',', $game->bet);
$this->Balance = $user->balance;
$this->SymbolGame = [
'0',
'1',
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12
];
$this->Bank = $game->get_gamebank();
$this->Percent = $this->shop->percent;
$this->WinGamble = $game->rezerv;
$this->slotDBId = $game->id;
$this->slotCurrency = $user->shop->currency;
$this->count_balance = $user->count_balance;
if( $user->address > 0 && $user->count_balance == 0 )
{
$this->Percent = 0;
$this->jpgPercentZero = true;
}
else if( $user->count_balance == 0 )
{
$this->Percent = 100;
}
if( !isset($this->user->session) || strlen($this->user->session) <= 0 )
{
$this->user->session = serialize([]);
}
$this->gameData = unserialize($this->user->session);
if( count($this->gameData) > 0 )
{
foreach( $this->gameData as $key => $vl )
{
if( $vl['timelife'] <= time() )
{
unset($this->gameData[$key]);
}
}
}
if( !isset($this->game->advanced) || strlen($this->game->advanced) <= 0 )
{
$this->game->advanced = serialize([]);
}
$this->gameDataStatic = unserialize($this->game->advanced);
if( count($this->gameDataStatic) > 0 )
{
foreach( $this->gameDataStatic as $key => $vl )
{
if( $vl['timelife'] <= time() )
{
unset($this->gameDataStatic[$key]);
}
}
}
}
public function is_active()
{
if( $this->game && $this->shop && $this->user && (!$this->game->view || $this->shop->is_blocked || $this->user->is_blocked || $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED) )
{
\VanguardLTE\Session::where('user_id', $this->user->id)->delete();
$this->user->update(['remember_token' => null]);
return false;
}
if( !$this->game->view )
{
return false;
}
if( $this->shop->is_blocked )
{
return false;
}
if( $this->user->is_blocked )
{
return false;
}
if( $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED )
{
return false;
}
return true;
}
public function SetGameData($key, $value)
{
$timeLife = 86400;
$this->gameData[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameData($key)
{
if( isset($this->gameData[$key]) )
{
return $this->gameData[$key]['payload'];
}
else
{
return 0;
}
}
public function FormatFloat($num)
{
$str0 = explode('.', $num);
if( isset($str0[1]) )
{
if( strlen($str0[1]) > 4 )
{
return round($num * 100) / 100;
}
else if( strlen($str0[1]) > 2 )
{
return floor($num * 100) / 100;
}
else
{
return $num;
}
}
else
{
return $num;
}
}
public function SaveGameData()
{
$this->user->session = serialize($this->gameData);
$this->user->save();
}
public function CheckBonusWin()
{
$allRateCnt = 0;
$allRate = 0;
foreach( $this->Paytable as $vl )
{
foreach( $vl as $vl2 )
{
if( $vl2 > 0 )
{
$allRateCnt++;
$allRate += $vl2;
break;
}
}
}
return $allRate / $allRateCnt;
}
public function GetRandomPay()
{
$allRate = [];
foreach( $this->Paytable as $vl )
{
foreach( $vl as $vl2 )
{
if( $vl2 > 0 )
{
$allRate[] = $vl2;
}
}
}
shuffle($allRate);
if( $this->game->stat_in < ($this->game->stat_out + ($allRate[0] * $this->AllBet)) )
{
$allRate[0] = 0;
}
return $allRate[0];
}
public function HasGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return true;
}
else
{
return false;
}
}
public function SaveGameDataStatic()
{
$this->game->advanced = serialize($this->gameDataStatic);
$this->game->save();
$this->game->refresh();
}
public function SetGameDataStatic($key, $value)
{
$timeLife = 86400;
$this->gameDataStatic[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return $this->gameDataStatic[$key]['payload'];
}
else
{
return 0;
}
}
public function HasGameData($key)
{
if( isset($this->gameData[$key]) )
{
return true;
}
else
{
return false;
}
}
public function GetHistory()
{
$history = \VanguardLTE\GameLog::whereRaw('game_id=? and user_id=? ORDER BY id DESC LIMIT 10', [
$this->slotDBId,
$this->playerId
])->get();
$this->lastEvent = 'NULL';
foreach( $history as $log )
{
$tmpLog = json_decode($log->str);
if( $tmpLog->responseEvent != 'gambleResult' )
{
$this->lastEvent = $log->str;
break;
}
}
if( isset($tmpLog) )
{
return $tmpLog;
}
else
{
return 'NULL';
}
}
public function UpdateJackpots($bet)
{
$bet = $bet * $this->CurrentDenom;
$count_balance = $this->count_balance;
$jsum = [];
$payJack = 0;
for( $i = 0; $i < count($this->jpgs); $i++ )
{
if( $count_balance == 0 || $this->jpgPercentZero )
{
$jsum[$i] = $this->jpgs[$i]->balance;
}
else if( $count_balance < $bet )
{
$jsum[$i] = $count_balance / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance;
}
else
{
$jsum[$i] = $bet / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance;
}
if( $this->jpgs[$i]->get_pay_sum() < $jsum[$i] && $this->jpgs[$i]->get_pay_sum() > 0 )
{
if( $this->jpgs[$i]->user_id && $this->jpgs[$i]->user_id != $this->user->id )
{
}
else
{
$payJack = $this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom;
$jsum[$i] = $jsum[$i] - $this->jpgs[$i]->get_pay_sum();
$this->SetBalance($this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom);
if( $this->jpgs[$i]->get_pay_sum() > 0 )
{
\VanguardLTE\StatGame::create([
'user_id' => $this->playerId,
'balance' => $this->Balance * $this->CurrentDenom,
'bet' => 0,
'win' => $this->jpgs[$i]->get_pay_sum(),
'game' => $this->game->name . ' JPG ' . $this->jpgs[$i]->id,
'in_game' => 0,
'in_jpg' => 0,
'in_profit' => 0,
'shop_id' => $this->shop_id,
'date_time' => \Carbon\Carbon::now()
]);
}
}
$i++;
}
$this->jpgs[$i]->balance = $jsum[$i];
$this->jpgs[$i]->save();
if( $this->jpgs[$i]->balance < $this->jpgs[$i]->get_min('start_balance') )
{
$summ = $this->jpgs[$i]->get_start_balance();
if( $summ > 0 )
{
$this->jpgs[$i]->add_jpg('add', $summ);
}
}
}
if( $payJack > 0 )
{
$payJack = sprintf('%01.2f', $payJack);
$this->Jackpots['jackPay'] = $payJack;
}
}
public function GetBank($slotState = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
$game = $this->game;
$this->Bank = $game->get_gamebank($slotState);
return $this->Bank / $this->CurrentDenom;
}
public function GetPercent()
{
return $this->Percent;
}
public function GetCountBalanceUser()
{
return $this->user->count_balance;
}
public function InternalErrorSilent($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
}
public function InternalError($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
exit( '' );
}
public function SetBank($slotState = '', $sum, $slotEvent = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
if( $this->GetBank($slotState) + $sum < 0 )
{
$this->InternalError('Bank_ ' . $sum . ' CurrentBank_ ' . $this->GetBank($slotState) . ' CurrentState_ ' . $slotState . ' Trigger_ ' . ($this->GetBank($slotState) + $sum));
}
$sum = $sum * $this->CurrentDenom;
$game = $this->game;
$bankBonusSum = 0;
if( $sum > 0 && $slotEvent == 'bet' )
{
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
$this->betProfit = 0;
$prc = $this->GetPercent();
$prc_b = 10;
if( $prc <= $prc_b )
{
$prc_b = 0;
}
$count_balance = $this->count_balance;
$gameBet = $sum / $this->GetPercent() * 100;
if( $count_balance < $gameBet && $count_balance > 0 )
{
$firstBid = $count_balance;
$secondBid = $gameBet - $firstBid;
if( isset($this->betRemains0) )
{
$secondBid = $this->betRemains0;
}
$bankSum = $firstBid / 100 * $this->GetPercent();
$sum = $bankSum + $secondBid;
$bankBonusSum = $firstBid / 100 * $prc_b;
}
else if( $count_balance > 0 )
{
$bankBonusSum = $gameBet / 100 * $prc_b;
}
for( $i = 0; $i < count($this->jpgs); $i++ )
{
if( !$this->jpgPercentZero )
{
if( $count_balance < $gameBet && $count_balance > 0 )
{
$this->toSlotJackBanks += ($count_balance / 100 * $this->jpgs[$i]->percent);
}
else if( $count_balance > 0 )
{
$this->toSlotJackBanks += ($gameBet / 100 * $this->jpgs[$i]->percent);
}
}
}
$this->toGameBanks = $sum;
$this->betProfit = $gameBet - $this->toGameBanks - $this->toSlotJackBanks - $this->toSysJackBanks;
}
if( $sum > 0 )
{
$this->toGameBanks = $sum;
}
if( $bankBonusSum > 0 )
{
$sum -= $bankBonusSum;
$game->set_gamebank($bankBonusSum, 'inc', 'bonus');
}
if( $sum == 0 && $slotEvent == 'bet' && isset($this->betRemains) )
{
$sum = $this->betRemains;
}
$game->set_gamebank($sum, 'inc', $slotState);
$game->save();
return $game;
}
public function SetBalance($sum, $slotEvent = '')
{
if( $this->GetBalance() + $sum < 0 )
{
$this->InternalError('Balance_ ' . $sum);
}
$sum = $sum * $this->CurrentDenom;
if( $sum < 0 && $slotEvent == 'bet' )
{
$user = $this->user;
if( $user->count_balance == 0 )
{
$remains = [];
$this->betRemains = 0;
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$remains[] = $sm - $user->address;
}
for( $i = 0; $i < count($remains); $i++ )
{
if( $this->betRemains < $remains[$i] )
{
$this->betRemains = $remains[$i];
}
}
}
if( $user->count_balance > 0 && $user->count_balance < abs($sum) )
{
$remains0 = [];
$sm = abs($sum);
$tmpSum = $sm - $user->count_balance;
$this->betRemains0 = $tmpSum;
if( $user->address > 0 )
{
$this->betRemains0 = 0;
if( $user->address < $tmpSum && $user->address > 0 )
{
$remains0[] = $tmpSum - $user->address;
}
for( $i = 0; $i < count($remains0); $i++ )
{
if( $this->betRemains0 < $remains0[$i] )
{
$this->betRemains0 = $remains0[$i];
}
}
}
}
$sum0 = abs($sum);
if( $user->count_balance == 0 )
{
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
else if( $user->count_balance > 0 && $user->count_balance < $sum0 )
{
$sm = $sum0 - $user->count_balance;
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
$this->user->count_balance = $this->user->updateCountBalance($sum, $this->count_balance);
$this->user->count_balance = $this->FormatFloat($this->user->count_balance);
}
$this->user->increment('balance', $sum);
$this->user->balance = $this->FormatFloat($this->user->balance);
$this->user->save();
return $this->user;
}
public function GetBalance()
{
$user = $this->user;
$this->Balance = $user->balance / $this->CurrentDenom;
return $this->Balance;
}
public function SaveLogReport($spinSymbols, $bet, $lines, $win, $slotState)
{
$reportName = $this->slotId . ' ' . $slotState;
if( $slotState == 'freespin' )
{
$reportName = $this->slotId . ' FG';
}
else if( $slotState == 'bet' )
{
$reportName = $this->slotId . '';
}
else if( $slotState == 'slotGamble' )
{
$reportName = $this->slotId . ' DG';
}
$game = $this->game;
if( $slotState == 'bet' )
{
$this->user->update_level('bet', $bet * $lines * $this->CurrentDenom);
}
if( $slotState != 'freespin' )
{
$game->increment('stat_in', $bet * $lines * $this->CurrentDenom);
}
$game->increment('stat_out', $win * $this->CurrentDenom);
$game->tournament_stat($slotState, $this->user->id, $bet * $lines * $this->CurrentDenom, $win * $this->CurrentDenom);
$this->user->update(['last_bid' => \Carbon\Carbon::now()]);
if( !isset($this->betProfit) )
{
$this->betProfit = 0;
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
}
if( !isset($this->toGameBanks) )
{
$this->toGameBanks = 0;
}
$this->game->increment('bids');
$this->game->refresh();
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $game->shop_id])->first();
if( $gamebank )
{
list($slotsBank, $bonusBank, $fishBank, $tableBank, $littleBank) = \VanguardLTE\Lib\Banker::get_all_banks($game->shop_id);
}
else
{
$slotsBank = $game->get_gamebank('', 'slots');
$bonusBank = $game->get_gamebank('bonus', 'bonus');
$fishBank = $game->get_gamebank('', 'fish');
$tableBank = $game->get_gamebank('', 'table_bank');
$littleBank = $game->get_gamebank('', 'little');
}
$totalBank = $slotsBank + $bonusBank + $fishBank + $tableBank + $littleBank;
\VanguardLTE\GameLog::create([
'game_id' => $this->slotDBId,
'user_id' => $this->playerId,
'ip' => $_SERVER['REMOTE_ADDR'],
'str' => $spinSymbols,
'shop_id' => $this->shop_id
]);
\VanguardLTE\StatGame::create([
'user_id' => $this->playerId,
'balance' => $this->Balance * $this->CurrentDenom,
'bet' => $bet * $lines * $this->CurrentDenom,
'win' => $win * $this->CurrentDenom,
'game' => $reportName,
'in_game' => $this->toGameBanks,
'in_jpg' => $this->toSlotJackBanks,
'in_profit' => $this->betProfit,
'denomination' => $this->CurrentDenom,
'shop_id' => $this->shop_id,
'slots_bank' => (double)$slotsBank,
'bonus_bank' => (double)$bonusBank,
'fish_bank' => (double)$fishBank,
'table_bank' => (double)$tableBank,
'little_bank' => (double)$littleBank,
'total_bank' => (double)$totalBank,
'date_time' => \Carbon\Carbon::now()
]);
}
public function GetSpinSettings($garantType = 'bet', $bet, $lines)
{
$curField = 10;
switch( $lines )
{
case 10:
$curField = 10;
break;
case 9:
case 8:
$curField = 9;
break;
case 7:
case 6:
$curField = 7;
break;
case 5:
case 4:
$curField = 5;
break;
case 3:
case 2:
$curField = 3;
break;
case 1:
$curField = 1;
break;
default:
$curField = 10;
break;
}
if( $garantType != 'bet' )
{
$pref = '_bonus';
}
else
{
$pref = '';
}
$this->AllBet = $bet * $lines;
$linesPercentConfigSpin = $this->game->get_lines_percent_config('spin');
$linesPercentConfigBonus = $this->game->get_lines_percent_config('bonus');
$currentPercent = $this->shop->percent;
$currentSpinWinChance = 0;
$currentBonusWinChance = 0;
$percentLevel = '';
foreach( $linesPercentConfigSpin['line' . $curField . $pref] as $k => $v )
{
$l = explode('_', $k);
$l0 = $l[0];
$l1 = $l[1];
if( $l0 <= $currentPercent && $currentPercent <= $l1 )
{
$percentLevel = $k;
break;
}
}
$currentSpinWinChance = $linesPercentConfigSpin['line' . $curField . $pref][$percentLevel];
$currentBonusWinChance = $linesPercentConfigBonus['line' . $curField . $pref][$percentLevel];
$RtpControlCount = 200;
if( !$this->HasGameDataStatic('SpinWinLimit') )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
if( !$this->HasGameDataStatic('RtpControlCount') )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
if( $this->game->stat_in > 0 )
{
$rtpRange = $this->game->stat_out / $this->game->stat_in * 100;
}
else
{
$rtpRange = 0;
}
if( $this->GetGameDataStatic('RtpControlCount') == 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
}
}
else if( $this->GetGameDataStatic('RtpControlCount') < 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
}
if( $this->GetGameDataStatic('RtpControlCount') < (-1 * $RtpControlCount) && $currentPercent - 1 <= $rtpRange && $rtpRange <= ($currentPercent + 2) )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
}
else
{
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
$bonusWin = rand(1, $currentBonusWinChance);
$spinWin = rand(1, $currentSpinWinChance);
$return = [
'none',
0
];
if( $bonusWin == 1 && $this->slotBonus )
{
$this->isBonusStart = true;
$garantType = 'bonus';
$winLimit = $this->GetBank($garantType);
$return = [
'bonus',
$winLimit
];
if( $this->game->stat_in < ($this->CheckBonusWin() * $bet + $this->game->stat_out) || $winLimit < ($this->CheckBonusWin() * $bet) )
{
$return = [
'none',
0
];
}
}
else if( $spinWin == 1 )
{
$winLimit = $this->GetBank($garantType);
$return = [
'win',
$winLimit
];
}
if( $garantType == 'bet' && $this->GetBalance() <= (2 / $this->CurrentDenom) )
{
$randomPush = rand(1, 10);
if( $randomPush == 1 )
{
$winLimit = $this->GetBank('');
$return = [
'win',
$winLimit
];
}
}
return $return;
}
public function GetRandomScatterPos($rp)
{
$rpResult = [];
for( $i = 0; $i < count($rp); $i++ )
{
if( $rp[$i] == '12' )
{
if( isset($rp[$i + 1]) && isset($rp[$i - 1]) )
{
array_push($rpResult, $i);
}
if( isset($rp[$i - 1]) && isset($rp[$i - 2]) )
{
array_push($rpResult, $i - 1);
}
if( isset($rp[$i + 1]) && isset($rp[$i + 2]) )
{
array_push($rpResult, $i + 1);
}
}
}
shuffle($rpResult);
if( !isset($rpResult[0]) )
{
$rpResult[0] = rand(2, count($rp) - 3);
}
return $rpResult[0];
}
public function GetGambleSettings()
{
$spinWin = rand(1, $this->WinGamble);
return $spinWin;
}
public function GetReelStrips($winType, $slotEvent)
{
$game = $this->game;
if( $slotEvent == 'freespin' )
{
$reel = new GameReel();
$fArr = $reel->reelsStripBonus;
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $reelStrip )
{
$curReel = array_shift($fArr);
if( count($curReel) )
{
$this->$reelStrip = $curReel;
}
}
}
if( $winType != 'bonus' )
{
$prs = [];
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $index => $reelStrip )
{
if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 )
{
$prs[$index + 1] = mt_rand(0, count($this->$reelStrip) - 3);
}
}
}
else
{
$reelsId = [];
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $index => $reelStrip )
{
if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 )
{
$prs[$index + 1] = $this->GetRandomScatterPos($this->$reelStrip);
$reelsId[] = $index + 1;
}
}
$scattersCnt = rand(3, count($reelsId));
shuffle($reelsId);
for( $i = 0; $i < count($reelsId); $i++ )
{
if( $i < $scattersCnt )
{
$prs[$reelsId[$i]] = $this->GetRandomScatterPos($this->{'reelStrip' . $reelsId[$i]});
}
else
{
$prs[$reelsId[$i]] = rand(0, count($this->{'reelStrip' . $reelsId[$i]}) - 3);
}
}
}
$reel = [
'rp' => []
];
foreach( $prs as $index => $value )
{
$key = $this->{'reelStrip' . $index};
$cnt = count($key);
$key[-1] = $key[$cnt - 1];
$key[$cnt] = $key[0];
$reel['reel' . $index][0] = $key[$value - 1];
$reel['reel' . $index][1] = $key[$value];
$reel['reel' . $index][2] = $key[$value + 1];
$reel['reel' . $index][3] = '';
$reel['rp'][] = $value;
}
return $reel;
}
}
}
| 412 | 0.631022 | 1 | 0.631022 | game-dev | MEDIA | 0.468293 | game-dev,web-backend | 0.805379 | 1 | 0.805379 |
mastercomfig/tf2-patches-old | 14,245 | src/game/client/replay/vgui/replaybrowsermainpanel.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#if defined( REPLAY_ENABLED )
#include "replaybrowsermainpanel.h"
#include "replaybrowserbasepage.h"
#include "confirm_delete_dialog.h"
#include "vgui_controls/PropertySheet.h"
#include "vgui_controls/TextImage.h"
#include "vgui/IInput.h"
#include "vgui/ISurface.h"
#include "ienginevgui.h"
#include "replay/ireplaymanager.h"
#include "replay/ireplaymoviemanager.h"
#include "econ/econ_controls.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
//-----------------------------------------------------------------------------
// Purpose: Replay deletion confirmation dialog
//-----------------------------------------------------------------------------
class CConfirmDeleteReplayDialog : public CConfirmDeleteDialog
{
DECLARE_CLASS_SIMPLE( CConfirmDeleteReplayDialog, CConfirmDeleteDialog );
public:
CConfirmDeleteReplayDialog( Panel *pParent, IReplayItemManager *pItemManager, int iPerformance )
: BaseClass( pParent )
{
m_pTextId = iPerformance >= 0 ? "#Replay_DeleteEditConfirm" : pItemManager->AreItemsMovies() ? "#Replay_DeleteMovieConfirm" : "#Replay_DeleteReplayConfirm";
}
const wchar_t *GetText()
{
return g_pVGuiLocalize->Find( m_pTextId );
}
const char *m_pTextId;
};
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CReplayBrowserPanel::CReplayBrowserPanel( Panel *parent )
: PropertyDialog(parent, "ReplayBrowser"),
m_pConfirmDeleteDialog( NULL )
{
// Clear out delete info
V_memset( &m_DeleteInfo, 0, sizeof( m_DeleteInfo ) );
// Replay browser is parented to the game UI panel
vgui::VPANEL gameuiPanel = enginevgui->GetPanel( PANEL_GAMEUIDLL );
SetParent( gameuiPanel );
SetMoveable( false );
SetSizeable( false );
vgui::HScheme scheme = vgui::scheme()->LoadSchemeFromFileEx( enginevgui->GetPanel( PANEL_CLIENTDLL ), "resource/ClientScheme.res", "ClientScheme");
SetScheme(scheme);
SetProportional( true );
// Setup page
m_pReplaysPage = new CReplayBrowserBasePage( this );
m_pReplaysPage->AddActionSignalTarget( this );
AddPage( m_pReplaysPage, "#Replay_MyReplays" );
m_pReplaysPage->SetVisible( true );
ListenForGameEvent( "gameui_hidden" );
// Create this now, so that it can be the default button (if created in .res file, it fights with PropertyDialog's OkButton & generates asserts)
CExButton *pCloseButton = new CExButton( this, "BackButton", "" );
GetFocusNavGroup().SetDefaultButton(pCloseButton);
m_flTimeOpened = 0.0f;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CReplayBrowserPanel::~CReplayBrowserPanel()
{
if ( m_pConfirmDeleteDialog )
{
m_pConfirmDeleteDialog->MarkForDeletion();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CReplayBrowserPanel::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
LoadControlSettings( "resource/ui/replaybrowser/mainpanel.res", "GAME" );
SetOKButtonVisible(false);
SetCancelButtonVisible(false);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CReplayBrowserPanel::PerformLayout( void )
{
if ( GetVParent() )
{
int w,h;
vgui::ipanel()->GetSize( GetVParent(), w, h );
SetBounds(0,0,w,h);
}
BaseClass::PerformLayout();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CReplayBrowserPanel::ShowPanel(bool bShow, ReplayHandle_t hReplayDetails/*=REPLAY_HANDLE_INVALID*/,
int iPerformance/*=-1*/ )
{
if ( bShow )
{
GetPropertySheet()->SetActivePage( m_pReplaysPage );
InvalidateLayout( false, true );
Activate();
m_flTimeOpened = gpGlobals->realtime;
}
else
{
PostMessage( m_pReplaysPage, new KeyValues("CancelSelection") );
}
SetVisible( bShow );
m_pReplaysPage->SetVisible( bShow );
if ( hReplayDetails != REPLAY_HANDLE_INVALID )
{
char szDetails[32];
V_snprintf( szDetails, sizeof( szDetails ), "details%i_%i", (int)hReplayDetails, iPerformance );
m_pReplaysPage->OnCommand( szDetails );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CReplayBrowserPanel::FireGameEvent( IGameEvent *event )
{
const char * type = event->GetName();
if ( Q_strcmp(type, "gameui_hidden") == 0 )
{
ShowPanel( false );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CReplayBrowserPanel::OnCommand( const char *command )
{
if ( !Q_stricmp( command, "back" ) )
{
if ( m_pReplaysPage->IsDetailsViewOpen() )
{
m_pReplaysPage->DeleteDetailsPanelAndShowReplayList();
}
else
{
// Close the main panel
ShowPanel( false );
// TODO: Properly manage the browser so that we don't have to recreate it ever time its opened
MarkForDeletion();
// If we're connected to a game server, we also close the game UI.
if ( engine->IsInGame() )
{
engine->ClientCmd_Unrestricted( "gameui_hide" );
}
}
}
BaseClass::OnCommand( command );
}
void CReplayBrowserPanel::OnKeyCodeTyped(vgui::KeyCode code)
{
if ( code == KEY_ESCAPE )
{
ShowPanel( false );
}
else
{
BaseClass::OnKeyCodeTyped( code );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CReplayBrowserPanel::OnKeyCodePressed(vgui::KeyCode code)
{
if ( GetBaseButtonCode( code ) == KEY_XBUTTON_B )
{
ShowPanel( false );
}
else if ( code == KEY_ENTER )
{
// do nothing, the default is to close the panel!
}
else
{
BaseClass::OnKeyCodePressed( code );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CReplayBrowserPanel::ShowDeleteReplayDenialDlg()
{
ShowMessageBox( "#Replay_DeleteDenialTitle", "#Replay_DeleteDenialText", "#GameUI_OK" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CReplayBrowserPanel::AttemptToDeleteReplayItem( Panel *pHandler, ReplayItemHandle_t hReplayItem,
IReplayItemManager *pItemManager, int iPerformance )
{
IQueryableReplayItem *pItem = pItemManager->GetItem( hReplayItem );
CGenericClassBasedReplay *pReplay = ToGenericClassBasedReplay( pItem->GetItemReplay() );
// If this is an actual replay the user is trying to delete, only allow it
// if the replay says it's OK. Don't execute this code for performances.
if ( !pItemManager->AreItemsMovies() && iPerformance < 0 && !pReplay->ShouldAllowDelete() )
{
ShowDeleteReplayDenialDlg();
return;
}
// Otherwise, show the confirm delete dlg
vgui::surface()->PlaySound( "replay\\replaydialog_warn.wav" );
ConfirmReplayItemDelete( pHandler, hReplayItem, pItemManager, iPerformance );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CReplayBrowserPanel::ConfirmReplayItemDelete( Panel *pHandler, ReplayItemHandle_t hReplayItem,
IReplayItemManager *pItemManager, int iPerformance )
{
CConfirmDeleteReplayDialog *pConfirm = vgui::SETUP_PANEL( new CConfirmDeleteReplayDialog( this, pItemManager, iPerformance ) );
if ( pConfirm )
{
// Cache replay and handler for later
m_DeleteInfo.m_hReplayItem = hReplayItem;
m_DeleteInfo.m_pItemManager = pItemManager;
m_DeleteInfo.m_hHandler = pHandler->GetVPanel();
m_DeleteInfo.m_iPerformance = iPerformance;
// Display the panel!
pConfirm->Show();
// Cache confirm dialog ptr
m_pConfirmDeleteDialog = pConfirm;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CReplayBrowserPanel::OnConfirmDelete( KeyValues *data )
{
// Clear confirm ptr
m_pConfirmDeleteDialog = NULL;
// User confirmed delete?
int nConfirmed = data->GetInt( "confirmed", 0 );
if ( !nConfirmed )
return;
// Get the replay from the dialog
ReplayItemHandle_t hReplayItem = m_DeleteInfo.m_hReplayItem;
// Post actions signal to the handler
KeyValues *pMsg = new KeyValues( "ReplayItemDeleted" );
pMsg->SetInt( "replayitem", (int)hReplayItem );
pMsg->SetInt( "perf", m_DeleteInfo.m_iPerformance );
PostMessage( m_DeleteInfo.m_hHandler, pMsg );
// Delete actual replay item
if ( m_DeleteInfo.m_iPerformance < 0 )
{
// Cleanup UI related to the replay/movie
CleanupUIForReplayItem( hReplayItem );
// Delete the replay/movie
m_DeleteInfo.m_pItemManager->DeleteItem( GetActivePage(), hReplayItem, false );
}
vgui::surface()->PlaySound( "replay\\deleted_take.wav" );
// Clear delete info
V_memset( &m_DeleteInfo, 0, sizeof( m_DeleteInfo ) );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CReplayBrowserPanel::OnSaveReplay( ReplayHandle_t hNewReplay )
{
// Verify that the handle is valid
Assert( g_pReplayManager->GetReplay( hNewReplay ) );
m_pReplaysPage->AddReplay( hNewReplay );
m_pReplaysPage->Repaint();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CReplayBrowserPanel::OnDeleteReplay( ReplayHandle_t hDeletedReplay )
{
// Verify that the handle is valid
Assert( g_pReplayManager->GetReplay( hDeletedReplay ) );
DeleteReplay( hDeletedReplay );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CReplayBrowserPanel::DeleteReplay( ReplayHandle_t hReplay )
{
m_pReplaysPage->DeleteReplay( hReplay );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CReplayBrowserPanel::CleanupUIForReplayItem( ReplayItemHandle_t hReplayItem )
{
if ( GetActivePage() == m_pReplaysPage )
{
m_pReplaysPage->CleanupUIForReplayItem( hReplayItem );
}
}
static vgui::DHANDLE<CReplayBrowserPanel> g_ReplayBrowserPanel;
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CReplayBrowserPanel *ReplayUI_OpenReplayBrowserPanel( ReplayHandle_t hReplayDetails,
int iPerformance )
{
if ( !g_ReplayBrowserPanel.Get() )
{
g_ReplayBrowserPanel = vgui::SETUP_PANEL( new CReplayBrowserPanel( NULL ) );
g_ReplayBrowserPanel->InvalidateLayout( false, true );
}
engine->ClientCmd_Unrestricted( "gameui_activate" );
g_ReplayBrowserPanel->ShowPanel( true, hReplayDetails, iPerformance );
extern IReplayMovieManager *g_pReplayMovieManager;
if ( g_pReplayMovieManager->GetMovieCount() > 0 )
{
// Fire a message the game DLL can intercept (for achievements, etc).
IGameEvent *event = gameeventmanager->CreateEvent( "browse_replays" );
if ( event )
{
gameeventmanager->FireEventClientSide( event );
}
}
return g_ReplayBrowserPanel;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CReplayBrowserPanel *ReplayUI_GetBrowserPanel( void )
{
return g_ReplayBrowserPanel.Get();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void ReplayUI_CloseReplayBrowser()
{
if ( g_ReplayBrowserPanel )
{
g_ReplayBrowserPanel->MarkForDeletion();
g_ReplayBrowserPanel = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void ReplayUI_ReloadBrowser( ReplayHandle_t hReplay/*=REPLAY_HANDLE_INVALID*/,
int iPerformance/*=-1*/ )
{
delete g_ReplayBrowserPanel.Get();
g_ReplayBrowserPanel = NULL;
ReplayUI_OpenReplayBrowserPanel( hReplay, iPerformance );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CON_COMMAND_F( open_replaybrowser, "Open the replay browser.", FCVAR_CLIENTDLL )
{
ReplayUI_OpenReplayBrowserPanel( REPLAY_HANDLE_INVALID, -1 );
g_ReplayBrowserPanel->InvalidateLayout( false, true );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CON_COMMAND_F( replay_reloadbrowser, "Reloads replay data and display replay browser", FCVAR_CLIENTDLL | FCVAR_CLIENTCMD_CAN_EXECUTE )
{
ReplayUI_ReloadBrowser();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CON_COMMAND_F( replay_hidebrowser, "Hides replay browser", FCVAR_CLIENTDLL )
{
ReplayUI_CloseReplayBrowser();
}
#endif | 412 | 0.91551 | 1 | 0.91551 | game-dev | MEDIA | 0.733178 | game-dev | 0.963659 | 1 | 0.963659 |
bozimmerman/CoffeeMud | 4,119 | com/planet_ink/coffee_mud/Abilities/Diseases/Disease_Sleepwalking.java | package com.planet_ink.coffee_mud.Abilities.Diseases;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2015-2025 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Disease_Sleepwalking extends Disease
{
@Override
public String ID()
{
return "Disease_Sleepwalking";
}
private final static String localizedName = CMLib.lang().L("Sleepwalking");
@Override
public String name()
{
return localizedName;
}
private final static String localizedStaticDisplay = "";
@Override
public String displayText()
{
return localizedStaticDisplay;
}
@Override
protected int canAffectCode()
{
return CAN_MOBS;
}
@Override
protected int canTargetCode()
{
return CAN_MOBS;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_MALICIOUS;
}
@Override
public boolean putInCommandlist()
{
return false;
}
@Override
protected int DISEASE_TICKS()
{
return 10;
}
@Override
protected int DISEASE_DELAY()
{
return 2;
}
@Override
protected String DISEASE_DONE()
{
return L("You feel more in control.");
}
@Override
protected String DISEASE_START()
{
return "";
}
@Override
protected String DISEASE_AFFECT()
{
return "";
}
@Override
public int spreadBitmap()
{
return 0;
}
@Override
public int difficultyLevel()
{
return 2;
}
@Override
public long flags()
{
return super.flags() | Ability.FLAG_MINDALTERING;
}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost, msg))
return false;
if((msg.source()==affected)
&&(CMLib.flags().isSleeping(affected))
&&((msg.sourceMinor()==CMMsg.TYP_ENTER)
||(msg.sourceMinor()==CMMsg.TYP_LEAVE)))
{
if(msg.sourceMessage()!=null)
msg.setSourceMessage(null);
}
return true;
}
@Override
public boolean tick(final Tickable ticking, final int tickID)
{
if(!super.tick(ticking,tickID))
return false;
if(affected==null)
return false;
if(!(affected instanceof MOB))
return true;
final MOB mob=(MOB)affected;
if((!mob.amDead())&&((--diseaseTick)<=0)&&(CMLib.flags().isSleeping(mob)))
{
final Room R=mob.location();
if((R!=null)&&(CMLib.flags().isInTheGame(mob, true))&&(!CMLib.flags().isBoundOrHeld(mob)))
{
final List<Integer> dirs=new ArrayList<Integer>(1);
for(final int d : Directions.CODES())
{
if((R.getRoomInDir(d)!=null)&&(R.getExitInDir(d)!=null)&&(R.getExitInDir(d).isOpen()))
dirs.add(Integer.valueOf(d));
}
if(dirs.size()>0)
{
final int dir=dirs.get(CMLib.dice().roll(1, dirs.size(), -1)).intValue();
CMLib.tracking().walk(mob, dir, false, true, true, true);
}
}
if(mob.location()==R)
diseaseTick=DISEASE_DELAY();
else
diseaseTick=CMLib.dice().roll(1, 3, -1);
}
return true;
}
}
| 412 | 0.85138 | 1 | 0.85138 | game-dev | MEDIA | 0.91028 | game-dev | 0.856381 | 1 | 0.856381 |
spoutcraft/Spoutcraft | 8,256 | src/main/java/org/spoutcraft/client/gui/error/GuiUnexpectedError.java | /*
* This file is part of Spoutcraft.
*
* Copyright (c) 2011 SpoutcraftDev <http://spoutcraft.org/>
* Spoutcraft is licensed under the GNU Lesser General Public License.
*
* Spoutcraft 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.
*
* Spoutcraft 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 org.spoutcraft.client.gui.error;
import java.awt.Desktop;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLConnection;
import org.lwjgl.Sys;
import org.lwjgl.opengl.GL11;
import net.minecraft.src.Minecraft;
import net.minecraft.src.GuiScreen;
import org.bukkit.ChatColor;
import org.spoutcraft.api.Spoutcraft;
import org.spoutcraft.api.gui.Button;
import org.spoutcraft.api.gui.Color;
import org.spoutcraft.api.gui.GenericButton;
import org.spoutcraft.api.gui.GenericLabel;
import org.spoutcraft.api.gui.GenericScrollArea;
import org.spoutcraft.api.gui.RenderPriority;
import org.spoutcraft.api.gui.WidgetAnchor;
import org.spoutcraft.client.SpoutClient;
public class GuiUnexpectedError extends GuiScreen {
private Throwable caused;
private GenericLabel hastebinLink;
private String hastebinURL;
private boolean generated = false;
public GuiUnexpectedError(Throwable caused) {
this.caused = caused;
}
public void initGui() {
GenericScrollArea screen = new GenericScrollArea();
screen.setHeight(height - 16 - 24).setWidth(width).setY(16 + 24).setX(0);
getScreen().attachWidget("Spoutcraft", screen);
GenericLabel label = new GenericLabel("Oh noes! An error has occurred!");
int size = Spoutcraft.getMinecraftFont().getTextWidth(label.getText());
label.setX((int) (width / 2 - size / 2)).setY(16);
label.setFixed(true).setPriority(RenderPriority.Lowest);
getScreen().attachWidget("Spoutcraft", label);
int top = 60;
Color grey = new Color(0.80F, 0.80F, 0.80F, 0.65F);
hastebinLink = new GenericLabel("Generating hastie...");
hastebinLink.setX(95).setY(top);
hastebinLink.setTextColor(grey);
screen.attachWidget("Spoutcraft", hastebinLink);
generateHastie();
Button button = new CopyErrorURL(this).setText("Copy Link");
button.setHeight(20).setWidth(80);
button.setX((int) (hastebinLink.getWidth() + hastebinLink.getX() + 10.0));
button.setY(top-5);
button.setAlign(WidgetAnchor.TOP_CENTER);
screen.attachWidget("Spoutcraft", button);
top += 25;
button = new ReportErrorButton().setText("Report");
button.setHeight(20).setWidth(70);
button.setX((int) (width / 2 - button.getWidth() - button.getWidth() / 2));
button.setY(top);
button.setAlign(WidgetAnchor.TOP_CENTER);
screen.attachWidget("Spoutcraft", button);
button = new IgnoreErrorButton().setText("Ignore");
button.setHeight(20).setWidth(70);
button.setX((int) (width / 2 + button.getWidth() / 2));
button.setY(top);
button.setAlign(WidgetAnchor.TOP_CENTER);
screen.attachWidget("Spoutcraft", button);
top += 30;
}
@Override
public void drawScreen(int var1, int var2, float var3) {
drawDefaultBackground();
}
private void generateHastie() {
if (generated) {
hastebinLink.setText("Error Link: " + ChatColor.GREEN + hastebinURL);
return;
}
try {
StringBuilder builder = new StringBuilder("Spoutcraft Error Report:\n");
builder.append(" Build: ").append(SpoutClient.getClientVersion()).append("\n");
builder.append("-----------------------------------").append("\n");
builder.append("Stack Trace:").append("\n");
builder.append(" Exception: ").append(caused.getClass().getSimpleName()).append("\n");
builder.append(" Message: ").append(caused.getMessage()).append("\n");
builder.append(" Trace:").append("\n");
StringWriter sw = new StringWriter();
caused.printStackTrace(new PrintWriter(sw));
String causeString = sw.toString();
builder.append(" ").append(sw).append("\n");
builder.append("-----------------------------------").append("\n");
builder.append("Minecraft Information:\n");
// ToDO:
//builder.append(" Texture Pack: ").append(Minecraft.getMinecraft().texturePackList.getSelectedTexturePack().getTexturePackFileName()).append("\n");
//builder.append(" Texture Pack Res: ").append(TileSize.int_size + "x").append("\n");
builder.append(" LWJGL Version: ").append(Sys.getVersion()).append("\n");
builder.append("System Information:\n");
builder.append(" Operating System: ").append(System.getProperty("os.name")).append("\n");
builder.append(" Operating System Version: ").append(System.getProperty("os.version")).append("\n");
builder.append(" Operating System Architecture: ").append(System.getProperty("os.arch")).append("\n");
builder.append(" Java version: ").append(System.getProperty("java.version")).append(" ").append(System.getProperty("sun.arch.data.model", "32")).append(" bit").append("\n");
builder.append(" Total Memory: ").append(Runtime.getRuntime().totalMemory() / 1024L / 1024L).append(" MB\n");
builder.append(" Max Memory: ").append(Runtime.getRuntime().maxMemory() / 1024L / 1024L).append(" MB\n");
builder.append(" Memory Free: ").append(Runtime.getRuntime().freeMemory() / 1024L / 1024L).append(" MB\n");
builder.append(" CPU Cores: ").append(Runtime.getRuntime().availableProcessors()).append("\n");
builder.append(" OpenGL Version: ").append(GL11.glGetString(GL11.GL_VERSION)).append("\n");
builder.append(" OpenGL Vendor: ").append(GL11.glGetString(GL11.GL_VENDOR)).append("\n");
String message = builder.toString();
PasteBinAPI pastebin = new PasteBinAPI("963f01dd506cb3f607a487bc34b60d16");
String response = pastebin.makePaste(message, "ser_" + System.currentTimeMillis(), "text");
System.out.println("pastebin response: " + response);
if (!response.startsWith("http://pastebin.com")) {
URL url = new URL("http://www.hastebin.com/documents");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(builder.toString());
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = rd.readLine();
hastebinURL = "hastebin.com/" + line.substring(8, line.length() - 2); // Get rid of the JSON stuff
wr.close();
rd.close();
} else {
hastebinURL = response;
}
hastebinLink.setText("Error: " + ChatColor.GREEN + hastebinURL);
generated = true;
} catch (Exception e) {
hastebinLink.setText("Connection error!");
}
}
protected void copyErrorToClipboard() {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(hastebinURL), null);
}
}
class CopyErrorURL extends GenericButton {
private GuiUnexpectedError error;
CopyErrorURL(GuiUnexpectedError error) {
this.error = error;
}
public void onButtonClick() {
error.copyErrorToClipboard();
}
}
class IgnoreErrorButton extends GenericButton {
public void onButtonClick() {
Minecraft.getMinecraft().displayGuiScreen(new org.spoutcraft.client.gui.mainmenu.MainMenu());
}
}
class ReportErrorButton extends GenericButton {
public void onButtonClick() {
try {
URL url = new URL("http://spout.in/issues");
Desktop.getDesktop().browse(url.toURI());
} catch (Exception e) { }
Minecraft.getMinecraft().displayGuiScreen(new org.spoutcraft.client.gui.mainmenu.MainMenu());
}
}
class ExitGameButton extends GenericButton {
public void onButtonClick() {
Minecraft.getMinecraft().shutdownMinecraftApplet();
}
}
| 412 | 0.779422 | 1 | 0.779422 | game-dev | MEDIA | 0.667831 | game-dev | 0.773686 | 1 | 0.773686 |
facebookarchive/FBAllocationTracker | 1,290 | FBAllocationTrackerTests/FBAllocationTrackerManagerTests.mm | /**
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#import <XCTest/XCTest.h>
#import "FBAllocationTrackerManager.h"
@interface _FBATMTestClass : NSObject
@end
@implementation _FBATMTestClass
@end
@interface FBAllocationTrackerManagerTests : XCTestCase
@end
@implementation FBAllocationTrackerManagerTests
- (void)setUp
{
[super setUp];
[[FBAllocationTrackerManager sharedManager] startTrackingAllocations];
[[FBAllocationTrackerManager sharedManager] enableGenerations];
}
- (void)tearDown
{
[[FBAllocationTrackerManager sharedManager] disableGenerations];
[[FBAllocationTrackerManager sharedManager] stopTrackingAllocations];
[super tearDown];
}
- (void)testAllocWithZoneIsTracked {
XCTAssertEqualObjects(@[], [[FBAllocationTrackerManager sharedManager] instancesOfClasses:@[[_FBATMTestClass class]]]);
id object = [[_FBATMTestClass allocWithZone:nil] init];
XCTAssertEqualObjects(@[object], [[FBAllocationTrackerManager sharedManager] instancesOfClasses:@[[_FBATMTestClass class]]]);
}
@end
| 412 | 0.81429 | 1 | 0.81429 | game-dev | MEDIA | 0.381566 | game-dev | 0.685451 | 1 | 0.685451 |
fossasia/x-mario-center | 6,061 | softwarecenter/backend/scagent.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Canonical
#
# Authors:
# Michael Vogt
#
# 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; version 3.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
from gi.repository import GObject
import logging
import softwarecenter.paths
from spawn_helper import SpawnHelper
from softwarecenter.i18n import get_language
from softwarecenter.distro import get_distro, get_current_arch
LOG = logging.getLogger(__name__)
class SoftwareCenterAgent(GObject.GObject):
__gsignals__ = {
"available-for-me": (GObject.SIGNAL_RUN_LAST,
GObject.TYPE_NONE,
(GObject.TYPE_PYOBJECT,),
),
"available": (GObject.SIGNAL_RUN_LAST,
GObject.TYPE_NONE,
(GObject.TYPE_PYOBJECT,),
),
"exhibits": (GObject.SIGNAL_RUN_LAST,
GObject.TYPE_NONE,
(GObject.TYPE_PYOBJECT,),
),
"error": (GObject.SIGNAL_RUN_LAST,
GObject.TYPE_NONE,
(str,),
),
}
def __init__(self, ignore_cache=False, xid=None):
GObject.GObject.__init__(self)
self.distro = get_distro()
self.ignore_cache = ignore_cache
self.xid = xid
def query_available(self, series_name=None, arch_tag=None):
self._query_available(series_name, arch_tag, for_qa=False)
def query_available_qa(self, series_name=None, arch_tag=None):
self._query_available(series_name, arch_tag, for_qa=True)
def _query_available(self, series_name, arch_tag, for_qa):
if not series_name:
series_name = self.distro.get_codename()
if not arch_tag:
arch_tag = get_current_arch()
# build the command
spawner = SpawnHelper()
spawner.parent_xid = self.xid
spawner.ignore_cache = self.ignore_cache
spawner.connect("data-available", self._on_query_available_data)
spawner.connect("error", lambda spawner, err: self.emit("error", err))
if for_qa:
spawner.needs_auth = True
spawner.run_generic_piston_helper(
"SoftwareCenterAgentAPI",
"available_apps_qa",
lang=get_language(),
series=series_name,
arch=arch_tag)
else:
spawner.run_generic_piston_helper(
"SoftwareCenterAgentAPI",
"available_apps",
lang=get_language(),
series=series_name,
arch=arch_tag)
def _on_query_available_data(self, spawner, piston_available):
self.emit("available", piston_available)
def query_available_for_me(self):
spawner = SpawnHelper()
spawner.parent_xid = self.xid
spawner.ignore_cache = self.ignore_cache
spawner.connect("data-available", self._on_query_available_for_me_data)
spawner.connect("error", lambda spawner, err: self.emit("error", err))
spawner.needs_auth = True
spawner.run_generic_piston_helper(
"SoftwareCenterAgentAPI", "subscriptions_for_me",
complete_only=True)
def _on_query_available_for_me_data(self, spawner,
piston_available_for_me):
self.emit("available-for-me", piston_available_for_me)
def query_exhibits(self):
spawner = SpawnHelper()
spawner.parent_xid = self.xid
spawner.ignore_cache = self.ignore_cache
spawner.connect("data-available", self._on_exhibits_data_available)
spawner.connect("error", lambda spawner, err: self.emit("error", err))
spawner.run_generic_piston_helper(
"SoftwareCenterAgentAPI", "exhibits",
lang=get_language(), series=self.distro.get_codename())
def _on_exhibits_data_available(self, spawner, exhibits):
for exhibit in exhibits:
# special case, if there is no title provided by the server
# just extract the title from the first "h1" html
if not hasattr(exhibit, "title_translated"):
if exhibit.html:
from softwarecenter.utils import get_title_from_html
exhibit.title_translated = get_title_from_html(
exhibit.html)
else:
exhibit.title_translated = ""
# ensure to fix #1004417
if exhibit.package_names:
exhibit.package_names = exhibit.package_names.strip()
self.emit("exhibits", exhibits)
if __name__ == "__main__":
def _available(agent, available):
print ("_available: %s" % available)
def _available_for_me(agent, available_for_me):
print ("_availalbe_for_me: %s" % available_for_me)
def _exhibits(agent, exhibits):
print ("exhibits: " % exhibits)
def _error(agent, msg):
print ("got a error" % msg)
#gtk.main_quit()
# test specific stuff
logging.basicConfig()
softwarecenter.paths.datadir = "./data"
scagent = SoftwareCenterAgent()
scagent.connect("available-for-me", _available_for_me)
scagent.connect("available", _available)
scagent.connect("exhibits", _exhibits)
scagent.connect("error", _error)
#scagent.query_available("natty", "i386")
#scagent.query_available_for_me()
scagent.query_exhibits()
from gi.repository import Gtk
Gtk.main()
| 412 | 0.883156 | 1 | 0.883156 | game-dev | MEDIA | 0.381312 | game-dev | 0.752691 | 1 | 0.752691 |
Hoto-Mocha/Re-ARranged-Pixel-Dungeon | 26,513 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/mobs/GnollGeomancer.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2025 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.actors.mobs;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.Badges;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.Statistics;
import com.shatteredpixel.shatteredpixeldungeon.actors.Actor;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Invisibility;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Paralysis;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.ShieldBuff;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs.Blacksmith;
import com.shatteredpixel.shatteredpixeldungeon.effects.CellEmitter;
import com.shatteredpixel.shatteredpixeldungeon.effects.Pushing;
import com.shatteredpixel.shatteredpixeldungeon.effects.Speck;
import com.shatteredpixel.shatteredpixeldungeon.effects.Splash;
import com.shatteredpixel.shatteredpixeldungeon.effects.TargetedCell;
import com.shatteredpixel.shatteredpixeldungeon.items.Item;
import com.shatteredpixel.shatteredpixeldungeon.items.quest.DarkGold;
import com.shatteredpixel.shatteredpixeldungeon.items.quest.Pickaxe;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfTeleportation;
import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfBlastWave;
import com.shatteredpixel.shatteredpixeldungeon.levels.Level;
import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain;
import com.shatteredpixel.shatteredpixeldungeon.mechanics.Ballistica;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene;
import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene;
import com.shatteredpixel.shatteredpixeldungeon.sprites.GnollGeomancerSprite;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet;
import com.shatteredpixel.shatteredpixeldungeon.sprites.MissileSprite;
import com.shatteredpixel.shatteredpixeldungeon.ui.BossHealthBar;
import com.shatteredpixel.shatteredpixeldungeon.utils.GLog;
import com.watabou.noosa.audio.Sample;
import com.watabou.utils.Bundle;
import com.watabou.utils.Callback;
import com.watabou.utils.GameMath;
import com.watabou.utils.PathFinder;
import com.watabou.utils.Random;
import java.util.ArrayList;
public class GnollGeomancer extends Mob {
{
HP = HT = 150;
spriteClass = GnollGeomancerSprite.class;
EXP = 20;
//acts after other mobs, just like sappers
actPriority = MOB_PRIO-1;
SLEEPING = new Sleeping();
HUNTING = new Hunting();
state = SLEEPING;
//FOV is used to attack hero when they are in open space created by geomancer
// but geomancer will lose sight and stop attacking if the hero flees behind walls.
// Because of this geomancer can see through high grass and shrouding fod
viewDistance = 12;
properties.add(Property.BOSS);
properties.add(Property.IMMOVABLE); //moves itself via ability, otherwise is static
}
private int abilityCooldown = Random.NormalIntRange(3, 5);
private boolean lastAbilityWasRockfall;
private int[] throwingRocksFromPos = null;
private int throwingRockToPos = -1; //only need 1 to pos, it's always the same.
private int sapperID = -1;
private int[] sapperSpawns = null;
@Override
protected boolean act() {
if (sapperSpawns == null){
sapperSpawns = new int[3];
int i = 0;
for (Mob m : Dungeon.level.mobs){
if (m instanceof GnollSapper){
sapperSpawns[i] = ((GnollSapper) m).spawnPos;
i++;
}
if (i == 3) break;
}
}
if (throwingRocksFromPos != null){
boolean attacked = false;
for (int rock : throwingRocksFromPos) {
if (rock != -1 && Dungeon.level.map[rock] == Terrain.MINE_BOULDER) {
attacked = true;
GnollGeomancer.doRockThrowAttack(this, rock, throwingRockToPos);
}
}
throwingRocksFromPos = null;
throwingRockToPos = -1;
spend(TICK);
return !attacked;
} else {
return super.act();
}
}
@Override
public boolean isInvulnerable(Class effect) {
return super.isInvulnerable(effect)
|| (buff(RockArmor.class) != null && effect != Pickaxe.class)
|| hasSapper();
}
@Override
public boolean add(Buff buff) {
//immune to buffs and debuff (except its own buffs) while sleeping
if (state == SLEEPING && !(buff instanceof RockArmor || buff instanceof DelayedRockFall)){
return false;
} else {
return super.add(buff);
}
}
@Override
public int damageRoll() {
return Random.NormalIntRange( 3, 6 );
}
@Override
public int attackSkill( Char target ) {
return 20;
}
@Override
public int drRoll() {
return super.drRoll() + Random.NormalIntRange(0, 6);
}
@Override
public boolean reset() {
return true;
}
@Override
public float spawningWeight() {
return 0;
}
@Override
public boolean heroShouldInteract() {
return super.heroShouldInteract() || buff(RockArmor.class) != null;
}
@Override
protected boolean getCloser(int target) {
return false;
}
@Override
protected boolean getFurther(int target) {
return false;
}
int hits = 0;
@Override
public boolean interact(Char c) {
if (c != Dungeon.hero || buff(RockArmor.class) == null) {
return super.interact(c);
} else {
final Pickaxe p = Dungeon.hero.belongings.getItem(Pickaxe.class);
if (p == null){
return true;
}
Dungeon.hero.sprite.attack(pos, new Callback() {
@Override
public void call() {
//does its own special damage calculation that's only influenced by pickaxe level and augment
//we pretend the geomancer is the owner here so that properties like hero str or or other equipment do not factor in
int dmg = p.damageRoll(GnollGeomancer.this);
boolean wasSleeping = state == SLEEPING;
//ensure we don't do enough damage to break the armor at the start
if (wasSleeping) dmg = Math.min(dmg, 15);
dmg = Math.min(dmg, buff(RockArmor.class).shielding());
damage(dmg, p);
sprite.bloodBurstA(Dungeon.hero.sprite.center(), dmg);
sprite.flash();
hits++;
if (hits == 1){
GLog.w( Messages.get(GnollGeomancer.this, "warning"));
} if (hits == 3){
GLog.n( Messages.get(GnollGeomancer.this, "alert"));
wasSleeping = false;
spend(TICK);
sprite.idle();
carveRockAndDash();
state = HUNTING;
enemy = Dungeon.hero;
BossHealthBar.assignBoss(GnollGeomancer.this);
for (Mob m : Dungeon.level.mobs){
if (m instanceof GnollGuard){
m.aggro(Dungeon.hero);
if (!((GnollGuard) m).hasSapper()){
m.beckon(pos);
}
} else if (m instanceof GnollSapper){
m.aggro(Dungeon.hero);
}
}
}
if (wasSleeping) {
state = SLEEPING;
alerted = false;
}
if (buff(RockArmor.class) == null){
Splash.around(sprite, 0x555555, 30);
sprite.idle();
}
Sample.INSTANCE.play(Assets.Sounds.MINE, 1f, Random.Float(0.85f, 1.15f));
Invisibility.dispel(Dungeon.hero);
Dungeon.hero.spendAndNext(p.delayFactor(GnollGeomancer.this));
}
});
return false;
}
}
@Override
public void damage(int dmg, Object src) {
int hpBracket = HT / 3;
int curbracket = HP / hpBracket;
if (curbracket == 3) curbracket--; //full HP isn't its own bracket
inFinalBracket = curbracket == 0;
super.damage(dmg, src);
abilityCooldown -= dmg/10f;
int newBracket = HP / hpBracket;
if (newBracket == 3) newBracket--; //full HP isn't its own bracket
if (newBracket != curbracket) {
//cannot be hit through multiple brackets at a time
if (HP <= (curbracket-1)*hpBracket){
HP = (curbracket-1)*hpBracket + 1;
}
BossHealthBar.bleed(newBracket <= 0);
carveRockAndDash();
Buff.affect(this, RockArmor.class).setShield(25);
}
}
private boolean inFinalBracket = false;
@Override
public boolean isAlive() {
//cannot die until final HP bracket, regardless of incoming dmg
return super.isAlive() || !inFinalBracket;
}
public void linkSapper( GnollSapper sapper ){
this.sapperID = sapper.id();
if (sprite instanceof GnollGeomancerSprite){
((GnollGeomancerSprite) sprite).setupArmor();
}
}
public boolean hasSapper(){
return sapperID != -1
&& Actor.findById(sapperID) instanceof GnollSapper
&& ((GnollSapper)Actor.findById(sapperID)).isAlive();
}
public void loseSapper(){
if (sapperID != -1){
sapperID = -1;
if (sprite instanceof GnollGeomancerSprite){
((GnollGeomancerSprite) sprite).loseArmor();
}
}
}
private void carveRockAndDash(){
//aim for closest sapper, preferring living ones within 16 tiles
int closestSapperPos = -1;
boolean closestisAlive = false;
for (int i = 0; i < sapperSpawns.length; i++){
if (sapperSpawns[i] == -1){
continue;
}
if (closestSapperPos == -1) {
closestSapperPos = sapperSpawns[i];
for (Mob m : Dungeon.level.mobs){
if (m instanceof GnollSapper && ((GnollSapper) m).spawnPos == closestSapperPos){
closestisAlive = true;
break;
}
}
continue;
}
boolean sapperAlive = false;
for (Mob m : Dungeon.level.mobs){
if (m instanceof GnollSapper && ((GnollSapper) m).spawnPos == sapperSpawns[i]){
sapperAlive = true;
break;
}
}
if ((sapperAlive && !closestisAlive && Dungeon.level.distance(pos, sapperSpawns[i]) <= 16)
|| Dungeon.level.trueDistance(pos, sapperSpawns[i]) < Dungeon.level.trueDistance(pos, closestSapperPos)) {
closestSapperPos = sapperSpawns[i];
closestisAlive = sapperAlive;
}
}
int dashPos = closestSapperPos;
//can only dash 3 times
if (dashPos == -1){
return;
}
//if spawn pos is more than 12 tiles away, get as close as possible
Ballistica path = new Ballistica(pos, dashPos, Ballistica.STOP_TARGET);
if (path.dist > 12){
dashPos = path.path.get(12);
}
if (Actor.findChar(dashPos) != null || Dungeon.level.traps.get(dashPos) != null){
ArrayList<Integer> candidates = new ArrayList<>();
for (int i : PathFinder.NEIGHBOURS8){
if (Actor.findChar(dashPos+i) == null && Dungeon.level.traps.get(dashPos+i) == null){
candidates.add(dashPos+i);
}
}
if (!candidates.isEmpty()) {
dashPos = Random.element(candidates);
}
}
for (int i = 0; i < sapperSpawns.length; i++){
if (sapperSpawns[i] == closestSapperPos){
sapperSpawns[i] = -1;
}
}
path = new Ballistica(pos, dashPos, Ballistica.STOP_TARGET);
ArrayList<Integer> cells = new ArrayList<>(path.subPath(0, path.dist));
cells.addAll(spreadDiamondAOE(cells));
cells.addAll(spreadDiamondAOE(cells));
cells.addAll(spreadDiamondAOE(cells));
ArrayList<Integer> exteriorCells = spreadDiamondAOE(cells);
for (int i : cells){
if (Dungeon.level.map[i] == Terrain.WALL_DECO){
Dungeon.level.drop(new DarkGold(), i).sprite.drop();
Dungeon.level.map[i] = Terrain.EMPTY_DECO;
} else if (Dungeon.level.solid[i]){
if (Random.Int(3) == 0){
Dungeon.level.map[i] = Terrain.MINE_BOULDER;
} else {
Dungeon.level.map[i] = Terrain.EMPTY_DECO;
}
} else if (Dungeon.level.map[i] == Terrain.HIGH_GRASS || Dungeon.level.map[i] == Terrain.FURROWED_GRASS){
Dungeon.level.map[i] = Terrain.GRASS;
}
CellEmitter.get( i - Dungeon.level.width() ).start(Speck.factory(Speck.ROCK), 0.07f, 10);
}
for (int i : exteriorCells){
if (!Dungeon.level.solid[i]
&& Dungeon.level.map[i] != Terrain.EMPTY_SP
&& !Dungeon.level.adjacent(i, Dungeon.level.entrance())
&& Dungeon.level.traps.get(i) == null
&& Dungeon.level.plants.get(i) == null
&& Actor.findChar(i) == null){
Dungeon.level.map[i] = Terrain.MINE_BOULDER;
}
}
if (Dungeon.level.solid[dashPos]){
Dungeon.level.map[dashPos] = Terrain.EMPTY_DECO;
}
//we potentially update a lot of cells, so might as well just reset properties instead of incrementally updating
Dungeon.level.buildFlagMaps();
Dungeon.level.cleanWalls();
GameScene.updateMap();
GameScene.updateFog();
Dungeon.observe();
PixelScene.shake(3, 0.7f);
Sample.INSTANCE.play(Assets.Sounds.ROCKS);
int oldpos = pos;
pos = dashPos;
spend(TICK);
abilityCooldown = 1;
Actor.add(new Pushing(this, oldpos, pos));
if (closestisAlive){
GnollSapper closest = null;
for (Mob m : Dungeon.level.mobs){
if (m instanceof GnollSapper && ((GnollSapper) m).spawnPos == closestSapperPos){
closest = (GnollSapper) m;
break;
}
}
if (closest != null){
Actor guard = closest.getPartner();
closest.linkPartner(this);
//moves sapper and its guard toward geomancer if it is too far away
if (Dungeon.level.distance(closest.pos, dashPos) > 3){
ArrayList<Integer> candidates = new ArrayList<>();
for (int i : PathFinder.NEIGHBOURS8){
if (!Dungeon.level.solid[dashPos+i]
&& Dungeon.level.traps.get(dashPos+i) == null
&& Dungeon.level.plants.get(dashPos+i) == null
&& Actor.findChar(dashPos+i) == null){
candidates.add(dashPos+i);
}
}
if (!candidates.isEmpty()){
int newSapperPos = Random.element(candidates);
ScrollOfTeleportation.appear(closest, newSapperPos);
closest.spawnPos = newSapperPos;
candidates.remove((Integer)newSapperPos);
if (guard instanceof GnollGuard && !candidates.isEmpty()){
ScrollOfTeleportation.appear((GnollGuard)guard, Random.element(candidates));
}
}
}
}
}
}
private ArrayList<Integer> spreadDiamondAOE(ArrayList<Integer> currentCells){
ArrayList<Integer> spreadCells = new ArrayList<>();
for (int i : currentCells){
for (int j : PathFinder.NEIGHBOURS4){
if (Dungeon.level.insideMap(i+j) && !spreadCells.contains(i+j) && !currentCells.contains(i+j)){
spreadCells.add(i+j);
}
}
}
return spreadCells;
}
@Override
public String description() {
if (state == SLEEPING){
return Messages.get(this, "desc_sleeping");
} else {
String desc = super.description();
if (buff(RockArmor.class) != null){
if (hasSapper()){
desc += "\n\n" + Messages.get(this, "desc_armor_sapper");
} else {
desc += "\n\n" + Messages.get(this, "desc_armor");
}
}
return desc;
}
}
@Override
public void die(Object cause) {
super.die(cause);
Blacksmith.Quest.beatBoss();
Sample.INSTANCE.playDelayed(Assets.Sounds.ROCKS, 0.1f);
PixelScene.shake( 3, 0.7f );
for (int i = 0; i < Dungeon.level.length(); i++){
if (Dungeon.level.map[i] == Terrain.MINE_BOULDER && Dungeon.level.trueDistance(i, pos) <= 6){
Level.set(i, Terrain.EMPTY_DECO);
GameScene.updateMap(i);
Splash.at(i, 0x555555, 15);
}
}
}
@Override
public void beckon(int cell) {
if (state == SLEEPING){
//do nothing
} else {
super.beckon(cell);
}
}
private class Sleeping extends Mob.Sleeping {
@Override
protected void awaken(boolean enemyInFOV) {
//do nothing, has special awakening rules
}
}
private class Hunting extends Mob.Hunting {
@Override
public boolean act(boolean enemyInFOV, boolean justAlerted) {
if (!enemyInFOV){
spend(TICK);
return true;
} else {
enemySeen = true;
//use abilities more frequently on the hero's initial approach or if sapper is alive
// but only if hero isn't stunned, to prevent stunlocking
if ((Dungeon.level.distance(pos, enemy.pos) > 2 || hasSapper())
&& buff(RockArmor.class) != null
&& enemy.buff(Paralysis.class) == null){
abilityCooldown -= 1f;
}
if (hasSapper()){
((GnollSapper)Actor.findById(sapperID)).aggro(enemy);
}
if (abilityCooldown-- <= 0){
boolean targetNextToBarricade = false;
for (int i : PathFinder.NEIGHBOURS8){
if (Dungeon.level.map[enemy.pos+i] == Terrain.BARRICADE
|| Dungeon.level.map[enemy.pos+i] == Terrain.ENTRANCE){
targetNextToBarricade = true;
break;
}
}
// 50/50 to either throw a rock or do rockfall, but never do rockfall twice
// unless target is next to a barricade, then always try to throw
// unless nothing to throw, then always rockfall
int hpBracket = HT / 3;
int curbracket = HP / hpBracket;
if (curbracket == 3) curbracket--; //full HP isn't its own bracket
Ballistica aim = GnollGeomancer.prepRockThrowAttack(enemy, GnollGeomancer.this);
if (aim != null && (targetNextToBarricade || lastAbilityWasRockfall || Random.Int(2) == 0)) {
lastAbilityWasRockfall = false;
throwingRocksFromPos = new int[]{-1, -1, -1};
throwingRockToPos = aim.collisionPos;
//do up to 3 thrown rock attacks at once, depending on HP
for (int i = 0; i < 3 - curbracket; i++){
if (aim == null) break;
throwingRocksFromPos[i] = aim.sourcePos;
Ballistica warnPath = new Ballistica(aim.sourcePos, aim.collisionPos, Ballistica.STOP_SOLID);
for (int j : warnPath.subPath(0, warnPath.dist)){
sprite.parent.add(new TargetedCell(j, 0xFF0000));
}
aim = GnollGeomancer.prepRockThrowAttack(enemy, GnollGeomancer.this);
}
Dungeon.hero.interrupt();
abilityCooldown = Random.NormalIntRange(3, 5);
spend(GameMath.gate(TICK, (int)Math.ceil(enemy.cooldown()), 3*TICK));
return true;
} else if (GnollGeomancer.prepRockFallAttack(enemy, GnollGeomancer.this, 6-2*curbracket, true)) {
lastAbilityWasRockfall = true;
Dungeon.hero.interrupt();
spend(GameMath.gate(TICK, (int)Math.ceil(enemy.cooldown()), 3*TICK));
abilityCooldown = Random.NormalIntRange(3, 5);
return true;
}
}
//does not perform regular attacks
spend(TICK);
return true;
}
}
}
//*** These methods are public static as their logic is also accessed by gnoll sappers ***
public static Ballistica prepRockThrowAttack( Char target, Char source ){
ArrayList<Integer> candidateRocks = new ArrayList<>();
for (int i = 0; i < Dungeon.level.length(); i++){
if (source.fieldOfView[i] && Dungeon.level.map[i] == Terrain.MINE_BOULDER){
if (new Ballistica(i, target.pos, Ballistica.PROJECTILE).collisionPos == target.pos){
candidateRocks.add(i);
}
}
}
//ignore rocks already being thrown
for (Char ch : Actor.chars()){
if (ch instanceof GnollGeomancer && ((GnollGeomancer) ch).throwingRocksFromPos != null){
for (int i : ((GnollGeomancer) ch).throwingRocksFromPos){
candidateRocks.remove((Integer)i);
}
} else if (ch instanceof GnollSapper){
candidateRocks.remove((Integer)((GnollSapper) ch).throwingRockFromPos);
}
}
if (candidateRocks.isEmpty()){
return null;
} else {
//throw closest rock to enemy
int throwingFromPos = candidateRocks.get(0);
for (int i : candidateRocks){
if (Dungeon.level.trueDistance(i, target.pos) < Dungeon.level.trueDistance(throwingFromPos, target.pos)){
throwingFromPos = i;
}
}
int throwingToPos = target.pos;
return new Ballistica(throwingFromPos, throwingToPos, Ballistica.PROJECTILE);
}
}
private static int rocksInFlight = 0;
private static ArrayList<Char> knockedChars = new ArrayList<>();
public static void doRockThrowAttack( Char source, int from, int to ){
Level.set(from, Terrain.EMPTY);
GameScene.updateMap(from);
source.sprite.attack(from, new Callback() {
@Override
public void call() {
source.sprite.idle();
//do nothing
}
});
Ballistica rockPath = new Ballistica(from, to, Ballistica.MAGIC_BOLT);
Sample.INSTANCE.play(Assets.Sounds.MISS);
((MissileSprite)source.sprite.parent.recycle( MissileSprite.class )).
reset( from, rockPath.collisionPos, new GnollGeomancer.Boulder(), new Callback() {
@Override
public void call() {
Splash.at(rockPath.collisionPos, 0x555555, 15);
Sample.INSTANCE.play(Assets.Sounds.ROCKS);
Char ch = Actor.findChar(rockPath.collisionPos);
if (ch == Dungeon.hero){
PixelScene.shake( 3, 0.7f );
} else {
PixelScene.shake(0.5f, 0.5f);
}
if (ch != null && !(ch instanceof GnollGeomancer)){
ch.damage(Random.NormalIntRange(6, 12), new GnollGeomancer.Boulder());
if (ch == Dungeon.hero){
Statistics.questScores[2] -= 100;
}
if (ch.isAlive()){
Buff.prolong( ch, Paralysis.class, ch instanceof GnollGuard ? 10 : 3 );
} else if (!ch.isAlive() && ch == Dungeon.hero) {
Badges.validateDeathFromEnemyMagic();
Dungeon.fail( source.getClass() );
GLog.n( Messages.get( GnollGeomancer.class, "rock_kill") );
}
if (!knockedChars.contains(ch) && rockPath.path.size() > rockPath.dist+1) {
Ballistica trajectory = new Ballistica(ch.pos, rockPath.path.get(rockPath.dist + 1), Ballistica.MAGIC_BOLT);
WandOfBlastWave.throwChar(ch, trajectory, 1, false, false, source);
knockedChars.add(ch);
}
} else if (ch == null) {
Dungeon.level.pressCell(rockPath.collisionPos);
}
rocksInFlight--;
if (rocksInFlight <= 0) {
rocksInFlight = 0;
source.next();
knockedChars.clear();
}
}
} );
rocksInFlight++;
}
public static class Boulder extends Item {
{
image = ItemSpriteSheet.GEO_BOULDER;
}
}
//similar overall logic as DM-300's rock fall attack, but with more parameters
public static boolean prepRockFallAttack( Char target, Char source, int range, boolean avoidBarricades ){
final int rockCenter = target.pos;
int safeCell;
do {
safeCell = rockCenter + PathFinder.NEIGHBOURS8[Random.Int(8)];
} while (safeCell == source.pos
|| (Dungeon.level.solid[safeCell] && Random.Int(5) != 0)
|| (Dungeon.level.traps.containsKey(safeCell) && Random.Int(5) != 0));
ArrayList<Integer> rockCells = new ArrayList<>();
int start = rockCenter - Dungeon.level.width() * range - range;
int pos;
for (int y = 0; y < 1+2*range; y++) {
pos = start + Dungeon.level.width() * y;
for (int x = 0; x < 1+2*range; x++) {
if (!Dungeon.level.insideMap(pos)) {
pos++;
continue;
}
if (avoidBarricades){
boolean barricade = false;
for (int j : PathFinder.NEIGHBOURS9){
if (Dungeon.level.map[pos+j] == Terrain.BARRICADE
|| Dungeon.level.map[pos+j] == Terrain.ENTRANCE){
barricade = true;
}
}
if (barricade){
pos++;
continue;
}
}
//add rock cell to pos, if it is not solid, isn't the safecell, and isn't where geomancer is standing
if (!Dungeon.level.solid[pos]
&& pos != safeCell
&& !(Actor.findChar(pos) instanceof GnollGeomancer)
&& !(source instanceof GnollGeomancer && Actor.findChar(pos) instanceof GnollSapper)
&& Random.Int(1+Dungeon.level.distance(rockCenter, pos)/2) == 0) {
rockCells.add(pos);
}
pos++;
}
}
for (int i : rockCells){
source.sprite.parent.add(new TargetedCell(i, 0xFF0000));
}
//don't want to overly punish players with slow move or attack speed
Buff.append(source, GnollRockFall.class, GameMath.gate(TICK, (int)Math.ceil(target.cooldown()), 3*TICK)).setRockPositions(rockCells);
source.sprite.attack(target.pos, new Callback() {
@Override
public void call() {
//do nothing
source.sprite.idle();
}
});
return true;
}
public static class GnollRockFall extends DelayedRockFall{
@Override
public void affectChar(Char ch) {
ch.damage(Random.NormalIntRange(6, 12), this);
if (ch == Dungeon.hero){
Statistics.questScores[2] -= 100;
}
if (ch.isAlive()) {
Buff.prolong(ch, Paralysis.class, ch instanceof GnollGuard ? 10 : 3);
} else if (ch == Dungeon.hero){
Dungeon.fail( target );
GLog.n( Messages.get( GnollGeomancer.class, "rockfall_kill") );
}
}
@Override
public void affectCell(int cell) {
if (Dungeon.level.map[cell] != Terrain.EMPTY_SP
&& !Dungeon.level.adjacent(cell, Dungeon.level.entrance())
&& Random.Int(3) == 0) {
Level.set(cell, Terrain.MINE_BOULDER);
GameScene.updateMap(cell);
}
}
}
public static class RockArmor extends ShieldBuff { }
public static final String HITS = "hits";
private static final String ABILITY_COOLDOWN = "ability_cooldown";
private static final String LAST_ABILITY_WAS_ROCKFALL = "last_ability_was_rockfall";
private static final String ROCK_FROM_POS = "rock_from_pos";
private static final String ROCK_TO_POS = "rock_to_pos";
private static final String SAPPER_ID = "sapper_id";
private static final String SAPPER_SPAWNS = "sapper_spawns";
@Override
public void storeInBundle(Bundle bundle) {
super.storeInBundle(bundle);
bundle.put(HITS, hits);
bundle.put(ABILITY_COOLDOWN, abilityCooldown);
bundle.put(LAST_ABILITY_WAS_ROCKFALL, lastAbilityWasRockfall);
if (throwingRocksFromPos != null) {
bundle.put(ROCK_FROM_POS, throwingRocksFromPos);
}
bundle.put(ROCK_TO_POS, throwingRockToPos);
bundle.put(SAPPER_ID, sapperID);
if (sapperSpawns != null){
bundle.put(SAPPER_SPAWNS, sapperSpawns);
}
}
@Override
public void restoreFromBundle(Bundle bundle) {
super.restoreFromBundle(bundle);
hits = bundle.getInt(HITS);
abilityCooldown = bundle.getInt(ABILITY_COOLDOWN);
lastAbilityWasRockfall = bundle.getBoolean(LAST_ABILITY_WAS_ROCKFALL);
if (bundle.contains(ROCK_FROM_POS)) {
throwingRocksFromPos = bundle.getIntArray(ROCK_FROM_POS);
}
throwingRockToPos = bundle.getInt(ROCK_TO_POS);
sapperID = bundle.getInt(SAPPER_ID);
if (bundle.contains(SAPPER_SPAWNS)) {
sapperSpawns = bundle.getIntArray(SAPPER_SPAWNS);
}
if (hits >= 3){
BossHealthBar.assignBoss(this);
}
}
}
| 412 | 0.972582 | 1 | 0.972582 | game-dev | MEDIA | 0.990403 | game-dev | 0.992456 | 1 | 0.992456 |
DragonBones/Tools | 9,363 | src/remote.ts | import * as http from "http";
import * as object from "./common/object";
import * as nodeUtils from "./common/nodeUtils";
import { Code, Gate } from "./common/server";
import * as dbft from "./format/dragonBonesFormat";
import * as spft from "./format/spineFormat";
import fromSpine from "./action/fromSpine";
import toFormat from "./action/toFormat";
import toNew from "./action/toNew";
import toBinary from "./action/toBinary";
import toWeb from "./action/toWeb";
// import toSpine from "./action/toSpine";
import format from "./action/formatFormat";
type Input = {
from: "spine" | "cocos";
to: "binary" | "new" | "v45" | "player" | "viewer" | "spine";
data: string; // DragonBones JSON string | spine JSON string { data: string, textureAtlas: string }
compress?: boolean;
forPro?: boolean;
textureAtlases?: string[]; // PNG Base64 string.
config?: any; // { web: web config, spine: spine verison }
};
type FormatType = "string" | "base64" | "binary";
class Output {
public format: FormatType;
public name: string;
public suffix: string;
public data: any;
public constructor(data: any, name: string = "", suffix: string = "", format: FormatType = "string") {
this.data = data;
this.format = format;
this.name = name;
this.suffix = suffix;
}
}
const gate = new Gate();
gate.actions["/convert"] = (request, response) => {
let jsonString = "";
request.addListener("data", (data: any) => {
jsonString += data;
});
request.addListener("end", () => {
request.removeAllListeners();
let input: Input;
try {
input = JSON.parse(jsonString);
}
catch (error) {
gate.responseEnd(response, Code.JSONError, Code[Code.JSONError], jsonString);
return;
}
try {
if (input.from) {
switch (input.from) {
case "spine": {
let spineInput: { name: string, data: string, textureAtlas: string } | null = null;
try {
spineInput = JSON.parse(input.data);
}
catch (error) {
}
if (!spineInput) {
gate.responseEnd(response, Code.DataError, Code[Code.DataError]);
return;
}
const spine = new spft.Spine();
object.copyObjectFrom(JSON.parse(spineInput.data), spine, spft.copyConfig);
const result = fromSpine({ name: spineInput.name, data: spine, textureAtlas: spineInput.textureAtlas }, true);
format(result);
object.compress(result, dbft.compressConfig);
gate.responseEnd(response, Code.Success, Code[Code.Success], result);
// TODO
break;
}
case "cocos": {
break;
}
}
}
else if (input.to) {
let dragonBonesData: dbft.DragonBones | null = null;
try {
dragonBonesData = toFormat(
input.data,
() => {
return [];
}
);
}
catch (error) {
}
if (!dragonBonesData) {
gate.responseEnd(response, Code.DataError, Code[Code.DataError], input.data);
return;
}
const toOutput: Output[] = [];
switch (input.to) {
case "binary": {
toNew(dragonBonesData, true);
format(dragonBonesData);
const result = new Buffer(toBinary(dragonBonesData)).toString("base64");
toOutput.push(
new Output(
result,
dragonBonesData.name,
"_ske.dbbin",
"base64"
)
);
break;
}
case "new": {
toNew(dragonBonesData, false);
format(dragonBonesData);
if (input.compress !== false) {
object.compress(dragonBonesData, dbft.compressConfig);
}
const result = JSON.stringify(dragonBonesData);
toOutput.push(
new Output(
result,
dragonBonesData.name,
"_ske.json",
"string"
)
);
break;
}
case "player":
case "viewer": {
toNew(dragonBonesData, true);
format(dragonBonesData);
const result = toWeb(
{
data: new Buffer(toBinary(dragonBonesData)),
textureAtlases: input.textureAtlases ? input.textureAtlases.map((v) => {
return new Buffer(v, "base64");
}) : [],
config: input.config
},
input.to === "player"
);
toOutput.push(
new Output(
result,
dragonBonesData.name,
".html",
"string"
)
);
break;
}
case "spine": {
// toNew(dragonBonesData, true);
// format(dragonBonesData);
// const result = toSpine(dragonBonesData, input.config, false);
// for (const spine of result.spines) {
// if (input.compress !== false) {
// object.compress(spine, spft.compressConfig);
// }
// toOutput.push(
// new Output(
// JSON.stringify(spine),
// result.spines.length > 1 ? `${dragonBonesData.name}_${spine.skeleton.name}` : dragonBonesData.name,
// ".json",
// "string"
// )
// );
// }
// if (result.textureAtlas) {
// toOutput.push(
// new Output(
// result.textureAtlas,
// dragonBonesData.name,
// ".atlas",
// "string"
// )
// );
// }
break;
}
default:
gate.responseEnd(response, Code.DataError, Code[Code.DataError], input.to);
return;
}
gate.responseEnd(response, Code.Success, Code[Code.Success], toOutput);
}
}
catch (error) {
gate.responseEnd(response, Code.ActionError, Code[Code.ActionError]);
return;
}
});
};
function execute(): void {
if (process.argv.length > 1) {
const port = Number(process.argv[2]);
if (port === port && port >= 0 && port <= 65535) {
const url = `http://${nodeUtils.findIP()}:${port}/dragonbones`;
gate.actions["/working_directory"] = (request, response) => {
// let jsonString = "";
request.addListener("data", () => {
// jsonString += data;
});
request.addListener("end", () => {
request.removeAllListeners();
gate.responseEnd(response, Code.Success, Code[Code.Success], { url: url, workingDirectory: __dirname });
});
};
gate.start("dragonbones", port, "/dragonbones");
console.log(url);
return;
}
}
const portServer = http.createServer();
portServer.listen(0, () => {
const port = (portServer.address() as any).port;
portServer.close();
gate.start("dragonbones", port, "/dragonbones");
console.log(`http://${nodeUtils.findIP()}:${port}/dragonbones`);
});
}
execute();
| 412 | 0.836871 | 1 | 0.836871 | game-dev | MEDIA | 0.306117 | game-dev | 0.898903 | 1 | 0.898903 |
MoeMod/CSMoE | 42,435 | dlls/doors.cpp | #include <stdlib.h>
#include <string.h>
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "player.h"
#include "doors.h"
#include "game.h"
#include "globals.h"
#include "subs.h"
#include "sound.h"
#include "buttons.h"
#include "decals.h"
#include "gamemode/mods.h"
#include "bot_include.h"
namespace sv {
/*
* Globals initialization
*/
const char* CRotDoor::pSoundsWood[] =
{
"debris/wood1.wav",
"debris/wood2.wav",
"debris/wood3.wav"
};
const char* CRotDoor::pSoundsFlesh[] =
{
"debris/flesh1.wav",
"debris/flesh2.wav",
"debris/flesh3.wav",
"debris/flesh5.wav",
"debris/flesh6.wav",
"debris/flesh7.wav"
};
const char* CRotDoor::pSoundsMetal[] =
{
"debris/metal1.wav",
"debris/metal2.wav",
"debris/metal3.wav"
};
const char* CRotDoor::pSoundsConcrete[] =
{
"debris/concrete1.wav",
"debris/concrete2.wav",
"debris/concrete3.wav"
};
const char* CRotDoor::pSoundsGlass[] =
{
"debris/glass1.wav",
"debris/glass2.wav",
"debris/glass3.wav"
};
TYPEDESCRIPTION CBaseDoor::m_SaveData[] =
{
DEFINE_FIELD (CBaseDoor, m_bHealthValue, FIELD_CHARACTER),
DEFINE_FIELD (CBaseDoor, m_bMoveSnd, FIELD_CHARACTER),
DEFINE_FIELD (CBaseDoor, m_bStopSnd, FIELD_CHARACTER),
DEFINE_FIELD (CBaseDoor, m_bLockedSound, FIELD_CHARACTER),
DEFINE_FIELD (CBaseDoor, m_bLockedSentence, FIELD_CHARACTER),
DEFINE_FIELD (CBaseDoor, m_bUnlockedSound, FIELD_CHARACTER),
DEFINE_FIELD (CBaseDoor, m_bUnlockedSentence, FIELD_CHARACTER),
};
TYPEDESCRIPTION CMomentaryDoor::m_SaveData[] =
{
DEFINE_FIELD (CMomentaryDoor, m_bMoveSnd, FIELD_CHARACTER),
};
IMPLEMENT_SAVERESTORE (CBaseDoor, CBaseToggle);
// play door or button locked or unlocked sounds.
// pass in pointer to valid locksound struct.
// if flocked is true, play 'door is locked' sound,
// otherwise play 'door is unlocked' sound
// NOTE: this routine is shared by doors and buttons
void PlayLockSounds(entvars_t *pev, locksound_t *pls, int flocked, int fbutton)
{
// LOCKED SOUND
// CONSIDER: consolidate the locksound_t struct (all entries are duplicates for lock/unlock)
// CONSIDER: and condense this code.
duration_t flsoundwait;
if (fbutton)
flsoundwait = BUTTON_SOUNDWAIT;
else
flsoundwait = DOOR_SOUNDWAIT;
if (flocked) {
int fplaysound = (pls->sLockedSound && gpGlobals->time > pls->flwaitSound);
int fplaysentence = (pls->sLockedSentence && !pls->bEOFLocked && gpGlobals->time > pls->flwaitSentence);
float fvol;
if (fplaysound && fplaysentence)
fvol = 0.25f;
else
fvol = 1.0f;
// if there is a locked sound, and we've debounced, play sound
if (fplaysound) {
// play 'door locked' sound
EMIT_SOUND(ENT(pev), CHAN_ITEM, (char *) STRING (pls->sLockedSound), fvol, ATTN_NORM);
pls->flwaitSound = gpGlobals->time + flsoundwait;
}
// if there is a sentence, we've not played all in list, and we've debounced, play sound
if (fplaysentence) {
// play next 'door locked' sentence in group
int iprev = pls->iLockedSentence;
pls->iLockedSentence = SENTENCEG_PlaySequentialSz(ENT(pev), STRING (pls->sLockedSentence), 0.85, ATTN_NORM,
0, 100, pls->iLockedSentence, FALSE);
pls->iUnlockedSentence = 0;
// make sure we don't keep calling last sentence in list
pls->bEOFLocked = (iprev == pls->iLockedSentence);
pls->flwaitSentence = gpGlobals->time + DOOR_SENTENCEWAIT;
}
} else {
// UNLOCKED SOUND
int fplaysound = (pls->sUnlockedSound && gpGlobals->time > pls->flwaitSound);
int fplaysentence = (pls->sUnlockedSentence && !pls->bEOFUnlocked && gpGlobals->time > pls->flwaitSentence);
float fvol;
// if playing both sentence and sound, lower sound volume so we hear sentence
if (fplaysound && fplaysentence)
fvol = 0.25f;
else
fvol = 1.0f;
// play 'door unlocked' sound if set
if (fplaysound) {
EMIT_SOUND(ENT(pev), CHAN_ITEM, (char *) STRING (pls->sUnlockedSound), fvol, ATTN_NORM);
pls->flwaitSound = gpGlobals->time + flsoundwait;
}
// play next 'door unlocked' sentence in group
if (fplaysentence) {
int iprev = pls->iUnlockedSentence;
pls->iUnlockedSentence = SENTENCEG_PlaySequentialSz(ENT(pev), STRING (pls->sUnlockedSentence), 0.85,
ATTN_NORM, 0, 100, pls->iUnlockedSentence, FALSE);
pls->iLockedSentence = 0;
// make sure we don't keep calling last sentence in list
pls->bEOFUnlocked = (iprev == pls->iUnlockedSentence);
pls->flwaitSentence = gpGlobals->time + DOOR_SENTENCEWAIT;
}
}
}
// Cache user-entity-field values until spawn is called.
void CBaseDoor::KeyValue(KeyValueData *pkvd)
{
//skin is used for content type
if (FStrEq(pkvd->szKeyName, "skin")) {
pev->skin = (int) Q_atof(pkvd->szValue);
pkvd->fHandled = TRUE;
} else if (FStrEq(pkvd->szKeyName, "movesnd")) {
m_bMoveSnd = (int) Q_atof(pkvd->szValue);
pkvd->fHandled = TRUE;
} else if (FStrEq(pkvd->szKeyName, "stopsnd")) {
m_bStopSnd = (int) Q_atof(pkvd->szValue);
pkvd->fHandled = TRUE;
} else if (FStrEq(pkvd->szKeyName, "healthvalue")) {
m_bHealthValue = (int) Q_atof(pkvd->szValue);
pkvd->fHandled = TRUE;
} else if (FStrEq(pkvd->szKeyName, "locked_sound")) {
m_bLockedSound = (int) Q_atof(pkvd->szValue);
pkvd->fHandled = TRUE;
} else if (FStrEq(pkvd->szKeyName, "locked_sentence")) {
m_bLockedSentence = (int) Q_atof(pkvd->szValue);
pkvd->fHandled = TRUE;
} else if (FStrEq(pkvd->szKeyName, "unlocked_sound")) {
m_bUnlockedSound = (int) Q_atof(pkvd->szValue);
pkvd->fHandled = TRUE;
} else if (FStrEq(pkvd->szKeyName, "unlocked_sentence")) {
m_bUnlockedSentence = (int) Q_atof(pkvd->szValue);
pkvd->fHandled = TRUE;
} else if (FStrEq(pkvd->szKeyName, "WaveHeight")) {
pev->scale = Q_atof(pkvd->szValue) * (1.0 / 8.0);
pkvd->fHandled = TRUE;
} else
CBaseToggle::KeyValue(pkvd);
}
// QUAKED func_door (0 .5 .8) ? START_OPEN x DOOR_DONT_LINK TOGGLE
// if two doors touch, they are assumed to be connected and operate as a unit.
// TOGGLE causes the door to wait in both the start and end states for a trigger event.
// START_OPEN causes the door to move to its destination when spawned, and operate in reverse.
// It is used to temporarily or permanently close off an area when triggered (not usefull for
// touch or takedamage doors).
// "angle" determines the opening direction
// "targetname" if set, no touch field will be spawned and a remote button or trigger field activates the door.
// "health" if set, door must be shot open
// "speed" movement speed (100 default)
// "wait" wait before returning (3 default, -1 = never return)
// "lip" lip remaining at end of move (8 default)
// "dmg" damage to inflict when blocked (2 default)
// "sounds"
// 0) no sound
// 1) stone
// 2) base
// 3) stone chain
// 4) screechy metal
LINK_ENTITY_TO_CLASS (func_door, CBaseDoor);
// func_water - same as a door.
class CFuncWater : public CBaseDoor {};
LINK_ENTITY_TO_CLASS (func_water, CFuncWater);
void CBaseDoor::Spawn()
{
Precache();
SetMovedir(pev);
//normal door
if (pev->skin == 0) {
if (pev->spawnflags & SF_DOOR_PASSABLE)
pev->solid = SOLID_NOT;
else
pev->solid = SOLID_BSP;
} else // special contents
{
pev->solid = SOLID_NOT;
// water is silent for now
pev->spawnflags |= SF_DOOR_SILENT;
}
pev->movetype = MOVETYPE_PUSH;
UTIL_SetOrigin(pev, pev->origin);
SET_MODEL(ENT(pev), STRING (pev->model));
if (pev->speed == 0)
pev->speed = 100;
m_vecPosition1 = pev->origin;
// Subtract 2 from size because the engine expands bboxes by 1 in all directions making the size too big
m_vecPosition2 = m_vecPosition1 + (pev->movedir * (fabs((float) (pev->movedir.x * (pev->size.x - 2))) +
fabs((float) (pev->movedir.y * (pev->size.y - 2))) +
fabs((float) (pev->movedir.z * (pev->size.z - 2))) - m_flLip));
assert (("door start/end positions are equal" && (m_vecPosition1 != m_vecPosition2)));
if (pev->spawnflags & SF_DOOR_START_OPEN) {
// swap pos1 and pos2, put door at pos2
UTIL_SetOrigin(pev, m_vecPosition2);
m_vecPosition2 = m_vecPosition1;
m_vecPosition1 = pev->origin;
}
m_toggle_state = TS_AT_BOTTOM;
// if the door is flagged for USE button activation only, use NULL touch function
if (pev->spawnflags & SF_DOOR_USE_ONLY) {
SetTouch(NULL);
} else {
// touchable button
SetTouch(&CBaseDoor::DoorTouch);
}
m_lastBlockedTimestamp = {};
}
void CBaseDoor::Restart()
{
SetMovedir(pev);
m_toggle_state = TS_AT_BOTTOM;
DoorGoDown();
if (pev->spawnflags & SF_DOOR_USE_ONLY)
SetTouch(NULL);
else
SetTouch(&CBaseDoor::DoorTouch);
}
void CBaseDoor::SetToggleState(int state)
{
if (state == TS_AT_TOP)
UTIL_SetOrigin(pev, m_vecPosition2);
else
UTIL_SetOrigin(pev, m_vecPosition1);
}
#define noiseMoving noise1
#define noiseArrived noise2
void CBaseDoor::Precache()
{
const char *pszSound = nullptr;
// set the door's "in-motion" sound
switch (m_bMoveSnd) {
case 0:
pev->noiseMoving = ALLOC_STRING("common/null.wav");
break;
case 1:
PRECACHE_SOUND("doors/doormove1.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove1.wav");
break;
case 2:
PRECACHE_SOUND("doors/doormove2.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove2.wav");
break;
case 3:
PRECACHE_SOUND("doors/doormove3.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove3.wav");
break;
case 4:
PRECACHE_SOUND("doors/doormove4.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove4.wav");
break;
case 5:
PRECACHE_SOUND("doors/doormove5.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove5.wav");
break;
case 6:
PRECACHE_SOUND("doors/doormove6.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove6.wav");
break;
case 7:
PRECACHE_SOUND("doors/doormove7.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove7.wav");
break;
case 8:
PRECACHE_SOUND("doors/doormove8.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove8.wav");
break;
case 9:
PRECACHE_SOUND("doors/doormove9.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove9.wav");
break;
case 10:
PRECACHE_SOUND("doors/doormove10.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove10.wav");
break;
default:
pev->noiseMoving = ALLOC_STRING("common/null.wav");
break;
}
// set the door's 'reached destination' stop sound
switch (m_bStopSnd) {
case 0:
pev->noiseArrived = ALLOC_STRING("common/null.wav");
break;
case 1:
PRECACHE_SOUND("doors/doorstop1.wav");
pev->noiseArrived = ALLOC_STRING("doors/doorstop1.wav");
break;
case 2:
PRECACHE_SOUND("doors/doorstop2.wav");
pev->noiseArrived = ALLOC_STRING("doors/doorstop2.wav");
break;
case 3:
PRECACHE_SOUND("doors/doorstop3.wav");
pev->noiseArrived = ALLOC_STRING("doors/doorstop3.wav");
break;
case 4:
PRECACHE_SOUND("doors/doorstop4.wav");
pev->noiseArrived = ALLOC_STRING("doors/doorstop4.wav");
break;
case 5:
PRECACHE_SOUND("doors/doorstop5.wav");
pev->noiseArrived = ALLOC_STRING("doors/doorstop5.wav");
break;
case 6:
PRECACHE_SOUND("doors/doorstop6.wav");
pev->noiseArrived = ALLOC_STRING("doors/doorstop6.wav");
break;
case 7:
PRECACHE_SOUND("doors/doorstop7.wav");
pev->noiseArrived = ALLOC_STRING("doors/doorstop7.wav");
break;
case 8:
PRECACHE_SOUND("doors/doorstop8.wav");
pev->noiseArrived = ALLOC_STRING("doors/doorstop8.wav");
break;
default:
pev->noiseArrived = ALLOC_STRING("common/null.wav");
break;
}
// get door button sounds, for doors which are directly 'touched' to open
if (m_bLockedSound) {
pszSound = ButtonSound((int) m_bLockedSound);
PRECACHE_SOUND(pszSound);
m_ls.sLockedSound = ALLOC_STRING(pszSound);
}
if (m_bUnlockedSound) {
pszSound = ButtonSound((int) m_bUnlockedSound);
PRECACHE_SOUND(pszSound);
m_ls.sUnlockedSound = ALLOC_STRING(pszSound);
}
// get sentence group names, for doors which are directly 'touched' to open
switch (m_bLockedSentence) {
case 1:
m_ls.sLockedSentence = ALLOC_STRING("NA");
break; // access denied
case 2:
m_ls.sLockedSentence = ALLOC_STRING("ND");
break; // security lockout
case 3:
m_ls.sLockedSentence = ALLOC_STRING("NF");
break; // blast door
case 4:
m_ls.sLockedSentence = ALLOC_STRING("NFIRE");
break; // fire door
case 5:
m_ls.sLockedSentence = ALLOC_STRING("NCHEM");
break; // chemical door
case 6:
m_ls.sLockedSentence = ALLOC_STRING("NRAD");
break; // radiation door
case 7:
m_ls.sLockedSentence = ALLOC_STRING("NCON");
break; // gen containment
case 8:
m_ls.sLockedSentence = ALLOC_STRING("NH");
break; // maintenance door
case 9:
m_ls.sLockedSentence = ALLOC_STRING("NG");
break; // broken door
default:
m_ls.sLockedSentence = 0;
break;
}
switch (m_bUnlockedSentence) {
case 1:
m_ls.sUnlockedSentence = ALLOC_STRING("EA");
break; // access granted
case 2:
m_ls.sUnlockedSentence = ALLOC_STRING("ED");
break; // security door
case 3:
m_ls.sUnlockedSentence = ALLOC_STRING("EF");
break; // blast door
case 4:
m_ls.sUnlockedSentence = ALLOC_STRING("EFIRE");
break; // fire door
case 5:
m_ls.sUnlockedSentence = ALLOC_STRING("ECHEM");
break; // chemical door
case 6:
m_ls.sUnlockedSentence = ALLOC_STRING("ERAD");
break; // radiation door
case 7:
m_ls.sUnlockedSentence = ALLOC_STRING("ECON");
break; // gen containment
case 8:
m_ls.sUnlockedSentence = ALLOC_STRING("EH");
break; // maintenance door
default:
m_ls.sUnlockedSentence = 0;
break;
}
}
// Doors not tied to anything (e.g. button, another door) can be touched, to make them activate.
void CBaseDoor::DoorTouch(CBaseEntity *pOther)
{
entvars_t *pevToucher = pOther->pev;
// Ignore touches by dead players
if (pevToucher->deadflag != DEAD_NO)
return;
// If door has master, and it's not ready to trigger,
// play 'locked' sound
if (!FStringNull(m_sMaster) && !UTIL_IsMasterTriggered(m_sMaster, pOther)) {
PlayLockSounds(pev, &m_ls, TRUE, FALSE);
}
// If door is somebody's target, then touching does nothing.
// You have to activate the owner (e.g. button).
if (!FStringNull(pev->targetname)) {
// play locked sound
PlayLockSounds(pev, &m_ls, TRUE, FALSE);
return;
}
// remember who activated the door
m_hActivator = pOther;
if (DoorActivate()) {
// Temporarily disable the touch function, until movement is finished.
SetTouch(NULL);
}
}
// Used by SUB_UseTargets, when a door is the target of a button.
void CBaseDoor::Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value)
{
m_hActivator = pActivator;
// if not ready to be used, ignore "use" command.
if (m_toggle_state == TS_AT_BOTTOM || ((pev->spawnflags & SF_DOOR_NO_AUTO_RETURN) && m_toggle_state == TS_AT_TOP)) {
DoorActivate();
}
}
// Causes the door to "do its thing", i.e. start moving, and cascade activation.
int CBaseDoor::DoorActivate()
{
if (!UTIL_IsMasterTriggered(m_sMaster, m_hActivator))
return 0;
// door should close
if ((pev->spawnflags & SF_DOOR_NO_AUTO_RETURN) && m_toggle_state == TS_AT_TOP) {
DoorGoDown();
} else // door should open
{
// give health if player opened the door (medikit)
if (m_hActivator != nullptr && m_hActivator->IsPlayer()) {
// VARS(m_eoActivator)->health += m_bHealthValue;
m_hActivator->TakeHealth(m_bHealthValue, DMG_GENERIC);
}
// play door unlock sounds
PlayLockSounds(pev, &m_ls, FALSE, FALSE);
DoorGoUp();
}
return 1;
}
// Starts the door going to its "up" position (simply ToggleData->vecPosition2).
void CBaseDoor::DoorGoUp()
{
entvars_t *pevActivator;
bool isReversing = (m_toggle_state == TS_GOING_DOWN);
// It could be going-down, if blocked.
#ifdef DOOR_ASSERT
assert (m_toggle_state == TS_AT_BOTTOM || m_toggle_state == TS_GOING_DOWN);
#else
if (m_toggle_state != TS_AT_BOTTOM && m_toggle_state != TS_GOING_DOWN)
return;
#endif
// emit door moving and stop sounds on CHAN_STATIC so that the multicast doesn't
// filter them out and leave a client stuck with looping door sounds!
if (!isReversing) {
if (!(pev->spawnflags & SF_DOOR_SILENT)) {
if (m_toggle_state != TS_GOING_UP && m_toggle_state != TS_GOING_DOWN) {
EMIT_SOUND(ENT(pev), CHAN_STATIC, (char *) STRING (pev->noiseMoving), VOL_NORM, ATTN_NORM);
}
if (TheBots != NULL) {
TheBots->OnEvent(EVENT_DOOR, m_hActivator);
}
}
}
m_toggle_state = TS_GOING_UP;
SetMoveDone (&CBaseDoor::DoorHitTop);
// BUGBUG: Triggered doors don't work with this yet
if (FClassnameIs(pev, "func_door_rotating")) {
float sign = 1.0;
if (m_hActivator != nullptr) {
pevActivator = m_hActivator->pev;
// Y axis rotation, move away from the player
if (!(pev->spawnflags & SF_DOOR_ONEWAY) && pev->movedir.y) {
Vector2D toActivator = pevActivator->origin.Make2D();
float loX = pev->mins.x + pev->origin.x;
float loY = pev->mins.y + pev->origin.y;
float hiX = pev->maxs.x + pev->origin.x;
float hiY = pev->maxs.y + pev->origin.y;
float momentArmX = toActivator.x - pev->origin.x;
float momentArmY = toActivator.y - pev->origin.y;
if (loX > toActivator.x) {
if (toActivator.y < loY) {
if (abs((int) momentArmY) > abs((int) momentArmX))
sign = (momentArmY < 0) ? 1 : -1;
else
sign = (momentArmX > 0) ? 1 : -1;
} else if (toActivator.y > hiY) {
if (abs((int) momentArmY) > abs((int) momentArmX))
sign = (momentArmY < 0) ? 1 : -1;
else
sign = (momentArmX < 0) ? 1 : -1;
} else
sign = (momentArmY < 0) ? 1 : -1;
} else {
if (toActivator.x <= hiX) {
if (toActivator.y < loY)
sign = (momentArmX > 0) ? 1 : -1;
else if (toActivator.y > hiY)
sign = (momentArmX < 0) ? 1 : -1;
} else if (toActivator.y < loY) {
if (abs((int) momentArmY) > abs((int) momentArmX))
sign = (momentArmY > 0) ? 1 : -1;
else
sign = (momentArmX > 0) ? 1 : -1;
} else if (toActivator.y > hiY) {
if (abs((int) momentArmY) > abs((int) momentArmX))
sign = (momentArmY > 0) ? 1 : -1;
else
sign = (momentArmX < 0) ? 1 : -1;
} else
sign = (momentArmY > 0) ? 1 : -1;
}
if (isReversing) {
sign = -sign;
}
}
}
AngularMove(m_vecAngle2 * sign, pev->speed);
} else
LinearMove(m_vecPosition2, pev->speed);
}
// The door has reached the "up" position. Either go back down, or wait for another activation.
void CBaseDoor::DoorHitTop()
{
if (!(pev->spawnflags & SF_DOOR_SILENT)) {
STOP_SOUND(ENT(pev), CHAN_STATIC, (char *) STRING (pev->noiseMoving));
EMIT_SOUND(ENT(pev), CHAN_STATIC, (char *) STRING (pev->noiseArrived), VOL_NORM, ATTN_NORM);
}
assert (m_toggle_state == TS_GOING_UP);
m_toggle_state = TS_AT_TOP;
// toggle-doors don't come down automatically, they wait for refire.
if (pev->spawnflags & SF_DOOR_NO_AUTO_RETURN) {
// Re-instate touch method, movement is complete
if (!(pev->spawnflags & SF_DOOR_USE_ONLY)) {
SetTouch(&CBaseDoor::DoorTouch);
}
} else {
// In flWait seconds, DoorGoDown will fire, unless wait is -1, then door stays open
pev->nextthink = pev->ltime + m_flWait;
SetThink(&CBaseDoor::DoorGoDown);
if (m_flWait == -1s) {
pev->nextthink = {};
}
}
// Fire the close target (if startopen is set, then "top" is closed) - netname is the close target
if (!FStringNull(pev->netname) && (pev->spawnflags & SF_DOOR_START_OPEN)) {
FireTargets(STRING (pev->netname), m_hActivator, this, USE_TOGGLE, 0);
}
// this isn't finished
SUB_UseTargets(m_hActivator, USE_TOGGLE, 0);
}
// Starts the door going to its "down" position (simply ToggleData->vecPosition1).
void CBaseDoor::DoorGoDown()
{
bool isReversing = (m_toggle_state == TS_GOING_UP);
if (!isReversing) {
if (!(pev->spawnflags & SF_DOOR_SILENT)) {
if (m_toggle_state != TS_GOING_UP && m_toggle_state != TS_GOING_DOWN) {
EMIT_SOUND(ENT(pev), CHAN_STATIC, (char *) STRING (pev->noiseMoving), VOL_NORM, ATTN_NORM);
}
if (TheBots != NULL) {
TheBots->OnEvent(EVENT_DOOR, m_hActivator);
}
}
}
#ifdef DOOR_ASSERT
assert (m_toggle_state == TS_AT_TOP);
#endif // DOOR_ASSERT
m_toggle_state = TS_GOING_DOWN;
SetMoveDone (&CBaseDoor::DoorHitBottom);
//rotating door
if (FClassnameIs(pev, "func_door_rotating")) {
AngularMove(m_vecAngle1, pev->speed);
} else
LinearMove(m_vecPosition1, pev->speed);
}
// The door has reached the "down" position. Back to quiescence.
void CBaseDoor::DoorHitBottom()
{
if (!(pev->spawnflags & SF_DOOR_SILENT)) {
STOP_SOUND(ENT(pev), CHAN_STATIC, (char *) STRING (pev->noiseMoving));
EMIT_SOUND(ENT(pev), CHAN_STATIC, (char *) STRING (pev->noiseArrived), VOL_NORM, ATTN_NORM);
}
assert (m_toggle_state == TS_GOING_DOWN);
m_toggle_state = TS_AT_BOTTOM;
// Re-instate touch method, cycle is complete
if (pev->spawnflags & SF_DOOR_USE_ONLY) {
// use only door
SetTouch(NULL);
} else {
// touchable door
SetTouch(&CBaseDoor::DoorTouch);
}
// this isn't finished
SUB_UseTargets(m_hActivator, USE_TOGGLE, 0);
// Fire the close target (if startopen is set, then "top" is closed) - netname is the close target
if (!FStringNull(pev->netname) && !(pev->spawnflags & SF_DOOR_START_OPEN)) {
FireTargets(STRING (pev->netname), m_hActivator, this, USE_TOGGLE, 0);
}
}
void CBaseDoor::Blocked(CBaseEntity *pOther)
{
edict_t *pentTarget = NULL;
CBaseDoor *pDoor = NULL;
const duration_t checkBlockedInterval = 0.25s;
// Hurt the blocker a little.
if (pev->dmg != 0.0f) {
pOther->TakeDamage(pev, pev, pev->dmg, DMG_CRUSH);
}
if (gpGlobals->time - m_lastBlockedTimestamp < checkBlockedInterval) {
return;
}
m_lastBlockedTimestamp = gpGlobals->time;
// if a door has a negative wait, it would never come back if blocked,
// so let it just squash the object to death real fast
if (m_flWait >= 0s) {
if (m_toggle_state == TS_GOING_DOWN) {
DoorGoUp();
} else {
DoorGoDown();
}
}
// Block all door pieces with the same targetname here.
if (!FStringNull(pev->targetname)) {
while (true) {
pentTarget = FIND_ENTITY_BY_TARGETNAME(pentTarget, STRING (pev->targetname));
if (VARS(pentTarget) != pev) {
if (FNullEnt(pentTarget))
break;
if (FClassnameIs(pentTarget, "func_door") || FClassnameIs(pentTarget, "func_door_rotating")) {
pDoor = GetClassPtr<CBaseDoor>(VARS(pentTarget));
if (pDoor->m_flWait >= 0s) {
if (pDoor->pev->velocity == pev->velocity && pDoor->pev->avelocity == pev->velocity) {
// this is the most hacked, evil, bastardized thing I've ever seen. kjb
if (FClassnameIs(pentTarget, "func_door")) {
// set origin to realign normal doors
pDoor->pev->origin = pev->origin;
// stop!
pDoor->pev->velocity = g_vecZero;
} else {
// set angles to realign rotating doors
pDoor->pev->angles = pev->angles;
pDoor->pev->avelocity = g_vecZero;
}
}
if (!(pev->spawnflags & SF_DOOR_SILENT)) {
STOP_SOUND(ENT(pev), CHAN_STATIC, (char *) STRING (pev->noiseMoving));
}
if (pDoor->m_toggle_state == TS_GOING_DOWN)
pDoor->DoorGoUp();
else
pDoor->DoorGoDown();
}
}
}
}
}
}
// QUAKED FuncRotDoorSpawn (0 .5 .8) ? START_OPEN REVERSE
// DOOR_DONT_LINK TOGGLE X_AXIS Y_AXIS
// if two doors touch, they are assumed to be connected and operate as a unit.
// TOGGLE causes the door to wait in both the start and end states for a trigger event.
// START_OPEN causes the door to move to its destination when spawned,
// and operate in reverse. It is used to temporarily or permanently
// close off an area when triggered (not usefull for touch or
// takedamage doors).
// You need to have an origin brush as part of this entity. The
// center of that brush will be
// the point around which it is rotated. It will rotate around the Z
// axis by default. You can
// check either the X_AXIS or Y_AXIS box to change that.
// "distance" is how many degrees the door will be rotated.
// "speed" determines how fast the door moves; default value is 100.
// REVERSE will cause the door to rotate in the opposite direction.
// "angle" determines the opening direction
// "targetname" if set, no touch field will be spawned and a remote button or trigger field activates the door.
// "health" if set, door must be shot open
// "speed" movement speed (100 default)
// "wait" wait before returning (3 default, -1 = never return)
// "dmg" damage to inflict when blocked (2 default)
// "sounds"
// 0) no sound
// 1) stone
// 2) base
// 3) stone chain
// 4) screechy metal
LINK_ENTITY_TO_CLASS (func_door_rotating, CRotDoor);
void CRotDoor::Restart()
{
pev->solid = SOLID_BSP;
pev->movetype = MOVETYPE_PUSH;
pev->deadflag = DEAD_NO;
if (pev->spawnflags & SF_BREAK_TRIGGER_ONLY)
pev->takedamage = DAMAGE_NO;
else
pev->takedamage = DAMAGE_YES;
pev->health = m_flHealth;
pev->effects &= ~EF_NODRAW;
CBaseToggle::AxisDir(pev);
if (pev->spawnflags & SF_DOOR_ROTATE_BACKWARDS) {
pev->movedir = pev->movedir * -1;
}
if (pev->speed == 0)
pev->speed = 100;
if (pev->spawnflags & SF_DOOR_START_OPEN) {
pev->angles = m_vecAngle1;
pev->movedir = pev->movedir * -1;
}
m_toggle_state = TS_AT_BOTTOM;
DoorGoDown();
}
void CRotDoor::Spawn()
{
m_Material = matWood;
Precache();
if (pev->spawnflags & SF_BREAK_TRIGGER_ONLY)
pev->takedamage = DAMAGE_NO;
else
pev->takedamage = DAMAGE_YES;
float flHealth = 1000.0f;
if (g_pModRunning->DamageTrack() == DT_ZB)
flHealth *= 10.0f;
pev->health = flHealth;
m_flHealth = flHealth;
pev->solid = SOLID_BSP;
// set the axis of rotation
CBaseToggle::AxisDir(pev);
// check for clockwise rotation
if (pev->spawnflags & SF_DOOR_ROTATE_BACKWARDS) {
pev->movedir = pev->movedir * -1;
}
//m_flWait = 2; who the hell did this? (sjb)
m_vecAngle1 = pev->angles;
m_vecAngle2 = pev->angles + pev->movedir * m_flMoveDistance;
assert (("rotating door start/end positions are equal" && (m_vecAngle1 != m_vecAngle2)));
if (pev->spawnflags & SF_DOOR_PASSABLE)
pev->solid = SOLID_NOT;
else
pev->solid = SOLID_BSP;
pev->movetype = MOVETYPE_PUSH;
UTIL_SetOrigin(pev, pev->origin);
SET_MODEL(ENT(pev), STRING (pev->model));
if (pev->speed == 0)
pev->speed = 100;
// DOOR_START_OPEN is to allow an entity to be lighted in the closed position
// but spawn in the open position
if (pev->spawnflags & SF_DOOR_START_OPEN) {
// swap pos1 and pos2, put door at pos2, invert movement direction
pev->angles = m_vecAngle2;
Vector vecSav = m_vecAngle1;
m_vecAngle2 = m_vecAngle1;
m_vecAngle1 = vecSav;
pev->movedir = pev->movedir * -1;
}
m_toggle_state = TS_AT_BOTTOM;
if (pev->spawnflags & SF_DOOR_USE_ONLY) {
SetTouch(NULL);
} else {
// touchable button
SetTouch(&CRotDoor::DoorTouch);
}
}
void CRotDoor::SetToggleState(int state)
{
if (state == TS_AT_TOP)
pev->angles = m_vecAngle2;
else
pev->angles = m_vecAngle1;
UTIL_SetOrigin(pev, pev->origin);
}
void CRotDoor::Precache()
{
CBaseDoor::Precache();
const char* pGibName = NULL;
switch (m_Material)
{
case matWood:
pGibName = "models/woodgibs.mdl";
PRECACHE_SOUND("debris/bustcrate1.wav");
PRECACHE_SOUND("debris/bustcrate2.wav");
break;
case matFlesh:
pGibName = "models/fleshgibs.mdl";
PRECACHE_SOUND("debris/bustflesh1.wav");
PRECACHE_SOUND("debris/bustflesh2.wav");
break;
case matComputer:
PRECACHE_SOUND("buttons/spark5.wav");
PRECACHE_SOUND("buttons/spark6.wav");
pGibName = "models/computergibs.mdl";
PRECACHE_SOUND("debris/bustmetal1.wav");
PRECACHE_SOUND("debris/bustmetal2.wav");
break;
case matGlass:
case matUnbreakableGlass:
pGibName = "models/glassgibs.mdl";
PRECACHE_SOUND("debris/bustglass1.wav");
PRECACHE_SOUND("debris/bustglass2.wav");
break;
case matMetal:
pGibName = "models/metalplategibs.mdl";
PRECACHE_SOUND("debris/bustmetal1.wav");
PRECACHE_SOUND("debris/bustmetal2.wav");
break;
case matCinderBlock:
pGibName = "models/cindergibs.mdl";
PRECACHE_SOUND("debris/bustconcrete1.wav");
PRECACHE_SOUND("debris/bustconcrete2.wav");
break;
case matRocks:
pGibName = "models/rockgibs.mdl";
PRECACHE_SOUND("debris/bustconcrete1.wav");
PRECACHE_SOUND("debris/bustconcrete2.wav");
break;
case matCeilingTile:
pGibName = "models/ceilinggibs.mdl";
PRECACHE_SOUND("debris/bustceiling.wav");
break;
default:
break;
}
MaterialSoundPrecache(m_Material);
if (m_iszGibModel)
{
pGibName = STRING(m_iszGibModel);
}
if (pGibName != NULL)
{
m_idShard = PRECACHE_MODEL((char*)pGibName);
}
}
void CRotDoor::DamageSound()
{
int pitch;
float fvol;
const char* rgpsz[6];
int i;
int material = m_Material;
if (RANDOM_LONG(0, 2))
pitch = PITCH_NORM;
else
pitch = 95 + RANDOM_LONG(0, 34);
fvol = RANDOM_FLOAT(0.75, 1.0);
if (material == matComputer && RANDOM_LONG(0, 1))
material = matMetal;
switch (material)
{
case matGlass:
case matComputer:
case matUnbreakableGlass:
rgpsz[0] = "debris/glass1.wav";
rgpsz[1] = "debris/glass2.wav";
rgpsz[2] = "debris/glass3.wav";
i = 3;
break;
case matWood:
rgpsz[0] = "debris/wood1.wav";
rgpsz[1] = "debris/wood2.wav";
rgpsz[2] = "debris/wood3.wav";
i = 3;
break;
case matMetal:
rgpsz[0] = "debris/metal1.wav";
rgpsz[1] = "debris/metal3.wav";
rgpsz[2] = "debris/metal2.wav";
i = 2;
break;
case matFlesh:
rgpsz[0] = "debris/flesh1.wav";
rgpsz[1] = "debris/flesh2.wav";
rgpsz[2] = "debris/flesh3.wav";
rgpsz[3] = "debris/flesh5.wav";
rgpsz[4] = "debris/flesh6.wav";
rgpsz[5] = "debris/flesh7.wav";
i = 6;
break;
case matRocks:
case matCinderBlock:
rgpsz[0] = "debris/concrete1.wav";
rgpsz[1] = "debris/concrete2.wav";
rgpsz[2] = "debris/concrete3.wav";
i = 3;
break;
case matCeilingTile:
// UNDONE: no ceiling tile shard sound yet
i = 0;
break;
}
if (i)
{
EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, rgpsz[RANDOM_LONG(0, i - 1)], fvol, ATTN_NORM, 0, pitch);
}
}
const char** CRotDoor::MaterialSoundList(Materials precacheMaterial, int& soundCount)
{
const char** pSoundList = NULL;
switch (precacheMaterial)
{
case matWood:
{
pSoundList = pSoundsWood;
soundCount = ARRAYSIZE(pSoundsWood);
break;
}
case matFlesh:
{
pSoundList = pSoundsFlesh;
soundCount = ARRAYSIZE(pSoundsFlesh);
break;
}
case matGlass:
case matComputer:
case matUnbreakableGlass:
{
pSoundList = pSoundsGlass;
soundCount = ARRAYSIZE(pSoundsGlass);
break;
}
case matMetal:
{
pSoundList = pSoundsMetal;
soundCount = ARRAYSIZE(pSoundsMetal);
break;
}
case matCinderBlock:
case matRocks:
{
pSoundList = pSoundsConcrete;
soundCount = ARRAYSIZE(pSoundsConcrete);
break;
}
case matCeilingTile:
case matNone:
default:
soundCount = 0;
break;
}
return pSoundList;
}
void CRotDoor::MaterialSoundPrecache(Materials precacheMaterial)
{
const char** pSoundList;
int i, soundCount = 0;
pSoundList = MaterialSoundList(precacheMaterial, soundCount);
for (i = 0; i < soundCount; ++i)
{
PRECACHE_SOUND((char*)pSoundList[i]);
}
}
void CRotDoor::MaterialSoundRandom(edict_t* pEdict, Materials soundMaterial, float volume)
{
int soundCount = 0;
const char** pSoundList = MaterialSoundList(soundMaterial, soundCount);
if (soundCount)
{
EMIT_SOUND(pEdict, CHAN_BODY, pSoundList[RANDOM_LONG(0, soundCount - 1)], volume, 1.0);
}
}
BOOL CRotDoor::IsBreakable()
{
return m_Material != matUnbreakableGlass;
}
// Special takedamage for func_door_rotating. Allows us to make
// exceptions that are breakable-specific
// bitsDamageType indicates the type of damage sustained ie: DMG_CRUSH
int CRotDoor::TakeDamage(entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType)
{
Vector vecTemp;
// if Attacker == Inflictor, the attack was a melee or other instant-hit attack.
// (that is, no actual entity projectile was involved in the attack so use the shooter's origin).
if (pevAttacker == pevInflictor)
{
vecTemp = pevInflictor->origin - (pev->absmin + (pev->size * 0.5f));
// if a client hit the breakable with a crowbar, and breakable is crowbar-sensitive, break it now.
if ((pevAttacker->flags & FL_CLIENT) && (pev->spawnflags & SF_BREAK_CROWBAR) && (bitsDamageType & DMG_CLUB))
{
flDamage = pev->health;
}
}
else
{
// an actual missile was involved.
vecTemp = pevInflictor->origin - (pev->absmin + (pev->size * 0.5f));
}
if (!IsBreakable())
return 0;
// Breakables take double damage from the crowbar
if (bitsDamageType & DMG_CLUB)
{
flDamage *= 2.0f;
}
// Boxes / glass / etc. don't take much poison damage, just the impact of the dart - consider that 10%
if (bitsDamageType & DMG_POISON)
{
flDamage *= 0.1f;
}
// this global is still used for glass and other non-monster killables, along with decals.
g_vecAttackDir = vecTemp.Normalize();
// do the damage
pev->health -= flDamage;
#ifdef XASH_DEDICATED
if (CBaseEntity::Instance(pevAttacker)->IsPlayer() && flDamage > 0.0f) {
MESSAGE_BEGIN(MSG_ONE, gmsgHitMsg, NULL, pevAttacker);
WRITE_LONG((long)flDamage);
WRITE_SHORT(ENTINDEX(edict()));
WRITE_BYTE(0);
MESSAGE_END();
}
#endif
if (pev->health <= 0)
{
pev->takedamage = DAMAGE_NO;
pev->deadflag = DEAD_DEAD;
pev->effects = EF_NODRAW;
Die();
if (m_flDelay == 0.0s)
{
m_flDelay = 0.1s;
}
pev->nextthink = pev->ltime + m_flDelay;
return 0;
}
// Make a shard noise each time func breakable is hit.
// Don't play shard noise if cbreakable actually died.
DamageSound();
return 1;
}
void CRotDoor::Die()
{
Vector vecSpot; // shard origin
Vector vecVelocity; // shard velocity
CBaseEntity* pEntity = NULL;
char cFlag = 0;
int pitch;
float fvol;
pev->takedamage = DAMAGE_NO;
pev->deadflag = DEAD_DEAD;
pev->effects = EF_NODRAW;
pitch = 95 + RANDOM_LONG(0, 29);
if (pitch > 97 && pitch < 103)
pitch = 100;
// The more negative pev->health, the louder
// the sound should be.
fvol = RANDOM_FLOAT(0.85, 1.0) + (abs((int)pev->health) / 100.0f);
if (fvol > 1.0f)
fvol = 1.0f;
switch (m_Material)
{
case matGlass:
switch (RANDOM_LONG(0, 1))
{
case 0: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustglass1.wav", fvol, ATTN_NORM, 0, pitch);
break;
case 1: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustglass2.wav", fvol, ATTN_NORM, 0, pitch);
break;
}
cFlag = BREAK_GLASS;
if (TheBots != NULL)
{
TheBots->OnEvent(EVENT_BREAK_GLASS, this);
}
break;
case matWood:
switch (RANDOM_LONG(0, 1))
{
case 0: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustcrate1.wav", fvol, ATTN_NORM, 0, pitch);
break;
case 1: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustcrate2.wav", fvol, ATTN_NORM, 0, pitch);
break;
}
cFlag = BREAK_WOOD;
if (TheBots != NULL)
{
TheBots->OnEvent(EVENT_BREAK_WOOD, this);
}
break;
case matMetal:
case matComputer:
switch (RANDOM_LONG(0, 1))
{
case 0: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustmetal1.wav", fvol, ATTN_NORM, 0, pitch);
break;
case 1: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustmetal2.wav", fvol, ATTN_NORM, 0, pitch);
break;
}
cFlag = BREAK_METAL;
if (TheBots != NULL)
{
TheBots->OnEvent(EVENT_BREAK_METAL, this);
}
break;
case matFlesh:
switch (RANDOM_LONG(0, 1))
{
case 0: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustflesh1.wav", fvol, ATTN_NORM, 0, pitch);
break;
case 1: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustflesh2.wav", fvol, ATTN_NORM, 0, pitch);
break;
}
cFlag = BREAK_FLESH;
if (TheBots != NULL)
{
TheBots->OnEvent(EVENT_BREAK_FLESH, this);
}
break;
case matCinderBlock:
case matRocks:
switch (RANDOM_LONG(0, 1))
{
case 0: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustconcrete1.wav", fvol, ATTN_NORM, 0, pitch);
break;
case 1: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustconcrete2.wav", fvol, ATTN_NORM, 0, pitch);
break;
}
cFlag = BREAK_CONCRETE;
if (TheBots != NULL)
{
TheBots->OnEvent(EVENT_BREAK_CONCRETE, this);
}
break;
case matCeilingTile:
EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustceiling.wav", fvol, ATTN_NORM, 0, pitch);
break;
default:
break;
}
if (m_Explosion == expDirected)
{
vecVelocity = g_vecAttackDir * 200.0f;
}
else
{
vecVelocity.x = 0;
vecVelocity.y = 0;
vecVelocity.z = 0;
}
vecSpot = pev->origin + (pev->mins + pev->maxs) * 0.5;
MESSAGE_BEGIN(MSG_PVS, SVC_TEMPENTITY, vecSpot);
WRITE_BYTE(TE_BREAKMODEL);
WRITE_COORD(vecSpot.x); // position
WRITE_COORD(vecSpot.y);
WRITE_COORD(vecSpot.z);
WRITE_COORD(pev->size.x); // size
WRITE_COORD(pev->size.y);
WRITE_COORD(pev->size.z);
WRITE_COORD(vecVelocity.x); // velocity
WRITE_COORD(vecVelocity.y);
WRITE_COORD(vecVelocity.z);
WRITE_BYTE(10); // randomization
WRITE_SHORT(m_idShard); // model id#
WRITE_BYTE(0); // # of shards, let client decide
WRITE_BYTE(25); // duration, 2.5 seconds
WRITE_BYTE(cFlag); // flags
MESSAGE_END();
float size = pev->size.x;
if (size < pev->size.y)
size = pev->size.y;
if (size < pev->size.z)
size = pev->size.z;
Vector mins = pev->absmin;
Vector maxs = pev->absmax;
mins.z = pev->absmax.z;
maxs.z += 8;
CBaseEntity* pList[256];
int count = UTIL_EntitiesInBox(pList, ARRAYSIZE(pList), mins, maxs, FL_ONGROUND);
if (count)
{
for (int i = 0; i < count; ++i)
{
pList[i]->pev->flags &= ~FL_ONGROUND;
pList[i]->pev->groundentity = NULL;
}
}
pev->solid = SOLID_NOT;
SUB_UseTargets(NULL, USE_TOGGLE, 0);
SetThink(NULL);
pev->nextthink = pev->ltime + 0.1s;
}
int CRotDoor::DamageDecal(int bitsDamageType)
{
if (m_Material == matGlass)
return DECAL_GLASSBREAK1 + RANDOM_LONG(0, 2);
if (m_Material == matUnbreakableGlass)
return DECAL_BPROOF1;
return CBaseEntity::DamageDecal(bitsDamageType);
}
void CRotDoor::KeyValue(KeyValueData* pkvd)
{
// UNDONE_WC: explicitly ignoring these fields, but they shouldn't be in the map file!
if (FStrEq(pkvd->szKeyName, "material"))
{
int i = Q_atoi(pkvd->szValue);
// 0:glass, 1:metal, 2:flesh, 3:wood
if (i < 0 || i >= matLastMaterial)
m_Material = matWood;
else
m_Material = (Materials)i;
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "gibmodel"))
{
m_iszGibModel = ALLOC_STRING(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else
CBaseToggle::KeyValue(pkvd);
}
LINK_ENTITY_TO_CLASS (momentary_door, CMomentaryDoor);
IMPLEMENT_SAVERESTORE (CMomentaryDoor, CBaseToggle);
void CMomentaryDoor::Spawn()
{
SetMovedir(pev);
pev->solid = SOLID_BSP;
pev->movetype = MOVETYPE_PUSH;
UTIL_SetOrigin(pev, pev->origin);
SET_MODEL(ENT(pev), STRING (pev->model));
if (pev->speed == 0)
pev->speed = 100;
if (pev->dmg == 0)
pev->dmg = 2;
m_vecPosition1 = pev->origin;
// Subtract 2 from size because the engine expands bboxes by 1 in all directions making the size too big
m_vecPosition2 = m_vecPosition1 + (pev->movedir * (fabs((float) (pev->movedir.x * (pev->size.x - 2))) +
fabs((float) (pev->movedir.y * (pev->size.y - 2))) +
fabs((float) (pev->movedir.z * (pev->size.z - 2))) - m_flLip));
assert ("door start/end positions are equal" && (m_vecPosition1 != m_vecPosition2));
if (pev->spawnflags & SF_DOOR_START_OPEN) {
// swap pos1 and pos2, put door at pos2
UTIL_SetOrigin(pev, m_vecPosition2);
m_vecPosition2 = m_vecPosition1;
m_vecPosition1 = pev->origin;
}
SetTouch(NULL);
Precache();
}
void CMomentaryDoor::Precache()
{
// set the door's "in-motion" sound
switch (m_bMoveSnd) {
case 0:
pev->noiseMoving = ALLOC_STRING("common/null.wav");
break;
case 1:
PRECACHE_SOUND("doors/doormove1.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove1.wav");
break;
case 2:
PRECACHE_SOUND("doors/doormove2.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove2.wav");
break;
case 3:
PRECACHE_SOUND("doors/doormove3.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove3.wav");
break;
case 4:
PRECACHE_SOUND("doors/doormove4.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove4.wav");
break;
case 5:
PRECACHE_SOUND("doors/doormove5.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove5.wav");
break;
case 6:
PRECACHE_SOUND("doors/doormove6.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove6.wav");
break;
case 7:
PRECACHE_SOUND("doors/doormove7.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove7.wav");
break;
case 8:
PRECACHE_SOUND("doors/doormove8.wav");
pev->noiseMoving = ALLOC_STRING("doors/doormove8.wav");
break;
default:
pev->noiseMoving = ALLOC_STRING("common/null.wav");
break;
}
}
void CMomentaryDoor::KeyValue(KeyValueData *pkvd)
{
if (FStrEq(pkvd->szKeyName, "movesnd")) {
m_bMoveSnd = (int) Q_atof(pkvd->szValue);
pkvd->fHandled = TRUE;
} else if (FStrEq(pkvd->szKeyName, "stopsnd")) {
//m_bStopSnd =(int) Q_atof(pkvd->szValue);
pkvd->fHandled = TRUE;
} else if (FStrEq(pkvd->szKeyName, "healthvalue")) {
//m_bHealthValue = (int)Q_atof(pkvd->szValue);
pkvd->fHandled = TRUE;
} else
CBaseToggle::KeyValue(pkvd);
}
void CMomentaryDoor::Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value)
{
// Momentary buttons will pass down a float in here
if (useType != USE_SET) {
return;
}
if (value > 1.0f)
value = 1.0f;
Vector move = m_vecPosition1 + (value * (m_vecPosition2 - m_vecPosition1));
Vector delta = move - pev->origin;
//float speed = delta.Length() * 10;
// move there in 0.1 sec
float speed = delta.Length() / 0.1f;
if (speed == 0)
return;
// This entity only thinks when it moves, so if it's thinking, it's in the process of moving
// play the sound when it starts moving (not yet thinking)
if (pev->nextthink < pev->ltime || pev->nextthink == time_point_t()) {
EMIT_SOUND(ENT(pev), CHAN_STATIC, (char *) STRING (pev->noiseMoving), VOL_NORM, ATTN_NORM);
}
#if 0
// If we already moving to designated point, return
else if (move == m_vecFinalDest)
{
return;
}
SetMoveDone (&CMomentaryDoor::DoorMoveDone);
#endif
LinearMove(move, speed);
}
}
| 412 | 0.952888 | 1 | 0.952888 | game-dev | MEDIA | 0.855689 | game-dev,audio-video-media | 0.972566 | 1 | 0.972566 |
davewx7/citadel | 1,499 | data/classes/bot_omni.cfg | {
bases: ["bot"],
properties: {
score_land: "def(class game_state game, map play_info, class card card, Loc loc) ->int
get_ai_score_land(card.name).score(game, play_info, card, loc)
",
score_summons: "def(class game_state game, map play_info, class card card, Loc loc) ->int
get_ai_score_summons(card.name).score(game, play_info, card, loc)
",
score_spell: "def(class game_state game, map play_info, class card card, [Loc] targets) ->int
get_ai_score_spell(card.name).score(game, play_info, card, targets)
",
choose_to_wait: "def(class game_state game, class card_base card) ->bool
false
",
get_ai_score_spell: "def(string key) -> class ai_score_spell
query_cache(global_cache(1024), [key],
construct('ai_score_spell', info)
where info = map<- lib.json.get_document_map('data/bot-scores.cfg')[key] or {}
)
",
get_ai_score_summons: "def(string key) -> class ai_score_summons
query_cache(global_cache(1024), [key],
construct('ai_score_summons', info)
where info = map<- lib.json.get_document_map('data/bot-scores.cfg')[key] or {}
)
",
get_ai_score_land: "def(string key) -> class ai_score_land
query_cache(global_cache(1024), [key],
construct('ai_score_land', info)
where info = map<- lib.json.get_document_map('data/bot-scores.cfg')[key] or {}
)
",
deck: "[string] :: [q(King's Rider), 'Mercenary', 'Thunderer', 'Dwarvish Armourer', 'Market', 'Anthem of Battle']*3 + ['Oldric, Lord of the Hold']*2",
},
}
| 412 | 0.625122 | 1 | 0.625122 | game-dev | MEDIA | 0.614668 | game-dev,web-backend | 0.827375 | 1 | 0.827375 |
anegostudios/vssurvivalmod | 10,897 | BlockBehavior/BehaviorUnstableFalling.cs | using System.Collections.Generic;
using Vintagestory.API;
using Vintagestory.API.Common;
using Vintagestory.API.Common.Entities;
using Vintagestory.API.Datastructures;
using Vintagestory.API.MathTools;
using Vintagestory.API.Server;
using Vintagestory.API.Util;
#nullable disable
namespace Vintagestory.GameContent
{
/// <summary>
/// Spawns an EntityBlockFalling when the user places a block that has air underneath it or if a neighbor block is
/// removed and causes air to be underneath it. Also has optional functionality to prevent a block being placed if it is unstable.
/// Uses the code "UnstableFalling".
/// </summary>
[DocumentAsJson]
[AddDocumentationProperty("AttachableFaces", "The faces that this block could be attached from which will prevent it from falling.", "System.String[]", "Optional", "None")]
[AddDocumentationProperty("AttachmentAreas", "A list of attachment areas per face that determine what blocks can be attached to.", "System.Collections.Generic.Dictionary{System.String,Vintagestory.API.Datastructures.RotatableCube}", "Optional", "None")]
[AddDocumentationProperty("AttachmentArea", "A single attachment area that determine what blocks can be attached to. Used if AttachmentAreas is not supplied.", "Vintagestory.API.Mathtools.Cuboidi", "Optional", "None")]
[AddDocumentationProperty("AllowUnstablePlacement","Can this block be placed in an unstable position?","System.Boolean","Optional","False",true)]
[AddDocumentationProperty("IgnorePlaceTest","(Obsolete) Please use the AllowUnstablePlacement attribute instead.","System.Boolean","Obsolete","",false)]
public class BlockBehaviorUnstableFalling : BlockBehavior
{
/// <summary>
/// A list of block types which this block can always be attached to, regardless if there is a correct attachment area.
/// </summary>
[DocumentAsJson("Optional", "None")]
AssetLocation[] exceptions;
/// <summary>
/// Can this block fall horizontally?
/// </summary>
[DocumentAsJson("Optional", "False")]
public bool fallSideways;
/// <summary>
/// A multiplier for the number of dust particles for the falling block. A value of 0 means no dust particles.
/// </summary>
[DocumentAsJson("Optional", "0")]
float dustIntensity;
/// <summary>
/// If <see cref="fallSideways"/> is enabled, this is the chance that the block will fall sideways instead of straight down.
/// </summary>
[DocumentAsJson("Optional", "0.3")]
float fallSidewaysChance = 0.3f;
/// <summary>
/// The path to the sound to play when the block falls.
/// </summary>
[DocumentAsJson("Optional", "None")]
AssetLocation fallSound;
/// <summary>
/// A multiplier of damage dealt to an entity when hit by the falling block. Damage depends on falling height.
/// </summary>
[DocumentAsJson("Optional", "1")]
float impactDamageMul;
/// <summary>
/// A set of attachment areas for the unstable block.
/// </summary>
Cuboidi[] attachmentAreas;
/// <summary>
/// The faces that this block could be attached from which will prevent it from falling.
/// </summary>
BlockFacing[] attachableFaces;
public BlockBehaviorUnstableFalling(Block block) : base(block)
{
}
public override void Initialize(JsonObject properties)
{
base.Initialize(properties);
attachableFaces = null;
if (properties["attachableFaces"].Exists)
{
string[] faces = properties["attachableFaces"].AsArray<string>();
attachableFaces = new BlockFacing[faces.Length];
for (int i = 0; i < faces.Length; i++)
{
attachableFaces[i] = BlockFacing.FromCode(faces[i]);
}
}
var areas = properties["attachmentAreas"].AsObject<Dictionary<string, RotatableCube>>(null);
attachmentAreas = new Cuboidi[6];
if (areas != null)
{
foreach (var val in areas)
{
val.Value.Origin.Set(8, 8, 8);
BlockFacing face = BlockFacing.FromFirstLetter(val.Key[0]);
attachmentAreas[face.Index] = val.Value.RotatedCopy().ConvertToCuboidi();
}
} else
{
attachmentAreas[4] = properties["attachmentArea"].AsObject<Cuboidi>(null);
}
exceptions = properties["exceptions"].AsObject(System.Array.Empty<AssetLocation>(), block.Code.Domain);
fallSideways = properties["fallSideways"].AsBool(false);
dustIntensity = properties["dustIntensity"].AsFloat(0);
fallSidewaysChance = properties["fallSidewaysChance"].AsFloat(0.3f);
string sound = properties["fallSound"].AsString(null);
if (sound != null)
{
fallSound = AssetLocation.Create(sound, block.Code.Domain);
}
impactDamageMul = properties["impactDamageMul"].AsFloat(1f);
}
public override bool CanPlaceBlock(IWorldAccessor world, IPlayer byPlayer, BlockSelection blockSel, ref EnumHandling handling, ref string failureCode)
{
handling = EnumHandling.PassThrough;
if (block.Attributes?["allowUnstablePlacement"].AsBool() == true) return true;
Cuboidi attachmentArea = attachmentAreas[4];
BlockPos pos = blockSel.Position.DownCopy();
Block onBlock = world.BlockAccessor.GetBlock(pos);
if (blockSel != null &&
!IsAttached(world.BlockAccessor, blockSel.Position) &&
!onBlock.CanAttachBlockAt(world.BlockAccessor, block, pos, BlockFacing.UP, attachmentArea) &&
!onBlock.WildCardMatch(exceptions))
{
handling = EnumHandling.PreventSubsequent;
failureCode = "requiresolidground";
return false;
}
return true;
}
public override void OnBlockPlaced(IWorldAccessor world, BlockPos blockPos, ref EnumHandling handling)
{
TryFalling(world, blockPos, ref handling);
}
public override void OnNeighbourBlockChange(IWorldAccessor world, BlockPos pos, BlockPos neibpos, ref EnumHandling handling)
{
base.OnNeighbourBlockChange(world, pos, neibpos, ref handling);
if (world.Side == EnumAppSide.Client) return;
EnumHandling bla = EnumHandling.PassThrough;
TryFalling(world, pos, ref bla);
}
private bool TryFalling(IWorldAccessor world, BlockPos pos, ref EnumHandling handling)
{
if (world.Side != EnumAppSide.Server) return false;
if (!fallSideways && IsAttached(world.BlockAccessor, pos)) return false;
ICoreServerAPI sapi = (world as IServerWorldAccessor).Api as ICoreServerAPI;
if (!sapi.World.Config.GetBool("allowFallingBlocks")) return false;
if (IsReplacableBeneath(world, pos) || (fallSideways && world.Rand.NextDouble() < fallSidewaysChance && IsReplacableBeneathAndSideways(world, pos)))
{
BlockPos ourPos = pos.Copy();
// Must run a frame later. This method is called from OnBlockPlaced, but at this point - if this is a freshly settled falling block, then the BE does not have its full data yet (because EntityBlockFalling makes a SetBlock, then only calls FromTreeAttributes on the BE
sapi.Event.EnqueueMainThreadTask(()=>{
var block = world.BlockAccessor.GetBlock(ourPos);
if (this.block != block) return; // Block was already removed
// Prevents duplication
Entity entity = world.GetNearestEntity(ourPos.ToVec3d().Add(0.5, 0.5, 0.5), 1, 1.5f, (e) =>
{
return e is EntityBlockFalling ebf && ebf.initialPos.Equals(ourPos);
});
if (entity != null) return;
var be = world.BlockAccessor.GetBlockEntity(ourPos);
EntityBlockFalling entityBf = new EntityBlockFalling(block, be, ourPos, fallSound, impactDamageMul, true, dustIntensity);
world.SpawnEntity(entityBf);
}, "falling");
handling = EnumHandling.PreventSubsequent;
return true;
}
handling = EnumHandling.PassThrough;
return false;
}
public virtual bool IsAttached(IBlockAccessor blockAccessor, BlockPos pos)
{
BlockPos tmpPos;
if (attachableFaces == null) // shorter code path for no attachableFaces specified (common case) - we test only the block below
{
tmpPos = pos.DownCopy();
Block block = blockAccessor.GetBlock(tmpPos);
return block.CanAttachBlockAt(blockAccessor, this.block, tmpPos, BlockFacing.UP, attachmentAreas[5]);
}
tmpPos = new BlockPos();
for (int i = 0; i < attachableFaces.Length; i++)
{
BlockFacing face = attachableFaces[i];
tmpPos.Set(pos).Add(face);
Block block = blockAccessor.GetBlock(tmpPos);
if (block.CanAttachBlockAt(blockAccessor, this.block, tmpPos, face.Opposite, attachmentAreas[face.Index]))
{
return true;
}
}
return false;
}
private bool IsReplacableBeneathAndSideways(IWorldAccessor world, BlockPos pos)
{
for (int i = 0; i < 4; i++)
{
BlockFacing facing = BlockFacing.HORIZONTALS[i];
Block nBlock = world.BlockAccessor.GetBlockOrNull(pos.X + facing.Normali.X, pos.Y + facing.Normali.Y, pos.Z + facing.Normali.Z);
if (nBlock != null && nBlock.Replaceable >= 6000)
{
nBlock = world.BlockAccessor.GetBlockOrNull(pos.X + facing.Normali.X, pos.Y + facing.Normali.Y - 1, pos.Z + facing.Normali.Z);
if (nBlock != null && nBlock.Replaceable >= 6000)
{
return true;
}
}
}
return false;
}
private bool IsReplacableBeneath(IWorldAccessor world, BlockPos pos)
{
Block bottomBlock = world.BlockAccessor.GetBlockBelow(pos);
return bottomBlock.Replaceable > 6000;
}
}
}
| 412 | 0.926014 | 1 | 0.926014 | game-dev | MEDIA | 0.890754 | game-dev | 0.900905 | 1 | 0.900905 |
oot-pc-port/oot-pc-port | 3,146 | asm/non_matchings/overlays/actors/ovl_Obj_Bean/func_80B8FEAC.s | glabel func_80B8FEAC
/* 0142C 80B8FEAC 27BDFFD8 */ addiu $sp, $sp, 0xFFD8 ## $sp = FFFFFFD8
/* 01430 80B8FEB0 AFB00018 */ sw $s0, 0x0018($sp)
/* 01434 80B8FEB4 AFA5002C */ sw $a1, 0x002C($sp)
/* 01438 80B8FEB8 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000
/* 0143C 80B8FEBC AFBF001C */ sw $ra, 0x001C($sp)
/* 01440 80B8FEC0 3C053E2A */ lui $a1, 0x3E2A ## $a1 = 3E2A0000
/* 01444 80B8FEC4 3C063C23 */ lui $a2, 0x3C23 ## $a2 = 3C230000
/* 01448 80B8FEC8 34C6D70A */ ori $a2, $a2, 0xD70A ## $a2 = 3C23D70A
/* 0144C 80B8FECC 34A5BA63 */ ori $a1, $a1, 0xBA63 ## $a1 = 3E2ABA63
/* 01450 80B8FED0 0C01DE80 */ jal Math_ApproxF
/* 01454 80B8FED4 24840054 */ addiu $a0, $a0, 0x0054 ## $a0 = 00000054
/* 01458 80B8FED8 30430001 */ andi $v1, $v0, 0x0001 ## $v1 = 00000000
/* 0145C 80B8FEDC 3C053D12 */ lui $a1, 0x3D12 ## $a1 = 3D120000
/* 01460 80B8FEE0 3C063A94 */ lui $a2, 0x3A94 ## $a2 = 3A940000
/* 01464 80B8FEE4 34C61C82 */ ori $a2, $a2, 0x1C82 ## $a2 = 3A941C82
/* 01468 80B8FEE8 34A531C4 */ ori $a1, $a1, 0x31C4 ## $a1 = 3D1231C4
/* 0146C 80B8FEEC AFA30024 */ sw $v1, 0x0024($sp)
/* 01470 80B8FEF0 0C01DE80 */ jal Math_ApproxF
/* 01474 80B8FEF4 26040050 */ addiu $a0, $s0, 0x0050 ## $a0 = 00000050
/* 01478 80B8FEF8 8FA30024 */ lw $v1, 0x0024($sp)
/* 0147C 80B8FEFC C6040050 */ lwc1 $f4, 0x0050($s0) ## 00000050
/* 01480 80B8FF00 240F0001 */ addiu $t7, $zero, 0x0001 ## $t7 = 00000001
/* 01484 80B8FF04 00621824 */ and $v1, $v1, $v0
/* 01488 80B8FF08 10600008 */ beq $v1, $zero, .L80B8FF2C
/* 0148C 80B8FF0C E6040058 */ swc1 $f4, 0x0058($s0) ## 00000058
/* 01490 80B8FF10 860E01B4 */ lh $t6, 0x01B4($s0) ## 000001B4
/* 01494 80B8FF14 5DC00007 */ bgtzl $t6, .L80B8FF34
/* 01498 80B8FF18 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
/* 0149C 80B8FF1C 0C2E3FD4 */ jal func_80B8FF50
/* 014A0 80B8FF20 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
/* 014A4 80B8FF24 10000003 */ beq $zero, $zero, .L80B8FF34
/* 014A8 80B8FF28 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
.L80B8FF2C:
/* 014AC 80B8FF2C A60F01B4 */ sh $t7, 0x01B4($s0) ## 000001B4
/* 014B0 80B8FF30 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
.L80B8FF34:
/* 014B4 80B8FF34 0C00BE5D */ jal func_8002F974
/* 014B8 80B8FF38 240500C6 */ addiu $a1, $zero, 0x00C6 ## $a1 = 000000C6
/* 014BC 80B8FF3C 8FBF001C */ lw $ra, 0x001C($sp)
/* 014C0 80B8FF40 8FB00018 */ lw $s0, 0x0018($sp)
/* 014C4 80B8FF44 27BD0028 */ addiu $sp, $sp, 0x0028 ## $sp = 00000000
/* 014C8 80B8FF48 03E00008 */ jr $ra
/* 014CC 80B8FF4C 00000000 */ nop
| 412 | 0.695749 | 1 | 0.695749 | game-dev | MEDIA | 0.932498 | game-dev | 0.788223 | 1 | 0.788223 |
merschformann/RAWSim-O | 2,381 | RAWSimO.Hardware/RobotHardware/Units.cs | ο»Ώusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RAWSimO.Hardware.RobotHardware
{
/// <summary>
///
/// </summary>
public struct Radius
{
private readonly int m_iValue;
public const int Straight = 32768;
public const int Maximum_Right = -2000;
public const int Maximum_Left = 2000;
/// <summary>
///
/// </summary>
/// <param name="iValue"></param>
/// <returns></returns>
public static implicit operator Radius(int iValue)
{
return new Radius(iValue);
}
/// <summary>
///
/// </summary>
/// <param name="iAngle"></param>
public Radius(int iAngle)
{
if ((iAngle > 2000) & (iAngle != 32768)) { iAngle = 2000; }
if (iAngle < -2000) { iAngle = -2000; }
if (iAngle == 0) { iAngle = Straight; }
this.m_iValue = iAngle;
}
/// <summary>
///
/// </summary>
public int ToInt
{
get
{
return this.m_iValue;
}
}
}
/// <summary>
/// This structure is used to read and set Roomba's velocity. This structure is designed to be used as a variable.
/// This structure also serves to keep any assigned variables within the limits of the SCI spec
/// The limits are: -500mm/s - 500 mm/s
///
/// </summary>
/// <example>
/// Velocity x = 250; //if the programmer sets this to a value > 500, then x will automatically set itself to 500
/// Radius y = -400;
/// this.CurrentRoomba.Drive(x, y);
/// </example>
public struct Velocity
{
private readonly int m_iValue;
public const int Maximum_Forward = 500;
public const int Maximum_Reverse = -500;
public static implicit operator Velocity(int iValue)
{
return new Velocity(iValue);
}
public Velocity(int iSpeed)
{
if (iSpeed > 500) { iSpeed = 500; };
if (iSpeed < -500) { iSpeed = -500; };
this.m_iValue = iSpeed;
}
public int ToInt
{
get
{
return this.m_iValue;
}
}
}
}
| 412 | 0.834985 | 1 | 0.834985 | game-dev | MEDIA | 0.79726 | game-dev | 0.865783 | 1 | 0.865783 |
emscripten-core/emscripten | 5,510 | test/third_party/bullet/src/BulletCollision/CollisionShapes/btConvexInternalShape.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_CONVEX_INTERNAL_SHAPE_H
#define BT_CONVEX_INTERNAL_SHAPE_H
#include "btConvexShape.h"
#include "LinearMath/btAabbUtil2.h"
///The btConvexInternalShape is an internal base class, shared by most convex shape implementations.
class btConvexInternalShape : public btConvexShape
{
protected:
//local scaling. collisionMargin is not scaled !
btVector3 m_localScaling;
btVector3 m_implicitShapeDimensions;
btScalar m_collisionMargin;
btScalar m_padding;
btConvexInternalShape();
public:
virtual ~btConvexInternalShape()
{
}
virtual btVector3 localGetSupportingVertex(const btVector3& vec)const;
const btVector3& getImplicitShapeDimensions() const
{
return m_implicitShapeDimensions;
}
///warning: use setImplicitShapeDimensions with care
///changing a collision shape while the body is in the world is not recommended,
///it is best to remove the body from the world, then make the change, and re-add it
///alternatively flush the contact points, see documentation for 'cleanProxyFromPairs'
void setImplicitShapeDimensions(const btVector3& dimensions)
{
m_implicitShapeDimensions = dimensions;
}
///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version
void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
{
getAabbSlow(t,aabbMin,aabbMax);
}
virtual void getAabbSlow(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const;
virtual void setLocalScaling(const btVector3& scaling);
virtual const btVector3& getLocalScaling() const
{
return m_localScaling;
}
const btVector3& getLocalScalingNV() const
{
return m_localScaling;
}
virtual void setMargin(btScalar margin)
{
m_collisionMargin = margin;
}
virtual btScalar getMargin() const
{
return m_collisionMargin;
}
btScalar getMarginNV() const
{
return m_collisionMargin;
}
virtual int getNumPreferredPenetrationDirections() const
{
return 0;
}
virtual void getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const
{
(void)penetrationVector;
(void)index;
btAssert(0);
}
virtual int calculateSerializeBufferSize() const;
///fills the dataBuffer and returns the struct name (and 0 on failure)
virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const;
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btConvexInternalShapeData
{
btCollisionShapeData m_collisionShapeData;
btVector3FloatData m_localScaling;
btVector3FloatData m_implicitShapeDimensions;
float m_collisionMargin;
int m_padding;
};
SIMD_FORCE_INLINE int btConvexInternalShape::calculateSerializeBufferSize() const
{
return sizeof(btConvexInternalShapeData);
}
///fills the dataBuffer and returns the struct name (and 0 on failure)
SIMD_FORCE_INLINE const char* btConvexInternalShape::serialize(void* dataBuffer, btSerializer* serializer) const
{
btConvexInternalShapeData* shapeData = (btConvexInternalShapeData*) dataBuffer;
btCollisionShape::serialize(&shapeData->m_collisionShapeData, serializer);
m_implicitShapeDimensions.serializeFloat(shapeData->m_implicitShapeDimensions);
m_localScaling.serializeFloat(shapeData->m_localScaling);
shapeData->m_collisionMargin = float(m_collisionMargin);
return "btConvexInternalShapeData";
}
///btConvexInternalAabbCachingShape adds local aabb caching for convex shapes, to avoid expensive bounding box calculations
class btConvexInternalAabbCachingShape : public btConvexInternalShape
{
btVector3 m_localAabbMin;
btVector3 m_localAabbMax;
bool m_isLocalAabbValid;
protected:
btConvexInternalAabbCachingShape();
void setCachedLocalAabb (const btVector3& aabbMin, const btVector3& aabbMax)
{
m_isLocalAabbValid = true;
m_localAabbMin = aabbMin;
m_localAabbMax = aabbMax;
}
inline void getCachedLocalAabb (btVector3& aabbMin, btVector3& aabbMax) const
{
btAssert(m_isLocalAabbValid);
aabbMin = m_localAabbMin;
aabbMax = m_localAabbMax;
}
inline void getNonvirtualAabb(const btTransform& trans,btVector3& aabbMin,btVector3& aabbMax, btScalar margin) const
{
//lazy evaluation of local aabb
btAssert(m_isLocalAabbValid);
btTransformAabb(m_localAabbMin,m_localAabbMax,margin,trans,aabbMin,aabbMax);
}
public:
virtual void setLocalScaling(const btVector3& scaling);
virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const;
void recalcLocalAabb();
};
#endif //BT_CONVEX_INTERNAL_SHAPE_H
| 412 | 0.910743 | 1 | 0.910743 | game-dev | MEDIA | 0.995554 | game-dev | 0.944476 | 1 | 0.944476 |
Secrets-of-Sosaria/World | 2,997 | Data/Scripts/Items/Magical/Gifts/Jewels/MagicTalisman.cs | using System;
using Server;
using Server.Misc;
namespace Server.Items
{
public class GiftTalismanLeather : GiftGoldRing
{
public override Catalogs DefaultCatalog{ get{ return Catalogs.Trinket; } }
[Constructable]
public GiftTalismanLeather()
{
ItemID = 0x2F58;
Resource = CraftResource.None;
Name = "talisman";
Layer = Layer.Trinket;
Weight = 1.0;
Hue = Utility.RandomColor(0);
}
public GiftTalismanLeather( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 1 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
//////////////////////////////////////////////////////////////////////
public class GiftTalismanSnake : GiftGoldRing
{
public override Catalogs DefaultCatalog{ get{ return Catalogs.Trinket; } }
[Constructable]
public GiftTalismanSnake()
{
ItemID = 0x2F59;
Resource = CraftResource.None;
Name = "talisman";
Layer = Layer.Trinket;
Weight = 1.0;
Hue = Utility.RandomColor(0);
}
public GiftTalismanSnake( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 1 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
//////////////////////////////////////////////////////////////////////
public class GiftTalismanTotem : GiftGoldRing
{
public override Catalogs DefaultCatalog{ get{ return Catalogs.Trinket; } }
[Constructable]
public GiftTalismanTotem()
{
ItemID = 0x2F5A;
Resource = CraftResource.None;
Name = "talisman";
Layer = Layer.Trinket;
Weight = 1.0;
Hue = Utility.RandomColor(0);
}
public GiftTalismanTotem( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 1 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
//////////////////////////////////////////////////////////////////////
public class GiftTalismanHoly : GiftGoldRing
{
public override Catalogs DefaultCatalog{ get{ return Catalogs.Trinket; } }
[Constructable]
public GiftTalismanHoly()
{
ItemID = 0x2F5B;
Resource = CraftResource.None;
Name = "talisman";
Layer = Layer.Trinket;
Weight = 1.0;
Hue = Utility.RandomColor(0);
}
public GiftTalismanHoly( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 1 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} | 412 | 0.537157 | 1 | 0.537157 | game-dev | MEDIA | 0.936474 | game-dev | 0.694491 | 1 | 0.694491 |
Swifter1243/BeatCraft | 7,292 | src/client/java/com/beatcraft/base_providers/ValueProvider.java | package com.beatcraft.base_providers;
import com.beatcraft.data.types.Color;
import com.beatcraft.memory.MemoryPool;
import net.minecraft.util.math.MathHelper;
import org.joml.Quaternionf;
import org.joml.Vector2f;
import org.joml.Vector3f;
import org.joml.Vector4f;
import java.util.function.Consumer;
public interface ValueProvider {
float[] getValues();
default int getSize() {
return getValues().length;
}
}
interface RotationProvider {
Quaternionf getRotation();
}
record StaticValueProvider(float[] values) implements ValueProvider {
@Override
public float[] getValues() {
return values;
}
}
record BaseProvider(float[] values) implements ValueProvider {
@Override
public float[] getValues() {
return values;
}
}
abstract class UpdatableValue implements ValueProvider {
public abstract void update();
}
class QuaternionProvider extends UpdatableValue implements RotationProvider {
private final float[] source;
private final float[] values;
private final Quaternionf rotation;
QuaternionProvider(float[] source) {
this.source = source;
values = new float[3];
rotation = new Quaternionf();
}
@Override
public Quaternionf getRotation() {
return rotation;
}
@Override
public void update() {
rotation.set(source[0], source[1], source[2], source[3]);
Vector3f e = MemoryPool.newVector3f();
rotation.getEulerAnglesXYZ(e);
values[0] = e.x;
values[1] = e.y;
values[2] = e.z;
MemoryPool.releaseSafe(e);
}
@Override
public float[] getValues() {
return values;
}
}
class SwizzleProvider extends UpdatableValue {
private final float[] source;
private final int[] parts;
private final float[] values;
SwizzleProvider(float[] source, int[] parts) {
this.source = source;
this.parts = parts;
values = new float[parts.length];
}
@Override
public void update() {
for (int i = 0; i < parts.length; i++) {
values[i] = source[parts[i]];
}
}
@Override
public float[] getValues() {
return values;
}
}
class SmoothRotationProvider extends UpdatableValue {
private final RotationProvider rotationProvider;
private final float mult;
private final float[] values = new float[3];
private double lastTime;
private final Quaternionf lastQuaternion = new Quaternionf();
SmoothRotationProvider(RotationProvider provider, float mult) {
rotationProvider = provider;
this.mult = mult;
lastTime = System.nanoTime() / 1_000_000_000d;
}
@Override
public void update() {
var t = System.nanoTime() / 1_000_000_000d;
var dt = t - lastTime;
lastTime = t;
lastQuaternion.slerp(rotationProvider.getRotation(), (float) dt * mult);
var e = MemoryPool.newVector3f();
lastQuaternion.getEulerAnglesXYZ(e);
values[0] = e.x;
values[1] = e.y;
values[2] = e.z;
MemoryPool.releaseSafe(e);
}
@Override
public float[] getValues() {
return values;
}
}
class SmoothValueProvider extends UpdatableValue {
private final float[] source;
private final float mult;
private final float[] values;
private double lastTime;
SmoothValueProvider(float[] source, float mult) {
this.source = source;
this.mult = mult;
this.values = new float[source.length];
lastTime = System.nanoTime() / 1_000_000_000d;
}
@Override
public void update() {
var t = System.nanoTime() / 1_000_000_000d;
var dt = t - lastTime;
lastTime = t;
for (int i = 0; i < source.length; i++) {
values[i] = MathHelper.lerp((float) dt * mult, values[i], source[i]);
}
}
@Override
public float[] getValues() {
return values;
}
}
class BaseValueProvider extends UpdatableValue {
private final float[] values;
private final Consumer<float[]> updater;
public BaseValueProvider(int size, Consumer<float[]> valueUpdater) {
values = new float[size];
updater = valueUpdater;
update();
}
@Override
public void update() {
updater.accept(values);
}
@Override
public float[] getValues() {
return values;
}
}
class BaseRotationProvider extends UpdatableValue implements RotationProvider {
private final float[] values;
private final Consumer<Quaternionf> updater;
private final Quaternionf rotation = new Quaternionf();
public BaseRotationProvider(Consumer<Quaternionf> valueUpdater) {
values = new float[3];
updater = valueUpdater;
}
@Override
public void update() {
updater.accept(rotation);
var e = MemoryPool.newVector3f();
rotation.getEulerAnglesXYZ(e);
values[0] = e.x;
values[1] = e.y;
values[2] = e.z;
MemoryPool.releaseSafe(e);
}
@Override
public float[] getValues() {
return values;
}
@Override
public Quaternionf getRotation() {
return rotation;
}
}
class ValueMixer extends UpdatableValue {
private final float[][] sources;
private final float[] values;
public ValueMixer(float[][] sources) {
this.sources = sources;
int i = 0;
for (var src : sources) {
if (src == null) continue;
for (var ignored : src) {
i++;
}
}
this.values = new float[i];
}
@Override
public void update() {
int i = 0;
for (var src : sources) {
if (src == null) continue;
for (var s : src) {
values[i] = s;
i++;
}
}
}
@Override
public float[] getValues() {
return values;
}
}
class ValueOperator extends UpdatableValue {
private final float[] src0;
private final float[] src1;
private final float[] values;
private final String operation;
public ValueOperator(float[] left, float[] right, String op) {
src0 = left;
src1 = right;
values = new float[left.length];
operation = op;
}
@Override
public void update() {
switch (operation) {
case "opAdd" -> {
for (int i = 0; i < src0.length; i++) {
values[i] = src0[i] + src1[i];
}
}
case "opSub" -> {
for (int i = 0; i < src0.length; i++) {
values[i] = src0[i] - src1[i];
}
}
case "opMul" -> {
for (int i = 0; i < src0.length; i++) {
values[i] = src0[i] * src1[i];
}
}
case "opDiv" -> {
for (int i = 0; i < src0.length; i++) {
values[i] = src0[i] / src1[i];
}
}
default -> throw new IllegalArgumentException("Invalid operation: '" + operation + "'");
}
}
@Override
public float[] getValues() {
return values;
}
}
| 412 | 0.946393 | 1 | 0.946393 | game-dev | MEDIA | 0.836733 | game-dev | 0.937172 | 1 | 0.937172 |
ACreTeam/ac-decomp | 3,184 | src/game/m_haniwaPortrait_ovl.c | #include "m_haniwaPortrait_ovl.h"
#include "m_rcp.h"
#include "sys_matrix.h"
extern cKF_Skeleton_R_c cKF_bs_r_hnw;
extern cKF_Animation_R_c cKF_ba_r_hnw_move;
static mHP_Ovl_c hp_ovl_data;
static void mHP_haniwaPortrait_shape_init(Submenu* submenu) {
mHP_Ovl_c* haniwaPortrait_ovl = submenu->overlay->hanwiaPortrait_ovl;
cKF_SkeletonInfo_R_ct(&haniwaPortrait_ovl->keyframe, &cKF_bs_r_hnw, NULL, haniwaPortrait_ovl->keyframe_work, haniwaPortrait_ovl->keyframe_morph);
cKF_SkeletonInfo_R_init(&haniwaPortrait_ovl->keyframe, haniwaPortrait_ovl->keyframe.skeleton, &cKF_ba_r_hnw_move, 1.0f, 9.0f, 1.0f, 0.3f, 0.0f, cKF_FRAMECONTROL_REPEAT, NULL);
}
static void mHP_haniwaPortrait_shape_move(Submenu* submenu) {
cKF_SkeletonInfo_R_play(&submenu->overlay->hanwiaPortrait_ovl->keyframe);
}
extern u8 hnw_tmem_txt[];
extern u16 hnw_face[];
static void mHP_haniwaPortrait_shape_draw(Submenu* submenu, mSM_MenuInfo_c* menu_info, GAME* game) {
GRAPH* graph = game->graph;
Mtx* mtx = GRAPH_ALLOC_TYPE(graph, Mtx, submenu->overlay->hanwiaPortrait_ovl->keyframe.skeleton->num_shown_joints);
if (mtx != NULL) {
_texture_z_light_fog_prim(game->graph);
Matrix_scale(0.01f, 0.01f, 0.01f, MTX_LOAD);
OPEN_DISP(graph);
gDPPipeSync(NOW_POLY_OPA_DISP++);
gSPMatrix(NOW_POLY_OPA_DISP++, _Matrix_to_Mtx_new(graph), G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW);
gSPSegment(NOW_POLY_OPA_DISP++, G_MWO_SEGMENT_B, hnw_tmem_txt);
gDPLoadTLUT_Dolphin(NOW_POLY_OPA_DISP++, 15, 16, 1, hnw_face);
if (menu_info->data0 == 0) {
gDPSetPrimColor(NOW_POLY_OPA_DISP++, 0, 128, 255, 255, 255, 255);
}
else {
gDPSetPrimColor(NOW_POLY_OPA_DISP++, 0, 128, 255, 255, 255, 255);
}
CLOSE_DISP(graph);
cKF_Si3_draw_R_SV(game, &submenu->overlay->hanwiaPortrait_ovl->keyframe, mtx, NULL, NULL, NULL);
}
}
static void mHP_set_haniwaPortrait(Submenu* submenu, mSM_MenuInfo_c* menu_info, GRAPH* graph, GAME* game, f32 x, f32 y) {
if (x < -128.0f || x > 448.0f || y < -128.0f || y > 368.0f) {
return;
}
Matrix_push();
OPEN_DISP(graph);
gDPPipeSync(NOW_POLY_OPA_DISP++);
CLOSE_DISP(graph);
(*submenu->overlay->change_view_proc)(graph, 105.0f, 25.0f, x * 4.0f, y * 4.0f, 0x0900, 128, 128);
mHP_haniwaPortrait_shape_draw(submenu, menu_info, game);
(*submenu->overlay->setup_view_proc)(submenu, graph, FALSE);
Matrix_pull();
}
extern void mHP_haniwaPortrait_ovl_construct(Submenu* submenu) {
Submenu_Overlay_c* overlay = submenu->overlay;
if (overlay->hanwiaPortrait_ovl == NULL) {
mem_clear((u8*)&hp_ovl_data, sizeof(mHP_Ovl_c), 0);
overlay->hanwiaPortrait_ovl = &hp_ovl_data;
submenu->overlay->hanwiaPortrait_ovl->set_haniwaPortrait_proc = &mHP_set_haniwaPortrait;
submenu->overlay->hanwiaPortrait_ovl->haniwaPortrait_shape_move_proc = &mHP_haniwaPortrait_shape_move;
mHP_haniwaPortrait_shape_init(submenu);
mHP_haniwaPortrait_shape_move(submenu);
}
}
extern void mHP_haniwaPortrait_ovl_destruct(Submenu* submenu) {
Submenu_Overlay_c* overlay = submenu->overlay;
cKF_SkeletonInfo_R_dt(&overlay->hanwiaPortrait_ovl->keyframe);
submenu->overlay->hanwiaPortrait_ovl = NULL;
}
| 412 | 0.840365 | 1 | 0.840365 | game-dev | MEDIA | 0.511655 | game-dev,graphics-rendering | 0.919201 | 1 | 0.919201 |
Assasain20/AngrySDK | 3,606 | data/scripts_common/menus/achievements.lua | AchievementPopup = ui.BGBox:inherit()
function AchievementPopup:new(achievement_id, o)
local o = o or {}
o.achievement_id = achievement_id
return ui.BGBox.new(self, o)
end
function AchievementPopup:init()
ui.BGBox.init(self)
self.components = {
left = "ACHIEVEMENT_BG_LEFT",
center = "ACHIEVEMENT_BG_MIDDLE",
right = "ACHIEVEMENT_BG_RIGHT"
}
self.hanchor = "RIGHT"
self.vanchor = "TOP"
local icon = ui.Image:new()
icon.name = "icon"
self:addChild(icon)
local title = ui.Text:new()
title.name = "title"
title.text = ""
title.font = "FONT_GAMECENTER_BASIC"
title.hanchor = "HCENTER"
title.vanchor = "TOP"
title.group = ""
self:addChild(title)
local description = ui.Text:new()
description.name = "description"
description.text = ""
description.font = "FONT_GAMECENTER_BASIC"
description.hanchor = "LEFT"
description.vanchor = "BOTTOM"
description.group = ""
self:addChild(description)
end
function AchievementPopup:onEntry()
ui.BGBox.onEntry(self)
self.timer = 2.7
end
function AchievementPopup:layout()
local sx = 1
local sy = 1
local tsx = 1
local tsy = 1
if isRetinaGraphicsEnabled() then
sx = 2
sy = 2
tsx = 2
tsy = 2
self.components = {
left = "ACHIEVEMENT_BG_LEFT_RETINA",
center = "ACHIEVEMENT_BG_MIDDLE_RETINA",
right = "ACHIEVEMENT_BG_RIGHT_RETINA"
}
else
self.components = {
left = "ACHIEVEMENT_BG_LEFT",
center = "ACHIEVEMENT_BG_MIDDLE",
right = "ACHIEVEMENT_BG_RIGHT"
}
end
ui.BGBox.layout(self)
local achievement
if gameCenter ~= nil then
achievement = gameCenter.achievements[self.achievement_id]
end
local title = self:getChild("title")
local description = self:getChild("description")
local icon = self:getChild("icon")
title.text = "Achievement Title"
if achievement ~= nil then
title.text = achievement.title or "Achievement Title"
end
description.text = "Earned an achievement."
if achievement ~= nil then
description.text = achievement.achievedText or "Earned an achievement."
end
if achievement ~= nil then
icon:setImage(achievement.icon)
else
icon:setImage("ACHIEVEMENT_GET_XXX_POINTS")
end
setFont(title.font)
local title_h = _G.res.getFontHeight() * tsy
local title_w = _G.res.getStringWidth(title.text) * tsx
setFont(description.font)
local desc_h = _G.res.getFontHeight() * tsy
local desc_w = _G.res.getStringWidth(description.text) * tsx
local bg_w, bg_h = _G.res.getSpriteBounds(self.components.right)
local icon_w, icon_h = _G.res.getSpriteBounds(icon.image)
icon_w = icon_w * sx
icon_h = icon_h * sy
self.width = _G.math.max(title_w, desc_w + icon_w) * 1.2
self.height = bg_h
self.x = screenWidth - bg_w
title.x = self.width * -0.5
title.y = self.height * 0.1
title.scaleX = tsx
title.scaleY = tsy
icon.x = self.width * -0.9
icon.y = self.height * 0.65
icon.scaleX = sx
icon.scaleY = sy
description.x = icon.x + icon_w
description.y = self.height * 0.75
description.scaleX = tsx
description.scaleY = tsy
end
function AchievementPopup:update(dt, time)
ui.BGBox.update(self, dt, time)
local _, box_h = _G.res.getSpriteBounds(self.components.right)
self.timer = self.timer - dt
if self.timer > 2.4 then
self.y = screenHeight - box_h * ((2.7 - self.timer) / 0.3)
elseif self.timer > 0.4 then
self.y = screenHeight - box_h
elseif self.timer > 0 then
self.y = screenHeight - box_h + box_h * ((0.4 - self.timer) / 0.3)
else
notificationsFrame:removeChild(self)
end
end
filename = "achievements.lua"
| 412 | 0.540615 | 1 | 0.540615 | game-dev | MEDIA | 0.60499 | game-dev,desktop-app | 0.747593 | 1 | 0.747593 |
revng/revng | 1,928 | lib/FunctionIsolation/RemoveExceptionalCalls.cpp | /// \file RemoveExceptionalCalls.cpp
//
// This file is distributed under the MIT License. See LICENSE.md for details.
//
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "revng/FunctionIsolation/RemoveExceptionalCalls.h"
#include "revng/Support/FunctionTags.h"
#include "revng/Support/IRHelpers.h"
using namespace llvm;
char RemoveExceptionalCalls::ID = 0;
using Register = RegisterPass<RemoveExceptionalCalls>;
static Register X("remove-exceptional-functions",
"Remove Exceptional Functions");
bool RemoveExceptionalCalls::runOnModule(llvm::Module &M) {
LLVMContext &C = M.getContext();
// Collect all calls to exceptional functions in lifted functions
std::set<CallBase *> ToErase;
for (Function &F : FunctionTags::Exceptional.functions(&M))
for (CallBase *Call : callers(&F))
if (FunctionTags::Isolated.isTagOf(Call->getParent()->getParent()))
ToErase.insert(Call);
std::set<Function *> ToCleanup;
for (CallBase *Call : ToErase) {
BasicBlock *BB = Call->getParent();
// Register function for cleanup
ToCleanup.insert(BB->getParent());
// Split containing basic block
BB->splitBasicBlock(Call);
// Record the old terminator so that we don't need to look for it again
llvm::Instruction *OldTerminator = BB->getTerminator();
// Terminate with an unreachable
auto Unreachable = new UnreachableInst(C, BB);
Unreachable->setDebugLoc(OldTerminator->getDebugLoc());
// Drop the old terminator
eraseFromParent(OldTerminator);
// Drop function call
auto *Undef = UndefValue::get(Call->getType());
Call->replaceAllUsesWith(Undef);
eraseFromParent(Call);
}
// Garbage collect dead blocks
for (Function *F : ToCleanup)
EliminateUnreachableBlocks(*F, nullptr, false);
return true;
}
| 412 | 0.940001 | 1 | 0.940001 | game-dev | MEDIA | 0.523449 | game-dev,compilers-parsers | 0.835326 | 1 | 0.835326 |
axmolengine/axmol | 6,523 | extensions/Particle3D/src/Particle3D/PU/PUDoEnableComponentEventHandler.cpp | /****************************************************************************
Copyright (C) 2013 Henry van Merode. All rights reserved.
Copyright (c) 2015-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
https://axmol.dev/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "Particle3D/PU/PUDoEnableComponentEventHandler.h"
#include "Particle3D/PU/PUAffector.h"
#include "Particle3D/PU/PUEmitter.h"
#include "Particle3D/PU/PUObserver.h"
namespace ax
{
//-----------------------------------------------------------------------
PUDoEnableComponentEventHandler::PUDoEnableComponentEventHandler()
: PUEventHandler(), _componentType(CT_EMITTER), _componentEnabled(true)
{}
//-----------------------------------------------------------------------
void PUDoEnableComponentEventHandler::handle(PUParticleSystem3D* particleSystem,
PUParticle3D* /*particle*/,
float /*timeElapsed*/)
{
/** Search for the component.
*/
// ParticleTechnique* technique = 0;
switch (_componentType)
{
case CT_EMITTER:
{
PUEmitter* emitter = particleSystem->getEmitter(_componentName);
if (!emitter)
{
// Search all techniques in this ParticleSystem for an emitter with the correct name
PUParticleSystem3D* system = particleSystem->getParentParticleSystem();
if (system)
{
auto children = system->getChildren();
for (auto&& iter : children)
{
PUParticleSystem3D* child = dynamic_cast<PUParticleSystem3D*>(iter);
if (child)
{
emitter = child->getEmitter(_componentName);
if (emitter)
{
break;
}
}
}
}
}
if (emitter)
{
emitter->setEnabled(_componentEnabled);
}
}
break;
case CT_AFFECTOR:
{
PUAffector* affector = particleSystem->getAffector(_componentName);
if (!affector)
{
// Search all techniques in this ParticleSystem for an emitter with the correct name
PUParticleSystem3D* system = particleSystem->getParentParticleSystem();
if (system)
{
auto children = system->getChildren();
for (auto&& iter : children)
{
PUParticleSystem3D* child = dynamic_cast<PUParticleSystem3D*>(iter);
if (child)
{
affector = child->getAffector(_componentName);
if (affector)
{
break;
}
}
}
}
}
if (affector)
{
affector->setEnabled(_componentEnabled);
}
}
break;
case CT_OBSERVER:
{
PUObserver* observer = particleSystem->getObserver(_componentName);
if (!observer)
{
// Search all techniques in this ParticleSystem for an emitter with the correct name
PUParticleSystem3D* system = particleSystem->getParentParticleSystem();
if (system)
{
auto children = system->getChildren();
for (auto&& iter : children)
{
PUParticleSystem3D* child = dynamic_cast<PUParticleSystem3D*>(iter);
if (child)
{
observer = child->getObserver(_componentName);
if (observer)
{
break;
}
}
}
}
}
if (observer)
{
observer->setEnabled(_componentEnabled);
}
}
break;
case CT_TECHNIQUE:
{
// Search in this ParticleSystem for a technique with the correct name
PUParticleSystem3D* system = particleSystem->getParentParticleSystem();
if (system)
{
auto children = system->getChildren();
for (auto&& iter : children)
{
PUParticleSystem3D* child = dynamic_cast<PUParticleSystem3D*>(iter);
if (child && child->getName() == _componentName)
{
child->setEnabled(_componentEnabled);
break;
}
}
}
}
break;
default:
break;
}
}
PUDoEnableComponentEventHandler* PUDoEnableComponentEventHandler::create()
{
auto peh = new PUDoEnableComponentEventHandler();
peh->autorelease();
return peh;
}
void PUDoEnableComponentEventHandler::copyAttributesTo(PUEventHandler* eventHandler)
{
PUEventHandler::copyAttributesTo(eventHandler);
PUDoEnableComponentEventHandler* doEnableComponentEventHandler =
static_cast<PUDoEnableComponentEventHandler*>(eventHandler);
doEnableComponentEventHandler->setComponentType(_componentType);
doEnableComponentEventHandler->setComponentName(_componentName);
doEnableComponentEventHandler->setComponentEnabled(_componentEnabled);
}
} // namespace ax
| 412 | 0.921438 | 1 | 0.921438 | game-dev | MEDIA | 0.741231 | game-dev | 0.851015 | 1 | 0.851015 |
Sicraftails/SMM-WE-OpenWE | 2,054 | objects/obj_thwomp_b_res/Mouse_4.gml | if (obj_levelmanager.editor == 1 && obj_levelmanager.editor_sonidos == 0 && global.resource_create == 0 && object_index != obj_resource_empty && obj_editormanager.expand_open == 0 && instance_exists(obj_cursor) && obj_cursor.dont_move == 0)
{
if (global.editor_activity == 1)
{
if (global.cursor == 0)
{
if (obj_parent_resource.alarm[0] == -1 && alarm[0] == -1)
{
if (mouse_x > (x + -11) && mouse_y > (y + 14) && mouse_x < (x + 18) && mouse_y < (y + 50))
{
audio_play_sound(snd_change_arrow, 0, false)
if (direct_t == 1)
{
direct_t = 2
rotacion = 270
}
else if (direct_t == 2)
{
direct_t = 3
rotacion = 90
}
else if (direct_t == 3)
{
direct_t = 1
rotacion = 0
}
}
else
{
audio_play_sound(snd_ground_bomb, 0, false)
xx = (x - mouse_x)
yy = (y - mouse_y)
with (obj_creation_preview)
{
xx = other.xx
yy = other.yy
}
x_start = x
y_start = y
global.resource_block = 1
drag = 1
obj_cursor.move = 1
ventana = 1
global.cursor = 1
with (obj_cursor)
event_user(0)
if (!instance_exists(obj_effect_touch))
instance_create(mouse_x, mouse_y, obj_effect_touch)
global.resource_move = object_index
alarm[0] = 1
}
}
}
}
}
| 412 | 0.799178 | 1 | 0.799178 | game-dev | MEDIA | 0.939092 | game-dev | 0.775511 | 1 | 0.775511 |
DrRed96/Nonsense-Client-Old | 13,565 | src/main/java/net/minecraft/item/ItemPotion.java | package net.minecraft.item;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.ai.attributes.IAttribute;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityPotion;
import net.minecraft.init.Items;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.potion.PotionHelper;
import net.minecraft.stats.StatList;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
public class ItemPotion extends Item
{
private Map<Integer, List<PotionEffect>> effectCache = Maps.<Integer, List<PotionEffect>>newHashMap();
private static final Map<List<PotionEffect>, Integer> SUB_ITEMS_CACHE = Maps.<List<PotionEffect>, Integer>newLinkedHashMap();
public ItemPotion()
{
this.setMaxStackSize(1);
this.setHasSubtypes(true);
this.setMaxDamage(0);
this.setCreativeTab(CreativeTabs.tabBrewing);
}
public List<PotionEffect> getEffects(ItemStack stack)
{
if (stack.hasTagCompound() && stack.getTagCompound().hasKey("CustomPotionEffects", 9))
{
List<PotionEffect> list1 = Lists.<PotionEffect>newArrayList();
NBTTagList nbttaglist = stack.getTagCompound().getTagList("CustomPotionEffects", 10);
for (int i = 0; i < nbttaglist.tagCount(); ++i)
{
NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i);
PotionEffect potioneffect = PotionEffect.readCustomPotionEffectFromNBT(nbttagcompound);
if (potioneffect != null)
{
list1.add(potioneffect);
}
}
return list1;
}
else
{
List<PotionEffect> list = (List)this.effectCache.get(Integer.valueOf(stack.getMetadata()));
if (list == null)
{
list = PotionHelper.getPotionEffects(stack.getMetadata(), false);
this.effectCache.put(Integer.valueOf(stack.getMetadata()), list);
}
return list;
}
}
public List<PotionEffect> getEffects(int meta)
{
List<PotionEffect> list = (List)this.effectCache.get(Integer.valueOf(meta));
if (list == null)
{
list = PotionHelper.getPotionEffects(meta, false);
this.effectCache.put(Integer.valueOf(meta), list);
}
return list;
}
/**
* Called when the player finishes using this Item (E.g. finishes eating.). Not called when the player stops using
* the Item before the action is complete.
*/
public ItemStack onItemUseFinish(ItemStack stack, World worldIn, EntityPlayer playerIn)
{
if (!playerIn.capabilities.isCreativeMode)
{
--stack.stackSize;
}
if (!worldIn.isRemote)
{
List<PotionEffect> list = this.getEffects(stack);
if (list != null)
{
for (PotionEffect potioneffect : list)
{
playerIn.addPotionEffect(new PotionEffect(potioneffect));
}
}
}
playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]);
if (!playerIn.capabilities.isCreativeMode)
{
if (stack.stackSize <= 0)
{
return new ItemStack(Items.glass_bottle);
}
playerIn.inventory.addItemStackToInventory(new ItemStack(Items.glass_bottle));
}
return stack;
}
/**
* How long it takes to use or consume an item
*/
public int getMaxItemUseDuration(ItemStack stack)
{
return 32;
}
/**
* returns the action that specifies what animation to play when the items is being used
*/
public EnumAction getItemUseAction(ItemStack stack)
{
return EnumAction.DRINK;
}
/**
* Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
*/
public ItemStack onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn)
{
if (isSplash(itemStackIn.getMetadata()))
{
if (!playerIn.capabilities.isCreativeMode)
{
--itemStackIn.stackSize;
}
worldIn.playSoundAtEntity(playerIn, "random.bow", 0.5F, 0.4F / (itemRand.nextFloat() * 0.4F + 0.8F));
if (!worldIn.isRemote)
{
worldIn.spawnEntityInWorld(new EntityPotion(worldIn, playerIn, itemStackIn));
}
playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]);
return itemStackIn;
}
else
{
playerIn.setItemInUse(itemStackIn, this.getMaxItemUseDuration(itemStackIn));
return itemStackIn;
}
}
/**
* returns wether or not a potion is a throwable splash potion based on damage value
*/
public static boolean isSplash(int meta)
{
return (meta & 16384) != 0;
}
public int getColorFromDamage(int meta)
{
return PotionHelper.getLiquidColor(meta, false);
}
public int getColorFromItemStack(ItemStack stack, int renderPass)
{
return renderPass > 0 ? 16777215 : this.getColorFromDamage(stack.getMetadata());
}
public boolean isEffectInstant(int meta)
{
List<PotionEffect> list = this.getEffects(meta);
if (list != null && !list.isEmpty())
{
for (PotionEffect potioneffect : list)
{
if (Potion.potionTypes[potioneffect.getPotionID()].isInstant())
{
return true;
}
}
return false;
}
else
{
return false;
}
}
public String getItemStackDisplayName(ItemStack stack)
{
if (stack.getMetadata() == 0)
{
return StatCollector.translateToLocal("item.emptyPotion.name").trim();
}
else
{
String s = "";
if (isSplash(stack.getMetadata()))
{
s = StatCollector.translateToLocal("potion.prefix.grenade").trim() + " ";
}
List<PotionEffect> list = Items.potionitem.getEffects(stack);
if (list != null && !list.isEmpty())
{
String s2 = ((PotionEffect)list.get(0)).getEffectName();
s2 = s2 + ".postfix";
return s + StatCollector.translateToLocal(s2).trim();
}
else
{
String s1 = PotionHelper.getPotionPrefix(stack.getMetadata());
return StatCollector.translateToLocal(s1).trim() + " " + super.getItemStackDisplayName(stack);
}
}
}
/**
* allows items to add custom lines of information to the mouseover description
*/
public void addInformation(ItemStack stack, EntityPlayer playerIn, List<String> tooltip, boolean advanced)
{
if (stack.getMetadata() != 0)
{
List<PotionEffect> list = Items.potionitem.getEffects(stack);
Multimap<String, AttributeModifier> multimap = HashMultimap.<String, AttributeModifier>create();
if (list != null && !list.isEmpty())
{
for (PotionEffect potioneffect : list)
{
String s1 = StatCollector.translateToLocal(potioneffect.getEffectName()).trim();
Potion potion = Potion.potionTypes[potioneffect.getPotionID()];
Map<IAttribute, AttributeModifier> map = potion.getAttributeModifierMap();
if (map != null && map.size() > 0)
{
for (Entry<IAttribute, AttributeModifier> entry : map.entrySet())
{
AttributeModifier attributemodifier = (AttributeModifier)entry.getValue();
AttributeModifier attributemodifier1 = new AttributeModifier(attributemodifier.getName(), potion.getAttributeModifierAmount(potioneffect.getAmplifier(), attributemodifier), attributemodifier.getOperation());
multimap.put(((IAttribute)entry.getKey()).getAttributeUnlocalizedName(), attributemodifier1);
}
}
if (potioneffect.getAmplifier() > 0)
{
s1 = s1 + " " + StatCollector.translateToLocal("potion.potency." + potioneffect.getAmplifier()).trim();
}
if (potioneffect.getDuration() > 20)
{
s1 = s1 + " (" + Potion.getDurationString(potioneffect) + ")";
}
if (potion.isBadEffect())
{
tooltip.add(EnumChatFormatting.RED + s1);
}
else
{
tooltip.add(EnumChatFormatting.GRAY + s1);
}
}
}
else
{
String s = StatCollector.translateToLocal("potion.empty").trim();
tooltip.add(EnumChatFormatting.GRAY + s);
}
if (!multimap.isEmpty())
{
tooltip.add("");
tooltip.add(EnumChatFormatting.DARK_PURPLE + StatCollector.translateToLocal("potion.effects.whenDrank"));
for (Entry<String, AttributeModifier> entry1 : multimap.entries())
{
AttributeModifier attributemodifier2 = (AttributeModifier)entry1.getValue();
double d0 = attributemodifier2.getAmount();
double d1;
if (attributemodifier2.getOperation() != 1 && attributemodifier2.getOperation() != 2)
{
d1 = attributemodifier2.getAmount();
}
else
{
d1 = attributemodifier2.getAmount() * 100.0D;
}
if (d0 > 0.0D)
{
tooltip.add(EnumChatFormatting.BLUE + StatCollector.translateToLocalFormatted("attribute.modifier.plus." + attributemodifier2.getOperation(), new Object[] {ItemStack.DECIMALFORMAT.format(d1), StatCollector.translateToLocal("attribute.name." + (String)entry1.getKey())}));
}
else if (d0 < 0.0D)
{
d1 = d1 * -1.0D;
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocalFormatted("attribute.modifier.take." + attributemodifier2.getOperation(), new Object[] {ItemStack.DECIMALFORMAT.format(d1), StatCollector.translateToLocal("attribute.name." + (String)entry1.getKey())}));
}
}
}
}
}
public boolean hasEffect(ItemStack stack)
{
List<PotionEffect> list = this.getEffects(stack);
return list != null && !list.isEmpty();
}
/**
* returns a list of items with the same ID, but different meta (eg: dye returns 16 items)
*/
public void getSubItems(Item itemIn, CreativeTabs tab, List<ItemStack> subItems)
{
super.getSubItems(itemIn, tab, subItems);
if (SUB_ITEMS_CACHE.isEmpty())
{
for (int i = 0; i <= 15; ++i)
{
for (int j = 0; j <= 1; ++j)
{
int lvt_6_1_;
if (j == 0)
{
lvt_6_1_ = i | 8192;
}
else
{
lvt_6_1_ = i | 16384;
}
for (int l = 0; l <= 2; ++l)
{
int i1 = lvt_6_1_;
if (l != 0)
{
if (l == 1)
{
i1 = lvt_6_1_ | 32;
}
else if (l == 2)
{
i1 = lvt_6_1_ | 64;
}
}
List<PotionEffect> list = PotionHelper.getPotionEffects(i1, false);
if (list != null && !list.isEmpty())
{
SUB_ITEMS_CACHE.put(list, Integer.valueOf(i1));
}
}
}
}
}
Iterator iterator = SUB_ITEMS_CACHE.values().iterator();
while (iterator.hasNext())
{
int j1 = ((Integer)iterator.next()).intValue();
subItems.add(new ItemStack(itemIn, 1, j1));
}
}
}
| 412 | 0.803316 | 1 | 0.803316 | game-dev | MEDIA | 0.989351 | game-dev | 0.983901 | 1 | 0.983901 |
lzk228/space-axolotl-14 | 1,292 | Content.Server/Weapons/Ranged/Systems/GunSystem.AutoFire.cs | using Content.Shared.Damage;
using Content.Shared.Weapons.Ranged.Components;
using Robust.Shared.Map;
namespace Content.Server.Weapons.Ranged.Systems;
public sealed partial class GunSystem
{
public override void Update(float frameTime)
{
base.Update(frameTime);
/*
* On server because client doesn't want to predict other's guns.
*/
// Automatic firing without stopping if the AutoShootGunComponent component is exist and enabled
var query = EntityQueryEnumerator<GunComponent>();
while (query.MoveNext(out var uid, out var gun))
{
if (gun.NextFire > Timing.CurTime)
continue;
if (TryComp(uid, out AutoShootGunComponent? autoShoot))
{
if (!autoShoot.Enabled)
continue;
AttemptShoot(uid, gun);
}
else if (gun.BurstActivated)
{
var parent = TransformSystem.GetParentUid(uid);
if (HasComp<DamageableComponent>(parent))
AttemptShoot(parent, uid, gun, gun.ShootCoordinates ?? new EntityCoordinates(uid, gun.DefaultDirection));
else
AttemptShoot(uid, gun);
}
}
}
}
| 412 | 0.901586 | 1 | 0.901586 | game-dev | MEDIA | 0.980192 | game-dev | 0.913338 | 1 | 0.913338 |
followingthefasciaplane/source-engine-diff-check | 11,063 | misc/game/shared/tf2/weapon_combat_laserrifle.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Laser Rifle & Shield combo
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "weapon_combatshield.h"
#include "weapon_combat_usedwithshieldbase.h"
#include "in_buttons.h"
#include "takedamageinfo.h"
#include "beam_shared.h"
#include "tf_gamerules.h"
// Damage CVars
ConVar weapon_combat_laserrifle_damage( "weapon_combat_laserrifle_damage","20", FCVAR_REPLICATED, "Laser rifle damage" );
ConVar weapon_combat_laserrifle_range( "weapon_combat_laserrifle_range","1000", FCVAR_REPLICATED, "Laser rifle maximum range" );
ConVar weapon_combat_laserrifle_ducking_mod( "weapon_combat_laserrifle_ducking_mod", "0.75", FCVAR_REPLICATED, "Laser rifle ducking ROF modifier" );
#if defined( CLIENT_DLL )
#include "fx.h"
#include "hud.h"
#include "c_te_effect_dispatch.h"
#include <vgui/ISurface.h>
#define CWeaponCombatLaserRifle C_WeaponCombatLaserRifle
#else
#include "te_effect_dispatch.h"
#endif
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
class CWeaponCombatLaserRifle : public CWeaponCombatUsedWithShieldBase
{
DECLARE_CLASS( CWeaponCombatLaserRifle, CWeaponCombatUsedWithShieldBase );
public:
DECLARE_NETWORKCLASS();
DECLARE_PREDICTABLE();
CWeaponCombatLaserRifle( void );
virtual const Vector& GetBulletSpread( void );
virtual void ItemBusyFrame( void );
virtual void ItemPostFrame( void );
virtual void PrimaryAttack( void );
virtual float GetFireRate( void );
virtual float GetDefaultAnimSpeed( void );
virtual void BulletWasFired( const Vector &vecStart, const Vector &vecEnd );
void RecalculateAccuracy( void );
// All predicted weapons need to implement and return true
virtual bool IsPredicted( void ) const
{
return true;
}
private:
CWeaponCombatLaserRifle( const CWeaponCombatLaserRifle & );
public:
#if defined( CLIENT_DLL )
virtual bool ShouldPredict( void )
{
if ( GetOwner() &&
GetOwner() == C_BasePlayer::GetLocalPlayer() )
return true;
return BaseClass::ShouldPredict();
}
virtual void DrawCrosshair( void );
#endif
private:
float m_flInaccuracy;
float m_flAccuracyTime;
};
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CWeaponCombatLaserRifle::CWeaponCombatLaserRifle( void )
{
SetPredictionEligible( true );
m_flInaccuracy = 0;
m_flAccuracyTime = 0;
}
IMPLEMENT_NETWORKCLASS_ALIASED( WeaponCombatLaserRifle, DT_WeaponCombatLaserRifle )
BEGIN_NETWORK_TABLE( CWeaponCombatLaserRifle, DT_WeaponCombatLaserRifle )
END_NETWORK_TABLE()
BEGIN_PREDICTION_DATA( CWeaponCombatLaserRifle )
END_PREDICTION_DATA()
LINK_ENTITY_TO_CLASS( weapon_combat_laserrifle, CWeaponCombatLaserRifle );
PRECACHE_WEAPON_REGISTER(weapon_combat_laserrifle);
//-----------------------------------------------------------------------------
// Purpose: Get the accuracy derived from weapon and player, and return it
//-----------------------------------------------------------------------------
const Vector& CWeaponCombatLaserRifle::GetBulletSpread( void )
{
static Vector cone = VECTOR_CONE_8DEGREES;
return cone;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CWeaponCombatLaserRifle::ItemBusyFrame( void )
{
BaseClass::ItemBusyFrame();
RecalculateAccuracy();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CWeaponCombatLaserRifle::ItemPostFrame( void )
{
CBaseTFPlayer *pOwner = ToBaseTFPlayer( GetOwner() );
if (!pOwner)
return;
if ( UsesClipsForAmmo1() )
{
CheckReload();
}
RecalculateAccuracy();
// Handle firing
if ( GetShieldState() == SS_DOWN && !m_bInReload )
{
if ( (pOwner->m_nButtons & IN_ATTACK ) && (m_flNextPrimaryAttack <= gpGlobals->curtime) )
{
if ( m_iClip1 > 0 )
{
// Fire the plasma shot
PrimaryAttack();
}
else
{
Reload();
}
}
// Reload button (or fire button when we're out of ammo)
if ( m_flNextPrimaryAttack <= gpGlobals->curtime )
{
if ( pOwner->m_nButtons & IN_RELOAD )
{
Reload();
}
else if ( !((pOwner->m_nButtons & IN_ATTACK) || (pOwner->m_nButtons & IN_ATTACK2) || (pOwner->m_nButtons & IN_RELOAD)) )
{
if ( !m_iClip1 && HasPrimaryAmmo() )
{
Reload();
}
}
}
}
// Prevent shield post frame if we're not ready to attack, or we're charging
AllowShieldPostFrame( m_flNextPrimaryAttack <= gpGlobals->curtime || m_bInReload );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CWeaponCombatLaserRifle::PrimaryAttack( void )
{
CBaseTFPlayer *pPlayer = (CBaseTFPlayer*)GetOwner();
if (!pPlayer)
return;
WeaponSound(SINGLE);
// Fire the bullets
Vector vecSrc = pPlayer->Weapon_ShootPosition( );
Vector vecAiming;
pPlayer->EyeVectors( &vecAiming );
PlayAttackAnimation( GetPrimaryAttackActivity() );
// Reduce the spread if the player's ducking
Vector vecSpread = GetBulletSpread();
vecSpread *= m_flInaccuracy;
TFGameRules()->FireBullets( CTakeDamageInfo( this, pPlayer, weapon_combat_laserrifle_damage.GetFloat(), DMG_PLASMA), 1,
vecSrc, vecAiming, vecSpread, weapon_combat_laserrifle_range.GetFloat(), m_iPrimaryAmmoType, 0, entindex(), 0 );
m_flInaccuracy += 0.3;
m_flInaccuracy = clamp(m_flInaccuracy, 0, 1);
m_flNextPrimaryAttack = gpGlobals->curtime + GetFireRate();
m_iClip1 = m_iClip1 - 1;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
float CWeaponCombatLaserRifle::GetFireRate( void )
{
float flFireRate = ( SequenceDuration() * 0.4 ) + SHARED_RANDOMFLOAT( 0.0, 0.035f );
CBaseTFPlayer *pPlayer = static_cast<CBaseTFPlayer*>( GetOwner() );
if ( pPlayer )
{
// Ducking players should fire more rapidly.
if ( pPlayer->GetFlags() & FL_DUCKING )
{
flFireRate *= weapon_combat_laserrifle_ducking_mod.GetFloat();
}
}
return flFireRate;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CWeaponCombatLaserRifle::RecalculateAccuracy( void )
{
CBaseTFPlayer *pPlayer = (CBaseTFPlayer*)GetOwner();
if (!pPlayer)
return;
m_flAccuracyTime += gpGlobals->frametime;
while ( m_flAccuracyTime > 0.05 )
{
if ( !(pPlayer->GetFlags() & FL_ONGROUND) )
{
m_flInaccuracy += 0.05;
}
else if ( pPlayer->GetFlags() & FL_DUCKING )
{
m_flInaccuracy -= 0.08;
}
/*
else if ( pPlayer->GetLocalVelocity().LengthSqr() > (100*100) )
{
// Never get worse than 1/2 accuracy from running
if ( m_flInaccuracy < 0.25 )
{
m_flInaccuracy += 0.01;
if ( m_flInaccuracy > 0.5 )
{
m_flInaccuracy = 0.5;
}
}
else if ( m_flInaccuracy > 0.25 )
{
m_flInaccuracy -= 0.01;
}
}
*/
else
{
m_flInaccuracy -= 0.04;
}
// Crouching prevents accuracy ever going beyond a point
if ( pPlayer->GetFlags() & FL_DUCKING )
{
m_flInaccuracy = clamp(m_flInaccuracy, 0, 0.8);
}
else
{
m_flInaccuracy = clamp(m_flInaccuracy, 0, 1);
}
m_flAccuracyTime -= 0.05;
#ifndef CLIENT_DLL
//if ( m_flInaccuracy )
//Msg("Inaccuracy %.2f (%.2f)\n", m_flInaccuracy, gpGlobals->curtime );
#endif
}
}
//-----------------------------------------------------------------------------
// Purpose: Match the anim speed to the weapon speed while crouching
//-----------------------------------------------------------------------------
float CWeaponCombatLaserRifle::GetDefaultAnimSpeed( void )
{
if ( GetOwner() && GetOwner()->IsPlayer() )
{
if ( GetOwner()->GetFlags() & FL_DUCKING )
return (1.0 + (1.0 - weapon_combat_laserrifle_ducking_mod.GetFloat()) );
}
return 1.0;
}
//-----------------------------------------------------------------------------
// Purpose: Draw the laser rifle effect
//-----------------------------------------------------------------------------
void CWeaponCombatLaserRifle::BulletWasFired( const Vector &vecStart, const Vector &vecEnd )
{
// Humans fire jazzed up bullets, Aliens fire laserbeams
if ( GetTeamNumber() == TEAM_HUMANS )
{
UTIL_Tracer( (Vector&)vecStart, (Vector&)vecEnd, entindex(), 1, 5000, false, "HLaserTracer" );
}
else
{
UTIL_Tracer( (Vector&)vecStart, (Vector&)vecEnd, entindex(), 1, 5000, false, "ALaserTracer" );
}
}
#ifdef CLIENT_DLL
//-----------------------------------------------------------------------------
// Purpose: Draw the weapon's crosshair
//-----------------------------------------------------------------------------
void CWeaponCombatLaserRifle::DrawCrosshair( void )
{
BaseClass::DrawCrosshair();
// Draw the targeting zone around the crosshair
int r, g, b, a;
gHUD.m_clrYellowish.GetColor( r, g, b, a );
// Check to see if we are in vgui mode
C_BaseTFPlayer *pPlayer = static_cast<C_BaseTFPlayer*>( GetOwner() );
if ( !pPlayer || pPlayer->IsInVGuiInputMode() )
return;
// Draw a crosshair & accuracy hoodad
int iBarWidth = XRES(10);
int iBarHeight = YRES(10);
int iTotalWidth = (iBarWidth * 2) + (40 * m_flInaccuracy) + XRES(10);
int iTotalHeight = (iBarHeight * 2) + (40 * m_flInaccuracy) + YRES(10);
// Horizontal bars
int iLeft = (ScreenWidth() - iTotalWidth) / 2;
int iMidHeight = (ScreenHeight() / 2);
Color dark( r, g, b, 32 );
Color light( r, g, b, 160 );
vgui::surface()->DrawSetColor( dark );
vgui::surface()->DrawFilledRect( iLeft, iMidHeight-1, iLeft+ iBarWidth, iMidHeight + 2 );
vgui::surface()->DrawFilledRect( iLeft + iTotalWidth - iBarWidth, iMidHeight-1, iLeft + iTotalWidth, iMidHeight + 2 );
vgui::surface()->DrawSetColor( light );
vgui::surface()->DrawFilledRect( iLeft, iMidHeight, iLeft + iBarWidth, iMidHeight + 1 );
vgui::surface()->DrawFilledRect( iLeft + iTotalWidth - iBarWidth, iMidHeight, iLeft + iTotalWidth, iMidHeight + 1 );
// Vertical bars
int iTop = (ScreenHeight() - iTotalHeight) / 2;
int iMidWidth = (ScreenWidth() / 2);
vgui::surface()->DrawSetColor( dark );
vgui::surface()->DrawFilledRect( iMidWidth-1, iTop, iMidWidth + 2, iTop + iBarHeight );
vgui::surface()->DrawFilledRect( iMidWidth-1, iTop + iTotalHeight - iBarHeight, iMidWidth + 2, iTop + iTotalHeight );
vgui::surface()->DrawSetColor( light );
vgui::surface()->DrawFilledRect( iMidWidth, iTop, iMidWidth + 1, iTop + iBarHeight );
vgui::surface()->DrawFilledRect( iMidWidth, iTop + iTotalHeight - iBarHeight, iMidWidth + 1, iTop + iTotalHeight );
}
#endif | 412 | 0.954792 | 1 | 0.954792 | game-dev | MEDIA | 0.920534 | game-dev | 0.931972 | 1 | 0.931972 |
microsoft/elfie-arriba | 24,654 | Arriba/Arriba/Structures/WordIndex.cs | ο»Ώ// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Arriba.Extensions;
using Arriba.Indexing;
using Arriba.Model;
using Arriba.Model.Expressions;
using Arriba.Serialization;
namespace Arriba.Structures
{
/// <summary>
/// WordIndex provides inverted index functionality for a given column.
/// </summary>
public class WordIndex : IBinarySerializable
{
public const int MinimumPrefixExpandLength = 3;
private IWordSplitter _splitter;
private List<WordIndexBlock> _blocks;
public WordIndex(IWordSplitter splitter)
{
_splitter = splitter;
_blocks = new List<WordIndexBlock>();
}
#region Search
/// <summary>
/// Find the items containing the exact word passed and add them to
/// the result set passed.
/// </summary>
/// <param name="word">Word to find</param>
/// <param name="result">Result to which to add matches</param>
public void WhereMatchExact(ByteBlock word, ShortSet result)
{
// Find the block with the exact word and find matches
foreach (WordIndexBlock block in _blocks)
{
ushort wordIndex = block.IndexOf(word);
if (wordIndex != ushort.MaxValue)
{
block.GetInSet(wordIndex, result);
return;
}
}
}
/// <summary>
/// Find the items containing *any word* starting with the word passed
/// and add the union of all of them to the result set passed.
/// </summary>
/// <param name="prefix">Prefix to find</param>
/// <param name="result">Result to which to add matches</param>
public void WhereMatches(ByteBlock prefix, ShortSet result)
{
if (result == null) throw new ArgumentNullException("result");
// Split each word in the input value
RangeSet prefixWords = _splitter.Split(prefix);
// Shortcut: If only one word, add directly to result set
if (prefixWords.Count == 1 && prefixWords.Ranges[0].Length == prefix.Length)
{
// Add matches for words starting with this prefix in every block
foreach (WordIndexBlock block in _blocks)
{
block.WhereMatches(prefix, result);
}
}
else
{
// We need to add (OR) the items which match all words (AND) in the split prefix
ShortSet matchesForAllWords = null;
ShortSet matchesForWord = new ShortSet(result.Capacity);
// For each found word, add all matches
for (int i = 0; i < prefixWords.Count; ++i)
{
Range word = prefixWords.Ranges[i];
ByteBlock wordBlock = new ByteBlock(prefix.Array, word.Index, word.Length);
matchesForWord.Clear();
// Add matches for words starting with this prefix in every block
foreach (WordIndexBlock block in _blocks)
{
block.WhereMatches(wordBlock, matchesForWord);
}
// AND matches for this word with each other word in the prefix
if (matchesForAllWords == null)
{
matchesForAllWords = new ShortSet(result.Capacity);
matchesForAllWords.Or(matchesForWord);
}
else
{
matchesForAllWords.And(matchesForWord);
}
}
// OR matches for ALL words with the final result
if (matchesForAllWords != null) result.Or(matchesForAllWords);
}
}
#endregion
#region Add/Remove
public void Index(ushort id, ByteBlock oldValue, ByteBlock newValue)
{
RangeSet oldValueWords = _splitter.Split(oldValue);
RangeSet newValueWords = _splitter.Split(newValue);
for (int i = 0; i < oldValueWords.Count; ++i)
{
Range word = oldValueWords.Ranges[i];
ByteBlock wordBlock = new ByteBlock(oldValue.Array, word.Index, word.Length);
RemoveWord(id, wordBlock);
}
for (int i = 0; i < newValueWords.Count; ++i)
{
Range word = newValueWords.Ranges[i];
ByteBlock wordBlock = new ByteBlock(newValue.Array, word.Index, word.Length);
AddWord(id, wordBlock);
}
}
/// <summary>
/// Add a given item to the index for a given word.
/// </summary>
/// <param name="id">Item to add</param>
/// <param name="word">Word with which to associate item</param>
public void AddWord(ushort id, ByteBlock word)
{
WordIndexBlock block = null;
ushort wordIndex = ushort.MaxValue;
// If the word is already in a block, get the index
for (int i = 0; i < _blocks.Count; ++i)
{
block = _blocks[i];
wordIndex = block.IndexOf(word);
if (wordIndex != ushort.MaxValue) break;
}
// If not, try to add the word to the last block
if (wordIndex == ushort.MaxValue && block != null)
{
wordIndex = block.Add(word);
}
// If the last block was full, add another block
if (wordIndex == ushort.MaxValue)
{
block = new WordIndexBlock();
wordIndex = block.Add(word);
_blocks.Add(block);
}
block.AddToSet(wordIndex, id);
}
/// <summary>
/// Remove a given item from the index for a given word.
/// </summary>
/// <param name="id">Item to remove</param>
/// <param name="word">Word from which to disassociate item</param>
public void RemoveWord(ushort id, ByteBlock word)
{
foreach (WordIndexBlock block in _blocks)
{
ushort wordIndex = block.IndexOf(word);
if (wordIndex != ushort.MaxValue)
{
block.RemoveFromSet(wordIndex, id);
break;
}
}
}
#endregion
#region Management
public void VerifyConsistency(IColumn column, VerificationLevel level, ExecutionDetails details)
{
foreach (WordIndexBlock block in _blocks)
{
block.VerifyConsistency(column, level, details);
}
}
#endregion
#region Dictionary Conversion [Testability]
public Dictionary<string, List<ushort>> ConvertToDictionary()
{
Dictionary<string, List<ushort>> result = new Dictionary<string, List<ushort>>();
foreach (WordIndexBlock block in _blocks)
{
block.ExportToDictionary(result);
}
return result;
}
#endregion
#region IBinarySerializable
public void ReadBinary(ISerializationContext context)
{
if (context == null) throw new ArgumentNullException("context");
_blocks.Clear();
int blockCount = context.Reader.ReadInt32();
for (int i = 0; i < blockCount; ++i)
{
WordIndexBlock block = new WordIndexBlock();
block.ReadBinary(context);
_blocks.Add(block);
}
}
public void WriteBinary(ISerializationContext context)
{
if (context == null) throw new ArgumentNullException("context");
context.Writer.Write(_blocks.Count);
foreach (WordIndexBlock block in _blocks)
{
block.WriteBinary(context);
}
}
#endregion
#region WordIndexBlock Nested Class
internal class WordIndexBlock : IBinarySerializable
{
private const ushort WordCountLimit = 65000;
private const ushort DenseSetLengthCutoff = 1024;
private SortedColumn<ByteBlock> _words;
private ByteBlockColumn _sets;
public WordIndexBlock()
{
_words = new SortedColumn<ByteBlock>(new ByteBlockColumn(ByteBlock.Zero), 0);
_sets = new ByteBlockColumn(ByteBlock.Zero);
}
#region Word Operations
/// <summary>
/// Return the index of a given word in this block.
/// </summary>
/// <param name="word">Word to find</param>
/// <returns>Index of word (and corresponding set) or ushort.MaxValue if not present.</returns>
public ushort IndexOf(ByteBlock word)
{
ushort index;
_words.TryGetIndexOf(word, out index);
return index;
}
/// <summary>
/// Add the given word and return the index.
/// </summary>
/// <param name="word">Word to add</param>
/// <returns>Index of new word, or ushort.MaxValue if unable to add</returns>
public ushort Add(ByteBlock word)
{
if (_words.Count < WordCountLimit)
{
ushort wordIndex = _words.Count;
_words.SetSize((ushort)(wordIndex + 1));
_sets.SetSize((ushort)(wordIndex + 1));
_words[wordIndex] = word;
return wordIndex;
}
return ushort.MaxValue;
}
/// <summary>
/// Add matches to the given set for all words starting with the provided prefix.
/// </summary>
/// <param name="prefix">Prefix for which to add matches</param>
/// <param name="result">Set to add all items containing words beginning with prefix</param>
public void WhereMatches(ByteBlock prefix, ShortSet result)
{
// Look for prefixes if above the length minimum; equality otherwise
if (prefix.Length < MinimumPrefixExpandLength)
{
WhereMatchesExact(prefix, result);
return;
}
IComparable<ByteBlock> isPrefixOf = prefix.GetExtendedIComparable(ByteBlock.Comparison.IsPrefixOf);
// Otherwise, find all words starting with this prefix
int firstIndex = _words.FindFirstWhere(isPrefixOf);
if (firstIndex < 0) return;
int lastIndex = _words.FindLastWhere(isPrefixOf);
IList<ushort> sortedIndexes;
int sortedIndexescount;
_words.TryGetSortedIndexes(out sortedIndexes, out sortedIndexescount);
for (int i = firstIndex; i <= lastIndex; ++i)
{
GetInSet(sortedIndexes[i], result);
}
}
/// <summary>
/// Add matches to the given set for all items with the exact value passed.
/// </summary>
/// <param name="value">Word for which to add matches</param>
/// <param name="result">Set to add all items containing the word to</param>
public void WhereMatchesExact(ByteBlock value, ShortSet result)
{
ushort index;
_words.TryGetIndexOf(value, out index);
if (index != ushort.MaxValue)
{
GetInSet(index, result);
}
}
#endregion
#region Set Operations
/// <summary>
/// Add a given item to a given set.
/// </summary>
/// <param name="setId">SetID (WordID) of word to add item to.</param>
/// <param name="itemId">ItemID to add for word</param>
public unsafe void AddToSet(ushort setId, ushort itemId)
{
ByteBlock set = _sets[setId];
fixed (byte* array = set.Array)
{
if (set.Length < DenseSetLengthCutoff)
{
// Sparse Set: Add values as individual ushorts.
ushort* valuesForWord = (ushort*)(array + set.Index);
ushort availableLength = (ushort)(set.Length / 2);
ushort usedLength = FindUsedLength(valuesForWord, availableLength);
// If this value was already added, stop
if (usedLength > 0 && valuesForWord[usedLength - 1] == itemId) return;
if (usedLength < availableLength)
{
// Set not full - append the new value
valuesForWord[usedLength] = itemId;
}
else
{
// Set is full - create a new one
if (set.Length * 2 >= DenseSetLengthCutoff)
{
// At cutoff - convert to dense set
byte[] newDenseBlock = new byte[ushort.MaxValue / 8];
fixed (byte* newArray = newDenseBlock)
{
ulong* newBits = (ulong*)(newArray);
for (int i = 0; i < usedLength; ++i)
{
ushort id = valuesForWord[i];
newBits[id / 64] |= (ShortSet.FirstBit >> id % 64);
}
newBits[itemId / 64] |= (ShortSet.FirstBit >> itemId % 64);
}
_sets[setId] = newDenseBlock;
}
else
{
// Below cutoff - keep sparse set
byte[] newBlock = new byte[Math.Max(2, set.Length * 2)];
// Copy current values
set.CopyTo(newBlock);
fixed (byte* newArray = newBlock)
{
ushort* newValues = (ushort*)newArray;
// Add new value
newValues[usedLength] = itemId;
// Pad remainder with sentinel maxvalue
for (int i = usedLength + 1; i < newBlock.Length / 2; ++i)
{
newValues[i] = ushort.MaxValue;
}
}
_sets[setId] = newBlock;
}
}
}
else
{
// Dense Set: Turn on the bit for the value
ulong* bitsForWord = (ulong*)(array + set.Index);
bitsForWord[itemId / 64] |= (ShortSet.FirstBit >> itemId % 64);
}
}
}
/// <summary>
/// Remove a given item from a given set.
/// </summary>
/// <param name="setId">SetID (WordID) of word to remove</param>
/// <param name="itemId">ItemID of item to remove from word</param>
public unsafe void RemoveFromSet(ushort setId, ushort itemId)
{
ByteBlock set = _sets[setId];
fixed (byte* array = set.Array)
{
if (set.Length < DenseSetLengthCutoff)
{
// Sparse Set: Remove the value and swap the last value.
ushort* valuesForWord = (ushort*)(array + set.Index);
ushort availableLength = (ushort)(set.Length / 2);
ushort usedLength = FindUsedLength(valuesForWord, availableLength);
if (usedLength == 1)
{
// If word is unique, remove the word and swap the last value.
// NOTE: Need to confirm last ID is really this one, because multiple copies of the word may be in the value.
if (valuesForWord[0] == itemId)
{
ushort lastWordIndex = (ushort)(_words.Count - 1);
if (lastWordIndex > 0 && lastWordIndex != setId)
{
_sets[setId] = _sets[lastWordIndex];
_words[setId] = _words[lastWordIndex];
}
_words.SetSize(lastWordIndex);
_sets.SetSize(lastWordIndex);
}
}
else
{
for (int i = 0; i < usedLength; ++i)
{
if (valuesForWord[i] == itemId)
{
// Swap the last value here
--usedLength;
valuesForWord[i] = valuesForWord[usedLength];
valuesForWord[usedLength] = ushort.MaxValue;
}
}
}
}
else
{
// Dense Set: Turn off the bit for the value
ulong* bitsForWord = (ulong*)(array + set.Index);
bitsForWord[itemId / 64] &= ~(ShortSet.FirstBit >> itemId % 64);
}
}
}
/// <summary>
/// Get the IDs listed in the set for a given word and add them
/// to a result ShortSet.
/// </summary>
/// <param name="setId">ID of set/word to add</param>
/// <param name="result">ShortSet to which to add results</param>
public unsafe void GetInSet(ushort setId, ShortSet result)
{
ByteBlock set = _sets[setId];
fixed (byte* array = set.Array)
{
if (set.Length < DenseSetLengthCutoff)
{
// Sparse Set: Add values as individual ushorts.
ushort* valuesForWord = (ushort*)(array + set.Index);
ushort usedLength = FindUsedLength(valuesForWord, (ushort)(set.Length / 2));
result.Or(valuesForWord, usedLength);
}
else
{
// Dense Set: Add values as ulong bits.
ulong* bitsForWord = (ulong*)(array + set.Index);
result.Or(bitsForWord, (ushort)(set.Length / 8));
}
}
}
/// <summary>
/// Find the used portion of a given sparse set. Sets are MaxValue
/// padded, so the used portion is the number of non-MaxValue values.
/// </summary>
/// <param name="set">Set array to search</param>
/// <param name="totalSpace">Length of full array</param>
/// <returns>Number of items set, totalSpace if all of them</returns>
private unsafe ushort FindUsedLength(ushort* set, ushort totalSpace)
{
// If the last value is set, there is no free space
if (set == null || totalSpace == 0 || set[totalSpace - 1] != ushort.MaxValue) return totalSpace;
int min = 0;
int max = totalSpace - 1;
// Find the first zero value in our array
while (min < max)
{
int mid = (min + max) / 2;
if (set[mid] != ushort.MaxValue)
{
min = mid + 1;
}
else
{
max = mid;
}
}
// Return the last index with a value (same as the length)
if (set[min] != ushort.MaxValue)
return (ushort)(min + 1);
else
return (ushort)min;
}
#endregion
#region Management
public void VerifyConsistency(IColumn column, VerificationLevel level, ExecutionDetails details)
{
if (_words.Count > WordCountLimit)
{
details.AddError(ExecutionDetails.WordIndexBlockTooFull, column.Name, _words.Count);
}
if (_words.Count != _sets.Count)
{
details.AddError(ExecutionDetails.WordIndexBlockSizesMismatch, column.Name, _words.Count, _sets.Count);
}
if (level == VerificationLevel.Full)
{
// Validate that all IDs in all sets are valid
// NOTE: Replacing with a validating GetInSet would be more thorough; check for duplicate values, padding problems, etc.
ShortSet allValidItems = new ShortSet(column.Count);
allValidItems.Not();
ShortSet items = new ShortSet(ushort.MaxValue);
for (ushort i = 0; i < _words.Count; ++i)
{
items.Clear();
GetInSet(i, items);
items.AndNot(allValidItems);
if (items.Count() > 0)
{
details.AddError(ExecutionDetails.WordIndexInvalidItemID, column.Name, _words[i], String.Join(", ", items.Values));
}
}
}
// Ask the Sets and Words columns to self-verify
_sets.VerifyConsistency(level, details);
_words.VerifyConsistency(level, details);
}
#endregion
#region Dictionary Conversion [Testability]
public void ExportToDictionary(Dictionary<string, List<ushort>> result)
{
IList<ushort> sortedWords;
int sortedWordsCount;
_words.TryGetSortedIndexes(out sortedWords, out sortedWordsCount);
for (int i = 0; i < _words.Count; ++i)
{
ushort lid = sortedWords[i];
string word = _words[lid].ToString();
ShortSet set = new ShortSet(ushort.MaxValue);
GetInSet(lid, set);
List<ushort> page;
if (!result.TryGetValue(word, out page))
{
page = new List<ushort>();
result[word] = page;
}
page.AddRange(set.Values);
}
}
#endregion
#region IBinarySerializable
public void ReadBinary(ISerializationContext context)
{
_words.ReadBinary(context);
_sets.ReadBinary(context);
}
public void WriteBinary(ISerializationContext context)
{
_words.WriteBinary(context);
_sets.WriteBinary(context);
}
#endregion
}
#endregion
}
}
| 412 | 0.919505 | 1 | 0.919505 | game-dev | MEDIA | 0.426649 | game-dev | 0.908859 | 1 | 0.908859 |
kessiler/muOnline-season6 | 1,456 | gameServer/gameServer/MagicInf.h | //-> Revised by DarkSim | 23.04.2013 | 1.01.00 GS-N
// -------------------------------------------------------------------------------
#pragma once
// -------------------------------------------------------------------------------
#include "MagicDamage.h"
// -------------------------------------------------------------------------------
#define MAX_MAGICINF 255
// -------------------------------------------------------------------------------
class CMagicInf
{
public:
CMagicInf();
virtual ~CMagicInf();
// ----
int IsMagic();
void Clear();
int Set(BYTE aType, BYTE aIndex, BYTE aLevel);
int GetDamage();
int Set(int aSkill, BYTE aLevel);
int UpdateMasterSkill(int iSkill, BYTE btLevel);
// ----
CMagicInf & operator = (CMagicInf const & __that)
{
this->m_Level = __that.m_Level;
this->m_Skill = __that.m_Skill;
this->m_DamageMin = __that.m_DamageMin;
this->m_DamageMax = __that.m_DamageMax;
this->m_bPass = __that.m_bPass; //new
return * this;
};
// ----
public:
BYTE m_Level; //+4
int m_Skill; //+8
int m_DamageMin; //+12
int m_DamageMax; //+16
BYTE m_bPass; //+20
// ----
}; extern CMagicInf DefMagicInf[];
// -------------------------------------------------------------------------------
int GetSkillNumberInex(int type, int Index, int level);
void MagicByteConvert(LPBYTE buf, CMagicInf Magici[], int maxmagic);
// ------------------------------------------------------------------------------- | 412 | 0.657074 | 1 | 0.657074 | game-dev | MEDIA | 0.503668 | game-dev | 0.623865 | 1 | 0.623865 |
KATRIN-Experiment/Kassiopeia | 2,656 | Kassiopeia/Trajectories/Include/KSTrajControlPositionNumericalError.h | #ifndef Kassiopeia_KSTrajControlPositionNumericalError_h_
#define Kassiopeia_KSTrajControlPositionNumericalError_h_
#include "KSComponentTemplate.h"
#include "KSTrajAdiabaticSpinTypes.h"
#include "KSTrajAdiabaticTypes.h"
#include "KSTrajExactSpinTypes.h"
#include "KSTrajExactTypes.h"
namespace Kassiopeia
{
class KSTrajControlPositionNumericalError :
public KSComponentTemplate<KSTrajControlPositionNumericalError>,
public KSTrajExactControl,
public KSTrajExactSpinControl,
public KSTrajAdiabaticSpinControl,
public KSTrajAdiabaticControl
{
public:
KSTrajControlPositionNumericalError();
KSTrajControlPositionNumericalError(const KSTrajControlPositionNumericalError& aCopy);
KSTrajControlPositionNumericalError* Clone() const override;
~KSTrajControlPositionNumericalError() override;
public:
void Calculate(const KSTrajExactParticle& aParticle, double& aValue) override;
void Check(const KSTrajExactParticle& anInitialParticle, const KSTrajExactParticle& aFinalParticle,
const KSTrajExactError& anError, bool& aFlag) override;
void Calculate(const KSTrajExactSpinParticle& aParticle, double& aValue) override;
void Check(const KSTrajExactSpinParticle& anInitialParticle, const KSTrajExactSpinParticle& aFinalParticle,
const KSTrajExactSpinError& anError, bool& aFlag) override;
void Calculate(const KSTrajAdiabaticSpinParticle& aParticle, double& aValue) override;
void Check(const KSTrajAdiabaticSpinParticle& anInitialParticle, const KSTrajAdiabaticSpinParticle& aFinalParticle,
const KSTrajAdiabaticSpinError& anError, bool& aFlag) override;
void Calculate(const KSTrajAdiabaticParticle& aParticle, double& aValue) override;
void Check(const KSTrajAdiabaticParticle& anInitialParticle, const KSTrajAdiabaticParticle& aFinalParticle,
const KSTrajAdiabaticError& anError, bool& aFlag) override;
protected:
virtual void ActivateObject();
public:
void SetAbsolutePositionError(double error)
{
fAbsoluteError = error;
};
void SetSafetyFactor(double safety)
{
fSafetyFactor = safety;
};
void SetSolverOrder(double order)
{
fSolverOrder = order;
};
private:
bool UpdateTimeStep(double error);
static double fEpsilon;
double fAbsoluteError; //max allowable error on position magnitude per step
double fSafetyFactor; //safety factor for increasing/decreasing step size
double fSolverOrder; //order of the associated runge-kutta stepper
double fTimeStep;
bool fFirstStep;
};
} // namespace Kassiopeia
#endif
| 412 | 0.877495 | 1 | 0.877495 | game-dev | MEDIA | 0.318715 | game-dev | 0.759687 | 1 | 0.759687 |
chenee/cocos2dx-swf | 18,040 | TangooBaby/libs/cocos2dx/effects/CCGrid.cpp | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2009 On-Core
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "ccMacros.h"
#include "effects/CCGrid.h"
#include "CCDirector.h"
#include "effects/CCGrabber.h"
#include "support/ccUtils.h"
#include "shaders/CCGLProgram.h"
#include "shaders/CCShaderCache.h"
#include "shaders/ccGLStateCache.h"
#include "CCGL.h"
#include "support/CCPointExtension.h"
#include "support/TransformUtils.h"
#include "kazmath/kazmath.h"
#include "kazmath/GL/matrix.h"
NS_CC_BEGIN
// implementation of CCGridBase
CCGridBase* CCGridBase::create(const CCSize& gridSize)
{
CCGridBase *pGridBase = new CCGridBase();
if (pGridBase)
{
if (pGridBase->initWithSize(gridSize))
{
pGridBase->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(pGridBase);
}
}
return pGridBase;
}
CCGridBase* CCGridBase::create(const CCSize& gridSize, CCTexture2D *texture, bool flipped)
{
CCGridBase *pGridBase = new CCGridBase();
if (pGridBase)
{
if (pGridBase->initWithSize(gridSize, texture, flipped))
{
pGridBase->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(pGridBase);
}
}
return pGridBase;
}
bool CCGridBase::initWithSize(const CCSize& gridSize, CCTexture2D *pTexture, bool bFlipped)
{
bool bRet = true;
m_bActive = false;
m_nReuseGrid = 0;
m_sGridSize = gridSize;
m_pTexture = pTexture;
CC_SAFE_RETAIN(m_pTexture);
m_bIsTextureFlipped = bFlipped;
CCSize texSize = m_pTexture->getContentSize();
m_obStep.x = texSize.width / m_sGridSize.width;
m_obStep.y = texSize.height / m_sGridSize.height;
m_pGrabber = new CCGrabber();
if (m_pGrabber)
{
m_pGrabber->grab(m_pTexture);
}
else
{
bRet = false;
}
m_pShaderProgram = CCShaderCache::sharedShaderCache()->programForKey(kCCShader_PositionTexture);
calculateVertexPoints();
return bRet;
}
bool CCGridBase::initWithSize(const CCSize& gridSize)
{
CCDirector *pDirector = CCDirector::sharedDirector();
CCSize s = pDirector->getWinSizeInPixels();
unsigned long POTWide = ccNextPOT((unsigned int)s.width);
unsigned long POTHigh = ccNextPOT((unsigned int)s.height);
// we only use rgba8888
CCTexture2DPixelFormat format = kCCTexture2DPixelFormat_RGBA8888;
void *data = calloc((int)(POTWide * POTHigh * 4), 1);
if (! data)
{
CCLOG("cocos2d: CCGrid: not enough memory.");
this->release();
return false;
}
CCTexture2D *pTexture = new CCTexture2D();
pTexture->initWithData(data, format, POTWide, POTHigh, s);
free(data);
if (! pTexture)
{
CCLOG("cocos2d: CCGrid: error creating texture");
return false;
}
initWithSize(gridSize, pTexture, false);
pTexture->release();
return true;
}
CCGridBase::~CCGridBase(void)
{
CCLOGINFO("cocos2d: deallocing %p", this);
//TODO: ? why 2.0 comments this line setActive(false);
CC_SAFE_RELEASE(m_pTexture);
CC_SAFE_RELEASE(m_pGrabber);
}
// properties
void CCGridBase::setActive(bool bActive)
{
m_bActive = bActive;
if (! bActive)
{
CCDirector *pDirector = CCDirector::sharedDirector();
ccDirectorProjection proj = pDirector->getProjection();
pDirector->setProjection(proj);
}
}
void CCGridBase::setTextureFlipped(bool bFlipped)
{
if (m_bIsTextureFlipped != bFlipped)
{
m_bIsTextureFlipped = bFlipped;
calculateVertexPoints();
}
}
void CCGridBase::set2DProjection()
{
CCDirector *director = CCDirector::sharedDirector();
CCSize size = director->getWinSizeInPixels();
glViewport(0, 0, (GLsizei)(size.width * CC_CONTENT_SCALE_FACTOR()), (GLsizei)(size.height * CC_CONTENT_SCALE_FACTOR()) );
kmGLMatrixMode(KM_GL_PROJECTION);
kmGLLoadIdentity();
kmMat4 orthoMatrix;
kmMat4OrthographicProjection(&orthoMatrix, 0, size.width * CC_CONTENT_SCALE_FACTOR(), 0, size.height * CC_CONTENT_SCALE_FACTOR(), -1, 1);
kmGLMultMatrix( &orthoMatrix );
kmGLMatrixMode(KM_GL_MODELVIEW);
kmGLLoadIdentity();
ccSetProjectionMatrixDirty();
}
void CCGridBase::beforeDraw(void)
{
// save projection
CCDirector *director = CCDirector::sharedDirector();
m_directorProjection = director->getProjection();
// 2d projection
// [director setProjection:kCCDirectorProjection2D];
set2DProjection();
m_pGrabber->beforeRender(m_pTexture);
}
void CCGridBase::afterDraw(cocos2d::CCNode *pTarget)
{
m_pGrabber->afterRender(m_pTexture);
// restore projection
CCDirector *director = CCDirector::sharedDirector();
director->setProjection(m_directorProjection);
if (pTarget->getCamera()->isDirty())
{
CCPoint offset = pTarget->getAnchorPointInPoints();
//
// XXX: Camera should be applied in the AnchorPoint
//
kmGLTranslatef(offset.x, offset.y, 0);
pTarget->getCamera()->locate();
kmGLTranslatef(-offset.x, -offset.y, 0);
}
ccGLBindTexture2D(m_pTexture->getName());
// restore projection for default FBO .fixed bug #543 #544
//TODO: CCDirector::sharedDirector()->setProjection(CCDirector::sharedDirector()->getProjection());
//TODO: CCDirector::sharedDirector()->applyOrientation();
blit();
}
void CCGridBase::blit(void)
{
CCAssert(0, "");
}
void CCGridBase::reuse(void)
{
CCAssert(0, "");
}
void CCGridBase::calculateVertexPoints(void)
{
CCAssert(0, "");
}
// implementation of CCGrid3D
CCGrid3D* CCGrid3D::create(const CCSize& gridSize, CCTexture2D *pTexture, bool bFlipped)
{
CCGrid3D *pRet= new CCGrid3D();
if (pRet)
{
if (pRet->initWithSize(gridSize, pTexture, bFlipped))
{
pRet->autorelease();
}
else
{
delete pRet;
pRet = NULL;
}
}
return pRet;
}
CCGrid3D* CCGrid3D::create(const CCSize& gridSize)
{
CCGrid3D *pRet= new CCGrid3D();
if (pRet)
{
if (pRet->initWithSize(gridSize))
{
pRet->autorelease();
}
else
{
delete pRet;
pRet = NULL;
}
}
return pRet;
}
CCGrid3D::CCGrid3D()
: m_pTexCoordinates(NULL)
, m_pVertices(NULL)
, m_pOriginalVertices(NULL)
, m_pIndices(NULL)
{
}
CCGrid3D::~CCGrid3D(void)
{
CC_SAFE_FREE(m_pTexCoordinates);
CC_SAFE_FREE(m_pVertices);
CC_SAFE_FREE(m_pIndices);
CC_SAFE_FREE(m_pOriginalVertices);
}
void CCGrid3D::blit(void)
{
int n = m_sGridSize.width * m_sGridSize.height;
ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position | kCCVertexAttribFlag_TexCoords );
m_pShaderProgram->use();
m_pShaderProgram->setUniformsForBuiltins();;
//
// Attributes
//
// position
glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, 0, m_pVertices);
// texCoords
glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, m_pTexCoordinates);
glDrawElements(GL_TRIANGLES, (GLsizei) n*6, GL_UNSIGNED_SHORT, m_pIndices);
CC_INCREMENT_GL_DRAWS(1);
}
void CCGrid3D::calculateVertexPoints(void)
{
float width = (float)m_pTexture->getPixelsWide();
float height = (float)m_pTexture->getPixelsHigh();
float imageH = m_pTexture->getContentSizeInPixels().height;
int x, y, i;
CC_SAFE_FREE(m_pVertices);
CC_SAFE_FREE(m_pOriginalVertices);
CC_SAFE_FREE(m_pTexCoordinates);
CC_SAFE_FREE(m_pIndices);
unsigned int numOfPoints = (m_sGridSize.width+1) * (m_sGridSize.height+1);
m_pVertices = malloc(numOfPoints * sizeof(ccVertex3F));
m_pOriginalVertices = malloc(numOfPoints * sizeof(ccVertex3F));
m_pTexCoordinates = malloc(numOfPoints * sizeof(ccVertex2F));
m_pIndices = (GLushort*)malloc(m_sGridSize.width * m_sGridSize.height * sizeof(GLushort) * 6);
GLfloat *vertArray = (GLfloat*)m_pVertices;
GLfloat *texArray = (GLfloat*)m_pTexCoordinates;
GLushort *idxArray = m_pIndices;
for (x = 0; x < m_sGridSize.width; ++x)
{
for (y = 0; y < m_sGridSize.height; ++y)
{
int idx = (y * m_sGridSize.width) + x;
GLfloat x1 = x * m_obStep.x;
GLfloat x2 = x1 + m_obStep.x;
GLfloat y1 = y * m_obStep.y;
GLfloat y2= y1 + m_obStep.y;
GLushort a = (GLushort)(x * (m_sGridSize.height + 1) + y);
GLushort b = (GLushort)((x + 1) * (m_sGridSize.height + 1) + y);
GLushort c = (GLushort)((x + 1) * (m_sGridSize.height + 1) + (y + 1));
GLushort d = (GLushort)(x * (m_sGridSize.height + 1) + (y + 1));
GLushort tempidx[6] = {a, b, d, b, c, d};
memcpy(&idxArray[6*idx], tempidx, 6*sizeof(GLushort));
int l1[4] = {a*3, b*3, c*3, d*3};
ccVertex3F e = {x1, y1, 0};
ccVertex3F f = {x2, y1, 0};
ccVertex3F g = {x2, y2, 0};
ccVertex3F h = {x1, y2, 0};
ccVertex3F l2[4] = {e, f, g, h};
int tex1[4] = {a*2, b*2, c*2, d*2};
CCPoint tex2[4] = {ccp(x1, y1), ccp(x2, y1), ccp(x2, y2), ccp(x1, y2)};
for (i = 0; i < 4; ++i)
{
vertArray[l1[i]] = l2[i].x;
vertArray[l1[i] + 1] = l2[i].y;
vertArray[l1[i] + 2] = l2[i].z;
texArray[tex1[i]] = tex2[i].x / width;
if (m_bIsTextureFlipped)
{
texArray[tex1[i] + 1] = (imageH - tex2[i].y) / height;
}
else
{
texArray[tex1[i] + 1] = tex2[i].y / height;
}
}
}
}
memcpy(m_pOriginalVertices, m_pVertices, (m_sGridSize.width+1) * (m_sGridSize.height+1) * sizeof(ccVertex3F));
}
ccVertex3F CCGrid3D::vertex(const CCPoint& pos)
{
CCAssert( pos.x == (unsigned int)pos.x && pos.y == (unsigned int) pos.y , "Numbers must be integers");
int index = (pos.x * (m_sGridSize.height+1) + pos.y) * 3;
float *vertArray = (float*)m_pVertices;
ccVertex3F vert = {vertArray[index], vertArray[index+1], vertArray[index+2]};
return vert;
}
ccVertex3F CCGrid3D::originalVertex(const CCPoint& pos)
{
CCAssert( pos.x == (unsigned int)pos.x && pos.y == (unsigned int) pos.y , "Numbers must be integers");
int index = (pos.x * (m_sGridSize.height+1) + pos.y) * 3;
float *vertArray = (float*)m_pOriginalVertices;
ccVertex3F vert = {vertArray[index], vertArray[index+1], vertArray[index+2]};
return vert;
}
void CCGrid3D::setVertex(const CCPoint& pos, const ccVertex3F& vertex)
{
CCAssert( pos.x == (unsigned int)pos.x && pos.y == (unsigned int) pos.y , "Numbers must be integers");
int index = (pos.x * (m_sGridSize.height + 1) + pos.y) * 3;
float *vertArray = (float*)m_pVertices;
vertArray[index] = vertex.x;
vertArray[index+1] = vertex.y;
vertArray[index+2] = vertex.z;
}
void CCGrid3D::reuse(void)
{
if (m_nReuseGrid > 0)
{
memcpy(m_pOriginalVertices, m_pVertices, (m_sGridSize.width+1) * (m_sGridSize.height+1) * sizeof(ccVertex3F));
--m_nReuseGrid;
}
}
// implementation of CCTiledGrid3D
CCTiledGrid3D::CCTiledGrid3D()
: m_pTexCoordinates(NULL)
, m_pVertices(NULL)
, m_pOriginalVertices(NULL)
, m_pIndices(NULL)
{
}
CCTiledGrid3D::~CCTiledGrid3D(void)
{
CC_SAFE_FREE(m_pTexCoordinates);
CC_SAFE_FREE(m_pVertices);
CC_SAFE_FREE(m_pOriginalVertices);
CC_SAFE_FREE(m_pIndices);
}
CCTiledGrid3D* CCTiledGrid3D::create(const CCSize& gridSize, CCTexture2D *pTexture, bool bFlipped)
{
CCTiledGrid3D *pRet= new CCTiledGrid3D();
if (pRet)
{
if (pRet->initWithSize(gridSize, pTexture, bFlipped))
{
pRet->autorelease();
}
else
{
delete pRet;
pRet = NULL;
}
}
return pRet;
}
CCTiledGrid3D* CCTiledGrid3D::create(const CCSize& gridSize)
{
CCTiledGrid3D *pRet= new CCTiledGrid3D();
if (pRet)
{
if (pRet->initWithSize(gridSize))
{
pRet->autorelease();
}
else
{
delete pRet;
pRet = NULL;
}
}
return pRet;
}
void CCTiledGrid3D::blit(void)
{
int n = m_sGridSize.width * m_sGridSize.height;
m_pShaderProgram->use();
m_pShaderProgram->setUniformsForBuiltins();
//
// Attributes
//
ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position | kCCVertexAttribFlag_TexCoords );
// position
glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, 0, m_pVertices);
// texCoords
glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, m_pTexCoordinates);
glDrawElements(GL_TRIANGLES, (GLsizei)n*6, GL_UNSIGNED_SHORT, m_pIndices);
CC_INCREMENT_GL_DRAWS(1);
}
void CCTiledGrid3D::calculateVertexPoints(void)
{
float width = (float)m_pTexture->getPixelsWide();
float height = (float)m_pTexture->getPixelsHigh();
float imageH = m_pTexture->getContentSizeInPixels().height;
int numQuads = m_sGridSize.width * m_sGridSize.height;
CC_SAFE_FREE(m_pVertices);
CC_SAFE_FREE(m_pOriginalVertices);
CC_SAFE_FREE(m_pTexCoordinates);
CC_SAFE_FREE(m_pIndices);
m_pVertices = malloc(numQuads*4*sizeof(ccVertex3F));
m_pOriginalVertices = malloc(numQuads*4*sizeof(ccVertex3F));
m_pTexCoordinates = malloc(numQuads*4*sizeof(ccVertex2F));
m_pIndices = (GLushort*)malloc(numQuads*6*sizeof(GLushort));
GLfloat *vertArray = (GLfloat*)m_pVertices;
GLfloat *texArray = (GLfloat*)m_pTexCoordinates;
GLushort *idxArray = m_pIndices;
int x, y;
for( x = 0; x < m_sGridSize.width; x++ )
{
for( y = 0; y < m_sGridSize.height; y++ )
{
float x1 = x * m_obStep.x;
float x2 = x1 + m_obStep.x;
float y1 = y * m_obStep.y;
float y2 = y1 + m_obStep.y;
*vertArray++ = x1;
*vertArray++ = y1;
*vertArray++ = 0;
*vertArray++ = x2;
*vertArray++ = y1;
*vertArray++ = 0;
*vertArray++ = x1;
*vertArray++ = y2;
*vertArray++ = 0;
*vertArray++ = x2;
*vertArray++ = y2;
*vertArray++ = 0;
float newY1 = y1;
float newY2 = y2;
if (m_bIsTextureFlipped)
{
newY1 = imageH - y1;
newY2 = imageH - y2;
}
*texArray++ = x1 / width;
*texArray++ = newY1 / height;
*texArray++ = x2 / width;
*texArray++ = newY1 / height;
*texArray++ = x1 / width;
*texArray++ = newY2 / height;
*texArray++ = x2 / width;
*texArray++ = newY2 / height;
}
}
for (x = 0; x < numQuads; x++)
{
idxArray[x*6+0] = (GLushort)(x * 4 + 0);
idxArray[x*6+1] = (GLushort)(x * 4 + 1);
idxArray[x*6+2] = (GLushort)(x * 4 + 2);
idxArray[x*6+3] = (GLushort)(x * 4 + 1);
idxArray[x*6+4] = (GLushort)(x * 4 + 2);
idxArray[x*6+5] = (GLushort)(x * 4 + 3);
}
memcpy(m_pOriginalVertices, m_pVertices, numQuads * 12 * sizeof(GLfloat));
}
void CCTiledGrid3D::setTile(const CCPoint& pos, const ccQuad3& coords)
{
CCAssert( pos.x == (unsigned int)pos.x && pos.y == (unsigned int) pos.y , "Numbers must be integers");
int idx = (m_sGridSize.height * pos.x + pos.y) * 4 * 3;
float *vertArray = (float*)m_pVertices;
memcpy(&vertArray[idx], &coords, sizeof(ccQuad3));
}
ccQuad3 CCTiledGrid3D::originalTile(const CCPoint& pos)
{
CCAssert( pos.x == (unsigned int)pos.x && pos.y == (unsigned int) pos.y , "Numbers must be integers");
int idx = (m_sGridSize.height * pos.x + pos.y) * 4 * 3;
float *vertArray = (float*)m_pOriginalVertices;
ccQuad3 ret;
memcpy(&ret, &vertArray[idx], sizeof(ccQuad3));
return ret;
}
ccQuad3 CCTiledGrid3D::tile(const CCPoint& pos)
{
CCAssert( pos.x == (unsigned int)pos.x && pos.y == (unsigned int) pos.y , "Numbers must be integers");
int idx = (m_sGridSize.height * pos.x + pos.y) * 4 * 3;
float *vertArray = (float*)m_pVertices;
ccQuad3 ret;
memcpy(&ret, &vertArray[idx], sizeof(ccQuad3));
return ret;
}
void CCTiledGrid3D::reuse(void)
{
if (m_nReuseGrid > 0)
{
int numQuads = m_sGridSize.width * m_sGridSize.height;
memcpy(m_pOriginalVertices, m_pVertices, numQuads * 12 * sizeof(GLfloat));
--m_nReuseGrid;
}
}
NS_CC_END
| 412 | 0.975339 | 1 | 0.975339 | game-dev | MEDIA | 0.460348 | game-dev,graphics-rendering | 0.971177 | 1 | 0.971177 |
exciting/exciting | 1,573 | src/src_gw/clean_gndstate.f90 |
subroutine clean_gndstate
use modmain
!if (allocated()) deallocate()
!----------------
! init0
!----------------
if (allocated(rhomt)) deallocate(rhomt)
if (allocated(rhoir)) deallocate(rhoir)
if (allocated(magmt)) deallocate(magmt)
if (allocated(magir)) deallocate(magir)
if (allocated(vclmt)) deallocate(vclmt)
if (allocated(vclir)) deallocate(vclir)
if (allocated(vxcmt)) deallocate(vxcmt)
if (allocated(vxcir)) deallocate(vxcir)
if (allocated(bxcmt)) deallocate(bxcmt)
if (allocated(bxcir)) deallocate(bxcir)
if (allocated(exmt)) deallocate(exmt)
if (allocated(exir)) deallocate(exir)
if (allocated(ecmt)) deallocate(ecmt)
if (allocated(ecir)) deallocate(ecir)
if (allocated(veffmt)) deallocate(veffmt)
if (allocated(veffir)) deallocate(veffir)
if (allocated(veffig)) deallocate(veffig)
if (allocated(chgmt)) deallocate(chgmt)
if (allocated(mommt)) deallocate(mommt)
if (allocated(forcehf)) deallocate(forcehf)
if (allocated(forcecr)) deallocate(forcecr)
if (allocated(forceibs)) deallocate(forceibs)
!----------------
! init1
!----------------
if (allocated(apwe)) deallocate(apwe)
if (allocated(lorbe)) deallocate(lorbe)
if (allocated(oalo)) deallocate(oalo)
if (allocated(ololo)) deallocate(ololo)
if (allocated(haa)) deallocate(haa)
if (allocated(hloa)) deallocate(hloa)
if (allocated(hlolo)) deallocate (hlolo)
if (allocated(gntyry)) deallocate (gntyry)
end subroutine
| 412 | 0.678056 | 1 | 0.678056 | game-dev | MEDIA | 0.385056 | game-dev | 0.956126 | 1 | 0.956126 |
Dimbreath/AzurLaneData | 1,251 | ko-KR/controller/command/ship/buildshipcommand.lua | slot0 = class("BuildShipCommand", pm.SimpleCommand)
function slot0.execute(slot0, slot1)
slot2 = slot1:getBody()
slot5, slot6, slot7 = BuildShip.canBuildShipByBuildId(slot2.buildId, slot2.count or 1)
if not slot5 then
if slot7 then
GoShoppingMsgBox(i18n("switch_to_shop_tip_1"), ChargeScene.TYPE_ITEM, slot7)
else
pg.TipsMgr.GetInstance():ShowTips(slot6)
end
return
end
pg.ConnectionMgr.GetInstance():Send(12002, {
id = slot3,
count = slot4
}, 12003, function (slot0)
if slot0.result == 0 then
pg.TrackerMgr.GetInstance():Tracking(TRACKING_BUILD_SHIP, uv0)
slot1 = pg.ship_data_create_material[uv1]
getProxy(BagProxy):removeItemById(slot1.use_item, slot1.number_1 * uv0)
slot3 = getProxy(PlayerProxy)
slot4 = slot3:getData()
slot9 = uv0
slot4:consume({
gold = slot1.use_gold * slot9
})
slot3:updatePlayer(slot4)
for slot9, slot10 in ipairs(slot0.build_info) do
getProxy(BuildShipProxy):addBuildShip(BuildShip.New(slot10))
end
uv2:sendNotification(GAME.BUILD_SHIP_DONE)
pg.TipsMgr.GetInstance():ShowTips(i18n("ship_buildShipMediator_startBuild"))
else
pg.TipsMgr.GetInstance():ShowTips(errorTip("ship_buildShip_error", slot0.result))
end
end)
end
return slot0
| 412 | 0.627959 | 1 | 0.627959 | game-dev | MEDIA | 0.59501 | game-dev | 0.893859 | 1 | 0.893859 |
ThePaperLuigi/The-Stars-Above | 4,459 | Projectiles/Celestial/BlackSilence/MookHeldBlade.cs | ο»Ώ
using Microsoft.Xna.Framework;
using StarsAbove.Buffs.Celestial.BlackSilence;
using StarsAbove.Systems.WeaponSystems;
using System;
using Terraria;
using Terraria.Audio;
using Terraria.Localization;
using Terraria.ModLoader;
using static Terraria.ModLoader.ModContent;
namespace StarsAbove.Projectiles.Celestial.BlackSilence
{
public class MookHeldBlade : ModProjectile
{
public override void SetStaticDefaults()
{
// DisplayName.SetDefault("Gloves of the Black Silence");
}
public override void SetDefaults()
{
AIType = 0;
Projectile.width = 70;
Projectile.height = 170;
Projectile.minion = false;
Projectile.minionSlots = 0f;
Projectile.timeLeft = 60;
Projectile.penetrate = -1;
Projectile.hide = false;
Projectile.alpha = 0;
Projectile.netImportant = true;
Projectile.ignoreWater = true;
Projectile.tileCollide = false;
DrawOriginOffsetY = 30;
}
bool firstSpawn = true;
int newOffsetY;
float spawnProgress;
bool dustSpawn = true;
float rotationStrength = 0.1f;
double deg;
bool startSound = true;
bool endSound = false;
public override bool PreAI()
{
Player player = Main.player[Projectile.owner];
return true;
}
public override void AI()
{
Player projOwner = Main.player[Projectile.owner];
Projectile.scale = 0.7f;
if (firstSpawn)
{
firstSpawn = false;
}
//projOwner.heldProj = Projectile.whoAmI;//The projectile draws in front of the player.
if (Projectile.spriteDirection == 1)
{//Adjust when facing the other direction
Projectile.ai[1] = 180;
}
else
{
Projectile.ai[1] = 359;
}
deg = Projectile.ai[1];
double rad = deg * (Math.PI / 180);
double dist = 16;
/*Position the player based on where the player is, the Sin/Cos of the angle times the /
/distance for the desired distance away from the player minus the projectile's width /
/and height divided by two so the center of the projectile is at the right place. */
Projectile.position.X = projOwner.Center.X - (int)(Math.Cos(rad) * dist) - Projectile.width / 2;
Projectile.position.Y = projOwner.Center.Y - (int)(Math.Sin(rad) * dist) - Projectile.height / 2;
Projectile.rotation -= 0.03f;
if (projOwner.dead && !projOwner.active || !projOwner.GetModPlayer<BlackSilencePlayer>().BlackSilenceHeld || !projOwner.HasBuff(BuffType<BlackSilenceAttackCooldown>()))
{//Disappear when player dies
//Projectile.Kill();
}
if (projOwner.GetModPlayer<BlackSilencePlayer>().chosenWeapon != 5)
{
//Projectile.Kill();
}
//Arms will hold the weapon.
projOwner.SetCompositeArmBack(true, Player.CompositeArmStretchAmount.Full, (projOwner.Center -
new Vector2(Projectile.Center.X + projOwner.velocity.X * 0.05f, Projectile.Center.Y + projOwner.velocity.Y * 0.05f)
).ToRotation() + MathHelper.PiOver2);
Projectile.alpha -= 40;
//Projectile.timeLeft = 10;//The prjoectile doesn't time out.
//Orient projectile
Projectile.direction = projOwner.direction;
Projectile.spriteDirection = Projectile.direction;
//Projectile.rotation += projOwner.velocity.X * 0.05f; //Rotate in the direction of the user when moving
//Cap alpha
/*if (Projectile.alpha < 0)
{
Projectile.alpha = 0;
}
if (Projectile.alpha > 255)
{
Projectile.alpha = 255;
}*/
if (spawnProgress > 1f)
{
spawnProgress = 1f;
}
if (spawnProgress < 0f)
{
spawnProgress = 0f;
}//Capping variables (there is 100% a better way to do this!)
}
private void Visuals()
{
}
public override void OnKill(int timeLeft)
{
}
}
}
| 412 | 0.806768 | 1 | 0.806768 | game-dev | MEDIA | 0.993379 | game-dev | 0.98559 | 1 | 0.98559 |
nativeapptemplate/NativeAppTemplate-Free-iOS | 2,887 | NativeAppTemplateTests/Testing/Repositories/TestItemTagRepository.swift | //
// TestItemTagRepository.swift
// NativeAppTemplate
//
// Created by Claude on 2025/06/22.
//
import Foundation
@testable import NativeAppTemplate
@MainActor
final class TestItemTagRepository: ItemTagRepositoryProtocol {
var itemTags: [ItemTag] = []
var state: DataState = .initial
var isEmpty: Bool { itemTags.isEmpty }
// A test-only
var error: NativeAppTemplateAPIError?
required init(itemTagsService: ItemTagsService) {
}
func findBy(id: String) -> ItemTag {
guard let itemTag = itemTags.first(where: { $0.id == id }) else {
fatalError("Test setup error: ItemTag with id '\(id)' not found. Available IDs: \(itemTags.map { $0.id })")
}
return itemTag
}
func reload(shopId: String) {
guard error == nil else {
state = .failed
return
}
state = .loading
state = .hasData
}
func fetchAll(shopId: String) async throws -> [ItemTag] {
guard error == nil else {
state = .failed
throw error!
}
return itemTags
}
func fetchDetail(id: String) async throws -> ItemTag {
guard error == nil else {
state = .failed
throw error!
}
guard let itemTag = itemTags.first(where: { $0.id == id }) else {
throw NativeAppTemplateAPIError.requestFailed(nil, 404, "ItemTag with id '\(id)' not found")
}
return itemTag
}
func create(shopId: String, itemTag: ItemTag) async throws -> ItemTag {
guard error == nil else {
state = .failed
throw error!
}
itemTags.append(itemTag)
return itemTag
}
func update(id: String, itemTag: ItemTag) async throws -> ItemTag {
guard error == nil else {
state = .failed
throw error!
}
if let index = itemTags.firstIndex(where: { $0.id == id }) {
itemTags[index] = itemTag
}
return itemTag
}
func destroy(id: String) async throws {
guard error == nil else {
state = .failed
throw error!
}
itemTags.removeAll { $0.id == id }
}
func complete(id: String) async throws -> ItemTag {
guard error == nil else {
state = .failed
throw error!
}
var itemTag = findBy(id: id)
let wasAlreadyCompleted = itemTag.alreadyCompleted
itemTag.state = .completed
itemTag.completedAt = Date()
_ = try await update(id: id, itemTag: itemTag)
// Preserve the alreadyCompleted flag for testing
itemTag.alreadyCompleted = wasAlreadyCompleted
return itemTag
}
func reset(id: String) async throws -> ItemTag {
guard error == nil else {
state = .failed
throw error!
}
var itemTag = findBy(id: id)
itemTag.state = .idled
itemTag.scanState = .unscanned
itemTag.completedAt = nil
_ = try await update(id: id, itemTag: itemTag)
return itemTag
}
// A test-only
func setItemTags(itemTags: [ItemTag]) {
self.itemTags = itemTags
}
}
| 412 | 0.967207 | 1 | 0.967207 | game-dev | MEDIA | 0.251216 | game-dev | 0.901644 | 1 | 0.901644 |
skyteks/WarKingdoms | 2,130 | Assets/Scripts/Movement/MovementNavigationAIPath.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
public class MovementNavigationAIPath : MovementNavigation
{
private static AstarPath aStarPath;
private static bool searchedForMesh;
private Pathfinding.Seeker seeker;
private Pathfinding.AIPath pathAI;
public override Vector3 velocity
{
get
{
return pathAI.velocity;
}
}
public override Vector3 destination
{
get
{
return pathAI.destination;
}
}
public override bool isOnMesh
{
get
{
return true;
}
}
public override bool hasPath
{
get
{
return pathAI.hasPath;
}
}
public override bool pathPending
{
get
{
return pathAI.pathPending;
}
}
public override bool isStopped
{
get
{
return pathAI.isStopped;
}
set
{
pathAI.isStopped = value;
}
}
public override float stoppingDistance
{
get
{
return pathAI.endReachedDistance;
}
set
{
pathAI.endReachedDistance = value;
}
}
protected override void Awake()
{
seeker = GetComponent<Pathfinding.Seeker>();
seeker?.SetEnabled(false);
pathAI = GetComponent<Pathfinding.AIPath>();
pathAI?.SetEnabled(false);
if (!searchedForMesh && aStarPath == null)
{
aStarPath = FindObjectOfType<AstarPath>();
searchedForMesh = true;
if (aStarPath != null)
{
aStarPath.showGraphs = true;
}
}
}
protected override void OnEnable()
{
seeker.enabled = true;
pathAI.enabled = true;
}
protected override void OnDisable()
{
seeker?.SetEnabled(false);
pathAI?.SetEnabled(false);
}
public override void SetDestination(Vector3 position)
{
pathAI.destination = position;
}
}
*/ | 412 | 0.647 | 1 | 0.647 | game-dev | MEDIA | 0.977198 | game-dev | 0.705448 | 1 | 0.705448 |
OvercastNetwork/SportBukkit | 1,359 | snapshot/Bukkit/src/main/java/org/bukkit/command/defaults/PluginsCommand.java | package org.bukkit.command.defaults;
import java.util.Arrays;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
public class PluginsCommand extends BukkitCommand {
public PluginsCommand(String name) {
super(name);
this.description = "Gets a list of plugins running on the server";
this.usageMessage = "/plugins";
this.setPermission("bukkit.command.plugins");
this.setAliases(Arrays.asList("pl"));
}
@Override
public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender)) return true;
sender.sendMessage("Plugins " + getPluginList());
return true;
}
private String getPluginList() {
StringBuilder pluginList = new StringBuilder();
Plugin[] plugins = Bukkit.getPluginManager().getPlugins();
for (Plugin plugin : plugins) {
if (pluginList.length() > 0) {
pluginList.append(ChatColor.WHITE);
pluginList.append(", ");
}
pluginList.append(plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED);
pluginList.append(plugin.getDescription().getName());
}
return "(" + plugins.length + "): " + pluginList.toString();
}
}
| 412 | 0.611065 | 1 | 0.611065 | game-dev | MEDIA | 0.910949 | game-dev | 0.659129 | 1 | 0.659129 |
bakanaouji/cpp-cfr | 2,536 | Game/Kuhn/Game.hpp | //
// Copyright (c) 2020 Kenshi Abe
//
#ifndef GAME_GAME_HPP
#define GAME_GAME_HPP
#include <array>
#include <random>
#include <string>
#include "Constant.hpp"
namespace Kuhn {
/// @class Game
/// @brief Kuhn poker
class Game {
public:
/// @param engine Mersenne Twister pseudo-random generator
explicit Game(std::mt19937 &engine);
/// @brief Copy constructor
/// @param obj source game
Game(const Game &obj);
/// @brief Get the name of this game
/// @return name of game
static std::string name();
/// @brief Get the number of players
/// @return number of players
static int playerNum();
/// @brief reset and start new game
/// @param skipChanceAction whether to sample an action of the chance player.
/// If this argument is set to false, `step` function is called recursively until
/// the acting player becomes a player other than the chance player.
void reset(bool skipChanceAction = true);
/// @brief transition current node to the next node
/// @param action action
void step(int action);
/// @brief Get the payoff of the specified player
/// @param playerIndex index of the player
/// @return payoff
double payoff(int playerIndex) const;
/// @brief Get the information set string representation
/// @return string representation of the current information set
std::string infoSetStr() const;
/// @brief Check whether the game is over
/// @return if the game is over, `true` is returned
bool done() const;
/// @brief Get the number of available actions at the current information set
/// @return number of available actions
int actionNum() const;
/// @brief Get the index of the acting player
/// @return index of acting player
int currentPlayer() const;
/// @brief Get the likelihood that the last action is chosen by the chance player
/// @return likelihood
double chanceProbability() const;
/// @brief Check whether the current acting player is the chance player
/// @return if the acting player is the chance player, `true` is returned
bool isChanceNode() const;
private:
std::mt19937 &mEngine;
std::array<int, CardNum> mCards;
std::array<double, PlayerNum> mPayoff;
int mCurrentPlayer;
double mChanceProbability;
int mFirstBetTurn;
int mBetPlayerNum;
int mTurnNum;
bool mDone;
uint8_t mInfoSets[PlayerNum][10];
};
} // namespace
#endif //GAME_GAME_HPP
| 412 | 0.789735 | 1 | 0.789735 | game-dev | MEDIA | 0.799078 | game-dev | 0.723721 | 1 | 0.723721 |
Gethe/wow-ui-source | 14,984 | Interface/AddOns/Blizzard_AuctionHouseUI/Shared/Blizzard_AuctionHouseSellFrame.lua |
AuctionHouseSellFrameAlignedControlMixin = {};
function AuctionHouseSellFrameAlignedControlMixin:OnLoad()
self:SetLabel(self.labelText);
end
function AuctionHouseSellFrameAlignedControlMixin:SetLabel(text)
self.Label:SetText(text or "");
self.LabelTitle:SetText(text or "");
end
function AuctionHouseSellFrameAlignedControlMixin:SetSubtext(text)
self.Subtext:SetText(text);
local hasSubtext = text ~= nil;
self.Label:SetShown(not hasSubtext);
self.LabelTitle:SetShown(hasSubtext);
self.Subtext:SetShown(hasSubtext);
end
function AuctionHouseSellFrameAlignedControlMixin:SetLabelColor(color)
self.Label:SetTextColor(color:GetRGB());
self.LabelTitle:SetTextColor(color:GetRGB());
end
AuctionHouseAlignedQuantityInputBoxMixin = {};
function AuctionHouseAlignedQuantityInputBoxMixin:OnEditFocusLost()
EditBox_ClearHighlight(self);
if self:GetNumber() < 1 then
self:Reset();
local inputChangedCallback = self:GetInputChangedCallback();
if inputChangedCallback then
inputChangedCallback();
end
end
end
function AuctionHouseAlignedQuantityInputBoxMixin:SetNextEditBox(nextEditBox)
self.nextEditBox = nextEditBox;
if nextEditBox then
nextEditBox.previousEditBox = self;
end
end
AuctionHouseQuantityInputMaxButtonMixin = {};
function AuctionHouseQuantityInputMaxButtonMixin:OnClick()
self:GetParent():GetParent():SetToMaxQuantity();
PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON);
end
AuctionHouseAlignedQuantityInputFrameMixin = {};
function AuctionHouseAlignedQuantityInputFrameMixin:GetQuantity()
return self.InputBox:GetNumber();
end
function AuctionHouseAlignedQuantityInputFrameMixin:SetQuantity(quantity)
self.InputBox:SetNumber(quantity);
end
function AuctionHouseAlignedQuantityInputFrameMixin:SetInputChangedCallback(callback)
self.InputBox:SetInputChangedCallback(callback);
end
function AuctionHouseAlignedQuantityInputFrameMixin:Reset()
self.InputBox:Reset();
end
function AuctionHouseAlignedQuantityInputFrameMixin:SetNextEditBox(nextEditBox)
self.InputBox:SetNextEditBox(nextEditBox);
end
AuctionHouseAlignedPriceInputFrameMixin = {};
function AuctionHouseAlignedPriceInputFrameMixin:OnLoad()
AuctionHouseSellFrameAlignedControlMixin.OnLoad(self);
if (C_AuctionHouse.SupportsCopperValues()) then
self.PerItemPostfix:ClearAllPoints();
self.PerItemPostfix:SetPoint("RIGHT", self.MoneyInputFrame, "LEFT", -20, -10);
end
end
function AuctionHouseAlignedPriceInputFrameMixin:SetNextEditBox(nextEditBox)
self.MoneyInputFrame:SetNextEditBox(nextEditBox);
end
function AuctionHouseAlignedPriceInputFrameMixin:Clear()
self.MoneyInputFrame:Clear();
end
function AuctionHouseAlignedPriceInputFrameMixin:SetAmount(amount)
if amount == 0 then
self.MoneyInputFrame:Clear();
else
self.MoneyInputFrame:SetAmount(amount);
end
end
function AuctionHouseAlignedPriceInputFrameMixin:GetAmount()
return self.MoneyInputFrame:GetAmount();
end
function AuctionHouseAlignedPriceInputFrameMixin:SetOnValueChangedCallback(callback)
return self.MoneyInputFrame:SetOnValueChangedCallback(callback);
end
function AuctionHouseAlignedPriceInputFrameMixin:SetErrorTooltip(tooltip)
self.PriceError:SetTooltip(tooltip);
end
function AuctionHouseAlignedPriceInputFrameMixin:SetErrorShown(shown)
self.PriceError:SetShown(shown);
end
AuctionHousePriceErrorFrameMixin = {};
function AuctionHousePriceErrorFrameMixin:OnEnter()
if self.tooltip then
GameTooltip:SetOwner(self, "ANCHOR_RIGHT");
local wrap = true;
GameTooltip_AddColoredLine(GameTooltip, self.tooltip, RED_FONT_COLOR, wrap);
GameTooltip:Show();
end
end
function AuctionHousePriceErrorFrameMixin:OnLeave()
GameTooltip_Hide();
end
function AuctionHousePriceErrorFrameMixin:SetTooltip(tooltip)
self.tooltip = tooltip;
end
AuctionHouseAlignedDurationMixin = {};
function AuctionHouseAlignedDurationMixin:OnLoad()
AuctionHouseSellFrameAlignedControlMixin.OnLoad(self);
local function IsSelected(index)
return self:GetDuration() == index;
end
local function SetSelected(index)
self:SetDuration(index);
end
self.Dropdown:SetWidth(115);
self.Dropdown.Text:SetFontObject("Number12Font");
self.Dropdown.Text:SetJustifyH("RIGHT");
self.Dropdown:SetupMenu(function(region, rootDescription)
rootDescription:SetTag("MENU_AUCTION_HOUSE_DURATION");
for index, durationText in ipairs({AUCTION_DURATION_ONE, AUCTION_DURATION_TWO, AUCTION_DURATION_THREE}) do
local radio = rootDescription:CreateRadio(durationText, IsSelected, SetSelected, index);
radio:AddInitializer(function(button, description, menu)
button.fontString:SetFontObject("Number12Font");
end);
end
end);
end
function AuctionHouseAlignedDurationMixin:OnShow()
if self.durationIndex == nil then
self.durationIndex = tonumber(GetCVar("auctionHouseDurationDropdown"));
end
self.Dropdown:GenerateMenu();
end
function AuctionHouseAlignedDurationMixin:GetDuration()
return self.durationIndex or tonumber(GetCVar("auctionHouseDurationDropdown"));
end
function AuctionHouseAlignedDurationMixin:SetDuration(index)
self.durationIndex = index;
SetCVar("auctionHouseDurationDropdown", index);
self:GetParent():OnDurationUpdated();
end
AuctionHouseAlignedPriceDisplayMixin = {};
function AuctionHouseAlignedPriceDisplayMixin:GetAmount(amount)
return self.MoneyDisplayFrame:GetAmount();
end
function AuctionHouseAlignedPriceDisplayMixin:SetAmount(amount)
self.MoneyDisplayFrame:SetAmount(amount);
end
AuctionHouseSellFramePostButtonMixin = {};
function AuctionHouseSellFramePostButtonMixin:OnClick()
self:GetParent():PostItem();
PlaySound(SOUNDKIT.LOOT_WINDOW_COIN_SOUND);
end
function AuctionHouseSellFramePostButtonMixin:OnEnter()
if self.tooltip then
GameTooltip:SetOwner(self, "ANCHOR_RIGHT");
local wrap = true;
GameTooltip_AddColoredLine(GameTooltip, self.tooltip, RED_FONT_COLOR, wrap);
GameTooltip:Show();
end
end
function AuctionHouseSellFramePostButtonMixin:OnLeave()
GameTooltip_Hide();
end
function AuctionHouseSellFramePostButtonMixin:SetTooltip(tooltip)
self.tooltip = tooltip;
end
AuctionHouseSellFrameOverlayMixin = {};
function AuctionHouseSellFrameOverlayMixin:OnEnter()
self:GetParent():OnOverlayEnter();
end
function AuctionHouseSellFrameOverlayMixin:OnLeave()
self:GetParent():OnOverlayLeave();
end
function AuctionHouseSellFrameOverlayMixin:OnClick()
self:GetParent():OnOverlayClick();
end
function AuctionHouseSellFrameOverlayMixin:OnReceiveDrag()
self:GetParent():OnOverlayReceiveDrag();
end
AuctionHouseSellFrameItemDisplayMixin = {};
function AuctionHouseSellFrameItemDisplayMixin:OnLoad()
AuctionHouseInteractableItemDisplayMixin.OnLoad(self);
self.NineSlice:Hide();
end
AuctionHouseSellFrameMixin = CreateFromMixins(AuctionHouseSortOrderSystemMixin);
local AUCTION_HOUSE_SELL_FRAME_EVENTS = {
"CURSOR_CHANGED",
"AUCTION_HOUSE_THROTTLED_SYSTEM_READY",
"AUCTION_HOUSE_THROTTLED_MESSAGE_SENT",
}
function AuctionHouseSellFrameMixin:OnLoad()
AuctionHouseBackgroundMixin.OnLoad(self);
AuctionHouseSortOrderSystemMixin.OnLoad(self);
self.ItemDisplay:SetAuctionHouseFrame(self:GetAuctionHouseFrame());
self.ItemDisplay:SetOnItemChangedCallback(function(item)
if item == nil then
local fromItemDisplay = true;
self:SetItem(item, fromItemDisplay);
else
self:GetAuctionHouseFrame():SetPostItem(item);
end
end);
self.ItemDisplay:SetItemValidationFunction(function(itemDisplay)
local itemLocation = itemDisplay:GetItemLocation();
return itemLocation == nil or C_AuctionHouse.IsSellItemValid(itemLocation);
end);
self.ItemDisplay.ItemButton.Highlight:ClearAllPoints();
self.ItemDisplay.ItemButton.Highlight:SetPoint("TOPLEFT", self.ItemDisplay.ItemButton, "TOPLEFT");
self.ItemDisplay.ItemButton.Highlight:SetPoint("BOTTOMRIGHT", self.ItemDisplay.ItemButton, "BOTTOMRIGHT");
self.QuantityInput:SetInputChangedCallback(function()
local maxQuantity = self:GetMaxQuantity();
if self.QuantityInput:GetQuantity() > maxQuantity then
self.QuantityInput:SetQuantity(maxQuantity);
end
self:UpdatePostState();
end);
self.PriceInput:SetOnValueChangedCallback(function()
self:UpdatePostState();
end);
self:UpdateFocusTabbing();
end
function AuctionHouseSellFrameMixin:OnShow()
FrameUtil.RegisterFrameForEvents(self, AUCTION_HOUSE_SELL_FRAME_EVENTS);
self.fixedWidth = self:GetWidth();
self.fixedHeight = self:GetHeight();
self:Layout();
end
function AuctionHouseSellFrameMixin:OnHide()
FrameUtil.UnregisterFrameForEvents(self, AUCTION_HOUSE_SELL_FRAME_EVENTS);
end
function AuctionHouseSellFrameMixin:OnEvent(event, ...)
if event == "CURSOR_CHANGED" then
if self.Overlay:IsMouseOver() then
self:OnOverlayEnter();
end
elseif event == "AUCTION_HOUSE_THROTTLED_SYSTEM_READY" or event == "AUCTION_HOUSE_THROTTLED_MESSAGE_SENT" then
self:UpdatePostButtonState();
end
end
function AuctionHouseSellFrameMixin:SetSearchResultPrice(searchResultPrice)
self.searchResultPrice = searchResultPrice;
end
function AuctionHouseSellFrameMixin:ClearSearchResultPrice()
self.searchResultPrice = nil;
end
function AuctionHouseSellFrameMixin:GetSearchResultPrice()
return self.searchResultPrice;
end
function AuctionHouseSellFrameMixin:UpdatePostState()
self:UpdateDeposit();
self:UpdateTotalPrice();
self:UpdatePostButtonState();
local quantity = self.QuantityInput:GetQuantity();
self.QuantityInput.MaxButton:SetEnabled(quantity < self:GetMaxQuantity());
local price = self.PriceInput:GetAmount();
local searchResultPrice = self:GetSearchResultPrice();
if searchResultPrice and price == (searchResultPrice - COPPER_PER_SILVER) then
self:ShowHelpTip();
else
self:HideHelpTip();
end
end
function AuctionHouseSellFrameMixin:UpdateFocusTabbing()
self.QuantityInput:SetNextEditBox(self.PriceInput.MoneyInputFrame.GoldBox);
self.PriceInput:SetNextEditBox(self.QuantityInput:IsShown() and self.QuantityInput.InputBox or nil);
end
function AuctionHouseSellFrameMixin:OnDurationUpdated()
self:UpdatePostState();
end
function AuctionHouseSellFrameMixin:SetToMaxQuantity()
self.QuantityInput:SetQuantity(self:GetMaxQuantity());
self:UpdatePostState();
end
function AuctionHouseSellFrameMixin:GetMaxQuantity()
local itemLocation = self.ItemDisplay:GetItemLocation();
return itemLocation and C_AuctionHouse.GetAvailablePostCount(itemLocation) or 1;
end
function AuctionHouseSellFrameMixin:SetItem(itemLocation, fromItemDisplay)
if itemLocation ~= nil then
if not C_AuctionHouse.IsSellItemValid(itemLocation) then
return false;
end
end
local itemKey = itemLocation and C_AuctionHouse.GetItemKeyFromItem(itemLocation);
local itemKeyInfo = itemKey and C_AuctionHouse.GetItemKeyInfo(itemKey);
self.ItemDisplay:SetItemLevelShown(itemKeyInfo and itemKeyInfo.isEquipment);
self.itemLocation = itemLocation;
if not fromItemDisplay then
local skipCallback = true;
self.ItemDisplay:SetItemLocation(itemLocation, skipCallback);
end
self.QuantityInput:Reset();
self.PriceInput:SetAmount(self:GetDefaultPrice());
self:UpdatePostState();
local showQuantity = self:GetMaxQuantity() > 1;
self.QuantityInput:SetShown(showQuantity);
-- Hack fix for a spacing problem: Without this line, the edit box would be scrolled to
-- the left and the text would not be visible. This seems to be a problem with setting
-- the text on the edit box and showing it in the same frame.
self.QuantityInput.InputBox:SetCursorPosition(0);
self:MarkDirty();
self:UpdateFocusTabbing();
return true;
end
function AuctionHouseSellFrameMixin:GetItem()
return self.itemLocation;
end
function AuctionHouseSellFrameMixin:GetDefaultPrice()
if (not C_AuctionHouse.ShouldAutoPopulatePrice() ) then
return 0;
end
local itemLocation = self:GetItem();
if itemLocation and itemLocation:IsValid() then
local itemLink = C_Item.GetItemLink(itemLocation);
local defaultPrice = COPPER_PER_SILVER;
if LinkUtil.IsLinkType(itemLink, "item") then
local vendorPrice = select(11, C_Item.GetItemInfo(itemLink));
defaultPrice = vendorPrice ~= nil and (vendorPrice * Constants.AuctionConstants.DEFAULT_AUCTION_PRICE_MULTIPLIER) or COPPER_PER_SILVER;
defaultPrice = defaultPrice + (COPPER_PER_SILVER - (defaultPrice % COPPER_PER_SILVER)); -- AH prices must be in silver increments.
end
return math.max(defaultPrice, COPPER_PER_SILVER);
end
return COPPER_PER_SILVER;
end
function AuctionHouseSellFrameMixin:GetDuration()
return self.Duration:GetDuration();
end
function AuctionHouseSellFrameMixin:GetQuantity()
return self.QuantityInput:GetQuantity();
end
function AuctionHouseSellFrameMixin:OnOverlayEnter()
local item = C_Cursor.GetCursorItem();
if item then
self.ItemDisplay:SetHighlightLocked(true);
end
end
function AuctionHouseSellFrameMixin:OnOverlayLeave()
self.ItemDisplay:SetHighlightLocked(false);
end
function AuctionHouseSellFrameMixin:OnOverlayClick()
local item = C_Cursor.GetCursorItem();
if item then
self.ItemDisplay:SwitchItemWithCursor();
end
end
function AuctionHouseSellFrameMixin:OnOverlayReceiveDrag()
self:OnOverlayClick();
end
function AuctionHouseSellFrameMixin:UpdatePostButtonState()
local canPostItem, reasonTooltip = self:CanPostItem();
self.PostButton:SetEnabled(canPostItem);
self.PostButton:SetTooltip(reasonTooltip);
end
function AuctionHouseSellFrameMixin:CanPostItem()
local item = self:GetItem();
if item == nil or not item:IsValid() then
return false, AUCTION_HOUSE_SELL_FRAME_ERROR_ITEM;
end
local hasEnoughMoneyForDeposit = GetMoney() >= self:GetDepositAmount();
if not hasEnoughMoneyForDeposit then
return false, AUCTION_HOUSE_SELL_FRAME_ERROR_DEPOSIT;
end
local quantity = self:GetQuantity();
if quantity < 1 then
return false, AUCTION_HOUSE_SELL_FRAME_ERROR_QUANTITY;
end
if not C_AuctionHouse.IsThrottledMessageSystemReady() then
return false, ERR_GENERIC_THROTTLE;
end
return true, nil;
end
function AuctionHouseSellFrameMixin:UpdateDeposit()
local depositCost = self:GetDepositAmount();
if ( not C_AuctionHouse.SupportsCopperValues() ) then
depositCost = math.ceil(depositCost / COPPER_PER_SILVER) * COPPER_PER_SILVER;
end
self.Deposit:SetAmount(depositCost);
end
function AuctionHouseSellFrameMixin:UpdateTotalPrice()
self.TotalPrice:SetAmount(self:GetTotalPrice());
end
function AuctionHouseSellFrameMixin:ShowHelpTip()
local helpTipInfo = {
text = AUCTION_HOUSE_UNDERCUT_TUTORIAL,
buttonStyle = HelpTip.ButtonStyle.GotIt,
targetPoint = HelpTip.Point.RightEdgeCenter,
alignment = HelpTip.Alignment.CENTER,
offsetX = -6,
offsetY = 2,
};
HelpTip:Show(self, helpTipInfo, self.PriceInput.MoneyInputFrame);
end
function AuctionHouseSellFrameMixin:HideHelpTip()
HelpTip:Acknowledge(self, AUCTION_HOUSE_UNDERCUT_TUTORIAL);
end
function AuctionHouseSellFrameMixin:GetDepositAmount()
-- Implement in your derived mixin.
end
function AuctionHouseSellFrameMixin:GetTotalPrice()
-- Implement in your derived mixin.
end
function AuctionHouseSellFrameMixin:PostItem()
-- Implement in your derived mixin.
end | 412 | 0.78334 | 1 | 0.78334 | game-dev | MEDIA | 0.983031 | game-dev | 0.844314 | 1 | 0.844314 |
saltyfishyjk/BUAA-Compiler | 1,631 | exam/mid-term/src/frontend/parser/expression/unaryexp/UnaryExpFuncParser.java | package frontend.parser.expression.unaryexp;
import frontend.lexer.Token;
import frontend.lexer.TokenListIterator;
import frontend.lexer.TokenType;
import frontend.parser.expression.FuncRParams;
import frontend.parser.expression.FuncRParamsParser;
import frontend.parser.terminal.Ident;
import frontend.parser.terminal.IdentParser;
public class UnaryExpFuncParser {
private TokenListIterator iterator;
/* UnaryExpFunc Attributes */
private Ident ident = null;
private FuncRParams funcRParams = null;
private Token leftParent; // '('
private Token rightParent; // ')'
private UnaryExpFunc unaryExpFunc = null;
public UnaryExpFuncParser(TokenListIterator iterator) {
this.iterator = iterator;
}
public UnaryExpFunc parseUnaryFuncExp() {
IdentParser identParser = new IdentParser(this.iterator);
this.ident = identParser.parseIdent();
this.leftParent = this.iterator.readNextToken();
this.rightParent = this.iterator.readNextToken();
if (!this.rightParent.getType().equals(TokenType.RPARENT)) {
this.iterator.unReadToken(1);
FuncRParamsParser funcRParamsParser = new FuncRParamsParser(this.iterator);
this.funcRParams = funcRParamsParser.parseFuncRParams();
this.rightParent = this.iterator.readNextToken();
unaryExpFunc = new UnaryExpFunc(this.ident, this.funcRParams,
this.leftParent, this.rightParent);
} else {
unaryExpFunc = new UnaryExpFunc(this.ident, this.leftParent, this.rightParent);
}
return unaryExpFunc;
}
}
| 412 | 0.71708 | 1 | 0.71708 | game-dev | MEDIA | 0.618214 | game-dev | 0.64541 | 1 | 0.64541 |
tdouguo/KIT | 2,376 | kit-unity/Common/UnityExtend/UI/Selectable/Tab.cs | ο»Ώ// ----------------------------------------------------------------------------------------------------
// Copyright Β© Guo jin ming. All rights reserved.
// Homepage: https://kylin.app/
// E-Mail: kevin@kylin.app
// ----------------------------------------------------------------------------------------------------
using UnityEngine;
using UnityEngine.UI;
namespace Kit
{
public class Tab : Selectable
{
public bool isOn;
public GameObject targetPage;
public TabGroup tabPageGroup;
public GameObject selectBackground;
protected override void Awake()
{
UGUIEventListener.Get(gameObject).onClick += delegate { SelectThis(); };
}
protected override void Start()
{
Init();
}
public void SelectThis()
{
if (!this.Equals(tabPageGroup.currentSelectTab))
{
isOn = true;
if (targetPage)
targetPage.SetActive(true);
if (selectBackground)
selectBackground.SetActive(true);
if (tabPageGroup.currentSelectTab)
{
tabPageGroup.currentSelectTab.isOn = false;
if (tabPageGroup.currentSelectTab.selectBackground)
tabPageGroup.currentSelectTab.selectBackground.SetActive(false);
}
if (tabPageGroup.currentActivityPage)
tabPageGroup.currentActivityPage.SetActive(false);
tabPageGroup.currentSelectTab = this;
tabPageGroup.currentActivityPage = targetPage;
}
}
void Init()
{
if (isOn)
{
if (targetPage)
targetPage.SetActive(true);
if (selectBackground)
selectBackground.SetActive(true);
if (tabPageGroup)
{
tabPageGroup.currentSelectTab = this;
tabPageGroup.currentActivityPage = targetPage;
}
}
else
{
if (targetPage)
targetPage.SetActive(false);
if (selectBackground)
selectBackground.SetActive(false);
}
}
}
}
| 412 | 0.862269 | 1 | 0.862269 | game-dev | MEDIA | 0.85554 | game-dev | 0.864272 | 1 | 0.864272 |
herobrine99dan/NESS-Reloaded | 2,574 | src/main/java/com/github/ness/check/movement/fly/FlyInvalidJumpMotion.java | package com.github.ness.check.movement.fly;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerMoveEvent;
import com.github.ness.NessPlayer;
import com.github.ness.check.CheckInfos;
import com.github.ness.check.ListeningCheck;
import com.github.ness.check.ListeningCheckFactory;
import com.github.ness.check.ListeningCheckInfo;
import com.github.ness.data.MovementValues;
import com.github.ness.data.MovementValuesHelper;
import com.github.ness.data.PlayerAction;
import com.github.ness.utility.Utility;
public class FlyInvalidJumpMotion extends ListeningCheck<PlayerMoveEvent> {
public static final ListeningCheckInfo<PlayerMoveEvent> checkInfo = CheckInfos.forEvent(PlayerMoveEvent.class);
public FlyInvalidJumpMotion(ListeningCheckFactory<?, PlayerMoveEvent> factory, NessPlayer player) {
super(factory, player);
}
@Override
protected void checkEvent(PlayerMoveEvent event) {
Player player = event.getPlayer();
double yDiff = event.getTo().getY() - event.getFrom().getY();
NessPlayer nessPlayer = this.player();
MovementValues movementValues = nessPlayer.getMovementValues();
if (movementValues.isNearLiquid() || movementValues.hasBlockNearHead()
|| movementValues.isNearMaterials("SNOW", "VINE", "LADDER")
|| isBlockUpperHeadOnGround(event.getTo()) || isBlockUpperHeadOnGround(event.getFrom())
|| movementValues.isAroundNonOccludingBlocks() || movementValues.getHelper().hasflybypass(nessPlayer)) {
return;
}
if (yDiff > 0 && !Utility.hasVehicleNear(player)) {
if (player.getVelocity().getY() == 0.42f
&& !movementValues.getHelper().isMathematicallyOnGround(event.getTo().getY())
&& movementValues.getHelper().isMathematicallyOnGround(event.getFrom().getY())) {
double yResult = Math.abs(yDiff - player.getVelocity().getY());
if (yResult != 0.0 && nessPlayer.milliSecondTimeDifference(PlayerAction.VELOCITY) > 1700) {
flag(" yResult: " + yResult + " yDiff: " + yDiff);
}
}
}
}
private boolean isBlockUpperHeadOnGround(Location loc) {
MovementValuesHelper helper = this.player().getMovementValues().getHelper();
if (helper.isBlockConsideredOnGround(loc.clone().add(0, 1.9, 0))) {
return true; // little optimization
}
for (double x = -0.29; x <= 0.29; x += 0.29) {
for (double z = -0.29; z <= 0.29; z += 0.29) {
if (helper.isBlockConsideredOnGround(loc.clone().add(x, 1.9, z))) {
return true;
}
}
}
return false;
}
}
| 412 | 0.957752 | 1 | 0.957752 | game-dev | MEDIA | 0.667326 | game-dev | 0.975509 | 1 | 0.975509 |
DruidMech/UE4-CPP-Shooter-Series | 4,679 | Source Code Per Lesson/Section 9 - Ammo Pickups/135 Overriding SetItemProperties/ShooterAnimInstance.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "ShooterAnimInstance.h"
#include "ShooterCharacter.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "Kismet/KismetMathLibrary.h"
UShooterAnimInstance::UShooterAnimInstance() :
Speed(0.f),
bIsInAir(false),
bIsAccelerating(false),
MovementOffsetYaw(0.f),
LastMovementOffsetYaw(0.f),
bAiming(false),
CharacterRotation(FRotator(0.f)),
CharacterRotationLastFrame(FRotator(0.f)),
TIPCharacterYaw(0.f),
TIPCharacterYawLastFrame(0.f),
YawDelta(0.f),
RootYawOffset(0.f),
Pitch(0.f),
bReloading(false),
OffsetState(EOffsetState::EOS_Hip),
RecoilWeight(1.0f)
{
}
void UShooterAnimInstance::UpdateAnimationProperties(float DeltaTime)
{
if (ShooterCharacter == nullptr)
{
ShooterCharacter = Cast<AShooterCharacter>(TryGetPawnOwner());
}
if (ShooterCharacter)
{
bCrouching = ShooterCharacter->GetCrouching();
bReloading = ShooterCharacter->GetCombatState() == ECombatState::ECS_Reloading;
// Get the lateral speed of the character from velocity
FVector Velocity{ ShooterCharacter->GetVelocity() };
Velocity.Z = 0;
Speed = Velocity.Size();
// Is the character in the air?
bIsInAir = ShooterCharacter->GetCharacterMovement()->IsFalling();
// Is the character accelerating?
if (ShooterCharacter->GetCharacterMovement()->GetCurrentAcceleration().Size() > 0.f)
{
bIsAccelerating = true;
}
else
{
bIsAccelerating = false;
}
FRotator AimRotation = ShooterCharacter->GetBaseAimRotation();
FRotator MovementRotation =
UKismetMathLibrary::MakeRotFromX(
ShooterCharacter->GetVelocity());
MovementOffsetYaw = UKismetMathLibrary::NormalizedDeltaRotator(
MovementRotation,
AimRotation).Yaw;
if (ShooterCharacter->GetVelocity().Size() > 0.f)
{
LastMovementOffsetYaw = MovementOffsetYaw;
}
bAiming = ShooterCharacter->GetAiming();
if (bReloading)
{
OffsetState = EOffsetState::EOS_Reloading;
}
else if (bIsInAir)
{
OffsetState = EOffsetState::EOS_InAir;
}
else if (ShooterCharacter->GetAiming())
{
OffsetState = EOffsetState::EOS_Aiming;
}
else
{
OffsetState = EOffsetState::EOS_Hip;
}
}
TurnInPlace();
Lean(DeltaTime);
}
void UShooterAnimInstance::NativeInitializeAnimation()
{
ShooterCharacter = Cast<AShooterCharacter>(TryGetPawnOwner());
}
void UShooterAnimInstance::TurnInPlace()
{
if (ShooterCharacter == nullptr) return;
Pitch = ShooterCharacter->GetBaseAimRotation().Pitch;
if (Speed > 0 || bIsInAir)
{
// Don't want to turn in place; Character is moving
RootYawOffset = 0.f;
TIPCharacterYaw = ShooterCharacter->GetActorRotation().Yaw;
TIPCharacterYawLastFrame = TIPCharacterYaw;
RotationCurveLastFrame = 0.f;
RotationCurve = 0.f;
}
else
{
TIPCharacterYawLastFrame = TIPCharacterYaw;
TIPCharacterYaw = ShooterCharacter->GetActorRotation().Yaw;
const float TIPYawDelta{ TIPCharacterYaw - TIPCharacterYawLastFrame };
// Root Yaw Offset, updated and clamped to [-180, 180]
RootYawOffset = UKismetMathLibrary::NormalizeAxis(RootYawOffset - TIPYawDelta);
// 1.0 if turning, 0.0 if not
const float Turning{ GetCurveValue(TEXT("Turning")) };
if (Turning > 0)
{
RotationCurveLastFrame = RotationCurve;
RotationCurve = GetCurveValue(TEXT("Rotation"));
const float DeltaRotation{ RotationCurve - RotationCurveLastFrame };
// RootYawOffset > 0, -> Turning Left. RootYawOffset < 0, -> Turning Right.
RootYawOffset > 0 ? RootYawOffset -= DeltaRotation : RootYawOffset += DeltaRotation;
const float ABSRootYawOffset{ FMath::Abs(RootYawOffset) };
if (ABSRootYawOffset > 90.f)
{
const float YawExcess{ ABSRootYawOffset - 90.f };
RootYawOffset > 0 ? RootYawOffset -= YawExcess : RootYawOffset += YawExcess;
}
}
}
if (bTurningInPlace)
{
if (bReloading)
{
RecoilWeight = 1.f;
}
else
{
RecoilWeight = 0.f;
}
}
else // not turning in place
{
if (bCrouching)
{
if (bReloading)
{
RecoilWeight = 1.f;
}
else
{
RecoilWeight = 0.1f;
}
}
else
{
if (bAiming)
{
RecoilWeight = 1.f;
}
else
{
RecoilWeight = 0.5f;
}
}
}
}
void UShooterAnimInstance::Lean(float DeltaTime)
{
if (ShooterCharacter == nullptr) return;
CharacterRotationLastFrame = CharacterRotation;
CharacterRotation = ShooterCharacter->GetActorRotation();
const FRotator Delta{ UKismetMathLibrary::NormalizedDeltaRotator(CharacterRotation, CharacterRotationLastFrame) };
const float Target{ Delta.Yaw / DeltaTime };
const float Interp{ FMath::FInterpTo(YawDelta, Target, DeltaTime, 6.f) };
YawDelta = FMath::Clamp(Interp, -90.f, 90.f);
}
| 412 | 0.90525 | 1 | 0.90525 | game-dev | MEDIA | 0.968643 | game-dev | 0.975682 | 1 | 0.975682 |
OpenNos/OpenNos | 40,504 | OpenNos.Handler/GuriPacketHandler.cs | ο»Ώusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenNos.Core;
using OpenNos.Data;
using OpenNos.DAL;
using OpenNos.Domain;
using OpenNos.GameObject;
using OpenNos.GameObject.Event;
using OpenNos.GameObject.Helpers;
namespace OpenNos.Handler
{
class GuriPacketHandler : IPacketHandler
{
#region Instantiation
public GuriPacketHandler(ClientSession session)
{
Session = session;
}
#endregion
#region Properties
private ClientSession Session { get; }
#endregion
#region Methods
/// <summary>
/// guri packet
/// </summary>
/// <param name="guriPacket"></param>
public void Guri(GuriPacket guriPacket)
{
if (guriPacket == null)
{
return;
}
if (guriPacket.Type == 10 && guriPacket.Data >= 973 && guriPacket.Data <= 999 && !Session.Character.EmoticonsBlocked)
{
if (guriPacket.User != null && Convert.ToInt64(guriPacket.User.Value) == Session.Character.CharacterId)
{
Session.CurrentMapInstance?.Broadcast(Session, Session.Character.GenerateEff(guriPacket.Data + 4099), ReceiverType.AllNoEmoBlocked);
}
else
{
Mate mate = Session.Character.Mates.FirstOrDefault(s => guriPacket.User != null && s.MateTransportId == Convert.ToInt32(guriPacket.User.Value));
if (mate != null)
{
Session.CurrentMapInstance?.Broadcast(Session, mate.GenerateEff(guriPacket.Data + 4099), ReceiverType.AllNoEmoBlocked);
}
}
}
else
{
switch (guriPacket.Type)
{
// SHELL IDENTIFYING
case 204:
if (guriPacket.User == null)
{
// WRONG PACKET
return;
}
InventoryType inventoryType = (InventoryType) guriPacket.Argument;
ItemInstance pearls = Session.Character.Inventory.FirstOrDefault(s => s.Value.ItemVNum == 1429).Value;
WearableInstance shell = (WearableInstance) Session.Character.Inventory.LoadBySlotAndType((short) guriPacket.User.Value, inventoryType);
if (pearls == null)
{
// USING PACKET LOGGER
return;
}
if (shell.EquipmentOptions.Any())
{
// ALREADY IDENTIFIED
Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("SHELL_ALREADY_IDENTIFIED"), 0));
return;
}
if (!ShellGeneratorHelper.Instance.ShellTypes.TryGetValue(shell.ItemVNum, out byte shellType))
{
// SHELL TYPE NOT IMPLEMENTED
return;
}
if (shellType != 8 && shellType != 9)
{
if (shell.Upgrade < 50 || shell.Upgrade > 90)
{
return;
}
}
if (shellType == 8 || shellType == 9)
{
switch (shell.Upgrade)
{
case 25:
case 30:
case 40:
case 55:
case 60:
case 65:
case 70:
case 75:
case 80:
case 85:
break;
default:
Session.Character.Inventory.RemoveItemAmountFromInventory(1, shell.Id);
Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("STOP_SPAWNING_BROKEN_SHELL"), 0));
return;
}
}
int perlsNeeded = shell.Upgrade / 10 + shell.Rare;
if (Session.Character.Inventory.CountItem(pearls.ItemVNum) < perlsNeeded)
{
// NOT ENOUGH PEARLS
return;
}
List<EquipmentOptionDTO> shellOptions = ShellGeneratorHelper.Instance.GenerateShell(shellType, shell.Rare, shell.Upgrade);
if (!shellOptions.Any())
{
Session.Character.Inventory.RemoveItemAmountFromInventory(1, shell.Id);
Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("STOP_SPAWNING_BROKEN_SHELL"), 0));
return;
}
shell.EquipmentOptions.AddRange(shellOptions);
Session.Character.Inventory.RemoveItemAmount(pearls.ItemVNum, perlsNeeded);
Session.CurrentMapInstance?.Broadcast(Session, Session.Character.GenerateEff(3006));
Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("SHELL_IDENTIFIED"), 0));
break;
case 205:
if (guriPacket.User == null)
{
return;
}
const int perfumeVnum = 1428;
InventoryType perfumeInventoryType = (InventoryType) guriPacket.Argument;
WearableInstance eq = (WearableInstance) Session.Character.Inventory.LoadBySlotAndType((short) guriPacket.User.Value, perfumeInventoryType);
if (eq.BoundCharacterId == Session.Character.CharacterId)
{
// ALREADY YOURS
return;
}
if (eq.ShellRarity == null)
{
// NO SHELL APPLIED
return;
}
int perfumesNeeded = ShellGeneratorHelper.Instance.PerfumeFromItemLevelAndShellRarity(eq.Item.LevelMinimum, (byte) eq.ShellRarity.Value);
if (Session.Character.Inventory.CountItem(perfumeVnum) < perfumesNeeded)
{
// NOT ENOUGH PEARLS
return;
}
Session.Character.Inventory.RemoveItemAmount(perfumeVnum, perfumesNeeded);
eq.BoundCharacterId = Session.Character.CharacterId;
break;
case 300:
if (guriPacket.Argument == 8023)
{
if (guriPacket.User == null)
{
return;
}
short slot = (short) guriPacket.User.Value;
ItemInstance box = Session.Character.Inventory.LoadBySlotAndType<BoxInstance>(slot, InventoryType.Equipment);
if (box != null)
{
if (guriPacket.Data > 0)
{
box.Item.Use(Session, ref box, 1, new[] {guriPacket.Data.ToString()});
}
else
{
box.Item.Use(Session, ref box, 1);
}
}
}
break;
case 501:
if (ServerManager.Instance.IceBreakerInWaiting && IceBreaker.Map.Sessions.Count() < IceBreaker.MaxAllowedPlayers)
{
ServerManager.Instance.TeleportOnRandomPlaceInMap(Session, IceBreaker.Map.MapInstanceId);
}
break;
case 502:
long? charid = guriPacket.User;
if (charid == null)
{
return;
}
ClientSession target = ServerManager.Instance.GetSessionByCharacterId(charid.Value);
IceBreaker.FrozenPlayers.Remove(target);
IceBreaker.AlreadyFrozenPlayers.Add(target);
target?.CurrentMapInstance?.Broadcast(
UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("ICEBREAKER_PLAYER_UNFROZEN"), target.Character?.Name), 0));
break;
case 506:
if (ServerManager.Instance.EventInWaiting)
{
Session.Character.IsWaitingForEvent = true;
}
break;
default:
if (guriPacket.Type == 199 && guriPacket.Argument == 2)
{
short[] listWingOfFriendship = {2160, 2312, 10048};
short vnumToUse = -1;
foreach (short vnum in listWingOfFriendship)
{
if (Session.Character.Inventory.CountItem(vnum) > 0)
{
vnumToUse = vnum;
}
}
if (vnumToUse != -1)
{
if (guriPacket.User == null)
{
return;
}
if (!long.TryParse(guriPacket.User.Value.ToString(), out long charId))
{
return;
}
ClientSession session = ServerManager.Instance.GetSessionByCharacterId(charId);
if (session != null)
{
if (Session.Character.IsFriendOfCharacter(charId))
{
if (session.CurrentMapInstance.MapInstanceType == MapInstanceType.BaseMapInstance)
{
if (Session.Character.MapInstance.MapInstanceType != MapInstanceType.BaseMapInstance)
{
Session.SendPacket(Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("CANT_USE_THAT"), 10));
return;
}
short mapy = session.Character.PositionY;
short mapx = session.Character.PositionX;
short mapId = session.Character.MapInstance.Map.MapId;
ServerManager.Instance.ChangeMap(Session.Character.CharacterId, mapId, mapx, mapy);
Session.Character.Inventory.RemoveItemAmount(vnumToUse);
}
else
{
if (Session.Character.MapInstance.MapInstanceType == MapInstanceType.Act4Instance && session.Character.Faction == Session.Character.Faction)
{
short mapy = session.Character.PositionY;
short mapx = session.Character.PositionX;
Guid mapId = session.CurrentMapInstance.MapInstanceId;
ServerManager.Instance.ChangeMapInstance(Session.Character.CharacterId, mapId, mapx, mapy);
Session.Character.Inventory.RemoveItemAmount(vnumToUse);
}
else
{
Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("USER_ON_INSTANCEMAP"), 0));
}
}
}
}
else
{
Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("USER_NOT_CONNECTED"), 0));
}
}
else
{
Session.SendPacket(Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("NO_WINGS"), 10));
}
}
else
{
switch (guriPacket.Type)
{
case 400:
if (guriPacket.Argument != 0)
{
if (!Session.HasCurrentMapInstance)
{
return;
}
MapNpc npc = Session.CurrentMapInstance.Npcs.FirstOrDefault(n => n.MapNpcId.Equals(guriPacket.Argument));
if (npc != null)
{
NpcMonster mapobject = ServerManager.Instance.GetNpc(npc.NpcVNum);
int rateDrop = ServerManager.Instance.DropRate;
int delay = (int) Math.Round((3 + mapobject.RespawnTime / 1000d) * Session.Character.TimesUsed);
delay = delay > 11 ? 8 : delay;
if (Session.Character.LastMapObject.AddSeconds(delay) < DateTime.Now)
{
if (mapobject.Drops.Any(s => s.MonsterVNum != null))
{
if (mapobject.VNumRequired > 10 && Session.Character.Inventory.CountItem(mapobject.VNumRequired) < mapobject.AmountRequired)
{
Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("NOT_ENOUGH_ITEM"), 0));
return;
}
}
Random random = new Random();
double randomAmount = ServerManager.Instance.RandomNumber() * random.NextDouble();
DropDTO drop = mapobject.Drops.FirstOrDefault(s => s.MonsterVNum == npc.NpcVNum);
if (drop != null)
{
if (npc.NpcVNum == 2004 && npc.IsOut == false)
{
ItemInstance newInv = Session.Character.Inventory.AddNewToInventory(drop.ItemVNum).FirstOrDefault();
if (newInv == null)
{
return;
}
Session.CurrentMapInstance.Broadcast(npc.GenerateOut());
Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(
string.Format(Language.Instance.GetMessageFromKey("RECEIVED_ITEM"), newInv.Item.Name), 0));
Session.SendPacket(Session.Character.GenerateSay(string.Format(Language.Instance.GetMessageFromKey("RECEIVED_ITEM"), newInv.Item.Name), 11));
return;
}
int dropChance = drop.DropChance;
if (randomAmount <= (double) dropChance * rateDrop / 5000.000)
{
short vnum = drop.ItemVNum;
ItemInstance newInv = Session.Character.Inventory.AddNewToInventory(vnum).FirstOrDefault();
Session.Character.LastMapObject = DateTime.Now;
Session.Character.TimesUsed++;
if (Session.Character.TimesUsed >= 4)
{
Session.Character.TimesUsed = 0;
}
if (newInv != null)
{
Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(
string.Format(Language.Instance.GetMessageFromKey("RECEIVED_ITEM"), newInv.Item.Name), 0));
Session.SendPacket(Session.Character.GenerateSay(string.Format(Language.Instance.GetMessageFromKey("RECEIVED_ITEM"), newInv.Item.Name),
11));
}
else
{
Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("NOT_ENOUGH_PLACE"), 0));
}
}
else
{
Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("TRY_FAILED"), 0));
}
}
}
else
{
Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(
string.Format(Language.Instance.GetMessageFromKey("TRY_FAILED_WAIT"),
(int) (Session.Character.LastMapObject.AddSeconds(delay) - DateTime.Now).TotalSeconds), 0));
}
}
}
break;
case 710:
if (guriPacket.Value != null)
{
// MapNpc npc = Session.CurrentMapInstance.Npcs.FirstOrDefault(n =>
// n.MapNpcId.Equals(Convert.ToInt16(guriPacket.Data)); NpcMonster mapObject
// = ServerManager.Instance.GetNpc(npc.NpcVNum); teleport free
}
break;
case 750:
if (!guriPacket.User.HasValue)
{
const short baseVnum = 1623;
if (short.TryParse(guriPacket.Argument.ToString(), out short faction))
{
if (Session.Character.Inventory.CountItem(baseVnum + faction) > 0)
{
Session.Character.Faction = (FactionType) faction;
Session.Character.Inventory.RemoveItemAmount(baseVnum + faction);
Session.SendPacket("scr 0 0 0 0 0 0 0");
Session.SendPacket(Session.Character.GenerateFaction());
Session.SendPacket(Session.Character.GenerateEff(4799 + faction));
Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey($"GET_PROTECTION_POWER_{faction}"), 0));
}
}
}
break;
case 2:
Session.CurrentMapInstance?.Broadcast(UserInterfaceHelper.Instance.GenerateGuri(2, 1, Session.Character.CharacterId), Session.Character.PositionX,
Session.Character.PositionY);
break;
case 4:
const int speakerVNum = 2173;
const int petnameVNum = 2157;
switch (guriPacket.Argument)
{
case 1:
Mate mate = Session.Character.Mates.FirstOrDefault(s => s.MateTransportId == guriPacket.Data);
if (guriPacket.Value.Length > 15)
{
Session.SendPacket(UserInterfaceHelper.Instance.GenerateInfo(Language.Instance.GetMessageFromKey("NEW_NAME_PET_MAX_LENGTH")));
return;
}
if (mate != null)
{
mate.Name = guriPacket.Value;
Session.CurrentMapInstance.Broadcast(mate.GenerateOut());
Session.CurrentMapInstance.Broadcast(mate.GenerateIn());
Session.SendPacket(UserInterfaceHelper.Instance.GenerateInfo(Language.Instance.GetMessageFromKey("NEW_NAME_PET")));
Session.SendPacket(Session.Character.GeneratePinit());
Session.SendPackets(Session.Character.GeneratePst());
Session.SendPackets(Session.Character.GenerateScP());
Session.Character.Inventory.RemoveItemAmount(petnameVNum);
}
break;
case 2:
int presentationVNum = Session.Character.Inventory.CountItem(1117) > 0 ? 1117 : (Session.Character.Inventory.CountItem(9013) > 0 ? 9013 : -1);
if (presentationVNum != -1)
{
string message = string.Empty;
// message = $" ";
string[] valuesplit = guriPacket.Value.Split(' ');
message = valuesplit.Aggregate(message, (current, t) => current + t + "^");
message = message.Substring(0, message.Length - 1); // Remove the last ^
message = message.Trim();
if (message.Length > 60)
{
message = message.Substring(0, 60);
}
Session.Character.Biography = message;
Session.SendPacket(Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("INTRODUCTION_SET"), 10));
Session.Character.Inventory.RemoveItemAmount(presentationVNum);
}
break;
case 3:
if (Session.Character.Inventory.CountItem(speakerVNum) > 0)
{
if (Session.Character == null || guriPacket.Value == null)
{
return;
}
string message = $"<{Language.Instance.GetMessageFromKey("SPEAKER")}> [{Session.Character.Name}]:";
string[] valuesplit = guriPacket.Value.Split(' ');
message = valuesplit.Aggregate(message, (current, t) => current + t + " ");
if (message.Length > 120)
{
message = message.Substring(0, 120);
}
message = message.Trim();
if (Session.Character.IsMuted())
{
Session.SendPacket(Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("SPEAKER_CANT_BE_USED"), 10));
return;
}
Session.Character.Inventory.RemoveItemAmount(speakerVNum);
ServerManager.Instance.Broadcast(Session.Character.GenerateSay(message, 13));
LogHelper.Instance.InsertChatLog(ChatType.Speaker, Session.Character.CharacterId, message, Session.IpAddress);
}
break;
}
// presentation message
// Speaker
break;
default:
if (guriPacket.Type == 199 && guriPacket.Argument == 1)
{
if (guriPacket.User != null && long.TryParse(guriPacket.User.Value.ToString(), out long charId))
{
if (!Session.Character.IsFriendOfCharacter(charId))
{
Session.SendPacket(Language.Instance.GetMessageFromKey("CHARACTER_NOT_IN_FRIENDLIST"));
return;
}
Session.SendPacket(UserInterfaceHelper.Instance.GenerateDelay(3000, 4, $"#guri^199^2^{guriPacket.User.Value}"));
}
}
else
{
switch (guriPacket.Type)
{
case 201:
if (Session.Character.StaticBonusList.Any(s => s.StaticBonusType == StaticBonusType.PetBasket))
{
Session.SendPacket(Session.Character.GenerateStashAll());
}
break;
case 202:
Session.SendPacket(Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("PARTNER_BACKPACK"), 10));
Session.SendPacket(Session.Character.GeneratePStashAll());
break;
default:
if (guriPacket.Type == 208 && guriPacket.Argument == 0)
{
if (guriPacket.User != null && short.TryParse(guriPacket.User.Value.ToString(), out short pearlSlot) &&
short.TryParse(guriPacket.Value, out short mountSlot))
{
ItemInstance mount = Session.Character.Inventory.LoadBySlotAndType<ItemInstance>(mountSlot, InventoryType.Main);
BoxInstance pearl = Session.Character.Inventory.LoadBySlotAndType<BoxInstance>(pearlSlot, InventoryType.Equipment);
if (mount != null && pearl != null)
{
pearl.HoldingVNum = mount.ItemVNum;
Session.Character.Inventory.RemoveItemAmountFromInventory(1, mount.Id);
}
}
}
else if (guriPacket.Type == 209 && guriPacket.Argument == 0)
{
if (guriPacket.User != null && short.TryParse(guriPacket.User.Value.ToString(), out short pearlSlot) &&
short.TryParse(guriPacket.Value, out short mountSlot))
{
WearableInstance fairy = Session.Character.Inventory.LoadBySlotAndType<WearableInstance>(mountSlot, InventoryType.Equipment);
BoxInstance pearl = Session.Character.Inventory.LoadBySlotAndType<BoxInstance>(pearlSlot, InventoryType.Equipment);
if (fairy != null && pearl != null)
{
pearl.HoldingVNum = fairy.ItemVNum;
pearl.ElementRate = fairy.ElementRate;
Session.Character.Inventory.RemoveItemAmountFromInventory(1, fairy.Id);
}
}
}
else if (guriPacket.Type == 203 && guriPacket.Argument == 0)
{
// SP points initialization
int[] listPotionResetVNums = {1366, 1427, 5115, 9040};
int vnumToUse = -1;
foreach (int vnum in listPotionResetVNums)
{
if (Session.Character.Inventory.CountItem(vnum) > 0)
{
vnumToUse = vnum;
}
}
if (vnumToUse != -1)
{
if (Session.Character.UseSp)
{
SpecialistInstance specialistInstance =
Session.Character.Inventory.LoadBySlotAndType<SpecialistInstance>((byte) EquipmentType.Sp, InventoryType.Wear);
if (specialistInstance != null)
{
specialistInstance.SlDamage = 0;
specialistInstance.SlDefence = 0;
specialistInstance.SlElement = 0;
specialistInstance.SlHP = 0;
specialistInstance.DamageMinimum = 0;
specialistInstance.DamageMaximum = 0;
specialistInstance.HitRate = 0;
specialistInstance.CriticalLuckRate = 0;
specialistInstance.CriticalRate = 0;
specialistInstance.DefenceDodge = 0;
specialistInstance.DistanceDefenceDodge = 0;
specialistInstance.ElementRate = 0;
specialistInstance.DarkResistance = 0;
specialistInstance.LightResistance = 0;
specialistInstance.FireResistance = 0;
specialistInstance.WaterResistance = 0;
specialistInstance.CriticalDodge = 0;
specialistInstance.CloseDefence = 0;
specialistInstance.DistanceDefence = 0;
specialistInstance.MagicDefence = 0;
specialistInstance.HP = 0;
specialistInstance.MP = 0;
Session.Character.Inventory.RemoveItemAmount(vnumToUse);
Session.Character.Inventory.DeleteFromSlotAndType((byte) EquipmentType.Sp, InventoryType.Wear);
Session.Character.Inventory.AddToInventoryWithSlotAndType(specialistInstance, InventoryType.Wear, (byte) EquipmentType.Sp);
Session.SendPacket(Session.Character.GenerateCond());
Session.SendPacket(specialistInstance.GenerateSlInfo());
Session.SendPacket(Session.Character.GenerateLev());
Session.SendPacket(Session.Character.GenerateStatChar());
Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("POINTS_RESET"), 0));
}
}
else
{
Session.SendPacket(Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("TRANSFORMATION_NEEDED"), 10));
}
}
else
{
Session.SendPacket(Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("NOT_ENOUGH_POINTS"), 10));
}
}
break;
}
}
break;
}
}
break;
}
}
}
#endregion
}
} | 412 | 0.921824 | 1 | 0.921824 | game-dev | MEDIA | 0.956968 | game-dev | 0.924608 | 1 | 0.924608 |
starryforest-ymxk/StarryFramework | 1,848 | Assets/StarryFramework/Editor/Inspector/FSMComponentInspector.cs | using UnityEditor;
using UnityEngine;
namespace StarryFramework.Editor
{
[CustomEditor(typeof(FSMComponent))]
internal sealed class FSMComponentInspector : FrameworkInspector
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
if (!EditorApplication.isPlaying)
{
EditorGUILayout.HelpBox("Available during runtime only.", MessageType.Info);
return;
}
FSMComponent t = (FSMComponent)target;
EditorGUILayout.LabelField("FSM Count", t.GetFSMCount().ToString());
FSMBase[] fsms = t.GetAllFSMs();
foreach (FSMBase fsm in fsms)
{
DrawFSM(fsm);
}
Repaint();
}
private void DrawFSM(FSMBase fsm)
{
EditorGUILayout.Space(6);
string content = fsm.IsRunning() ? $"{fsm.GetCurrentStateName()}, {fsm.GetCurrentStateTime():F2} s" : (fsm.IsDestroyed() ? "Destroyed" : "Not Running");
Rect r = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none);
EditorGUILayout.BeginHorizontal();
{
fsm.Foldout = EditorGUI.Foldout(r, fsm.Foldout, GUIContent.none);
EditorGUI.LabelField(r, fsm.FullName, content);
}
EditorGUILayout.EndHorizontal();
if (fsm.Foldout)
{
IVariable[] variables = fsm.GetAllData();
EditorGUILayout.BeginVertical(StyleFramework.box);
{
foreach (var a in variables)
{
EditorGUILayout.LabelField(a.Key, a.GetValueString());
}
}
EditorGUILayout.EndVertical();
}
}
}
}
| 412 | 0.838042 | 1 | 0.838042 | game-dev | MEDIA | 0.761667 | game-dev | 0.859109 | 1 | 0.859109 |
ReactiveDrop/reactivedrop_public_src | 2,748 | src/game/server/swarm/asw_order_nearby_aliens.cpp | // Orders nearby aliens to a named info_target
#include "cbase.h"
#include "asw_gamerules.h"
#include "iasw_spawnable_npc.h"
#include "asw_spawn_manager.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
class CASW_Order_Nearby_Aliens : public CPointEntity
{
private:
DECLARE_DATADESC();
public:
DECLARE_CLASS( CASW_Order_Nearby_Aliens, CPointEntity );
~CASW_Order_Nearby_Aliens( void );
virtual void Spawn( void );
CBaseEntity* GetOrderTarget();
EHANDLE m_hAlienOrderTarget;
const char* GetAlienClass();
AlienOrder_t m_AlienOrders;
string_t m_AlienOrderTargetName; // name of our moveto target
int m_AlienClassNum;
float m_fRadius;
// Input handlers
void InputOrderAliens( inputdata_t &inputdata );
};
LINK_ENTITY_TO_CLASS( asw_order_nearby_aliens, CASW_Order_Nearby_Aliens );
BEGIN_DATADESC( CASW_Order_Nearby_Aliens )
DEFINE_KEYFIELD( m_fRadius, FIELD_FLOAT, "radius" ),
DEFINE_KEYFIELD( m_AlienClassNum, FIELD_INTEGER, "AlienClass" ),
DEFINE_KEYFIELD( m_AlienOrders, FIELD_INTEGER, "AlienOrders" ),
DEFINE_KEYFIELD( m_AlienOrderTargetName, FIELD_STRING, "AlienOrderTargetName" ),
DEFINE_INPUTFUNC( FIELD_VOID, "SendOrders", InputOrderAliens ),
END_DATADESC()
CASW_Order_Nearby_Aliens::~CASW_Order_Nearby_Aliens( void )
{
}
void CASW_Order_Nearby_Aliens::Spawn( void )
{
SetSolid( SOLID_NONE );
SetMoveType( MOVETYPE_NONE );
}
void CASW_Order_Nearby_Aliens::InputOrderAliens( inputdata_t &inputdata )
{
// find all aliens within our radius
const char *szAlienClass = GetAlienClass();
CBaseEntity *pEntity = NULL;
while ( ( pEntity = gEntList.FindEntityByClassname( pEntity, szAlienClass ) ) != NULL )
{
float dist = ( GetAbsOrigin() - pEntity->GetAbsOrigin() ).Length2D();
if ( dist <= m_fRadius )
{
IASW_Spawnable_NPC *pAlien = dynamic_cast< IASW_Spawnable_NPC * >( pEntity );
Assert( pAlien );
if ( pAlien )
{
// give the orders
pAlien->SetAlienOrders( m_AlienOrders, vec3_origin, GetOrderTarget() );
}
}
}
}
const char* CASW_Order_Nearby_Aliens::GetAlienClass()
{
if ( m_AlienClassNum < 0 || m_AlienClassNum >= ASWSpawnManager()->GetNumAlienClasses() )
{
m_AlienClassNum = 0;
}
return ASWSpawnManager()->GetAlienClass( m_AlienClassNum )->m_pszAlienClass;
}
CBaseEntity* CASW_Order_Nearby_Aliens::GetOrderTarget()
{
if (m_hAlienOrderTarget.Get() == NULL &&
(m_AlienOrders == AOT_MoveTo || m_AlienOrders == AOT_MoveToIgnoringMarines )
)
{
m_hAlienOrderTarget = gEntList.FindEntityByName( NULL, m_AlienOrderTargetName, NULL );
if( !m_hAlienOrderTarget.Get() )
{
DevWarning("asw_spawner can't find order object\n", GetDebugName() );
return NULL;
}
}
return m_hAlienOrderTarget.Get();
}
| 412 | 0.867506 | 1 | 0.867506 | game-dev | MEDIA | 0.926564 | game-dev | 0.924639 | 1 | 0.924639 |
Sigma-Skidder-Team/SigmaRebase | 5,520 | src/main/java/net/minecraft/block/AbstractFurnaceBlock.java | package net.minecraft.block;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.inventory.container.Container;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.item.ItemStack;
import net.minecraft.state.BooleanProperty;
import net.minecraft.state.DirectionProperty;
import net.minecraft.state.StateContainer;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.tileentity.AbstractFurnaceTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.Mirror;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.World;
public abstract class AbstractFurnaceBlock extends ContainerBlock
{
public static final DirectionProperty FACING = HorizontalBlock.HORIZONTAL_FACING;
public static final BooleanProperty LIT = BlockStateProperties.LIT;
protected AbstractFurnaceBlock(AbstractBlock.Properties properties)
{
super(properties);
this.setDefaultState(this.stateContainer.getBaseState().with(FACING, Direction.NORTH).with(LIT, Boolean.valueOf(false)));
}
public ActionResultType onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit)
{
if (worldIn.isRemote)
{
return ActionResultType.SUCCESS;
}
else
{
this.interactWith(worldIn, pos, player);
return ActionResultType.CONSUME;
}
}
/**
* Interface for handling interaction with blocks that impliment AbstractFurnaceBlock. Called in onBlockActivated
* inside AbstractFurnaceBlock.
*/
protected abstract void interactWith(World worldIn, BlockPos pos, PlayerEntity player);
public BlockState getStateForPlacement(BlockItemUseContext context)
{
return this.getDefaultState().with(FACING, context.getPlacementHorizontalFacing().getOpposite());
}
/**
* Called by ItemBlocks after a block is set in the world, to allow post-place logic
*/
public void onBlockPlacedBy(World worldIn, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack)
{
if (stack.hasDisplayName())
{
TileEntity tileentity = worldIn.getTileEntity(pos);
if (tileentity instanceof AbstractFurnaceTileEntity)
{
((AbstractFurnaceTileEntity)tileentity).setCustomName(stack.getDisplayName());
}
}
}
public void onReplaced(BlockState state, World worldIn, BlockPos pos, BlockState newState, boolean isMoving)
{
if (!state.isIn(newState.getBlock()))
{
TileEntity tileentity = worldIn.getTileEntity(pos);
if (tileentity instanceof AbstractFurnaceTileEntity)
{
InventoryHelper.dropInventoryItems(worldIn, pos, (AbstractFurnaceTileEntity)tileentity);
((AbstractFurnaceTileEntity)tileentity).grantStoredRecipeExperience(worldIn, Vector3d.copyCentered(pos));
worldIn.updateComparatorOutputLevel(pos, this);
}
super.onReplaced(state, worldIn, pos, newState, isMoving);
}
}
/**
* @deprecated call via {@link IBlockState#hasComparatorInputOverride()} whenever possible. Implementing/overriding
* is fine.
*/
public boolean hasComparatorInputOverride(BlockState state)
{
return true;
}
/**
* @deprecated call via {@link IBlockState#getComparatorInputOverride(World,BlockPos)} whenever possible.
* Implementing/overriding is fine.
*/
public int getComparatorInputOverride(BlockState blockState, World worldIn, BlockPos pos)
{
return Container.calcRedstone(worldIn.getTileEntity(pos));
}
/**
* The type of render function called. MODEL for mixed tesr and static model, MODELBLOCK_ANIMATED for TESR-only,
* LIQUID for vanilla liquids, INVISIBLE to skip all rendering
* @deprecated call via {@link IBlockState#getRenderType()} whenever possible. Implementing/overriding is fine.
*/
public BlockRenderType getRenderType(BlockState state)
{
return BlockRenderType.MODEL;
}
/**
* Returns the blockstate with the given rotation from the passed blockstate. If inapplicable, returns the passed
* blockstate.
* @deprecated call via {@link IBlockState#withRotation(Rotation)} whenever possible. Implementing/overriding is
* fine.
*/
public BlockState rotate(BlockState state, Rotation rot)
{
return state.with(FACING, rot.rotate(state.get(FACING)));
}
/**
* Returns the blockstate with the given mirror of the passed blockstate. If inapplicable, returns the passed
* blockstate.
* @deprecated call via {@link IBlockState#withMirror(Mirror)} whenever possible. Implementing/overriding is fine.
*/
public BlockState mirror(BlockState state, Mirror mirrorIn)
{
return state.rotate(mirrorIn.toRotation(state.get(FACING)));
}
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder)
{
builder.add(FACING, LIT);
}
}
| 412 | 0.919215 | 1 | 0.919215 | game-dev | MEDIA | 0.99735 | game-dev | 0.988087 | 1 | 0.988087 |
lzk228/space-axolotl-14 | 5,679 | Content.Shared/NameModifier/EntitySystems/NameModifierSystem.cs | using System.Linq;
using Content.Shared.Inventory;
using Content.Shared.NameModifier.Components;
namespace Content.Shared.NameModifier.EntitySystems;
/// <inheritdoc cref="NameModifierComponent"/>
public sealed class NameModifierSystem : EntitySystem
{
[Dependency] private readonly MetaDataSystem _metaData = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<NameModifierComponent, EntityRenamedEvent>(OnEntityRenamed);
}
private void OnEntityRenamed(Entity<NameModifierComponent> ent, ref EntityRenamedEvent args)
{
SetBaseName(ent, args.NewName);
RefreshNameModifiers((ent.Owner, ent.Comp));
}
private void SetBaseName(Entity<NameModifierComponent> entity, string name)
{
if (name == entity.Comp.BaseName)
return;
// Set the base name to the new name
entity.Comp.BaseName = name;
Dirty(entity);
}
/// <summary>
/// Returns the base name of the entity, without any modifiers applied.
/// If the entity doesn't have a <see cref="NameModifierComponent"/>,
/// this returns the entity's metadata name.
/// </summary>
public string GetBaseName(Entity<NameModifierComponent?> entity)
{
if (Resolve(entity, ref entity.Comp, logMissing: false))
return entity.Comp.BaseName;
return Name(entity);
}
/// <summary>
/// Raises a <see cref="RefreshNameModifiersEvent"/> to gather modifiers and
/// updates the entity's name to its base name with modifiers applied.
/// This will add a <see cref="NameModifierComponent"/> if any modifiers are added.
/// </summary>
/// <remarks>
/// Call this to update the entity's name when adding or removing a modifier.
/// </remarks>
public void RefreshNameModifiers(Entity<NameModifierComponent?> entity)
{
var meta = MetaData(entity);
var baseName = meta.EntityName;
if (Resolve(entity, ref entity.Comp, logMissing: false))
baseName = entity.Comp.BaseName;
// Raise an event to get any modifiers
// If the entity already has the component, use its BaseName, otherwise use the entity's name from metadata
var modifierEvent = new RefreshNameModifiersEvent(baseName);
RaiseLocalEvent(entity, ref modifierEvent);
// Nothing added a modifier, so we can just use the base name
if (modifierEvent.ModifierCount == 0)
{
// If the entity doesn't have the component, we're done
if (entity.Comp == null)
return;
// Restore the base name
_metaData.SetEntityName(entity, entity.Comp.BaseName, meta, raiseEvents: false);
// The component isn't doing anything anymore, so remove it
RemComp<NameModifierComponent>(entity);
return;
}
// We have at least one modifier, so we need to apply it to the entity.
// Get the final name with modifiers applied
var modifiedName = modifierEvent.GetModifiedName();
// Add the component if needed, and initialize it with the base name
if (!EnsureComp<NameModifierComponent>(entity, out var comp))
SetBaseName((entity, comp), meta.EntityName);
// Set the entity's name with modifiers applied
_metaData.SetEntityName(entity, modifiedName, meta, raiseEvents: false);
}
}
/// <summary>
/// Raised on an entity when <see cref="NameModifierSystem.RefreshNameModifiers"/> is called.
/// Subscribe to this event and use its methods to add modifiers to the entity's name.
/// </summary>
[ByRefEvent]
public sealed class RefreshNameModifiersEvent : IInventoryRelayEvent
{
/// <summary>
/// The entity's name without any modifiers applied.
/// If you want to base a modifier on the entity's name, use
/// this so you don't include other modifiers.
/// </summary>
public readonly string BaseName;
private readonly List<(LocId LocId, int Priority, (string, object)[] ExtraArgs)> _modifiers = [];
/// <inheritdoc/>
public SlotFlags TargetSlots => ~SlotFlags.POCKET;
/// <summary>
/// How many modifiers have been added to this event.
/// </summary>
public int ModifierCount => _modifiers.Count;
public RefreshNameModifiersEvent(string baseName)
{
BaseName = baseName;
}
/// <summary>
/// Adds a modifier to the entity's name.
/// The original name will be passed to Fluent as <c>$baseName</c> along with any <paramref name="extraArgs"/>.
/// Modifiers with a higher <paramref name="priority"/> will be applied later.
/// </summary>
public void AddModifier(LocId locId, int priority = 0, params (string, object)[] extraArgs)
{
_modifiers.Add((locId, priority, extraArgs));
}
/// <summary>
/// Returns the final name with all modifiers applied.
/// </summary>
public string GetModifiedName()
{
// Start out with the entity's name name
var name = BaseName;
// Iterate through all the modifiers in priority order
foreach (var modifier in _modifiers.OrderBy(n => n.Priority))
{
// Grab any extra args needed by the Loc string
var args = modifier.ExtraArgs;
// Add the current version of the entity name as an arg
Array.Resize(ref args, args.Length + 1);
args[^1] = ("baseName", name);
// Resolve the Loc string and use the result as the base in the next iteration.
name = Loc.GetString(modifier.LocId, args);
}
return name;
}
}
| 412 | 0.840687 | 1 | 0.840687 | game-dev | MEDIA | 0.814862 | game-dev | 0.857762 | 1 | 0.857762 |
libretro/nxengine-libretro | 18,678 | nxengine/ai/boss/x.cpp |
#include "../stdai.h"
#include "x.h"
#include "x.fdh"
#define STATE_X_APPEAR 1 // script-triggered: must stay constant
#define STATE_X_FIGHT_BEGIN 10 // script-triggered: must stay constant
#define STATE_X_TRAVEL 20
#define STATE_X_BRAKE 30
#define STATE_X_OPEN_DOORS 40
#define STATE_X_FIRE_TARGETS 50
#define STATE_X_FIRE_FISHIES 60
#define STATE_X_CLOSE_DOORS 70
#define STATE_X_EXPLODING 80
#define STATE_DOOR_OPENING 10 // makes the doors open
#define STATE_DOOR_OPENING_PARTIAL 20 // makes the doors open part-way
#define STATE_DOOR_CLOSING 30 // closes the doors
#define STATE_DOOR_FINISHED 40 // doors are finished moving
#define STATE_TREAD_STOPPED 20
#define STATE_TREAD_RUN 30
#define STATE_TREAD_BRAKE 40
#define STATE_FISHSPAWNER_FIRE 10
#define STATE_TARGET_FIRE 10
#define DOORS_OPEN_DIST (32 << CSF) // how far the doors open
#define DOORS_OPEN_FISHY_DIST (20 << CSF) // how far the doors open during fish-missile phase
// the treads start moving at slightly different times
// which we change direction, etc.
static const int tread_turnon_times[] = { 4, 8, 10, 12 };
INITFUNC(AIRoutines)
{
ONTICK(OBJ_X_FISHY_MISSILE, ai_x_fishy_missile);
ONTICK(OBJ_X_DEFEATED, ai_x_defeated);
ONDEATH(OBJ_X_TARGET, ondeath_x_target);
ONDEATH(OBJ_X_MAINOBJECT, ondeath_x_mainobject);
}
void XBoss::OnMapEntry(void)
{
NX_LOG("XBoss::OnMapEntry()\n");
memset(&X, 0, sizeof(X));
memset(&body, 0, sizeof(body));
memset(&treads, 0, sizeof(treads));
memset(&internals, 0, sizeof(internals));
memset(&doors, 0, sizeof(doors));
memset(&targets, 0, sizeof(targets));
memset(&fishspawners, 0, sizeof(fishspawners));
npieces = 0;
mainobject = CreateObject(0, 0, OBJ_X_MAINOBJECT);
mainobject->sprite = SPR_NULL;
game.stageboss.object = mainobject;
}
void XBoss::OnMapExit()
{
// we'll let the map loader code handle deleting all our pieces.
// here's just a good-form failsafe to ensure XBoss::Run() runs no more.
mainobject = NULL;
game.stageboss.object = NULL;
}
/*
void c------------------------------() {}
*/
void XBoss::Run()
{
Object *o = mainobject;
int i;
if (!mainobject) return;
if (o->state == 0 || (!X.initilized && o->state != STATE_X_APPEAR))
{
o->hp = 1;
o->x = -(SCREEN_WIDTH << CSF);
return;
}
switch(o->state)
{
// script triggered us to initilize/appear
// (there is a hvtrigger, right before player first walks by us
// and sees us inactive, which sends us this ANP).
case STATE_X_APPEAR:
{
if (!X.initilized)
{
Init();
X.initilized = true;
}
}
break;
// script has triggered the fight to begin
case STATE_X_FIGHT_BEGIN:
{
o->timer = 0;
o->state++;
}
case STATE_X_FIGHT_BEGIN+1:
{
if (++o->timer > 100)
{
FACEPLAYER;
o->timer = 0;
o->state = STATE_X_TRAVEL;
}
}
break;
// starts the treads and moves us in the currently-facing direction
case STATE_X_TRAVEL:
{
// count number of times we've traveled, we brake
// and attack every third time.
o->timer2++;
o->timer = 0;
o->state++;
}
case STATE_X_TRAVEL+1:
{
o->timer++;
// trigger the treads to start moving,
// and put them slightly out of sync with each-other.
for(int i=0;i<4;i++)
{
if (o->timer == tread_turnon_times[i])
{
treads[i]->state = STATE_TREAD_RUN;
treads[i]->dir = o->dir;
}
}
if (o->timer > 120)
{
// time to attack? we attack every 3rd travel
// if so skid to a stop, that's the first step.
if (o->timer2 >= 3)
{
o->timer2 = 0;
o->dir ^= 1;
o->state = STATE_X_BRAKE;
o->timer = 0;
}
else
{
// passed player? skid and turn around.
if ((o->dir == RIGHT && o->x > player->x) || \
(o->dir == LEFT && o->x < player->x))
{
o->dir ^= 1;
o->state = STATE_X_TRAVEL;
}
}
}
}
break;
// skidding to a stop in preparation to attack
case STATE_X_BRAKE:
{
o->timer = 0;
o->state++;
}
case STATE_X_BRAKE+1:
{
o->timer++;
// trigger the treads to start braking,
// and put them slightly out of sync with each-other.
for(int i=0;i<4;i++)
{
if (o->timer == tread_turnon_times[i])
{
treads[i]->state = STATE_TREAD_BRAKE;
treads[i]->dir = o->dir;
}
}
if (o->timer > 50)
{
o->state = STATE_X_OPEN_DOORS;
o->timer = 0;
}
}
break;
// doors opening to attack
case STATE_X_OPEN_DOORS:
{
o->timer = 0;
o->savedhp = o->hp;
// select type of attack depending on where we are in the battle
if (!AllTargetsDestroyed())
{
SetStates(doors, 2, STATE_DOOR_OPENING);
o->state = STATE_X_FIRE_TARGETS;
}
else
{
SetStates(doors, 2, STATE_DOOR_OPENING_PARTIAL);
o->state = STATE_X_FIRE_FISHIES;
}
}
break;
// firing targets (early battle)
case STATE_X_FIRE_TARGETS:
{
if (doors[0]->state == STATE_DOOR_FINISHED)
{
doors[0]->state = 0;
SetStates(targets, 4, STATE_TARGET_FIRE);
}
if (++o->timer > 300 || AllTargetsDestroyed())
{
o->state = STATE_X_CLOSE_DOORS;
o->timer = 0;
}
}
break;
// firing fishy missiles (late battle)
case STATE_X_FIRE_FISHIES:
{
if (doors[0]->state == STATE_DOOR_FINISHED)
{
doors[0]->state = 0;
SetStates(fishspawners, 4, STATE_FISHSPAWNER_FIRE);
internals->flags |= FLAG_SHOOTABLE;
}
if (++o->timer > 300 || (o->savedhp - o->hp) > 200)
{
o->state = STATE_X_CLOSE_DOORS;
o->timer = 0;
}
}
break;
// doors closing after attack
case STATE_X_CLOSE_DOORS:
{
o->timer = 0;
o->state++;
SetStates(doors, 2, STATE_DOOR_CLOSING);
}
case STATE_X_CLOSE_DOORS+1:
{
if (doors[0]->state == STATE_DOOR_FINISHED)
{
doors[0]->state = 0;
// just turn off everything for both types of attacks;
// turning off the attack type that wasn't enabled isn't harmful.
SetStates(targets, 4, 0);
SetStates(fishspawners, 4, 0);
internals->flags &= ~FLAG_SHOOTABLE;
}
if (++o->timer > 50)
{
FACEPLAYER;
o->state = STATE_X_TRAVEL;
o->timer = 0;
}
}
break;
// exploding
case STATE_X_EXPLODING:
{
SetStates(fishspawners, 4, 0);
KillObjectsOfType(OBJ_X_FISHY_MISSILE);
StartScript(1000);
o->timer = 0;
o->state++;
}
case STATE_X_EXPLODING+1:
{
game.quaketime = 2;
o->timer++;
if ((o->timer % 8) == 0)
sound(SND_ENEMY_HURT_BIG);
SmokePuff(o->CenterX() + (nx_random(-72, 72) << CSF),
o->CenterY() + (nx_random(-64, 64) << CSF));
if (o->timer > 100)
{
starflash.Start(o->CenterX(), o->CenterY());
sound(SND_EXPLOSION1);
o->timer = 0;
o->state++;
}
}
break;
case STATE_X_EXPLODING+2:
{
game.quaketime = 40;
if (++o->timer > 50)
{
CreateObject(o->x, o->y - (24 << CSF), OBJ_X_DEFEATED);
DeleteMonster();
return;
}
}
break;
}
// call AI for all tread pieces
for(i=0;i<4;i++)
{
run_tread(i);
run_fishy_spawner(i);
}
}
// moved this to aftermove so xinertia on treads is already applied
// when we calculate the main object position.
void XBoss::RunAftermove()
{
Object *o = mainobject;
int i;
if (!mainobject || mainobject->state == 0 || !X.initilized)
return;
// main object pulled along as treads move
int tread_center = (treads[UL]->x + treads[UR]->x + \
treads[LL]->x + treads[LR]->x) / 4;
o->x += (tread_center - o->x) / 16;
run_internals();
for(i=0;i<4;i++)
{
run_body(i);
run_target(i);
}
for(i=0;i<2;i++)
{
run_door(i);
}
}
void ondeath_x_mainobject(Object *internals)
{
// do nothing really, this function is just there to override
// the default so we are not destroyed--our 0 HP level will
// be noticed in run_internals() and trigger the defeat sequence.
internals->flags &= ~FLAG_SHOOTABLE;
}
/*
void c------------------------------() {}
*/
void XBoss::run_tread(int index)
{
Object *o = treads[index];
switch(o->state)
{
case 0:
{
o->flags |= (FLAG_SOLID_BRICK | FLAG_INVULNERABLE | FLAG_NOREARTOPATTACK);
o->state = STATE_TREAD_STOPPED;
}
case STATE_TREAD_STOPPED:
{
o->frame = 0;
o->damage = 0;
o->flags &= ~FLAG_BOUNCY;
}
break;
case STATE_TREAD_RUN:
{
o->flags |= FLAG_BOUNCY;
o->timer = 0;
o->frame = 2;
o->animtimer = 0;
o->state++;
}
case STATE_TREAD_RUN+1:
{
ANIMATE(0, 2, 3);
XACCEL(0x20);
if (++o->timer > 30)
{
o->flags &= ~FLAG_BOUNCY;
o->frame = 0;
o->animtimer = 0;
o->state++;
}
}
break;
case STATE_TREAD_RUN+2:
{
ANIMATE(1, 0, 1);
XACCEL(0x20);
o->timer++;
}
break;
case STATE_TREAD_BRAKE:
{
o->frame = 2;
o->animtimer = 0;
o->flags |= FLAG_BOUNCY;
o->state++;
}
case STATE_TREAD_BRAKE+1:
{
ANIMATE(0, 2, 3);
XACCEL(0x20);
if ((o->dir == RIGHT && o->xinertia > 0) || \
(o->dir == LEFT && o->xinertia < 0))
{
o->xinertia = 0;
o->state = STATE_TREAD_STOPPED;
}
}
break;
}
// make motor noise
switch(o->state)
{
case STATE_TREAD_RUN+1:
case STATE_TREAD_BRAKE+1:
{
if (o->timer & 1)
sound(SND_MOTOR_SKIP);
}
break;
case STATE_TREAD_RUN+2:
{
if ((o->timer % 4) == 1)
sound(SND_MOTOR_RUN);
}
break;
}
// determine if player is in a position where he could get run over.
if (o->state > STATE_TREAD_STOPPED && o->xinertia != 0)
{
if (abs(player->y - o->CenterY()) <= (5 << CSF))
o->damage = 10;
else
o->damage = 0;
}
else
{
o->damage = 0;
}
LIMITX(0x400);
}
void XBoss::run_body(int i)
{
// set body position based on main object position and
// our linked tread position. first get the center point we should be at...
body[i]->x = (mainobject->x + treads[i]->x) / 2;
body[i]->y = (mainobject->y + treads[i]->y) / 2;
// ...and place our center pixel at those coordinates.
int dx = (sprites[body[i]->sprite].w / 2) - 8;
int dy = (sprites[body[i]->sprite].h / 2) - 8;
body[i]->x -= dx << CSF;
body[i]->y -= dy << CSF;
// tweaks
if (i == UL || i == LL)
{
body[i]->x -= (6 << CSF);
}
else
{
body[i]->x += (7 << CSF);
}
if (i == LL || i == LR)
{
body[i]->y += (8 << CSF);
}
}
void XBoss::run_internals()
{
internals->x = mainobject->x;
internals->y = mainobject->y;
// select frame
if (internals->shaketime & 2)
{
internals->frame = 1;
}
else
{
internals->frame = (mainobject->state < 10) ? 2 : 0;
}
// link damage to main object
if (internals->hp < 1000)
{
mainobject->DealDamage(1000 - internals->hp);
internals->hp = 1000;
}
// trigger explosion sequence when monster defeated
if (mainobject->hp <= 0 && mainobject->state < STATE_X_EXPLODING)
{
mainobject->shaketime = 150;
mainobject->state = STATE_X_EXPLODING;
}
}
void XBoss::run_door(int index)
{
Object *o = doors[index];
switch(o->state)
{
// doors opening all the way
case STATE_DOOR_OPENING:
{
o->xmark += (1 << CSF);
if (o->xmark >= DOORS_OPEN_DIST)
{
o->xmark = DOORS_OPEN_DIST;
o->state = STATE_DOOR_FINISHED;
}
}
break;
// doors opening partially for fish-missile launchers to fire
case STATE_DOOR_OPENING_PARTIAL:
{
o->xmark += (1 << CSF);
if (o->xmark >= DOORS_OPEN_FISHY_DIST)
{
o->xmark = DOORS_OPEN_FISHY_DIST;
o->state = STATE_DOOR_FINISHED;
}
}
break;
// doors closing
case STATE_DOOR_CLOSING:
{
o->xmark -= (1 << CSF);
if (o->xmark <= 0)
{
o->xmark = 0;
o->state = STATE_DOOR_FINISHED;
}
}
break;
// this is a signal to the main object that the doors
// are finished with the last command.
case STATE_DOOR_FINISHED:
break;
}
// set position relative to main object.
// doors open in opposite directions.
if (o->dir == LEFT) o->x = (mainobject->x - o->xmark);
else o->x = (mainobject->x + o->xmark);
o->y = mainobject->y;
}
void XBoss::run_fishy_spawner(int index)
{
Object *o = fishspawners[index];
switch(o->state)
{
case STATE_FISHSPAWNER_FIRE:
{
o->timer = 20 + (index * 20);
o->state++;
}
case STATE_FISHSPAWNER_FIRE+1:
{
if (o->timer)
{
o->timer--;
break;
}
// keep appropriate position relative to main object
// UL UR LL LR
static const int xoffs[] = { -64 <<CSF, 76 <<CSF, -64 <<CSF, 76 <<CSF };
static const int yoffs[] = { 27 <<CSF, 27 <<CSF, -16 <<CSF, -16 <<CSF };
o->x = (mainobject->x + xoffs[index]);
o->y = (mainobject->y + yoffs[index]);
Object *missile = CreateObject(o->x, o->y, OBJ_X_FISHY_MISSILE);
missile->dir = index;
sound(SND_EM_FIRE);
o->timer = 120;
}
break;
}
}
void XBoss::run_target(int index)
{
Object *o = targets[index];
// has this target been destroyed?
// (we don't really kill the object until the battle is over,
// to avoid having to deal with dangling pointers).
if (o->invisible)
return;
switch(o->state)
{
case 0:
o->flags &= ~FLAG_SHOOTABLE;
o->frame &= 3;
o->state = 1;
break;
case STATE_TARGET_FIRE:
{
o->timer = 40 + (index * 10);
o->flags |= FLAG_SHOOTABLE;
o->state++;
}
case STATE_TARGET_FIRE+1:
{
if (--o->timer <= 16)
{
// flash shortly before firing
if (o->timer & 2) o->frame |= 4;
else o->frame &= 3;
if (o->timer <= 0)
{
o->timer = 40;
EmFireAngledShot(o, OBJ_GAUDI_FLYING_SHOT, 2, 0x500);
sound(SND_EM_FIRE);
}
}
}
break;
}
// keep appropriate position on internals
// UL UR LL LR
static const int xoffs[] = { -22 <<CSF, 28 <<CSF, -15 <<CSF, 17 <<CSF };
static const int yoffs[] = { -16 <<CSF, -16 <<CSF, 14 <<CSF, 14 <<CSF };
o->x = internals->x + xoffs[index];
o->y = internals->y + yoffs[index];
}
void ondeath_x_target(Object *o)
{
SmokeClouds(o, 8, 8, 8);
sound(SND_LITTLE_CRASH);
o->flags &= ~FLAG_SHOOTABLE;
o->invisible = true;
}
/*
void c------------------------------() {}
*/
void XBoss::Init()
{
int i;
mainobject->hp = 700;
mainobject->state = 1;
mainobject->x = (128 * TILE_W) << CSF;
mainobject->y = (200 << CSF);
mainobject->flags = FLAG_IGNORE_SOLID;
// put X behind the flying gaudis
mainobject->PushBehind(lowestobject);
// create body pieces
for(i=3;i>=0;i--)
{
body[i] = CreatePiece(0, 0, OBJ_X_BODY);
body[i]->dir = (i == UL || i == LL) ? LEFT : RIGHT;
body[i]->frame = (i == LL || i == LR) ? 1 : 0;
}
// create treads
for(i=0;i<4;i++)
{
int x = (i == UL || i == LL) ? 0xf8000 : 0x108000;
int y = (i == UL || i == UR) ? 0x12000 : (0x20000 - (16 << CSF));
int sprite = (i == UL || i == UR) ? SPR_X_TREAD_UPPER : SPR_X_TREAD_LOWER;
treads[i] = CreateTread(x, y, sprite);
treads[i]->smushdamage = 10;
}
// create internals
internals = CreatePiece(0, 0, OBJ_X_INTERNALS);
internals->hp = 1000;
internals->flags &= ~FLAG_SHOW_FLOATTEXT;
// create targets
for(i=0;i<4;i++)
{
targets[i] = CreatePiece(0, 0, OBJ_X_TARGET);
targets[i]->sprite = SPR_X_TARGETS;
targets[i]->frame = i;
targets[i]->hp = 60;
targets[i]->flags &= ~FLAG_SHOW_FLOATTEXT;
}
// create fishy-missile shooters
for(i=0;i<4;i++)
{
fishspawners[i] = CreatePiece(0, 0, OBJ_X_FISHY_SPAWNER);
fishspawners[i]->sprite = SPR_NULL;
fishspawners[i]->invisible = true;
fishspawners[i]->flags = 0;
}
// create doors
for(i=0;i<2;i++)
{
doors[i] = CreatePiece(0, 0, OBJ_X_DOOR);
doors[i]->sprite = SPR_X_DOOR;
doors[i]->dir = i;
}
sprites[SPR_X_DOOR].frame[0].dir[LEFT].drawpoint.x = 40;
sprites[SPR_X_DOOR].frame[0].dir[LEFT].drawpoint.y = 16;
sprites[SPR_X_DOOR].frame[0].dir[RIGHT].drawpoint.x = -9;
sprites[SPR_X_DOOR].frame[0].dir[RIGHT].drawpoint.y = 16;
}
// create an object and record it as a piece of the monster
// so we can delete all the pieces later via DeleteMonster().
Object *XBoss::CreatePiece(int x, int y, int object)
{
Object *piece = CreateObject(x, y, object);
piecelist[npieces++] = piece;
piece->PushBehind(mainobject);
return piece;
}
// create an object of type OBJ_X_TREAD and give it the specified sprite.
Object *XBoss::CreateTread(int x, int y, int sprite)
{
Object *tread = CreatePiece(x, y, OBJ_X_TREAD);
tread->sprite = sprite;
return tread;
}
// delete all pieces of the monster
void XBoss::DeleteMonster()
{
for(int i=0;i<npieces;i++)
piecelist[i]->Delete();
mainobject->Delete();
mainobject = NULL;
game.stageboss.object = NULL;
}
// return true if all the targets behind the doors have been destroyed.
bool XBoss::AllTargetsDestroyed()
{
for(int i=0;i<4;i++)
{
if (!targets[i]->invisible)
return false;
}
return true;
}
/*
void c------------------------------() {}
*/
// sets state on an array on objects
void XBoss::SetStates(Object *objects[], int nobjects, int state)
{
for(int i=0;i<nobjects;i++)
objects[i]->state = state;
}
// sets direction on an array on objects
void XBoss::SetDirs(Object *objects[], int nobjects, int dir)
{
for(int i=0;i<nobjects;i++)
objects[i]->dir = dir;
}
/*
void c------------------------------() {}
*/
void ai_x_fishy_missile(Object *o)
{
if (o->state == 0)
{
static const int angle_for_dirs[] = { 160, 224, 96, 32 };
o->angle = angle_for_dirs[o->dir];
o->dir = RIGHT;
o->state = 1;
}
vector_from_angle(o->angle, 0x400, &o->xinertia, &o->yinertia);
int desired_angle = GetAngle(o->x, o->y, player->x, player->y);
if (o->angle >= desired_angle)
{
if ((o->angle - desired_angle) < 128)
{
o->angle--;
}
else
{
o->angle++;
}
}
else
{
if ((o->angle - desired_angle) < 128)
{
o->angle++;
}
else
{
o->angle--;
}
}
// smoke trails
if (++o->timer2 > 2)
{
o->timer2 = 0;
Caret *c = effect(o->ActionPointX(), o->ActionPointY(), EFFECT_SMOKETRAIL_SLOW);
c->xinertia = -o->xinertia >> 2;
c->yinertia = -o->yinertia >> 2;
}
o->frame = (o->angle + 16) / 32;
if (o->frame > 7) o->frame = 7;
}
// this is the cat that falls out after you defeat him
void ai_x_defeated(Object *o)
{
o->timer++;
if ((o->timer % 4) == 0)
{
SmokeClouds(o, 1, 16, 16);
}
switch(o->state)
{
case 0:
{
SmokeClouds(o, 8, 16, 16);
o->state = 1;
}
case 1:
{
if (o->timer > 50)
{
o->state = 2;
o->xinertia = -0x100;
}
// three-position shake
o->x += (o->timer & 2) ? (1 << CSF) : -(1 << CSF);
}
break;
case 2:
{
o->yinertia += 0x40;
if (o->y > (map.ysize * TILE_H) << CSF) o->Delete();
}
break;
}
}
| 412 | 0.90071 | 1 | 0.90071 | game-dev | MEDIA | 0.821258 | game-dev | 0.982145 | 1 | 0.982145 |
SinlessDevil/ColliderMeshTool | 4,205 | Assets/Plugins/Zenject/Source/Binding/Binders/Factory/FactoryFromBinder/SubContainerBinder/FactorySubContainerBinder2.cs | using System;
namespace Zenject
{
[NoReflectionBaking]
public class FactorySubContainerBinder<TParam1, TParam2, TContract>
: FactorySubContainerBinderWithParams<TContract>
{
public FactorySubContainerBinder(
DiContainer bindContainer, BindInfo bindInfo, FactoryBindInfo factoryBindInfo, object subIdentifier)
: base(bindContainer, bindInfo, factoryBindInfo, subIdentifier)
{
}
public ScopeConcreteIdArgConditionCopyNonLazyBinder ByMethod(Action<DiContainer, TParam1, TParam2> installerMethod)
{
var subcontainerBindInfo = new SubContainerCreatorBindInfo();
ProviderFunc =
(container) => new SubContainerDependencyProvider(
ContractType, SubIdentifier,
new SubContainerCreatorByMethod<TParam1, TParam2>(
container, subcontainerBindInfo, installerMethod), false);
return new ScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo);
}
#if !NOT_UNITY3D
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewGameObjectMethod(
Action<DiContainer, TParam1, TParam2> installerMethod)
{
var gameObjectInfo = new GameObjectCreationParameters();
ProviderFunc =
(container) => new SubContainerDependencyProvider(
ContractType, SubIdentifier,
new SubContainerCreatorByNewGameObjectMethod<TParam1, TParam2>(
container, gameObjectInfo, installerMethod), false);
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabMethod(
Func<InjectContext, UnityEngine.Object> prefabGetter, Action<DiContainer, TParam1, TParam2> installerMethod)
{
var gameObjectInfo = new GameObjectCreationParameters();
ProviderFunc =
(container) => new SubContainerDependencyProvider(
ContractType, SubIdentifier,
new SubContainerCreatorByNewPrefabMethod<TParam1, TParam2>(
container,
new PrefabProviderCustom(prefabGetter),
gameObjectInfo, installerMethod), false);
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabMethod(
UnityEngine.Object prefab, Action<DiContainer, TParam1, TParam2> installerMethod)
{
BindingUtil.AssertIsValidPrefab(prefab);
var gameObjectInfo = new GameObjectCreationParameters();
ProviderFunc =
(container) => new SubContainerDependencyProvider(
ContractType, SubIdentifier,
new SubContainerCreatorByNewPrefabMethod<TParam1, TParam2>(
container,
new PrefabProvider(prefab),
gameObjectInfo, installerMethod), false);
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabResourceMethod(
string resourcePath, Action<DiContainer, TParam1, TParam2> installerMethod)
{
BindingUtil.AssertIsValidResourcePath(resourcePath);
var gameObjectInfo = new GameObjectCreationParameters();
ProviderFunc =
(container) => new SubContainerDependencyProvider(
ContractType, SubIdentifier,
new SubContainerCreatorByNewPrefabMethod<TParam1, TParam2>(
container,
new PrefabProviderResource(resourcePath),
gameObjectInfo, installerMethod), false);
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo);
}
#endif
}
}
| 412 | 0.829287 | 1 | 0.829287 | game-dev | MEDIA | 0.886282 | game-dev | 0.72911 | 1 | 0.72911 |
edvartGB/unity_asv_sim | 4,723 | Assets/Scripts/Sensors And Actuators/Lidar/Lidar2D.cs | using System;
using RosMessageTypes.Sensor;
using Unity.Collections;
using Unity.Jobs;
using Unity.Robotics.Core;
using Unity.Robotics.ROSTCPConnector;
using UnityEngine;
public class Lidar2D : MonoBehaviour
{
public float minAngleDegrees = -45.0f;
public float maxAngleDegrees = 45.0f;
public float angleIncrementDegrees = 1.0f;
public float minRange = 0.1f;
public float maxRange = 50.0f;
public float Hz = 5.0f;
public string topicName = "scan";
public string frameId = "lidar_link";
public bool publishData = true;
public bool drawRays = false;
private Vector3 transformScale;
private float scanTime;
private float timeSinceScan = 0.0f;
private Vector3[] scanDirVectors;
private LaserScanMsg msg = new LaserScanMsg();
private ROSConnection ros;
void Start()
{
ros = ROSConnection.GetOrCreateInstance();
ros.RegisterPublisher<LaserScanMsg>(topicName);
scanDirVectors = GenerateScanVectors();
}
void FixedUpdate(){
timeSinceScan += Time.deltaTime;
if (timeSinceScan < 1.0f/Hz){
return;
}
transformScale = transform.lossyScale;
scanDirVectors = GenerateScanVectors();
float[] dists = PerformScan(scanDirVectors);
if (publishData){
msg = DistancesToLaserscan(dists);
ros.Publish(topicName, msg);
}
timeSinceScan = 0.0f;
}
private Vector3[] GenerateScanVectors()
{
int numBeams = (int)((maxAngleDegrees-minAngleDegrees)/(angleIncrementDegrees));
Debug.Assert(numBeams >= 0, "Number of beams is negative. Check min/max angle and angle increment.");
Vector3[] scanVectors = new Vector3[numBeams];
float minAngleRad = Mathf.Deg2Rad*minAngleDegrees;
float angleIncrementRad = Mathf.Deg2Rad*angleIncrementDegrees;
for (int i = 0; i < numBeams; i++)
{
float hRot = minAngleRad + angleIncrementRad*i;
float x = -Mathf.Sin(hRot);
float y = 0;
float z = Mathf.Cos(hRot);
scanVectors[i].x = x;
scanVectors[i].y = y;
scanVectors[i].z = z;
}
return scanVectors;
}
private float[] PerformScan(Vector3[] dirs)
{
int numPoints = dirs.Length;
var commands = new NativeArray<RaycastCommand>(numPoints, Allocator.TempJob);
var results = new NativeArray<RaycastHit>(numPoints, Allocator.TempJob);
for (int i = 0; i < numPoints; i++)
{
Vector3 origin = transform.position;
Vector3 direction = transform.rotation * dirs[i];
commands[i] = new RaycastCommand(origin, direction, QueryParameters.Default, maxRange);
}
int batchSize = 500;
JobHandle handle = RaycastCommand.ScheduleBatch(commands, results, batchSize, 1);
handle.Complete();
float[] dists = new float[numPoints+1];
for (int i = 0; i < numPoints; i++)
{
var hit = results[i];
if (hit.collider != null && (transform.position - hit.point).sqrMagnitude > minRange * minRange)
{
Vector3 beam = transform.InverseTransformPoint(hit.point);
dists[i] = hit.distance;
if (drawRays)
{
Debug.DrawLine(transform.position, transform.TransformPoint(beam), Color.red);
}
}
else{
dists[i] = float.NaN;
}
}
results.Dispose();
commands.Dispose();
return dists;
}
private LaserScanMsg DistancesToLaserscan(float[] dists){
LaserScanMsg msg = new LaserScanMsg();
msg.header.frame_id = frameId;
var publishTime = Clock.Now;
var sec = publishTime;
var nanosec = ((publishTime - Math.Floor(publishTime)) * Clock.k_NanoSecondsInSeconds);
msg.header.stamp.sec = (int)sec;
msg.header.stamp.nanosec = (uint)nanosec;
msg.angle_min = minAngleDegrees*Mathf.Deg2Rad;
msg.angle_max = maxAngleDegrees*Mathf.Deg2Rad;
msg.angle_increment = angleIncrementDegrees*Mathf.Deg2Rad;
msg.scan_time = 1f/Hz;
msg.range_min = minRange;
msg.range_max = maxRange;
msg.ranges = dists;
return msg;
}
}
| 412 | 0.818909 | 1 | 0.818909 | game-dev | MEDIA | 0.702482 | game-dev,graphics-rendering | 0.975204 | 1 | 0.975204 |
exmex/UnityMoba | 1,518 | Assets/Prefabs/EquipSkill/Scripts/UTGBattlePassiveSkillBehaviourR60030080.cs | ο»Ώusing UnityEngine;
using System.Collections;
public class UTGBattlePassiveSkillBehaviourR60030080 : NTGBattlePassiveSkillBehaviour
{
public float pDuration;
public float moveAmount;
public override void Respawn()
{
base.Respawn();
pDuration = this.duration;
moveAmount = -owner.baseAttrs.MoveSpeed * this.param[0];
owner.baseAttrs.MoveSpeed += moveAmount;
owner.ApplyBaseAttrs();
FXEA();
FXEB();
StartCoroutine(doBoost());
}
public override void Notify(NTGBattlePassive.Event e, object param)
{
base.Notify(e, param);
if (e == NTGBattlePassive.Event.PassiveAdd)
{
var p = (NTGBattlePassiveSkillBehaviour)param;
shooter = p.shooter;
pDuration = p.duration;
owner.baseAttrs.MoveSpeed -= moveAmount;
moveAmount = -owner.baseAttrs.MoveSpeed * p.param[0];
owner.baseAttrs.MoveSpeed += moveAmount;
owner.ApplyBaseAttrs();
}
else if(e == NTGBattlePassive.Event.PassiveRemove)
{
owner.baseAttrs.MoveSpeed -= moveAmount;
owner.ApplyBaseAttrs();
Release();
}
}
private IEnumerator doBoost()
{
while (pDuration > 0)
{
pDuration -= 0.1f;
yield return new WaitForSeconds(0.1f);
}
owner.baseAttrs.MoveSpeed -= moveAmount;
owner.ApplyBaseAttrs();
Release();
}
}
| 412 | 0.833205 | 1 | 0.833205 | game-dev | MEDIA | 0.972611 | game-dev | 0.8781 | 1 | 0.8781 |
StrangeLoopGames/EcoModKit | 5,383 | Examples/CornOnTheCob/Client/Assets/EcoModKit/ThirdParty/DOTween/Modules/DOTweenModuleUtils.cs | // Author: Daniele Giardini - http://www.demigiant.com
// Created: 2018/07/13
using System;
using System.Reflection;
using UnityEngine;
using DG.Tweening.Core;
using DG.Tweening.Plugins.Core.PathCore;
using DG.Tweening.Plugins.Options;
#pragma warning disable 1591
namespace DG.Tweening
{
/// <summary>
/// Utility functions that deal with available Modules.
/// Modules defines:
/// - DOTAUDIO
/// - DOTPHYSICS
/// - DOTPHYSICS2D
/// - DOTSPRITE
/// - DOTUI
/// Extra defines set and used for implementation of external assets:
/// - DOTWEEN_TMP βΊ TextMesh Pro
/// - DOTWEEN_TK2D βΊ 2D Toolkit
/// </summary>
public static class DOTweenModuleUtils
{
static bool _initialized;
#region Reflection
/// <summary>
/// Called via Reflection by DOTweenComponent on Awake
/// </summary>
#if UNITY_2018_1_OR_NEWER
[UnityEngine.Scripting.Preserve]
#endif
public static void Init()
{
if (_initialized) return;
_initialized = true;
DOTweenExternalCommand.SetOrientationOnPath += Physics.SetOrientationOnPath;
#if UNITY_EDITOR
#if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1
UnityEditor.EditorApplication.playmodeStateChanged += PlaymodeStateChanged;
#else
UnityEditor.EditorApplication.playModeStateChanged += PlaymodeStateChanged;
#endif
#endif
}
#if UNITY_2018_1_OR_NEWER
#pragma warning disable
[UnityEngine.Scripting.Preserve]
// Just used to preserve methods when building, never called
static void Preserver()
{
Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
MethodInfo mi = typeof(MonoBehaviour).GetMethod("Stub");
}
#pragma warning restore
#endif
#endregion
#if UNITY_EDITOR
// Fires OnApplicationPause in DOTweenComponent even when Editor is paused (otherwise it's only fired at runtime)
#if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1
static void PlaymodeStateChanged()
#else
static void PlaymodeStateChanged(UnityEditor.PlayModeStateChange state)
#endif
{
if (DOTween.instance == null) return;
DOTween.instance.OnApplicationPause(UnityEditor.EditorApplication.isPaused);
}
#endif
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// βββ INTERNAL CLASSES ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
public static class Physics
{
// Called via DOTweenExternalCommand callback
public static void SetOrientationOnPath(PathOptions options, Tween t, Quaternion newRot, Transform trans)
{
#if false // PHYSICS_MARKER
if (options.isRigidbody) ((Rigidbody)t.target).rotation = newRot;
else trans.rotation = newRot;
#else
trans.rotation = newRot;
#endif
}
// Returns FALSE if the DOTween's Physics2D Module is disabled, or if there's no Rigidbody2D attached
public static bool HasRigidbody2D(Component target)
{
#if false // PHYSICS2D_MARKER
return target.GetComponent<Rigidbody2D>() != null;
#else
return false;
#endif
}
#region Called via Reflection
// Called via Reflection by DOTweenPathInspector
// Returns FALSE if the DOTween's Physics Module is disabled, or if there's no rigidbody attached
#if UNITY_2018_1_OR_NEWER
[UnityEngine.Scripting.Preserve]
#endif
public static bool HasRigidbody(Component target)
{
#if false // PHYSICS_MARKER
return target.GetComponent<Rigidbody>() != null;
#else
return false;
#endif
}
// Called via Reflection by DOTweenPath
#if UNITY_2018_1_OR_NEWER
[UnityEngine.Scripting.Preserve]
#endif
public static TweenerCore<Vector3, Path, PathOptions> CreateDOTweenPathTween(
MonoBehaviour target, bool tweenRigidbody, bool isLocal, Path path, float duration, PathMode pathMode
){
TweenerCore<Vector3, Path, PathOptions> t;
#if false // PHYSICS_MARKER
Rigidbody rBody = tweenRigidbody ? target.GetComponent<Rigidbody>() : null;
if (tweenRigidbody && rBody != null) {
t = isLocal
? rBody.DOLocalPath(path, duration, pathMode)
: rBody.DOPath(path, duration, pathMode);
} else {
t = isLocal
? target.transform.DOLocalPath(path, duration, pathMode)
: target.transform.DOPath(path, duration, pathMode);
}
#else
t = isLocal
? target.transform.DOLocalPath(path, duration, pathMode)
: target.transform.DOPath(path, duration, pathMode);
#endif
return t;
}
#endregion
}
}
}
| 412 | 0.866743 | 1 | 0.866743 | game-dev | MEDIA | 0.967968 | game-dev | 0.935364 | 1 | 0.935364 |
gflze/CSGO-ZE-Configs | 6,740 | stripper/ze_silent_hill_2_illusion_b5.cfg | ;fix trigger_push spawnflag bug due to csgo jank
modify:
{
match:
{
"classname" "trigger_push"
"spawnflags" "4097"
}
replace:
{
"spawnflags" "1"
}
}
;Replace physics-based level system with a vscript one
filter:
{
"classname" "func_physbox"
"targetname" "music phy"
}
filter:
{
"classname" "func_physbox"
"targetname" "lv2 white phy"
}
filter:
{
"classname" "func_physbox"
"targetname" "lv2 black phys"
}
filter:
{
"classname" "func_physbox"
"targetname" "lv1 phys"
}
filter:
{
"classname" "func_physbox"
"targetname" "stageromm phys"
}
add:
{
"classname" "logic_relay"
"targetname" "stripper_lvl1_relay"
"OnTrigger" "lv1 tele,Enable,,0,-1"
"OnTrigger" "stgae2 tele,Disable,,0,-1"
}
add:
{
"classname" "logic_relay"
"targetname" "stripper_lvl2white_relay"
"OnTrigger" "stgae2 tele,Enable,,0,-1"
"OnTrigger" "whitestage,Enable,,0,-1"
"OnTrigger" "whitestage2,Enable,,0,-1"
}
add:
{
"classname" "logic_relay"
"targetname" "stripper_lvl2black_relay"
"OnTrigger" "stgae2 teleEnable0-1"
"OnTrigger" "whitestage2Disable0-1"
"OnTrigger" "whitestageDisable0-1"
"OnTrigger" "blackstageEnable0-1"
"OnTrigger" "blackstage2Enable0-1"
"OnTrigger" "blacktriggerEnable0-1"
"OnTrigger" "sctele4Disable0-1"
"OnTrigger" "sctele3Disable0-1"
"OnTrigger" "nowhiteDisable0-1"
"OnTrigger" "exwihteEnable0-1"
"OnTrigger" "exwihte2Enable0-1"
"OnTrigger" "nowhite2Disable0-1"
"OnTrigger" "sun_button stage2Kill0-1"
"OnTrigger" "sun_sign3Kill0-1"
"OnTrigger" "sun_grey3Kill0-1"
"OnTrigger" "stage2 balckwaterKill0-1"
"OnTrigger" "stage3 horrowalltriggleEnable0-1"
"OnTrigger" "sun_button2Unlock0-1"
"OnTrigger" "sun_buttonKill0-1"
"OnTrigger" "stage3 chipKill0-1"
"OnTrigger" "stage3 horrorwall2Toggle0-1"
"OnTrigger" "whitezombieteleEnable0-1"
}
add:
{
"classname" "logic_relay"
"targetname" "stripper_lvlbonus_relay"
"OnTrigger" "lv2 white brushEnable0-1"
"OnTrigger" "lv2 black brushEnable0-1"
"OnTrigger" "lv1brushEnable0-1"
"OnTrigger" "stageroom teleEnable0-1"
}
add:
{
"classname" "logic_relay"
"targetname" "stripper_music_relay"
"OnTrigger" "stage1 startKill0-1"
"OnTrigger" "stage1 twoEnable0-1"
"OnTrigger" "stage1 trueKill0-1"
"OnTrigger" "stage1 true3Kill0-1"
"OnTrigger" "stage1 twoEnable0-1"
"OnTrigger" "musicbounEnable0-1"
"OnTrigger" "blackstageKill0-1"
"OnTrigger" "whitestageKill0-1"
}
add:
{
"classname" "logic_relay"
"targetname" "stripper_levels"
"OnSpawn" "!selfRunScriptCode::_<-delegate{_get=function(idx){return idx}}:{}0-1"
"OnSpawn" "!selfRunScriptCode::__<-(32).tochar()0-1"
"OnSpawn" "!selfRunScriptCodeif (!(_.lvl in getroottable())) ::lvl<-10.02-1"
"OnSpawn" "!selfRunScriptCodeif (!(_.alt_music in getroottable())) ::alt_music<-false0.02-1"
"OnSpawn" "!selfRunScriptCodeif (::lvl == 1) EntFire(_.stripper_lvl1_relay,_.Trigger,__,0,null)0.05-1"
"OnSpawn" "!selfRunScriptCodeif (::lvl == 2) EntFire(_.stripper_lvl2white_relay,_.Trigger,__,0,null)0.05-1"
"OnSpawn" "!selfRunScriptCodeif (::lvl == 3) EntFire(_.stripper_lvl2black_relay,_.Trigger,__,0,null)0.05-1"
"OnSpawn" "!selfRunScriptCodeif (::lvl == 4) EntFire(_.stripper_lvlbonus_relay,_.Trigger,__,0,null)0.05-1"
"OnSpawn" "!selfRunScriptCodeif (::alt_music) EntFire(_.stripper_music_relay,_.Trigger,__,0,null)0.05-1"
}
modify:
{
match:
{
"classname" "func_button"
"targetname" "stage1 button"
}
insert:
{
"OnPressed" "stripper_levelsRunScriptCode::lvl<-133-1"
}
}
modify:
{
match:
{
"classname" "func_button"
"targetname" "stage2 button"
}
insert:
{
"OnPressed" "stripper_levelsRunScriptCode::lvl<-233-1"
}
}
modify:
{
match:
{
"classname" "func_button"
"targetname" "stage3 button"
}
insert:
{
"OnPressed" "stripper_levelsRunScriptCode::lvl<-333-1"
}
}
modify:
{
match:
{
"classname" "trigger_once"
"targetname" "black end"
}
insert:
{
"OnTrigger" "stripper_levelsRunScriptCode::lvl<-43-1"
"OnTrigger" "stripper_levelsRunScriptCode::alt_music<-true2-1"
"OnTrigger" "stripper_music_relayTrigger2-1"
}
}
modify:
{
match:
{
"classname" "trigger_once"
"hammerid" "96215"
}
insert:
{
"OnTrigger" "stripper_levelsRunScriptCode::lvl<-23-1"
}
}
modify:
{
match:
{
"classname" "trigger_once"
"targetname" "whiteend"
}
insert:
{
"OnStartTouch" "stripper_levelsRunScriptCode::lvl<-33-1"
}
}
;patch early trigger nuke exploit for trimming team
modify:
{
match:
{
"classname" "trigger_once"
"targetname" "black end"
}
delete:
{
"OnStartTouch" "S2BOOMTELEEnable3-1"
}
insert:
{
"OnStartTouch" "S2BOOMTELEEnable7-1"
}
}
;prevent players blocking bridge from moving up
modify:
{
match:
{
"classname" "func_movelinear"
"targetname" "move1"
}
replace:
{
"blockdamage" "99999"
}
}
;block off infecting through playerclip/fence props in split hallway
add:
{
"classname" "func_brush"
"origin" "5562 -334.5 699"
"model" "*267"
"angles" "0 90 90"
"rendermode" "10"
}
add:
{
"classname" "func_brush"
"origin" "5568 504.5 699"
"model" "*267"
"angles" "0 90 90"
"rendermode" "10"
}
add:
{
"classname" "func_brush"
"origin" "5576 1017.5 699"
"model" "*267"
"angles" "0 90 90"
"rendermode" "10"
}
add:
{
"classname" "func_brush"
"origin" "5631.64 1475.65 425.44"
"model" "*206"
"angles" "0 132 0"
"rendermode" "10"
}
add:
{
"classname" "func_brush"
"origin" "5631.64 1475.65 408.44"
"model" "*206"
"angles" "0 132 0"
"rendermode" "10"
}
add:
{
"classname" "func_brush"
"origin" "5591.49 1369.6 408.44"
"model" "*206"
"angles" "0 0 0"
"rendermode" "10"
}
add:
{
"classname" "func_brush"
"origin" "5591.49 1245.6 408.44"
"model" "*206"
"angles" "0 0 0"
"rendermode" "10"
}
; Translate the map
;############################ THIS CHANGE WILL NOT WORK WITHOUT HAVING ###################################
;############################ csgo/scripts/vscripts/gfl/sh2_patched.nut ##################################
;###################################### IN THE SERVER FILES ##############################################
;############# https://github.com/gflze/CSGO-ZE-Configs/blob/master/vscripts/sh2_patched.nut #############
modify:
{
match:
{
"classname" "logic_script"
"targetname" "sh2script"
}
replace:
{
"vscripts" "gfl/sh2_patched.nut"
}
}
; Move game_text to the left due to CSGO cutting off text
modify:
{
match:
{
"classname" "game_text"
}
replace:
{
"x" "0.15"
}
}
; Translation credits
modify:
{
match:
{
"classname" "logic_auto"
}
insert:
{
"OnMapSpawn" "cmd,Command,say << Map translated by koen >>,10,1"
}
}
| 412 | 0.905891 | 1 | 0.905891 | game-dev | MEDIA | 0.860918 | game-dev | 0.917245 | 1 | 0.917245 |
manisha-v/MineBlaster | 8,482 | codes/Library/PackageCache/com.unity.timeline@1.2.18/Runtime/Playables/DirectorControlPlayable.cs | using System;
using UnityEngine;
using UnityEngine.Playables;
namespace UnityEngine.Timeline
{
/// <summary>
/// Playable Behaviour used to control a PlayableDirector.
/// </summary>
/// <remarks>
/// This playable is used to control other PlayableDirector components from a Timeline sequence.
/// </remarks>
public class DirectorControlPlayable : PlayableBehaviour
{
/// <summary>
/// The PlayableDirector being controlled by this PlayableBehaviour
/// </summary>
public PlayableDirector director;
private bool m_SyncTime = false;
private double m_AssetDuration = double.MaxValue;
/// <summary>
/// Creates a Playable with a DirectorControlPlayable attached
/// </summary>
/// <param name="graph">The graph to inject the playable into</param>
/// <param name="director">The director to control</param>
/// <returns>Returns a Playable with a DirectorControlPlayable attached</returns>
public static ScriptPlayable<DirectorControlPlayable> Create(PlayableGraph graph, PlayableDirector director)
{
if (director == null)
return ScriptPlayable<DirectorControlPlayable>.Null;
var handle = ScriptPlayable<DirectorControlPlayable>.Create(graph);
handle.GetBehaviour().director = director;
#if UNITY_EDITOR
if (!Application.isPlaying && UnityEditor.PrefabUtility.IsPartOfPrefabInstance(director))
UnityEditor.PrefabUtility.prefabInstanceUpdated += handle.GetBehaviour().OnPrefabUpdated;
#endif
return handle;
}
public override void OnPlayableDestroy(Playable playable)
{
#if UNITY_EDITOR
if (!Application.isPlaying)
UnityEditor.PrefabUtility.prefabInstanceUpdated -= OnPrefabUpdated;
#endif
if (director != null && director.playableAsset != null)
director.Stop();
}
/// <summary>
/// This function is called during the PrepareFrame phase of the PlayableGraph.
/// </summary>
/// <param name="playable">The Playable that owns the current PlayableBehaviour.</param>
/// <param name="info">A FrameData structure that contains information about the current frame context.</param>
public override void PrepareFrame(Playable playable, FrameData info)
{
if (director == null || !director.isActiveAndEnabled || director.playableAsset == null)
return;
// resync the time on an evaluate or a time jump (caused by loops, or some setTime calls)
m_SyncTime |= (info.evaluationType == FrameData.EvaluationType.Evaluate) ||
DetectDiscontinuity(playable, info);
SyncSpeed(info.effectiveSpeed);
SyncPlayState(playable.GetGraph(), playable.GetTime());
}
/// <summary>
/// This function is called when the Playable play state is changed to Playables.PlayState.Playing.
/// </summary>
/// <param name="playable">The Playable that owns the current PlayableBehaviour.</param>
/// <param name="info">A FrameData structure that contains information about the current frame context.</param>
public override void OnBehaviourPlay(Playable playable, FrameData info)
{
m_SyncTime = true;
if (director != null && director.playableAsset != null)
m_AssetDuration = director.playableAsset.duration;
}
/// <summary>
/// This function is called when the Playable play state is changed to PlayState.Paused.
/// </summary>
/// <param name="playable">The playable this behaviour is attached to.</param>
/// <param name="info">A FrameData structure that contains information about the current frame context.</param>
public override void OnBehaviourPause(Playable playable, FrameData info)
{
if (director != null && director.playableAsset != null)
{
if (info.effectivePlayState == PlayState.Playing) // graph was paused
director.Pause();
else
director.Stop();
}
}
/// <summary>
/// This function is called during the ProcessFrame phase of the PlayableGraph.
/// </summary>
/// <param name="playable">The playable this behaviour is attached to.</param>
/// <param name="info">A FrameData structure that contains information about the current frame context.</param>
/// <param name="playerData">unused</param>
public override void ProcessFrame(Playable playable, FrameData info, object playerData)
{
if (director == null || !director.isActiveAndEnabled || director.playableAsset == null)
return;
if (m_SyncTime || DetectOutOfSync(playable))
{
UpdateTime(playable);
director.Evaluate();
}
m_SyncTime = false;
}
#if UNITY_EDITOR
void OnPrefabUpdated(GameObject go)
{
// When the prefab asset is updated, we rebuild the graph to reflect the changes in editor
if (UnityEditor.PrefabUtility.GetRootGameObject(director) == go)
director.RebuildGraph();
}
#endif
void SyncSpeed(double speed)
{
if (director.playableGraph.IsValid())
{
int roots = director.playableGraph.GetRootPlayableCount();
for (int i = 0; i < roots; i++)
{
var rootPlayable = director.playableGraph.GetRootPlayable(i);
if (rootPlayable.IsValid())
{
rootPlayable.SetSpeed(speed);
}
}
}
}
void SyncPlayState(PlayableGraph graph, double playableTime)
{
bool expectedFinished = (playableTime >= m_AssetDuration) && director.extrapolationMode == DirectorWrapMode.None;
if (graph.IsPlaying() && !expectedFinished)
director.Play();
else
director.Pause();
}
bool DetectDiscontinuity(Playable playable, FrameData info)
{
return Math.Abs(playable.GetTime() - playable.GetPreviousTime() - info.m_DeltaTime * info.m_EffectiveSpeed) > DiscreteTime.tickValue;
}
bool DetectOutOfSync(Playable playable)
{
double expectedTime = playable.GetTime();
if (playable.GetTime() >= m_AssetDuration)
{
if (director.extrapolationMode == DirectorWrapMode.None)
return false;
else if (director.extrapolationMode == DirectorWrapMode.Hold)
expectedTime = m_AssetDuration;
else if (m_AssetDuration > float.Epsilon) // loop
expectedTime = expectedTime % m_AssetDuration;
}
if (!Mathf.Approximately((float)expectedTime, (float)director.time))
{
#if UNITY_EDITOR
double lastDelta = playable.GetTime() - playable.GetPreviousTime();
if (UnityEditor.Unsupported.IsDeveloperBuild())
Debug.LogWarningFormat("Internal Warning - Control track desync detected on {2} ({0:F10} vs {1:F10} with delta {3:F10}). Time will be resynchronized. Known to happen with nested control tracks", playable.GetTime(), director.time, director.name, lastDelta);
#endif
return true;
}
return false;
}
// We need to handle loop modes explicitly since we are setting the time directly
void UpdateTime(Playable playable)
{
double duration = Math.Max(0.1, director.playableAsset.duration);
switch (director.extrapolationMode)
{
case DirectorWrapMode.Hold:
director.time = Math.Min(duration, Math.Max(0, playable.GetTime()));
break;
case DirectorWrapMode.Loop:
director.time = Math.Max(0, playable.GetTime() % duration);
break;
case DirectorWrapMode.None:
director.time = playable.GetTime();
break;
}
}
}
}
| 412 | 0.903997 | 1 | 0.903997 | game-dev | MEDIA | 0.958321 | game-dev | 0.954605 | 1 | 0.954605 |
mastercomfig/tf2-patches-old | 2,437 | src/game/client/tf/c_tf_buff_banner.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#include "cbase.h"
#include "c_tf_buff_banner.h"
#include "c_tf_player.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
IMPLEMENT_NETWORKCLASS_ALIASED( TFBuffBanner, DT_TFBuffBanner )
BEGIN_NETWORK_TABLE( C_TFBuffBanner, DT_TFBuffBanner )
END_NETWORK_TABLE()
C_TFBuffBanner::C_TFBuffBanner()
{
m_flDetachTime = 0.f;
m_iBuffType = 0;
}
// -----------------------------------------------------------------------------
// Purpose:
// -----------------------------------------------------------------------------
void CTFBuffBanner::NotifyBoneAttached( C_BaseAnimating* attachTarget )
{
if ( m_hBuffItem )
{
if ( attachTarget != m_hBuffItem->GetOwner() )
{
// We are being moved to a corpse. Let our associated buff item know.
m_hBuffItem->SetBanner( NULL );
}
else
{
float flDuration = 10.f; // 10 is default
CALL_ATTRIB_HOOK_FLOAT_ON_OTHER( attachTarget, flDuration, mod_buff_duration );
m_flDetachTime = gpGlobals->curtime + flDuration;
SetNextClientThink( CLIENT_THINK_ALWAYS );
}
}
BaseClass::NotifyBoneAttached( attachTarget );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFBuffBanner::ClientThink( void )
{
BaseClass::ClientThink();
// DO THIS AFTER BASECLASS::CLIENTTHINK
if ( !m_pAttachedTo || !m_hBuffItem )
{
if ( m_hBuffItem )
{
m_hBuffItem->SetBanner( NULL );
}
Release();
return;
}
// Parachute's never expire
if ( m_iBuffType == EParachute )
{
m_flDetachTime = gpGlobals->curtime + 10.0f;
}
// Normal Banners
if ( m_pAttachedTo )
{
if ( gpGlobals->curtime > m_flDetachTime || !m_hBuffItem )
{
// Destroy us automatically after a period of time.
if ( m_hBuffItem )
{
m_hBuffItem->SetBanner( NULL );
}
Release();
}
else if ( m_pAttachedTo->IsEffectActive( EF_NODRAW ) && !IsEffectActive( EF_NODRAW ) )
{
AddEffects( EF_NODRAW );
UpdateVisibility();
}
else if ( !m_pAttachedTo->IsEffectActive( EF_NODRAW ) && IsEffectActive( EF_NODRAW ) && (m_pAttachedTo != C_BasePlayer::GetLocalPlayer()) )
{
RemoveEffects( EF_NODRAW );
UpdateVisibility();
}
}
} | 412 | 0.974391 | 1 | 0.974391 | game-dev | MEDIA | 0.426785 | game-dev | 0.984437 | 1 | 0.984437 |
petiaccja/Inline-Engine | 6,154 | Engine/GameLogic/EntitySchemeSet.hpp | #pragma once
#include "ComponentMatrix.hpp"
#include "ComponentScheme.hpp"
#include <compare>
#include <memory>
#include <vector>
namespace inl::game {
class Scene;
class Entity;
class EntitySchemeSet {
using EntityVector = ContiguousVector<std::unique_ptr<Entity>>;
template <bool Const>
class generic_iterator {
friend generic_iterator<!Const>;
using EntityIterator = std::conditional_t<Const, EntityVector::const_iterator, EntityVector::iterator>;
public:
using value_type = Entity;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = Entity*;
using iterator_category = std::random_access_iterator_tag;
generic_iterator() = default;
generic_iterator(EntityIterator it) : m_it(it) {}
generic_iterator(const generic_iterator& rhs) = default;
template <class Dummy = void, class = std::enable_if_t<Const, Dummy>>
generic_iterator(const generic_iterator<false>& rhs) : m_it(rhs.m_it) {}
templ::add_const_conditional_t<value_type, Const>& operator*() const { return **m_it; }
templ::add_const_conditional_t<value_type, Const>* operator->() const { return m_it->get(); }
generic_iterator& operator+=(size_t n);
generic_iterator& operator-=(size_t n);
friend generic_iterator operator+(const generic_iterator& it, size_t n) { return generic_iterator{ it } += n; }
friend generic_iterator operator-(const generic_iterator& it, size_t n) { return generic_iterator{ it } -= n; }
friend generic_iterator operator+(size_t n, const generic_iterator& it) { return it + n; }
generic_iterator& operator++();
generic_iterator& operator--();
generic_iterator operator++(int);
generic_iterator operator--(int);
size_t operator-(const generic_iterator& rhs) const;
auto operator<=>(const generic_iterator&) const = default;
private:
EntityIterator m_it;
};
public:
using iterator = generic_iterator<false>;
using const_iterator = generic_iterator<true>;
EntitySchemeSet(Scene& parent);
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
const_iterator cbegin() const;
const_iterator cend() const;
template <class... Components>
Entity& Create(Components&&... components);
void Destroy(Entity& entity);
void Clear();
size_t Size() const;
bool Empty() const;
EntitySchemeSet& operator+=(EntitySchemeSet&& rhs);
template <class... ComponentTypes>
void SetComponentTypes();
template <class ComponentType>
void AddComponentType();
void RemoveComponentType(size_t index);
void CopyComponentTypes(const EntitySchemeSet& model);
Entity& operator[](size_t index);
const Entity& operator[](size_t index) const;
template <class Component>
size_t SpliceExtend(EntitySchemeSet& source, size_t sourceIndex, Component&& component);
size_t SpliceReduce(EntitySchemeSet& source, size_t sourceIndex, size_t skippedComponent);
size_t Splice(EntitySchemeSet& source, size_t sourceIndex);
Scene& GetParent();
const Scene& GetParent() const;
ComponentMatrix& GetMatrix();
const ComponentMatrix& GetMatrix() const;
const ComponentScheme& GetScheme() const;
private:
EntityVector m_entities;
ComponentMatrix m_components;
Scene& m_parent;
ComponentScheme m_scheme;
};
} // namespace inl::game
#include "Entity.hpp"
namespace inl::game {
template <bool Const>
EntitySchemeSet::generic_iterator<Const>& EntitySchemeSet::generic_iterator<Const>::operator+=(size_t n) {
m_it += n;
return *this;
}
template <bool Const>
EntitySchemeSet::generic_iterator<Const>& EntitySchemeSet::generic_iterator<Const>::operator-=(size_t n) {
m_it -= n;
return *this;
}
template <bool Const>
EntitySchemeSet::generic_iterator<Const>& EntitySchemeSet::generic_iterator<Const>::operator++() {
++m_it;
return *this;
}
template <bool Const>
EntitySchemeSet::generic_iterator<Const>& EntitySchemeSet::generic_iterator<Const>::operator--() {
--m_it;
return *this;
}
template <bool Const>
EntitySchemeSet::generic_iterator<Const> EntitySchemeSet::generic_iterator<Const>::operator++(int) {
auto cpy = *this;
++*this;
return cpy;
}
template <bool Const>
EntitySchemeSet::generic_iterator<Const> EntitySchemeSet::generic_iterator<Const>::operator--(int) {
auto cpy = *this;
--*this;
return cpy;
}
template <bool Const>
size_t EntitySchemeSet::generic_iterator<Const>::operator-(const generic_iterator& rhs) const {
return m_it - rhs.m_it;
}
template <class... Components>
Entity& EntitySchemeSet::Create(Components&&... components) {
size_t index = m_entities.size();
m_entities.push_back(std::make_unique<Entity>(&m_parent, this, index));
if (!m_components.types.empty()) {
m_components.entities.emplace_back(std::forward<Components>(components)...);
}
return *m_entities.back();
}
template <class... ComponentTypes>
void EntitySchemeSet::SetComponentTypes() {
m_components.types.clear();
(..., m_components.types.push_back(ComponentVector<std::decay_t<ComponentTypes>>{}));
m_components.entities.resize(m_entities.size());
m_scheme = { typeid(ComponentTypes)... };
}
template <class ComponentType>
void EntitySchemeSet::AddComponentType() {
m_components.types.push_back(ComponentVector<std::decay_t<ComponentType>>{});
m_scheme.Insert(typeid(ComponentType));
}
template <class Component>
size_t EntitySchemeSet::SpliceExtend(EntitySchemeSet& source, size_t sourceIndex, Component&& component) {
m_entities.push_back(std::move(source.m_entities[sourceIndex]));
source.m_entities.erase(source.m_entities.begin() + sourceIndex);
m_components.entities.emplace_back();
if (!source.m_components.entities.empty()) {
m_components.entities.back().assign_extend(std::move(source.m_components.entities.back()), std::forward<Component>(component));
source.m_components.entities.erase(source.m_components.entities.begin() + sourceIndex);
}
else {
m_components.entities.back().assign_extend({}, std::forward<Component>(component));
}
m_entities.back()->m_index = m_entities.size() - 1;
m_entities.back()->m_set = this;
if (source.Size() > sourceIndex) {
source.m_entities[sourceIndex]->m_index = sourceIndex;
}
return m_entities.size() - 1;
}
} // namespace inl::game | 412 | 0.980626 | 1 | 0.980626 | game-dev | MEDIA | 0.32498 | game-dev | 0.947783 | 1 | 0.947783 |
GlodBlock/ExtendedAE | 1,857 | src/main/java/com/glodblock/github/extendedae/client/gui/widget/AssemblerMatrixSlot.java | package com.glodblock.github.extendedae.client.gui.widget;
import appeng.crafting.pattern.EncodedPatternItem;
import appeng.menu.slot.AppEngSlot;
import appeng.util.inv.AppEngInternalInventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
public class AssemblerMatrixSlot extends AppEngSlot {
private final long id;
private final int offset;
public AssemblerMatrixSlot(AppEngInternalInventory machineInv, int machineInvSlot, int offset, long id, int x, int y) {
super(machineInv, machineInvSlot);
this.id = id;
this.offset = offset;
this.x = x;
this.y = y;
}
public int getActuallySlot() {
return this.getSlotIndex() + this.offset;
}
public long getID() {
return this.id;
}
@Override
public ItemStack getDisplayStack() {
if (isRemote()) {
final ItemStack is = super.getDisplayStack();
if (!is.isEmpty() && is.getItem() instanceof EncodedPatternItem<?> iep) {
final ItemStack out = iep.getOutput(is);
if (!out.isEmpty()) {
return out;
}
}
}
return super.getDisplayStack();
}
@Override
public boolean hasItem() {
return !this.getItem().isEmpty();
}
@Override
public final boolean mayPlace(ItemStack stack) {
return false;
}
@Override
public final void set(ItemStack stack) {
}
@Override
public void initialize(ItemStack stack) {
}
@Override
public final int getMaxStackSize() {
return 0;
}
@Override
public final ItemStack remove(int amount) {
return ItemStack.EMPTY;
}
@Override
public final boolean mayPickup(Player player) {
return false;
}
}
| 412 | 0.93437 | 1 | 0.93437 | game-dev | MEDIA | 0.979488 | game-dev | 0.857569 | 1 | 0.857569 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.