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
PaperMC/Paper
2,793
paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFireball.java
package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; import net.minecraft.world.entity.projectile.AbstractHurtingProjectile; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.util.CraftVector; import org.bukkit.entity.Fireball; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; public class CraftFireball extends AbstractProjectile implements Fireball { public CraftFireball(CraftServer server, AbstractHurtingProjectile entity) { super(server, entity); } @Override public AbstractHurtingProjectile getHandle() { return (AbstractHurtingProjectile) this.entity; } @Override public float getYield() { return this.getHandle().bukkitYield; } @Override public boolean isIncendiary() { return this.getHandle().isIncendiary; } @Override public void setIsIncendiary(boolean isIncendiary) { this.getHandle().isIncendiary = isIncendiary; } @Override public void setYield(float yield) { this.getHandle().bukkitYield = yield; } @Override public Vector getDirection() { return this.getAcceleration(); } @Override public void setDirection(Vector direction) { Preconditions.checkArgument(direction != null, "Vector direction cannot be null"); if (direction.isZero()) { this.setVelocity(direction); this.setAcceleration(direction); return; } direction = direction.clone().normalize(); this.setVelocity(direction.clone().multiply(this.getVelocity().length())); this.setAcceleration(direction.multiply(this.getAcceleration().length())); } @Override public void setAcceleration(@NotNull Vector acceleration) { Preconditions.checkArgument(acceleration != null, "Vector acceleration cannot be null"); // SPIGOT-6993: AbstractHurtingProjectile#assignDirectionalMovement will normalize the given values // Note: Because of MC-80142 the fireball will stutter on the client when setting the power to something other than 0 or the normalized vector * 0.1 this.getHandle().assignDirectionalMovement(CraftVector.toVec3(acceleration), acceleration.length()); this.update(); // SPIGOT-6579 } @NotNull @Override public Vector getAcceleration() { return CraftVector.toBukkit(this.getHandle().getDeltaMovement()); } // Paper start - Expose power on fireball projectiles @Override public void setPower(final Vector power) { this.setAcceleration(power); } @Override public Vector getPower() { return this.getAcceleration(); } // Paper end - Expose power on fireball projectiles }
1
0.826903
1
0.826903
game-dev
MEDIA
0.95057
game-dev
0.835748
1
0.835748
StranikS-Scan/WorldOfTanks-Decompiled
1,935
source/res/story_mode/scripts/client/story_mode/gui/scaleform/daapi/view/lobby/header/battle_selector_items.py
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: story_mode/scripts/client/story_mode/gui/scaleform/daapi/view/lobby/header/battle_selector_items.py from __future__ import absolute_import from gui.Scaleform.daapi.view.lobby.header import battle_selector_items from gui.shared.utils import SelectorBattleTypesUtils as selectorUtils from story_mode_common.story_mode_constants import QUEUE_TYPE, PREBATTLE_TYPE from story_mode.gui.story_mode_gui_constants import PREBATTLE_ACTION_NAME, SELECTOR_BATTLE_TYPES from story_mode.skeletons.story_mode_controller import IStoryModeController from gui.impl import backport from gui.impl.gen import R from helpers import dependency def addStoryModeType(items): items.append(_StoryModeItem(backport.text(R.strings.sm_lobby.headerButtons.battle.types.story_mode()), PREBATTLE_ACTION_NAME.STORY_MODE, 2, SELECTOR_BATTLE_TYPES.STORY_MODE)) class _StoryModeItem(battle_selector_items._SelectorItem): storyModeCtrl = dependency.descriptor(IStoryModeController) def select(self): super(_StoryModeItem, self).select() selectorUtils.setBattleTypeAsKnown(self._selectorType) def isRandomBattle(self): return True def setLocked(self, value): self._isLocked = value if self._isLocked: self._isDisabled = True self._isSelected = False def getSmallIcon(self): return backport.image(R.images.story_mode.gui.maps.icons.battleTypes.c_40x40.story_mode()) def getLargerIcon(self): return backport.image(R.images.story_mode.gui.maps.icons.battleTypes.c_64x64.story_mode()) def isInSquad(self, state): return state.isInUnit(PREBATTLE_TYPE.STORY_MODE) def _update(self, state): self._isSelected = state.isQueueSelected(QUEUE_TYPE.STORY_MODE) self._isDisabled = state.hasLockedState or not self.storyModeCtrl.isEnabled() and not self._isSelected
1
0.871011
1
0.871011
game-dev
MEDIA
0.873814
game-dev
0.958465
1
0.958465
FrederoxDev/Amethyst
2,228
AmethystAPI/src/mc/src/common/world/inventory/transaction/ItemUseInventoryTransaction.hpp
/// @symbolgeneration #pragma once #include "mc/src/common/network/NetworkBlockPosition.hpp" #include "mc/src/common/world/Facing.hpp" #include "mc/src/common/world/inventory/transaction/ComplexInventoryTransaction.hpp" #include "mc/src/common/world/level/block/Block.hpp" #include "mc/src/common/world/phys/Vec3.hpp" class Player; enum class InventoryTransactionError : uint64_t { Unknown0 = 0, Success = 1, Unknown2 = 2, ProbablyError = 3, StateMismatch = 7 }; class ItemUseInventoryTransaction : public ComplexInventoryTransaction { public: enum class ActionType { Place, Use, Destroy }; ActionType mActionType; NetworkBlockPosition mPos; BlockRuntimeId mTargetBlockId; FacingID mFace; int32_t mSlot; NetworkItemStackDescriptor mItem; Vec3 mFromPos; Vec3 mClickPos; public: ItemUseInventoryTransaction(); void setTargetBlock(const Block& block) { this->mTargetBlockId = block.getRuntimeId(); } /*void setSelectedItem(const ItemStack& stack) { NetworkItemStackDescriptor networkDescriptor(stack); }*/ /// @signature {48 89 5C 24 ? 55 56 57 41 54 41 55 41 56 41 57 48 8D AC 24 ? ? ? ? 48 81 EC ? ? ? ? 0F 29 B4 24 ? ? ? ? 48 8B 05 ? ? ? ? 48 33 C4 48 89 85 ? ? ? ? 45 0F B6 E0} MC InventoryTransactionError handle(Player& player, bool isSenderAuthority); void resendPlayerState(Player& player) const { using function = decltype(&ItemUseInventoryTransaction::resendPlayerState); static auto func = std::bit_cast<function>(SigScan("48 89 5C 24 ? 48 89 74 24 ? 48 89 7C 24 ? 55 48 8D 6C 24 ? 48 81 EC ? ? ? ? 48 8B 05 ? ? ? ? 48 33 C4 48 89 45 ? 48 8B DA 48 8B 8A")); (this->*func)(player); } void resendBlocksAroundArea(Player& player, const BlockPos& pos, FacingID facing) const { using function = decltype(&ItemUseInventoryTransaction::resendBlocksAroundArea); static auto func = std::bit_cast<function>(SigScan("48 89 5C 24 ? 48 89 7C 24 ? 55 48 8B EC 48 83 EC ? 48 8B 05 ? ? ? ? 48 33 C4 48 89 45 ? 48 8B CA")); (this->*func)(player, pos, facing); } }; static_assert(sizeof(ItemUseInventoryTransaction) == 0x100);
1
0.920411
1
0.920411
game-dev
MEDIA
0.682428
game-dev
0.737505
1
0.737505
magefree/mage
1,836
Mage.Sets/src/mage/cards/k/KatakiWarsWage.java
package mage.cards.k; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.triggers.BeginningOfUpkeepTriggeredAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.costs.mana.GenericManaCost; import mage.abilities.effects.Effect; import mage.abilities.effects.common.SacrificeSourceUnlessPaysEffect; import mage.abilities.effects.common.continuous.GainAbilityAllEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.filter.FilterPermanent; /** * * @author Loki */ public final class KatakiWarsWage extends CardImpl { private static final FilterPermanent filter = new FilterPermanent("artifacts"); static { filter.add(CardType.ARTIFACT.getPredicate()); } public KatakiWarsWage(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{W}"); this.supertype.add(SuperType.LEGENDARY); this.subtype.add(SubType.SPIRIT); this.power = new MageInt(2); this.toughness = new MageInt(1); // All artifacts have "At the beginning of your upkeep, sacrifice this artifact unless you pay {1}." Ability gainedAbility = new BeginningOfUpkeepTriggeredAbility(new SacrificeSourceUnlessPaysEffect(new GenericManaCost(1))); Effect effect = new GainAbilityAllEffect(gainedAbility, Duration.WhileOnBattlefield, filter, false); effect.setText("All artifacts have \"At the beginning of your upkeep, sacrifice this artifact unless you pay {1}.\""); this.addAbility(new SimpleStaticAbility(effect)); } private KatakiWarsWage(final KatakiWarsWage card) { super(card); } @Override public KatakiWarsWage copy() { return new KatakiWarsWage(this); } }
1
0.891748
1
0.891748
game-dev
MEDIA
0.975051
game-dev
0.995507
1
0.995507
jaseowns/uo_outlands_razor_scripts
1,481
outlands.uorazorscripts.com/script/1e0a6976-fe7e-45eb-b11b-12d6228089d1
# This is an automated backup - check out https://outlands.uorazorscripts.com/script/1e0a6976-fe7e-45eb-b11b-12d6228089d1 for latest # Automation by Jaseowns ## Script: Bapeth's Ship Slot Aux Regular Passive ability (Top Row) ## Created by: barryroser#0 ############################################# # Bapeths Ship Slot "Aux Regular Passive" ability (Top Row) # # "****REQUIRED****" # Bapeths Ship Cooldowns xml file (copy paste into your characters Cooldown file) # "COPY" Link to get Bapeths Cooldowns "https://outlands.uorazorscripts.com/script/f1e41e2d-411e-461e-9fd0-c4fc2dc234b1" # "PASTE" FILE PATH : C:\Program Files (x86)\Ultima Online Outlands\ClassicUO\Data\Profiles\"YOUR-ACCOUNT-NAME"\UO Outlands\"YOUR-CHARACTER" Open file in notepad # The cooldowns with "Tigger Text" Must be adjusted to "your ships stats" in the UO in game Options # # This script will use a passive ability # Passive abilities must be "slotted in your ships BOTTOM ROW" of upgrades # If your passive ability is not in the bottom roe the script will not work # # Script will loop into 'Master Background' if you have it in your script library # # Script starts here clearsysmsg say "[AuxiliaryAbility" getlabel backpack ping if insysmsg "you must wait" overhead "Regular Cooling..." 38 script 'Master Background' stop elseif insysmsg "currently be repaired" overhead "It would be no use..." 38 else overhead '*Aux Regular Passive Ability*' 87 endif script 'Master Background'
1
0.860956
1
0.860956
game-dev
MEDIA
0.516193
game-dev
0.905949
1
0.905949
LingFeng-bbben/MajdataPlay
1,900
Assets/Plugins/UniTask/Runtime/CancellationTokenSourceExtensions.cs
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member using System.Threading; using UnityEngine; using Cysharp.Threading.Tasks.Triggers; using System; using Cysharp.Threading.Tasks.Internal; namespace Cysharp.Threading.Tasks { public static partial class CancellationTokenSourceExtensions { readonly static Action<object> CancelCancellationTokenSourceStateDelegate = new Action<object>(CancelCancellationTokenSourceState); static void CancelCancellationTokenSourceState(object state) { var cts = (CancellationTokenSource)state; cts.Cancel(); } public static IDisposable CancelAfterSlim(this CancellationTokenSource cts, int millisecondsDelay, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update) { return CancelAfterSlim(cts, TimeSpan.FromMilliseconds(millisecondsDelay), delayType, delayTiming); } public static IDisposable CancelAfterSlim(this CancellationTokenSource cts, TimeSpan delayTimeSpan, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update) { return PlayerLoopTimer.StartNew(delayTimeSpan, false, delayType, delayTiming, cts.Token, CancelCancellationTokenSourceStateDelegate, cts); } public static void RegisterRaiseCancelOnDestroy(this CancellationTokenSource cts, Component component) { RegisterRaiseCancelOnDestroy(cts, component.gameObject); } public static void RegisterRaiseCancelOnDestroy(this CancellationTokenSource cts, GameObject gameObject) { var trigger = gameObject.GetAsyncDestroyTrigger(); trigger.CancellationToken.RegisterWithoutCaptureExecutionContext(CancelCancellationTokenSourceStateDelegate, cts); } } }
1
0.666388
1
0.666388
game-dev
MEDIA
0.915867
game-dev
0.788168
1
0.788168
FalconClient/FalconClient
2,518
src/main/java/net/minecraft/item/ItemLilyPad.java
package net.minecraft.item; import net.minecraft.block.Block; import net.minecraft.block.BlockLiquid; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.stats.StatList; import net.minecraft.util.BlockPos; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; public class ItemLilyPad extends ItemColored { public ItemLilyPad(Block block) { super(block, false); } /** * 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) { MovingObjectPosition movingobjectposition = this.getMovingObjectPositionFromPlayer(worldIn, playerIn, true); if (movingobjectposition == null) { return itemStackIn; } else { if (movingobjectposition.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { BlockPos blockpos = movingobjectposition.getBlockPos(); if (!worldIn.isBlockModifiable(playerIn, blockpos)) { return itemStackIn; } if (!playerIn.canPlayerEdit(blockpos.offset(movingobjectposition.sideHit), movingobjectposition.sideHit, itemStackIn)) { return itemStackIn; } BlockPos blockpos1 = blockpos.up(); IBlockState iblockstate = worldIn.getBlockState(blockpos); if (iblockstate.getBlock().getMaterial() == Material.water && ((Integer)iblockstate.getValue(BlockLiquid.LEVEL)).intValue() == 0 && worldIn.isAirBlock(blockpos1)) { worldIn.setBlockState(blockpos1, Blocks.waterlily.getDefaultState()); if (!playerIn.capabilities.isCreativeMode) { --itemStackIn.stackSize; } playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); } } return itemStackIn; } } public int getColorFromItemStack(ItemStack stack, int renderPass) { return Blocks.waterlily.getRenderColor(Blocks.waterlily.getStateFromMeta(stack.getMetadata())); } }
1
0.793333
1
0.793333
game-dev
MEDIA
0.998948
game-dev
0.968179
1
0.968179
Pizzalol/SpellLibrary
2,406
game/scripts/vscripts/heroes/hero_pudge/Modifiers/modifier_dismember_lua.lua
modifier_dismember_lua = class({}) -------------------------------------------------------------------------------- function modifier_dismember_lua:IsDebuff() return true end -------------------------------------------------------------------------------- function modifier_dismember_lua:IsStunDebuff() return true end -------------------------------------------------------------------------------- function modifier_dismember_lua:OnCreated( kv ) self.dismember_damage = self:GetAbility():GetSpecialValueFor( "dismember_damage" ) self.tick_rate = self:GetAbility():GetSpecialValueFor( "tick_rate" ) self.strength_damage_scepter = self:GetAbility():GetSpecialValueFor( "strength_damage_scepter" ) if IsServer() then self:GetParent():InterruptChannel() self:OnIntervalThink() self:StartIntervalThink( self.tick_rate ) end end -------------------------------------------------------------------------------- function modifier_dismember_lua:OnDestroy() if IsServer() then self:GetCaster():InterruptChannel() end end -------------------------------------------------------------------------------- function modifier_dismember_lua:OnIntervalThink() if IsServer() then local flDamage = self.dismember_damage if self:GetCaster():HasScepter() then flDamage = flDamage + ( self:GetCaster():GetStrength() * self.strength_damage_scepter ) self:GetCaster():Heal( flDamage, self:GetAbility() ) end local damage = { victim = self:GetParent(), attacker = self:GetCaster(), damage = flDamage, damage_type = DAMAGE_TYPE_MAGICAL, ability = self:GetAbility() } ApplyDamage( damage ) EmitSoundOn( "Hero_Pudge.Dismember", self:GetParent() ) end end -------------------------------------------------------------------------------- function modifier_dismember_lua:CheckState() local state = { [MODIFIER_STATE_STUNNED] = true, [MODIFIER_STATE_INVISIBLE] = false, } return state end -------------------------------------------------------------------------------- function modifier_dismember_lua:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_OVERRIDE_ANIMATION, } return funcs end -------------------------------------------------------------------------------- function modifier_dismember_lua:GetOverrideAnimation( params ) return ACT_DOTA_DISABLED end --------------------------------------------------------------------------------
1
0.883858
1
0.883858
game-dev
MEDIA
0.952997
game-dev
0.795063
1
0.795063
dreameatergames/nuquake_enhanced
13,035
quake/server/sv_user.c
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // sv_user.c -- server code for moving users #include "quakedef.h" edict_t *sv_player; extern cvar_t sv_friction; cvar_t sv_edgefriction = {"edgefriction", "2"}; extern cvar_t sv_stopspeed; static vec3_t forward, right, up; vec3_t wishdir; float wishspeed; // world float *angles; float *origin; float *velocity; qboolean onground; usercmd_t cmd; cvar_t sv_idealpitchscale = {"sv_idealpitchscale","0.8"}; /* =============== SV_SetIdealPitch =============== */ #define MAX_FORWARD 6 void SV_SetIdealPitch (void) { float sinval, cosval; trace_t tr; vec3_t top, bottom; float z[MAX_FORWARD]; int i, j; int step, dir, steps; if (!((int)sv_player->v.flags & FL_ONGROUND)) return; #if defined(_arch_dreamcast) && defined(ENABLE_DC_MATH) fsincos(sv_player->v.angles[YAW], &sinval, &cosval); #else float angleval = sv_player->v.angles[YAW] * M_PI*2 / 360; sinval = SIN(angleval); cosval = COS(angleval); #endif for (i=0 ; i<MAX_FORWARD ; i++) { top[0] = sv_player->v.origin[0] + cosval*(i+3)*12; top[1] = sv_player->v.origin[1] + sinval*(i+3)*12; top[2] = sv_player->v.origin[2] + sv_player->v.view_ofs[2]; bottom[0] = top[0]; bottom[1] = top[1]; bottom[2] = top[2] - 160; tr = SV_Move (top, vec3_origin, vec3_origin, bottom, 1, sv_player); if (tr.allsolid) return; // looking at a wall, leave ideal the way is was if (tr.fraction == 1) return; // near a dropoff z[i] = top[2] + tr.fraction*(bottom[2]-top[2]); } dir = 0; steps = 0; for (j=1 ; j<i ; j++) { step = z[j] - z[j-1]; if (step > -ON_EPSILON && step < ON_EPSILON) continue; if (dir && ( step-dir > ON_EPSILON || step-dir < -ON_EPSILON ) ) return; // mixed changes steps++; dir = step; } if (!dir) { sv_player->v.idealpitch = 0; return; } if (steps < 2) return; sv_player->v.idealpitch = -dir * sv_idealpitchscale.value; } /* ================== SV_UserFriction ================== */ void SV_UserFriction (void) { float *vel; float speed, newspeed, control; vec3_t start, stop; float friction; trace_t trace; vel = velocity; speed = SQRT(vel[0]*vel[0] +vel[1]*vel[1]); if (!speed) return; // if the leading edge is over a dropoff, increase friction start[0] = stop[0] = origin[0] + vel[0]/speed*16; start[1] = stop[1] = origin[1] + vel[1]/speed*16; start[2] = origin[2] + sv_player->v.mins[2]; stop[2] = start[2] - 34; trace = SV_Move (start, vec3_origin, vec3_origin, stop, true, sv_player); if (trace.fraction == 1.0) friction = sv_friction.value*sv_edgefriction.value; else friction = sv_friction.value; // apply friction control = speed < sv_stopspeed.value ? sv_stopspeed.value : speed; newspeed = speed - host_frametime*control*friction; if (newspeed < 0) newspeed = 0; newspeed /= speed; vel[0] = vel[0] * newspeed; vel[1] = vel[1] * newspeed; vel[2] = vel[2] * newspeed; } /* ============== SV_Accelerate ============== */ cvar_t sv_maxspeed = {"sv_maxspeed", "320", false, true}; cvar_t sv_accelerate = {"sv_accelerate", "10"}; #if 0 void SV_Accelerate (vec3_t wishvel) { int i; float addspeed, accelspeed; vec3_t pushvec; if (wishspeed == 0) return; VectorSubtract (wishvel, velocity, pushvec); addspeed = VectorNormalize (pushvec); accelspeed = sv_accelerate.value*host_frametime*addspeed; if (accelspeed > addspeed) accelspeed = addspeed; for (i=0 ; i<3 ; i++) velocity[i] += accelspeed*pushvec[i]; } #endif void SV_Accelerate (void) { int i; float addspeed, accelspeed, currentspeed; currentspeed = DotProduct (velocity, wishdir); addspeed = wishspeed - currentspeed; if (addspeed <= 0) return; accelspeed = sv_accelerate.value*host_frametime*wishspeed; if (accelspeed > addspeed) accelspeed = addspeed; for (i=0 ; i<3 ; i++) velocity[i] += accelspeed*wishdir[i]; } void SV_AirAccelerate (vec3_t wishveloc) { int i; float addspeed, wishspd, accelspeed, currentspeed; wishspd = VectorNormalize (wishveloc); if (wishspd > 30) wishspd = 30; currentspeed = DotProduct (velocity, wishveloc); addspeed = wishspd - currentspeed; if (addspeed <= 0) return; // accelspeed = sv_accelerate.value * host_frametime; accelspeed = sv_accelerate.value*wishspeed * host_frametime; if (accelspeed > addspeed) accelspeed = addspeed; for (i=0 ; i<3 ; i++) velocity[i] += accelspeed*wishveloc[i]; } void DropPunchAngle (void) { float len; len = VectorNormalize (sv_player->v.punchangle); len -= 10*host_frametime; if (len < 0) len = 0; VectorScale (sv_player->v.punchangle, len, sv_player->v.punchangle); } /* =================== SV_WaterMove =================== */ void SV_WaterMove (void) { int i; vec3_t wishvel; float speed, newspeed, wishspeed, addspeed, accelspeed; // // user intentions // AngleVectors (sv_player->v.v_angle, forward, right, up); for (i=0 ; i<3 ; i++) wishvel[i] = forward[i]*cmd.forwardmove + right[i]*cmd.sidemove; if (!cmd.forwardmove && !cmd.sidemove && !cmd.upmove) wishvel[2] -= 60; // drift towards bottom else wishvel[2] += cmd.upmove; wishspeed = Length(wishvel); if (wishspeed > sv_maxspeed.value) { VectorScale (wishvel, sv_maxspeed.value/wishspeed, wishvel); wishspeed = sv_maxspeed.value; } wishspeed *= 0.7; // // water friction // speed = Length (velocity); if (speed) { newspeed = speed - host_frametime * speed * sv_friction.value; if (newspeed < 0) newspeed = 0; VectorScale (velocity, newspeed/speed, velocity); } else newspeed = 0; // // water acceleration // if (!wishspeed) return; addspeed = wishspeed - newspeed; if (addspeed <= 0) return; VectorNormalize (wishvel); accelspeed = sv_accelerate.value * wishspeed * host_frametime; if (accelspeed > addspeed) accelspeed = addspeed; for (i=0 ; i<3 ; i++) velocity[i] += accelspeed * wishvel[i]; } void SV_WaterJump (void) { if (sv.time > sv_player->v.teleport_time || !sv_player->v.waterlevel) { sv_player->v.flags = (int)sv_player->v.flags & ~FL_WATERJUMP; sv_player->v.teleport_time = 0; } sv_player->v.velocity[0] = sv_player->v.movedir[0]; sv_player->v.velocity[1] = sv_player->v.movedir[1]; } /* =================== SV_AirMove =================== */ void SV_AirMove (void) { int i; vec3_t wishvel; float fmove, smove; AngleVectors (sv_player->v.angles, forward, right, up); fmove = cmd.forwardmove; smove = cmd.sidemove; // hack to not let you back into teleporter if (sv.time < sv_player->v.teleport_time && fmove < 0) fmove = 0; for (i=0 ; i<3 ; i++) wishvel[i] = forward[i]*fmove + right[i]*smove; if ( (int)sv_player->v.movetype != MOVETYPE_WALK) wishvel[2] = cmd.upmove; else wishvel[2] = 0; VectorCopy (wishvel, wishdir); wishspeed = VectorNormalize(wishdir); if (wishspeed > sv_maxspeed.value) { VectorScale (wishvel, sv_maxspeed.value/wishspeed, wishvel); wishspeed = sv_maxspeed.value; } if ( sv_player->v.movetype == MOVETYPE_NOCLIP) { // noclip VectorCopy (wishvel, velocity); } else if ( onground ) { SV_UserFriction (); SV_Accelerate (); } else { // not on ground, so little effect on velocity SV_AirAccelerate (wishvel); } } /* =================== SV_ClientThink the move fields specify an intended velocity in pix/sec the angle fields specify an exact angular motion in degrees =================== */ void SV_ClientThink (void) { vec3_t v_angle; if (sv_player->v.movetype == MOVETYPE_NONE) return; onground = !!((int)(sv_player->v.flags) & FL_ONGROUND); origin = sv_player->v.origin; velocity = sv_player->v.velocity; DropPunchAngle (); // // if dead, behave differently // if (sv_player->v.health <= 0) return; // // angles // show 1/3 the pitch angle and all the roll angle cmd = host_client->cmd; angles = sv_player->v.angles; VectorAdd (sv_player->v.v_angle, sv_player->v.punchangle, v_angle); angles[ROLL] = V_CalcRoll (sv_player->v.angles, sv_player->v.velocity)*4; if (!sv_player->v.fixangle) { angles[PITCH] = -v_angle[PITCH]/3; angles[YAW] = v_angle[YAW]; } if ( (int)sv_player->v.flags & FL_WATERJUMP ) { SV_WaterJump (); return; } // // walk // if ( (sv_player->v.waterlevel >= 2) && (sv_player->v.movetype != MOVETYPE_NOCLIP) ) { SV_WaterMove (); return; } SV_AirMove (); } /* =================== SV_ReadClientMove =================== */ void SV_ReadClientMove (usercmd_t *move) { int i; vec3_t angle; int bits; // read ping time host_client->ping_times[host_client->num_pings%NUM_PING_TIMES] = sv.time - MSG_ReadFloat (); host_client->num_pings++; // read current angles for (i=0 ; i<3 ; i++) angle[i] = MSG_ReadAngle (); VectorCopy (angle, host_client->edict->v.v_angle); // read movement move->forwardmove = MSG_ReadShort (); move->sidemove = MSG_ReadShort (); move->upmove = MSG_ReadShort (); // read buttons bits = MSG_ReadByte (); host_client->edict->v.button0 = bits & 1; host_client->edict->v.button2 = (bits & 2)>>1; i = MSG_ReadByte (); if (i) host_client->edict->v.impulse = i; #ifdef QUAKE2 // read light level host_client->edict->v.light_level = MSG_ReadByte (); #endif } /* =================== SV_ReadClientMessage Returns false if the client should be killed =================== */ qboolean SV_ReadClientMessage (void) { int ret; int cmd; char *s; do { nextmsg: ret = NET_GetMessage (host_client->netconnection); if (ret == -1) { Sys_Printf ("SV_ReadClientMessage: NET_GetMessage failed\n"); return false; } if (!ret) return true; MSG_BeginReading (); while (1) { if (!host_client->active) return false; // a command caused an error if (msg_badread) { Sys_Printf ("SV_ReadClientMessage: badread\n"); return false; } cmd = MSG_ReadChar (); switch (cmd) { case -1: goto nextmsg; // end of message default: Sys_Printf ("SV_ReadClientMessage: unknown command char\n"); return false; case clc_nop: // Sys_Printf ("clc_nop\n"); break; case clc_stringcmd: s = MSG_ReadString (); if (host_client->privileged) ret = 2; else ret = 0; if (strncasecmp(s, "status", 6) == 0) ret = 1; else if (strncasecmp(s, "god", 3) == 0) ret = 1; else if (strncasecmp(s, "notarget", 8) == 0) ret = 1; else if (strncasecmp(s, "fly", 3) == 0) ret = 1; else if (strncasecmp(s, "name", 4) == 0) ret = 1; else if (strncasecmp(s, "noclip", 6) == 0) ret = 1; else if (strncasecmp(s, "say", 3) == 0) ret = 1; else if (strncasecmp(s, "say_team", 8) == 0) ret = 1; else if (strncasecmp(s, "tell", 4) == 0) ret = 1; else if (strncasecmp(s, "color", 5) == 0) ret = 1; else if (strncasecmp(s, "kill", 4) == 0) ret = 1; else if (strncasecmp(s, "pause", 5) == 0) ret = 1; else if (strncasecmp(s, "spawn", 5) == 0) ret = 1; else if (strncasecmp(s, "begin", 5) == 0) ret = 1; else if (strncasecmp(s, "prespawn", 8) == 0) ret = 1; else if (strncasecmp(s, "kick", 4) == 0) ret = 1; else if (strncasecmp(s, "ping", 4) == 0) ret = 1; else if (strncasecmp(s, "give", 4) == 0) ret = 1; else if (strncasecmp(s, "ban", 3) == 0) ret = 1; if (ret == 2) Cbuf_InsertText (s); else if (ret == 1) Cmd_ExecuteString (s, src_client); else Con_DPrintf("%s tried to %s\n", host_client->name, s); break; case clc_disconnect: // Sys_Printf ("SV_ReadClientMessage: client disconnected\n"); return false; case clc_move: SV_ReadClientMove (&host_client->cmd); break; } } } while (ret == 1); return true; } /* ================== SV_RunClients ================== */ void SV_RunClients (void) { int i; for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++) { if (!host_client->active) continue; sv_player = host_client->edict; if (!SV_ReadClientMessage ()) { SV_DropClient (false); // client misbehaved... continue; } if (!host_client->spawned) { // clear client movement until a new packet is received memset (&host_client->cmd, 0, sizeof(host_client->cmd)); continue; } // always pause in single player if in console or menus if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) ) SV_ClientThink (); } }
1
0.822074
1
0.822074
game-dev
MEDIA
0.357729
game-dev
0.973742
1
0.973742
The-Assembly-Knight/tilt-yard
1,521
include/tiltyard_API.h
#pragma once #include <sys/types.h> #include <stdint.h> typedef struct { uint8_t *base; size_t capacity; size_t offset; size_t last_alloc_offset; size_t high_water; size_t alloc_count; } Arena; typedef struct { size_t capacity; size_t used; size_t available; size_t high_water; size_t alloc_count; size_t last_alloc_offset; } TiltyardStats; Arena *tiltyard_create(size_t capacity); void *tiltyard_alloc(Arena *arena, size_t size); void *tiltyard_calloc(Arena *arena, size_t size); void *tiltyard_alloc_aligned(Arena *arena, size_t size, size_t alignment); void *tiltyard_calloc_aligned(Arena *arena, size_t size, size_t alignment); void tiltyard_destroy(Arena *arena); void tiltyard_wipe(Arena *arena); void tiltyard_null(Arena **arena); void tiltyard_destroy_and_null(Arena **arena); void tiltyard_wipe_destroy_and_null(Arena **arena); void tiltyard_reset(Arena *arena); size_t tiltyard_get_marker(Arena *arena); void tiltyard_reset_to(Arena *arena, size_t marker); void tiltyard_clean_until(Arena *arena, size_t marker); void tiltyard_clean_from(Arena *arena, size_t marker); void tiltyard_clean_from_until(Arena *arena, size_t marker_beg, size_t marker_end); size_t tiltyard_get_capacity(Arena *arena); size_t tiltyard_get_used_capacity(Arena *arena); size_t tiltyard_get_available_capacity(Arena *arena); size_t tiltyard_get_high_water(Arena *arena); size_t tiltyard_get_alloc_count(Arena *arena); size_t tiltyard_get_last_alloc(Arena *arena); TiltyardStats tiltyard_get_stats(Arena *arena);
1
0.758426
1
0.758426
game-dev
MEDIA
0.74662
game-dev
0.500717
1
0.500717
fholger/thedarkmodvr
11,735
game/ModMenu.cpp
/***************************************************************************** The Dark Mod GPL Source Code This file is part of the The Dark Mod Source Code, originally based on the Doom 3 GPL Source Code as published in 2011. The Dark Mod Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For details, see LICENSE.TXT. Project: The Dark Mod (http://www.thedarkmod.com/) ******************************************************************************/ #include "precompiled.h" #pragma hdrstop #include <string> #include "ModMenu.h" #include "Shop/Shop.h" #include "Objectives/MissionData.h" #include "declxdata.h" #include "ZipLoader/ZipLoader.h" #include "Missions/MissionManager.h" #ifdef _WINDOWS #include <process.h> #else #include <limits.h> #include <unistd.h> #endif CModMenu::CModMenu() : _modTop(0) {} #include <StdFilesystem.h> namespace fs = stdext; // Handle mainmenu commands void CModMenu::HandleCommands(const idStr& cmd, idUserInterface* gui) { if (cmd == "refreshMissionList") { int numNewMods = gameLocal.m_MissionManager->GetNumNewMods(); if (numNewMods > 0) { // Update mission DB records gameLocal.m_MissionManager->RefreshMetaDataForNewFoundMods(); gui->SetStateString("newFoundMissionsText", common->Translate( "#str_02143" ) ); // New missions available gui->SetStateString("newFoundMissionsList", gameLocal.m_MissionManager->GetNewFoundModsText()); gui->HandleNamedEvent("OnNewMissionsFound"); gameLocal.m_MissionManager->ClearNewModList(); } gameLocal.m_MissionManager->ReloadModList(); // Update the GUI state UpdateGUI(gui); } else if (cmd == "mainMenuStartup") { gui->SetStateBool("curModIsCampaign", gameLocal.m_MissionManager->CurrentModIsCampaign()); //stgatilov: we need to set cvar early, otherwise state switching code will "play nosound" gui->SetStateBool("menu_bg_music", cv_tdm_menu_music.GetBool()); } else if (cmd == "loadModNotes") { // Get selected mod int modIndex = gui->GetStateInt("missionList_sel_0", "-1"); CModInfoPtr info = gameLocal.m_MissionManager->GetModInfo(modIndex); // Load the readme.txt contents, if available gui->SetStateString("ModNotesText", info != NULL ? info->GetModNotes() : ""); } else if (cmd == "onMissionSelected") { UpdateSelectedMod(gui); } /*else if (cmd == "eraseSelectedModFromDisk") { int modIndex = gui->GetStateInt("missionList_sel_0", "-1"); CModInfoPtr info = gameLocal.m_MissionManager->GetModInfo(modIndex); if (info != NULL) { gameLocal.m_MissionManager->CleanupModFolder(info->modName); } gui->HandleNamedEvent("OnSelectedMissionErasedFromDisk"); // Update the selected mission UpdateSelectedMod(gui); }*/ else if (cmd == "update") { gameLocal.Error("Deprecated update method called by main menu."); } else if (cmd == "onClickInstallSelectedMission") { // Get selected mod int modIndex = gui->GetStateInt("missionList_sel_0", "-1"); CModInfoPtr info = gameLocal.m_MissionManager->GetModInfo(modIndex); if (info == NULL) return; // sanity check // Issue the named command to the GUI gui->SetStateString("modInstallProgressText", common->Translate( "#str_02504" ) + info->displayName); // "Installing Mission Package\n\n" } else if (cmd == "installSelectedMission") { // Get selected mod int modIndex = gui->GetStateInt("missionList_sel_0", "-1"); CModInfoPtr info = gameLocal.m_MissionManager->GetModInfo(modIndex); if (info == NULL) return; // sanity check if (!PerformVersionCheck(info, gui)) { return; // version check failed } InstallMod(info, gui); } else if (cmd == "darkmodRestart") { RestartEngine(); } else if (cmd == "briefing_show") { // Display the briefing text _briefingPage = 1; DisplayBriefingPage(gui); } else if (cmd == "briefing_scroll_down_request") { // Display the next page of briefing text _briefingPage++; DisplayBriefingPage(gui); } else if (cmd == "briefing_scroll_up_request") { // Display the previous page of briefing text _briefingPage--; DisplayBriefingPage(gui); } else if (cmd == "uninstallMod") { UninstallMod(gui); } else if (cmd == "startSelect") // grayman #2933 - save mission start position { gameLocal.m_StartPosition = gui->GetStateString("startSelect", ""); } } void CModMenu::UpdateSelectedMod(idUserInterface* gui) { // Get selected mod int modIndex = gui->GetStateInt("missionList_sel_0", "-1"); CModInfoPtr info = gameLocal.m_MissionManager->GetModInfo(modIndex); if (info != NULL) { bool missionIsCurrentlyInstalled = gameLocal.m_MissionManager->GetCurrentModName() == info->modName; idStr name = common->Translate( info != NULL ? info->displayName : ""); gui->SetStateString("mod_name", name); gui->SetStateString("mod_desc", common->Translate( info != NULL ? info->description : "")); gui->SetStateString("mod_author", info != NULL ? info->author : ""); gui->SetStateString("mod_image", info != NULL ? info->image : ""); // Don't display the install button if the mod is already installed gui->SetStateBool("installModButtonVisible", !missionIsCurrentlyInstalled); gui->SetStateBool("hasModNoteButton", info->HasModNotes()); // Set the mod size info std::size_t missionSize = info->GetModFolderSize(); idStr missionSizeStr = info->GetModFolderSizeString(); gui->SetStateString("selectedModSize", missionSize > 0 ? missionSizeStr : "-"); gui->SetStateBool("eraseSelectedModButtonVisible", missionSize > 0 && !missionIsCurrentlyInstalled); // 07208: "You're about to delete the gameplay contents of the mission folder from your disk (mainly savegames and screenshots):" // 07209: "Note that the mission PK4 itself in your darkmod/fms/ folder will not be removed by this operation, you'll still able to play the mission." idStr eraseMissionText = va( idStr( common->Translate( "#str_07208" ) ) + "\n\n%s\n\n" + common->Translate( "#str_07209" ), info->GetModFolderPath().c_str() ); gui->SetStateString("eraseMissionText", eraseMissionText); gui->SetStateString("selectedModCompleted", info->GetModCompletedString()); gui->SetStateString("selectedModLastPlayDate", info->GetKeyValue("last_play_date", "-")); gui->SetStateBool("modToInstallVisible", true); } else { gui->SetStateBool("modToInstallVisible", false); gui->SetStateBool("installModButtonVisible", false); gui->SetStateString("selectedModSize", "0 Bytes"); gui->SetStateBool("eraseSelectedModButtonVisible", false); gui->SetStateBool("hasModNoteButton", false); } } // Displays the current page of briefing text void CModMenu::DisplayBriefingPage(idUserInterface* gui) { // look up the briefing xdata, which is in "maps/<map name>/mission_briefing" idStr briefingData = idStr("maps/") + gameLocal.m_MissionManager->GetCurrentStartingMap() + "/mission_briefing"; gameLocal.Printf("DisplayBriefingPage: briefingData is %s\n", briefingData.c_str()); // Load the XData declaration const tdmDeclXData* xd = static_cast<const tdmDeclXData*>( declManager->FindType(DECL_XDATA, briefingData, false) ); const char* briefing = ""; bool scrollDown = false; bool scrollUp = false; if (xd != NULL) { gameLocal.Printf("DisplayBriefingPage: xdata found.\n"); // get page count from xdata (tels: and if nec., translate it #3193) idStr strNumPages = common->Translate( xd->m_data.GetString("num_pages") ); if (!strNumPages.IsNumeric()) { gameLocal.Warning("DisplayBriefingPage: num_pages '%s' is not numeric!", strNumPages.c_str()); } else { int numPages = atoi(strNumPages.c_str()); gameLocal.Printf("DisplayBriefingPage: numPages is %d\n", numPages); // ensure current page is between 1 and page count, inclusive _briefingPage = idMath::ClampInt(1, numPages, _briefingPage); // load up page text idStr page = va("page%d_body", _briefingPage); gameLocal.Printf("DisplayBriefingPage: current page is %d\n", _briefingPage); // Tels: Translate it properly briefing = common->Translate( xd->m_data.GetString(page) ); // set scroll button visibility scrollDown = numPages > _briefingPage; scrollUp = _briefingPage > 1; } } else { gameLocal.Warning("DisplayBriefingPage: Could not find briefing xdata: %s", briefingData.c_str()); } // update GUI gui->SetStateString("BriefingText", briefing); gui->SetStateBool("ScrollDownVisible", scrollDown); gui->SetStateBool("ScrollUpVisible", scrollUp); } void CModMenu::UpdateGUI(idUserInterface* gui) { const int num_mods = gameLocal.m_MissionManager->GetNumMods(); CModInfoPtr info; for (int index = 0; index < num_mods; ++index) { info = gameLocal.m_MissionManager->GetModInfo(index); idStr name = common->Translate( info != NULL ? info->displayName : ""); // alexdiru #4499 /* // grayman #3110 idStr prefix = ""; idStr suffix = ""; common->GetI18N()->MoveArticlesToBack( name, prefix, suffix ); if ( !suffix.IsEmpty() ) { // found, remove prefix and append suffix name.StripLeadingOnce( prefix.c_str() ); name += suffix; } */ name += "\t"; if (info->ModCompleted()) { name += "mtr_complete"; } gui->SetStateString( va("missionList_item_%d", index), name); } CModInfoPtr curModInfo = gameLocal.m_MissionManager->GetCurrentModInfo(); gui->SetStateBool("hasCurrentMod", curModInfo != NULL); gui->SetStateString("currentModName", common->Translate( curModInfo != NULL ? curModInfo->displayName : "#str_02189" )); // <No Mission Installed> gui->SetStateString("currentModDesc", common->Translate( curModInfo != NULL ? curModInfo->description : "" )); gui->StateChanged(gameLocal.time); } bool CModMenu::PerformVersionCheck(const CModInfoPtr& mission, idUserInterface* gui) { // Check the required TDM version of this FM if (CompareVersion(TDM_VERSION_MAJOR, TDM_VERSION_MINOR, mission->requiredMajor, mission->requiredMinor) == OLDER) { gui->SetStateString("requiredVersionCheckFailText", // "Cannot install this mission, as it requires\n%s v%d.%02d.\n\nYou are running v%d.%02d. Please run the tdm_update application to update your installation.", va( common->Translate( "#str_07210" ), GAME_VERSION, mission->requiredMajor, mission->requiredMinor, TDM_VERSION_MAJOR, TDM_VERSION_MINOR)); gui->HandleNamedEvent("OnRequiredVersionCheckFail"); return false; } return true; // version check passed } void CModMenu::InstallMod(const CModInfoPtr& mod, idUserInterface* gui) { assert(mod != NULL); assert(gui != NULL); // Perform the installation CMissionManager::InstallResult result = gameLocal.m_MissionManager->InstallMod(mod->modName); if (result != CMissionManager::INSTALLED_OK) { idStr msg; switch (result) { case CMissionManager::COPY_FAILURE: msg = common->Translate( "#str_02010" ); // Could not copy files... break; default: msg = common->Translate( "#str_02011" ); // No further explanation available. Well, this was kind of unexpected. }; // Feed error messages to GUI gui->SetStateString("modInstallationFailedText", msg); gui->HandleNamedEvent("OnModInstallationFailed"); } else { gui->HandleNamedEvent("OnModInstallationFinished"); } } void CModMenu::UninstallMod(idUserInterface* gui) { gameLocal.m_MissionManager->UninstallMod(); gui->HandleNamedEvent("OnModUninstallFinished"); } void CModMenu::RestartEngine() { // We restart the game by issuing a restart engine command only, this activates any newly installed mod cmdSystem->SetupReloadEngine(idCmdArgs()); }
1
0.957623
1
0.957623
game-dev
MEDIA
0.811948
game-dev,desktop-app
0.946915
1
0.946915
andstatus/game2048
1,544
src/commonMain/kotlin/org/andstatus/game2048/view/SelectTheme.kt
package org.andstatus.game2048.view import korlibs.io.async.launch import korlibs.korge.time.delay import korlibs.korge.view.Container import korlibs.korge.view.addTo import korlibs.korge.view.position import korlibs.time.milliseconds import org.andstatus.game2048.MyContext fun ViewData.selectTheme(myContext: MyContext) = myWindow("select_theme") { var selected = myContext.settings.colorThemeEnum var buttons: List<Container> = emptyList() suspend fun button(buttonEnum: ColorThemeEnum, yInd: Int, handler: (ColorThemeEnum) -> Unit): Container = wideButton( if (buttonEnum == selected) "radio_button_checked" else "radio_button_unchecked", buttonEnum.labelKey ) { handler(buttonEnum) }.apply { position(buttonXs[0], buttonYs[yInd]) addTo(window) } suspend fun showOptions(handler: (ColorThemeEnum) -> Unit) { val oldButtons = buttons buttons = listOf( button(ColorThemeEnum.DEVICE_DEFAULT, 1, handler), button(ColorThemeEnum.DARK, 2, handler), button(ColorThemeEnum.LIGHT, 3, handler) ) oldButtons.forEach { b -> b.removeFromParent() } } fun onSelected(colorTheme: ColorThemeEnum) { selected = colorTheme korgeCoroutineScope.launch { showOptions {} delay(100.milliseconds) presenter.onSelectColorTheme(selected) window.removeFromParent() } } showOptions(::onSelected) }
1
0.90771
1
0.90771
game-dev
MEDIA
0.268613
game-dev
0.969362
1
0.969362
DrFlower/TowerDefense-GameFramework-Demo
2,030
Assets/GameFramework/Libraries/GameFramework/Entity/EntityManager.EntityInstanceObject.cs
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2021 Jiang Yin. All rights reserved. // Homepage: https://gameframework.cn/ // Feedback: mailto:ellan@gameframework.cn //------------------------------------------------------------ using GameFramework.ObjectPool; namespace GameFramework.Entity { internal sealed partial class EntityManager : GameFrameworkModule, IEntityManager { /// <summary> /// 实体实例对象。 /// </summary> private sealed class EntityInstanceObject : ObjectBase { private object m_EntityAsset; private IEntityHelper m_EntityHelper; public EntityInstanceObject() { m_EntityAsset = null; m_EntityHelper = null; } public static EntityInstanceObject Create(string name, object entityAsset, object entityInstance, IEntityHelper entityHelper) { if (entityAsset == null) { throw new GameFrameworkException("Entity asset is invalid."); } if (entityHelper == null) { throw new GameFrameworkException("Entity helper is invalid."); } EntityInstanceObject entityInstanceObject = ReferencePool.Acquire<EntityInstanceObject>(); entityInstanceObject.Initialize(name, entityInstance); entityInstanceObject.m_EntityAsset = entityAsset; entityInstanceObject.m_EntityHelper = entityHelper; return entityInstanceObject; } public override void Clear() { base.Clear(); m_EntityAsset = null; m_EntityHelper = null; } protected internal override void Release(bool isShutdown) { m_EntityHelper.ReleaseEntity(m_EntityAsset, Target); } } } }
1
0.824002
1
0.824002
game-dev
MEDIA
0.90941
game-dev
0.813611
1
0.813611
qcdong2016/QCEditor
19,463
cocos2d/external/bullet/include/bullet/BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /// 2009 March: btGeneric6DofConstraint refactored by Roman Ponomarev /// Added support for generic constraint solver through getInfo1/getInfo2 methods /* 2007-09-09 btGeneric6DofConstraint Refactored by Francisco Le?n email: projectileman@yahoo.com http://gimpact.sf.net */ #ifndef BT_GENERIC_6DOF_CONSTRAINT_H #define BT_GENERIC_6DOF_CONSTRAINT_H #include "LinearMath/btVector3.h" #include "btJacobianEntry.h" #include "btTypedConstraint.h" class btRigidBody; #ifdef BT_USE_DOUBLE_PRECISION #define btGeneric6DofConstraintData2 btGeneric6DofConstraintDoubleData2 #define btGeneric6DofConstraintDataName "btGeneric6DofConstraintDoubleData2" #else #define btGeneric6DofConstraintData2 btGeneric6DofConstraintData #define btGeneric6DofConstraintDataName "btGeneric6DofConstraintData" #endif //BT_USE_DOUBLE_PRECISION //! Rotation Limit structure for generic joints class btRotationalLimitMotor { public: //! limit_parameters //!@{ btScalar m_loLimit;//!< joint limit btScalar m_hiLimit;//!< joint limit btScalar m_targetVelocity;//!< target motor velocity btScalar m_maxMotorForce;//!< max force on motor btScalar m_maxLimitForce;//!< max force on limit btScalar m_damping;//!< Damping. btScalar m_limitSoftness;//! Relaxation factor btScalar m_normalCFM;//!< Constraint force mixing factor btScalar m_stopERP;//!< Error tolerance factor when joint is at limit btScalar m_stopCFM;//!< Constraint force mixing factor when joint is at limit btScalar m_bounce;//!< restitution factor bool m_enableMotor; //!@} //! temp_variables //!@{ btScalar m_currentLimitError;//! How much is violated this limit btScalar m_currentPosition; //! current value of angle int m_currentLimit;//!< 0=free, 1=at lo limit, 2=at hi limit btScalar m_accumulatedImpulse; //!@} btRotationalLimitMotor() { m_accumulatedImpulse = 0.f; m_targetVelocity = 0; m_maxMotorForce = 0.1f; m_maxLimitForce = 300.0f; m_loLimit = 1.0f; m_hiLimit = -1.0f; m_normalCFM = 0.f; m_stopERP = 0.2f; m_stopCFM = 0.f; m_bounce = 0.0f; m_damping = 1.0f; m_limitSoftness = 0.5f; m_currentLimit = 0; m_currentLimitError = 0; m_enableMotor = false; } btRotationalLimitMotor(const btRotationalLimitMotor & limot) { m_targetVelocity = limot.m_targetVelocity; m_maxMotorForce = limot.m_maxMotorForce; m_limitSoftness = limot.m_limitSoftness; m_loLimit = limot.m_loLimit; m_hiLimit = limot.m_hiLimit; m_normalCFM = limot.m_normalCFM; m_stopERP = limot.m_stopERP; m_stopCFM = limot.m_stopCFM; m_bounce = limot.m_bounce; m_currentLimit = limot.m_currentLimit; m_currentLimitError = limot.m_currentLimitError; m_enableMotor = limot.m_enableMotor; } //! Is limited bool isLimited() { if(m_loLimit > m_hiLimit) return false; return true; } //! Need apply correction bool needApplyTorques() { if(m_currentLimit == 0 && m_enableMotor == false) return false; return true; } //! calculates error /*! calculates m_currentLimit and m_currentLimitError. */ int testLimitValue(btScalar test_value); //! apply the correction impulses for two bodies btScalar solveAngularLimits(btScalar timeStep,btVector3& axis, btScalar jacDiagABInv,btRigidBody * body0, btRigidBody * body1); }; class btTranslationalLimitMotor { public: btVector3 m_lowerLimit;//!< the constraint lower limits btVector3 m_upperLimit;//!< the constraint upper limits btVector3 m_accumulatedImpulse; //! Linear_Limit_parameters //!@{ btScalar m_limitSoftness;//!< Softness for linear limit btScalar m_damping;//!< Damping for linear limit btScalar m_restitution;//! Bounce parameter for linear limit btVector3 m_normalCFM;//!< Constraint force mixing factor btVector3 m_stopERP;//!< Error tolerance factor when joint is at limit btVector3 m_stopCFM;//!< Constraint force mixing factor when joint is at limit //!@} bool m_enableMotor[3]; btVector3 m_targetVelocity;//!< target motor velocity btVector3 m_maxMotorForce;//!< max force on motor btVector3 m_currentLimitError;//! How much is violated this limit btVector3 m_currentLinearDiff;//! Current relative offset of constraint frames int m_currentLimit[3];//!< 0=free, 1=at lower limit, 2=at upper limit btTranslationalLimitMotor() { m_lowerLimit.setValue(0.f,0.f,0.f); m_upperLimit.setValue(0.f,0.f,0.f); m_accumulatedImpulse.setValue(0.f,0.f,0.f); m_normalCFM.setValue(0.f, 0.f, 0.f); m_stopERP.setValue(0.2f, 0.2f, 0.2f); m_stopCFM.setValue(0.f, 0.f, 0.f); m_limitSoftness = 0.7f; m_damping = btScalar(1.0f); m_restitution = btScalar(0.5f); for(int i=0; i < 3; i++) { m_enableMotor[i] = false; m_targetVelocity[i] = btScalar(0.f); m_maxMotorForce[i] = btScalar(0.f); } } btTranslationalLimitMotor(const btTranslationalLimitMotor & other ) { m_lowerLimit = other.m_lowerLimit; m_upperLimit = other.m_upperLimit; m_accumulatedImpulse = other.m_accumulatedImpulse; m_limitSoftness = other.m_limitSoftness ; m_damping = other.m_damping; m_restitution = other.m_restitution; m_normalCFM = other.m_normalCFM; m_stopERP = other.m_stopERP; m_stopCFM = other.m_stopCFM; for(int i=0; i < 3; i++) { m_enableMotor[i] = other.m_enableMotor[i]; m_targetVelocity[i] = other.m_targetVelocity[i]; m_maxMotorForce[i] = other.m_maxMotorForce[i]; } } //! Test limit /*! - free means upper < lower, - locked means upper == lower - limited means upper > lower - limitIndex: first 3 are linear, next 3 are angular */ inline bool isLimited(int limitIndex) { return (m_upperLimit[limitIndex] >= m_lowerLimit[limitIndex]); } inline bool needApplyForce(int limitIndex) { if(m_currentLimit[limitIndex] == 0 && m_enableMotor[limitIndex] == false) return false; return true; } int testLimitValue(int limitIndex, btScalar test_value); btScalar solveLinearAxis( btScalar timeStep, btScalar jacDiagABInv, btRigidBody& body1,const btVector3 &pointInA, btRigidBody& body2,const btVector3 &pointInB, int limit_index, const btVector3 & axis_normal_on_a, const btVector3 & anchorPos); }; enum bt6DofFlags { BT_6DOF_FLAGS_CFM_NORM = 1, BT_6DOF_FLAGS_CFM_STOP = 2, BT_6DOF_FLAGS_ERP_STOP = 4 }; #define BT_6DOF_FLAGS_AXIS_SHIFT 3 // bits per axis /// btGeneric6DofConstraint between two rigidbodies each with a pivotpoint that descibes the axis location in local space /*! btGeneric6DofConstraint can leave any of the 6 degree of freedom 'free' or 'locked'. currently this limit supports rotational motors<br> <ul> <li> For Linear limits, use btGeneric6DofConstraint.setLinearUpperLimit, btGeneric6DofConstraint.setLinearLowerLimit. You can set the parameters with the btTranslationalLimitMotor structure accsesible through the btGeneric6DofConstraint.getTranslationalLimitMotor method. At this moment translational motors are not supported. May be in the future. </li> <li> For Angular limits, use the btRotationalLimitMotor structure for configuring the limit. This is accessible through btGeneric6DofConstraint.getLimitMotor method, This brings support for limit parameters and motors. </li> <li> Angulars limits have these possible ranges: <table border=1 > <tr> <td><b>AXIS</b></td> <td><b>MIN ANGLE</b></td> <td><b>MAX ANGLE</b></td> </tr><tr> <td>X</td> <td>-PI</td> <td>PI</td> </tr><tr> <td>Y</td> <td>-PI/2</td> <td>PI/2</td> </tr><tr> <td>Z</td> <td>-PI</td> <td>PI</td> </tr> </table> </li> </ul> */ ATTRIBUTE_ALIGNED16(class) btGeneric6DofConstraint : public btTypedConstraint { protected: //! relative_frames //!@{ btTransform m_frameInA;//!< the constraint space w.r.t body A btTransform m_frameInB;//!< the constraint space w.r.t body B //!@} //! Jacobians //!@{ btJacobianEntry m_jacLinear[3];//!< 3 orthogonal linear constraints btJacobianEntry m_jacAng[3];//!< 3 orthogonal angular constraints //!@} //! Linear_Limit_parameters //!@{ btTranslationalLimitMotor m_linearLimits; //!@} //! hinge_parameters //!@{ btRotationalLimitMotor m_angularLimits[3]; //!@} protected: //! temporal variables //!@{ btScalar m_timeStep; btTransform m_calculatedTransformA; btTransform m_calculatedTransformB; btVector3 m_calculatedAxisAngleDiff; btVector3 m_calculatedAxis[3]; btVector3 m_calculatedLinearDiff; btScalar m_factA; btScalar m_factB; bool m_hasStaticBody; btVector3 m_AnchorPos; // point betwen pivots of bodies A and B to solve linear axes bool m_useLinearReferenceFrameA; bool m_useOffsetForConstraintFrame; int m_flags; //!@} btGeneric6DofConstraint& operator=(btGeneric6DofConstraint& other) { btAssert(0); (void) other; return *this; } int setAngularLimits(btConstraintInfo2 *info, int row_offset,const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB); int setLinearLimits(btConstraintInfo2 *info, int row, const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB); void buildLinearJacobian( btJacobianEntry & jacLinear,const btVector3 & normalWorld, const btVector3 & pivotAInW,const btVector3 & pivotBInW); void buildAngularJacobian(btJacobianEntry & jacAngular,const btVector3 & jointAxisW); // tests linear limits void calculateLinearInfo(); //! calcs the euler angles between the two bodies. void calculateAngleInfo(); public: BT_DECLARE_ALIGNED_ALLOCATOR(); ///for backwards compatibility during the transition to 'getInfo/getInfo2' bool m_useSolveConstraintObsolete; btGeneric6DofConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB ,bool useLinearReferenceFrameA); btGeneric6DofConstraint(btRigidBody& rbB, const btTransform& frameInB, bool useLinearReferenceFrameB); //! Calcs global transform of the offsets /*! Calcs the global transform for the joint offset for body A an B, and also calcs the agle differences between the bodies. \sa btGeneric6DofConstraint.getCalculatedTransformA , btGeneric6DofConstraint.getCalculatedTransformB, btGeneric6DofConstraint.calculateAngleInfo */ void calculateTransforms(const btTransform& transA,const btTransform& transB); void calculateTransforms(); //! Gets the global transform of the offset for body A /*! \sa btGeneric6DofConstraint.getFrameOffsetA, btGeneric6DofConstraint.getFrameOffsetB, btGeneric6DofConstraint.calculateAngleInfo. */ const btTransform & getCalculatedTransformA() const { return m_calculatedTransformA; } //! Gets the global transform of the offset for body B /*! \sa btGeneric6DofConstraint.getFrameOffsetA, btGeneric6DofConstraint.getFrameOffsetB, btGeneric6DofConstraint.calculateAngleInfo. */ const btTransform & getCalculatedTransformB() const { return m_calculatedTransformB; } const btTransform & getFrameOffsetA() const { return m_frameInA; } const btTransform & getFrameOffsetB() const { return m_frameInB; } btTransform & getFrameOffsetA() { return m_frameInA; } btTransform & getFrameOffsetB() { return m_frameInB; } //! performs Jacobian calculation, and also calculates angle differences and axis virtual void buildJacobian(); virtual void getInfo1 (btConstraintInfo1* info); void getInfo1NonVirtual (btConstraintInfo1* info); virtual void getInfo2 (btConstraintInfo2* info); void getInfo2NonVirtual (btConstraintInfo2* info,const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB); void updateRHS(btScalar timeStep); //! Get the rotation axis in global coordinates /*! \pre btGeneric6DofConstraint.buildJacobian must be called previously. */ btVector3 getAxis(int axis_index) const; //! Get the relative Euler angle /*! \pre btGeneric6DofConstraint::calculateTransforms() must be called previously. */ btScalar getAngle(int axis_index) const; //! Get the relative position of the constraint pivot /*! \pre btGeneric6DofConstraint::calculateTransforms() must be called previously. */ btScalar getRelativePivotPosition(int axis_index) const; void setFrames(const btTransform & frameA, const btTransform & frameB); //! Test angular limit. /*! Calculates angular correction and returns true if limit needs to be corrected. \pre btGeneric6DofConstraint::calculateTransforms() must be called previously. */ bool testAngularLimitMotor(int axis_index); void setLinearLowerLimit(const btVector3& linearLower) { m_linearLimits.m_lowerLimit = linearLower; } void getLinearLowerLimit(btVector3& linearLower) { linearLower = m_linearLimits.m_lowerLimit; } void setLinearUpperLimit(const btVector3& linearUpper) { m_linearLimits.m_upperLimit = linearUpper; } void getLinearUpperLimit(btVector3& linearUpper) { linearUpper = m_linearLimits.m_upperLimit; } void setAngularLowerLimit(const btVector3& angularLower) { for(int i = 0; i < 3; i++) m_angularLimits[i].m_loLimit = btNormalizeAngle(angularLower[i]); } void getAngularLowerLimit(btVector3& angularLower) { for(int i = 0; i < 3; i++) angularLower[i] = m_angularLimits[i].m_loLimit; } void setAngularUpperLimit(const btVector3& angularUpper) { for(int i = 0; i < 3; i++) m_angularLimits[i].m_hiLimit = btNormalizeAngle(angularUpper[i]); } void getAngularUpperLimit(btVector3& angularUpper) { for(int i = 0; i < 3; i++) angularUpper[i] = m_angularLimits[i].m_hiLimit; } //! Retrieves the angular limit informacion btRotationalLimitMotor * getRotationalLimitMotor(int index) { return &m_angularLimits[index]; } //! Retrieves the limit informacion btTranslationalLimitMotor * getTranslationalLimitMotor() { return &m_linearLimits; } //first 3 are linear, next 3 are angular void setLimit(int axis, btScalar lo, btScalar hi) { if(axis<3) { m_linearLimits.m_lowerLimit[axis] = lo; m_linearLimits.m_upperLimit[axis] = hi; } else { lo = btNormalizeAngle(lo); hi = btNormalizeAngle(hi); m_angularLimits[axis-3].m_loLimit = lo; m_angularLimits[axis-3].m_hiLimit = hi; } } //! Test limit /*! - free means upper < lower, - locked means upper == lower - limited means upper > lower - limitIndex: first 3 are linear, next 3 are angular */ bool isLimited(int limitIndex) { if(limitIndex<3) { return m_linearLimits.isLimited(limitIndex); } return m_angularLimits[limitIndex-3].isLimited(); } virtual void calcAnchorPos(void); // overridable int get_limit_motor_info2( btRotationalLimitMotor * limot, const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB, btConstraintInfo2 *info, int row, btVector3& ax1, int rotational, int rotAllowed = false); // access for UseFrameOffset bool getUseFrameOffset() { return m_useOffsetForConstraintFrame; } void setUseFrameOffset(bool frameOffsetOnOff) { m_useOffsetForConstraintFrame = frameOffsetOnOff; } ///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5). ///If no axis is provided, it uses the default axis for this constraint. virtual void setParam(int num, btScalar value, int axis = -1); ///return the local value of parameter virtual btScalar getParam(int num, int axis = -1) const; void setAxis( const btVector3& axis1, const btVector3& axis2); 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; }; struct btGeneric6DofConstraintData { btTypedConstraintData m_typeConstraintData; btTransformFloatData m_rbAFrame; // constraint axii. Assumes z is hinge axis. btTransformFloatData m_rbBFrame; btVector3FloatData m_linearUpperLimit; btVector3FloatData m_linearLowerLimit; btVector3FloatData m_angularUpperLimit; btVector3FloatData m_angularLowerLimit; int m_useLinearReferenceFrameA; int m_useOffsetForConstraintFrame; }; struct btGeneric6DofConstraintDoubleData2 { btTypedConstraintDoubleData m_typeConstraintData; btTransformDoubleData m_rbAFrame; // constraint axii. Assumes z is hinge axis. btTransformDoubleData m_rbBFrame; btVector3DoubleData m_linearUpperLimit; btVector3DoubleData m_linearLowerLimit; btVector3DoubleData m_angularUpperLimit; btVector3DoubleData m_angularLowerLimit; int m_useLinearReferenceFrameA; int m_useOffsetForConstraintFrame; }; SIMD_FORCE_INLINE int btGeneric6DofConstraint::calculateSerializeBufferSize() const { return sizeof(btGeneric6DofConstraintData2); } ///fills the dataBuffer and returns the struct name (and 0 on failure) SIMD_FORCE_INLINE const char* btGeneric6DofConstraint::serialize(void* dataBuffer, btSerializer* serializer) const { btGeneric6DofConstraintData2* dof = (btGeneric6DofConstraintData2*)dataBuffer; btTypedConstraint::serialize(&dof->m_typeConstraintData,serializer); m_frameInA.serialize(dof->m_rbAFrame); m_frameInB.serialize(dof->m_rbBFrame); int i; for (i=0;i<3;i++) { dof->m_angularLowerLimit.m_floats[i] = m_angularLimits[i].m_loLimit; dof->m_angularUpperLimit.m_floats[i] = m_angularLimits[i].m_hiLimit; dof->m_linearLowerLimit.m_floats[i] = m_linearLimits.m_lowerLimit[i]; dof->m_linearUpperLimit.m_floats[i] = m_linearLimits.m_upperLimit[i]; } dof->m_useLinearReferenceFrameA = m_useLinearReferenceFrameA? 1 : 0; dof->m_useOffsetForConstraintFrame = m_useOffsetForConstraintFrame ? 1 : 0; return btGeneric6DofConstraintDataName; } #endif //BT_GENERIC_6DOF_CONSTRAINT_H
1
0.95267
1
0.95267
game-dev
MEDIA
0.97748
game-dev
0.98346
1
0.98346
EmeraldCoasttt/BrutalDoomPlatinum
3,367
ZScript/weather/precipitation.zs
class MoveTracer : LineTracer { bool bHitPortal; bool bHitWater; void Reset() { bHitPortal = bHitWater = false; results.hitType = TRACE_HitNone; results.ffloor = null; results.crossedWater = null; results.crossed3DWater = null; } override ETraceStatus TraceCallback() { if (results.crossedWater || results.crossed3DWater) { bHitWater = true; results.hitPos = results.crossedWater ? results.crossedWaterPos : results.crossed3DWaterPos; return TRACE_Stop; } switch (results.HitType) { case TRACE_CrossingPortal: results.hitType = TRACE_HitNone; bHitPortal = true; break; case TRACE_HitWall: if (results.tier == TIER_Middle && (results.hitLine.flags & Line.ML_TWOSIDED) && !(results.hitLine.flags & Line.ML_BLOCKEVERYTHING)) { break; } case TRACE_HitFloor: case TRACE_HitCeiling: if (results.ffloor && (!(results.ffloor.flags & F3DFloor.FF_EXISTS) || !(results.ffloor.flags & F3DFloor.FF_SOLID))) { results.ffloor = null; break; } return TRACE_Stop; break; case TRACE_HitActor: if (results.hitActor.bSolid && (results.hitActor != players[consoleplayer].camera || (players[consoleplayer].camera == players[consoleplayer].mo && (players[consoleplayer].cheats & CF_CHASECAM)))) return TRACE_Stop; break; } results.distance = 0; return TRACE_Skip; } } class Precipitation : Actor { static const double windTab[] = { 5/32., 10/32., 25/32. }; const MIN_MAP_UNIT = 1 / 65536.; private transient MoveTracer moveTracer; private bool bKilled; Default { FloatBobPhase 0; Radius 1; Height 2; +NOBLOCKMAP +SYNCHRONIZED +WINDTHRUST +DONTBLAST +NOTONAUTOMAP } override void Tick() { if (IsFrozen()) return; if (bWindThrust) { int special = CurSector.special; switch (special) { // Wind_East case 40: case 41: case 42: Thrust(windTab[special-40], 0); break; // Wind_North case 43: case 44: case 45: Thrust(windTab[special-43], 90); break; // Wind_South case 46: case 47: case 48: Thrust(windTab[special-46], 270); break; // Wind_West case 49: case 50: case 51: Thrust(windTab[special-49], 180); break; } } if (!moveTracer) moveTracer = new("MoveTracer"); bool bHit; if (!(vel ~== (0,0,0))) { moveTracer.Reset(); bHit = moveTracer.Trace(pos, CurSector, vel, 1, TRACE_ReportPortals|TRACE_HitSky) || moveTracer.bHitWater; if (moveTracer.results.hitType == TRACE_HasHitSky) { Destroy(); return; } SetOrigin(moveTracer.results.hitPos - moveTracer.results.hitVector*MIN_MAP_UNIT, true); if (moveTracer.bHitPortal) vel.xy = RotateVector(vel.xy, DeltaAngle(VectorAngle(vel.x, vel.y), moveTracer.results.srcAngleFromTarget)); if (moveTracer.bHitWater) bNoGravity = true; CheckPortalTransition(); } if (!bNoGravity && pos.z > floorz) vel.z -= GetGravity(); if (bHit) { vel = (0,0,0); if (!bKilled) { bKilled = true; SetState(FindState("Death")); return; } } if (!CheckNoDelay()) return; if (tics > 0) --tics; while (!tics) { if (!SetState(CurState.NextState)) return; } } }
1
0.97759
1
0.97759
game-dev
MEDIA
0.941957
game-dev
0.998502
1
0.998502
MBU-Team/OpenMBU
2,839
game/common/local/chineseStrings_U1.inf
[Strings] $Text::ESRBWarning = "ESRB Notice: Game Experience May Change During Online Play"; $Text::NewContent = "下載新內容!"; $Text::PDLCFreeThanks = "好好享受免費的 Marble Blast Ultra 地圖!"; $Text::PDLCThanksPack1 = "感謝您解鎖 Marble Fu 資料套件!"; $Text::PDLCThanksPack2 = "感謝您解鎖 Agoraphobia 資料套件!"; $Text::PDLCThanksPackBoth = "感謝您解鎖 Marble Fu 及 Agoraphobia 資料套件!"; $Text::UnlockFreeMap = "解鎖免費地圖"; // Displayed on main menu $Text::UnlockMapPack = "解鎖地圖套件"; // "" $Text::CorruptPDLC = "無法讀取%1,可能已毀損,請再下載一次。"; // Displayed if PDLC corrupt; %1 replaced with XCONTENT_DATA.szDisplayName $Text::DownloadContent = "內容下載"; $Text::UnlockPDLC0 = "解鎖 Marble It Up!"; // Displayed on mission selection $Text::UnlockPDLC1 = "解鎖 Marble Fu 資料套件"; // "" $Text::UnlockPDLC2 = "解鎖 Agoraphobia 資料套件"; // "" $Text::PDLCUpsell00 = "解鎖 Marble Blast 多人遊戲地圖套件\n\n"; // PDLC Upsell Screen $Text::PDLCUpsell01 = "有 5 個全新的多人遊戲關卡喔!\n\n"; // "" $Text::PDLCUpsell02 = "快來試試看贏得新的成就 (值 20 點玩家分數喔)!\n\n"; // "" $Text::PDLCUpsell03 = "\n\n"; // "" $Text::PDLCUpsell04 = "\n\n"; // "" $Text::RTArcadeMenu="返回 Arcade"; $Text::GGCredits="<spush><font:Arial Bold:%1>GarageGames Team<spop>\n\n<spush><font:Arial Bold:%2>Development<spop>\nTim Aste\nJane Chase\nTimothy Clarke\nAdam deGrandis\nClark Fagot\nMatt Fairfax\nMark Frohnmayer\nBen Garney\nTim Gift\nDavey Jackson\nJustin Kovac\nJoe Maruschak\nMark McCoy\nJay Moore\nRick Overman\nJohn Quigley\nBrian Ramage\nKevin Ryan\nLiam Ryan\nAlex Swanson\nJeff Tunnell\nPat Wilson\n\n<spush><font:Arial Bold:%2>Special Thanks<spop>\nCafe Aroma\nCafe Yumm!\nMezza Luna Pizzeria\nPizza Research Institute\nThe GarageGames Community"; $Text::AchievementName13 = "獵殺藍寶石"; $Text::AchievementName14 = "地圖套件大師"; $Text::AchievementName15 = "高塔大師"; $Text::AchievementDescription13 = "在 Marble It Up! 多人遊戲中收集到一顆藍寶石。"; $Text::AchievementDescription14 = "在 Playground, Bowl, Concentric, Vortex Effect, Blast Club 關卡中的任何 3 個關卡,獲得 40 的寶石 (Marble 套件)。"; $Text::AchievementDescription15 = "在高塔地圖中收集 50 顆寶石 (Agoraphobia 套件)。"; $Text::LevelNameMP11 = "Marble It Up! (Add-on)"; // Add-on levels $Text::LevelNameMP12 = "Playground (Add-on)"; // "" $Text::LevelNameMP13 = "Bowl (Add-on)"; // "" $Text::LevelNameMP14 = "Concentric (Add-on)"; // "" $Text::LevelNameMP15 = "Vortex Effect (Add-on)"; // "" $Text::LevelNameMP16 = "Blast Club (Add-on)"; // "" $Text::LevelNameMP17 = "Core (Add-on)"; // "" $Text::LevelNameMP18 = "Triumvirate (Add-on)"; // "" $Text::LevelNameMP19 = "Ziggurat (Add-on)"; // "" $Text::LevelNameMP20 = "Promontory (Add-on)"; // "" $Text::LevelNameMP21 = "Spires (Add-on)"; // ""
1
0.914972
1
0.914972
game-dev
MEDIA
0.845678
game-dev
0.857901
1
0.857901
GetEnvy/Envy
12,860
Services/BugTrap/BugTrapSort/BugTrapSort.cpp
// BugTrapSort.cpp : Defines the entry point for the console application. // #include "stdafx.h" class ATL_NO_VTABLE CZipHandler { public: CZipHandler(LPCTSTR szFilename = NULL) throw() : hArchive( NULL ) { if ( szFilename ) Open( szFilename ); } bool Open(LPCTSTR szFilename) throw() { if ( hArchive ) unzClose( hArchive ); hArchive = unzOpen( CT2CA( szFilename ) ); if ( ! hArchive ) { TCHAR szFileShort[ MAX_PATH ]; if ( GetShortPathName( szFilename, szFileShort, MAX_PATH ) ) hArchive = unzOpen( CT2CA( szFileShort ) ); } return ( hArchive != NULL ); } ~CZipHandler() throw() { if ( hArchive ) { unzClose( hArchive ); hArchive = NULL; } } operator unzFile() const throw() { return hArchive; } bool Extract(LPCTSTR szSrc, LPCTSTR szDst) throw() { bool ret = false; char* pBuf = NULL; DWORD dwSize = 0; if ( Extract( szSrc, &pBuf, &dwSize ) ) { HANDLE hFile = CreateFile( szDst, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); if ( hFile != INVALID_HANDLE_VALUE ) { DWORD dwWritten = 0; if ( WriteFile( hFile, pBuf, dwSize, &dwWritten, NULL ) ) ret = ( dwWritten == dwSize ); } CloseHandle( hFile ); } delete [] pBuf; return ret; } bool Extract(LPCTSTR szSrc, char** ppBuf, DWORD* pdwSize = NULL) throw() { if ( pdwSize ) *pdwSize = 0; *ppBuf = NULL; bool ret = false; if ( unzLocateFile( hArchive, CT2CA( szSrc ), 2 ) == UNZ_OK ) { unz_file_info fi = {}; if ( unzGetCurrentFileInfo( hArchive, &fi, NULL, NULL, NULL, NULL, NULL, NULL ) == UNZ_OK ) { if ( unzOpenCurrentFile( hArchive ) == UNZ_OK ) { if ( pdwSize ) *pdwSize = fi.uncompressed_size; *ppBuf = new char[ fi.uncompressed_size + 2 ]; if ( *ppBuf ) { ZeroMemory( *ppBuf, fi.uncompressed_size + 2 ); ret = ( unzReadCurrentFile( hArchive, *ppBuf, fi.uncompressed_size ) == (int)fi.uncompressed_size ); } unzCloseCurrentFile( hArchive ); } } } return ret; } protected: unzFile hArchive; }; typedef struct { CString sIf; CString sIs; CString sThen; } CRule; typedef CAtlList< CRule > CRuleList; typedef CAtlMap< CString, bool > CStringMap; CString g_sConfig; CRuleList g_oRules; CString g_sOutput; CString g_sInput; CStringMap g_oModules; #define REPLACE(x) \ x.Replace( _T("{VER_FULL}"), sVersion ); \ x.Replace( _T("{VER_NUMBER}"), sVersionNumber ); \ x.Replace( _T("{VER_CONFIG}"), sVersionConfig ); \ x.Replace( _T("{VER_PLATFORM}"), sVersionPlatform ); \ x.Replace( _T("{VER_REVISION}"), sVersionRevision ); \ x.Replace( _T("{VER_DATE}"), sVersionDate ); \ x.Replace( _T("{TIMESTAMP}"), sTimestamp ); \ x.Replace( _T("{USER}"), sUser ); \ x.Replace( _T("{COMPUTER}"), sComputer ); \ x.Replace( _T("{CPU}"), sCPU ); \ x.Replace( _T("{WHAT}"), sWhat ); \ x.Replace( _T("{MODULE}"), sModule ); \ x.Replace( _T("{ADDRESS}"), sAddress ); CString GetValue(IXMLDOMElement* pRoot, LPCTSTR szXPath) { CComPtr< IXMLDOMNode > pNode; HRESULT hr = pRoot->selectSingleNode( CComBSTR( szXPath ), &pNode ); if ( hr != S_OK ) return CString(); CComBSTR bstrVersion; hr = pNode->get_text( &bstrVersion ); if ( hr != S_OK ) return CString(); return (LPCWSTR)bstrVersion; } CString GetTime(IXMLDOMElement* pRoot, LPCTSTR szNode, LPCTSTR szFormat) { try { FILETIME fTimestamp; (__int64&)fTimestamp = _tstoi64( GetValue( pRoot, szNode ) ); CTime tTimeStamp( fTimestamp ); return tTimeStamp.FormatGmt( szFormat ); } catch( ... ) { } return CString(); } bool ProcessReport(const CString& sInput) { _tprintf( _T("Processing %s ...\n"), PathFindFileName( sInput ) ); bool bZip = ( sInput.Find( _T(".zip") ) != -1 ); CComPtr< IXMLDOMDocument > pFile; HRESULT hr = pFile.CoCreateInstance( CLSID_DOMDocument ); if ( FAILED( hr ) ) return false; hr = pFile->put_async( VARIANT_FALSE ); if ( hr != S_OK ) return false; CZipHandler pZip; VARIANT_BOOL ret = VARIANT_FALSE; if ( bZip ) { if ( ! pZip.Open( sInput ) ) return false; char* pBuf = NULL; if ( ! pZip.Extract( _T("errorlog.xml"), &pBuf ) ) { delete [] pBuf; return false; } hr = pFile->loadXML( CComBSTR( pBuf ), &ret ); delete [] pBuf; } else { hr = pFile->load( CComVariant( sInput + _T("errorlog.xml") ), &ret ); } if ( hr != S_OK || ! ret ) return false; CComPtr< IXMLDOMElement > pRoot; hr = pFile->get_documentElement( &pRoot ); if ( hr != S_OK ) return false; CString sTimestamp = GetTime( pRoot, _T("/report/timestamp"), _T("%y%m%d-%H%M%S") ); if ( sTimestamp.IsEmpty() ) sTimestamp = _T("UNKNOWN"); CString sVersion = GetValue( pRoot, _T("/report/version") ); CString sComputer = GetValue( pRoot, _T("/report/computer") ); if ( sComputer.IsEmpty() ) sComputer = _T("UNKNOWN"); CString sUser = GetValue( pRoot, _T("/report/user") ); if ( sUser.IsEmpty() ) sUser = _T("UNKNOWN"); CString sCPU = GetValue( pRoot, _T("/report/cpus/cpu/description") ); if ( sCPU.IsEmpty() ) { sCPU = GetValue( pRoot, _T("/report/cpus/cpu/id") ); if ( sCPU.IsEmpty() ) sCPU = _T("UNKNOWN"); } CString sWhat = GetValue( pRoot, _T("/report/error/what") ); if ( sWhat.IsEmpty() ) sWhat = _T("UNKNOWN"); CString sAddress = GetValue( pRoot, _T("/report/error/address") ); sAddress = sAddress.Right( 4 ); sAddress.MakeLower(); CString sModule = PathFindFileName( GetValue( pRoot, _T("/report/error/module") ) ); sModule.MakeLower(); bool bGood; if ( sModule.IsEmpty() || ( g_oModules.Lookup( sModule, bGood ) && ! bGood ) || ( g_oModules.Lookup( sModule + _T(":") + sAddress, bGood ) && ! bGood ) ) { CString sOrigAddress = sAddress; CString sOrigModule = sModule; CComPtr< IXMLDOMNode > pStack; hr = pRoot->selectSingleNode( CComBSTR( _T("/report/threads/thread/stack") ), &pStack ); if ( hr == S_OK ) { CComPtr< IXMLDOMNodeList > pFrames; hr = pStack->get_childNodes( &pFrames ); if ( hr == S_OK ) { long n = 0; hr = pFrames->get_length( &n ); for ( long i = 0; hr == S_OK && i < n; ++i ) { CComPtr< IXMLDOMNode > pFrame; hr = pFrames->get_item( i, &pFrame ); if ( hr == S_OK ) { CComQIPtr< IXMLDOMElement > pFrameE( pFrame ); sAddress = GetValue( pFrameE, _T("address") ); sAddress = sAddress.Right( 4 ); sAddress.MakeLower(); sModule = PathFindFileName( GetValue( pFrameE, _T("module") ) ); if ( ! sModule.IsEmpty() ) { sModule.MakeLower(); if ( ( ! g_oModules.Lookup( sModule, bGood ) || bGood ) && ( ! g_oModules.Lookup( sModule + _T(":") + sAddress, bGood ) || bGood ) ) break; // } sAddress.Empty(); sModule.Empty(); } } } } if ( sModule.IsEmpty() ) { sAddress = sOrigAddress; sModule = sOrigModule; } } if ( sAddress.IsEmpty() ) sAddress = _T("UNKNOWN"); if ( sModule.IsEmpty() ) sModule = _T("UNKNOWN"); // int i = 0; CString sVersionNumber = sVersion.Tokenize( _T(" "), i ); if ( i == -1 ) sVersionNumber = _T("UNKNOWN"); CString sVersionConfig = ( i == -1 ) ? _T("") : sVersion.Tokenize( _T(" "), i ); if ( i == -1 ) sVersionConfig = _T("UNKNOWN"); if ( sVersionConfig.CompareNoCase( _T("release") ) == 0 ) sVersionConfig = _T("r"); else if ( sVersionConfig.CompareNoCase( _T("debug") ) == 0 ) sVersionConfig = _T("d"); CString sVersionPlatform = ( i == -1 ) ? _T("") : sVersion.Tokenize( _T(" "), i ); if ( i == -1 ) sVersionPlatform = _T("UNKNOWN"); if ( sVersionPlatform.Find( _T("32") ) != -1 ) sVersionPlatform = _T("32"); else if ( sVersionPlatform.Find( _T("64") ) != -1 ) sVersionPlatform = _T("64"); CString sVersionRevision = ( i == -1 ) ? _T("") : sVersion.Tokenize( _T(" "), i ); if ( i == -1 ) sVersionRevision = _T("UNKNOWN"); sVersionRevision.Trim( _T(" ()") ); sVersionRevision.MakeLower(); CString sVersionDate = ( i == -1 ) ? _T("") : sVersion.Tokenize( _T(" "), i ); if ( i == -1 ) sVersionDate = _T("UNKNOWN"); sVersionDate.Trim( _T(" ()") ); if ( sVersion.IsEmpty() ) sVersion = _T("UNKNOWN"); _tprintf( _T("Version: %ls\n"), sVersion ); CString sOutput = g_sOutput; for ( POSITION pos = g_oRules.GetHeadPosition(); pos; ) { CRule r = g_oRules.GetNext( pos ); REPLACE( r.sIf ); if ( StrStrI( r.sIf, r.sIs ) ) { sOutput = r.sThen; break; } } if ( sOutput.IsEmpty() ) // return true; REPLACE( sOutput ); if ( sOutput.IsEmpty() ) // return true; sOutput.TrimRight( _T("\\") ) += _T("\\"); int res = SHCreateDirectory( GetDesktopWindow(), sOutput ); if ( res != ERROR_SUCCESS && res != ERROR_FILE_EXISTS && res != ERROR_ALREADY_EXISTS ) return false; if ( bZip ) { if ( ! pZip.Extract( _T("errorlog.xml"), sOutput + _T("errorlog.xml") ) ) return false; pZip.Extract( _T("crashdump.dmp"), sOutput + _T("crashdump.dmp") ); pZip.Extract( _T("settings.reg"), sOutput + _T("settings.reg") ); } else { if ( ! CopyFile( sInput + _T("errorlog.xml"), sOutput + _T("errorlog.xml"), FALSE ) ) return false; CopyFile( sInput + _T("crashdump.dmp"), sOutput + _T("crashdump.dmp"), FALSE ); CopyFile( sInput + _T("settings.reg"), sOutput + _T("settings.reg"), FALSE ); } return true; } bool Enum(LPCTSTR szInput, CAtlList< CString >& oDirs) { bool ret = false; CString sDir = szInput; sDir = sDir.Left( (DWORD)( PathFindFileName( szInput ) - szInput ) ); WIN32_FIND_DATA wfa = {}; HANDLE hFF = FindFirstFile( szInput, &wfa ); if ( hFF != INVALID_HANDLE_VALUE ) { do { if ( *wfa.cFileName != _T('.') ) { if ( ( wfa.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 ) { ret = true; // Add folder without subfolders if ( ! Enum( sDir + wfa.cFileName + _T("\\*.*"), oDirs ) ) oDirs.AddTail( sDir + wfa.cFileName + _T("\\") ); } else if ( _tcsstr( wfa.cFileName, _T(".zip") ) ) { // Add .zip-file oDirs.AddTail( sDir + wfa.cFileName ); } } } while ( FindNextFile( hFF, &wfa ) ); FindClose( hFF ); } return ret; } int _tmain(int argc, _TCHAR* argv[]) { if ( argc != 2 ) return 1; CoInitializeEx( NULL, COINIT_MULTITHREADED ); g_sConfig = argv[ 1 ]; GetPrivateProfileString( _T("options"), _T("output"), NULL, g_sOutput.GetBuffer( 4096 ), 4096, g_sConfig ); g_sOutput.ReleaseBuffer(); if ( ! g_sOutput.IsEmpty() ) g_sOutput.TrimRight( _T("\\") ) += _T("\\"); GetPrivateProfileString( _T("options"), _T("input"), NULL, g_sInput.GetBuffer( 4096 ), 4096, g_sConfig ); g_sInput.ReleaseBuffer(); if ( g_sInput.IsEmpty() ) g_sInput = _T(".\\*.*"); // CString sModules; GetPrivateProfileString( _T("options"), _T("accept"), NULL, sModules.GetBuffer( 4096 ), 4096, g_sConfig ); sModules.ReleaseBuffer(); for ( int i = 0; ; ) { CString sModule = sModules.Tokenize( _T("|"), i ); if ( sModule.IsEmpty() || i == -1 ) break; sModule.MakeLower(); bool foo; if ( g_oModules.Lookup( sModule, foo ) ) { _tprintf( _T("Duplicate in [options] \"accept\" parameter: %s\n"), sModule ); return 1; } g_oModules.SetAt( sModule, true ); } // GetPrivateProfileString( _T("options"), _T("ignore"), NULL, sModules.GetBuffer( 4096 ), 4096, g_sConfig ); sModules.ReleaseBuffer(); for ( int i = 0; ; ) { CString sModule = sModules.Tokenize( _T("|"), i ); if ( sModule.IsEmpty() || i == -1 ) break; sModule.MakeLower(); bool foo; if ( g_oModules.Lookup( sModule, foo ) ) { _tprintf( _T("Duplicate in [options] \"ignore\" parameter: %s\n"), sModule ); return 1; } g_oModules.SetAt( sModule, false ); } // CAutoVectorPtr< TCHAR > pSections( new TCHAR[ 16384 ] ); GetPrivateProfileString( NULL, NULL, NULL, pSections, 16384, g_sConfig ); // for ( LPCTSTR szSect = pSections; szSect && *szSect; szSect += lstrlen( szSect ) + 1 ) { if ( lstrcmpi( szSect, _T("options") ) == 0 ) continue; // CRule r; GetPrivateProfileString( szSect, _T("if"), NULL, r.sIf.GetBuffer( 4096 ), 4096, g_sConfig ); r.sIf.ReleaseBuffer(); GetPrivateProfileString( szSect, _T("output"), NULL, r.sThen.GetBuffer( 4096 ), 4096, g_sConfig ); r.sThen.ReleaseBuffer(); CString sIses; GetPrivateProfileString( szSect, _T("is"), NULL, sIses.GetBuffer( 4096 ), 4096, g_sConfig ); sIses.ReleaseBuffer(); for ( int i = 0; ; ) { r.sIs = sIses.Tokenize( _T("|"), i ); if ( r.sIs.IsEmpty() || i == -1 ) break; g_oRules.AddTail( r ); } } pSections.Free(); CAtlList< CString > oDirs; Enum( g_sInput, oDirs ); _tprintf( _T("Processing %d reports from folder %s ...\n"), oDirs.GetCount(), g_sInput ); for ( POSITION pos = oDirs.GetHeadPosition(); pos; ) { if ( ! ProcessReport( oDirs.GetNext( pos ) ) ) _tprintf( _T("Report load error!\n") ); } _tprintf( _T("Done.\n") ); CoUninitialize(); return 0; }
1
0.98272
1
0.98272
game-dev
MEDIA
0.185055
game-dev
0.995542
1
0.995542
Jukoz/middle-earth
14,375
src/main/java/net/jukoz/me/entity/beasts/trolls/TrollEntity.java
package net.jukoz.me.entity.beasts.trolls; import net.jukoz.me.MiddleEarth; import net.jukoz.me.entity.ModEntities; import net.jukoz.me.entity.beasts.AbstractBeastEntity; import net.jukoz.me.entity.dwarves.longbeards.LongbeardDwarfEntity; import net.jukoz.me.entity.elves.galadhrim.GaladhrimElfEntity; import net.jukoz.me.entity.goals.*; import net.jukoz.me.entity.hobbits.shire.ShireHobbitEntity; import net.jukoz.me.entity.humans.bandit.BanditHumanEntity; import net.jukoz.me.entity.humans.gondor.GondorHumanEntity; import net.jukoz.me.entity.humans.rohan.RohanHumanEntity; import net.jukoz.me.entity.projectile.boulder.BoulderEntity; import net.jukoz.me.item.ModFoodItems; import net.jukoz.me.resources.StateSaverAndLoader; import net.jukoz.me.resources.datas.Disposition; import net.jukoz.me.resources.persistent_datas.PlayerData; import net.minecraft.entity.*; import net.minecraft.entity.ai.goal.*; import net.minecraft.entity.attribute.DefaultAttributeContainer; import net.minecraft.entity.attribute.EntityAttributes; import net.minecraft.entity.data.DataTracker; import net.minecraft.entity.data.TrackedData; import net.minecraft.entity.data.TrackedDataHandlerRegistry; import net.minecraft.entity.mob.MobEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtList; import net.minecraft.particle.ParticleTypes; import net.minecraft.registry.RegistryKeys; import net.minecraft.registry.tag.TagKey; import net.minecraft.sound.SoundEvents; import net.minecraft.util.Identifier; import net.minecraft.util.math.*; import net.minecraft.world.World; import java.util.List; public class TrollEntity extends AbstractBeastEntity { private int throwCooldown = 100; public final AnimationState throwingAnimationState = new AnimationState(); private int throwingAnimationTimeout = 0; private int bondingTries = 0; private int bondingTimeout = 0; public static final TrackedData<Boolean> THROWING = DataTracker.registerData(TrollEntity.class, TrackedDataHandlerRegistry.BOOLEAN); /* Temporary disabled until next update @Override public boolean hasArmorSlot() { return false; }*/ public TrollEntity(EntityType<? extends TrollEntity> entityType, World world) { super(entityType, world); } public static DefaultAttributeContainer.Builder setAttributes() { return MobEntity.createMobAttributes() .add(EntityAttributes.GENERIC_MOVEMENT_SPEED, 0.35f) .add(EntityAttributes.GENERIC_MAX_HEALTH, 120.0) .add(EntityAttributes.GENERIC_KNOCKBACK_RESISTANCE, 0.6) .add(EntityAttributes.GENERIC_ATTACK_SPEED, 0.9) .add(EntityAttributes.GENERIC_FOLLOW_RANGE, 28.0) .add(EntityAttributes.GENERIC_ATTACK_DAMAGE, 10.0) .add(EntityAttributes.GENERIC_JUMP_STRENGTH, 0.0); } @Override protected void initGoals() { this.goalSelector.add(1, new SwimGoal(this)); this.goalSelector.add(2, new BeastSitGoal(this)); this.goalSelector.add(3, new MeleeAttackGoal(this, 0.9f, false)); this.goalSelector.add(4, new ChargeAttackGoal(this, this.getDisposition(), maxChargeCooldown())); this.goalSelector.add(5, new WanderAroundFarGoal(this, 1.0)); this.goalSelector.add(6, new LookAtEntityGoal(this, PlayerEntity.class, 6.0f)); this.goalSelector.add(7, new LookAroundGoal(this)); this.targetSelector.add(1, new BeastTrackOwnerAttackerGoal((AbstractBeastEntity) this)); this.targetSelector.add(2, new BeastAttackWithOwnerGoal((AbstractBeastEntity)this)); this.targetSelector.add(3, new BeastRevengeGoal(this, new Class[0])); this.targetSelector.add(5, new ActiveTargetGoal<>(this, GaladhrimElfEntity.class, true)); this.targetSelector.add(6, new ActiveTargetGoal<>(this, LongbeardDwarfEntity.class, true)); this.targetSelector.add(7, new ActiveTargetGoal<>(this, GondorHumanEntity.class, true)); this.targetSelector.add(8, new ActiveTargetGoal<>(this, RohanHumanEntity.class, true)); this.targetSelector.add(9, new ActiveTargetGoal<>(this, BanditHumanEntity.class, true)); this.targetSelector.add(0, new ActiveTargetGoal<>(this, ShireHobbitEntity.class, true)); } protected void initDataTracker(DataTracker.Builder builder) { super.initDataTracker(builder); builder.add(THROWING, false); } @Override public void onTrackedDataSet(TrackedData<?> data) { if(!this.firstUpdate && THROWING.equals(data)) { this.throwCooldown = this.throwCooldown == 0 ? 200 : this.throwCooldown; } super.onTrackedDataSet(data); } @Override protected void setupAnimationStates() { if (this.idleAnimationTimeout <= 0) { this.idleAnimationTimeout = this.random.nextInt(40) + 80; this.idleAnimationState.start(this.age); } else { --this.idleAnimationTimeout; } if(this.isSitting()) { this.sittingAnimationState.startIfNotRunning(this.age); } else { this.sittingAnimationState.stop(); } if(this.isThrowing() && this.throwingAnimationTimeout <= 0) { this.throwingAnimationTimeout = 100; this.throwingAnimationState.start(this.age); }else { --this.throwingAnimationTimeout; } if(isThrowing()) { this.setMovementSpeed(0); } if(!this.isThrowing()) { this.throwingAnimationState.stop(); } } @Override public void tick() { super.tick(); if(this.getTarget() != null) { this.getLookControl().lookAt(this.getTarget()); } if(this.isCharging()) { chargeAttack(); if(!chargeAnimationState.isRunning()) { this.chargeAnimationState.start(this.age); } } if(throwCooldown == 0 && this.getTarget() != null && !isCharging()) { if(this.squaredDistanceTo(this.getTarget()) >= 25 && !this.hasPassengers() && canThrow()) { this.setThrowing(true); throwCooldown = 200; } } if(this.isThrowing() && canThrow()) { this.setVelocity(Vec3d.ZERO); if(throwCooldown <= 180) { throwAttack(); } } if(throwCooldown > 0) { --this.throwCooldown; } if (!this.getWorld().isClient) { if(this.bondingTimeout > 0) { this.bondingTimeout--; } } } @Override protected Disposition getDisposition() { return Disposition.EVIL; } @Override protected float getSaddledSpeed(PlayerEntity controllingPlayer) { return (float)this.getAttributeValue(EntityAttributes.GENERIC_MOVEMENT_SPEED) * 0.5f; } public boolean isCommandItem(ItemStack stack) { return stack.isIn(TagKey.of(RegistryKeys.ITEM, Identifier.of(MiddleEarth.MOD_ID, "bones"))); } @Override public void writeCustomDataToNbt(NbtCompound nbt) { super.writeCustomDataToNbt(nbt); nbt.putBoolean("ChestedTroll", this.hasChest()); if (this.hasChest()) { NbtList nbtList = new NbtList(); for(int i = 2; i < this.items.size(); ++i) { ItemStack itemStack = this.items.getStack(i); if (!itemStack.isEmpty()) { NbtCompound nbtCompound = new NbtCompound(); nbtCompound.putByte("Slot", (byte)i); nbtList.add(itemStack.encode(this.getRegistryManager(), nbtCompound)); } } nbt.put("Items", nbtList); } } @Override public void readCustomDataFromNbt(NbtCompound nbt) { super.readCustomDataFromNbt(nbt); this.setHasChest(nbt.getBoolean("ChestedTroll")); this.onChestedStatusChanged(); if (this.hasChest()) { NbtList nbtList = nbt.getList("Items", 10); for(int i = 0; i < nbtList.size(); ++i) { NbtCompound nbtCompound = nbtList.getCompound(i); int j = nbtCompound.getByte("Slot") & 255; if (j >= 2 && j < this.items.size()) { this.items.setStack(j, ItemStack.fromNbt(getRegistryManager(), nbtCompound).orElse(ItemStack.EMPTY)); } } } if (nbt.contains("SaddleItem", 10)) { ItemStack itemStack = (ItemStack)ItemStack.fromNbt(this.getRegistryManager(), nbt.getCompound("SaddleItem")).orElse(ItemStack.EMPTY); if (itemStack.isOf(Items.SADDLE)) { this.items.setStack(0, itemStack); } } this.updateSaddledFlag(); } @Override public boolean tryAttack(Entity target) { this.attackTicksLeft = ATTACK_COOLDOWN; this.getWorld().sendEntityStatus(this, EntityStatuses.PLAY_ATTACK_SOUND); float f = this.getAttackDamage(); float g = (int)f > 0 ? f / 2.0f + (float)this.random.nextInt((int)f) : f; boolean bl = target.damage(this.getDamageSources().mobAttack(this), g); if (bl) { double d; if (target instanceof LivingEntity) { LivingEntity livingEntity = (LivingEntity)target; d = livingEntity.getAttributeValue(EntityAttributes.GENERIC_KNOCKBACK_RESISTANCE); } else { d = 0.0; } double e = Math.max(0.0, 1.0 - d); target.setVelocity(target.getVelocity().multiply(1f + (0.8f * e))); //.add(0.0, (double)0.1f * e, 0.0)); } this.playSound(SoundEvents.ENTITY_HOGLIN_ATTACK, 1.5f, 0.8f); return bl; } @Override public boolean shouldAttackWhenMounted() { return true; } public boolean canThrow() { return !this.isSitting(); } public void setThrowing(boolean throwing) { this.dataTracker.set(THROWING, throwing); } public boolean isThrowing() { return this.dataTracker.get(THROWING); } @Override public int chargeDuration() { return 25; } @Override public boolean isBondingItem(ItemStack itemStack) { return false; } public int getBondingTimeout() { return bondingTimeout; } public void setBondingTimeout(int bondingTimeout) { this.bondingTimeout = bondingTimeout; } @Override public void tryBonding(PlayerEntity player) { if(player.isCreative()) { tameBeast(player); this.getWorld().sendEntityStatus(this, EntityStatuses.ADD_POSITIVE_PLAYER_REACTION_PARTICLES); this.setChargeTimeout(0); } else if(this.getBondingTimeout() <= 0) { if(random.nextFloat() <= 0.4f) { this.bondingTries++; if(bondingTries == 3) { tameBeast(player); this.getWorld().sendEntityStatus(this, EntityStatuses.ADD_POSITIVE_PLAYER_REACTION_PARTICLES); this.setChargeTimeout(0); } } player.getStackInHand(player.getActiveHand()).decrement(1); this.setBondingTimeout(40); } } public void throwAttack() { Entity target = this.getTarget(); if(target instanceof PlayerEntity player) { PlayerData data = StateSaverAndLoader.getPlayerState(player); Disposition playerDisposition = data.getCurrentDisposition(); if(playerDisposition == this.getDisposition()){ return; } } if(target != null && !this.getWorld().isClient) { this.setThrowing(false); Vec3d rotationVec = this.getRotationVec(1.0f); BoulderEntity boulder = new BoulderEntity(ModEntities.BOULDER, this, this.getWorld()); double x = target.getX() - this.getX(); double y = target.getBodyY(0.3333333333333333) - boulder.getY(); double z = target.getZ() - this.getZ(); double c = Math.sqrt(x * x + z * z); boulder.setPosition(this.getX() + rotationVec.x * 2.0f, this.getBodyY(0.75f), boulder.getZ() + rotationVec.z * 2.0f); boulder.setVelocity(x * 0.8d, y + c * 0.3d , z * 0.8d, 1.0f, 8 - this.getWorld().getDifficulty().getId() * 4); if(boulder != null) { this.getWorld().spawnEntity(boulder); } } } @Override public void chargeAttack() { List<Entity> entities = this.getWorld().getOtherEntities(this, this.getBoundingBox().expand(0.2f, 0.0, 0.2f)); if(!this.isTame() && !this.getWorld().isClient) { if(targetDir == Vec3d.ZERO && this.getTarget() != null) { targetDir = new Vec3d( this.getTarget().getBlockPos().getX() - this.getBlockPos().getX(), this.getTarget().getBlockPos().getY() - this.getBlockPos().getY(), this.getTarget().getBlockPos().getZ() - this.getBlockPos().getZ()); } this.setYaw((float) Math.toDegrees(Math.atan2(-targetDir.x, targetDir.z))); this.setVelocity(targetDir.multiply(1,0,1).normalize().multiply(1.0d - ((double)(this.chargeTimeout - (maxChargeCooldown() - chargeDuration())) / chargeDuration())).add(0, this.getVelocity().y, 0)); } else if (this.getWorld().isClient) { this.setVelocity(this.getRotationVector().multiply(1,0,1).normalize().multiply(1.0d - ((double)(this.chargeTimeout - (maxChargeCooldown() - chargeDuration())) / chargeDuration())).add(0, this.getVelocity().y, 0)); } for(Entity entity : entities) { if(entity.getUuid() != this.getOwnerUuid() && entity != this && !this.getPassengerList().contains(entity)) { entity.damage(entity.getDamageSources().mobAttack(this), 16.0f); } } this.getWorld().addParticle(ParticleTypes.EXPLOSION, this.getX(), this.getY(), this.getZ(), 0, 0, 0); this.chargeAnimationState.startIfNotRunning(this.age); } }
1
0.867217
1
0.867217
game-dev
MEDIA
0.989727
game-dev
0.975676
1
0.975676
schollz/miditocv
2,191
lua-5.4.6/src/ltable.h
/* ** $Id: ltable.h $ ** Lua tables (hash) ** See Copyright Notice in lua.h */ #ifndef ltable_h #define ltable_h #include "lobject.h" #define gnode(t,i) (&(t)->node[i]) #define gval(n) (&(n)->i_val) #define gnext(n) ((n)->u.next) /* ** Clear all bits of fast-access metamethods, which means that the table ** may have any of these metamethods. (First access that fails after the ** clearing will set the bit again.) */ #define invalidateTMcache(t) ((t)->flags &= ~maskflags) /* true when 't' is using 'dummynode' as its hash part */ #define isdummy(t) ((t)->lastfree == NULL) /* allocated size for hash nodes */ #define allocsizenode(t) (isdummy(t) ? 0 : sizenode(t)) /* returns the Node, given the value of a table entry */ #define nodefromval(v) cast(Node *, (v)) LUAI_FUNC const TValue *luaH_getint (Table *t, lua_Integer key); LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value); LUAI_FUNC const TValue *luaH_getshortstr (Table *t, TString *key); LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key); LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key); LUAI_FUNC void luaH_newkey (lua_State *L, Table *t, const TValue *key, TValue *value); LUAI_FUNC void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value); LUAI_FUNC void luaH_finishset (lua_State *L, Table *t, const TValue *key, const TValue *slot, TValue *value); LUAI_FUNC Table *luaH_new (lua_State *L); LUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned int nasize, unsigned int nhsize); LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize); LUAI_FUNC void luaH_free (lua_State *L, Table *t); LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key); LUAI_FUNC lua_Unsigned luaH_getn (Table *t); LUAI_FUNC unsigned int luaH_realasize (const Table *t); #if defined(LUA_DEBUG) LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key); #endif #endif
1
0.92577
1
0.92577
game-dev
MEDIA
0.356399
game-dev
0.631624
1
0.631624
It-Life/Deer_GameFramework_Wolong
9,776
Assets/Standard Assets/DeerExample/UIExtensions/Editor/Scripts/HorizontalSelectorEditor.cs
using UnityEditor; using UnityEngine; using static tackor.UIExtension.HorizontalSelector; namespace tackor.UIExtension { [CustomEditor(typeof(HorizontalSelector))] public class HorizontalSelectorEditor : Editor { private GUISkin customSkin; private HorizontalSelector hsTarget; private int currentTab; private void OnEnable() { hsTarget = (HorizontalSelector)target; customSkin = (GUISkin)Resources.Load("UIExtensionGUISkin"); if (hsTarget.defaultIndex > hsTarget.items.Count - 1) hsTarget.defaultIndex = 0; } public override void OnInspectorGUI() { //base.OnInspectorGUI(); GUIContent[] toolbarTabs = new GUIContent[3]; toolbarTabs[0] = new GUIContent("Content"); toolbarTabs[1] = new GUIContent("Resources"); toolbarTabs[2] = new GUIContent("Settings"); //Tabs---- currentTab = EditorHandler.DrawTabs(currentTab, toolbarTabs, customSkin); if (GUILayout.Button(new GUIContent("Content", "Content"), customSkin.FindStyle("Tab Content"))) currentTab = 0; if (GUILayout.Button(new GUIContent("Resources", "Resources"), customSkin.FindStyle("Tab Resources"))) currentTab = 1; if (GUILayout.Button(new GUIContent("Settings", "Settings"), customSkin.FindStyle("Tab Settings"))) currentTab = 2; GUILayout.EndHorizontal(); var items = serializedObject.FindProperty("items"); var onValueChanged = serializedObject.FindProperty("onValueChanged"); var animator = serializedObject.FindProperty("m_Animator"); var label = serializedObject.FindProperty ("label"); var labelHelper = serializedObject.FindProperty("labelHelper"); var labelIcon = serializedObject.FindProperty("labelIcon"); var labelIconHelper = serializedObject.FindProperty("labelIconHelper"); var indicatorParent = serializedObject.FindProperty("indicatorParent"); var indicatorObject = serializedObject.FindProperty("indicatorObject"); var indicatorText = serializedObject.FindProperty("indicatorText"); var enableIcon = serializedObject.FindProperty("enableIcon"); var saveSelected = serializedObject.FindProperty("saveSelected"); var saveKey = serializedObject.FindProperty("saveKey"); var indicatorType = serializedObject.FindProperty("indicatorType"); var invokeAtStart = serializedObject.FindProperty("invokeAtStart"); var invertAnimation = serializedObject.FindProperty("invertAnimation"); var loopSelection = serializedObject.FindProperty("loopSelection"); var defaultIndex = serializedObject.FindProperty("defaultIndex"); var iconScale = serializedObject.FindProperty("iconScale"); var contentSpacing = serializedObject.FindProperty("contentSpacing"); var contentLayout = serializedObject.FindProperty("contentLayout"); var contentLayoutHelper = serializedObject.FindProperty("contentLayoutHelper"); var enableUIManager = serializedObject.FindProperty("enableUIManager"); switch (currentTab) { case 0: //Content Header --------------------------- EditorHandler.DrawHeader(customSkin, "Content Header", 6); // defaultIndex if (hsTarget.items.Count > 0) { if (Application.isPlaying) { GUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.BeginHorizontal(); GUI.enabled = false; EditorGUILayout.LabelField(new GUIContent("Current Item:"), customSkin.FindStyle("Text"), GUILayout.Width(74)); EditorGUILayout.LabelField(new GUIContent(hsTarget.items[hsTarget.index].itemTitle), customSkin.FindStyle("Text")); GUILayout.EndHorizontal(); GUILayout.Space(2); EditorGUILayout.IntSlider(hsTarget.index, 0, hsTarget.items.Count - 1); GUI.enabled = true; GUILayout.EndVertical(); } else { GUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.BeginHorizontal(); GUI.enabled = false; EditorGUILayout.LabelField(new GUIContent("Selected Item: "), customSkin.FindStyle("Text"), GUILayout.Width(78)); GUI.enabled = true; EditorGUILayout.LabelField(new GUIContent(hsTarget.items[defaultIndex.intValue].itemTitle), customSkin.FindStyle("Text")); GUILayout.EndHorizontal(); GUILayout.Space(2); defaultIndex.intValue = EditorGUILayout.IntSlider(defaultIndex.intValue, 0, hsTarget.items.Count - 1); GUILayout.EndVertical(); } } else { EditorGUILayout.HelpBox("There is no item in the list.", MessageType.Warning); } //Selector Items GUILayout.BeginVertical(); EditorGUI.indentLevel = 1; EditorGUILayout.PropertyField(items, new GUIContent("Selector Items"), true); EditorGUI.indentLevel = 1; GUILayout.EndVertical(); //Events Header --------------------------- EditorHandler.DrawHeader(customSkin, "Events Header", 10); EditorGUILayout.PropertyField(onValueChanged, new GUIContent("On Value Changed"), true); break; case 1: //Core Header --------------------------- EditorHandler.DrawHeader(customSkin, "Core Header", 6); EditorHandler.DrawProperty(label, customSkin, "Label"); EditorHandler.DrawProperty(labelHelper, customSkin, "Label Helper"); EditorHandler.DrawProperty(labelIcon, customSkin, "Label Icon"); EditorHandler.DrawProperty(labelIconHelper, customSkin, "Label Icon Helper"); EditorHandler.DrawProperty(indicatorParent, customSkin, "Indicator Parent"); EditorHandler.DrawProperty(indicatorObject, customSkin, "Indicator Object"); EditorHandler.DrawProperty(indicatorText, customSkin, "Indicator Text"); EditorHandler.DrawProperty(contentLayout, customSkin, "Content Layout"); EditorHandler.DrawProperty(contentLayoutHelper, customSkin, "Content Layout Helper"); EditorHandler.DrawProperty(animator, customSkin, "Animator"); break; case 2: //Customization Header --------------------------- EditorHandler.DrawHeader(customSkin, "Customization Header", 6); //EnableIcon GUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.Space(-3); enableIcon.boolValue = EditorHandler.DrawTogglePlain(enableIcon.boolValue, customSkin, "Enable Icon"); GUILayout.Space(3); if (enableIcon.boolValue == true && hsTarget.labelIcon == null) { EditorGUILayout.HelpBox("'Enable Icon' is enabled but 'Label Icon' is not assigned. Go to Resources tab and assign the correct variable.", MessageType.Error); } else if (enableIcon.boolValue == true && hsTarget.labelIcon != null) { hsTarget.labelIcon.gameObject.SetActive(true); } else if (enableIcon.boolValue == false && hsTarget.labelIcon != null) { hsTarget.labelIcon.gameObject.SetActive(false); } GUILayout.EndVertical(); //IndicatorType GUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.Space(-3); EditorHandler.DrawProperty(indicatorType, customSkin, "Indicator Type"); GUILayout.Space(3); GUILayout.BeginHorizontal(); switch ((IndicatorType)indicatorType.enumValueIndex) { case IndicatorType.Point: if (hsTarget.indicatorObject == null) EditorGUILayout.HelpBox("'Enable Indicators' is enabled but 'Indicator Object' is not assigned. Go to Resources tab and assign the correct variable.", MessageType.Error); if (hsTarget.indicatorParent == null) EditorGUILayout.HelpBox("'Enable Indicators' is enabled but 'Indicator Parent' is not assigned. Go to Resources tab and assign the correct variable.", MessageType.Error); else hsTarget.indicatorParent.gameObject.SetActive(true); if (hsTarget.indicatorText != null) hsTarget.indicatorText.gameObject.SetActive(false); break; case IndicatorType.Text: hsTarget.indicatorParent.gameObject.SetActive(false); if (hsTarget.indicatorText != null) hsTarget.indicatorText.gameObject.SetActive(true); break; case IndicatorType.None: default: hsTarget.indicatorParent.gameObject.SetActive(false); if (hsTarget.indicatorText != null) hsTarget.indicatorText.gameObject.SetActive(false); break; } GUILayout.EndHorizontal(); GUILayout.EndVertical(); //IconScale EditorHandler.DrawProperty(iconScale, customSkin, "Icon Scale"); //ContentSpacing EditorHandler.DrawProperty(contentSpacing, customSkin, "Content Spacing"); hsTarget.UpdateContentLayout(); //Options Header --------------------------- EditorHandler.DrawHeader(customSkin, "Options Header", 10); //Invoke At Start invokeAtStart.boolValue = EditorHandler.DrawToggle(invokeAtStart.boolValue, customSkin, "Invoke At Start"); //Invert Animation invertAnimation.boolValue = EditorHandler.DrawToggle(invertAnimation.boolValue, customSkin, "Invert Animation"); //Loop Selection loopSelection.boolValue = EditorHandler.DrawToggle(loopSelection.boolValue, customSkin, "Loop Selection"); GUI.enabled = true; //Save Selected GUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.Space(-3); saveSelected.boolValue = EditorHandler.DrawTogglePlain(saveSelected.boolValue, customSkin, "Save Selected"); GUILayout.Space(3); if (saveSelected.boolValue) { EditorHandler.DrawPropertyCW(saveKey, customSkin, "Save Key:", 90); EditorGUILayout.HelpBox("Each selector should has its own unique save key.", MessageType.Info); } GUILayout.EndVertical(); break; default: break; } this.Repaint(); serializedObject.ApplyModifiedProperties(); } } }
1
0.930575
1
0.930575
game-dev
MEDIA
0.690546
game-dev,desktop-app
0.971177
1
0.971177
dsh2dsh/op2ogse
13,566
gamedata/scripts/xr/xr_zoneguard.script
---------------------------------------------------------------------------------------------------- -- ---------------------------------------------------------------------------------------------------- -- : Andrey Fidrya (Zmey) af@svitonline.com ---------------------------------------------------------------------------------------------------- -- , -- N local not_on_pos_max_kill_distance = 20 -- 15 - local zone_appear_in_db_wait_timeout = 15000 teams = {} local state_none = 0 local state_walking = 1 local state_going_to_plr = 2 local state_standing = 3 local body_state_free = 0 local body_state_danger = 1 ---------------------------------------------------------------------------------------------------------------------- class "evaluator_need_zoneguard" (property_evaluator) function evaluator_need_zoneguard:__init(storage, name) super(nil, name) self.st = storage end function evaluator_need_zoneguard:evaluate() return xr_logic.is_active(self.object, self.st) end --------------------------------------------------------------------------------------------------------------------- class "action_zoneguard_activity" (action_base) function action_zoneguard_activity:__init(npc_name, action_name, storage) super(nil, action_name) self.st = storage self.move_mgr = move_mgr.move_mgr(storage.npc) self.was_reset = false end function action_zoneguard_activity:initialize() --printf("_bp: action_zoneguard_activity: initialize") action_base.initialize(self) self.object:set_node_evaluator() self.object:set_path_evaluator() self.object:set_desired_position() self.object:set_desired_direction() --xr_reactions.add_rule(self.object, "ignore") --self.object:enable_talk() -- meet_talk_enabled = true self.move_mgr:initialize() self:reset_scheme() end function action_zoneguard_activity:activate_scheme() self.was_reset = false end function action_zoneguard_activity:reset_scheme() self.was_reset = true if not teams[self.st.team] then teams[self.st.team] = {} end self:reset_trigger() --xr_state.anim_update(nil, self.object) --self.object:clear_animations() if self.st.path_walk_info == nil then self.st.path_walk_info = utils.path_parse_waypoints(self.st.path_walk) end if self.st.path_look_info == nil then self.st.path_look_info = utils.path_parse_waypoints(self.st.path_look) end self.move_mgr:reset(self.st.path_walk, self.st.path_walk_info, self.st.path_look, self.st.path_look_info, self.st.walker_team) self.talked = false self.snd = {} if self.st.snd_greet then --self.snd.rnd = snd_prob --self.snd.maxidle = 3 --self.snd.sumidle = 2 self.snd.themes = self.st.snd_greet end self.sound_activated = false self.state = state_walking self.zone_appear_wait_end_time = nil end function action_zoneguard_activity:reset_trigger() local who_triggered = teams[self.st.team].triggered if who_triggered and who_triggered == self.object:id() then teams[self.st.team].triggered = nil end end function action_zoneguard_activity:talk_with_plr(actor) if self.st.enable_dialog and not self.talked then if not self.object:is_talking() then --self.object:switch_to_talk() actor:run_talk_dialog(self.object) self.talked = true end end end function action_zoneguard_activity:get_sug_body_state(actor) if self.st.no_danger or self.object:relation(actor) == game_object.friend then return body_state_free --"guard" else return body_state_danger --"threat" end end function action_zoneguard_activity:go_to_actor(actor, update_state) self.object:set_path_type(game_object.level_path) local target_vert = actor:level_vertex_id() if self.object:accessible(target_vert) then self.object:set_dest_level_vertex_id(target_vert) end if update_state then local sug_body_state = self:get_sug_body_state(actor) state_mgr.set_state(self.object, if_then_else(sug_body_state == body_state_free, "run", "assault"), nil, nil, { look_object = actor }, {animation = true}) end end function action_zoneguard_activity:stand_still(actor) local sug_body_state = self:get_sug_body_state(actor) local snd if self.st.snd_anim_sync and self.st.snd_greet then snd = self.st.snd_greet else snd = nil end if self.st.anim then state_mgr.set_state(self.object, self.st.anim, nil, nil, { look_object = actor }, {animation = true}, snd) else state_mgr.set_state(self.object, if_then_else(sug_body_state == body_state_free, "guard", "threat"), nil, nil, { look_object = actor }, {animation = true}, snd) end end function action_zoneguard_activity:execute() action_base.execute(self) if not self.was_reset then self:reset_scheme() end local prev_state repeat prev_state = self.state self:fsm_step() until prev_state == self.state end function action_zoneguard_activity:ignore_actor(actor) if self.st.ignore_friends and self.object:relation(actor) == game_object.friend then return true end if self.st.ignore_cond and xr_logic.pick_section_from_condlist(actor, self.object, self.st.ignore_cond.condlist) ~= nil then return true end return false end function action_zoneguard_activity:fsm_step() if not self.st.zone_guard_obj and self.st.zone_guard then self.st.zone_guard_obj = db.zone_by_name[self.st.zone_guard] if self.st.zone_guard_obj then if self.st.zone_guard_obj:clsid() == clsid.script_zone then abort("object '%s': you must use a restrictor instead of script zone '%s'", self.object:name(), self.st.zone_guard) end self.zone_appear_wait_end_time = nil else --printf("_bp: object '%s': waiting for zone_guard '%s'", -- self.object:name(), self.st.zone_guard) if not self.zone_appear_wait_end_time then self.zone_appear_wait_end_time = time_global() + zone_appear_in_db_wait_timeout elseif time_global() >= self.zone_appear_wait_end_time then abort("object '%s': unable to find zone_guard '%s' on the map", self.object:name(), self.st.zone_guard) end return end end if not self.st.zone_warn_obj then self.st.zone_warn_obj = db.zone_by_name[self.st.zone_warn] if self.st.zone_warn_obj then if self.st.zone_warn_obj:clsid() == clsid.script_zone then abort("object '%s': you must use a restrictor instead of script zone '%s'", self.object:name(), self.st.zone_warn) end self.zone_appear_wait_end_time = nil else --printf("_bp: object '%s': waiting for zone_warn '%s'", -- self.object:name(), self.st.zone_warn) if not self.zone_appear_wait_end_time then self.zone_appear_wait_end_time = time_global() + zone_appear_in_db_wait_timeout elseif time_global() >= self.zone_appear_wait_end_time then abort("object '%s': unable to find zone_warn '%s' on the map", self.object:name(), self.st.zone_warn) end return end end local actor = db.actor if not actor then return end if self.sound_activated and distance_between(self.object, actor) <= 5 then --printf("_bp: zoneguard: sound_update: maxidle = %d, sumidle = %s", self.snd.maxidle, self.snd.sumidle) xr_sound.set_sound(self.object, self.snd.themes) else xr_sound.set_sound(self.object, nil) end local see_actor = self.object:see(actor) if self.st.zone_guard_obj then if self.move_mgr:arrived_to_first_waypoint() or distance_between(self.object, self.st.zone_guard_obj) <= not_on_pos_max_kill_distance then if see_actor and self.st.zone_guard_obj:inside(actor:position()) then if not self:ignore_actor(actor) then -- FIXME: -- set_relation hit , -- , -- zoneguard. --self.object:set_relation(game_object.enemy, actor) local h = hit() h.power = 0 h.direction = self.object:direction() h.bone = "bip01_spine" h.draftsman = actor h.impulse = 0 h.type = hit.wound self.object:hit(h) end end end end if self.state == state_walking then if actor:alive() and see_actor and self.st.zone_warn_obj:inside(actor:position()) and teams[self.st.team].triggered == nil and not self:ignore_actor(actor) and self.move_mgr:arrived_to_first_waypoint() then if not self.st.no_move then self:go_to_actor(actor, true) self.state = state_going_to_plr else self:stand_still(actor) self.state = state_standing end --utils.stalker_look_at_stalker(self.object, actor) teams[self.st.team].triggered = self.object:id() if self.st.snd_greet and not self.sound_activated then --xr_sound.sound_update(self.object, self.snd) self.sound_activated = true end else self.move_mgr:update() if self.move_mgr:arrived_to_first_waypoint() then if xr_logic.try_switch_to_another_section(self.object, self.st, actor) then return end end end return end if xr_logic.try_switch_to_another_section(self.object, self.st, actor) then return end if self.state ~= state_walking and (not actor:alive() or not self.st.zone_warn_obj:inside(actor:position())) then self.move_mgr:reset(self.st.path_walk, self.st.path_walk_info, self.st.path_look, self.st.path_look_info, self.st.walker_team) self:reset_trigger() self.talked = false self.sound_activated = false self.state = state_walking return end --self.object:set_item(object.idle, self.object:best_weapon()) --utils.stalker_look_at_stalker(self.object, actor) if self.state == state_standing then if not self.st.no_move then if distance_between(self.object, actor) >= 4 then self:go_to_actor(actor, true) self.state = state_going_to_plr return end else if distance_between(self.object, actor) < 3 then self:talk_with_plr(actor) end end --if self.st.anim then --printf("_bp: anim_update: %s", self.st.anim) --xr_state.anim_update(self.st.anim, self.object) --end return end if self.state == state_going_to_plr then if distance_between(self.object, actor) >= 3 then -- false .. , -- . self:go_to_actor(actor, false) else self:stand_still(actor) self:talk_with_plr(actor) self.state = state_standing end return end end function action_zoneguard_activity:finalize() --self.object:disable_talk() self:reset_trigger() self.move_mgr:finalize() xr_sound.set_sound(self.object, nil) action_base.finalize(self) end --------------------------------------------------------------------------------------------------------------------- function add_to_binder(npc, ini, scheme, section, storage) local operators = {} local properties = {} local manager = npc:motivation_action_manager() properties["need_zoneguard"] = xr_evaluators_id.zmey_zoneguard_base + 1 operators["action_zoneguard"] = xr_actions_id.zmey_zoneguard_base + 1 -- evaluators manager:add_evaluator(properties["need_zoneguard"], this.evaluator_need_zoneguard(db.storage[npc:id()].zoneguard, "zoneguard_need")) local new_action = this.action_zoneguard_activity(npc, "action_zoneguard_activity", storage) new_action:add_precondition(world_property(stalker_ids.property_alive, true)) -- added by Dima if nil ~= stalker_ids.property_danger then new_action:add_precondition(world_property(stalker_ids.property_danger, false)) end new_action:add_precondition(world_property(stalker_ids.property_enemy, false)) new_action:add_precondition(world_property(properties["need_zoneguard"], true)) xr_motivator.addCommonPrecondition(new_action) new_action:add_effect(world_property(properties["need_zoneguard"], false)) manager:add_action(operators["action_zoneguard"], new_action) xr_logic.subscribe_action_for_events(npc, storage, new_action) new_action = manager:action(xr_actions_id.alife) new_action:add_precondition(world_property(properties["need_zoneguard"], false)) end -- enable - function set_scheme(npc, ini, scheme, section, gulag_name) local st = xr_logic.assign_storage_and_bind(npc, ini, scheme, section) st.logic = xr_logic.cfg_get_switch_conditions(ini, section, npc) st.path_walk = utils.cfg_get_string (ini, section, "path_walk", npc, true, gulag_name) st.path_look = utils.cfg_get_string (ini, section, "path_look", npc, false, gulag_name) st.team = utils.cfg_get_string (ini, section, "team", npc, true, gulag_name) st.zone_guard = utils.cfg_get_string (ini, section, "zone_guard", npc, false, gulag_name) st.zone_warn = utils.cfg_get_string (ini, section, "zone_warn", npc, true, gulag_name) st.walker_team = utils.cfg_get_string (ini, section, "walker_team", npc, false, gulag_name) st.no_move = utils.cfg_get_bool (ini, section, "no_move", npc, false) st.snd_greet = utils.cfg_get_string (ini, section, "snd_greet", npc, false, "") st.enable_dialog = utils.cfg_get_bool (ini, section, "enable_dialog", npc, false) st.ignore_friends = utils.cfg_get_bool (ini, section, "ignore_friends", npc, false) st.ignore_cond = xr_logic.cfg_get_condlist (ini, section, "ignore_cond", npc) st.no_danger = utils.cfg_get_bool (ini, section, "no_danger", npc, false) st.anim = utils.cfg_get_string (ini, section, "anim", npc, false, "") st.snd_anim_sync = utils.cfg_get_bool (ini, section, "snd_anim_sync", npc, false) --printf("_bp: st.anim == %s", st.anim) st.path_walk_info = nil -- reset(), st.path_look_info = nil -- . st.zone_guard_obj = nil st.zone_warn_obj = nil if not st.walker_team then st.walker_team = st.team end end
1
0.960318
1
0.960318
game-dev
MEDIA
0.844229
game-dev
0.963214
1
0.963214
spartanoah/acrimony-client
5,720
com/mojang/realmsclient/gui/screens/RealmsCreateRealmScreen.java
/* * Decompiled with CFR 0.153-SNAPSHOT (d6f6758-dirty). */ package com.mojang.realmsclient.gui.screens; import com.mojang.realmsclient.RealmsMainScreen; import com.mojang.realmsclient.dto.RealmsServer; import com.mojang.realmsclient.gui.screens.RealmsLongRunningMcoTaskScreen; import com.mojang.realmsclient.gui.screens.RealmsResetWorldScreen; import com.mojang.realmsclient.util.RealmsTasks; import net.minecraft.realms.Realms; import net.minecraft.realms.RealmsButton; import net.minecraft.realms.RealmsEditBox; import net.minecraft.realms.RealmsScreen; import org.lwjgl.input.Keyboard; public class RealmsCreateRealmScreen extends RealmsScreen { private final RealmsServer server; private RealmsMainScreen lastScreen; private RealmsEditBox nameBox; private RealmsEditBox descriptionBox; private static int CREATE_BUTTON = 0; private static int CANCEL_BUTTON = 1; private static int NAME_BOX_ID = 3; private static int DESCRIPTION_BOX_ID = 4; private RealmsButton createButton; public RealmsCreateRealmScreen(RealmsServer server, RealmsMainScreen lastScreen) { this.server = server; this.lastScreen = lastScreen; } @Override public void tick() { if (this.nameBox != null) { this.nameBox.tick(); } if (this.descriptionBox != null) { this.descriptionBox.tick(); } } @Override public void init() { Keyboard.enableRepeatEvents(true); this.buttonsClear(); this.createButton = RealmsCreateRealmScreen.newButton(CREATE_BUTTON, this.width() / 2 - 100, this.height() / 4 + 120 + 17, 97, 20, RealmsCreateRealmScreen.getLocalizedString("mco.create.world")); this.buttonsAdd(this.createButton); this.buttonsAdd(RealmsCreateRealmScreen.newButton(CANCEL_BUTTON, this.width() / 2 + 5, this.height() / 4 + 120 + 17, 95, 20, RealmsCreateRealmScreen.getLocalizedString("gui.cancel"))); this.createButton.active(false); this.nameBox = this.newEditBox(NAME_BOX_ID, this.width() / 2 - 100, 65, 200, 20); this.nameBox.setFocus(true); this.descriptionBox = this.newEditBox(DESCRIPTION_BOX_ID, this.width() / 2 - 100, 115, 200, 20); } @Override public void removed() { Keyboard.enableRepeatEvents(false); } @Override public void buttonClicked(RealmsButton button) { if (!button.active()) { return; } if (button.id() == CANCEL_BUTTON) { Realms.setScreen(this.lastScreen); } else if (button.id() == CREATE_BUTTON) { this.createWorld(); } } @Override public void keyPressed(char ch, int eventKey) { if (this.nameBox != null) { this.nameBox.keyPressed(ch, eventKey); } if (this.descriptionBox != null) { this.descriptionBox.keyPressed(ch, eventKey); } this.createButton.active(this.valid()); switch (eventKey) { case 15: { if (this.nameBox != null) { this.nameBox.setFocus(!this.nameBox.isFocused()); } if (this.descriptionBox == null) break; this.descriptionBox.setFocus(!this.descriptionBox.isFocused()); break; } case 28: case 156: { this.buttonClicked(this.createButton); break; } case 1: { Realms.setScreen(this.lastScreen); } } } private void createWorld() { if (this.valid()) { RealmsResetWorldScreen resetWorldScreen = new RealmsResetWorldScreen(this.lastScreen, this.server, this.lastScreen.newScreen(), RealmsCreateRealmScreen.getLocalizedString("mco.selectServer.create"), RealmsCreateRealmScreen.getLocalizedString("mco.create.world.subtitle"), 0xA0A0A0, RealmsCreateRealmScreen.getLocalizedString("mco.create.world.skip")); resetWorldScreen.setResetTitle(RealmsCreateRealmScreen.getLocalizedString("mco.create.world.reset.title")); RealmsTasks.WorldCreationTask worldCreationTask = new RealmsTasks.WorldCreationTask(this.server.id, this.nameBox.getValue(), this.descriptionBox.getValue(), resetWorldScreen); RealmsLongRunningMcoTaskScreen longRunningMcoTaskScreen = new RealmsLongRunningMcoTaskScreen(this.lastScreen, worldCreationTask); longRunningMcoTaskScreen.start(); Realms.setScreen(longRunningMcoTaskScreen); } } private boolean valid() { return this.nameBox.getValue() != null && !this.nameBox.getValue().trim().equals(""); } @Override public void mouseClicked(int x, int y, int buttonNum) { if (this.nameBox != null) { this.nameBox.mouseClicked(x, y, buttonNum); } if (this.descriptionBox != null) { this.descriptionBox.mouseClicked(x, y, buttonNum); } } @Override public void render(int xm, int ym, float a) { this.renderBackground(); this.drawCenteredString(RealmsCreateRealmScreen.getLocalizedString("mco.selectServer.create"), this.width() / 2, 11, 0xFFFFFF); this.drawString(RealmsCreateRealmScreen.getLocalizedString("mco.configure.world.name"), this.width() / 2 - 100, 52, 0xA0A0A0); this.drawString(RealmsCreateRealmScreen.getLocalizedString("mco.configure.world.description"), this.width() / 2 - 100, 102, 0xA0A0A0); if (this.nameBox != null) { this.nameBox.render(); } if (this.descriptionBox != null) { this.descriptionBox.render(); } super.render(xm, ym, a); } }
1
0.933701
1
0.933701
game-dev
MEDIA
0.973655
game-dev
0.943482
1
0.943482
sandialabs/InterSpec
8,911
external_libs/muparserx-4.0.7/value_test/mpIToken.cpp
/* __________ ____ ___ _____ __ _\______ \_____ _______ ______ __________\ \/ / / \| | \ ___/\__ \\_ __ \/ ___// __ \_ __ \ / | Y Y \ | / | / __ \| | \/\___ \\ ___/| | \/ \ |__|_| /____/|____| (____ /__| /____ >\___ >__| /___/\ \ \/ \/ \/ \/ \_/ muParserX - A C++ math parser library with array and string support Copyright 2010 Ingo Berg This program is free software: you can redistribute it and/or modify it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses. */ #include "mpIToken.h" #include <iostream> #include <algorithm> #include <vector> #include <list> #include <cassert> #include "mpIPrecedence.h" MUP_NAMESPACE_START #ifdef MUP_LEAKAGE_REPORT std::list<IToken*> IToken::s_Tokens; #endif #ifndef _UNICODE //--------------------------------------------------------------------------- /** \brief Overloaded streaming operator for outputting the value type into an std::ostream. \param a_Stream The stream object \param a_Val The value object to be streamed This function is only present if _UNICODE is not defined. */ std::ostream& operator<<(std::ostream &a_Stream, const IToken &tok) { return a_Stream << tok.ToString(); } #else //--------------------------------------------------------------------------- /** \brief Overloaded streaming operator for outputting the value type into an std::ostream. \param a_Stream The stream object \param a_Val The value object to be streamed This function is only present if _UNICODE is defined. */ std::wostream& operator<<(std::wostream &a_Stream, const IToken &tok) { return a_Stream << tok.ToString(); } #endif #ifdef MUP_LEAKAGE_REPORT void IToken::LeakageReport() { using namespace std; console() << "\n"; console() << "Memory leakage report:\n\n"; if (IToken::s_Tokens.size()) { list<IToken*>::const_iterator item = IToken::s_Tokens.begin(); std::vector<int> stat(cmCOUNT, 0); for (; item!=IToken::s_Tokens.end(); ++item) { console() << "Addr: 0x" << hex << *item << " Ident: \"" << (*item)->GetIdent() << "\""; console() << "\tCode: " << g_sCmdCode[(*item)->GetCode()] << "\n"; stat[(*item)->GetCode()]++; } console() << "Leaked tokens: " << dec << (int)IToken::s_Tokens.size() << std::endl; for (int i=0; i<cmCOUNT; ++i) console() << g_sCmdCode[i] << ":" << stat[i] << "\n"; console() << endl; } else { console() << "No tokens leaked!\n"; } } #endif //------------------------------------------------------------------------------ IToken::IToken(ECmdCode a_iCode) :m_eCode(a_iCode) ,m_sIdent() ,m_nPosExpr(-1) ,m_nRefCount(0) ,m_flags(0) { #ifdef MUP_LEAKAGE_REPORT IToken::s_Tokens.push_back(this); #endif } //------------------------------------------------------------------------------ IToken::IToken(ECmdCode a_iCode, string_type a_sIdent) :m_eCode(a_iCode) ,m_sIdent(a_sIdent) ,m_nPosExpr(-1) ,m_nRefCount(0) ,m_flags(0) { #ifdef MUP_LEAKAGE_REPORT IToken::s_Tokens.push_back(this); #endif } /** \brief Destructor (trivial). */ IToken::~IToken() { #ifdef MUP_LEAKAGE_REPORT std::list<IToken*>::iterator it = std::find(IToken::s_Tokens.begin(), IToken::s_Tokens.end(), this); IToken::s_Tokens.remove(this); #endif } //------------------------------------------------------------------------------ /** \brief Copy constructor. \param ref The token to copy basic state information from. The copy constructor must be implemented in order not to screw up the reference count of the created object. CC's are used in the Clone function and they would start with a reference count != 0 introducing memory leaks if the default CC where used. */ IToken::IToken(const IToken &ref) { m_eCode = ref.m_eCode; m_sIdent = ref.m_sIdent; m_flags = ref.m_flags; m_nPosExpr = ref.m_nPosExpr; // The following items must be initialised // (rather than just beeing copied) m_nRefCount = 0; } //------------------------------------------------------------------------------ void IToken::ResetRef() { m_nRefCount = 0; } //------------------------------------------------------------------------------ void IToken::Release() { delete this; } //------------------------------------------------------------------------------ string_type IToken::ToString() const { return AsciiDump(); } //------------------------------------------------------------------------------ int IToken::GetExprPos() const { return m_nPosExpr; } //------------------------------------------------------------------------------ void IToken::SetExprPos(int nPos) { m_nPosExpr = nPos; } //------------------------------------------------------------------------------ /** \brief return the token code. \sa ECmdCode */ ECmdCode IToken::GetCode() const { return m_eCode; } //------------------------------------------------------------------------------ /** \brief Return the token identifier string. */ const string_type& IToken::GetIdent() const { return m_sIdent; } //------------------------------------------------------------------------------ void IToken::SetIdent(const string_type &a_sIdent) { m_sIdent = a_sIdent; } //------------------------------------------------------------------------------ string_type IToken::AsciiDump() const { stringstream_type ss; ss << g_sCmdCode[m_eCode]; return ss.str().c_str(); } //------------------------------------------------------------------------------ void IToken::IncRef() const { ++m_nRefCount; } //------------------------------------------------------------------------------ long IToken::DecRef() const { return --m_nRefCount; } //------------------------------------------------------------------------------ long IToken::GetRef() const { return m_nRefCount; } //--------------------------------------------------------------------------- void IToken::AddFlags(int flags) { m_flags |= flags; } //--------------------------------------------------------------------------- bool IToken::IsFlagSet(int flags) const { return (m_flags & flags)==flags; } //--------------------------------------------------------------------------- ICallback* IToken::AsICallback() { return NULL; } //--------------------------------------------------------------------------- IValue* IToken::AsIValue() { return NULL; } //--------------------------------------------------------------------------- IPrecedence* IToken::AsIPrecedence() { return NULL; } //------------------------------------------------------------------------------ void IToken::Compile(const string_type &sArg) { } //--------------------------------------------------------------------------- // // Generic token implementation // //--------------------------------------------------------------------------- GenericToken::GenericToken(ECmdCode a_iCode, string_type a_sIdent) :IToken(a_iCode, a_sIdent) {} //--------------------------------------------------------------------------- GenericToken::GenericToken(ECmdCode a_iCode) :IToken(a_iCode, _T("")) {} //--------------------------------------------------------------------------- GenericToken::~GenericToken() {} //--------------------------------------------------------------------------- GenericToken::GenericToken(const GenericToken &a_Tok) :IToken(a_Tok) {} //--------------------------------------------------------------------------- IToken* GenericToken::Clone() const { return new GenericToken(*this); } //------------------------------------------------------------------------------ string_type GenericToken::AsciiDump() const { stringstream_type ss; ss << g_sCmdCode[ GetCode() ]; ss << _T(" [addr=0x") << std::hex << this << _T("]"); return ss.str(); } MUP_NAMESPACE_END
1
0.845658
1
0.845658
game-dev
MEDIA
0.425351
game-dev
0.949535
1
0.949535
ProjectIgnis/CardScripts
1,023
official/c32548609.lua
--エレキンモグラ --Wattmole local s,id=GetID() function s.initial_effect(c) --extra attack local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_EXTRA_ATTACK) e1:SetValue(1) c:RegisterEffect(e1) --destroy local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(id,0)) e2:SetCategory(CATEGORY_DESTROY) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_BATTLE_START) e2:SetCondition(s.descon) e2:SetTarget(s.destg) e2:SetOperation(s.desop) c:RegisterEffect(e2) end function s.descon(e,tp,eg,ep,ev,re,r,rp) local d=Duel.GetAttackTarget() return e:GetHandler()==Duel.GetAttacker() and d and d:IsFacedown() and d:IsDefensePos() end function s.destg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetAttackTarget():IsRelateToBattle() end Duel.SetOperationInfo(0,CATEGORY_DESTROY,Duel.GetAttackTarget(),1,0,0) end function s.desop(e,tp,eg,ep,ev,re,r,rp) local d=Duel.GetAttackTarget() if d:IsRelateToBattle() then Duel.Destroy(d,REASON_EFFECT) end end
1
0.815778
1
0.815778
game-dev
MEDIA
0.948871
game-dev
0.903259
1
0.903259
osgcc/ryzom
23,366
ryzom/server/src/entities_game_service/phrase_manager/faber_phrase.cpp
// Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/> // Copyright (C) 2010 Winch Gate Property Limited // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include "stdpch.h" #include "nel/misc/command.h" #include "phrase_manager/faber_phrase.h" #include "game_share/brick_families.h" #include "s_phrase_factory.h" #include "entity_manager/entity_manager.h" #include "player_manager/character.h" #include "phrase_manager/phrase_manager.h" #include "player_manager/player_manager.h" #include "player_manager/player.h" #include "phrase_manager/phrase_utilities_functions.h" #include "entity_structure/statistic.h" DEFAULT_SPHRASE_FACTORY( CFaberPhrase, BRICK_TYPE::FABER ); using namespace std; using namespace NLMISC; extern CPlayerManager PlayerManager; extern NLMISC::CRandom RandomGenerator; //----------------------------------------------- // ctor //----------------------------------------------- CFaberPhrase::CFaberPhrase() { _FaberAction = 0; _SabrinaCost = 0; _SabrinaRelativeCost = 1.0f; _FocusCost = 0; _FaberTime = 0; _CraftedItemStaticForm = 0; _RootFaberBricks = false; _RootFaberPlan = 0; // recommended skill level for using crafted item _Recommended = 0; // Item stats modifier _MBOQuality = 0; _MBODurability = 0.0f; _MBOWeight = 0.0f; _MBODmg = 0.0f; _MBOSpeed = 0.0f; _MBORange = 0.0f; _MBOProtection = 0.0f; _MBOSapLoad = 0.0f; // energy buff on item _MBOHitPoint = 0; _MBOSap = 0; _MBOStamina = 0; _MBOFocus = 0; _IsStatic = true; _PhraseType = BRICK_TYPE::FABER; } //----------------------------------------------- // CFaberPhrase build //----------------------------------------------- bool CFaberPhrase::build( const TDataSetRow & actorRowId, const std::vector< const CStaticBrick* >& bricks, bool buildToExecute ) { H_AUTO(CFaberPhrase_build); // we are sure there is at least one brick and that there are non NULL; nlassert( !bricks.empty() ); _ActorRowId = actorRowId; // compute cost and credit and parse other params for ( uint i = 0; i < bricks.size(); ++i ) { const CStaticBrick & brick = *bricks[i]; if( brick.SabrinaValue > 0 ) _SabrinaCost += brick.SabrinaValue; if( brick.SabrinaRelativeValue > 0.0f ) _SabrinaRelativeCost += brick.SabrinaRelativeValue; /* if( brick.Family == BRICK_FAMILIES::BCPA ) { if( _RootFaberBricks == false ) { _RootFaberBricks = true; } else { PHRASE_UTILITIES::sendDynamicSystemMessage(actorRowId, "ONLY_ONE_ROOT_FABER"); return false; } } else*/ if( ( brick.Family >= BRICK_FAMILIES::BeginFaberOption && brick.Family <= BRICK_FAMILIES::EndFaberOption ) || ( brick.Family >= BRICK_FAMILIES::BeginFaberCredit && brick.Family <= BRICK_FAMILIES::EndFaberCredit ) ) { for ( uint j = 0 ; j < brick.Params.size() ; ++j) { const TBrickParam::IId* param = brick.Params[j]; switch(param->id()) { case TBrickParam::FOCUS: INFOLOG("FOCUS: %i",((CSBrickParamCraftFocus *)param)->Focus); _FocusCost += ((CSBrickParamCraftFocus *)param)->Focus; break; case TBrickParam::CR_RECOMMENDED: INFOLOG("RECOMMENDED: %i",((CSBrickParamCraftRecommended *)param)->Recommended); _Recommended = ((CSBrickParamCraftRecommended *)param)->Recommended; break; case TBrickParam::CR_HP: INFOLOG("HP: %i",((CSBrickParamCraftHP *)param)->HitPoint); _MBOHitPoint += ((CSBrickParamCraftHP *)param)->HitPoint; break; case TBrickParam::CR_SAP: INFOLOG("SAP: %i",((CSBrickParamCraftSap *)param)->Sap); _MBOSap = ((CSBrickParamCraftSap *)param)->Sap; break; case TBrickParam::CR_STA: INFOLOG("STA: %i",((CSBrickParamCraftSta *)param)->Stamina); _MBOStamina += ((CSBrickParamCraftSta *)param)->Stamina; break; case TBrickParam::CR_FOCUS: INFOLOG("FOCUS: %i",((CSBrickParamCraftFocus *)param)->Focus); _MBOFocus += ((CSBrickParamCraftFocus *)param)->Focus; break; case TBrickParam::CR_QUALITY: INFOLOG("QUALITY: %d", ((CSBrickParamCraftQuality *)param)->Quality); _MBOQuality += (sint16)((CSBrickParamCraftQuality *)param)->Quality; break; case TBrickParam::CR_DURABILITY: INFOLOG("DURABILITY: %.2f", ((CSBrickParamCraftDurability *)param)->Durability); _MBODurability += ((CSBrickParamCraftDurability *)param)->Durability; break; case TBrickParam::CR_DAMAGE: INFOLOG("DAMAGE: %.2f", ((CSBrickParamCraftDamage *)param)->Damage); _MBODmg += ((CSBrickParamCraftDamage *)param)->Damage; break; case TBrickParam::CR_HITRATE: INFOLOG("HITRATE: %.2f", ((CSBrickParamCraftHitRate *)param)->HitRate); _MBODmg += ((CSBrickParamCraftHitRate *)param)->HitRate; break; case TBrickParam::CR_RANGE: INFOLOG("RANGE: %.2f", ((CSBrickParamCraftRange *)param)->Range); _MBORange += ((CSBrickParamCraftRange *)param)->Range; break; case TBrickParam::CR_DMG_PROTECTION: INFOLOG("DMG_PROTECTION: %.2f", ((CSBrickParamCraftDmgProtection *)param)->DmgProtection); _MBOProtection += ((CSBrickParamCraftDmgProtection *)param)->DmgProtection; break; case TBrickParam::CR_SAPLOAD: INFOLOG("SAPLOAD: %.2f", ((CSBrickParamCraftSapload *)param)->Sapload); _MBOProtection += ((CSBrickParamCraftSapload *)param)->Sapload; break; case TBrickParam::CR_WEIGHT: INFOLOG("WEIGHT: %.2f", ((CSBrickParamCraftWeight *)param)->Weight); _MBOWeight += ((CSBrickParamCraftWeight *)param)->Weight; break; default: // unused param ? break; } } } } CCharacter * c = dynamic_cast< CCharacter * > ( CEntityBaseManager::getEntityBasePtr( _ActorRowId ) ); if( c == 0 ) { nlwarning("<CFaberPhrase::build> Player character not found but his crafting action still running!!!"); return false; } /* if( ( _RootFaberBricks == false ) || ( _Recommended == 0 ) && ( _SabrinaCost > (sint32)_Recommended ) ) { PHRASE_UTILITIES::sendDynamicSystemMessage(actorRowId, "CRAFT_SENTENCE_INCORRECT"); return false; } */ return true; }// CFaberPhrase build //----------------------------------------------- // CFaberPhrase evaluate //----------------------------------------------- bool CFaberPhrase::evaluate() { return true; }// CFaberPhrase evaluate //----------------------------------------------- // CFaberPhrase validate //----------------------------------------------- bool CFaberPhrase::validate() { H_AUTO(CFaberPhrase_validate); if ( !CraftSystemEnabled ) return false; CCharacter * c = (CCharacter *) CEntityBaseManager::getEntityBasePtr( _ActorRowId ); if( c == 0 ) { nlwarning("<CFaberPhrase::validate> Player character not found but his crafting action still running!!!"); return false; } // test entity can use action if (c->canEntityUseAction() == false) { return false; } // check right hand item is a crafting tool CGameItemPtr rightHandItem = c->getRightHandItem(); if (rightHandItem == NULL || rightHandItem->getStaticForm() == NULL || rightHandItem->getStaticForm()->Family != ITEMFAMILY::CRAFTING_TOOL) { PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "CRAFT_NEED_CRAFTING_TOOL"); return false; } // check tool is not worned if( rightHandItem->getItemWornState() == ITEM_WORN_STATE::Worned ) { PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "CRAFT_NEED_CRAFTING_TOOL"); return false; } // check quality of right hand item (need be >= Recommended (level of item)) if (rightHandItem->recommended()+49 < _Recommended) { PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "CRAFT_NEED_RECOMMENDED_CRAFTING_TOOL"); return false; } // entities cant craft if in combat /* commented as test of right hand item is now made... TDataSetRow entityRowId = CPhraseManager::getInstance().getEntityEngagedMeleeBy( _ActorRowId ); if (TheDataset.isAccessible(entityRowId)) { PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "CANT_CRAFT_ENGAGED_IN_MELEE"); return false; } */ const sint32 focus = c->getScores()._PhysicalScores[ SCORES::focus ].Current; if ( focus < _FocusCost ) { PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "CANT_CRAFT_NOT_ENOUGHT_FOCUS"); c->unlockFaberRms(); return false; } const sint32 hp = c->currentHp(); if (hp <= 0 || c->isDead()) { PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "CANT_CRAFT_WHEN_DEAD"); c->unlockFaberRms(); return false; } /// todo alain : test if on mount // store vector of pointer on raw material item if( state() == Evaluated ) { if( c->lockFaberRms() ) { _Mps.clear(); _MpsFormula.clear(); if( c->getFillFaberRms( _Mps, _MpsFormula, _LowerRmQuality ) == false ) //TODO check exec step { c->unlockFaberRms(); PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "CANT_FOUND_RM"); return false; } } else { c->unlockFaberRms(); PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "CANT_LOCK_RM"); return false; } } return true; }// CFaberPhrase validate //----------------------------------------------- // CFaberPhrase update //----------------------------------------------- bool CFaberPhrase::update() { return true; }// CFaberPhrase update //----------------------------------------------- // CFaberPhrase execute //----------------------------------------------- void CFaberPhrase::execute() { H_AUTO(CFaberPhrase_execute); CCharacter* player = PlayerManager.getChar(_ActorRowId); if (!player) return; const CStaticBrick * plan = CSheets::getSBrickForm( player->getCraftPlan() ); if( plan == 0 ) { nlwarning("<CFaberPhrase::execute> Can't found static form of craft plan %s", player->getCraftPlan().toString().c_str() ); return; } /// set Faber time if not set (default is 2 sec) if ( !_FaberTime) { _FaberTime = (NLMISC::TGameCycle)(plan->CraftingDuration * 10); } nldebug("CFaberPhrase::execute> _FaberTime = %d",_FaberTime); const NLMISC::TGameCycle time = CTickEventHandler::getGameCycle(); _ExecutionEndDate = time + _FaberTime ; player->setCurrentAction(CLIENT_ACTION_TYPE::Faber,_ExecutionEndDate); player->staticActionInProgress(true); // set behaviour PHRASE_UTILITIES::sendUpdateBehaviour( _ActorRowId, MBEHAV::FABER ); }// CFaberPhrase execute //----------------------------------------------- // CFaberPhrase launch //----------------------------------------------- bool CFaberPhrase::launch() { // apply imediatly _ApplyDate = 0; return true; }// CFaberPhrase launch //----------------------------------------------- // CFaberPhrase apply //----------------------------------------------- void CFaberPhrase::apply() { H_AUTO(CFaberPhrase_apply); CCharacter * c = dynamic_cast< CCharacter * > ( CEntityBaseManager::getEntityBasePtr( _ActorRowId ) ); if( c == 0 ) { nlwarning("<CFaberPhrase::apply> Player character not found but his crafting action still running!!!"); stop(); return; } // apply wearing equipment penalty on Recommended skill _Recommended -= (uint32)(_Recommended * c->wearMalus() * WearMalusCraftFactor); const CStaticBrick * plan = CSheets::getSBrickForm( c->getCraftPlan() ); if( plan == 0 ) { nlwarning("<CFaberPhrase::apply> Can't found static form of craft plan %s", c->getCraftPlan().toString().c_str() ); PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "UNKNOWN_CRAFT_PLAN"); stop(); return; } _RootFaberPlan = plan; // TODO check compatibility of Rms with plan // temporary only check number of Mp match with plan sint32 nbMp = (sint32)_Mps.size(); uint32 nbMpNeedeInPlan = 0; uint32 neededMp = (uint32)_RootFaberPlan->Faber->NeededMps.size(); for( uint mp = 0; mp < neededMp; ++mp ) { //for each type of Mp needed nbMpNeedeInPlan += _RootFaberPlan->Faber->NeededMps[ mp ].Quantity; } if( nbMpNeedeInPlan != _Mps.size() ) { nlwarning("<CFaberPhrase::apply> Craft plan %s need %d Raw Material and client send %d Raw Material", c->getCraftPlan().toString().c_str(), _RootFaberPlan->Faber->NeededMps.size(), _Mps.size() ); PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "RAW_MATERIAL_MISSING"); stop(); return; } nbMp = (sint32)_MpsFormula.size(); uint32 nbMpForumulaNeedeInPlan = 0; neededMp = (uint32)_RootFaberPlan->Faber->NeededMpsFormula.size(); for( uint mp = 0; mp < neededMp; ++mp ) { //for each type of Mp needed nbMpForumulaNeedeInPlan += _RootFaberPlan->Faber->NeededMpsFormula[ mp ].Quantity; } if( nbMpForumulaNeedeInPlan != _MpsFormula.size() ) { nlwarning("<CFaberPhrase::apply> Craft plan %s need %d Raw Material Formula and client send %d Raw Material Formula", c->getCraftPlan().toString().c_str(), _RootFaberPlan->Faber->NeededMpsFormula.size(), _MpsFormula.size() ); PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "RAW_MATERIAL_MISSING"); stop(); return; } // Check skill on faber plan if( _RootFaberPlan->getSkill(0) == SKILLS::unknown ) { nlwarning("<CFaberPhrase::apply> Craft plan %s contains an invalid skill", c->getCraftPlan().toString().c_str() ); PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "INVALID_CRAFT_PLAN"); stop(); return; } _CraftedItemStaticForm = CSheets::getForm( plan->Faber->CraftedItem ); if( _CraftedItemStaticForm == 0 ) { nlwarning("<CFaberPhrase::apply> Can't found static form of crafted item %s", plan->Faber->CraftedItem.toString().c_str() ); PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "UNKNOWN_CRAFTED_ITEM"); stop(); return; } // build the craft action _FaberAction = IFaberActionFactory::buildAction( _ActorRowId, this, _CraftedItemStaticForm->Type ); if ( !_FaberAction ) { nlwarning( "<CFaberPhrase build> could not build action for plan brick %s", _RootFaberPlan->SheetId.toString().c_str() ); stop(); return; } neededMp = (uint32)_RootFaberPlan->Faber->NeededMps.size(); EGSPD::CPeople::TPeople civRestriction = _RootFaberPlan->CivRestriction; uint32 usedMp=0; vector< const CStaticItem * > usedMps = _Mps; for( uint mp = 0; mp < neededMp; ++mp ) { //for each type of Mp needed for( uint k = 0; k < _RootFaberPlan->Faber->NeededMps[ mp ].Quantity; ++k ) { bool found_mp = false; for(uint u_mp = 0; u_mp < usedMps.size(); ++u_mp) { // for each Mp of one type (we have Quantity by type) uint32 NumMpParameters = (uint32)usedMps[u_mp]->Mp->MpFaberParameters.size(); // for each Faber parameters in Mp for( uint j = 0; j < NumMpParameters; ++j ) { // check if Mp Type match with Faber waiting Type if( _RootFaberPlan->Faber->NeededMps[mp].MpType == usedMps[u_mp]->Mp->MpFaberParameters[j].MpFaberType ) { found_mp = true; usedMp++; break; } } if (found_mp) { // Bypass if : Plan is common if ( civRestriction != EGSPD::CPeople::Common ) { switch (usedMps[u_mp]->Mp->Ecosystem) { // I can't found some thing to do this ugly translation. case ECOSYSTEM::desert: if (civRestriction != EGSPD::CPeople::Fyros) { nlwarning( "<CFaberPhrase build> bad civilisation mp for plan brick %s", _RootFaberPlan->SheetId.toString().c_str() ); stop(); return; } break; case ECOSYSTEM::forest: if (civRestriction != EGSPD::CPeople::Matis) { nlwarning( "<CFaberPhrase build> bad civilisation mp for plan brick %s", _RootFaberPlan->SheetId.toString().c_str() ); stop(); return; } break; case ECOSYSTEM::lacustre: if (civRestriction != EGSPD::CPeople::Tryker) { nlwarning( "<CFaberPhrase build> bad civilisation mp for plan brick %s", _RootFaberPlan->SheetId.toString().c_str() ); stop(); return; } break; case ECOSYSTEM::jungle: if (civRestriction != EGSPD::CPeople::Zorai) { nlwarning( "<CFaberPhrase build> bad civilisation mp for plan brick %s", _RootFaberPlan->SheetId.toString().c_str() ); stop(); return; } break; } } usedMps.erase(usedMps.begin()+u_mp); break; } } if (!found_mp) { nlinfo("NOT FOUND : wanted %d\n", _RootFaberPlan->Faber->NeededMps[ mp ].MpType); } } } if (!usedMps.empty()) { nlwarning( "<CFaberPhrase build> could not build action for plan brick %s", _RootFaberPlan->SheetId.toString().c_str() ); stop(); return; } if (usedMp != nbMpNeedeInPlan) { nlwarning( "<CFaberPhrase build> could not build action for plan brick %s", _RootFaberPlan->SheetId.toString().c_str() ); stop(); return; } // spend energies SCharacteristicsAndScores &focus = c->getScores()._PhysicalScores[SCORES::focus]; if ( focus.Current != 0) { focus.Current = focus.Current - _FocusCost; if (focus.Current < 0) focus.Current = 0; } // apply action of the sentence _FaberAction->apply(this); _CraftedItem = 0; }//CFaberPhrase apply //----------------------------------------------- // CFaberPhrase systemCraftItem: //----------------------------------------------- CGameItemPtr CFaberPhrase::systemCraftItem( const NLMISC::CSheetId& sheet, const std::vector< NLMISC::CSheetId >& Mp, const std::vector< NLMISC::CSheetId >& MpFormula ) { H_AUTO(CFaberPhrase_systemCraftItem); std::vector< const CStaticBrick* > bricks; _RootFaberPlan = CSheets::getSBrickForm( sheet ); const CStaticBrick * rootFaberBricks = CSheets::getSBrickForm( CSheetId("bcpa01.sbrick") ); if( rootFaberBricks ) { _RootFaberBricks = true; } else { nlwarning("<CFaberPhrase::systemCraftItem> Can't found form of root faber brick bcpa01.sbrick"); return 0; } CGameItemPtr craftedItem = 0; if( _RootFaberPlan && _RootFaberPlan->Faber ) { _CraftedItemStaticForm = CSheets::getForm( _RootFaberPlan->Faber->CraftedItem ); if( _CraftedItemStaticForm == 0 ) { return 0; } bricks.push_back( rootFaberBricks ); bricks.push_back( _RootFaberPlan ); for( vector< NLMISC::CSheetId >::const_iterator it = Mp.begin(); it != Mp.end(); ++it ) { const CStaticItem * mp = CSheets::getForm( (*it) ); if( mp == 0 ) { nlwarning("<CFaberPhrase::systemCraftItem> Can't found form for Mp %s for craft %s item", (*it).toString().c_str(), sheet.toString().c_str() ); return 0; } _Mps.push_back( mp ); } // Check quantity of gived Mps if( _RootFaberPlan->Faber->NeededMps.size() > _Mps.size() ) { nlwarning("<CFaberPhrase::systemCraftItem> Not enought gived RM for crafting %s (gived Mp %d, Needed Mp %d)", sheet.toString().c_str(), _Mps.size(), _RootFaberPlan->Faber->NeededMps.size() ); return 0; } for( vector< NLMISC::CSheetId >::const_iterator it = MpFormula.begin(); it != MpFormula.end(); ++it ) { const CStaticItem * mp = CSheets::getForm( (*it) ); if( mp == 0 ) { nlwarning("<CFaberPhrase::systemCraftItem> Can't found form for Mp Formula %s for craft %s item", (*it).toString().c_str(), sheet.toString().c_str() ); return 0; } _MpsFormula.push_back( mp ); } // Check quantity of gived Mps formula if( _RootFaberPlan->Faber->NeededMpsFormula.size() > _MpsFormula.size() ) { nlwarning("<CFaberPhrase::systemCraftItem> Not enought gived RM formula for crafting %s (gived Mp %d, Needed Mp %d)", sheet.toString().c_str(), _MpsFormula.size(), _RootFaberPlan->Faber->NeededMpsFormula.size() ); return 0; } // build the craft action _FaberAction = IFaberActionFactory::buildAction( _ActorRowId, this, _CraftedItemStaticForm->Type ); if ( !_FaberAction ) { nlwarning( "<CFaberPhrase build> could not build action for root faber %s", _RootFaberPlan->SheetId.toString().c_str() ); return 0; } _FaberAction->systemApply(this); if( _CraftedItem != 0 ) { _CraftedItem->setDefaultColor(); } craftedItem = _CraftedItem; _CraftedItem = 0; } return craftedItem; } // systemCraftItem // //----------------------------------------------- // CFaberPhrase end //----------------------------------------------- void CFaberPhrase::end() { H_AUTO(CFaberPhrase_end); CCharacter* player = PlayerManager.getChar(_ActorRowId); if (!player) return; player->unlockFaberRms(); player->clearCurrentAction(); player->staticActionInProgress(false); //player->sendCloseTempInventoryImpulsion(); // set behaviour PHRASE_UTILITIES::sendUpdateBehaviour( _ActorRowId, MBEHAV::FABER_END ); } // end // //----------------------------------------------- // CFaberPhrase stop //----------------------------------------------- void CFaberPhrase::stop() { H_AUTO(CFaberPhrase_stop); CCharacter* player = PlayerManager.getChar(_ActorRowId); if (!player) return; player->unlockFaberRms(); player->clearCurrentAction(); player->staticActionInProgress(false); player->sendCloseTempInventoryImpulsion(); // set behaviour PHRASE_UTILITIES::sendUpdateBehaviour( _ActorRowId, MBEHAV::FABER_END ); // send message PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "FABER_CANCEL"); } // stop // NLMISC_COMMAND(simuCraft, "Craft simulation to verify probabilities to succesfully craft an item","<Nb simulations><level skill><item quality>") { if (args.size() != 3) return false; uint32 nbSimu, skillLevel, itemQuality; NLMISC::fromString(args[0], nbSimu); NLMISC::fromString(args[1], skillLevel); NLMISC::fromString(args[2], itemQuality); sint32 deltaLvl = skillLevel - itemQuality; float sf; uint32 nbFullSuccess = 0; uint32 nbPartialSuccess = 0; uint32 nbMiss = 0; double XpGain = 0; sint32 skillValue = 0; sint32 deltaLvlXp = 0; for(uint32 i = 0; i < nbSimu; ++i) { uint8 roll =(uint8) RandomGenerator.rand(100); sf = CStaticSuccessTable::getSuccessFactor( SUCCESS_TABLE_TYPE::Craft, deltaLvl, roll ); // xp gains skillValue = skillLevel; sint32 minimum = max( (sint32)10, min( (sint32)50, (sint32)( skillValue + 10 ) ) ); deltaLvlXp = deltaLvl * (sint32)50 / minimum; if(sf == 1.0f) { ++nbFullSuccess; XpGain += CStaticSuccessTable::getXPGain(SUCCESS_TABLE_TYPE::Craft, deltaLvlXp); } else if( sf > 0.0f) { ++nbPartialSuccess; XpGain += CStaticSuccessTable::getXPGain(SUCCESS_TABLE_TYPE::Craft, deltaLvlXp) * sf; } else ++nbMiss; } nlinfo("FaberSimu: Results after %d roll: Sucess: %d (%.2f%%), partial sucess: %d (%.2f%%), Miss: %d (%.2f%%), Xp Gain %d", nbSimu, nbFullSuccess, 100.0f*nbFullSuccess/nbSimu, nbPartialSuccess, 100.0f*nbPartialSuccess/nbSimu, nbMiss, 100.0f*nbMiss/nbSimu, uint32(1000.f*XpGain / (nbSimu-nbMiss/2) ) ); return true; }
1
0.953492
1
0.953492
game-dev
MEDIA
0.50488
game-dev,testing-qa
0.939567
1
0.939567
hellfire3d/SBSPSS
14,504
source/frontend/start.cpp
/*========================================================================= start.cpp Author: PKG Created: Project: Spongebob Purpose: Copyright (c) 2000 Climax Development Ltd ===========================================================================*/ /*---------------------------------------------------------------------- Includes -------- */ #include "frontend\start.h" #ifndef __GFX_FONT_H__ #include "gfx\font.h" #endif #ifndef __GFX_SPRBANK_H__ #include "gfx\sprbank.h" #endif #ifndef __LOCALE_TEXTDBASE_H__ #include "locale\textdbase.h" #endif #ifndef __GFX_FADER_H__ #include "gfx\fader.h" #endif #ifndef __PRIM_HEADER__ #include "gfx\prim.h" #endif #ifndef __GUI_GFACTORY_H__ #include "gui\gfactory.h" #endif #ifndef __GUI_GFRAME_H__ #include "gui\gframe.h" #endif #ifndef __GUI_GTEXTBOX_H__ #include "gui\gtextbox.h" #endif #ifndef __GAME_GAMESLOT_H__ #include "game\gameslot.h" #endif #ifndef __PAD_PADS_H__ #include "pad\pads.h" #endif #ifndef __GAME_GAME_H__ #include "game\game.h" #endif #ifndef __SOUND_SOUND_H__ #include "sound\sound.h" #endif #ifndef __MAP_MAP_H__ #include "map\map.h" #endif /* Std Lib ------- */ /* Data ---- */ #ifndef __SPR_SPRITES_H__ #include <sprites.h> #endif #ifndef __SPR_SHOP_H__ #include <shop.h> #endif /*---------------------------------------------------------------------- Tyepdefs && Defines ------------------- */ /*---------------------------------------------------------------------- Structure defintions -------------------- */ /*---------------------------------------------------------------------- Function Prototypes ------------------- */ /*---------------------------------------------------------------------- Vars ---- */ const int CFrontEndStart::s_itemFrames[]= { FRM_TEDDY, // SHOPITEM_TEDDY FRM_SARNIE, // SHOPITEM_SARNIE FRM_CUPCAKE, // SHOPITEM_CUPCAKE FRM_PREZZIE, // SHOPITEM_PREZZIE FRM_JELLY2, // SHOPITEM_JELLY2 FRM_CAKE, // SHOPITEM_CAKE FRM_BLOWER, // SHOPITEM_BLOWER FRM_PARTYHAT, // SHOPITEM_PARTYHAT }; /*---------------------------------------------------------------------- Function: Purpose: Params: Returns: ---------------------------------------------------------------------- */ void CFrontEndStart::init() { CGUITextBox *tb; m_emptyGuiFrame=new ("Frame") CGUIGroupFrame(); m_emptyGuiFrame->init(NULL); m_emptyGuiFrame->setObjectXYWH((512-416)/2,130,416,96); m_emptyGuiFrame->setFlags(CGUIObject::FLAG_DRAWBORDER); m_confirmEraseGuiFrame=new ("Frame") CGUIControlFrame(); m_confirmEraseGuiFrame->init(NULL); m_confirmEraseGuiFrame->setObjectXYWH((512-416)/2,130,416,96); CGUIFactory::createValueButtonFrame(m_confirmEraseGuiFrame, 8,55,400,20, STR__NO,&m_confirmFlag,CONFIRM_NO); CGUIFactory::createValueButtonFrame(m_confirmEraseGuiFrame, 8,70,400,20, STR__YES,&m_confirmFlag,CONFIRM_YES); tb=new ("textbox") CGUITextBox(); tb->init(m_confirmEraseGuiFrame); tb->setObjectXYWH(8,5,400,35); tb->setText(STR__SLOT_SELECT_SCREEN__CONFIRM_ERASE_GAME); m_createdSlotGuiFrame=new ("Frame") CGUIControlFrame(); m_createdSlotGuiFrame->init(NULL); m_createdSlotGuiFrame->setObjectXYWH((512-416)/2,130,416,96); CGUIFactory::createValueButtonFrame(m_createdSlotGuiFrame, 8,55,400,20, STR__OK,&m_confirmFlag,CONFIRM_OK); tb=new ("textbox") CGUITextBox(); tb->init(m_createdSlotGuiFrame); tb->setObjectXYWH(8,5,400,35); tb->setText(STR__SLOT_SELECT_SCREEN__NEW_SLOT_CREATED); m_font=new ("ChooseSlotFont") FontBank(); m_font->initialise(&standardFont); m_font->setJustification(FontBank::JUST_LEFT); m_font->setOt(0); m_font->setPrintArea(0,0,712,256); m_spriteBank=new ("PartItemSprites") SpriteBank(); m_spriteBank->load(SHOP_SHOP_SPR); } /*---------------------------------------------------------------------- Function: Purpose: Params: Returns: ---------------------------------------------------------------------- */ void CFrontEndStart::shutdown() { m_spriteBank->dump(); delete m_spriteBank; m_font->dump(); delete m_font; m_createdSlotGuiFrame->shutdown(); m_confirmEraseGuiFrame->shutdown(); m_emptyGuiFrame->shutdown(); } /*---------------------------------------------------------------------- Function: Purpose: Params: Returns: ---------------------------------------------------------------------- */ void CFrontEndStart::select() { CFader::setFadingIn(); m_state=STATE_SELECT; m_selectedSlot=0; m_slotDrawOffset=0; CSoundMediator::setSong(CSoundMediator::SONG_MEMCARD2); m_musicStarted=false; } /*---------------------------------------------------------------------- Function: Purpose: Params: Returns: ---------------------------------------------------------------------- */ void CFrontEndStart::unselect() { CSoundMediator::dumpSong(); } /*---------------------------------------------------------------------- Function: Purpose: Params: Returns: ---------------------------------------------------------------------- */ void CFrontEndStart::render() { POLY_G4 *g4; g4=GetPrimG4(); setXYWH(g4,0,0,512,256); setRGB0(g4, 0,150, 50); setRGB1(g4, 0,150, 50); setRGB2(g4,150, 50, 0); setRGB3(g4,150, 50, 0); AddPrimToList(g4,MAX_OT-1); drawGameSlot(m_slotDrawOffset,m_selectedSlot); if(m_slotDrawOffset) { int ofs; ofs=m_slotDrawOffset<0?512:-512; drawGameSlot(ofs+m_slotDrawOffset,m_lastSelectedSlot); } switch(m_state) { case STATE_SELECT: if(!m_slotDrawOffset) { drawInstructions(); } m_emptyGuiFrame->render(); break; case STATE_CONFIRM_ERASE: m_confirmEraseGuiFrame->render(); break; case STATE_EXITING_TO_FRONT_END: case STATE_EXITING_TO_GAME: m_emptyGuiFrame->render(); break; case STATE_SLOT_CREATED: m_createdSlotGuiFrame->render(); break; } } /*---------------------------------------------------------------------- Function: Purpose: Params: Returns: ---------------------------------------------------------------------- */ void CFrontEndStart::drawGameSlot(int _xOff,int _slotNumber) { int xbase; CGameSlotManager::GameSlot *gameSlot; TPOLY_F4 *f4; int x,y; sFrameHdr *fh; int i; char buf[100]; xbase=_xOff+SLOT_FRAME_X; CGameSlotManager::setActiveSlot(_slotNumber); gameSlot=CGameSlotManager::getSlotData(); drawBambooBorder(xbase,SLOT_FRAME_Y,SLOT_FRAME_W,SLOT_FRAME_H,3); f4=GetPrimTF4(); setXYWH(f4,xbase,SLOT_FRAME_Y,SLOT_FRAME_W,SLOT_FRAME_H); setRGB0(f4, 0, 0, 90); setTSemiTrans(f4,true); AddPrimToList(f4,3); x=xbase+SLOT_SLOTNUMBER_X; y=SLOT_FRAME_Y+SLOT_SLOTNUMBER_Y; sprintf(buf,TranslationDatabase::getString(STR__SLOT_SELECT_SCREEN__SLOT_NUMBER),_slotNumber+1,4); m_font->print(x,y,buf); if(gameSlot->m_isInUse) { int chapter,level; gameSlot->getHighestLevelOpen(&chapter,&level); sprintf(buf,TranslationDatabase::getString(STR__SLOT_SELECT_SCREEN__LEVEL_REACHED),chapter+1,level+1); m_font->print(xbase+SLOT_LEVEL_TEXT_X,SLOT_FRAME_Y+SLOT_LEVEL_TEXT_Y,buf); x=xbase+SLOT_TOKENCOUNT_X; y=SLOT_FRAME_Y+SLOT_TOKENCOUNT_Y; fh=m_spriteBank->getFrameHeader(FRM_SMALLTOKEN); m_spriteBank->printFT4(fh,x,y,0,0,2); x+=fh->W; sprintf(buf,"x%d",CGameSlotManager::getSlotData()->getNumberOfKelpTokensHeld()); m_font->print(x,y,buf); x=xbase+SLOT_ITEM_X; y=SLOT_FRAME_Y+SLOT_ITEM_Y; for(i=0;i<8;i++) { POLY_FT4 *ft4; ft4=m_spriteBank->printFT4(s_itemFrames[i],x,y,0,0,2); if(!gameSlot->isPartyItemHeld(i)) { setRGB0(ft4,35,35,35); } x+=SLOT_ITEM_YGAP; } } else { m_font->setJustification(FontBank::JUST_CENTRE); m_font->print(xbase+SLOT_EMPTYTEXT_X,SLOT_FRAME_Y+SLOT_EMPTYTEXT_Y,STR__SLOT_SELECT_SCREEN__EMPTY_SLOT); m_font->setJustification(FontBank::JUST_LEFT); } } /*---------------------------------------------------------------------- Function: Purpose: Params: Returns: ---------------------------------------------------------------------- */ void CFrontEndStart::drawInstructions() { int slotInUse; SpriteBank *sb; sFrameHdr *fh1,*fh2; int width; int x,y; int text; CGameSlotManager::setActiveSlot(m_selectedSlot); slotInUse=CGameSlotManager::getSlotData()->m_isInUse; sb=CGameScene::getSpriteBank(); m_font->setColour(255,255,255); y=INSTRUCTIONS_YSTART; fh1=sb->getFrameHeader(FRM__BUTL); fh2=sb->getFrameHeader(FRM__BUTR); width=fh1->W+INSTRUCTIONS_GAP_BETWEEN_BUTTONS+fh2->W+INSTRUCTIONS_GAP_BETWEEN_BUTTONS_AND_TEXT+m_font->getStringWidth(STR__SLOT_SELECT_SCREEN__LEFT_RIGHT_TO_SELECT_SLOT); x=256-(width/2); sb->printFT4(fh1,x,y+INSTRUCTIONS_BUTTON_Y_OFFSET,0,0,0); x+=fh1->W+INSTRUCTIONS_GAP_BETWEEN_BUTTONS; sb->printFT4(fh2,x,y+INSTRUCTIONS_BUTTON_Y_OFFSET,0,0,0); x+=fh2->W+INSTRUCTIONS_GAP_BETWEEN_BUTTONS_AND_TEXT; m_font->print(x,y,STR__SLOT_SELECT_SCREEN__LEFT_RIGHT_TO_SELECT_SLOT); text=slotInUse?STR__SLOT_SELECT_SCREEN__CROSS_TO_CONFIRM:STR__SLOT_SELECT_SCREEN__CROSS_TO_CREATE; y+=INSTRUCTIONS_Y_SPACE_BETWEEN_LINES; fh1=sb->getFrameHeader(FRM__BUTX); width=fh1->W+INSTRUCTIONS_GAP_BETWEEN_BUTTONS_AND_TEXT+m_font->getStringWidth(text); x=256-(width/2); sb->printFT4(fh1,x,y+INSTRUCTIONS_BUTTON_Y_OFFSET,0,0,0); x+=fh1->W+INSTRUCTIONS_GAP_BETWEEN_BUTTONS_AND_TEXT; m_font->print(x,y,text); y+=INSTRUCTIONS_Y_SPACE_BETWEEN_LINES; fh1=sb->getFrameHeader(FRM__BUTC); width=fh1->W+INSTRUCTIONS_GAP_BETWEEN_BUTTONS_AND_TEXT+m_font->getStringWidth(STR__SLOT_SELECT_SCREEN__CIRCLE_TO_ERASE_SLOT); x=256-(width/2); if(slotInUse) { sb->printFT4(fh1,x,y+INSTRUCTIONS_BUTTON_Y_OFFSET,0,0,0); } x+=fh1->W+INSTRUCTIONS_GAP_BETWEEN_BUTTONS_AND_TEXT; if(slotInUse) { m_font->print(x,y,STR__SLOT_SELECT_SCREEN__CIRCLE_TO_ERASE_SLOT); } y+=INSTRUCTIONS_Y_SPACE_BETWEEN_LINES; fh1=sb->getFrameHeader(FRM__BUTT); width=fh1->W+INSTRUCTIONS_GAP_BETWEEN_BUTTONS_AND_TEXT+m_font->getStringWidth(STR__SLOT_SELECT_SCREEN__TRIANGLE_TO_EXIT); x=256-(width/2); sb->printFT4(fh1,x,y+INSTRUCTIONS_BUTTON_Y_OFFSET,0,0,0); x+=fh1->W+INSTRUCTIONS_GAP_BETWEEN_BUTTONS_AND_TEXT; m_font->print(x,y,STR__SLOT_SELECT_SCREEN__TRIANGLE_TO_EXIT); } /*---------------------------------------------------------------------- Function: Purpose: Params: Returns: ---------------------------------------------------------------------- */ void CFrontEndStart::think(int _frames) { if(!CFader::isFading()) { if(!m_musicStarted) { CSoundMediator::playSong(); m_musicStarted=true; } if(m_slotDrawOffset==0) { if(m_state==STATE_SELECT) { // Select a slot int pad=PadGetDown(0); if(pad&PAD_LEFT) { m_lastSelectedSlot=m_selectedSlot; if(--m_selectedSlot<0) { m_selectedSlot=CGameSlotManager::NUM_GAME_SLOTS-1; } m_slotDrawOffset=-500; CSoundMediator::playSfx(CSoundMediator::SFX_FRONT_END__MOVE_CURSOR); } else if(pad&PAD_RIGHT) { m_lastSelectedSlot=m_selectedSlot; if(++m_selectedSlot>=CGameSlotManager::NUM_GAME_SLOTS) { m_selectedSlot=0; } m_slotDrawOffset=+500; CSoundMediator::playSfx(CSoundMediator::SFX_FRONT_END__MOVE_CURSOR); } else if(pad&PAD_CROSS) { CGameSlotManager::GameSlot *gameSlot; CGameSlotManager::setActiveSlot(m_selectedSlot); gameSlot=CGameSlotManager::getSlotData(); if(gameSlot->m_isInUse) { int chapter,level; gameSlot->getHighestLevelOpen(&chapter,&level); CMapScene::setLevelToStartOn(chapter,level); gameSlot->m_lives=CGameSlotManager::INITIAL_LIVES; gameSlot->m_continues=CGameSlotManager::INITIAL_CONTINUES; m_state=STATE_EXITING_TO_GAME; CFader::setFadingOut(); CSoundMediator::playSfx(CSoundMediator::SFX_FRONT_END__OK); } else { m_state=STATE_SLOT_CREATED; m_confirmFlag=CONFIRM_NONE; m_createdSlotGuiFrame->select(); gameSlot->m_isInUse=true; CSoundMediator::playSfx(CSoundMediator::SFX_FRONT_END__OK); } } else if(pad&PAD_CIRCLE) { CGameSlotManager::GameSlot *gameSlot; CGameSlotManager::setActiveSlot(m_selectedSlot); gameSlot=CGameSlotManager::getSlotData(); if(gameSlot->m_isInUse) { m_state=STATE_CONFIRM_ERASE; m_confirmFlag=CONFIRM_NONE; m_confirmEraseGuiFrame->select(); CSoundMediator::playSfx(CSoundMediator::SFX_FRONT_END__OK); } } else if(pad&PAD_TRIANGLE) { m_state=STATE_EXITING_TO_FRONT_END; CFader::setFadingOut(); CSoundMediator::playSfx(CSoundMediator::SFX_FRONT_END__OK); } m_emptyGuiFrame->think(_frames); } else if(m_state==STATE_SLOT_CREATED) { m_createdSlotGuiFrame->think(_frames); if(m_confirmFlag==CONFIRM_OK) { m_createdSlotGuiFrame->unselect(); m_state=STATE_SELECT; } } else if(m_state==STATE_CONFIRM_ERASE) { m_confirmEraseGuiFrame->think(_frames); if(m_confirmFlag==CONFIRM_YES) { CGameSlotManager::eraseGameSlot(m_selectedSlot); m_state=STATE_SELECT; m_confirmEraseGuiFrame->unselect(); } else if(m_confirmFlag==CONFIRM_NO) { m_state=STATE_SELECT; m_confirmEraseGuiFrame->unselect(); } } } else { // Slide the slot boxes about.. for(int i=0;i<_frames;i++) { int delta=m_slotDrawOffset/3; if(m_slotDrawOffset<0) { if(!delta)delta=-1; } else if(m_slotDrawOffset>0) { if(!delta)delta=+1; } else { break; } m_slotDrawOffset-=delta; } } } /* if(!m_shuttingDown) { if(/m_selectedSlot!=NO_SLOT_SELECTED|| m_escapeToTitles||/ { m_shuttingDown=true; CFader::setFadingOut(); } } */ } /*---------------------------------------------------------------------- Function: Purpose: Params: Returns: ---------------------------------------------------------------------- */ int CFrontEndStart::isReadyToExit() { return !CFader::isFading()&&(m_state==STATE_EXITING_TO_FRONT_END||m_state==STATE_EXITING_TO_GAME); } /*---------------------------------------------------------------------- Function: Purpose: Params: Returns: ---------------------------------------------------------------------- */ CFrontEndScene::FrontEndMode CFrontEndStart::getNextMode() { return m_state==STATE_EXITING_TO_GAME?CFrontEndScene::MODE__EXIT_TO_GAME:CFrontEndScene::MODE__MAIN_TITLES; } /*=========================================================================== end */
1
0.888589
1
0.888589
game-dev
MEDIA
0.756737
game-dev
0.924953
1
0.924953
PhoenixBladez/SpiritMod
6,670
Particles/ParticleHandler.cs
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using SpiritMod.Utilities; using System; using System.Collections.Generic; using System.Runtime.Serialization; using Terraria; using Terraria.ModLoader; namespace SpiritMod.Particles { public static class ParticleHandler { private static readonly int MaxParticlesAllowed = 500; private static Particle[] particles; private static int nextVacantIndex; private static int activeParticles; private static Dictionary<Type, int> particleTypes; private static Dictionary<int, Texture2D> particleTextures; private static List<Particle> particleInstances; private static List<Particle> batchedAlphaBlendParticles; private static List<Particle> batchedAdditiveBlendParticles; internal static void RegisterParticles() { particles = new Particle[MaxParticlesAllowed]; particleTypes = new Dictionary<Type, int>(); particleTextures = new Dictionary<int, Texture2D>(); particleInstances = new List<Particle>(); batchedAlphaBlendParticles = new List<Particle>(MaxParticlesAllowed); batchedAdditiveBlendParticles = new List<Particle>(MaxParticlesAllowed); Type baseParticleType = typeof(Particle); SpiritMod spiritMod = ModContent.GetInstance<SpiritMod>(); foreach (Type type in spiritMod.Code.GetTypes()) { if (type.IsSubclassOf(baseParticleType) && !type.IsAbstract && type != baseParticleType) { int assignedType = particleTypes.Count; particleTypes[type] = assignedType; string texturePath = type.Namespace.Replace('.', '/') + "/" + type.Name; particleTextures[assignedType] = ModContent.GetTexture(texturePath); particleInstances.Add((Particle)FormatterServices.GetUninitializedObject(type)); } } } internal static void Unload() { particles = null; particleTypes = null; particleTextures = null; particleInstances = null; batchedAlphaBlendParticles = null; batchedAdditiveBlendParticles = null; } /// <summary> /// Spawns the particle instance provided into the world (if the particle limit is not reached). /// </summary> public static void SpawnParticle(Particle particle) { if (activeParticles == MaxParticlesAllowed) return; particles[nextVacantIndex] = particle; particle.ID = nextVacantIndex; particle.Type = particleTypes[particle.GetType()]; if (nextVacantIndex + 1 < particles.Length && particles[nextVacantIndex + 1] == null) nextVacantIndex++; else for (int i = 0; i < particles.Length; i++) if (particles[i] == null) nextVacantIndex = i; activeParticles++; } public static void SpawnParticle(int type, Vector2 position, Vector2 velocity, Vector2 origin = default, float rotation = 0f, float scale = 1f) { Particle particle = new Particle(); // yes i know constructors exist. yes i'm doing this so you dont have to make constructors over and over. particle.Position = position; particle.Velocity = velocity; particle.Color = Color.White; particle.Origin = origin; particle.Rotation = rotation; particle.Scale = scale; particle.Type = type; SpawnParticle(particle); } public static void SpawnParticle(int type, Vector2 position, Vector2 velocity) { Particle particle = new Particle(); particle.Position = position; particle.Velocity = velocity; particle.Color = Color.White; particle.Origin = Vector2.Zero; particle.Rotation = 0f; particle.Scale = 1f; particle.Type = type; SpawnParticle(particle); } /// <summary> /// Deletes the particle at the given index. You typically do not have to use this; use Particle.Kill() instead. /// </summary> public static void DeleteParticleAtIndex(int index) { particles[index] = null; activeParticles--; nextVacantIndex = index; } /// <summary> /// Clears all the currently spawned particles. /// </summary> public static void ClearAllParticles() { for (int i = 0; i < particles.Length; i++) particles[i] = null; activeParticles = 0; nextVacantIndex = 0; } internal static void UpdateAllParticles() { foreach (Particle particle in particles) { if (particle == null) continue; particle.TimeActive++; particle.Position += particle.Velocity; particle.Update(); } } internal static void RunRandomSpawnAttempts() { foreach (Particle particle in particleInstances) if (Main.rand.NextFloat() < particle.SpawnChance) particle.OnSpawnAttempt(); } internal static void DrawAllParticles(SpriteBatch spriteBatch) { foreach (Particle particle in particles) { if (particle == null || particle is ScreenParticle && ModContent.GetInstance<SpiritClientConfig>().ForegroundParticles == false) continue; if (particle.UseAdditiveBlend) batchedAdditiveBlendParticles.Add(particle); else batchedAlphaBlendParticles.Add(particle); } spriteBatch.End(); if (batchedAlphaBlendParticles.Count > 0) { spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, null, null, Main.GameViewMatrix.ZoomMatrix); foreach (Particle particle in batchedAlphaBlendParticles) if (particle.UseCustomDraw) particle.CustomDraw(spriteBatch); else spriteBatch.Draw(particleTextures[particle.Type], particle.Position - Main.screenPosition, null, particle.Color, particle.Rotation, particle.Origin, particle.Scale * Main.GameViewMatrix.Zoom, SpriteEffects.None, 0f); spriteBatch.End(); } if(batchedAdditiveBlendParticles.Count > 0) { spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone, null, Main.GameViewMatrix.ZoomMatrix); foreach (Particle particle in batchedAdditiveBlendParticles) if (particle.UseCustomDraw) particle.CustomDraw(spriteBatch); else spriteBatch.Draw(particleTextures[particle.Type], particle.Position - Main.screenPosition, null, particle.Color, particle.Rotation, particle.Origin, particle.Scale * Main.GameViewMatrix.Zoom, SpriteEffects.None, 0f); spriteBatch.End(); } batchedAlphaBlendParticles.Clear(); batchedAdditiveBlendParticles.Clear(); spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); } /// <summary> /// Gets the texture of the given particle type. /// </summary> public static Texture2D GetTexture(int type) => particleTextures[type]; /// <summary> /// Returns the numeric type of the given particle. /// </summary> public static int ParticleType<T>() => particleTypes[typeof(T)]; } }
1
0.675672
1
0.675672
game-dev
MEDIA
0.865021
game-dev,graphics-rendering
0.954771
1
0.954771
justindujardin/angular-rpg
1,429
src/app/routes/combat/combat.types.ts
import { ElementRef } from '@angular/core'; import { Point } from '../../core'; import { NamedMouseElement } from '../../core/input'; import { GameEntityObject } from '../../scene/objects/game-entity-object'; /** * Describe a selectable menu item for a user input in combat. */ export interface ICombatMenuItem { select(): any; label: string; id: string; source?: GameEntityObject; } export interface ICombatDamageSummary { id: string; timeout: number; value: number; classes: { miss: boolean; heal: boolean; }; position: Point; } /** Description of a combat entity attack */ export interface CombatAttackSummary { damage: number; attacker: GameEntityObject; defender: GameEntityObject; } /** * Completion callback for a player action. */ export type IPlayerActionCallback = (action: IPlayerAction, error?: any) => void; /** * A Player action during combat */ export interface IPlayerAction { name: string; from: GameEntityObject | null; to: GameEntityObject | null; act(): Promise<boolean>; } /** * Attach an HTML element to the position of a game object. */ export interface UIAttachment { object: GameEntityObject; offset: Point; element: ElementRef; } /** The user clicked on the combat scene */ export interface CombatSceneClick { /** The mouse information */ mouse: NamedMouseElement; /** The scene objects under the mouse */ hits: GameEntityObject[]; }
1
0.768022
1
0.768022
game-dev
MEDIA
0.503742
game-dev
0.600741
1
0.600741
Source-SDK-Archives/source-sdk-2004
7,149
src_mod/public/tier1/utlstack.h
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// #ifndef UTLSTACK_H #define UTLSTACK_H #include <assert.h> #include <string.h> #include "utlmemory.h" //----------------------------------------------------------------------------- // The CUtlStack class: // A growable stack class which doubles in size by default. // It will always keep all elements consecutive in memory, and may move the // elements around in memory (via a realloc) when elements are pushed or // popped. Clients should therefore refer to the elements of the stack // by index (they should *never* maintain pointers to elements in the stack). //----------------------------------------------------------------------------- template< class T > class CUtlStack { public: // constructor, destructor CUtlStack( int growSize = 0, int initSize = 0 ); ~CUtlStack(); // element access T& operator[]( int i ); T const& operator[]( int i ) const; T& Element( int i ); T const& Element( int i ) const; // Gets the base address (can change when adding elements!) T* Base(); T const* Base() const; // Looks at the stack top T& Top(); T const& Top() const; // Size int Count() const; // Is element index valid? bool IsIdxValid( int i ) const; // Adds an element, uses default constructor int Push(); // Adds an element, uses copy constructor int Push( T const& src ); // Pops the stack void Pop(); void Pop( T& oldTop ); // Makes sure we have enough memory allocated to store a requested # of elements void EnsureCapacity( int num ); // Clears the stack, no deallocation void Clear(); // Memory deallocation void Purge(); private: // Grows the stack allocation void GrowStack(); // For easier access to the elements through the debugger void ResetDbgInfo(); CUtlMemory<T> m_Memory; int m_Size; // For easier access to the elements through the debugger T* m_pElements; }; //----------------------------------------------------------------------------- // For easier access to the elements through the debugger //----------------------------------------------------------------------------- template< class T > inline void CUtlStack<T>::ResetDbgInfo() { m_pElements = m_Memory.Base(); } //----------------------------------------------------------------------------- // constructor, destructor //----------------------------------------------------------------------------- template< class T > CUtlStack<T>::CUtlStack( int growSize, int initSize ) : m_Memory(growSize, initSize), m_Size(0) { ResetDbgInfo(); } template< class T > CUtlStack<T>::~CUtlStack() { Purge(); } //----------------------------------------------------------------------------- // element access //----------------------------------------------------------------------------- template< class T > inline T& CUtlStack<T>::operator[]( int i ) { assert( IsIdxValid(i) ); return m_Memory[i]; } template< class T > inline T const& CUtlStack<T>::operator[]( int i ) const { assert( IsIdxValid(i) ); return m_Memory[i]; } template< class T > inline T& CUtlStack<T>::Element( int i ) { assert( IsIdxValid(i) ); return m_Memory[i]; } template< class T > inline T const& CUtlStack<T>::Element( int i ) const { assert( IsIdxValid(i) ); return m_Memory[i]; } //----------------------------------------------------------------------------- // Gets the base address (can change when adding elements!) //----------------------------------------------------------------------------- template< class T > inline T* CUtlStack<T>::Base() { return m_Memory.Base(); } template< class T > inline T const* CUtlStack<T>::Base() const { return m_Memory.Base(); } //----------------------------------------------------------------------------- // Returns the top of the stack //----------------------------------------------------------------------------- template< class T > inline T& CUtlStack<T>::Top() { assert( m_Size > 0 ); return Element(m_Size-1); } template< class T > inline T const& CUtlStack<T>::Top() const { assert( m_Size > 0 ); return Element(m_Size-1); } //----------------------------------------------------------------------------- // Size //----------------------------------------------------------------------------- template< class T > inline int CUtlStack<T>::Count() const { return m_Size; } //----------------------------------------------------------------------------- // Is element index valid? //----------------------------------------------------------------------------- template< class T > inline bool CUtlStack<T>::IsIdxValid( int i ) const { return (i >= 0) && (i < m_Size); } //----------------------------------------------------------------------------- // Grows the stack //----------------------------------------------------------------------------- template< class T > void CUtlStack<T>::GrowStack() { if (m_Size >= m_Memory.NumAllocated()) m_Memory.Grow(); ++m_Size; ResetDbgInfo(); } //----------------------------------------------------------------------------- // Makes sure we have enough memory allocated to store a requested # of elements //----------------------------------------------------------------------------- template< class T > void CUtlStack<T>::EnsureCapacity( int num ) { m_Memory.EnsureCapacity(num); ResetDbgInfo(); } //----------------------------------------------------------------------------- // Adds an element, uses default constructor //----------------------------------------------------------------------------- template< class T > int CUtlStack<T>::Push() { GrowStack(); Construct( &Element(m_Size-1) ); return m_Size - 1; } //----------------------------------------------------------------------------- // Adds an element, uses copy constructor //----------------------------------------------------------------------------- template< class T > int CUtlStack<T>::Push( T const& src ) { GrowStack(); CopyConstruct( &Element(m_Size-1), src ); return m_Size - 1; } //----------------------------------------------------------------------------- // Pops the stack //----------------------------------------------------------------------------- template< class T > void CUtlStack<T>::Pop() { assert( m_Size > 0 ); Destruct( &Element(m_Size-1) ); --m_Size; } template< class T > void CUtlStack<T>::Pop( T& oldTop ) { assert( m_Size > 0 ); oldTop = Top(); Pop(); } //----------------------------------------------------------------------------- // Element removal //----------------------------------------------------------------------------- template< class T > void CUtlStack<T>::Clear() { for (int i = m_Size; --i >= 0; ) Destruct(&Element(i)); m_Size = 0; } //----------------------------------------------------------------------------- // Memory deallocation //----------------------------------------------------------------------------- template< class T > void CUtlStack<T>::Purge() { Clear(); m_Memory.Purge( ); ResetDbgInfo(); } #endif // UTLSTACK_H
1
0.821505
1
0.821505
game-dev
MEDIA
0.227598
game-dev
0.743814
1
0.743814
rashiph/DecompliedDotNetLibraries
3,965
System/System/CodeDom/CodeNamespaceImportCollection.cs
namespace System.CodeDom { using System; using System.Collections; using System.Reflection; using System.Runtime.InteropServices; [Serializable, ClassInterface(ClassInterfaceType.AutoDispatch), ComVisible(true)] public class CodeNamespaceImportCollection : IList, ICollection, IEnumerable { private ArrayList data = new ArrayList(); private Hashtable keys = new Hashtable(StringComparer.OrdinalIgnoreCase); public void Add(CodeNamespaceImport value) { if (!this.keys.ContainsKey(value.Namespace)) { this.keys[value.Namespace] = value; this.data.Add(value); } } public void AddRange(CodeNamespaceImport[] value) { if (value == null) { throw new ArgumentNullException("value"); } foreach (CodeNamespaceImport import in value) { this.Add(import); } } public void Clear() { this.data.Clear(); this.keys.Clear(); } public IEnumerator GetEnumerator() { return this.data.GetEnumerator(); } private void SyncKeys() { this.keys = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (CodeNamespaceImport import in this) { this.keys[import.Namespace] = import; } } void ICollection.CopyTo(Array array, int index) { this.data.CopyTo(array, index); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } int IList.Add(object value) { return this.data.Add((CodeNamespaceImport) value); } void IList.Clear() { this.Clear(); } bool IList.Contains(object value) { return this.data.Contains(value); } int IList.IndexOf(object value) { return this.data.IndexOf((CodeNamespaceImport) value); } void IList.Insert(int index, object value) { this.data.Insert(index, (CodeNamespaceImport) value); this.SyncKeys(); } void IList.Remove(object value) { this.data.Remove((CodeNamespaceImport) value); this.SyncKeys(); } void IList.RemoveAt(int index) { this.data.RemoveAt(index); this.SyncKeys(); } public int Count { get { return this.data.Count; } } public CodeNamespaceImport this[int index] { get { return (CodeNamespaceImport) this.data[index]; } set { this.data[index] = value; this.SyncKeys(); } } int ICollection.Count { get { return this.Count; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return null; } } bool IList.IsFixedSize { get { return false; } } bool IList.IsReadOnly { get { return false; } } object IList.this[int index] { get { return this[index]; } set { this[index] = (CodeNamespaceImport) value; this.SyncKeys(); } } } }
1
0.681295
1
0.681295
game-dev
MEDIA
0.186463
game-dev
0.849501
1
0.849501
vegapnk/Cumpilation
3,119
1.5/Source/Gathering/Patches/Patch_CasualSexHelper_FindNearbyBucketToMasturbate.cs
using HarmonyLib; using rjw; using rjw.Modules.Shared.Logs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Verse; namespace Cumpilation.Gathering { /// <summary> /// Changes the Position that (Player) Pawns want to Masturbate at. /// If there is a supported and free Fluid-Gatherer (Sink), a position next to it will be chosen. /// /// Extracted and Extended behaviour from Amevarashi Sexperience: /// https://gitgud.io/amevarashi/rjw-sexperience/-/blob/master/Source/RJWSexperience/Patches/RJW_Patch.cs#L123 /// </summary> [HarmonyPatch(typeof(CasualSex_Helper), nameof(CasualSex_Helper.FindSexLocation))] public static class Patch_CasualSexHelper_FindNearbyBucketToMasturbate { /// <summary> /// If masturbation and current map has a bucket, return location near the bucket /// </summary> /// <param name="__result">The place to stand near a bucket</param> /// <returns>Run original method</returns> public static bool Prefix(Pawn pawn, Pawn partner, ref IntVec3 __result) { if (partner != null && partner != pawn) return true; // Not masturbation if (pawn.Faction?.IsPlayer != true && !pawn.IsPrisonerOfColony) { return true; } ISexPartHediff genitalWithMostFluid = Genital_Helper.get_AllPartsHediffList(pawn) .Where(part => part is ISexPartHediff) .Cast<ISexPartHediff>() .Where(part => GatheringUtility.HasAnySupportedFluidGatheringDefs(part)) .OrderByDescending(f => f.GetPartComp().FluidAmount) .FirstOrFallback(); if (genitalWithMostFluid == null) return true; Building fluidSink = GatheringUtility.FindClosestFluidSink(pawn, genitalWithMostFluid.GetPartComp().Fluid); if (fluidSink == null) { ModLog.Debug($"Did not find a (supported) Fluid-Sink for {pawn}s Masturbation - Continuing with normal location-detection."); return true; } else { ModLog.Debug($"Found a fluid-sink {fluidSink}@{fluidSink.Position} for {pawn} to masturbate his {genitalWithMostFluid} into."); } IntVec3 cellCandidate = GenAdjFast.AdjacentCells8Way(fluidSink.Position) .Where(cell => cell.Standable(fluidSink.Map)) .OrderBy(cell => cell.DistanceTo(pawn.Position)) .FirstOrFallback(); if (cellCandidate != null) { __result = cellCandidate; ModLog.Debug($"Found good Sink {fluidSink} for {pawn}s masturbation --- setting location to {__result}"); return false; } else { ModLog.Debug($"Failed to find situable location near a sink at {fluidSink.Position} for {pawn}s masturbation"); return true; } } } }
1
0.870044
1
0.870044
game-dev
MEDIA
0.581086
game-dev
0.770339
1
0.770339
OtherMythos/ProceduralExplorationGame
1,603
native/core/src/MapGen/BaseClient/Steps/MergeSmallRegionsMapGenStep.cpp
#include "MergeSmallRegionsMapGenStep.h" #include "MapGen/ExplorationMapDataPrerequisites.h" #include "MapGen/BaseClient/MapGenBaseClientPrerequisites.h" #include <cassert> #include <cmath> #include <set> namespace ProceduralExplorationGameCore{ MergeSmallRegionsMapGenStep::MergeSmallRegionsMapGenStep() : MapGenStep("Merge Small Regions"){ } MergeSmallRegionsMapGenStep::~MergeSmallRegionsMapGenStep(){ } bool MergeSmallRegionsMapGenStep::processStep(const ExplorationMapInputData* input, ExplorationMapData* mapData, ExplorationMapGenWorkspace* workspace){ std::vector<RegionData>& regionData = (*mapData->ptr<std::vector<RegionData>>("regionData")); for(RegionData& d : regionData){ if(d.total >= 200) continue; //Don't attempt to merge small main regions, so the session can guarantee having the correct number. if(d.meta & static_cast<AV::uint8>(RegionMeta::MAIN_REGION)){ continue; } //Go through the edges and check the neighbours for a region std::set<RegionId> foundRegions; findNeighboursForRegion(mapData, d, foundRegions); for(RegionId r : foundRegions){ //TODO do I need this? if(r == 0x0 || r == REGION_ID_WATER) continue; RegionData& sd = regionData[r]; if(d.id == sd.id) continue; mergeRegionData(mapData, d, sd); //Just take the first value for now. break; } } return true; } }
1
0.755934
1
0.755934
game-dev
MEDIA
0.43156
game-dev
0.949812
1
0.949812
ACreTeam/ac-decomp
20,569
src/AUS/game/m_collision_bg_column.c_inc
// GAFU01 reworks how fg collisions are processed static int mCoBG_it_is_hole(mActor_name_t item, ACTOR* actorx) { if (ITEM_IS_HOLE(item) || item == HOLE_SHINE || item == RSV_HOLE) { return TRUE; } return FALSE; } static int mCoBG_it_is_tree_level2(mActor_name_t item, ACTOR* actorx) { return IS_ITEM_SMALL_TREE(item) != FALSE; } static int mCoBG_it_is_tree_level3(mActor_name_t item, ACTOR* actorx) { return IS_ITEM_MED_TREE(item) != FALSE; } static int mCoBG_it_is_tree_level4(mActor_name_t item, ACTOR* actorx) { return IS_ITEM_LARGE_TREE(item) != FALSE; } static int mCoBG_it_is_tree_level5(mActor_name_t item, ACTOR* actorx) { return IS_ITEM_FULL_TREE(item) != FALSE; } static int mCoBG_it_is_stump0(mActor_name_t item, ACTOR* actorx) { // OK, this is just bad. There was no need to wastefully use the // 'IS_ITEM_TREE_STUMP' macro only to filter out the size 0 stumps. if (IS_ITEM_TREE_STUMP(item) && (item == TREE_STUMP001 || item == TREE_PALM_STUMP001 || item == CEDAR_TREE_STUMP001 || item == GOLD_TREE_STUMP001)) { return TRUE; } return FALSE; } static int mCoBG_it_is_stump1(mActor_name_t item, ACTOR* actorx) { // This just keeps getting worse haha if (IS_ITEM_TREE_STUMP(item) && !mCoBG_it_is_stump0(item, actorx)) { return TRUE; } return FALSE; } static int mCoBG_it_is_stone(mActor_name_t item, ACTOR* actorx) { return (IS_ITEM_STONE(item) || IS_ITEM_STONE_TC(item)) != FALSE; } static int mCoBG_it_is_post(mActor_name_t item, ACTOR* actorx) { if (item == DUMMY_MAILBOX0 || item == DUMMY_MAILBOX1 || item == DUMMY_MAILBOX2 || item == DUMMY_MAILBOX3) { return TRUE; } return FALSE; } static int mCoBG_it_is_sign(mActor_name_t item, ACTOR* actorx) { if (item == DUMMY_RESERVE || ITEM_IS_SIGNBOARD(item)) { return TRUE; } return FALSE; } static int mCoBG_it_is_sign_dummy(mActor_name_t item, ACTOR* actorx) { return item == RSV_SIGNBOARD; } static int mCoBG_it_is_flag(mActor_name_t item, ACTOR* actorx) { if (item == DUMMY_KOINOBORI || item == DUMMY_FLAG) { return TRUE; } return FALSE; } typedef int (*mCoBG_COL_ITEM_CHK_PROC)(mActor_name_t item, ACTOR* actorx); typedef struct { mCoBG_COL_ITEM_CHK_PROC chk_proc; f32 radius; f32 height; int chk_old_on_ground; } mCoBG_fg_collision_data_c; static mCoBG_fg_collision_data_c mCoBG_fg_collision_data[] = { // clang-format off { mCoBG_it_is_hole, 19.0f, 0.0f, TRUE }, { mCoBG_it_is_tree_level2, 19.0f, 30.0f, FALSE }, { mCoBG_it_is_tree_level3, 19.0f, 40.0f, FALSE }, { mCoBG_it_is_tree_level4, 19.0f, 60.0f, FALSE }, { mCoBG_it_is_tree_level5, 19.0f, 80.0f, FALSE }, { mCoBG_it_is_stump0, 10.0f, 30.0f, FALSE }, { mCoBG_it_is_stump1, 18.0f, 30.0f, FALSE }, { mCoBG_it_is_stone, 19.0f, 31.5f, FALSE }, { mCoBG_it_is_post, 15.0f, 50.0f, FALSE }, { mCoBG_it_is_sign, 19.0f, 45.0f, FALSE }, { mCoBG_it_is_sign_dummy, 10.0f, 45.0f, FALSE }, { mCoBG_it_is_flag, 19.0f, 160.0f, FALSE }, // clang-format on }; static mCoBG_fg_collision_data_c* mCoBG_get_fg_collision_data_p(ACTOR* actorx, mActor_name_t item) { u32 i; mCoBG_fg_collision_data_c* col_p = mCoBG_fg_collision_data; for (i = 0; i < ARRAY_COUNT(mCoBG_fg_collision_data); i++) { if (col_p->chk_proc(item, actorx) == TRUE) { return col_p; } col_p++; } return NULL; } typedef struct { xyz_t pos; int in_use; f32 start_radius; f32 end_radius; f32 now_radius; s16 start_timer; s16 now_timer; } mCoBG_regist_circle_info_c; static int mCoBG_regist_decal_circle_count = 0; static mCoBG_regist_circle_info_c mCoBG_regist_circle_info[3]; static mCoBG_column_c mCoBG_decal_circle[3]; static f32 mCoBG_CalcAdjust(s16 now_a, s16 start_a, s16 end_a, f32 start_val, f32 end_val) { if (start_a == end_a) { return start_val; } if (now_a <= start_a) { return start_val; } if (now_a >= end_a) { return end_val; } { f32 d_a = now_a - start_a; f32 n_a = end_a - start_a; f32 n_val = end_val - start_val; return start_val + d_a * (n_val / n_a); } } static void mCoBG_CalcTimerDecalCircleOne(mCoBG_regist_circle_info_c* regist, mCoBG_column_c* col_circle) { if (regist->in_use == TRUE) { if (regist->start_timer != -100) { regist->now_radius = mCoBG_CalcAdjust(regist->start_timer - regist->now_timer, 0, regist->start_timer, regist->start_radius, regist->end_radius); col_circle->pos = regist->pos; col_circle->height = regist->pos.y; col_circle->radius = regist->now_radius; col_circle->atr_wall = TRUE; col_circle->ux = (int)(col_circle->pos.x / mFI_UT_WORLDSIZE_X_F); col_circle->uz = (int)(col_circle->pos.z / mFI_UT_WORLDSIZE_Z_F); regist->now_timer--; if (regist->now_timer < 0) { regist->in_use = FALSE; mCoBG_regist_decal_circle_count--; } } } } extern void mCoBG_CalcTimerDecalCircle(void) { int i; mCoBG_regist_circle_info_c* regist = mCoBG_regist_circle_info; mCoBG_column_c* col_circle = mCoBG_decal_circle; if (mCoBG_regist_decal_circle_count > 0) { for (i = 0; i < 3; i++) { mCoBG_CalcTimerDecalCircleOne(regist, col_circle); regist++; col_circle++; } } } extern int mCoBG_RegistDecalCircle(const xyz_t* pos, f32 start_radius, f32 end_radius, s16 timer) { int i; mCoBG_regist_circle_info_c* regist = mCoBG_regist_circle_info; mCoBG_column_c* col_circle = mCoBG_decal_circle; if (mCoBG_regist_decal_circle_count < 3) { for (i = 0; i < 3; i++) { if (regist->in_use == FALSE) { // @BUG - this will clobber data below mCoBG_regist_circle_info??? // because we don't break/return after finding a free // circle and we clear the WHOLE array, we can clear into // mCoBG_decal_circle's data. #ifndef BUGFIXES bzero(regist, sizeof(mCoBG_regist_circle_info)); #else bzero(regist, sizeof(mCoBG_regist_circle_info_c)); #endif bzero(col_circle, sizeof(mCoBG_column_c)); regist->in_use = TRUE; regist->pos = *pos; regist->start_radius = start_radius; regist->end_radius = end_radius; regist->now_radius = start_radius; regist->start_timer = timer; regist->now_timer = timer; mCoBG_CalcTimerDecalCircleOne(regist, col_circle); mCoBG_regist_decal_circle_count++; // @BUG - shouldn't this exit immediately? // As it stands, all free 'decal circle' collision columns // will be utilized. #ifdef BUGFIXES return i; #endif } regist++; col_circle++; } } return -1; } extern void mCoBG_InitDecalCircle(void) { // @BUG - they incorrectly clear 3x the memory necessary. // I'm guessing that they did 3 * sizeof(array) rather than // 3 * sizeof(struct). #ifndef BUGFIXES bzero(mCoBG_regist_circle_info, 3 * sizeof(mCoBG_regist_circle_info)); #else bzero(mCoBG_regist_circle_info, sizeof(mCoBG_regist_circle_info_c)); #endif bzero(mCoBG_decal_circle, sizeof(mCoBG_decal_circle)); mCoBG_regist_decal_circle_count = 0; } // @unused, @fabricated extern void mCoBG_CrossOffDecalCircle(int idx) { if (idx >= 0 && idx < 3) { bzero(&mCoBG_regist_circle_info[idx], sizeof(mCoBG_regist_circle_info_c)); bzero(&mCoBG_decal_circle[idx], sizeof(mCoBG_decal_circle)); mCoBG_regist_decal_circle_count--; } } // GAFU01 passes in the actor and uses data driven approach // to process static int mCoBG_MakeOneColumnCollisionData(ACTOR* actorx, mCoBG_column_c* col, mCoBG_UnitInfo_c* ut_info, int old_on_ground, mCoBG_COLUMN_CHECK_ITEM_TYPE_PROC check_proc, int ux, int uz) { if ((check_proc != NULL && (*check_proc)(ut_info->item) == FALSE) || check_proc == NULL) { mCoBG_fg_collision_data_c* col_data_p; if (ut_info->ut_x == ux && ut_info->ut_z == uz) { return FALSE; } col_data_p = mCoBG_get_fg_collision_data_p(actorx, ut_info->item); if (col_data_p != NULL) { if (col_data_p->chk_old_on_ground == TRUE && old_on_ground != TRUE) { return FALSE; } col->pos.x = ut_info->ut_x * mFI_UT_WORLDSIZE_X_F + mFI_UT_WORLDSIZE_HALF_X_F; col->pos.z = ut_info->ut_z * mFI_UT_WORLDSIZE_Z_F + mFI_UT_WORLDSIZE_HALF_Z_F; col->pos.y = 0.0f; col->ux = ut_info->ut_x; col->uz = ut_info->ut_z; col->pos.y = mCoBG_GetBgY_OnlyCenter_FromWpos2(col->pos, 0.0f); col->height = col->pos.y + col_data_p->height; col->radius = col_data_p->radius; col->atr_wall = col_data_p->chk_old_on_ground; return TRUE; } } return FALSE; } // GAFU01 passes in the actor static void mCoBG_MakeColumnCollisionData(ACTOR* actorx, mCoBG_column_c* col, int* col_count_p, mCoBG_UnitInfo_c* ut_info, int count, int old_on_ground, mCoBG_COLUMN_CHECK_ITEM_TYPE_PROC check_item_proc, int ux, int uz) { int count_sq = SQ(count); int i; *col_count_p = 0; for (i = 0; i < count_sq; i++) { if (*col_count_p < 16) { // GAFU01 checks the collision exists instead of just processing it always if (mCoBG_MakeOneColumnCollisionData(actorx, col, ut_info, old_on_ground, check_item_proc, ux, uz)) { col++; (*col_count_p)++; } } ut_info++; } } static void mCoBG_ColumnCheck_NormalWall(xyz_t* rev, mCoBG_ActorInf_c* actor_info, const xyz_t* pos, const xyz_t* old_pos, mCoBG_column_c* col, s16 attr_wall) { f32 ground_dist = actor_info->ground_dist; f32 now_y = ground_dist + pos->y; if (mCoBG_JudgePointInCircle_Xyz(old_pos, &col->pos, col->radius) == FALSE && (col->height >= (now_y + 3.0f))) { f32 dx = pos->x - col->pos.x; f32 dz = pos->z - col->pos.z; f32 dist = sqrtf(SQ(dx) + SQ(dz)); f32 check_dist = actor_info->range + col->radius; if (dist < check_dist) { xyz_t rev_vec; f32 rev_dist = check_dist - dist; xyz_t rev_unit_vec; mCoBG_WallHeight_c height; s16 angle = atans_table(dz, dx); f32 div; rev_vec.x = pos->x - col->pos.x; rev_vec.y = 0.0f; rev_vec.z = pos->z - col->pos.z; if (F32_IS_ZERO(dist)) { div = 1.0f; } else { div = 1.0f / dist; } rev_unit_vec.x = rev_vec.x * div; rev_unit_vec.y = 0.0f; rev_unit_vec.z = rev_vec.z * div; rev->x = rev_unit_vec.x * rev_dist; rev->y = rev_unit_vec.y * rev_dist; rev->z = rev_unit_vec.z * rev_dist; height.top = col->height; height.bot = col->pos.y; mCoBG_RegistCollisionWallInfo(actor_info, actor_info->wall_info, &height, angle, FALSE); } else { f32 diff = dist - check_dist; if (diff > 0.0f && diff < 2.7f) { mCoBG_WallHeight_c height; s16 angle = atans_table(dz, dx); height.top = col->height; height.bot = col->pos.y; mCoBG_RegistCollisionWallInfo(actor_info, actor_info->wall_info, &height, angle, FALSE); } } } } static void mCoBG_ColumnCheckOldOnGround_AttrWall(xyz_t* rev, mCoBG_ActorInf_c* actor_info, const xyz_t* pos, const xyz_t* old_pos, mCoBG_column_c* col) { if (mCoBG_JudgePointInCircle_Xyz(old_pos, &col->pos, col->radius) == FALSE) { f32 dx = pos->x - col->pos.x; f32 dz = pos->z - col->pos.z; f32 dist = sqrtf(SQ(dx) + SQ(dz)); f32 check_dist = actor_info->range + col->radius; if (dist < check_dist) { xyz_t rev_vec; f32 rev_dist = check_dist - dist; xyz_t rev_unit_vec; s16 angle = atans_table(dz, dx); f32 div; rev_vec.x = pos->x - col->pos.x; rev_vec.y = 0.0f; rev_vec.z = pos->z - col->pos.z; if (F32_IS_ZERO(dist)) { div = 1.0f; } else { div = 1.0f / dist; } rev_unit_vec.x = rev_vec.x * div; rev_unit_vec.y = 0.0f; rev_unit_vec.z = rev_vec.z * div; rev->x = rev_unit_vec.x * rev_dist; rev->y = rev_unit_vec.y * rev_dist; rev->z = rev_unit_vec.z * rev_dist; mCoBG_RegistCollisionWallInfo(actor_info, actor_info->wall_info, NULL, angle, TRUE); } else { f32 diff = dist - check_dist; if (diff > 0.0f && diff < 2.7f) { s16 angle = atans_table(dz, dx); mCoBG_RegistCollisionWallInfo(actor_info, actor_info->wall_info, NULL, angle, TRUE); } } } } static void mCoBG_ColumnCheckNotOldOnGround_AttrWall(xyz_t* rev, mCoBG_ActorInf_c* actor_info, const xyz_t* pos, const xyz_t* old_pos, mCoBG_column_c* col) { // nothing } typedef void (*mCoBG_ATR_COLUMN_SUB_PROC)(xyz_t* rev, mCoBG_ActorInf_c* actor_info, const xyz_t* pos, const xyz_t* old_pos, mCoBG_column_c* col); static void mCoBG_ColumnCheck_AttrWall(xyz_t* rev, mCoBG_ActorInf_c* actor_info, const xyz_t* pos, const xyz_t* old_pos, mCoBG_column_c* col, s16 attr_wall) { if (attr_wall != FALSE) { static mCoBG_ATR_COLUMN_SUB_PROC atr_column_sub_proc_table[] = { &mCoBG_ColumnCheckNotOldOnGround_AttrWall, &mCoBG_ColumnCheckOldOnGround_AttrWall }; (*atr_column_sub_proc_table[actor_info->old_on_ground])(rev, actor_info, pos, old_pos, col); } } typedef void (*mCoBG_WALL_CHECK_PROC)(xyz_t* rev, mCoBG_ActorInf_c* actor_info, const xyz_t* pos, const xyz_t* old_pos, mCoBG_column_c* col, s16 attr_wall); static void mCoBG_ColumnWallCheck(xyz_t* rev, mCoBG_ActorInf_c* actor_info, const xyz_t* pos, mCoBG_column_c* col, int col_count, s16 attr_wall) { static mCoBG_WALL_CHECK_PROC column_wall_check_func[] = { &mCoBG_ColumnCheck_NormalWall, &mCoBG_ColumnCheck_AttrWall }; static xyz_t reverse0 = { 0.0f, 0.0f, 0.0f }; *rev = reverse0; if (col_count != 0) { int i; for (i = 0; i < col_count; i++) { xyz_t reverse = { 0.0f, 0.0f, 0.0f }; xyz_t tmp_pos; tmp_pos.x = pos->x + rev->x; tmp_pos.y = pos->y + rev->y; tmp_pos.z = pos->z + rev->z; (*column_wall_check_func[col->atr_wall])(&reverse, actor_info, &tmp_pos, &actor_info->old_center_pos, col, attr_wall); rev->x += reverse.x; rev->z += reverse.z; rev->y = 0.0f; col++; } } } static f32 mCoBG_GetBGHeight_Column(const xyz_t* pos, mCoBG_UnitInfo_c* ut_info) { mCoBG_column_c col; if (mCoBG_MakeOneColumnCollisionData(NULL, &col, ut_info, FALSE, NULL, -1, -1) && mCoBG_JudgePointInCircle_Xyz(pos, &col.pos, col.radius)) { return col.height; } return 0.0f; } static int mCoBG_LineWallCheck_Column(xyz_t* rev, mCoBG_column_c* col, int col_count, const xyz_t* start_pos, const xyz_t* end_pos) { int i; xyz_t vec_end_start; xyz_t tmp_end; static xyz_t reverse0 = { 0.0f, 0.0f, 0.0f }; xyz_t reverse = reverse0; for (i = 0; i < col_count; i++) { f32 vec_end_start_len_xz; tmp_end.x = end_pos->x + reverse.x; tmp_end.y = end_pos->y + reverse.y; tmp_end.z = end_pos->z + reverse.z; reverse = reverse0; vec_end_start.x = start_pos->x - tmp_end.x; vec_end_start.y = start_pos->y - tmp_end.y; vec_end_start.z = start_pos->z - tmp_end.z; vec_end_start_len_xz = sqrtf(SQ(vec_end_start.x) + SQ(vec_end_start.z)); if (!F32_IS_ZERO(vec_end_start_len_xz)) { xyz_t cross0; xyz_t cross1; if (mCoBG_JudgePointInCircle_Xyz(start_pos, &col->pos, col->radius) == FALSE && mCoBG_GetCrossCircleAndLine2DvectorPlaneXZ_Xyz(&cross0, &cross1, start_pos, &vec_end_start, &col->pos, col->radius)) { f32 rev_dist_xz; xyz_t reverse_vec; xyz_t delta_cross0_xz; xyz_t delta_cross1_xz; f32 dist_sq_cross0_xz; f32 dist_sq_cross1_xz; delta_cross0_xz.x = cross0.x - start_pos->x; delta_cross0_xz.z = cross0.z - start_pos->z; delta_cross1_xz.x = cross1.x - start_pos->x; delta_cross1_xz.z = cross1.z - start_pos->z; dist_sq_cross0_xz = SQ(delta_cross0_xz.x) + SQ(delta_cross0_xz.z); dist_sq_cross1_xz = SQ(delta_cross1_xz.x) + SQ(delta_cross1_xz.z); if (dist_sq_cross0_xz < dist_sq_cross1_xz) { if (((cross0.x >= start_pos->x && cross0.x <= tmp_end.x) || (cross0.x >= tmp_end.x && cross0.x <= start_pos->x)) && ((cross0.z >= start_pos->z && cross0.z <= tmp_end.z) || (cross0.z >= tmp_end.z && cross0.z <= start_pos->z)) ) { f32 mult; rev_dist_xz = vec_end_start_len_xz - sqrtf(dist_sq_cross0_xz); mult = rev_dist_xz / vec_end_start_len_xz; reverse_vec.x = vec_end_start.x * mult; reverse_vec.y = vec_end_start.y * mult; reverse_vec.z = vec_end_start.z * mult; if ((end_pos->y + reverse_vec.y) <= col->height) { *rev = reverse_vec; return TRUE; } } } else { if (((cross1.x >= start_pos->x && cross1.x <= tmp_end.x) || (cross1.x >= tmp_end.x && cross1.x <= start_pos->x)) && ((cross1.z >= start_pos->z && cross1.z <= tmp_end.z) || (cross1.z >= tmp_end.z && cross1.z <= start_pos->z)) ) { f32 mult; rev_dist_xz = vec_end_start_len_xz - sqrtf(dist_sq_cross1_xz); mult = rev_dist_xz / vec_end_start_len_xz; reverse_vec.x = vec_end_start.x * mult; reverse_vec.y = vec_end_start.y * mult; reverse_vec.z = vec_end_start.z * mult; if ((end_pos->y + reverse_vec.y) <= col->height) { *rev = reverse_vec; return TRUE; } } } } col++; } } return FALSE; } static int mCoBG_LineGroundCheck_Column(xyz_t* rev, mCoBG_column_c* col, int col_count, const xyz_t* start_pos, const xyz_t* end_pos) { int i; static xyz_t reverse0; // @BUG - isn't this supposed to be initialized with data? xyz_t reverse; xyz_t tmp_end; xyz_t vec_end_start; reverse = reverse0; for (i = 0; i < col_count; i++) { if (start_pos->y > col->height && end_pos->y < col->height) { f32 vec_y; tmp_end.x = end_pos->x + reverse.x; tmp_end.y = end_pos->y + reverse.y; tmp_end.z = end_pos->z + reverse.z; reverse = reverse0; vec_y = col->height - tmp_end.y; vec_end_start.x = start_pos->x - tmp_end.x; vec_end_start.y = start_pos->y - tmp_end.y; vec_end_start.z = start_pos->z - tmp_end.z; if (!F32_IS_ZERO(vec_end_start.y)) { f32 mult = vec_y / vec_end_start.y; reverse.x = vec_end_start.x * mult; reverse.y = vec_end_start.y * mult; reverse.z = vec_end_start.z * mult; *rev = reverse; return TRUE; } return FALSE; } col++; } return FALSE; }
1
0.862504
1
0.862504
game-dev
MEDIA
0.823345
game-dev
0.971983
1
0.971983
EphemeralSpace/ephemeral-space
25,294
Content.Server/Antag/AntagSelectionSystem.cs
using System.Linq; using Content.Server.Administration.Managers; using Content.Server.Antag.Components; using Content.Server.Chat.Managers; using Content.Server.GameTicking; using Content.Server.GameTicking.Events; using Content.Server.GameTicking.Rules; using Content.Server.Ghost.Roles; using Content.Server.Ghost.Roles.Components; using Content.Server.Mind; using Content.Server.Objectives; using Content.Server.Players.PlayTimeTracking; using Content.Server.Preferences.Managers; using Content.Server.Roles; using Content.Server.Roles.Jobs; using Content.Server.Shuttles.Components; using Content.Shared.Administration.Logs; using Content.Shared.Antag; using Content.Shared.Clothing; using Content.Shared.Database; using Content.Shared.GameTicking; using Content.Shared.GameTicking.Components; using Content.Shared.Ghost; using Content.Shared.Humanoid; using Content.Shared.Mind; using Content.Shared.Players; using Content.Shared.Roles; using Content.Shared.Whitelist; using Robust.Server.Audio; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Enums; using Robust.Shared.Map; using Robust.Shared.Player; using Robust.Shared.Prototypes; using Robust.Shared.Random; using Robust.Shared.Utility; // ES START using Content.Shared._ES.Lobby.Components; // ES END namespace Content.Server.Antag; public sealed partial class AntagSelectionSystem : GameRuleSystem<AntagSelectionComponent> { [Dependency] private readonly AudioSystem _audio = default!; [Dependency] private readonly IBanManager _ban = default!; [Dependency] private readonly IChatManager _chat = default!; [Dependency] private readonly GhostRoleSystem _ghostRole = default!; [Dependency] private readonly JobSystem _jobs = default!; [Dependency] private readonly LoadoutSystem _loadout = default!; [Dependency] private readonly MindSystem _mind = default!; [Dependency] private readonly IPlayerManager _playerManager = default!; [Dependency] private readonly PlayTimeTrackingSystem _playTime = default!; [Dependency] private readonly IServerPreferencesManager _pref = default!; [Dependency] private readonly RoleSystem _role = default!; [Dependency] private readonly TransformSystem _transform = default!; [Dependency] private readonly EntityWhitelistSystem _whitelist = default!; [Dependency] private readonly ISharedAdminLogManager _adminLogger = default!; // arbitrary random number to give late joining some mild interest. public const float LateJoinRandomChance = 0.5f; /// <inheritdoc/> public override void Initialize() { base.Initialize(); Log.Level = LogLevel.Debug; SubscribeLocalEvent<GhostRoleAntagSpawnerComponent, TakeGhostRoleEvent>(OnTakeGhostRole); SubscribeLocalEvent<AntagSelectionComponent, ObjectivesTextGetInfoEvent>(OnObjectivesTextGetInfo); SubscribeLocalEvent<NoJobsAvailableSpawningEvent>(OnJobNotAssigned); SubscribeLocalEvent<RulePlayerSpawningEvent>(OnPlayerSpawning); SubscribeLocalEvent<RulePlayerJobsAssignedEvent>(OnJobsAssigned); SubscribeLocalEvent<PlayerSpawnCompleteEvent>(OnSpawnComplete); } private void OnTakeGhostRole(Entity<GhostRoleAntagSpawnerComponent> ent, ref TakeGhostRoleEvent args) { if (args.TookRole) return; if (ent.Comp.Rule is not { } rule || ent.Comp.Definition is not { } def) return; if (!Exists(rule) || !TryComp<AntagSelectionComponent>(rule, out var select)) return; MakeAntag((rule, select), args.Player, def, ignoreSpawner: true); args.TookRole = true; _ghostRole.UnregisterGhostRole((ent, Comp<GhostRoleComponent>(ent))); } private void OnPlayerSpawning(RulePlayerSpawningEvent args) { var pool = args.PlayerPool; var query = QueryActiveRules(); while (query.MoveNext(out var uid, out _, out var comp, out _)) { if (comp.SelectionTime != AntagSelectionTime.PrePlayerSpawn && comp.SelectionTime != AntagSelectionTime.IntraPlayerSpawn) continue; if (comp.AssignmentComplete) continue; ChooseAntags((uid, comp), pool); // We choose the antags here... if (comp.SelectionTime == AntagSelectionTime.PrePlayerSpawn) { AssignPreSelectedSessions((uid, comp)); // ...But only assign them if PrePlayerSpawn foreach (var session in comp.AssignedSessions) { args.PlayerPool.Remove(session); GameTicker.PlayerJoinGame(session); } } } // If IntraPlayerSpawn is selected, delayed rules should choose at this point too. var queryDelayed = QueryDelayedRules(); while (queryDelayed.MoveNext(out var uid, out _, out var comp, out _)) { if (comp.SelectionTime != AntagSelectionTime.IntraPlayerSpawn) continue; ChooseAntags((uid, comp), pool); } } private void OnJobsAssigned(RulePlayerJobsAssignedEvent args) { var query = QueryActiveRules(); while (query.MoveNext(out var uid, out _, out var comp, out _)) { if (comp.SelectionTime != AntagSelectionTime.PostPlayerSpawn && comp.SelectionTime != AntagSelectionTime.IntraPlayerSpawn) continue; ChooseAntags((uid, comp), args.Players); AssignPreSelectedSessions((uid, comp)); } } private void OnJobNotAssigned(NoJobsAvailableSpawningEvent args) { // If someone fails to spawn in due to there being no jobs, they should be removed from any preselected antags. // We only care about delayed rules, since if they're active the player should have already been removed via MakeAntag. var query = QueryDelayedRules(); while (query.MoveNext(out var uid, out _, out var comp, out _)) { if (comp.SelectionTime != AntagSelectionTime.IntraPlayerSpawn) continue; if (!comp.RemoveUponFailedSpawn) continue; foreach (var def in comp.Definitions) { if (!comp.PreSelectedSessions.TryGetValue(def, out var session)) break; session.Remove(args.Player); } } } private void OnSpawnComplete(PlayerSpawnCompleteEvent args) { if (!args.LateJoin) return; // TODO: this really doesn't handle multiple latejoin definitions well // eventually this should probably store the players per definition with some kind of unique identifier. // something to figure out later. var query = QueryAllRules(); var rules = new List<(EntityUid, AntagSelectionComponent)>(); while (query.MoveNext(out var uid, out var antag, out _)) { if (HasComp<ActiveGameRuleComponent>(uid)) rules.Add((uid, antag)); } RobustRandom.Shuffle(rules); foreach (var (uid, antag) in rules) { if (!RobustRandom.Prob(LateJoinRandomChance)) continue; if (!antag.Definitions.Any(p => p.LateJoinAdditional)) continue; DebugTools.AssertNotEqual(antag.SelectionTime, AntagSelectionTime.PrePlayerSpawn); // do not count players in the lobby for the antag ratio var players = _playerManager.NetworkedSessions.Count(x => x.AttachedEntity != null); if (!TryGetNextAvailableDefinition((uid, antag), out var def, players)) continue; if (TryMakeAntag((uid, antag), args.Player, def.Value)) break; } } protected override void Added(EntityUid uid, AntagSelectionComponent component, GameRuleComponent gameRule, GameRuleAddedEvent args) { base.Added(uid, component, gameRule, args); for (var i = 0; i < component.Definitions.Count; i++) { var def = component.Definitions[i]; if (def.MinRange != null) { def.Min = def.MinRange.Value.Next(RobustRandom); } if (def.MaxRange != null) { def.Max = def.MaxRange.Value.Next(RobustRandom); } } } protected override void Started(EntityUid uid, AntagSelectionComponent component, GameRuleComponent gameRule, GameRuleStartedEvent args) { base.Started(uid, component, gameRule, args); // If the round has not yet started, we defer antag selection until roundstart if (GameTicker.RunLevel != GameRunLevel.InRound) return; if (component.AssignmentComplete) return; var players = _playerManager.Sessions .Where(x => GameTicker.PlayerGameStatuses.TryGetValue(x.UserId, out var status) && status == PlayerGameStatus.JoinedGame) .ToList(); ChooseAntags((uid, component), players, midround: true); AssignPreSelectedSessions((uid, component)); } /// <summary> /// Chooses antagonists from the given selection of players /// </summary> /// <param name="ent">The antagonist rule entity</param> /// <param name="pool">The players to choose from</param> /// <param name="midround">Disable picking players for pre-spawn antags in the middle of a round</param> public void ChooseAntags(Entity<AntagSelectionComponent> ent, IList<ICommonSession> pool, bool midround = false) { foreach (var def in ent.Comp.Definitions) { ChooseAntags(ent, pool, def, midround: midround); } ent.Comp.PreSelectionsComplete = true; } /// <summary> /// Chooses antagonists from the given selection of players for the given antag definition. /// </summary> /// <param name="ent">The antagonist rule entity</param> /// <param name="pool">The players to choose from</param> /// <param name="def">The antagonist selection parameters and criteria</param> /// <param name="midround">Disable picking players for pre-spawn antags in the middle of a round</param> public void ChooseAntags(Entity<AntagSelectionComponent> ent, IList<ICommonSession> pool, AntagSelectionDefinition def, bool midround = false) { var playerPool = GetPlayerPool(ent, pool, def); var existingAntagCount = ent.Comp.PreSelectedSessions.TryGetValue(def, out var existingAntags) ? existingAntags.Count : 0; var count = GetTargetAntagCount(ent, GetTotalPlayerCount(pool), def) - existingAntagCount; // if there is both a spawner and players getting picked, let it fall back to a spawner. var noSpawner = def.SpawnerPrototype == null; var picking = def.PickPlayer; if (midround && ent.Comp.SelectionTime == AntagSelectionTime.PrePlayerSpawn) { // prevent antag selection from happening if the round is on-going, requiring a spawner if used midround. // this is so rules like nukies, if added by an admin midround, dont make random living people nukies Log.Info($"Antags for rule {ent:?} get picked pre-spawn so only spawners will be made."); DebugTools.Assert(def.SpawnerPrototype != null, $"Rule {ent:?} had no spawner for pre-spawn rule added mid-round!"); picking = false; } for (var i = 0; i < count; i++) { var session = (ICommonSession?)null; if (picking) { if (!playerPool.TryPickAndTake(RobustRandom, out session) && noSpawner) { Log.Warning($"Couldn't pick a player for {ToPrettyString(ent):rule}, no longer choosing antags for this definition"); break; } if (session != null && ent.Comp.PreSelectedSessions.Values.Any(x => x.Contains(session))) { Log.Warning($"Somehow picked {session} for an antag when this rule already selected them previously"); continue; } } if (session == null) MakeAntag(ent, null, def); // This is for spawner antags else { if (!ent.Comp.PreSelectedSessions.TryGetValue(def, out var set)) ent.Comp.PreSelectedSessions.Add(def, set = new HashSet<ICommonSession>()); set.Add(session); // Selection done! Log.Debug($"Pre-selected {session.Name} as antagonist: {ToPrettyString(ent)}"); _adminLogger.Add(LogType.AntagSelection, $"Pre-selected {session.Name} as antagonist: {ToPrettyString(ent)}"); } } } /// <summary> /// Assigns antag roles to sessions selected for it. /// </summary> public void AssignPreSelectedSessions(Entity<AntagSelectionComponent> ent) { // Only assign if there's been a pre-selection, and the selection hasn't already been made if (!ent.Comp.PreSelectionsComplete || ent.Comp.AssignmentComplete) return; foreach (var def in ent.Comp.Definitions) { if (!ent.Comp.PreSelectedSessions.TryGetValue(def, out var set)) continue; foreach (var session in set) { TryMakeAntag(ent, session, def); } } ent.Comp.AssignmentComplete = true; } /// <summary> /// Tries to makes a given player into the specified antagonist. /// </summary> public bool TryMakeAntag(Entity<AntagSelectionComponent> ent, ICommonSession? session, AntagSelectionDefinition def, bool ignoreSpawner = false, bool checkPref = true, bool onlyPreSelect = false) { _adminLogger.Add(LogType.AntagSelection, $"Start trying to make {session} become the antagonist: {ToPrettyString(ent)}"); if (checkPref && !ValidAntagPreference(session, def.PrefRoles)) return false; if (!IsSessionValid(ent, session, def) || !IsEntityValid(session?.AttachedEntity, def)) return false; if (onlyPreSelect && session != null) { if (!ent.Comp.PreSelectedSessions.TryGetValue(def, out var set)) ent.Comp.PreSelectedSessions.Add(def, set = new HashSet<ICommonSession>()); set.Add(session); Log.Debug($"Pre-selected {session!.Name} as antagonist: {ToPrettyString(ent)}"); _adminLogger.Add(LogType.AntagSelection, $"Pre-selected {session.Name} as antagonist: {ToPrettyString(ent)}"); } else { MakeAntag(ent, session, def, ignoreSpawner); } return true; } /// <summary> /// Makes a given player into the specified antagonist. /// </summary> public void MakeAntag(Entity<AntagSelectionComponent> ent, ICommonSession? session, AntagSelectionDefinition def, bool ignoreSpawner = false) { EntityUid? antagEnt = null; var isSpawner = false; if (session != null) { if (!ent.Comp.PreSelectedSessions.TryGetValue(def, out var set)) ent.Comp.PreSelectedSessions.Add(def, set = new HashSet<ICommonSession>()); set.Add(session); ent.Comp.AssignedSessions.Add(session); // we shouldn't be blocking the entity if they're just a ghost or smth. if (!HasComp<GhostComponent>(session.AttachedEntity)) antagEnt = session.AttachedEntity; } else if (!ignoreSpawner && def.SpawnerPrototype != null) // don't add spawners if we have a player, dummy. { antagEnt = Spawn(def.SpawnerPrototype); isSpawner = true; } if (!antagEnt.HasValue) { var getEntEv = new AntagSelectEntityEvent(session, ent); RaiseLocalEvent(ent, ref getEntEv, true); antagEnt = getEntEv.Entity; } if (antagEnt is not { } player) { Log.Error($"Attempted to make {session} antagonist in gamerule {ToPrettyString(ent)} but there was no valid entity for player."); _adminLogger.Add(LogType.AntagSelection,$"Attempted to make {session} antagonist in gamerule {ToPrettyString(ent)} but there was no valid entity for player."); if (session != null && ent.Comp.RemoveUponFailedSpawn) { ent.Comp.AssignedSessions.Remove(session); ent.Comp.PreSelectedSessions[def].Remove(session); } return; } // TODO: This is really messy because this part runs twice for midround events. // Once when the ghostrole spawner is created and once when a player takes it. // Therefore any component subscribing to this has to make sure both subscriptions return the same value // or the ghost role raffle location preview will be wrong. var getPosEv = new AntagSelectLocationEvent(session, ent); RaiseLocalEvent(ent, ref getPosEv, true); if (getPosEv.Handled) { var playerXform = Transform(player); var pos = RobustRandom.Pick(getPosEv.Coordinates); _transform.SetMapCoordinates((player, playerXform), pos); } // If we want to just do a ghost role spawner, set up data here and then return early. // This could probably be an event in the future if we want to be more refined about it. if (isSpawner) { if (!TryComp<GhostRoleAntagSpawnerComponent>(player, out var spawnerComp)) { Log.Error($"Antag spawner {player} does not have a GhostRoleAntagSpawnerComponent."); _adminLogger.Add(LogType.AntagSelection,$"Antag spawner {player} in gamerule {ToPrettyString(ent)} failed due to not having GhostRoleAntagSpawnerComponent."); if (session != null) { ent.Comp.AssignedSessions.Remove(session); ent.Comp.PreSelectedSessions[def].Remove(session); } return; } spawnerComp.Rule = ent; spawnerComp.Definition = def; return; } // The following is where we apply components, equipment, and other changes to our antagonist entity. EntityManager.AddComponents(player, def.Components); // Equip the entity's RoleLoadout and LoadoutGroup List<ProtoId<StartingGearPrototype>> gear = new(); if (def.StartingGear is not null) gear.Add(def.StartingGear.Value); _loadout.Equip(player, gear, def.RoleLoadout); if (session != null) { var curMind = session.GetMind(); if (curMind == null || !TryComp<MindComponent>(curMind.Value, out var mindComp) || mindComp.OwnedEntity != antagEnt) { curMind = _mind.CreateMind(session.UserId, Name(antagEnt.Value)); _mind.SetUserId(curMind.Value, session.UserId); } _mind.TransferTo(curMind.Value, antagEnt, ghostCheckOverride: true); _role.MindAddRoles(curMind.Value, def.MindRoles, null, true); ent.Comp.AssignedMinds.Add((curMind.Value, Name(player))); SendBriefing(session, def.Briefing); Log.Debug($"Assigned {ToPrettyString(curMind)} as antagonist: {ToPrettyString(ent)}"); _adminLogger.Add(LogType.AntagSelection, $"Assigned {ToPrettyString(curMind)} as antagonist: {ToPrettyString(ent)}"); } var afterEv = new AfterAntagEntitySelectedEvent(session, player, ent, def); RaiseLocalEvent(ent, ref afterEv, true); } /// <summary> /// Gets an ordered player pool based on player preferences and the antagonist definition. /// </summary> public AntagSelectionPlayerPool GetPlayerPool(Entity<AntagSelectionComponent> ent, IList<ICommonSession> sessions, AntagSelectionDefinition def) { var preferredList = new List<ICommonSession>(); var fallbackList = new List<ICommonSession>(); foreach (var session in sessions) { if (!IsSessionValid(ent, session, def) || !IsEntityValid(session.AttachedEntity, def)) continue; if (ent.Comp.PreSelectedSessions.TryGetValue(def, out var preSelected) && preSelected.Contains(session)) continue; // Add player to the appropriate antag pool if (ValidAntagPreference(session, def.PrefRoles)) { preferredList.Add(session); } else if (ValidAntagPreference(session, def.FallbackRoles)) { fallbackList.Add(session); } } return new AntagSelectionPlayerPool(new() { preferredList, fallbackList }); } /// <summary> /// Checks if a given session is valid for an antagonist. /// </summary> public bool IsSessionValid(Entity<AntagSelectionComponent> ent, ICommonSession? session, AntagSelectionDefinition def, EntityUid? mind = null) { // TODO ROLE TIMERS // Check if antag role requirements are met if (session == null) return true; if (session.Status is SessionStatus.Disconnected or SessionStatus.Zombie) return false; if (ent.Comp.AssignedSessions.Contains(session)) return false; mind ??= session.GetMind(); //todo: we need some way to check that we're not getting the same role twice. (double picking thieves or zombies through midrounds) switch (def.MultiAntagSetting) { case AntagAcceptability.None: { if (_role.MindIsAntagonist(mind)) return false; if (GetPreSelectedAntagSessions(def).Contains(session)) // Used for rules where the antag has been selected, but not started yet return false; break; } case AntagAcceptability.NotExclusive: { if (_role.MindIsExclusiveAntagonist(mind)) return false; if (GetPreSelectedExclusiveAntagSessions(def).Contains(session)) return false; break; } } // todo: expand this to allow for more fine antag-selection logic for game rules. if (!_jobs.CanBeAntag(session)) return false; return true; } /// <summary> /// Checks if a given entity (mind/session not included) is valid for a given antagonist. /// </summary> public bool IsEntityValid(EntityUid? entity, AntagSelectionDefinition def) { // If the player has not spawned in as any entity (e.g., in the lobby), they can be given an antag role/entity. if (entity == null) return true; // ES START if (HasComp<ESTheatergoerMarkerComponent>(entity)) return true; // ES END if (HasComp<PendingClockInComponent>(entity)) return false; if (!def.AllowNonHumans && !HasComp<HumanoidAppearanceComponent>(entity)) return false; if (def.Whitelist != null) { if (!_whitelist.IsValid(def.Whitelist, entity.Value)) return false; } if (def.Blacklist != null) { if (_whitelist.IsValid(def.Blacklist, entity.Value)) return false; } return true; } private void OnObjectivesTextGetInfo(Entity<AntagSelectionComponent> ent, ref ObjectivesTextGetInfoEvent args) { if (ent.Comp.AgentName is not { } name) return; args.Minds = ent.Comp.AssignedMinds; args.AgentName = Loc.GetString(name); } } /// <summary> /// Event raised on a game rule entity in order to determine what the antagonist entity will be. /// Only raised if the selected player's current entity is invalid. /// </summary> [ByRefEvent] public record struct AntagSelectEntityEvent(ICommonSession? Session, Entity<AntagSelectionComponent> GameRule) { public readonly ICommonSession? Session = Session; public bool Handled => Entity != null; public EntityUid? Entity; } /// <summary> /// Event raised on a game rule entity to determine the location for the antagonist. /// </summary> [ByRefEvent] public record struct AntagSelectLocationEvent(ICommonSession? Session, Entity<AntagSelectionComponent> GameRule) { public readonly ICommonSession? Session = Session; public bool Handled => Coordinates.Any(); public List<MapCoordinates> Coordinates = new(); } /// <summary> /// Event raised on a game rule entity after the setup logic for an antag is complete. /// Used for applying additional more complex setup logic. /// </summary> [ByRefEvent] public readonly record struct AfterAntagEntitySelectedEvent(ICommonSession? Session, EntityUid EntityUid, Entity<AntagSelectionComponent> GameRule, AntagSelectionDefinition Def);
1
0.941635
1
0.941635
game-dev
MEDIA
0.786735
game-dev
0.950492
1
0.950492
armory3d/armory
3,698
lib/haxebullet/bullet/LinearMath/btGrahamScan2dConvexHull.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2011 Advanced Micro Devices, Inc. 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 GRAHAM_SCAN_2D_CONVEX_HULL_H #define GRAHAM_SCAN_2D_CONVEX_HULL_H #include "btVector3.h" #include "btAlignedObjectArray.h" struct GrahamVector3 : public btVector3 { GrahamVector3(const btVector3& org, int orgIndex) :btVector3(org), m_orgIndex(orgIndex) { } btScalar m_angle; int m_orgIndex; }; struct btAngleCompareFunc { btVector3 m_anchor; btAngleCompareFunc(const btVector3& anchor) : m_anchor(anchor) { } bool operator()(const GrahamVector3& a, const GrahamVector3& b) const { if (a.m_angle != b.m_angle) return a.m_angle < b.m_angle; else { btScalar al = (a-m_anchor).length2(); btScalar bl = (b-m_anchor).length2(); if (al != bl) return al < bl; else { return a.m_orgIndex < b.m_orgIndex; } } } }; inline void GrahamScanConvexHull2D(btAlignedObjectArray<GrahamVector3>& originalPoints, btAlignedObjectArray<GrahamVector3>& hull, const btVector3& normalAxis) { btVector3 axis0,axis1; btPlaneSpace1(normalAxis,axis0,axis1); if (originalPoints.size()<=1) { for (int i=0;i<originalPoints.size();i++) hull.push_back(originalPoints[0]); return; } //step1 : find anchor point with smallest projection on axis0 and move it to first location for (int i=0;i<originalPoints.size();i++) { // const btVector3& left = originalPoints[i]; // const btVector3& right = originalPoints[0]; btScalar projL = originalPoints[i].dot(axis0); btScalar projR = originalPoints[0].dot(axis0); if (projL < projR) { originalPoints.swap(0,i); } } //also precompute angles originalPoints[0].m_angle = -1e30f; for (int i=1;i<originalPoints.size();i++) { btVector3 ar = originalPoints[i]-originalPoints[0]; btScalar ar1 = axis1.dot(ar); btScalar ar0 = axis0.dot(ar); if( ar1*ar1+ar0*ar0 < FLT_EPSILON ) { originalPoints[i].m_angle = 0.0f; } else { originalPoints[i].m_angle = btAtan2Fast(ar1, ar0); } } //step 2: sort all points, based on 'angle' with this anchor btAngleCompareFunc comp(originalPoints[0]); originalPoints.quickSortInternal(comp,1,originalPoints.size()-1); int i; for (i = 0; i<2; i++) hull.push_back(originalPoints[i]); //step 3: keep all 'convex' points and discard concave points (using back tracking) for (; i != originalPoints.size(); i++) { bool isConvex = false; while (!isConvex&& hull.size()>1) { btVector3& a = hull[hull.size()-2]; btVector3& b = hull[hull.size()-1]; isConvex = btCross(a-b,a-originalPoints[i]).dot(normalAxis)> 0; if (!isConvex) hull.pop_back(); else hull.push_back(originalPoints[i]); } if( hull.size() == 1 ) { hull.push_back( originalPoints[i] ); } } } #endif //GRAHAM_SCAN_2D_CONVEX_HULL_H
1
0.82091
1
0.82091
game-dev
MEDIA
0.920043
game-dev
0.985154
1
0.985154
Anthonyy232/Nagi
4,873
src/Nagi.WinUI/ViewModels/GenreViewModel.cs
using System; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using System.Threading; using System.Threading.Tasks; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Microsoft.Extensions.Logging; using Nagi.Core.Services.Abstractions; using Nagi.WinUI.Navigation; using Nagi.WinUI.Pages; using Nagi.WinUI.Services.Abstractions; namespace Nagi.WinUI.ViewModels; /// <summary> /// A display-optimized representation of a genre for the user interface. /// </summary> public partial class GenreViewModelItem : ObservableObject { [ObservableProperty] public partial Guid Id { get; set; } [ObservableProperty] public partial string Name { get; set; } = string.Empty; } /// <summary> /// Manages the state and logic for the genre list page. /// </summary> public partial class GenreViewModel : ObservableObject, IDisposable { private readonly NotifyCollectionChangedEventHandler _collectionChangedHandler; private readonly ILibraryService _libraryService; private readonly ILogger<GenreViewModel> _logger; private readonly IMusicPlaybackService _musicPlaybackService; private readonly INavigationService _navigationService; private bool _isDisposed; public GenreViewModel(ILibraryService libraryService, IMusicPlaybackService musicPlaybackService, INavigationService navigationService, ILogger<GenreViewModel> logger) { _libraryService = libraryService; _musicPlaybackService = musicPlaybackService; _navigationService = navigationService; _logger = logger; // Store the handler in a field so we can reliably unsubscribe from it later. _collectionChangedHandler = (s, e) => OnPropertyChanged(nameof(HasGenres)); Genres.CollectionChanged += _collectionChangedHandler; } [ObservableProperty] public partial ObservableCollection<GenreViewModelItem> Genres { get; set; } = new(); [ObservableProperty] public partial bool IsLoading { get; set; } [ObservableProperty] public partial bool HasLoadError { get; set; } /// <summary> /// Gets a value indicating whether there are any genres to display. /// </summary> public bool HasGenres => Genres.Any(); /// <summary> /// Cleans up resources by unsubscribing from event handlers. /// </summary> public void Dispose() { if (_isDisposed) return; if (Genres != null) Genres.CollectionChanged -= _collectionChangedHandler; _isDisposed = true; GC.SuppressFinalize(this); } /// <summary> /// Navigates to the detailed view for the selected genre. /// </summary> [RelayCommand] public void NavigateToGenreDetail(GenreViewModelItem? genre) { if (genre is null) return; var navParam = new GenreViewNavigationParameter { GenreId = genre.Id, GenreName = genre.Name }; _navigationService.Navigate(typeof(GenreViewPage), navParam); } /// <summary> /// Asynchronously loads all genres from the library. /// </summary> /// <param name="cancellationToken">A token to monitor for cancellation requests.</param> [RelayCommand] public async Task LoadGenresAsync(CancellationToken cancellationToken) { if (IsLoading) return; IsLoading = true; HasLoadError = false; try { var genreModels = await _libraryService.GetAllGenresAsync(); if (cancellationToken.IsCancellationRequested) return; var sortedGenres = genreModels .OrderBy(g => g.Name) .Select(g => new GenreViewModelItem { Id = g.Id, Name = g.Name }); // Efficiently replace the entire collection. Genres = new ObservableCollection<GenreViewModelItem>(sortedGenres); } catch (OperationCanceledException) { _logger.LogInformation("Genre loading was canceled"); } catch (Exception ex) { _logger.LogError(ex, "Failed to load genres"); HasLoadError = true; Genres.Clear(); } finally { IsLoading = false; } } /// <summary> /// Clears the current queue and starts playing all songs in the selected genre. /// </summary> [RelayCommand] private async Task PlayGenreAsync(Guid genreId) { if (IsLoading || genreId == Guid.Empty) return; try { await _musicPlaybackService.PlayGenreAsync(genreId); } catch (Exception ex) { // This is a critical failure as it directly impacts core user functionality. _logger.LogCritical(ex, "Failed to play genre {GenreId}", genreId); } } }
1
0.787831
1
0.787831
game-dev
MEDIA
0.657116
game-dev
0.93286
1
0.93286
Nenkai/GBFRDataTools
1,439
GBFRDataTools.FSM/Components/Actions/AI/Enemy/Tayuitar/Em1900OverDriveRushBaseAction.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; namespace GBFRDataTools.FSM.Components.Actions.AI.Enemy.Tayuitar; public class Em1900OverDriveRushBaseAction : ActionComponent { [JsonIgnore] public override string ComponentName => nameof(Em1900OverDriveRushBaseAction); [JsonPropertyName("isFirst_")] public bool IsFirst { get; set; } = false; // Offset 0xAC [JsonPropertyName("isFinish_")] public bool IsFinish { get; set; } = false; // Offset 0xAD [JsonPropertyName("nextWeaponType_")] public int NextWeaponType { get; set; } = 0; // Offset 0xB0 [JsonPropertyName("homingRate_")] public float HomingRate { get; set; } = 0f; // Offset 0xB4 [JsonPropertyName("homingRateStop_")] public float HomingRateStop { get; set; } = 0.1f; // Offset 0xB8 [JsonPropertyName("dushTime_")] public float DushTime { get; set; } = 2f; // Offset 0xBC [JsonPropertyName("intervalShotFrameNum_")] public int IntervalShotFrameNum { get; set; } = 1; // Offset 0x70 [JsonPropertyName("homingBeamRate_")] public float HomingBeamRate { get; set; } = 0f; // Offset 0xC0 [JsonPropertyName("isEnableBeam_")] public bool IsEnableBeam { get; set; } = true; // Offset 0xC4 public Em1900OverDriveRushBaseAction() { } }
1
0.649488
1
0.649488
game-dev
MEDIA
0.36402
game-dev
0.524641
1
0.524641
ReactiveDrop/reactivedrop_public_src
22,717
src/game/shared/swarm/asw_holdout_mode.cpp
#include "cbase.h" #include "asw_shareddefs.h" #include "asw_holdout_mode.h" #include "asw_holdout_wave.h" #include "filesystem.h" #include "asw_util_shared.h" #ifdef GAME_DLL #include "asw_spawn_manager.h" #include "asw_spawn_group.h" #include "asw_game_resource.h" #include "asw_marine_resource.h" #include "asw_marine.h" #include "asw_weapon.h" #include "asw_gamerules.h" #include "asw_equipment_list.h" #include "asw_alien.h" #include "asw_buzzer.h" #include "entityinput.h" #include "entityoutput.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Holdout_Mode, DT_ASW_Holdout_Mode ) ConVar asw_holdout_debug( "asw_holdout_debug", "0", FCVAR_CHEAT | FCVAR_REPLICATED, "Show debug text for holdout mode" ); BEGIN_NETWORK_TABLE( CASW_Holdout_Mode, DT_ASW_Holdout_Mode ) #ifdef CLIENT_DLL RecvPropInt( RECVINFO( m_nCurrentWave ) ), RecvPropInt( RECVINFO( m_nCurrentScore ) ), RecvPropInt( RECVINFO( m_nAliensKilledThisWave ) ), RecvPropTime( RECVINFO( m_flCurrentWaveStartTime ) ), RecvPropTime( RECVINFO( m_flResupplyEndTime ) ), RecvPropString( RECVINFO( m_netHoldoutFilename ) ), #else SendPropInt( SENDINFO( m_nCurrentWave ) ), SendPropInt( SENDINFO( m_nCurrentScore ) ), SendPropInt( SENDINFO( m_nAliensKilledThisWave ) ), SendPropTime( SENDINFO( m_flCurrentWaveStartTime ) ), SendPropTime( SENDINFO( m_flResupplyEndTime ) ), SendPropString( SENDINFO( m_netHoldoutFilename ) ), #endif END_NETWORK_TABLE() #ifdef GAME_DLL LINK_ENTITY_TO_CLASS( asw_holdout_mode, CASW_Holdout_Mode ); BEGIN_DATADESC( CASW_Holdout_Mode ) DEFINE_KEYFIELD( m_holdoutFilename, FIELD_STRING, "filename" ), DEFINE_THINKFUNC( HoldoutThink ), DEFINE_OUTPUT(m_OnWave[0], "OnWave01"), DEFINE_OUTPUT(m_OnWave[1], "OnWave02"), DEFINE_OUTPUT(m_OnWave[2], "OnWave03"), DEFINE_OUTPUT(m_OnWave[3], "OnWave04"), DEFINE_OUTPUT(m_OnWave[4], "OnWave05"), DEFINE_OUTPUT(m_OnWave[5], "OnWave06"), DEFINE_OUTPUT(m_OnWave[6], "OnWave07"), DEFINE_OUTPUT(m_OnWave[7], "OnWave08"), DEFINE_OUTPUT(m_OnWave[8], "OnWave09"), DEFINE_OUTPUT(m_OnWave[9], "OnWave10"), DEFINE_OUTPUT(m_OnAnnounceWave[0], "OnAnnounceWave01"), DEFINE_OUTPUT(m_OnAnnounceWave[1], "OnAnnounceWave02"), DEFINE_OUTPUT(m_OnAnnounceWave[2], "OnAnnounceWave03"), DEFINE_OUTPUT(m_OnAnnounceWave[3], "OnAnnounceWave04"), DEFINE_OUTPUT(m_OnAnnounceWave[4], "OnAnnounceWave05"), DEFINE_OUTPUT(m_OnAnnounceWave[5], "OnAnnounceWave06"), DEFINE_OUTPUT(m_OnAnnounceWave[6], "OnAnnounceWave07"), DEFINE_OUTPUT(m_OnAnnounceWave[7], "OnAnnounceWave08"), DEFINE_OUTPUT(m_OnAnnounceWave[8], "OnAnnounceWave09"), DEFINE_OUTPUT(m_OnAnnounceWave[9], "OnAnnounceWave10"), DEFINE_OUTPUT(m_OnWaveDefault, "OnWaveDefault"), DEFINE_OUTPUT(m_OnAnnounceWaveDefault, "OnAnnounceWaveDefault"), DEFINE_INPUTFUNC( FIELD_VOID, "UnlockResupply", InputUnlockResupply ), END_DATADESC() #endif const char *HoldoutEventTypeAsString( ASW_Holdout_Event_t nEventType ) { switch( nEventType ) { case HOLDOUT_EVENT_START_WAVE_ENTRY: return "HOLDOUT_EVENT_START_WAVE_ENTRY"; case HOLDOUT_EVENT_SINGLE_SPAWN: return "HOLDOUT_EVENT_SINGLE_SPAWN"; case HOLDOUT_EVENT_STATE_CHANGE: return "HOLDOUT_EVENT_STATE_CHANGE"; } return "Unknown"; } const char *HoldoutStateAsString( ASW_Holdout_State_t nState ) { switch( nState ) { case HOLDOUT_STATE_BRIEFING: return "HOLDOUT_STATE_BRIEFING"; case HOLDOUT_STATE_ANNOUNCE_NEW_WAVE: return "HOLDOUT_STATE_ANNOUNCE_NEW_WAVE"; case HOLDOUT_STATE_WAVE_IN_PROGRESS: return "HOLDOUT_STATE_WAVE_IN_PROGRESS"; case HOLDOUT_STATE_SHOWING_WAVE_SCORE: return "HOLDOUT_STATE_SHOWING_WAVE_SCORE"; case HOLDOUT_STATE_RESUPPLY: return "HOLDOUT_STATE_RESUPPLY"; } return "Unknown"; } CASW_Holdout_Mode *g_pHoldoutMode = NULL; CASW_Holdout_Mode* ASWHoldoutMode() { return g_pHoldoutMode; } CASW_Holdout_Mode::CASW_Holdout_Mode() { Assert( !g_pHoldoutMode ); g_pHoldoutMode = this; m_nCurrentWave = -1; m_nCurrentScore = 0; #ifdef GAME_DLL m_holdoutFilename = NULL_STRING; m_nUnlockedResupply = 0; m_bResurrectingMarines = false; #endif m_netHoldoutFilename.GetForModify()[0] = 0; } CASW_Holdout_Mode::~CASW_Holdout_Mode() { m_Waves.PurgeAndDeleteElements(); Assert( g_pHoldoutMode == this ); g_pHoldoutMode = NULL; } #ifdef GAME_DLL void CASW_Holdout_Mode::Spawn() { Precache(); BaseClass::Spawn(); } void CASW_Holdout_Mode::Activate( void ) { BaseClass::Activate(); Q_strncpy( m_netHoldoutFilename.GetForModify(), STRING( m_holdoutFilename ), MAX_PATH ); } void CASW_Holdout_Mode::Precache() { BaseClass::Precache(); Assert( ASWSpawnManager() ); int nCount = ASWSpawnManager()->GetNumAlienClasses(); for ( int i = 0; i < nCount; i++ ) { UTIL_PrecacheOther( ASWSpawnManager()->GetAlienClass(i)->m_pszAlienClass ); } } void CASW_Holdout_Mode::InputUnlockResupply( inputdata_t &inputdata ) { m_nUnlockedResupply += 1; hudtextparms_s tTextParam; tTextParam.x = -1; tTextParam.y = 0.25; tTextParam.effect = 0; tTextParam.r1 = 255; tTextParam.g1 = 170; tTextParam.b1 = 0; tTextParam.a1 = 255; tTextParam.r2 = 255; tTextParam.g2 = 170; tTextParam.b2 = 0; tTextParam.a2 = 255; tTextParam.fadeinTime = 0.1; tTextParam.fadeoutTime = 0.5; tTextParam.holdTime = 5.0; tTextParam.fxTime = 0; tTextParam.channel = 1; if ( m_nHoldoutState == HOLDOUT_STATE_WAVE_IN_PROGRESS ) { UTIL_HudMessageAll( tTextParam, "Resupply unlocked!\nYou will resupply at the end of THIS round\n" ); } else { UTIL_HudMessageAll( tTextParam, "Resupply unlocked!\nYou will resupply at the end of NEXT round\n" ); } } void CASW_Holdout_Mode::HoldoutThink() { if ( asw_holdout_debug.GetBool() ) { engine->Con_NPrintf( 1, "Holdout events:" ); for ( int i = 0; i < m_Events.Count(); i++ ) { CASW_Holdout_Event *pEvent = m_Events[ i ]; if ( pEvent->m_EventType == HOLDOUT_EVENT_START_WAVE_ENTRY || pEvent->m_EventType == HOLDOUT_EVENT_SINGLE_SPAWN ) { CASW_Holdout_Spawn_Event *pSpawnEvent = static_cast<CASW_Holdout_Spawn_Event*>( pEvent ); engine->Con_NPrintf( i + 1, "%f:%s %d x %s over %f group=%s", gpGlobals->curtime - pEvent->m_flEventTime, HoldoutEventTypeAsString( pEvent->m_EventType ), pSpawnEvent->m_pWaveEntry->GetQuantity(), STRING( pSpawnEvent->m_pWaveEntry->GetAlienClass() ), pSpawnEvent->m_pWaveEntry->GetSpawnDuration(), pSpawnEvent->m_pWaveEntry->GetSpawnGroupName() ); } else if ( pEvent->m_EventType == HOLDOUT_EVENT_STATE_CHANGE ) { CASW_Holdout_State_Change_Event *pStateEvent = static_cast<CASW_Holdout_State_Change_Event*>( pEvent ); engine->Con_NPrintf( i + 1, "%f:%s to %d", gpGlobals->curtime - pEvent->m_flEventTime, HoldoutEventTypeAsString( pEvent->m_EventType ), HoldoutStateAsString( pStateEvent->m_NewState ) ); } else { engine->Con_NPrintf( i + 1, "%f:%s", gpGlobals->curtime - pEvent->m_flEventTime, HoldoutEventTypeAsString( pEvent->m_EventType ) ); } } engine->Con_NPrintf( m_Events.Count() + 2, " " ); } // see if any events need to be processed while ( m_Events.Count() > 0 ) { CASW_Holdout_Event *pEvent = m_Events[ 0 ]; if ( pEvent->m_flEventTime > gpGlobals->curtime ) break; m_Events.Remove( 0 ); ProcessEvent( pEvent ); } SetThink( &CASW_Holdout_Mode::HoldoutThink ); if ( m_bResurrectingMarines ) { ResurrectDeadMarines(); SetNextThink( gpGlobals->curtime + 0.25f ); } else if ( m_Events.Count() <= 0 ) { SetNextThink( gpGlobals->curtime + 1.0f ); } else { SetNextThink( MIN( gpGlobals->curtime + 1.0f, m_Events[ 0 ]->m_flEventTime ) ); } } void CASW_Holdout_Mode::ProcessEvent( CASW_Holdout_Event *pEvent ) { switch( pEvent->m_EventType ) { case HOLDOUT_EVENT_START_WAVE_ENTRY: // start spawning aliens from a wave entry { // find the wave entry and spawngroup CASW_Holdout_Spawn_Event *pSpawnEvent = static_cast<CASW_Holdout_Spawn_Event*>( pEvent ); CASW_Holdout_Wave_Entry *pEntry = pSpawnEvent->m_pWaveEntry; CASW_Spawn_Group *pSpawnGroup = pEntry->GetSpawnGroup(); if ( !pSpawnGroup ) { delete pEvent; return; } // spawn any aliens that need to be spawned right now int nToSpawnNow = ( pEntry->GetSpawnDuration() <= 0.0f ) ? pEntry->GetQuantity() : MIN( 1, pEntry->GetQuantity() ); SpawnAliens( nToSpawnNow, pEntry, pSpawnGroup ); // for spawns spread over a duration, add a single spawn event for each int nToSpawnLater = pEntry->GetQuantity() - nToSpawnNow; float flInterval = pEntry->GetSpawnDuration() / (float) nToSpawnLater; for ( int i = 0; i < nToSpawnLater; i++ ) { if ( asw_holdout_debug.GetBool() ) { Msg( "Adding a single spawn from HOLDOUT_EVENT_START_WAVE_ENTRY as %d want to spawn over time\n", nToSpawnLater ); } CASW_Holdout_Spawn_Event *pSingleSpawn = new CASW_Holdout_Spawn_Event; pSingleSpawn->m_pWaveEntry = pEntry; pSingleSpawn->m_EventType = HOLDOUT_EVENT_SINGLE_SPAWN; pSingleSpawn->m_flEventTime = pEvent->m_flEventTime + flInterval * ( i + 1 ); AddEvent( pSingleSpawn ); } } break; case HOLDOUT_EVENT_SINGLE_SPAWN: // single spawn from an entry that spawns its quantity over a duration { // find the wave entry and spawngroup CASW_Holdout_Spawn_Event *pSpawnEvent = static_cast<CASW_Holdout_Spawn_Event*>( pEvent ); CASW_Holdout_Wave_Entry *pEntry = pSpawnEvent->m_pWaveEntry; CASW_Spawn_Group *pSpawnGroup = pEntry->GetSpawnGroup(); if ( !pSpawnGroup ) { delete pEvent; return; } SpawnAliens( 1, pEntry, pSpawnGroup ); } break; case HOLDOUT_EVENT_STATE_CHANGE: { CASW_Holdout_State_Change_Event *pStateChangeEvent = static_cast<CASW_Holdout_State_Change_Event*>( pEvent ); ChangeHoldoutState( pStateChangeEvent->m_NewState ); } break; } delete pEvent; } void CASW_Holdout_Mode::StartWave( int nWave ) { m_Events.PurgeAndDeleteElements(); m_bResurrectingMarines = false; if ( nWave < 0 || nWave >= m_Waves.Count() ) { Warning( "StartWave called with wave out of range: %d\n", nWave ); return; } m_nCurrentWave = nWave; m_nAliensKilledThisWave = 0; m_flCurrentWaveStartTime = gpGlobals->curtime; // add events to spawn each entry in this wave CASW_Holdout_Wave *pWave = m_Waves[ m_nCurrentWave ]; for ( int i = 0; i < pWave->GetNumEntries(); i++ ) { if ( asw_holdout_debug.GetBool() ) { Msg( "Adding a spawn entry from StartWave. Entry %d\n", i ); } CASW_Holdout_Spawn_Event *pEvent = new CASW_Holdout_Spawn_Event; pEvent->m_pWaveEntry = pWave->GetEntry( i ); pEvent->m_EventType = HOLDOUT_EVENT_START_WAVE_ENTRY; pEvent->m_flEventTime = m_flCurrentWaveStartTime + pEvent->m_pWaveEntry->GetSpawnDelay(); AddEvent( pEvent ); } if ( m_nCurrentWave < MAX_HOLDOUT_WAVES ) { m_OnWave[m_nCurrentWave].FireOutput( this, this ); } m_OnWaveDefault.FireOutput( this, this ); } void CASW_Holdout_Mode::AddEvent( CASW_Holdout_Event *pEvent ) { m_Events.Insert( pEvent ); if ( pEvent->m_flEventTime < GetNextThink() ) { SetNextThink( pEvent->m_flEventTime ); } } int CASW_Holdout_Mode::SpawnAliens( int nQuantity, CASW_Holdout_Wave_Entry *pEntry, CASW_Spawn_Group *pSpawnGroup ) { Assert( ASWSpawnManager() ); // pick N spawners from the spawngroup CUtlVector< CASW_Base_Spawner* > spawners; pSpawnGroup->PickSpawnersRandomly( nQuantity, false, &spawners ); const char *szAlienClass = STRING( pEntry->GetAlienClass() ); int nSpawned = 0; Vector vecHullMins, vecHullMaxs; ASWSpawnManager()->GetAlienBounds( pEntry->GetAlienClass(), vecHullMins, vecHullMaxs ); // tell each spawner to spawn an alien of our class for ( int i = 0; i < spawners.Count(); i++ ) { IASW_Spawnable_NPC* pAlien = spawners[i]->SpawnAlien( szAlienClass, vecHullMins, vecHullMaxs ); if ( pAlien ) { pAlien->SetHoldoutAlien(); nSpawned++; } } // for each failure, add an event to try again // TODO: keep track of failure count, so we give up eventually with a warning? for ( int i = 0; i < ( nQuantity - nSpawned ); i++ ) { if ( asw_holdout_debug.GetBool() ) { Msg( "Adding a spawn entry from SpawnAliens. As some aliens failed to spawn %d/%d\n", i, ( nQuantity - nSpawned ) ); } CASW_Holdout_Spawn_Event *pSingleSpawn = new CASW_Holdout_Spawn_Event; pSingleSpawn->m_pWaveEntry = pEntry; pSingleSpawn->m_EventType = HOLDOUT_EVENT_SINGLE_SPAWN; pSingleSpawn->m_flEventTime = gpGlobals->curtime + 1.0f + 0.1f * i; AddEvent( pSingleSpawn ); } return nSpawned; } ConVar asw_holdout_announce_time( "asw_holdout_announce_time", "5.0f", FCVAR_CHEAT, "How many seconds between announcing a wave and actually starting a wave."); ConVar asw_holdout_wave_score_time( "asw_holdout_wave_score_time", "5.0f", FCVAR_CHEAT, "How many seconds to show the end wave scores for."); ConVar asw_holdout_resupply_time( "asw_holdout_resupply_time", "20.0f", FCVAR_CHEAT, "How many seconds marines have to pick new weapons in the resupply stage."); void CASW_Holdout_Mode::ChangeHoldoutState( ASW_Holdout_State_t nNewState ) { if ( asw_holdout_debug.GetBool() ) { Msg( "%f: ChangeHoldoutState %s\n", gpGlobals->curtime, HoldoutStateAsString( nNewState ) ); } //ASW_Holdout_State_t nOldState = GetHoldoutState(); m_nHoldoutState = (int) nNewState; // States with a fixed duration schedule another state change here switch( nNewState ) { case HOLDOUT_STATE_ANNOUNCE_NEW_WAVE: { // advance to the next wave SetCurrentWave( GetCurrentWave() + 1 ); m_bResurrectingMarines = false; // send a message to all clients telling them to show the wave announce animation CRecipientFilter filter; filter.AddAllPlayers(); UserMessageBegin( filter, "ASWNewHoldoutWave" ); WRITE_BYTE( GetCurrentWave() ); WRITE_FLOAT( asw_holdout_announce_time.GetFloat() ); MessageEnd(); // actually start the wave after a short delay CASW_Holdout_State_Change_Event *pStateEvent = new CASW_Holdout_State_Change_Event; pStateEvent->m_EventType = HOLDOUT_EVENT_STATE_CHANGE; pStateEvent->m_NewState = HOLDOUT_STATE_WAVE_IN_PROGRESS; pStateEvent->m_flEventTime = gpGlobals->curtime + asw_holdout_announce_time.GetFloat(); AddEvent( pStateEvent ); if ( m_nCurrentWave < MAX_HOLDOUT_WAVES ) { m_OnAnnounceWave[m_nCurrentWave].FireOutput( this, this ); } m_OnAnnounceWaveDefault.FireOutput( this, this ); } break; case HOLDOUT_STATE_WAVE_IN_PROGRESS: { StartWave( GetCurrentWave() ); } break; case HOLDOUT_STATE_SHOWING_WAVE_SCORE: { CASW_Holdout_State_Change_Event *pStateEvent = new CASW_Holdout_State_Change_Event; pStateEvent->m_EventType = HOLDOUT_EVENT_STATE_CHANGE; pStateEvent->m_flEventTime = gpGlobals->curtime + asw_holdout_wave_score_time.GetFloat(); if ( GetCurrentWave() >= m_Waves.Count() - 1 ) { pStateEvent->m_NewState = HOLDOUT_STATE_COMPLETE; // finished holdout mode! } else if ( m_nUnlockedResupply > 0 || m_Waves[ GetCurrentWave() ]->WaveHasResupply() ) { pStateEvent->m_NewState = HOLDOUT_STATE_RESUPPLY; } else { pStateEvent->m_NewState = HOLDOUT_STATE_ANNOUNCE_NEW_WAVE; } AddEvent( pStateEvent ); // resurrect dead marines m_bResurrectingMarines = true; // tell clients to show the wave end scores: CRecipientFilter filter; filter.AddAllPlayers(); UserMessageBegin( filter, "ASWShowHoldoutWaveEnd" ); WRITE_BYTE( GetCurrentWave() ); WRITE_FLOAT( asw_holdout_wave_score_time.GetFloat() ); MessageEnd(); } break; case HOLDOUT_STATE_RESUPPLY: { if ( GetCurrentWave() < m_Waves.Count() - 1 ) { if ( m_nUnlockedResupply > 0 ) { m_nUnlockedResupply -= 1; } else { Warning( "Giving a resupply, but it has not been unlocked! (m_nUnlockedResupply <= 0)\n" ); } RefillMarineAmmo(); CASW_Holdout_State_Change_Event *pStateEvent = new CASW_Holdout_State_Change_Event; pStateEvent->m_EventType = HOLDOUT_EVENT_STATE_CHANGE; pStateEvent->m_NewState = HOLDOUT_STATE_ANNOUNCE_NEW_WAVE; pStateEvent->m_flEventTime = gpGlobals->curtime + asw_holdout_resupply_time.GetFloat(); AddEvent( pStateEvent ); // tell clients to show the resupply UI: CRecipientFilter filter; filter.AddAllPlayers(); UserMessageBegin( filter, "ASWShowHoldoutResupply" ); MessageEnd(); m_flResupplyEndTime = pStateEvent->m_flEventTime; } else { // completed all the waves! if ( asw_holdout_debug.GetBool() ) { Msg( "Finished all holdout waves!\n" ); } } } break; case HOLDOUT_STATE_COMPLETE: { ASWGameRules()->MissionComplete( true ); } break; } } void CASW_Holdout_Mode::OnMissionStart() { // announce the first wave after a short delay CASW_Holdout_State_Change_Event *pStateEvent = new CASW_Holdout_State_Change_Event; pStateEvent->m_EventType = HOLDOUT_EVENT_STATE_CHANGE; pStateEvent->m_NewState = HOLDOUT_STATE_ANNOUNCE_NEW_WAVE; pStateEvent->m_flEventTime = gpGlobals->curtime + 3.0f; AddEvent( pStateEvent ); } void CASW_Holdout_Mode::OnAlienKilled( CBaseEntity *pAlien, const CTakeDamageInfo &info ) { if ( !pAlien ) return; IASW_Spawnable_NPC *pSpawnable = NULL; if ( pAlien->IsAlienClassType() ) { CASW_Alien *pAlienNPC = static_cast<CASW_Alien*>( pAlien ); pSpawnable = pAlienNPC; } else if ( pAlien->Classify() == CLASS_ASW_BUZZER ) { CASW_Buzzer *pBuzzer = static_cast<CASW_Buzzer*>( pAlien ); pSpawnable = pBuzzer; } if ( !pSpawnable || !pSpawnable->IsHoldoutAlien() ) return; m_nAliensKilledThisWave++; if ( m_nAliensKilledThisWave >= m_Waves[ GetCurrentWave() ]->GetTotalAliens() ) { // all aliens have been killed - show the wave scores after a short delay CASW_Holdout_State_Change_Event *pStateEvent = new CASW_Holdout_State_Change_Event; pStateEvent->m_EventType = HOLDOUT_EVENT_STATE_CHANGE; pStateEvent->m_NewState = HOLDOUT_STATE_SHOWING_WAVE_SCORE; pStateEvent->m_flEventTime = gpGlobals->curtime + 2.0f; AddEvent( pStateEvent ); } m_nCurrentScore += 100; // TODO: different values per alien type } void CASW_Holdout_Mode::RefillMarineAmmo() { CASW_Game_Resource *pGameResource = ASWGameResource(); for (int i=0;i<pGameResource->GetMaxMarineResources();i++) { if (pGameResource->GetMarineResource(i) != NULL && pGameResource->GetMarineResource(i)->GetMarineEntity()) { CASW_Marine *pMarine = pGameResource->GetMarineResource(i)->GetMarineEntity(); for (int k=0;k<3;k++) { CASW_Weapon *pWeapon = pMarine->GetASWWeapon(k); if (!pWeapon) continue; // refill bullets in the gun pWeapon->m_iClip1 = pWeapon->GetMaxClip1(); pWeapon->m_iClip2 = pWeapon->GetMaxClip2(); // give the marine a load of ammo of that type pMarine->GiveAmmo(10000, pWeapon->GetPrimaryAmmoType()); pMarine->GiveAmmo(10000, pWeapon->GetSecondaryAmmoType()); } } } } void CASW_Holdout_Mode::ResurrectDeadMarines() { const int numMarineResources = ASWGameResource()->GetMaxMarineResources(); CASW_Marine *pAliveMarine = NULL; for ( int i=0; i < numMarineResources ; i++ ) { CASW_Marine_Resource *pMR = ASWGameResource()->GetMarineResource( i ); CASW_Marine *pMarine = pMR ? pMR->GetMarineEntity() : NULL; if ( pMarine && pMR->GetHealthPercent() > 0 ) { pAliveMarine = pMarine; break; } } for ( int i=0; i < numMarineResources ; i++ ) { CASW_Marine_Resource *pMR = ASWGameResource()->GetMarineResource( i ); if ( pMR && pMR->GetHealthPercent() <= 0 ) // if marine exists, is dead { ASWGameRules()->Resurrect( pMR, pAliveMarine ); return; // don't do two in a frame } } } // player has picked a new weapon from the resupply panel void CASW_Holdout_Mode::LoadoutSelect( CASW_Marine_Resource *pMarineResource, int nEquipIndex, int nInvSlot ) { CASW_Marine *pMarine = pMarineResource->GetMarineEntity(); if ( !pMarine ) return; // remove the old weapon in this slot, if any CASW_Weapon *pOldWeapon = pMarine->GetASWWeapon( nInvSlot ); if ( pOldWeapon ) { pMarine->DropWeapon( pOldWeapon, true ); UTIL_Remove( pOldWeapon ); } // give them the new weapon ASWGameRules()->GiveStartingWeaponToMarine( pMarine, nEquipIndex, nInvSlot ); pMarineResource->UpdateWeaponIndices(); } CON_COMMAND( asw_holdout_start_wave, "Starts a holdout wave" ) { if ( !ASWHoldoutMode() ) { Msg( "Unable to start holdout wave as this isn't a holdout map\n" ); return; } if ( args.ArgC() != 2 ) { Msg( "Usage: asw_holdout_start_wave [wave num]\n" ); return; } ASWHoldoutMode()->StartWave( atoi( args[1] ) ); } #endif // GAME_DLL void CASW_Holdout_Mode::LevelInitPostEntity() { #ifdef GAME_DLL LoadWaves(); SetThink( &CASW_Holdout_Mode::HoldoutThink ); SetNextThink( gpGlobals->curtime + 1.0f ); #endif } #ifdef CLIENT_DLL void CASW_Holdout_Mode::OnDataChanged(DataUpdateType_t updateType) { BaseClass::OnDataChanged( updateType ); if ( updateType == DATA_UPDATE_CREATED ) { LoadWaves(); } } #endif void CASW_Holdout_Mode::UpdateOnRemove() { BaseClass::UpdateOnRemove(); m_Waves.PurgeAndDeleteElements(); } void CASW_Holdout_Mode::LoadWaves() { m_Waves.PurgeAndDeleteElements(); if ( asw_holdout_debug.GetBool() ) { Msg( "CASW_Holdout_Mode::LoadWaves\n" ); } char tempfile[MAX_PATH]; Q_snprintf( tempfile, sizeof( tempfile ), "resource/holdout/%s.txt", m_netHoldoutFilename.Get() ); KeyValues *pKV = new KeyValues( "HoldoutWaves" ); if ( pKV ) { if ( !UTIL_RD_LoadKeyValuesFromFile( pKV, g_pFullFileSystem, tempfile, "GAME" ) ) { Warning( "Failed to load holdout resource file: '%s' Attempting to load default.\n", tempfile ); Q_snprintf( tempfile, sizeof( tempfile ), "resource/holdout/%s.txt", "HoldoutWaves_Default" ); if ( !UTIL_RD_LoadKeyValuesFromFile( pKV, g_pFullFileSystem, tempfile, "GAME" ) ) { Warning( "WARNING: Failed to load default holdout resource file. 'resource/holdout/HoldoutWaves_Default.txt' is missing!\n" ); pKV->deleteThis(); return; } } KeyValues *pKeys = pKV; while ( pKeys ) { if ( asw_holdout_debug.GetBool() ) { Msg( " Loading a wave\n" ); } CASW_Holdout_Wave *pWave = new CASW_Holdout_Wave; pWave->LoadFromKeyValues( m_Waves.Count(), pKeys ); m_Waves.AddToTail( pWave ); pKeys = pKeys->GetNextKey(); } pKV->deleteThis(); } } float CASW_Holdout_Mode::GetWaveProgress() { if ( GetCurrentWave() < 0 || GetCurrentWave() >= m_Waves.Count() ) return 1.0f; return 1.0f - ( (float) GetAliensKilledThisWave() / (float) m_Waves[ GetCurrentWave() ]->GetTotalAliens() ); }
1
0.985453
1
0.985453
game-dev
MEDIA
0.589636
game-dev
0.988554
1
0.988554
dufernst/LegionCore-7.3.5
17,808
src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp
/* * Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Ignis the Furnace Master SDAuthor: PrinceCreed SD%Complete: 100 EndScriptData */ #include "ulduar.h" #include "SpellAuraEffects.h" #include "Vehicle.h" enum Yells { SAY_AGGRO = -1603220, SAY_SLAY_1 = -1603221, SAY_SLAY_2 = -1603222, SAY_DEATH = -1603223, SAY_SUMMON = -1603224, SAY_SLAG_POT = -1603225, SAY_SCORCH_1 = -1603226, SAY_SCORCH_2 = -1603227, SAY_BERSERK = -1603228, EMOTE_JETS = -1603229 }; enum Spells { // Ignis SPELL_FLAME_JETS = 62680, SPELL_SCORCH = 62546, SPELL_SLAG_POT = 62717, SPELL_SLAG_IMBUED_10 = 62836, SPELL_SLAG_IMBUED_25 = 63536, SPELL_SLAG_POT_DAMAGE = 65722, SPELL_ACTIVATE_CONSTRUCT = 62488, SPELL_STRENGHT = 64473, SPELL_GRAB = 62707, SPELL_BERSERK = 47008, // Iron Construct SPELL_HEAT = 65667, SPELL_MOLTEN = 62373, SPELL_BRITTLE = 62382, SPELL_SHATTER = 62383, SPELL_FREEZE_ANIM = 63354, // Scorch Ground SPELL_SCORCH_GROUND = 62548 }; enum Events { EVENT_NONE, EVENT_JET, EVENT_SCORCH, EVENT_SLAG_POT, EVENT_GRAB_POT, EVENT_CHANGE_POT, EVENT_END_POT, EVENT_CONSTRUCT, EVENT_BERSERK }; enum Npcs { NPC_IRON_CONSTRUCT = 33121, NPC_SCORCH_GROUND = 33221 }; #define ACTION_REMOVE_BUFF 1 enum Achievements { ACHIEVEMENT_SHATTERED_10 = 2925, ACHIEVEMENT_SHATTERED_25 = 2926, ACHIEV_TIMED_START_EVENT = 20951, }; const Position Pos[20] = { {630.366f,216.772f,360.891f,M_PI}, {630.594f,231.846f,360.891f,M_PI}, {630.435f,337.246f,360.886f,M_PI}, {630.493f,313.349f,360.886f,M_PI}, {630.444f,321.406f,360.886f,M_PI}, {630.366f,247.307f,360.888f,M_PI}, {630.698f,305.311f,360.886f,M_PI}, {630.500f,224.559f,360.891f,M_PI}, {630.668f,239.840f,360.890f,M_PI}, {630.384f,329.585f,360.886f,M_PI}, {543.220f,313.451f,360.886f,0}, {543.356f,329.408f,360.886f,0}, {543.076f,247.458f,360.888f,0}, {543.117f,232.082f,360.891f,0}, {543.161f,305.956f,360.886f,0}, {543.277f,321.482f,360.886f,0}, {543.316f,337.468f,360.886f,0}, {543.280f,239.674f,360.890f,0}, {543.265f,217.147f,360.891f,0}, {543.256f,224.831f,360.891f,0} }; class boss_ignis : public CreatureScript { public: boss_ignis() : CreatureScript("boss_ignis") { } CreatureAI* GetAI(Creature* pCreature) const override { return new boss_ignis_AI (pCreature); } struct boss_ignis_AI : public BossAI { boss_ignis_AI(Creature *pCreature) : BossAI(pCreature, BOSS_IGNIS), vehicle(me->GetVehicleKit()) { me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true); } Vehicle* vehicle; std::vector<ObjectGuid> construct_list; ObjectGuid SlagPotGUID; uint32 ConstructTimer; uint8 ConstructVal; bool Shattered; void Reset() override { _Reset(); events.ScheduleEvent(EVENT_JET, 30000); events.ScheduleEvent(EVENT_SCORCH, 25000); events.ScheduleEvent(EVENT_SLAG_POT, 35000); events.ScheduleEvent(EVENT_CONSTRUCT, 15000); events.ScheduleEvent(EVENT_END_POT, 40000); events.ScheduleEvent(EVENT_BERSERK, 480000); me->SetReactState(REACT_DEFENSIVE); ConstructVal = 0; SlagPotGUID.Clear(); ConstructTimer = 0; Shattered = false; me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); if (instance) { instance->DoStopTimedAchievement(CRITERIA_TIMED_TYPE_EVENT2, ACHIEV_TIMED_START_EVENT); } construct_list.clear(); if (vehicle) vehicle->RemoveAllPassengers(); for (uint8 n = 0; n < 20; n++) { if (Creature* Construct = me->SummonCreature(NPC_IRON_CONSTRUCT, Pos[n], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3000)) construct_list.push_back(Construct->GetGUID()); } } void EnterCombat(Unit* /*who*/) override { _EnterCombat(); DoScriptText(SAY_AGGRO, me); SetCombatMovement(true); // Stokin' the Furnace if (instance) instance->DoStartTimedAchievement(CRITERIA_TIMED_TYPE_EVENT2, ACHIEV_TIMED_START_EVENT); } void JustDied(Unit* /*victim*/) override { _JustDied(); DoScriptText(SAY_DEATH, me); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; if (ConstructTimer) { if (ConstructTimer <= diff) { if (ConstructVal >= 2) { ConstructTimer = 0; ConstructVal = 0; Shattered = true; return; } else { ConstructTimer = 0; ConstructVal = 0; } } else ConstructTimer -= diff; } events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while(uint32 eventId = events.ExecuteEvent()) { switch(eventId) { case EVENT_JET: me->MonsterTextEmote(EMOTE_JETS, ObjectGuid::Empty, true); DoCastAOE(SPELL_FLAME_JETS); events.ScheduleEvent(EVENT_JET, urand(35000,40000)); break; case EVENT_SLAG_POT: if (Unit *pTarget = SelectTarget(SELECT_TARGET_RANDOM, 1, 100, true)) { DoScriptText(SAY_SLAG_POT, me); SlagPotGUID = pTarget->GetGUID(); DoCast(pTarget, SPELL_GRAB); events.DelayEvents(3000); events.ScheduleEvent(EVENT_GRAB_POT, 500); } events.ScheduleEvent(EVENT_SLAG_POT, RAID_MODE(30000, 15000)); break; case EVENT_GRAB_POT: if (Unit* SlagPotTarget = Unit::GetUnit(*me, SlagPotGUID)) { SlagPotTarget->EnterVehicle(me, 0); events.ScheduleEvent(EVENT_CHANGE_POT, 1000); } break; case EVENT_CHANGE_POT: if (Unit* SlagPotTarget = Unit::GetUnit(*me, SlagPotGUID)) { me->CastSpell(SlagPotTarget, SPELL_SLAG_POT, true); SlagPotTarget->ChangeSeat(1); events.ScheduleEvent(EVENT_END_POT, 10000); } break; case EVENT_END_POT: if (Unit* SlagPotTarget = Unit::GetUnit(*me, SlagPotGUID)) { SlagPotTarget->ExitVehicle(); SlagPotTarget = NULL; SlagPotGUID.Clear(); } break; case EVENT_SCORCH: DoScriptText(RAND(SAY_SCORCH_1, SAY_SCORCH_2), me); if (Unit *pTarget = me->getVictim()) me->SummonCreature(NPC_SCORCH_GROUND,pTarget->GetPositionX(),pTarget->GetPositionY(),pTarget->GetPositionZ(),0,TEMPSUMMON_TIMED_DESPAWN,45000); DoCast(SPELL_SCORCH); events.ScheduleEvent(EVENT_SCORCH, 25000); break; case EVENT_CONSTRUCT: if (!construct_list.empty()) { std::vector<ObjectGuid>::iterator itr = (construct_list.begin()+rand()%construct_list.size()); if (Creature* pTarget = me->GetMap()->GetCreature(*itr)) { DoScriptText(SAY_SUMMON, me); DoCast(me, SPELL_STRENGHT, true); DoCast(me, SPELL_ACTIVATE_CONSTRUCT); pTarget->setFaction(16); pTarget->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); construct_list.erase(itr); } } events.ScheduleEvent(EVENT_CONSTRUCT, RAID_MODE(40000, 30000)); break; case EVENT_BERSERK: DoCast(me, SPELL_BERSERK, true); DoScriptText(SAY_BERSERK, me); break; } } DoMeleeAttackIfReady(); } void KilledUnit(Unit* who) override { if (!(rand()%5)) DoScriptText(RAND(SAY_SLAY_1, SAY_SLAY_2), me); } void DoAction(const int32 action) override { switch(action) { case ACTION_REMOVE_BUFF: me->RemoveAuraFromStack(SPELL_STRENGHT); if (!ConstructTimer) ConstructTimer = 5000; ConstructVal++; break; } } bool isShattered() { return Shattered; } }; }; class npc_iron_construct : public CreatureScript { public: npc_iron_construct() : CreatureScript("npc_iron_construct") { } CreatureAI* GetAI(Creature* pCreature) const override { return new npc_iron_constructAI (pCreature); } struct npc_iron_constructAI : public ScriptedAI { npc_iron_constructAI(Creature *pCreature) : ScriptedAI(pCreature) { instance = pCreature->GetInstanceScript(); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED | UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); me->SetReactState(REACT_PASSIVE); me->AddAura(SPELL_FREEZE_ANIM, me); me->setFaction(35); } InstanceScript *instance; bool Brittled; void Reset() override { Brittled = false; } void DamageTaken(Unit* /*attacker*/, uint32 &damage, DamageEffectType dmgType) override { if (me->HasAura(SPELL_BRITTLE) && damage >= 5000) { DoCastAOE(SPELL_SHATTER, true); if (Creature *pIgnis = me->GetCreature(*me, instance->GetGuidData(DATA_IGNIS))) pIgnis->AI()->DoAction(ACTION_REMOVE_BUFF); me->DespawnOrUnsummon(1000); } } void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id == SPELL_ACTIVATE_CONSTRUCT && me->HasReactState(REACT_PASSIVE)) { me->SetReactState(REACT_AGGRESSIVE); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED | UNIT_FLAG_REMOVE_CLIENT_CONTROL); me->RemoveAurasDueToSpell(SPELL_FREEZE_ANIM); me->AI()->AttackStart(caster->getVictim()); me->AI()->DoZoneInCombat(); } } void UpdateAI(uint32 uiDiff) override { Map *cMap = me->GetMap(); if (me->HasAura(SPELL_MOLTEN) && me->HasAura(SPELL_HEAT)) me->RemoveAura(SPELL_HEAT); if (Aura * aur = me->GetAura((SPELL_HEAT))) { if (aur->GetStackAmount() >= 10) { me->RemoveAura(SPELL_HEAT); DoCast(me, SPELL_MOLTEN, true); Brittled = false; } } // Water pools if (me->IsInWater() && !Brittled && me->HasAura(SPELL_MOLTEN)) { me->AddAura(SPELL_BRITTLE, me); me->RemoveAura(SPELL_MOLTEN); Brittled = true; } DoMeleeAttackIfReady(); } }; }; class npc_scorch_ground : public CreatureScript { public: npc_scorch_ground() : CreatureScript("npc_scorch_ground") { } CreatureAI* GetAI(Creature* pCreature) const override { return new npc_scorch_groundAI (pCreature); } struct npc_scorch_groundAI : public Scripted_NoMovementAI { npc_scorch_groundAI(Creature* pCreature) : Scripted_NoMovementAI(pCreature) { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED); me->SetDisplayId(16925); } void Reset() override { DoCast(me, SPELL_SCORCH_GROUND); } }; }; class spell_ignis_slag_pot : public SpellScriptLoader { public: spell_ignis_slag_pot() : SpellScriptLoader("spell_ignis_slag_pot") { } class spell_ignis_slag_pot_AuraScript : public AuraScript { PrepareAuraScript(spell_ignis_slag_pot_AuraScript) bool Validate(SpellInfo const * /*SpellInfo*/) override { if (!sSpellStore.LookupEntry(SPELL_SLAG_POT_DAMAGE)) return false; if (!sSpellStore.LookupEntry(SPELL_SLAG_POT)) return false; if (!sSpellStore.LookupEntry(SPELL_SLAG_IMBUED_10)) return false; if (!sSpellStore.LookupEntry(SPELL_SLAG_IMBUED_25)) return false; return true; } void HandleEffectPeriodic(AuraEffect const * aurEff) { Unit* aurEffCaster = aurEff->GetCaster(); if (!aurEffCaster) return; Unit * target = GetTarget(); aurEffCaster->CastSpell(target, SPELL_SLAG_POT_DAMAGE, true); if (target->isAlive() && !GetDuration()) { if (aurEffCaster->GetMap()->GetDifficultyID() == DIFFICULTY_10_N) target->CastSpell(target, SPELL_SLAG_IMBUED_10, true); else if (aurEffCaster->GetMap()->GetDifficultyID() == DIFFICULTY_25_N) target->CastSpell(target, SPELL_SLAG_IMBUED_25, true); } } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_ignis_slag_pot_AuraScript::HandleEffectPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); } }; AuraScript* GetAuraScript() const override { return new spell_ignis_slag_pot_AuraScript(); } }; class achievement_shattered : public AchievementCriteriaScript { public: achievement_shattered() : AchievementCriteriaScript("achievement_shattered") { } bool OnCheck(Player* player, Unit* target) override { if (!target) return false; if (Creature * ignis = target->ToCreature()) if (boss_ignis::boss_ignis_AI* ignisAI = CAST_AI(boss_ignis::boss_ignis_AI, ignis->AI())) if (ignisAI->isShattered()) return true; return false; } }; void AddSC_boss_ignis() { new boss_ignis(); new npc_iron_construct(); new npc_scorch_ground(); new spell_ignis_slag_pot(); new achievement_shattered(); if (VehicleSeatEntry* vehSeat = const_cast<VehicleSeatEntry*>(sVehicleSeatStore.LookupEntry(3206))) vehSeat->Flags |= 0x400; }
1
0.94475
1
0.94475
game-dev
MEDIA
0.993445
game-dev
0.922822
1
0.922822
Admiral-Fish/PokeFinder
3,055
Core/Gen5/EncounterArea5.hpp
/* * This file is part of PokéFinder * Copyright (C) 2017-2024 by Admiral_Fish, bumba, and EzPzStreamz * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef ENCOUNTERAREA5_HPP #define ENCOUNTERAREA5_HPP #include <Core/Parents/EncounterArea.hpp> /** * @brief Contains information about the encounters for an area. This includes location, rate, and the slots. */ class EncounterArea5 : public EncounterArea { public: /** * @brief Construct a new EncounterArea5 object * * @param location Location number * @param rate Encounter rate of the area * @param season Whether encounter area has seasonal encounters * @param encounter Encounter type of the area * @param pokemon Available pokemon of the area */ EncounterArea5(u8 location, u8 rate, bool season, Encounter encounter, const std::array<Slot, 12> &pokemon) : EncounterArea(location, rate, encounter, pokemon), season(season) { } /** * @brief Calculates the level of a pokemon * * @param encounterSlot Pokemon index to use * @param prng Level RNG call * @param force Whether Pressure lead is being used * * @return Level of the encounter */ u8 calculateLevel(u8 encounterSlot, u8 prng, bool force) const { const Slot &slot = pokemon[encounterSlot]; u8 min = slot.getMinLevel(); u8 max = slot.getMaxLevel(); u8 range = max - min + 1; u8 level = min + (prng % range); if (force) { u8 max = level; for (u8 i = 0; i < pokemon.size() && pokemon[i].getSpecie() != 0; i++) { if (slot.getSpecie() == pokemon[i].getSpecie()) { max = std::max(max, pokemon[i].getMaxLevel()); } } if (range > 1 && (level + 5) <= max) { return level + 5; } else { return max; } } return level; } /** * @brief Returns if the encounter area has multiple seasonal differences * * @return true Differences based on the season * @return false No differences based on the season */ bool getSeason() const { return season; } private: bool season; }; #endif // ENCOUNTERAREA5_HPP
1
0.873479
1
0.873479
game-dev
MEDIA
0.883488
game-dev
0.855602
1
0.855602
MCreator-Examples/Tale-of-Biomes
2,060
src/main/java/net/nwtg/taleofbiomes/client/screens/SleepingEffect3Overlay.java
package net.nwtg.taleofbiomes.client.screens; import org.checkerframework.checker.units.qual.h; import net.nwtg.taleofbiomes.procedures.SleepingEffect3DisplayOverlayIngameProcedure; import net.neoforged.neoforge.client.event.RenderGuiEvent; import net.neoforged.fml.common.EventBusSubscriber; import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.bus.api.EventPriority; import net.neoforged.api.distmarker.Dist; import net.minecraft.world.level.Level; import net.minecraft.world.entity.player.Player; import net.minecraft.resources.ResourceLocation; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.Minecraft; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.platform.GlStateManager; @EventBusSubscriber({Dist.CLIENT}) public class SleepingEffect3Overlay { @SubscribeEvent(priority = EventPriority.NORMAL) public static void eventHandler(RenderGuiEvent.Pre event) { int w = event.getGuiGraphics().guiWidth(); int h = event.getGuiGraphics().guiHeight(); Level world = null; double x = 0; double y = 0; double z = 0; Player entity = Minecraft.getInstance().player; if (entity != null) { world = entity.level(); x = entity.getX(); y = entity.getY(); z = entity.getZ(); } RenderSystem.disableDepthTest(); RenderSystem.depthMask(false); RenderSystem.enableBlend(); RenderSystem.setShader(GameRenderer::getPositionTexShader); RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); RenderSystem.setShaderColor(1, 1, 1, 1); if (SleepingEffect3DisplayOverlayIngameProcedure.execute(world, entity)) { event.getGuiGraphics().blit(ResourceLocation.parse("tale_of_biomes:textures/screens/sleeping_effect_3.png"), 0, 0, 0, 0, w, h, w, h); } RenderSystem.depthMask(true); RenderSystem.defaultBlendFunc(); RenderSystem.enableDepthTest(); RenderSystem.disableBlend(); RenderSystem.setShaderColor(1, 1, 1, 1); } }
1
0.785706
1
0.785706
game-dev
MEDIA
0.923248
game-dev,graphics-rendering
0.956941
1
0.956941
flarialmc/dll
1,367
src/SDK/Client/Item/ItemStack.cpp
#include "ItemStack.hpp" #include <Utils/VersionUtils.hpp> #include <Utils/Memory/Game/SignatureAndOffsetManager.hpp> bool ItemStack::isValid() const { return item.counter != nullptr; } Item* ItemStack::getItem() const { return item.get(); } bool ItemStack::isEnchanted() { using isEnchantedFunc = bool(__fastcall*)(ItemStack*); static auto getIsEnchanted = reinterpret_cast<isEnchantedFunc>(GET_SIG_ADDRESS("ItemStack::isEnchanted")); return getIsEnchanted(this); } short ItemStack::getDamageValue() { if (item.counter == nullptr) return 0; if(VersionUtils::checkAboveOrEqual(21, 40)) { using getDamageValueFunc = short (__fastcall *)(ItemStack *); static auto getDamageValue = reinterpret_cast<getDamageValueFunc>(GET_SIG_ADDRESS("ItemStack::getDamageValue")); return getDamageValue(this); } else { using getDamageValueFunc = short (__fastcall *)(Item *, void *); static auto getDamageValue = reinterpret_cast<getDamageValueFunc>(GET_SIG_ADDRESS("Item::getDamageValue")); return getDamageValue(this->item.get(), this->tag); } } short ItemStack::getMaxDamage() { using getMaxDamageFunc = short(__fastcall*)(ItemStack*); static auto getMaxDamage = reinterpret_cast<getMaxDamageFunc>(GET_SIG_ADDRESS("ItemStack::getMaxDamage")); return getMaxDamage(this); }
1
0.822557
1
0.822557
game-dev
MEDIA
0.676352
game-dev
0.83369
1
0.83369
etlegacy/etlegacy
49,246
src/renderer/tr_animation_mds.c
/* * Wolfenstein: Enemy Territory GPL Source Code * Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company. * * ET: Legacy * Copyright (C) 2012-2024 ET:Legacy team <mail@etlegacy.com> * * This file is part of ET: Legacy - http://www.etlegacy.com * * ET: Legacy 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. * * ET: Legacy 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 ET: Legacy. If not, see <http://www.gnu.org/licenses/>. * * In addition, Wolfenstein: Enemy Territory GPL Source Code is also * subject to certain additional terms. You should have received a copy * of these additional terms immediately following the terms and conditions * of the GNU General Public License which accompanied the source code. * If not, please request a copy in writing from id Software at the address below. * * id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. */ /** * @file renderer/tr_animation_mds.c */ #include "tr_local.h" /* All bones should be an identity orientation to display the mesh exactly as it is specified. For all other frames, the bones represent the transformation from the orientation of the bone in the base frame to the orientation in this frame. */ //#define HIGH_PRECISION_BONES // enable this for 32bit precision bones //#define DBG_PROFILE_BONES //----------------------------------------------------------------------------- // Static Vars, ugly but easiest (and fastest) means of seperating RB_SurfaceAnim // and R_CalcBones static float frontlerp, backlerp; static float torsoFrontlerp, torsoBacklerp; static int *triangles, *boneRefs; static int indexes; static glIndex_t *pIndexes; static int baseIndex, baseVertex, oldIndexes; static int numVerts; static mdsVertex_t *v; static mdsBoneFrame_t bones[MDS_MAX_BONES], rawBones[MDS_MAX_BONES], oldBones[MDS_MAX_BONES]; static char validBones[MDS_MAX_BONES]; static char newBones[MDS_MAX_BONES]; static mdsBoneFrame_t *bonePtr, *bone, *parentBone; static mdsBoneFrameCompressed_t *cBonePtr, *cTBonePtr, *cOldBonePtr, *cOldTBonePtr, *cBoneList, *cOldBoneList, *cBoneListTorso, *cOldBoneListTorso; static mdsBoneInfo_t *boneInfo, *thisBoneInfo, *parentBoneInfo; static mdsFrame_t *frame, *torsoFrame; static mdsFrame_t *oldFrame, *oldTorsoFrame; static int frameSize; static short *sh, *sh2; static float *pf; static vec3_t angles, tangles, torsoParentOffset, torsoAxis[3], tmpAxis[3]; static float *tempVert, *tempNormal; static vec3_t vec, v2, dir; static float diff, a1, a2; static int render_count; static float lodRadius, lodScale; static int *collapse_map, *pCollapseMap; static int collapse[MDS_MAX_VERTS], *pCollapse; static int p0, p1, p2; static qboolean isTorso, fullTorso; static vec4_t m1[4], m2[4]; static vec3_t t; static refEntity_t lastBoneEntity; static int totalrv, totalrt, totalv, totalt; //----------------------------------------------------------------------------- /** * @brief RB_ProjectRadius * @param[in] r * @param[in] location * @return */ static float RB_ProjectRadius(float r, vec3_t location) { float pr; float dist; float c; vec3_t p; float projected[4]; c = DotProduct(backEnd.viewParms.orientation.axis[0], backEnd.viewParms.orientation.origin); dist = DotProduct(backEnd.viewParms.orientation.axis[0], location) - c; if (dist <= 0) { return 0; } p[0] = 0; p[1] = Q_fabs(r); p[2] = -dist; projected[0] = p[0] * backEnd.viewParms.projectionMatrix[0] + p[1] * backEnd.viewParms.projectionMatrix[4] + p[2] * backEnd.viewParms.projectionMatrix[8] + backEnd.viewParms.projectionMatrix[12]; projected[1] = p[0] * backEnd.viewParms.projectionMatrix[1] + p[1] * backEnd.viewParms.projectionMatrix[5] + p[2] * backEnd.viewParms.projectionMatrix[9] + backEnd.viewParms.projectionMatrix[13]; projected[2] = p[0] * backEnd.viewParms.projectionMatrix[2] + p[1] * backEnd.viewParms.projectionMatrix[6] + p[2] * backEnd.viewParms.projectionMatrix[10] + backEnd.viewParms.projectionMatrix[14]; projected[3] = p[0] * backEnd.viewParms.projectionMatrix[3] + p[1] * backEnd.viewParms.projectionMatrix[7] + p[2] * backEnd.viewParms.projectionMatrix[11] + backEnd.viewParms.projectionMatrix[15]; pr = projected[1] / projected[3]; if (pr > 1.0f) { pr = 1.0f; } return pr; } /** * @brief R_CullModel * @param[in] header * @param[in] ent * @return */ static int R_CullModel(mdsHeader_t *header, trRefEntity_t *ent) { vec3_t bounds[2]; int i; int frameSize = (int) (sizeof(mdsFrame_t) - sizeof(mdsBoneFrameCompressed_t) + header->numBones * sizeof(mdsBoneFrameCompressed_t)); // compute frame pointers mdsFrame_t *newFrame = ( mdsFrame_t * )(( byte * ) header + header->ofsFrames + ent->e.frame * frameSize); mdsFrame_t *oldFrame = ( mdsFrame_t * )(( byte * ) header + header->ofsFrames + ent->e.oldframe * frameSize); // cull bounding sphere ONLY if this is not an upscaled entity if (!ent->e.nonNormalizedAxes) { if (ent->e.frame == ent->e.oldframe) { switch (R_CullLocalPointAndRadius(newFrame->localOrigin, newFrame->radius)) { case CULL_OUT: tr.pc.c_sphere_cull_md3_out++; return CULL_OUT; case CULL_IN: tr.pc.c_sphere_cull_md3_in++; return CULL_IN; case CULL_CLIP: tr.pc.c_sphere_cull_md3_clip++; break; } } else { int sphereCull, sphereCullB; sphereCull = R_CullLocalPointAndRadius(newFrame->localOrigin, newFrame->radius); if (newFrame == oldFrame) { sphereCullB = sphereCull; } else { sphereCullB = R_CullLocalPointAndRadius(oldFrame->localOrigin, oldFrame->radius); } if (sphereCull == sphereCullB) { if (sphereCull == CULL_OUT) { tr.pc.c_sphere_cull_md3_out++; return CULL_OUT; } else if (sphereCull == CULL_IN) { tr.pc.c_sphere_cull_md3_in++; return CULL_IN; } else { tr.pc.c_sphere_cull_md3_clip++; } } } } // calculate a bounding box in the current coordinate system for (i = 0 ; i < 3 ; i++) { bounds[0][i] = oldFrame->bounds[0][i] < newFrame->bounds[0][i] ? oldFrame->bounds[0][i] : newFrame->bounds[0][i]; bounds[1][i] = oldFrame->bounds[1][i] > newFrame->bounds[1][i] ? oldFrame->bounds[1][i] : newFrame->bounds[1][i]; } switch (R_CullLocalBox(bounds)) { case CULL_IN: tr.pc.c_box_cull_md3_in++; return CULL_IN; case CULL_CLIP: tr.pc.c_box_cull_md3_clip++; return CULL_CLIP; case CULL_OUT: default: tr.pc.c_box_cull_md3_out++; return CULL_OUT; } } /** * @brief RB_CalcMDSLod * @param[in] refent * @param[in] origin * @param[in] radius * @param[in] modelBias * @param[in] modelScale * @return */ float RB_CalcMDSLod(refEntity_t *refent, vec3_t origin, float radius, float modelBias, float modelScale) { float flod; float projectedRadius; // compute projected bounding sphere and use that as a criteria for selecting LOD projectedRadius = RB_ProjectRadius(radius, origin); if (projectedRadius != 0.f) { float lodScale = r_lodScale->value; // fudge factor since MDS uses a much smoother method of LOD // ri.Printf (PRINT_ALL, "projected radius: %f\n", projectedRadius); flod = projectedRadius * lodScale * modelScale; } else { // object intersects near view plane, e.g. view weapon flod = 1.0f; } if (refent->reFlags & REFLAG_FORCE_LOD) { flod *= 0.5f; } // like reflag_force_lod, but separate for the moment if (refent->reFlags & REFLAG_DEAD_LOD) { flod *= 0.8f; } flod -= 0.25f * (r_lodBias->value) + modelBias; if (flod < 0.0f) { flod = 0.0f; } else if (flod > 1.0f) { flod = 1.0f; } return flod; } /** * @brief R_ComputeFogNum * @param[in] header * @param[in] ent * @return */ static int R_ComputeFogNum(mdsHeader_t *header, trRefEntity_t *ent) { int i, j; fog_t *fog; mdsFrame_t *mdsFrame; vec3_t localOrigin; if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { return 0; } // FIXME: non-normalized axis issues mdsFrame = ( mdsFrame_t * )(( byte * ) header + header->ofsFrames + (sizeof(mdsFrame_t) + sizeof(mdsBoneFrameCompressed_t) * (header->numBones - 1)) * ent->e.frame); VectorAdd(ent->e.origin, mdsFrame->localOrigin, localOrigin); for (i = 1 ; i < tr.world->numfogs ; i++) { fog = &tr.world->fogs[i]; for (j = 0 ; j < 3 ; j++) { if (localOrigin[j] - mdsFrame->radius >= fog->bounds[1][j]) { break; } if (localOrigin[j] + mdsFrame->radius <= fog->bounds[0][j]) { break; } } if (j == 3) { return i; } } return 0; } /** * @brief R_AddAnimSurfaces * @param[in] ent */ void R_AddAnimSurfaces(trRefEntity_t *ent) { mdsHeader_t *header = tr.currentModel->model.mds; mdsSurface_t *surface; shader_t *shader = 0; int i, fogNum, cull; qboolean personalModel = (ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal; // don't add third_person objects if not in a portal // cull the entire model if merged bounding box of both frames // is outside the view frustum. cull = R_CullModel(header, ent); if (cull == CULL_OUT) { return; } // set up lighting now that we know we aren't culled if (!personalModel || r_shadows->integer > 1) { R_SetupEntityLighting(&tr.refdef, ent); } // see if we are in a fog volume fogNum = R_ComputeFogNum(header, ent); surface = ( mdsSurface_t * )((byte *)header + header->ofsSurfaces); for (i = 0 ; i < header->numSurfaces ; i++) { if (ent->e.customShader) { shader = R_GetShaderByHandle(ent->e.customShader); } else if (ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins) { skin_t *skin; int hash; int j; skin = R_GetSkinByHandle(ent->e.customSkin); // match the surface name to something in the skin file shader = tr.defaultShader; if (ent->e.renderfx & RF_BLINK) { char *s = va("%s_b", surface->name); // append '_b' for 'blink' hash = Com_HashKey(s, strlen(s)); for (j = 0 ; j < skin->numSurfaces ; j++) { if (hash != skin->surfaces[j].hash) { continue; } if (!strcmp(skin->surfaces[j].name, s)) { shader = skin->surfaces[j].shader; break; } } } if (shader == tr.defaultShader) // blink reference in skin was not found { hash = Com_HashKey(surface->name, sizeof(surface->name)); for (j = 0 ; j < skin->numSurfaces ; j++) { // the names have both been lowercased if (hash != skin->surfaces[j].hash) { continue; } if (!strcmp(skin->surfaces[j].name, surface->name)) { shader = skin->surfaces[j].shader; break; } } } if (shader == tr.defaultShader) { Ren_Developer("WARNING: no shader for surface %s in skin %s\n", surface->name, skin->name); } else if (shader->defaultShader) { Ren_Developer("WARNING: shader %s in skin %s not found\n", shader->name, skin->name); } } else { shader = R_GetShaderByHandle(surface->shaderIndex); } // don't add third_person objects if not viewing through a portal if (!personalModel) { R_AddDrawSurf((void *)surface, shader, fogNum, 0, 0); } surface = ( mdsSurface_t * )((byte *)surface + surface->ofsEnd); } } /** * @brief LocalMatrixTransformVector * @param[in] in * @param[in] mat * @param[out] out */ static ID_INLINE void LocalMatrixTransformVector(vec3_t in, vec3_t mat[3], vec3_t out) { out[0] = in[0] * mat[0][0] + in[1] * mat[0][1] + in[2] * mat[0][2]; out[1] = in[0] * mat[1][0] + in[1] * mat[1][1] + in[2] * mat[1][2]; out[2] = in[0] * mat[2][0] + in[1] * mat[2][1] + in[2] * mat[2][2]; } /* * @brief LocalMatrixTransformVectorTranslate * @param[in] in * @param[in] mat * @param[in] tr * @param[out] out * * @note Unused static ID_INLINE void LocalMatrixTransformVectorTranslate(vec3_t in, vec3_t mat[3], vec3_t tr, vec3_t out) { out[0] = in[0] * mat[0][0] + in[1] * mat[0][1] + in[2] * mat[0][2] + tr[0]; out[1] = in[0] * mat[1][0] + in[1] * mat[1][1] + in[2] * mat[1][2] + tr[1]; out[2] = in[0] * mat[2][0] + in[1] * mat[2][1] + in[2] * mat[2][2] + tr[2]; } */ /** * @brief LocalScaledMatrixTransformVector * @param[in] in * @param[in] s * @param[in] mat * @param[out] out */ static ID_INLINE void LocalScaledMatrixTransformVector(vec3_t in, float s, vec3_t mat[3], vec3_t out) { out[0] = (1.0f - s) * in[0] + s * (in[0] * mat[0][0] + in[1] * mat[0][1] + in[2] * mat[0][2]); out[1] = (1.0f - s) * in[1] + s * (in[0] * mat[1][0] + in[1] * mat[1][1] + in[2] * mat[1][2]); out[2] = (1.0f - s) * in[2] + s * (in[0] * mat[2][0] + in[1] * mat[2][1] + in[2] * mat[2][2]); } /* * @brief LocalScaledMatrixTransformVectorTranslate * @param[in] in * @param[in] s * @param[in] mat * @param[in] tr * @param[out] out * * @note Unused static ID_INLINE void LocalScaledMatrixTransformVectorTranslate(vec3_t in, float s, vec3_t mat[3], vec3_t tr, vec3_t out) { out[0] = (1.0f - s) * in[0] + s * (in[0] * mat[0][0] + in[1] * mat[0][1] + in[2] * mat[0][2] + tr[0]); out[1] = (1.0f - s) * in[1] + s * (in[0] * mat[1][0] + in[1] * mat[1][1] + in[2] * mat[1][2] + tr[1]); out[2] = (1.0f - s) * in[2] + s * (in[0] * mat[2][0] + in[1] * mat[2][1] + in[2] * mat[2][2] + tr[2]); } */ /* * @brief LocalScaledMatrixTransformVectorFullTranslate * @param[in] in * @param[in] s * @param[in] mat * @param[in] tr * @param[out] out * * @note Unused static ID_INLINE void LocalScaledMatrixTransformVectorFullTranslate(vec3_t in, float s, vec3_t mat[3], vec3_t tr, vec3_t out) { out[0] = (1.0f - s) * in[0] + s * (in[0] * mat[0][0] + in[1] * mat[0][1] + in[2] * mat[0][2]) + tr[0]; out[1] = (1.0f - s) * in[1] + s * (in[0] * mat[1][0] + in[1] * mat[1][1] + in[2] * mat[1][2]) + tr[1]; out[2] = (1.0f - s) * in[2] + s * (in[0] * mat[2][0] + in[1] * mat[2][1] + in[2] * mat[2][2]) + tr[2]; } */ /* * @brief LocalAddScaledMatrixTransformVectorFullTranslate * @param[in] in * @param[in] s * @param[in] mat * @param[in] tr * @param[out] out * * @note Unused static ID_INLINE void LocalAddScaledMatrixTransformVectorFullTranslate(vec3_t in, float s, vec3_t mat[3], vec3_t tr, vec3_t out) { out[0] += s * (in[0] * mat[0][0] + in[1] * mat[0][1] + in[2] * mat[0][2]) + tr[0]; out[1] += s * (in[0] * mat[1][0] + in[1] * mat[1][1] + in[2] * mat[1][2]) + tr[1]; out[2] += s * (in[0] * mat[2][0] + in[1] * mat[2][1] + in[2] * mat[2][2]) + tr[2]; } */ /** * @brief LocalAddScaledMatrixTransformVectorTranslate * @param[in] in * @param[in] s * @param[in] mat * @param[in] tr * @param[out] out */ static ID_INLINE void LocalAddScaledMatrixTransformVectorTranslate(vec3_t in, float s, vec3_t mat[3], vec3_t tr, vec3_t out) { out[0] += s * (in[0] * mat[0][0] + in[1] * mat[0][1] + in[2] * mat[0][2] + tr[0]); out[1] += s * (in[0] * mat[1][0] + in[1] * mat[1][1] + in[2] * mat[1][2] + tr[1]); out[2] += s * (in[0] * mat[2][0] + in[1] * mat[2][1] + in[2] * mat[2][2] + tr[2]); } /* * @brief LocalAddScaledMatrixTransformVector * @param[in] in * @param[in] s * @param[in] mat * @param[out] out * * @note Unused static ID_INLINE void LocalAddScaledMatrixTransformVector(vec3_t in, float s, vec3_t mat[3], vec3_t out) { out[0] += s * (in[0] * mat[0][0] + in[1] * mat[0][1] + in[2] * mat[0][2]); out[1] += s * (in[0] * mat[1][0] + in[1] * mat[1][1] + in[2] * mat[1][2]); out[2] += s * (in[0] * mat[2][0] + in[1] * mat[2][1] + in[2] * mat[2][2]); } */ static float LAVangle; static float sp, sy, cp, cy; /** * @brief LocalAngleVector * @param[in] angles * @param[out] forward */ static ID_INLINE void LocalAngleVector(vec3_t angles, vec3_t forward) { LAVangle = angles[YAW] * (M_TAU_F / 360); sy = sin(LAVangle); cy = cos(LAVangle); LAVangle = angles[PITCH] * (M_TAU_F / 360); sp = sin(LAVangle); cp = cos(LAVangle); forward[0] = cp * cy; forward[1] = cp * sy; forward[2] = -sp; } /** * @brief LocalVectorMA * @param[in] org * @param[in] dist * @param[in] vec * @param[out] out */ static ID_INLINE void LocalVectorMA(vec3_t org, float dist, vec3_t vec, vec3_t out) { out[0] = org[0] + dist * vec[0]; out[1] = org[1] + dist * vec[1]; out[2] = org[2] + dist * vec[2]; } #define ANGLES_SHORT_TO_FLOAT(pf, sh) { *(pf++) = SHORT2ANGLE(*(sh++)); *(pf++) = SHORT2ANGLE(*(sh++)); *(pf++) = SHORT2ANGLE(*(sh++)); } /** * @brief SLerp_Normal * @param[in] from * @param[in] to * @param[in] tt * @param[out] out */ static ID_INLINE void SLerp_Normal(vec3_t from, vec3_t to, float tt, vec3_t out) { float ft = 1.0f - tt; out[0] = from[0] * ft + to[0] * tt; out[1] = from[1] * ft + to[1] * tt; out[2] = from[2] * ft + to[2] * tt; VectorNormalize(out); } /* =============================================================================== 4x4 Matrices =============================================================================== */ /* * @brief Matrix4Multiply * @param[in] a * @param[in] b * @param[out] dst * * @note Unused static ID_INLINE void Matrix4Multiply(const vec4_t a[4], const vec4_t b[4], vec4_t dst[4]) { dst[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0] + a[0][2] * b[2][0] + a[0][3] * b[3][0]; dst[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1] + a[0][2] * b[2][1] + a[0][3] * b[3][1]; dst[0][2] = a[0][0] * b[0][2] + a[0][1] * b[1][2] + a[0][2] * b[2][2] + a[0][3] * b[3][2]; dst[0][3] = a[0][0] * b[0][3] + a[0][1] * b[1][3] + a[0][2] * b[2][3] + a[0][3] * b[3][3]; dst[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0] + a[1][2] * b[2][0] + a[1][3] * b[3][0]; dst[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1] + a[1][2] * b[2][1] + a[1][3] * b[3][1]; dst[1][2] = a[1][0] * b[0][2] + a[1][1] * b[1][2] + a[1][2] * b[2][2] + a[1][3] * b[3][2]; dst[1][3] = a[1][0] * b[0][3] + a[1][1] * b[1][3] + a[1][2] * b[2][3] + a[1][3] * b[3][3]; dst[2][0] = a[2][0] * b[0][0] + a[2][1] * b[1][0] + a[2][2] * b[2][0] + a[2][3] * b[3][0]; dst[2][1] = a[2][0] * b[0][1] + a[2][1] * b[1][1] + a[2][2] * b[2][1] + a[2][3] * b[3][1]; dst[2][2] = a[2][0] * b[0][2] + a[2][1] * b[1][2] + a[2][2] * b[2][2] + a[2][3] * b[3][2]; dst[2][3] = a[2][0] * b[0][3] + a[2][1] * b[1][3] + a[2][2] * b[2][3] + a[2][3] * b[3][3]; dst[3][0] = a[3][0] * b[0][0] + a[3][1] * b[1][0] + a[3][2] * b[2][0] + a[3][3] * b[3][0]; dst[3][1] = a[3][0] * b[0][1] + a[3][1] * b[1][1] + a[3][2] * b[2][1] + a[3][3] * b[3][1]; dst[3][2] = a[3][0] * b[0][2] + a[3][1] * b[1][2] + a[3][2] * b[2][2] + a[3][3] * b[3][2]; dst[3][3] = a[3][0] * b[0][3] + a[3][1] * b[1][3] + a[3][2] * b[2][3] + a[3][3] * b[3][3]; } */ /** * @brief Matrix4MultiplyInto3x3AndTranslation * @param[in] a * @param[in] b * @param[out] dst * @param[out] t * * @note const usage would require an explicit cast, non ANSI C * @see unix/const-arg.c */ static ID_INLINE void Matrix4MultiplyInto3x3AndTranslation(/*const*/ vec4_t a[4], /*const*/ vec4_t b[4], vec3_t dst[3], vec3_t t) { dst[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0] + a[0][2] * b[2][0] + a[0][3] * b[3][0]; dst[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1] + a[0][2] * b[2][1] + a[0][3] * b[3][1]; dst[0][2] = a[0][0] * b[0][2] + a[0][1] * b[1][2] + a[0][2] * b[2][2] + a[0][3] * b[3][2]; t[0] = a[0][0] * b[0][3] + a[0][1] * b[1][3] + a[0][2] * b[2][3] + a[0][3] * b[3][3]; dst[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0] + a[1][2] * b[2][0] + a[1][3] * b[3][0]; dst[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1] + a[1][2] * b[2][1] + a[1][3] * b[3][1]; dst[1][2] = a[1][0] * b[0][2] + a[1][1] * b[1][2] + a[1][2] * b[2][2] + a[1][3] * b[3][2]; t[1] = a[1][0] * b[0][3] + a[1][1] * b[1][3] + a[1][2] * b[2][3] + a[1][3] * b[3][3]; dst[2][0] = a[2][0] * b[0][0] + a[2][1] * b[1][0] + a[2][2] * b[2][0] + a[2][3] * b[3][0]; dst[2][1] = a[2][0] * b[0][1] + a[2][1] * b[1][1] + a[2][2] * b[2][1] + a[2][3] * b[3][1]; dst[2][2] = a[2][0] * b[0][2] + a[2][1] * b[1][2] + a[2][2] * b[2][2] + a[2][3] * b[3][2]; t[2] = a[2][0] * b[0][3] + a[2][1] * b[1][3] + a[2][2] * b[2][3] + a[2][3] * b[3][3]; } /* * @brief Matrix4Transpose * @param[in] matrix * @param[out] transpose * * @note Unused static ID_INLINE void Matrix4Transpose(const vec4_t matrix[4], vec4_t transpose[4]) { int i, j; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { transpose[i][j] = matrix[j][i]; } } } */ /* * @brief Matrix4FromAxis * @param[in] axis * @param[out] dst * * @note Unused static ID_INLINE void Matrix4FromAxis(const vec3_t axis[3], vec4_t dst[4]) { int i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { dst[i][j] = axis[i][j]; } dst[3][i] = 0; dst[i][3] = 0; } dst[3][3] = 1; } */ /* * @brief Matrix4FromScaledAxis * @param[in] axis * @param[in] scale * @param[out] dst * * @note Unused static ID_INLINE void Matrix4FromScaledAxis(const vec3_t axis[3], const float scale, vec4_t dst[4]) { int i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { dst[i][j] = scale * axis[i][j]; if (i == j) { dst[i][j] += 1.0f - scale; } } dst[3][i] = 0; dst[i][3] = 0; } dst[3][3] = 1; } */ /* * @brief Matrix4FromTranslation * @param[in] t * @param[out] dst * * @note Unused static ID_INLINE void Matrix4FromTranslation(const vec3_t t, vec4_t dst[4]) { int i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { if (i == j) { dst[i][j] = 1; } else { dst[i][j] = 0; } } dst[i][3] = t[i]; dst[3][i] = 0; } dst[3][3] = 1; } */ /** * @brief Can put an axis rotation followed by a translation directly into one matrix * @param[in] axis * @param[in] t * @param[out] dst * * @note const usage would require an explicit cast, non ANSI C * * @see unix/const-arg.c */ static ID_INLINE void Matrix4FromAxisPlusTranslation(/*const*/ vec3_t axis[3], const vec3_t t, vec4_t dst[4]) { int i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { dst[i][j] = axis[i][j]; } dst[3][i] = 0; dst[i][3] = t[i]; } dst[3][3] = 1; } /** * @brief Can put a scaled axis rotation followed by a translation directly into one matrix * @param[in] axis * @param[in] scale * @param[in] t * @param[out] dst * * @note const usage would require an explicit cast, non ANSI C * * @see unix/const-arg.c */ static ID_INLINE void Matrix4FromScaledAxisPlusTranslation(/*const*/ vec3_t axis[3], const float scale, const vec3_t t, vec4_t dst[4]) { int i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { dst[i][j] = scale * axis[i][j]; if (i == j) { dst[i][j] += 1.0f - scale; } } dst[3][i] = 0; dst[i][3] = t[i]; } dst[3][3] = 1; } /* * @brief Matrix4FromScale * @param[in] scale * @param[out ] dst * * @note Unused static ID_INLINE void Matrix4FromScale(const float scale, vec4_t dst[4]) { int i, j; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { if (i == j) { dst[i][j] = scale; } else { dst[i][j] = 0; } } } dst[3][3] = 1; } */ /* * @brief Matrix4TransformVector * @param[in] m * @param[in] src * @param[out] dst * * @note Unused static ID_INLINE void Matrix4TransformVector(const vec4_t m[4], const vec3_t src, vec3_t dst) { dst[0] = m[0][0] * src[0] + m[0][1] * src[1] + m[0][2] * src[2] + m[0][3]; dst[1] = m[1][0] * src[0] + m[1][1] * src[1] + m[1][2] * src[2] + m[1][3]; dst[2] = m[2][0] * src[0] + m[2][1] * src[1] + m[2][2] * src[2] + m[2][3]; } */ /* =============================================================================== 3x3 Matrices =============================================================================== */ /** * @brief Matrix3Transpose * @param[in] matrix * @param[out] transpose */ static ID_INLINE void Matrix3Transpose(const vec3_t matrix[3], vec3_t transpose[3]) { int i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { transpose[i][j] = matrix[j][i]; } } } /** * @brief R_CalcBone * @param[in] header * @param refent - unused * @param[in] boneNum */ void R_CalcBone(mdsHeader_t *header, const refEntity_t *refent, int boneNum) { thisBoneInfo = &boneInfo[boneNum]; if (thisBoneInfo->torsoWeight != 0.f) { cTBonePtr = &cBoneListTorso[boneNum]; isTorso = qtrue; if (thisBoneInfo->torsoWeight == 1.0f) { fullTorso = qtrue; } } else { isTorso = qfalse; fullTorso = qfalse; } cBonePtr = &cBoneList[boneNum]; bonePtr = &bones[boneNum]; // we can assume the parent has already been uncompressed for this frame + lerp if (thisBoneInfo->parent >= 0) { parentBone = &bones[thisBoneInfo->parent]; parentBoneInfo = &boneInfo[thisBoneInfo->parent]; } else { parentBone = NULL; parentBoneInfo = NULL; } #ifdef HIGH_PRECISION_BONES // rotation if (fullTorso) { VectorCopy(cTBonePtr->angles, angles); } else { VectorCopy(cBonePtr->angles, angles); if (isTorso) { VectorCopy(cTBonePtr->angles, tangles); // blend the angles together for (j = 0; j < 3; j++) { diff = tangles[j] - angles[j]; if (Q_fabs(diff) > 180) { diff = AngleNormalize180(diff); } angles[j] = angles[j] + thisBoneInfo->torsoWeight * diff; } } } #else // rotation if (fullTorso) { sh = (short *)cTBonePtr->angles; pf = angles; ANGLES_SHORT_TO_FLOAT(pf, sh); } else { sh = (short *)cBonePtr->angles; pf = angles; ANGLES_SHORT_TO_FLOAT(pf, sh); if (isTorso) { int j; sh = (short *)cTBonePtr->angles; pf = tangles; ANGLES_SHORT_TO_FLOAT(pf, sh); // blend the angles together for (j = 0; j < 3; j++) { diff = tangles[j] - angles[j]; if (Q_fabs(diff) > 180) { diff = AngleNormalize180(diff); } angles[j] = angles[j] + thisBoneInfo->torsoWeight * diff; } } } #endif AnglesToAxis(angles, bonePtr->matrix); // translation if (parentBone) { #ifdef HIGH_PRECISION_BONES if (fullTorso) { angles[0] = cTBonePtr->ofsAngles[0]; angles[1] = cTBonePtr->ofsAngles[1]; angles[2] = 0; LocalAngleVector(angles, vec); LocalVectorMA(parentBone->translation, thisBoneInfo->parentDist, vec, bonePtr->translation); } else { angles[0] = cBonePtr->ofsAngles[0]; angles[1] = cBonePtr->ofsAngles[1]; angles[2] = 0; LocalAngleVector(angles, vec); if (isTorso) { tangles[0] = cTBonePtr->ofsAngles[0]; tangles[1] = cTBonePtr->ofsAngles[1]; tangles[2] = 0; LocalAngleVector(tangles, v2); // blend the angles together SLerp_Normal(vec, v2, thisBoneInfo->torsoWeight, vec); LocalVectorMA(parentBone->translation, thisBoneInfo->parentDist, vec, bonePtr->translation); } else // legs bone { LocalVectorMA(parentBone->translation, thisBoneInfo->parentDist, vec, bonePtr->translation); } } #else if (fullTorso) { sh = (short *)cTBonePtr->ofsAngles; pf = angles; *(pf++) = SHORT2ANGLE(*(sh++)); *(pf++) = SHORT2ANGLE(*(sh++)); *(pf++) = 0; LocalAngleVector(angles, vec); LocalVectorMA(parentBone->translation, thisBoneInfo->parentDist, vec, bonePtr->translation); } else { sh = (short *)cBonePtr->ofsAngles; pf = angles; *(pf++) = SHORT2ANGLE(*(sh++)); *(pf++) = SHORT2ANGLE(*(sh++)); *(pf++) = 0; LocalAngleVector(angles, vec); if (isTorso) { sh = (short *)cTBonePtr->ofsAngles; pf = tangles; *(pf++) = SHORT2ANGLE(*(sh++)); *(pf++) = SHORT2ANGLE(*(sh++)); *(pf++) = 0; LocalAngleVector(tangles, v2); // blend the angles together SLerp_Normal(vec, v2, thisBoneInfo->torsoWeight, vec); LocalVectorMA(parentBone->translation, thisBoneInfo->parentDist, vec, bonePtr->translation); } else // legs bone { LocalVectorMA(parentBone->translation, thisBoneInfo->parentDist, vec, bonePtr->translation); } } #endif } else // just use the frame position { bonePtr->translation[0] = frame->parentOffset[0]; bonePtr->translation[1] = frame->parentOffset[1]; bonePtr->translation[2] = frame->parentOffset[2]; } if (boneNum == header->torsoParent) // this is the torsoParent { VectorCopy(bonePtr->translation, torsoParentOffset); } validBones[boneNum] = 1; rawBones[boneNum] = *bonePtr; newBones[boneNum] = 1; } /** * @brief R_CalcBoneLerp * @param[in] header * @param[in] refent * @param[in] boneNum */ void R_CalcBoneLerp(mdsHeader_t *header, const refEntity_t *refent, int boneNum) { if (!refent || !header || boneNum < 0 || boneNum >= MDS_MAX_BONES) { return; } thisBoneInfo = &boneInfo[boneNum]; if (!thisBoneInfo) { return; } if (thisBoneInfo->parent >= 0) { parentBone = &bones[thisBoneInfo->parent]; parentBoneInfo = &boneInfo[thisBoneInfo->parent]; } else { parentBone = NULL; parentBoneInfo = NULL; } if (thisBoneInfo->torsoWeight != 0.f) { cTBonePtr = &cBoneListTorso[boneNum]; cOldTBonePtr = &cOldBoneListTorso[boneNum]; isTorso = qtrue; if (thisBoneInfo->torsoWeight == 1.0f) { fullTorso = qtrue; } } else { isTorso = qfalse; fullTorso = qfalse; } cBonePtr = &cBoneList[boneNum]; cOldBonePtr = &cOldBoneList[boneNum]; bonePtr = &bones[boneNum]; newBones[boneNum] = 1; // rotation (take into account 170 to -170 lerps, which need to take the shortest route) if (fullTorso) { sh = (short *)cTBonePtr->angles; sh2 = (short *)cOldTBonePtr->angles; pf = angles; a1 = SHORT2ANGLE(*(sh++)); a2 = SHORT2ANGLE(*(sh2++)); diff = AngleNormalize180(a1 - a2); *(pf++) = a1 - torsoBacklerp * diff; a1 = SHORT2ANGLE(*(sh++)); a2 = SHORT2ANGLE(*(sh2++)); diff = AngleNormalize180(a1 - a2); *(pf++) = a1 - torsoBacklerp * diff; a1 = SHORT2ANGLE(*(sh++)); a2 = SHORT2ANGLE(*(sh2++)); diff = AngleNormalize180(a1 - a2); *(pf++) = a1 - torsoBacklerp * diff; } else { sh = (short *)cBonePtr->angles; sh2 = (short *)cOldBonePtr->angles; pf = angles; a1 = SHORT2ANGLE(*(sh++)); a2 = SHORT2ANGLE(*(sh2++)); diff = AngleNormalize180(a1 - a2); *(pf++) = a1 - backlerp * diff; a1 = SHORT2ANGLE(*(sh++)); a2 = SHORT2ANGLE(*(sh2++)); diff = AngleNormalize180(a1 - a2); *(pf++) = a1 - backlerp * diff; a1 = SHORT2ANGLE(*(sh++)); a2 = SHORT2ANGLE(*(sh2++)); diff = AngleNormalize180(a1 - a2); *(pf++) = a1 - backlerp * diff; if (isTorso) { int j; sh = (short *)cTBonePtr->angles; sh2 = (short *)cOldTBonePtr->angles; pf = tangles; a1 = SHORT2ANGLE(*(sh++)); a2 = SHORT2ANGLE(*(sh2++)); diff = AngleNormalize180(a1 - a2); *(pf++) = a1 - torsoBacklerp * diff; a1 = SHORT2ANGLE(*(sh++)); a2 = SHORT2ANGLE(*(sh2++)); diff = AngleNormalize180(a1 - a2); *(pf++) = a1 - torsoBacklerp * diff; a1 = SHORT2ANGLE(*(sh++)); a2 = SHORT2ANGLE(*(sh2++)); diff = AngleNormalize180(a1 - a2); *(pf++) = a1 - torsoBacklerp * diff; // blend the angles together for (j = 0; j < 3; j++) { diff = tangles[j] - angles[j]; if (Q_fabs(diff) > 180) { diff = AngleNormalize180(diff); } angles[j] = angles[j] + thisBoneInfo->torsoWeight * diff; } } } AnglesToAxis(angles, bonePtr->matrix); if (parentBone) { if (fullTorso) { sh = (short *)cTBonePtr->ofsAngles; sh2 = (short *)cOldTBonePtr->ofsAngles; } else { sh = (short *)cBonePtr->ofsAngles; sh2 = (short *)cOldBonePtr->ofsAngles; } pf = angles; *(pf++) = SHORT2ANGLE(*(sh++)); *(pf++) = SHORT2ANGLE(*(sh++)); *(pf++) = 0; LocalAngleVector(angles, v2); // new pf = angles; *(pf++) = SHORT2ANGLE(*(sh2++)); *(pf++) = SHORT2ANGLE(*(sh2++)); *(pf++) = 0; LocalAngleVector(angles, vec); // old // blend the angles together if (fullTorso) { SLerp_Normal(vec, v2, torsoFrontlerp, dir); } else { SLerp_Normal(vec, v2, frontlerp, dir); } // translation if (!fullTorso && isTorso) // partial legs/torso, need to lerp according to torsoWeight { // calc the torso frame sh = (short *)cTBonePtr->ofsAngles; sh2 = (short *)cOldTBonePtr->ofsAngles; pf = angles; *(pf++) = SHORT2ANGLE(*(sh++)); *(pf++) = SHORT2ANGLE(*(sh++)); *(pf++) = 0; LocalAngleVector(angles, v2); // new pf = angles; *(pf++) = SHORT2ANGLE(*(sh2++)); *(pf++) = SHORT2ANGLE(*(sh2++)); *(pf++) = 0; LocalAngleVector(angles, vec); // old // blend the angles together SLerp_Normal(vec, v2, torsoFrontlerp, v2); // blend the torso/legs together SLerp_Normal(dir, v2, thisBoneInfo->torsoWeight, dir); } LocalVectorMA(parentBone->translation, thisBoneInfo->parentDist, dir, bonePtr->translation); } else // just interpolate the frame positions { bonePtr->translation[0] = frontlerp * frame->parentOffset[0] + backlerp * oldFrame->parentOffset[0]; bonePtr->translation[1] = frontlerp * frame->parentOffset[1] + backlerp * oldFrame->parentOffset[1]; bonePtr->translation[2] = frontlerp * frame->parentOffset[2] + backlerp * oldFrame->parentOffset[2]; } if (boneNum == header->torsoParent) // this is the torsoParent { VectorCopy(bonePtr->translation, torsoParentOffset); } validBones[boneNum] = 1; rawBones[boneNum] = *bonePtr; newBones[boneNum] = 1; } /** * @brief R_CalcBones * @param[in] header * @param[in] refent * @param[in,out] boneList This list should only be built and modified from within here * @param[in] numBones */ void R_CalcBones(mdsHeader_t *header, const refEntity_t *refent, int *boneList, int numBones) { int i; int *boneRefs; float torsoWeight; // if the entity has changed since the last time the bones were built, reset them if (memcmp(&lastBoneEntity, refent, sizeof(refEntity_t))) { // different, cached bones are not valid Com_Memset(validBones, 0, header->numBones); lastBoneEntity = *refent; // (SA) also reset these counter statics //----(SA) print stats for the complete model (not per-surface) if (r_bonesDebug->integer == 4 && totalrt) { Ren_Print("Lod %.2f verts %4d/%4d tris %4d/%4d (%.2f%%)\n", lodScale, totalrv, totalv, totalrt, totalt, ( float )(100.0 * totalrt) / (float) totalt); } totalrv = totalrt = totalv = totalt = 0; } Com_Memset(newBones, 0, header->numBones); if (refent->oldframe == refent->frame) { backlerp = 0; frontlerp = 1; } else { backlerp = refent->backlerp; frontlerp = 1.0f - backlerp; } if (refent->oldTorsoFrame == refent->torsoFrame) { torsoBacklerp = 0; torsoFrontlerp = 1; } else { torsoBacklerp = refent->torsoBacklerp; torsoFrontlerp = 1.0f - torsoBacklerp; } frameSize = (int) (sizeof(mdsFrame_t) + (header->numBones - 1) * sizeof(mdsBoneFrameCompressed_t)); frame = ( mdsFrame_t * )((byte *)header + header->ofsFrames + refent->frame * frameSize); torsoFrame = ( mdsFrame_t * )((byte *)header + header->ofsFrames + refent->torsoFrame * frameSize); oldFrame = ( mdsFrame_t * )((byte *)header + header->ofsFrames + refent->oldframe * frameSize); oldTorsoFrame = ( mdsFrame_t * )((byte *)header + header->ofsFrames + refent->oldTorsoFrame * frameSize); // lerp all the needed bones (torsoParent is always the first bone in the list) cBoneList = frame->bones; cBoneListTorso = torsoFrame->bones; boneInfo = ( mdsBoneInfo_t * )((byte *)header + header->ofsBones); boneRefs = boneList; // Matrix3Transpose(refent->torsoAxis, torsoAxis); #ifdef HIGH_PRECISION_BONES if (qtrue) { #else if (backlerp == 0.f && torsoBacklerp == 0.f) { #endif for (i = 0; i < numBones; i++, boneRefs++) { if (validBones[*boneRefs]) { // this bone is still in the cache bones[*boneRefs] = rawBones[*boneRefs]; continue; } // find our parent, and make sure it has been calculated if ((boneInfo[*boneRefs].parent >= 0) && (!validBones[boneInfo[*boneRefs].parent] && !newBones[boneInfo[*boneRefs].parent])) { R_CalcBone(header, refent, boneInfo[*boneRefs].parent); } R_CalcBone(header, refent, *boneRefs); } } else // interpolated { cOldBoneList = oldFrame->bones; cOldBoneListTorso = oldTorsoFrame->bones; for (i = 0; i < numBones; i++, boneRefs++) { if (validBones[*boneRefs]) { // this bone is still in the cache bones[*boneRefs] = rawBones[*boneRefs]; continue; } // find our parent, and make sure it has been calculated if ((boneInfo[*boneRefs].parent >= 0) && (!validBones[boneInfo[*boneRefs].parent] && !newBones[boneInfo[*boneRefs].parent])) { R_CalcBoneLerp(header, refent, boneInfo[*boneRefs].parent); } R_CalcBoneLerp(header, refent, *boneRefs); } } // adjust for torso rotations torsoWeight = 0; boneRefs = boneList; for (i = 0; i < numBones; i++, boneRefs++) { thisBoneInfo = &boneInfo[*boneRefs]; bonePtr = &bones[*boneRefs]; // add torso rotation if (thisBoneInfo->torsoWeight > 0) { if (!newBones[*boneRefs]) { // just copy it back from the previous calc bones[*boneRefs] = oldBones[*boneRefs]; continue; } if (!(thisBoneInfo->flags & BONEFLAG_TAG)) { // 1st multiply with the bone->matrix // 2nd translation for rotation relative to bone around torso parent offset VectorSubtract(bonePtr->translation, torsoParentOffset, t); Matrix4FromAxisPlusTranslation(bonePtr->matrix, t, m1); // 3rd scaled rotation // 4th translate back to torso parent offset // use previously created matrix if available for the same weight if (torsoWeight != thisBoneInfo->torsoWeight) { Matrix4FromScaledAxisPlusTranslation(torsoAxis, thisBoneInfo->torsoWeight, torsoParentOffset, m2); torsoWeight = thisBoneInfo->torsoWeight; } // multiply matrices to create one matrix to do all calculations Matrix4MultiplyInto3x3AndTranslation(m2, m1, bonePtr->matrix, bonePtr->translation); } else // tag's require special handling { // rotate each of the axis by the torsoAngles LocalScaledMatrixTransformVector(bonePtr->matrix[0], thisBoneInfo->torsoWeight, torsoAxis, tmpAxis[0]); LocalScaledMatrixTransformVector(bonePtr->matrix[1], thisBoneInfo->torsoWeight, torsoAxis, tmpAxis[1]); LocalScaledMatrixTransformVector(bonePtr->matrix[2], thisBoneInfo->torsoWeight, torsoAxis, tmpAxis[2]); Com_Memcpy(bonePtr->matrix, tmpAxis, sizeof(tmpAxis)); // rotate the translation around the torsoParent VectorSubtract(bonePtr->translation, torsoParentOffset, t); LocalScaledMatrixTransformVector(t, thisBoneInfo->torsoWeight, torsoAxis, bonePtr->translation); VectorAdd(bonePtr->translation, torsoParentOffset, bonePtr->translation); } } } // backup the final bones Com_Memcpy(oldBones, bones, sizeof(bones[0]) * header->numBones); } #ifdef DBG_PROFILE_BONES #define DBG_SHOWTIME Ren_Print("%i: %i, ", di++, (dt = ri.Milliseconds()) - ldt); ldt = dt; #else #define DBG_SHOWTIME ; #endif /** * @brief RB_SurfaceAnim * @param[in] surface */ void RB_SurfaceAnim(mdsSurface_t *surface) { int j, k; refEntity_t *refent; int *boneList; mdsHeader_t *header; #ifdef DBG_PROFILE_BONES int di = 0, dt, ldt; dt = ri.Milliseconds(); ldt = dt; #endif refent = &backEnd.currentEntity->e; boneList = ( int * )((byte *)surface + surface->ofsBoneReferences); header = ( mdsHeader_t * )((byte *)surface + surface->ofsHeader); R_CalcBones(header, (const refEntity_t *)refent, boneList, surface->numBoneReferences); DBG_SHOWTIME // calculate LOD // TODO: lerp the radius and origin VectorAdd(refent->origin, frame->localOrigin, vec); lodRadius = frame->radius; lodScale = RB_CalcMDSLod(refent, vec, lodRadius, header->lodBias, header->lodScale); //DBG_SHOWTIME // modification to allow dead skeletal bodies to go below minlod (experiment) if (refent->reFlags & REFLAG_DEAD_LOD) { if (lodScale < 0.35f) // allow dead to lod down to 35% (even if below surf->minLod) (%35 is arbitrary and probably not good generally. worked for the blackguard/infantry as a test though) { lodScale = 0.35f; } render_count = round(surface->numVerts * lodScale); } else { render_count = round(surface->numVerts * lodScale); if (render_count < surface->minLod) { if (!(refent->reFlags & REFLAG_DEAD_LOD)) { render_count = surface->minLod; } } } if (render_count > surface->numVerts) { render_count = surface->numVerts; } RB_CheckOverflow(render_count, surface->numTriangles * 3); //DBG_SHOWTIME // setup triangle list //DBG_SHOWTIME collapse_map = ( int * )(( byte * )surface + surface->ofsCollapseMap); triangles = ( int * )((byte *)surface + surface->ofsTriangles); indexes = surface->numTriangles * 3; baseIndex = tess.numIndexes; baseVertex = tess.numVertexes; oldIndexes = baseIndex; tess.numVertexes += render_count; pIndexes = &tess.indexes[baseIndex]; //DBG_SHOWTIME if (render_count == surface->numVerts) { for (j = 0; j < indexes; j++) { pIndexes[j] = triangles[j] + baseVertex; } tess.numIndexes += indexes; } else { int *collapseEnd; pCollapse = collapse; for (j = 0; j < render_count; pCollapse++, j++) { *pCollapse = j; } pCollapseMap = &collapse_map[render_count]; for (collapseEnd = collapse + surface->numVerts ; pCollapse < collapseEnd; pCollapse++, pCollapseMap++) { *pCollapse = collapse[*pCollapseMap]; } for (j = 0 ; j < indexes ; j += 3) { p0 = collapse[*(triangles++)]; p1 = collapse[*(triangles++)]; p2 = collapse[*(triangles++)]; // FIXME // note: serious optimization opportunity here, // by sorting the triangles the following "continue" // could have been made into a "break" statement. if (p0 == p1 || p1 == p2 || p2 == p0) { continue; } *(pIndexes++) = baseVertex + p0; *(pIndexes++) = baseVertex + p1; *(pIndexes++) = baseVertex + p2; tess.numIndexes += 3; } baseIndex = tess.numIndexes; } //DBG_SHOWTIME // deform the vertexes by the lerped bones numVerts = surface->numVerts; v = ( mdsVertex_t * )((byte *)surface + surface->ofsVerts); tempVert = ( float * )(tess.xyz + baseVertex); tempNormal = ( float * )(tess.normal + baseVertex); for (j = 0; j < render_count; j++, tempVert += 4, tempNormal += 4) { mdsWeight_t *w; VectorClear(tempVert); w = v->weights; for (k = 0 ; k < v->numWeights ; k++, w++) { bone = &bones[w->boneIndex]; LocalAddScaledMatrixTransformVectorTranslate(w->offset, w->boneWeight, bone->matrix, bone->translation, tempVert); } LocalMatrixTransformVector(v->normal, bones[v->weights[0].boneIndex].matrix, tempNormal); tess.texCoords[baseVertex + j][0][0] = v->texCoords[0]; tess.texCoords[baseVertex + j][0][1] = v->texCoords[1]; v = (mdsVertex_t *)&v->weights[v->numWeights]; } DBG_SHOWTIME if (r_bonesDebug->integer) { if (r_bonesDebug->integer < 3) { int i; // DEBUG: show the bones as a stick figure with axis at each bone boneRefs = ( int * )((byte *)surface + surface->ofsBoneReferences); for (i = 0; i < surface->numBoneReferences; i++, boneRefs++) { bonePtr = &bones[*boneRefs]; GL_Bind(tr.whiteImage); glLineWidth(1); glBegin(GL_LINES); for (j = 0; j < 3; j++) { VectorClear(vec); vec[j] = 1; glColor3fv(vec); glVertex3fv(bonePtr->translation); VectorMA(bonePtr->translation, 5, bonePtr->matrix[j], vec); glVertex3fv(vec); } glEnd(); // connect to our parent if it's valid if (validBones[boneInfo[*boneRefs].parent]) { glLineWidth(2); glBegin(GL_LINES); glColor3f(.6f, .6f, .6f); glVertex3fv(bonePtr->translation); glVertex3fv(bones[boneInfo[*boneRefs].parent].translation); glEnd(); } glLineWidth(1); } } if (r_bonesDebug->integer == 3 || r_bonesDebug->integer == 4) { int render_indexes = (tess.numIndexes - oldIndexes); // show mesh edges tempVert = ( float * )(tess.xyz + baseVertex); tempNormal = ( float * )(tess.normal + baseVertex); GL_Bind(tr.whiteImage); glLineWidth(1); glBegin(GL_LINES); glColor3f(.0f, .0f, .8f); pIndexes = &tess.indexes[oldIndexes]; for (j = 0; j < render_indexes / 3; j++, pIndexes += 3) { glVertex3fv(tempVert + 4 * pIndexes[0]); glVertex3fv(tempVert + 4 * pIndexes[1]); glVertex3fv(tempVert + 4 * pIndexes[1]); glVertex3fv(tempVert + 4 * pIndexes[2]); glVertex3fv(tempVert + 4 * pIndexes[2]); glVertex3fv(tempVert + 4 * pIndexes[0]); } glEnd(); // track debug stats if (r_bonesDebug->integer == 4) { totalrv += render_count; totalrt += render_indexes / 3; totalv += surface->numVerts; totalt += surface->numTriangles; } if (r_bonesDebug->integer == 3) { Ren_Print("Lod %.2f verts %4d/%4d tris %4d/%4d (%.2f%%)\n", lodScale, render_count, surface->numVerts, render_indexes / 3, surface->numTriangles, (100.0 * render_indexes / 3) / (double) surface->numTriangles); } } } if (r_bonesDebug->integer > 1) { // dont draw the actual surface tess.numIndexes = oldIndexes; tess.numVertexes = baseVertex; return; } #ifdef DBG_PROFILE_BONES Ren_Print("\n"); #endif } /** * @brief R_RecursiveBoneListAdd * @param[in] bi * @param[in,out] boneList * @param[in,out] numBones * @param[in] boneInfoList */ void R_RecursiveBoneListAdd(int bi, int *boneList, int *numBones, mdsBoneInfo_t *boneInfoList) { if (boneInfoList[bi].parent >= 0) { R_RecursiveBoneListAdd(boneInfoList[bi].parent, boneList, numBones, boneInfoList); } boneList[(*numBones)++] = bi; } /** * @brief R_GetBoneTag * @param[out] outTag * @param[in] mds * @param[in] startTagIndex * @param[in] refent * @param[in] tagName * @return */ int R_GetBoneTag(orientation_t *outTag, mdsHeader_t *mds, int startTagIndex, const refEntity_t *refent, const char *tagName) { int i; mdsTag_t *pTag; mdsBoneInfo_t *boneInfoList; int boneList[MDS_MAX_BONES]; int numBones; if (startTagIndex > mds->numTags) { Com_Memset(outTag, 0, sizeof(*outTag)); return -1; } // find the correct tag pTag = ( mdsTag_t * )((byte *)mds + mds->ofsTags); pTag += startTagIndex; for (i = startTagIndex; i < mds->numTags; i++, pTag++) { if (!strcmp(pTag->name, tagName)) { break; } } if (i >= mds->numTags) { Com_Memset(outTag, 0, sizeof(*outTag)); return -1; } // now build the list of bones we need to calc to get this tag's bone information boneInfoList = ( mdsBoneInfo_t * )((byte *)mds + mds->ofsBones); numBones = 0; R_RecursiveBoneListAdd(pTag->boneIndex, boneList, &numBones, boneInfoList); // calc the bones R_CalcBones((mdsHeader_t *)mds, refent, boneList, numBones); // now extract the orientation for the bone that represents our tag Com_Memcpy(outTag->axis, bones[pTag->boneIndex].matrix, sizeof(outTag->axis)); VectorCopy(bones[pTag->boneIndex].translation, outTag->origin); /* code not functional, not in backend if (r_bonesDebug->integer == 4) { int j; // DEBUG: show the tag position/axis GL_Bind( tr.whiteImage ); glLineWidth( 2 ); glBegin( GL_LINES ); for (j=0; j<3; j++) { VectorClear(vec); vec[j] = 1; glColor3fv( vec ); glVertex3fv( outTag->origin ); VectorMA( outTag->origin, 8, outTag->axis[j], vec ); glVertex3fv( vec ); } glEnd(); glLineWidth( 1 ); } */ return i; }
1
0.980114
1
0.980114
game-dev
MEDIA
0.52925
game-dev
0.953532
1
0.953532
ValkyrienSkies/Valkyrien-Skies-2
2,530
common/src/main/java/org/valkyrienskies/mod/mixin/mod_compat/create/client/MixinSchematicTransformation.java
package org.valkyrienskies.mod.mixin.mod_compat.create.client; import dev.engine_room.flywheel.lib.transform.TransformStack; import com.mojang.blaze3d.vertex.PoseStack; import com.simibubi.create.content.schematics.client.SchematicTransformation; import net.createmod.catnip.animation.AnimationTickHolder; import net.createmod.catnip.math.VecHelper; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.world.phys.Vec3; 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.Redirect; import org.valkyrienskies.core.api.ships.Ship; import org.valkyrienskies.mod.common.VSClientGameUtils; import org.valkyrienskies.mod.common.VSGameUtilsKt; /** * SchematicTransformation is responsible for the render transform of the schematic preview * <p> * Create applies both the camera and schematic positions in the same operation, the latter of which does not respect ship-space. * This mixin redirects the operation and fixes it by extracting the position components from the argument. * I can't think of a better way to get around it. */ @Mixin(value = {SchematicTransformation.class}, remap = false) public abstract class MixinSchematicTransformation { @Shadow private BlockPos target; @Shadow private Vec3 chasingPos; @Shadow private Vec3 prevChasingPos; @Redirect( method = {"applyTransformations(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/world/phys/Vec3;)V"}, at = @At( value = "INVOKE", target = "Ldev/engine_room/flywheel/lib/transform/TransformStack;translate(Lnet/minecraft/world/phys/Vec3;)Ljava/lang/Object;", ordinal = 0 ), require = 0 ) private Object redirectTranslate(TransformStack instance, Vec3 orig) { PoseStack ms = (PoseStack)instance; Ship ship = VSGameUtilsKt.getShipObjectManagingPos(Minecraft.getInstance().level, target.getX(), target.getY(), target.getZ()); if (ship != null) { float pt = AnimationTickHolder.getPartialTicks(); Vec3 pos = VecHelper.lerp(pt, prevChasingPos, chasingPos); Vec3 camera = pos.subtract(orig); VSClientGameUtils.transformRenderWithShip(ship.getTransform(), ms, pos.x, pos.y, pos.z, camera.x, camera.y, camera.z); return instance; } else { return instance.translate(orig); } } }
1
0.876887
1
0.876887
game-dev
MEDIA
0.916412
game-dev
0.718289
1
0.718289
EQEmu/Server
6,070
zone/lua_group.cpp
#ifdef LUA_EQEMU #include "../common/data_verification.h" #include <luabind/luabind.hpp> #include <luabind/object.hpp> #include "groups.h" #include "masterentity.h" #include "lua_group.h" #include "lua_mob.h" #include "lua_client.h" #include "lua_npc.h" void Lua_Group::DisbandGroup() { Lua_Safe_Call_Void(); self->DisbandGroup(); } bool Lua_Group::IsGroupMember(const char* name) { Lua_Safe_Call_Bool(); return self->IsGroupMember(name); } bool Lua_Group::IsGroupMember(Lua_Mob c) { Lua_Safe_Call_Bool(); return self->IsGroupMember(c); } void Lua_Group::CastGroupSpell(Lua_Mob caster, int spell_id) { Lua_Safe_Call_Void(); self->CastGroupSpell(caster, spell_id); } void Lua_Group::SplitExp(uint64 exp, Lua_Mob other) { Lua_Safe_Call_Void(); self->SplitExp(ExpSource::Quest, exp, other); } void Lua_Group::GroupMessage(Lua_Mob sender, const char* message) { Lua_Safe_Call_Void(); self->GroupMessage(sender, Language::CommonTongue, Language::MaxValue, message); } void Lua_Group::GroupMessage(Lua_Mob sender, uint8 language, const char* message) { Lua_Safe_Call_Void(); self->GroupMessage(sender, language, Language::MaxValue, message); } uint32 Lua_Group::GetTotalGroupDamage(Lua_Mob other) { Lua_Safe_Call_Int(); return self->GetTotalGroupDamage(other); } void Lua_Group::SplitMoney(uint32 copper, uint32 silver, uint32 gold, uint32 platinum) { Lua_Safe_Call_Void(); self->SplitMoney(copper, silver, gold, platinum); } void Lua_Group::SplitMoney(uint32 copper, uint32 silver, uint32 gold, uint32 platinum, Lua_Client splitter) { Lua_Safe_Call_Void(); self->SplitMoney(copper, silver, gold, platinum, splitter); } void Lua_Group::SetLeader(Lua_Mob c) { Lua_Safe_Call_Void(); self->SetLeader(c); } Lua_Mob Lua_Group::GetLeader() { Lua_Safe_Call_Class(Lua_Mob); return self->GetLeader(); } std::string Lua_Group::GetLeaderName() { Lua_Safe_Call_String(); return self->GetLeaderName(); } bool Lua_Group::IsLeader(const char* name) { Lua_Safe_Call_Bool(); return self->IsLeader(name); } bool Lua_Group::IsLeader(Lua_Mob c) { Lua_Safe_Call_Bool(); return self->IsLeader(c); } int Lua_Group::GroupCount() { Lua_Safe_Call_Int(); return self->GroupCount(); } uint32 Lua_Group::GetHighestLevel() { Lua_Safe_Call_Int(); return self->GetHighestLevel(); } uint32 Lua_Group::GetLowestLevel() { Lua_Safe_Call_Int(); return self->GetLowestLevel(); } void Lua_Group::TeleportGroup(Lua_Mob sender, uint32 zone_id, uint32 instance_id, float x, float y, float z, float h) { Lua_Safe_Call_Void(); self->TeleportGroup(sender, zone_id, instance_id, x, y, z, h); } int Lua_Group::GetID() { Lua_Safe_Call_Int(); return self->GetID(); } Lua_Mob Lua_Group::GetMember(int member_index) { Lua_Safe_Call_Class(Lua_Mob); if (!EQ::ValueWithin(member_index, 0, 5)) { return Lua_Mob(); } return self->members[member_index]; } uint8 Lua_Group::GetMemberRole(Lua_Mob member) { Lua_Safe_Call_Int(); return self->GetMemberRole(member); } uint8 Lua_Group::GetMemberRole(const char* name) { Lua_Safe_Call_Int(); return self->GetMemberRole(name); } bool Lua_Group::DoesAnyMemberHaveExpeditionLockout(std::string expedition_name, std::string event_name) { Lua_Safe_Call_Bool(); return self->AnyMemberHasDzLockout(expedition_name, event_name); } bool Lua_Group::DoesAnyMemberHaveExpeditionLockout(std::string expedition_name, std::string event_name, int max_check_count) { Lua_Safe_Call_Bool(); return self->AnyMemberHasDzLockout(expedition_name, event_name); // max_check_count deprecated } uint32 Lua_Group::GetAverageLevel() { Lua_Safe_Call_Int(); return self->GetAvgLevel(); } luabind::scope lua_register_group() { return luabind::class_<Lua_Group>("Group") .def(luabind::constructor<>()) .property("null", &Lua_Group::Null) .property("valid", &Lua_Group::Valid) .def("CastGroupSpell", (void(Lua_Group::*)(Lua_Mob,int))&Lua_Group::CastGroupSpell) .def("DisbandGroup", (void(Lua_Group::*)(void))&Lua_Group::DisbandGroup) .def("DoesAnyMemberHaveExpeditionLockout", (bool(Lua_Group::*)(std::string, std::string))&Lua_Group::DoesAnyMemberHaveExpeditionLockout) .def("DoesAnyMemberHaveExpeditionLockout", (bool(Lua_Group::*)(std::string, std::string, int))&Lua_Group::DoesAnyMemberHaveExpeditionLockout) .def("GetAverageLevel", (uint32(Lua_Group::*)(void))&Lua_Group::GetAverageLevel) .def("GetHighestLevel", (uint32(Lua_Group::*)(void))&Lua_Group::GetHighestLevel) .def("GetID", (int(Lua_Group::*)(void))&Lua_Group::GetID) .def("GetLeader", (Lua_Mob(Lua_Group::*)(void))&Lua_Group::GetLeader) .def("GetLeaderName", (const char*(Lua_Group::*)(void))&Lua_Group::GetLeaderName) .def("GetLowestLevel", (uint32(Lua_Group::*)(void))&Lua_Group::GetLowestLevel) .def("GetMember", (Lua_Mob(Lua_Group::*)(int))&Lua_Group::GetMember) .def("GetMemberRole", (uint8(Lua_Group::*)(Lua_Mob))&Lua_Group::GetMemberRole) .def("GetMemberRole", (uint8(Lua_Group::*)(const char*))&Lua_Group::GetMemberRole) .def("GetTotalGroupDamage", (uint32(Lua_Group::*)(Lua_Mob))&Lua_Group::GetTotalGroupDamage) .def("GroupCount", (int(Lua_Group::*)(void))&Lua_Group::GroupCount) .def("GroupMessage", (void(Lua_Group::*)(Lua_Mob,const char*))&Lua_Group::GroupMessage) .def("GroupMessage", (void(Lua_Group::*)(Lua_Mob,uint8,const char*))&Lua_Group::GroupMessage) .def("IsGroupMember", (bool(Lua_Group::*)(const char*))&Lua_Group::IsGroupMember) .def("IsGroupMember", (bool(Lua_Group::*)(Lua_Mob))&Lua_Group::IsGroupMember) .def("IsLeader", (bool(Lua_Group::*)(const char*))&Lua_Group::IsLeader) .def("IsLeader", (bool(Lua_Group::*)(Lua_Mob))&Lua_Group::IsLeader) .def("SetLeader", (void(Lua_Group::*)(Lua_Mob))&Lua_Group::SetLeader) .def("SplitExp", (void(Lua_Group::*)(uint32,Lua_Mob))&Lua_Group::SplitExp) .def("SplitMoney", (void(Lua_Group::*)(uint32,uint32,uint32,uint32))&Lua_Group::SplitMoney) .def("SplitMoney", (void(Lua_Group::*)(uint32,uint32,uint32,uint32,Lua_Client))&Lua_Group::SplitMoney) .def("TeleportGroup", (void(Lua_Group::*)(Lua_Mob,uint32,uint32,float,float,float,float))&Lua_Group::TeleportGroup); } #endif
1
0.688843
1
0.688843
game-dev
MEDIA
0.783554
game-dev
0.807127
1
0.807127
Pascal-Jansen/Bayesian-Optimization-for-Unity
10,142
Assets/QuestionnaireToolkit/Editor/QTManagerEditor.cs
using System; using System.Collections; using System.Collections.Generic; using QuestionnaireToolkit.Editor; using QuestionnaireToolkit.Scripts; using UnityEditor; using UnityEngine; [CanEditMultipleObjects] [CustomEditor(typeof(QTManager))] public class QTManagerEditor : Editor { private SerializedProperty pageHeight; private SerializedProperty dynamicHeight; private SerializedProperty useCustomTransform; private SerializedProperty distanceToCamera; private SerializedProperty pageScaleFactor; private SerializedProperty pageBackgroundColor; private SerializedProperty pageBottomColor; private SerializedProperty highlightColor; private SerializedProperty sliderValue; private SerializedProperty showTopPanel; private SerializedProperty showBottomPanel; private SerializedProperty showPageNumber; private SerializedProperty showPrevButton; private ReorderableList questionnaires; private QTManager manager; private SerializedProperty displayMode; private SerializedProperty deviceType; private SerializedProperty orientation; private SerializedProperty colorScheme; private GUIStyle noteStyle; private Texture image; private Texture logo; void OnEnable() { noteStyle = new GUIStyle(); noteStyle.wordWrap = true; noteStyle.normal.textColor = Color.white; noteStyle.fontStyle = FontStyle.Bold; displayMode = serializedObject.FindProperty("displayMode"); orientation = serializedObject.FindProperty("orientation"); colorScheme = serializedObject.FindProperty("colorScheme"); deviceType = serializedObject.FindProperty("deviceType"); pageHeight = serializedObject.FindProperty("pageHeight"); dynamicHeight = serializedObject.FindProperty("dynamicHeight"); useCustomTransform = serializedObject.FindProperty("useCustomTransform"); distanceToCamera = serializedObject.FindProperty("distanceToCamera"); pageScaleFactor = serializedObject.FindProperty("pageScaleFactor"); pageBackgroundColor = serializedObject.FindProperty("pageBackgroundColor"); pageBottomColor = serializedObject.FindProperty("pageBottomColor"); highlightColor = serializedObject.FindProperty("highlightColor"); sliderValue = serializedObject.FindProperty("sliderValue"); showTopPanel = serializedObject.FindProperty("showTopPanel"); showBottomPanel = serializedObject.FindProperty("showBottomPanel"); showPageNumber = serializedObject.FindProperty("showPageNumber"); showPrevButton = serializedObject.FindProperty("showPrevButton"); questionnaires = new ReorderableList(serializedObject.FindProperty("questionnaires"), false, false, true); questionnaires.elementNameProperty = "Questionnaires"; manager = (QTManager) target; questionnaires.onChangedCallback += (list) => { manager.ReorderQuestionnaires(list.Length, list.Index); }; questionnaires.onSelectCallback += (list) => { manager.selectedQuestionnaire = list.Index; manager.ShowSelectedQuestionnaire(list.Index); }; questionnaires.onRemoveCallback += (list) => { var i = list.Index; list.RemoveItem(list.Index); manager.DeleteQuestionnaire(list.Length, i); }; image = AssetDatabase.LoadAssetAtPath<Texture>("Assets/QuestionnaireToolkit/Textures/Banner/ManagerBanner.png"); logo = AssetDatabase.LoadAssetAtPath<Texture>("Assets/QuestionnaireToolkit/Textures/QT_Logo_Mini2_Right.png"); } public override void OnInspectorGUI() { TagsAndLayers.RefreshQtTags(); // always keep tag list fresh! serializedObject.Update(); GUILayout.Space(5); var rect = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.Height(30)); EditorGUI.DrawRect(new Rect(rect.x, rect.y + 3f, rect.width, rect.height), new Color(0.0f, 0.125f, 0.376f, 1)); EditorGUI.DrawRect(new Rect(rect.x + 2, rect.y + 5, rect.width - 4f, rect.height - 4), Color.white); GUI.DrawTexture(new Rect(rect.x - 14, rect.y, 250, rect.height + 6f), image, ScaleMode.ScaleToFit); GUI.DrawTexture(new Rect(rect.x + rect.width - 50, rect.y + 4, 60, rect.height - 3), logo, ScaleMode.ScaleToFit); GUILayout.Space(5); GUILayout.Label("General Display Settings", EditorStyles.boldLabel); //manager.displayMode = (QuestionnaireManager.DisplayMode)EditorGUILayout.EnumPopup("Display Mode", manager.displayMode); EditorGUILayout.PropertyField(displayMode); if (manager.displayMode == QTManager.DisplayMode.VR) { EditorGUILayout.PropertyField(deviceType); } //manager.orientation = (QuestionnaireManager.Orientation)EditorGUILayout.EnumPopup("Orientation", manager.orientation); EditorGUILayout.PropertyField(orientation); GUILayout.BeginHorizontal(); GUILayout.Label("Dynamic Page Height", GUILayout.Width(EditorGUIUtility.labelWidth)); dynamicHeight.boolValue = EditorGUILayout.Toggle( dynamicHeight.boolValue); GUILayout.EndHorizontal(); if (!dynamicHeight.boolValue) { GUILayout.BeginHorizontal(); GUILayout.Label("Page Height", GUILayout.Width(EditorGUIUtility.labelWidth)); pageHeight.floatValue = EditorGUILayout.FloatField( pageHeight.floatValue); GUILayout.EndHorizontal(); } if (manager.displayMode == QTManager.DisplayMode.VR) { GUILayout.BeginHorizontal(); GUILayout.Label("Use Custom Transform", GUILayout.Width(EditorGUIUtility.labelWidth)); useCustomTransform.boolValue = EditorGUILayout.Toggle( useCustomTransform.boolValue); GUILayout.EndHorizontal(); if (!useCustomTransform.boolValue) { GUILayout.BeginHorizontal(); GUILayout.Label("Distance To Camera", GUILayout.Width(EditorGUIUtility.labelWidth)); distanceToCamera.floatValue = EditorGUILayout.FloatField( distanceToCamera.floatValue ); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Page Scale Factor", GUILayout.Width(EditorGUIUtility.labelWidth)); pageScaleFactor.floatValue = EditorGUILayout.FloatField( pageScaleFactor.floatValue ); GUILayout.EndHorizontal(); } } //manager.colorScheme = (QuestionnaireManager.ColorScheme)EditorGUILayout.EnumPopup("Color Scheme", manager.colorScheme); EditorGUILayout.PropertyField(colorScheme); if (manager.colorScheme == QTManager.ColorScheme.Custom) { pageBackgroundColor.colorValue = EditorGUILayout.ColorField("Page Background Color", pageBackgroundColor.colorValue); pageBottomColor.colorValue = EditorGUILayout.ColorField("Page Bottom Color", pageBottomColor.colorValue); highlightColor.colorValue = EditorGUILayout.ColorField("Highlight Color", highlightColor.colorValue); } GUILayout.BeginHorizontal(); GUILayout.Label("Background Transparency", GUILayout.Width(EditorGUIUtility.labelWidth)); sliderValue.floatValue = GUILayout.HorizontalSlider(sliderValue.floatValue, 0, 100); sliderValue.floatValue = EditorGUILayout.FloatField( Mathf.Round(sliderValue.floatValue), GUILayout.Width(EditorGUIUtility.fieldWidth)); GUILayout.EndHorizontal(); /* GUILayout.BeginHorizontal(); GUILayout.Label("Show Top Panel", GUILayout.Width(EditorGUIUtility.labelWidth)); showTopPanel.boolValue = EditorGUILayout.Toggle( showTopPanel.boolValue); GUILayout.EndHorizontal(); */ GUILayout.BeginHorizontal(); GUILayout.Label("Show Bottom Panel", GUILayout.Width(EditorGUIUtility.labelWidth)); showBottomPanel.boolValue = EditorGUILayout.Toggle( showBottomPanel.boolValue); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Show Page Number", GUILayout.Width(EditorGUIUtility.labelWidth)); showPageNumber.boolValue = EditorGUILayout.Toggle( showPageNumber.boolValue); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Show Prev Button", GUILayout.Width(EditorGUIUtility.labelWidth)); showPrevButton.boolValue = EditorGUILayout.Toggle( showPrevButton.boolValue); GUILayout.EndHorizontal(); GUILayout.Label("Questionnaire Management", EditorStyles.boldLabel); //draw the list using GUILayout, you can of course specify your own position and label questionnaires.DoLayoutList(); GUILayout.BeginHorizontal(); if (GUILayout.Button("Create Questionnaire")) { manager.CreateQuestionnaire(); } if (GUILayout.Button("Copy")) { manager.CopyQuestionnaire(); } if (GUILayout.Button(manager.selectedQuestionnaire > -1 && manager.selectedQuestionnaire < manager.questionnaires.Count ? "Delete (Element " + manager.selectedQuestionnaire + ")" : "Delete (Nothing selected)")) { manager.DeleteQuestionnaire(); } GUILayout.EndHorizontal(); EditorGUILayout.Space(); serializedObject.ApplyModifiedProperties(); } }
1
0.874909
1
0.874909
game-dev
MEDIA
0.851869
game-dev
0.839399
1
0.839399
Dimbreath/AzurLaneData
2,336
zh-CN/controller/command/technology/metacharacter/metacharactiveenergycommand.lua
slot0 = class("MetaCharActiveEnergyCommand", pm.SimpleCommand) function slot0.execute(slot0, slot1) if not getProxy(BayProxy):getShipById(slot1:getBody().shipId) then return end if not slot5:getMetaCharacter():getBreakOutInfo():getNextInfo() then return end slot9, slot10 = slot7:getLimited() if slot5.level < slot9 or slot6:getCurRepairExp() < slot10 then pg.TipsMgr.GetInstance():ShowTips("level or repair progress is not enough") return end slot11, slot12 = slot7:getConsume() if getProxy(PlayerProxy):getData().gold < slot11 then pg.TipsMgr.GetInstance():ShowTips("gold not enough") return end slot14 = getProxy(BagProxy) if _.any(slot12, function (slot0) return uv0:getItemCountById(slot0.itemId) < slot0.count end) then pg.TipsMgr.GetInstance():ShowTips("item not enough") return end print("63303 meta energy", slot5.id) pg.ConnectionMgr.GetInstance():Send(63303, { ship_id = slot5.id }, 63304, function (slot0) if slot0.result == 0 then print("63304 meta energy success", uv0.id) slot1 = Clone(uv0) uv1:updateStar(uv0, slot1.configId, uv2.id) uv3:updateShip(uv0) if getProxy(CollectionProxy):getShipGroup(slot1.groupId) then slot3.star = uv0:getStar() slot2:updateShipGroup(slot3) end slot7 = uv5 uv4:consume({ gold = slot7 }) getProxy(PlayerProxy):updatePlayer(uv4) for slot7, slot8 in pairs(uv6) do uv1:sendNotification(GAME.CONSUME_ITEM, Item.New({ count = slot8.count, id = slot8.itemId, type = DROP_TYPE_ITEM })) end getProxy(MetaCharacterProxy):getMetaProgressVOByID(uv7.id):updateShip(uv0) uv1:sendNotification(GAME.ENERGY_META_ACTIVATION_DONE, { newShip = uv0, oldShip = slot1 }) else pg.TipsMgr.GetInstance():ShowTips(errorTip("", slot0.result)) end end) end function slot0.updateStar(slot0, slot1, slot2, slot3) slot1.configId = slot3 for slot8, slot9 in ipairs(pg.ship_data_template[slot1.configId].buff_list) do if not slot1.skills[slot9] then slot1.skills[slot9] = { exp = 0, level = 1, id = slot9 } end end slot1:updateMaxLevel(slot4.max_level) for slot9, slot10 in ipairs(pg.ship_data_template[slot2].buff_list) do if not table.contains(slot4.buff_list, slot10) then slot1.skills[slot10] = nil end end end return slot0
1
0.814901
1
0.814901
game-dev
MEDIA
0.734252
game-dev
0.943625
1
0.943625
hiperbou/kotlin-phaser
1,546
examples/src/main/kotlin/examples/video/SnapshotBlendMode.kt
package examples.video import Phaser.* class SnapshotBlendMode: State() { //var game = Phaser.Game(800, 600, Phaser.CANVAS, "phaser-example", object{ var preload= preload; var create= create }) lateinit var video:Video lateinit var bmd:BitmapData var alpha:dynamic = object{ public var alpha = 0.2 } override fun preload() { game.load.image("swirl", "assets/pics/swirl1.jpg") } override fun create() { // No properties at all means we"ll create a video stream from a webcam video = game.add.video() // If access to the camera is allowed video.onAccess.add(this::camAllowed, this) // If access to the camera is denied video.onError.add(this::camBlocked, this) // Start the stream video.startMediaStream() } fun camAllowed() { bmd = game.add.bitmapData(video.width, video.height) bmd.addToWorld(game.world.centerX, game.world.centerY, 0.5, 0.5) // Grab a frame every 50ms game.time.events.loop(50, this::takeSnapshot, this) game.add.tween(alpha).to( object{ var alpha= 0.5 }, 1000, "Cubic.easeInOut", true, 0, -1, true) } fun camBlocked(video:Video, error:Any) { console.log("Camera was blocked", video, error) } fun takeSnapshot() { if (bmd.width !== video.width || bmd.height !== video.height) { bmd.resize(video.width, video.height) } video.grab(true, alpha.alpha) bmd.draw(video.snapshot) bmd.draw("swirl", 0, 0, video.width, video.height, "color") } }
1
0.580121
1
0.580121
game-dev
MEDIA
0.554722
game-dev,graphics-rendering
0.614188
1
0.614188
blurite/rsprot
6,125
protocol/osrs-230/osrs-230-model/src/main/kotlin/net/rsprot/protocol/game/outgoing/map/RebuildRegion.kt
package net.rsprot.protocol.game.outgoing.map import net.rsprot.protocol.ServerProtCategory import net.rsprot.protocol.game.outgoing.GameServerProtCategory import net.rsprot.protocol.game.outgoing.map.util.RebuildRegionZone import net.rsprot.protocol.message.OutgoingGameMessage /** * Rebuild region is used to send a dynamic map to the client, * built up out of zones (8x8x1 tiles), allowing for any kind * of unique instancing to occur. * @property zoneX the x coordinate of the center zone around * which the build area is built * @property zoneZ the z coordinate of the center zone around * which the build area is built * @property reload whether to forcibly reload the map client-sided. * If this property is false, the client will only reload if * the last rebuild had difference [zoneX] or [zoneZ] coordinates * than this one. * @property zones the list of zones to build, in a specific order. */ public class RebuildRegion private constructor( private val _zoneX: UShort, private val _zoneZ: UShort, public val reload: Boolean, public val zones: List<RebuildRegionZone?>, ) : OutgoingGameMessage { public constructor( zoneX: Int, zoneZ: Int, reload: Boolean, zoneProvider: RebuildRegionZoneProvider, ) : this( zoneX.toUShort(), zoneZ.toUShort(), reload, buildRebuildRegionZones( zoneX, zoneZ, zoneProvider, ), ) public val zoneX: Int get() = _zoneX.toInt() public val zoneZ: Int get() = _zoneZ.toInt() override val category: ServerProtCategory get() = GameServerProtCategory.HIGH_PRIORITY_PROT @Suppress("DuplicatedCode") override fun estimateSize(): Int { val header = Short.SIZE_BYTES + Short.SIZE_BYTES + Byte.SIZE_BYTES val notNullCount = zones.count { zone -> zone != null } val bitCount = (27 * notNullCount) + (zones.size - notNullCount) val bitBufByteCount = (bitCount + 7) ushr 3 // While a little wasteful, it is expensive to determine the true // number of bytes necessary since we only transmit xteas for // each referenced mapsquare at most one time // In here, we just assume each zone belongs in a unique mapsquare // The buffers are pooled anyway so it isn't like we're typically // allocating a ton here, just picking a larger buffer out of the pool. val xteaSize = notNullCount * (4 * Int.SIZE_BYTES) return header + Short.SIZE_BYTES + bitBufByteCount + xteaSize } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as RebuildRegion if (_zoneX != other._zoneX) return false if (_zoneZ != other._zoneZ) return false if (reload != other.reload) return false if (zones != other.zones) return false return true } override fun hashCode(): Int { var result = _zoneX.hashCode() result = 31 * result + _zoneZ.hashCode() result = 31 * result + reload.hashCode() result = 31 * result + zones.hashCode() return result } override fun toString(): String = "RebuildRegion(" + "zoneX=$zoneX, " + "zoneZ=$zoneZ, " + "reload=$reload, " + "zones=$zones" + ")" /** * Zone provider acts as a function to provide all the necessary information * needed for rebuild region to function, in the order the client * expects it in. */ @JvmDefaultWithCompatibility public fun interface RebuildRegionZoneProvider { /** * Provides a zone that the client must copy based on the parameters. * In order to calculate the mapsquare id for xtea keys, use [getMapsquareId]. * * @param zoneX the x coordinate of the region zone * @param zoneZ the z coordinate of the region zone * @param level the level of the region zone * @return the zone to be copied, or null if there's no zone to be copied there. */ public fun provide( zoneX: Int, zoneZ: Int, level: Int, ): RebuildRegionZone? /** * Calculates the mapsquare id based on the zone coordinates. * @param zoneX the x coordinate of the zone * @param zoneZ the z coordinate of the zone */ public fun getMapsquareId( zoneX: Int, zoneZ: Int, ): Int = (zoneX and 0x7FF ushr 3 shl 8) or (zoneZ and 0x7FF ushr 3) } private companion object { /** * Builds a list of rebuild region zones to be written to the client, * in order as the client expects them. * @param centerZoneX the center zone x coordinate around which the build area is built * @param centerZoneZ the center zone z coordinate around which the build area is built * @param zoneProvider the functional interface providing the necessary information * to be written to the client * @return a list of rebuild region zones (or nulls) for each zone in the build area. */ private fun buildRebuildRegionZones( centerZoneX: Int, centerZoneZ: Int, zoneProvider: RebuildRegionZoneProvider, ): List<RebuildRegionZone?> { val zones = ArrayList<RebuildRegionZone?>(4 * 13 * 13) for (level in 0..<4) { for (zoneX in (centerZoneX - 6)..(centerZoneX + 6)) { for (zoneZ in (centerZoneZ - 6)..(centerZoneZ + 6)) { zones += zoneProvider.provide( zoneX, zoneZ, level, ) } } } return zones } } }
1
0.896543
1
0.896543
game-dev
MEDIA
0.787632
game-dev
0.814126
1
0.814126
MohistMC/Youer
1,892
src/main/java/ca/spottedleaf/dataconverter/minecraft/versions/V3812.java
package ca.spottedleaf.dataconverter.minecraft.versions; import ca.spottedleaf.dataconverter.converters.DataConverter; import ca.spottedleaf.dataconverter.minecraft.MCVersions; import ca.spottedleaf.dataconverter.minecraft.datatypes.MCTypeRegistry; import ca.spottedleaf.dataconverter.types.ListType; import ca.spottedleaf.dataconverter.types.MapType; import ca.spottedleaf.dataconverter.types.ObjectType; import ca.spottedleaf.dataconverter.util.NamespaceUtil; public final class V3812 { private static final int VERSION = MCVersions.V24W05B + 1; public static void register() { MCTypeRegistry.ENTITY.addConverterForId("minecraft:wolf", new DataConverter<>(VERSION) { @Override public MapType<String> convert(final MapType<String> data, final long sourceVersion, final long toVersion) { boolean doubleHealth = false; final ListType attributes = data.getList("Attributes", ObjectType.MAP); if (attributes != null) { for (int i = 0, len = attributes.size(); i < len; ++i) { final MapType<String> attribute = attributes.getMap(i); if (!"minecraft:generic.max_health".equals(NamespaceUtil.correctNamespace(attribute.getString("Name")))) { continue; } final double base = attribute.getDouble("Base", 0.0D); if (base == 20.0D) { attribute.setDouble("Base", 40.0D); doubleHealth = true; } } } if (doubleHealth) { data.setFloat("Health", data.getFloat("Health", 0.0F) * 2.0F); } return null; } }); } private V3812() {} }
1
0.716623
1
0.716623
game-dev
MEDIA
0.518034
game-dev
0.887728
1
0.887728
Iskallia/Vault-public-S1
3,940
src/main/java/iskallia/vault/command/GearDebugCommand.java
package iskallia.vault.command; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import iskallia.vault.init.ModAttributes; import iskallia.vault.init.ModItems; import iskallia.vault.item.gear.VaultGear; import iskallia.vault.util.EntityHelper; import net.minecraft.command.CommandSource; import net.minecraft.item.ItemStack; import java.util.Random; import static net.minecraft.command.Commands.argument; import static net.minecraft.command.Commands.literal; public class GearDebugCommand extends Command { private static final Random COLOR_RAND = new Random(); @Override public String getName() { return "gear_debug"; } @Override public int getRequiredPermissionLevel() { return 2; } @Override public void build(LiteralArgumentBuilder<CommandSource> builder) { builder .then(literal("helmet") .then(argument("model", IntegerArgumentType.integer(0, 12 - 1)) .executes(ctx -> giveHelmet(ctx, IntegerArgumentType.getInteger(ctx, "model"))))) .then(literal("chestplate") .then(argument("model", IntegerArgumentType.integer(0, 12 - 1)) .executes(ctx -> giveChestplate(ctx, IntegerArgumentType.getInteger(ctx, "model"))))) .then(literal("leggings") .then(argument("model", IntegerArgumentType.integer(0, 12 - 1)) .executes(ctx -> giveLeggings(ctx, IntegerArgumentType.getInteger(ctx, "model"))))) .then(literal("boots") .then(argument("model", IntegerArgumentType.integer(0, 12 - 1)) .executes(ctx -> giveBoots(ctx, IntegerArgumentType.getInteger(ctx, "model"))))) .build(); } private int giveHelmet(CommandContext<CommandSource> context, int model) throws CommandSyntaxException { ItemStack helmetStack = new ItemStack(ModItems.HELMET); configureGear(helmetStack, model); EntityHelper.giveItem(context.getSource().asPlayer(), helmetStack); return 0; } private int giveChestplate(CommandContext<CommandSource> context, int model) throws CommandSyntaxException { ItemStack chestStack = new ItemStack(ModItems.CHESTPLATE); configureGear(chestStack, model); EntityHelper.giveItem(context.getSource().asPlayer(), chestStack); return 0; } private int giveLeggings(CommandContext<CommandSource> context, int model) throws CommandSyntaxException { ItemStack leggingsStack = new ItemStack(ModItems.LEGGINGS); configureGear(leggingsStack, model); EntityHelper.giveItem(context.getSource().asPlayer(), leggingsStack); return 0; } private int giveBoots(CommandContext<CommandSource> context, int model) throws CommandSyntaxException { ItemStack bootsStack = new ItemStack(ModItems.BOOTS); configureGear(bootsStack, model); EntityHelper.giveItem(context.getSource().asPlayer(), bootsStack); return 0; } private void configureGear(ItemStack gearStack, int model) { ModAttributes.GEAR_STATE.create(gearStack, VaultGear.State.IDENTIFIED); gearStack.getOrCreateTag().remove("RollTicks"); gearStack.getOrCreateTag().remove("LastModelHit"); ModAttributes.GEAR_RARITY.create(gearStack, VaultGear.Rarity.OMEGA); ModAttributes.GEAR_SET.create(gearStack, VaultGear.Set.NONE); ModAttributes.GEAR_MODEL.create(gearStack, model); ModAttributes.GEAR_COLOR.create(gearStack, 0xFF_FFFFFF); } @Override public boolean isDedicatedServerOnly() { return false; } }
1
0.923507
1
0.923507
game-dev
MEDIA
0.988043
game-dev
0.885057
1
0.885057
showlab/BYOC
8,387
BlendshapeToolkit/Library/PackageCache/com.unity.visualscripting@1.8.0/Editor/VisualScripting.Core/Inspection/MetadataListAdaptor.cs
using System; using System.Collections; using Unity.VisualScripting.ReorderableList; using UnityEditor; using UnityEngine; using UnityObject = UnityEngine.Object; namespace Unity.VisualScripting { public class MetadataListAdaptor : MetadataCollectionAdaptor, IReorderableListDropTarget { public MetadataListAdaptor(Metadata metadata, Inspector parentInspector) : base((Metadata)metadata, parentInspector) { if (metadata == null) { throw new ArgumentNullException(nameof(metadata)); } this.metadata = metadata; metadata.valueChanged += (previousValue) => { if (!metadata.isList) { throw new InvalidOperationException("Metadata for list adaptor is not a list: " + metadata); } if (metadata.value == null) { metadata.value = ConstructList(); } }; } public event Action<object> itemAdded; public Metadata metadata { get; private set; } protected virtual IList ConstructList() { if (metadata.listType.IsArray) { return Array.CreateInstance(metadata.listElementType, 0); } else { try { return (IList)metadata.listType.Instantiate(false); } catch (Exception ex) { throw new InvalidOperationException($"Could not create list instance of type '{metadata.listType}'.", ex); } } } protected virtual object ConstructItem() { return metadata.listElementType.TryInstantiate(false); } #region Manipulation public object this[int index] { get { return ((IList)metadata)[index]; } set { metadata.RecordUndo(); ((IList)metadata)[index] = value; } } public override int Count => metadata.Count; public override void Add() { if (!CanAdd()) { return; } var newItem = ConstructItem(); metadata.RecordUndo(); metadata.Add(newItem); itemAdded?.Invoke(newItem); parentInspector.SetHeightDirty(); } public override void Clear() { metadata.RecordUndo(); metadata.Clear(); parentInspector.SetHeightDirty(); } public override void Insert(int index) { if (!CanAdd()) { return; } var newItem = ConstructItem(); metadata.RecordUndo(); metadata.Insert(index, newItem); itemAdded?.Invoke(newItem); parentInspector.SetHeightDirty(); } public override void Remove(int index) { metadata.RecordUndo(); metadata.RemoveAt(index); parentInspector.SetHeightDirty(); } public override void Move(int sourceIndex, int destinationIndex) { metadata.RecordUndo(); metadata.Move(sourceIndex, destinationIndex); } public override void Duplicate(int index) { metadata.RecordUndo(); metadata.Duplicate(index); itemAdded?.Invoke(this[index + 1]); parentInspector.SetHeightDirty(); } protected virtual bool CanAdd() { return true; } public override bool CanDrag(int index) { return true; } public override bool CanRemove(int index) { return true; } #endregion #region Drag & Drop private static MetadataListAdaptor selectedList; private static object selectedItem; public bool CanDropInsert(int insertionIndex) { if (!ReorderableListControl.CurrentListPosition.Contains(Event.current.mousePosition)) { return false; } var data = DragAndDrop.GetGenericData(DraggedListItem.TypeName); return data is DraggedListItem && metadata.listElementType.IsInstanceOfType(((DraggedListItem)data).item); } protected virtual bool CanDrop(object item) { return true; } public void ProcessDropInsertion(int insertionIndex) { if (Event.current.type == EventType.DragPerform) { var draggedItem = (DraggedListItem)DragAndDrop.GetGenericData(DraggedListItem.TypeName); if (draggedItem.sourceListAdaptor == this) { Move(draggedItem.index, insertionIndex); } else { if (CanDrop(draggedItem.item)) { metadata.Insert(insertionIndex, draggedItem.item); itemAdded?.Invoke(draggedItem.item); draggedItem.sourceListAdaptor.Remove(draggedItem.index); selectedList = this; draggedItem.sourceListAdaptor.parentInspector.SetHeightDirty(); parentInspector.SetHeightDirty(); } } GUI.changed = true; Event.current.Use(); } } #endregion #region Drawing public override float GetItemAdaptiveWidth(int index) { return LudiqGUI.GetInspectorAdaptiveWidth(metadata[index]); } public override float GetItemHeight(float width, int index) { return LudiqGUI.GetInspectorHeight(parentInspector, metadata[index], width, GUIContent.none); } public bool alwaysDragAndDrop { get; set; } = false; public override void DrawItem(Rect position, int index) { LudiqGUI.Inspector(metadata[index], position, GUIContent.none); var item = this[index]; var controlID = GUIUtility.GetControlID(FocusType.Passive); switch (Event.current.GetTypeForControl(controlID)) { case EventType.MouseDown: // Exclude delete button from draggable position var draggablePosition = ReorderableListGUI.CurrentItemTotalPosition; draggablePosition.xMax = position.xMax + 2; if (Event.current.button == (int)MouseButton.Left && draggablePosition.Contains(Event.current.mousePosition)) { selectedList = this; selectedItem = item; if (alwaysDragAndDrop || Event.current.alt) { GUIUtility.hotControl = controlID; Event.current.Use(); } } break; case EventType.MouseDrag: if (GUIUtility.hotControl == controlID) { GUIUtility.hotControl = 0; DragAndDrop.PrepareStartDrag(); DragAndDrop.objectReferences = new UnityObject[0]; DragAndDrop.paths = new string[0]; DragAndDrop.SetGenericData(DraggedListItem.TypeName, new DraggedListItem(this, index, item)); DragAndDrop.StartDrag(metadata.path); Event.current.Use(); } break; } } public override void DrawItemBackground(Rect position, int index) { base.DrawItemBackground(position, index); if (this == selectedList && this[index] == selectedItem) { //GUI.DrawTexture(new RectOffset(1, 1, 1, 1).Add(position), ReorderableListStyles.SelectionBackgroundColor.GetPixel()); } } #endregion } }
1
0.980987
1
0.980987
game-dev
MEDIA
0.478711
game-dev
0.992902
1
0.992902
magefree/mage
2,719
Mage.Tests/src/test/java/org/mage/test/cards/single/ktk/DeflectingPalmTest.java
package org.mage.test.cards.single.ktk; import mage.constants.PhaseStep; import mage.constants.Zone; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBase; /** * @author Susucr */ public class DeflectingPalmTest extends CardTestPlayerBase { /** * {@link mage.cards.d.DeflectingPalm Deflecting Palm} {R}{W} * Instant * The next time a source of your choice would deal damage to you this turn, prevent that damage. If damage is prevented this way, Deflecting Palm deals that much damage to that source’s controller. */ private static final String palm = "Deflecting Palm"; @Test public void test_DamageOnCreature_NoPrevent() { addCard(Zone.HAND, playerA, palm, 1); addCard(Zone.BATTLEFIELD, playerB, "Goblin Piker", 1); // 2/1 addCard(Zone.BATTLEFIELD, playerA, "Caelorna, Coral Tyrant"); // 0/8 addCard(Zone.BATTLEFIELD, playerA, "Plateau", 2); castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerA, palm); setChoice(playerA, "Goblin Piker"); // source to prevent from attack(2, playerB, "Goblin Piker", playerA); block(2, playerA, "Caelorna, Coral Tyrant", "Goblin Piker"); setStrictChooseMode(true); setStopAt(2, PhaseStep.POSTCOMBAT_MAIN); execute(); assertDamageReceived(playerA, "Caelorna, Coral Tyrant", 2); // no prevent assertLife(playerB, 20); } @Test public void test_DamageOnYou_Prevent() { addCard(Zone.HAND, playerA, palm, 1); addCard(Zone.BATTLEFIELD, playerB, "Goblin Piker", 1); // 2/1 addCard(Zone.BATTLEFIELD, playerA, "Plateau", 2); castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerA, palm); setChoice(playerA, "Goblin Piker"); // source to prevent from attack(2, playerB, "Goblin Piker", playerA); setStrictChooseMode(true); setStopAt(2, PhaseStep.POSTCOMBAT_MAIN); execute(); assertLife(playerA, 20); assertLife(playerB, 20 - 2); } @Test public void test_DoubleStrike_Prevent_ThenConsumedAndNoPrevent() { addCard(Zone.HAND, playerA, palm, 1); addCard(Zone.BATTLEFIELD, playerB, "Blade Historian", 1); // 2/3 "Attacking creatures you control have double strike." addCard(Zone.BATTLEFIELD, playerA, "Plateau", 2); castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerA, palm); setChoice(playerA, "Blade Historian"); // source to prevent from attack(2, playerB, "Blade Historian", playerA); setStrictChooseMode(true); setStopAt(2, PhaseStep.POSTCOMBAT_MAIN); execute(); assertLife(playerA, 20 - 2); assertLife(playerB, 20 - 2); } }
1
0.972161
1
0.972161
game-dev
MEDIA
0.970659
game-dev
0.985195
1
0.985195
AionGermany/aion-germany
2,667
AL-Game/data/scripts/system/handlers/quest/lakrum/_72576UrgentOrdersUrkisRequest.java
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. */ package quest.lakrum; import com.aionemu.gameserver.model.DialogAction; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; /** * @author QuestGenerator by Mariella */ public class _72576UrgentOrdersUrkisRequest extends QuestHandler { private final static int questId = 72576; public _72576UrgentOrdersUrkisRequest() { super(questId); } @Override public void register() { qe.registerQuestNpc(836608).addOnQuestStart(questId); // Urki qe.registerQuestNpc(836608).addOnTalkEvent(questId); // Urki } @Override public boolean onLvlUpEvent(QuestEnv env) { return defaultOnLvlUpEvent(env, 1000, true); } @Override public boolean onDialogEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); DialogAction dialog = env.getDialog(); int targetId = env.getTargetId(); if (qs == null || qs.getStatus() == QuestStatus.NONE || qs.canRepeat()) { if (targetId == 836608) { switch (dialog) { case QUEST_SELECT: { return sendQuestDialog(env, 4762); } case QUEST_ACCEPT_1: case QUEST_ACCEPT_SIMPLE: { return sendQuestStartDialog(env); } case QUEST_REFUSE_SIMPLE: { return closeDialogWindow(env); } default: break; } } } else if (qs.getStatus() == QuestStatus.START) { switch (targetId) { case 836608: { switch (dialog) { case QUEST_SELECT: { return sendQuestDialog(env, 1011); } case FINISH_DIALOG: { return sendQuestSelectionDialog(env); } default: break; } break; } default: break; } } return false; } }
1
0.92705
1
0.92705
game-dev
MEDIA
0.963349
game-dev
0.974547
1
0.974547
cnlohr/embeddedDOOM
16,655
src/s_sound.c
// Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- // // $Id:$ // // Copyright (C) 1993-1996 by id Software, Inc. // // This source is available for distribution and/or modification // only under the terms of the DOOM Source Code License as // published by id Software. All rights reserved. // // The source is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // FITNESS FOR A PARTICULAR PURPOSE. See the DOOM Source Code License // for more details. // // $Log:$ // // DESCRIPTION: none // //----------------------------------------------------------------------------- //static const char //rcsid[] = "$Id: s_sound.c,v 1.6 1997/02/03 22:45:12 b1 Exp $"; #include <stdio.h> #include <stdlib.h> #include "i_system.h" #include "i_sound.h" #include "sounds.h" #include "s_sound.h" #include "z_zone.h" #include "m_random.h" #include "w_wad.h" #include "doomdef.h" #include "p_local.h" #include "doomstat.h" #ifndef STUB_SOUND // Purpose? const char snd_prefixen[] = { 'P', 'P', 'A', 'S', 'S', 'S', 'M', 'M', 'M', 'S', 'S', 'S' }; #define S_MAX_VOLUME 127 // when to clip out sounds // Does not fit the large outdoor areas. #define S_CLIPPING_DIST (1200*0x10000) // Distance tp origin when sounds should be maxed out. // This should relate to movement clipping resolution // (see BLOCKMAP handling). // Originally: (200*0x10000). #define S_CLOSE_DIST (160*0x10000) #define S_ATTENUATOR ((S_CLIPPING_DIST-S_CLOSE_DIST)>>FRACBITS) // Adjustable by menu. #define NORM_VOLUME snd_MaxVolume #define NORM_PITCH 128 #define NORM_PRIORITY 64 #define NORM_SEP 128 #define S_PITCH_PERTURB 1 #define S_STEREO_SWING (96*0x10000) // percent attenuation from front to back #define S_IFRACVOL 30 #define NA 0 #define S_NUMCHANNELS 2 // Current music/sfx card - index useless // w/o a reference LUT in a sound module. extern int snd_MusicDevice; extern int snd_SfxDevice; // Config file? Same disclaimer as above. extern int snd_DesiredMusicDevice; extern int snd_DesiredSfxDevice; typedef struct { // sound information (if null, channel avail.) sfxinfo_t* sfxinfo; // origin of sound void* origin; // handle of the sound being played int handle; } channel_t; // the set of channels available static channel_t* channels; // These are not used, but should be (menu). // Maximum volume of a sound effect. // Internal default is max out of 0-15. int snd_SfxVolume = 15; // Maximum volume of music. Useless so far. int snd_MusicVolume = 15; // whether songs are mus_paused static boolean mus_paused; // music currently being played static musicinfo_t* mus_playing=0; // following is set // by the defaults code in M_misc: // number of channels available int numChannels; static int nextcleanup; // // Internals. // int S_getChannel ( void* origin, sfxinfo_t* sfxinfo ); int S_AdjustSoundParams ( mobj_t* listener, mobj_t* source, int* vol, int* sep, int* pitch ); void S_StopChannel(int cnum); // // Initializes sound stuff, including volume // Sets channels, SFX and music volume, // allocates channel buffer, sets S_sfx lookup. // void S_Init ( int sfxVolume, int musicVolume ) { int i; fprintf( stderr, "S_Init: default sfx volume %d\n", sfxVolume); // Whatever these did with DMX, these are rather dummies now. I_SetChannels(); S_SetSfxVolume(sfxVolume); // No music with Linux - another dummy. S_SetMusicVolume(musicVolume); // Allocating the internal channels for mixing // (the maximum numer of sounds rendered // simultaneously) within zone memory. channels = (channel_t *) Z_Malloc(numChannels*sizeof(channel_t), PU_STATIC, 0); // Free all channels for use for (i=0 ; i<numChannels ; i++) channels[i].sfxinfo = 0; // no sounds are playing, and they are not mus_paused mus_paused = 0; // Note that sounds have not been cached (yet). for (i=1 ; i<NUMSFX ; i++) S_sfx[i].lumpnum = S_sfx[i].usefulness = -1; } // // Per level startup code. // Kills playing sounds at start of level, // determines music if any, changes music. // void S_Start(void) { int cnum; int mnum; // kill all playing sounds at start of level // (trust me - a good idea) for (cnum=0 ; cnum<numChannels ; cnum++) if (channels[cnum].sfxinfo) S_StopChannel(cnum); // start new music for the level mus_paused = 0; if (gamemode == commercial) mnum = mus_runnin + gamemap - 1; else { int spmus[]= { // Song - Who? - Where? mus_e3m4, // American e4m1 mus_e3m2, // Romero e4m2 mus_e3m3, // Shawn e4m3 mus_e1m5, // American e4m4 mus_e2m7, // Tim e4m5 mus_e2m4, // Romero e4m6 mus_e2m6, // J.Anderson e4m7 CHIRON.WAD mus_e2m5, // Shawn e4m8 mus_e1m9 // Tim e4m9 }; if (gameepisode < 4) mnum = mus_e1m1 + (gameepisode-1)*9 + gamemap-1; else mnum = spmus[gamemap-1]; } // HACK FOR COMMERCIAL // if (commercial && mnum > mus_e3m9) // mnum -= mus_e3m9; S_ChangeMusic(mnum, true); nextcleanup = 15; } void S_StartSoundAtVolume ( void* origin_p, int sfx_id, int volume ) { int rc; int sep; int pitch; int priority; sfxinfo_t* sfx; int cnum; mobj_t* origin = (mobj_t *) origin_p; // Debug. /*fprintf( stderr, "S_StartSoundAtVolume: playing sound %d (%s)\n", sfx_id, S_sfx[sfx_id].name );*/ // check for bogus sound # if (sfx_id < 1 || sfx_id > NUMSFX) I_Error("Bad sfx #: %d", sfx_id); sfx = &S_sfx[sfx_id]; // Initialize sound parameters if (sfx->link) { pitch = sfx->pitch; priority = sfx->priority; volume += sfx->volume; if (volume < 1) return; if (volume > snd_SfxVolume) volume = snd_SfxVolume; } else { pitch = NORM_PITCH; priority = NORM_PRIORITY; } // Check to see if it is audible, // and if not, modify the params if (origin && origin != players[consoleplayer].mo) { rc = S_AdjustSoundParams(players[consoleplayer].mo, origin, &volume, &sep, &pitch); if ( origin->x == players[consoleplayer].mo->x && origin->y == players[consoleplayer].mo->y) { sep = NORM_SEP; } if (!rc) return; } else { sep = NORM_SEP; } // hacks to vary the sfx pitches if (sfx_id >= sfx_sawup && sfx_id <= sfx_sawhit) { pitch += 8 - (M_Random()&15); if (pitch<0) pitch = 0; else if (pitch>255) pitch = 255; } else if (sfx_id != sfx_itemup && sfx_id != sfx_tink) { pitch += 16 - (M_Random()&31); if (pitch<0) pitch = 0; else if (pitch>255) pitch = 255; } // kill old sound S_StopSound(origin); // try to find a channel cnum = S_getChannel(origin, sfx); if (cnum<0) return; // // This is supposed to handle the loading/caching. // For some odd reason, the caching is done nearly // each time the sound is needed? // // get lumpnum if necessary if (sfx->lumpnum < 0) sfx->lumpnum = I_GetSfxLumpNum(sfx); #ifndef SNDSRV // cache data if necessary if (!sfx->data) { fprintf( stderr, "S_StartSoundAtVolume: 16bit and not pre-cached - wtf?\n"); // DOS remains, 8bit handling //sfx->data = (void *) W_CacheLumpNum(sfx->lumpnum, PU_MUSIC); // fprintf( stderr, // "S_StartSoundAtVolume: loading %d (lump %d) : 0x%x\n", // sfx_id, sfx->lumpnum, (int)sfx->data ); } #endif // increase the usefulness if (sfx->usefulness++ < 0) sfx->usefulness = 1; // Assigns the handle to one of the channels in the // mix/output buffer. channels[cnum].handle = I_StartSound(sfx_id, /*sfx->data,*/ volume, sep, pitch, priority); } void S_StartSound ( void* origin, int sfx_id ) { #ifdef SAWDEBUG // if (sfx_id == sfx_sawful) // sfx_id = sfx_itemup; #endif S_StartSoundAtVolume(origin, sfx_id, snd_SfxVolume); // UNUSED. We had problems, had we not? #ifdef SAWDEBUG { int i; int n; static mobj_t* last_saw_origins[10] = {1,1,1,1,1,1,1,1,1,1}; static int first_saw=0; static int next_saw=0; if (sfx_id == sfx_sawidl || sfx_id == sfx_sawful || sfx_id == sfx_sawhit) { for (i=first_saw;i!=next_saw;i=(i+1)%10) if (last_saw_origins[i] != origin) fprintf(stderr, "old origin 0x%lx != " "origin 0x%lx for sfx %d\n", last_saw_origins[i], origin, sfx_id); last_saw_origins[next_saw] = origin; next_saw = (next_saw + 1) % 10; if (next_saw == first_saw) first_saw = (first_saw + 1) % 10; for (n=i=0; i<numChannels ; i++) { if (channels[i].sfxinfo == &S_sfx[sfx_sawidl] || channels[i].sfxinfo == &S_sfx[sfx_sawful] || channels[i].sfxinfo == &S_sfx[sfx_sawhit]) n++; } if (n>1) { for (i=0; i<numChannels ; i++) { if (channels[i].sfxinfo == &S_sfx[sfx_sawidl] || channels[i].sfxinfo == &S_sfx[sfx_sawful] || channels[i].sfxinfo == &S_sfx[sfx_sawhit]) { fprintf(stderr, "chn: sfxinfo=0x%lx, origin=0x%lx, " "handle=%d\n", channels[i].sfxinfo, channels[i].origin, channels[i].handle); } } fprintf(stderr, "\n"); } } } #endif } void S_StopSound(void *origin) { int cnum; for (cnum=0 ; cnum<numChannels ; cnum++) { if (channels[cnum].sfxinfo && channels[cnum].origin == origin) { S_StopChannel(cnum); break; } } } // // Stop and resume music, during game PAUSE. // void S_PauseSound(void) { if (mus_playing && !mus_paused) { I_PauseSong(mus_playing->handle); mus_paused = true; } } void S_ResumeSound(void) { if (mus_playing && mus_paused) { I_ResumeSong(mus_playing->handle); mus_paused = false; } } // // Updates music & sounds // void S_UpdateSounds(void* listener_p) { int audible; int cnum; int volume; int sep; int pitch; sfxinfo_t* sfx; channel_t* c; mobj_t* listener = (mobj_t*)listener_p; // Clean up unused data. // This is currently not done for 16bit (sounds cached static). // DOS 8bit remains. /*if (gametic > nextcleanup) { for (i=1 ; i<NUMSFX ; i++) { if (S_sfx[i].usefulness < 1 && S_sfx[i].usefulness > -1) { if (--S_sfx[i].usefulness == -1) { Z_ChangeTag(S_sfx[i].data, PU_CACHE); S_sfx[i].data = 0; } } } nextcleanup = gametic + 15; }*/ for (cnum=0 ; cnum<numChannels ; cnum++) { c = &channels[cnum]; sfx = c->sfxinfo; if (c->sfxinfo) { if (I_SoundIsPlaying(c->handle)) { // initialize parameters volume = snd_SfxVolume; pitch = NORM_PITCH; sep = NORM_SEP; if (sfx->link) { pitch = sfx->pitch; volume += sfx->volume; if (volume < 1) { S_StopChannel(cnum); continue; } else if (volume > snd_SfxVolume) { volume = snd_SfxVolume; } } // check non-local sounds for distance clipping // or modify their params if (c->origin && listener_p != c->origin) { audible = S_AdjustSoundParams(listener, c->origin, &volume, &sep, &pitch); if (!audible) { S_StopChannel(cnum); } else I_UpdateSoundParams(c->handle, volume, sep, pitch); } } else { // if channel is allocated but sound has stopped, // free it S_StopChannel(cnum); } } } // kill music if it is a single-play && finished // if ( mus_playing // && !I_QrySongPlaying(mus_playing->handle) // && !mus_paused ) // S_StopMusic(); } void S_SetMusicVolume(int volume) { if (volume < 0 || volume > 127) { I_Error("Attempt to set music volume at %d", volume); } I_SetMusicVolume(127); I_SetMusicVolume(volume); snd_MusicVolume = volume; } void S_SetSfxVolume(int volume) { if (volume < 0 || volume > 127) I_Error("Attempt to set sfx volume at %d", volume); snd_SfxVolume = volume; } // // Starts some music with the music id found in sounds.h. // void S_StartMusic(int m_id) { S_ChangeMusic(m_id, false); } void S_ChangeMusic ( int musicnum, int looping ) { musicinfo_t* music; char namebuf[9]; if ( (musicnum <= mus_None) || (musicnum >= NUMMUSIC) ) { I_Error("Bad music number %d", musicnum); } else music = &S_music[musicnum]; if (mus_playing == music) return; // shutdown old music S_StopMusic(); // get lumpnum if neccessary if (!music->lumpnum) { sprintf(namebuf, "d_%s", music->name); music->lumpnum = W_GetNumForName(namebuf); } // load & register it music->data = (void *) W_CacheLumpNum(music->lumpnum, PU_MUSIC); music->handle = I_RegisterSong(music->data); // play it I_PlaySong(music->handle, looping); mus_playing = music; } void S_StopMusic(void) { if (mus_playing) { if (mus_paused) I_ResumeSong(mus_playing->handle); I_StopSong(mus_playing->handle); I_UnRegisterSong(mus_playing->handle); Z_ChangeTag(mus_playing->data, PU_CACHE); mus_playing->data = 0; mus_playing = 0; } } void S_StopChannel(int cnum) { int i; channel_t* c = &channels[cnum]; if (c->sfxinfo) { // stop the sound playing if (I_SoundIsPlaying(c->handle)) { #ifdef SAWDEBUG if (c->sfxinfo == &S_sfx[sfx_sawful]) fprintf(stderr, "stopped\n"); #endif I_StopSound(c->handle); } // check to see // if other channels are playing the sound for (i=0 ; i<numChannels ; i++) { if (cnum != i && c->sfxinfo == channels[i].sfxinfo) { break; } } // degrade usefulness of sound data c->sfxinfo->usefulness--; c->sfxinfo = 0; } } // // Changes volume, stereo-separation, and pitch variables // from the norm of a sound effect to be played. // If the sound is not audible, returns a 0. // Otherwise, modifies parameters and returns 1. // int S_AdjustSoundParams ( mobj_t* listener, mobj_t* source, int* vol, int* sep, int* pitch ) { fixed_t approx_dist; fixed_t adx; fixed_t ady; angle_t angle; // calculate the distance to sound origin // and clip it if necessary adx = abs(listener->x - source->x); ady = abs(listener->y - source->y); // From _GG1_ p.428. Appox. eucledian distance fast. approx_dist = adx + ady - ((adx < ady ? adx : ady)>>1); if (gamemap != 8 && approx_dist > S_CLIPPING_DIST) { return 0; } // angle of source to listener angle = R_PointToAngle2(listener->x, listener->y, source->x, source->y); if (angle > listener->angle) angle = angle - listener->angle; else angle = angle + (0xffffffff - listener->angle); angle >>= ANGLETOFINESHIFT; // stereo separation *sep = 128 - (FixedMul(S_STEREO_SWING,finesine[angle])>>FRACBITS); // volume calculation if (approx_dist < S_CLOSE_DIST) { *vol = snd_SfxVolume; } else if (gamemap == 8) { if (approx_dist > S_CLIPPING_DIST) approx_dist = S_CLIPPING_DIST; *vol = 15+ ((snd_SfxVolume-15) *((S_CLIPPING_DIST - approx_dist)>>FRACBITS)) / S_ATTENUATOR; } else { // distance effect *vol = (snd_SfxVolume * ((S_CLIPPING_DIST - approx_dist)>>FRACBITS)) / S_ATTENUATOR; } return (*vol > 0); } // // S_getChannel : // If none available, return -1. Otherwise channel #. // int S_getChannel ( void* origin, sfxinfo_t* sfxinfo ) { // channel number to use int cnum; channel_t* c; // Find an open channel for (cnum=0 ; cnum<numChannels ; cnum++) { if (!channels[cnum].sfxinfo) break; else if (origin && channels[cnum].origin == origin) { S_StopChannel(cnum); break; } } // None available if (cnum == numChannels) { // Look for lower priority for (cnum=0 ; cnum<numChannels ; cnum++) if (channels[cnum].sfxinfo->priority >= sfxinfo->priority) break; if (cnum == numChannels) { // FUCK! No lower priority. Sorry, Charlie. return -1; } else { // Otherwise, kick out lower priority. S_StopChannel(cnum); } } c = &channels[cnum]; // channel is decided to be cnum. c->sfxinfo = sfxinfo; c->origin = origin; return cnum; } #endif
1
0.881184
1
0.881184
game-dev
MEDIA
0.805196
game-dev,audio-video-media
0.927404
1
0.927404
Valkryst/VNameGenerator
8,340
README.md
As of this project's inception, the included algorithms are the only ones my research has turned up. If you know of any other _unique_ algorithms for name generation, then please let me know. I would love to implement them. ## Table of Contents * [Installation](https://github.com/Valkryst/VNameGenerator#installation) * [Gradle](https://github.com/Valkryst/VNameGenerator#-gradle) * [Maven](https://github.com/Valkryst/VNameGenerator#-maven) * [sbt](https://github.com/Valkryst/VNameGenerator#-scala-sbt) * [Algorithms](https://github.com/Valkryst/VNameGenerator#algorithms) * [Combinatorial](https://github.com/Valkryst/VNameGenerator#combinatorial) * [Consonant Vowel](https://github.com/Valkryst/VNameGenerator#consonant-vowel) * [Context Free Grammar](https://github.com/Valkryst/VNameGenerator#context-free-grammar) * [Markov Chain](https://github.com/Valkryst/VNameGenerator#markov-chain) ## Installation VNameGenerator is hosted on the [JitPack package repository](https://jitpack.io/#Valkryst/VNameGenerator) which supports Gradle, Maven, and sbt. ### ![Gradle](https://i.imgur.com/qtc6bXq.png?1) Gradle Add JitPack to your `build.gradle` at the end of repositories. ``` allprojects { repositories { ... maven { url 'https://jitpack.io' } } } ``` Add VNameGenerator as a dependency. ``` dependencies { implementation 'com.github.Valkryst:VNameGenerator:2025.10.1-fix' } ``` ### ![Maven](https://i.imgur.com/2TZzobp.png?1) Maven Add JitPack as a repository. ``` xml <repositories> <repository> <id>jitpack.io</id> <url>https://jitpack.io</url> </repository> </repositories> ``` Add VNameGenerator as a dependency. ```xml <dependency> <groupId>com.github.Valkryst</groupId> <artifactId>VNameGenerator</artifactId> <version>2025.10.1-fix</version> </dependency> ``` ### ![Scala SBT](https://i.imgur.com/Nqv3mVd.png?1) Scala SBT Add JitPack as a resolver. ``` resolvers += "jitpack" at "https://jitpack.io" ``` Add VNameGenerator as a dependency. ``` libraryDependencies += "com.github.Valkryst" % "VNameGenerator" % "2025.10.1-fix" ``` ## Algorithms The _Combinatorial_, _Consonant Vowel_, and _Markov Chain_ algorithms will generate names with a length of `(maxLength * 0.5)` to `maxLength`. This was done to improve the quality of the generated names. Names are guaranteed to begin with a capital character. ### Combinatorial 1. A beginning is chosen and added to the name. 2. While the name is less than the maximum length, middles are chosen and added to the name. 3. An ending is chosen and added to the end of the name, overwriting existing characters in order to fit within the maximum length. ```java public class Example { public static void main(final String[] args) { final var beginnings = new String[] { "th", "bo", "ja", "fu" }; final var middles = new String[] { "la", "su", "dhu", "li", "da", "zk", "fr"}; final var endings = new String[] { "r", "t", "gh", "or", "al", "ar", "is" }; final var generator = new CombinatorialGenerator(beginnings, middles, endings); for (int i = 0 ; i < 20 ; i++) { System.out.println(generator.generate(10)); } } } ``` ``` Thlifrdhgh Bolalar Fusuladagh Thlis Thlagh Thlilifis Jadasugh Fuzklr Jadhular Jadaal Bosulaligh Jafrgh Jadar Bodhugh Bolazkr Thlidadis Fudhr Thzklaar Jazklidgh Bozkr ``` ### Consonant Vowel 1. A consonant is chosen and added to the name. 2. A vowel is chosen and added to the name. 3. Repeat the previous steps until the name is equal to the maximum length. ```java public class Example { public static void main(final String[] args) { final var generator = new ConsonantVowelGenerator(); for (int i = 0 ; i < 20 ; i++) { System.out.println(generator.generate(10)); } } } ``` ``` Itleanas Netemete Auieie Stvetoerit Ataseander Ouitha Auyuyieyoe Arhaea Aauuiaui Thatatea Seenesor Itstisme Titire Eouuyuoo Leteisha Ayueea Waatanto Eoyouo Eeoyieuuui Haontiseal ``` ### Context Free Grammar Click [here](http://www.tutorialspoint.com/automata_theory/context_free_grammar_introduction.htm) to learn more about CFGs and how they work. I do not recommend using this method as it is difficult to create a set of rules that results in good quality names, and a large variety of names. ```java public class Example { public static void main(final String[] args) { /* * This set of rules was created using the following set of names. * * Balin, Bifur, Bofur, Bombur, Borin, Dain, Dis, Dori, Dwalin, Farin, * Fili, Floi, Frar, Frerin, Fror, Fundin, Gaiml, Gimli, Gloin, Groin, * Gror, Ibun, Khim, Kili, Loni, Mim, Nain, Nali, Nar, Narvi, Nori, Oin, * Ori, Telchar, Thorin, Thrain, Thror */ final List<String> rules = new ArrayList<>(); rules.add("S B D F G I K L M N O T"); rules.add("A a aL aI aR"); rules.add("B b bA bI bO"); rules.add("C c"); rules.add("D d dA dI dO dW dU"); rules.add("E e eR eL"); rules.add("F f fA fI fL fR fU fO"); rules.add("G g gA gI gL gR"); rules.add("H h hI hA"); rules.add("I i"); rules.add("K k kH kI"); rules.add("L l lO"); rules.add("M m mI"); rules.add("N n nA nO"); rules.add("O o oI oR"); rules.add("P p"); rules.add("Q q"); rules.add("R r rI rO rV"); rules.add("S s"); rules.add("T t tE tH"); rules.add("U u uR uN"); rules.add("V v"); rules.add("W w wA"); rules.add("X x"); rules.add("Y y"); rules.add("Z z"); final var generator = new GrammarGenerator(rules); final int maxLength = 10; String temp; for (int i = 0 ; i < 20 ; i++) { do { temp = generator.generate(10); } while (temp.length() < (maxLength / 2)); System.out.println(temp); } } } ``` ``` Ororv Dwarv Naloro Ororo Grori Daloi Narori Nalorv Noroi Terororoi Dunai Flori Glori Thalo Funal Baloroi Khari Ororv Thalor Dwari ``` ### Markov Chain Click [here](https://en.wikipedia.org/wiki/Markov_chain) to learn more about Markov Chains and how they work. I recommend using this method with a large set of training names. Smaller sets will result in the generation of many similar names, whereas larger sets will result in more unique and varied names. ```java public class Example { public static void main(final String[] args) { final String[] trainingNames = new String[] { "ailios", "ailisl", "aimil", "aingealag", "anabla", "anna", "aoife", "barabal", "baraball", "barabla", "bearnas", "beasag", "beathag", "beileag", "beitidh", "beitiris", "beitris", "bhioctoria", "brighde", "brìde", "cairistiòna", "cairistìne", "cairistìona", "caitir", "caitlin", "caitrìona", "calaminag", "catrìona", "ceana", "ceit", "ceiteag", "ceitidh", "ciorsdan", "ciorstag", "ciorstaidh", "ciorstan", "cotrìona", "criosaidh", "curstag", "curstaidh", "deirdre", "deòiridh", "deònaidh", "dior-bhorgàil", "diorbhail", "doileag", "doilidh", "doirin", "dolag", "ealasaid", "eamhair", "eilidh", "eimhir", "eiric", "eithrig", "eubh", "eubha", "èibhlin", "fionnaghal", "fionnuala", "floireans", "flòraidh", "frangag", "giorsail", "giorsal", "gormall", "gormlaith", "isbeil", "iseabail", "iseabal", "leagsaidh", "leitis", "lili", "liùsaidh", "lucrais", "lìosa", "magaidh", "maighread", "mairead", "mairearad", "malamhìn", "malmhìn", "marsail", "marsaili", "marta", "milread", "moibeal", "moire", "moireach", "muire", "muireall", "màili", "màiri", "mòr", "mòrag", "nansaidh", "oighrig", "olibhia", "peanaidh", "peigi", "raghnaid", "raodhailt", "raonaid", "raonaild", "rut", "seasaìdh", "seonag", "seònaid", "simeag", "siubhan", "siùsaidh", "siùsan", "sorcha", "stineag", "sìle", "sìleas", "sìlis", "sìne", "sìneag", "sìonag", "teasag", "teàrlag", "ùna", "una" }; final MarkovGenerator generator = new MarkovGenerator(trainingNames); for (int i = 0 ; i < 20 ; i++) { System.out.println(generator.generate(10)); } } } ``` ``` Sorsag Iria Unabarst Nualasana Tirdreal Craoilisl Nearaidha Lrealairea Nuala Almhalamh Reabarnaig Ireag Geabl Abara Unaba Ighang Beitrìd Ciorcha Caimeabal Mhailil ```
1
0.672427
1
0.672427
game-dev
MEDIA
0.267916
game-dev
0.796947
1
0.796947
Open-KO/KnightOnline
20,096
ItemEditor/base.cpp
/* */ #include "base.h" //----------------------------------------------------------------------------- char pTexName[0xFF]; _N3TexHeader HeaderOrg; uint8_t* compTexData; int compTexSize; int iPixelSize; uint16_t* m_pIndices0; _N3VertexT1* m_pVertices0; int m_iMaxNumIndices0; int m_iMaxNumVertices0; int m_nVC; int m_nFC; int m_nUVC; __VertexSkinned* m_pSkinVertices; __VertexXyzNormal* m_pVertices; uint16_t* m_pwVtxIndices; float* m_pfUVs; uint16_t* m_pwUVsIndices; aiScene m_Scene; e_ItemType eType; //----------------------------------------------------------------------------- std::wstring s2ws(const std::string& s) { int len; int slength = (int)s.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len); std::wstring r(buf); delete[] buf; return r; } //----------------------------------------------------------------------------- void N3LoadTexture(const char* szFN) { size_t last_slash = 0; size_t last_point = 0; memset(pTexName, 0x00, 0xFF); size_t len = strlen(szFN); while (szFN[last_slash++] != '\\' && last_slash < len) ; while (szFN[last_point++] != '.' && last_point < len) ; for (size_t i = last_slash; i < last_point - 1; ++i) { pTexName[i - last_slash] = szFN[i]; } strcat(pTexName, ".bmp"); printf("Texture: %s (%s)\n", pTexName, szFN); FILE* fpTexture = fopen(szFN, "rb"); if(fpTexture == nullptr) { fprintf(stderr, "ERROR: Missing texture %s\n", szFN); return; } int nL0 = 0; fread(&nL0, sizeof(int), 1, fpTexture); char m_szName0[NAME_LENGTH] = {}; if(nL0 > 0) { memset(&m_szName0, 0, (nL0+1)); fread(&m_szName0, sizeof(char), nL0, fpTexture); } fread(&HeaderOrg, sizeof(_N3TexHeader), 1, fpTexture); printf("\nTexName: %s\n", m_szName0); printf("H.szID -> %c%c%c%hu\n", HeaderOrg.szID[0], HeaderOrg.szID[1], HeaderOrg.szID[2], (uint8_t) HeaderOrg.szID[3] ); printf("H.nWidth -> %d\n", HeaderOrg.nWidth); printf("H.nHeight -> %d\n", HeaderOrg.nHeight); printf("H.Format -> %d\n", HeaderOrg.Format); printf("H.bMipMap -> %d\n\n", HeaderOrg.bMipMap); iPixelSize = 0; switch(HeaderOrg.Format) { case D3DFMT_DXT1: { compTexSize = (HeaderOrg.nWidth*HeaderOrg.nHeight/2); } break; case D3DFMT_DXT3: { compTexSize = (HeaderOrg.nWidth*HeaderOrg.nHeight); } break; case D3DFMT_DXT5: { compTexSize = (HeaderOrg.nWidth*HeaderOrg.nHeight); } break; case D3DFMT_A1R5G5B5: case D3DFMT_A4R4G4B4: { iPixelSize = 2; } break; case D3DFMT_R8G8B8: { iPixelSize = 3; } break; case D3DFMT_A8R8G8B8: case D3DFMT_X8R8G8B8: { iPixelSize = 4; } break; default: { fprintf(stderr, "\nERROR: Unknown texture format %d. (need to implement this)\n", HeaderOrg.Format ); return; } break; } if(iPixelSize == 0) { if(compTexData) { delete compTexData; compTexData = nullptr; } compTexData = new uint8_t[compTexSize]; fread(compTexData, sizeof(uint8_t), compTexSize, fpTexture); } else { if(compTexData) { delete compTexData; compTexData = nullptr; } compTexSize = (HeaderOrg.nWidth*HeaderOrg.nHeight*iPixelSize); compTexData = new uint8_t[compTexSize]; fread(compTexData, sizeof(uint8_t), compTexSize, fpTexture); } fclose(fpTexture); } //----------------------------------------------------------------------------- void N3LoadMesh(const char* szFN) { FILE* fpMesh = fopen(szFN, "rb"); if(fpMesh == nullptr) { fprintf(stderr, "\nERROR: Missing mesh %s\n", szFN); return; } int nL0 = 0; fread(&nL0, sizeof(int), 1, fpMesh); char m_szName0[NAME_LENGTH] = {}; if(nL0 > 0) { memset(&m_szName0, 0, (nL0+1)); fread(&m_szName0, sizeof(char), nL0, fpMesh); } int m_iNumCollapses0; int m_iTotalIndexChanges0; int m_iMinNumVertices0; int m_iMinNumIndices0; fread(&m_iNumCollapses0, sizeof(int), 1, fpMesh); fread(&m_iTotalIndexChanges0, sizeof(int), 1, fpMesh); fread(&m_iMaxNumVertices0, sizeof(int), 1, fpMesh); fread(&m_iMaxNumIndices0, sizeof(int), 1, fpMesh); fread(&m_iMinNumVertices0, sizeof(int), 1, fpMesh); fread(&m_iMinNumIndices0, sizeof(int), 1, fpMesh); if(m_pVertices0) { delete[] m_pVertices0; m_pVertices0 = nullptr; } if(m_iMaxNumVertices0 > 0) { m_pVertices0 = new _N3VertexT1[m_iMaxNumVertices0]; memset(m_pVertices0, 0, sizeof(_N3VertexT1)*m_iMaxNumVertices0); fread(m_pVertices0, sizeof(_N3VertexT1), m_iMaxNumVertices0, fpMesh); } if(m_pIndices0) { delete m_pIndices0; m_pIndices0 = nullptr; } if(m_iMaxNumIndices0 > 0) { m_pIndices0 = new uint16_t[m_iMaxNumIndices0]; memset(m_pIndices0, 0, sizeof(uint16_t)*m_iMaxNumIndices0); fread(m_pIndices0, sizeof(uint16_t), m_iMaxNumIndices0, fpMesh); } // NOTE: read in the "collapses" (I think this is used to set the vertices // based on how close the player is to the object) _N3EdgeCollapse* m_pCollapses = new _N3EdgeCollapse[(m_iNumCollapses0+1)]; memset(&m_pCollapses[m_iNumCollapses0], 0, sizeof(_N3EdgeCollapse)); if(m_iNumCollapses0 > 0) { fread(m_pCollapses, sizeof(_N3EdgeCollapse), m_iNumCollapses0, fpMesh); memset(&m_pCollapses[m_iNumCollapses0], 0, sizeof(_N3EdgeCollapse)); } int* m_pAllIndexChanges = new int[m_iTotalIndexChanges0]; if(m_iTotalIndexChanges0 > 0) { fread(m_pAllIndexChanges, sizeof(int), m_iTotalIndexChanges0, fpMesh); } int m_iLODCtrlValueCount0; fread(&m_iLODCtrlValueCount0, sizeof(int), 1, fpMesh); _N3LODCtrlValue* m_pLODCtrlValues = new _N3LODCtrlValue[m_iLODCtrlValueCount0]; if(m_iLODCtrlValueCount0) { fread(m_pLODCtrlValues, sizeof(_N3LODCtrlValue), m_iLODCtrlValueCount0, fpMesh); } if(m_pAllIndexChanges && m_iLODCtrlValueCount0) { int m_iNumIndices = 0; int m_iNumVertices = 0; int c = 0; int LOD = 0; // TEMP HACK /* if(m_szName0[0] == 'a') { LOD = 1; } */ int iDiff = m_pLODCtrlValues[LOD].iNumVertices - m_iNumVertices; while(m_pLODCtrlValues[LOD].iNumVertices > m_iNumVertices) { if(c >= m_iNumCollapses0) break; if(m_pCollapses[c].NumVerticesToLose+m_iNumVertices > m_pLODCtrlValues[LOD].iNumVertices) break; m_iNumIndices += m_pCollapses[c].NumIndicesToLose; m_iNumVertices += m_pCollapses[c].NumVerticesToLose; int tmp0 = m_pCollapses[c].iIndexChanges; int tmp1 = tmp0+m_pCollapses[c].NumIndicesToChange; for(int i=tmp0; i<tmp1; i++) { m_pIndices0[m_pAllIndexChanges[i]] = m_iNumVertices-1; } c++; m_iMaxNumIndices0 = m_iNumIndices; m_iMaxNumVertices0 = m_iNumVertices; } // NOTE: if we break on a collapse that isn't intended to be one we // should collapse up to then keep collapsing until we find one while(m_pCollapses[c].bShouldCollapse) { if(c >= m_iNumCollapses0) break; m_iNumIndices += m_pCollapses[c].NumIndicesToLose; m_iNumVertices += m_pCollapses[c].NumVerticesToLose; int tmp0 = m_pCollapses[c].iIndexChanges; int tmp1 = tmp0+m_pCollapses[c].NumIndicesToChange; for(int i=tmp0; i<tmp1; i++) { m_pIndices0[m_pAllIndexChanges[i]] = m_iNumVertices-1; } c++; m_iMaxNumIndices0 = m_iNumIndices; m_iMaxNumVertices0 = m_iNumVertices; } } delete[] m_pLODCtrlValues; delete[] m_pAllIndexChanges; delete[] m_pCollapses; printf("\nMeshName: %s\n", m_szName0); printf("m_iNumCollapses -> %d\n", m_iNumCollapses0); printf("m_iTotalIndexChanges -> %d\n", m_iTotalIndexChanges0); printf("m_iMaxNumVertices -> %d\n", m_iMaxNumVertices0); printf("m_iMaxNumIndices -> %d\n", m_iMaxNumIndices0); printf("m_iMinNumVertices -> %d\n", m_iMinNumVertices0); printf("m_iMinNumIndices -> %d\n", m_iMinNumIndices0); printf("m_iLODCtrlValueCount -> %d\n", m_iLODCtrlValueCount0); fclose(fpMesh); } //----------------------------------------------------------------------------- bool CN3BaseFileAccess_Load(FILE* hFile) { std::string m_szName = ""; int nL = 0; fread(&nL, sizeof(int), 1, hFile); if(nL > 0) { std::vector<char> buffer(nL+1, '\0'); fread(&buffer[0], sizeof(char), nL, hFile); m_szName = &buffer[0]; } return true; } //----------------------------------------------------------------------------- bool CN3CPlugBase_Load(FILE* hFile) { CN3BaseFileAccess_Load(hFile); int nL = 0; char szFN[512] = ""; e_PlugType m_ePlugType; fread(&m_ePlugType, sizeof(e_PlugType), 1, hFile); if(m_ePlugType > PLUGTYPE_MAX) { m_ePlugType = PLUGTYPE_NORMAL; } int m_nJointIndex; fread(&m_nJointIndex, sizeof(int), 1, hFile); glm::vec3 m_vPosition; fread(&m_vPosition, sizeof(glm::vec3), 1, hFile); _N3Matrix44 m_MtxRot; fread(&m_MtxRot, sizeof(_N3Matrix44), 1, hFile); glm::vec3 m_vScale; fread(&m_vScale, sizeof(glm::vec3), 1, hFile); _N3Material m_Mtl; fread(&m_Mtl, sizeof(_N3Material), 1, hFile); fread(&nL, sizeof(int), 1, hFile); if(nL > 0) { fread(szFN, sizeof(char), nL, hFile); N3LoadMesh(szFN); } fread(&nL, sizeof(int), 1, hFile); if(nL > 0) { fread(szFN, sizeof(char), nL, hFile); szFN[nL] = '\0'; N3LoadTexture(szFN); } return 0; } //----------------------------------------------------------------------------- bool CN3CPlug_Load(FILE* hFile) { CN3CPlugBase_Load(hFile); return true; } //----------------------------------------------------------------------------- bool CN3IMesh_Create(int nFC, int nVC, int nUVC) { if(nFC<=0 || nVC<=0) return false; m_nFC = nFC; m_nVC = nVC; if(m_pVertices) delete m_pVertices; if(m_pwVtxIndices) delete m_pwVtxIndices; if(m_pfUVs) delete m_pfUVs; if(m_pwUVsIndices) delete m_pwUVsIndices; m_pVertices = new __VertexXyzNormal[nVC]; memset(m_pVertices, 0, sizeof(__VertexXyzNormal) * nVC); m_pwVtxIndices = new uint16_t[nFC*3]; memset(m_pwVtxIndices, 0, 2 * nFC * 3); // uint16_t if(nUVC > 0) { m_nUVC = nUVC; m_pfUVs = new float[nUVC*2]; memset(m_pfUVs, 0, 8 * nUVC); m_pwUVsIndices = new uint16_t[nFC*3]; memset(m_pwUVsIndices, 0, 2 * nFC * 3); // uint16_t } return true; } //----------------------------------------------------------------------------- bool CN3Skin_Create(int nFC, int nVC, int nUVC) { if(false == CN3IMesh_Create(nFC, nVC, nUVC)) return false; delete [] m_pSkinVertices; m_pSkinVertices = new __VertexSkinned[nVC]; memset(m_pSkinVertices, 0, sizeof(__VertexSkinned)*nVC); return true; } //----------------------------------------------------------------------------- bool CN3IMesh_Load(FILE* hFile) { CN3BaseFileAccess_Load(hFile); int nFC = 0, nVC = 0, nUVC = 0; fread(&nFC, sizeof(int), 1, hFile); fread(&nVC, sizeof(int), 1, hFile); fread(&nUVC, sizeof(int), 1, hFile); if(nFC > 0 && nVC > 0) { CN3Skin_Create(nFC, nVC, nUVC); fread(m_pVertices, sizeof(__VertexXyzNormal), nVC, hFile); fread(m_pwVtxIndices, 2*3, nFC, hFile); } if(m_nUVC > 0) { fread(m_pfUVs, 8, nUVC, hFile); fread(m_pwUVsIndices, 2*3, nFC, hFile); } return true; } //----------------------------------------------------------------------------- bool CN3Skin_Load(FILE* hFile) { CN3IMesh_Load(hFile); return true; } //----------------------------------------------------------------------------- bool CN3CPart_Load(FILE* hFile) { CN3BaseFileAccess_Load(hFile); int nL = 0; char szFN[256] = ""; int m_dwReserved; fread(&m_dwReserved, sizeof(int), 1, hFile); _N3Material m_MtlOrg; fread(&m_MtlOrg, sizeof(_N3Material), 1, hFile); fread(&nL, sizeof(int), 1, hFile); if(nL > 0) { fread(szFN, sizeof(char), nL, hFile); N3LoadTexture(szFN); } fread(&nL, sizeof(int), 1, hFile); if(nL > 0) { fread(szFN, sizeof(char), nL, hFile); szFN[nL] = '\0'; FILE* fpSkin = fopen(szFN, "rb"); if(fpSkin == nullptr) { fprintf(stderr, "\nERROR: Missing skin %s\n", szFN); return false; } CN3BaseFileAccess_Load(fpSkin); CN3Skin_Load(fpSkin); } return true; } //----------------------------------------------------------------------------- e_ItemType MakeResrcFileNameForUPC( __TABLE_ITEM_BASIC* pItem, std::string* pszResrcFN, std::string* pszIconFN, e_PartPosition& ePartPosition, e_PlugPosition& ePlugPosition, e_Race eRace ) { ePartPosition = PART_POS_UNKNOWN; ePlugPosition = PLUG_POS_UNKNOWN; if(pszResrcFN) *pszResrcFN = ""; if(pszIconFN) *pszIconFN = ""; if(nullptr == pItem) return ITEM_TYPE_UNKNOWN; e_ItemType eType = ITEM_TYPE_UNKNOWN; e_ItemPosition ePos = (e_ItemPosition)pItem->byAttachPoint; int iPos = 0; std::string szExt; if(ePos>=ITEM_POS_DUAL && ePos<=ITEM_POS_TWOHANDLEFT) { if(ITEM_POS_DUAL==ePos||ITEM_POS_RIGHTHAND==ePos||ITEM_POS_TWOHANDRIGHT==ePos) ePlugPosition = PLUG_POS_RIGHTHAND; else if(ITEM_POS_LEFTHAND==ePos||ITEM_POS_TWOHANDLEFT==ePos) ePlugPosition = PLUG_POS_LEFTHAND; eType = ITEM_TYPE_PLUG; szExt = ".n3cplug"; } else if(ePos>=ITEM_POS_UPPER && ePos<=ITEM_POS_SHOES) { if(ITEM_POS_UPPER == ePos) ePartPosition = PART_POS_UPPER; else if(ITEM_POS_LOWER == ePos) ePartPosition = PART_POS_LOWER; else if(ITEM_POS_HEAD == ePos) ePartPosition = PART_POS_HAIR_HELMET; else if(ITEM_POS_GLOVES == ePos) ePartPosition = PART_POS_HANDS; else if(ITEM_POS_SHOES == ePos) ePartPosition = PART_POS_FEET; eType = ITEM_TYPE_PART; szExt = ".n3cpart"; iPos = ePartPosition + 1; } else if(ePos>=ITEM_POS_EAR && ePos<=ITEM_POS_INVENTORY) { eType = ITEM_TYPE_ICONONLY; szExt = ".dxt"; } else if(ePos == ITEM_POS_GOLD) { eType = ITEM_TYPE_GOLD; szExt = ".dxt"; } else if(ePos == ITEM_POS_SONGPYUN) { eType = ITEM_TYPE_SONGPYUN; szExt = ".dxt"; } else printf("Invalid Item Position\n"); std::vector<char> buffer(256, '\0'); if(pszResrcFN) { if(pItem->dwIDResrc) { if(eRace!=RACE_UNKNOWN && ePos>=/*ITEM_POS_DUAL*/ITEM_POS_UPPER && ePos<=ITEM_POS_SHOES) { // NOTE: no idea but perhaps this will work for now sprintf(&buffer[0], "Item\\%.1d_%.4d_%.2d_%.1d%s", (pItem->dwIDResrc / 10000000), ((pItem->dwIDResrc / 1000) % 10000) + eRace, (pItem->dwIDResrc / 10) % 100, pItem->dwIDResrc % 10, szExt.c_str() ); } else { sprintf(&buffer[0], "Item\\%.1d_%.4d_%.2d_%.1d%s", (pItem->dwIDResrc / 10000000), (pItem->dwIDResrc / 1000) % 10000, (pItem->dwIDResrc / 10) % 100, pItem->dwIDResrc % 10, szExt.c_str() ); } *pszResrcFN = &buffer[0]; } else { *pszResrcFN = ""; } } if(pszIconFN) { sprintf(&buffer[0], "UI\\ItemIcon_%.1d_%.4d_%.2d_%.1d.dxt", (pItem->dwIDIcon / 10000000), (pItem->dwIDIcon / 1000) % 10000, (pItem->dwIDIcon / 10) % 100, pItem->dwIDIcon % 10 ); *pszIconFN = &buffer[0]; } return eType; } //----------------------------------------------------------------------------- void GenerateScene(void) { float* vertices = nullptr; uint32_t* elements = nullptr; int iVC = 0; int iFC = 0; if(eType == ITEM_TYPE_PLUG) { vertices = new float[5*m_iMaxNumVertices0]; memset(vertices, 0, 5*m_iMaxNumVertices0); for(int i=0; i<m_iMaxNumVertices0; i++) { vertices[5*i+0] = m_pVertices0[i].x; vertices[5*i+1] = m_pVertices0[i].y; vertices[5*i+2] = m_pVertices0[i].z; vertices[5*i+3] = m_pVertices0[i].tu; vertices[5*i+4] = m_pVertices0[i].tv; } iVC = m_iMaxNumVertices0; iFC = m_iMaxNumIndices0/3; elements = new uint32_t[m_iMaxNumIndices0]; memset(elements, 0, m_iMaxNumIndices0*sizeof(uint32_t)); for(int i=0; i<m_iMaxNumIndices0; i++) { elements[i] = (uint32_t) m_pIndices0[i]; } } else if(eType == ITEM_TYPE_PART) { vertices = new float[5*3*m_nFC]; memset(vertices, 0, 5*3*m_nFC*sizeof(float)); for(int i=0; i<3*m_nFC; i++) { vertices[5*i+0] = m_pVertices[m_pwVtxIndices[i]].x; vertices[5*i+1] = m_pVertices[m_pwVtxIndices[i]].y; vertices[5*i+2] = m_pVertices[m_pwVtxIndices[i]].z; vertices[5*i+3] = m_pfUVs[2*m_pwUVsIndices[i]+0]; vertices[5*i+4] = m_pfUVs[2*m_pwUVsIndices[i]+1]; } iVC = 3*m_nFC; iFC = m_nFC; elements = new uint32_t[3*m_nFC]; memset(elements, 0, 3*m_nFC*sizeof(uint32_t)); for(int i=0; i<3*m_nFC; i++) { elements[i] = (uint32_t) (i); } } else if(eType==ITEM_TYPE_ICONONLY || eType==ITEM_TYPE_GOLD || eType==ITEM_TYPE_SONGPYUN) { // NOTE: need to offset the position to get the icon to display in the center float _vertices[] = { -0.25f+0.25f/4.0f, 0.25f-0.25f/4.0f, -0.1f, 0.0f, 0.0f, // Top-left 0.25f+0.25f/4.0f, 0.25f-0.25f/4.0f, -0.1f, 1.0f, 0.0f, // Top-right 0.25f+0.25f/4.0f, -0.25f-0.25f/4.0f, -0.1f, 1.0f, 1.0f, // Bottom-right -0.25f+0.25f/4.0f, -0.25f-0.25f/4.0f, -0.1f, 0.0f, 1.0f // Bottom-left }; vertices = new float[5*3*2]; memset(vertices, 0, 5*3*2*sizeof(float)); for(int i=0; i<5*3*2; i++) { vertices[i] = _vertices[i]; } iVC = 3*2; iFC = 2; uint32_t _elements[] = { 0, 1, 2, 2, 3, 0 }; elements = new uint32_t[3*2]; memset(elements, 0, 3*2*sizeof(uint32_t)); for(int i=0; i<3*2; i++) { elements[i] = _elements[i]; } } //---- m_Scene.mRootNode = new aiNode(); m_Scene.mMaterials = new aiMaterial*[1]; m_Scene.mMaterials[0] = nullptr; m_Scene.mNumMaterials = 1; m_Scene.mMaterials[0] = new aiMaterial(); aiString strTex(pTexName); m_Scene.mMaterials[0]->AddProperty( &strTex, AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0) ); if(vertices!=nullptr && elements!=nullptr) { m_Scene.mMeshes = new aiMesh*[1]; m_Scene.mMeshes[0] = nullptr; m_Scene.mNumMeshes = 1; m_Scene.mMeshes[0] = new aiMesh(); m_Scene.mMeshes[0]->mMaterialIndex = 0; m_Scene.mRootNode->mMeshes = new uint32_t[1]; m_Scene.mRootNode->mMeshes[0] = 0; m_Scene.mRootNode->mNumMeshes = 1; aiMesh* pMesh = m_Scene.mMeshes[0]; pMesh->mVertices = new aiVector3D[iVC]; pMesh->mNumVertices = iVC; pMesh->mTextureCoords[0] = new aiVector3D[iVC]; pMesh->mNumUVComponents[0] = iVC; for (int i = 0; i < iVC; ++i) { Vertex v; v.x = vertices[5*i+0]; v.y = vertices[5*i+1]; v.z = vertices[5*i+2]; v.u = vertices[5*i+3]; v.v = vertices[5*i+4]; pMesh->mVertices[i] = aiVector3D(v.x, v.y, v.z); pMesh->mTextureCoords[0][i] = aiVector3D(v.u, (1.0f-v.v), 0); } pMesh->mFaces = new aiFace[iFC]; pMesh->mNumFaces = iFC; for (int i = 0; i < iFC; ++i) { aiFace& face = pMesh->mFaces[i]; face.mIndices = new uint32_t[3]; face.mNumIndices = 3; face.mIndices[0] = elements[3*i+0]; face.mIndices[1] = elements[3*i+1]; face.mIndices[2] = elements[3*i+2]; } } else { printf("Failed!\n"); printf("\nERROR: Mesh data missing!\n"); system("pause"); exit(-1); } delete vertices; delete elements; printf("Success!\n"); } //----------------------------------------------------------------------------- bool N3MeshConverter::Convert(char* filename) { Assimp::Exporter* pExporter = new Assimp::Exporter(); int len_fn = strlen(filename); char* exten = &filename[len_fn-7]; if(!strcmp(exten, "n3cplug")) { eType = ITEM_TYPE_PLUG; char tmp[0xFF] = ""; sprintf(tmp, "./item/%s", filename); FILE* pFile = fopen(tmp, "rb"); if(pFile == nullptr) { fprintf(stderr, "ERROR: Missing N3Plug %s\n", tmp); delete pExporter; return false; } CN3CPlug_Load(pFile); fclose(pFile); } else if(!strcmp(exten, "n3cpart")) { eType = ITEM_TYPE_PART; char tmp[0xFF] = ""; sprintf(tmp, "./item/%s", filename); FILE* pFile = fopen(tmp, "rb"); if(pFile == nullptr) { fprintf(stderr, "ERROR: Missing N3Part %s\n", tmp); delete pExporter; return false; } CN3CPart_Load(pFile); fclose(pFile); } printf("\n\"%s\"", filename); printf("\nGenerating scene... "); GenerateScene(); printf("\nExporting to %s... ", "obj"); char output_fn[0xFFFF] = {}; filename[len_fn-8] = '\0'; sprintf(output_fn, "./Item_output/%s.obj", filename); aiReturn ret = pExporter->Export(&m_Scene, "obj", output_fn); if(ret == aiReturn_SUCCESS) { printf("Done!\n"); } else { printf("Failed!\n"); delete pExporter; return false; } delete pExporter; return true; }
1
0.980875
1
0.980875
game-dev
MEDIA
0.471408
game-dev,graphics-rendering
0.995374
1
0.995374
EatBingChilling/LuminaCN
2,121
app/src/main/java/com/phoenix/luminacn/game/module/impl/effect/BaseEffectElement.kt
package com.phoenix.luminacn.game.module.impl.effect import com.phoenix.luminacn.constructors.CheatCategory import com.phoenix.luminacn.constructors.Element import com.phoenix.luminacn.game.InterceptablePacket import com.phoenix.luminacn.game.module.api.setting.EffectSetting import org.cloudburstmc.protocol.bedrock.data.entity.EntityDataTypes import org.cloudburstmc.protocol.bedrock.packet.MobEffectPacket import org.cloudburstmc.protocol.bedrock.packet.PlayerAuthInputPacket abstract class BaseEffectElement( name: String, displayNameResId: Int, private val effectId: Int? = null, private val effectSetting: Number? = null ) : Element( name = name, category = CheatCategory.World, displayNameResId = displayNameResId ) { protected val amplifierValue by floatValue("amplifier", 1f, 1f..5f) protected val effect by EffectSetting(this, EntityDataTypes.VISIBLE_MOB_EFFECTS, effectSetting!!.toInt()) override fun onDisabled() { super.onDisabled() if (isSessionCreated && effectId != null) { removeEffect() } } override fun beforePacketBound(interceptablePacket: InterceptablePacket) { if (!isEnabled) return val packet = interceptablePacket.packet if (packet is PlayerAuthInputPacket && session.localPlayer.tickExists % 20 == 0L && effectId != null) { addEffect() } } protected fun addEffect(customEffectId: Int? = null) { session.clientBound(MobEffectPacket().apply { runtimeEntityId = session.localPlayer.runtimeEntityId event = MobEffectPacket.Event.ADD this.effectId = customEffectId ?: effectId amplifier = amplifierValue.toInt() - 1 isParticles = false duration = 360000 }) } protected fun removeEffect(customEffectId: Int? = null) { session.clientBound(MobEffectPacket().apply { runtimeEntityId = session.localPlayer.runtimeEntityId event = MobEffectPacket.Event.REMOVE this.effectId = customEffectId ?: effectId }) } }
1
0.905071
1
0.905071
game-dev
MEDIA
0.962394
game-dev
0.921802
1
0.921802
Rakashazi/emu-ex-plus-alpha
2,169
imagine/include/imagine/base/EventLoop.hh
#pragma once /* This file is part of Imagine. Imagine 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. Imagine 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 Imagine. If not, see <http://www.gnu.org/licenses/> */ #include <imagine/config/defs.hh> #if defined __ANDROID__ #include <imagine/base/eventloop/ALooperEventLoop.hh> #elif defined __linux__ #include <imagine/base/eventloop/GlibEventLoop.hh> #elif defined __APPLE__ #include <imagine/base/eventloop/CFEventLoop.hh> #endif #include <utility> #include <string_view> namespace IG { class EventLoop : public EventLoopImpl { public: using EventLoopImpl::EventLoopImpl; constexpr EventLoop() = default; static EventLoop forThread(); static EventLoop makeForThread(); void run(const bool& condition); void stop(); explicit operator bool() const; }; struct FDEventSourceDesc { std::string_view debugLabel{}; std::optional<EventLoop> eventLoop{}; PollEventFlags events{pollEventInput}; }; class FDEventSource : public FDEventSourceImpl { public: constexpr FDEventSource() = default; FDEventSource(MaybeUniqueFileDescriptor fd, FDEventSourceDesc desc, PollEventDelegate del): FDEventSourceImpl{std::move(fd), desc, del}, debugLabel_{desc.debugLabel.size() ? desc.debugLabel : "unnamed"} { if(desc.eventLoop) attach(*desc.eventLoop, desc.events); } bool attach(EventLoop loop = {}, PollEventFlags events = pollEventInput); void detach(); void setEvents(PollEventFlags); void dispatchEvents(PollEventFlags); void setCallback(PollEventDelegate); bool hasEventLoop() const; int fd() const; std::string_view debugLabel() const { return debugLabel_; } protected: ConditionalMember<Config::DEBUG_BUILD, std::string_view> debugLabel_{}; }; }
1
0.725485
1
0.725485
game-dev
MEDIA
0.190652
game-dev
0.825583
1
0.825583
MohistMC/Youer
2,828
src/main/java/org/bukkit/craftbukkit/inventory/view/CraftAnvilView.java
package org.bukkit.craftbukkit.inventory.view; import net.minecraft.world.inventory.AnvilMenu; import org.bukkit.craftbukkit.inventory.CraftInventoryAnvil; import org.bukkit.craftbukkit.inventory.CraftInventoryView; import org.bukkit.entity.HumanEntity; import org.bukkit.inventory.AnvilInventory; import org.bukkit.inventory.view.AnvilView; import org.jetbrains.annotations.Nullable; public class CraftAnvilView extends CraftInventoryView<AnvilMenu, AnvilInventory> implements AnvilView { public CraftAnvilView(final HumanEntity player, final AnvilInventory viewing, final AnvilMenu container) { super(player, viewing, container); } @Nullable @Override public String getRenameText() { return this.container.itemName; } @Override public int getRepairItemCountCost() { return this.container.repairItemCountCost; } @Override public int getRepairCost() { return this.container.getCost(); } @Override public int getMaximumRepairCost() { return this.container.maximumRepairCost; } @Override public void setRepairItemCountCost(final int cost) { this.container.repairItemCountCost = cost; } @Override public void setRepairCost(final int cost) { this.container.cost.set(cost); } @Override public void setMaximumRepairCost(final int cost) { this.container.maximumRepairCost = cost; } // Paper start @Override public boolean bypassesEnchantmentLevelRestriction() { return this.container.bypassEnchantmentLevelRestriction; } @Override public void bypassEnchantmentLevelRestriction(final boolean bypassEnchantmentLevelRestriction) { this.container.bypassEnchantmentLevelRestriction = bypassEnchantmentLevelRestriction; } // Paper end public void updateFromLegacy(CraftInventoryAnvil legacy) { if (legacy.isRepairCostSet()) { this.setRepairCost(legacy.getRepairCost()); } if (legacy.isRepairCostAmountSet()) { this.setRepairItemCountCost(legacy.getRepairCostAmount()); } if (legacy.isMaximumRepairCostSet()) { this.setMaximumRepairCost(legacy.getMaximumRepairCost()); } } // Purpur start - Anvil API @Override public boolean canBypassCost() { return this.container.bypassCost; } @Override public void setBypassCost(boolean bypassCost) { this.container.bypassCost = bypassCost; } @Override public boolean canDoUnsafeEnchants() { return this.container.canDoUnsafeEnchants; } @Override public void setDoUnsafeEnchants(boolean canDoUnsafeEnchants) { this.container.canDoUnsafeEnchants = canDoUnsafeEnchants; } // Purpur end - Anvil API }
1
0.852808
1
0.852808
game-dev
MEDIA
0.994376
game-dev
0.854036
1
0.854036
matt-kempster/m2c
2,618
tests/end_to_end/misc1/irix-o2-regvars.s
.set noat # allow manual use of $at .set noreorder # don't insert nops after branches glabel test /* 0000B0 004000B0 3C0E0041 */ lui $t6, %hi(D_410170) /* 0000B4 004000B4 8DCE0170 */ lw $t6, %lo(D_410170)($t6) /* 0000B8 004000B8 27BDFFD0 */ addiu $sp, $sp, -0x30 /* 0000BC 004000BC 0004C0C0 */ sll $t8, $a0, 3 /* 0000C0 004000C0 AFBF001C */ sw $ra, 0x1c($sp) /* 0000C4 004000C4 AFA40030 */ sw $a0, 0x30($sp) /* 0000C8 004000C8 01D81021 */ addu $v0, $t6, $t8 /* 0000CC 004000CC 8C460004 */ lw $a2, 4($v0) /* 0000D0 004000D0 8C590008 */ lw $t9, 8($v0) /* 0000D4 004000D4 00A03825 */ move $a3, $a1 /* 0000D8 004000D8 00807825 */ move $t7, $a0 /* 0000DC 004000DC 24C60001 */ addiu $a2, $a2, 1 /* 0000E0 004000E0 AFA6002C */ sw $a2, 0x2c($sp) /* 0000E4 004000E4 AFAF0010 */ sw $t7, 0x10($sp) /* 0000E8 004000E8 24040001 */ addiu $a0, $zero, 1 /* 0000EC 004000EC 24050002 */ addiu $a1, $zero, 2 /* 0000F0 004000F0 0C100050 */ jal func_00400140 /* 0000F4 004000F4 AFB90024 */ sw $t9, 0x24($sp) /* 0000F8 004000F8 8FA6002C */ lw $a2, 0x2c($sp) /* 0000FC 004000FC 14400003 */ bnez $v0, .L0040010C /* 000100 00400100 00402825 */ move $a1, $v0 /* 000104 00400104 1000000A */ b .L00400130 /* 000108 00400108 00001025 */ move $v0, $zero .L0040010C: /* 00010C 0040010C 8FA40024 */ lw $a0, 0x24($sp) /* 000110 00400110 0C100056 */ jal func_00400158 /* 000114 00400114 AFA50028 */ sw $a1, 0x28($sp) /* 000118 00400118 8FA90030 */ lw $t1, 0x30($sp) /* 00011C 0040011C 3C010041 */ lui $at, %hi(D_410178) /* 000120 00400120 24080005 */ addiu $t0, $zero, 5 /* 000124 00400124 00290821 */ addu $at, $at, $t1 /* 000128 00400128 8FA20028 */ lw $v0, 0x28($sp) /* 00012C 0040012C A0280178 */ sb $t0, %lo(D_410178)($at) .L00400130: /* 000130 00400130 8FBF001C */ lw $ra, 0x1c($sp) /* 000134 00400134 27BD0030 */ addiu $sp, $sp, 0x30 /* 000138 00400138 03E00008 */ jr $ra /* 00013C 0040013C 00000000 */ nop glabel func_00400140 /* 000140 00400140 AFA40000 */ sw $a0, ($sp) /* 000144 00400144 AFA50004 */ sw $a1, 4($sp) /* 000148 00400148 AFA60008 */ sw $a2, 8($sp) /* 00014C 0040014C AFA7000C */ sw $a3, 0xc($sp) /* 000150 00400150 03E00008 */ jr $ra /* 000154 00400154 24020001 */ addiu $v0, $zero, 1 glabel func_00400158 /* 000158 00400158 AFA40000 */ sw $a0, ($sp) /* 00015C 0040015C AFA50004 */ sw $a1, 4($sp) /* 000160 00400160 AFA60008 */ sw $a2, 8($sp) /* 000164 00400164 03E00008 */ jr $ra /* 000168 00400168 24020001 */ addiu $v0, $zero, 1 /* 00016C 0040016C 00000000 */ nop
1
0.603046
1
0.603046
game-dev
MEDIA
0.724596
game-dev
0.519849
1
0.519849
Potion-Studios/Oh-The-Biomes-Weve-Gone
2,070
Common/src/main/java/net/potionstudios/biomeswevegone/world/level/levelgen/surfacerules/BandsRuleSource.java
package net.potionstudios.biomeswevegone.world.level.levelgen.surfacerules; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.util.KeyDispatchDataCodec; import net.minecraft.util.random.SimpleWeightedRandomList; import net.minecraft.util.valueproviders.IntProvider; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.SurfaceRules; import org.jetbrains.annotations.NotNull; public record BandsRuleSource(SimpleWeightedRandomList<BlockState> bandStates, IntProvider bandSizeProvider, IntProvider bandsCountProvider, float frequency, int noiseScale) implements SurfaceRules.RuleSource { public static final KeyDispatchDataCodec<BandsRuleSource> CODEC = KeyDispatchDataCodec.of(RecordCodecBuilder.mapCodec(builder -> builder.group( SimpleWeightedRandomList.wrappedCodec(BlockState.CODEC).fieldOf("band_states").forGetter(bandsRuleSource -> bandsRuleSource.bandStates), IntProvider.POSITIVE_CODEC.fieldOf("band_size").forGetter(bandsRuleSource -> bandsRuleSource.bandSizeProvider), IntProvider.POSITIVE_CODEC.fieldOf("bands_count").forGetter(bandsRuleSource -> bandsRuleSource.bandsCountProvider), Codec.FLOAT.fieldOf("frequency").forGetter(bandsRuleSource -> bandsRuleSource.frequency), Codec.INT.fieldOf("noise_scale").forGetter(bandsRuleSource -> bandsRuleSource.noiseScale) ).apply(builder, BandsRuleSource::new)) ); @Override public @NotNull KeyDispatchDataCodec<? extends SurfaceRules.RuleSource> codec() { return CODEC; } @Override public SurfaceRules.SurfaceRule apply(SurfaceRules.Context context) { return (x, y, z) -> { if (context.system instanceof BandsContext bandsContext) { return bandsContext.getBandsState(this, this.bandStates, this.bandSizeProvider, this.bandsCountProvider, x, y, z, this.frequency, this.noiseScale); } return Blocks.STONE.defaultBlockState(); }; } }
1
0.589963
1
0.589963
game-dev
MEDIA
0.984806
game-dev
0.780984
1
0.780984
Sandern/lambdawars
22,441
src/game/client/C_MaterialModifyControl.cpp
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: Material Modify control entity. // //=============================================================================// #include "cbase.h" #include "ProxyEntity.h" #include "materialsystem/IMaterial.h" #include "materialsystem/IMaterialVar.h" #include "materialsystem/ITexture.h" #include "iviewrender.h" #include "texture_group_names.h" #include "BaseAnimatedTextureProxy.h" #include "imaterialproxydict.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define MATERIAL_MODIFY_STRING_SIZE 255 #define MATERIAL_MODIFY_ANIMATION_UNSET -1 // Must match MaterialModifyControl.cpp enum MaterialModifyMode_t { MATERIAL_MODIFY_MODE_NONE = 0, MATERIAL_MODIFY_MODE_SETVAR = 1, MATERIAL_MODIFY_MODE_ANIM_SEQUENCE = 2, MATERIAL_MODIFY_MODE_FLOAT_LERP = 3, }; ConVar debug_materialmodifycontrol_client( "debug_materialmodifycontrol_client", "0" ); struct materialanimcommands_t { int iFrameStart; int iFrameEnd; bool bWrap; float flFrameRate; }; struct materialfloatlerpcommands_t { int flStartValue; int flEndValue; float flTransitionTime; }; //------------------------------------------------------------------------------ // FIXME: This really should inherit from something more lightweight //------------------------------------------------------------------------------ class C_MaterialModifyControl : public C_BaseEntity { public: DECLARE_CLASS( C_MaterialModifyControl, C_BaseEntity ); C_MaterialModifyControl(); void OnPreDataChanged( DataUpdateType_t updateType ); void OnDataChanged( DataUpdateType_t updateType ); bool ShouldDraw(); IMaterial *GetMaterial( void ) { return m_pMaterial; } const char *GetMaterialVariableName( void ) { return m_szMaterialVar; } const char *GetMaterialVariableValue( void ) { return m_szMaterialVarValue; } DECLARE_CLIENTCLASS(); // Animated texture and Float Lerp usage bool HasNewAnimationCommands( void ) { return m_bHasNewAnimationCommands; } void ClearAnimationCommands( void ) { m_bHasNewAnimationCommands = false; } // Animated texture usage void GetAnimationCommands( materialanimcommands_t *pCommands ); // FloatLerp usage void GetFloatLerpCommands( materialfloatlerpcommands_t *pCommands ); void SetAnimationStartTime( float flTime ) { m_flAnimationStartTime = flTime; } float GetAnimationStartTime( void ) const { return m_flAnimationStartTime; } MaterialModifyMode_t GetModifyMode( void ) const { return ( MaterialModifyMode_t)m_nModifyMode; } private: char m_szMaterialName[MATERIAL_MODIFY_STRING_SIZE]; char m_szMaterialVar[MATERIAL_MODIFY_STRING_SIZE]; char m_szMaterialVarValue[MATERIAL_MODIFY_STRING_SIZE]; IMaterial *m_pMaterial; bool m_bHasNewAnimationCommands; // Animation commands from the server int m_iFrameStart; int m_iFrameEnd; bool m_bWrap; float m_flFramerate; bool m_bNewAnimCommandsSemaphore; bool m_bOldAnimCommandsSemaphore; // Float lerp commands from the server float m_flFloatLerpStartValue; float m_flFloatLerpEndValue; float m_flFloatLerpTransitionTime; bool m_bFloatLerpWrap; float m_flAnimationStartTime; int m_nModifyMode; }; IMPLEMENT_CLIENTCLASS_DT(C_MaterialModifyControl, DT_MaterialModifyControl, CMaterialModifyControl) RecvPropString( RECVINFO( m_szMaterialName ) ), RecvPropString( RECVINFO( m_szMaterialVar ) ), RecvPropString( RECVINFO( m_szMaterialVarValue ) ), RecvPropInt( RECVINFO(m_iFrameStart) ), RecvPropInt( RECVINFO(m_iFrameEnd) ), RecvPropInt( RECVINFO(m_bWrap) ), RecvPropFloat( RECVINFO(m_flFramerate) ), RecvPropInt( RECVINFO(m_bNewAnimCommandsSemaphore) ), RecvPropFloat( RECVINFO(m_flFloatLerpStartValue) ), RecvPropFloat( RECVINFO(m_flFloatLerpEndValue) ), RecvPropFloat( RECVINFO(m_flFloatLerpTransitionTime) ), RecvPropInt( RECVINFO(m_bFloatLerpWrap) ), RecvPropInt( RECVINFO(m_nModifyMode) ), END_RECV_TABLE() //------------------------------------------------------------------------------ // Purpose: //------------------------------------------------------------------------------ C_MaterialModifyControl::C_MaterialModifyControl() { m_pMaterial = NULL; m_bOldAnimCommandsSemaphore = false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_MaterialModifyControl::OnPreDataChanged( DataUpdateType_t updateType ) { BaseClass::OnPreDataChanged( updateType ); m_bOldAnimCommandsSemaphore = m_bNewAnimCommandsSemaphore; } //------------------------------------------------------------------------------ // Purpose: //------------------------------------------------------------------------------ void C_MaterialModifyControl::OnDataChanged( DataUpdateType_t updateType ) { if( updateType == DATA_UPDATE_CREATED ) { m_pMaterial = materials->FindMaterial( m_szMaterialName, TEXTURE_GROUP_OTHER ); // Clear out our variables m_bHasNewAnimationCommands = true; } // Detect changes in the anim commands if ( m_bNewAnimCommandsSemaphore != m_bOldAnimCommandsSemaphore ) { m_bHasNewAnimationCommands = true; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_MaterialModifyControl::GetAnimationCommands( materialanimcommands_t *pCommands ) { pCommands->iFrameStart = m_iFrameStart; pCommands->iFrameEnd = m_iFrameEnd; pCommands->bWrap = m_bWrap; pCommands->flFrameRate = m_flFramerate; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_MaterialModifyControl::GetFloatLerpCommands( materialfloatlerpcommands_t *pCommands ) { pCommands->flStartValue = m_flFloatLerpStartValue; pCommands->flEndValue = m_flFloatLerpEndValue; pCommands->flTransitionTime = m_flFloatLerpTransitionTime; } //------------------------------------------------------------------------------ // Purpose: We don't draw. //------------------------------------------------------------------------------ bool C_MaterialModifyControl::ShouldDraw() { return false; } //============================================================================= // // THE MATERIALMODIFYPROXY ITSELF // class CMaterialModifyProxy : public CBaseAnimatedTextureProxy { public: CMaterialModifyProxy(); virtual ~CMaterialModifyProxy(); virtual bool Init( IMaterial *pMaterial, KeyValues *pKeyValues ); virtual void OnBind( void *pEntity ); virtual IMaterial *GetMaterial(); private: void OnBindSetVar( C_MaterialModifyControl *pControl ); void OnBindAnimatedTexture( C_MaterialModifyControl *pControl ); void OnBindFloatLerp( C_MaterialModifyControl *pControl ); float GetAnimationStartTime( void* pArg ); void AnimationWrapped( void* pArg ); IMaterial *m_pMaterial; // texture animation stuff int m_iFrameStart; int m_iFrameEnd; bool m_bReachedEnd; bool m_bCustomWrap; float m_flCustomFramerate; // float lerp stuff IMaterialVar *m_pMaterialVar; int m_flStartValue; int m_flEndValue; float m_flStartTime; float m_flTransitionTime; }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CMaterialModifyProxy::CMaterialModifyProxy() { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CMaterialModifyProxy::~CMaterialModifyProxy() { } bool CMaterialModifyProxy::Init( IMaterial *pMaterial, KeyValues *pKeyValues ) { // set var stuff m_pMaterial = pMaterial; // float lerp stuff m_flStartValue = MATERIAL_MODIFY_ANIMATION_UNSET; m_flEndValue = MATERIAL_MODIFY_ANIMATION_UNSET; // animated stuff // m_pMaterial = pMaterial; // m_iFrameStart = MATERIAL_MODIFY_ANIMATION_UNSET; // m_iFrameEnd = MATERIAL_MODIFY_ANIMATION_UNSET; // m_bReachedEnd = false; // return CBaseAnimatedTextureProxy::Init( pMaterial, pKeyValues ); return true; } void CMaterialModifyProxy::OnBind( void *pEntity ) { // Get the modified material vars from the entity input IClientRenderable *pRend = (IClientRenderable *)pEntity; if ( pRend ) { C_BaseEntity *pBaseEntity = pRend->GetIClientUnknown()->GetBaseEntity(); if ( pBaseEntity ) { if( debug_materialmodifycontrol_client.GetBool() ) { // DevMsg( 1, "%s\n", pBaseEntity->GetDebugName() ); } int numChildren = 0; bool gotOne = false; for ( C_BaseEntity *pChild = pBaseEntity->FirstMoveChild(); pChild; pChild = pChild->NextMovePeer() ) { numChildren++; C_MaterialModifyControl *pControl = dynamic_cast<C_MaterialModifyControl*>( pChild ); if ( !pControl ) continue; if( debug_materialmodifycontrol_client.GetBool() ) { // DevMsg( 1, "pControl: 0x%p\n", pControl ); } switch( pControl->GetModifyMode() ) { case MATERIAL_MODIFY_MODE_NONE: break; case MATERIAL_MODIFY_MODE_SETVAR: gotOne = true; OnBindSetVar( pControl ); break; case MATERIAL_MODIFY_MODE_ANIM_SEQUENCE: OnBindAnimatedTexture( pControl ); break; case MATERIAL_MODIFY_MODE_FLOAT_LERP: OnBindFloatLerp( pControl ); break; default: Assert( 0 ); break; } } if( gotOne ) { // DevMsg( 1, "numChildren: %d\n", numChildren ); } } } } IMaterial *CMaterialModifyProxy::GetMaterial() { return m_pMaterial; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMaterialModifyProxy::OnBindSetVar( C_MaterialModifyControl *pControl ) { IMaterial *pMaterial = pControl->GetMaterial(); if( !pMaterial ) { Assert( 0 ); return; } if ( pMaterial != m_pMaterial ) { // Warning( "\t%s!=%s\n", pMaterial->GetName(), m_pMaterial->GetName() ); return; } bool bFound; IMaterialVar *pMaterialVar = pMaterial->FindVar( pControl->GetMaterialVariableName(), &bFound, false ); if ( !bFound ) return; if( Q_strcmp( pControl->GetMaterialVariableValue(), "" ) ) { // const char *pMaterialName = m_pMaterial->GetName(); // const char *pMaterialVarName = pMaterialVar->GetName(); // const char *pMaterialVarValue = pControl->GetMaterialVariableValue(); // if( debug_materialmodifycontrol_client.GetBool() // && Q_stristr( m_pMaterial->GetName(), "faceandhair" ) // && Q_stristr( pMaterialVar->GetName(), "self" ) // ) // { // static int count = 0; // DevMsg( 1, "CMaterialModifyProxy::OnBindSetVar \"%s\" %s=%s %d pControl=0x%p\n", // m_pMaterial->GetName(), pMaterialVar->GetName(), pControl->GetMaterialVariableValue(), count++, pControl ); // } pMaterialVar->SetValueAutodetectType( pControl->GetMaterialVariableValue() ); } } //----------------------------------------------------------------------------- // Does the dirty deed //----------------------------------------------------------------------------- void CMaterialModifyProxy::OnBindAnimatedTexture( C_MaterialModifyControl *pControl ) { assert ( m_AnimatedTextureVar ); if( m_AnimatedTextureVar->GetType() != MATERIAL_VAR_TYPE_TEXTURE ) return; ITexture *pTexture; pTexture = m_AnimatedTextureVar->GetTextureValue(); if ( !pControl ) return; if ( pControl->HasNewAnimationCommands() ) { // Read the data from the modify entity materialanimcommands_t sCommands; pControl->GetAnimationCommands( &sCommands ); m_iFrameStart = sCommands.iFrameStart; m_iFrameEnd = sCommands.iFrameEnd; m_bCustomWrap = sCommands.bWrap; m_flCustomFramerate = sCommands.flFrameRate; m_bReachedEnd = false; m_flStartTime = gpGlobals->curtime; pControl->ClearAnimationCommands(); } // Init all the vars based on whether we're using the base material settings, // or the custom ones from the entity input. int numFrames; bool bWrapAnimation; float flFrameRate; int iLastFrame; // Do we have a custom frame section from the server? if ( m_iFrameStart != MATERIAL_MODIFY_ANIMATION_UNSET ) { if ( m_iFrameEnd == MATERIAL_MODIFY_ANIMATION_UNSET ) { m_iFrameEnd = pTexture->GetNumAnimationFrames(); } numFrames = (m_iFrameEnd - m_iFrameStart) + 1; bWrapAnimation = m_bCustomWrap; flFrameRate = m_flCustomFramerate; iLastFrame = (m_iFrameEnd - 1); } else { numFrames = pTexture->GetNumAnimationFrames(); bWrapAnimation = m_WrapAnimation; flFrameRate = m_FrameRate; iLastFrame = (numFrames - 1); } // Have we already reached the end? If so, stay there. if ( m_bReachedEnd && !bWrapAnimation ) { m_AnimatedTextureFrameNumVar->SetIntValue( iLastFrame ); return; } // NOTE: Must not use relative time based methods here // because the bind proxy can be called many times per frame. // Prevent multiple Wrap callbacks to be sent for no wrap mode float startTime; if ( m_iFrameStart != MATERIAL_MODIFY_ANIMATION_UNSET ) { startTime = m_flStartTime; } else { startTime = GetAnimationStartTime(pControl); } float deltaTime = gpGlobals->curtime - startTime; float prevTime = deltaTime - gpGlobals->frametime; // Clamp.. if (deltaTime < 0.0f) deltaTime = 0.0f; if (prevTime < 0.0f) prevTime = 0.0f; float frame = flFrameRate * deltaTime; float prevFrame = flFrameRate * prevTime; int intFrame = ((int)frame) % numFrames; int intPrevFrame = ((int)prevFrame) % numFrames; if ( m_iFrameStart != MATERIAL_MODIFY_ANIMATION_UNSET ) { intFrame += m_iFrameStart; intPrevFrame += m_iFrameStart; } // Report wrap situation... if (intPrevFrame > intFrame) { m_bReachedEnd = true; if (bWrapAnimation) { AnimationWrapped( pControl ); } else { // Only sent the wrapped message once. // when we're in non-wrapping mode if (prevFrame < numFrames) AnimationWrapped( pControl ); intFrame = numFrames - 1; } } m_AnimatedTextureFrameNumVar->SetIntValue( intFrame ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CMaterialModifyProxy::GetAnimationStartTime( void* pArg ) { IClientRenderable *pRend = (IClientRenderable *)pArg; if (!pRend) return 0.0f; C_BaseEntity* pEntity = pRend->GetIClientUnknown()->GetBaseEntity(); if (pEntity) { return pEntity->GetTextureAnimationStartTime(); } return 0.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMaterialModifyProxy::AnimationWrapped( void* pArg ) { IClientRenderable *pRend = (IClientRenderable *)pArg; if (!pRend) return; C_BaseEntity* pEntity = pRend->GetIClientUnknown()->GetBaseEntity(); if (pEntity) { pEntity->TextureAnimationWrapped(); } } //----------------------------------------------------------------------------- // Does the dirty deed //----------------------------------------------------------------------------- void CMaterialModifyProxy::OnBindFloatLerp( C_MaterialModifyControl *pControl ) { if ( !pControl ) return; if ( pControl->HasNewAnimationCommands() ) { pControl->SetAnimationStartTime( gpGlobals->curtime ); pControl->ClearAnimationCommands(); } // Read the data from the modify entity materialfloatlerpcommands_t sCommands; pControl->GetFloatLerpCommands( &sCommands ); m_flStartValue = sCommands.flStartValue; m_flEndValue = sCommands.flEndValue; m_flTransitionTime = sCommands.flTransitionTime; m_flStartTime = pControl->GetAnimationStartTime(); bool bFound; m_pMaterialVar = m_pMaterial->FindVar( pControl->GetMaterialVariableName(), &bFound, false ); if( bFound ) { float currentValue; if( m_flTransitionTime > 0.0f ) { currentValue = m_flStartValue + ( m_flEndValue - m_flStartValue ) * clamp( ( ( gpGlobals->curtime - m_flStartTime ) / m_flTransitionTime ), 0.0f, 1.0f ); } else { currentValue = m_flEndValue; } if( debug_materialmodifycontrol_client.GetBool() && Q_stristr( m_pMaterial->GetName(), "faceandhair" ) && Q_stristr( m_pMaterialVar->GetName(), "warp" ) ) { static int count = 0; DevMsg( 1, "CMaterialFloatLerpProxy::OnBind \"%s\" %s=%f %d\n", m_pMaterial->GetName(), m_pMaterialVar->GetName(), currentValue, count++ ); } m_pMaterialVar->SetFloatValue( currentValue ); } } //============================================================================= // // MATERIALMODIFYANIMATED PROXY // class CMaterialModifyAnimatedProxy : public CBaseAnimatedTextureProxy { public: CMaterialModifyAnimatedProxy() {}; virtual ~CMaterialModifyAnimatedProxy() {}; virtual bool Init( IMaterial *pMaterial, KeyValues *pKeyValues ); virtual void OnBind( void *pEntity ); virtual float GetAnimationStartTime( void* pBaseEntity ); virtual void AnimationWrapped( void* pC_BaseEntity ); private: IMaterial *m_pMaterial; int m_iFrameStart; int m_iFrameEnd; bool m_bReachedEnd; float m_flStartTime; bool m_bCustomWrap; float m_flCustomFramerate; }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CMaterialModifyAnimatedProxy::Init( IMaterial *pMaterial, KeyValues *pKeyValues ) { m_pMaterial = pMaterial; m_iFrameStart = MATERIAL_MODIFY_ANIMATION_UNSET; m_iFrameEnd = MATERIAL_MODIFY_ANIMATION_UNSET; m_bReachedEnd = false; return CBaseAnimatedTextureProxy::Init( pMaterial, pKeyValues ); } //----------------------------------------------------------------------------- // Does the dirty deed //----------------------------------------------------------------------------- void CMaterialModifyAnimatedProxy::OnBind( void *pEntity ) { assert ( m_AnimatedTextureVar ); if( m_AnimatedTextureVar->GetType() != MATERIAL_VAR_TYPE_TEXTURE ) return; ITexture *pTexture; pTexture = m_AnimatedTextureVar->GetTextureValue(); // Get the modified material vars from the entity input IClientRenderable *pRend = (IClientRenderable *)pEntity; if ( pRend ) { C_BaseEntity *pBaseEntity = pRend->GetIClientUnknown()->GetBaseEntity(); if ( pBaseEntity ) { for ( C_BaseEntity *pChild = pBaseEntity->FirstMoveChild(); pChild; pChild = pChild->NextMovePeer() ) { C_MaterialModifyControl *pControl = dynamic_cast<C_MaterialModifyControl*>( pChild ); if ( !pControl ) continue; if ( !pControl->HasNewAnimationCommands() ) continue; // Read the data from the modify entity materialanimcommands_t sCommands; pControl->GetAnimationCommands( &sCommands ); m_iFrameStart = sCommands.iFrameStart; m_iFrameEnd = sCommands.iFrameEnd; m_bCustomWrap = sCommands.bWrap; m_flCustomFramerate = sCommands.flFrameRate; m_bReachedEnd = false; m_flStartTime = gpGlobals->curtime; pControl->ClearAnimationCommands(); } } } // Init all the vars based on whether we're using the base material settings, // or the custom ones from the entity input. int numFrames; bool bWrapAnimation; float flFrameRate; int iLastFrame; // Do we have a custom frame section from the server? if ( m_iFrameStart != MATERIAL_MODIFY_ANIMATION_UNSET ) { if ( m_iFrameEnd == MATERIAL_MODIFY_ANIMATION_UNSET ) { m_iFrameEnd = pTexture->GetNumAnimationFrames(); } numFrames = (m_iFrameEnd - m_iFrameStart) + 1; bWrapAnimation = m_bCustomWrap; flFrameRate = m_flCustomFramerate; iLastFrame = (m_iFrameEnd - 1); } else { numFrames = pTexture->GetNumAnimationFrames(); bWrapAnimation = m_WrapAnimation; flFrameRate = m_FrameRate; iLastFrame = (numFrames - 1); } // Have we already reached the end? If so, stay there. if ( m_bReachedEnd && !bWrapAnimation ) { m_AnimatedTextureFrameNumVar->SetIntValue( iLastFrame ); return; } // NOTE: Must not use relative time based methods here // because the bind proxy can be called many times per frame. // Prevent multiple Wrap callbacks to be sent for no wrap mode float startTime; if ( m_iFrameStart != MATERIAL_MODIFY_ANIMATION_UNSET ) { startTime = m_flStartTime; } else { startTime = GetAnimationStartTime(pEntity); } float deltaTime = gpGlobals->curtime - startTime; float prevTime = deltaTime - gpGlobals->frametime; // Clamp.. if (deltaTime < 0.0f) deltaTime = 0.0f; if (prevTime < 0.0f) prevTime = 0.0f; float frame = flFrameRate * deltaTime; float prevFrame = flFrameRate * prevTime; int intFrame = ((int)frame) % numFrames; int intPrevFrame = ((int)prevFrame) % numFrames; if ( m_iFrameStart != MATERIAL_MODIFY_ANIMATION_UNSET ) { intFrame += m_iFrameStart; intPrevFrame += m_iFrameStart; } // Report wrap situation... if (intPrevFrame > intFrame) { m_bReachedEnd = true; if (bWrapAnimation) { AnimationWrapped( pEntity ); } else { // Only sent the wrapped message once. // when we're in non-wrapping mode if (prevFrame < numFrames) AnimationWrapped( pEntity ); intFrame = numFrames - 1; } } m_AnimatedTextureFrameNumVar->SetIntValue( intFrame ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CMaterialModifyAnimatedProxy::GetAnimationStartTime( void* pArg ) { IClientRenderable *pRend = (IClientRenderable *)pArg; if (!pRend) return 0.0f; C_BaseEntity* pEntity = pRend->GetIClientUnknown()->GetBaseEntity(); if (pEntity) { return pEntity->GetTextureAnimationStartTime(); } return 0.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMaterialModifyAnimatedProxy::AnimationWrapped( void* pArg ) { IClientRenderable *pRend = (IClientRenderable *)pArg; if (!pRend) return; C_BaseEntity* pEntity = pRend->GetIClientUnknown()->GetBaseEntity(); if (pEntity) { pEntity->TextureAnimationWrapped(); } } EXPOSE_MATERIAL_PROXY( CMaterialModifyProxy, MaterialModify ); EXPOSE_MATERIAL_PROXY( CMaterialModifyAnimatedProxy, MaterialModifyAnimated );
1
0.964799
1
0.964799
game-dev
MEDIA
0.580587
game-dev,graphics-rendering
0.748349
1
0.748349
lsdlsd88/JC4827W543
2,294
1-Demo/Demo_Arduino/Libraries/blinker-library-master/src/modules/ArduinoJson/ArduinoJson/Object/ObjectIterator.hpp
// ArduinoJson - https://arduinojson.org // Copyright © 2014-2022, Benoit BLANCHON // MIT License #pragma once #include "../Object/Pair.hpp" #include "../Variant/SlotFunctions.hpp" namespace ARDUINOJSON_NAMESPACE { class PairPtr { public: PairPtr(MemoryPool *pool, VariantSlot *slot) : _pair(pool, slot) {} const Pair *operator->() const { return &_pair; } const Pair &operator*() const { return _pair; } private: Pair _pair; }; class ObjectIterator { public: ObjectIterator() : _slot(0) {} explicit ObjectIterator(MemoryPool *pool, VariantSlot *slot) : _pool(pool), _slot(slot) {} Pair operator*() const { return Pair(_pool, _slot); } PairPtr operator->() { return PairPtr(_pool, _slot); } bool operator==(const ObjectIterator &other) const { return _slot == other._slot; } bool operator!=(const ObjectIterator &other) const { return _slot != other._slot; } ObjectIterator &operator++() { _slot = _slot->next(); return *this; } ObjectIterator &operator+=(size_t distance) { _slot = _slot->next(distance); return *this; } VariantSlot *internal() { return _slot; } private: MemoryPool *_pool; VariantSlot *_slot; }; class PairConstPtr { public: PairConstPtr(const VariantSlot *slot) : _pair(slot) {} const PairConst *operator->() const { return &_pair; } const PairConst &operator*() const { return _pair; } private: PairConst _pair; }; class ObjectConstIterator { public: ObjectConstIterator() : _slot(0) {} explicit ObjectConstIterator(const VariantSlot *slot) : _slot(slot) {} PairConst operator*() const { return PairConst(_slot); } PairConstPtr operator->() { return PairConstPtr(_slot); } bool operator==(const ObjectConstIterator &other) const { return _slot == other._slot; } bool operator!=(const ObjectConstIterator &other) const { return _slot != other._slot; } ObjectConstIterator &operator++() { _slot = _slot->next(); return *this; } ObjectConstIterator &operator+=(size_t distance) { _slot = _slot->next(distance); return *this; } const VariantSlot *internal() { return _slot; } private: const VariantSlot *_slot; }; } // namespace ARDUINOJSON_NAMESPACE
1
0.859687
1
0.859687
game-dev
MEDIA
0.331039
game-dev
0.831663
1
0.831663
ReactVision/virocore
6,666
ios/Libraries/bullet/include/BulletCollision/CollisionShapes/btHeightfieldTerrainShape.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_HEIGHTFIELD_TERRAIN_SHAPE_H #define BT_HEIGHTFIELD_TERRAIN_SHAPE_H #include "btConcaveShape.h" ///btHeightfieldTerrainShape simulates a 2D heightfield terrain /** The caller is responsible for maintaining the heightfield array; this class does not make a copy. The heightfield can be dynamic so long as the min/max height values capture the extremes (heights must always be in that range). The local origin of the heightfield is assumed to be the exact center (as determined by width and length and height, with each axis multiplied by the localScaling). \b NOTE: be careful with coordinates. If you have a heightfield with a local min height of -100m, and a max height of +500m, you may be tempted to place it at the origin (0,0) and expect the heights in world coordinates to be -100 to +500 meters. Actually, the heights will be -300 to +300m, because bullet will re-center the heightfield based on its AABB (which is determined by the min/max heights). So keep in mind that once you create a btHeightfieldTerrainShape object, the heights will be adjusted relative to the center of the AABB. This is different to the behavior of many rendering engines, but is useful for physics engines. Most (but not all) rendering and heightfield libraries assume upAxis = 1 (that is, the y-axis is "up"). This class allows any of the 3 coordinates to be "up". Make sure your choice of axis is consistent with your rendering system. The heightfield heights are determined from the data type used for the heightfieldData array. - PHY_UCHAR: height at a point is the uchar value at the grid point, multipled by heightScale. uchar isn't recommended because of its inability to deal with negative values, and low resolution (8-bit). - PHY_SHORT: height at a point is the short int value at that grid point, multipled by heightScale. - PHY_FLOAT: height at a point is the float value at that grid point. heightScale is ignored when using the float heightfield data type. Whatever the caller specifies as minHeight and maxHeight will be honored. The class will not inspect the heightfield to discover the actual minimum or maximum heights. These values are used to determine the heightfield's axis-aligned bounding box, multiplied by localScaling. For usage and testing see the TerrainDemo. */ ATTRIBUTE_ALIGNED16(class) btHeightfieldTerrainShape : public btConcaveShape { protected: btVector3 m_localAabbMin; btVector3 m_localAabbMax; btVector3 m_localOrigin; ///terrain data int m_heightStickWidth; int m_heightStickLength; btScalar m_minHeight; btScalar m_maxHeight; btScalar m_width; btScalar m_length; btScalar m_heightScale; union { const unsigned char* m_heightfieldDataUnsignedChar; const short* m_heightfieldDataShort; const btScalar* m_heightfieldDataFloat; const void* m_heightfieldDataUnknown; }; PHY_ScalarType m_heightDataType; bool m_flipQuadEdges; bool m_useDiamondSubdivision; bool m_useZigzagSubdivision; int m_upAxis; btVector3 m_localScaling; virtual btScalar getRawHeightFieldValue(int x,int y) const; void quantizeWithClamp(int* out, const btVector3& point,int isMax) const; void getVertex(int x,int y,btVector3& vertex) const; /// protected initialization /** Handles the work of constructors so that public constructors can be backwards-compatible without a lot of copy/paste. */ void initialize(int heightStickWidth, int heightStickLength, const void* heightfieldData, btScalar heightScale, btScalar minHeight, btScalar maxHeight, int upAxis, PHY_ScalarType heightDataType, bool flipQuadEdges); public: BT_DECLARE_ALIGNED_ALLOCATOR(); /// preferred constructor /** This constructor supports a range of heightfield data types, and allows for a non-zero minimum height value. heightScale is needed for any integer-based heightfield data types. */ btHeightfieldTerrainShape(int heightStickWidth,int heightStickLength, const void* heightfieldData, btScalar heightScale, btScalar minHeight, btScalar maxHeight, int upAxis, PHY_ScalarType heightDataType, bool flipQuadEdges); /// legacy constructor /** The legacy constructor assumes the heightfield has a minimum height of zero. Only unsigned char or floats are supported. For legacy compatibility reasons, heightScale is calculated as maxHeight / 65535 (and is only used when useFloatData = false). */ btHeightfieldTerrainShape(int heightStickWidth,int heightStickLength,const void* heightfieldData, btScalar maxHeight,int upAxis,bool useFloatData,bool flipQuadEdges); virtual ~btHeightfieldTerrainShape(); void setUseDiamondSubdivision(bool useDiamondSubdivision=true) { m_useDiamondSubdivision = useDiamondSubdivision;} ///could help compatibility with Ogre heightfields. See https://code.google.com/p/bullet/issues/detail?id=625 void setUseZigzagSubdivision(bool useZigzagSubdivision=true) { m_useZigzagSubdivision = useZigzagSubdivision;} virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; virtual void processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const; virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; virtual void setLocalScaling(const btVector3& scaling); virtual const btVector3& getLocalScaling() const; //debugging virtual const char* getName()const {return "HEIGHTFIELD";} }; #endif //BT_HEIGHTFIELD_TERRAIN_SHAPE_H
1
0.881006
1
0.881006
game-dev
MEDIA
0.96658
game-dev
0.989135
1
0.989135
thantthet/keymagic-3
4,448
keymagic-ibus/src/ffi_bridge.h
#ifndef KEYMAGIC_FFI_BRIDGE_H #define KEYMAGIC_FFI_BRIDGE_H #include <glib.h> G_BEGIN_DECLS /** * FFI Bridge to keymagic-core (Rust library) * * This module provides a C interface to the Rust keymagic-core library, * handling the conversion between C types and Rust FFI types. */ /* Opaque handle to Rust EngineHandle */ typedef void* EngineHandle; /** * Key processing result from engine * Matches the ProcessKeyOutput structure from keymagic-core FFI */ typedef struct { gchar* text; /* Output text (may be NULL) */ gchar* composing_text; /* Current composing text (may be NULL) */ gboolean is_processed; /* TRUE if engine handled the key */ gint action_type; /* Action type (Insert, Backspace, etc.) */ gint delete_count; /* Number of characters to delete */ } KeyProcessingResult; /** * Engine result codes */ typedef enum { KEYMAGIC_RESULT_SUCCESS = 0, KEYMAGIC_RESULT_ERROR = 1, KEYMAGIC_RESULT_INVALID_ENGINE = 2, KEYMAGIC_RESULT_INVALID_KEYBOARD = 3 } KeyMagicResult; /** * Load a keyboard layout from .km2 file * * @param km2_file_path Path to .km2 keyboard file * @return Engine handle or NULL on failure */ EngineHandle* keymagic_ffi_load_keyboard(const gchar* km2_file_path); /** * Free/destroy an engine handle * * @param engine Engine handle to destroy */ void keymagic_ffi_destroy_engine(EngineHandle* engine); /** * Process a key event * * @param engine Engine handle * @param keyval Key value (GDK keyval) * @param keycode Hardware keycode * @param modifiers Modifier state * @param result Output result structure (caller must free) * @return Result code */ KeyMagicResult keymagic_ffi_process_key(EngineHandle* engine, guint keyval, guint keycode, guint modifiers, KeyProcessingResult* result); /** * Reset engine state * * @param engine Engine handle * @return Result code */ KeyMagicResult keymagic_ffi_reset_engine(EngineHandle* engine); /** * Get current composing text from engine * * @param engine Engine handle * @return Current composing text (caller must free) or NULL */ gchar* keymagic_ffi_get_composing_text(EngineHandle* engine); /** * Set composing text in engine (for sync purposes) * * @param engine Engine handle * @param text Text to set as composing text * @return Result code */ KeyMagicResult keymagic_ffi_set_composing_text(EngineHandle* engine, const gchar* text); /** * Free a string returned by the FFI layer * * @param str String to free */ void keymagic_ffi_free_string(gchar* str); /** * Free a KeyProcessingResult structure * * @param result Result structure to free */ void keymagic_ffi_free_result(KeyProcessingResult* result); /** * Load KM2 file for metadata access * * @param km2_path Path to .km2 file * @return Handle to KM2 file or NULL on error */ void* keymagic_ffi_km2_load(const gchar* km2_path); /** * Free KM2 file handle * * @param handle KM2 file handle */ void keymagic_ffi_km2_free(void* handle); /** * Get keyboard name from KM2 file * * @param handle KM2 file handle * @return Keyboard name (caller must free) or NULL */ gchar* keymagic_ffi_km2_get_name(void* handle); /** * Get keyboard description from KM2 file * * @param handle KM2 file handle * @return Description (caller must free) or NULL */ gchar* keymagic_ffi_km2_get_description(void* handle); /** * Get keyboard hotkey from KM2 file * * @param handle KM2 file handle * @return Hotkey string (caller must free) or NULL */ gchar* keymagic_ffi_km2_get_hotkey(void* handle); /** * Parse hotkey string using Rust FFI * * @param hotkey_str Hotkey string (e.g., "Ctrl+Shift+M") * @param key_code_out Output for VirtualKey code * @param ctrl_out Output for Ctrl modifier * @param alt_out Output for Alt modifier * @param shift_out Output for Shift modifier * @param meta_out Output for Meta/Super modifier * @return TRUE if parsing succeeded, FALSE otherwise */ gboolean keymagic_ffi_parse_hotkey(const gchar* hotkey_str, gint* key_code_out, gboolean* ctrl_out, gboolean* alt_out, gboolean* shift_out, gboolean* meta_out); G_END_DECLS #endif /* KEYMAGIC_FFI_BRIDGE_H */
1
0.91307
1
0.91307
game-dev
MEDIA
0.569251
game-dev
0.678493
1
0.678493
liuhaopen/UnityMMO
6,975
Assets/Scripts/UnityCocosAction/CocosFade.cs
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace Cocos { //因为需要为各种不同的组件获取或设置颜色,所以FadeIn等action支持传入实现过本接口的实例,可以参考ColorAttrCatcherTextMeshPro.cs实现你自己的组件 public interface IColorAttrCatcher { System.Func<Transform, Color> GetColor{get;} System.Action<Transform, Color> SetColor{get;} } // // FadeTo // public class FadeTo : ActionInterval { protected Material material; protected Graphic graphic; protected float toOpacity; public float fromOpacity; protected IColorAttrCatcher attrCatcher; public static FadeTo Create(float d, float opacity, IColorAttrCatcher attrCatcher=null) { FadeTo action = new FadeTo(); if (action != null && action.InitWithDuration(d, opacity, attrCatcher)) return action; return null; } public bool InitWithDuration(float duration, float opacity, IColorAttrCatcher attrCatcher=null) { if (base.InitWithDuration(duration)) { this.toOpacity = opacity; this.attrCatcher = attrCatcher; return true; } return false; } public override Action Clone() { return FadeTo.Create(duration, toOpacity); } public override Action Reverse() { Debug.LogError("reverse() not supported in FadeTo"); return null; } public override void StartWithTarget(Transform target) { base.StartWithTarget(target); if (target != null) { if (attrCatcher == null) { var renderer = target.GetComponent<MeshRenderer>(); if (renderer != null) material = renderer.material; if (material != null) { fromOpacity = material.color.a * 255.0f; } else { graphic = target.GetComponent<Image>(); if (graphic == null) graphic = target.GetComponent<Text>(); if (graphic != null) fromOpacity = graphic.color.a * 255.0f; } } else { var color = attrCatcher.GetColor(target); fromOpacity = color.a * 255.0f; } } } public override void Update(float time) { Color color; if (attrCatcher == null) { if (material != null) { color = material.color; color.a = (fromOpacity + (toOpacity - fromOpacity)*time)/255.0f; material.color = color; } else if (graphic != null) { color = graphic.color; color.a = (fromOpacity + (toOpacity - fromOpacity)*time)/255.0f; graphic.color = color; } } else { color = attrCatcher.GetColor(target); color.a = (fromOpacity + (toOpacity - fromOpacity)*time)/255.0f; attrCatcher.SetColor(target, color); } } } // // FadeIn // public class FadeIn : FadeTo { FadeTo reverseAction; public static FadeIn Create(float d, IColorAttrCatcher attrCatcher=null) { FadeIn action = new FadeIn(); if (action != null && action.InitWithDuration(d, 255.0f, attrCatcher)) return action; return null; } public override Action Clone() { return FadeIn.Create(duration); } public void SetReverseAction(FadeTo ac) { reverseAction = ac; } public override Action Reverse() { var action = FadeOut.Create(duration); action.SetReverseAction(this); return action; } public override void StartWithTarget(Transform target) { base.StartWithTarget(target); if (reverseAction != null) toOpacity = reverseAction.fromOpacity; else toOpacity = 255.0f; } } // // FadeOut // public class FadeOut : FadeTo { FadeTo reverseAction; public static FadeOut Create(float d, IColorAttrCatcher attrCatcher=null) { FadeOut action = new FadeOut(); if (action != null && action.InitWithDuration(d, 0.0f, attrCatcher)) return action; return null; } public override Action Clone() { return FadeOut.Create(duration); } public void SetReverseAction(FadeTo ac) { reverseAction = ac; } public override Action Reverse() { var action = FadeIn.Create(duration); action.SetReverseAction(this); return action; } public override void StartWithTarget(Transform target) { base.StartWithTarget(target); if (reverseAction != null) toOpacity = reverseAction.fromOpacity; else toOpacity = 0.0f; } } //仅作例子参考用 public class ColorAttrCatcherGraphic : IColorAttrCatcher { public Func<Transform, Color> GetColor { get => GetColorFunc; } public System.Action<Transform, Color> SetColor { get => SetColorFunc; } public static ColorAttrCatcherGraphic Ins = new ColorAttrCatcherGraphic(); public static Color GetColorFunc(Transform target) { if (target != null) { var graphic = target.GetComponent<Graphic>(); if (graphic != null) return graphic.color; Debug.LogError("action target has no Graphic component, please don't use ColorAttrCatcherGraphic!" + new System.Diagnostics.StackTrace().ToString()); } return Color.white; } public static void SetColorFunc(Transform target, Color color) { if (target != null) { var graphic = target.GetComponent<Graphic>(); if (graphic != null) graphic.color = color; else Debug.LogError("action target has no Graphic component, please don't use ColorAttrCatcherGraphic!" + new System.Diagnostics.StackTrace().ToString()); } } } }
1
0.965278
1
0.965278
game-dev
MEDIA
0.805204
game-dev
0.991823
1
0.991823
KosmX/minecraftPlayerAnimator
2,535
minecraft/common/src/main/java/dev/kosmx/playerAnim/minecraftApi/PlayerAnimationFactory.java
package dev.kosmx.playerAnim.minecraftApi; import dev.kosmx.playerAnim.api.layered.AnimationStack; import dev.kosmx.playerAnim.api.layered.IAnimation; import net.minecraft.client.player.AbstractClientPlayer; import net.minecraft.resources.ResourceLocation; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; /** * Animation factory, the factory will be invoked whenever a client-player is constructed. * The returned animation will be automatically registered and added to playerAssociated data. * <p> * {@link PlayerAnimationAccess#REGISTER_ANIMATION_EVENT} is invoked <strong>after</strong> factories are done. */ public interface PlayerAnimationFactory { FactoryHolder ANIMATION_DATA_FACTORY = new FactoryHolder(); @Nullable IAnimation invoke(@NotNull AbstractClientPlayer player); class FactoryHolder { private FactoryHolder() {} private static final List<Function<AbstractClientPlayer, DataHolder>> factories = new ArrayList<>(); /** * Animation factory * @param id animation id or <code>null</code> if you don't want to add to playerAssociated data * @param priority animation priority * @param factory animation factory */ public void registerFactory(@Nullable ResourceLocation id, int priority, @NotNull PlayerAnimationFactory factory) { factories.add(player -> Optional.ofNullable(factory.invoke(player)).map(animation -> new DataHolder(id, priority, animation)).orElse(null)); } @ApiStatus.Internal private record DataHolder(@Nullable ResourceLocation id, int priority, @NotNull IAnimation animation) {} @ApiStatus.Internal public void prepareAnimations(AbstractClientPlayer player, AnimationStack playerStack, Map<ResourceLocation, IAnimation> animationMap) { for (Function<AbstractClientPlayer, DataHolder> factory: factories) { DataHolder dataHolder = factory.apply(player); if (dataHolder != null) { playerStack.addAnimLayer(dataHolder.priority(), dataHolder.animation()); if (dataHolder.id() != null) { animationMap.put(dataHolder.id(), dataHolder.animation()); } } } } } }
1
0.895362
1
0.895362
game-dev
MEDIA
0.767547
game-dev
0.756565
1
0.756565
ImLegiitXD/Dream-Advanced
18,179
dll/back/1.8.9/net/minecraft/world/chunk/storage/AnvilChunkLoader.java
package net.minecraft.world.chunk.storage; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.util.ResourceLocation; import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.MinecraftException; import net.minecraft.world.NextTickListEntry; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.NibbleArray; import net.minecraft.world.storage.IThreadedFileIO; import net.minecraft.world.storage.ThreadedFileIOBase; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class AnvilChunkLoader implements IChunkLoader, IThreadedFileIO { private static final Logger logger = LogManager.getLogger(); private Map<ChunkCoordIntPair, NBTTagCompound> chunksToRemove = new ConcurrentHashMap(); private Set<ChunkCoordIntPair> pendingAnvilChunksCoordinates = Collections.<ChunkCoordIntPair>newSetFromMap(new ConcurrentHashMap()); /** Save directory for chunks using the Anvil format */ private final File chunkSaveLocation; private boolean field_183014_e = false; public AnvilChunkLoader(File chunkSaveLocationIn) { this.chunkSaveLocation = chunkSaveLocationIn; } /** * Loads the specified(XZ) chunk into the specified world. */ public Chunk loadChunk(World worldIn, int x, int z) throws IOException { ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(x, z); NBTTagCompound nbttagcompound = (NBTTagCompound)this.chunksToRemove.get(chunkcoordintpair); if (nbttagcompound == null) { DataInputStream datainputstream = RegionFileCache.getChunkInputStream(this.chunkSaveLocation, x, z); if (datainputstream == null) { return null; } nbttagcompound = CompressedStreamTools.read(datainputstream); } return this.checkedReadChunkFromNBT(worldIn, x, z, nbttagcompound); } /** * Wraps readChunkFromNBT. Checks the coordinates and several NBT tags. */ protected Chunk checkedReadChunkFromNBT(World worldIn, int x, int z, NBTTagCompound p_75822_4_) { if (!p_75822_4_.hasKey("Level", 10)) { logger.error("Chunk file at " + x + "," + z + " is missing level data, skipping"); return null; } else { NBTTagCompound nbttagcompound = p_75822_4_.getCompoundTag("Level"); if (!nbttagcompound.hasKey("Sections", 9)) { logger.error("Chunk file at " + x + "," + z + " is missing block data, skipping"); return null; } else { Chunk chunk = this.readChunkFromNBT(worldIn, nbttagcompound); if (!chunk.isAtLocation(x, z)) { logger.error("Chunk file at " + x + "," + z + " is in the wrong location; relocating. (Expected " + x + ", " + z + ", got " + chunk.xPosition + ", " + chunk.zPosition + ")"); nbttagcompound.setInteger("xPos", x); nbttagcompound.setInteger("zPos", z); chunk = this.readChunkFromNBT(worldIn, nbttagcompound); } return chunk; } } } public void saveChunk(World worldIn, Chunk chunkIn) throws MinecraftException, IOException { worldIn.checkSessionLock(); try { NBTTagCompound nbttagcompound = new NBTTagCompound(); NBTTagCompound nbttagcompound1 = new NBTTagCompound(); nbttagcompound.setTag("Level", nbttagcompound1); this.writeChunkToNBT(chunkIn, worldIn, nbttagcompound1); this.addChunkToPending(chunkIn.getChunkCoordIntPair(), nbttagcompound); } catch (Exception exception) { logger.error((String)"Failed to save chunk", (Throwable)exception); } } protected void addChunkToPending(ChunkCoordIntPair p_75824_1_, NBTTagCompound p_75824_2_) { if (!this.pendingAnvilChunksCoordinates.contains(p_75824_1_)) { this.chunksToRemove.put(p_75824_1_, p_75824_2_); } ThreadedFileIOBase.getThreadedIOInstance().queueIO(this); } /** * Returns a boolean stating if the write was unsuccessful. */ public boolean writeNextIO() { if (this.chunksToRemove.isEmpty()) { if (this.field_183014_e) { logger.info("ThreadedAnvilChunkStorage ({}): All chunks are saved", new Object[] {this.chunkSaveLocation.getName()}); } return false; } else { ChunkCoordIntPair chunkcoordintpair = (ChunkCoordIntPair)this.chunksToRemove.keySet().iterator().next(); boolean lvt_3_1_; try { this.pendingAnvilChunksCoordinates.add(chunkcoordintpair); NBTTagCompound nbttagcompound = (NBTTagCompound)this.chunksToRemove.remove(chunkcoordintpair); if (nbttagcompound != null) { try { this.func_183013_b(chunkcoordintpair, nbttagcompound); } catch (Exception exception) { logger.error((String)"Failed to save chunk", (Throwable)exception); } } lvt_3_1_ = true; } finally { this.pendingAnvilChunksCoordinates.remove(chunkcoordintpair); } return lvt_3_1_; } } private void func_183013_b(ChunkCoordIntPair p_183013_1_, NBTTagCompound p_183013_2_) throws IOException { DataOutputStream dataoutputstream = RegionFileCache.getChunkOutputStream(this.chunkSaveLocation, p_183013_1_.chunkXPos, p_183013_1_.chunkZPos); CompressedStreamTools.write(p_183013_2_, dataoutputstream); dataoutputstream.close(); } /** * Save extra data associated with this Chunk not normally saved during autosave, only during chunk unload. * Currently unused. */ public void saveExtraChunkData(World worldIn, Chunk chunkIn) throws IOException { } /** * Called every World.tick() */ public void chunkTick() { } /** * Save extra data not associated with any Chunk. Not saved during autosave, only during world unload. Currently * unused. */ public void saveExtraData() { try { this.field_183014_e = true; while (true) { if (this.writeNextIO()) { continue; } } } finally { this.field_183014_e = false; } } /** * Writes the Chunk passed as an argument to the NBTTagCompound also passed, using the World argument to retrieve * the Chunk's last update time. */ private void writeChunkToNBT(Chunk chunkIn, World worldIn, NBTTagCompound p_75820_3_) { p_75820_3_.setByte("V", (byte)1); p_75820_3_.setInteger("xPos", chunkIn.xPosition); p_75820_3_.setInteger("zPos", chunkIn.zPosition); p_75820_3_.setLong("LastUpdate", worldIn.getTotalWorldTime()); p_75820_3_.setIntArray("HeightMap", chunkIn.getHeightMap()); p_75820_3_.setBoolean("TerrainPopulated", chunkIn.isTerrainPopulated()); p_75820_3_.setBoolean("LightPopulated", chunkIn.isLightPopulated()); p_75820_3_.setLong("InhabitedTime", chunkIn.getInhabitedTime()); ExtendedBlockStorage[] aextendedblockstorage = chunkIn.getBlockStorageArray(); NBTTagList nbttaglist = new NBTTagList(); boolean flag = !worldIn.provider.getHasNoSky(); for (ExtendedBlockStorage extendedblockstorage : aextendedblockstorage) { if (extendedblockstorage != null) { NBTTagCompound nbttagcompound = new NBTTagCompound(); nbttagcompound.setByte("Y", (byte)(extendedblockstorage.getYLocation() >> 4 & 255)); byte[] abyte = new byte[extendedblockstorage.getData().length]; NibbleArray nibblearray = new NibbleArray(); NibbleArray nibblearray1 = null; for (int i = 0; i < extendedblockstorage.getData().length; ++i) { char c0 = extendedblockstorage.getData()[i]; int j = i & 15; int k = i >> 8 & 15; int l = i >> 4 & 15; if (c0 >> 12 != 0) { if (nibblearray1 == null) { nibblearray1 = new NibbleArray(); } nibblearray1.set(j, k, l, c0 >> 12); } abyte[i] = (byte)(c0 >> 4 & 255); nibblearray.set(j, k, l, c0 & 15); } nbttagcompound.setByteArray("Blocks", abyte); nbttagcompound.setByteArray("Data", nibblearray.getData()); if (nibblearray1 != null) { nbttagcompound.setByteArray("Add", nibblearray1.getData()); } nbttagcompound.setByteArray("BlockLight", extendedblockstorage.getBlocklightArray().getData()); if (flag) { nbttagcompound.setByteArray("SkyLight", extendedblockstorage.getSkylightArray().getData()); } else { nbttagcompound.setByteArray("SkyLight", new byte[extendedblockstorage.getBlocklightArray().getData().length]); } nbttaglist.appendTag(nbttagcompound); } } p_75820_3_.setTag("Sections", nbttaglist); p_75820_3_.setByteArray("Biomes", chunkIn.getBiomeArray()); chunkIn.setHasEntities(false); NBTTagList nbttaglist1 = new NBTTagList(); for (int i1 = 0; i1 < chunkIn.getEntityLists().length; ++i1) { for (Entity entity : chunkIn.getEntityLists()[i1]) { NBTTagCompound nbttagcompound1 = new NBTTagCompound(); if (entity.writeToNBTOptional(nbttagcompound1)) { chunkIn.setHasEntities(true); nbttaglist1.appendTag(nbttagcompound1); } } } p_75820_3_.setTag("Entities", nbttaglist1); NBTTagList nbttaglist2 = new NBTTagList(); for (TileEntity tileentity : chunkIn.getTileEntityMap().values()) { NBTTagCompound nbttagcompound2 = new NBTTagCompound(); tileentity.writeToNBT(nbttagcompound2); nbttaglist2.appendTag(nbttagcompound2); } p_75820_3_.setTag("TileEntities", nbttaglist2); List<NextTickListEntry> list = worldIn.getPendingBlockUpdates(chunkIn, false); if (list != null) { long j1 = worldIn.getTotalWorldTime(); NBTTagList nbttaglist3 = new NBTTagList(); for (NextTickListEntry nextticklistentry : list) { NBTTagCompound nbttagcompound3 = new NBTTagCompound(); ResourceLocation resourcelocation = (ResourceLocation)Block.blockRegistry.getNameForObject(nextticklistentry.getBlock()); nbttagcompound3.setString("i", resourcelocation == null ? "" : resourcelocation.toString()); nbttagcompound3.setInteger("x", nextticklistentry.position.getX()); nbttagcompound3.setInteger("y", nextticklistentry.position.getY()); nbttagcompound3.setInteger("z", nextticklistentry.position.getZ()); nbttagcompound3.setInteger("t", (int)(nextticklistentry.scheduledTime - j1)); nbttagcompound3.setInteger("p", nextticklistentry.priority); nbttaglist3.appendTag(nbttagcompound3); } p_75820_3_.setTag("TileTicks", nbttaglist3); } } /** * Reads the data stored in the passed NBTTagCompound and creates a Chunk with that data in the passed World. * Returns the created Chunk. */ private Chunk readChunkFromNBT(World worldIn, NBTTagCompound p_75823_2_) { int i = p_75823_2_.getInteger("xPos"); int j = p_75823_2_.getInteger("zPos"); Chunk chunk = new Chunk(worldIn, i, j); chunk.setHeightMap(p_75823_2_.getIntArray("HeightMap")); chunk.setTerrainPopulated(p_75823_2_.getBoolean("TerrainPopulated")); chunk.setLightPopulated(p_75823_2_.getBoolean("LightPopulated")); chunk.setInhabitedTime(p_75823_2_.getLong("InhabitedTime")); NBTTagList nbttaglist = p_75823_2_.getTagList("Sections", 10); int k = 16; ExtendedBlockStorage[] aextendedblockstorage = new ExtendedBlockStorage[k]; boolean flag = !worldIn.provider.getHasNoSky(); for (int l = 0; l < nbttaglist.tagCount(); ++l) { NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(l); int i1 = nbttagcompound.getByte("Y"); ExtendedBlockStorage extendedblockstorage = new ExtendedBlockStorage(i1 << 4, flag); byte[] abyte = nbttagcompound.getByteArray("Blocks"); NibbleArray nibblearray = new NibbleArray(nbttagcompound.getByteArray("Data")); NibbleArray nibblearray1 = nbttagcompound.hasKey("Add", 7) ? new NibbleArray(nbttagcompound.getByteArray("Add")) : null; char[] achar = new char[abyte.length]; for (int j1 = 0; j1 < achar.length; ++j1) { int k1 = j1 & 15; int l1 = j1 >> 8 & 15; int i2 = j1 >> 4 & 15; int j2 = nibblearray1 != null ? nibblearray1.get(k1, l1, i2) : 0; achar[j1] = (char)(j2 << 12 | (abyte[j1] & 255) << 4 | nibblearray.get(k1, l1, i2)); } extendedblockstorage.setData(achar); extendedblockstorage.setBlocklightArray(new NibbleArray(nbttagcompound.getByteArray("BlockLight"))); if (flag) { extendedblockstorage.setSkylightArray(new NibbleArray(nbttagcompound.getByteArray("SkyLight"))); } extendedblockstorage.removeInvalidBlocks(); aextendedblockstorage[i1] = extendedblockstorage; } chunk.setStorageArrays(aextendedblockstorage); if (p_75823_2_.hasKey("Biomes", 7)) { chunk.setBiomeArray(p_75823_2_.getByteArray("Biomes")); } NBTTagList nbttaglist1 = p_75823_2_.getTagList("Entities", 10); if (nbttaglist1 != null) { for (int k2 = 0; k2 < nbttaglist1.tagCount(); ++k2) { NBTTagCompound nbttagcompound1 = nbttaglist1.getCompoundTagAt(k2); Entity entity = EntityList.createEntityFromNBT(nbttagcompound1, worldIn); chunk.setHasEntities(true); if (entity != null) { chunk.addEntity(entity); Entity entity1 = entity; for (NBTTagCompound nbttagcompound4 = nbttagcompound1; nbttagcompound4.hasKey("Riding", 10); nbttagcompound4 = nbttagcompound4.getCompoundTag("Riding")) { Entity entity2 = EntityList.createEntityFromNBT(nbttagcompound4.getCompoundTag("Riding"), worldIn); if (entity2 != null) { chunk.addEntity(entity2); entity1.mountEntity(entity2); } entity1 = entity2; } } } } NBTTagList nbttaglist2 = p_75823_2_.getTagList("TileEntities", 10); if (nbttaglist2 != null) { for (int l2 = 0; l2 < nbttaglist2.tagCount(); ++l2) { NBTTagCompound nbttagcompound2 = nbttaglist2.getCompoundTagAt(l2); TileEntity tileentity = TileEntity.createAndLoadEntity(nbttagcompound2); if (tileentity != null) { chunk.addTileEntity(tileentity); } } } if (p_75823_2_.hasKey("TileTicks", 9)) { NBTTagList nbttaglist3 = p_75823_2_.getTagList("TileTicks", 10); if (nbttaglist3 != null) { for (int i3 = 0; i3 < nbttaglist3.tagCount(); ++i3) { NBTTagCompound nbttagcompound3 = nbttaglist3.getCompoundTagAt(i3); Block block; if (nbttagcompound3.hasKey("i", 8)) { block = Block.getBlockFromName(nbttagcompound3.getString("i")); } else { block = Block.getBlockById(nbttagcompound3.getInteger("i")); } worldIn.scheduleBlockUpdate(new BlockPos(nbttagcompound3.getInteger("x"), nbttagcompound3.getInteger("y"), nbttagcompound3.getInteger("z")), block, nbttagcompound3.getInteger("t"), nbttagcompound3.getInteger("p")); } } } return chunk; } }
1
0.947281
1
0.947281
game-dev
MEDIA
0.980829
game-dev
0.977847
1
0.977847
pia-foss/desktop
5,119
deps/breakpad/google_breakpad/processor/code_modules.h
// Copyright 2006 Google LLC // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google LLC nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // code_modules.h: Contains all of the CodeModule objects that were loaded // into a single process. // // Author: Mark Mentovai #ifndef GOOGLE_BREAKPAD_PROCESSOR_CODE_MODULES_H__ #define GOOGLE_BREAKPAD_PROCESSOR_CODE_MODULES_H__ #include <stddef.h> #include <vector> #include "google_breakpad/common/breakpad_types.h" #include "processor/linked_ptr.h" namespace google_breakpad { class CodeModule; class CodeModules { public: virtual ~CodeModules() {} // The number of contained CodeModule objects. virtual unsigned int module_count() const = 0; // Random access to modules. Returns the module whose code is present // at the address indicated by |address|. If no module is present at this // address, returns NULL. Ownership of the returned CodeModule is retained // by the CodeModules object; pointers returned by this method are valid for // comparison with pointers returned by the other Get methods. virtual const CodeModule* GetModuleForAddress(uint64_t address) const = 0; // Returns the module corresponding to the main executable. If there is // no main executable, returns NULL. Ownership of the returned CodeModule // is retained by the CodeModules object; pointers returned by this method // are valid for comparison with pointers returned by the other Get // methods. virtual const CodeModule* GetMainModule() const = 0; // Sequential access to modules. A sequence number of 0 corresponds to the // module residing lowest in memory. If the sequence number is out of // range, returns NULL. Ownership of the returned CodeModule is retained // by the CodeModules object; pointers returned by this method are valid for // comparison with pointers returned by the other Get methods. virtual const CodeModule* GetModuleAtSequence( unsigned int sequence) const = 0; // Sequential access to modules. This is similar to GetModuleAtSequence, // except no ordering requirement is enforced. A CodeModules implementation // may return CodeModule objects from GetModuleAtIndex in any order it // wishes, provided that the order remain the same throughout the life of // the CodeModules object. Typically, GetModuleAtIndex would be used by // a caller to enumerate all CodeModule objects quickly when the enumeration // does not require any ordering. If the index argument is out of range, // returns NULL. Ownership of the returned CodeModule is retained by // the CodeModules object; pointers returned by this method are valid for // comparison with pointers returned by the other Get methods. virtual const CodeModule* GetModuleAtIndex(unsigned int index) const = 0; // Creates a new copy of this CodeModules object, which the caller takes // ownership of. The new object will also contain copies of the existing // object's child CodeModule objects. The new CodeModules object may be of // a different concrete class than the object being copied, but will behave // identically to the copied object as far as the CodeModules and CodeModule // interfaces are concerned, except that the order that GetModuleAtIndex // returns objects in may differ between a copy and the original CodeModules // object. virtual const CodeModules* Copy() const = 0; // Returns a vector of all modules which address ranges needed to be shrunk // down due to address range conflicts with other modules. virtual std::vector<linked_ptr<const CodeModule> > GetShrunkRangeModules() const = 0; }; } // namespace google_breakpad #endif // GOOGLE_BREAKPAD_PROCESSOR_CODE_MODULES_H__
1
0.835457
1
0.835457
game-dev
MEDIA
0.168333
game-dev
0.55895
1
0.55895
Dimbreath/AzurLaneData
970
en-US/gamecfg/buff/buff_11410.lua
return { {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, desc_get = "出击时,编队中每有一个铁血阵营潜艇角色,自身命中、装填属性上升$1,雷击属性上升$2", name = "狼群战术-U81", init_effect = "", id = 11410, time = 0, picture = "", desc = "出击时,编队中每有一个铁血阵营潜艇角色,自身命中、装填属性上升$1,雷击属性上升$2", stack = 1, color = "red", icon = 11410, last_effect = "", effect_list = { { type = "BattleBuffAddBuff", trigger = { "onSubmarineRaid" }, arg_list = { minTargetNumber = 1, nationality = 4, buff_id = 11411, isBuffStackByCheckTarget = true, check_target = { "TargetNationalityFriendly", "TargetShipTypeFriendly" }, ship_type_list = { 8 } } }, { type = "BattleBuffCastSkill", trigger = { "onSubmarineRaid" }, arg_list = { minTargetNumber = 1, nationality = 4, skill_id = 11410, check_target = { "TargetNationalityFriendly", "TargetShipTypeFriendly" }, ship_type_list = { 8 } } } } }
1
0.609427
1
0.609427
game-dev
MEDIA
0.909046
game-dev
0.607451
1
0.607451
colorblindness/3arthh4ck
1,820
src/main/java/me/earth/earthhack/impl/modules/movement/jesus/ListenerCollision.java
package me.earth.earthhack.impl.modules.movement.jesus; import me.earth.earthhack.impl.event.events.misc.CollisionEvent; import me.earth.earthhack.impl.event.listeners.ModuleListener; import me.earth.earthhack.impl.modules.movement.jesus.mode.JesusMode; import me.earth.earthhack.impl.util.math.position.PositionUtil; import net.minecraft.block.BlockLiquid; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import java.util.Objects; final class ListenerCollision extends ModuleListener<Jesus, CollisionEvent> { public ListenerCollision(Jesus module) { super(module, CollisionEvent.class); } @Override public void invoke(CollisionEvent event) { if (event.getEntity() != null && mc.player != null && (event.getEntity().equals(mc.player) && module.mode.getValue() != JesusMode.Dolphin || event.getEntity().getControllingPassenger() != null && Objects.equals( event.getEntity().getControllingPassenger(), mc.player)) && event.getBlock() instanceof BlockLiquid && !mc.player.isSneaking() && mc.player.fallDistance < 3.0F && !PositionUtil.inLiquid() && PositionUtil.inLiquid(false) && PositionUtil.isAbove(event.getPos())) { BlockPos pos = event.getPos(); event.setBB(new AxisAlignedBB(pos.getX(), pos.getY(), pos.getZ(), pos.getX() + 1, pos.getY() + 0.99, pos.getZ() + 1)); } } }
1
0.655928
1
0.655928
game-dev
MEDIA
0.985616
game-dev
0.856615
1
0.856615
ftsf/nimsynth
1,993
src/machines/generators/adsr.nim
import strutils import math import common import core.envelope # envelope {.this:self.} type ADSRMachine = ref object of Machine env: Envelope method init(self: ADSRMachine) = procCall init(Machine(self)) name = "adsr" nInputs = 0 nOutputs = 1 stereo = false env.init() globalParams.add([ Parameter(kind: Trigger, name: "trigger", min: 0, max: 1, onchange: proc(newValue: float32, voice: int) = if newValue == OffNote or newValue == 0: env.release() else: env.trigger() ), Parameter(name: "a", kind: Float, separator: true, min: 0.0, max: 5.0, default: 0.001, onchange: proc(newValue: float32, voice: int) = self.env.a = exp(newValue) - 1.0 , getValueString: proc(value: float32, voice: int): string = return (exp(value) - 1.0).formatFloat(ffDecimal, 2) & " s" ), Parameter(name: "d", kind: Float, min: 0.0, max: 5.0, default: 0.1, onchange: proc(newValue: float32, voice: int) = self.env.d = exp(newValue) - 1.0 , getValueString: proc(value: float32, voice: int): string = return (exp(value) - 1.0).formatFloat(ffDecimal, 2) & " s" ), Parameter(name: "ds", kind: Float, min: 0.1, max: 10.0, default: 1.0, onchange: proc(newValue: float32, voice: int) = self.env.decayExp = newValue ), Parameter(name: "s", kind: Float, min: 0.0, max: 1.0, default: 0.5, onchange: proc(newValue: float32, voice: int) = self.env.s = newValue ), Parameter(name: "r", kind: Float, min: 0.0, max: 5.0, default: 0.01, onchange: proc(newValue: float32, voice: int) = self.env.r = exp(newValue) - 1.0 , getValueString: proc(value: float32, voice: int): string = return (exp(value) - 1.0).formatFloat(ffDecimal, 2) & " s" ), ]) setDefaults() method process(self: ADSRMachine) = outputSamples[0] = env.process() proc newADSRMachine(): Machine = var m = new(ADSRMachine) m.init() return m registerMachine("adsr", newADSRMachine, "generator")
1
0.886607
1
0.886607
game-dev
MEDIA
0.362764
game-dev
0.943715
1
0.943715
JiepengTan/Lockstep.Math
18,203
Runtime/BaseType/LQuaternion.cs
//https://github.com/JiepengTan/LockstepMath using System; using Lockstep.Math; using static Lockstep.Math.LVector3; namespace Lockstep.Math { public struct LQuaternion { #region public members public LFloat x; public LFloat y; public LFloat z; public LFloat w; #endregion #region constructor public LQuaternion(LFloat p_x, LFloat p_y, LFloat p_z, LFloat p_w){ x = p_x; y = p_y; z = p_z; w = p_w; } public LQuaternion(int p_x, int p_y, int p_z, int p_w){ x._val = p_x; y._val = p_y; z._val = p_z; w._val = p_w; } #endregion #region public properties public LFloat this[int index] { get { switch (index) { case 0: return x; case 1: return y; case 2: return z; case 3: return w; default: throw new IndexOutOfRangeException("Invalid LQuaternion index!"); } } set { switch (index) { case 0: x = value; break; case 1: y = value; break; case 2: z = value; break; case 3: w = value; break; default: throw new IndexOutOfRangeException("Invalid LQuaternion index!"); } } } public static LQuaternion identity { get { return new LQuaternion(0, 0, 0, 1); } } public LVector3 eulerAngles { get { LMatrix33 m = QuaternionToMatrix(this); return (180 / LMath.PI * MatrixToEuler(m)); } set { this = Euler(value); } } #endregion #region public functions /// <summary> /// 夹角大小 /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static LFloat Angle(LQuaternion a, LQuaternion b){ LFloat single = Dot(a, b); return LMath.Acos(LMath.Min(LMath.Abs(single), LFloat.one)) * 2 * (180 / LMath.PI); } /// <summary> /// 轴向旋转 /// </summary> /// <param name="angle"></param> /// <param name="axis"></param> /// <returns></returns> public static LQuaternion AngleAxis(LFloat angle, LVector3 axis){ axis = axis.normalized; angle = angle * LMath.Deg2Rad; LQuaternion q = new LQuaternion(); LFloat halfAngle = angle * LFloat.half; LFloat s = LMath.Sin(halfAngle); q.w = LMath.Cos(halfAngle); q.x = s * axis.x; q.y = s * axis.y; q.z = s * axis.z; return q; } /// <summary> /// 点乘 /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static LFloat Dot(LQuaternion a, LQuaternion b){ return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } /// <summary> /// 欧拉角转四元数 /// </summary> /// <param name="euler"></param> /// <returns></returns> public static LQuaternion Euler(LVector3 euler){ return Euler(euler.x, euler.y, euler.z); } /// <summary> /// 欧拉角转四元数 /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="z"></param> /// <returns></returns> public static LQuaternion Euler(LFloat x, LFloat y, LFloat z){ LFloat cX = LMath.Cos(x * LMath.PI / 360); LFloat sX = LMath.Sin(x * LMath.PI / 360); LFloat cY = LMath.Cos(y * LMath.PI / 360); LFloat sY = LMath.Sin(y * LMath.PI / 360); LFloat cZ = LMath.Cos(z * LMath.PI / 360); LFloat sZ = LMath.Sin(z * LMath.PI / 360); LQuaternion qX = new LQuaternion(sX, LFloat.zero, LFloat.zero, cX); LQuaternion qY = new LQuaternion(LFloat.zero, sY, LFloat.zero, cY); LQuaternion qZ = new LQuaternion(LFloat.zero, LFloat.zero, sZ, cZ); LQuaternion q = (qY * qX) * qZ; return q; } /// <summary> /// 向量间的角度 /// </summary> /// <param name="fromDirection"></param> /// <param name="toDirection"></param> /// <returns></returns> public static LQuaternion FromToRotation(LVector3 fromDirection, LVector3 toDirection){ throw new IndexOutOfRangeException("Not Available!"); } /// <summary> /// 四元数的逆 /// </summary> /// <param name="rotation"></param> /// <returns></returns> public static LQuaternion Inverse(LQuaternion rotation){ return new LQuaternion(-rotation.x, -rotation.y, -rotation.z, rotation.w); } /// <summary> /// 线性插值 /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="t"></param> /// <returns></returns> public static LQuaternion Lerp(LQuaternion a, LQuaternion b, LFloat t){ if (t > 1) { t = LFloat.one; } if (t < 0) { t = LFloat.zero; } return LerpUnclamped(a, b, t); } /// <summary> /// 线性插值(无限制) /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="t"></param> /// <returns></returns> public static LQuaternion LerpUnclamped(LQuaternion a, LQuaternion b, LFloat t){ LQuaternion tmpQuat = new LQuaternion(); if (Dot(a, b) < 0) { tmpQuat.Set(a.x + t * (-b.x - a.x), a.y + t * (-b.y - a.y), a.z + t * (-b.z - a.z), a.w + t * (-b.w - a.w)); } else { tmpQuat.Set(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y), a.z + t * (b.z - a.z), a.w + t * (b.w - a.w)); } LFloat nor = LMath.Sqrt(Dot(tmpQuat, tmpQuat)); return new LQuaternion(tmpQuat.x / nor, tmpQuat.y / nor, tmpQuat.z / nor, tmpQuat.w / nor); } /// <summary> /// 注视旋转 /// </summary> /// <param name="forward"></param> /// <returns></returns> public static LQuaternion LookRotation(LVector3 forward){ LVector3 up = LVector3.up; return LookRotation(forward, up); } /// <summary> /// 注视旋转 /// </summary> /// <param name="forward"></param> /// <param name="upwards"></param> /// <returns></returns> public static LQuaternion LookRotation(LVector3 forward, LVector3 upwards){ LMatrix33 m = LookRotationToMatrix(forward, upwards); return MatrixToQuaternion(m); } /// <summary> /// 向目标角度旋转 /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="maxDegreesDelta"></param> /// <returns></returns> public static LQuaternion RotateTowards(LQuaternion from, LQuaternion to, LFloat maxDegreesDelta){ LFloat num = LQuaternion.Angle(from, to); LQuaternion result = new LQuaternion(); if (num == 0) { result = to; } else { LFloat t = LMath.Min(LFloat.one, maxDegreesDelta / num); result = LQuaternion.SlerpUnclamped(from, to, t); } return result; } /// <summary> /// 球形插值 /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="t"></param> /// <returns></returns> public static LQuaternion Slerp(LQuaternion a, LQuaternion b, LFloat t){ if (t > 1) { t = LFloat.one; } if (t < 0) { t = LFloat.zero; } return SlerpUnclamped(a, b, t); } /// <summary> /// 球形插值(无限制) /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="t"></param> /// <returns></returns> public static LQuaternion SlerpUnclamped(LQuaternion q1, LQuaternion q2, LFloat t){ LFloat dot = Dot(q1, q2); LQuaternion tmpQuat = new LQuaternion(); if (dot < 0) { dot = -dot; tmpQuat.Set(-q2.x, -q2.y, -q2.z, -q2.w); } else tmpQuat = q2; if (dot < 1) { LFloat angle = LMath.Acos(dot); LFloat sinadiv, sinat, sinaomt; sinadiv = 1 / LMath.Sin(angle); sinat = LMath.Sin(angle * t); sinaomt = LMath.Sin(angle * (1 - t)); tmpQuat.Set((q1.x * sinaomt + tmpQuat.x * sinat) * sinadiv, (q1.y * sinaomt + tmpQuat.y * sinat) * sinadiv, (q1.z * sinaomt + tmpQuat.z * sinat) * sinadiv, (q1.w * sinaomt + tmpQuat.w * sinat) * sinadiv); return tmpQuat; } else { return Lerp(q1, tmpQuat, t); } } /// <summary> /// 设置四元数 /// </summary> /// <param name="new_x"></param> /// <param name="new_y"></param> /// <param name="new_z"></param> /// <param name="new_w"></param> public void Set(LFloat new_x, LFloat new_y, LFloat new_z, LFloat new_w){ x = new_x; y = new_y; z = new_z; w = new_w; } /// <summary> /// 设置角度 /// </summary> /// <param name="fromDirection"></param> /// <param name="toDirection"></param> public void SetFromToRotation(LVector3 fromDirection, LVector3 toDirection){ this = FromToRotation(fromDirection, toDirection); } /// <summary> /// 设置注视旋转 /// </summary> /// <param name="view"></param> public void SetLookRotation(LVector3 view){ this = LookRotation(view); } /// <summary> /// 设置注视旋转 /// </summary> /// <param name="view"></param> /// <param name="up"></param> public void SetLookRotation(LVector3 view, LVector3 up){ this = LookRotation(view, up); } /// <summary> /// 转换为角轴 /// </summary> /// <param name="angle"></param> /// <param name="axis"></param> public void ToAngleAxis(out LFloat angle, out LVector3 axis){ angle = 2 * LMath.Acos(w); if (angle == 0) { axis = LVector3.right; return; } LFloat div = 1 / LMath.Sqrt(1 - w * w); axis = new LVector3(x * div, y * div, z * div); angle = angle * 180 / LMath.PI; } public override string ToString(){ return String.Format("({0}, {1}, {2}, {3})", x, y, z, w); } public override int GetHashCode(){ return this.x.GetHashCode() ^ this.y.GetHashCode() << 2 ^ this.z.GetHashCode() >> 2 ^ this.w.GetHashCode() >> 1; } public override bool Equals(object other){ return this == (LQuaternion) other; } #endregion #region private functions private LVector3 MatrixToEuler(LMatrix33 m){ LVector3 v = new LVector3(); if (m[1, 2] < 1) { if (m[1, 2] > -1) { v.x = LMath.Asin(-m[1, 2]); v.y = LMath.Atan2(m[0, 2], m[2, 2]); v.z = LMath.Atan2(m[1, 0], m[1, 1]); } else { v.x = LMath.PI * LFloat.half; v.y = LMath.Atan2(m[0, 1], m[0, 0]); v.z = (LFloat) 0; } } else { v.x = -LMath.PI * LFloat.half; v.y = LMath.Atan2(-m[0, 1], m[0, 0]); v.z = (LFloat) 0; } for (int i = 0; i < 3; i++) { if (v[i] < 0) { v[i] += LMath.PI2; } else if (v[i] > LMath.PI2) { v[i] -= LMath.PI2; } } return v; } public static LMatrix33 QuaternionToMatrix(LQuaternion quat){ LMatrix33 m = new LMatrix33(); LFloat x = quat.x * 2; LFloat y = quat.y * 2; LFloat z = quat.z * 2; LFloat xx = quat.x * x; LFloat yy = quat.y * y; LFloat zz = quat.z * z; LFloat xy = quat.x * y; LFloat xz = quat.x * z; LFloat yz = quat.y * z; LFloat wx = quat.w * x; LFloat wy = quat.w * y; LFloat wz = quat.w * z; m[0] = 1 - (yy + zz); m[1] = xy + wz; m[2] = xz - wy; m[3] = xy - wz; m[4] = 1 - (xx + zz); m[5] = yz + wx; m[6] = xz + wy; m[7] = yz - wx; m[8] = 1 - (xx + yy); return m; } private static LQuaternion MatrixToQuaternion(LMatrix33 m){ LQuaternion quat = new LQuaternion(); LFloat fTrace = m[0, 0] + m[1, 1] + m[2, 2]; LFloat root; if (fTrace > 0) { root = LMath.Sqrt(fTrace + 1); quat.w = LFloat.half * root; root = LFloat.half / root; quat.x = (m[2, 1] - m[1, 2]) * root; quat.y = (m[0, 2] - m[2, 0]) * root; quat.z = (m[1, 0] - m[0, 1]) * root; } else { int[] s_iNext = new int[] {1, 2, 0}; int i = 0; if (m[1, 1] > m[0, 0]) { i = 1; } if (m[2, 2] > m[i, i]) { i = 2; } int j = s_iNext[i]; int k = s_iNext[j]; root = LMath.Sqrt(m[i, i] - m[j, j] - m[k, k] + 1); if (root < 0) { throw new IndexOutOfRangeException("error!"); } quat[i] = LFloat.half * root; root = LFloat.half / root; quat.w = (m[k, j] - m[j, k]) * root; quat[j] = (m[j, i] + m[i, j]) * root; quat[k] = (m[k, i] + m[i, k]) * root; } LFloat nor = LMath.Sqrt(Dot(quat, quat)); quat = new LQuaternion(quat.x / nor, quat.y / nor, quat.z / nor, quat.w / nor); return quat; } private static LMatrix33 LookRotationToMatrix(LVector3 viewVec, LVector3 upVec){ LVector3 z = viewVec; LMatrix33 m = new LMatrix33(); LFloat mag = z.magnitude; if (mag <= 0) { m = LMatrix33.identity; } z /= mag; LVector3 x = Cross(upVec, z); mag = x.magnitude; if (mag <= 0) { m = LMatrix33.identity; } x /= mag; LVector3 y = Cross(z, x); m[0, 0] = x.x; m[0, 1] = y.x; m[0, 2] = z.x; m[1, 0] = x.y; m[1, 1] = y.y; m[1, 2] = z.y; m[2, 0] = x.z; m[2, 1] = y.z; m[2, 2] = z.z; return m; } #endregion #region operator public static LQuaternion operator *(LQuaternion lhs, LQuaternion rhs){ return new LQuaternion(lhs.w * rhs.x + lhs.x * rhs.w + lhs.y * rhs.z - lhs.z * rhs.y, lhs.w * rhs.y + lhs.y * rhs.w + lhs.z * rhs.x - lhs.x * rhs.z, lhs.w * rhs.z + lhs.z * rhs.w + lhs.x * rhs.y - lhs.y * rhs.x, lhs.w * rhs.w - lhs.x * rhs.x - lhs.y * rhs.y - lhs.z * rhs.z); } public static LVector3 operator *(LQuaternion rotation, LVector3 point){ LFloat _2x = rotation.x * 2; LFloat _2y = rotation.y * 2; LFloat _2z = rotation.z * 2; LFloat _2xx = rotation.x * _2x; LFloat _2yy = rotation.y * _2y; LFloat _2zz = rotation.z * _2z; LFloat _2xy = rotation.x * _2y; LFloat _2xz = rotation.x * _2z; LFloat _2yz = rotation.y * _2z; LFloat _2xw = rotation.w * _2x; LFloat _2yw = rotation.w * _2y; LFloat _2zw = rotation.w * _2z; var x = (1 - (_2yy + _2zz)) * point.x + (_2xy - _2zw) * point.y + (_2xz + _2yw) * point.z; var y = (_2xy + _2zw) * point.x + (1 - (_2xx + _2zz)) * point.y + (_2yz - _2xw) * point.z; var z = (_2xz - _2yw) * point.x + (_2yz + _2xw) * point.y + (1 - (_2xx + _2yy)) * point.z; return new LVector3(x, y, z); } public static bool operator ==(LQuaternion lhs, LQuaternion rhs){ var isEqu = lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w; return isEqu; } public static bool operator !=(LQuaternion lhs, LQuaternion rhs){ return !(lhs == rhs); } #endregion } } /* */
1
0.902289
1
0.902289
game-dev
MEDIA
0.42993
game-dev,graphics-rendering
0.957207
1
0.957207
MontyTRC89/Tomb-Editor
11,271
TombLib/TombLib/Catalogs/TEN Node Catalogs/Keypad.lua
LevelVars.Engine.Keypad = LevelVars.Engine.Keypad or {} LevelVars.Engine.ActivatedKeypad = nil -- !Name "Create a keypad" -- !Section "User interface" -- !Description "Creates a keypad." -- !Arguments "NewLine, 80, Moveables, Keypad Object" -- !Arguments "Numerical, 20, [ 1000 | 9999 ], Pass code" -- !Arguments "NewLine, Volumes, Volume to use for the keypad" LevelFuncs.Engine.Node.KeypadCreate = function(object, code, volume) local dataName = object .. "_KeypadData" local codeS = tostring(code) LevelVars.Engine.Keypad[dataName] = {} LevelVars.Engine.Keypad[dataName].Code = LevelVars.Engine.Keypad[dataName].Code or codeS LevelVars.Engine.Keypad[dataName].CodeInput = "" LevelVars.Engine.Keypad[dataName].Volume = volume LevelVars.Engine.Keypad[dataName].Status = false LevelVars.Engine.Keypad[dataName].CursorX = 1 LevelVars.Engine.Keypad[dataName].CursorY = 1 end -- !Name "Run a keypad (triggers)" -- !Section "User interface" -- !Description "Creates a keypad to activate the triggers using Trigger Triggerer." -- !Arguments "NewLine, Moveables, Keypad object" -- !Arguments "NewLine, Moveables, Trigger Triggerer object to activate" LevelFuncs.Engine.Node.KeypadTrigger = function(object, triggerer) local dataName = object .. "_KeypadData" if LevelVars.Engine.Keypad[dataName].Status then local triggerer = GetMoveableByName(triggerer) local volume = GetVolumeByName(LevelVars.Engine.Keypad[dataName].Volume) triggerer:Enable() LevelVars.Engine.Keypad[dataName] = nil LevelVars.Engine.ActivatedKeypad = nil volume:Disable() end LevelFuncs.Engine.ActivateKeypad(object) end -- !Name "Run a keypad (volume event)" -- !Section "User interface" -- !Description "Creates a keypad to run a volume event." -- !Arguments "NewLine, Moveables, Keypad object" -- !Arguments "NewLine, 65, VolumeEventSets, Target event set" -- !Arguments "VolumeEvents, 35, Event to run" LevelFuncs.Engine.Node.KeypadVolume = function(object, volumeEvent, eventType) local dataName = object .. "_KeypadData" if LevelVars.Engine.Keypad[dataName].Status then local volume = GetVolumeByName(LevelVars.Engine.Keypad[dataName].Volume) LevelVars.Engine.Keypad[dataName] = nil LevelVars.Engine.ActivatedKeypad = nil TEN.Logic.HandleEvent(volumeEvent, eventType, Lara) volume:Disable() end LevelFuncs.Engine.ActivateKeypad(object) end -- !Name "Run a keypad (script function)" -- !Section "User interface" -- !Description "Creates a keypad to run a script function." -- !Arguments "NewLine, Moveables, Keypad object" -- !Arguments "NewLine, LuaScript, Target Lua script function" "NewLine, String, Arguments" LevelFuncs.Engine.Node.KeypadScript = function(object, funcName, args) local dataName = object .. "_KeypadData" if LevelVars.Engine.Keypad[dataName].Status then local volume = GetVolumeByName(LevelVars.Engine.Keypad[dataName].Volume) LevelVars.Engine.Keypad[dataName] = nil LevelVars.Engine.ActivatedKeypad = nil funcName(table.unpack(LevelFuncs.Engine.Node.SplitString(args, ","))) volume:Disable() end LevelFuncs.Engine.ActivateKeypad(object) end LevelFuncs.Engine.ActivateKeypad = function(object) local target = GetMoveableByName(object) Lara:Interact(target) if Lara:GetAnim() == 197 and Lara:GetFrame() >= 22 and Lara:GetFrame() <= 22 then Lara:SetVisible(false) View.SetFOV(30) LevelVars.Engine.ActivatedKeypad = object TEN.Logic.AddCallback(TEN.Logic.CallbackPoint.PREFREEZE, LevelFuncs.Engine.RunKeypad) Flow.SetFreezeMode(Flow.FreezeMode.SPECTATOR) end end LevelFuncs.Engine.ExitKeypad = function(object, status) local cameraObject = GetMoveableByName("keypadCam1") local dataName = object .. "_KeypadData" LevelVars.Engine.Keypad[dataName].Status = status View.SetFOV(80) Lara:SetVisible(true) ResetObjCamera() cameraObject:Destroy() Flow.SetFreezeMode(Flow.FreezeMode.NONE) TEN.Logic.RemoveCallback(TEN.Logic.CallbackPoint.PREFREEZE, LevelFuncs.Engine.RunKeypad) end LevelFuncs.Engine.RunKeypad = function() local soundIDs = { ["Clear"] = 983, -- TR5_Keypad_Hash (Cancel) ["Enter"] = 984, -- TR5_Keypad_Asterisk (Confirm) [0] = 985, -- TR5_Keypad_0 [1] = 986, -- TR5_Keypad_1 [2] = 987, -- TR5_Keypad_2 [3] = 988, -- TR5_Keypad_3 [4] = 989, -- TR5_Keypad_4 [5] = 990, -- TR5_Keypad_5 [6] = 991, -- TR5_Keypad_6 [7] = 992, -- TR5_Keypad_7 [8] = 993, -- TR5_Keypad_8 [9] = 994, -- TR5_Keypad_9 ["Failure"] = 995, -- TR5_Keypad_Entry_No ["Success"] = 996, -- TR5_Keypad_Entry_Yes ["Click"] = 644, -- TR2_Click } local object = LevelVars.Engine.ActivatedKeypad local dataName = object .. "_KeypadData" local target = GetMoveableByName(object) local targetPos = target:GetPosition() local targetRot = target:GetRotation() local targetRoom = target:GetRoomNumber() local offset = 296 local heightOffset = 618 local cameraPos = targetPos if (targetRot.y == 0) then cameraPos = Vec3(targetPos.x, targetPos.y-heightOffset, targetPos.z - offset) elseif (targetRot.y == 90) then cameraPos = Vec3(targetPos.x- offset, targetPos.y-heightOffset, targetPos.z) elseif (targetRot.y == 180) then cameraPos = Vec3(targetPos.x, targetPos.y-heightOffset, targetPos.z + offset) elseif (targetRot.y == 270) then cameraPos = Vec3(targetPos.x+ offset, targetPos.y-heightOffset, targetPos.z ) end if not IsNameInUse("keypadCam1") then Moveable(TEN.Objects.ObjID.CAMERA_TARGET, "keypadCam1", cameraPos, Rotation(0,0,0), targetRoom) end local cameraObject = GetMoveableByName("keypadCam1") cameraObject:SetPosition(cameraPos) cameraObject:SetRoomNumber(targetRoom) cameraObject:AttachObjCamera(0, target, 0) local keypad = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {"Clear", 0, "Enter"} } -- Mesh mappings (1-12 dark keys, 13-24 bright keys) local meshMappings = { [1] = {dark = 13, bright = 1}, [2] = {dark = 14, bright = 2}, [3] = {dark = 15, bright = 3}, [4] = {dark = 16, bright = 4}, [5] = {dark = 17, bright = 5}, [6] = {dark = 18, bright = 6}, [7] = {dark = 19, bright = 7}, [8] = {dark = 20, bright = 8}, [9] = {dark = 21, bright = 9}, ["Clear"] = {dark = 22, bright = 10}, [0] = {dark = 23, bright = 11}, ["Enter"] = {dark = 24, bright = 12} } -- Starting cursor position local correctCode = LevelVars.Engine.Keypad[dataName].Code local maxCodeLength = string.len(correctCode) if KeyIsHit(ActionID.ACTION) then local selectedKey = keypad[LevelVars.Engine.Keypad[dataName].CursorY][LevelVars.Engine.Keypad[dataName].CursorX] TEN.Sound.PlaySound(soundIDs[selectedKey]) if selectedKey == "Clear" then LevelVars.Engine.Keypad[dataName].CodeInput = "" -- Clear the entered code TEN.Sound.PlaySound(soundIDs["Clear"]) elseif selectedKey == "Enter" then if LevelVars.Engine.Keypad[dataName].CodeInput == correctCode then TEN.Sound.PlaySound(soundIDs["Success"]) for _, mesh in pairs(meshMappings) do target:SetMeshVisible(mesh.dark, true) -- Show dark keys target:SetMeshVisible(mesh.bright, false) -- Hide bright keys end LevelFuncs.Engine.ExitKeypad(object, true) return else TEN.Sound.PlaySound(soundIDs["Failure"]) LevelVars.Engine.Keypad[dataName].CodeInput = "" -- Reset the entered code if incorrect end else if string.len(LevelVars.Engine.Keypad[dataName].CodeInput) < maxCodeLength then LevelVars.Engine.Keypad[dataName].CodeInput = LevelVars.Engine.Keypad[dataName].CodeInput .. tostring(selectedKey) end end elseif KeyIsHit(ActionID.FORWARD) then LevelVars.Engine.Keypad[dataName].CursorY = LevelVars.Engine.Keypad[dataName].CursorY -1 TEN.Sound.PlaySound(soundIDs["Click"]) elseif KeyIsHit(ActionID.BACK) then LevelVars.Engine.Keypad[dataName].CursorY = LevelVars.Engine.Keypad[dataName].CursorY + 1 TEN.Sound.PlaySound(soundIDs["Click"]) elseif KeyIsHit(ActionID.LEFT) then LevelVars.Engine.Keypad[dataName].CursorX = LevelVars.Engine.Keypad[dataName].CursorX - 1 TEN.Sound.PlaySound(soundIDs["Click"]) elseif KeyIsHit(ActionID.RIGHT) then LevelVars.Engine.Keypad[dataName].CursorX = LevelVars.Engine.Keypad[dataName].CursorX + 1 TEN.Sound.PlaySound(soundIDs["Click"]) elseif KeyIsHit(ActionID.INVENTORY) then TEN.Sound.PlaySound(soundIDs["Failure"]) LevelVars.Engine.Keypad[dataName].CodeInput = "" LevelVars.Engine.Keypad[dataName].CursorX = 1 LevelVars.Engine.Keypad[dataName].CursorY = 1 for _, mesh in pairs(meshMappings) do target:SetMeshVisible(mesh.dark, true) -- Show dark keys target:SetMeshVisible(mesh.bright, false) -- Hide bright keys end LevelFuncs.Engine.ExitKeypad(object, false) return end -- Clamp cursorX within the valid range of the current row LevelVars.Engine.Keypad[dataName].CursorX = math.max(1, math.min(LevelVars.Engine.Keypad[dataName].CursorX, 3)) -- Clamp cursorY within the total number of rows LevelVars.Engine.Keypad[dataName].CursorY = math.max(1, math.min(LevelVars.Engine.Keypad[dataName].CursorY, 4)) -- Function to format entered code with dashes local codeWithDashes = LevelVars.Engine.Keypad[dataName].CodeInput or "" while string.len(codeWithDashes) < maxCodeLength do codeWithDashes = codeWithDashes .. "-" end -- Function to update mesh visibility for y = 1, #keypad do for x = 1, #keypad[y] do local key = keypad[y][x] if meshMappings[key] then if x == LevelVars.Engine.Keypad[dataName].CursorX and y == LevelVars.Engine.Keypad[dataName].CursorY then -- Highlight the selected key (bright mesh) target:SetMeshVisible(meshMappings[key].dark, false) target:SetMeshVisible(meshMappings[key].bright, true) else -- Show dark keys for others target:SetMeshVisible(meshMappings[key].dark, true) target:SetMeshVisible(meshMappings[key].bright, false) end end end end -- Display entered code with dashes local controlsText = TEN.Strings.DisplayString(codeWithDashes, TEN.Vec2(TEN.Util.PercentToScreen(57.5, 19.5)), 1.60, TEN.Color(255,255,255), false, {Strings.DisplayStringOption.RIGHT}) ShowString(controlsText, 1 / 30) end
1
0.859729
1
0.859729
game-dev
MEDIA
0.539437
game-dev
0.860011
1
0.860011
SeleDreams/godot-2-3ds
92,467
scene/gui/tree.cpp
/*************************************************************************/ /* tree.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "tree.h" #include "globals.h" #include "os/input.h" #include "os/keyboard.h" #include "os/os.h" #include "print_string.h" #include "scene/main/viewport.h" void TreeItem::move_to_top() { if (!parent || parent->childs == this) return; //already on top TreeItem *prev = get_prev(); prev->next = next; next = parent->childs; parent->childs = this; } void TreeItem::move_to_bottom() { if (!parent || !next) return; while (next) { if (parent->childs == this) parent->childs = next; TreeItem *n = next; next = n->next; n->next = this; } } Size2 TreeItem::Cell::get_icon_size() const { if (icon.is_null()) return Size2(); if (icon_region == Rect2i()) return icon->get_size(); else return icon_region.size; } void TreeItem::Cell::draw_icon(const RID &p_where, const Point2 &p_pos, const Size2 &p_size) const { if (icon.is_null()) return; Size2i dsize = (p_size == Size2()) ? icon->get_size() : p_size; if (icon_region == Rect2i()) { icon->draw_rect_region(p_where, Rect2(p_pos, dsize), Rect2(Point2(), icon->get_size())); } else { icon->draw_rect_region(p_where, Rect2(p_pos, dsize), icon_region); } } void TreeItem::_changed_notify(int p_cell) { tree->item_changed(p_cell, this); } void TreeItem::_changed_notify() { tree->item_changed(-1, this); } void TreeItem::_cell_selected(int p_cell) { tree->item_selected(p_cell, this); } void TreeItem::_cell_deselected(int p_cell) { tree->item_deselected(p_cell, this); } /* cell mode */ void TreeItem::set_cell_mode(int p_column, TreeCellMode p_mode) { ERR_FAIL_INDEX(p_column, cells.size()); Cell &c = cells[p_column]; c.mode = p_mode; c.min = 0; c.max = 100; c.step = 1; c.val = 0; c.checked = false; c.icon = Ref<Texture>(); c.text = ""; c.icon_max_w = 0; _changed_notify(p_column); } TreeItem::TreeCellMode TreeItem::get_cell_mode(int p_column) const { ERR_FAIL_INDEX_V(p_column, cells.size(), TreeItem::CELL_MODE_STRING); return cells[p_column].mode; } /* check mode */ void TreeItem::set_checked(int p_column, bool p_checked) { ERR_FAIL_INDEX(p_column, cells.size()); cells[p_column].checked = p_checked; _changed_notify(p_column); } bool TreeItem::is_checked(int p_column) const { ERR_FAIL_INDEX_V(p_column, cells.size(), false); return cells[p_column].checked; } void TreeItem::set_text(int p_column, String p_text) { ERR_FAIL_INDEX(p_column, cells.size()); cells[p_column].text = p_text; if (cells[p_column].mode == TreeItem::CELL_MODE_RANGE || cells[p_column].mode == TreeItem::CELL_MODE_RANGE_EXPRESSION) { cells[p_column].min = 0; cells[p_column].max = p_text.get_slice_count(","); cells[p_column].step = 0; } _changed_notify(p_column); } String TreeItem::get_text(int p_column) const { ERR_FAIL_INDEX_V(p_column, cells.size(), ""); return cells[p_column].text; } void TreeItem::set_icon(int p_column, const Ref<Texture> &p_icon) { ERR_FAIL_INDEX(p_column, cells.size()); cells[p_column].icon = p_icon; _changed_notify(p_column); } Ref<Texture> TreeItem::get_icon(int p_column) const { ERR_FAIL_INDEX_V(p_column, cells.size(), Ref<Texture>()); return cells[p_column].icon; } void TreeItem::set_icon_region(int p_column, const Rect2 &p_icon_region) { ERR_FAIL_INDEX(p_column, cells.size()); cells[p_column].icon_region = p_icon_region; _changed_notify(p_column); } Rect2 TreeItem::get_icon_region(int p_column) const { ERR_FAIL_INDEX_V(p_column, cells.size(), Rect2()); return cells[p_column].icon_region; } void TreeItem::set_icon_max_width(int p_column, int p_max) { ERR_FAIL_INDEX(p_column, cells.size()); cells[p_column].icon_max_w = p_max; _changed_notify(p_column); } int TreeItem::get_icon_max_width(int p_column) const { ERR_FAIL_INDEX_V(p_column, cells.size(), 0); return cells[p_column].icon_max_w; } /* range works for mode number or mode combo */ void TreeItem::set_range(int p_column, double p_value) { ERR_FAIL_INDEX(p_column, cells.size()); if (cells[p_column].step > 0) p_value = Math::stepify(p_value, cells[p_column].step); if (p_value < cells[p_column].min) p_value = cells[p_column].min; if (p_value > cells[p_column].max) p_value = cells[p_column].max; cells[p_column].val = p_value; _changed_notify(p_column); } double TreeItem::get_range(int p_column) const { ERR_FAIL_INDEX_V(p_column, cells.size(), 0); return cells[p_column].val; } bool TreeItem::is_range_exponential(int p_column) const { ERR_FAIL_INDEX_V(p_column, cells.size(), false); return cells[p_column].expr; } void TreeItem::set_range_config(int p_column, double p_min, double p_max, double p_step, bool p_exp) { ERR_FAIL_INDEX(p_column, cells.size()); cells[p_column].min = p_min; cells[p_column].max = p_max; cells[p_column].step = p_step; cells[p_column].expr = p_exp; _changed_notify(p_column); } void TreeItem::get_range_config(int p_column, double &r_min, double &r_max, double &r_step) const { ERR_FAIL_INDEX(p_column, cells.size()); r_min = cells[p_column].min; r_max = cells[p_column].max; r_step = cells[p_column].step; } void TreeItem::set_metadata(int p_column, const Variant &p_meta) { ERR_FAIL_INDEX(p_column, cells.size()); cells[p_column].meta = p_meta; } Variant TreeItem::get_metadata(int p_column) const { ERR_FAIL_INDEX_V(p_column, cells.size(), Variant()); return cells[p_column].meta; } void TreeItem::set_custom_draw(int p_column, Object *p_object, const StringName &p_callback) { ERR_FAIL_INDEX(p_column, cells.size()); ERR_FAIL_NULL(p_object); cells[p_column].custom_draw_obj = p_object->get_instance_ID(); cells[p_column].custom_draw_callback = p_callback; } void TreeItem::set_collapsed(bool p_collapsed) { if (collapsed == p_collapsed) return; collapsed = p_collapsed; TreeItem *ci = tree->selected_item; if (ci) { while (ci && ci != this) { ci = ci->parent; } if (ci) { // collapsing cursor/selectd, move it! if (tree->select_mode == Tree::SELECT_MULTI) { tree->selected_item = this; emit_signal("cell_selected"); } else { select(tree->selected_col); } tree->update(); } } _changed_notify(); if (tree) tree->emit_signal("item_collapsed", this); } bool TreeItem::is_collapsed() { return collapsed; } TreeItem *TreeItem::get_next() { return next; } TreeItem *TreeItem::get_prev() { if (!parent || parent->childs == this) return NULL; TreeItem *prev = parent->childs; while (prev && prev->next != this) prev = prev->next; return prev; } TreeItem *TreeItem::get_parent() { return parent; } TreeItem *TreeItem::get_children() { return childs; } TreeItem *TreeItem::get_prev_visible() { TreeItem *current = this; TreeItem *prev = current->get_prev(); if (!prev) { current = current->parent; if (!current || (current == tree->root && tree->hide_root)) return NULL; } else { current = prev; while (!current->collapsed && current->childs) { //go to the very end current = current->childs; while (current->next) current = current->next; } } return current; } TreeItem *TreeItem::get_next_visible() { TreeItem *current = this; if (!current->collapsed && current->childs) { current = current->childs; } else if (current->next) { current = current->next; } else { while (current && !current->next) { current = current->parent; } if (current == NULL) return NULL; else current = current->next; } return current; } void TreeItem::remove_child(TreeItem *p_item) { ERR_FAIL_NULL(p_item); TreeItem **c = &childs; while (*c) { if ((*c) == p_item) { TreeItem *aux = *c; *c = (*c)->next; aux->parent = NULL; return; } c = &(*c)->next; } ERR_FAIL(); } void TreeItem::set_selectable(int p_column, bool p_selectable) { ERR_FAIL_INDEX(p_column, cells.size()); cells[p_column].selectable = p_selectable; } bool TreeItem::is_selectable(int p_column) const { ERR_FAIL_INDEX_V(p_column, cells.size(), false); return cells[p_column].selectable; } bool TreeItem::is_selected(int p_column) { ERR_FAIL_INDEX_V(p_column, cells.size(), false); return cells[p_column].selectable && cells[p_column].selected; } void TreeItem::set_as_cursor(int p_column) { ERR_FAIL_INDEX(p_column, cells.size()); if (!tree) return; if (tree->select_mode != Tree::SELECT_MULTI) return; tree->selected_item = this; tree->selected_col = p_column; tree->update(); } void TreeItem::select(int p_column) { ERR_FAIL_INDEX(p_column, cells.size()); _cell_selected(p_column); } void TreeItem::deselect(int p_column) { ERR_FAIL_INDEX(p_column, cells.size()); _cell_deselected(p_column); } void TreeItem::add_button(int p_column, const Ref<Texture> &p_button, int p_id, bool p_disabled, const String &p_tooltip) { ERR_FAIL_INDEX(p_column, cells.size()); ERR_FAIL_COND(!p_button.is_valid()); TreeItem::Cell::Button button; button.texture = p_button; if (p_id < 0) p_id = cells[p_column].buttons.size(); button.id = p_id; button.disabled = p_disabled; button.tooltip = p_tooltip; cells[p_column].buttons.push_back(button); _changed_notify(p_column); } int TreeItem::get_button_count(int p_column) const { ERR_FAIL_INDEX_V(p_column, cells.size(), -1); return cells[p_column].buttons.size(); } Ref<Texture> TreeItem::get_button(int p_column, int p_idx) const { ERR_FAIL_INDEX_V(p_column, cells.size(), Ref<Texture>()); ERR_FAIL_INDEX_V(p_idx, cells[p_column].buttons.size(), Ref<Texture>()); return cells[p_column].buttons[p_idx].texture; } int TreeItem::get_button_id(int p_column, int p_idx) const { ERR_FAIL_INDEX_V(p_column, cells.size(), -1); ERR_FAIL_INDEX_V(p_idx, cells[p_column].buttons.size(), -1); return cells[p_column].buttons[p_idx].id; } void TreeItem::erase_button(int p_column, int p_idx) { ERR_FAIL_INDEX(p_column, cells.size()); ERR_FAIL_INDEX(p_idx, cells[p_column].buttons.size()); cells[p_column].buttons.remove(p_idx); _changed_notify(p_column); } int TreeItem::get_button_by_id(int p_column, int p_id) const { ERR_FAIL_INDEX_V(p_column, cells.size(), -1); for (int i = 0; i < cells[p_column].buttons.size(); i++) { if (cells[p_column].buttons[i].id == p_id) return i; } return -1; } bool TreeItem::is_button_disabled(int p_column, int p_idx) const { ERR_FAIL_INDEX_V(p_column, cells.size(), false); ERR_FAIL_INDEX_V(p_idx, cells[p_column].buttons.size(), false); return cells[p_column].buttons[p_idx].disabled; } void TreeItem::set_button(int p_column, int p_idx, const Ref<Texture> &p_button) { ERR_FAIL_COND(p_button.is_null()); ERR_FAIL_INDEX(p_column, cells.size()); ERR_FAIL_INDEX(p_idx, cells[p_column].buttons.size()); cells[p_column].buttons[p_idx].texture = p_button; _changed_notify(p_column); } void TreeItem::set_button_color(int p_column, int p_idx, const Color &p_color) { ERR_FAIL_INDEX(p_column, cells.size()); ERR_FAIL_INDEX(p_idx, cells[p_column].buttons.size()); cells[p_column].buttons[p_idx].color = p_color; _changed_notify(p_column); } void TreeItem::set_editable(int p_column, bool p_editable) { ERR_FAIL_INDEX(p_column, cells.size()); cells[p_column].editable = p_editable; _changed_notify(p_column); } bool TreeItem::is_editable(int p_column) { ERR_FAIL_INDEX_V(p_column, cells.size(), false); return cells[p_column].editable; } void TreeItem::set_custom_color(int p_column, const Color &p_color) { ERR_FAIL_INDEX(p_column, cells.size()); cells[p_column].custom_color = true; cells[p_column].color = p_color; _changed_notify(p_column); } Color TreeItem::get_custom_color(int p_column) const { ERR_FAIL_INDEX_V(p_column, cells.size(), Color()); if (!cells[p_column].custom_color) return Color(); return cells[p_column].color; } void TreeItem::clear_custom_color(int p_column) { ERR_FAIL_INDEX(p_column, cells.size()); cells[p_column].custom_color = false; cells[p_column].color = Color(); _changed_notify(p_column); } void TreeItem::set_tooltip(int p_column, const String &p_tooltip) { ERR_FAIL_INDEX(p_column, cells.size()); cells[p_column].tooltip = p_tooltip; } String TreeItem::get_tooltip(int p_column) const { ERR_FAIL_INDEX_V(p_column, cells.size(), ""); return cells[p_column].tooltip; } void TreeItem::set_custom_bg_color(int p_column, const Color &p_color, bool p_bg_outline) { ERR_FAIL_INDEX(p_column, cells.size()); cells[p_column].custom_bg_color = true; cells[p_column].custom_bg_outline = p_bg_outline; cells[p_column].bg_color = p_color; _changed_notify(p_column); } void TreeItem::clear_custom_bg_color(int p_column) { ERR_FAIL_INDEX(p_column, cells.size()); cells[p_column].custom_bg_color = false; cells[p_column].bg_color = Color(); _changed_notify(p_column); } Color TreeItem::get_custom_bg_color(int p_column) const { ERR_FAIL_INDEX_V(p_column, cells.size(), Color()); if (!cells[p_column].custom_bg_color) return Color(); return cells[p_column].bg_color; } void TreeItem::_bind_methods() { ObjectTypeDB::bind_method(_MD("set_cell_mode", "column", "mode"), &TreeItem::set_cell_mode); ObjectTypeDB::bind_method(_MD("get_cell_mode", "column"), &TreeItem::get_cell_mode); ObjectTypeDB::bind_method(_MD("set_checked", "column", "checked"), &TreeItem::set_checked); ObjectTypeDB::bind_method(_MD("is_checked", "column"), &TreeItem::is_checked); ObjectTypeDB::bind_method(_MD("set_text", "column", "text"), &TreeItem::set_text); ObjectTypeDB::bind_method(_MD("get_text", "column"), &TreeItem::get_text); ObjectTypeDB::bind_method(_MD("set_icon", "column", "texture:Texture"), &TreeItem::set_icon); ObjectTypeDB::bind_method(_MD("get_icon:Texture", "column"), &TreeItem::get_icon); ObjectTypeDB::bind_method(_MD("set_icon_region", "column", "region"), &TreeItem::set_icon_region); ObjectTypeDB::bind_method(_MD("get_icon_region", "column"), &TreeItem::get_icon_region); ObjectTypeDB::bind_method(_MD("set_icon_max_width", "column", "width"), &TreeItem::set_icon_max_width); ObjectTypeDB::bind_method(_MD("get_icon_max_width", "column"), &TreeItem::get_icon_max_width); ObjectTypeDB::bind_method(_MD("set_range", "column", "value"), &TreeItem::set_range); ObjectTypeDB::bind_method(_MD("get_range", "column"), &TreeItem::get_range); ObjectTypeDB::bind_method(_MD("set_range_config", "column", "min", "max", "step", "expr"), &TreeItem::set_range_config, DEFVAL(false)); ObjectTypeDB::bind_method(_MD("get_range_config", "column"), &TreeItem::_get_range_config); ObjectTypeDB::bind_method(_MD("set_metadata", "column", "meta"), &TreeItem::set_metadata); ObjectTypeDB::bind_method(_MD("get_metadata", "column"), &TreeItem::get_metadata); ObjectTypeDB::bind_method(_MD("set_custom_draw", "column", "object", "callback"), &TreeItem::set_custom_draw); ObjectTypeDB::bind_method(_MD("set_collapsed", "enable"), &TreeItem::set_collapsed); ObjectTypeDB::bind_method(_MD("is_collapsed"), &TreeItem::is_collapsed); ObjectTypeDB::bind_method(_MD("get_next:TreeItem"), &TreeItem::get_next); ObjectTypeDB::bind_method(_MD("get_prev:TreeItem"), &TreeItem::get_prev); ObjectTypeDB::bind_method(_MD("get_parent:TreeItem"), &TreeItem::get_parent); ObjectTypeDB::bind_method(_MD("get_children:TreeItem"), &TreeItem::get_children); ObjectTypeDB::bind_method(_MD("get_next_visible:TreeItem"), &TreeItem::get_next_visible); ObjectTypeDB::bind_method(_MD("get_prev_visible:TreeItem"), &TreeItem::get_prev_visible); ObjectTypeDB::bind_method(_MD("remove_child:TreeItem", "child"), &TreeItem::_remove_child); ObjectTypeDB::bind_method(_MD("set_selectable", "column", "selectable"), &TreeItem::set_selectable); ObjectTypeDB::bind_method(_MD("is_selectable", "column"), &TreeItem::is_selectable); ObjectTypeDB::bind_method(_MD("is_selected", "column"), &TreeItem::is_selected); ObjectTypeDB::bind_method(_MD("select", "column"), &TreeItem::select); ObjectTypeDB::bind_method(_MD("deselect", "column"), &TreeItem::deselect); ObjectTypeDB::bind_method(_MD("set_editable", "column", "enabled"), &TreeItem::set_editable); ObjectTypeDB::bind_method(_MD("is_editable", "column"), &TreeItem::is_editable); ObjectTypeDB::bind_method(_MD("set_custom_color", "column", "color"), &TreeItem::set_custom_color); ObjectTypeDB::bind_method(_MD("clear_custom_color", "column"), &TreeItem::clear_custom_color); ObjectTypeDB::bind_method(_MD("set_custom_bg_color", "column", "color", "just_outline"), &TreeItem::set_custom_bg_color, DEFVAL(false)); ObjectTypeDB::bind_method(_MD("clear_custom_bg_color", "column"), &TreeItem::clear_custom_bg_color); ObjectTypeDB::bind_method(_MD("get_custom_bg_color", "column"), &TreeItem::get_custom_bg_color); ObjectTypeDB::bind_method(_MD("add_button", "column", "button:Texture", "button_idx", "disabled", "tooltip"), &TreeItem::add_button, DEFVAL(-1), DEFVAL(false), DEFVAL("")); ObjectTypeDB::bind_method(_MD("get_button_count", "column"), &TreeItem::get_button_count); ObjectTypeDB::bind_method(_MD("get_button:Texture", "column", "button_idx"), &TreeItem::get_button); ObjectTypeDB::bind_method(_MD("set_button", "column", "button_idx", "button:Texture"), &TreeItem::set_button); ObjectTypeDB::bind_method(_MD("erase_button", "column", "button_idx"), &TreeItem::erase_button); ObjectTypeDB::bind_method(_MD("is_button_disabled", "column", "button_idx"), &TreeItem::is_button_disabled); ObjectTypeDB::bind_method(_MD("set_tooltip", "column", "tooltip"), &TreeItem::set_tooltip); ObjectTypeDB::bind_method(_MD("get_tooltip", "column"), &TreeItem::get_tooltip); ObjectTypeDB::bind_method(_MD("move_to_top"), &TreeItem::move_to_top); ObjectTypeDB::bind_method(_MD("move_to_bottom"), &TreeItem::move_to_bottom); BIND_CONSTANT(CELL_MODE_STRING); BIND_CONSTANT(CELL_MODE_CHECK); BIND_CONSTANT(CELL_MODE_RANGE); BIND_CONSTANT(CELL_MODE_RANGE_EXPRESSION); BIND_CONSTANT(CELL_MODE_ICON); BIND_CONSTANT(CELL_MODE_CUSTOM); } void TreeItem::clear_children() { TreeItem *c = childs; while (c) { TreeItem *aux = c; c = c->get_next(); aux->parent = 0; // so it wont try to recursively autoremove from me in here memdelete(aux); } childs = 0; }; TreeItem::TreeItem(Tree *p_tree) { tree = p_tree; collapsed = false; parent = 0; // parent item next = 0; // next in list childs = 0; //child items } TreeItem::~TreeItem() { clear_children(); if (parent) parent->remove_child(this); if (tree && tree->root == this) { tree->root = 0; } if (tree && tree->popup_edited_item == this) { tree->popup_edited_item = NULL; tree->pressing_for_editor = false; } if (tree && tree->selected_item == this) tree->selected_item = NULL; if (tree && tree->drop_mode_over == this) tree->drop_mode_over = NULL; if (tree && tree->single_select_defer == this) tree->single_select_defer = NULL; if (tree && tree->edited_item == this) { tree->edited_item = NULL; tree->pressing_for_editor = false; } } /**********************************************/ /**********************************************/ /**********************************************/ /**********************************************/ /**********************************************/ /**********************************************/ void Tree::update_cache() { cache.font = get_font("font"); cache.tb_font = get_font("title_button_font"); cache.bg = get_stylebox("bg"); cache.selected = get_stylebox("selected"); cache.selected_focus = get_stylebox("selected_focus"); cache.cursor = get_stylebox("cursor"); cache.cursor_unfocus = get_stylebox("cursor_unfocused"); cache.button_pressed = get_stylebox("button_pressed"); cache.checked = get_icon("checked"); cache.unchecked = get_icon("unchecked"); cache.arrow_collapsed = get_icon("arrow_collapsed"); cache.arrow = get_icon("arrow"); cache.select_arrow = get_icon("select_arrow"); cache.updown = get_icon("updown"); cache.font_color = get_color("font_color"); cache.font_color_selected = get_color("font_color_selected"); cache.guide_color = get_color("guide_color"); cache.drop_position_color = get_color("drop_position_color"); cache.hseparation = get_constant("hseparation"); cache.vseparation = get_constant("vseparation"); cache.item_margin = get_constant("item_margin"); cache.button_margin = get_constant("button_margin"); cache.guide_width = get_constant("guide_width"); cache.draw_relationship_lines = get_constant("draw_relationship_lines"); cache.relationship_line_color = get_color("relationship_line_color"); cache.scroll_border = get_constant("scroll_border"); cache.scroll_speed = get_constant("scroll_speed"); cache.title_button = get_stylebox("title_button_normal"); cache.title_button_pressed = get_stylebox("title_button_pressed"); cache.title_button_hover = get_stylebox("title_button_hover"); cache.title_button_color = get_color("title_button_color"); v_scroll->set_custom_step(cache.font->get_height()); } int Tree::compute_item_height(TreeItem *p_item) const { if (p_item == root && hide_root) return 0; int height = cache.font->get_height(); for (int i = 0; i < columns.size(); i++) { for (int j = 0; j < p_item->cells[i].buttons.size(); j++) { Size2i s; // = cache.button_pressed->get_minimum_size(); s += p_item->cells[i].buttons[j].texture->get_size(); if (s.height > height) height = s.height; } switch (p_item->cells[i].mode) { case TreeItem::CELL_MODE_CHECK: { int check_icon_h = cache.checked->get_height(); if (height < check_icon_h) height = check_icon_h; } case TreeItem::CELL_MODE_STRING: case TreeItem::CELL_MODE_CUSTOM: case TreeItem::CELL_MODE_ICON: { Ref<Texture> icon = p_item->cells[i].icon; if (!icon.is_null()) { Size2i s = p_item->cells[i].get_icon_size(); if (p_item->cells[i].icon_max_w > 0 && s.width > p_item->cells[i].icon_max_w) { s.height = s.height * p_item->cells[i].icon_max_w / s.width; } if (s.height > height) height = s.height; } } break; default: { } } } height += cache.vseparation; return height; } int Tree::get_item_height(TreeItem *p_item) const { int height = compute_item_height(p_item); height += cache.vseparation; if (!p_item->collapsed) { /* if not collapsed, check the childs */ TreeItem *c = p_item->childs; while (c) { height += get_item_height(c); c = c->next; } } return height; } void Tree::draw_item_rect(const TreeItem::Cell &p_cell, const Rect2i &p_rect, const Color &p_color) { Rect2i rect = p_rect; RID ci = get_canvas_item(); if (!p_cell.icon.is_null()) { Size2i bmsize = p_cell.get_icon_size(); if (p_cell.icon_max_w > 0 && bmsize.width > p_cell.icon_max_w) { bmsize.height = bmsize.height * p_cell.icon_max_w / bmsize.width; bmsize.width = p_cell.icon_max_w; } p_cell.draw_icon(ci, rect.pos + Size2i(0, Math::floor((rect.size.y - bmsize.y) / 2)), bmsize); rect.pos.x += bmsize.x + cache.hseparation; rect.size.x -= bmsize.x + cache.hseparation; } // if (p_tool) // rect.size.x-=Math::floor(rect.size.y/2); Ref<Font> font = cache.font; rect.pos.y += Math::floor((rect.size.y - font->get_height()) / 2.0) + font->get_ascent(); font->draw(ci, rect.pos, p_cell.text, p_color, rect.size.x); } #if 0 void Tree::draw_item_text(String p_text,const Ref<Texture>& p_icon,int p_icon_max_w,bool p_tool,Rect2i p_rect,const Color& p_color) { RID ci = get_canvas_item(); if (!p_icon.is_null()) { Size2i bmsize = p_icon->get_size(); if (p_icon_max_w>0 && bmsize.width > p_icon_max_w) { bmsize.height = bmsize.height * p_icon_max_w / bmsize.width; bmsize.width=p_icon_max_w; } draw_texture_rect(p_icon,Rect2(p_rect.pos + Size2i(0,Math::floor((p_rect.size.y-bmsize.y)/2)),bmsize)); p_rect.pos.x+=bmsize.x+cache.hseparation; p_rect.size.x-=bmsize.x+cache.hseparation; } if (p_tool) p_rect.size.x-=Math::floor(p_rect.size.y/2); Ref<Font> font = cache.font; p_rect.pos.y+=Math::floor((p_rect.size.y-font->get_height())/2.0) +font->get_ascent(); font->draw(ci,p_rect.pos,p_text,p_color,p_rect.size.x); } #endif int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2 &p_draw_size, TreeItem *p_item) { if (p_pos.y - cache.offset.y > (p_draw_size.height)) return -1; //draw no more! RID ci = get_canvas_item(); int htotal = 0; int label_h = compute_item_height(p_item); /* Calculate height of the label part */ label_h += cache.vseparation; /* Draw label, if height fits */ bool skip = (p_item == root && hide_root); if (!skip && (p_pos.y + label_h - cache.offset.y) > 0) { if (!hide_folding && p_item->childs) { //has childs, draw the guide box Ref<Texture> arrow; if (p_item->collapsed) { arrow = cache.arrow_collapsed; } else { arrow = cache.arrow; } arrow->draw(ci, p_pos + p_draw_ofs + Point2i(0, (label_h - arrow->get_height()) / 2) - cache.offset); } //draw separation. // if (p_item->get_parent()!=root || !hide_root) Ref<Font> font = cache.font; int font_ascent = font->get_ascent(); int ofs = p_pos.x + (hide_folding ? cache.hseparation : cache.item_margin); for (int i = 0; i < columns.size(); i++) { int w = get_column_width(i); if (i == 0) { w -= ofs; if (w <= 0) { ofs = get_column_width(0); continue; } } else { ofs += cache.hseparation; w -= cache.hseparation; } int bw = 0; for (int j = p_item->cells[i].buttons.size() - 1; j >= 0; j--) { Ref<Texture> b = p_item->cells[i].buttons[j].texture; Size2 s = b->get_size() + cache.button_pressed->get_minimum_size(); Point2i o = Point2i(ofs + w - s.width, p_pos.y) - cache.offset + p_draw_ofs; if (cache.click_type == Cache::CLICK_BUTTON && cache.click_item == p_item && cache.click_column == i && cache.click_index == j && !p_item->cells[i].buttons[j].disabled) { //being pressed cache.button_pressed->draw(get_canvas_item(), Rect2(o, s)); } o.y += (label_h - s.height) / 2; o += cache.button_pressed->get_offset(); b->draw(ci, o, p_item->cells[i].buttons[j].disabled ? Color(1, 1, 1, 0.5) : p_item->cells[i].buttons[j].color); w -= s.width + cache.button_margin; bw += s.width + cache.button_margin; } Rect2i item_rect = Rect2i(Point2i(ofs, p_pos.y) - cache.offset + p_draw_ofs, Size2i(w, label_h)); Rect2i cell_rect = item_rect; if (i != 0) { cell_rect.pos.x -= cache.hseparation; cell_rect.size.x += cache.hseparation; } VisualServer::get_singleton()->canvas_item_add_line(ci, Point2i(cell_rect.pos.x, cell_rect.pos.y + cell_rect.size.height), cell_rect.pos + cell_rect.size, cache.guide_color, 1); if (i == 0) { if (p_item->cells[0].selected && select_mode == SELECT_ROW) { Rect2i row_rect = Rect2i(Point2i(cache.bg->get_margin(MARGIN_LEFT), item_rect.pos.y), Size2i(get_size().width - cache.bg->get_minimum_size().width, item_rect.size.y)); //Rect2 r = Rect2i(row_rect.pos,row_rect.size); //r.grow(cache.selected->get_margin(MARGIN_LEFT)); if (has_focus()) cache.selected_focus->draw(ci, row_rect); else cache.selected->draw(ci, row_rect); } } if (p_item->cells[i].selected && select_mode != SELECT_ROW) { Rect2i r(item_rect.pos, item_rect.size); if (p_item->cells[i].text.size() > 0) { float icon_width = p_item->cells[i].get_icon_size().width; r.pos.x += icon_width; r.size.x -= icon_width; } //r.grow(cache.selected->get_margin(MARGIN_LEFT)); if (has_focus()) { cache.selected_focus->draw(ci, r); p_item->set_meta("__focus_rect", Rect2(r.pos, r.size)); } else { cache.selected->draw(ci, r); } if (text_editor->is_visible()) { Vector2 ofs(0, (text_editor->get_size().height - r.size.height) / 2); text_editor->set_pos(get_global_pos() + r.pos - ofs); } } if (p_item->cells[i].custom_bg_color) { Rect2 r = cell_rect; r.pos.x -= cache.hseparation; r.size.x += cache.hseparation; if (p_item->cells[i].custom_bg_outline) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x, r.pos.y, r.size.x, 1), p_item->cells[i].bg_color); VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x, r.pos.y + r.size.y - 1, r.size.x, 1), p_item->cells[i].bg_color); VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x, r.pos.y, 1, r.size.y), p_item->cells[i].bg_color); VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x + r.size.x - 1, r.pos.y, 1, r.size.y), p_item->cells[i].bg_color); } else { VisualServer::get_singleton()->canvas_item_add_rect(ci, r, p_item->cells[i].bg_color); } } if (drop_mode_flags && drop_mode_over == p_item) { Rect2 r = cell_rect; if (drop_mode_section == -1 || drop_mode_section == 0) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x, r.pos.y, r.size.x, 1), cache.drop_position_color); } if (drop_mode_section == 0) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x, r.pos.y, 1, r.size.y), cache.drop_position_color); VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x + r.size.x - 1, r.pos.y, 1, r.size.y), cache.drop_position_color); } if (drop_mode_section == 1 || drop_mode_section == 0) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x, r.pos.y + r.size.y, r.size.x, 1), cache.drop_position_color); } } Color col = p_item->cells[i].custom_color ? p_item->cells[i].color : get_color(p_item->cells[i].selected ? "font_color_selected" : "font_color"); Point2i text_pos = item_rect.pos; text_pos.y += Math::floor((item_rect.size.y - font->get_height()) / 2) + font_ascent; switch (p_item->cells[i].mode) { case TreeItem::CELL_MODE_STRING: { draw_item_rect(p_item->cells[i], item_rect, col); } break; case TreeItem::CELL_MODE_CHECK: { Ref<Texture> checked = cache.checked; Ref<Texture> unchecked = cache.unchecked; Point2i check_ofs = item_rect.pos; check_ofs.y += Math::floor((item_rect.size.y - checked->get_height()) / 2); if (p_item->cells[i].checked) { checked->draw(ci, check_ofs); } else { unchecked->draw(ci, check_ofs); } int check_w = checked->get_width() + cache.hseparation; text_pos.x += check_w; item_rect.size.x -= check_w; item_rect.pos.x += check_w; draw_item_rect(p_item->cells[i], item_rect, col); //font->draw( ci, text_pos, p_item->cells[i].text, col,item_rect.size.x-check_w ); } break; case TreeItem::CELL_MODE_RANGE: case TreeItem::CELL_MODE_RANGE_EXPRESSION: { if (p_item->cells[i].text != "") { if (!p_item->cells[i].editable) break; int option = (int)p_item->cells[i].val; String s = p_item->cells[i].text; s = s.get_slicec(',', option); Ref<Texture> downarrow = cache.select_arrow; font->draw(ci, text_pos, s, col, item_rect.size.x - downarrow->get_width()); //? Point2i arrow_pos = item_rect.pos; arrow_pos.x += item_rect.size.x - downarrow->get_width(); arrow_pos.y += Math::floor(((item_rect.size.y - downarrow->get_height())) / 2.0); downarrow->draw(ci, arrow_pos); } else { Ref<Texture> updown = cache.updown; String valtext = String::num(p_item->cells[i].val, Math::step_decimals(p_item->cells[i].step)); //String valtext = rtos( p_item->cells[i].val ); font->draw(ci, text_pos, valtext, col, item_rect.size.x - updown->get_width()); if (!p_item->cells[i].editable) break; Point2i updown_pos = item_rect.pos; updown_pos.x += item_rect.size.x - updown->get_width(); updown_pos.y += Math::floor(((item_rect.size.y - updown->get_height())) / 2.0); updown->draw(ci, updown_pos); } } break; case TreeItem::CELL_MODE_ICON: { if (p_item->cells[i].icon.is_null()) break; Size2i icon_size = p_item->cells[i].get_icon_size(); if (p_item->cells[i].icon_max_w > 0 && icon_size.width > p_item->cells[i].icon_max_w) { icon_size.height = icon_size.height * p_item->cells[i].icon_max_w / icon_size.width; icon_size.width = p_item->cells[i].icon_max_w; } Point2i icon_ofs = (item_rect.size - icon_size) / 2; icon_ofs += item_rect.pos; draw_texture_rect(p_item->cells[i].icon, Rect2(icon_ofs, icon_size)); //p_item->cells[i].icon->draw(ci, icon_ofs); } break; case TreeItem::CELL_MODE_CUSTOM: { // int option = (int)p_item->cells[i].val; if (p_item->cells[i].custom_draw_obj) { Object *cdo = ObjectDB::get_instance(p_item->cells[i].custom_draw_obj); if (cdo) cdo->call(p_item->cells[i].custom_draw_callback, p_item, Rect2(item_rect)); } if (!p_item->cells[i].editable) { draw_item_rect(p_item->cells[i], item_rect, col); break; } Ref<Texture> downarrow = cache.select_arrow; Rect2i ir = item_rect; ir.size.width -= downarrow->get_width(); draw_item_rect(p_item->cells[i], ir, col); Point2i arrow_pos = item_rect.pos; arrow_pos.x += item_rect.size.x - downarrow->get_width(); arrow_pos.y += Math::floor(((item_rect.size.y - downarrow->get_height())) / 2.0); downarrow->draw(ci, arrow_pos); } break; } if (i == 0) { ofs = get_column_width(0); } else { ofs += w + bw; } if (select_mode == SELECT_MULTI && selected_item == p_item && selected_col == i) { if (has_focus()) cache.cursor->draw(ci, cell_rect); else cache.cursor_unfocus->draw(ci, cell_rect); } } //separator //get_painter()->draw_fill_rect( Point2i(0,pos.y),Size2i(get_size().width,1),color( COLOR_TREE_GRID) ); //pos=p_pos; //reset pos } Point2 children_pos = p_pos; if (!skip) { children_pos.x += cache.item_margin; htotal += label_h; children_pos.y += htotal; } if (!p_item->collapsed) { /* if not collapsed, check the childs */ TreeItem *c = p_item->childs; while (c) { if (cache.draw_relationship_lines == 1) { int root_ofs = children_pos.x + (hide_folding ? cache.hseparation : cache.item_margin); int parent_ofs = p_pos.x + (hide_folding ? cache.hseparation : cache.item_margin); Point2i root_pos = Point2i(root_ofs, children_pos.y + label_h / 2) - cache.offset + p_draw_ofs; if (c->get_children() != NULL) root_pos -= Point2i(cache.arrow->get_width(), 0); Point2i parent_pos = Point2i(parent_ofs - cache.arrow->get_width() / 2, p_pos.y + label_h / 2 + cache.arrow->get_height() / 2) - cache.offset + p_draw_ofs; VisualServer::get_singleton()->canvas_item_add_line(ci, root_pos, Point2i(parent_pos.x, root_pos.y), cache.relationship_line_color); VisualServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y), parent_pos, cache.relationship_line_color); } int child_h = draw_item(children_pos, p_draw_ofs, p_draw_size, c); if (child_h < 0 && cache.draw_relationship_lines == 0) return -1; // break, stop drawing, no need to anymore htotal += child_h; children_pos.y += child_h; c = c->next; } } return htotal; } int Tree::_count_selected_items(TreeItem *p_from) const { int count = 0; for (int i = 0; i < columns.size(); i++) { if (p_from->is_selected(i)) count++; } if (p_from->get_children()) { count += _count_selected_items(p_from->get_children()); } if (p_from->get_next()) { count += _count_selected_items(p_from->get_next()); } return count; } void Tree::select_single_item(TreeItem *p_selected, TreeItem *p_current, int p_col, TreeItem *p_prev, bool *r_in_range, bool p_force_deselect) { TreeItem::Cell &selected_cell = p_selected->cells[p_col]; bool switched = false; if (r_in_range && !*r_in_range && (p_current == p_selected || p_current == p_prev)) { *r_in_range = true; switched = true; } bool emitted_row = false; for (int i = 0; i < columns.size(); i++) { TreeItem::Cell &c = p_current->cells[i]; if (!c.selectable) continue; if (select_mode == SELECT_ROW) { if (p_selected == p_current && !c.selected) { c.selected = true; selected_item = p_selected; selected_col = 0; selected_item = p_selected; if (!emitted_row) { emit_signal("item_selected"); emitted_row = true; } //if (p_col==i) // p_current->selected_signal.call(p_col); } else if (c.selected) { c.selected = false; //p_current->deselected_signal.call(p_col); } } else if (select_mode == SELECT_SINGLE || select_mode == SELECT_MULTI) { if (!r_in_range && &selected_cell == &c) { if (!selected_cell.selected) { selected_cell.selected = true; selected_item = p_selected; selected_col = i; emit_signal("cell_selected"); if (select_mode == SELECT_MULTI) emit_signal("multi_selected", p_current, i, true); else if (select_mode == SELECT_SINGLE) emit_signal("item_selected"); } else if (select_mode == SELECT_MULTI && (selected_item != p_selected || selected_col != i)) { selected_item = p_selected; selected_col = i; emit_signal("cell_selected"); } } else { if (r_in_range && *r_in_range && !p_force_deselect) { if (!c.selected && c.selectable) { c.selected = true; emit_signal("multi_selected", p_current, i, true); } } else if (!r_in_range || p_force_deselect) { if (select_mode == SELECT_MULTI && c.selected) emit_signal("multi_selected", p_current, i, false); c.selected = false; } //p_current->deselected_signal.call(p_col); } } } if (!switched && r_in_range && *r_in_range && (p_current == p_selected || p_current == p_prev)) { *r_in_range = false; } TreeItem *c = p_current->childs; while (c) { select_single_item(p_selected, c, p_col, p_prev, r_in_range, p_current->is_collapsed() || p_force_deselect); c = c->next; } } Rect2 Tree::search_item_rect(TreeItem *p_from, TreeItem *p_item) { return Rect2(); } void Tree::_range_click_timeout() { if (range_item_last && !range_drag_enabled && Input::get_singleton()->is_mouse_button_pressed(BUTTON_LEFT)) { Point2 pos = get_local_mouse_pos() - cache.bg->get_offset(); if (show_column_titles) { pos.y -= _get_title_button_height(); if (pos.y < 0) { range_click_timer->stop(); return; } } click_handled = false; InputModifierState mod = InputModifierState(); // should be irrelevant.. blocked++; propagate_mouse_event(pos + cache.offset, 0, 0, false, root, BUTTON_LEFT, mod); blocked--; if (range_click_timer->is_one_shot()) { range_click_timer->set_wait_time(0.05); range_click_timer->set_one_shot(false); range_click_timer->start(); } if (!click_handled) range_click_timer->stop(); } else { range_click_timer->stop(); } } int Tree::propagate_mouse_event(const Point2i &p_pos, int x_ofs, int y_ofs, bool p_doubleclick, TreeItem *p_item, int p_button, const InputModifierState &p_mod) { int item_h = compute_item_height(p_item) + cache.vseparation; bool skip = (p_item == root && hide_root); if (!skip && p_pos.y < item_h) { // check event! if (range_click_timer->get_time_left() > 0 && p_item != range_item_last) { return -1; } if (!hide_folding && (p_pos.x >= x_ofs && p_pos.x < (x_ofs + cache.item_margin))) { if (p_item->childs) p_item->set_collapsed(!p_item->is_collapsed()); return -1; //handled! } int x = p_pos.x; /* find clicked column */ int col = -1; int col_ofs = 0; int col_width = 0; for (int i = 0; i < columns.size(); i++) { col_width = get_column_width(i); if (x > col_width) { col_ofs += col_width; x -= col_width; continue; } col = i; break; } if (col == -1) return -1; else if (col == 0) { int margin = x_ofs + cache.item_margin; //-cache.hseparation; //int lm = cache.bg->get_margin(MARGIN_LEFT); col_width -= margin; col_ofs += margin; x -= margin; } else { col_width -= cache.hseparation; x -= cache.hseparation; } TreeItem::Cell &c = p_item->cells[col]; bool already_selected = c.selected; bool already_cursor = (p_item == selected_item) && col == selected_col; for (int j = c.buttons.size() - 1; j >= 0; j--) { Ref<Texture> b = c.buttons[j].texture; int w = b->get_size().width + cache.button_pressed->get_minimum_size().width; if (x > col_width - w) { if (c.buttons[j].disabled) { pressed_button = -1; cache.click_type = Cache::CLICK_NONE; return -1; } pressed_button = j; cache.click_type = Cache::CLICK_BUTTON; cache.click_index = j; cache.click_id = c.buttons[j].id; cache.click_item = p_item; cache.click_column = col; cache.click_pos = get_global_mouse_pos() - get_global_pos(); update(); //emit_signal("button_pressed"); return -1; } col_width -= w + cache.button_margin; } if (p_button == BUTTON_LEFT || (p_button == BUTTON_RIGHT && allow_rmb_select)) { /* process selection */ if (p_doubleclick && (!c.editable || c.mode == TreeItem::CELL_MODE_CUSTOM || c.mode == TreeItem::CELL_MODE_ICON /*|| c.mode==TreeItem::CELL_MODE_CHECK*/)) { //it' s confusing for check emit_signal("item_activated"); incr_search.clear(); return -1; } if (select_mode == SELECT_MULTI && p_mod.command && c.selectable) { if (!c.selected || p_button == BUTTON_RIGHT) { p_item->select(col); emit_signal("multi_selected", p_item, col, true); if (p_button == BUTTON_RIGHT) { emit_signal("item_rmb_selected", get_local_mouse_pos()); } //p_item->selected_signal.call(col); } else { p_item->deselect(col); emit_signal("multi_selected", p_item, col, false); //p_item->deselected_signal.call(col); } } else { if (c.selectable) { if (select_mode == SELECT_MULTI && p_mod.shift && selected_item && selected_item != p_item) { bool inrange = false; select_single_item(p_item, root, col, selected_item, &inrange); if (p_button == BUTTON_RIGHT) { emit_signal("item_rmb_selected", get_local_mouse_pos()); } } else { int icount = _count_selected_items(root); if (select_mode == SELECT_MULTI && icount > 1 && p_button != BUTTON_RIGHT) { single_select_defer = p_item; single_select_defer_column = col; } else { if (p_button != BUTTON_RIGHT || !c.selected) { select_single_item(p_item, root, col); } if (p_button == BUTTON_RIGHT) { emit_signal("item_rmb_selected", get_local_mouse_pos()); } } } //if (!c.selected && select_mode==SELECT_MULTI) { // emit_signal("multi_selected",p_item,col,true); //} update(); } } } if (!c.editable) return -1; // if cell is not editable, don't bother /* editing */ bool bring_up_editor = force_select_on_already_selected ? (c.selected && already_selected) : c.selected; String editor_text = c.text; switch (c.mode) { case TreeItem::CELL_MODE_STRING: { //nothing in particular if (select_mode == SELECT_MULTI && (get_tree()->get_last_event_id() == focus_in_id || !already_cursor)) { bring_up_editor = false; } } break; case TreeItem::CELL_MODE_CHECK: { Ref<Texture> checked = cache.checked; bring_up_editor = false; //checkboxes are not edited with editor if (x >= 0 && x <= checked->get_width() + cache.hseparation) { p_item->set_checked(col, !c.checked); item_edited(col, p_item); click_handled = true; //p_item->edited_signal.call(col); } } break; case TreeItem::CELL_MODE_RANGE: case TreeItem::CELL_MODE_RANGE_EXPRESSION: { if (c.text != "") { //if (x >= (get_column_width(col)-item_h/2)) { popup_menu->clear(); for (int i = 0; i < c.text.get_slice_count(","); i++) { String s = c.text.get_slicec(',', i); popup_menu->add_item(s, i); } popup_menu->set_size(Size2(col_width, 0)); popup_menu->set_pos(get_global_pos() + Point2i(col_ofs, _get_title_button_height() + y_ofs + item_h) - cache.offset); popup_menu->popup(); popup_edited_item = p_item; popup_edited_item_col = col; //} bring_up_editor = false; } else { if (x >= (col_width - item_h / 2)) { /* touching the combo */ bool up = p_pos.y < (item_h / 2); if (p_button == BUTTON_LEFT) { if (range_click_timer->get_time_left() == 0) { range_item_last = p_item; range_up_last = up; range_click_timer->set_wait_time(0.6); range_click_timer->set_one_shot(true); range_click_timer->start(); } else if (up != range_up_last) { return -1; // break. avoid changing direction on mouse held } p_item->set_range(col, c.val + (up ? 1.0 : -1.0) * c.step); item_edited(col, p_item); } else if (p_button == BUTTON_RIGHT) { p_item->set_range(col, (up ? c.max : c.min)); item_edited(col, p_item); } else if (p_button == BUTTON_WHEEL_UP) { p_item->set_range(col, c.val + c.step); item_edited(col, p_item); } else if (p_button == BUTTON_WHEEL_DOWN) { p_item->set_range(col, c.val - c.step); item_edited(col, p_item); } //p_item->edited_signal.call(col); bring_up_editor = false; } else { editor_text = String::num(p_item->cells[col].val, Math::step_decimals(p_item->cells[col].step)); if (select_mode == SELECT_MULTI && get_tree()->get_last_event_id() == focus_in_id) bring_up_editor = false; } } click_handled = true; } break; case TreeItem::CELL_MODE_ICON: { bring_up_editor = false; } break; case TreeItem::CELL_MODE_CUSTOM: { edited_item = p_item; edited_col = col; custom_popup_rect = Rect2i(get_global_pos() + Point2i(col_ofs, _get_title_button_height() + y_ofs + item_h - cache.offset.y), Size2(get_column_width(col), item_h)); emit_signal("custom_popup_edited", ((bool)(x >= (col_width - item_h / 2)))); bring_up_editor = false; item_edited(col, p_item); click_handled = true; return -1; } break; }; if (!bring_up_editor || p_button != BUTTON_LEFT) return -1; click_handled = true; popup_edited_item = p_item; popup_edited_item_col = col; pressing_item_rect = Rect2(get_global_pos() + Point2i(col_ofs, _get_title_button_height() + y_ofs) - cache.offset, Size2(col_width, item_h)); pressing_for_editor_text = editor_text; pressing_for_editor = true; return -1; //select } else { Point2i new_pos = p_pos; if (!skip) { x_ofs += cache.item_margin; //new_pos.x-=cache.item_margin; y_ofs += item_h; new_pos.y -= item_h; } if (!p_item->collapsed) { /* if not collapsed, check the childs */ TreeItem *c = p_item->childs; while (c) { int child_h = propagate_mouse_event(new_pos, x_ofs, y_ofs, p_doubleclick, c, p_button, p_mod); if (child_h < 0) return -1; // break, stop propagating, no need to anymore new_pos.y -= child_h; y_ofs += child_h; c = c->next; item_h += child_h; } } } return item_h; // nothing found } void Tree::_text_editor_modal_close() { if (Input::get_singleton()->is_key_pressed(KEY_ESCAPE) || Input::get_singleton()->is_key_pressed(KEY_ENTER) || Input::get_singleton()->is_key_pressed(KEY_RETURN)) { return; } if (value_editor->has_point(value_editor->get_local_mouse_pos())) return; text_editor_enter(text_editor->get_text()); } void Tree::text_editor_enter(String p_text) { text_editor->hide(); value_editor->hide(); if (!popup_edited_item) return; if (popup_edited_item_col < 0 || popup_edited_item_col > columns.size()) return; TreeItem::Cell &c = popup_edited_item->cells[popup_edited_item_col]; switch (c.mode) { case TreeItem::CELL_MODE_STRING: { c.text = p_text; //popup_edited_item->edited_signal.call( popup_edited_item_col ); } break; case TreeItem::CELL_MODE_RANGE: { c.val = p_text.to_double(); if (c.step > 0) c.val = Math::stepify(c.val, c.step); if (c.val < c.min) c.val = c.min; else if (c.val > c.max) c.val = c.max; //popup_edited_item->edited_signal.call( popup_edited_item_col ); } break; case TreeItem::CELL_MODE_RANGE_EXPRESSION: { if (evaluator) c.val = evaluator->eval(p_text); else c.val = p_text.to_double(); } break; default: { ERR_FAIL(); } } item_edited(popup_edited_item_col, popup_edited_item); update(); } void Tree::value_editor_changed(double p_value) { if (updating_value_editor) { return; } if (!popup_edited_item) { return; } TreeItem::Cell &c = popup_edited_item->cells[popup_edited_item_col]; c.val = p_value; item_edited(popup_edited_item_col, popup_edited_item); update(); } void Tree::popup_select(int p_option) { if (!popup_edited_item) return; if (popup_edited_item_col < 0 || popup_edited_item_col > columns.size()) return; popup_edited_item->cells[popup_edited_item_col].val = p_option; //popup_edited_item->edited_signal.call( popup_edited_item_col ); update(); item_edited(popup_edited_item_col, popup_edited_item); } void Tree::_input_event(InputEvent p_event) { switch (p_event.type) { case InputEvent::KEY: { if (!p_event.key.pressed) break; if (p_event.key.mod.alt || p_event.key.mod.command || (p_event.key.mod.shift && p_event.key.unicode == 0) || p_event.key.mod.meta) break; if (!root) return; if (hide_root && !root->get_next_visible()) return; switch (p_event.key.scancode) { #define EXIT_BREAK \ { \ if (!cursor_can_exit_tree) accept_event(); \ break; \ } case KEY_RIGHT: { //TreeItem *next = NULL; if (!selected_item) break; if (select_mode == SELECT_ROW) EXIT_BREAK; if (selected_col >= (columns.size() - 1)) EXIT_BREAK; if (select_mode == SELECT_MULTI) { selected_col++; emit_signal("cell_selected"); } else { selected_item->select(selected_col + 1); } update(); ensure_cursor_is_visible(); accept_event(); } break; case KEY_LEFT: { // TreeItem *next = NULL; if (!selected_item) break; if (select_mode == SELECT_ROW) EXIT_BREAK; if (selected_col <= 0) EXIT_BREAK; if (select_mode == SELECT_MULTI) { selected_col--; emit_signal("cell_selected"); } else { selected_item->select(selected_col - 1); } update(); accept_event(); } break; case KEY_DOWN: { TreeItem *next = NULL; if (!selected_item) { next = hide_root ? root->get_next_visible() : root; selected_item = 0; } else { next = selected_item->get_next_visible(); // if (diff < uint64_t(GLOBAL_DEF("gui/incr_search_max_interval_msec",2000))) { if (last_keypress != 0) { //incr search next int col; next = _search_item_text(next, incr_search, &col, true); if (!next) { accept_event(); return; } } } if (select_mode == SELECT_MULTI) { if (!next) EXIT_BREAK; selected_item = next; emit_signal("cell_selected"); update(); } else { int col = selected_col < 0 ? 0 : selected_col; while (next && !next->cells[col].selectable) next = next->get_next_visible(); if (!next) EXIT_BREAK; // do nothing.. next->select(col); } ensure_cursor_is_visible(); accept_event(); } break; case KEY_UP: { TreeItem *prev = NULL; if (!selected_item) { prev = get_last_item(); selected_col = 0; } else { prev = selected_item->get_prev_visible(); if (last_keypress != 0) { //incr search next int col; prev = _search_item_text(prev, incr_search, &col, true, true); if (!prev) { accept_event(); return; } } } if (select_mode == SELECT_MULTI) { if (!prev) break; selected_item = prev; emit_signal("cell_selected"); update(); } else { int col = selected_col < 0 ? 0 : selected_col; while (prev && !prev->cells[col].selectable) prev = prev->get_prev_visible(); if (!prev) break; // do nothing.. prev->select(col); } ensure_cursor_is_visible(); accept_event(); } break; case KEY_PAGEDOWN: { TreeItem *next = NULL; if (!selected_item) break; next = selected_item; for (int i = 0; i < 10; i++) { TreeItem *_n = next->get_next_visible(); if (_n) { next = _n; } else { break; } } if (next == selected_item) break; if (select_mode == SELECT_MULTI) { selected_item = next; emit_signal("cell_selected"); update(); } else { while (next && !next->cells[selected_col].selectable) next = next->get_next_visible(); if (!next) EXIT_BREAK; // do nothing.. next->select(selected_col); } ensure_cursor_is_visible(); } break; case KEY_PAGEUP: { TreeItem *prev = NULL; if (!selected_item) break; prev = selected_item; for (int i = 0; i < 10; i++) { TreeItem *_n = prev->get_prev_visible(); if (_n) { prev = _n; } else { break; } } if (prev == selected_item) break; if (select_mode == SELECT_MULTI) { selected_item = prev; emit_signal("cell_selected"); update(); } else { while (prev && !prev->cells[selected_col].selectable) prev = prev->get_prev_visible(); if (!prev) EXIT_BREAK; // do nothing.. prev->select(selected_col); } ensure_cursor_is_visible(); } break; case KEY_F2: case KEY_RETURN: case KEY_ENTER: { if (selected_item) { //bring up editor if possible if (!edit_selected()) { emit_signal("item_activated"); incr_search.clear(); } } accept_event(); } break; case KEY_SPACE: { if (select_mode == SELECT_MULTI) { if (!selected_item) break; if (selected_item->is_selected(selected_col)) { selected_item->deselect(selected_col); emit_signal("multi_selected", selected_item, selected_col, false); } else if (selected_item->is_selectable(selected_col)) { selected_item->select(selected_col); emit_signal("multi_selected", selected_item, selected_col, true); } } accept_event(); } break; default: { if (p_event.key.unicode > 0) { _do_incr_search(String::chr(p_event.key.unicode)); accept_event(); return; } else { if (p_event.key.scancode != KEY_SHIFT) last_keypress = 0; } } break; last_keypress = 0; } } break; case InputEvent::MOUSE_MOTION: { if (cache.font.is_null()) // avoid a strange case that may fuckup stuff update_cache(); const InputEventMouseMotion &b = p_event.mouse_motion; Ref<StyleBox> bg = cache.bg; Point2 pos = Point2(b.x, b.y) - bg->get_offset(); Cache::ClickType old_hover = cache.hover_type; int old_index = cache.hover_index; cache.hover_type = Cache::CLICK_NONE; cache.hover_index = 0; if (show_column_titles) { pos.y -= _get_title_button_height(); if (pos.y < 0) { pos.x += cache.offset.x; int len = 0; for (int i = 0; i < columns.size(); i++) { len += get_column_width(i); if (pos.x < len) { cache.hover_type = Cache::CLICK_TITLE; cache.hover_index = i; update(); break; } } } } if (drop_mode_flags && root) { Point2 mpos = Point2(b.x, b.y); mpos -= cache.bg->get_offset(); mpos.y -= _get_title_button_height(); if (mpos.y >= 0) { if (h_scroll->is_visible()) mpos.x += h_scroll->get_val(); if (v_scroll->is_visible()) mpos.y += v_scroll->get_val(); int col, h, section; TreeItem *it = _find_item_at_pos(root, mpos, col, h, section); if (it != drop_mode_over || section != drop_mode_section) { drop_mode_over = it; drop_mode_section = section; update(); } } } if (cache.hover_type != old_hover || cache.hover_index != old_index) { update(); } if (pressing_for_editor && popup_edited_item && (popup_edited_item->get_cell_mode(popup_edited_item_col) == TreeItem::CELL_MODE_RANGE || popup_edited_item->get_cell_mode(popup_edited_item_col) == TreeItem::CELL_MODE_RANGE_EXPRESSION)) { //range drag if (!range_drag_enabled) { Vector2 cpos = Vector2(b.x, b.y); if (cpos.distance_to(pressing_pos) > 2) { range_drag_enabled = true; range_drag_capture_pos = cpos; range_drag_base = popup_edited_item->get_range(popup_edited_item_col); Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED); } } else { TreeItem::Cell &c = popup_edited_item->cells[popup_edited_item_col]; float diff_y = -b.relative_y; diff_y = Math::pow(ABS(diff_y), 1.8) * SGN(diff_y); diff_y *= 0.1; range_drag_base = CLAMP(range_drag_base + c.step * diff_y, c.min, c.max); popup_edited_item->set_range(popup_edited_item_col, range_drag_base); item_edited(popup_edited_item_col, popup_edited_item); } } if (drag_touching && !drag_touching_deaccel) { drag_accum -= b.relative_y; v_scroll->set_val(drag_from + drag_accum); drag_speed = -b.speed_y; } } break; case InputEvent::MOUSE_BUTTON: { if (cache.font.is_null()) // avoid a strange case that may fuckup stuff update_cache(); const InputEventMouseButton &b = p_event.mouse_button; if (!b.pressed) { if (b.button_index == BUTTON_LEFT) { Ref<StyleBox> bg = cache.bg; Point2 pos = Point2(b.x, b.y) - bg->get_offset(); if (show_column_titles) { pos.y -= _get_title_button_height(); if (pos.y < 0) { pos.x += cache.offset.x; int len = 0; for (int i = 0; i < columns.size(); i++) { len += get_column_width(i); if (pos.x < len) { emit_signal("column_title_pressed", i); break; } } } } if (single_select_defer) { select_single_item(single_select_defer, root, single_select_defer_column); single_select_defer = NULL; } range_click_timer->stop(); if (pressing_for_editor) { if (range_drag_enabled) { range_drag_enabled = false; Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE); warp_mouse(range_drag_capture_pos); } else edit_selected(); pressing_for_editor = false; } if (cache.click_type == Cache::CLICK_BUTTON) { // make sure in case of wrong reference after reconstructing whole TreeItems cache.click_item = get_item_at_pos(cache.click_pos); emit_signal("button_pressed", cache.click_item, cache.click_column, cache.click_id); } cache.click_type = Cache::CLICK_NONE; cache.click_index = -1; cache.click_id = -1; cache.click_item = NULL; cache.click_column = 0; if (drag_touching) { if (drag_speed == 0) { drag_touching_deaccel = false; drag_touching = false; set_fixed_process(false); } else { drag_touching_deaccel = true; } } update(); } break; } if (range_drag_enabled) break; switch (b.button_index) { case BUTTON_RIGHT: case BUTTON_LEFT: { Ref<StyleBox> bg = cache.bg; Point2 pos = Point2(b.x, b.y) - bg->get_offset(); cache.click_type = Cache::CLICK_NONE; if (show_column_titles && b.button_index == BUTTON_LEFT) { pos.y -= _get_title_button_height(); if (pos.y < 0) { pos.x += cache.offset.x; int len = 0; for (int i = 0; i < columns.size(); i++) { len += get_column_width(i); if (pos.x < len) { cache.click_type = Cache::CLICK_TITLE; cache.click_index = i; //cache.click_id=; update(); break; } } break; } } if (!root || (!root->get_children() && hide_root)) { if (b.button_index == BUTTON_RIGHT && allow_rmb_select) { emit_signal("empty_tree_rmb_selected", get_local_mouse_pos()); } break; } click_handled = false; pressing_for_editor = false; blocked++; bool handled = propagate_mouse_event(pos + cache.offset, 0, 0, b.doubleclick, root, b.button_index, b.mod); blocked--; if (pressing_for_editor) { pressing_pos = Point2(b.x, b.y); } if (b.button_index == BUTTON_RIGHT) break; if (drag_touching) { set_fixed_process(false); drag_touching_deaccel = false; drag_touching = false; drag_speed = 0; drag_from = 0; } if (!click_handled) { drag_speed = 0; drag_accum = 0; // last_drag_accum=0; drag_from = v_scroll->get_val(); drag_touching = OS::get_singleton()->has_touchscreen_ui_hint(); drag_touching_deaccel = false; if (drag_touching) { set_fixed_process(true); } } } break; case BUTTON_WHEEL_UP: { v_scroll->set_val(v_scroll->get_val() - v_scroll->get_page() * b.factor / 8); } break; case BUTTON_WHEEL_DOWN: { v_scroll->set_val(v_scroll->get_val() + v_scroll->get_page() * b.factor / 8); } break; } } break; } } bool Tree::edit_selected() { TreeItem *s = get_selected(); ERR_EXPLAIN("No item selected!"); ERR_FAIL_COND_V(!s, false); ensure_cursor_is_visible(); int col = get_selected_column(); ERR_EXPLAIN("No item column selected!"); ERR_FAIL_INDEX_V(col, columns.size(), false); if (!s->cells[col].editable) return false; Rect2 rect = s->get_meta("__focus_rect"); popup_edited_item = s; popup_edited_item_col = col; TreeItem::Cell &c = s->cells[col]; if (c.mode == TreeItem::CELL_MODE_CHECK) { s->set_checked(col, !c.checked); item_edited(col, s); return true; } else if (c.mode == TreeItem::CELL_MODE_CUSTOM) { edited_item = s; edited_col = col; custom_popup_rect = Rect2i(get_global_pos() + rect.pos, rect.size); emit_signal("custom_popup_edited", false); item_edited(col, s); return true; } else if ((c.mode == TreeItem::CELL_MODE_RANGE || c.mode == TreeItem::CELL_MODE_RANGE_EXPRESSION) && c.text != "") { popup_menu->clear(); for (int i = 0; i < c.text.get_slice_count(","); i++) { String s = c.text.get_slicec(',', i); popup_menu->add_item(s, i); } popup_menu->set_size(Size2(rect.size.width, 0)); popup_menu->set_pos(get_global_pos() + rect.pos + Point2i(0, rect.size.height)); popup_menu->popup(); popup_edited_item = s; popup_edited_item_col = col; return true; } else if (c.mode == TreeItem::CELL_MODE_STRING || c.mode == TreeItem::CELL_MODE_RANGE || c.mode == TreeItem::CELL_MODE_RANGE_EXPRESSION) { Vector2 ofs(0, (text_editor->get_size().height - rect.size.height) / 2); Point2i textedpos = get_global_pos() + rect.pos - ofs; text_editor->set_pos(textedpos); text_editor->set_size(rect.size); text_editor->clear(); text_editor->set_text(c.mode == TreeItem::CELL_MODE_STRING ? c.text : String::num(c.val, Math::step_decimals(c.step))); text_editor->select_all(); if (c.mode == TreeItem::CELL_MODE_RANGE || c.mode == TreeItem::CELL_MODE_RANGE_EXPRESSION) { value_editor->set_pos(textedpos + Point2i(0, text_editor->get_size().height)); value_editor->set_size(Size2(rect.size.width, 1)); value_editor->show_modal(); updating_value_editor = true; value_editor->set_min(c.min); value_editor->set_max(c.max); value_editor->set_step(c.step); value_editor->set_val(c.val); value_editor->set_exp_unit_value(c.expr); updating_value_editor = false; } text_editor->show_modal(); text_editor->grab_focus(); return true; } return false; } Size2 Tree::get_internal_min_size() const { Size2i size = cache.bg->get_offset(); if (root) size.height += get_item_height(root); for (int i = 0; i < columns.size(); i++) { size.width += columns[i].min_width; } return size; } void Tree::update_scrollbars() { Size2 size = get_size(); int tbh; if (show_column_titles) { tbh = _get_title_button_height(); } else { tbh = 0; } Size2 hmin = h_scroll->get_combined_minimum_size(); Size2 vmin = v_scroll->get_combined_minimum_size(); v_scroll->set_begin(Point2(size.width - vmin.width, cache.bg->get_margin(MARGIN_TOP))); v_scroll->set_end(Point2(size.width, size.height - cache.bg->get_margin(MARGIN_TOP) - cache.bg->get_margin(MARGIN_BOTTOM))); h_scroll->set_begin(Point2(0, size.height - hmin.height)); h_scroll->set_end(Point2(size.width - vmin.width, size.height)); Size2 min = get_internal_min_size(); if (min.height < size.height - hmin.height) { v_scroll->hide(); cache.offset.y = 0; } else { v_scroll->show(); v_scroll->set_max(min.height); v_scroll->set_page(size.height - hmin.height - tbh); cache.offset.y = v_scroll->get_val(); } if (min.width < size.width - vmin.width) { h_scroll->hide(); cache.offset.x = 0; } else { h_scroll->show(); h_scroll->set_max(min.width); h_scroll->set_page(size.width - vmin.width); cache.offset.x = h_scroll->get_val(); } } int Tree::_get_title_button_height() const { return show_column_titles ? cache.font->get_height() + cache.title_button->get_minimum_size().height : 0; } void Tree::_notification(int p_what) { if (p_what == NOTIFICATION_FOCUS_ENTER) { focus_in_id = get_tree()->get_last_event_id(); } if (p_what == NOTIFICATION_MOUSE_EXIT) { if (cache.hover_type != Cache::CLICK_NONE) { cache.hover_type = Cache::CLICK_NONE; update(); } } if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { drag_touching = false; } if (p_what == NOTIFICATION_ENTER_TREE) { update_cache(); } if (p_what == NOTIFICATION_DRAG_END) { drop_mode_flags = 0; scrolling = false; set_fixed_process(false); update(); } if (p_what == NOTIFICATION_DRAG_BEGIN) { single_select_defer = NULL; if (cache.scroll_speed > 0 && get_rect().has_point(get_viewport()->get_mouse_pos() - get_global_pos())) { scrolling = true; set_fixed_process(true); } } if (p_what == NOTIFICATION_FIXED_PROCESS) { if (drag_touching) { if (drag_touching_deaccel) { float pos = v_scroll->get_val(); pos += drag_speed * get_fixed_process_delta_time(); bool turnoff = false; if (pos < 0) { pos = 0; turnoff = true; set_fixed_process(false); drag_touching = false; drag_touching_deaccel = false; } if (pos > (v_scroll->get_max() - v_scroll->get_page())) { pos = v_scroll->get_max() - v_scroll->get_page(); turnoff = true; } v_scroll->set_val(pos); float sgn = drag_speed < 0 ? -1 : 1; float val = Math::abs(drag_speed); val -= 1000 * get_fixed_process_delta_time(); if (val < 0) { turnoff = true; } drag_speed = sgn * val; if (turnoff) { set_fixed_process(false); drag_touching = false; drag_touching_deaccel = false; } } else { } } if (scrolling) { Point2 point = get_viewport()->get_mouse_pos() - get_global_pos(); if (point.x < cache.scroll_border) { point.x -= cache.scroll_border; } else if (point.x > get_size().width - cache.scroll_border) { point.x -= get_size().width - cache.scroll_border; } else { point.x = 0; } if (point.y < cache.scroll_border) { point.y -= cache.scroll_border; } else if (point.y > get_size().height - cache.scroll_border) { point.y -= get_size().height - cache.scroll_border; } else { point.y = 0; } point *= cache.scroll_speed * get_fixed_process_delta_time(); point += get_scroll(); h_scroll->set_val(point.x); v_scroll->set_val(point.y); } } if (p_what == NOTIFICATION_DRAW) { update_cache(); update_scrollbars(); RID ci = get_canvas_item(); VisualServer::get_singleton()->canvas_item_set_clip(ci, true); Ref<StyleBox> bg = cache.bg; Ref<StyleBox> bg_focus = get_stylebox("bg_focus"); Point2 draw_ofs; draw_ofs += bg->get_offset(); Size2 draw_size = get_size() - bg->get_minimum_size(); bg->draw(ci, Rect2(Point2(), get_size())); if (has_focus()) { VisualServer::get_singleton()->canvas_item_add_clip_ignore(ci, true); bg_focus->draw(ci, Rect2(Point2(), get_size())); VisualServer::get_singleton()->canvas_item_add_clip_ignore(ci, false); } int tbh = _get_title_button_height(); draw_ofs.y += tbh; draw_size.y -= tbh; if (root) { draw_item(Point2(), draw_ofs, draw_size, root); } int ofs = 0; // int from_y=exposed.pos.y+bg->get_margin(MARGIN_TOP); // int size_y=exposed.size.height-bg->get_minimum_size().height; for (int i = 0; i < (columns.size() - 1 - 1); i++) { ofs += get_column_width(i); //get_painter()->draw_fill_rect( Point2(ofs+cache.hseparation/2, from_y), Size2( 1, size_y ),color( COLOR_TREE_GRID) ); } if (show_column_titles) { //title butons int ofs = cache.bg->get_margin(MARGIN_LEFT); for (int i = 0; i < columns.size(); i++) { Ref<StyleBox> sb = (cache.click_type == Cache::CLICK_TITLE && cache.click_index == i) ? cache.title_button_pressed : ((cache.hover_type == Cache::CLICK_TITLE && cache.hover_index == i) ? cache.title_button_hover : cache.title_button); Ref<Font> f = cache.tb_font; Rect2 tbrect = Rect2(ofs - cache.offset.x, bg->get_margin(MARGIN_TOP), get_column_width(i), tbh); sb->draw(ci, tbrect); ofs += tbrect.size.width; //text int clip_w = tbrect.size.width - sb->get_minimum_size().width; f->draw_halign(ci, tbrect.pos + Point2i(sb->get_offset().x, (tbrect.size.height - f->get_height()) / 2 + f->get_ascent()), HALIGN_CENTER, clip_w, columns[i].title, cache.title_button_color); } } } if (p_what == NOTIFICATION_THEME_CHANGED) { update_cache(); } } Size2 Tree::get_minimum_size() const { return Size2(1, 1); } TreeItem *Tree::create_item(TreeItem *p_parent) { ERR_FAIL_COND_V(blocked > 0, NULL); TreeItem *ti = memnew(TreeItem(this)); ti->cells.resize(columns.size()); ERR_FAIL_COND_V(!ti, NULL); if (p_parent) { /* Always append at the end */ TreeItem *last = 0; TreeItem *c = p_parent->childs; while (c) { last = c; c = c->next; } if (last) { last->next = ti; } else { p_parent->childs = ti; } ti->parent = p_parent; } else { if (root) ti->childs = root; root = ti; } return ti; } TreeItem *Tree::get_root() { return root; } TreeItem *Tree::get_last_item() { TreeItem *last = root; while (last) { if (last->next) last = last->next; else if (last->childs) last = last->childs; else break; } return last; } void Tree::item_edited(int p_column, TreeItem *p_item) { edited_item = p_item; edited_col = p_column; emit_signal("item_edited"); } void Tree::item_changed(int p_column, TreeItem *p_item) { update(); } void Tree::item_selected(int p_column, TreeItem *p_item) { if (select_mode == SELECT_MULTI) { if (!p_item->cells[p_column].selectable) return; p_item->cells[p_column].selected = true; //emit_signal("multi_selected",p_item,p_column,true); - NO this is for TreeItem::select } else { select_single_item(p_item, root, p_column); } update(); } void Tree::item_deselected(int p_column, TreeItem *p_item) { if (select_mode == SELECT_MULTI || select_mode == SELECT_SINGLE) { p_item->cells[p_column].selected = false; } update(); } void Tree::set_select_mode(SelectMode p_mode) { select_mode = p_mode; } void Tree::clear() { if (blocked > 0) { ERR_FAIL_COND(blocked > 0); } if (pressing_for_editor) { if (range_drag_enabled) { range_drag_enabled = false; Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE); warp_mouse(range_drag_capture_pos); } pressing_for_editor = false; } if (root) { memdelete(root); root = NULL; }; selected_item = NULL; edited_item = NULL; popup_edited_item = NULL; update(); }; void Tree::set_hide_root(bool p_enabled) { hide_root = p_enabled; update(); } void Tree::set_column_min_width(int p_column, int p_min_width) { ERR_FAIL_INDEX(p_column, columns.size()); if (p_min_width < 1) return; columns[p_column].min_width = p_min_width; update(); } void Tree::set_column_expand(int p_column, bool p_expand) { ERR_FAIL_INDEX(p_column, columns.size()); columns[p_column].expand = p_expand; update(); } TreeItem *Tree::get_selected() const { return selected_item; } int Tree::get_selected_column() const { return selected_col; } TreeItem *Tree::get_edited() const { return edited_item; } int Tree::get_edited_column() const { return edited_col; } TreeItem *Tree::get_next_selected(TreeItem *p_item) { //if (!p_item) // return NULL; if (!root) return NULL; while (true) { if (!p_item) { p_item = root; } else { if (p_item->childs) { p_item = p_item->childs; } else if (p_item->next) { p_item = p_item->next; } else { while (!p_item->next) { p_item = p_item->parent; if (p_item == NULL) return NULL; } p_item = p_item->next; } } for (int i = 0; i < columns.size(); i++) if (p_item->cells[i].selected) return p_item; } return NULL; } int Tree::get_column_width(int p_column) const { ERR_FAIL_INDEX_V(p_column, columns.size(), -1); if (!columns[p_column].expand) return columns[p_column].min_width; Ref<StyleBox> bg = cache.bg; int expand_area = get_size().width - (bg->get_margin(MARGIN_LEFT) + bg->get_margin(MARGIN_RIGHT)); if (v_scroll->is_visible()) expand_area -= v_scroll->get_combined_minimum_size().width; int expanding_columns = 0; int expanding_total = 0; for (int i = 0; i < columns.size(); i++) { if (!columns[i].expand) { expand_area -= columns[i].min_width; } else { expanding_total += columns[i].min_width; expanding_columns++; } } if (expand_area < expanding_total) return columns[p_column].min_width; ERR_FAIL_COND_V(expanding_columns == 0, -1); // shouldnt happen return expand_area * columns[p_column].min_width / expanding_total; } void Tree::propagate_set_columns(TreeItem *p_item) { p_item->cells.resize(columns.size()); TreeItem *c = p_item->get_children(); while (c) { propagate_set_columns(c); c = c->get_next(); } } void Tree::set_columns(int p_columns) { ERR_FAIL_COND(p_columns < 1); ERR_FAIL_COND(blocked > 0); columns.resize(p_columns); if (root) propagate_set_columns(root); if (selected_col >= p_columns) selected_col = p_columns - 1; update(); } int Tree::get_columns() const { return columns.size(); } void Tree::_scroll_moved(float) { update(); } Rect2 Tree::get_custom_popup_rect() const { return custom_popup_rect; } int Tree::get_item_offset(TreeItem *p_item) const { TreeItem *it = root; int ofs = _get_title_button_height(); if (!it) return 0; while (true) { if (it == p_item) return ofs; ofs += compute_item_height(it) + cache.vseparation; if (it->childs && !it->collapsed) { it = it->childs; } else if (it->next) { it = it->next; } else { while (!it->next) { it = it->parent; if (it == NULL) return 0; } it = it->next; } } return -1; //not found } void Tree::ensure_cursor_is_visible() { if (!is_inside_tree()) return; TreeItem *selected = get_selected(); if (!selected) return; int ofs = get_item_offset(selected); if (ofs == -1) return; int h = compute_item_height(selected) + cache.vseparation; int screenh = get_size().height - h_scroll->get_combined_minimum_size().height; if (ofs + h > v_scroll->get_val() + screenh) v_scroll->call_deferred("set_val", ofs - screenh + h); else if (ofs < v_scroll->get_val()) v_scroll->set_val(ofs); } int Tree::get_pressed_button() const { return pressed_button; } Rect2 Tree::get_item_rect(TreeItem *p_item, int p_column) const { ERR_FAIL_NULL_V(p_item, Rect2()); ERR_FAIL_COND_V(p_item->tree != this, Rect2()); if (p_column != -1) { ERR_FAIL_INDEX_V(p_column, columns.size(), Rect2()); } int ofs = get_item_offset(p_item); int height = compute_item_height(p_item); Rect2 r; r.pos.y = ofs; r.size.height = height; if (p_column == -1) { r.pos.x = 0; r.size.x = get_size().width; } else { int accum = 0; for (int i = 0; i < p_column; i++) { accum += get_column_width(i); } r.pos.x = accum; r.size.x = get_column_width(p_column); } return r; } void Tree::set_column_titles_visible(bool p_show) { show_column_titles = p_show; update(); } bool Tree::are_column_titles_visible() const { return show_column_titles; } void Tree::set_column_title(int p_column, const String &p_title) { ERR_FAIL_INDEX(p_column, columns.size()); columns[p_column].title = p_title; update(); } String Tree::get_column_title(int p_column) const { ERR_FAIL_INDEX_V(p_column, columns.size(), ""); return columns[p_column].title; } Point2 Tree::get_scroll() const { Point2 ofs; if (h_scroll->is_visible()) ofs.x = h_scroll->get_val(); if (v_scroll->is_visible()) ofs.y = v_scroll->get_val(); return ofs; } TreeItem *Tree::_search_item_text(TreeItem *p_at, const String &p_find, int *r_col, bool p_selectable, bool p_backwards) { while (p_at) { for (int i = 0; i < columns.size(); i++) { if (p_at->get_text(i).findn(p_find) == 0 && (!p_selectable || p_at->is_selectable(i))) { if (r_col) *r_col = i; return p_at; } } if (p_backwards) p_at = p_at->get_prev_visible(); else p_at = p_at->get_next_visible(); } return NULL; } TreeItem *Tree::search_item_text(const String &p_find, int *r_col, bool p_selectable) { if (!root) return NULL; return _search_item_text(root, p_find, r_col, p_selectable); } void Tree::_do_incr_search(const String &p_add) { uint64_t time = OS::get_singleton()->get_ticks_usec() / 1000; // convert to msec uint64_t diff = time - last_keypress; if (diff > uint64_t(GLOBAL_DEF("gui/incr_search_max_interval_msec", 2000))) incr_search = p_add; else incr_search += p_add; last_keypress = time; int col; TreeItem *item = search_item_text(incr_search, &col, true); if (!item) return; item->select(col); ensure_cursor_is_visible(); } TreeItem *Tree::_find_item_at_pos(TreeItem *p_item, const Point2 &p_pos, int &r_column, int &h, int &section) const { Point2 pos = p_pos; if (root != p_item || !hide_root) { h = compute_item_height(p_item) + cache.vseparation; if (pos.y < h) { if (drop_mode_flags == DROP_MODE_ON_ITEM) { section = 0; } else if (drop_mode_flags == DROP_MODE_INBETWEEN) { section = pos.y < h / 2 ? -1 : 1; } else if (pos.y < h / 4) { section = -1; } else if (pos.y >= (h * 3 / 4)) { section = 1; } else { section = 0; } for (int i = 0; i < columns.size(); i++) { int w = get_column_width(i); if (pos.x < w) { r_column = i; return p_item; } pos.x -= w; } return NULL; } else { pos.y -= h; } } else { h = 0; } if (p_item->is_collapsed()) return NULL; // do not try childs, it's collapsed TreeItem *n = p_item->get_children(); while (n) { int ch; TreeItem *r = _find_item_at_pos(n, pos, r_column, ch, section); pos.y -= ch; h += ch; if (r) return r; n = n->get_next(); } return NULL; } int Tree::get_column_at_pos(const Point2 &p_pos) const { if (root) { Point2 pos = p_pos; pos -= cache.bg->get_offset(); pos.y -= _get_title_button_height(); if (pos.y < 0) return -1; if (h_scroll->is_visible()) pos.x += h_scroll->get_val(); if (v_scroll->is_visible()) pos.y += v_scroll->get_val(); int col, h, section; TreeItem *it = _find_item_at_pos(root, pos, col, h, section); if (it) { return col; } } return -1; } int Tree::get_drop_section_at_pos(const Point2 &p_pos) const { if (root) { Point2 pos = p_pos; pos -= cache.bg->get_offset(); pos.y -= _get_title_button_height(); if (pos.y < 0) return -100; if (h_scroll->is_visible()) pos.x += h_scroll->get_val(); if (v_scroll->is_visible()) pos.y += v_scroll->get_val(); int col, h, section; TreeItem *it = _find_item_at_pos(root, pos, col, h, section); if (it) { return section; } } return -100; } TreeItem *Tree::get_item_at_pos(const Point2 &p_pos) const { if (root) { Point2 pos = p_pos; pos -= cache.bg->get_offset(); pos.y -= _get_title_button_height(); if (pos.y < 0) return NULL; if (h_scroll->is_visible()) pos.x += h_scroll->get_val(); if (v_scroll->is_visible()) pos.y += v_scroll->get_val(); int col, h, section; TreeItem *it = _find_item_at_pos(root, pos, col, h, section); if (it) { return it; } } return NULL; } String Tree::get_tooltip(const Point2 &p_pos) const { if (root) { Point2 pos = p_pos; pos -= cache.bg->get_offset(); pos.y -= _get_title_button_height(); if (pos.y < 0) return Control::get_tooltip(p_pos); if (h_scroll->is_visible()) pos.x += h_scroll->get_val(); if (v_scroll->is_visible()) pos.y += v_scroll->get_val(); int col, h, section; TreeItem *it = _find_item_at_pos(root, pos, col, h, section); if (it) { TreeItem::Cell &c = it->cells[col]; int col_width = get_column_width(col); for (int j = c.buttons.size() - 1; j >= 0; j--) { Ref<Texture> b = c.buttons[j].texture; Size2 size = b->get_size() + cache.button_pressed->get_minimum_size(); if (pos.x > col_width - size.width) { String tooltip = c.buttons[j].tooltip; if (tooltip != "") { return tooltip; } } col_width -= size.width; } String ret; if (it->get_tooltip(col) == "") ret = it->get_text(col); else ret = it->get_tooltip(col); return ret; } } return Control::get_tooltip(p_pos); } void Tree::set_cursor_can_exit_tree(bool p_enable) { cursor_can_exit_tree = p_enable; } bool Tree::can_cursor_exit_tree() const { return cursor_can_exit_tree; } void Tree::set_hide_folding(bool p_hide) { hide_folding = p_hide; update(); } bool Tree::is_folding_hidden() const { return hide_folding; } void Tree::set_value_evaluator(ValueEvaluator *p_evaluator) { evaluator = p_evaluator; } void Tree::set_drop_mode_flags(int p_flags) { if (drop_mode_flags == p_flags) return; drop_mode_flags = p_flags; if (drop_mode_flags == 0) { drop_mode_over = NULL; } update(); } int Tree::get_drop_mode_flags() const { return drop_mode_flags; } void Tree::set_single_select_cell_editing_only_when_already_selected(bool p_enable) { force_select_on_already_selected = p_enable; } bool Tree::get_single_select_cell_editing_only_when_already_selected() const { return force_select_on_already_selected; } void Tree::set_allow_rmb_select(bool p_allow) { allow_rmb_select = p_allow; } bool Tree::get_allow_rmb_select() const { return allow_rmb_select; } void Tree::_bind_methods() { ObjectTypeDB::bind_method(_MD("_range_click_timeout"), &Tree::_range_click_timeout); ObjectTypeDB::bind_method(_MD("_input_event"), &Tree::_input_event); ObjectTypeDB::bind_method(_MD("_popup_select"), &Tree::popup_select); ObjectTypeDB::bind_method(_MD("_text_editor_enter"), &Tree::text_editor_enter); ObjectTypeDB::bind_method(_MD("_text_editor_modal_close"), &Tree::_text_editor_modal_close); ObjectTypeDB::bind_method(_MD("_value_editor_changed"), &Tree::value_editor_changed); ObjectTypeDB::bind_method(_MD("_scroll_moved"), &Tree::_scroll_moved); ObjectTypeDB::bind_method(_MD("clear"), &Tree::clear); ObjectTypeDB::bind_method(_MD("create_item:TreeItem", "parent:TreeItem"), &Tree::_create_item, DEFVAL(Variant())); ObjectTypeDB::bind_method(_MD("get_root:TreeItem"), &Tree::get_root); ObjectTypeDB::bind_method(_MD("set_column_min_width", "column", "min_width"), &Tree::set_column_min_width); ObjectTypeDB::bind_method(_MD("set_column_expand", "column", "expand"), &Tree::set_column_expand); ObjectTypeDB::bind_method(_MD("get_column_width", "column"), &Tree::get_column_width); ObjectTypeDB::bind_method(_MD("set_hide_root", "enable"), &Tree::set_hide_root); ObjectTypeDB::bind_method(_MD("get_next_selected:TreeItem", "from:TreeItem"), &Tree::_get_next_selected); ObjectTypeDB::bind_method(_MD("get_selected:TreeItem"), &Tree::get_selected); ObjectTypeDB::bind_method(_MD("get_selected_column"), &Tree::get_selected_column); ObjectTypeDB::bind_method(_MD("get_pressed_button"), &Tree::get_pressed_button); ObjectTypeDB::bind_method(_MD("set_select_mode", "mode"), &Tree::set_select_mode); ObjectTypeDB::bind_method(_MD("set_columns", "amount"), &Tree::set_columns); ObjectTypeDB::bind_method(_MD("get_columns"), &Tree::get_columns); ObjectTypeDB::bind_method(_MD("get_edited:TreeItem"), &Tree::get_edited); ObjectTypeDB::bind_method(_MD("get_edited_column"), &Tree::get_edited_column); ObjectTypeDB::bind_method(_MD("get_custom_popup_rect"), &Tree::get_custom_popup_rect); ObjectTypeDB::bind_method(_MD("get_item_area_rect", "item:TreeItem", "column"), &Tree::_get_item_rect, DEFVAL(-1)); ObjectTypeDB::bind_method(_MD("get_item_at_pos:TreeItem", "pos"), &Tree::get_item_at_pos); ObjectTypeDB::bind_method(_MD("get_column_at_pos", "pos"), &Tree::get_column_at_pos); ObjectTypeDB::bind_method(_MD("ensure_cursor_is_visible"), &Tree::ensure_cursor_is_visible); ObjectTypeDB::bind_method(_MD("set_column_titles_visible", "visible"), &Tree::set_column_titles_visible); ObjectTypeDB::bind_method(_MD("are_column_titles_visible"), &Tree::are_column_titles_visible); ObjectTypeDB::bind_method(_MD("set_column_title", "column", "title"), &Tree::set_column_title); ObjectTypeDB::bind_method(_MD("get_column_title", "column"), &Tree::get_column_title); ObjectTypeDB::bind_method(_MD("get_scroll"), &Tree::get_scroll); ObjectTypeDB::bind_method(_MD("set_hide_folding", "hide"), &Tree::set_hide_folding); ObjectTypeDB::bind_method(_MD("is_folding_hidden"), &Tree::is_folding_hidden); ObjectTypeDB::bind_method(_MD("set_drop_mode_flags", "flags"), &Tree::set_drop_mode_flags); ObjectTypeDB::bind_method(_MD("get_drop_mode_flags"), &Tree::get_drop_mode_flags); ObjectTypeDB::bind_method(_MD("set_allow_rmb_select", "allow"), &Tree::set_allow_rmb_select); ObjectTypeDB::bind_method(_MD("get_allow_rmb_select"), &Tree::get_allow_rmb_select); ObjectTypeDB::bind_method(_MD("set_single_select_cell_editing_only_when_already_selected", "enable"), &Tree::set_single_select_cell_editing_only_when_already_selected); ObjectTypeDB::bind_method(_MD("get_single_select_cell_editing_only_when_already_selected"), &Tree::get_single_select_cell_editing_only_when_already_selected); ADD_SIGNAL(MethodInfo("item_selected")); ADD_SIGNAL(MethodInfo("cell_selected")); ADD_SIGNAL(MethodInfo("multi_selected", PropertyInfo(Variant::OBJECT, "item"), PropertyInfo(Variant::INT, "column"), PropertyInfo(Variant::BOOL, "selected"))); ADD_SIGNAL(MethodInfo("item_rmb_selected", PropertyInfo(Variant::VECTOR2, "pos"))); ADD_SIGNAL(MethodInfo("empty_tree_rmb_selected", PropertyInfo(Variant::VECTOR2, "pos"))); ADD_SIGNAL(MethodInfo("item_edited")); ADD_SIGNAL(MethodInfo("item_collapsed", PropertyInfo(Variant::OBJECT, "item"))); //ADD_SIGNAL( MethodInfo("item_doubleclicked" ) ); ADD_SIGNAL(MethodInfo("button_pressed", PropertyInfo(Variant::OBJECT, "item"), PropertyInfo(Variant::INT, "column"), PropertyInfo(Variant::INT, "id"))); ADD_SIGNAL(MethodInfo("custom_popup_edited", PropertyInfo(Variant::BOOL, "arrow_clicked"))); ADD_SIGNAL(MethodInfo("item_activated")); ADD_SIGNAL(MethodInfo("column_title_pressed", PropertyInfo(Variant::INT, "column"))); BIND_CONSTANT(SELECT_SINGLE); BIND_CONSTANT(SELECT_ROW); BIND_CONSTANT(SELECT_MULTI); BIND_CONSTANT(DROP_MODE_DISABLED); BIND_CONSTANT(DROP_MODE_ON_ITEM); BIND_CONSTANT(DROP_MODE_INBETWEEN); } Tree::Tree() { selected_col = 0; columns.resize(1); selected_item = NULL; edited_item = NULL; selected_col = -1; edited_col = -1; hide_root = false; select_mode = SELECT_SINGLE; root = 0; popup_menu = NULL; popup_edited_item = NULL; text_editor = NULL; set_focus_mode(FOCUS_ALL); popup_menu = memnew(PopupMenu); popup_menu->hide(); add_child(popup_menu); popup_menu->set_as_toplevel(true); text_editor = memnew(LineEdit); add_child(text_editor); text_editor->set_as_toplevel(true); text_editor->hide(); value_editor = memnew(HSlider); add_child(value_editor); value_editor->set_as_toplevel(true); value_editor->hide(); h_scroll = memnew(HScrollBar); v_scroll = memnew(VScrollBar); add_child(h_scroll); add_child(v_scroll); range_click_timer = memnew(Timer); range_click_timer->connect("timeout", this, "_range_click_timeout"); add_child(range_click_timer); h_scroll->connect("value_changed", this, "_scroll_moved"); v_scroll->connect("value_changed", this, "_scroll_moved"); text_editor->connect("text_entered", this, "_text_editor_enter"); text_editor->connect("modal_close", this, "_text_editor_modal_close"); popup_menu->connect("item_pressed", this, "_popup_select"); value_editor->connect("value_changed", this, "_value_editor_changed"); value_editor->set_as_toplevel(true); text_editor->set_as_toplevel(true); updating_value_editor = false; pressed_button = -1; show_column_titles = false; cache.click_type = Cache::CLICK_NONE; cache.hover_type = Cache::CLICK_NONE; cache.hover_index = -1; cache.click_index = -1; cache.click_id = -1; cache.click_item = NULL; cache.click_column = 0; last_keypress = 0; focus_in_id = 0; blocked = 0; cursor_can_exit_tree = true; set_stop_mouse(true); drag_speed = 0; drag_touching = false; drag_touching_deaccel = false; pressing_for_editor = false; range_drag_enabled = false; hide_folding = false; evaluator = NULL; drop_mode_flags = 0; drop_mode_over = NULL; drop_mode_section = 0; single_select_defer = NULL; force_select_on_already_selected = false; allow_rmb_select = false; } Tree::~Tree() { if (root) { memdelete(root); } }
1
0.969154
1
0.969154
game-dev
MEDIA
0.494532
game-dev
0.985474
1
0.985474
gold-meridian/daybreak-mod
2,560
src/LiquidSlopesPatch/Common/ModCompat/SpookyMod.cs
using System.Reflection; using MonoMod.Cil; using Spooky.Content.Biomes; using Spooky.Content.Tiles.Water; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace LiquidSlopesPatch.Common.ModCompat; [ExtendsFromMod("Spooky")] internal sealed class SpookyMod : ModSystem { public override void Load() { base.Load(); var tpb = typeof(TarPitsBiome); MonoModHooks.Add(tpb.GetMethod(nameof(TarPitsBiome.WaterOpacityChanger), BindingFlags.NonPublic | BindingFlags.Instance), WaterOpacityChanger_FixStructTypes); } private static void WaterOpacityChanger_FixStructTypes(TarPitsBiome self, ILContext il) { ILCursor c = new(il); c.GotoNext(MoveType.After, i => i.MatchMul(), i => i.MatchStloc(7)); //match to saving of num at the line float num = ptr2->Opacity * (isBackgroundDraw ? 1f : DEFAULT_OPACITY[ptr2->Type]); c.EmitLdloca(7); //parse through num with a reference through the delegate //Ldloc2 or ptr2 is a pointer, (pointers are just accesses to fields through memory) which means that we can't parse them through a delegate by themselves //Here we parse through the pointer (ptr2) value for Type and Opacity since thats the only LiquidDrawCache values we use c.EmitLdloc2(); c.EmitLdfld(typeof(RewrittenLiquidRenderer.LiquidDrawCache).GetField("Opacity")); //we get ptr2.Opacity by parsing throgh both ptr2 and the Opacity field c.EmitLdloc2(); c.EmitLdfld(typeof(RewrittenLiquidRenderer.LiquidDrawCache).GetField("Type")); //we get ptr2.Opacity by parsing throgh both ptr2 and the Type field c.EmitLdarg(5); c.EmitDelegate((ref float num, float ptr2Opacity, byte ptr2Type, bool isBackgroundDraw) => { //Anything placed in this delegate is like calling a new method float LiquidOpacity = self.WaterOpacity; //ranges from 1f to 0f bool opacityCondition = ptr2Type == LiquidID.Water && Main.waterStyle == ModContent.GetInstance<TarWaterStyle>().Slot; //the condition for when our opacity should be applied //This gets the liquid type water and gets the water style for our liquid, this can be changed to anything boolean related //We set num (or the opacity of the draw liquid) to either the original value or our value depending on the condition above num = opacityCondition ? ptr2Opacity * (isBackgroundDraw ? 1f : LiquidOpacity) : num; } ); } }
1
0.855763
1
0.855763
game-dev
MEDIA
0.935611
game-dev
0.926059
1
0.926059
sun8829/OdyAndroidStore
4,373
app/src/main/java/com/huaye/odyandroidstore/utils/StringUtils.java
package com.huaye.odyandroidstore.utils; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2016/8/16 * desc : 字符串相关工具类 * </pre> */ public class StringUtils { private StringUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * 判断字符串是否为null或长度为0 * * @param s 待校验字符串 * @return {@code true}: 空<br> {@code false}: 不为空 */ public static boolean isEmpty(CharSequence s) { return s == null || s.length() == 0; } /** * 判断字符串是否为null或全为空格 * * @param s 待校验字符串 * @return {@code true}: null或全空格<br> {@code false}: 不为null且不全空格 */ public static boolean isSpace(String s) { return (s == null || s.trim().length() == 0); } /** * 判断两字符串是否相等 * * @param a 待校验字符串a * @param b 待校验字符串b * @return {@code true}: 相等<br>{@code false}: 不相等 */ public static boolean equals(CharSequence a, CharSequence b) { if (a == b) return true; int length; if (a != null && b != null && (length = a.length()) == b.length()) { if (a instanceof String && b instanceof String) { return a.equals(b); } else { for (int i = 0; i < length; i++) { if (a.charAt(i) != b.charAt(i)) return false; } return true; } } return false; } /** * 判断两字符串忽略大小写是否相等 * * @param a 待校验字符串a * @param b 待校验字符串b * @return {@code true}: 相等<br>{@code false}: 不相等 */ public static boolean equalsIgnoreCase(String a, String b) { return (a == b) || (b != null) && (a.length() == b.length()) && a.regionMatches(true, 0, b, 0, b.length()); } /** * null转为长度为0的字符串 * * @param s 待转字符串 * @return s为null转为长度为0字符串,否则不改变 */ public static String null2Length0(String s) { return s == null ? "" : s; } /** * 返回字符串长度 * * @param s 字符串 * @return null返回0,其他返回自身长度 */ public static int length(CharSequence s) { return s == null ? 0 : s.length(); } /** * 首字母大写 * * @param s 待转字符串 * @return 首字母大写字符串 */ public static String upperFirstLetter(String s) { if (isEmpty(s) || !Character.isLowerCase(s.charAt(0))) return s; return String.valueOf((char) (s.charAt(0) - 32)) + s.substring(1); } /** * 首字母小写 * * @param s 待转字符串 * @return 首字母小写字符串 */ public static String lowerFirstLetter(String s) { if (isEmpty(s) || !Character.isUpperCase(s.charAt(0))) return s; return String.valueOf((char) (s.charAt(0) + 32)) + s.substring(1); } /** * 反转字符串 * * @param s 待反转字符串 * @return 反转字符串 */ public static String reverse(String s) { int len = length(s); if (len <= 1) return s; int mid = len >> 1; char[] chars = s.toCharArray(); char c; for (int i = 0; i < mid; ++i) { c = chars[i]; chars[i] = chars[len - i - 1]; chars[len - i - 1] = c; } return new String(chars); } /** * 转化为半角字符 * * @param s 待转字符串 * @return 半角字符串 */ public static String toDBC(String s) { if (isEmpty(s)) return s; char[] chars = s.toCharArray(); for (int i = 0, len = chars.length; i < len; i++) { if (chars[i] == 12288) { chars[i] = ' '; } else if (65281 <= chars[i] && chars[i] <= 65374) { chars[i] = (char) (chars[i] - 65248); } else { chars[i] = chars[i]; } } return new String(chars); } /** * 转化为全角字符 * * @param s 待转字符串 * @return 全角字符串 */ public static String toSBC(String s) { if (isEmpty(s)) return s; char[] chars = s.toCharArray(); for (int i = 0, len = chars.length; i < len; i++) { if (chars[i] == ' ') { chars[i] = (char) 12288; } else if (33 <= chars[i] && chars[i] <= 126) { chars[i] = (char) (chars[i] + 65248); } else { chars[i] = chars[i]; } } return new String(chars); } }
1
0.915201
1
0.915201
game-dev
MEDIA
0.226048
game-dev
0.911606
1
0.911606
pablushaa/AllahClientRecode
2,207
net/minecraft/world/chunk/storage/AnvilSaveHandler.java
package net.minecraft.world.chunk.storage; import java.io.File; import javax.annotation.Nullable; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.datafix.DataFixer; import net.minecraft.world.WorldProvider; import net.minecraft.world.WorldProviderEnd; import net.minecraft.world.WorldProviderHell; import net.minecraft.world.storage.SaveHandler; import net.minecraft.world.storage.ThreadedFileIOBase; import net.minecraft.world.storage.WorldInfo; public class AnvilSaveHandler extends SaveHandler { public AnvilSaveHandler(File p_i46650_1_, String p_i46650_2_, boolean p_i46650_3_, DataFixer dataFixerIn) { super(p_i46650_1_, p_i46650_2_, p_i46650_3_, dataFixerIn); } /** * initializes and returns the chunk loader for the specified world provider */ public IChunkLoader getChunkLoader(WorldProvider provider) { File file1 = this.getWorldDirectory(); if (provider instanceof WorldProviderHell) { File file3 = new File(file1, "DIM-1"); file3.mkdirs(); return new AnvilChunkLoader(file3, this.dataFixer); } else if (provider instanceof WorldProviderEnd) { File file2 = new File(file1, "DIM1"); file2.mkdirs(); return new AnvilChunkLoader(file2, this.dataFixer); } else { return new AnvilChunkLoader(file1, this.dataFixer); } } /** * Saves the given World Info with the given NBTTagCompound as the Player. */ public void saveWorldInfoWithPlayer(WorldInfo worldInformation, @Nullable NBTTagCompound tagCompound) { worldInformation.setSaveVersion(19133); super.saveWorldInfoWithPlayer(worldInformation, tagCompound); } /** * Called to flush all changes to disk, waiting for them to complete. */ public void flush() { try { ThreadedFileIOBase.getThreadedIOInstance().waitForFinish(); } catch (InterruptedException interruptedexception) { interruptedexception.printStackTrace(); } RegionFileCache.clearRegionFileReferences(); } }
1
0.917179
1
0.917179
game-dev
MEDIA
0.970556
game-dev
0.874139
1
0.874139
Refactorio/RedMew
21,300
map_gen/maps/diggy/feature/diggy_cave_collapse.lua
--[[-- info Provides the ability to collapse caves when digging. ]] -- dependencies local Event = require 'utils.event' local Template = require 'map_gen.maps.diggy.template' local ScoreTracker = require 'utils.score_tracker' local Debug = require 'map_gen.maps.diggy.debug' local Task = require 'utils.task' local Token = require 'utils.token' local Game = require 'utils.game' local Global = require 'utils.global' local CreateParticles = require 'features.create_particles' local RS = require 'map_gen.shared.redmew_surface' local Popup = require 'features.gui.popup' local table = require 'utils.table' local random = math.random local floor = math.floor local pairs = pairs local pcall = pcall local is_diggy_rock = Template.is_diggy_rock local template_insert = Template.insert local raise_event = script.raise_event local set_timeout = Task.set_timeout local set_timeout_in_ticks = Task.set_timeout_in_ticks local ceiling_crumble = CreateParticles.ceiling_crumble local clear_table = table.clear_table local collapse_rocks = Template.diggy_rocks local collapse_rocks_size = #collapse_rocks local cave_collapses_name = 'cave-collapses' -- this local DiggyCaveCollapse = {} local config local n = 9 local radius = 0 local radius_sq = 0 local center_radius_sq = 0 local disc_radius_sq = 0 local center_weight local disc_weight local ring_weight local disc_blur_sum = 0 local center_value = 0 local disc_value = 0 local ring_value = 0 local enable_stress_grid = 0 local stress_map_add local mask_disc_blur local mask_init local stress_map_check_stress_in_threshold local support_beam_entities local on_surface_created local stress_threshold_causing_collapse = 3.57 local near_stress_threshold_causing_collapse = 3.3 -- just above the threshold of a normal 4 pillar grid local show_deconstruction_alert_message = {} local stress_map_storage = {} local new_tile_map = {} local collapse_positions_storage = {} Global.register( { new_tile_map = new_tile_map, stress_map_storage = stress_map_storage, deconstruction_alert_message_shown = show_deconstruction_alert_message, collapse_positions_storage = collapse_positions_storage }, function(tbl) new_tile_map = tbl.new_tile_map stress_map_storage = tbl.stress_map_storage show_deconstruction_alert_message = tbl.deconstruction_alert_message_shown collapse_positions_storage = tbl.collapse_positions_storage end ) local defaultValue = 0 local collapse_alert = {type = 'item', name = 'stone'} DiggyCaveCollapse.events = { --[[-- When stress at certain position is above the collapse threshold - position LuaPosition - surface LuaSurface - player_index Number (index of player that caused the collapse) ]] on_collapse_triggered = Event.generate_event_name('on_collapse_triggered'), --[[-- After a collapse - position LuaPosition - surface LuaSurface - player_index Number (index of player that caused the collapse) ]] on_collapse = Event.generate_event_name('on_collapse') } local function create_collapse_template(positions, surface) local entities = {} local entity_count = 0 local find_entities_filtered = surface.find_entities_filtered for _, position in pairs(positions) do local x = position.x local y = position.y local do_insert = true for _, entity in pairs(find_entities_filtered({area = {position, {x + 1, y + 1}}})) do pcall( function() local strength = support_beam_entities[entity.name] if strength then do_insert = false else if entity.name ~= 'tank' then entity.die() else entity.health = entity.health - 100 if entity.health == 0 then entity.die() end end end end ) end if do_insert then entity_count = entity_count + 1 entities[entity_count] = {position = position, name = collapse_rocks[random(collapse_rocks_size)]} end end return entities end local function create_collapse_alert(surface, position) local target = surface.create_entity({position = position, name = 'big-rock'}) for _, player in pairs(game.connected_players) do player.add_custom_alert(target, collapse_alert, {'diggy.cave_collapse'}, true) end target.destroy() end local function collapse(args) local position = args.position local surface = args.surface local positions = {} local count = 0 local strength = config.collapse_threshold_total_strength mask_disc_blur( position.x, position.y, strength, function(x, y, value) stress_map_check_stress_in_threshold( surface, x, y, value, function(_, c_x, c_y) count = count + 1 positions[count] = {x = c_x, y = c_y} end ) end ) if #positions == 0 then return end create_collapse_alert(surface, position) template_insert(surface, {}, {{ name = 'big-explosion', position = position }}) template_insert(surface, {}, create_collapse_template(positions, surface)) raise_event(DiggyCaveCollapse.events.on_collapse, args) ScoreTracker.change_for_global(cave_collapses_name, 1) end local on_collapse_timeout_finished = Token.register(collapse) local on_near_threshold = Token.register( function(params) ceiling_crumble(params.surface, params.position) end ) local function spawn_collapse_text(surface, position) local color = { r = 1, g = random(1, 100) * 0.01, b = 0 } Game.create_local_flying_text({ surface = surface, color = color, text = config.cracking_sounds[random(#config.cracking_sounds)], position = position, }) end local function on_collapse_triggered(event) local surface = event.surface local position = event.position local x = position.x local y = position.y local x_t = new_tile_map[x] if x_t and x_t[y] then template_insert(surface, {}, {{position = position, name = 'big-rock'}}) return end spawn_collapse_text(surface, position) set_timeout(config.collapse_delay, on_collapse_timeout_finished, event) end local function on_built_tile(surface, new_tile, tiles) local new_tile_strength = support_beam_entities[new_tile.name] for _, tile in pairs(tiles) do if new_tile_strength then stress_map_add(surface, tile.position, -1 * new_tile_strength, true) end local old_tile_strength = support_beam_entities[tile.old_tile.name] if (old_tile_strength) then stress_map_add(surface, tile.position, old_tile_strength, true) end end end --It is impossible to track which player marked the tile for deconstruction local function on_robot_mined_tile(event) local surface for _, tile in pairs(event.tiles) do local strength = support_beam_entities[tile.old_tile.name] if strength then surface = surface or event.robot.surface stress_map_add(surface, tile.position, strength, true) end end end local function on_player_mined_tile(event) local surface = game.surfaces[event.surface_index] for _, tile in pairs(event.tiles) do local strength = support_beam_entities[tile.old_tile.name] if strength then stress_map_add(surface, tile.position, strength, true, event.player_index) end end end local function on_mined_entity(event) local entity = event.entity local name = entity.name local strength = support_beam_entities[name] if strength then local player_index if not is_diggy_rock(name) then player_index = event.player_index end stress_map_add(entity.surface, entity.position, strength, false, player_index) end end local function on_entity_died(event) local entity = event.entity local name = entity.name local strength = support_beam_entities[name] if strength then local player_index if not is_diggy_rock(name) then local cause = event.cause player_index = cause and cause.type == 'character' and cause.player and cause.player.index or nil end stress_map_add(entity.surface, entity.position, strength, false, player_index) end end local function script_raised_destroy(event) local cause = event.cause if cause and not (cause == "room_clearing" or cause == "die_faster" or cause == "alien_emerges") then return end local entity = event.entity local name = entity.name local strength = support_beam_entities[name] if strength then stress_map_add(entity.surface, entity.position, strength, false) end end local function on_built_entity(event) local entity = event.entity local strength = support_beam_entities[entity.name] if strength then stress_map_add(entity.surface, entity.position, -1 * strength) end end local function on_placed_entity(event) local strength = support_beam_entities[event.entity.name] if strength then stress_map_add(event.entity.surface, event.entity.position, -1 * strength) end end local on_new_tile_timeout_finished = Token.register( function(args) local x_t = new_tile_map[args.x] if x_t then x_t[args.y] = nil --reset new tile status. This tile can cause a chain collapse now end end ) local function on_void_removed(event) local strength = support_beam_entities['out-of-map'] local position = event.position if strength then stress_map_add(event.surface, position, strength) end local x = position.x local y = position.y --To avoid room collapse: local x_t = new_tile_map[x] if x_t then x_t[y] = true else x_t = { [y] = true } new_tile_map[x] = x_t end set_timeout(3, on_new_tile_timeout_finished, {x = x, y = y}) end --[[-- Registers all event handlers.] @param global_config Table {@see Diggy.Config}. ]] --Special thanks to justarandomgeek from the main factorio discord guild for helping to teach orange how image classes work. function DiggyCaveCollapse.register(cfg) ScoreTracker.register(cave_collapses_name, {'diggy.score_cave_collapses'}, '[img=entity.small-remnants]') local global_to_show = storage.config.score.global_to_show global_to_show[#global_to_show + 1] = cave_collapses_name config = cfg support_beam_entities = config.support_beam_entities if support_beam_entities['stone-path'] then support_beam_entities['stone-brick'] = support_beam_entities['stone-path'] else support_beam_entities['stone-brick'] = nil end if support_beam_entities['hazard-concrete'] then support_beam_entities['hazard-concrete-left'] = support_beam_entities['hazard-concrete'] support_beam_entities['hazard-concrete-right'] = support_beam_entities['hazard-concrete'] else support_beam_entities['hazard-concrete-left'] = nil support_beam_entities['hazard-concrete-right'] = nil end if support_beam_entities['refined-hazard-concrete'] then support_beam_entities['refined-hazard-concrete-left'] = support_beam_entities['refined-hazard-concrete'] support_beam_entities['refined-hazard-concrete-right'] = support_beam_entities['refined-hazard-concrete'] else support_beam_entities['refined-hazard-concrete-left'] = nil support_beam_entities['refined-hazard-concrete-right'] = nil end Event.add(DiggyCaveCollapse.events.on_collapse_triggered, on_collapse_triggered) Event.add(defines.events.on_robot_built_entity, on_built_entity) Event.add( defines.events.on_robot_built_tile, function(event) on_built_tile(event.robot.surface, event.item, event.tiles) end ) Event.add( defines.events.on_player_built_tile, function(event) on_built_tile(game.surfaces[event.surface_index], event.tile, event.tiles) end ) Event.add(defines.events.on_robot_mined_tile, on_robot_mined_tile) Event.add(defines.events.on_player_mined_tile, on_player_mined_tile) Event.add(defines.events.on_built_entity, on_built_entity) Event.add(Template.events.on_placed_entity, on_placed_entity) Event.add(defines.events.on_entity_died, on_entity_died) Event.add(defines.events.script_raised_destroy, script_raised_destroy) Event.add(defines.events.on_player_mined_entity, on_mined_entity) Event.add(Template.events.on_void_removed, on_void_removed) Event.add(defines.events.on_surface_created, on_surface_created) Event.add( defines.events.on_marked_for_deconstruction, function(event) local entity = event.entity local name = entity.name if is_diggy_rock(name) then return end if name == 'deconstructible-tile-proxy' or nil ~= support_beam_entities[name] then entity.cancel_deconstruction(game.get_player(event.player_index).force) end end ) Event.add( defines.events.on_player_created, function(event) show_deconstruction_alert_message[event.player_index] = true end ) Event.add( defines.events.on_pre_player_mined_item, function(event) local player_index = event.player_index if not show_deconstruction_alert_message[player_index] then return end if (nil ~= support_beam_entities[event.entity.name]) then Popup.player( game.get_player(player_index), {'diggy.cave_collapse_warning'} ) show_deconstruction_alert_message[player_index] = nil end end ) enable_stress_grid = config.enable_stress_grid on_surface_created({surface_index = 1}) mask_init(config) if (config.enable_mask_debug) then local surface = RS.get_surface() mask_disc_blur( 0, 0, 10, function(x, y, fraction) Debug.print_grid_value(fraction, surface, {x = x, y = y}) end ) end end -- --STRESS MAP -- --[[-- Adds a fraction to a given location on the stress_map. Returns the new fraction value of that position. @param stress_map Table of {x,y} @param position Table with x and y @param number fraction @return number sum of old fraction + new fraction ]] ---Adds a fraction to a given location on the stress_map. Returns the new fraction value of that position. ---@param stress_map table ---@param x number ---@param y number ---@param fraction number ---@param player_index number ---@param surface LuaSurface local function add_fraction(stress_map, x, y, fraction, player_index, surface) x = 2 * floor(x * 0.5) y = 2 * floor(y * 0.5) local x_t = stress_map[x] if not x_t then x_t = {} stress_map[x] = x_t end local value = x_t[y] if not value then value = defaultValue end value = value + fraction x_t[y] = value if fraction > 0 then if value > stress_threshold_causing_collapse then raise_event( DiggyCaveCollapse.events.on_collapse_triggered, { surface = surface, position = {x = x, y = y}, player_index = player_index } ) elseif value > near_stress_threshold_causing_collapse then set_timeout_in_ticks(2, on_near_threshold, {surface = surface, position = {x = x, y = y}}) end end if enable_stress_grid then Debug.print_colored_grid_value(value, surface, {x = x, y = y}, 0.5, false, value / stress_threshold_causing_collapse, {r = 0, g = 1, b = 0}, {r = 1, g = -1, b = 0}, {r = 0, g = 1, b = 0}, {r = 1, g = 1, b = 1}) end return value end on_surface_created = function(event) local index = event.surface_index if stress_map_storage[index] then clear_table(stress_map_storage[index]) else stress_map_storage[index] = {} end local map = stress_map_storage[index] map['surface_index'] = index map[1] = {index = 1} map[2] = {index = 2} map[3] = {index = 3} map[4] = {index = 4} end ---Checks whether a tile's pressure is within a given threshold and calls the handler if not. ---@param surface LuaSurface ---@param x number ---@param y number ---@param threshold number ---@param callback function stress_map_check_stress_in_threshold = function(surface, x, y, threshold, callback) local stress_map = stress_map_storage[surface.index] local value = add_fraction(stress_map, x, y, 0, nil, surface) if (value >= stress_threshold_causing_collapse - threshold) then callback(surface, x, y) end end stress_map_add = function(surface, position, factor, no_blur, player_index) local x_start = floor(position.x) local y_start = floor(position.y) local stress_map = stress_map_storage[surface.index] if not stress_map then return end if no_blur then add_fraction(stress_map, x_start, y_start, factor, player_index, surface) return end for x = -radius, radius do for y = -radius, radius do local value = 0 local distance_sq = x * x + y * y if distance_sq <= center_radius_sq then value = center_value elseif distance_sq <= disc_radius_sq then value = disc_value elseif distance_sq <= radius_sq then value = ring_value end if value > 0.001 or value < -0.001 then add_fraction(stress_map, x + x_start, y + y_start, value * factor, player_index, surface) end end end end DiggyCaveCollapse.stress_map_add = stress_map_add -- -- MASK -- mask_init = function(config) -- luacheck: ignore 431 (intentional upvalue shadow) n = config.mask_size local ring_weights = config.mask_relative_ring_weights ring_weight = ring_weights[1] disc_weight = ring_weights[2] center_weight = ring_weights[3] radius = floor(n * 0.5) radius_sq = (radius + 0.2) * (radius + 0.2) center_radius_sq = radius_sq / 9 disc_radius_sq = radius_sq * 4 / 9 for x = -radius, radius do for y = -radius, radius do local distance_sq = x * x + y * y if distance_sq <= center_radius_sq then disc_blur_sum = disc_blur_sum + center_weight elseif distance_sq <= disc_radius_sq then disc_blur_sum = disc_blur_sum + disc_weight elseif distance_sq <= radius_sq then disc_blur_sum = disc_blur_sum + ring_weight end end end center_value = center_weight / disc_blur_sum disc_value = disc_weight / disc_blur_sum ring_value = ring_weight / disc_blur_sum end --[[-- Applies a blur Applies the disc in 3 discs: center, (middle) disc and (outer) ring. The relative weights for tiles in a disc are: center: 3/3 disc: 2/3 ring: 1/3 The sum of all values is 1 @param x_start number center point @param y_start number center point @param factor the factor to multiply the cell value with (value = cell_value * factor) @param callback function to execute on each tile within the mask callback(x, y, value) ]] mask_disc_blur = function(x_start, y_start, factor, callback) x_start = floor(x_start) y_start = floor(y_start) for x = -radius, radius do for y = -radius, radius do local value = 0 local distance_sq = x * x + y * y if distance_sq <= center_radius_sq then value = center_value elseif distance_sq <= disc_radius_sq then value = disc_value elseif distance_sq <= radius_sq then value = ring_value end if value > 0.001 or value < -0.001 then callback(x_start + x, y_start + y, value * factor) end end end end function DiggyCaveCollapse.get_extra_map_info() return [[Cave Collapse, it might just collapse! Place stone walls, stone paths and (refined) concrete to reinforce the mine. If you see cracks appear, run!]] end Event.on_init( function() if storage.config.redmew_surface.enabled then on_surface_created({surface_index = RS.get_surface().index}) end end ) return DiggyCaveCollapse
1
0.896516
1
0.896516
game-dev
MEDIA
0.997565
game-dev
0.980334
1
0.980334
magefree/mage
1,574
Mage.Sets/src/mage/cards/p/PixieQueen.java
package mage.cards.p; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.continuous.GainAbilityTargetEffect; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Duration; import mage.constants.Zone; import mage.target.common.TargetCreaturePermanent; /** * * @author hanasu */ public final class PixieQueen extends CardImpl { public PixieQueen(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{2}{G}{G}"); this.subtype.add(SubType.FAERIE); this.power = new MageInt(1); this.toughness = new MageInt(1); // Flying this.addAbility(FlyingAbility.getInstance()); // {G}{G}{G}, {tap}: Target creature gains flying until end of turn. Ability ability = new SimpleActivatedAbility(new GainAbilityTargetEffect(FlyingAbility.getInstance(), Duration.EndOfTurn), new ManaCostsImpl<>("{G}{G}{G}")); ability.addTarget(new TargetCreaturePermanent()); ability.addCost(new TapSourceCost()); this.addAbility(ability); } private PixieQueen(final PixieQueen card) { super(card); } @Override public PixieQueen copy() { return new PixieQueen(this); } }
1
0.895709
1
0.895709
game-dev
MEDIA
0.972711
game-dev
0.975494
1
0.975494
glKarin/com.n0n3m4.diii4a
9,143
Q3E/src/main/jni/darkmod/game/SndProp.h
/***************************************************************************** The Dark Mod GPL Source Code This file is part of the The Dark Mod Source Code, originally based on the Doom 3 GPL Source Code as published in 2011. The Dark Mod Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For details, see LICENSE.TXT. Project: The Dark Mod (http://www.thedarkmod.com/) ******************************************************************************/ /******************************************************************************/ /* */ /* Dark Mod Sound Propagation (C) by Chris Sarantos in USA 2005 */ /* All rights reserved */ /* */ /******************************************************************************/ /****************************************************************************** * * DESCRIPTION: Sound propagation class for propagating suspicious sounds to AI * during gameplay. Friend class to CsndPropLoader. * *****************************************************************************/ #ifndef SNDPROP_H #define SNDPROP_H #include "SndPropLoader.h" /****************************************************************************** * * DESCRIPTION: Sound propagation class for propagating suspicious sounds to AI * during gameplay. Friend class to CsndPropLoader. * *****************************************************************************/ template <class type> class CMatRUT; /** * Team bitmask definition, for comparing team alert flags * with team status of an entity **/ typedef struct STeamBits_s { unsigned int friendly : 1; unsigned int neutral : 1; unsigned int enemy : 1; unsigned int same : 1; } STeamBits; typedef union UTeamMask_s { unsigned int m_field; STeamBits m_bits; } UTeamMask; /** * Array entry in populated areas array **/ typedef struct SPopArea_s { int addedTime; // timestamp at which this entry was added from the AI list bool bVisited; // area was visited at least once in wavefront expansion idList< idEntityPtr<idAI> > AIContents; // list of AI that are present in area //TODO: Handle Listeners in another list here idList<int> VisitedPorts; // portals that the sound flooded in on (reduces comp. time to store this) } SPopArea; /** * Portal data stored in an event area **/ typedef struct SPortEvent_s { float Loss; // dynamic array to store the current loss at the portal float Dist; // distance at portal (used to add AI loss to existing loss) float Att; // attenuation at portal (again used for final AI calculation) int Floods; // How many floods did it take to get to that particular portal SsndPortal *ThisPort; // pointer to the snd portal object for this portal SPortEvent_s *PrevPort; // the portal visited immediately before each portal } SPortEvent; /** * Array entry in event areas array (storing visited areas information) **/ typedef struct SEventArea_s { bool bVisited; // area was visited at least once in wavefront expansion SPortEvent *PortalDat; // Array of event data for each portal in the area } SEventArea; /** * Expansion queue entry for the wavefront expansion algorithm **/ typedef struct SExpQue_s { int area; // area number int portalH; // portal handle of the portal flooded in on float curDist; // total distance travelled by wave so far float curAtt; // total attenuation due to material losses so far float curLoss; // total loss so far SPortEvent *PrevPort; // previous portal flooded through along path } SExpQue; class CsndProp : public CsndPropBase { public: CsndProp( void ); ~CsndProp( void ); void Clear( void ); void Save(idSaveGame *savefile) const; void Restore(idRestoreGame *savefile); void Propagate( float volMod, float durMod, const idStr& soundName, idVec3 origin, idEntity *maker, USprFlags *addFlags = NULL, int msgTag = 0 ); // grayman #3355 /** * Get the appropriate vars from the sndPropLoader after * it has loaded data for the map. * * Also looks up door entity pointers for current map and * puts them into area/portal tree * * Also initializes various members **/ void SetupFromLoader( const CsndPropLoader *in ); /** * Check if a sound is defined in the soundprop def file **/ bool CheckSound( const char *sndNameGlobal, bool isEnv ); /** * Insert the loss argument into the portal data array entry for * the given portal handle. * * This one calls the base class function, plus updates the portal losses timestamp * grayman #3042 - split into AI- and Player-specific loss **/ void SetPortalAILoss( int handle, float value ); void SetPortalPlayerLoss( int handle, float value ); /** * Static var for AI checking the default threshold **/ static float s_SPROP_DEFAULT_TRESHOLD; protected: /** * Wavefront expansion algorithm, starts with volume volInit at point origin * * Returns true if the expansion died out naturally rather than being stopped * by a computation limit. **/ bool ExpandWave(float volInit, idVec3 origin, float minAudThresh); /** * Faster and less accurate wavefront expansion algorithm. * Only visits areas once. * * The wave expands until it reaches the maxDist argument distance or until * the number of nodes traversed exceeds the MaxNodes argument. Note the float/int * difference between the last two default-valued arguments. * * If MaxDist is set to -1, no distance limit is applied. * If MaxFloods is set to -1, the global maximum flood limit is used. **/ /*bool ExpandWaveFast( float volInit, idVec3 origin, float MaxDist = -1, int MaxFloods = -1 );*/ // grayman - not used /** * Process the populated areas after a sound propagation event. **/ void ProcessPopulated( float volInit, idVec3 origin, SSprParms *propParms ); /** * Process individual AI. Messages the individual AI, and will later calculate * the effects of environmental sounds in the signal/noise response of the AI. * * Called by ProcessPopulated **/ void ProcessAI( idAI* ai, idVec3 origin, SSprParms *propParms ); bool Intersection(const idVec3& p1, const idVec3& p2, const idVec3& w1, const idVec3& w2, idVec3& ip, float& scale); // grayman #3660 /** * Copy parms from loader object, and also initialize several member vars **/ void SetupParms( const idDict *parms, SSprParms *propParms, USprFlags *addFlags, UTeamMask *tmask ); /** * Detailed path minimization. Finds the optimum path taking points along the portal surfaces * Writes the final loss info and apparent location of the sound to propParms. **/ void DetailedMin( idAI* AI, SSprParms *propParms, SPortEvent *pPortEv, int AIArea, float volInit ); idVec3 SurfPoint( idVec3 p1, idVec3 p2, SsndPortal *portal ); // grayman #3660 /** * Takes point 1, point 2, a winding, and the center point of the winding * Returns the point on the winding surface that is closest * to the line p1-p2. * * If the line intersects the portal surface, the optimum point will * be the intersection point. Otherwise, the point will be somewhere * along the outer boundary of the surface. * * Assumes a rectangular portal with 4 winding points. * * grayman #3660 - That assumption can cause big problems because * portals aren't necessarily rectangle and many times will have more * than 4 winding points. * * Therefore, this method has been replaced. **/ //idVec3 OptSurfPoint( idVec3 p1, idVec3 p2, const idWinding& wind, idVec3 WCenter ); /** * Draws debug lines between a list of points. Used for soundprop debugging **/ void DrawLines(idList<idVec3>& pointlist); protected: /** * Time stamp for the current propagation event [ms] **/ int m_TimeStampProp; /** * Time stamp for the last time portal losses were updated * Used to see if env. sounds need to be repropagated when doors/windows change state **/ int m_TimeStampPortLoss; /** * Populated areas : List of indices of AI populated areas for this expansion **/ idList<int> m_PopAreasInd; /** * Populated areas array: Lists the AI present in each area * and which portals the sound flowed in on, for later AI processing. * * Stays in memory between events. Each entry has a timestamp, * and only entries whose indices are in the m_PopAreasInd list are * checked when processing AI. **/ SPopArea *m_PopAreas; /** * Array of areas. Areas that have been visited will have the * current loss at each portal. Size is the total number of areas * Entries for areas not visited in this propagation are NULL * * For now, this is cleared and re-written for every new sound event * later on, we might see if we can re-use it for multiple events that * come from close to the same spot, for optimization. **/ SEventArea *m_EventAreas; }; #endif
1
0.905381
1
0.905381
game-dev
MEDIA
0.932863
game-dev
0.542548
1
0.542548
VAR-solutions/Algorithms
2,891
Combinatorial Game Theory/Sprague-Grundy Theorem/sprague.cpp
#include<bits/stdc++.h> using namespace std; /* piles[] -> Array having the initial count of stones/coins in each piles before the game has started. n -> Number of piles Grundy[] -> Array having the Grundy Number corresponding to the initial position of each piles in the game The piles[] and Grundy[] are having 0-based indexing*/ #define PLAYER1 1 #define PLAYER2 2 // A Function to calculate Mex of all the values in that set int calculateMex(unordered_set<int> Set) { int Mex = 0; while (Set.find(Mex) != Set.end()) Mex++; return (Mex); } // A function to Compute Grundy Number of 'n' int calculateGrundy(int n, int Grundy[]) { Grundy[0] = 0; Grundy[1] = 1; Grundy[2] = 2; Grundy[3] = 3; if (Grundy[n] != -1) return (Grundy[n]); unordered_set<int> Set; // A Hash Table for (int i=1; i<=3; i++) Set.insert (calculateGrundy (n-i, Grundy)); // Store the result Grundy[n] = calculateMex (Set); return (Grundy[n]); } // A function to declare the winner of the game void declareWinner(int whoseTurn, int piles[], int Grundy[], int n) { int xorValue = Grundy[piles[0]]; for (int i=1; i<=n-1; i++) xorValue = xorValue ^ Grundy[piles[i]]; if (xorValue != 0) { if (whoseTurn == PLAYER1) printf("Player 1 will win\n"); else printf("Player 2 will win\n"); } else { if (whoseTurn == PLAYER1) printf("Player 2 will win\n"); else printf("Player 1 will win\n"); } return; } // Driver program to test above functions int main() { // Test Case 1 int piles[] = {3, 4, 5}; int n = sizeof(piles)/sizeof(piles[0]); // Find the maximum element int maximum = *max_element(piles, piles + n); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy[maximum + 1]; memset(Grundy, -1, sizeof (Grundy)); // Calculate Grundy Value of piles[i] and store it for (int i=0; i<=n-1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER1, piles, Grundy, n); /* Test Case 2 int piles[] = {3, 8, 2}; int n = sizeof(piles)/sizeof(piles[0]); int maximum = *max_element (piles, piles + n); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy [maximum + 1]; memset(Grundy, -1, sizeof (Grundy)); // Calculate Grundy Value of piles[i] and store it for (int i=0; i<=n-1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER2, piles, Grundy, n); */ return (0); }
1
0.5694
1
0.5694
game-dev
MEDIA
0.466234
game-dev,cli-devtools
0.872954
1
0.872954
donkeyProgramming/TheAssetEditor
13,082
Shared/GameFiles/FastBin/FastBinParser2.cs
using Serilog; using Shared.Core.ByteParsing; using Shared.Core.ErrorHandling; using Shared.Core.PackFiles.Models; using static Shared.Core.ByteParsing.ByteChunk; namespace Shared.GameFormats.FastBin { public class UndefinedSection { public uint Version { get; init; } public string Name { get; init; } } public class UndefinedSectionParser { public static UndefinedSection Parse(ByteChunk chunk, string sectionName, uint expectedVersion) { ushort itemCount = 0; var serialiseVersion = chunk.ReadUShort(); if (serialiseVersion != 0) itemCount = chunk.ReadUShort(); var unknownData = chunk.ReadUShort(); // Always 0? Equals(expectedVersion, serialiseVersion); Equals(itemCount, 0); return new UndefinedSection() { Name = sectionName, Version = serialiseVersion }; } } public class FastBinFile2 { public UndefinedSection BATTLEFIELD_BUILDING_LIST { get; set; } public UndefinedSection BATTLEFIELD_BUILDING_LIST_FAR { get; set; } public UndefinedSection CAPTURE_LOCATION_SET { get; set; } public UndefinedSection EF_LINE_LIST { get; set; } public UndefinedSection GO_OUTLINES { get; set; } public UndefinedSection NON_TERRAIN_OUTLINES { get; set; } public UndefinedSection ZONES_TEMPLATE_LIST { get; set; } public UndefinedSection PREFAB_INSTANCE_LIST { get; set; } public UndefinedSection BMD_OUTLINE_LIST { get; set; } public UndefinedSection TERRAIN_OUTLINES { get; set; } public UndefinedSection LITE_BUILDING_OUTLINES { get; set; } public UndefinedSection CAMERA_ZONES { get; set; } public UndefinedSection CIVILIAN_DEPLOYMENT_LIST { get; set; } public UndefinedSection CIVILIAN_SHELTER_LIST { get; set; } } public class FastBinParser2 { ILogger _logger = Logging.Create<FastBinParser>(); public FasBinFile Load(PackFile pf) { _logger.Here().Information($"Parsing {pf.Name}____________"); var outputFile = new FasBinFile(); var chunk = pf.DataSource.ReadDataAsChunk(); var formatStr = chunk.ReadFixedLength(8); if (formatStr != "FASTBIN0") throw new NotImplementedException("Unsupported file format for this parser"); var rootVersion = chunk.ReadUShort(); if (rootVersion != 27) throw new NotImplementedException("Unsupported version for this parser"); var output = new FastBinFile2(); output.BATTLEFIELD_BUILDING_LIST = UndefinedSectionParser.Parse(chunk, "BATTLEFIELD_BUILDING_LIST", 1); output.BATTLEFIELD_BUILDING_LIST_FAR = UndefinedSectionParser.Parse(chunk, "BATTLEFIELD_BUILDING_LIST_FAR", 1); output.CAPTURE_LOCATION_SET = UndefinedSectionParser.Parse(chunk, "CAPTURE_LOCATION_SET", 11); output.EF_LINE_LIST = UndefinedSectionParser.Parse(chunk, "EF_LINE_LIST", 0); output.GO_OUTLINES = UndefinedSectionParser.Parse(chunk, "GO_OUTLINES", 0); output.NON_TERRAIN_OUTLINES = UndefinedSectionParser.Parse(chunk, "NON_TERRAIN_OUTLINES", 1); output.ZONES_TEMPLATE_LIST = UndefinedSectionParser.Parse(chunk, "ZONES_TEMPLATE_LIST", 1); output.PREFAB_INSTANCE_LIST = UndefinedSectionParser.Parse(chunk, "PREFAB_INSTANCE_LIST", 1); output.BMD_OUTLINE_LIST = UndefinedSectionParser.Parse(chunk, "BMD_OUTLINE_LIST", 1); output.TERRAIN_OUTLINES = UndefinedSectionParser.Parse(chunk, "TERRAIN_OUTLINES", 1); output.LITE_BUILDING_OUTLINES = UndefinedSectionParser.Parse(chunk, "LITE_BUILDING_OUTLINES", 1); output.CAMERA_ZONES = UndefinedSectionParser.Parse(chunk, "CAMERA_ZONES", 0); output.CIVILIAN_DEPLOYMENT_LIST = UndefinedSectionParser.Parse(chunk, "CIVILIAN_DEPLOYMENT_LIST", 1); output.CIVILIAN_SHELTER_LIST = UndefinedSectionParser.Parse(chunk, "CIVILIAN_SHELTER_LIST", 1); //PARSE_BATTLEFIELD_BUILDING_LIST(outputFile, chunk); //PARSE_BATTLEFIELD_BUILDING_LIST_FAR(outputFile, chunk); //PARSE_CAPTURE_LOCATION_SET(outputFile, chunk); //PARSE_EF_LINE_LIST(outputFile, chunk); //PARSE_GO_OUTLINES(outputFile, chunk); //5 //PARSE_NON_TERRAIN_OUTLINES(outputFile, chunk); //PARSE_ZONES_TEMPLATE_LIST(outputFile, chunk); //PARSE_PREFAB_INSTANCE_LIST(outputFile, chunk); //PARSE_BMD_OUTLINE_LIST(outputFile, chunk); //PARSE_TERRAIN_OUTLINES(outputFile, chunk); //PARSE_LITE_BUILDING_OUTLINES(outputFile, chunk); //PARSE_CAMERA_ZONES(outputFile, chunk); //PARSE_CIVILIAN_DEPLOYMENT_LIST(outputFile, chunk); //PARSE_CIVILIAN_SHELTER_LIST(outputFile, chunk); PARSE_PROP_LIST(outputFile, chunk); return null; } void PARSE_BATTLEFIELD_BUILDING_LIST(FasBinFile outputFile, ByteChunk chunk) { AssertVersionAndCount("PARSE_BATTLEFIELD_BUILDING_LIST", chunk, 1, 0); } void PARSE_BATTLEFIELD_BUILDING_LIST_FAR(FasBinFile outputFile, ByteChunk chunk) { AssertVersionAndCount("PARSE_BATTLEFIELD_BUILDING_LIST_FAR", chunk, 1, 0); } void PARSE_CAPTURE_LOCATION_SET(FasBinFile outputFile, ByteChunk chunk) { AssertVersionAndCount("PARSE_CAPTURE_LOCATION_SET", chunk, 2, 0); } void PARSE_EF_LINE_LIST(FasBinFile outputFile, ByteChunk chunk) { AssertVersionAndCount("PARSE_EF_LINE_LIST", chunk, 0, 0); } void PARSE_GO_OUTLINES(FasBinFile outputFile, ByteChunk chunk) { AssertVersionAndCount("PARSE_GO_OUTLINES", chunk, 0, 0); } void PARSE_NON_TERRAIN_OUTLINES(FasBinFile outputFile, ByteChunk chunk) { AssertVersionAndCount("PARSE_NON_TERRAIN_OUTLINES", chunk, 1, 0); } void PARSE_ZONES_TEMPLATE_LIST(FasBinFile outputFile, ByteChunk chunk) { AssertVersionAndCount("PARSE_ZONES_TEMPLATE_LIST", chunk, 1, 0); } void PARSE_PREFAB_INSTANCE_LIST(FasBinFile outputFile, ByteChunk chunk) { AssertVersionAndCount("PARSE_PREFAB_INSTANCE_LIST", chunk, 1, 0); } void PARSE_BMD_OUTLINE_LIST(FasBinFile outputFile, ByteChunk chunk) { AssertVersionAndCount("PARSE_BMD_OUTLINE_LIST", chunk, 0, 0); } void PARSE_TERRAIN_OUTLINES(FasBinFile outputFile, ByteChunk chunk) { AssertVersionAndCount("PARSE_TERRAIN_OUTLINES", chunk, 0, 1); } void PARSE_LITE_BUILDING_OUTLINES(FasBinFile outputFile, ByteChunk chunk) { AssertVersionAndCount("PARSE_LITE_BUILDING_OUTLINES", chunk, 0, 0); } void PARSE_CAMERA_ZONES(FasBinFile outputFile, ByteChunk chunk) { AssertVersionAndCount("PARSE_CAMERA_ZONES", chunk, 0, 0); } void PARSE_CIVILIAN_DEPLOYMENT_LIST(FasBinFile outputFile, ByteChunk chunk) { AssertVersionAndCount("PARSE_CAMERPARSE_CIVILIAN_DEPLOYMENT_LISTA_ZONES", chunk, 0, 0); } void PARSE_CIVILIAN_SHELTER_LIST(FasBinFile outputFile, ByteChunk chunk) { AssertVersionAndCount("PARSE_CIVILIAN_SHELTER_LIST", chunk, 0, 0); } void PARSE_PROP_LIST(FasBinFile outputFile, ByteChunk chunk) { GetVerionAndCount("PARSE_PROP_LIST", chunk, out var version, out var count); var byteOffsetStart = chunk.Index; chunk.Index = byteOffsetStart; if (version == 2) { //var keyIndex = chunk.ReadUShort(); // Could this be the key index? // if (keyIndex != 0) // throw new NotImplementedException("Check what this is"); var propFileRef = new string[count]; for (var i = 0; i < count; i++) propFileRef[i] = chunk.ReadString(); var numChildren = chunk.ReadUInt32(); ; for (var popChildIndex = 0; popChildIndex < numChildren; popChildIndex++) { var start = chunk.Index; // 103 bytes for each item from the looks of things - v15 // 102 bytes for each item from the looks of things - v14 var propVersion = chunk.ReadUShort(); if (!(propVersion == 15 || propVersion == 14)) throw new NotImplementedException("Check what this is"); var keyIndex = chunk.ReadInt32(); var matrix = new float[12]; for (var i = 0; i < 12; i++) matrix[i] = chunk.ReadSingle(); var ind = chunk.Index; // 8 bit flags.. //var dataTest0 = new List<UnknownParseResult>(); //var unkDataSize0 = 7; //for (int i = 0; i < unkDataSize0; i++) //{ // dataTest0.Add(chunk.PeakUnknown()); // chunk.ReadByte(); //} var decal = chunk.ReadBool(); var logic_decal = chunk.ReadBool(); var is_fauna = chunk.ReadBool(); var snow_inside = chunk.ReadBool(); var snow_outside = chunk.ReadBool(); var destruction_inside = chunk.ReadBool(); var destruction_outside = chunk.ReadBool(); var animated = chunk.ReadBool(); //chunk.ReadByte(); var decal_parallax_scale = chunk.ReadSingle(); var decal_tiling = chunk.ReadSingle(); //var decal_override_gbuffer_normal = chunk.ReadBool(); //var visible_in_shroud = chunk.ReadBool(); //var decal_apply_to_terrain = chunk.ReadBool(); //var decal_apply_to_gbuffer_objects = chunk.ReadBool(); //var decal_render_above_snow = chunk.ReadBool(); var x0 = chunk.PeakUnknown(); var b0 = chunk.ReadByte(); //var unk = chunk.ReadUShort(); // Related to animated //if (animated != 0) // throw new NotImplementedException("Check what this is"); var flags_serialise_version = chunk.ReadUShort(); // 5 bit flags var dataTest1 = new List<UnknownParseResult>(); var unkDataSize1 = 11; for (var i = 0; i < unkDataSize1; i++) { dataTest1.Add(chunk.PeakUnknown()); chunk.ReadByte(); } var height_mode = chunk.ReadString(); // 254 var pdlc_mask = chunk.ReadInt32(); var cast_shadows = chunk.ReadBool(); var no_culling = chunk.ReadBool(); if (propVersion == 15) { var terrain_bent = chunk.ReadBool(); } var dataRead = chunk.Index - start; //var ukn = chunk.ReadBytes(3); } //170 start of item //254 start of bhm_parent //84 bytes // // 273 } else { throw new ArgumentException("Unsuported version"); } } void GetVerionAndCount(string desc, ByteChunk chunk, out ushort serialiseVersion, out int itemCount) { var indexAtStart = chunk.Index; itemCount = -1; serialiseVersion = chunk.ReadUShort(); if (serialiseVersion != 0) itemCount = chunk.ReadUShort(); var unknownData = chunk.ReadUShort(); // Always 0? _logger.Here().Information($"At index {indexAtStart} - Version:{serialiseVersion} NumElements:{itemCount} unk:{unknownData} - {desc}"); } void AssertVersionAndCount(string desc, ByteChunk chunk, ushort expectedSerialiseVersion, uint expectedItemCount) { GetVerionAndCount(desc, chunk, out var acutalSerialiseVersion, out var actualItemCount); //if (acutalSerialiseVersion != expectedSerialiseVersion) // throw new ArgumentException("Unexpected version"); // //if (actualItemCount != expectedItemCount) // throw new ArgumentException("Unexpected item count"); } } }
1
0.885669
1
0.885669
game-dev
MEDIA
0.265368
game-dev
0.759041
1
0.759041
SinlessDevil/ZenjectTemplate
54,672
Assets/Shaders/Toony Colors Pro/Editor/Shader Generator/Config.cs
// Toony Colors Pro+Mobile 2 // (c) 2014-2023 Jean Moreno #define WRITE_UNCOMPRESSED_SERIALIZED_DATA using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using UnityEditor; using UnityEngine; using ToonyColorsPro.Utilities; using ToonyColorsPro.ShaderGenerator.CodeInjection; // Represents a Toony Colors Pro 2 configuration to generate the corresponding shader // (new version for Shader Generator 2) namespace ToonyColorsPro { namespace ShaderGenerator { internal interface IMaterialPropertyName { string GetPropertyName(); } internal static class UniqueMaterialPropertyName { internal delegate bool CheckUniqueVariableName(string variableName, IMaterialPropertyName materialPropertyName); internal static event CheckUniqueVariableName checkUniqueVariableName; internal static string GetUniquePropertyName(string baseName, IMaterialPropertyName materialPropertyName) { if (checkUniqueVariableName == null) { return baseName; } //name doesn't exist: all good if (checkUniqueVariableName(baseName, materialPropertyName)) return baseName; //extract the last digits of the name, if any for (var i = baseName.Length - 1; i >= 0; i--) { if (baseName[i] >= '0' && baseName[i] <= '9') continue; baseName = baseName.Substring(0, i + 1); break; } //check if name is unique: requires a class that registers to the event and supply its own checks var newName = baseName; var count = 1; while (!checkUniqueVariableName(newName, materialPropertyName)) { newName = string.Format("{0}{1}", baseName, count); count++; } return newName; } } [Serialization.SerializeAs("config")] internal class Config { #pragma warning disable 414 [Serialization.SerializeAs("ver")] string tcp2version { get { return ShaderGenerator2.TCP2_VERSION; } } [Serialization.SerializeAs("unity")] string unityVersion { get { return Application.unityVersion; } } #pragma warning restore 414 internal const string kSerializationPrefix = "/* TCP_DATA "; internal const string kSerializationPrefixUncompressed = "/* TCP_DATA u "; internal const string kSerializationSuffix = " */"; internal const string kHashPrefix = "/* TCP_HASH "; internal const string kHashSuffix = " */"; internal string Filename = "My TCP2 Shader"; internal string ShaderName = "Toony Colors Pro 2/User/My TCP2 Shader"; [Serialization.SerializeAs("tmplt")] internal string templateFile = "TCP2_ShaderTemplate_Default"; [Serialization.SerializeAs("features")] internal List<string> Features = new List<string>(); internal List<string> ExtraTempFeatures = new List<string>(); [Serialization.SerializeAs("flags")] internal List<string> Flags = new List<string>(); [Serialization.SerializeAs("flags_extra")] internal Dictionary<string, List<string>> FlagsExtra = new Dictionary<string, List<string>>(); [Serialization.SerializeAs("keywords")] internal Dictionary<string, string> Keywords = new Dictionary<string, string>(); internal bool isModifiedExternally = false; internal bool isTerrainShader { get { return this.Features.Contains("TERRAIN_SHADER"); } } // UI list of Shader Properties struct ShaderPropertyGroup { public GUIContent header; public bool hasModifiedShaderProperties; public bool hasErrors; public List<ShaderProperty> shaderProperties; } List<ShaderPropertyGroup> shaderPropertiesUIGroups = new List<ShaderPropertyGroup>(); Dictionary<string, bool> headersExpanded = new Dictionary<string, bool>(); // the struct array above is always recreated, so we can't track expanded state there List<ShaderProperty> visibleShaderProperties = new List<ShaderProperty>(); //Serialize all cached Shader Properties so that their custom implementation is saved, even if they are not used in the shader [Serialization.SerializeAs("shaderProperties")] List<ShaderProperty> cachedShaderProperties = new List<ShaderProperty>(); List<List<ShaderProperty>> shaderPropertiesPerPass; [Serialization.SerializeAs("customTextures")] List<ShaderProperty.CustomMaterialProperty> customMaterialPropertiesList = new List<ShaderProperty.CustomMaterialProperty>(); ReorderableLayoutList customTexturesLayoutList = new ReorderableLayoutList(); /// Iterate through all Shader Properties associated with this config, including Material Layers and Code Injection IEnumerable<ShaderProperty> IterateAllShaderProperties() { var processed = new HashSet<ShaderProperty>(); foreach (var shaderProperty in cachedShaderProperties) { if (processed.Contains(shaderProperty)) continue; processed.Add(shaderProperty); yield return shaderProperty; } foreach (var shaderProperty in visibleShaderProperties) { if (processed.Contains(shaderProperty)) continue; processed.Add(shaderProperty); yield return shaderProperty; } foreach (var materialLayer in materialLayers) { if (materialLayer.sourceShaderProperty != null) { if (processed.Contains(materialLayer.sourceShaderProperty)) continue; processed.Add(materialLayer.sourceShaderProperty); yield return materialLayer.sourceShaderProperty; } if (materialLayer.noiseProperty != null) { if (processed.Contains(materialLayer.noiseProperty)) continue; processed.Add(materialLayer.noiseProperty); yield return materialLayer.noiseProperty; } if (materialLayer.contrastProperty != null) { if (processed.Contains(materialLayer.contrastProperty)) continue; processed.Add(materialLayer.contrastProperty); yield return materialLayer.contrastProperty; } } foreach (var injectedFile in codeInjection.injectedFiles) { foreach (var point in injectedFile.injectedPoints) { foreach (var shaderProperty in point.shaderProperties) { if (shaderProperty != null) { if (processed.Contains(shaderProperty)) continue; processed.Add(shaderProperty); yield return shaderProperty; } } } } } public ShaderProperty customMaterialPropertyShaderProperty = new ShaderProperty("_CustomMaterialPropertyDummy", ShaderProperty.VariableType.color_rgba); internal ShaderProperty.CustomMaterialProperty[] CustomMaterialProperties { get { return customMaterialPropertiesList.ToArray(); } } internal ShaderProperty[] VisibleShaderProperties { get { return visibleShaderProperties.ToArray(); } } internal ShaderProperty[] AllShaderProperties { get { return cachedShaderProperties.ToArray(); } } // Code Injection properties [Serialization.SerializeAs("codeInjection")] internal CodeInjectionManager codeInjection = new CodeInjectionManager(); // Material Layers [Serialization.SerializeAs("matLayers")] internal List<MaterialLayer> materialLayers = new List<MaterialLayer>(); KeyValuePair<string, string>[] _materialLayersNames; internal KeyValuePair<string, string>[] materialLayersNames { get { if (_materialLayersNames == null || _materialLayersNames.Length != materialLayers.Count) { var list = materialLayers.ConvertAll(element => new KeyValuePair<string, string>(element.name, element.uid)); list.Insert(0, new KeyValuePair<string, string>("Base", null)); _materialLayersNames = list.ToArray(); } return _materialLayersNames; } } ReorderableLayoutList matLayersLayoutList = new ReorderableLayoutList(); internal MaterialLayer GetMaterialLayerByUID(string uid) { return materialLayers.Find(ml => ml.uid == uid); } internal string[] GetShaderPropertiesNeededFeaturesForPass(int passIndex) { if (shaderPropertiesPerPass == null || shaderPropertiesPerPass.Count == 0) return new string[0]; if (passIndex >= shaderPropertiesPerPass.Count) return new string[0]; if (shaderPropertiesPerPass[passIndex] == null || shaderPropertiesPerPass[passIndex].Count == 0) return new string[0]; List<string> usedMaterialLayersVertex = new List<string>(); List<string> usedMaterialLayersFragment = new List<string>(); var features = new List<string>(); foreach (var sp in shaderPropertiesPerPass[passIndex]) { features.AddRange(sp.NeededFeatures()); // figure out used MaterialLayers and their programs foreach (string uid in sp.linkedMaterialLayers) { if (sp.Program == ShaderProperty.ProgramType.Vertex) { if (!usedMaterialLayersVertex.Contains(uid)) { usedMaterialLayersVertex.Add(uid); } } else if (sp.Program == ShaderProperty.ProgramType.Fragment) { if (!usedMaterialLayersFragment.Contains(uid)) { usedMaterialLayersFragment.Add(uid); } } } } // needed features for Material Layer sources // HACK: We override the program type so that the relevant needed features get added. // This is cleaner than refactoring all the methods called. Action<ShaderProperty, ShaderProperty.ProgramType> GetNeededFeaturesForProperty = (shaderProperty, programType) => { if (shaderProperty == null) { return; } var program = shaderProperty.Program; shaderProperty.Program = programType; { features.AddRange(shaderProperty.NeededFeatures()); } shaderProperty.Program = program; }; foreach (string uid in usedMaterialLayersVertex) { var ml = this.GetMaterialLayerByUID(uid); GetNeededFeaturesForProperty(ml.sourceShaderProperty, ShaderProperty.ProgramType.Vertex); GetNeededFeaturesForProperty(ml.contrastProperty, ShaderProperty.ProgramType.Vertex); GetNeededFeaturesForProperty(ml.noiseProperty, ShaderProperty.ProgramType.Vertex); } foreach (string uid in usedMaterialLayersFragment) { var ml = this.GetMaterialLayerByUID(uid); GetNeededFeaturesForProperty(ml.sourceShaderProperty, ShaderProperty.ProgramType.Fragment); GetNeededFeaturesForProperty(ml.contrastProperty, ShaderProperty.ProgramType.Fragment); GetNeededFeaturesForProperty(ml.noiseProperty, ShaderProperty.ProgramType.Fragment); } return features.Distinct().ToArray(); } internal string[] GetShaderPropertiesNeededFeaturesAll() { if (shaderPropertiesPerPass == null || shaderPropertiesPerPass.Count == 0) { return new string[0]; } List<string> features = new List<string>(); for (int i = 0; i < shaderPropertiesPerPass.Count; i++) { features.AddRange(GetShaderPropertiesNeededFeaturesForPass(i)); } return features.Distinct().ToArray(); /* if (shaderPropertiesPerPass == null || shaderPropertiesPerPass.Count == 0) return new string[0]; // iterate through used Shader Properties for all passes and toggle needed features List<string> usedMaterialLayers = new List<string>(); var features = new List<string>(); foreach (var list in shaderPropertiesPerPass) { foreach (var sp in list) { features.AddRange(sp.NeededFeatures()); foreach (string uid in sp.linkedMaterialLayers) { if (!usedMaterialLayers.Contains(uid)) { usedMaterialLayers.Add(uid); } } } } // needed features for Material Layer sources foreach (string uid in usedMaterialLayers) { var ml = this.GetMaterialLayerByUID(uid); features.AddRange(ml.sourceShaderProperty.NeededFeatures()); } return features.Distinct().ToArray(); */ } internal string[] GetHooksNeededFeatures() { // iterate through Hook Shader Properties and toggle features if needed var features = new List<string>(); foreach (var sp in visibleShaderProperties) { if (sp.isHook && !string.IsNullOrEmpty(sp.toggleFeatures)) { if (sp.manuallyModified) { features.AddRange(sp.toggleFeatures.Split(',')); } } } return features.ToArray(); } internal string[] GetCodeInjectionNeededFeatures() { return codeInjection.GetNeededFeatures(); } /// <summary> /// Remove all features associated with specific Shader Property options, /// so that they don't stay when toggling an option on, compile, then off /// </summary> internal void ClearShaderPropertiesFeatures() { foreach (var f in ShaderProperty.AllOptionFeatures()) { Utils.RemoveIfExists(this.Features, f); } } //-------------------------------------------------------------------------------------------------- private enum ParseBlock { None, Features, Flags } internal static Config CreateFromFile(TextAsset asset) { return CreateFromFile(asset.text); } internal static Config CreateFromFile(string text) { var lines = text.Split(new[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries); var config = new Config(); //Flags var currentBlock = ParseBlock.None; for (var i = 0; i < lines.Length; i++) { var line = lines[i]; if (line.StartsWith("//")) continue; var data = line.Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries); if (line.StartsWith("#")) { currentBlock = ParseBlock.None; switch (data[0]) { case "#filename": config.Filename = data[1]; break; case "#shadername": config.ShaderName = data[1]; break; case "#features": currentBlock = ParseBlock.Features; break; case "#flags": currentBlock = ParseBlock.Flags; break; default: Debug.LogWarning("[TCP2 Shader Config] Unrecognized tag: " + data[0] + "\nline " + (i + 1)); break; } } else { if (data.Length > 1) { var enabled = false; bool.TryParse(data[1], out enabled); if (enabled) { if (currentBlock == ParseBlock.Features) config.Features.Add(data[0]); else if (currentBlock == ParseBlock.Flags) config.Flags.Add(data[0]); else Debug.LogWarning("[TCP2 Shader Config] Unrecognized line while parsing : " + line + "\nline " + (i + 1)); } } } } return config; } internal static Config CreateFromShader(Shader shader) { var shaderImporter = ShaderImporter.GetAtPath(AssetDatabase.GetAssetPath(shader)) as ShaderImporter; var config = new Config { ShaderName = shader.name, Filename = Path.GetFileName(AssetDatabase.GetAssetPath(shader)).Replace(".shader", "") }; var valid = config.ParseUserData(shaderImporter); valid |= config.ParseSerializedDataAndHash(shaderImporter, null, false); //first run (see method comment) if (valid) return config; return null; } internal Config Copy() { var config = new Config { Filename = Filename, ShaderName = ShaderName }; foreach (var feature in Features) config.Features.Add(feature); foreach (var flag in Flags) config.Flags.Add(flag); foreach (var kvp in FlagsExtra) config.FlagsExtra.Add(kvp.Key, new List<string>(kvp.Value)); foreach (var kvp in Keywords) config.Keywords.Add(kvp.Key, kvp.Value); config.templateFile = templateFile; config.codeInjection = codeInjection; return config; } //Copy implementations from this config to another public void CopyImplementationsTo(Config otherConfig) { for (int i = 0; i < this.cachedShaderProperties.Count; i++) { for (int j = 0; j < otherConfig.cachedShaderProperties.Count; j++) { if (this.cachedShaderProperties[i].Name == otherConfig.cachedShaderProperties[j].Name) { otherConfig.cachedShaderProperties[j].implementations = this.cachedShaderProperties[i].implementations; otherConfig.cachedShaderProperties[j].CheckHash(); otherConfig.cachedShaderProperties[j].CheckErrors(); break; } } } for (int i = 0; i < otherConfig.cachedShaderProperties.Count; i++) { otherConfig.cachedShaderProperties[i].ResolveShaderPropertyReferences(); } } public void CopyCustomTexturesTo(Config otherConfig) { otherConfig.customMaterialPropertiesList = this.customMaterialPropertiesList; for (int i = 0; i < otherConfig.cachedShaderProperties.Count; i++) { otherConfig.cachedShaderProperties[i].ResolveShaderPropertyReferences(); } } internal bool HasErrors() { foreach (var shaderProperty in visibleShaderProperties) { if (shaderProperty.error) return true; } foreach (var customTexture in CustomMaterialProperties) { if (customTexture.HasErrors) return true; } return false; } internal string GetConfigFileCustomData() { return string.Format("CF:{0}", templateFile); } internal int ToHash() { var sb = new StringBuilder(); /* sb.Append(Filename); sb.Append(ShaderName); */ var orderedFeatures = new List<string>(Features); orderedFeatures.Sort(); var orderedFlags = new List<string>(Flags); orderedFlags.Sort(); var orderedFlagsExtra = new List<string>(); foreach (var kvp in FlagsExtra) foreach (var flag in kvp.Value) orderedFlagsExtra.Add(flag); orderedFlagsExtra.Sort(); var sortedKeywordsKeys = new List<string>(Keywords.Keys); sortedKeywordsKeys.Sort(); var sortedKeywordsValues = new List<string>(Keywords.Values); sortedKeywordsValues.Sort(); foreach (var f in orderedFeatures) sb.Append(f); foreach (var f in orderedFlags) sb.Append(f); foreach (var f in sortedKeywordsKeys) sb.Append(f); foreach (var f in sortedKeywordsValues) sb.Append(f); foreach (var sp in visibleShaderProperties) sb.Append(sp); foreach (var ct in customMaterialPropertiesList) sb.Append(ct); return sb.ToString().GetHashCode(); } bool ParseUserData(ShaderImporter importer) { if (string.IsNullOrEmpty(importer.userData)) return false; var data = importer.userData.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); var customDataList = new List<string>(); foreach (var d in data) { if (string.IsNullOrEmpty(d)) continue; switch (d[0]) { //Features case 'F': if (d == "F") break; //Prevent getting "empty" feature Features.Add(d.Substring(1)); break; //Flags case 'f': Flags.Add(d.Substring(1)); break; //Keywords case 'K': var kw = d.Substring(1).Split(':'); if (kw.Length != 2) { Debug.LogError("[TCP2 Shader Generator] Error while parsing userData: invalid Keywords format."); return false; } else { Keywords.Add(kw[0], kw[1]); } break; //Custom Data case 'c': customDataList.Add(d.Substring(1)); break; //old format default: Features.Add(d); break; } } foreach (var customData in customDataList) { //Configuration File if (customData.StartsWith("CF:")) { templateFile = customData.Substring(3); } } return true; } private static string CompressString(string uncompressed) { var bytes = Encoding.UTF8.GetBytes(uncompressed); using (var compressedStream = new MemoryStream()) { using (var gZipStream = new GZipStream(compressedStream, CompressionMode.Compress)) { gZipStream.Write(bytes, 0, bytes.Length); } bytes = compressedStream.ToArray(); } return Convert.ToBase64String(bytes); } private static string UncompressString(string compressed) { var bytes = Convert.FromBase64String(compressed); var buffer = new byte[4096]; var uncompressedStream = new MemoryStream(); using (var compressedStream = new MemoryStream(bytes)) { using (var gZipStream = new GZipStream(compressedStream, CompressionMode.Decompress)) { var length = 0; do { length = gZipStream.Read(buffer, 0, 4096); if (length > 0) uncompressedStream.Write(buffer, 0, length); } while (length > 0); } } return Encoding.UTF8.GetString(uncompressedStream.ToArray()); } //New serialization format, embedded into the shader source in a comment internal string GetSerializedData() { var serialized = Serialization.Serialize(this); #if WRITE_UNCOMPRESSED_SERIALIZED_DATA return kSerializationPrefixUncompressed + serialized + kSerializationSuffix; #else return kSerializationPrefix + CompressString(serialized) + kSerializationSuffix; #endif } //This method is executed twice because of an ordering problem: // - first run: it needs to fetch the template used from TCP_DATA // - then it loads that template and generate the serialized properties // - second run: now that the serialized properties exist, replace their implementations with the ones in TPC2_DATA internal bool ParseSerializedDataAndHash(ShaderImporter importer, Template template, bool dontRebuildCustomTextures) { //try to find serialized TCP2 data var unityPath = importer.assetPath; var osPath = Application.dataPath + "/" + unityPath.Substring("Assets/".Length); if (File.Exists(osPath)) { var code = File.ReadAllLines(osPath); for (var i = code.Length - 1; i >= 0; i--) { var line = code[i].Trim(); const string serializedPrefix = kSerializationPrefix; const string serializedPrefixU = kSerializationPrefixUncompressed; const string serializedSuffix = kSerializationSuffix; const string hashPrefix = kHashPrefix; const string hashSuffix = kHashSuffix; //hash is always inserted after serialized data, so the function shouldn't return without it being checked if (line.StartsWith(hashPrefix)) { var hash = line.Substring(hashPrefix.Length, line.Length - hashPrefix.Length - hashSuffix.Length); //list of all lines, remove them from the end until the serialized prefix is found var codeLines = new List<string>(code); for (int j = codeLines.Count - 1; j >= 0; j--) { bool @break = codeLines[j].StartsWith(hashPrefix); codeLines.RemoveAt(j); if (@break) break; } var sb = new StringBuilder(); foreach (var l in codeLines) { sb.AppendLine(l); } string normalizedLineEndings = sb.ToString().Replace("\r\n", "\n"); var fileHash = ShaderGenerator2.GetHash(normalizedLineEndings); this.isModifiedExternally = string.Compare(fileHash, hash, StringComparison.Ordinal) != 0; } if (line.StartsWith(serializedPrefix) || line.StartsWith(serializedPrefixU)) { string extractedData = line; int j = i; while (!extractedData.Contains(" */") && j < code.Length) { j++; if (j < code.Length) { line = code[j].Trim(); extractedData += "\n" + line; } else { Debug.LogError(ShaderGenerator2.ErrorMsg("Incomplete serialized data in shader file.")); return false; } } var serializedData = ""; if (extractedData.StartsWith(serializedPrefixU)) { serializedData = extractedData.Substring(serializedPrefixU.Length, extractedData.Length - serializedPrefixU.Length - serializedSuffix.Length); } else { serializedData = extractedData.Substring(serializedPrefix.Length, extractedData.Length - serializedPrefix.Length - serializedSuffix.Length); serializedData = UncompressString(serializedData); } return ParseSerializedData(serializedData, template, dontRebuildCustomTextures); } } } return false; } public bool ParseSerializedData(string serializedData, Template template, bool dontRebuildCustomTextures, bool resetEmptyImplementations = false) { Func<object, string, object> onDeserializeShaderPropertyList = (obj, data) => { //called with data in format 'list[sp(field:value;field:value...),sp(field:value;...)]' // - make a new list, and pull matching sp from it // - reset the implementations of the remaining sp for the undo/redo system var shaderPropertiesTempList = new List<ShaderProperty>(cachedShaderProperties); var split = Serialization.SplitExcludingBlocks(data.Substring(5, data.Length - 6), ',', true, true, "()", "[]"); foreach (var spData in split) { //try to match existing Shader Property by its name string name = null; //exclude 'sp(' and ')' and extract fields var vars = Serialization.SplitExcludingBlocks(spData.Substring(3, spData.Length - 4), ';', true, true, "()", "[]"); foreach (var v in vars) { //find 'name' and remove 'name:' and quotes to extract value if (v.StartsWith("name:")) name = v.Substring(6, v.Length - 7); } if (name != null) { //find corresponding shader property, if it exists var matchedSp = shaderPropertiesTempList.Find(sp => sp.Name == name); //if no match, try to find it in the template's shader properties if (matchedSp == null && template != null) { matchedSp = Array.Find(template.shaderProperties, sp => sp.Name == name); if (matchedSp != null) { cachedShaderProperties.Add(matchedSp); shaderPropertiesTempList.Add(matchedSp); } } if (matchedSp != null) { shaderPropertiesTempList.Remove(matchedSp); Func<object, string, object> onDeserializeImplementation = (impObj, impData) => { return this.DeserializeImplementationHandler(impObj, impData, matchedSp); }; var implementationHandling = new Dictionary<Type, Func<object, string, object>> { { typeof(ShaderProperty.Implementation), onDeserializeImplementation } }; Serialization.DeserializeTo(matchedSp, spData, typeof(ShaderProperty), null, implementationHandling); matchedSp.CheckHash(); matchedSp.CheckErrors(); } } } if (resetEmptyImplementations) { foreach (var remainingShaderProperty in shaderPropertiesTempList) { remainingShaderProperty.ResetDefaultImplementation(); } } return null; }; // try { var shaderPropertyHandling = new Dictionary<Type, Func<object, string, object>> { { typeof(List<ShaderProperty>), onDeserializeShaderPropertyList } }; if (dontRebuildCustomTextures) { // if not building the custom material properties list, just skip its deserialization, else use the custom handling shaderPropertyHandling.Add(typeof(List<ShaderProperty.CustomMaterialProperty>), (obj, data) => { return null; }); } Serialization.DeserializeTo(this, serializedData, GetType(), null, shaderPropertyHandling); return true; } // catch (Exception e) { // Debug.LogError(ShaderGenerator2.ErrorMsg(string.Format("Deserialization error:\n'{0}'\n{1}", e.Message, e.StackTrace.Replace(Application.dataPath, "")))); // return false; } } internal object DeserializeImplementationHandler(object impObj, string serializedData, ShaderProperty existingShaderProperty) { //make sure to deserialize as a new object, so that final Implementation subtype is kept instead of creating base Implementation class var imp = Serialization.Deserialize(serializedData, new object[] { existingShaderProperty }); //if custom material property, find the one with the matching serialized name if (imp is ShaderProperty.Imp_CustomMaterialProperty) { var ict = (imp as ShaderProperty.Imp_CustomMaterialProperty); var matchedCt = customMaterialPropertiesList.Find(ct => ct.PropertyName == ict.LinkedCustomMaterialPropertyName); //will be the match, or null if nothing found ict.LinkedCustomMaterialProperty = matchedCt; ict.UpdateChannels(); } else if (imp is ShaderProperty.Imp_ShaderPropertyReference) { //find existing shader property and link it here //TODO: what if the shader property hasn't been deserialized yet? var ispr = (imp as ShaderProperty.Imp_ShaderPropertyReference); var channels = ispr.Channels; var matchedLinkedSp = visibleShaderProperties.Find(sp => sp.Name == ispr.LinkedShaderPropertyName); ispr.LinkedShaderProperty = matchedLinkedSp; //restore channels from serialized data (it is reset when assigning a new linked shader property) if (!string.IsNullOrEmpty(channels)) ispr.Channels = channels; } else if (imp is ShaderProperty.Imp_MaterialProperty_Texture) { // find existing shader property for uv if that option is enabled, and link it var impt = (imp as ShaderProperty.Imp_MaterialProperty_Texture); var channels = impt.UVChannels; var matchedLinkedSp = visibleShaderProperties.Find(sp => sp.Name == impt.LinkedShaderPropertyName); impt.LinkedShaderProperty = matchedLinkedSp; //restore channels from serialized data (it is reset when assigning a new linked shader property) if (!string.IsNullOrEmpty(channels)) impt.UVChannels = channels; } return imp; } internal void AutoNames() { var rawName = ShaderName.Replace("Toony Colors Pro 2/", ""); if (!ProjectOptions.data.SubFolders) { rawName = Path.GetFileName(rawName); } Filename = rawName; } //-------------------------------------------------------------------------------------------------- // FEATURES internal bool HasFeature(string feature) { return Features.Contains(feature); } internal bool HasFeaturesAny(params string[] features) { foreach (var f in features) { if (Features.Contains(f)) { return true; } } return false; } internal bool HasFeaturesAll(params string[] features) { foreach (var f in features) { if (f[0] == '!') { if (Features.Contains(f.Substring(1))) { return false; } } else { if (!Features.Contains(f)) { return false; } } } return true; } internal void ToggleFeature(string feature, bool enable) { if (string.IsNullOrEmpty(feature)) return; if (!Features.Contains(feature) && enable) Features.Add(feature); else if (Features.Contains(feature) && !enable) Features.Remove(feature); } //-------------------------------------------------------------------------------------------------- // FLAGS internal bool HasFlag(string block, string flag) { if (block == "pragma_surface_shader") { return Flags.Contains(flag); } else { return FlagsExtra.ContainsKey(block) && FlagsExtra[block].Contains(flag); } } internal void ToggleFlag(string block, string flag, bool enable) { List<string> flagList = null; if (block == "pragma_surface_shader") { flagList = Flags; } else { if (!FlagsExtra.ContainsKey(block)) { FlagsExtra.Add(block, new List<string>()); } flagList = FlagsExtra[block]; } if (!flagList.Contains(flag) && enable) flagList.Add(flag); else if (flagList.Contains(flag) && !enable) flagList.Remove(flag); } //-------------------------------------------------------------------------------------------------- // KEYWORDS internal bool HasKeyword(string key) { return GetKeyword(key) != null; } internal string GetKeyword(string key) { if (key == null) return null; if (!Keywords.ContainsKey(key)) return null; return Keywords[key]; } internal void SetKeyword(string key, string value) { if (string.IsNullOrEmpty(value)) { if (Keywords.ContainsKey(key)) Keywords.Remove(key); } else { if (Keywords.ContainsKey(key)) Keywords[key] = value; else Keywords.Add(key, value); } } internal void RemoveKeyword(string key) { if (Keywords.ContainsKey(key)) Keywords.Remove(key); } //-------------------------------------------------------------------------------------------------- // SHADER PROPERTIES / CUSTOM MATERIAL PROPERTIES void ExpandAllGroups() { var keys = headersExpanded.Keys.ToArray(); foreach (var key in keys) { headersExpanded[key] = true; } } void FoldAllGroups() { var keys = headersExpanded.Keys.ToArray(); foreach (var key in keys) { headersExpanded[key] = false; } } public string getHeadersExpanded() { string headersFoldout = ""; foreach (var kvp in headersExpanded) { if (kvp.Value) { headersFoldout += kvp.Key + ","; } } return headersFoldout.TrimEnd(','); } public void setHeadersExpanded(string expandedHeaders) { var array = expandedHeaders.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var keys = headersExpanded.Keys.ToArray(); foreach (var key in keys) { headersExpanded[key] = Array.Exists(array, str => str == key); } } public string getShaderPropertiesExpanded() { string spExpanded = ""; foreach (var sp in IterateAllShaderProperties()) { if (sp.expanded) { spExpanded += sp.Name + ","; } } return spExpanded.TrimEnd(','); } public void setShaderPropertiesExpanded(string spExpanded) { var array = spExpanded.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var sp in IterateAllShaderProperties()) { sp.expanded = Array.Exists(array, str => str == sp.Name); } } internal void ShaderPropertiesGUI() { GUILayout.Space(6); GUILayout.BeginHorizontal(); // Expand / Fold All if (GUILayout.Button(TCP2_GUI.TempContent(" Expand All "), EditorStyles.miniButtonLeft)) { ExpandAllGroups(); } if (GUILayout.Button(TCP2_GUI.TempContent(" Fold All "), EditorStyles.miniButtonRight)) { FoldAllGroups(); } GUILayout.FlexibleSpace(); // Reset All bool canReset = false; foreach (var sp in cachedShaderProperties) { if (sp.manuallyModified) { canReset = true; break; } } using (new EditorGUI.DisabledScope(!canReset)) { if (GUILayout.Button(TCP2_GUI.TempContent(" Reset All "), EditorStyles.miniButton)) { if (EditorUtility.DisplayDialog("Reset All Shader Properties", "All Custom Shader Properties will be cleared!\nThis can't be undone!\nProceed?", "Yes", "No")) { foreach (var sp in cachedShaderProperties) { sp.ResetDefaultImplementation(); } } } } GUILayout.EndHorizontal(); GUILayout.Space(4); if (ShaderGenerator2.ContextualHelpBox( "This section allows you to modify some shader properties that will be used in the shader, based on the features enabled in the corresponding tab.\nClick here to open the documentation and see some examples.", "shaderproperties")) { GUILayout.Space(4); } if (visibleShaderProperties.Count == 0) { EditorGUILayout.HelpBox("There are no shader properties for this template.", MessageType.Info); } else { for (int i = 0; i < shaderPropertiesUIGroups.Count; i++) { var group = shaderPropertiesUIGroups[i]; if (group.header != null) { EditorGUI.BeginChangeCheck(); // hover rect as in 2019.3 UI var rect = GUILayoutUtility.GetRect(group.header, EditorStyles.foldout, GUILayout.ExpandWidth(true)); TCP2_GUI.DrawHoverRect(rect); rect.xMin += 4; // small left padding headersExpanded[group.header.text] = TCP2_GUI.HeaderFoldoutHighlightErrorGrayPosition(rect, headersExpanded[group.header.text], group.header, group.hasErrors, group.hasModifiedShaderProperties); if (EditorGUI.EndChangeCheck()) { // expand/fold all when alt/control is held if (Event.current.alt || Event.current.control) { if (headersExpanded[group.header.text]) { ExpandAllGroups(); } else { FoldAllGroups(); } } } } if (group.header == null || headersExpanded[group.header.text]) { foreach (var sp in group.shaderProperties) { sp.ShowGUILayout(14); } } } } // Custom Material Properties if (visibleShaderProperties.Count > 0) { CustomMaterialPropertiesGUI(); } } // Material Layers UI float tabOffsets; float tabOffsetsTarget; int selected; internal void MaterialLayersGUI(out bool shaderPropertiesChange) { bool spChange = false; //button callbacks ShaderProperty.CustomMaterialProperty.ButtonClick onAdd = index => { materialLayers.Add(new MaterialLayer()); _materialLayersNames = null; spChange = true; }; ShaderProperty.CustomMaterialProperty.ButtonClick onRemove = index => { foreach (var shaderProperty in cachedShaderProperties) { if (shaderProperty.linkedMaterialLayers.Contains(materialLayers[index].uid)) { shaderProperty.RemoveMaterialLayer(materialLayers[index].uid); } } materialLayers[index].sourceShaderProperty.WillBeRemoved(); materialLayers.RemoveAt(index); _materialLayersNames = null; spChange = true; }; //draw element callback Action<int, float> DrawMaterialLayer = (index, margin) => { var matLayer = materialLayers[index]; EditorGUILayout.BeginVertical(EditorStyles.helpBox); { using (new SGUILayout.IndentedLine(margin)) { // Header const float buttonWidth = 20; var rect = EditorGUILayout.GetControlRect(GUILayout.Height(EditorGUIUtility.singleLineHeight)); rect.width -= buttonWidth * 2; TCP2_GUI.DrawHoverRect(rect); EditorGUI.BeginChangeCheck(); matLayer.expanded = GUI.Toggle(rect, matLayer.expanded, TCP2_GUI.TempContent("Layer: " + matLayer.name), TCP2_GUI.HeaderDropDown); if (EditorGUI.EndChangeCheck()) { if (Event.current.alt || Event.current.control) { var state = matLayer.expanded; foreach (var ml in materialLayers) { ml.expanded = state; } } } // Add/Remove buttons rect.x += rect.width; rect.width = buttonWidth; rect.height = EditorGUIUtility.singleLineHeight; if (GUI.Button(rect, "+", EditorStyles.miniButtonLeft)) { onAdd(index); } rect.x += rect.width; if (GUI.Button(rect, "-", EditorStyles.miniButtonRight)) { onRemove(index); } } // Parameters: if (matLayer.expanded) { using (new SGUILayout.IndentedLine(margin)) { matLayer.name = EditorGUILayout.DelayedTextField(TCP2_GUI.TempContent("Name"), matLayer.name); } using (new SGUILayout.IndentedLine(margin)) { GUILayout.Label(TCP2_GUI.TempContent("ID"), GUILayout.Width(EditorGUIUtility.labelWidth - 4)); using (new EditorGUI.DisabledScope(true)) { EditorGUILayout.TextField(GUIContent.none, matLayer.uid); } } using (new SGUILayout.IndentedLine(margin)) { using (new EditorGUI.DisabledScope(true)) { GUILayout.Label("The ID will be replaced with the actual Material Layer name for variables and labels in the final shader.", SGUILayout.Styles.GrayMiniLabelWrap); } } using (new SGUILayout.IndentedLine(margin)) { EditorGUI.BeginChangeCheck(); matLayer.UseContrastProperty = EditorGUILayout.Toggle(TCP2_GUI.TempContent("Add Contrast Property", "Automatically add a range property to adjust the layer contrast in the material inspector"), matLayer.UseContrastProperty); } using (new SGUILayout.IndentedLine(margin)) { matLayer.UseNoiseProperty = EditorGUILayout.Toggle(TCP2_GUI.TempContent("Add Noise Property", "Automatically add a properties to adjust the layer based on a noise texture"), matLayer.UseNoiseProperty); if (EditorGUI.EndChangeCheck()) { spChange = true; } if (GUILayout.Button(TCP2_GUI.TempContent("Load Source Preset "), EditorStyles.miniPullDown, GUILayout.ExpandWidth(false))) { matLayer.ShowPresetsMenu(); } } matLayer.sourceShaderProperty.ShowGUILayout(margin); if (matLayer.UseContrastProperty) { matLayer.contrastProperty.ShowGUILayout(margin); } if (matLayer.UseNoiseProperty) { matLayer.noiseProperty.ShowGUILayout(margin); } } } EditorGUILayout.EndVertical(); }; if (materialLayers.Count == 0) { if (TCP2_GUI.HelpBoxWithButton("No Material Layers defined.", "Add", 48)) { materialLayers.Add(new MaterialLayer()); _materialLayersNames = null; spChange = true; } } else { matLayersLayoutList.DoLayoutList(DrawMaterialLayer, materialLayers, new RectOffset(2, 0, 0, 2)); CustomMaterialPropertiesGUI(); } shaderPropertiesChange = spChange; } void CustomMaterialPropertiesGUI() { GUILayout.Space(4); TCP2_GUI.SeparatorSimple(); GUILayout.Label("Custom Material Properties", EditorStyles.boldLabel); GUILayout.Space(2); if (ShaderGenerator2.ContextualHelpBox( "You can define your own material properties here, that can then be shared between multiple Shader Properties. For example, this can allow you to pack textures however you want, having a mask for each R,G,B,A channel.", "custommaterialproperties")) { GUILayout.Space(4); } if (customMaterialPropertiesList == null || customMaterialPropertiesList.Count == 0) { if (TCP2_GUI.HelpBoxWithButton("No custom material properties defined.", "Add", 48)) { ShowCustomMaterialPropertyMenu(0); } } else { //button callbacks ShaderProperty.CustomMaterialProperty.ButtonClick onAdd = index => ShowCustomMaterialPropertyMenu(index); ShaderProperty.CustomMaterialProperty.ButtonClick onRemove = index => { customMaterialPropertiesList[index].WillBeRemoved(); customMaterialPropertiesList.RemoveAt(index); }; //draw element callback Action<int, float> DrawCustomTextureItem = (index, margin) => { customMaterialPropertiesList[index].ShowGUILayout(index, onAdd, onRemove); }; customTexturesLayoutList.DoLayoutList(DrawCustomTextureItem, customMaterialPropertiesList, new RectOffset(2, 0, 0, 2)); } } void ShowCustomMaterialPropertyMenu(int index) { var menu = new GenericMenu(); var impType = typeof(ShaderProperty.Imp_MaterialProperty); var subTypes = impType.Assembly.GetTypes().Where(type => type.IsSubclassOf(impType)); foreach (var type in subTypes) { var menuLabel = type.GetProperty("MenuLabel", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); string label = (string)menuLabel.GetValue(null, null); label = label.Replace("Material Property/", ""); menu.AddItem(new GUIContent(label), false, OnAddCustomMaterialProperty, new object[] { index, type }); } menu.ShowAsContext(); } void OnAddCustomMaterialProperty(object data) { var array = (object[])data; int index = (int)array[0]; var type = (Type)array[1]; if (customMaterialPropertiesList.Count == 0) { customMaterialPropertiesList.Add(CreateUniqueCustomTexture(type)); } else { customMaterialPropertiesList.Insert(index + 1, CreateUniqueCustomTexture(type)); } ShaderGenerator2.PushUndoState(); } //Get a Shader Property from the list by its name internal ShaderProperty GetShaderPropertyByName(string name) { foreach (var sp in visibleShaderProperties) if (sp.Name == name) return sp; return null; } //Check if the supplied property name is unique internal bool IsUniquePropertyName(string name, IMaterialPropertyName propertyName) { //check existing Shader Properties of Material Property type foreach (var sp in visibleShaderProperties) { foreach (var imp in sp.implementations) { var mp = imp as ShaderProperty.Imp_MaterialProperty; if (mp != null && mp is IMaterialPropertyName && mp != propertyName && !mp.ignoreUniquePropertyName && mp.PropertyName == name) { return false; } } } //check Custom Material Properties foreach (var ct in customMaterialPropertiesList) { if (ct != propertyName && ct.PropertyName == name) { return false; } } return true; } ShaderProperty.CustomMaterialProperty CreateUniqueCustomTexture(Type impType) { return new ShaderProperty.CustomMaterialProperty(this.customMaterialPropertyShaderProperty, impType); } internal void ClearShaderProperties() { this.cachedShaderProperties.Clear(); this.visibleShaderProperties.Clear(); } //Update available Shader Properties based on conditions internal void UpdateShaderProperties(Template template) { //Add Unity versions to features #if UNITY_5_4_OR_NEWER Utils.AddIfMissing(Features, "UNITY_5_4"); #endif #if UNITY_5_5_OR_NEWER Utils.AddIfMissing(Features, "UNITY_5_5"); #endif #if UNITY_5_6_OR_NEWER Utils.AddIfMissing(Features, "UNITY_5_6"); #endif #if UNITY_2017_1_OR_NEWER Utils.AddIfMissing(this.Features, "UNITY_2017_1"); #endif #if UNITY_2018_1_OR_NEWER Utils.AddIfMissing(this.Features, "UNITY_2018_1"); #endif #if UNITY_2018_2_OR_NEWER Utils.AddIfMissing(this.Features, "UNITY_2018_2"); #endif #if UNITY_2018_3_OR_NEWER Utils.AddIfMissing(this.Features, "UNITY_2018_3"); #endif #if UNITY_2019_1_OR_NEWER Utils.AddIfMissing(this.Features, "UNITY_2019_1"); #endif #if UNITY_2019_2_OR_NEWER Utils.AddIfMissing(this.Features, "UNITY_2019_2"); #endif #if UNITY_2019_3_OR_NEWER Utils.AddIfMissing(this.Features, "UNITY_2019_3"); #endif #if UNITY_2019_4_OR_NEWER Utils.AddIfMissing(this.Features, "UNITY_2019_4"); #endif #if UNITY_2020_1_OR_NEWER Utils.AddIfMissing(this.Features, "UNITY_2020_1"); #endif #if UNITY_2021_1_OR_NEWER Utils.AddIfMissing(this.Features, "UNITY_2021_1"); #endif #if UNITY_2021_2_OR_NEWER Utils.AddIfMissing(this.Features, "UNITY_2021_2"); #endif #if UNITY_2022_2_OR_NEWER Utils.AddIfMissing(this.Features, "UNITY_2022_2"); #endif var parsedLines = template.GetParsedLinesFromConditions(this, null, null); //Clear arrays: will be refilled with the template's shader properties visibleShaderProperties.Clear(); Dictionary<int, GUIContent> shaderPropertiesHeaders; visibleShaderProperties.AddRange(template.GetConditionalShaderProperties(parsedLines, out shaderPropertiesHeaders)); foreach (var sp in visibleShaderProperties) { //add to the cached properties, to be found back if needed (in case of features change) if (!cachedShaderProperties.Contains(sp)) { cachedShaderProperties.Add(sp); } // resolve linked shader property references now that all visible shader properties are known sp.ResolveShaderPropertyReferences(); sp.onImplementationsChanged -= onShaderPropertyImplementationsChanged; // lazy way to make sure we don't subscribe more than once sp.onImplementationsChanged += onShaderPropertyImplementationsChanged; } // Material Layers foreach (var ml in materialLayers) { visibleShaderProperties.Add(ml.sourceShaderProperty); if (ml.contrastProperty != null) { visibleShaderProperties.Add(ml.contrastProperty); } if (ml.noiseProperty != null) { visibleShaderProperties.Add(ml.noiseProperty); } } //Find used shader properties per pass, to extract used features for each template.UpdateInjectionPoints(parsedLines); shaderPropertiesPerPass = template.FindUsedShaderPropertiesPerPass(parsedLines); // Build list of shader properties and headers for the UI shaderPropertiesUIGroups.Clear(); ShaderPropertyGroup currentGroup = new ShaderPropertyGroup() { shaderProperties = new List<ShaderProperty>(), hasModifiedShaderProperties = false, hasErrors = false, header = null }; Action addCurrentGroup = () => { if (currentGroup.shaderProperties.Count > 0) { shaderPropertiesUIGroups.Add(currentGroup); if (!headersExpanded.ContainsKey(currentGroup.header.text)) { headersExpanded.Add(currentGroup.header.text, false); } } }; for (int i = 0; i < visibleShaderProperties.Count; i++) { if (shaderPropertiesHeaders.ContainsKey(i)) { addCurrentGroup(); currentGroup = new ShaderPropertyGroup() { shaderProperties = new List<ShaderProperty>(), hasModifiedShaderProperties = false, hasErrors = false, header = shaderPropertiesHeaders[i] }; } var shaderProperty = visibleShaderProperties[i]; if (shaderProperty.isMaterialLayerProperty) { // Don't show Material Layer source in regular Shader Properties continue; } currentGroup.shaderProperties.Add(shaderProperty); currentGroup.hasModifiedShaderProperties |= shaderProperty.manuallyModified; currentGroup.hasErrors |= shaderProperty.error; } addCurrentGroup(); } public void UpdateCustomMaterialProperties() { foreach(var cmp in customMaterialPropertiesList) { cmp.implementation.CheckErrors(); } } private void onShaderPropertyImplementationsChanged() { ShaderGenerator2.NeedsShaderPropertiesUpdate = true; ShaderGenerator2.PushUndoState(); } //Process #KEYWORDS line from Template //Use temp features & flags to avoid permanent toggles (e.g. NOTILE_SAMPLING) //As long as the original features are there, they should be triggered each time anyway /// <returns>'true' if a new feature/flag has been added/removed, so that we can reprocess the whole keywords block</returns> internal bool ProcessKeywords(string line, List<string> tempFeatures, List<string> tempFlags, Dictionary<string, List<string>> tempExtraFlags) { if (string.IsNullOrEmpty(line)) { return false; } //Inside valid block var parts = line.Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries); // Fixed expressions first: switch (parts[0]) { case "set": //legacy case "set_keyword": { var keywordValue = parts.Length > 2 ? parts[2] : ""; if (Keywords.ContainsKey(parts[1])) Keywords[parts[1]] = keywordValue; else Keywords.Add(parts[1], keywordValue); break; } case "enable_kw": //legacy case "feature_on": { if (Utils.AddIfMissing(tempFeatures, parts[1])) { return true; } break; } case "disable_kw": //legacy case "feature_off": { if (Utils.RemoveIfExists(tempFeatures, parts[1])) { return true; } break; } case "enable_flag": //legacy case "flag_on": if (tempFlags != null) { if (Utils.AddIfMissing(tempFlags, parts[1])) { return true; } } break; case "disable_flag": //legacy case "flag_off": if (tempFlags != null) { if (Utils.RemoveIfExists(tempFlags, parts[1])) { return true; } } break; default: { // Dynamic afterwards: if (parts[0].StartsWith("flag_on:")) { if (tempExtraFlags == null) { return false; } string block = parts[0].Substring("flag_on:".Length); if (!tempExtraFlags.ContainsKey(block)) tempExtraFlags.Add(block, new List<string>()); if (Utils.AddIfMissing(tempExtraFlags[block], parts[1])) { return true; } } else if (parts[0].StartsWith("flag_off:")) { if (tempExtraFlags == null) { return false; } string block = parts[0].Substring("flag_on:".Length); if (!tempExtraFlags.ContainsKey(block)) { return false; } if (Utils.RemoveIfExists(tempExtraFlags[block], parts[1])) { if (tempExtraFlags[block].Count == 0) { tempExtraFlags.Remove(block); } return true; } } } break; } return false; } // Cache the expanded state of the visible shader properties, to restore them after shader generation/update static HashSet<string> expandedCache; static Dictionary<string, bool> headersExpandedCache; void UI_CacheExpandedState() { headersExpandedCache = new Dictionary<string, bool>(); foreach (var kvp in headersExpanded) { headersExpandedCache.Add(kvp.Key, kvp.Value); } expandedCache = new HashSet<string>(); foreach (var shaderProperty in visibleShaderProperties) { if (shaderProperty.expanded) { expandedCache.Add(shaderProperty.Name); } } } void UI_RestoreExpandedState() { if (expandedCache == null && headersExpandedCache == null) { return; } foreach (var kvp in headersExpandedCache) { if (headersExpanded.ContainsKey(kvp.Key)) { headersExpanded[kvp.Key] = kvp.Value; } else { headersExpanded.Add(kvp.Key, kvp.Value); } } foreach (var shaderProperty in visibleShaderProperties) { if (expandedCache.Contains(shaderProperty.Name)) { shaderProperty.expanded = true; } } expandedCache = null; headersExpandedCache = null; } // Useful callbacks public void OnBeforeGenerateShader() { UI_CacheExpandedState(); } public void OnAfterGenerateShader() { UI_RestoreExpandedState(); } } } }
1
0.937928
1
0.937928
game-dev
MEDIA
0.779743
game-dev,graphics-rendering
0.967234
1
0.967234
rive-app/rive-runtime
2,448
tests/bench/iterate_raw_path.cpp
/* * Copyright 2022 Rive */ #include "bench.hpp" #include "rive/math/raw_path.hpp" #include "rive/math/simd.hpp" using namespace rive; static Vec2D randpt() { return Vec2D(float(rand()), float(rand())) * 100 / (float)RAND_MAX; } // Measure the speed of RawPath iteration. In an attempt to be representative of // algorithms that need to know p0 for lines and cubics, we sum up the midpoints // of lines and cubics. class IterateRawPath : public Bench { public: IterateRawPath() { // Make a random path. srand(0); for (int i = 0; i < 1000000; ++i) { int r = rand() % 22; if (r == 0) { m_path.move(randpt()); } else if (r == 1) { m_path.close(); } else if (r < 12) { m_path.line(randpt()); } else { m_path.cubic(randpt(), randpt(), randpt()); } } } private: int run() const override { float4 midpointsSum{}; float2 startPt{}; for (auto [verb, p] : m_path) { switch (verb) { case PathVerb::move: startPt = simd::load2f(&p[0].x); break; case PathVerb::line: { float4 p0_1 = simd::load4f(&p[0].x); midpointsSum += p0_1 * .5f; break; } case PathVerb::cubic: { float4 p0_1 = simd::load4f(&p[0].x); midpointsSum += p0_1 * float4{.125f, .125f, .75f, .75f}; float4 p2_3 = simd::load4f(&p[2].x); midpointsSum += p2_3 * float4{.75f, .75f, .125f, .125f}; break; } case PathVerb::close: { float4 p0_1; p0_1.xy = simd::load2f(&p[0].x); p0_1.zw = startPt; midpointsSum += p0_1 * .5f; break; } case PathVerb::quad: RIVE_UNREACHABLE(); } } midpointsSum.xy += midpointsSum.zw; return (int)(midpointsSum.x + midpointsSum.y); } RawPath m_path; }; REGISTER_BENCH(IterateRawPath);
1
0.938528
1
0.938528
game-dev
MEDIA
0.614759
game-dev,graphics-rendering
0.974037
1
0.974037
magarena/magarena
2,412
release/Magarena/scripts/Oriss__Samite_Guardian.groovy
def CARD_NAMED_ORISS = new MagicCardFilterImpl() { public boolean accept(final MagicSource source,final MagicPlayer player,final MagicCard target) { return target.getName().equals("Oriss, Samite Guardian"); } public boolean acceptType(final MagicTargetType targetType) { return targetType == MagicTargetType.Hand; } }; def A_CARD_NAMED_ORISS = new MagicTargetChoice( CARD_NAMED_ORISS, MagicTargetHint.None, "a card named Oriss, Samite Guardian from your hand" ); [ new MagicPermanentActivation( new MagicActivationHints(MagicTiming.FirstMain), "Grandeur" ) { @Override public Iterable<? extends MagicEvent> getCostEvent(final MagicPermanent source) { return [new MagicDiscardChosenEvent(source,A_CARD_NAMED_ORISS)]; } @Override public MagicEvent getPermanentEvent(final MagicPermanent source,final MagicPayedCost payedCost) { return new MagicEvent( source, NEG_TARGET_PLAYER, this, "Target player\$ can't cast spells this turn, and creatures that player controls can't attack this turn." ); } @Override public void executeEvent(final MagicGame outerGame, final MagicEvent event) { event.processTargetPlayer(outerGame, { final MagicPlayer outerPlayer -> outerGame.doAction(new AddStaticAction(new MagicStatic(MagicLayer.Player, MagicStatic.UntilEOT) { @Override public void modPlayer(final MagicPermanent source, final MagicPlayer player) { if (player.getId() == outerPlayer.getId()) { player.setState(MagicPlayerState.CantCastSpells); } } })); outerGame.doAction(new AddStaticAction(new MagicStatic(MagicLayer.Game, MagicStatic.UntilEOT) { @Override public void modGame(final MagicPermanent source, final MagicGame game) { final MagicPlayer p = outerPlayer.map(game); CREATURE_YOU_CONTROL.filter(p) each { it.addAbility(MagicAbility.CannotAttack); } } })) }); } } ]
1
0.890716
1
0.890716
game-dev
MEDIA
0.937761
game-dev
0.843061
1
0.843061
nanshaws/LibgdxTutorial
5,400
chapter8/gdx-ai-tests/src/com/badlogic/gdx/ai/tests/fsm/BobState.java
/******************************************************************************* * Copyright 2014 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.ai.tests.fsm; import com.badlogic.gdx.ai.GdxAI; import com.badlogic.gdx.ai.fsm.State; import com.badlogic.gdx.ai.msg.MessageManager; import com.badlogic.gdx.ai.msg.Telegram; /** @author davebaol */ public enum BobState implements State<Bob> { ENTER_MINE_AND_DIG_FOR_NUGGET() { @Override public void enter (Bob bob) { // if the miner is not already located at the goldmine, he must // change location to the gold mine if (bob.getLocation() != Location.GOLD_MINE) { talk(bob, "Walkin' to the goldmine"); bob.setLocation(Location.GOLD_MINE); } } @Override public void update (Bob bob) { // Now bob is at the goldmine he digs for gold until he // is carrying in excess of MAX_NUGGETS. If he gets thirsty during // his digging he packs up work for a while and changes state to // go to the saloon for a whiskey. bob.addToGoldCarried(1); bob.increaseFatigue(); talk(bob, "Pickin' up a nugget"); // if enough gold mined, go and put it in the bank if (bob.isPocketsFull()) { bob.getStateMachine().changeState(VISIT_BANK_AND_DEPOSIT_GOLD); } if (bob.isThirsty()) { bob.getStateMachine().changeState(QUENCH_THIRST); } } @Override public void exit (Bob bob) { talk(bob, "Ah'm leavin' the goldmine with mah pockets full o' sweet gold"); } }, GO_HOME_AND_SLEEP_TILL_RESTED() { @Override public void enter (Bob bob) { if (bob.getLocation() != Location.SHACK) { talk(bob, "Walkin' home"); bob.setLocation(Location.SHACK); // Let Elsa know I'm home MessageManager.getInstance().dispatchMessage( // 0.0f, // time delay bob, // ID of sender bob.elsa, // ID of recipient MessageType.HI_HONEY_I_M_HOME, // the message null); } } @Override public void update (Bob bob) { // if miner is not fatigued start to dig for nuggets again. if (!bob.isFatigued()) { talk(bob, "All mah fatigue has drained away. Time to find more gold!"); bob.getStateMachine().changeState(ENTER_MINE_AND_DIG_FOR_NUGGET); } else { // sleep bob.decreaseFatigue(); talk(bob, "ZZZZ... "); } } @Override public void exit (Bob bob) { } @Override public boolean onMessage (Bob bob, Telegram telegram) { if (telegram.message == MessageType.STEW_READY) { talk(bob, "Message STEW_READY handled at time: " + GdxAI.getTimepiece().getTime()); talk(bob, "Okay Hun, ahm a comin'!"); bob.getStateMachine().changeState(EAT_STEW); return true; } return false; // send message to global message handler } }, QUENCH_THIRST() { @Override public void enter (Bob bob) { if (bob.getLocation() != Location.SALOON) { bob.setLocation(Location.SALOON); talk(bob, "Boy, ah sure is thusty! Walking to the saloon"); } } @Override public void update (Bob bob) { bob.buyAndDrinkAWhiskey(); talk(bob, "That's mighty fine sippin liquer"); bob.getStateMachine().changeState(ENTER_MINE_AND_DIG_FOR_NUGGET); } @Override public void exit (Bob bob) { talk(bob, "Leaving the saloon, feelin' good"); } }, VISIT_BANK_AND_DEPOSIT_GOLD() { @Override public void enter (Bob bob) { // On entry bob makes sure he is located at the bank if (bob.getLocation() != Location.BANK) { talk(bob, "Goin' to the bank. Yes siree"); bob.setLocation(Location.BANK); } } @Override public void update (Bob bob) { // Deposit the gold bob.addToWealth(bob.getGoldCarried()); bob.setGoldCarried(0); talk(bob, "Depositing gold. Total savings now: " + bob.getWealth()); // Wealthy enough to have a well earned rest? if (bob.getWealth() >= Bob.COMFORT_LEVEL) { talk(bob, "WooHoo! Rich enough for now. Back home to mah li'lle lady"); bob.getStateMachine().changeState(GO_HOME_AND_SLEEP_TILL_RESTED); } else { // otherwise get more gold bob.getStateMachine().changeState(ENTER_MINE_AND_DIG_FOR_NUGGET); } } @Override public void exit (Bob bob) { talk(bob, "Leavin' the bank"); } }, EAT_STEW() { @Override public void enter (Bob bob) { talk(bob, "Smells Reaaal goood Elsa!"); } @Override public void update (Bob bob) { talk(bob, "Tastes real good too!"); bob.getStateMachine().revertToPreviousState(); } @Override public void exit (Bob bob) { talk(bob, "Thankya li'lle lady. Ah better get back to whatever ah wuz doin'"); } }; @Override public boolean onMessage (Bob bob, Telegram telegram) { return false; } protected void talk (Bob bob, String msg) { GdxAI.getLogger().info(bob.getClass().getSimpleName(), msg); } }
1
0.548036
1
0.548036
game-dev
MEDIA
0.894606
game-dev
0.856522
1
0.856522
MATTYOneInc/AionEncomBase_Java8
2,390
AL-Game/src/com/aionemu/gameserver/skillengine/effect/SearchEffect.java
/* * * Encom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Encom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with Encom. If not, see <http://www.gnu.org/licenses/>. */ package com.aionemu.gameserver.skillengine.effect; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import com.aionemu.gameserver.configs.main.SecurityConfig; import com.aionemu.gameserver.model.gameobjects.Creature; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.model.gameobjects.state.CreatureSeeState; import com.aionemu.gameserver.network.aion.serverpackets.SM_PLAYER_STATE; import com.aionemu.gameserver.services.player.PlayerVisualStateService; import com.aionemu.gameserver.skillengine.model.Effect; import com.aionemu.gameserver.utils.PacketSendUtility; /** * @author Sweetkr */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SearchEffect") public class SearchEffect extends EffectTemplate { @XmlAttribute protected CreatureSeeState state; @Override public void applyEffect(Effect effect) { effect.addToEffectedController(); } @Override public void endEffect(Effect effect) { Creature effected = effect.getEffected(); effected.unsetSeeState(state); if (SecurityConfig.INVIS && effected instanceof Player) { PlayerVisualStateService.seeValidate((Player) effected); } PacketSendUtility.broadcastPacketAndReceive(effected, new SM_PLAYER_STATE(effected)); } @Override public void startEffect(final Effect effect) { final Creature effected = effect.getEffected(); effected.setSeeState(state); if (SecurityConfig.INVIS && effected instanceof Player) { PlayerVisualStateService.seeValidate((Player) effected); } PacketSendUtility.broadcastPacketAndReceive(effected, new SM_PLAYER_STATE(effected)); } }
1
0.639644
1
0.639644
game-dev
MEDIA
0.91274
game-dev
0.711187
1
0.711187
opentibiabr/canary
5,450
data-otservbr-global/npc/narsai.lua
local internalNpcName = "Narsai" local npcType = Game.createNpcType(internalNpcName) local npcConfig = {} npcConfig.name = internalNpcName npcConfig.description = internalNpcName npcConfig.health = 100 npcConfig.maxHealth = npcConfig.health npcConfig.walkInterval = 2000 npcConfig.walkRadius = 2 npcConfig.outfit = { lookType = 1199, lookHead = 114, lookBody = 74, lookLegs = 10, lookFeet = 79, lookAddons = 1, } npcConfig.flags = { floorchange = false, } local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) npcType.onThink = function(npc, interval) npcHandler:onThink(npc, interval) end npcType.onAppear = function(npc, creature) npcHandler:onAppear(npc, creature) end npcType.onDisappear = function(npc, creature) npcHandler:onDisappear(npc, creature) end npcType.onMove = function(npc, creature, fromPosition, toPosition) npcHandler:onMove(npc, creature, fromPosition, toPosition) end npcType.onSay = function(npc, creature, type, message) npcHandler:onSay(npc, creature, type, message) end npcType.onCloseChannel = function(npc, creature) npcHandler:onCloseChannel(npc, creature) end local function greetCallback(npc, creature) local player = Player(creature) local playerId = player:getId() if player:getStorageValue(Storage.Quest.U12_20.KilmareshQuest.First.Access) < 1 then npcHandler:setMessage(MESSAGE_GREET, "How could I help you?") -- It needs to be revised, it's not the same as the global npcHandler:setTopic(playerId, 1) elseif (player:getStorageValue(Storage.Quest.U12_20.KilmareshQuest.First.JamesfrancisTask) >= 0 and player:getStorageValue(Storage.Quest.U12_20.KilmareshQuest.First.JamesfrancisTask) <= 50) and player:getStorageValue(Storage.Quest.U12_20.KilmareshQuest.First.Mission) < 3 then npcHandler:setMessage(MESSAGE_GREET, "How could I help you?") -- It needs to be revised, it's not the same as the global npcHandler:setTopic(playerId, 15) elseif player:getStorageValue(Storage.Quest.U12_20.KilmareshQuest.First.Mission) == 4 then npcHandler:setMessage(MESSAGE_GREET, "How could I help you?") -- It needs to be revised, it's not the same as the global player:setStorageValue(Storage.Quest.U12_20.KilmareshQuest.First.Mission, 5) npcHandler:setTopic(playerId, 20) end return true end local function creatureSayCallback(npc, creature, type, message) local player = Player(creature) local playerId = player:getId() if not npcHandler:checkInteraction(npc, creature) then return false end if MsgContains(message, "mission") and player:getStorageValue(Storage.Quest.U12_20.KilmareshQuest.Eighth.Narsai) == 1 then if player:getStorageValue(Storage.Quest.U12_20.KilmareshQuest.Eighth.Narsai) == 1 then npcHandler:say({ "Could you help me do a ritual?" }, npc, creature) -- It needs to be revised, it's not the same as the global npcHandler:setTopic(playerId, 1) npcHandler:setTopic(playerId, 1) end elseif MsgContains(message, "yes") and npcHandler:getTopic(playerId) == 1 and player:getStorageValue(Storage.Quest.U12_20.KilmareshQuest.Eighth.Narsai) == 1 then if player:getStorageValue(Storage.Quest.U12_20.KilmareshQuest.Eighth.Narsai) == 1 then player:addItem(31714, 1) npcHandler:say({ "Here is the list of ingredients that are missing to complete the ritual. " }, npc, creature) -- It needs to be revised, it's not the same as the global player:setStorageValue(Storage.Quest.U12_20.KilmareshQuest.Eighth.Narsai, 2) npcHandler:setTopic(playerId, 2) npcHandler:setTopic(playerId, 2) else npcHandler:say({ "Sorry." }, npc, creature) -- It needs to be revised, it's not the same as the global end end if MsgContains(message, "mission") and player:getStorageValue(Storage.Quest.U12_20.KilmareshQuest.Eighth.Narsai) == 2 then if player:getStorageValue(Storage.Quest.U12_20.KilmareshQuest.Eighth.Narsai) == 2 then npcHandler:say({ "Did you bring all the materials I informed you about?" }, npc, creature) -- It needs to be revised, it's not the same as the global npcHandler:setTopic(playerId, 3) npcHandler:setTopic(playerId, 3) end elseif MsgContains(message, "yes") and npcHandler:getTopic(playerId) == 3 and player:getStorageValue(Storage.Quest.U12_20.KilmareshQuest.Eighth.Narsai) == 2 then if player:getStorageValue(Storage.Quest.U12_20.KilmareshQuest.Eighth.Narsai) == 2 and player:getItemById(31335, 10) and player:getItemById(10279, 2) and player:getItemById(31332, 5) then player:removeItem(31335, 10) player:removeItem(10279, 2) player:removeItem(31332, 5) npcHandler:say({ "Thank you this stage of the ritual is complete." }, npc, creature) -- It needs to be revised, it's not the same as the global player:setStorageValue(Storage.Quest.U12_20.KilmareshQuest.Eighth.Narsai, 3) npcHandler:setTopic(playerId, 4) npcHandler:setTopic(playerId, 4) else npcHandler:say({ "Sorry." }, npc, creature) -- It needs to be revised, it's not the same as the global end end return true end npcHandler:setMessage(MESSAGE_WALKAWAY, "Well, bye then.") npcHandler:setCallback(CALLBACK_SET_INTERACTION, onAddFocus) npcHandler:setCallback(CALLBACK_REMOVE_INTERACTION, onReleaseFocus) npcHandler:setCallback(CALLBACK_GREET, greetCallback) npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new(), npcConfig.name, true, true, true) -- npcType registering the npcConfig table npcType:register(npcConfig)
1
0.939446
1
0.939446
game-dev
MEDIA
0.955828
game-dev
0.931489
1
0.931489
mangosArchives/Mangos-Zero-server-old
9,169
src/game/Level0.cpp
/* * Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "Common.h" #include "Database/DatabaseEnv.h" #include "World.h" #include "Player.h" #include "Opcodes.h" #include "Chat.h" #include "ObjectAccessor.h" #include "Language.h" #include "AccountMgr.h" #include "ScriptMgr.h" #include "SystemConfig.h" #include "revision.h" #include "revision_nr.h" #include "Util.h" bool ChatHandler::HandleHelpCommand(char* args) { if (!*args) { ShowHelpForCommand(getCommandTable(), "help"); ShowHelpForCommand(getCommandTable(), ""); } else { if (!ShowHelpForCommand(getCommandTable(), args)) SendSysMessage(LANG_NO_CMD); } return true; } bool ChatHandler::HandleCommandsCommand(char* /*args*/) { ShowHelpForCommand(getCommandTable(), ""); return true; } bool ChatHandler::HandleAccountCommand(char* args) { // let show subcommands at unexpected data in args if (*args) return false; AccountTypes gmlevel = GetAccessLevel(); PSendSysMessage(LANG_ACCOUNT_LEVEL, uint32(gmlevel)); return true; } bool ChatHandler::HandleStartCommand(char* /*args*/) { Player *chr = m_session->GetPlayer(); if (chr->IsTaxiFlying()) { SendSysMessage(LANG_YOU_IN_FLIGHT); SetSentErrorMessage(true); return false; } if (chr->isInCombat()) { SendSysMessage(LANG_YOU_IN_COMBAT); SetSentErrorMessage(true); return false; } // cast spell Stuck chr->CastSpell(chr, 7355, false); return true; } bool ChatHandler::HandleServerInfoCommand(char* /*args*/) { uint32 activeClientsNum = sWorld.GetActiveSessionCount(); uint32 queuedClientsNum = sWorld.GetQueuedSessionCount(); uint32 maxActiveClientsNum = sWorld.GetMaxActiveSessionCount(); uint32 maxQueuedClientsNum = sWorld.GetMaxQueuedSessionCount(); std::string str = secsToTimeString(sWorld.GetUptime()); char const* full; if (m_session) full = _FULLVERSION(REVISION_DATE, REVISION_TIME, REVISION_NR, "|cffffffff|Hurl:" REVISION_ID "|h" REVISION_ID "|h|r"); else full = _FULLVERSION(REVISION_DATE, REVISION_TIME, REVISION_NR, REVISION_ID); SendSysMessage(full); if (sScriptMgr.IsScriptLibraryLoaded()) { char const* ver = sScriptMgr.GetScriptLibraryVersion(); if (ver && *ver) PSendSysMessage(LANG_USING_SCRIPT_LIB, ver); else SendSysMessage(LANG_USING_SCRIPT_LIB_UNKNOWN); } else SendSysMessage(LANG_USING_SCRIPT_LIB_NONE); PSendSysMessage(LANG_USING_WORLD_DB, sWorld.GetDBVersion()); PSendSysMessage(LANG_USING_EVENT_AI, sWorld.GetCreatureEventAIVersion()); PSendSysMessage(LANG_CONNECTED_USERS, activeClientsNum, maxActiveClientsNum, queuedClientsNum, maxQueuedClientsNum); PSendSysMessage(LANG_UPTIME, str.c_str()); return true; } bool ChatHandler::HandleDismountCommand(char* /*args*/) { //If player is not mounted, so go out :) if (!m_session->GetPlayer()->IsMounted()) { SendSysMessage(LANG_CHAR_NON_MOUNTED); SetSentErrorMessage(true); return false; } if (m_session->GetPlayer()->IsTaxiFlying()) { SendSysMessage(LANG_YOU_IN_FLIGHT); SetSentErrorMessage(true); return false; } m_session->GetPlayer()->Unmount(); m_session->GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_MOUNTED); return true; } bool ChatHandler::HandleSaveCommand(char* /*args*/) { Player *player = m_session->GetPlayer(); // save GM account without delay and output message (testing, etc) if (GetAccessLevel() > SEC_PLAYER) { player->SaveToDB(); SendSysMessage(LANG_PLAYER_SAVED); return true; } // save or plan save after 20 sec (logout delay) if current next save time more this value and _not_ output any messages to prevent cheat planning uint32 save_interval = sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE); if (save_interval == 0 || (save_interval > 20 * IN_MILLISECONDS && player->GetSaveTimer() <= save_interval - 20 * IN_MILLISECONDS)) player->SaveToDB(); return true; } bool ChatHandler::HandleGMListIngameCommand(char* /*args*/) { std::list< std::pair<std::string, bool> > names; { HashMapHolder<Player>::ReadGuard g(HashMapHolder<Player>::GetLock()); HashMapHolder<Player>::MapType &m = sObjectAccessor.GetPlayers(); for (HashMapHolder<Player>::MapType::const_iterator itr = m.begin(); itr != m.end(); ++itr) { AccountTypes itr_sec = itr->second->GetSession()->GetSecurity(); if ((itr->second->isGameMaster() || (itr_sec > SEC_PLAYER && itr_sec <= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_GM_LEVEL_IN_GM_LIST))) && (!m_session || itr->second->IsVisibleGloballyFor(m_session->GetPlayer()))) names.push_back(std::make_pair<std::string, bool>(GetNameLink(itr->second), itr->second->isAcceptWhispers())); } } if (!names.empty()) { SendSysMessage(LANG_GMS_ON_SRV); char const* accepts = GetMangosString(LANG_GM_ACCEPTS_WHISPER); char const* not_accept = GetMangosString(LANG_GM_NO_WHISPER); for (std::list<std::pair< std::string, bool> >::const_iterator iter = names.begin(); iter != names.end(); ++iter) PSendSysMessage("%s - %s", iter->first.c_str(), iter->second ? accepts : not_accept); } else SendSysMessage(LANG_GMS_NOT_LOGGED); return true; } bool ChatHandler::HandleAccountPasswordCommand(char* args) { // allow use from RA, but not from console (not have associated account id) if (!GetAccountId()) { SendSysMessage(LANG_RA_ONLY_COMMAND); SetSentErrorMessage(true); return false; } // allow or quoted string with possible spaces or literal without spaces char *old_pass = ExtractQuotedOrLiteralArg(&args); char *new_pass = ExtractQuotedOrLiteralArg(&args); char *new_pass_c = ExtractQuotedOrLiteralArg(&args); if (!old_pass || !new_pass || !new_pass_c) return false; std::string password_old = old_pass; std::string password_new = new_pass; std::string password_new_c = new_pass_c; if (password_new != password_new_c) { SendSysMessage(LANG_NEW_PASSWORDS_NOT_MATCH); SetSentErrorMessage(true); return false; } if (!sAccountMgr.CheckPassword(GetAccountId(), password_old)) { SendSysMessage(LANG_COMMAND_WRONGOLDPASSWORD); SetSentErrorMessage(true); return false; } AccountOpResult result = sAccountMgr.ChangePassword(GetAccountId(), password_new); switch (result) { case AOR_OK: SendSysMessage(LANG_COMMAND_PASSWORD); break; case AOR_PASS_TOO_LONG: SendSysMessage(LANG_PASSWORD_TOO_LONG); SetSentErrorMessage(true); return false; case AOR_NAME_NOT_EXIST: // not possible case, don't want get account name for output default: SendSysMessage(LANG_COMMAND_NOTCHANGEPASSWORD); SetSentErrorMessage(true); return false; } // OK, but avoid normal report for hide passwords, but log use command for anyone LogCommand(".account password *** *** ***"); SetSentErrorMessage(true); return false; } bool ChatHandler::HandleAccountLockCommand(char* args) { // allow use from RA, but not from console (not have associated account id) if (!GetAccountId()) { SendSysMessage(LANG_RA_ONLY_COMMAND); SetSentErrorMessage(true); return false; } bool value; if (!ExtractOnOff(&args, value)) { SendSysMessage(LANG_USE_BOL); SetSentErrorMessage(true); return false; } if (value) { LoginDatabase.PExecute("UPDATE account SET locked = '1' WHERE id = '%u'", GetAccountId()); PSendSysMessage(LANG_COMMAND_ACCLOCKLOCKED); } else { LoginDatabase.PExecute("UPDATE account SET locked = '0' WHERE id = '%u'", GetAccountId()); PSendSysMessage(LANG_COMMAND_ACCLOCKUNLOCKED); } return true; } /// Display the 'Message of the day' for the realm bool ChatHandler::HandleServerMotdCommand(char* /*args*/) { PSendSysMessage(LANG_MOTD_CURRENT, sWorld.GetMotd()); return true; }
1
0.971418
1
0.971418
game-dev
MEDIA
0.491095
game-dev
0.974008
1
0.974008
darkforest-eth/eth
27,499
contracts/libraries/LibGameUtils.sol
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; // External contract imports import {DFArtifactFacet} from "../facets/DFArtifactFacet.sol"; // Library imports import {ABDKMath64x64} from "../vendor/libraries/ABDKMath64x64.sol"; // Storage imports import {LibStorage, GameStorage, GameConstants, SnarkConstants} from "./LibStorage.sol"; import { Biome, SpaceType, Planet, PlanetType, PlanetEventType, Artifact, ArtifactType, ArtifactRarity, Upgrade, PlanetDefaultStats } from "../DFTypes.sol"; library LibGameUtils { function gs() internal pure returns (GameStorage storage) { return LibStorage.gameStorage(); } function gameConstants() internal pure returns (GameConstants storage) { return LibStorage.gameConstants(); } function snarkConstants() internal pure returns (SnarkConstants storage) { return LibStorage.snarkConstants(); } // inclusive on both ends function _calculateByteUInt( bytes memory _b, uint256 _startByte, uint256 _endByte ) public pure returns (uint256 _byteUInt) { for (uint256 i = _startByte; i <= _endByte; i++) { _byteUInt += uint256(uint8(_b[i])) * (256**(_endByte - i)); } } function _locationIdValid(uint256 _loc) public view returns (bool) { return (_loc < (21888242871839275222246405745257275088548364400416034343698204186575808495617 / gameConstants().PLANET_RARITY)); } // if you don't check the public input snark perlin config values, then a player could specify a planet with for example the wrong PLANETHASH_KEY and the SNARK would verify but they'd have created an invalid planet. // the zkSNARK verification function checks that the SNARK proof is valid; a valid proof might be "i know the existence of a planet at secret coords with address 0x123456... and mimc key 42". but if this universe's mimc key is 43 this is still an invalid planet, so we have to check that this SNARK proof is a proof for the right mimc key (and spacetype key, perlin length scale, etc.) function revertIfBadSnarkPerlinFlags(uint256[5] memory perlinFlags, bool checkingBiome) public view returns (bool) { require(perlinFlags[0] == snarkConstants().PLANETHASH_KEY, "bad planethash mimc key"); if (checkingBiome) { require(perlinFlags[1] == snarkConstants().BIOMEBASE_KEY, "bad spacetype mimc key"); } else { require(perlinFlags[1] == snarkConstants().SPACETYPE_KEY, "bad spacetype mimc key"); } require(perlinFlags[2] == snarkConstants().PERLIN_LENGTH_SCALE, "bad perlin length scale"); require((perlinFlags[3] == 1) == snarkConstants().PERLIN_MIRROR_X, "bad perlin mirror x"); require((perlinFlags[4] == 1) == snarkConstants().PERLIN_MIRROR_Y, "bad perlin mirror y"); return true; } function spaceTypeFromPerlin(uint256 perlin) public view returns (SpaceType) { if (perlin >= gameConstants().PERLIN_THRESHOLD_3) { return SpaceType.DEAD_SPACE; } else if (perlin >= gameConstants().PERLIN_THRESHOLD_2) { return SpaceType.DEEP_SPACE; } else if (perlin >= gameConstants().PERLIN_THRESHOLD_1) { return SpaceType.SPACE; } return SpaceType.NEBULA; } function _getPlanetLevelTypeAndSpaceType(uint256 _location, uint256 _perlin) public view returns ( uint256, PlanetType, SpaceType ) { SpaceType spaceType = spaceTypeFromPerlin(_perlin); bytes memory _b = abi.encodePacked(_location); // get the uint value of byte 4 - 6 uint256 _planetLevelUInt = _calculateByteUInt(_b, 4, 6); uint256 level; // reverse-iterate thresholds and return planet type accordingly for (uint256 i = (gs().planetLevelThresholds.length - 1); i >= 0; i--) { if (_planetLevelUInt < gs().planetLevelThresholds[i]) { level = i; break; } } if (spaceType == SpaceType.NEBULA && level > 4) { // clip level to <= 3 if in nebula level = 4; } if (spaceType == SpaceType.SPACE && level > 5) { // clip level to <= 4 if in space level = 5; } // clip level to <= MAX_NATURAL_PLANET_LEVEL if (level > gameConstants().MAX_NATURAL_PLANET_LEVEL) { level = gameConstants().MAX_NATURAL_PLANET_LEVEL; } // get planet type PlanetType planetType = PlanetType.PLANET; uint8[5] memory weights = gameConstants().PLANET_TYPE_WEIGHTS[uint8(spaceType)][level]; uint256[5] memory thresholds; { uint256 weightSum; for (uint8 i = 0; i < weights.length; i++) { weightSum += weights[i]; } thresholds[0] = weightSum - weights[0]; for (uint8 i = 1; i < weights.length; i++) { thresholds[i] = thresholds[i - 1] - weights[i]; } for (uint8 i = 0; i < weights.length; i++) { thresholds[i] = (thresholds[i] * 256) / weightSum; } } uint8 typeByte = uint8(_b[8]); for (uint8 i = 0; i < thresholds.length; i++) { if (typeByte >= thresholds[i]) { planetType = PlanetType(i); break; } } return (level, planetType, spaceType); } function _getRadius() public view returns (uint256) { uint256 nPlayers = gs().playerIds.length; uint256 worldRadiusMin = gameConstants().WORLD_RADIUS_MIN; uint256 target4 = gs().initializedPlanetCountByLevel[4] + 20 * nPlayers; uint256 targetRadiusSquared4 = (target4 * gs().cumulativeRarities[4] * 100) / 314; uint256 r4 = ABDKMath64x64.toUInt(ABDKMath64x64.sqrt(ABDKMath64x64.fromUInt(targetRadiusSquared4))); if (r4 < worldRadiusMin) { return worldRadiusMin; } else { return r4; } } function _randomArtifactTypeAndLevelBonus( uint256 artifactSeed, Biome biome, SpaceType spaceType ) internal pure returns (ArtifactType, uint256) { uint256 lastByteOfSeed = artifactSeed % 0xFF; uint256 secondLastByteOfSeed = ((artifactSeed - lastByteOfSeed) / 256) % 0xFF; ArtifactType artifactType = ArtifactType.Pyramid; if (lastByteOfSeed < 39) { artifactType = ArtifactType.Monolith; } else if (lastByteOfSeed < 78) { artifactType = ArtifactType.Colossus; } // else if (lastByteOfSeed < 117) { // artifactType = ArtifactType.Spaceship; // } else if (lastByteOfSeed < 156) { artifactType = ArtifactType.Pyramid; } else if (lastByteOfSeed < 171) { artifactType = ArtifactType.Wormhole; } else if (lastByteOfSeed < 186) { artifactType = ArtifactType.PlanetaryShield; } else if (lastByteOfSeed < 201) { artifactType = ArtifactType.PhotoidCannon; } else if (lastByteOfSeed < 216) { artifactType = ArtifactType.BloomFilter; } else if (lastByteOfSeed < 231) { artifactType = ArtifactType.BlackDomain; } else { if (biome == Biome.Ice) { artifactType = ArtifactType.PlanetaryShield; } else if (biome == Biome.Lava) { artifactType = ArtifactType.PhotoidCannon; } else if (biome == Biome.Wasteland) { artifactType = ArtifactType.BloomFilter; } else if (biome == Biome.Corrupted) { artifactType = ArtifactType.BlackDomain; } else { artifactType = ArtifactType.Wormhole; } artifactType = ArtifactType.PhotoidCannon; } uint256 bonus = 0; if (secondLastByteOfSeed < 4) { bonus = 2; } else if (secondLastByteOfSeed < 16) { bonus = 1; } return (artifactType, bonus); } // TODO v0.6: handle corrupted biomes function _getBiome(SpaceType spaceType, uint256 biomebase) public view returns (Biome) { if (spaceType == SpaceType.DEAD_SPACE) { return Biome.Corrupted; } uint256 biome = 3 * uint256(spaceType); if (biomebase < gameConstants().BIOME_THRESHOLD_1) biome += 1; else if (biomebase < gameConstants().BIOME_THRESHOLD_2) biome += 2; else biome += 3; return Biome(biome); } function defaultUpgrade() public pure returns (Upgrade memory) { return Upgrade({ popCapMultiplier: 100, popGroMultiplier: 100, rangeMultiplier: 100, speedMultiplier: 100, defMultiplier: 100 }); } function timeDelayUpgrade(Artifact memory artifact) public pure returns (Upgrade memory) { if (artifact.artifactType == ArtifactType.PhotoidCannon) { uint256[6] memory range = [uint256(100), 200, 200, 200, 200, 200]; uint256[6] memory speedBoosts = [uint256(100), 500, 1000, 1500, 2000, 2500]; return Upgrade({ popCapMultiplier: 100, popGroMultiplier: 100, rangeMultiplier: range[uint256(artifact.rarity)], speedMultiplier: speedBoosts[uint256(artifact.rarity)], defMultiplier: 100 }); } return defaultUpgrade(); } /** The upgrade applied to a movement when abandoning a planet. */ function abandoningUpgrade() public view returns (Upgrade memory) { return Upgrade({ popCapMultiplier: 100, popGroMultiplier: 100, rangeMultiplier: gameConstants().ABANDON_RANGE_CHANGE_PERCENT, speedMultiplier: gameConstants().ABANDON_SPEED_CHANGE_PERCENT, defMultiplier: 100 }); } function _getUpgradeForArtifact(Artifact memory artifact) public pure returns (Upgrade memory) { if (artifact.artifactType == ArtifactType.PlanetaryShield) { uint256[6] memory defenseMultipliersPerRarity = [uint256(100), 150, 200, 300, 450, 650]; return Upgrade({ popCapMultiplier: 100, popGroMultiplier: 100, rangeMultiplier: 20, speedMultiplier: 20, defMultiplier: defenseMultipliersPerRarity[uint256(artifact.rarity)] }); } if (artifact.artifactType == ArtifactType.PhotoidCannon) { uint256[6] memory def = [uint256(100), 50, 40, 30, 20, 10]; return Upgrade({ popCapMultiplier: 100, popGroMultiplier: 100, rangeMultiplier: 100, speedMultiplier: 100, defMultiplier: def[uint256(artifact.rarity)] }); } if (uint256(artifact.artifactType) >= 5) { return Upgrade({ popCapMultiplier: 100, popGroMultiplier: 100, rangeMultiplier: 100, speedMultiplier: 100, defMultiplier: 100 }); } Upgrade memory ret = Upgrade({ popCapMultiplier: 100, popGroMultiplier: 100, rangeMultiplier: 100, speedMultiplier: 100, defMultiplier: 100 }); if (artifact.artifactType == ArtifactType.Monolith) { ret.popCapMultiplier += 5; ret.popGroMultiplier += 5; } else if (artifact.artifactType == ArtifactType.Colossus) { ret.speedMultiplier += 5; } else if (artifact.artifactType == ArtifactType.Spaceship) { ret.rangeMultiplier += 5; } else if (artifact.artifactType == ArtifactType.Pyramid) { ret.defMultiplier += 5; } if (artifact.planetBiome == Biome.Ocean) { ret.speedMultiplier += 5; ret.defMultiplier += 5; } else if (artifact.planetBiome == Biome.Forest) { ret.defMultiplier += 5; ret.popCapMultiplier += 5; ret.popGroMultiplier += 5; } else if (artifact.planetBiome == Biome.Grassland) { ret.popCapMultiplier += 5; ret.popGroMultiplier += 5; ret.rangeMultiplier += 5; } else if (artifact.planetBiome == Biome.Tundra) { ret.defMultiplier += 5; ret.rangeMultiplier += 5; } else if (artifact.planetBiome == Biome.Swamp) { ret.speedMultiplier += 5; ret.rangeMultiplier += 5; } else if (artifact.planetBiome == Biome.Desert) { ret.speedMultiplier += 10; } else if (artifact.planetBiome == Biome.Ice) { ret.rangeMultiplier += 10; } else if (artifact.planetBiome == Biome.Wasteland) { ret.defMultiplier += 10; } else if (artifact.planetBiome == Biome.Lava) { ret.popCapMultiplier += 10; ret.popGroMultiplier += 10; } else if (artifact.planetBiome == Biome.Corrupted) { ret.rangeMultiplier += 5; ret.speedMultiplier += 5; ret.popCapMultiplier += 5; ret.popGroMultiplier += 5; } uint256 scale = 1 + (uint256(artifact.rarity) / 2); ret.popCapMultiplier = scale * ret.popCapMultiplier - (scale - 1) * 100; ret.popGroMultiplier = scale * ret.popGroMultiplier - (scale - 1) * 100; ret.speedMultiplier = scale * ret.speedMultiplier - (scale - 1) * 100; ret.rangeMultiplier = scale * ret.rangeMultiplier - (scale - 1) * 100; ret.defMultiplier = scale * ret.defMultiplier - (scale - 1) * 100; return ret; } function artifactRarityFromPlanetLevel(uint256 planetLevel) public pure returns (ArtifactRarity) { if (planetLevel <= 1) return ArtifactRarity.Common; else if (planetLevel <= 3) return ArtifactRarity.Rare; else if (planetLevel <= 5) return ArtifactRarity.Epic; else if (planetLevel <= 7) return ArtifactRarity.Legendary; else return ArtifactRarity.Mythic; } // planets can have multiple artifacts on them. this function updates all the // internal contract book-keeping to reflect that the given artifact was // put on. note that this function does not transfer the artifact. function _putArtifactOnPlanet(uint256 artifactId, uint256 locationId) public { gs().artifactIdToPlanetId[artifactId] = locationId; gs().planetArtifacts[locationId].push(artifactId); } // planets can have multiple artifacts on them. this function updates all the // internal contract book-keeping to reflect that the given artifact was // taken off the given planet. note that this function does not transfer the // artifact. // // if the given artifact is not on the given planet, reverts // if the given artifact is currently activated, reverts function _takeArtifactOffPlanet(uint256 artifactId, uint256 locationId) public { uint256 artifactsOnThisPlanet = gs().planetArtifacts[locationId].length; bool hadTheArtifact = false; for (uint256 i = 0; i < artifactsOnThisPlanet; i++) { if (gs().planetArtifacts[locationId][i] == artifactId) { Artifact memory artifact = DFArtifactFacet(address(this)).getArtifact(gs().planetArtifacts[locationId][i]); require( !isActivated(artifact), "you cannot take an activated artifact off a planet" ); gs().planetArtifacts[locationId][i] = gs().planetArtifacts[locationId][ artifactsOnThisPlanet - 1 ]; hadTheArtifact = true; break; } } require(hadTheArtifact, "this artifact was not present on this planet"); gs().artifactIdToPlanetId[artifactId] = 0; gs().planetArtifacts[locationId].pop(); } // an artifact is only considered 'activated' if this method returns true. // we do not have an `isActive` field on artifact; the times that the // artifact was last activated and deactivated are sufficent to determine // whether or not the artifact is activated. function isActivated(Artifact memory artifact) public pure returns (bool) { return artifact.lastDeactivated < artifact.lastActivated; } function isArtifactOnPlanet(uint256 locationId, uint256 artifactId) public returns (bool) { for (uint256 i; i < gs().planetArtifacts[locationId].length; i++) { if (gs().planetArtifacts[locationId][i] == artifactId) { return true; } } return false; } // if the given artifact is on the given planet, then return the artifact // otherwise, return a 'null' artifact function getPlanetArtifact(uint256 locationId, uint256 artifactId) public view returns (Artifact memory) { for (uint256 i; i < gs().planetArtifacts[locationId].length; i++) { if (gs().planetArtifacts[locationId][i] == artifactId) { return DFArtifactFacet(address(this)).getArtifact(artifactId); } } return _nullArtifact(); } // if the given planet has an activated artifact on it, then return the artifact // otherwise, return a 'null artifact' function getActiveArtifact(uint256 locationId) public view returns (Artifact memory) { for (uint256 i; i < gs().planetArtifacts[locationId].length; i++) { Artifact memory artifact = DFArtifactFacet(address(this)).getArtifact(gs().planetArtifacts[locationId][i]); if (isActivated(artifact)) { return artifact; } } return _nullArtifact(); } // the space junk that a planet starts with function getPlanetDefaultSpaceJunk(Planet memory planet) public view returns (uint256) { if (planet.isHomePlanet) return 0; return gameConstants().PLANET_LEVEL_JUNK[planet.planetLevel]; } // constructs a new artifact whose `isInititalized` field is set to `false` // used to represent the concept of 'no artifact' function _nullArtifact() private pure returns (Artifact memory) { return Artifact( false, 0, 0, ArtifactRarity(0), Biome(0), 0, address(0), ArtifactType(0), 0, 0, 0, 0, address(0) ); } function _buffPlanet(uint256 location, Upgrade memory upgrade) public { Planet storage planet = gs().planets[location]; planet.populationCap = (planet.populationCap * upgrade.popCapMultiplier) / 100; planet.populationGrowth = (planet.populationGrowth * upgrade.popGroMultiplier) / 100; planet.range = (planet.range * upgrade.rangeMultiplier) / 100; planet.speed = (planet.speed * upgrade.speedMultiplier) / 100; planet.defense = (planet.defense * upgrade.defMultiplier) / 100; } function _debuffPlanet(uint256 location, Upgrade memory upgrade) public { Planet storage planet = gs().planets[location]; planet.populationCap = (planet.populationCap * 100) / upgrade.popCapMultiplier; planet.populationGrowth = (planet.populationGrowth * 100) / upgrade.popGroMultiplier; planet.range = (planet.range * 100) / upgrade.rangeMultiplier; planet.speed = (planet.speed * 100) / upgrade.speedMultiplier; planet.defense = (planet.defense * 100) / upgrade.defMultiplier; } // planets support a limited amount of incoming arrivals // the owner can send a maximum of 5 arrivals to this planet // separately, everyone other than the owner can also send a maximum // of 5 arrivals in aggregate function checkPlanetDOS(uint256 locationId, address sender) public view { uint8 arrivalsFromOwner = 0; uint8 arrivalsFromOthers = 0; for (uint8 i = 0; i < gs().planetEvents[locationId].length; i++) { if (gs().planetEvents[locationId][i].eventType == PlanetEventType.ARRIVAL) { if ( gs().planetArrivals[gs().planetEvents[locationId][i].id].player == gs().planets[locationId].owner ) { arrivalsFromOwner++; } else { arrivalsFromOthers++; } } } if (sender == gs().planets[locationId].owner) { require(arrivalsFromOwner < 6, "Planet is rate-limited"); } else { require(arrivalsFromOthers < 6, "Planet is rate-limited"); } require(arrivalsFromOwner + arrivalsFromOthers < 12, "Planet is rate-limited"); } function updateWorldRadius() public { if (!gameConstants().WORLD_RADIUS_LOCKED) { gs().worldRadius = _getRadius(); } } function isPopCapBoost(uint256 _location) public pure returns (bool) { bytes memory _b = abi.encodePacked(_location); return uint256(uint8(_b[9])) < 16; } function isPopGroBoost(uint256 _location) public pure returns (bool) { bytes memory _b = abi.encodePacked(_location); return uint256(uint8(_b[10])) < 16; } function isRangeBoost(uint256 _location) public pure returns (bool) { bytes memory _b = abi.encodePacked(_location); return uint256(uint8(_b[11])) < 16; } function isSpeedBoost(uint256 _location) public pure returns (bool) { bytes memory _b = abi.encodePacked(_location); return uint256(uint8(_b[12])) < 16; } function isDefBoost(uint256 _location) public pure returns (bool) { bytes memory _b = abi.encodePacked(_location); return uint256(uint8(_b[13])) < 16; } function isHalfSpaceJunk(uint256 _location) public pure returns (bool) { bytes memory _b = abi.encodePacked(_location); return uint256(uint8(_b[14])) < 16; } function _defaultPlanet( uint256 location, uint256 level, PlanetType planetType, SpaceType spaceType, uint256 TIME_FACTOR_HUNDREDTHS ) public view returns (Planet memory _planet) { PlanetDefaultStats storage _planetDefaultStats = LibStorage.planetDefaultStats()[level]; bool deadSpace = spaceType == SpaceType.DEAD_SPACE; bool deepSpace = spaceType == SpaceType.DEEP_SPACE; bool mediumSpace = spaceType == SpaceType.SPACE; _planet.owner = address(0); _planet.planetLevel = level; _planet.populationCap = _planetDefaultStats.populationCap; _planet.populationGrowth = _planetDefaultStats.populationGrowth; _planet.range = _planetDefaultStats.range; _planet.speed = _planetDefaultStats.speed; _planet.defense = _planetDefaultStats.defense; _planet.silverCap = _planetDefaultStats.silverCap; if (planetType == PlanetType.SILVER_MINE) { _planet.silverGrowth = _planetDefaultStats.silverGrowth; } if (isPopCapBoost(location)) { _planet.populationCap *= 2; } if (isPopGroBoost(location)) { _planet.populationGrowth *= 2; } if (isRangeBoost(location)) { _planet.range *= 2; } if (isSpeedBoost(location)) { _planet.speed *= 2; } if (isDefBoost(location)) { _planet.defense *= 2; } // space type buffs and debuffs if (deadSpace) { // dead space buff _planet.range = _planet.range * 2; _planet.speed = _planet.speed * 2; _planet.populationCap = _planet.populationCap * 2; _planet.populationGrowth = _planet.populationGrowth * 2; _planet.silverCap = _planet.silverCap * 2; _planet.silverGrowth = _planet.silverGrowth * 2; // dead space debuff _planet.defense = (_planet.defense * 3) / 20; } else if (deepSpace) { // deep space buff _planet.range = (_planet.range * 3) / 2; _planet.speed = (_planet.speed * 3) / 2; _planet.populationCap = (_planet.populationCap * 3) / 2; _planet.populationGrowth = (_planet.populationGrowth * 3) / 2; _planet.silverCap = (_planet.silverCap * 3) / 2; _planet.silverGrowth = (_planet.silverGrowth * 3) / 2; // deep space debuff _planet.defense = _planet.defense / 4; } else if (mediumSpace) { // buff _planet.range = (_planet.range * 5) / 4; _planet.speed = (_planet.speed * 5) / 4; _planet.populationCap = (_planet.populationCap * 5) / 4; _planet.populationGrowth = (_planet.populationGrowth * 5) / 4; _planet.silverCap = (_planet.silverCap * 5) / 4; _planet.silverGrowth = (_planet.silverGrowth * 5) / 4; // debuff _planet.defense = _planet.defense / 2; } // apply buffs/debuffs for nonstandard planets // generally try to make division happen later than multiplication to avoid weird rounding _planet.planetType = planetType; if (planetType == PlanetType.SILVER_MINE) { _planet.silverCap *= 2; _planet.defense /= 2; } else if (planetType == PlanetType.SILVER_BANK) { _planet.speed /= 2; _planet.silverCap *= 10; _planet.populationGrowth = 0; _planet.populationCap *= 5; } else if (planetType == PlanetType.TRADING_POST) { _planet.defense /= 2; _planet.silverCap *= 2; } // initial population (pirates) and silver _planet.population = (_planet.populationCap * _planetDefaultStats.barbarianPercentage) / 100; // pirates adjusted for def debuffs, and buffed in space/deepspace if (deadSpace) { _planet.population *= 20; } else if (deepSpace) { _planet.population *= 10; } else if (mediumSpace) { _planet.population *= 4; } if (planetType == PlanetType.SILVER_BANK) { _planet.population /= 2; } // Adjust silver cap for mine if (planetType == PlanetType.SILVER_MINE) { _planet.silver = _planet.silverCap / 2; } // apply time factor _planet.speed *= TIME_FACTOR_HUNDREDTHS / 100; _planet.populationGrowth *= TIME_FACTOR_HUNDREDTHS / 100; _planet.silverGrowth *= TIME_FACTOR_HUNDREDTHS / 100; } }
1
0.761253
1
0.761253
game-dev
MEDIA
0.950549
game-dev
0.916608
1
0.916608
banzaicloud/pipeline
5,605
.gen/anchore/model_content_java_package_response.go
/* Anchore Engine API Server This is the Anchore Engine API. Provides the primary external API for users of the service. API version: 0.1.20 Contact: nurmi@anchore.com */ // Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package anchore import ( "encoding/json" ) // ContentJAVAPackageResponse Java package content listings from images type ContentJAVAPackageResponse struct { ImageDigest *string `json:"imageDigest,omitempty"` ContentType *string `json:"content_type,omitempty"` Content []ContentJAVAPackageResponseContentInner `json:"content,omitempty"` } // NewContentJAVAPackageResponse instantiates a new ContentJAVAPackageResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewContentJAVAPackageResponse() *ContentJAVAPackageResponse { this := ContentJAVAPackageResponse{} return &this } // NewContentJAVAPackageResponseWithDefaults instantiates a new ContentJAVAPackageResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewContentJAVAPackageResponseWithDefaults() *ContentJAVAPackageResponse { this := ContentJAVAPackageResponse{} return &this } // GetImageDigest returns the ImageDigest field value if set, zero value otherwise. func (o *ContentJAVAPackageResponse) GetImageDigest() string { if o == nil || o.ImageDigest == nil { var ret string return ret } return *o.ImageDigest } // GetImageDigestOk returns a tuple with the ImageDigest field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ContentJAVAPackageResponse) GetImageDigestOk() (*string, bool) { if o == nil || o.ImageDigest == nil { return nil, false } return o.ImageDigest, true } // HasImageDigest returns a boolean if a field has been set. func (o *ContentJAVAPackageResponse) HasImageDigest() bool { if o != nil && o.ImageDigest != nil { return true } return false } // SetImageDigest gets a reference to the given string and assigns it to the ImageDigest field. func (o *ContentJAVAPackageResponse) SetImageDigest(v string) { o.ImageDigest = &v } // GetContentType returns the ContentType field value if set, zero value otherwise. func (o *ContentJAVAPackageResponse) GetContentType() string { if o == nil || o.ContentType == nil { var ret string return ret } return *o.ContentType } // GetContentTypeOk returns a tuple with the ContentType field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ContentJAVAPackageResponse) GetContentTypeOk() (*string, bool) { if o == nil || o.ContentType == nil { return nil, false } return o.ContentType, true } // HasContentType returns a boolean if a field has been set. func (o *ContentJAVAPackageResponse) HasContentType() bool { if o != nil && o.ContentType != nil { return true } return false } // SetContentType gets a reference to the given string and assigns it to the ContentType field. func (o *ContentJAVAPackageResponse) SetContentType(v string) { o.ContentType = &v } // GetContent returns the Content field value if set, zero value otherwise. func (o *ContentJAVAPackageResponse) GetContent() []ContentJAVAPackageResponseContentInner { if o == nil || o.Content == nil { var ret []ContentJAVAPackageResponseContentInner return ret } return o.Content } // GetContentOk returns a tuple with the Content field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ContentJAVAPackageResponse) GetContentOk() ([]ContentJAVAPackageResponseContentInner, bool) { if o == nil || o.Content == nil { return nil, false } return o.Content, true } // HasContent returns a boolean if a field has been set. func (o *ContentJAVAPackageResponse) HasContent() bool { if o != nil && o.Content != nil { return true } return false } // SetContent gets a reference to the given []ContentJAVAPackageResponseContentInner and assigns it to the Content field. func (o *ContentJAVAPackageResponse) SetContent(v []ContentJAVAPackageResponseContentInner) { o.Content = v } func (o ContentJAVAPackageResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.ImageDigest != nil { toSerialize["imageDigest"] = o.ImageDigest } if o.ContentType != nil { toSerialize["content_type"] = o.ContentType } if o.Content != nil { toSerialize["content"] = o.Content } return json.Marshal(toSerialize) } type NullableContentJAVAPackageResponse struct { value *ContentJAVAPackageResponse isSet bool } func (v NullableContentJAVAPackageResponse) Get() *ContentJAVAPackageResponse { return v.value } func (v *NullableContentJAVAPackageResponse) Set(val *ContentJAVAPackageResponse) { v.value = val v.isSet = true } func (v NullableContentJAVAPackageResponse) IsSet() bool { return v.isSet } func (v *NullableContentJAVAPackageResponse) Unset() { v.value = nil v.isSet = false } func NewNullableContentJAVAPackageResponse(val *ContentJAVAPackageResponse) *NullableContentJAVAPackageResponse { return &NullableContentJAVAPackageResponse{value: val, isSet: true} } func (v NullableContentJAVAPackageResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableContentJAVAPackageResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
1
0.661964
1
0.661964
game-dev
MEDIA
0.366288
game-dev
0.623974
1
0.623974
PotRooms/StarResonanceData
1,090
lua/table/gen/SystemAwardGainTableMgr.lua
local SystemAwardGainTableRow local mgr = require("utility.table_manager") local TableInitUtility = Panda.TableInitUtility local super = require("table.table_manager_base") local SystemAwardGainTableMgr = class("SystemAwardGainTableMgr", super) function SystemAwardGainTableMgr:ctor(ptr, fields) super.ctor(self, ptr, fields) end function SystemAwardGainTableMgr:GetRow(key, notErrorWhenNotFound) local ret = self.__rows[key] if ret ~= nil then return ret end ret = super.GetRow(self, key, "int") if not ret then if not notErrorWhenNotFound then logError("SystemAwardGainTableMgr:GetRow key:{0} failed in scene:{1}", key, self.GetCurrentSceneId()) end return nil end return ret end function SystemAwardGainTableMgr:GetDatas() return super.GetDatas(self) end local wrapper return { __init = function(ptr, fields) wrapper = SystemAwardGainTableMgr.new(ptr, fields) end, GetRow = function(key, notErrorWhenNotFound) return wrapper:GetRow(key, notErrorWhenNotFound) end, GetDatas = function() return wrapper:GetDatas() end }
1
0.877716
1
0.877716
game-dev
MEDIA
0.641075
game-dev,desktop-app
0.636308
1
0.636308
frankfenghua/ios
7,462
Creating Games with cocos2d for iPhone/9007OS_Code bundle/Chapter 05 -Brick/ch5-brick/libs/Box2D/Collision/b2DynamicTree.h
/* * Copyright (c) 2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef B2_DYNAMIC_TREE_H #define B2_DYNAMIC_TREE_H #include <Box2D/Collision/b2Collision.h> #include <Box2D/Common/b2GrowableStack.h> #define b2_nullNode (-1) /// A node in the dynamic tree. The client does not interact with this directly. struct b2TreeNode { bool IsLeaf() const { return child1 == b2_nullNode; } /// Enlarged AABB b2AABB aabb; void* userData; union { int32 parent; int32 next; }; int32 child1; int32 child2; // leaf = 0, free node = -1 int32 height; }; /// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. /// A dynamic tree arranges data in a binary tree to accelerate /// queries such as volume queries and ray casts. Leafs are proxies /// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor /// so that the proxy AABB is bigger than the client object. This allows the client /// object to move by small amounts without triggering a tree update. /// /// Nodes are pooled and relocatable, so we use node indices rather than pointers. class b2DynamicTree { public: /// Constructing the tree initializes the node pool. b2DynamicTree(); /// Destroy the tree, freeing the node pool. ~b2DynamicTree(); /// Create a proxy. Provide a tight fitting AABB and a userData pointer. int32 CreateProxy(const b2AABB& aabb, void* userData); /// Destroy a proxy. This asserts if the id is invalid. void DestroyProxy(int32 proxyId); /// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB, /// then the proxy is removed from the tree and re-inserted. Otherwise /// the function returns immediately. /// @return true if the proxy was re-inserted. bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement); /// Get proxy user data. /// @return the proxy user data or 0 if the id is invalid. void* GetUserData(int32 proxyId) const; /// Get the fat AABB for a proxy. const b2AABB& GetFatAABB(int32 proxyId) const; /// Query an AABB for overlapping proxies. The callback class /// is called for each proxy that overlaps the supplied AABB. template <typename T> void Query(T* callback, const b2AABB& aabb) const; /// Ray-cast against the proxies in the tree. This relies on the callback /// to perform a exact ray-cast in the case were the proxy contains a shape. /// The callback also performs the any collision filtering. This has performance /// roughly equal to k * log(n), where k is the number of collisions and n is the /// number of proxies in the tree. /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). /// @param callback a callback class that is called for each proxy that is hit by the ray. template <typename T> void RayCast(T* callback, const b2RayCastInput& input) const; /// Validate this tree. For testing. void Validate() const; /// Compute the height of the binary tree in O(N) time. Should not be /// called often. int32 GetHeight() const; /// Get the maximum balance of an node in the tree. The balance is the difference /// in height of the two children of a node. int32 GetMaxBalance() const; /// Get the ratio of the sum of the node areas to the root area. float32 GetAreaRatio() const; /// Build an optimal tree. Very expensive. For testing. void RebuildBottomUp(); private: int32 AllocateNode(); void FreeNode(int32 node); void InsertLeaf(int32 node); void RemoveLeaf(int32 node); int32 Balance(int32 index); int32 ComputeHeight() const; int32 ComputeHeight(int32 nodeId) const; void ValidateStructure(int32 index) const; void ValidateMetrics(int32 index) const; int32 m_root; b2TreeNode* m_nodes; int32 m_nodeCount; int32 m_nodeCapacity; int32 m_freeList; /// This is used to incrementally traverse the tree for re-balancing. uint32 m_path; int32 m_insertionCount; }; inline void* b2DynamicTree::GetUserData(int32 proxyId) const { b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); return m_nodes[proxyId].userData; } inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const { b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); return m_nodes[proxyId].aabb; } template <typename T> inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const { b2GrowableStack<int32, 256> stack; stack.Push(m_root); while (stack.GetCount() > 0) { int32 nodeId = stack.Pop(); if (nodeId == b2_nullNode) { continue; } const b2TreeNode* node = m_nodes + nodeId; if (b2TestOverlap(node->aabb, aabb)) { if (node->IsLeaf()) { bool proceed = callback->QueryCallback(nodeId); if (proceed == false) { return; } } else { stack.Push(node->child1); stack.Push(node->child2); } } } } template <typename T> inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) const { b2Vec2 p1 = input.p1; b2Vec2 p2 = input.p2; b2Vec2 r = p2 - p1; b2Assert(r.LengthSquared() > 0.0f); r.Normalize(); // v is perpendicular to the segment. b2Vec2 v = b2Cross(1.0f, r); b2Vec2 abs_v = b2Abs(v); // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) float32 maxFraction = input.maxFraction; // Build a bounding box for the segment. b2AABB segmentAABB; { b2Vec2 t = p1 + maxFraction * (p2 - p1); segmentAABB.lowerBound = b2Min(p1, t); segmentAABB.upperBound = b2Max(p1, t); } b2GrowableStack<int32, 256> stack; stack.Push(m_root); while (stack.GetCount() > 0) { int32 nodeId = stack.Pop(); if (nodeId == b2_nullNode) { continue; } const b2TreeNode* node = m_nodes + nodeId; if (b2TestOverlap(node->aabb, segmentAABB) == false) { continue; } // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) b2Vec2 c = node->aabb.GetCenter(); b2Vec2 h = node->aabb.GetExtents(); float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h); if (separation > 0.0f) { continue; } if (node->IsLeaf()) { b2RayCastInput subInput; subInput.p1 = input.p1; subInput.p2 = input.p2; subInput.maxFraction = maxFraction; float32 value = callback->RayCastCallback(subInput, nodeId); if (value == 0.0f) { // The client has terminated the ray cast. return; } if (value > 0.0f) { // Update segment bounding box. maxFraction = value; b2Vec2 t = p1 + maxFraction * (p2 - p1); segmentAABB.lowerBound = b2Min(p1, t); segmentAABB.upperBound = b2Max(p1, t); } } else { stack.Push(node->child1); stack.Push(node->child2); } } } #endif
1
0.926087
1
0.926087
game-dev
MEDIA
0.372672
game-dev
0.977081
1
0.977081
hola/challenge_haggling
8,879
submissions/5b6449d4adb0280402fd7789/src/Detective/TelepatePlayer.cs
#define LOG_OFFERS using System; namespace Haggle { public enum TelepateType { Normal, Greed, Benevolent } public class TelepatePlayer : IPlayer { private readonly TelepateType m_greed = TelepateType.Normal; private readonly float AcceptThreshold = 0.9f; private readonly float MinEnemyIncomeThreshold = 0.3f; private int[] m_counts; private int[] m_values; private int m_rounds; private LogDelegate m_log; private int m_maxIncome; private int [][] m_allValues; private int m_myValuesIndex; private OfferHolder [] m_offers; private CheckList<string> m_rejectedOffers; private OfferHolder m_lastOffer = null; private CheckList<int> m_excludedValues; public TelepatePlayer(TelepateType greed, float acceptThreshold, float minEnemyIncomeThreshold) { m_greed = greed; AcceptThreshold = acceptThreshold; MinEnemyIncomeThreshold = minEnemyIncomeThreshold; } public void Init(object me, int[] counts, int[] values, int max_rounds, LogDelegate log) { m_counts = counts; m_values = values; m_rounds = max_rounds * 2; m_log = log; m_maxIncome = 0; int count = 0; for (int i = 0; i < counts.Length; i++) { m_maxIncome += m_counts[i] * values[i]; count += m_counts[i]; } Generator generator = new Generator(m_counts, 1, count, m_maxIncome); int currentSet = -1; int currentValues = -1; for (int i = 0; i < generator.Combinations.Count; i++) { if (Utils.ArrayEquals(m_counts, generator.Combinations[i].Item1)) { currentSet = i; m_allValues = generator.Combinations[currentSet].Item2; for (int j = 0; j < m_allValues.Length; j++) { if (Utils.ArrayEquals(m_allValues[j], m_values)) { currentValues = j; break; } } break; } } if (currentSet == -1 || currentValues == -1) throw new HaggleException("Data and values not found in generated sets!"); m_myValuesIndex = currentValues; m_rejectedOffers = new CheckList<string>(); m_excludedValues = new CheckList<int>(); m_excludedValues.Add(currentValues); m_log("I'm telepate player, greed " + m_greed); } public void SetEnemyData(int [] values) { m_log("Enemy items: " + String.Join(",", values)); for (int j = 0; j < m_allValues.Length; j++) { if (!Utils.ArrayEquals(m_allValues[j], values)) m_excludedValues.Add(j); } m_offers = AnalyzerEngine.FindBestOffers(m_counts, m_allValues, m_excludedValues, m_myValuesIndex); if (m_greed == TelepateType.Greed) Array.Sort(m_offers, (x, y) => x.MyIncome - x.EnemyAverage * 0.1f > y.MyIncome - y.EnemyAverage * 0.1f ? -1 : 1); else if (m_greed == TelepateType.Benevolent) Array.Sort(m_offers, (x, y) => x.MyIncome * 1.1f + x.EnemyAverage > y.MyIncome * 1.1f + y.EnemyAverage ? -1 : 1); //else //Array.Sort(m_offers, (x, y) => x.MyIncome + x.EnemyAverage * 0.1f > y.MyIncome + y.EnemyAverage * 0.1f ? -1 : 1); #if LOG_OFFERS m_log("Initial list of offers"); for (int i = 0; i < m_offers.Length; i++) m_log(Utils.Format("{0}: valid: {1}", m_offers[i], ValidOffer(m_offers[i], false))); #endif } #if !DEBUG_RIG [Bridge.Name("offer")] #endif public int[] CheckOffer(int[] o) { if (o != null) { m_rounds--; bool accept = CheckOffer(o, m_rounds); if (accept) { m_log(Utils.Format("Accepting offer {0}", Utils.StringJoin(",", o))); return null; } } m_rounds--; if (m_rounds == 0) return m_counts; OfferHolder offer = MakeOffer(m_rounds); m_log(Utils.Format("[{0}] Sending offer {1}", m_rounds, offer)); return Utils.ArrayClone(offer.Offer); } private bool ValidOffer(OfferHolder offer, bool enemyOffers) { if (offer.MyIncome == 0 || offer.EnemyAverage <= 0 || offer.EnemyMedian <= 0) return false; if (!enemyOffers) { if (m_greed != TelepateType.Greed) { if (offer.EnemyAverage < this.m_maxIncome * MinEnemyIncomeThreshold) return false; } if (m_rejectedOffers.Contains(offer.OfferCode)) return false; } return true; } public OfferHolder MakeOffer(int turnsLeft) { OfferHolder selectedOffer = null; for (int i = 0; i < m_offers.Length; i++) if (ValidOffer(m_offers[i], false)) { selectedOffer = m_offers[i]; break; } if (selectedOffer != null) { this.m_log("Selected offer " + selectedOffer); } if (m_greed == TelepateType.Greed) { if (selectedOffer == null) // no offers left, stick with last one selectedOffer = m_lastOffer; } else { if (turnsLeft <= 2) { this.m_log("======== Making final offer! ========"); selectedOffer = null; for (var i = 0; i < this.m_offers.Length; i++) { if (this.m_offers[i].EnemyAverage > this.m_maxIncome * MinEnemyIncomeThreshold && this.m_offers[i].MyIncome > 0) { return this.m_offers[i]; } } } if (selectedOffer == null) // no offers left, try relaxed list { m_log("!!!!!!!!!!!! No meaninful offers left!"); for (int i = 0; i < m_offers.Length; i++) if (m_offers[i].EnemyAverage > 0 && m_offers[i].MyIncome > 0 && !m_rejectedOffers.Contains(m_offers[i].OfferCode)) // relaxed check: not fairest option, but still good { selectedOffer = m_offers[i]; break; } if (selectedOffer == null) // no offers left, stick with last one { m_log("No offers left and no relaxed found!"); selectedOffer = m_lastOffer; } } } m_rejectedOffers.Add(selectedOffer.OfferCode); m_lastOffer = selectedOffer; return selectedOffer; } public bool CheckOffer(int[] offer, int turnsLeft) { OfferHolder holder = AnalyzerEngine.TestOffer(m_counts, m_allValues, m_excludedValues, m_myValuesIndex, offer); if (holder == null) // should never happen now { m_log("!!!!Empty offer!!!!"); return false; } m_log(Utils.Format("[{0}] Checking offer {1}", turnsLeft, holder)); if (holder.MyIncome >= m_maxIncome * AcceptThreshold) // always accept return true; if (turnsLeft <= 1 && holder.MyIncome > 0) // all telepates are French { m_log("I surrender! Give me at least " + holder.MyIncome); return true; } if (!ValidOffer(holder, true)) return false; if (m_lastOffer != null && holder.MyIncome >= m_lastOffer.MyIncome) // better than my current offer return true; return false; } #if DEBUG_RIG public override string ToString() { return string.Format("Telepate{1} [{0}, {2}]", GetHashCode(), m_greed, AcceptThreshold); } #endif } }
1
0.690298
1
0.690298
game-dev
MEDIA
0.802461
game-dev
0.884482
1
0.884482
IronWarrior/ProjectileShooting
33,255
Assets/Scripts/Math3d.cs
using UnityEngine; using System.Collections; using System; public class Math3d : MonoBehaviour { private static Transform tempChild = null; private static Transform tempParent = null; public static void Init() { tempChild = (new GameObject("Math3d_TempChild")).transform; tempParent = (new GameObject("Math3d_TempParent")).transform; tempChild.gameObject.hideFlags = HideFlags.HideAndDontSave; DontDestroyOnLoad(tempChild.gameObject); tempParent.gameObject.hideFlags = HideFlags.HideAndDontSave; DontDestroyOnLoad(tempParent.gameObject); //set the parent tempChild.parent = tempParent; } //increase or decrease the length of vector by size public static Vector3 AddVectorLength(Vector3 vector, float size) { //get the vector length float magnitude = Vector3.Magnitude(vector); //change the length magnitude += size; //normalize the vector Vector3 vectorNormalized = Vector3.Normalize(vector); //scale the vector return Vector3.Scale(vectorNormalized, new Vector3(magnitude, magnitude, magnitude)); } //create a vector of direction "vector" with length "size" public static Vector3 SetVectorLength(Vector3 vector, float size) { //normalize the vector Vector3 vectorNormalized = Vector3.Normalize(vector); //scale the vector return vectorNormalized *= size; } //caclulate the rotational difference from A to B public static Quaternion SubtractRotation(Quaternion B, Quaternion A) { Quaternion C = Quaternion.Inverse(A) * B; return C; } //Find the line of intersection between two planes. The planes are defined by a normal and a point on that plane. //The outputs are a point on the line and a vector which indicates it's direction. If the planes are not parallel, //the function outputs true, otherwise false. public static bool PlanePlaneIntersection(out Vector3 linePoint, out Vector3 lineVec, Vector3 plane1Normal, Vector3 plane1Position, Vector3 plane2Normal, Vector3 plane2Position) { linePoint = Vector3.zero; lineVec = Vector3.zero; //We can get the direction of the line of intersection of the two planes by calculating the //cross product of the normals of the two planes. Note that this is just a direction and the line //is not fixed in space yet. We need a point for that to go with the line vector. lineVec = Vector3.Cross(plane1Normal, plane2Normal); //Next is to calculate a point on the line to fix it's position in space. This is done by finding a vector from //the plane2 location, moving parallel to it's plane, and intersecting plane1. To prevent rounding //errors, this vector also has to be perpendicular to lineDirection. To get this vector, calculate //the cross product of the normal of plane2 and the lineDirection. Vector3 ldir = Vector3.Cross(plane2Normal, lineVec); float denominator = Vector3.Dot(plane1Normal, ldir); //Prevent divide by zero and rounding errors by requiring about 5 degrees angle between the planes. if (Mathf.Abs(denominator) > 0.006f) { Vector3 plane1ToPlane2 = plane1Position - plane2Position; float t = Vector3.Dot(plane1Normal, plane1ToPlane2) / denominator; linePoint = plane2Position + t * ldir; return true; } //output not valid else { return false; } } //Get the intersection between a line and a plane. //If the line and plane are not parallel, the function outputs true, otherwise false. public static bool LinePlaneIntersection(out Vector3 intersection, Vector3 linePoint, Vector3 lineVec, Vector3 planeNormal, Vector3 planePoint) { float length; float dotNumerator; float dotDenominator; Vector3 vector; intersection = Vector3.zero; //calculate the distance between the linePoint and the line-plane intersection point dotNumerator = Vector3.Dot((planePoint - linePoint), planeNormal); dotDenominator = Vector3.Dot(lineVec, planeNormal); //line and plane are not parallel if (dotDenominator != 0.0f) { length = dotNumerator / dotDenominator; //create a vector from the linePoint to the intersection point vector = SetVectorLength(lineVec, length); //get the coordinates of the line-plane intersection point intersection = linePoint + vector; return true; } //output not valid else { return false; } } //Calculate the intersection point of two lines. Returns true if lines intersect, otherwise false. //Note that in 3d, two lines do not intersect most of the time. So if the two lines are not in the //same plane, use ClosestPointsOnTwoLines() instead. public static bool LineLineIntersection(out Vector3 intersection, Vector3 linePoint1, Vector3 lineVec1, Vector3 linePoint2, Vector3 lineVec2) { intersection = Vector3.zero; Vector3 lineVec3 = linePoint2 - linePoint1; Vector3 crossVec1and2 = Vector3.Cross(lineVec1, lineVec2); Vector3 crossVec3and2 = Vector3.Cross(lineVec3, lineVec2); float planarFactor = Vector3.Dot(lineVec3, crossVec1and2); //Lines are not coplanar. Take into account rounding errors. if ((planarFactor >= 0.00001f) || (planarFactor <= -0.00001f)) { return false; } //Note: sqrMagnitude does x*x+y*y+z*z on the input vector. float s = Vector3.Dot(crossVec3and2, crossVec1and2) / crossVec1and2.sqrMagnitude; if ((s >= 0.0f) && (s <= 1.0f)) { intersection = linePoint1 + (lineVec1 * s); return true; } else { return false; } } //Two non-parallel lines which may or may not touch each other have a point on each line which are closest //to each other. This function finds those two points. If the lines are not parallel, the function //outputs true, otherwise false. public static bool ClosestPointsOnTwoLines(out Vector3 closestPointLine1, out Vector3 closestPointLine2, Vector3 linePoint1, Vector3 lineVec1, Vector3 linePoint2, Vector3 lineVec2) { closestPointLine1 = Vector3.zero; closestPointLine2 = Vector3.zero; float a = Vector3.Dot(lineVec1, lineVec1); float b = Vector3.Dot(lineVec1, lineVec2); float e = Vector3.Dot(lineVec2, lineVec2); float d = a * e - b * b; //lines are not parallel if (d != 0.0f) { Vector3 r = linePoint1 - linePoint2; float c = Vector3.Dot(lineVec1, r); float f = Vector3.Dot(lineVec2, r); float s = (b * f - c * e) / d; float t = (a * f - c * b) / d; closestPointLine1 = linePoint1 + lineVec1 * s; closestPointLine2 = linePoint2 + lineVec2 * t; return true; } else { return false; } } //This function returns a point which is a projection from a point to a line. //The line is regarded infinite. If the line is finite, use ProjectPointOnLineSegment() instead. public static Vector3 ProjectPointOnLine(Vector3 linePoint, Vector3 lineVec, Vector3 point) { //get vector from point on line to point in space Vector3 linePointToPoint = point - linePoint; float t = Vector3.Dot(linePointToPoint, lineVec); return linePoint + lineVec * t; } //This function returns a point which is a projection from a point to a line segment. //If the projected point lies outside of the line segment, the projected point will //be clamped to the appropriate line edge. //If the line is infinite instead of a segment, use ProjectPointOnLine() instead. public static Vector3 ProjectPointOnLineSegment(Vector3 linePoint1, Vector3 linePoint2, Vector3 point) { Vector3 vector = linePoint2 - linePoint1; Vector3 projectedPoint = ProjectPointOnLine(linePoint1, vector.normalized, point); int side = PointOnWhichSideOfLineSegment(linePoint1, linePoint2, projectedPoint); //The projected point is on the line segment if (side == 0) { return projectedPoint; } if (side == 1) { return linePoint1; } if (side == 2) { return linePoint2; } //output is invalid return Vector3.zero; } //This function returns a point which is a projection from a point to a plane. public static Vector3 ProjectPointOnPlane(Vector3 planeNormal, Vector3 planePoint, Vector3 point) { float distance; Vector3 translationVector; //First calculate the distance from the point to the plane: distance = SignedDistancePlanePoint(planeNormal, planePoint, point); //Reverse the sign of the distance distance *= -1; //Get a translation vector translationVector = SetVectorLength(planeNormal, distance); //Translate the point to form a projection return point + translationVector; } //Projects a vector onto a plane. The output is not normalized. public static Vector3 ProjectVectorOnPlane(Vector3 planeNormal, Vector3 vector) { return vector - (Vector3.Dot(vector, planeNormal) * planeNormal); } //Get the shortest distance between a point and a plane. The output is signed so it holds information //as to which side of the plane normal the point is. public static float SignedDistancePlanePoint(Vector3 planeNormal, Vector3 planePoint, Vector3 point) { return Vector3.Dot(planeNormal, (point - planePoint)); } //This function calculates a signed (+ or - sign instead of being ambiguous) dot product. It is basically used //to figure out whether a vector is positioned to the left or right of another vector. The way this is done is //by calculating a vector perpendicular to one of the vectors and using that as a reference. This is because //the result of a dot product only has signed information when an angle is transitioning between more or less //then 90 degrees. public static float SignedDotProduct(Vector3 vectorA, Vector3 vectorB, Vector3 normal) { Vector3 perpVector; float dot; //Use the geometry object normal and one of the input vectors to calculate the perpendicular vector perpVector = Vector3.Cross(normal, vectorA); //Now calculate the dot product between the perpendicular vector (perpVector) and the other input vector dot = Vector3.Dot(perpVector, vectorB); return dot; } public static float SignedVectorAngle(Vector3 referenceVector, Vector3 otherVector, Vector3 normal) { Vector3 perpVector; float angle; //Use the geometry object normal and one of the input vectors to calculate the perpendicular vector perpVector = Vector3.Cross(normal, referenceVector); //Now calculate the dot product between the perpendicular vector (perpVector) and the other input vector angle = Vector3.Angle(referenceVector, otherVector); angle *= Mathf.Sign(Vector3.Dot(perpVector, otherVector)); return angle; } //Calculate the angle between a vector and a plane. The plane is made by a normal vector. //Output is in radians. public static float AngleVectorPlane(Vector3 vector, Vector3 normal) { float dot; float angle; //calculate the the dot product between the two input vectors. This gives the cosine between the two vectors dot = Vector3.Dot(vector, normal); //this is in radians angle = (float)Math.Acos(dot); return 1.570796326794897f - angle; //90 degrees - angle } //Calculate the dot product as an angle public static float DotProductAngle(Vector3 vec1, Vector3 vec2) { double dot; double angle; //get the dot product dot = Vector3.Dot(vec1, vec2); //Clamp to prevent NaN error. Shouldn't need this in the first place, but there could be a rounding error issue. if (dot < -1.0f) { dot = -1.0f; } if (dot > 1.0f) { dot = 1.0f; } //Calculate the angle. The output is in radians //This step can be skipped for optimization... angle = Math.Acos(dot); return (float)angle; } //Convert a plane defined by 3 points to a plane defined by a vector and a point. //The plane point is the middle of the triangle defined by the 3 points. public static void PlaneFrom3Points(out Vector3 planeNormal, out Vector3 planePoint, Vector3 pointA, Vector3 pointB, Vector3 pointC) { planeNormal = Vector3.zero; planePoint = Vector3.zero; //Make two vectors from the 3 input points, originating from point A Vector3 AB = pointB - pointA; Vector3 AC = pointC - pointA; //Calculate the normal planeNormal = Vector3.Normalize(Vector3.Cross(AB, AC)); //Get the points in the middle AB and AC Vector3 middleAB = pointA + (AB / 2.0f); Vector3 middleAC = pointA + (AC / 2.0f); //Get vectors from the middle of AB and AC to the point which is not on that line. Vector3 middleABtoC = pointC - middleAB; Vector3 middleACtoB = pointB - middleAC; //Calculate the intersection between the two lines. This will be the center //of the triangle defined by the 3 points. //We could use LineLineIntersection instead of ClosestPointsOnTwoLines but due to rounding errors //this sometimes doesn't work. Vector3 temp; ClosestPointsOnTwoLines(out planePoint, out temp, middleAB, middleABtoC, middleAC, middleACtoB); } //Returns the forward vector of a quaternion public static Vector3 GetForwardVector(Quaternion q) { return q * Vector3.forward; } //Returns the up vector of a quaternion public static Vector3 GetUpVector(Quaternion q) { return q * Vector3.up; } //Returns the right vector of a quaternion public static Vector3 GetRightVector(Quaternion q) { return q * Vector3.right; } //Gets a quaternion from a matrix public static Quaternion QuaternionFromMatrix(Matrix4x4 m) { return Quaternion.LookRotation(m.GetColumn(2), m.GetColumn(1)); } //Gets a position from a matrix public static Vector3 PositionFromMatrix(Matrix4x4 m) { Vector4 vector4Position = m.GetColumn(3); return new Vector3(vector4Position.x, vector4Position.y, vector4Position.z); } //This is an alternative for Quaternion.LookRotation. Instead of aligning the forward and up vector of the game //object with the input vectors, a custom direction can be used instead of the fixed forward and up vectors. //alignWithVector and alignWithNormal are in world space. //customForward and customUp are in object space. //Usage: use alignWithVector and alignWithNormal as if you are using the default LookRotation function. //Set customForward and customUp to the vectors you wish to use instead of the default forward and up vectors. public static void LookRotationExtended(ref GameObject gameObjectInOut, Vector3 alignWithVector, Vector3 alignWithNormal, Vector3 customForward, Vector3 customUp) { //Set the rotation of the destination Quaternion rotationA = Quaternion.LookRotation(alignWithVector, alignWithNormal); //Set the rotation of the custom normal and up vectors. //When using the default LookRotation function, this would be hard coded to the forward and up vector. Quaternion rotationB = Quaternion.LookRotation(customForward, customUp); //Calculate the rotation gameObjectInOut.transform.rotation = rotationA * Quaternion.Inverse(rotationB); } //This function transforms one object as if it was parented to the other. //Before using this function, the Init() function must be called //Input: parentRotation and parentPosition: the current parent transform. //Input: startParentRotation and startParentPosition: the transform of the parent object at the time the objects are parented. //Input: startChildRotation and startChildPosition: the transform of the child object at the time the objects are parented. //Output: childRotation and childPosition. //All transforms are in world space. public static void TransformWithParent(out Quaternion childRotation, out Vector3 childPosition, Quaternion parentRotation, Vector3 parentPosition, Quaternion startParentRotation, Vector3 startParentPosition, Quaternion startChildRotation, Vector3 startChildPosition) { childRotation = Quaternion.identity; childPosition = Vector3.zero; //set the parent start transform tempParent.rotation = startParentRotation; tempParent.position = startParentPosition; tempParent.localScale = Vector3.one; //to prevent scale wandering //set the child start transform tempChild.rotation = startChildRotation; tempChild.position = startChildPosition; tempChild.localScale = Vector3.one; //to prevent scale wandering //translate and rotate the child by moving the parent tempParent.rotation = parentRotation; tempParent.position = parentPosition; //get the child transform childRotation = tempChild.rotation; childPosition = tempChild.position; } //With this function you can align a triangle of an object with any transform. //Usage: gameObjectInOut is the game object you want to transform. //alignWithVector, alignWithNormal, and alignWithPosition is the transform with which the triangle of the object should be aligned with. //triangleForward, triangleNormal, and trianglePosition is the transform of the triangle from the object. //alignWithVector, alignWithNormal, and alignWithPosition are in world space. //triangleForward, triangleNormal, and trianglePosition are in object space. //trianglePosition is the mesh position of the triangle. The effect of the scale of the object is handled automatically. //trianglePosition can be set at any position, it does not have to be at a vertex or in the middle of the triangle. public static void PreciseAlign(ref GameObject gameObjectInOut, Vector3 alignWithVector, Vector3 alignWithNormal, Vector3 alignWithPosition, Vector3 triangleForward, Vector3 triangleNormal, Vector3 trianglePosition) { //Set the rotation. LookRotationExtended(ref gameObjectInOut, alignWithVector, alignWithNormal, triangleForward, triangleNormal); //Get the world space position of trianglePosition Vector3 trianglePositionWorld = gameObjectInOut.transform.TransformPoint(trianglePosition); //Get a vector from trianglePosition to alignWithPosition Vector3 translateVector = alignWithPosition - trianglePositionWorld; //Now transform the object so the triangle lines up correctly. gameObjectInOut.transform.Translate(translateVector, Space.World); } //Convert a position, direction, and normal vector to a transform void VectorsToTransform(ref GameObject gameObjectInOut, Vector3 positionVector, Vector3 directionVector, Vector3 normalVector) { gameObjectInOut.transform.position = positionVector; gameObjectInOut.transform.rotation = Quaternion.LookRotation(directionVector, normalVector); } //This function finds out on which side of a line segment the point is located. //The point is assumed to be on a line created by linePoint1 and linePoint2. If the point is not on //the line segment, project it on the line using ProjectPointOnLine() first. //Returns 0 if point is on the line segment. //Returns 1 if point is outside of the line segment and located on the side of linePoint1. //Returns 2 if point is outside of the line segment and located on the side of linePoint2. public static int PointOnWhichSideOfLineSegment(Vector3 linePoint1, Vector3 linePoint2, Vector3 point) { Vector3 lineVec = linePoint2 - linePoint1; Vector3 pointVec = point - linePoint1; float dot = Vector3.Dot(pointVec, lineVec); //point is on side of linePoint2, compared to linePoint1 if (dot > 0) { //point is on the line segment if (pointVec.magnitude <= lineVec.magnitude) { return 0; } //point is not on the line segment and it is on the side of linePoint2 else { return 2; } } //Point is not on side of linePoint2, compared to linePoint1. //Point is not on the line segment and it is on the side of linePoint1. else { return 1; } } //Returns the pixel distance from the mouse pointer to a line. //Alternative for HandleUtility.DistanceToLine(). Works both in Editor mode and Play mode. //Do not call this function from OnGUI() as the mouse position will be wrong. public static float MouseDistanceToLine(Vector3 linePoint1, Vector3 linePoint2) { Camera currentCamera; Vector3 mousePosition; #if UNITY_EDITOR if (Camera.current != null) { currentCamera = Camera.current; } else { currentCamera = Camera.main; } //convert format because y is flipped mousePosition = new Vector3(Event.current.mousePosition.x, currentCamera.pixelHeight - Event.current.mousePosition.y, 0f); #else currentCamera = Camera.main; mousePosition = Input.mousePosition; #endif Vector3 screenPos1 = currentCamera.WorldToScreenPoint(linePoint1); Vector3 screenPos2 = currentCamera.WorldToScreenPoint(linePoint2); Vector3 projectedPoint = ProjectPointOnLineSegment(screenPos1, screenPos2, mousePosition); //set z to zero projectedPoint = new Vector3(projectedPoint.x, projectedPoint.y, 0f); Vector3 vector = projectedPoint - mousePosition; return vector.magnitude; } //Returns the pixel distance from the mouse pointer to a camera facing circle. //Alternative for HandleUtility.DistanceToCircle(). Works both in Editor mode and Play mode. //Do not call this function from OnGUI() as the mouse position will be wrong. //If you want the distance to a point instead of a circle, set the radius to 0. public static float MouseDistanceToCircle(Vector3 point, float radius) { Camera currentCamera; Vector3 mousePosition; #if UNITY_EDITOR if (Camera.current != null) { currentCamera = Camera.current; } else { currentCamera = Camera.main; } //convert format because y is flipped mousePosition = new Vector3(Event.current.mousePosition.x, currentCamera.pixelHeight - Event.current.mousePosition.y, 0f); #else currentCamera = Camera.main; mousePosition = Input.mousePosition; #endif Vector3 screenPos = currentCamera.WorldToScreenPoint(point); //set z to zero screenPos = new Vector3(screenPos.x, screenPos.y, 0f); Vector3 vector = screenPos - mousePosition; float fullDistance = vector.magnitude; float circleDistance = fullDistance - radius; return circleDistance; } //Returns true if a line segment (made up of linePoint1 and linePoint2) is fully or partially in a rectangle //made up of RectA to RectD. The line segment is assumed to be on the same plane as the rectangle. If the line is //not on the plane, use ProjectPointOnPlane() on linePoint1 and linePoint2 first. public static bool IsLineInRectangle(Vector3 linePoint1, Vector3 linePoint2, Vector3 rectA, Vector3 rectB, Vector3 rectC, Vector3 rectD) { bool pointAInside = false; bool pointBInside = false; pointAInside = IsPointInRectangle(linePoint1, rectA, rectC, rectB, rectD); if (!pointAInside) { pointBInside = IsPointInRectangle(linePoint2, rectA, rectC, rectB, rectD); } //none of the points are inside, so check if a line is crossing if (!pointAInside && !pointBInside) { bool lineACrossing = AreLineSegmentsCrossing(linePoint1, linePoint2, rectA, rectB); bool lineBCrossing = AreLineSegmentsCrossing(linePoint1, linePoint2, rectB, rectC); bool lineCCrossing = AreLineSegmentsCrossing(linePoint1, linePoint2, rectC, rectD); bool lineDCrossing = AreLineSegmentsCrossing(linePoint1, linePoint2, rectD, rectA); if (lineACrossing || lineBCrossing || lineCCrossing || lineDCrossing) { return true; } else { return false; } } else { return true; } } //Returns true if "point" is in a rectangle mad up of RectA to RectD. The line point is assumed to be on the same //plane as the rectangle. If the point is not on the plane, use ProjectPointOnPlane() first. public static bool IsPointInRectangle(Vector3 point, Vector3 rectA, Vector3 rectC, Vector3 rectB, Vector3 rectD) { Vector3 vector; Vector3 linePoint; //get the center of the rectangle vector = rectC - rectA; float size = -(vector.magnitude / 2f); vector = AddVectorLength(vector, size); Vector3 middle = rectA + vector; Vector3 xVector = rectB - rectA; float width = xVector.magnitude / 2f; Vector3 yVector = rectD - rectA; float height = yVector.magnitude / 2f; linePoint = ProjectPointOnLine(middle, xVector.normalized, point); vector = linePoint - point; float yDistance = vector.magnitude; linePoint = ProjectPointOnLine(middle, yVector.normalized, point); vector = linePoint - point; float xDistance = vector.magnitude; if ((xDistance <= width) && (yDistance <= height)) { return true; } else { return false; } } //Returns true if line segment made up of pointA1 and pointA2 is crossing line segment made up of //pointB1 and pointB2. The two lines are assumed to be in the same plane. public static bool AreLineSegmentsCrossing(Vector3 pointA1, Vector3 pointA2, Vector3 pointB1, Vector3 pointB2) { Vector3 closestPointA; Vector3 closestPointB; int sideA; int sideB; Vector3 lineVecA = pointA2 - pointA1; Vector3 lineVecB = pointB2 - pointB1; bool valid = ClosestPointsOnTwoLines(out closestPointA, out closestPointB, pointA1, lineVecA.normalized, pointB1, lineVecB.normalized); //lines are not parallel if (valid) { sideA = PointOnWhichSideOfLineSegment(pointA1, pointA2, closestPointA); sideB = PointOnWhichSideOfLineSegment(pointB1, pointB2, closestPointB); if ((sideA == 0) && (sideB == 0)) { return true; } else { return false; } } //lines are parallel else { return false; } } public static bool LineSphereIntersection(Ray ray, Vector3 center, float radius, out float t0, out float t1) { t0 = t1 = 0; Vector3 L = center - ray.origin; float tca = Vector3.Dot(L, ray.direction); /*if (tca < 0) { return false; }*/ float d2 = Vector3.Dot(L, L) - tca * tca; float radiusSquared = radius * radius; if (d2 > radiusSquared) return false; float thc = Mathf.Sqrt(radiusSquared - d2); t0 = tca - thc; t1 = tca + thc; if (t0 > t1) { float temp = t0; t0 = t1; t1 = temp; } return true; } /// <summary> /// Determines the closest point between a point and a triangle. /// Borrowed from RPGMesh class of the RPGController package for Unity, by fholm /// The code in this method is copyrighted by the SlimDX Group under the MIT license: /// /// Copyright (c) 2007-2010 SlimDX Group /// /// 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. /// /// </summary> /// <param name="point">The point to test.</param> /// <param name="vertex1">The first vertex to test.</param> /// <param name="vertex2">The second vertex to test.</param> /// <param name="vertex3">The third vertex to test.</param> /// <param name="result">When the method completes, contains the closest point between the two objects.</param> public static void ClosestPointOnTriangleToPoint(Vector3 vertex1, Vector3 vertex2, Vector3 vertex3, Vector3 point, out Vector3 result) { //Source: Real-Time Collision Detection by Christer Ericson //Reference: Page 136 //Check if P in vertex region outside A Vector3 ab = vertex2 - vertex1; Vector3 ac = vertex3 - vertex1; Vector3 ap = point - vertex1; float d1 = Vector3.Dot(ab, ap); float d2 = Vector3.Dot(ac, ap); if (d1 <= 0.0f && d2 <= 0.0f) { result = vertex1; //Barycentric coordinates (1,0,0) return; } //Check if P in vertex region outside B Vector3 bp = point - vertex2; float d3 = Vector3.Dot(ab, bp); float d4 = Vector3.Dot(ac, bp); if (d3 >= 0.0f && d4 <= d3) { result = vertex2; // barycentric coordinates (0,1,0) return; } //Check if P in edge region of AB, if so return projection of P onto AB float vc = d1 * d4 - d3 * d2; if (vc <= 0.0f && d1 >= 0.0f && d3 <= 0.0f) { float v = d1 / (d1 - d3); result = vertex1 + v * ab; //Barycentric coordinates (1-v,v,0) return; } //Check if P in vertex region outside C Vector3 cp = point - vertex3; float d5 = Vector3.Dot(ab, cp); float d6 = Vector3.Dot(ac, cp); if (d6 >= 0.0f && d5 <= d6) { result = vertex3; //Barycentric coordinates (0,0,1) return; } //Check if P in edge region of AC, if so return projection of P onto AC float vb = d5 * d2 - d1 * d6; if (vb <= 0.0f && d2 >= 0.0f && d6 <= 0.0f) { float w = d2 / (d2 - d6); result = vertex1 + w * ac; //Barycentric coordinates (1-w,0,w) return; } //Check if P in edge region of BC, if so return projection of P onto BC float va = d3 * d6 - d5 * d4; if (va <= 0.0f && (d4 - d3) >= 0.0f && (d5 - d6) >= 0.0f) { float w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); result = vertex2 + w * (vertex3 - vertex2); //Barycentric coordinates (0,1-w,w) return; } //P inside face region. Compute Q through its barycentric coordinates (u,v,w) float denom = 1.0f / (va + vb + vc); float v2 = vb * denom; float w2 = vc * denom; result = vertex1 + ab * v2 + ac * w2; //= u*vertex1 + v*vertex2 + w*vertex3, u = va * denom = 1.0f - v - w } }
1
0.841643
1
0.841643
game-dev
MEDIA
0.748914
game-dev,graphics-rendering
0.6992
1
0.6992
Snapchat/Spectacles-Sample
2,366
Essentials/Assets/Instantiation/JS/CircleAreaInstantiatorJS.js
/** * CircleAreaInstantiator - JavaScript version of the C# utility * Instantiates prefabs within a circular area */ //@input SceneObject center {"hint":"Center of the circle area"} //@input Asset.ObjectPrefab prefab {"hint":"Prefab to instantiate"} //@input float numberOfPrefabs = 10 {"hint":"Number of prefabs to instantiate"} //@input float radius = 5.0 {"hint":"Radius of the circle"} function CircleAreaInstantiator() { // Initialize with the proper pattern script.createEvent("OnStartEvent").bind(onStart); function onStart() { instantiatePrefabs(); } // Method to instantiate prefabs within the circle area function instantiatePrefabs() { if (!script.center || !script.prefab) { print("Error: Center or prefab not assigned!"); return; } var centerPosition = script.center.getTransform().getWorldPosition(); for (var i = 0; i < script.numberOfPrefabs; i++) { // Random angle and distance to place the prefab var angle = Math.random() * Math.PI * 2; var distance = Math.random() * script.radius; // Calculate position based on angle and distance var randomPosition = new vec3( centerPosition.x + Math.cos(angle) * distance, centerPosition.y + Math.sin(angle) * distance, centerPosition.z ); // Create a prefab instance at the random position createPrefabInstance(randomPosition); } } // Helper method to create a prefab instance at a specific position function createPrefabInstance(position) { if (script.prefab) { // In a real implementation, we would use StudioLib's actual instantiation API // For this example, we'll just log what would happen print("Created prefab instance at position: " + position.x + ", " + position.y + ", " + position.z); // The actual instantiation code would be something like: var instance = script.prefab.instantiate(script.sceneObject); instance.getTransform().setWorldPosition(position); } } } // Register the script script.CircleAreaInstantiator = CircleAreaInstantiator; CircleAreaInstantiator();
1
0.582926
1
0.582926
game-dev
MEDIA
0.390389
game-dev
0.733354
1
0.733354
DLindustries/System
3,064
src/main/java/dlindustries/vigillant/system/utils/BlockUtils.java
package dlindustries.vigillant.system.utils; import dlindustries.vigillant.system.utils.rotation.Rotation; import net.minecraft.block.Block; import net.minecraft.block.Blocks; import net.minecraft.block.RespawnAnchorBlock; import net.minecraft.entity.Entity; import net.minecraft.entity.ItemEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Box; import net.minecraft.util.math.Direction; import java.util.List; import java.util.stream.Stream; import static dlindustries.vigillant.system.system.mc; public final class BlockUtils { public static boolean isBlock(BlockPos pos, Block block) { return mc.world.getBlockState(pos).getBlock() == block; } public static void rotateToBlock(BlockPos pos) { assert mc.player != null; //WTF!!! Rotation rotation = RotationUtils.getDirection(mc.player, pos.toCenterPos()); mc.player.setPitch((float) rotation.pitch()); mc.player.setYaw((float) rotation.yaw()); } public static boolean isAnchorCharged(BlockPos pos) { if (isBlock(pos, Blocks.RESPAWN_ANCHOR)) { return mc.world.getBlockState(pos).get(RespawnAnchorBlock.CHARGES) != 0; } return false; } public static boolean isAnchorNotCharged(BlockPos pos) { if (isBlock(pos, Blocks.RESPAWN_ANCHOR)) { return mc.world.getBlockState(pos).get(RespawnAnchorBlock.CHARGES) == 0; } return false; } public static boolean canPlaceBlockClient(BlockPos block) { BlockPos up = block.up(); if(!mc.world.isAir(up)) return false; double x = up.getX(); double y = up.getY(); double z = up.getZ(); List<Entity> list = mc.world.getOtherEntities(null, new Box(x, y, z, x + 1, y + 1, z + 1)); list.removeIf(entity -> entity instanceof ItemEntity); return list.isEmpty(); } public static Stream<BlockPos> getAllInBoxStream(BlockPos from, BlockPos to) { BlockPos min = new BlockPos(Math.min(from.getX(), to.getX()), Math.min(from.getY(), to.getY()), Math.min(from.getZ(), to.getZ())); BlockPos max = new BlockPos(Math.max(from.getX(), to.getX()), Math.max(from.getY(), to.getY()), Math.max(from.getZ(), to.getZ())); Stream<BlockPos> stream = Stream.iterate(min, (pos) -> { int x = pos.getX(); int y = pos.getY(); int z = pos.getZ(); ++x; if (x > max.getX()) { x = min.getX(); ++y; } if (y > max.getY()) { y = min.getY(); ++z; } if (z > max.getZ()) throw new IllegalStateException("Stream limit didn't work."); else return new BlockPos(x, y, z); }); int limit = (max.getX() - min.getX() + 1) * (max.getY() - min.getY() + 1) * (max.getZ() - min.getZ() + 1); return stream.limit(limit); } public static boolean canPlaceGlowstone(BlockPos pos) { // Check if target position is replaceable if (!mc.world.getBlockState(pos).isReplaceable()) return false; // Check all directions for a solid face to place against for (Direction direction : Direction.values()) { BlockPos neighbor = pos.offset(direction); if (mc.world.getBlockState(neighbor).isSolid()) { return true; } } return false; } }
1
0.821272
1
0.821272
game-dev
MEDIA
0.98528
game-dev
0.963971
1
0.963971
flame-engine/flame
1,210
examples/lib/stories/bridge_libraries/flame_forge2d/contact_callbacks_example.dart
import 'dart:math' as math; import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/balls.dart'; import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/boundaries.dart'; import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; class ContactCallbacksExample extends Forge2DGame { static const description = ''' This example shows how `BodyComponent`s can react to collisions with other bodies. Tap the screen to add balls, the white balls will give an impulse to the balls that it collides with. '''; ContactCallbacksExample() : super(gravity: Vector2(0, 10.0), world: ContactCallbackWorld()); } class ContactCallbackWorld extends Forge2DWorld with TapCallbacks, HasGameReference<Forge2DGame> { @override Future<void> onLoad() async { super.onLoad(); final boundaries = createBoundaries(game); addAll(boundaries); } @override void onTapDown(TapDownEvent info) { super.onTapDown(info); final position = info.localPosition; if (math.Random().nextInt(10) < 2) { add(WhiteBall(position)); } else { add(Ball(position)); } } }
1
0.784183
1
0.784183
game-dev
MEDIA
0.942895
game-dev
0.692308
1
0.692308