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
DayZMod/DayZ
1,546
SQF/dayz_code/system/scheduler/sched_throwable.sqf
// (c) facoptere@gmail.com, licensed to DayZMod for the community // automatically select primary weapon after inactivity on throwable weapon // (The problem in ArmA is that when a player select a throwable, he still holds the primary weapon in hand, // the throwable appears in his hand only when the player clicks on fire button) sched_throwable_init = { sched_throwable_prevmuzz=""; sched_throwable_time=0; objNull }; sched_throwable = { private ["_stance","_cur_muzz","_type", "_x"]; if ((!isNil "player") and {(!isNull player)}) then { _cur_muzz = currentMuzzle player; if (((!isNil "_cur_muzz") and {(_cur_muzz != "")}) AND {(0 == getNumber(configFile >> "CfgWeapons" >> _cur_muzz >> "type"))}) then { if (sched_throwable_prevmuzz != _cur_muzz) then { sched_throwable_prevmuzz = currentMuzzle player; sched_throwable_time = diag_tickTime+11; }; if (((player getVariable["combattimeout", diag_tickTime])-diag_tickTime)>27) then { sched_throwable_time = diag_tickTime+21; }; }; if (abs(sched_throwable_time-diag_tickTime)<2) then { _stance = toArray (animationState player); _stance = if ((!isNil "_stance") and {(count _stance>17)}) then {toString [_stance select 17]} else {""}; _type = 4096; switch _stance do { case "p": { _type = 2; }; case "r": { _type = 1; }; }; { if (_type == getNumber(configFile >> "CfgWeapons" >> _x >> "type")) exitWith { player selectWeapon _x; }; } count (weapons player); sched_throwable_time = 0; }; }; objNull };
412
0.911373
1
0.911373
game-dev
MEDIA
0.988127
game-dev
0.848979
1
0.848979
pkmn/ps
1,786
sim/test/sim/rulesets.js
'use strict'; const assert = require('../assert'); describe('Rulesets', function () { it('all formats should have functional rulesets', function () { for (const format of Dex.formats.all()) { assert.doesNotThrow(() => Dex.formats.getRuleTable(format)); } }); it('should not contain unused rules', function () { const used = new Set([ 'Crown Tundra Pokedex', 'EV Limit', 'Exact HP Mod', 'Galar Expansion Pokedex', 'Galar Pokedex', 'Hoenn Pokedex', 'Isle of Armor Pokedex', 'Limit One Restricted', 'Min Team Size', 'New Alola Pokedex', 'New Unova Pokedex', 'Obtainable Abilities', 'Obtainable Formes', 'Obtainable Misc', 'Obtainable Moves', 'Overflow Stat Mod', 'Sinnoh Pokedex', 'Sketch Post-Gen 7 Moves', 'Stadium Items Clause', 'Adjust Level Down', 'Allow AVs', 'Event Moves Clause', 'Item Clause', 'Kalos Pokedex', 'Max Total Level', 'Min Level', 'NC 1997 Move Legality', 'NC 2000 Move Legality', 'Old Alola Pokedex', 'Old Unova Pokedex', 'Stadium Sleep Clause', 'Best Of', 'DC Timer Bank', 'DC Timer', 'Timeout Auto Choose', 'Timer Accelerate', 'Timer Add Per Turn', 'Timer Grace', 'Timer Max First Turn', 'Timer Max Per Turn', 'Guaranteed Secondary Mod', ]); for (const format of Dex.formats.formatsListCache) { for (const r of format.ruleset) { const rule = r.split(' = ')[0]; if (rule.startsWith('[')) continue; used.add(rule.replace(/^\W+/, '')); } } const unused = new Set(); for (let i = 1; i <= 9; i++) { const dex = Dex.forGen(i); for (const r in dex.data.Rulesets) { if (r === 'validatestats') continue; const rule = dex.data.Rulesets[r].name; if (rule.startsWith('[')) continue; if (!used.has(rule)) unused.add(rule); } } assert.deepEqual(unused, new Set()); }); });
412
0.859477
1
0.859477
game-dev
MEDIA
0.344005
game-dev
0.929039
1
0.929039
KAMKEEL/CustomNPC-Plus
3,136
src/main/java/noppes/npcs/entity/EntityNPCFlying.java
package noppes.npcs.entity; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; public abstract class EntityNPCFlying extends EntityNPCInterface { public boolean flyLimitAllow = false; public EntityNPCFlying(World world) { super(world); } @Override public boolean canFly() { return ais.movementType == 1; } @Override public void fall(float distance) { if (!canFly()) super.fall(distance); } @Override protected void updateFallState(double p_180433_1_, boolean p_180433_3_) { if (!canFly()) super.updateFallState(p_180433_1_, p_180433_3_); } @Override public boolean isOnLadder() { return false; } @Override public void onLivingUpdate() { super.onLivingUpdate(); } public void moveEntityWithHeading(float p_70612_1_, float p_70612_2_) { if (!this.canFly() || this.hurtTime != 0 || !this.canBreathe()) { super.moveEntityWithHeading(p_70612_1_, p_70612_2_); return; } boolean aboveLimit = false; double heightOffGround = this.posY - this.worldObj.getTopSolidOrLiquidBlock((int) this.posX, (int) this.posZ); if (heightOffGround < 0) { Vec3 pos = Vec3.createVectorHelper(this.posX, this.posY, this.posZ); Vec3 posLimit = Vec3.createVectorHelper(this.posX, this.posY - this.ais.flyHeightLimit, this.posZ); MovingObjectPosition mob = this.worldObj.rayTraceBlocks(pos, posLimit, true); if (mob == null || mob.typeOfHit == MovingObjectPosition.MovingObjectType.MISS) { aboveLimit = true; } } else if (heightOffGround > this.ais.flyHeightLimit) { aboveLimit = true; } if (aboveLimit && this.ais.hasFlyLimit || (heightOffGround < Math.ceil(this.height) && this.motionY == 0)) { this.flyLimitAllow = false; if (!this.getNavigator().noPath() && this.motionY > 0) { this.motionY = 0; } else { super.moveEntityWithHeading(p_70612_1_, p_70612_2_); return; } } this.flyLimitAllow = true; double d3 = this.motionY; super.moveEntityWithHeading(p_70612_1_, p_70612_2_); this.motionY = d3; if (this.getNavigator().noPath()) { this.motionY = -Math.abs(this.ais.flyGravity); } this.updateLimbSwing(); this.velocityChanged = true; } public void updateLimbSwing() { this.prevLimbSwingAmount = this.limbSwingAmount; double distanceX = this.posX - this.prevPosX; double distanceZ = this.posZ - this.prevPosZ; float distance = MathHelper.sqrt_double(distanceX * distanceX + distanceZ * distanceZ) * 4.0F; if (distance > 1.0F) { distance = 1.0F; } this.limbSwingAmount += (distance - this.limbSwingAmount) * 0.4F; this.limbSwing += this.limbSwingAmount; } }
412
0.864295
1
0.864295
game-dev
MEDIA
0.963081
game-dev
0.991318
1
0.991318
SkelletonX/DDTank4.1
19,621
Source Server/SourceQuest4.5/Bussiness/Bussiness.Managers/PetMgr.cs
using log4net; using SqlDataProvider.Data; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; namespace Bussiness.Managers { public class PetMgr { private static readonly ILog ilog_0; private static Dictionary<string, PetConfig> dictionary_0; private static Dictionary<int, PetLevel> dictionary_1; private static Dictionary<int, PetSkillElementInfo> dictionary_2; private static Dictionary<int, PetSkillInfo> dictionary_3; private static Dictionary<int, PetSkillTemplateInfo> dictionary_4; private static Dictionary<int, PetTemplateInfo> dictionary_5; private static Dictionary<int, PetFightPropertyInfo> dictionary_6; private static Dictionary<int, PetStarExpInfo> dictionary_7; private static List<GameNeedPetSkillInfo> list_0; private static Random random_0; private static ReaderWriterLock readerWriterLock_0; public static bool Init() { try { random_0 = new Random(); return ReLoad(); } catch (Exception ex) { if (ilog_0.IsErrorEnabled) { ilog_0.Error("PetInfoMgr", ex); } return false; } } public static bool ReLoad() { try { Dictionary<string, PetConfig> sbgjaFH96yj7P79ekB = new Dictionary<string, PetConfig>(); Dictionary<int, PetLevel> EvHSgt7QX8VsEd0yEZ = new Dictionary<int, PetLevel>(); Dictionary<int, PetSkillElementInfo> R11rtWo1p4Y2vEtvxF = new Dictionary<int, PetSkillElementInfo>(); Dictionary<int, PetSkillInfo> m8Jor90v2RFloePXnt = new Dictionary<int, PetSkillInfo>(); Dictionary<int, PetSkillTemplateInfo> YHCrVLAS0QefBk0Ur5 = new Dictionary<int, PetSkillTemplateInfo>(); new Dictionary<int, PetTemplateInfo>(); Dictionary<int, PetTemplateInfo> w2gAkTbu06gsoxFCZU = new Dictionary<int, PetTemplateInfo>(); Dictionary<int, PetFightPropertyInfo> PnKXOFTHDG3PZUPkBD = new Dictionary<int, PetFightPropertyInfo>(); Dictionary<int, PetStarExpInfo> w84AGjgion3EqNro8x = new Dictionary<int, PetStarExpInfo>(); if (smethod_0(sbgjaFH96yj7P79ekB, EvHSgt7QX8VsEd0yEZ, R11rtWo1p4Y2vEtvxF, m8Jor90v2RFloePXnt, YHCrVLAS0QefBk0Ur5, w2gAkTbu06gsoxFCZU, PnKXOFTHDG3PZUPkBD, w84AGjgion3EqNro8x)) { try { dictionary_0 = sbgjaFH96yj7P79ekB; dictionary_1 = EvHSgt7QX8VsEd0yEZ; dictionary_2 = R11rtWo1p4Y2vEtvxF; dictionary_3 = m8Jor90v2RFloePXnt; dictionary_4 = YHCrVLAS0QefBk0Ur5; dictionary_5 = w2gAkTbu06gsoxFCZU; dictionary_6 = PnKXOFTHDG3PZUPkBD; dictionary_7 = w84AGjgion3EqNro8x; List<GameNeedPetSkillInfo> needPetSkillInfoList = LoadGameNeedPetSkill(); if (needPetSkillInfoList.Count > 0) { Interlocked.Exchange(ref list_0, needPetSkillInfoList); } return true; } catch { } } } catch (Exception ex) { if (ilog_0.IsErrorEnabled) { ilog_0.Error("PetMgr", ex); } } return false; } public static PetStarExpInfo[] GetPetStarExp() { return dictionary_7.Values.ToArray(); } public static PetStarExpInfo FindPetStarExp(int oldID) { readerWriterLock_0.AcquireWriterLock(-1); try { if (dictionary_7.ContainsKey(oldID)) { return dictionary_7[oldID]; } } finally { readerWriterLock_0.ReleaseWriterLock(); } return null; } private static bool smethod_0(Dictionary<string, PetConfig> sbgjaFH96yj7P79ekB, Dictionary<int, PetLevel> EvHSgt7QX8VsEd0yEZ, Dictionary<int, PetSkillElementInfo> R11rtWo1p4Y2vEtvxF, Dictionary<int, PetSkillInfo> m8Jor90v2RFloePXnt, Dictionary<int, PetSkillTemplateInfo> YHCrVLAS0QefBk0Ur5, Dictionary<int, PetTemplateInfo> w2gAkTbu06gsoxFCZU, Dictionary<int, PetFightPropertyInfo> PnKXOFTHDG3PZUPkBD, Dictionary<int, PetStarExpInfo> w84AGjgion3EqNro8x) { using (ProduceBussiness produceBussiness = new ProduceBussiness()) { PetConfig[] allPetConfig = produceBussiness.GetAllPetConfig(); PetLevel[] allPetLevel = produceBussiness.GetAllPetLevel(); PetSkillElementInfo[] skillElementInfo1 = produceBussiness.GetAllPetSkillElementInfo(); PetSkillInfo[] allPetSkillInfo = produceBussiness.GetAllPetSkillInfo(); PetSkillTemplateInfo[] skillTemplateInfo1 = produceBussiness.GetAllPetSkillTemplateInfo(); PetTemplateInfo[] allPetTemplateInfo = produceBussiness.GetAllPetTemplateInfo(); PetFightPropertyInfo[] petFightProperty = produceBussiness.GetAllPetFightProperty(); PetStarExpInfo[] allPetStarExp = produceBussiness.GetAllPetStarExp(); PetConfig[] array = allPetConfig; foreach (PetConfig petConfig in array) { if (!sbgjaFH96yj7P79ekB.ContainsKey(petConfig.Name)) { sbgjaFH96yj7P79ekB.Add(petConfig.Name, petConfig); } } PetLevel[] array2 = allPetLevel; foreach (PetLevel petLevel in array2) { if (!EvHSgt7QX8VsEd0yEZ.ContainsKey(petLevel.Level)) { EvHSgt7QX8VsEd0yEZ.Add(petLevel.Level, petLevel); } } PetSkillElementInfo[] array3 = skillElementInfo1; foreach (PetSkillElementInfo skillElementInfo2 in array3) { if (!R11rtWo1p4Y2vEtvxF.ContainsKey(skillElementInfo2.ID)) { R11rtWo1p4Y2vEtvxF.Add(skillElementInfo2.ID, skillElementInfo2); } } PetSkillTemplateInfo[] array4 = skillTemplateInfo1; foreach (PetSkillTemplateInfo skillTemplateInfo2 in array4) { if (!YHCrVLAS0QefBk0Ur5.ContainsKey(skillTemplateInfo2.SkillID)) { YHCrVLAS0QefBk0Ur5.Add(skillTemplateInfo2.SkillID, skillTemplateInfo2); } } PetTemplateInfo[] array5 = allPetTemplateInfo; foreach (PetTemplateInfo petTemplateInfo in array5) { if (!w2gAkTbu06gsoxFCZU.ContainsKey(petTemplateInfo.TemplateID)) { w2gAkTbu06gsoxFCZU.Add(petTemplateInfo.TemplateID, petTemplateInfo); } } PetSkillInfo[] array6 = allPetSkillInfo; foreach (PetSkillInfo petSkillInfo in array6) { if (!m8Jor90v2RFloePXnt.ContainsKey(petSkillInfo.ID)) { m8Jor90v2RFloePXnt.Add(petSkillInfo.ID, petSkillInfo); } } PetFightPropertyInfo[] array7 = petFightProperty; foreach (PetFightPropertyInfo fightPropertyInfo in array7) { if (!PnKXOFTHDG3PZUPkBD.ContainsKey(fightPropertyInfo.ID)) { PnKXOFTHDG3PZUPkBD.Add(fightPropertyInfo.ID, fightPropertyInfo); } } PetStarExpInfo[] array8 = allPetStarExp; foreach (PetStarExpInfo petStarExpInfo in array8) { if (!w84AGjgion3EqNro8x.ContainsKey(petStarExpInfo.OldID)) { w84AGjgion3EqNro8x.Add(petStarExpInfo.OldID, petStarExpInfo); } } } return true; } public static PetFightPropertyInfo FindFightProperty(int level) { readerWriterLock_0.AcquireWriterLock(-1); try { if (dictionary_6.ContainsKey(level)) { return dictionary_6[level]; } } finally { readerWriterLock_0.ReleaseWriterLock(); } return null; } public static int GetEvolutionGP(int level) { return FindFightProperty(level + 1)?.Exp ?? (-1); } public static int GetEvolutionMax() { return dictionary_6.Count; } public static int GetEvolutionGrade(int GP) { int count = dictionary_6.Count; if (GP >= FindFightProperty(count).Exp) { return count; } for (int level = 1; level <= count; level++) { PetFightPropertyInfo fightProperty = FindFightProperty(level); if (fightProperty == null) { return 1; } if (GP < fightProperty.Exp) { if (level - 1 >= 0) { return level - 1; } return 0; } } return 0; } public static PetConfig FindConfig(string key) { if (dictionary_0 == null) { Init(); } if (dictionary_0.ContainsKey(key)) { return dictionary_0[key]; } return null; } public static PetLevel FindPetLevel(int level) { if (dictionary_1 == null) { Init(); } if (dictionary_1.ContainsKey(level)) { return dictionary_1[level]; } return null; } public static PetSkillElementInfo FindPetSkillElement(int SkillID) { if (dictionary_2 == null) { Init(); } if (dictionary_2.ContainsKey(SkillID)) { return dictionary_2[SkillID]; } return null; } public static PetSkillInfo FindPetSkill(int SkillID) { if (dictionary_3 == null) { Init(); } if (dictionary_3.ContainsKey(SkillID)) { return dictionary_3[SkillID]; } return null; } public static PetSkillInfo[] GetPetSkills() { List<PetSkillInfo> petSkillInfoList = new List<PetSkillInfo>(); if (dictionary_3 == null) { Init(); } foreach (PetSkillInfo petSkillInfo in dictionary_3.Values) { petSkillInfoList.Add(petSkillInfo); } return petSkillInfoList.ToArray(); } public static PetSkillTemplateInfo GetPetSkillTemplate(int ID) { if (dictionary_4 == null) { Init(); } if (dictionary_4.ContainsKey(ID)) { return dictionary_4[ID]; } return null; } public static PetTemplateInfo FindPetTemplate(int TemplateID) { readerWriterLock_0.AcquireWriterLock(-1); try { if (dictionary_5.ContainsKey(TemplateID)) { return dictionary_5[TemplateID]; } } finally { readerWriterLock_0.ReleaseWriterLock(); } return null; } public static PetTemplateInfo FindPetTemplateByKind(int star, int kindId) { foreach (PetTemplateInfo petTemplateInfo in dictionary_5.Values) { if (petTemplateInfo.KindID == kindId && star == petTemplateInfo.StarLevel) { return petTemplateInfo; } } return null; } public static List<int> GetPetSkillByKindID(int KindID, int lv, int playerLevel) { List<int> intList = new List<int>(); List<string> stringList = new List<string>(); PetSkillTemplateInfo[] petSkillByKindId = GetPetSkillByKindID(KindID); int num2 = (lv > playerLevel) ? playerLevel : lv; for (int index = 1; index <= num2; index++) { PetSkillTemplateInfo[] array = petSkillByKindId; foreach (PetSkillTemplateInfo skillTemplateInfo in array) { if (skillTemplateInfo.MinLevel == index) { string deleteSkillIds = skillTemplateInfo.DeleteSkillIDs; char[] chArray = new char[1] { ',' }; string[] array2 = deleteSkillIds.Split(chArray); foreach (string str in array2) { stringList.Add(str); } intList.Add(skillTemplateInfo.SkillID); } } } foreach (string s in stringList) { if (!string.IsNullOrEmpty(s)) { int num3 = int.Parse(s); intList.Remove(num3); } } intList.Sort(); return intList; } public static PetSkillTemplateInfo[] GetPetSkillByKindID(int KindID) { List<PetSkillTemplateInfo> skillTemplateInfoList = new List<PetSkillTemplateInfo>(); foreach (PetSkillTemplateInfo skillTemplateInfo in dictionary_4.Values) { if (skillTemplateInfo.KindID == KindID) { skillTemplateInfoList.Add(skillTemplateInfo); } } return skillTemplateInfoList.ToArray(); } public static List<UsersPetInfo> CreateFirstAdoptList(int userID, int playerLevel) { List<int> intList = new List<int> { 100301, 110301, 120301, 130301 }; List<UsersPetInfo> usersPetInfoList = new List<UsersPetInfo>(); for (int place = 0; place < intList.Count; place++) { UsersPetInfo pet = CreatePet(FindPetTemplate(intList[place]), userID, place, playerLevel); pet.IsExit = true; usersPetInfoList.Add(pet); } return usersPetInfoList; } public static string ActiveEquipSkill(int Level) { string str = "0,0"; int num = 1; if (Level >= 20 && Level < 30) { num++; } if (Level >= 30 && Level < 50) { num += 2; } if (Level >= 50 && Level < 60) { num += 3; } if (Level >= 60) { num += 4; } for (int index = 1; index < num; index++) { str = str + "|0," + index; } return str; } public static int UpdateEvolution(int TemplateID, int lv) { string str = TemplateID.ToString(); int int32_1 = Convert.ToInt32(FindConfig("EvolutionLevel1").Value); int int32_2 = Convert.ToInt32(FindConfig("EvolutionLevel2").Value); return FindPetTemplate((str.Substring(str.Length - 1, 1) == "1") ? ((lv < int32_1) ? TemplateID : ((lv >= int32_2) ? (TemplateID + 2) : (TemplateID + 1))) : ((!(str.Substring(str.Length - 1, 1) == "2")) ? TemplateID : (TemplateID + 1)))?.TemplateID ?? TemplateID; } public static string UpdateSkillPet(int Level, int TemplateID, int playerLevel) { PetTemplateInfo petTemplate = FindPetTemplate(TemplateID); if (petTemplate == null) { ilog_0.Error("Pet not found: " + TemplateID); return ""; } List<int> petSkillByKindId = GetPetSkillByKindID(petTemplate.KindID, Level, playerLevel); string str = petSkillByKindId[0] + ",0"; for (int index = 1; index < petSkillByKindId.Count; index++) { str = str + "|" + petSkillByKindId[index] + "," + index; } return str; } public static int GetLevel(int GP, int playerLevel) { if (GP >= FindPetLevel(playerLevel).GP) { return playerLevel; } for (int level2 = 1; level2 <= playerLevel; level2++) { if (GP < FindPetLevel(level2).GP) { if (level2 - 1 != 0) { return level2 - 1; } return 1; } } return 1; } public static int GetGP(int level, int playerLevel) { for (int level2 = 1; level2 <= playerLevel; level2++) { if (level == FindPetLevel(level2).Level) { return FindPetLevel(level2).GP; } } return 0; } public static void GetEvolutionPropArr(UsersPetInfo _petInfo, PetTemplateInfo petTempleteInfo, ref double[] propArr, ref double[] growArr) { double[] numArray1 = new double[5] { _petInfo.Blood * 100, _petInfo.Attack * 100, _petInfo.Defence * 100, _petInfo.Agility * 100, _petInfo.Luck * 100 }; double[] numArray2 = new double[5] { _petInfo.BloodGrow, _petInfo.AttackGrow, _petInfo.DefenceGrow, _petInfo.AgilityGrow, _petInfo.LuckGrow }; double[] numArray3 = new double[5] { petTempleteInfo.HighBlood, petTempleteInfo.HighAttack, petTempleteInfo.HighDefence, petTempleteInfo.HighAgility, petTempleteInfo.HighLuck }; double[] propArr2 = new double[5] { petTempleteInfo.HighBloodGrow, petTempleteInfo.HighAttackGrow, petTempleteInfo.HighDefenceGrow, petTempleteInfo.HighAgilityGrow, petTempleteInfo.HighLuckGrow }; double[] numArray4 = numArray3; double[] addedPropArr1 = GetAddedPropArr(1, propArr2); double[] numArray5 = numArray3; double[] addedPropArr2 = GetAddedPropArr(2, propArr2); double[] numArray6 = numArray3; double[] addedPropArr3 = GetAddedPropArr(3, propArr2); if (_petInfo.Level < 30) { for (int index3 = 0; index3 < numArray4.Length; index3++) { numArray4[index3] += (double)(_petInfo.Level - 1) * addedPropArr1[index3] - numArray1[index3]; addedPropArr1[index3] -= numArray2[index3]; numArray4[index3] = Math.Ceiling(numArray4[index3] / 10.0) / 10.0; addedPropArr1[index3] = Math.Ceiling(addedPropArr1[index3] / 10.0) / 10.0; } propArr = numArray4; growArr = addedPropArr1; } else if (_petInfo.Level < 50) { for (int index2 = 0; index2 < numArray5.Length; index2++) { numArray5[index2] += (double)(_petInfo.Level - 30) * addedPropArr2[index2] + 29.0 * addedPropArr1[index2] - numArray1[index2]; addedPropArr2[index2] -= numArray2[index2]; numArray5[index2] = Math.Ceiling(numArray5[index2] / 10.0) / 10.0; addedPropArr2[index2] = Math.Ceiling(addedPropArr2[index2] / 10.0) / 10.0; } propArr = numArray5; growArr = addedPropArr2; } else { for (int index = 0; index < numArray6.Length; index++) { numArray6[index] += (double)(_petInfo.Level - 50) * addedPropArr3[index] + 20.0 * addedPropArr2[index] + 29.0 * addedPropArr1[index] - numArray1[index]; addedPropArr3[index] -= numArray2[index]; numArray6[index] = Math.Ceiling(numArray6[index] / 10.0) / 10.0; addedPropArr3[index] = Math.Ceiling(addedPropArr3[index] / 10.0) / 10.0; } propArr = numArray6; growArr = addedPropArr3; } } public static double[] GetAddedPropArr(int grade, double[] propArr) { double[] numArray = new double[5] { propArr[0] * Math.Pow(2.0, grade - 1), 0.0, 0.0, 0.0, 0.0 }; for (int index = 1; index < 5; index++) { numArray[index] = propArr[index] * Math.Pow(1.5, grade - 1); } return numArray; } public static UsersPetInfo CreatePet(PetTemplateInfo info, int userID, int place, int playerLevel) { UsersPetInfo usersPetInfo = new UsersPetInfo(); double num = (double)info.StarLevel * 0.1; Random random = new Random(); usersPetInfo.BloodGrow = (int)Math.Ceiling((double)(random.Next((int)((double)info.HighBlood / (1.7 - num)), info.HighBlood - (int)((double)info.HighBlood / 17.1)) / 10)); usersPetInfo.AttackGrow = random.Next((int)((double)info.HighAttack / (1.7 - num)), info.HighAttack - (int)((double)info.HighAttack / 17.1)); usersPetInfo.DefenceGrow = random.Next((int)((double)info.HighDefence / (1.7 - num)), info.HighDefence - (int)((double)info.HighDefence / 17.1)); usersPetInfo.AgilityGrow = random.Next((int)((double)info.HighAgility / (1.7 - num)), info.HighAgility - (int)((double)info.HighAgility / 17.1)); usersPetInfo.LuckGrow = random.Next((int)((double)info.HighLuck / (1.7 - num)), info.HighLuck - (int)((double)info.HighLuck / 17.1)); usersPetInfo.ID = 0; usersPetInfo.Hunger = 10000; usersPetInfo.TemplateID = info.TemplateID; usersPetInfo.Name = info.Name; usersPetInfo.UserID = userID; usersPetInfo.Place = place; usersPetInfo.Level = 1; usersPetInfo.BuildProp(usersPetInfo); usersPetInfo.Skill = UpdateSkillPet(1, info.TemplateID, playerLevel); usersPetInfo.SkillEquip = ActiveEquipSkill(1); return usersPetInfo; } public static UsersPetInfo CreateNewPet() { string[] strArray = FindConfig("NewPet").Value.Split(','); int index = random_0.Next(strArray.Length); return CreatePet(FindPetTemplate(Convert.ToInt32(strArray[index])), -1, -1, 60); } public static GameNeedPetSkillInfo[] GetGameNeedPetSkill() { return list_0.ToArray(); } public static List<GameNeedPetSkillInfo> LoadGameNeedPetSkill() { List<GameNeedPetSkillInfo> needPetSkillInfoList = new List<GameNeedPetSkillInfo>(); List<string> stringList = new List<string>(); foreach (PetSkillInfo petSkillInfo in dictionary_3.Values) { string effectPic2 = petSkillInfo.EffectPic; if (!string.IsNullOrEmpty(effectPic2) && !stringList.Contains(effectPic2)) { needPetSkillInfoList.Add(new GameNeedPetSkillInfo { Pic = petSkillInfo.Pic, EffectPic = petSkillInfo.EffectPic }); stringList.Add(effectPic2); } } foreach (PetSkillElementInfo skillElementInfo in dictionary_2.Values) { string effectPic = skillElementInfo.EffectPic; if (!string.IsNullOrEmpty(effectPic) && !stringList.Contains(effectPic)) { needPetSkillInfoList.Add(new GameNeedPetSkillInfo { Pic = skillElementInfo.Pic, EffectPic = skillElementInfo.EffectPic }); stringList.Add(effectPic); } } return needPetSkillInfoList; } static PetMgr() { ilog_0 = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); list_0 = new List<GameNeedPetSkillInfo>(); readerWriterLock_0 = new ReaderWriterLock(); } } }
412
0.637474
1
0.637474
game-dev
MEDIA
0.733326
game-dev
0.801089
1
0.801089
techlabxe/game-programmer-book-build
1,439
src/08_2DCollision/BakudanBitoWithCollision/Sequence/Game/Judge.cpp
#include "GameLib/GameLib.h" #include "GameLib/Framework.h" using namespace GameLib; #include "Image.h" #include "Sequence/Game/Judge.h" #include "Sequence/Game/Parent.h" namespace Sequence{ namespace Game{ Judge::Judge() : mImage( 0 ), mCursorPosistion( 0 ){ mImage = new Image( "data/image/dummy.dds" ); } Judge::~Judge(){ SAFE_DELETE( mImage ); } void Judge::update( Parent* parent ){ Framework f = Framework::instance();; if ( f.isKeyTriggered( 'w' ) ){ --mCursorPosistion; if ( mCursorPosistion < 0 ){ //}CiX͍őlɃ[v mCursorPosistion = 1; } }else if ( f.isKeyTriggered( 'z' ) ){ ++mCursorPosistion; if ( mCursorPosistion > 1 ){ //1z0Ƀ[v mCursorPosistion = 0; } }else if ( f.isKeyTriggered( ' ' ) ){ if ( mCursorPosistion == 0 ){ //ď parent->moveTo( Parent::NEXT_READY ); }else if ( mCursorPosistion == 1 ){ //^Cg parent->moveTo( Parent::NEXT_TITLE ); } } //` //܂Q[ parent->drawState(); //ɏd˂ mImage->draw(); //܂ǂ̂\ f.drawDebugString( 0, 0, "[ʲò]" ); Parent::PlayerID winner = parent->winner(); if ( winner == Parent::PLAYER_1 ){ f.drawDebugString( 0, 1, "1P !" ); }else if ( winner == Parent::PLAYER_2 ){ f.drawDebugString( 0, 1, "2P !" ); }else{ f.drawDebugString( 0, 1, "ż! ˷ܹ!" ); } //߂ʁ[ f.drawDebugString( 1, 3, " ۼ" ); f.drawDebugString( 1, 4, " " ); //J[\ f.drawDebugString( 0, mCursorPosistion + 3, ">" ); } } //namespace Game } //namespace Sequence
412
0.650139
1
0.650139
game-dev
MEDIA
0.363203
game-dev
0.900867
1
0.900867
BredaUniversityGames/Y2024-25-PR-BB
1,699
engine/renderer/private/graphics_resources.cpp
#include "graphics_resources.hpp" #include "resource_management/buffer_resource_manager.hpp" #include "resource_management/image_resource_manager.hpp" #include "resource_management/material_resource_manager.hpp" #include "resource_management/mesh_resource_manager.hpp" #include "resource_management/model_resource_manager.hpp" #include "resource_management/sampler_resource_manager.hpp" GraphicsResources::GraphicsResources(const std::shared_ptr<VulkanContext>& vulkanContext) : _vulkanContext(vulkanContext) { _samplerResourceManager = std::make_shared<class SamplerResourceManager>(_vulkanContext); _samplerResourceManager->CreateDefaultSampler(); _bufferResourceManager = std::make_shared<class BufferResourceManager>(_vulkanContext); _imageResourceManager = std::make_shared<class ImageResourceManager>(_vulkanContext, _samplerResourceManager->GetDefaultSamplerHandle()); _materialResourceManager = std::make_shared<class MaterialResourceManager>(_imageResourceManager); _meshResourceManager = std::make_shared<class MeshResourceManager>(_vulkanContext); _modelResourceManager = std::make_shared<class ModelResourceManager>(_vulkanContext, _imageResourceManager, _materialResourceManager, _meshResourceManager); } void GraphicsResources::Clean() { _meshResourceManager->Clean(); _materialResourceManager->Clean(); _imageResourceManager->Clean(); _bufferResourceManager->Clean(); _samplerResourceManager->Clean(); } GraphicsResources::~GraphicsResources() { _meshResourceManager.reset(); _materialResourceManager.reset(); _imageResourceManager.reset(); _bufferResourceManager.reset(); _samplerResourceManager.reset(); }
412
0.618052
1
0.618052
game-dev
MEDIA
0.730475
game-dev,graphics-rendering
0.552638
1
0.552638
HbmMods/Hbm-s-Nuclear-Tech-GIT
2,885
src/main/java/com/hbm/inventory/gui/GUIForceField.java
package com.hbm.inventory.gui; import org.lwjgl.opengl.GL11; import com.hbm.inventory.container.ContainerForceField; import com.hbm.lib.RefStrings; import com.hbm.packet.PacketDispatcher; import com.hbm.packet.toserver.AuxButtonPacket; import com.hbm.tileentity.machine.TileEntityForceField; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.util.ResourceLocation; public class GUIForceField extends GuiInfoContainer { public static ResourceLocation texture = new ResourceLocation(RefStrings.MODID + ":textures/gui/gui_field.png"); private TileEntityForceField diFurnace; public GUIForceField(InventoryPlayer invPlayer, TileEntityForceField tedf) { super(new ContainerForceField(invPlayer, tedf)); diFurnace = tedf; this.xSize = 176; this.ySize = 168; } @Override public void drawScreen(int mouseX, int mouseY, float f) { super.drawScreen(mouseX, mouseY, f); this.drawElectricityInfo(this, mouseX, mouseY, guiLeft + 8, guiTop + 69 - 52, 16, 52, diFurnace.power, diFurnace.maxPower); this.drawCustomInfoStat(mouseX, mouseY, guiLeft + 62, guiTop + 69 - 52, 16, 52, mouseX, mouseY, new String[]{ diFurnace.health + " / " + diFurnace.maxHealth + "HP"} ); } @Override protected void drawGuiContainerForegroundLayer(int i, int j) { String name = this.diFurnace.hasCustomInventoryName() ? this.diFurnace.getInventoryName() : I18n.format(this.diFurnace.getInventoryName()); this.fontRendererObj.drawString(name, this.xSize / 2 - this.fontRendererObj.getStringWidth(name) / 2, 6, 4210752); this.fontRendererObj.drawString(I18n.format("container.inventory"), 8, this.ySize - 96 + 2, 4210752); } protected void mouseClicked(int x, int y, int i) { super.mouseClicked(x, y, i); if(guiLeft + 142 <= x && guiLeft + 142 + 18 > x && guiTop + 34 < y && guiTop + 34 + 18 >= y) { mc.getSoundHandler().playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F)); PacketDispatcher.wrapper.sendToServer(new AuxButtonPacket(diFurnace.xCoord, diFurnace.yCoord, diFurnace.zCoord, 0, 0)); } } @Override protected void drawGuiContainerBackgroundLayer(float p_146976_1_, int p_146976_2_, int p_146976_3_) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); Minecraft.getMinecraft().getTextureManager().bindTexture(texture); drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); int i = (int)diFurnace.getPowerScaled(52); drawTexturedModalRect(guiLeft + 8, guiTop + 69 - i, 176, 52 - i, 16, i); int j = diFurnace.getHealthScaled(52); drawTexturedModalRect(guiLeft + 62, guiTop + 69 - j, 192, 52 - j, 16, j); if(diFurnace.isOn) { drawTexturedModalRect(guiLeft + 142, guiTop + 34, 176, 52, 18, 18); } } }
412
0.859864
1
0.859864
game-dev
MEDIA
0.949174
game-dev
0.925711
1
0.925711
P3pp3rF1y/AncientWarfare2
1,846
src/main/java/net/shadowmage/ancientwarfare/npc/item/ItemRoutingOrder.java
package net.shadowmage.ancientwarfare.npc.item; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; import net.shadowmage.ancientwarfare.core.network.NetworkHandler; import net.shadowmage.ancientwarfare.core.util.RayTraceUtils; import net.shadowmage.ancientwarfare.npc.orders.RoutingOrder; import java.util.ArrayList; import java.util.List; public class ItemRoutingOrder extends ItemOrders { public ItemRoutingOrder() { super("routing_order"); } @Override public List<BlockPos> getPositionsForRender(ItemStack stack) { List<BlockPos> positionList = new ArrayList<>(); RoutingOrder order = RoutingOrder.getRoutingOrder(stack); if (order != null && !order.isEmpty()) { for (RoutingOrder.RoutePoint e : order.getEntries()) { positionList.add(e.getTarget()); } } return positionList; } @Override public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) { if (!world.isRemote) NetworkHandler.INSTANCE.openGui(player, NetworkHandler.GUI_NPC_ROUTING_ORDER, 0, 0, 0); return new ActionResult<>(EnumActionResult.SUCCESS, player.getHeldItem(hand)); } @Override public void onKeyAction(EntityPlayer player, ItemStack stack, ItemAltFunction altFunction) { RoutingOrder order = RoutingOrder.getRoutingOrder(stack); if (order != null) { RayTraceResult hit = RayTraceUtils.getPlayerTarget(player, 5, 0); if (hit != null && hit.typeOfHit == RayTraceResult.Type.BLOCK) { order.addRoutePoint(hit.sideHit, hit.getBlockPos()); order.write(stack); addMessage(player); } } } }
412
0.968321
1
0.968321
game-dev
MEDIA
0.99621
game-dev
0.987778
1
0.987778
AoTTG-2/AoTTG-2
2,822
Assets/Scripts/Characters/Titan/Attacks/BodyslamAttack.cs
using System; using Assets.Scripts.Characters.Humans; using UnityEngine; using Random = UnityEngine.Random; namespace Assets.Scripts.Characters.Titan.Attacks { public class BodySlamAttack : Attack<MindlessTitan> { private readonly string _startAnimation = "attack_abnormal_jump"; private readonly string _endAnimation = "attack_abnormal_getup"; private bool HasExploded { get; set; } private float WaitTime { get; set; } public override Type[] TargetTypes { get; } = { typeof(Human) }; public override bool CanAttack() { if (Titan.TargetDistance >= Titan.AttackDistance * 2) return false; if (IsDisabled()) return false; Vector3 vector18 = Titan.Target.transform.position - Titan.transform.position; var angle = -Mathf.Atan2(vector18.z, vector18.x) * Mathf.Rad2Deg; var between = -Mathf.DeltaAngle(angle, Titan.gameObject.transform.rotation.eulerAngles.y - 90f); return Mathf.Abs(between) < 90f && between > 0 && Titan.TargetDistance < Titan.AttackDistance * 0.5f; } public override void Execute() { if (IsFinished) return; if (!Titan.Animation.IsPlaying(_startAnimation) && !Titan.Animation.IsPlaying(_endAnimation)) { Titan.CrossFade(_startAnimation, 0.1f); HasExploded = false; //(this.myDifficulty <= 0) ? UnityEngine.Random.Range((float)1f, (float)4f) : UnityEngine.Random.Range((float)0f, (float)1f); WaitTime = Random.Range(0f, 1f); return; } if (!HasExploded && Titan.Animation[_startAnimation].normalizedTime >= 0.75f) { HasExploded = true; GameObject obj9; var rotation = Quaternion.Euler(270f, Titan.transform.rotation.eulerAngles.y, 0f); if (Titan.photonView.isMine) { obj9 = PhotonNetwork.Instantiate("FX/boom4", Titan.Body.AttackAbnormalJump.position, rotation, 0); } else { return; } obj9.transform.localScale = Titan.transform.localScale; if (obj9.GetComponent<EnemyfxIDcontainer>() != null) { obj9.GetComponent<EnemyfxIDcontainer>().titanName = Titan.name; } } if (Titan.Animation[_startAnimation].normalizedTime >= 1f + WaitTime) { Titan.Animation.CrossFade(_endAnimation, 0.1f); } if (Titan.Animation[_endAnimation].normalizedTime >= 1f) { IsFinished = true; } } } }
412
0.938988
1
0.938988
game-dev
MEDIA
0.991493
game-dev
0.982369
1
0.982369
Emudofus/Dofus
2,733
com/ankamagames/dofus/network/messages/game/actions/fight/GameActionFightReflectSpellMessage.as
package com.ankamagames.dofus.network.messages.game.actions.fight { import com.ankamagames.dofus.network.messages.game.actions.AbstractGameActionMessage; import com.ankamagames.jerakine.network.INetworkMessage; import flash.utils.ByteArray; import com.ankamagames.jerakine.network.CustomDataWrapper; import com.ankamagames.jerakine.network.ICustomDataOutput; import com.ankamagames.jerakine.network.ICustomDataInput; [Trusted] public class GameActionFightReflectSpellMessage extends AbstractGameActionMessage implements INetworkMessage { public static const protocolId:uint = 5531; private var _isInitialized:Boolean = false; public var targetId:int = 0; override public function get isInitialized():Boolean { return (((super.isInitialized) && (this._isInitialized))); } override public function getMessageId():uint { return (5531); } public function initGameActionFightReflectSpellMessage(actionId:uint=0, sourceId:int=0, targetId:int=0):GameActionFightReflectSpellMessage { super.initAbstractGameActionMessage(actionId, sourceId); this.targetId = targetId; this._isInitialized = true; return (this); } override public function reset():void { super.reset(); this.targetId = 0; this._isInitialized = false; } override public function pack(output:ICustomDataOutput):void { var data:ByteArray = new ByteArray(); this.serialize(new CustomDataWrapper(data)); writePacket(output, this.getMessageId(), data); } override public function unpack(input:ICustomDataInput, length:uint):void { this.deserialize(input); } override public function serialize(output:ICustomDataOutput):void { this.serializeAs_GameActionFightReflectSpellMessage(output); } public function serializeAs_GameActionFightReflectSpellMessage(output:ICustomDataOutput):void { super.serializeAs_AbstractGameActionMessage(output); output.writeInt(this.targetId); } override public function deserialize(input:ICustomDataInput):void { this.deserializeAs_GameActionFightReflectSpellMessage(input); } public function deserializeAs_GameActionFightReflectSpellMessage(input:ICustomDataInput):void { super.deserialize(input); this.targetId = input.readInt(); } } }//package com.ankamagames.dofus.network.messages.game.actions.fight
412
0.804328
1
0.804328
game-dev
MEDIA
0.974772
game-dev
0.861309
1
0.861309
QianMo/NPR-Cartoon-Shader-Library
18,583
Assets/[Models]/UnityChanTPK/Script/SpringBone/Utility/GameObjectUtil.cs
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using UnityEngine; namespace FUnit { namespace GameObjectExtensions { public static class GameObjectUtil { public enum SearchOptions { None, IgnoreNamespace // Maya風「namespace:objectname」の「namespace:」の部分を無視 } public static T AcquireComponent<T> ( this GameObject inGameObject, bool inCreateIfNotFound = false ) where T : Component { var component = inGameObject.GetComponent<T>(); if (null == component && inCreateIfNotFound) { component = inGameObject.AddComponent<T>(); } return component; } // ioComponentがnullの場合、inGameObjectとから最初に見つけたTを取得。 // 存在しなかった場合はfalseを返す。 public static bool AcquireComponent<T>(this GameObject inGameObject, ref T ioComponent) { if (ioComponent == null) { ioComponent = inGameObject.GetComponent<T>(); } return ioComponent != null; } public static IEnumerable<Transform> GetAllSceneTransforms() { var activeScene = UnityEngine.SceneManagement.SceneManager.GetActiveScene(); var rootObjects = activeScene.GetRootGameObjects(); var allTransforms = new List<Transform>(); foreach (var rootObject in rootObjects) { allTransforms.AddRange(rootObject.GetComponentsInChildren<Transform>(true)); } return allTransforms; } // ioComponentがnullの場合、inGameObjectとその子供たちから最初に見つけたTを取得。 // 存在しなかった場合はfalseを返す。 public static bool AcquireComponentInChildren<T> ( this GameObject inGameObject, ref T ioComponent, bool inCreateIfNotFound = false ) where T : Component { if (ioComponent == null) { ioComponent = inGameObject.GetComponentInChildren<T>(); } if (ioComponent == null && inCreateIfNotFound) { ioComponent = inGameObject.AddComponent<T>(); } return ioComponent != null; } // 指定したクラスの名前→コンポーネントのマップを作成 public static Dictionary<string, T> BuildNameToComponentMap<T> ( this GameObject rootObject, bool includeInactive ) where T : Component { var components = rootObject.GetComponentsInChildren<T>(includeInactive); return components.ToDictionary(item => item.name, item => item); } public static List<Transform> FindAllBonesByAnySubstring(this GameObject inRootObject, string[] inSubstrings) { var bones = new List<Transform>(); var substringCount = inSubstrings.Length; for (int substringIndex = 0; substringIndex < substringCount; substringIndex++) { FindAllBonesBySubstring(inRootObject, inSubstrings[substringIndex], bones); } return bones; } public static List<Transform> FindAllBonesBySubstring ( this GameObject inRootObject, string inSubstring ) { var list = new List<Transform>(); FindAllBonesBySubstring(inRootObject, inSubstring, list); return list; } public static void FindAllBonesBySubstring ( this GameObject inRootObject, string inSubstring, List<Transform> outBones ) { var bones = GetAllBones(inRootObject); var upperSubstring = inSubstring.ToUpperInvariant(); var matchingBones = from bone in bones where bone.name.ToUpperInvariant().Contains(upperSubstring) select bone; outBones.AddRange(matchingBones); } public static IEnumerable<Transform> GetAllBones(this GameObject rootObject) { var skinnedMeshRenderers = rootObject.GetComponentsInChildren<SkinnedMeshRenderer>(true); var bones = new HashSet<Transform>(); foreach (var renderer in skinnedMeshRenderers) { var rendererBones = renderer.bones; foreach (var bone in rendererBones) { bones.Add(bone); } } return bones; } public static List<Transform> FindAllChildrenByAnySubstring(this GameObject inRootObject, string[] inSubstrings) { var children = new List<Transform>(); var substringCount = inSubstrings.Length; for (int substringIndex = 0; substringIndex < substringCount; substringIndex++) { FindAllChildrenBySubstring(inRootObject, inSubstrings[substringIndex], children); } return children; } public static List<Transform> FindAllChildrenBySubstring ( this GameObject inRootObject, string inSubstring ) { var children = new List<Transform>(); FindAllChildrenBySubstring(inRootObject, inSubstring, children); return children; } public static void FindAllChildrenBySubstring ( this GameObject inRootObject, string inSubstring, List<Transform> outChildren ) { var upperSubstring = inSubstring.ToUpperInvariant(); var children = inRootObject.GetComponentsInChildren<Transform>(); var childCount = children.Length; for (var childIndex = 0; childIndex < childCount; childIndex++) { var child = children[childIndex]; if (child.name.ToUpperInvariant().Contains(upperSubstring)) { outChildren.Add(child); } } } public static IEnumerable<SkinnedMeshRenderer> FindBlendShapeRenderers(this GameObject rootObject) { return rootObject.GetComponentsInChildren<SkinnedMeshRenderer>(true) .Where(renderer => renderer.sharedMesh != null && renderer.sharedMesh.blendShapeCount > 0); } public static int FindBlendShapeTargetIndex(SkinnedMeshRenderer renderer, string targetName) { var sharedMesh = renderer.sharedMesh; var targetCount = (sharedMesh != null) ? sharedMesh.blendShapeCount : 0; var periodPrefixedName = "." + targetName; for (int targetIndex = 0; targetIndex < targetCount; targetIndex++) { var currentTargetName = sharedMesh.GetBlendShapeName(targetIndex); if (currentTargetName == targetName || currentTargetName.EndsWith(periodPrefixedName)) { return targetIndex; } } return -1; } public static Transform FindBoneByAnySubstring(this GameObject inRootObject, string[] inSubstrings) { var substringCount = inSubstrings.Length; for (var substringIndex = 0; substringIndex < substringCount; substringIndex++) { var bone = FindBoneBySubstring(inRootObject, inSubstrings[substringIndex]); if (bone != null) { return bone; } } return null; } // 名前にinSubstringが入っているボーンを検索します。 public static Transform FindBoneBySubstring(this GameObject inRootObject, string inSubstring) { var bones = GetAllBones(inRootObject); var upperSubstring = inSubstring.ToUpperInvariant(); return bones.FirstOrDefault(item => item.name.ToUpperInvariant().Contains(upperSubstring)); } public static Transform FindChildByName ( this GameObject inRoot, string inName, SearchOptions searchOptions = SearchOptions.IgnoreNamespace ) { return FindChildComponentByName<Transform>(inRoot, inName, searchOptions); } // 子供の指定した名前のオブジェクトを検出 public static T FindChildComponentByName<T> ( this GameObject inRoot, string inName, SearchOptions searchOptions = SearchOptions.IgnoreNamespace ) where T : Component { var lowerName = inName.ToLowerInvariant(); if (searchOptions == SearchOptions.IgnoreNamespace) { lowerName = RemoveNamespaceFromName(lowerName); } var children = inRoot.GetComponentsInChildren<T>(); var childCount = children.Length; for (int childIndex = 0; childIndex < childCount; childIndex++) { var child = children[childIndex]; var childName = child.gameObject.name.ToLowerInvariant(); if (searchOptions == SearchOptions.IgnoreNamespace) { childName = RemoveNamespaceFromName(childName); } if (childName == lowerName) { return child; } } return null; } // 子供の指定した名前のオブジェクトを検出 public static T[] FindChildComponentsByName<T> ( this GameObject inRoot, string[] inNames, SearchOptions searchOptions = SearchOptions.IgnoreNamespace ) where T : Component { var children = inRoot.GetComponentsInChildren<T>(); var outputList = new List<T>(); var childCount = children.Length; for (var childIndex = 0; childIndex < childCount; ++childIndex) { var child = children[childIndex]; var childName = child.gameObject.name.ToLowerInvariant(); if (searchOptions == SearchOptions.IgnoreNamespace) { childName = RemoveNamespaceFromName(childName); if (System.Array.Exists(inNames, searchName => RemoveNamespaceFromName(searchName.ToLowerInvariant()) == childName)) { outputList.Add(child); } } else { if (System.Array.Exists(inNames, searchName => searchName.ToLowerInvariant() == childName)) { outputList.Add(child); } } } return outputList.ToArray(); } // 正規表現で子供を検出 public static List<T> FindChildComponentsByRegularExpression<T> ( this GameObject rootObject, string pattern, RegexOptions regexOptions = RegexOptions.IgnoreCase, bool includeInactive = true ) where T : Component { var matchingComponents = new List<T>(); var regularExpression = new Regex(pattern, regexOptions); var allComponents = rootObject.GetComponentsInChildren<T>(includeInactive); var componentCount = allComponents.Length; for (int componentIndex = 0; componentIndex < componentCount; componentIndex++) { var component = allComponents[componentIndex]; if (regularExpression.IsMatch(component.name)) { matchingComponents.Add(component); } } return matchingComponents; } public static Transform[] FindChildrenByName ( this GameObject inRoot, string[] inNames, SearchOptions searchOptions = SearchOptions.IgnoreNamespace ) { return FindChildComponentsByName<Transform>(inRoot, inNames, searchOptions); } // この処理は重いので毎フレーム呼び出したりしないように public static GameObject FindGameObjectByInstanceID(int instanceIDToFind) { var objectList = Object.FindObjectsOfType<GameObject>(); var objectCount = objectList.Length; for (int objectIndex = 0; objectIndex < objectCount; objectIndex++) { var gameObject = objectList[objectIndex]; if (gameObject.GetInstanceID() == instanceIDToFind) { return gameObject; } } return null; } public static T RemoveAllOldAndAddNewComponent<T>(this GameObject gameObject) where T : Component { const int AttemptCount = 100; for (var attempt = 0; attempt < AttemptCount; ++attempt) { var oldComponent = gameObject.GetComponent<T>(); if (null != oldComponent) { Object.DestroyImmediate(oldComponent); } else { break; } } return gameObject.AddComponent<T>(); } public static string RemoveNamespaceFromName(string inName) { var splitName = inName.Split(new char[] { ':' }, System.StringSplitOptions.None); return (splitName.Length > 0) ? splitName[splitName.Length - 1] : ""; } public static IEnumerable<T> RemoveNulls<T>(IEnumerable<T> originalCollection) where T : Object { return originalCollection.Where(item => item != null); } public static int GetTransformDepth(Transform inObject) { var depth = 0; var currentObject = inObject; while (currentObject != null) { currentObject = currentObject.parent; ++depth; } return depth; } public static List<T> SortComponentsByDepth<T>(IEnumerable<T> sourceItems) where T : Component { var itemDepthList = sourceItems .Select(item => new ItemWithDepth<T>(item)) .ToList(); itemDepthList.Sort((a, b) => a.depth.CompareTo(b.depth)); var itemCount = itemDepthList.Count; var sortedItems = new List<T>(itemCount); for (int itemIndex = 0; itemIndex < itemCount; itemIndex++) { sortedItems.Add(itemDepthList[itemIndex].item); } return sortedItems; } #if UNITY_EDITOR // This exists here so we can pick objects from their OnGUI functions // (See e.g. SpringCapsuleCollider.OnGUI()) public static void SelectObjectInteractively(Object target) { #if UNITY_EDITOR_OSX if (Event.current.command) #else if (Event.current.control) #endif { // Toggle if (UnityEditor.Selection.Contains(target)) { RemoveFromSelection(target); } else { AddToSelection(target); } } else if (Event.current.shift) { AddToSelection(target); } else if (Event.current.alt) { RemoveFromSelection(target); } else { UnityEditor.Selection.objects = new Object[] { target }; } } private static void AddToSelection(Object target) { if (!UnityEditor.Selection.Contains(target)) { var newSelection = UnityEditor.Selection.objects.ToList(); newSelection.Add(target); UnityEditor.Selection.objects = newSelection.ToArray(); } } private static void RemoveFromSelection(Object target) { if (UnityEditor.Selection.Contains(target)) { UnityEditor.Selection.objects = UnityEditor.Selection.objects .Where(item => item != target) .ToArray(); } } #endif private class ItemWithDepth<T> where T : Component { public T item; public int depth; public ItemWithDepth(T inItem) { item = inItem; depth = GetTransformDepth(item.transform); } } } } }
412
0.89054
1
0.89054
game-dev
MEDIA
0.933646
game-dev
0.952565
1
0.952565
oiuv/mud
1,006
d/dali/npc/jiang.c
// wujiang.c 武将 inherit NPC; void create() { set_name("武将", ({ "wu jiang", "wu", "jiang" })); set("gender", "男性"); set("age", random(10) + 30); set("str", 25); set("dex", 16); set("long", "他站在那里,的确有说不出的威风。\n"); set("combat_exp", 75000); set("shen_type", 1); set("attitude", "peaceful"); set_skill("unarmed", 60); set_skill("force", 60); set_skill("sword", 60); set_skill("dodge", 60); set_skill("parry", 60); set_temp("apply/attack", 50); set_temp("apply/defense", 50); set_temp("apply/armor", 50); set_temp("apply/damage", 30); set("neili", 400); set("max_neili", 400); set("jiali", 10); setup(); carry_object("/clone/weapon/gangjian")->wield(); carry_object(__DIR__"obj/tiejia")->wear(); } void init() { object ob; ::init(); if (interactive(ob = this_player()) && (int)ob->query_condition("killer")) { remove_call_out("kill_ob"); call_out("kill_ob", 1, ob); } }
412
0.797379
1
0.797379
game-dev
MEDIA
0.938989
game-dev
0.724233
1
0.724233
rexrainbow/C2Plugins
4,064
plugins/rex_board_hexShapeMap/edittime.js
function GetPluginSettings() { return { "name": "Hex shape map", "id": "Rex_hexShapeMap", "version": "0.1", "description": "Shape map of hex grid", "author": "Rex.Rainbow", "help url": "https://rexrainbow.github.io/C2RexDoc/c2rexpluginsACE/plugin_rex_hexshapemap.html", "category": "Rex - Board - application", "type": "object", // not in layout "rotatable": false, "flags": 0 }; }; ////////////////////////////////////////////////////////////// // Conditions ////////////////////////////////////////////////////////////// // Actions AddObjectParam("Board", "Board object"); AddObjectParam("Tile", "Tile object."); AddLayerParam("Layer", "Layer name of number."); AddNumberParam("Radius", "Radius in grids.", 1); AddAction(1, 0, "Reset in hexagon", "Reset board", "Reset board <i>{0}</i> and fill tile <i>{1}</i> on layer <i>{2}</i> in hexagon shape with radius to <i>{3}</i>", "Reset board and fill tile with hexagon shape.", "ResetHexagon"); AddObjectParam("Board", "Board object"); AddObjectParam("Tile", "Tile object."); AddLayerParam("Layer", "Layer name of number."); AddComboParamOption("Down/Right"); AddComboParamOption("Top/Left"); AddComboParam("Face", "Face of triangle.", 0); AddNumberParam("Height", "Height in grids.", 1); AddAction(2, 0, "Reset in triangle", "Reset board", "Reset board <i>{0}</i> and fill tile <i>{1}</i> on layer <i>{2}</i> in <i>{3}</i> triangle shape with height to <i>{4}</i>", "Reset board and fill tile with triangle shape.", "ResetTriangle"); AddObjectParam("Board", "Board object"); AddObjectParam("Tile", "Tile object."); AddLayerParam("Layer", "Layer name of number."); AddComboParamOption("Type 0"); AddComboParamOption("Type 1"); AddComboParamOption("Type 2"); AddComboParam("Face", "Type of parallelogram.", 0); AddNumberParam("Width", "Width in grids.", 1); AddNumberParam("Height", "Height in grids.", 1); AddAction(3, 0, "Reset in parallelogram", "Reset board", "Reset board <i>{0}</i> and fill tile <i>{1}</i> on layer <i>{2}</i> in <i>{3}</i> parallelogram shape with <i>{4}</i>x<i>{5}</i>", "Reset board and fill tile with parallelogram shape.", "ResetParallelogram"); ////////////////////////////////////////////////////////////// // Expressions ACESDone(); // Property grid properties for this plugin var property_list = [ ]; // Called by IDE when a new object type is to be created function CreateIDEObjectType() { return new IDEObjectType(); } // Class representing an object type in the IDE function IDEObjectType() { assert2(this instanceof arguments.callee, "Constructor called as a function"); } // Called by IDE when a new object instance of this type is to be created IDEObjectType.prototype.CreateInstance = function(instance) { return new IDEInstance(instance, this); } // Class representing an individual instance of an object in the IDE function IDEInstance(instance, type) { assert2(this instanceof arguments.callee, "Constructor called as a function"); // Save the constructor parameters this.instance = instance; this.type = type; // Set the default property values from the property table this.properties = {}; for (var i = 0; i < property_list.length; i++) this.properties[property_list[i].name] = property_list[i].initial_value; } // Called by the IDE after all initialization on this instance has been completed IDEInstance.prototype.OnCreate = function() { } // Called by the IDE after a property has been changed IDEInstance.prototype.OnPropertyChanged = function(property_name) { } // Called by the IDE to draw this instance in the editor IDEInstance.prototype.Draw = function(renderer) { } // Called by the IDE when the renderer has been released (ie. editor closed) // All handles to renderer-created resources (fonts, textures etc) must be dropped. // Don't worry about releasing them - the renderer will free them - just null out references. IDEInstance.prototype.OnRendererReleased = function() { }
412
0.79762
1
0.79762
game-dev
MEDIA
0.405843
game-dev,desktop-app
0.941442
1
0.941442
JudsonSS/Jogos
1,358
Labs/Lab20S/TopGear/TopGear/Game.cpp
/********************************************************************************** // Game (Cdigo Fonte) // // Criao: 08 Dez 2012 // Atualizao: 10 Ago 2021 // Compilador: Visual C++ 2019 // // Descrio: Uma class abstrata para representar um jogo. // // Para criar um jogo o programador deve criar uma classe derivada // de Game e sobrescrever os mtodos Init, Update, Draw e Finalize. // Para rodar o jogo, deve-se passar o objeto Game para o mtodo // Start() de um objeto Engine. // **********************************************************************************/ #include "Game.h" #include "Engine.h" // ------------------------------------------------------------------------------- // Inicializao de membros estticos da classe Window* & Game::window = Engine::window; // ponteiro para a janela float & Game::gameTime = Engine::frameTime; // tempo do ltimo quadro // ------------------------------------------------------------------------------- Game::Game() { } // ------------------------------------------------------------------------------- Game::~Game() { } // ------------------------------------------------------------------------------- void Game::OnPause() { Sleep(10); } // -------------------------------------------------------------------------------
412
0.521629
1
0.521629
game-dev
MEDIA
0.929084
game-dev
0.622815
1
0.622815
RetroAchievements/RAEmus
4,787
bizhawk/BizHawk.Client.Common/lua/EmuLuaLibrary.Joypad.cs
using System; using LuaInterface; namespace BizHawk.Client.Common { public sealed class JoypadLuaLibrary : LuaLibraryBase { public JoypadLuaLibrary(Lua lua) : base(lua) { } public JoypadLuaLibrary(Lua lua, Action<string> logOutputCallback) : base(lua, logOutputCallback) { } public override string Name { get { return "joypad"; } } [LuaMethodAttributes( "get", "returns a lua table of the controller buttons pressed. If supplied, it will only return a table of buttons for the given controller" )] public LuaTable Get(int? controller = null) { var buttons = Lua.NewTable(); var adaptor = Global.AutofireStickyXORAdapter; foreach (var button in adaptor.Source.Type.BoolButtons) { if (!controller.HasValue) { buttons[button] = adaptor[button]; } else if (button.Length >= 3 && button.Substring(0, 2) == "P" + controller) { buttons[button.Substring(3)] = adaptor["P" + controller + " " + button.Substring(3)]; } } foreach (var button in adaptor.Source.Type.FloatControls) { if (controller == null) { buttons[button] = adaptor.GetFloat(button); } else if (button.Length >= 3 && button.Substring(0, 2) == "P" + controller) { buttons[button.Substring(3)] = adaptor.GetFloat("P" + controller + " " + button.Substring(3)); } } buttons["clear"] = null; buttons["getluafunctionslist"] = null; buttons["output"] = null; return buttons; } [LuaMethodAttributes( "getimmediate", "returns a lua table of any controller buttons currently pressed by the user" )] public LuaTable GetImmediate() { var buttons = Lua.NewTable(); foreach (var button in Global.ActiveController.Type.BoolButtons) { buttons[button] = Global.ActiveController[button]; } return buttons; } [LuaMethodAttributes( "setfrommnemonicstr", "sets the given buttons to their provided values for the current frame, string will be interpretted the same way an entry from a movie input log would be" )] public void SetFromMnemonicStr(string inputLogEntry) { try { var lg = Global.MovieSession.MovieControllerInstance(); lg.SetControllersAsMnemonic(inputLogEntry); foreach (var button in lg.Type.BoolButtons) { Global.LuaAndAdaptor.SetButton(button, lg.IsPressed(button)); } foreach (var floatButton in lg.Type.FloatControls) { Global.LuaAndAdaptor.SetFloat(floatButton, lg.GetFloat(floatButton)); } } catch (Exception) { Log("invalid mnemonic string: " + inputLogEntry); } } [LuaMethodAttributes( "set", "sets the given buttons to their provided values for the current frame" )] public void Set(LuaTable buttons, int? controller = null) { try { foreach (var button in buttons.Keys) { var invert = false; bool? theValue; var theValueStr = buttons[button].ToString(); if (!String.IsNullOrWhiteSpace(theValueStr)) { if (theValueStr.ToLower() == "false") { theValue = false; } else if (theValueStr.ToLower() == "true") { theValue = true; } else { invert = true; theValue = null; } } else { theValue = null; } var toPress = button.ToString(); if (controller.HasValue) { toPress = "P" + controller + " " + button; } if (!invert) { if (theValue.HasValue) // Force { Global.LuaAndAdaptor.SetButton(toPress, theValue.Value); Global.ActiveController.Overrides(Global.LuaAndAdaptor); } else // Unset { Global.LuaAndAdaptor.UnSet(toPress); Global.ActiveController.Overrides(Global.LuaAndAdaptor); } } else // Inverse { Global.LuaAndAdaptor.SetInverse(toPress); Global.ActiveController.Overrides(Global.LuaAndAdaptor); } } } catch { /*Eat it*/ } } [LuaMethodAttributes( "setanalog", "sets the given analog controls to their provided values for the current frame. Note that unlike set() there is only the logic of overriding with the given value." )] public void SetAnalog(LuaTable controls, object controller = null) { try { foreach (var name in controls.Keys) { var theValueStr = controls[name].ToString(); if (!String.IsNullOrWhiteSpace(theValueStr)) { try { var theValue = float.Parse(theValueStr); if (controller == null) { Global.StickyXORAdapter.SetFloat(name.ToString(), theValue); } else { Global.StickyXORAdapter.SetFloat("P" + controller + " " + name, theValue); } } catch { } } } } catch { /*Eat it*/ } } } }
412
0.783765
1
0.783765
game-dev
MEDIA
0.818335
game-dev
0.831339
1
0.831339
cmangos/mangos-wotlk
3,846
src/game/AI/ScriptDevAI/scripts/northrend/draktharon_keep/draktharon_keep.h
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information * This program is free software licensed under GPL version 2 * Please see the included DOCS/LICENSE.TXT for more information */ #ifndef DEF_DRAKTHARON_KEEP_H #define DEF_DRAKTHARON_KEEP_H enum { MAX_ENCOUNTER = 4, TYPE_TROLLGORE = 0, TYPE_NOVOS = 1, TYPE_KING_DRED = 2, TYPE_THARONJA = 3, NPC_NOVOS = 26631, NPC_KING_DRED = 27483, // Adds of King Dred Encounter - deaths counted for achievement NPC_DRAKKARI_GUTRIPPER = 26641, NPC_DRAKKARI_SCYTHECLAW = 26628, NPC_WORLD_TRIGGER = 22515, // Novos Encounter NPC_CRYSTAL_HANDLER = 26627, NPC_HULKING_CORPSE = 27597, NPC_FETID_TROLL_CORPSE = 27598, NPC_RISON_SHADOWCASTER = 27600, NPC_ROTTED_TROLL_CORPSE = 32786, // On heroic as effect of 59910 SPELL_BEAM_CHANNEL = 52106, SPELL_CRYSTAL_HANDLER_DEATH_1 = 47336, SPELL_CRYSTAL_HANDLER_DEATH_2 = 55801, SPELL_CRYSTAL_HANDLER_DEATH_3 = 55803, SPELL_CRYSTAL_HANDLER_DEATH_4 = 55805, MAX_CRYSTALS = 4, NPC_CRYSTAL_CHANNEL_TARGET = 26712, GO_CRYSTAL_SW = 189299, GO_CRYSTAL_NE = 189300, GO_CRYSTAL_NW = 189301, GO_CRYSTAL_SE = 189302, // Achievement Criterias to be handled with SD2 ACHIEV_CRIT_BETTER_OFF_DREAD = 7318, ACHIEV_CRIT_CONSUME_JUNCTION = 7579, ACHIEV_CRIT_OH_NOVOS = 7361, }; static const uint32 aCrystalHandlerDeathSpells[MAX_CRYSTALS] = {SPELL_CRYSTAL_HANDLER_DEATH_1, SPELL_CRYSTAL_HANDLER_DEATH_2, SPELL_CRYSTAL_HANDLER_DEATH_3, SPELL_CRYSTAL_HANDLER_DEATH_4}; struct NovosCrystalInfo { ObjectGuid m_crystalGuid; ObjectGuid m_channelGuid; bool m_bWasUsed; }; class instance_draktharon_keep : public ScriptedInstance { public: instance_draktharon_keep(Map* pMap); ~instance_draktharon_keep() {} void Initialize() override; void SetData(uint32 uiType, uint32 uiData) override; uint32 GetData(uint32 uiType) const override; void OnCreatureEnterCombat(Creature* pCreature) override; void OnCreatureEvade(Creature* pCreature) override; void OnCreatureDeath(Creature* pCreature) override; void OnCreatureCreate(Creature* pCreature) override; void OnObjectCreate(GameObject* pGo) override; void GetTrollgoreOutsideTriggers(GuidVector& vTriggers) const { vTriggers = m_vTriggerGuids; } ObjectGuid GetTrollgoreCornerTrigger() const { return m_trollgoreCornerTriggerGuid; } bool CheckAchievementCriteriaMeet(uint32 uiCriteriaId, Player const* pSource, Unit const* pTarget, uint32 uiMiscValue1 /* = 0*/) const override; const char* Save() const override { return m_strInstData.c_str(); } void Load(const char* chrIn) override; Creature* GetNextCrystalTarget(Creature* pCrystalHandler, uint8& uiIndex) const; void DoHandleCrystal(uint8 uiIndex); Creature* GetSummonDummy(); protected: void DoSortNovosDummies(); uint32 m_auiEncounter[MAX_ENCOUNTER]; std::string m_strInstData; uint32 m_uiDreadAddsKilled; bool m_bNovosAddGrounded; bool m_bTrollgoreConsume; ObjectGuid m_novosChannelGuid; ObjectGuid m_trollgoreCornerTriggerGuid; NovosCrystalInfo m_aNovosCrystalInfo[MAX_CRYSTALS]; GuidVector m_vSummonDummyGuids; GuidList m_lNovosDummyGuids; GuidVector m_vTriggerGuids; }; #endif
412
0.949323
1
0.949323
game-dev
MEDIA
0.93789
game-dev
0.751808
1
0.751808
ProjectIgnis/CardScripts
1,718
unofficial/c511001730.lua
--Twin Volcano local s,id=GetID() function s.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --damage local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(33737664,0)) e2:SetCategory(CATEGORY_DAMAGE) e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e2:SetRange(LOCATION_SZONE) e2:SetCountLimit(1) e2:SetCode(EVENT_PHASE+PHASE_STANDBY) e2:SetCondition(s.damcon) e2:SetTarget(s.damtg) e2:SetOperation(s.damop) c:RegisterEffect(e2) --damage2 local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(511000527,0)) e2:SetCategory(CATEGORY_DAMAGE) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e2:SetRange(LOCATION_SZONE) e2:SetCost(s.cost) e2:SetTarget(s.damtg) e2:SetOperation(s.damop2) c:RegisterEffect(e2) end function s.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToGraveAsCost() end Duel.SendtoGrave(e:GetHandler(),REASON_COST) end function s.damcon(e,tp,eg,ep,ev,re,r,rp) return tp==Duel.GetTurnPlayer() end function s.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(500) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,500) end function s.damop(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end function s.damop2(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end
412
0.7594
1
0.7594
game-dev
MEDIA
0.987382
game-dev
0.748833
1
0.748833
ISSMteam/ISSM
1,783
src/m/classes/radaroverlay.m
%RADAROVERLAY class definition % % Usage: % radaroverlay=radaroverlay(); classdef radaroverlay properties (SetAccess=public) pwr = NaN; x = NaN; y = NaN; outerindex = NaN; outerx = NaN; outery = NaN; outerheight = NaN; end methods function self = radaroverlay(varargin) % {{{ switch nargin case 0 self=setdefaultparameters(self); otherwise error('constructor not supported'); end end % }}} function self = setdefaultparameters(self) % {{{ end % }}} function disp(self) % {{{ disp(sprintf(' radaroverlay parameters:')); fielddisplay(self,'pwr','radar power image (matrix)'); fielddisplay(self,'x','corresponding x coordinates [m]'); fielddisplay(self,'y','corresponding y coordinates [m]'); fielddisplay(self,'outerindex','outer triangulation corresponding to space between mesh and the bounding box'); fielddisplay(self,'outerx','outer x corresponding to space between mesh and the bounding box'); fielddisplay(self,'outery','outer y corresponding to space between mesh and the bounding box'); fielddisplay(self,'outerheight','outer height corresponding to space between mesh and the bounding box'); end % }}} function savemodeljs(self,fid,modelname) % {{{ if ~isnan(self.pwr), writejs1Darray(fid,[modelname '.radaroverlay.xlim'],[min(self.x) max(self.x)]); writejs1Darray(fid,[modelname '.radaroverlay.ylim'],[min(self.y) max(self.y)]); writejs2Darray(fid,[modelname '.radaroverlay.outerindex'],self.outerindex); writejs1Darray(fid,[modelname '.radaroverlay.outerx'],self.outerx); writejs1Darray(fid,[modelname '.radaroverlay.outery'],self.outery); writejs1Darray(fid,[modelname '.radaroverlay.outerheight'],self.outerheight) end end % }}} end end
412
0.865099
1
0.865099
game-dev
MEDIA
0.260171
game-dev
0.792299
1
0.792299
LiteLDev/LeviLamina
1,350
src-server/mc/world/actor/animal/PolarBear.h
#pragma once #include "mc/_HeaderOutputPredefine.h" // auto generated inclusion list #include "mc/world/actor/animal/Animal.h" // auto generated forward declare list // clang-format off class ActorDefinitionGroup; class EntityContext; struct ActorDefinitionIdentifier; // clang-format on class PolarBear : public ::Animal { public: // prevent constructor by default PolarBear(); public: // virtual functions // NOLINTBEGIN // vIndex: 85 virtual bool canFreeze() const /*override*/; // vIndex: 8 virtual ~PolarBear() /*override*/ = default; // NOLINTEND public: // member functions // NOLINTBEGIN MCAPI PolarBear( ::ActorDefinitionGroup* definitions, ::ActorDefinitionIdentifier const& definitionName, ::EntityContext& entityContext ); // NOLINTEND public: // constructor thunks // NOLINTBEGIN MCAPI void* $ctor( ::ActorDefinitionGroup* definitions, ::ActorDefinitionIdentifier const& definitionName, ::EntityContext& entityContext ); // NOLINTEND public: // virtual function thunks // NOLINTBEGIN MCFOLD bool $canFreeze() const; // NOLINTEND public: // vftables // NOLINTBEGIN MCNAPI static void** $vftable(); // NOLINTEND };
412
0.609223
1
0.609223
game-dev
MEDIA
0.691693
game-dev
0.62977
1
0.62977
gameplay3d/gameplay-deps
2,335
bullet-2.82-r2704/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.cpp
/* 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. */ /// This file was created by Alex Silverman #include "BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.h" #include "BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.h" //#include "BulletCollision/CollisionShapes/btOptimizedBvh.h" ///Obtains the material for a specific triangle const btMaterial * btMultimaterialTriangleMeshShape::getMaterialProperties(int partID, int triIndex) { const unsigned char * materialBase = 0; int numMaterials; PHY_ScalarType materialType; int materialStride; const unsigned char * triangleMaterialBase = 0; int numTriangles; int triangleMaterialStride; PHY_ScalarType triangleType; ((btTriangleIndexVertexMaterialArray*)m_meshInterface)->getLockedReadOnlyMaterialBase(&materialBase, numMaterials, materialType, materialStride, &triangleMaterialBase, numTriangles, triangleMaterialStride, triangleType, partID); // return the pointer to the place with the friction for the triangle // TODO: This depends on whether it's a moving mesh or not // BUG IN GIMPACT //return (btScalar*)(&materialBase[triangleMaterialBase[(triIndex-1) * triangleMaterialStride] * materialStride]); int * matInd = (int *)(&(triangleMaterialBase[(triIndex * triangleMaterialStride)])); btMaterial *matVal = (btMaterial *)(&(materialBase[*matInd * materialStride])); return (matVal); }
412
0.746574
1
0.746574
game-dev
MEDIA
0.836872
game-dev,graphics-rendering
0.768015
1
0.768015
Pursue525/Nattalie-1.12.2
6,558
src/net/minecraft/block/BlockEndPortalFrame.java
package net.minecraft.block; import com.google.common.base.Predicates; import java.util.List; import java.util.Random; import javax.annotation.Nullable; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.properties.PropertyDirection; import net.minecraft.block.state.BlockFaceShape; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.BlockWorldState; import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.pattern.BlockPattern; import net.minecraft.block.state.pattern.BlockStateMatcher; import net.minecraft.block.state.pattern.FactoryBlockPattern; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.util.EnumFacing; import net.minecraft.util.Mirror; import net.minecraft.util.Rotation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class BlockEndPortalFrame extends Block { public static final PropertyDirection FACING = BlockHorizontal.FACING; public static final PropertyBool EYE = PropertyBool.create("eye"); protected static final AxisAlignedBB AABB_BLOCK = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.8125D, 1.0D); protected static final AxisAlignedBB AABB_EYE = new AxisAlignedBB(0.3125D, 0.8125D, 0.3125D, 0.6875D, 1.0D, 0.6875D); private static BlockPattern portalShape; public BlockEndPortalFrame() { super(Material.ROCK, MapColor.GREEN); this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH).withProperty(EYE, Boolean.valueOf(false))); } /** * Used to determine ambient occlusion and culling when rebuilding chunks for render */ public boolean isOpaqueCube(IBlockState state) { return false; } public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return AABB_BLOCK; } public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn, boolean p_185477_7_) { addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_BLOCK); if (((Boolean)worldIn.getBlockState(pos).getValue(EYE)).booleanValue()) { addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_EYE); } } /** * Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState state, Random rand, int fortune) { return Items.field_190931_a; } /** * Called by ItemBlocks just before a block is actually set in the world, to allow for adjustments to the * IBlockstate */ public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { return this.getDefaultState().withProperty(FACING, placer.getHorizontalFacing().getOpposite()).withProperty(EYE, Boolean.valueOf(false)); } public boolean hasComparatorInputOverride(IBlockState state) { return true; } public int getComparatorInputOverride(IBlockState blockState, World worldIn, BlockPos pos) { return ((Boolean)blockState.getValue(EYE)).booleanValue() ? 15 : 0; } /** * Convert the given metadata into a BlockState for this Block */ public IBlockState getStateFromMeta(int meta) { return this.getDefaultState().withProperty(EYE, Boolean.valueOf((meta & 4) != 0)).withProperty(FACING, EnumFacing.getHorizontal(meta & 3)); } /** * Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState state) { int i = 0; i = i | ((EnumFacing)state.getValue(FACING)).getHorizontalIndex(); if (((Boolean)state.getValue(EYE)).booleanValue()) { i |= 4; } return i; } /** * Returns the blockstate with the given rotation from the passed blockstate. If inapplicable, returns the passed * blockstate. */ public IBlockState withRotation(IBlockState state, Rotation rot) { return state.withProperty(FACING, rot.rotate((EnumFacing)state.getValue(FACING))); } /** * Returns the blockstate with the given mirror of the passed blockstate. If inapplicable, returns the passed * blockstate. */ public IBlockState withMirror(IBlockState state, Mirror mirrorIn) { return state.withRotation(mirrorIn.toRotation((EnumFacing)state.getValue(FACING))); } protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, new IProperty[] {FACING, EYE}); } public boolean isFullCube(IBlockState state) { return false; } public static BlockPattern getOrCreatePortalShape() { if (portalShape == null) { portalShape = FactoryBlockPattern.start().aisle("?vvv?", ">???<", ">???<", ">???<", "?^^^?").where('?', BlockWorldState.hasState(BlockStateMatcher.ANY)).where('^', BlockWorldState.hasState(BlockStateMatcher.forBlock(Blocks.END_PORTAL_FRAME).where(EYE, Predicates.equalTo(Boolean.valueOf(true))).where(FACING, Predicates.equalTo(EnumFacing.SOUTH)))).where('>', BlockWorldState.hasState(BlockStateMatcher.forBlock(Blocks.END_PORTAL_FRAME).where(EYE, Predicates.equalTo(Boolean.valueOf(true))).where(FACING, Predicates.equalTo(EnumFacing.WEST)))).where('v', BlockWorldState.hasState(BlockStateMatcher.forBlock(Blocks.END_PORTAL_FRAME).where(EYE, Predicates.equalTo(Boolean.valueOf(true))).where(FACING, Predicates.equalTo(EnumFacing.NORTH)))).where('<', BlockWorldState.hasState(BlockStateMatcher.forBlock(Blocks.END_PORTAL_FRAME).where(EYE, Predicates.equalTo(Boolean.valueOf(true))).where(FACING, Predicates.equalTo(EnumFacing.EAST)))).build(); } return portalShape; } public BlockFaceShape func_193383_a(IBlockAccess p_193383_1_, IBlockState p_193383_2_, BlockPos p_193383_3_, EnumFacing p_193383_4_) { return p_193383_4_ == EnumFacing.DOWN ? BlockFaceShape.SOLID : BlockFaceShape.UNDEFINED; } }
412
0.85775
1
0.85775
game-dev
MEDIA
0.985454
game-dev
0.948639
1
0.948639
CalamityTeam/CalamityModPublic
5,009
Projectiles/Rogue/ButcherKnife.cs
using System; using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace CalamityMod.Projectiles.Rogue { public class ButcherKnife : ModProjectile, ILocalizedModType { public new string LocalizationCategory => "Projectiles.Rogue"; private static float RotationIncrement = 0.22f; private static float ReboundTime = 26f; public override void SetStaticDefaults() { ProjectileID.Sets.TrailCacheLength[Projectile.type] = 6; ProjectileID.Sets.TrailingMode[Projectile.type] = 0; } public override void SetDefaults() { Projectile.width = 14; Projectile.height = 14; Projectile.friendly = true; Projectile.ignoreWater = true; Projectile.penetrate = -1; Projectile.timeLeft = 300; Projectile.DamageType = RogueDamageClass.Instance; Projectile.extraUpdates = 1; Projectile.usesLocalNPCImmunity = true; Projectile.localNPCHitCooldown = 60; Projectile.tileCollide = true; } public override void AI() { if (Main.rand.NextBool()) { Dust.NewDust(Projectile.position + Projectile.velocity, Projectile.width, Projectile.height, DustID.Blood, Projectile.velocity.X * 0.5f, Projectile.velocity.Y * 0.5f); } DrawOffsetX = -11; DrawOriginOffsetY = -10; DrawOriginOffsetX = 0; // ai[0] stores whether the knife is returning. If 0, it isn't. If 1, it is. if (Projectile.ai[0] == 0f) { Projectile.ai[1] += 1f; if (Projectile.ai[1] >= ReboundTime) { Projectile.ai[0] = 1f; Projectile.ai[1] = 0f; Projectile.netUpdate = true; } } else { Projectile.tileCollide = false; float returnSpeed = 16f; float acceleration = 3.2f; Player owner = Main.player[Projectile.owner]; // Delete the knife if it's excessively far away. Vector2 playerCenter = owner.Center; float xDist = playerCenter.X - Projectile.Center.X; float yDist = playerCenter.Y - Projectile.Center.Y; float dist = (float)Math.Sqrt((double)(xDist * xDist + yDist * yDist)); if (dist > 3000f) Projectile.Kill(); dist = returnSpeed / dist; xDist *= dist; yDist *= dist; // Home back in on the player. if (Projectile.velocity.X < xDist) { Projectile.velocity.X = Projectile.velocity.X + acceleration; if (Projectile.velocity.X < 0f && xDist > 0f) Projectile.velocity.X += acceleration; } else if (Projectile.velocity.X > xDist) { Projectile.velocity.X = Projectile.velocity.X - acceleration; if (Projectile.velocity.X > 0f && xDist < 0f) Projectile.velocity.X -= acceleration; } if (Projectile.velocity.Y < yDist) { Projectile.velocity.Y = Projectile.velocity.Y + acceleration; if (Projectile.velocity.Y < 0f && yDist > 0f) Projectile.velocity.Y += acceleration; } else if (Projectile.velocity.Y > yDist) { Projectile.velocity.Y = Projectile.velocity.Y - acceleration; if (Projectile.velocity.Y > 0f && yDist < 0f) Projectile.velocity.Y -= acceleration; } // Delete the projectile if it touches its owner. if (Main.myPlayer == Projectile.owner) if (Projectile.Hitbox.Intersects(owner.Hitbox)) Projectile.Kill(); } // Rotate the knife as it flies. Projectile.rotation += RotationIncrement; return; } public override bool OnTileCollide(Vector2 oldVelocity) { Projectile.ai[0] += 0.1f; if (Projectile.velocity.X != oldVelocity.X) { Projectile.velocity.X = -oldVelocity.X; } if (Projectile.velocity.Y != oldVelocity.Y) { Projectile.velocity.Y = -oldVelocity.Y; } return false; } public override bool PreDraw(ref Color lightColor) { CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1); return false; } } }
412
0.796719
1
0.796719
game-dev
MEDIA
0.997562
game-dev
0.923724
1
0.923724
geektcp/UeCore
6,496
src/bindings/scriptdev2/scripts/world/mob_generic_creature.cpp
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Generic_Creature SD%Complete: 80 SDComment: Should be replaced with core based AI SDCategory: Creatures EndScriptData */ #include "precompiled.h" #define GENERIC_CREATURE_COOLDOWN 5000 struct generic_creatureAI : public ScriptedAI { generic_creatureAI(Creature* pCreature) : ScriptedAI(pCreature) {Reset();} uint32 GlobalCooldown; // This variable acts like the global cooldown that players have (1.5 seconds) uint32 BuffTimer; // This variable keeps track of buffs bool IsSelfRooted; void Reset() override { GlobalCooldown = 0; BuffTimer = 0; // Rebuff as soon as we can IsSelfRooted = false; } void Aggro(Unit* who) override { if (!m_creature->CanReachWithMeleeAttack(who)) { IsSelfRooted = true; } } void UpdateAI(const uint32 diff) override { // Always decrease our global cooldown first if (GlobalCooldown > diff) GlobalCooldown -= diff; else GlobalCooldown = 0; // Buff timer (only buff when we are alive and not in combat if (!m_creature->isInCombat() && m_creature->isAlive()) { if (BuffTimer < diff) { // Find a spell that targets friendly and applies an aura (these are generally buffs) SpellEntry const* info = SelectSpell(m_creature, -1, -1, SELECT_TARGET_ANY_FRIEND, 0, 0, 0, 0, SELECT_EFFECT_AURA); if (info && !GlobalCooldown) { // Cast the buff spell DoCastSpell(m_creature, info); // Set our global cooldown GlobalCooldown = GENERIC_CREATURE_COOLDOWN; // Set our timer to 10 minutes before rebuff BuffTimer = 600000; }// Try agian in 30 seconds else BuffTimer = 30000; } else BuffTimer -= diff; } // Return since we have no target if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; // Return if we already cast a spell if (m_creature->IsNonMeleeSpellCasted(false)) return; // If we are within range melee the target if (m_creature->CanReachWithMeleeAttack(m_creature->getVictim())) { // Make sure our attack is ready if (m_creature->isAttackReady()) { bool Healing = false; SpellEntry const* info = nullptr; // Select a healing spell if less than 30% hp if (m_creature->GetHealthPercent() < 30.0f) info = SelectSpell(m_creature, -1, -1, SELECT_TARGET_ANY_FRIEND, 0, 0, 0, 0, SELECT_EFFECT_HEALING); // No healing spell available, select a hostile spell if (info) Healing = true; else info = SelectSpell(m_creature->getVictim(), -1, -1, SELECT_TARGET_ANY_ENEMY, 0, 0, 0, 0, SELECT_EFFECT_DONTCARE); // 50% chance if elite or higher, 20% chance if not, to replace our white hit with a spell if (info && (rand() % (m_creature->GetCreatureInfo()->Rank > 1 ? 2 : 5) == 0) && !GlobalCooldown) { // Cast the spell if (Healing)DoCastSpell(m_creature, info); else DoCastSpell(m_creature->getVictim(), info); // Set our global cooldown GlobalCooldown = GENERIC_CREATURE_COOLDOWN; } else m_creature->AttackerStateUpdate(m_creature->getVictim()); m_creature->resetAttackTimer(); } } else { bool Healing = false; SpellEntry const* info = nullptr; // Select a healing spell if less than 30% hp ONLY 33% of the time if (m_creature->GetHealthPercent() < 30.0f && !urand(0, 2)) info = SelectSpell(m_creature, -1, -1, SELECT_TARGET_ANY_FRIEND, 0, 0, 0, 0, SELECT_EFFECT_HEALING); // No healing spell available, See if we can cast a ranged spell (Range must be greater than ATTACK_DISTANCE) if (info) Healing = true; else info = SelectSpell(m_creature->getVictim(), -1, -1, SELECT_TARGET_ANY_ENEMY, 0, 0, ATTACK_DISTANCE, 0, SELECT_EFFECT_DONTCARE); // Found a spell, check if we arn't on cooldown if (info && !GlobalCooldown) { // If we are currently moving stop us and set the movement generator if (!IsSelfRooted) { IsSelfRooted = true; } // Cast spell if (Healing) DoCastSpell(m_creature, info); else DoCastSpell(m_creature->getVictim(), info); // Set our global cooldown GlobalCooldown = GENERIC_CREATURE_COOLDOWN; }// If no spells available and we arn't moving run to target else if (IsSelfRooted) { // Cancel our current spell and then allow movement agian m_creature->InterruptNonMeleeSpells(false); IsSelfRooted = false; } } } }; CreatureAI* GetAI_generic_creature(Creature* pCreature) { return new generic_creatureAI(pCreature); } void AddSC_generic_creature() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "generic_creature"; pNewScript->GetAI = &GetAI_generic_creature; pNewScript->RegisterSelf(false); }
412
0.883908
1
0.883908
game-dev
MEDIA
0.985752
game-dev
0.965233
1
0.965233
squeek502/AppleCore
3,182
java/squeek/applecore/AppleCore.java
package squeek.applecore; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.MetadataCollection; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLInterModComms; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import squeek.applecore.api_impl.AppleCoreAccessorMutatorImpl; import squeek.applecore.api_impl.AppleCoreRegistryImpl; import squeek.applecore.asm.TransformerModuleHandler; import squeek.applecore.commands.Commands; import squeek.applecore.network.SyncHandler; import squeek.asmhelper.applecore.ObfHelper; import java.io.InputStream; import java.util.Map; @IFMLLoadingPlugin.SortingIndex(1100) @IFMLLoadingPlugin.MCVersion("1.12.2") @IFMLLoadingPlugin.TransformerExclusions({"squeek.applecore.asm", "squeek.asmhelper"}) @Mod(modid = ModInfo.MODID, name = ModInfo.MODNAME, version = ModInfo.VERSION, acceptedMinecraftVersions="[1.12.2]", acceptableRemoteVersions = "*", dependencies = "required-after:forge@[14.23,)") public class AppleCore implements IFMLLoadingPlugin { public static final Logger LOG = LogManager.getLogger(ModInfo.MODID); @EventHandler public void preInit(FMLPreInitializationEvent event) { // too lazy to figure out a real solution for this (@Mod enforces mcmod.info filename) // this will at least allow the metadata to populate the mod listing, though InputStream is = MetadataCollection.class.getResourceAsStream("/applecore.info"); MetadataCollection metadataCollection = MetadataCollection.from(is, ModInfo.MODID); Loader.instance().activeModContainer().bindMetadata(metadataCollection); // force initialization of the singletons AppleCoreAccessorMutatorImpl.values(); AppleCoreRegistryImpl.values(); FMLInterModComms.sendRuntimeMessage(ModInfo.MODID, "versionchecker", "addVersionCheck", "http://www.ryanliptak.com/minecraft/versionchecker/squeek502/AppleCore"); } @EventHandler public void postInit(FMLPostInitializationEvent event) { AppleCoreRegistryImpl.INSTANCE.init(); } @EventHandler public void init(FMLInitializationEvent event) { SyncHandler.init(); } @EventHandler public void onServerStarting(FMLServerStartingEvent event) { Commands.init(event.getServer()); } @Override public String[] getASMTransformerClass() { return new String[]{TransformerModuleHandler.class.getName()}; } @Override public String getModContainerClass() { return null; } @Override public String getSetupClass() { return null; } @Override public void injectData(Map<String, Object> data) { ObfHelper.setObfuscated((Boolean) data.get("runtimeDeobfuscationEnabled")); ObfHelper.setRunsAfterDeobfRemapper(true); } @Override public String getAccessTransformerClass() { return null; } }
412
0.896811
1
0.896811
game-dev
MEDIA
0.85594
game-dev
0.861379
1
0.861379
anegostudios/vssurvivalmod
8,436
Block/BlockSign.cs
using System.Collections.Generic; using Vintagestory.API.Client; using Vintagestory.API.Common; using Vintagestory.API.MathTools; using Vintagestory.API.Util; using System; #nullable disable namespace Vintagestory.GameContent { public class TextAreaConfig { public int MaxWidth = 160; public int MaxHeight = 165; public float FontSize = 20; public bool BoldFont = false; public EnumVerticalAlign VerticalAlign = EnumVerticalAlign.Top; public string FontName = GuiStyle.StandardFontName; public float textVoxelOffsetX; public float textVoxelOffsetY; public float textVoxelOffsetZ; public float textVoxelWidth = 14f; public float textVoxelHeight = 6.5f; public bool WithScrollbar = false; public TextAreaConfig CopyWithFontSize(float fontSize) { return new TextAreaConfig() { MaxWidth = MaxWidth, MaxHeight = MaxHeight, FontSize = fontSize, BoldFont = BoldFont, FontName = FontName, textVoxelWidth = textVoxelWidth, textVoxelHeight = textVoxelHeight, textVoxelOffsetX = textVoxelOffsetX, textVoxelOffsetY = textVoxelOffsetY, textVoxelOffsetZ = textVoxelOffsetZ, WithScrollbar = WithScrollbar, VerticalAlign = VerticalAlign }; } } public class BlockSign : Block { WorldInteraction[] interactions; public TextAreaConfig signConfig; protected bool isWallSign; public override void OnLoaded(ICoreAPI api) { base.OnLoaded(api); PlacedPriorityInteract = true; isWallSign = Variant["attachment"] == "wall"; // For performance, do this test only once, not multiple times every tick if entities need to check this collisionbox signConfig = new TextAreaConfig(); if (Attributes != null) { signConfig = this.Attributes.AsObject<TextAreaConfig>(signConfig); } if (api.Side != EnumAppSide.Client) return; AfterSignRenderer.Registered = false; interactions = ObjectCacheUtil.GetOrCreate(api, "signBlockInteractions", () => { List<ItemStack> stacksList = new List<ItemStack>(); foreach (CollectibleObject collectible in api.World.Collectibles) { if (collectible.Attributes?["pigment"].Exists == true) { stacksList.Add(new ItemStack(collectible)); } } return new WorldInteraction[] { new WorldInteraction() { ActionLangCode = "blockhelp-sign-write", HotKeyCode = "shift", MouseButton = EnumMouseButton.Right, Itemstacks = stacksList.ToArray() } }; }); } public override Cuboidf[] GetCollisionBoxes(IBlockAccessor blockAccessor, BlockPos pos) { if (isWallSign) return base.GetCollisionBoxes(blockAccessor, pos); BlockEntitySign besign = blockAccessor.GetBlockEntity(pos) as BlockEntitySign; if (besign != null) return besign.colSelBox; return base.GetCollisionBoxes(blockAccessor, pos); } public override Cuboidf[] GetSelectionBoxes(IBlockAccessor blockAccessor, BlockPos pos) { if (isWallSign) return base.GetCollisionBoxes(blockAccessor, pos); BlockEntitySign besign = blockAccessor.GetBlockEntity(pos) as BlockEntitySign; if (besign != null) return besign.colSelBox; return base.GetSelectionBoxes(blockAccessor, pos); } public override bool TryPlaceBlock(IWorldAccessor world, IPlayer byPlayer, ItemStack itemstack, BlockSelection bs, ref string failureCode) { BlockPos supportingPos = bs.Position.AddCopy(bs.Face.Opposite); Block supportingBlock = world.BlockAccessor.GetBlock(supportingPos); if (bs.Face.IsHorizontal && (supportingBlock.CanAttachBlockAt(world.BlockAccessor, this, supportingPos, bs.Face) || supportingBlock.GetAttributes(world.BlockAccessor, supportingPos)?.IsTrue("partialAttachable") == true)) { Block wallblock = world.BlockAccessor.GetBlock(CodeWithParts("wall", bs.Face.Opposite.Code)); if (!wallblock.CanPlaceBlock(world, byPlayer, bs, ref failureCode)) { return false; } world.BlockAccessor.SetBlock(wallblock.BlockId, bs.Position); return true; } if (!CanPlaceBlock(world, byPlayer, bs, ref failureCode)) { return false; } BlockFacing[] horVer = SuggestedHVOrientation(byPlayer, bs); AssetLocation blockCode = CodeWithParts(horVer[0].Code); Block block = world.BlockAccessor.GetBlock(blockCode); world.BlockAccessor.SetBlock(block.BlockId, bs.Position); BlockEntitySign bect = world.BlockAccessor.GetBlockEntity(bs.Position) as BlockEntitySign; if (bect != null) { BlockPos targetPos = bs.DidOffset ? bs.Position.AddCopy(bs.Face.Opposite) : bs.Position; double dx = byPlayer.Entity.Pos.X - (targetPos.X + bs.HitPosition.X); double dz = (float)byPlayer.Entity.Pos.Z - (targetPos.Z + bs.HitPosition.Z); float angleHor = (float)Math.Atan2(dx, dz); float deg45 = GameMath.PIHALF / 2; float roundRad = ((int)Math.Round(angleHor / deg45)) * deg45; bect.MeshAngleRad = roundRad; } return true; } public override ItemStack[] GetDrops(IWorldAccessor world, BlockPos pos, IPlayer byPlayer, float dropQuantityMultiplier = 1f) { Block block = world.BlockAccessor.GetBlock(CodeWithParts("ground", "north")); if (block == null) block = world.BlockAccessor.GetBlock(CodeWithParts("wall", "north")); return new ItemStack[] { new ItemStack(block) }; } public override ItemStack OnPickBlock(IWorldAccessor world, BlockPos pos) { Block block = world.BlockAccessor.GetBlock(CodeWithParts("ground", "north")); if (block == null) block = world.BlockAccessor.GetBlock(CodeWithParts("wall", "north")); return new ItemStack(block); } public override void OnNeighbourBlockChange(IWorldAccessor world, BlockPos pos, BlockPos neibpos) { base.OnNeighbourBlockChange(world, pos, neibpos); } public override bool OnBlockInteractStart(IWorldAccessor world, IPlayer byPlayer, BlockSelection blockSel) { BlockEntity entity = world.BlockAccessor.GetBlockEntity(blockSel.Position); if (entity is BlockEntitySign) { BlockEntitySign besigh = (BlockEntitySign)entity; besigh.OnRightClick(byPlayer); return true; } return true; } public override AssetLocation GetHorizontallyFlippedBlockCode(EnumAxis axis) { BlockFacing facing = BlockFacing.FromCode(LastCodePart()); if (facing.Axis == axis) { return CodeWithParts(facing.Opposite.Code); } return Code; } public override WorldInteraction[] GetPlacedBlockInteractionHelp(IWorldAccessor world, BlockSelection selection, IPlayer forPlayer) { return interactions.Append(base.GetPlacedBlockInteractionHelp(world, selection, forPlayer)); } public override AssetLocation GetRotatedBlockCode(int angle) { BlockFacing beforeFacing = BlockFacing.FromCode(LastCodePart()); int rotatedIndex = GameMath.Mod(beforeFacing.HorizontalAngleIndex - angle / 90, 4); BlockFacing nowFacing = BlockFacing.HORIZONTALS_ANGLEORDER[rotatedIndex]; return CodeWithParts(nowFacing.Code); } } }
412
0.869347
1
0.869347
game-dev
MEDIA
0.88828
game-dev
0.739688
1
0.739688
pmret/papermario
1,263
src/world/area_jan/jan_07/trees.c
#include "jan_07.h" #define NAME_SUFFIX _Trees #include "common/foliage.inc.c" #define NAME_SUFFIX FoliageModelList N(Tree1_LeafModels) = FOLIAGE_MODEL_LIST(MODEL_o7, MODEL_o8, MODEL_o9, MODEL_o10, MODEL_o11); FoliageModelList N(Tree1_TrunkModels) = FOLIAGE_MODEL_LIST(MODEL_o6); FoliageDropList N(Tree1_Drops) = { .count = 1, .drops = { { .itemID = ITEM_COIN, .pos = { -150, 100, -80 }, .spawnMode = ITEM_SPAWN_MODE_FALL_SPAWN_ONCE, .pickupFlag = GF_JAN07_Tree1_Coin, }, } }; FoliageVectorList N(Tree1_Effects) = { .count = 2, .vectors = { { -232.0f, 114.0f, -75.0f }, { -147.0f, 114.0f, -85.0f }, } }; ShakeTreeConfig N(ShakeTree_Tree1) = { .leaves = &N(Tree1_LeafModels), .trunk = &N(Tree1_TrunkModels), .drops = &N(Tree1_Drops), .vectors = &N(Tree1_Effects), }; BombTrigger N(BombPos_Tree1) = { .pos = { -192.0f, 0.0f, -105.0f }, .diameter = 0.0f }; EvtScript N(EVS_SetupTrees) = { Set(LVar0, Ref(N(ShakeTree_Tree1))) BindTrigger(Ref(N(EVS_ShakeTree_Trees)), TRIGGER_WALL_HAMMER, COLLIDER_o62, 1, 0) BindTrigger(Ref(N(EVS_ShakeTree_Trees)), TRIGGER_POINT_BOMB, Ref(N(BombPos_Tree1)), 1, 0) Return End };
412
0.800537
1
0.800537
game-dev
MEDIA
0.400131
game-dev
0.933678
1
0.933678
Sigma-Skidder-Team/SigmaRemap
2,749
src/main/java/mapped/ItemStackHelper.java
package mapped; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.ListNBT; import net.minecraft.util.NonNullList; import java.util.List; import java.util.function.Predicate; public class ItemStackHelper { public static ItemStack method26563(List<ItemStack> var0, int var1, int var2) { return var1 >= 0 && var1 < var0.size() && !((ItemStack)var0.get(var1)).isEmpty() && var2 > 0 ? ((ItemStack)var0.get(var1)).split(var2) : ItemStack.EMPTY; } public static ItemStack method26564(List<ItemStack> var0, int var1) { return var1 >= 0 && var1 < var0.size() ? var0.set(var1, ItemStack.EMPTY) : ItemStack.EMPTY; } public static CompoundNBT saveAllItems(CompoundNBT var0, NonNullList<ItemStack> var1) { return method26566(var0, var1, true); } public static CompoundNBT method26566(CompoundNBT var0, NonNullList<ItemStack> var1, boolean var2) { ListNBT var5 = new ListNBT(); for (int var6 = 0; var6 < var1.size(); var6++) { ItemStack var7 = (ItemStack)var1.get(var6); if (!var7.isEmpty()) { CompoundNBT var8 = new CompoundNBT(); var8.putByte("Slot", (byte)var6); var7.method32112(var8); var5.add(var8); } } if (!var5.isEmpty() || var2) { var0.put("Items", var5); } return var0; } public static void loadAllItems(CompoundNBT var0, NonNullList<ItemStack> var1) { ListNBT var4 = var0.getList("Items", 10); for (int var5 = 0; var5 < var4.size(); var5++) { CompoundNBT var6 = var4.getCompound(var5); int var7 = var6.getByte("Slot") & 255; if (var7 >= 0 && var7 < var1.size()) { var1.set(var7, ItemStack.read(var6)); } } } public static int method26568(IInventory var0, Predicate<ItemStack> var1, int var2, boolean var3) { int var6 = 0; for (int var7 = 0; var7 < var0.getSizeInventory(); var7++) { ItemStack var8 = var0.getStackInSlot(var7); int var9 = method26569(var8, var1, var2 - var6, var3); if (var9 > 0 && !var3 && var8.isEmpty()) { var0.setInventorySlotContents(var7, ItemStack.EMPTY); } var6 += var9; } return var6; } public static int method26569(ItemStack var0, Predicate<ItemStack> var1, int var2, boolean var3) { if (var0.isEmpty() || !var1.test(var0)) { return 0; } else if (!var3) { int var6 = var2 >= 0 ? Math.min(var2, var0.getCount()) : var0.getCount(); var0.shrink(var6); return var6; } else { return var0.getCount(); } } }
412
0.588303
1
0.588303
game-dev
MEDIA
0.682306
game-dev
0.665412
1
0.665412
rexrainbow/phaser3-rex-notes
1,626
examples/parse-itemtable/owner-access.js
import phaser from 'phaser/src/phaser.js'; import ParsePlugin from '../../plugins/parse-plugin.js'; class Demo extends Phaser.Scene { constructor() { super({ key: 'examples' }) this.txt; } preload() { this.plugins.get('rexParse').preload(this); } create() { Parse.serverURL = 'https://parseapi.back4app.com'; // This is your Server URL Parse.initialize( 'HSEc6FPwSQxMPzFwBooEme2n0agfUIBgFcO8LNtr', // This is your Application ID 'DbgfGW40cdqUQug8cv6NDAplB1D9daNIjcYtdGSQ' // This is your Javascript key ); var rexParse = this.plugins.get('rexParse'); var table = rexParse.add.itemTable({ className: 'ownerTest', primaryKeys: ['name'], ownerWrite: true, }); rexParse.quickLogin('rex', 'aabb') .then(function () { console.log('login'); return table .save({ name: 'player0', hp: 20 }); }) .catch(function (error) { console.log(error); }) } update() { } } var config = { type: Phaser.AUTO, parent: 'phaser-example', width: 800, height: 600, scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, }, scene: Demo, plugins: { global: [{ key: 'rexParse', plugin: ParsePlugin, start: true }] } }; var game = new Phaser.Game(config);
412
0.579997
1
0.579997
game-dev
MEDIA
0.675887
game-dev,web-frontend
0.877217
1
0.877217
folgerwang/UnrealEngine
2,457
Engine/Source/Programs/AutomationTool/Gauntlet/Unreal/Game/Samples/ElementalDemoTest.cs
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Gauntlet; using System.IO; using System.IO.Compression; namespace UE4Game { /// <summary> /// Runs automated tests on a platform /// </summary> public class ElementalDemoTest : DefaultTest { public ElementalDemoTest(Gauntlet.UnrealTestContext InContext) : base(InContext) { } public override UE4TestConfig GetConfiguration() { // just need a single client UE4TestConfig Config = base.GetConfiguration(); UnrealTestRole ClientRole = Config.RequireRole(UnrealTargetRole.Client); ClientRole.CommandLine += " -unattended"; Config.MaxDuration = 5 * 600; // 5min should be plenty return Config; } public override void CreateReport(TestResult Result, UnrealTestContext Contex, UnrealBuildSource Build, IEnumerable<UnrealRoleArtifacts> Artifacts, string ArtifactPath) { UnrealRoleArtifacts ClientArtifacts = Artifacts.Where(A => A.SessionRole.RoleType == UnrealTargetRole.Client).FirstOrDefault(); var SnapshotSummary = new UnrealSnapshotSummary<UnrealHealthSnapshot>(ClientArtifacts.AppInstance.StdOut); Log.Info("Elemental Performance Report"); Log.Info(SnapshotSummary.ToString()); base.CreateReport(Result, Contex, Build, Artifacts, ArtifactPath); } public override void SaveArtifacts_DEPRECATED(string OutputPath) { string UploadFolder = Globals.Params.ParseValue("uploadfolder", ""); if (UploadFolder.Count() > 0 && Directory.CreateDirectory(UploadFolder).Exists) { string PlatformString = TestInstance.ClientApps[0].Device.Platform.ToString(); string ArtifactDir = TestInstance.ClientApps[0].ArtifactPath; string ProfilingDir = Path.Combine(ArtifactDir, "Profiling"); string FPSChartsDir = Path.Combine(ProfilingDir, "FPSChartStats").ToLower(); string FpsChartsZipPath = Path.Combine(TestInstance.ClientApps[0].ArtifactPath, "FPSCharts.zip").ToLower(); if (Directory.Exists(FPSChartsDir)) { ZipFile.CreateFromDirectory(FPSChartsDir, FpsChartsZipPath); string DestFileName = "ElementalDemoTest-" + PlatformString + ".zip"; string DestZipFile = Path.Combine(UploadFolder, DestFileName); File.Copy(FpsChartsZipPath, DestZipFile); } } else { Log.Info("Not uploading CSV Result UploadFolder: '" + UploadFolder + "'"); } } } }
412
0.915769
1
0.915769
game-dev
MEDIA
0.743473
game-dev
0.876122
1
0.876122
microsoft/Windows-classic-samples
2,487
Samples/UPnPGenericUCP/cpp/CAsyncResult.h
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved // // CAsyncResult.h : class definition // class CUPnPAsyncResult : public IUPnPAsyncResult { public: CUPnPAsyncResult() { m_lRefCount = 0; m_hReady = 0; } ~CUPnPAsyncResult() { ::CloseHandle(m_hReady); } public: //Initialization Method STDMETHODIMP Init() { HRESULT hr = S_OK; m_hReady = ::CreateEvent(NULL, // default security attributes FALSE, // manual reset event object FALSE, // initial state is unsignaled NULL); // unnamed object if (!m_hReady) { hr = E_FAIL; } return hr; } // IUnknown methods STDMETHODIMP QueryInterface(_In_ REFIID iid, _Out_ LPVOID* ppvObject ) { HRESULT hr = S_OK; if(NULL == ppvObject) { hr = E_POINTER; } else { *ppvObject = NULL; } if(SUCCEEDED(hr)) { if(IsEqualIID(iid, IID_IUnknown) || IsEqualIID(iid, IID_IUPnPAsyncResult)) { *ppvObject = static_cast<IUPnPAsyncResult*>(this); AddRef(); } else { hr = E_NOINTERFACE; } } return hr; }; STDMETHODIMP_(ULONG) AddRef() { return ::InterlockedIncrement(&m_lRefCount); }; STDMETHODIMP_(ULONG) Release() { LONG lRefCount = ::InterlockedDecrement(&m_lRefCount); if(0 == lRefCount) { delete this; } return lRefCount; }; // ISynchronize methods //+--------------------------------------------------------------------------- // // Member: AsyncOperationComplete // // Purpose: Called when an Async operation has been completed // // Arguments: // ullRequestID [in] ID of the completed request // // Returns: None // // Notes: // // STDMETHODIMP AsyncOperationComplete(_In_ ULONG64 ullRequestID) { UNREFERENCED_PARAMETER(ullRequestID); HRESULT hr = S_OK; if(!SetEvent(m_hReady)) { // If SetEvent fails, then the completion event fails to trigger hr = E_HANDLE; } return hr; }; public: HANDLE GetHandle(){ return m_hReady;} private: LONG m_lRefCount; HANDLE m_hReady; };
412
0.896203
1
0.896203
game-dev
MEDIA
0.257752
game-dev
0.913871
1
0.913871
DragonBones/DragonBonesCSharp
19,696
Unity/Demos/Assets/DragonBones/Editor/UnityEditor.cs
/** * The MIT License (MIT) * * Copyright (c) 2012-2017 DragonBones team and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEditor; using UnityEditor.SceneManagement; using System.Text.RegularExpressions; namespace DragonBones { public class UnityEditor { [MenuItem("GameObject/DragonBones/Armature Object", false, 10)] private static void _CreateArmatureObjectMenuItem() { _CreateEmptyObject(GetSelectionParentTransform()); } [MenuItem("Assets/Create/DragonBones/Armature Object", true)] private static bool _CreateArmatureObjectFromSkeValidateMenuItem() { return _GetDragonBonesSkePaths().Count > 0; } [MenuItem("Assets/Create/DragonBones/Armature Object", false, 10)] private static void _CreateArmatureObjectFromSkeMenuItem() { var parentTransform = GetSelectionParentTransform(); foreach (var dragonBonesJSONPath in _GetDragonBonesSkePaths()) { var armatureComponent = _CreateEmptyObject(parentTransform); var dragonBonesJSON = AssetDatabase.LoadMainAssetAtPath(dragonBonesJSONPath) as TextAsset; ChangeDragonBonesData(armatureComponent, dragonBonesJSON); } } [MenuItem("GameObject/DragonBones/Armature Object(UGUI)", false, 11)] private static void _CreateUGUIArmatureObjectMenuItem() { var armatureComponent = _CreateEmptyObject(GetSelectionParentTransform()); armatureComponent.isUGUI = true; if (armatureComponent.GetComponentInParent<Canvas>() == null) { var canvas = GameObject.Find("/Canvas"); if (canvas) { armatureComponent.transform.SetParent(canvas.transform); } } armatureComponent.transform.localScale = Vector2.one * 100.0f; armatureComponent.transform.localPosition = Vector3.zero; } [MenuItem("Assets/Create/DragonBones/Armature Object(UGUI)", true)] private static bool _CreateUGUIArmatureObjectFromJSONValidateMenuItem() { return _GetDragonBonesSkePaths().Count > 0; } [MenuItem("Assets/Create/DragonBones/Armature Object(UGUI)", false, 11)] private static void _CreateUGUIArmatureObjectFromJSOIMenuItem() { var parentTransform = GetSelectionParentTransform(); foreach (var dragonBonesJSONPath in _GetDragonBonesSkePaths()) { var armatureComponent = _CreateEmptyObject(parentTransform); armatureComponent.isUGUI = true; if (armatureComponent.GetComponentInParent<Canvas>() == null) { var canvas = GameObject.Find("/Canvas"); if (canvas) { armatureComponent.transform.SetParent(canvas.transform); } } armatureComponent.transform.localScale = Vector2.one * 100.0f; armatureComponent.transform.localPosition = Vector3.zero; var dragonBonesJSON = AssetDatabase.LoadMainAssetAtPath(dragonBonesJSONPath) as TextAsset; ChangeDragonBonesData(armatureComponent, dragonBonesJSON); } } [MenuItem("Assets/Create/DragonBones/Create Unity Data", true)] private static bool _CreateUnityDataValidateMenuItem() { return _GetDragonBonesSkePaths(true).Count > 0; } [MenuItem("Assets/Create/DragonBones/Create Unity Data", false, 32)] private static void _CreateUnityDataMenuItem() { foreach (var dragonBonesSkePath in _GetDragonBonesSkePaths(true)) { var dragonBonesSke = AssetDatabase.LoadMainAssetAtPath(dragonBonesSkePath) as TextAsset; var textureAtlasJSONs = new List<string>(); GetTextureAtlasConfigs(textureAtlasJSONs, AssetDatabase.GetAssetPath(dragonBonesSke.GetInstanceID())); UnityDragonBonesData.TextureAtlas[] textureAtlas = new UnityDragonBonesData.TextureAtlas[textureAtlasJSONs.Count]; for (int i = 0; i < textureAtlasJSONs.Count; ++i) { string path = textureAtlasJSONs[i]; //load textureAtlas data UnityDragonBonesData.TextureAtlas ta = new UnityDragonBonesData.TextureAtlas(); ta.textureAtlasJSON = AssetDatabase.LoadAssetAtPath<TextAsset>(path); //load texture path = path.Substring(0, path.LastIndexOf(".json")); ta.texture = AssetDatabase.LoadAssetAtPath<Texture2D>(path + ".png"); //load material ta.material = AssetDatabase.LoadAssetAtPath<Material>(path + "_Mat.mat"); ta.uiMaterial = AssetDatabase.LoadAssetAtPath<Material>(path + "_UI_Mat.mat"); textureAtlas[i] = ta; } // CreateUnityDragonBonesData(dragonBonesSke, textureAtlas); } } public static UnityDragonBonesData.TextureAtlas[] GetTextureAtlasByJSONs(List<string> textureAtlasJSONs) { UnityDragonBonesData.TextureAtlas[] textureAtlas = new UnityDragonBonesData.TextureAtlas[textureAtlasJSONs.Count]; for (int i = 0; i < textureAtlasJSONs.Count; ++i) { string path = textureAtlasJSONs[i]; //load textureAtlas data UnityDragonBonesData.TextureAtlas ta = new UnityDragonBonesData.TextureAtlas(); ta.textureAtlasJSON = AssetDatabase.LoadAssetAtPath<TextAsset>(path); //load texture path = path.Substring(0, path.LastIndexOf(".json")); ta.texture = AssetDatabase.LoadAssetAtPath<Texture2D>(path + ".png"); //load material ta.material = AssetDatabase.LoadAssetAtPath<Material>(path + "_Mat.mat"); ta.uiMaterial = AssetDatabase.LoadAssetAtPath<Material>(path + "_UI_Mat.mat"); textureAtlas[i] = ta; } return textureAtlas; } public static bool ChangeDragonBonesData(UnityArmatureComponent _armatureComponent, TextAsset dragonBoneJSON) { if (dragonBoneJSON != null) { var textureAtlasJSONs = new List<string>(); UnityEditor.GetTextureAtlasConfigs(textureAtlasJSONs, AssetDatabase.GetAssetPath(dragonBoneJSON.GetInstanceID())); UnityDragonBonesData.TextureAtlas[] textureAtlas = UnityEditor.GetTextureAtlasByJSONs(textureAtlasJSONs); UnityDragonBonesData data = UnityEditor.CreateUnityDragonBonesData(dragonBoneJSON, textureAtlas); _armatureComponent.unityData = data; var dragonBonesData = UnityFactory.factory.LoadData(data, _armatureComponent.isUGUI); if (dragonBonesData != null) { Undo.RecordObject(_armatureComponent, "Set DragonBones"); _armatureComponent.unityData = data; var armatureName = dragonBonesData.armatureNames[0]; ChangeArmatureData(_armatureComponent, armatureName, _armatureComponent.unityData.dataName); _armatureComponent.gameObject.name = armatureName; EditorUtility.SetDirty(_armatureComponent); return true; } else { EditorUtility.DisplayDialog("Error", "Could not load dragonBones data.", "OK", null); return false; } } else if (_armatureComponent.unityData != null) { Undo.RecordObject(_armatureComponent, "Set DragonBones"); _armatureComponent.unityData = null; if (_armatureComponent.armature != null) { _armatureComponent.Dispose(false); } EditorUtility.SetDirty(_armatureComponent); return true; } return false; } public static void ChangeArmatureData(UnityArmatureComponent _armatureComponent, string armatureName, string dragonBonesName) { bool isUGUI = _armatureComponent.isUGUI; UnityDragonBonesData unityData = null; Slot slot = null; if (_armatureComponent.armature != null) { unityData = _armatureComponent.unityData; slot = _armatureComponent.armature.parent; _armatureComponent.Dispose(false); UnityFactory.factory._dragonBones.AdvanceTime(0.0f); _armatureComponent.unityData = unityData; } _armatureComponent.armatureName = armatureName; _armatureComponent.isUGUI = isUGUI; _armatureComponent = UnityFactory.factory.BuildArmatureComponent(_armatureComponent.armatureName, dragonBonesName, null, _armatureComponent.unityData.dataName, _armatureComponent.gameObject, _armatureComponent.isUGUI); if (slot != null) { slot.childArmature = _armatureComponent.armature; } _armatureComponent.sortingLayerName = _armatureComponent.sortingLayerName; _armatureComponent.sortingOrder = _armatureComponent.sortingOrder; } public static UnityEngine.Transform GetSelectionParentTransform() { var parent = Selection.activeObject as GameObject; return parent != null ? parent.transform : null; } public static void GetTextureAtlasConfigs(List<string> textureAtlasFiles, string filePath, string rawName = null, string suffix = "tex") { var folder = Directory.GetParent(filePath).ToString(); var name = rawName != null ? rawName : filePath.Substring(0, filePath.LastIndexOf(".")).Substring(filePath.LastIndexOf("/") + 1); if (name.LastIndexOf("_ske") == name.Length - 4) { name = name.Substring(0, name.LastIndexOf("_ske")); } int index = 0; var textureAtlasName = ""; var textureAtlasConfigFile = ""; textureAtlasName = !string.IsNullOrEmpty(name) ? name + (!string.IsNullOrEmpty(suffix) ? "_" + suffix : suffix) : suffix; textureAtlasConfigFile = folder + "/" + textureAtlasName + ".json"; if (File.Exists(textureAtlasConfigFile)) { textureAtlasFiles.Add(textureAtlasConfigFile); return; } while (true) { textureAtlasName = (!string.IsNullOrEmpty(name) ? name + (!string.IsNullOrEmpty(suffix) ? "_" + suffix : suffix) : suffix) + "_" + (index++); textureAtlasConfigFile = folder + "/" + textureAtlasName + ".json"; if (File.Exists(textureAtlasConfigFile)) { textureAtlasFiles.Add(textureAtlasConfigFile); } else if (index > 1) { break; } } if (textureAtlasFiles.Count > 0 || rawName != null) { return; } GetTextureAtlasConfigs(textureAtlasFiles, filePath, "", suffix); if (textureAtlasFiles.Count > 0) { return; } index = name.LastIndexOf("_"); if (index >= 0) { name = name.Substring(0, index); GetTextureAtlasConfigs(textureAtlasFiles, filePath, name, suffix); if (textureAtlasFiles.Count > 0) { return; } GetTextureAtlasConfigs(textureAtlasFiles, filePath, name, ""); if (textureAtlasFiles.Count > 0) { return; } } if (suffix != "texture") { GetTextureAtlasConfigs(textureAtlasFiles, filePath, null, "texture"); } } public static UnityDragonBonesData CreateUnityDragonBonesData(TextAsset dragonBonesAsset, UnityDragonBonesData.TextureAtlas[] textureAtlas) { if (dragonBonesAsset != null) { bool isDirty = false; string path = AssetDatabase.GetAssetPath(dragonBonesAsset); path = path.Substring(0, path.Length - 5); int index = path.LastIndexOf("_ske"); if (index > 0) { path = path.Substring(0, index); } // string dataPath = path + "_Data.asset"; var jsonObject = (Dictionary<string, object>)MiniJSON.Json.Deserialize(dragonBonesAsset.text); if (dragonBonesAsset.text == "DBDT") { int headerLength = 0; jsonObject = BinaryDataParser.DeserializeBinaryJsonData(dragonBonesAsset.bytes, out headerLength); } else { jsonObject = MiniJSON.Json.Deserialize(dragonBonesAsset.text) as Dictionary<string, object>; } var dataName = jsonObject.ContainsKey("name") ? jsonObject["name"] as string : ""; //先从缓存里面取 UnityDragonBonesData data = UnityFactory.factory.GetCacheUnityDragonBonesData(dataName); //缓存中没有,从资源里面取 if (data == null) { data = AssetDatabase.LoadAssetAtPath<UnityDragonBonesData>(dataPath); } //资源里面也没有,那么重新创建 if (data == null) { data = UnityDragonBonesData.CreateInstance<UnityDragonBonesData>(); data.dataName = dataName; AssetDatabase.CreateAsset(data, dataPath); isDirty = true; } // if (string.IsNullOrEmpty(data.dataName) || !data.dataName.Equals(dataName)) { //走到这里,说明原先已经创建了,之后手动改了名字,既然又走了创建流程,那么名字也重置下 data.dataName = dataName; isDirty = true; } if (data.dragonBonesJSON != dragonBonesAsset) { data.dragonBonesJSON = dragonBonesAsset; isDirty = true; } if (textureAtlas != null && textureAtlas.Length > 0 && textureAtlas[0] != null && textureAtlas[0].texture != null) { if (data.textureAtlas == null || data.textureAtlas.Length != textureAtlas.Length) { isDirty = true; } else { for (int i = 0; i < textureAtlas.Length; ++i) { if (textureAtlas[i].material != data.textureAtlas[i].material || textureAtlas[i].uiMaterial != data.textureAtlas[i].uiMaterial || textureAtlas[i].texture != data.textureAtlas[i].texture || textureAtlas[i].textureAtlasJSON != data.textureAtlas[i].textureAtlasJSON ) { isDirty = true; break; } } } data.textureAtlas = textureAtlas; } if (isDirty) { AssetDatabase.Refresh(); EditorUtility.SetDirty(data); } // UnityFactory.factory.AddCacheUnityDragonBonesData(data); AssetDatabase.SaveAssets(); return data; } return null; } private static List<string> _GetDragonBonesSkePaths(bool isCreateUnityData = false) { var dragonBonesSkePaths = new List<string>(); foreach (var guid in Selection.assetGUIDs) { var assetPath = AssetDatabase.GUIDToAssetPath(guid); if (assetPath.EndsWith(".json")) { var jsonCode = File.ReadAllText(assetPath); if (jsonCode.IndexOf("\"armature\":") > 0) { dragonBonesSkePaths.Add(assetPath); } } if (assetPath.EndsWith(".bytes")) { TextAsset asset = AssetDatabase.LoadAssetAtPath<TextAsset>(assetPath); if (asset && asset.text == "DBDT") { dragonBonesSkePaths.Add(assetPath); } } else if (!isCreateUnityData && assetPath.EndsWith("_Data.asset")) { UnityDragonBonesData data = AssetDatabase.LoadAssetAtPath<UnityDragonBonesData>(assetPath); dragonBonesSkePaths.Add(AssetDatabase.GetAssetPath(data.dragonBonesJSON)); } } return dragonBonesSkePaths; } private static UnityArmatureComponent _CreateEmptyObject(UnityEngine.Transform parentTransform) { var gameObject = new GameObject("New Armature Object", typeof(UnityArmatureComponent)); var armatureComponent = gameObject.GetComponent<UnityArmatureComponent>(); gameObject.transform.SetParent(parentTransform, false); // EditorUtility.FocusProjectWindow(); Selection.activeObject = gameObject; EditorGUIUtility.PingObject(Selection.activeObject); Undo.RegisterCreatedObjectUndo(gameObject, "Create Armature Object"); EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); return armatureComponent; } } }
412
0.902495
1
0.902495
game-dev
MEDIA
0.923118
game-dev
0.796913
1
0.796913
gandrewstone/GameMaker
4,796
code/DRV/COORD2D.HPP
//------------------------------- // Copyright 1994 G. Andrew Stone // Recreational Software Designs // NOT PUBLIC DOMAIN! //------------------------------- #ifndef COORDINATE #define COORDINATE #include "gen.h" inline int Min (int a, int b) { if (a>b) return b; return a; } inline int Max (int a, int b) { if (b>a) return b; return a; } inline int Abs (int a) { if (a<0) return (-a); else return (a); } inline void Swap(int &a,int &b) { int c=a; a=b; b=c; } class Box2d; class Coord2d { public: int x,y; void Set(int xin,int yin) { x=xin; y=yin;} Coord2d(int xin,int yin) { Set(xin,yin); } Coord2d(void) {} void Wrap(Coord2d Bnds) { if (y<0) y += Bnds.y; else if (y>=Bnds.y) y -= Bnds.y; if (x<0) x += Bnds.x; else if (x>=Bnds.x) x -= Bnds.x; } friend boolean operator > (Coord2d a,Coord2d b) { return((boolean)((a.x>b.x)&&(a.y>b.y))); } friend boolean operator &> (Coord2d a,Coord2d b) { return((boolean)((a.x>b.x)&&(a.y>b.y))); } friend boolean operator < (Coord2d a,Coord2d b) { return((boolean)((a.x<b.x)&&(a.y<b.y))); } friend boolean operator >= (Coord2d a,Coord2d b) { return((boolean)((a.x>=b.x)&&(a.y>=b.y))); } friend boolean operator <= (Coord2d a,Coord2d b) { return((boolean)((a.x<=b.x)&&(a.y<=b.y))); } friend boolean operator != (Coord2d a,Coord2d b) { return((boolean)((a.x!=b.x)||(a.y!=b.y))); } friend void Swap(Coord2d &a,Coord2d &b) { Coord2d c=a; a=b; b=c; } boolean In(Coord2d LowBnd,Coord2d UpBnd) { return ((boolean)((*this >=LowBnd)&&(*this <= UpBnd))); } boolean In(Box2d &b); friend Coord2d Min (Coord2d &a, Coord2d &b) { Coord2d r; r.x= Min(a.x,b.x); r.y= Min(a.y,b.y); return(r); } friend Coord2d Max (Coord2d &a, Coord2d &b) { Coord2d r; r.x= Max(a.x,b.x); r.y= Max(a.y,b.y); return(r); } Coord2d operator += (int v) { x += v; y += v; return *this; } Coord2d operator -= (int v) { x -= v; y -= v; return *this; } Coord2d operator *= (int v) { x *= v; y *= v; return *this; } Coord2d operator /= (int v) { x /= v; y /= v; return *this; } Coord2d operator += (Coord2d &p) { x += p.x; y += p.y; return *this;} Coord2d operator -= (const Coord2d &p) { x -= p.x; y -= p.y; return *this;} Coord2d operator *= (const Coord2d &p) { x *= p.x; y *= p.y; return *this;} Coord2d operator /= (const Coord2d &p) { x /= p.x; y /= p.y; return *this;} Coord2d operator -- () { x--; y--; return *this;} Coord2d operator ++ () { x++; y++; return *this;} friend Coord2d operator * (int v,Coord2d &r) { Coord2d p(v*r.x,v*r.y); return p; } friend Coord2d operator * (Coord2d &r,int v) { Coord2d p(v*r.x,v*r.y); return p; } friend Coord2d operator / (int v,Coord2d &r) { Coord2d p(v/r.x,v/r.y); return p; } friend Coord2d operator - (Coord2d &r,int v) { Coord2d p(r.x-v,r.y-v); return p; } friend Coord2d operator + (Coord2d &r,int v) { Coord2d p(r.x+v,r.y+v); return p; } friend Coord2d operator / (Coord2d &r,int v) { Coord2d p(r.x/v,r.y/v); return p; } friend Coord2d operator - (Coord2d &q,Coord2d &r) { Coord2d p(q.x-r.x,q.y-r.y); return p;} friend Coord2d operator + (Coord2d &q,Coord2d &r) { Coord2d p(q.x+r.x,q.y+r.y); return p;} friend Coord2d operator / (Coord2d &q,Coord2d &r) { Coord2d p(q.x/r.x,q.y/r.y); return p;} friend Coord2d operator * (Coord2d &q,Coord2d &r) { Coord2d p(q.x*r.x,q.y*r.y); return p;} }; class Box2d { public: Coord2d ul,lr; Box2d(int x,int y,int x1,int y1) { Set(x,y,x1,y1); } Box2d(Coord2d ull,Coord2d lrr) { Set(ull,lrr); } Box2d() {} void Box2d::Set(Coord2d ull,Coord2d lrr) { ul=ull; lr=lrr; } void Box2d::Set(int x,int y,int x1,int y1) { ul.x=x,ul.y=y; lr.x=x1; lr.y=y1; } boolean In(Box2d b) // is one box inside another? { return ( (boolean) (ul.In(b)&&lr.In(b)) ); } void operator -= (Coord2d c) { ul -= c; lr -= c; } }; inline boolean Coord2d::In(Box2d &b) { return ((boolean)((*this >=b.ul)&&(*this <= b.lr))); } inline Coord2d SignC(Coord2d &a) { Coord2d r; r.x= Sign(a.x); r.y= Sign(a.y); return(r); } inline Coord2d Abs(Coord2d &a) { Coord2d r; r.x= Abs(a.x); r.y= Abs(a.y); return(r); } inline Coord2d AbsC(Coord2d &a) { Coord2d p( Abs(a.x),Abs(a.y) ); return p;} inline Coord2d MakeCoord(int &x,int &y) { Coord2d r(x,y); return r; } inline Coord2d MakeCoord2d (int xin, int yin) { Coord2d r(xin,yin); return(r); } inline Coord2d Pt(int x,int y) { Coord2d r(x,y); return (r); } inline Box2d MakeBox2d (int x,int y,int x1,int y1) { Box2d r(x,y,x1,y1); return r; } inline Box2d MakeBox2d (Coord2d ul,Coord2d lr) { Box2d r(ul,lr); return r; } #endif 
412
0.567286
1
0.567286
game-dev
MEDIA
0.278059
game-dev
0.924862
1
0.924862
diamondo25/rsvp-server
19,301
WvsBeta.Center/PartyData/Party.cs
using System; using System.Collections.Generic; using System.Linq; using log4net; using WvsBeta.Common; using WvsBeta.Common.Sessions; namespace WvsBeta.Center { public class DoorInformation { public int TownID { get; private set; } public int FieldID { get; private set; } public short FieldPosX { get; private set; } public short FieldPosY { get; private set; } public DoorInformation(int townId, int fieldId, short fieldPosX, short fieldPosY) { TownID = townId; FieldID = fieldId; FieldPosX = fieldPosX; FieldPosY = fieldPosY; } public static readonly DoorInformation DefaultNoDoor = new DoorInformation(Constants.InvalidMap, Constants.InvalidMap, -1, -1); public void Encode(Packet packet) { packet.WriteInt(TownID); packet.WriteInt(FieldID); packet.WriteShort(FieldPosX); packet.WriteShort(FieldPosY); } public void Decode(Packet packet) { TownID = packet.ReadInt(); FieldID = packet.ReadInt(); FieldPosX = packet.ReadShort(); FieldPosY = packet.ReadShort(); } /// <summary> /// Edge case for memcpy'd struct (eg PARTYDATA::Decode), where it memcpys a tagPOINT{int,int} /// </summary> /// <param name="packet"></param> public void EncodeWithInts(Packet packet) { packet.WriteInt(TownID); packet.WriteInt(FieldID); packet.WriteInt(FieldPosX); packet.WriteInt(FieldPosY); } /// <summary> /// Decode a particular packet as shorts, NOT ints. /// </summary> /// <param name="packet"></param> public DoorInformation(Packet packet) { Decode(packet); } } public class PartyMember { public int CharacterID { get; } public string CharacterName { get; set; } public bool IsLeader { get; set; } public DoorInformation Door { get; set; } = DoorInformation.DefaultNoDoor; public PartyMember(int i, string n, bool l) { CharacterID = i; CharacterName = n; IsLeader = l; } public void SendPacket(Packet packet) { GetCharacter(true)?.SendPacket(packet); } public bool IsOnline => CenterServer.Instance.IsOnline(CharacterID); public Character GetCharacter(bool onlyOnline) { return CenterServer.Instance.FindCharacter(CharacterID, onlyOnline); } public int GetChannel() { return GetCharacter(true)?.ChannelID ?? PartyPacket.CHANNEL_ID_OFFLINE; } public int GetMap() { return GetCharacter(true)?.MapID ?? 0; } public void SendHpUpdate() { var chr = GetCharacter(true); if (chr == null) return; CenterServer.Instance.SendPacketToServer(PartyPacket.RequestHpUpdate(chr.ID), chr.ChannelID); } public void EncodeForMigration(Packet pw) { pw.WriteInt(CharacterID); pw.WriteString(CharacterName); pw.WriteBool(IsLeader); Door.Encode(pw); } public PartyMember(Packet pr) { CharacterID = pr.ReadInt(); CharacterName = pr.ReadString(); IsLeader = pr.ReadBool(); Door = new DoorInformation(pr); } } public class Party { private static ILog _log = LogManager.GetLogger("Party"); private static ILog _chatLog = LogManager.GetLogger("PartyChatLog"); public readonly int partyId; public readonly int world; public readonly PartyMember[] members = new PartyMember[Constants.MaxPartyMembers]; public PartyMember leader { get; private set; } private Party(int id, PartyMember ldr) { partyId = id; leader = ldr; members[0] = ldr; SendUpdatePartyData(); } public Party(Packet pr) { partyId = pr.ReadInt(); var leaderId = pr.ReadInt(); for (var i = 0; i < Constants.MaxPartyMembers; i++) { if (!pr.ReadBool()) continue; var member = new PartyMember(pr); members[i] = member; if (member.CharacterID == leaderId) leader = member; var actualPlayer = member.GetCharacter(false); if (actualPlayer != null) { actualPlayer.PartyID = partyId; } } if (leader == null) { _log.Error($"Built a party without a leader? Expected charid {leaderId} to be the member, but not found in data."); } } /// <summary> /// Get the PartyMember element by Character ID /// </summary> /// <param name="id"></param> /// <returns></returns> public PartyMember GetById(int id) { return members.FirstOrDefault(x => x != null && x.CharacterID == id); } public bool IsFull() => GetFirstFreeSlot() == -1; public int GetFirstFreeSlot() => GetCharacterSlot(null); public int GetCharacterSlot(PartyMember pm) { for (var i = 0; i < Constants.MaxPartyMembers; i++) { if (members[i] == pm) return i; } return -1; } public int GetCharacterSlot(int characterId) { for (var i = 0; i < Constants.MaxPartyMembers; i++) { if (members[i]?.CharacterID == characterId) return i; } return -1; } public IEnumerable<PartyMember> GetAllMembers(int skip = -1, bool onlyOnline = true) { for (var i = 0; i < Constants.MaxPartyMembers; i++) { var partyMember = members[i]; if (partyMember == null) continue; if (partyMember.CharacterID == skip) continue; if (onlyOnline && partyMember.IsOnline == false) continue; yield return partyMember; } } public void ForAllMembers(Action<PartyMember> action, int skip = -1, bool onlyOnline = true) { GetAllMembers(skip, onlyOnline).ForEach(action); } public void Invite(int invitor, int invitee) => OnlyByLeader(invitor, ldr => { var toInvite = CenterServer.Instance.FindCharacter(invitee); if (toInvite == null) { ldr.SendPacket(PartyPacket.PartyError(PartyFunction.UNABLE_TO_FIND_PLAYER)); } else if (Invites.ContainsKey(toInvite.ID)) { ldr.SendPacket(PartyPacket.PartyErrorWithName(PartyFunction.INVITE_USER_ALREADY_HAS_INVITE, toInvite.Name)); } else if (toInvite.PartyID != 0) { ldr.SendPacket(PartyPacket.PartyError(PartyFunction.JOIN_ALREADY_JOINED)); } else if (IsFull()) { ldr.SendPacket(PartyPacket.PartyError(PartyFunction.JOIN_ALREADY_FULL)); } else { _log.Debug($"Sending invite from party {partyId} from character {invitor} to {invitee}"); toInvite.SendPacket(PartyPacket.PartyInvite(this)); Invites.Add(toInvite.ID, this); //TODO do invites expire? } }); public void DeclineInvite(Character decliner) { if (Invites.ContainsKey(decliner.ID)) { _log.Debug($"Invite to party {partyId} has been declined by {decliner.ID}"); Invites.Remove(decliner.ID); leader.SendPacket(PartyPacket.PartyErrorWithName(PartyFunction.INVITE_REJECTED, decliner.Name)); } else { Program.MainForm.LogAppend("Trying to decline party invite while no invite exists. CharacterID: {0}, party ID {1}", decliner.ID, partyId); } } public void TryJoin(Character chr) { if (!Invites.ContainsKey(chr.ID)) { Program.MainForm.LogAppend("Trying to join party while no invite. CharacterID: {0}, party ID {1}", chr.ID, partyId); chr.SendPacket(PartyPacket.PartyError(PartyFunction.UNABLE_TO_FIND_PLAYER)); return; } Invites.Remove(chr.ID); if (IsFull()) { _log.Warn($"Invite accepted to party {partyId} by {chr.ID}, but its already full."); chr.SendPacket(PartyPacket.PartyError(PartyFunction.JOIN_ALREADY_FULL)); return; } if (chr.PartyID != 0) { _log.Warn($"Invite accepted to party {partyId} by {chr.ID}, the person is already in a party"); chr.SendPacket(PartyPacket.PartyError(PartyFunction.JOIN_ALREADY_JOINED)); return; } if (leader.GetMap() != chr.MapID) { _log.Warn($"Invite accepted to party {partyId} by {chr.ID}, but is not in the same map."); chr.SendPacket(PartyPacket.PartyError(PartyFunction.UNABLE_TO_FIND_PLAYER)); return; } Join(chr); } private void Join(Character chr) { var slot = GetFirstFreeSlot(); if (slot == -1) { _log.Error($"Trying to join the party, but the free slot is -1??? Party {partyId} Character {chr.ID}"); return; } _log.Debug($"{chr.ID} joins the party {partyId} under slot {slot}"); chr.PartyID = partyId; var member = new PartyMember(chr.ID, chr.Name, false); members[slot] = member; ForAllMembers(m => m.SendPacket(PartyPacket.JoinParty(member, this))); member.SendHpUpdate(); SendUpdatePartyData(); } public void Leave(Character fucker) { var slot = GetCharacterSlot(fucker.ID); if (slot == -1 || fucker.PartyID == 0) { _log.Error($"{fucker.ID} tried to get out of party {partyId}, but is not in it?"); fucker.SendPacket(PartyPacket.PartyError(PartyFunction.WITHDRAW_NOT_JOINED)); } else if (fucker.ID == leader.CharacterID) { _log.Debug($"Disbanding because {fucker.ID} left the party {partyId} (leader)"); Disband(fucker); } else { _log.Debug($"{fucker.ID} left the party {partyId} from slot {slot}"); var leaving = members[slot]; members[slot] = null; ForAllMembers(m => m.SendPacket(PartyPacket.MemberLeft(m, leaving, this, false, false))); leaving.SendPacket(PartyPacket.MemberLeft(leaving, leaving, this, false, false)); fucker.PartyID = 0; SendUpdatePartyData(); } } public void SilentUpdate(int charId, int disconnecting = -1) { var member = GetById(charId); ForAllMembers(m => m.SendPacket(PartyPacket.SilentUpdate(m, this, disconnecting))); member.SendHpUpdate(); SendUpdatePartyData(); } private void Disband(Character disbander) => OnlyByLeader(disbander.ID, ldr => { _log.Debug($"Disbanding party {partyId} by character {disbander.ID}"); ForAllMembers(m => { m.SendPacket(PartyPacket.MemberLeft(m, ldr, this, true, false)); var c = m.GetCharacter(false); if (c != null) { c.PartyID = 0; } else { _log.Debug($"Unable to set PartyID to 0 of {m.CharacterID}"); } }, -1, false); for (var i = 0; i < Constants.MaxPartyMembers; i++) { members[i] = null; } leader = null; Parties.Remove(partyId); var discardedInvites = Invites.Where(x => x.Value.partyId == partyId).Select(x => x.Key).ToArray(); discardedInvites.ForEach(x => Invites.Remove(x)); SendPartyDisband(); }); public void Expel(int expellerId, int toExpel) => OnlyByLeader(expellerId, ldr => { var slot = GetCharacterSlot(toExpel); if (slot == -1) { _log.Error($"Expelling {toExpel} from party {partyId} by {expellerId}, but was not in party???"); return; } _log.Info($"Expelling {toExpel} from party {partyId} by {expellerId}?"); var expelled = members[slot]; members[slot] = null; ForAllMembers(m => m.SendPacket(PartyPacket.MemberLeft(m, expelled, this, false, true))); expelled.SendPacket(PartyPacket.MemberLeft(expelled, expelled, this, false, true)); var expellchr = expelled.GetCharacter(false); if (expellchr != null) { expellchr.PartyID = 0; } else { _log.Debug($"Unable to set PartyID to 0 of {toExpel}"); } SendUpdatePartyData(); }); public void Chat(int chatter, string text) { var chr = GetById(chatter); if (members.Count(e => e?.IsOnline ?? false) <= 1) { chr.SendPacket(PartyPacket.NoneOnline()); } else { var allMembers = GetAllMembers(chatter).ToArray(); chr.GetCharacter(false).WrappedLogging(() => { _chatLog.Info(new MultiPeopleChatLog($"{chr.CharacterName}: {text}") { characterIDs = allMembers.Select(x => x.CharacterID).ToArray(), characterNames = allMembers.Select(x => x.CharacterName).ToArray(), }); }); // Send to all other members allMembers.ForEach(m => m.SendPacket(PartyPacket.PartyChat(chr.CharacterName, text, 1))); } } public void OnlyByLeader(int possibleImpostor, Action<PartyMember> action) { if (possibleImpostor == leader.CharacterID) { action(leader); } else { _log.Warn($"Trying to run func for only the leader, but {possibleImpostor} is not the leader of party {partyId}!"); } } public void UpdateDoor(DoorInformation newDoor, int charId) { Program.MainForm.LogDebug("UPDATING DOOR: " + charId); var member = GetById(charId); if (member == null) return; member.Door = newDoor; var idx = GetCharacterSlot(member); var packet = PartyPacket.UpdateDoor(newDoor, (byte)idx); ForAllMembers(m => { m.SendPacket(packet); }); } private void SendUpdatePartyData() { var pw = new Packet(ISServerMessages.PartyInformationUpdate); pw.WriteInt(partyId); pw.WriteInt(leader.CharacterID); for (var i = 0; i < Constants.MaxPartyMembers; i++) { var member = members[i]; pw.WriteInt(member?.CharacterID ?? 0); } CenterServer.Instance.World.SendPacketToEveryGameserver(pw); } private void SendPartyDisband() { var pw = new Packet(ISServerMessages.PartyDisbanded); pw.WriteInt(partyId); CenterServer.Instance.World.SendPacketToEveryGameserver(pw); } /****************************************************************/ private static readonly LoopingID IdGenerator = new LoopingID(1, int.MaxValue); public static readonly Dictionary<int, Party> Parties = new Dictionary<int, Party>(); //partyId -> party public static readonly Dictionary<int, Party> Invites = new Dictionary<int, Party>(); //invitee -> party public static void CreateParty(Character leader, DoorInformation doorInfo) { if (leader == null) { return; } // Allow beginners to create parties from lvl 10 and up if (leader.Job == 0 && leader.Level < 10) { _log.Warn($"Cannot create party because the leader would be beginner under lvl 10. Leader {leader.ID}"); leader.SendPacket(PartyPacket.PartyError(PartyFunction.CREATE_NEW_BEGINNER_DISALLOWED)); return; } if (leader.PartyID != 0) { _log.Warn($"Cannot create party because the leader is already in a party. Leader {leader.ID}"); leader.SendPacket(PartyPacket.PartyError(PartyFunction.CREATE_NEW_ALREADY_JOINED)); return; } var ldr = new PartyMember(leader.ID, leader.Name, true); ldr.Door = doorInfo; var id = IdGenerator.NextValue(); var pty = new Party(id, ldr); _log.Info($"Created party {id} with leader {leader.ID}"); Parties.Add(pty.partyId, pty); leader.PartyID = pty.partyId; leader.SendPacket(PartyPacket.PartyCreated(pty)); } public static void EncodeForMigration(Packet pw) { pw.WriteInt(IdGenerator.Current); pw.WriteInt(Parties.Count); foreach (var kvp in Parties) { pw.WriteInt(kvp.Key); var party = kvp.Value; pw.WriteInt(party.leader.CharacterID); for (var i = 0; i < Constants.MaxPartyMembers; i++) { var member = party.members[i]; if (member != null) { pw.WriteBool(true); member.EncodeForMigration(pw); } else { pw.WriteBool(false); } } } } public static void DecodeForMigration(Packet pr) { IdGenerator.Reset(pr.ReadInt()); var parties = pr.ReadInt(); for (var i = 0; i < parties; i++) { var party = new Party(pr); Parties.Add(party.partyId, party); } } } }
412
0.7332
1
0.7332
game-dev
MEDIA
0.60561
game-dev
0.858294
1
0.858294
OctoAwesome/octoawesome
2,478
OctoAwesome/OctoAwesome.Basics/Definitions/Items/Bucket.cs
using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; using OctoAwesome.Information; using OctoAwesome.Services; namespace OctoAwesome.Basics.Definitions.Items { /// <summary> /// Bucket item for inventories. /// </summary> public class Bucket : Item, IFluidInventory { /// <inheritdoc /> public int Quantity { get; private set; } /// <inheritdoc /> public IBlockDefinition? FluidBlock { get; private set; } /// <inheritdoc /> public int MaxQuantity { get; } /// <summary> /// Initializes a new instance of the <see cref="Bucket"/> class. /// </summary> /// <param name="definition">The bucket item definition.</param> /// <param name="materialDefinition">The material definition the bucket is made out of.</param> public Bucket(BucketDefinition definition, IMaterialDefinition materialDefinition) : base(definition, materialDefinition) { MaxQuantity = 1250; } /// <inheritdoc /> public void AddFluid(int quantity, IBlockDefinition fluidBlock) { if (!Definition.CanMineMaterial(fluidBlock.Material)) return; if (Quantity < 125) Quantity += quantity; FluidBlock = fluidBlock; } /// <inheritdoc /> public override int Hit(IMaterialDefinition material, IBlockInteraction hitInfo, decimal volumeRemaining, int volumePerHit) { if (!Definition.CanMineMaterial(material)) return 0; if (material is IFluidMaterialDefinition fluid) { if (!(FluidBlock is null) && fluid != FluidBlock.Material) return 0; if (Quantity + volumePerHit >= MaxQuantity) return MaxQuantity - Quantity; return volumePerHit; } return base.Hit(material, hitInfo, volumeRemaining, volumePerHit); } /// <inheritdoc /> public override int Apply(IMaterialDefinition material, IBlockInteraction hitInfo, decimal volumeRemaining) { if (Quantity > 125 && FluidBlock is not null) { BlockInteractionService.CalculatePositionAndRotation(hitInfo, out var facingDirection, out _); } return base.Apply(material, hitInfo, volumeRemaining); } } }
412
0.791262
1
0.791262
game-dev
MEDIA
0.163274
game-dev
0.858252
1
0.858252
mastercomfig/tf2-patches-old
28,193
src/ivp/ivp_intern/ivp_physic_private.cxx
// Copyright (C) Ipion Software GmbH 1999-2000. All rights reserved. #include <ivp_physics.hxx> #ifndef WIN32 # pragma implementation "ivp_physic_private.hxx" # pragma implementation "ivp_listener_object.hxx" # pragma implementation "ivp_listener_collision.hxx" # pragma implementation "ivp_controller.hxx" #endif #include <ivp_listener_object.hxx> #include <ivp_listener_collision.hxx> #include <ivp_physic_private.hxx> #include <ivp_i_object_vhash.hxx> #include <ivp_i_collision_vhash.hxx> #include <ivp_mindist_intern.hxx> //because of Mindist #include <ivp_friction.hxx> #include <ivu_active_value.hxx> #include <ivp_actuator.hxx> #include <ivp_debug_manager.hxx> //because of debug psi_synchrone #include <ivp_merge_core.hxx> #include <ivp_debug.hxx> #include <ivp_universe_manager.hxx> #include <ivp_authenticity.hxx> void IVP_Listener_Collision::event_pre_collision( IVP_Event_Collision *){;}; // the user app sould override this void IVP_Listener_Collision::event_post_collision( IVP_Event_Collision *){;}; // the user app sould override this void IVP_Listener_Collision::event_collision_object_deleted( IVP_Real_Object *){;}; // only object private callbacks are called // friction // set the IVP_LISTENER_COLLISION_CALLBACK_FRICTION bit in the constructor if you want to use this void IVP_Listener_Collision::event_friction_created(IVP_Event_Friction *){;}; // the user app sould override this void IVP_Listener_Collision::event_friction_deleted(IVP_Event_Friction *){;}; // the user app sould override this IVP_Cluster *IVP_Cluster_Manager::get_root_cluster() { return root_cluster; } IVP_Cluster_Manager::IVP_Cluster_Manager(IVP_Environment *env) { P_MEM_CLEAR(this); environment = env; root_cluster = new IVP_Cluster(env); this->obj_callback_hash = new IVP_Object_Callback_Table_Hash(16); this->collision_callback_hash = new IVP_Collision_Callback_Table_Hash(16); } void IVP_Cluster_Manager::fire_event_object_deleted(IVP_Event_Object *event_obj) { IVP_Object_Callback_Table *obj_table; IVP_Real_Object *ro = event_obj->real_object; obj_table = this->obj_callback_hash->find_table(ro); if ( obj_table != NULL ) { int i; for (i=obj_table->listeners.len()-1; i>=0; i--) { IVP_Listener_Object *lis = obj_table->listeners.element_at(i); lis->event_object_deleted(event_obj); if (i>0 && !obj_callback_hash->find_table(ro)) break; // object deleted } } } void IVP_Cluster_Manager::fire_event_object_frozen(IVP_Event_Object *event_obj) { IVP_Object_Callback_Table *obj_table; IVP_Real_Object *ro = event_obj->real_object; obj_table = this->obj_callback_hash->find_table(ro); if ( obj_table != NULL ) { int i; for (i=obj_table->listeners.len()-1; i>=0; i--) { IVP_Listener_Object *lis = obj_table->listeners.element_at(i); lis->event_object_frozen(event_obj); if (i>0 && !obj_callback_hash->find_table(ro)) break; // object deleted } } } void IVP_Cluster_Manager::fire_event_object_created(IVP_Event_Object *event_obj) { IVP_Object_Callback_Table *obj_table; IVP_Real_Object *ro = event_obj->real_object; obj_table = this->obj_callback_hash->find_table(ro); if ( obj_table != NULL ) { int i; for (i=obj_table->listeners.len()-1; i>=0; i--) { IVP_Listener_Object *lis = obj_table->listeners.element_at(i); lis->event_object_created(event_obj); if (i>0 && !obj_callback_hash->find_table(ro)) break; // object deleted } } } void IVP_Cluster_Manager::fire_event_object_revived(IVP_Event_Object *event_obj) { IVP_Object_Callback_Table *obj_table; IVP_Real_Object *ro = event_obj->real_object; obj_table = this->obj_callback_hash->find_table(ro); if ( obj_table != NULL ) { int i; for (i=obj_table->listeners.len()-1; i>=0; i--) { IVP_Listener_Object *lis = obj_table->listeners.element_at(i); lis->event_object_revived(event_obj); if (i>0 && !obj_callback_hash->find_table(ro)) break; // object deleted } } } void IVP_Cluster_Manager::fire_event_pre_collision(IVP_Real_Object *real_object, IVP_Event_Collision *event_obj) { IVP_Collision_Callback_Table *obj_table; obj_table = this->collision_callback_hash->find_table(real_object); if ( obj_table != NULL ) { int i; for (i=obj_table->listeners.len()-1; i>=0; i--) { IVP_Listener_Collision *lis = obj_table->listeners.element_at(i); if (!(lis->get_enabled_callbacks() & IVP_LISTENER_COLLISION_CALLBACK_PRE_COLLISION)) continue; lis->event_pre_collision(event_obj); if (i>0 && !collision_callback_hash->find_table(real_object)) break; // object deleted } } } void IVP_Cluster_Manager::fire_event_post_collision(IVP_Real_Object *real_object, IVP_Event_Collision *event_obj) { IVP_Collision_Callback_Table *obj_table; obj_table = this->collision_callback_hash->find_table(real_object); if ( obj_table != NULL ) { int i; for (i=obj_table->listeners.len()-1; i>=0; i--) { IVP_Listener_Collision *lis = obj_table->listeners.element_at(i); if (!(lis->get_enabled_callbacks() & IVP_LISTENER_COLLISION_CALLBACK_POST_COLLISION)) continue; lis->event_post_collision(event_obj); if (i>0 && !collision_callback_hash->find_table(real_object)) break; // object deleted } } } void IVP_Cluster_Manager::fire_event_collision_object_deleted(IVP_Real_Object *real_object) { IVP_Collision_Callback_Table *obj_table; obj_table = this->collision_callback_hash->find_table(real_object); if ( obj_table != NULL ) { int i; for (i=obj_table->listeners.len()-1; i>=0; i--) { IVP_Listener_Collision *lis = obj_table->listeners.element_at(i); if (!(lis->get_enabled_callbacks() & IVP_LISTENER_COLLISION_CALLBACK_OBJECT_DELETED)) continue; lis->event_collision_object_deleted(real_object); if (i>0 && !collision_callback_hash->find_table(real_object)) break; // object deleted } } } void IVP_Cluster_Manager::fire_event_friction_created(IVP_Real_Object *real_object, IVP_Event_Friction *event_friction) { IVP_Collision_Callback_Table *obj_table; obj_table = this->collision_callback_hash->find_table(real_object); if ( obj_table != NULL ) { int i; for (i=obj_table->listeners.len()-1; i>=0; i--) { IVP_Listener_Collision *lis = obj_table->listeners.element_at(i); if (!(lis->get_enabled_callbacks() & IVP_LISTENER_COLLISION_CALLBACK_FRICTION)) continue; lis->event_friction_created(event_friction); if (i>0 && !collision_callback_hash->find_table(real_object)) break; // object deleted } } } void IVP_Cluster_Manager::fire_event_friction_deleted(IVP_Real_Object *real_object, IVP_Event_Friction *event_friction) { IVP_Collision_Callback_Table *obj_table; obj_table = this->collision_callback_hash->find_table(real_object); if ( obj_table != NULL ) { int i; for (i=obj_table->listeners.len()-1; i>=0; i--) { IVP_Listener_Collision *lis = obj_table->listeners.element_at(i); if (!(lis->get_enabled_callbacks() & IVP_LISTENER_COLLISION_CALLBACK_FRICTION)) continue; lis->event_friction_deleted(event_friction); if (i>0 && !collision_callback_hash->find_table(real_object)) break; // object deleted } } } IVP_Real_Object *IVP_Cluster_Manager::get_next_real_object_in_cluster_tree(IVP_Object *object){ IVP_Object *next_object; if (number_of_real_objects == 0) return NULL; if (object == NULL){ IVP_Cluster *root = get_root_cluster(); object = root->get_first_object_of_cluster(); next_object = object; // no object supplied: we get the root cluster and we want the first object in root cluster! if (!object) return NULL; } else { next_object = object->next_in_cluster; // object supplied: just get the next object in cluster } IVP_OBJECT_TYPE type = object->get_type(); // try to go down as deep as possible if(type == IVP_CLUSTER){ IVP_Cluster *cluster = object->to_cluster(); while(1){ object = cluster->get_first_object_of_cluster(); if (object){ type = object->get_type(); if (type != IVP_CLUSTER) return object->to_real(); cluster = object->to_cluster(); continue; }else{ break; // just get next_in_cluster } } } IVP_Object *next; // go up until a next pointer is found for (next=next_object; !next; next=object->next_in_cluster) { IVP_Object *old_father = object; object = object->father_cluster; if (!object){ IVP_Cluster *root = get_root_cluster(); if ( root == old_father ) return(NULL); /* necessary to avoid endless loop caused by the last object * (ball's father is cluster; cluster has no father, * therefore we would "get_root_cluster()" which is the same as * the old cluster and whose first object is the "static ball" * --> perfect endless loop :-) [SF, 25 nov 1999] */ object = root->get_first_object_of_cluster(); if (!object) return NULL; } } // now a next is found object = next; type = object->get_type(); if (type == IVP_CLUSTER){ return get_next_real_object_in_cluster_tree(object); } return object->to_real(); } void IVP_Cluster_Manager::check_for_unused_objects(IVP_Universe_Manager *um){ const IVP_Universe_Manager_Settings *ums = um->provide_universe_settings(); if (number_of_real_objects < ums->num_objects_in_environment_threshold_0) return; { int i = int( ums->check_objects_per_second_threshold_0 * environment->get_delta_PSI_time()); for ( ; i>=0; i-- ){ IVP_Real_Object *an_object = this->an_object_to_be_checked; this->an_object_to_be_checked = get_next_real_object_in_cluster_tree(this->an_object_to_be_checked); if (!an_object) return; // no objects available if (an_object->get_collision_check_reference_count() != 0) continue; um->object_no_longer_needed(an_object); if (number_of_real_objects < ums->num_objects_in_environment_threshold_0) return; } } if (number_of_real_objects < ums->num_objects_in_environment_threshold_1) return; { int i = int( ums->check_objects_per_second_threshold_1 * environment->get_delta_PSI_time()); for ( ; i>=0; i-- ){ IVP_Real_Object *an_object = this->an_object_to_be_checked; if (!an_object) return; // no objects available this->an_object_to_be_checked = get_next_real_object_in_cluster_tree(this->an_object_to_be_checked); if (an_object->get_collision_check_reference_count() != 1) continue; um->object_no_longer_needed(an_object); if (number_of_real_objects < ums->num_objects_in_environment_threshold_1) return; } } return; } IVP_Universe_Manager_Settings::IVP_Universe_Manager_Settings(){ num_objects_in_environment_threshold_0 = 1; check_objects_per_second_threshold_0 = 1; num_objects_in_environment_threshold_1 = 1000000; check_objects_per_second_threshold_1 = 10; }; IVP_Object_Callback_Table::~IVP_Object_Callback_Table() { return; } IVP_Collision_Callback_Table::~IVP_Collision_Callback_Table() { return; } IVP_Cluster_Manager::~IVP_Cluster_Manager() { P_DELETE( root_cluster ); P_DELETE(this->obj_callback_hash); P_DELETE(this->collision_callback_hash); } void IVP_Cluster_Manager::add_listener_object(IVP_Real_Object *real_object, IVP_Listener_Object *listener) { IVP_Object_Callback_Table *obj_table; obj_table = this->obj_callback_hash->find_table(real_object); if ( obj_table != NULL ) { obj_table->listeners.add(listener); } else { obj_table = new IVP_Object_Callback_Table(); obj_table->real_object = real_object; obj_table->listeners.add(listener); this->obj_callback_hash->add_table(obj_table); real_object->flags.object_listener_exists = 1; } return; } void IVP_Cluster_Manager::add_listener_collision(IVP_Real_Object *real_object, IVP_Listener_Collision *listener) { IVP_Collision_Callback_Table *obj_table; obj_table = this->collision_callback_hash->find_table(real_object); if ( obj_table != NULL ) { obj_table->listeners.add(listener); } else { obj_table = new IVP_Collision_Callback_Table(); obj_table->real_object = real_object; obj_table->listeners.add(listener); this->collision_callback_hash->add_table(obj_table); real_object->flags.collision_listener_exists = 1; } return; } void IVP_Cluster_Manager::remove_listener_object(IVP_Real_Object *real_object, IVP_Listener_Object *listener) { IVP_Object_Callback_Table *obj_table; obj_table = this->obj_callback_hash->find_table(real_object); if ( obj_table != NULL ) { obj_table->listeners.remove(listener); if ( obj_table->listeners.len() == 0 ) { this->obj_callback_hash->remove_table(real_object); delete obj_table; real_object->flags.object_listener_exists = 0; } } return; } void IVP_Cluster_Manager::remove_listener_collision(IVP_Real_Object *real_object, IVP_Listener_Collision *listener) { IVP_Collision_Callback_Table *obj_table; obj_table = this->collision_callback_hash->find_table(real_object); if ( obj_table != NULL ) { obj_table->listeners.remove(listener); if ( obj_table->listeners.len() == 0 ) { this->collision_callback_hash->remove_table(real_object); delete obj_table; real_object->flags.collision_listener_exists = 0; } } return; } void IVP_Cluster_Manager::add_object(IVP_Real_Object * /*real_object*/ ){ this->number_of_real_objects++; } void IVP_Cluster_Manager::remove_object(IVP_Real_Object *real_object) { this->number_of_real_objects--; IVP_Object_Callback_Table *obj_table; obj_table = this->obj_callback_hash->find_table(real_object); if ( obj_table != NULL ) { this->obj_callback_hash->remove_table(real_object); delete obj_table; } IVP_Collision_Callback_Table *coll_table; coll_table = this->collision_callback_hash->find_table(real_object); if ( coll_table != NULL ) { this->collision_callback_hash->remove_table(real_object); delete coll_table; } if (real_object == an_object_to_be_checked){ an_object_to_be_checked = get_next_real_object_in_cluster_tree(an_object_to_be_checked); if (real_object == an_object_to_be_checked){ an_object_to_be_checked = NULL; } } IVP_Universe_Manager *um = environment->get_universe_manager(); if (um){ um->event_object_deleted(real_object); } return; } // a not simulated object is revived and will be simulated again in next PSI // returns IVP_TRUE when a friction system was grown -> needed for sim_unit revival algorithm IVP_BOOL IVP_Core::revive_simulation_core() { IVP_Core *core=this; IVP_ASSERT( !core->physical_unmoveable ); IVP_ASSERT( core->movement_state == IVP_MT_NOT_SIM); for(int c = core->objects.len()-1;c>=0;c--) { IVP_Real_Object *r_obj=core->objects.element_at(c); IVP_IF(1) { IVP_ASSERT( r_obj->get_movement_state() >= IVP_MT_NOT_SIM ); } r_obj->set_movement_state(IVP_MT_MOVING); } core->init_core_for_simulation(); IVP_Event_Sim es(environment, environment->get_next_PSI_time() - environment->get_current_time()); core->calc_next_PSI_matrix_zero_speed(&es); // @@@ hack, go back to last PSI at wakeup at PSI ( satisfy init_PSI ) IVP_IF (environment->get_env_state() == IVP_ES_PSI){ IVP_DOUBLE d_time = environment->get_delta_PSI_time(); core->time_of_last_psi += -d_time; } IVP_IF(IVP_DEBUG_OBJECT0){ const char *search0 = IVP_DEBUG_OBJECT0; const char *name0 = core->objects.element_at(0)->get_name(); if ( !P_String::string_cmp(name0, search0, IVP_FALSE)){ if ( core->environment->get_current_time().get_time() >= IVP_DEBUG_TIME){ printf("revive object %s time:%f\n", name0, environment->get_current_time().get_time()); } } } IVP_IF(IVP_DEBUG_OBJECT1){ const char *search0 = IVP_DEBUG_OBJECT1; const char *name0 = core->objects.element_at(0)->get_name(); if ( !P_String::string_cmp(name0, search0, IVP_FALSE)){ if ( core->environment->get_current_time().get_time() >= IVP_DEBUG_TIME){ printf("revive object %s time:%f\n", name0, environment->get_current_time().get_time()); } } } //IVP_Friction_Info_For_Core *my_info=core->moveable_core_has_friction_info(); //if(my_info==NULL) { // grow a friction system (search for near objects and put them into one friction system ) IVP_BOOL fs_was_grown=core->grow_friction_system(); //} for(int d = core->objects.len()-1;d>=0;d--) { IVP_Real_Object *r_obj=core->objects.element_at(d); { // fire object-dependant 'object revived' event IVP_Event_Object event_revived; event_revived.real_object = r_obj; event_revived.environment = core->environment; core->environment->get_cluster_manager()->fire_event_object_revived(&event_revived); } { // fire global 'object revived' event IVP_Event_Object event_revived; event_revived.real_object = r_obj; event_revived.environment = core->environment; core->environment->fire_event_object_revived(&event_revived); } } return fs_was_grown; } void IVP_Core::fire_event_object_frozen(){ // fire events for (int i=this->objects.len()-1; i>=0; i--) { IVP_Real_Object *real_object = this->objects.element_at(i); { // fire object-dependant 'object frozen' event IVP_Event_Object event_frozen; event_frozen.real_object = real_object; event_frozen.environment = this->environment; this->environment->get_cluster_manager()->fire_event_object_frozen(&event_frozen); } { // fire global 'object frozen' event IVP_Event_Object event_frozen; event_frozen.real_object = real_object; event_frozen.environment = this->environment; this->environment->fire_event_object_frozen(&event_frozen); } } } void IVP_Core::freeze_simulation_core(){ IVP_Core *r_core=this; r_core->stop_physical_movement(); //because of Interpolations /// deactivate all mindists IVP_IF(IVP_DEBUG_OBJECT0){ const char *search0 = IVP_DEBUG_OBJECT0; const char *name0 = r_core->objects.element_at(0)->get_name(); if ( !P_String::string_cmp(name0, search0, IVP_FALSE)){ if ( r_core->environment->get_current_time().get_time() >= IVP_DEBUG_TIME){ printf("freeze object %s time:%f\n", name0, environment->get_current_time().get_time()); } } } IVP_IF(IVP_DEBUG_OBJECT1){ const char *search0 = IVP_DEBUG_OBJECT1; const char *name0 = r_core->objects.element_at(0)->get_name(); if ( !P_String::string_cmp(name0, search0, IVP_FALSE)){ if ( r_core->environment->get_current_time().get_time() >= IVP_DEBUG_TIME){ printf("freeze object %s time:%f\n", name0, environment->get_current_time().get_time()); } } } fire_event_object_frozen(); } void IVP_Core::debug_out_movement_vars() { printf("core_status %lx trans %f %f %f rot %f %f %f\n",(long)this&0x0000ffff,speed.k[0],speed.k[1],speed.k[2],rot_speed.k[0],rot_speed.k[1],rot_speed.k[2]); } void IVP_Core::debug_vec_movement_state() { IVP_Core *my_core=this; IVP_Core *one_object=this; IVP_IF( 0 ){ char *out_text; IVP_U_Float_Point ivp_pointer; IVP_U_Point ivp_start; int v_color; ivp_start.set(my_core->get_position_PSI()); ivp_pointer.set(0.0f,-7.0f,0.0f); out_text=p_make_string("oob%lx_sp%.3f",(long)one_object&0x0000ffff,one_object->speed.real_length());//,one_object->get_energy_on_test(&one_object->speed,&one_object->rot_speed)); if(my_core->movement_state==IVP_MT_CALM) { //out_text=p_export_error("%lxo_calm%lx",(long)one_object&0x0000ffff,(long)fr_i&0x0000ffff); //sprintf(out_text,"%ldobj_calm%lx",counter,(long)one_object); v_color=3; } else { if(my_core->movement_state==IVP_MT_SLOW) { //out_text=p_export_error("%lxdo_not_m%lx",(long)one_object&0x0000ffff,(long)fr_i&0x0000ffff); v_color=6; } else { //out_text=p_export_error("%lxdo_moved%lx",(long)one_object&0x0000ffff,(long)fr_i&0x0000ffff); //sprintf(out_text,"%obj_moved%lx",(long)one_object); v_color=1; } } this->environment->add_draw_vector(&ivp_start,&ivp_pointer,out_text,v_color); P_FREE(out_text); } } // check for not moving objects // object is removed from simulation if not moving for 1 sec or slowling moving for 10 sec // exception: objects belonging to friction systems // friction systems are tested separately, all objects of fr_system are removed at a time IVP_Friction_System::IVP_Friction_System(IVP_Environment *env) { IVP_IF(env->get_debug_manager()->check_fs) { fprintf(env->get_debug_manager()->out_deb_file,"create_fs %f %lx\n",env->get_current_time().get_time(),(long)this); } //printf("creating_new_fs %lx at time %f\n",(long)this,env->get_current_time()); l_environment=env; //first_friction_obj=NULL; union_find_necessary=IVP_FALSE; first_friction_dist=NULL; friction_obj_number=0; friction_dist_number=0; static_fs_handle.l_friction_system=this; energy_fs_handle.l_friction_system=this; } IVP_Friction_System::~IVP_Friction_System() { //printf("deleting_of_fs %lx at time %f\n",(long)this,l_environment->get_current_time()); IVP_IF(l_environment->get_debug_manager()->check_fs) { fprintf(l_environment->get_debug_manager()->out_deb_file,"delete_fs %f %lx\n",l_environment->get_current_time().get_time(),(long)this); } // deleteing of real friction systems filled with information is not yet implemented (not trivial : unlink whole friction infos) //Assertion: when } void IVP_Friction_System::fs_recalc_all_contact_points() { for (int i = fr_pairs_of_objs.len()-1; i>=0;i--){ IVP_Friction_Core_Pair *my_pair = fr_pairs_of_objs.element_at(i); IVP_FLOAT energy_diff_sum=0.0f; for (int j = my_pair->fr_dists.len()-1; j>=0;j--){ IVP_Contact_Point *fr_mindist = my_pair->fr_dists.element_at(j); IVP_FLOAT old_gap_len=fr_mindist->get_gap_length(); fr_mindist->recalc_friction_s_vals(); //energy considerations //when gap is gettinger bigger, potential energy is gained //when pressure is going up, do not mind IVP_FLOAT gap_diff= old_gap_len - fr_mindist->get_gap_length(); energy_diff_sum+=fr_mindist->now_friction_pressure * gap_diff; } if(energy_diff_sum > 0.0f) { my_pair->integrated_anti_energy += energy_diff_sum; } } } // is union find necessary after removing of dist ? IVP_BOOL IVP_Friction_System::dist_removed_update_pair_info(IVP_Contact_Point *old_dist) { //manage info of obj pairs { IVP_Friction_Core_Pair *my_pair_info; IVP_Core *core0,*core1; core0=old_dist->get_synapse(0)->l_obj->physical_core; core1=old_dist->get_synapse(1)->l_obj->physical_core; my_pair_info=this->get_pair_info_for_objs(core0,core1); if(!my_pair_info) { CORE; } my_pair_info->del_fr_dist_obj_pairs(old_dist); if(my_pair_info->number_of_pair_dists()==0) { this->del_fr_pair(my_pair_info); P_DELETE(my_pair_info); // start union find return IVP_TRUE; } else { return IVP_FALSE; } } } void IVP_Friction_System::remove_dist_from_system(IVP_Contact_Point *old_dist) { IVP_IF(l_environment->get_debug_manager()->check_fs) { fprintf(l_environment->get_debug_manager()->out_deb_file,"rem_dist_from_fs %f %lx from %lx\n",l_environment->get_current_time().get_time(),(long)old_dist,(long)this); } //manage list of all dists { IVP_Contact_Point *previous=old_dist->prev_dist_in_friction; IVP_Contact_Point *following=old_dist->next_dist_in_friction; if(following!=NULL) { following->prev_dist_in_friction=previous; } if(previous) { previous->next_dist_in_friction=following; } else { this->first_friction_dist=following; } } friction_dist_number--; } void IVP_Friction_System::dist_added_update_pair_info(IVP_Contact_Point *new_dist) { //manage info of obj pairs { IVP_Friction_Core_Pair *my_pair_info; IVP_Core *core0,*core1; core0=new_dist->get_synapse(0)->l_obj->physical_core; core1=new_dist->get_synapse(1)->l_obj->physical_core; my_pair_info=this->get_pair_info_for_objs(core0,core1); if(my_pair_info) { ; } else { my_pair_info=new IVP_Friction_Core_Pair(); my_pair_info->objs[0]=core0; my_pair_info->objs[1]=core1; this->add_fr_pair(my_pair_info); } my_pair_info->add_fr_dist_obj_pairs(new_dist); } } void IVP_Friction_System::add_dist_to_system(IVP_Contact_Point *new_dist) { IVP_IF(l_environment->get_debug_manager()->check_fs) { fprintf(l_environment->get_debug_manager()->out_deb_file,"add_dist_to_fs %f %lx to %lx\n",l_environment->get_current_time().get_time(),(long)new_dist,(long)this); } new_dist->l_friction_system=this; //manage list of all dists { IVP_Contact_Point *first=this->first_friction_dist; new_dist->prev_dist_in_friction=NULL; new_dist->next_dist_in_friction=first; this->first_friction_dist=new_dist; if(first) { first->prev_dist_in_friction=new_dist; } } //new_dist->number_in_friction = this->friction_dist_number; //dists are numbered the wrong way: last has number 0 IVP_IF(l_environment->debug_information->debug_mindist){ printf("added_dist %d\n",(int)friction_dist_number); } friction_dist_number++; //fr_solver.calc_calc_solver(this); //solver matrix must be greater and temporary results also } void IVP_Friction_System::add_core_to_system(IVP_Core *new_obj) { IVP_IF(l_environment->get_debug_manager()->check_fs) { fprintf(l_environment->get_debug_manager()->out_deb_file,"add_core_to_fs %f %lx to %lx\n",l_environment->get_current_time().get_time(),(long)new_obj,(long)this); } cores_of_friction_system.add(new_obj); if(!new_obj->physical_unmoveable) { moveable_cores_of_friction_system.add(new_obj); new_obj->add_core_controller(&static_fs_handle); new_obj->add_core_controller(this); new_obj->add_core_controller(&energy_fs_handle); //new_obj->sim_unit_of_core->add_controller_of_core( new_obj, &this->static_fs_handle ); //new_obj->sim_unit_of_core->add_controller_of_core( new_obj, this ); //new_obj->sim_unit_of_core->add_controller_of_core( new_obj, &this->energy_fs_handle ); } friction_obj_number++; } void IVP_Friction_System::remove_core_from_system(IVP_Core *old_obj) { IVP_IF(l_environment->get_debug_manager()->check_fs) { fprintf(l_environment->get_debug_manager()->out_deb_file,"remove_core_from_fs %f %lx from %lx\n",l_environment->get_current_time().get_time(),(long)old_obj,(long)this); } if(!old_obj->physical_unmoveable) { moveable_cores_of_friction_system.remove(old_obj); old_obj->rem_core_controller(&this->energy_fs_handle); old_obj->rem_core_controller(this); old_obj->rem_core_controller(&static_fs_handle); } cores_of_friction_system.remove(old_obj); friction_obj_number--; } void IVP_Environment::remove_revive_core(IVP_Core *c) { int index=this->core_revive_list.index_of(c); if(index>=0) { IVP_ASSERT(c->is_in_wakeup_vec==IVP_TRUE); this->core_revive_list.remove_at(index); c->is_in_wakeup_vec=IVP_FALSE; } } void IVP_Environment::add_revive_core(IVP_Core *c) { if(c->is_in_wakeup_vec==IVP_TRUE) { return; } IVP_IF(1) { IVP_ASSERT(this->core_revive_list.index_of(c)<0); } core_revive_list.add(c); c->is_in_wakeup_vec=IVP_TRUE; } void IVP_Environment::revive_cores_PSI(){ for(int i=core_revive_list.len()-1;i>=0;i--) { IVP_Core *my_core=core_revive_list.element_at(i); IVP_ASSERT(my_core->physical_unmoveable==IVP_FALSE); my_core->ensure_core_to_be_in_simulation(); my_core->is_in_wakeup_vec=IVP_FALSE; } core_revive_list.clear(); } void IVP_Universe_Manager::ensure_objects_in_environment(IVP_Real_Object * /*object*/, IVP_U_Float_Point * /*sphere_center*/, IVP_DOUBLE /*sphere_radius*/) { ; } void IVP_Universe_Manager::object_no_longer_needed(IVP_Real_Object *) { ; } void IVP_Universe_Manager::event_object_deleted(IVP_Real_Object *) { ; } const IVP_Universe_Manager_Settings *IVP_Universe_Manager::provide_universe_settings() { return NULL; }
412
0.966266
1
0.966266
game-dev
MEDIA
0.77551
game-dev
0.924295
1
0.924295
SOUI2/soui
2,258
third-part/skia/src/animator/SkDrawGroup.h
/* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkDrawGroup_DEFINED #define SkDrawGroup_DEFINED #include "SkDrawable.h" #include "SkIntArray.h" #include "SkMemberInfo.h" class SkGroup : public SkDrawable { //interface for schema element <g> public: DECLARE_MEMBER_INFO(Group); SkGroup(); virtual ~SkGroup(); virtual bool addChild(SkAnimateMaker& , SkDisplayable* child) SK_OVERRIDE; virtual bool contains(SkDisplayable* ); SkGroup* copy(); SkBool copySet(int index); virtual SkDisplayable* deepCopy(SkAnimateMaker* ); virtual bool doEvent(SkDisplayEvent::Kind , SkEventState* state ); virtual bool draw(SkAnimateMaker& ); #ifdef SK_DUMP_ENABLED virtual void dump(SkAnimateMaker* ); virtual void dumpDrawables(SkAnimateMaker* ); virtual void dumpEvents(); #endif int findGroup(SkDrawable* drawable, SkTDDrawableArray** list, SkGroup** parent, SkGroup** found, SkTDDrawableArray** grandList); virtual bool enable(SkAnimateMaker& ); SkTDDrawableArray* getChildren() { return &fChildren; } SkGroup* getOriginal() { return fOriginal; } virtual bool hasEnable() const; virtual void initialize(); SkBool isACopy() { return fOriginal != NULL; } void markCopyClear(int index); void markCopySet(int index); void markCopySize(int index); bool markedForDelete(int index) const { return (fCopies[index >> 5] & 1 << (index & 0x1f)) == 0; } void reset(); bool resolveIDs(SkAnimateMaker& maker, SkDisplayable* original, SkApply* ); virtual void setSteps(int steps); #ifdef SK_DEBUG virtual void validate(); #endif protected: bool ifCondition(SkAnimateMaker& maker, SkDrawable* drawable, SkString& conditionString); SkString condition; SkString enableCondition; SkTDDrawableArray fChildren; SkTDDrawableArray* fParentList; SkTDIntArray fCopies; SkGroup* fOriginal; private: typedef SkDrawable INHERITED; }; class SkSave: public SkGroup { DECLARE_MEMBER_INFO(Save); virtual bool draw(SkAnimateMaker& ); private: typedef SkGroup INHERITED; }; #endif // SkDrawGroup_DEFINED
412
0.805255
1
0.805255
game-dev
MEDIA
0.872332
game-dev
0.681319
1
0.681319
Momo-Softworks/Cold-Sweat
1,937
src/main/java/com/momosoftworks/coldsweat/api/temperature/effect/player/FreezeShiverEffect.java
package com.momosoftworks.coldsweat.api.temperature.effect.player; import com.momosoftworks.coldsweat.api.temperature.effect.TempEffect; import com.momosoftworks.coldsweat.api.temperature.effect.TempEffectType; import com.momosoftworks.coldsweat.config.ConfigSettings; import com.momosoftworks.coldsweat.data.codec.util.IntegerBounds; import com.momosoftworks.coldsweat.util.math.CSMath; import net.minecraft.client.Minecraft; import net.minecraft.world.entity.LivingEntity; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.ViewportEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; public class FreezeShiverEffect extends TempEffect { public FreezeShiverEffect(TempEffectType<?> type, LivingEntity entity, IntegerBounds bounds) { super(type, entity, bounds); } @OnlyIn(Dist.CLIENT) @SubscribeEvent public void shiverCamera(ViewportEvent.ComputeCameraAngles event) { if (!this.test(Minecraft.getInstance().player)) return; LivingEntity entity = this.entity(); if (!Minecraft.getInstance().isPaused() && ConfigSettings.DISTORTION_EFFECTS.get()) { double effect = this.getEffectFactor(); double tickTime = entity.tickCount + event.getPartialTick(); float shiverIntensity = (float) CSMath.blend(0, (Math.sin(tickTime / 10) + 1) * 0.03f + 0.01f, effect, 0, 1); shiverIntensity *= ConfigSettings.SHIVER_INTENSITY.get(); // Multiply the effect for lower framerates shiverIntensity *= Minecraft.getInstance().getDeltaFrameTime() * 10; // Rotate camera float shiverRotation = (float) (Math.sin(tickTime * 2.5) * shiverIntensity); entity.setYRot(entity.getYRot() + shiverRotation); } } @Override public Side getSide() { return Side.CLIENT; } }
412
0.804924
1
0.804924
game-dev
MEDIA
0.889541
game-dev
0.832823
1
0.832823
PiratesOnlineRewritten/Pirates-Online-Rewritten
11,946
pirates/friends/GuildMember.py
from direct.gui.DirectGui import * from pandac.PandaModules import * from direct.directnotify import DirectNotifyGlobal from otp.otpbase import OTPLocalizer from otp.otpbase import OTPGlobals from pirates.piratesgui import PDialog from pirates.piratesgui import PiratesGuiGlobals from pirates.piratesbase import PiratesGlobals from pirates.piratesgui.RequestButton import RequestButton GUILDRANK_VETERAN = 4 GUILDRANK_GM = 3 GUILDRANK_OFFICER = 2 GUILDRANK_MEMBER = 1 class GuildMemberButton(RequestButton): def __init__(self, text, command): RequestButton.__init__(self, text, command, 2.0) self.initialiseoptions(GuildMemberButton) self['text_pos'] = (0.05, 0.025) class GuildMemberButtonYesNo(RequestButton): def __init__(self, text, command): RequestButton.__init__(self, text, command, 1.0) self.initialiseoptions(GuildMemberButtonYesNo) self['text_pos'] = (0.05, 0.025) class GuildMember(DirectFrame): notify = DirectNotifyGlobal.directNotify.newCategory('GuildMember') def __init__(self, avId, avName, guildId, canpromote, candemote, cankick): guiMain = loader.loadModel('models/gui/gui_main') DirectFrame.__init__(self, relief=None, pos=(-0.6, 0, 0.42), image=guiMain.find('**/general_frame_e'), image_pos=(0.25, 0, 0.24), image_scale=(0.3, 0.0, 0.34)) self.initialiseoptions(GuildMember) self.avId = avId self.avName = avName self.guildId = guildId self.canpromote = canpromote self.candemote = candemote self.cankick = cankick rank = base.cr.guildManager.getRank(avId) self.title = None self.message = None self.avocateMessage = None self.bTopEditButton = None self.bBottomEditButton = None self.bKick = None self.bAvocateConfrim = None self.bAvocateCancel = None self.bAvocate = None guiMain = loader.loadModel('models/gui/gui_main') self.title = DirectLabel(parent=self, relief=None, text=OTPLocalizer.GuildMemberTitle, text_scale=PiratesGuiGlobals.TextScaleTitleSmall, text_align=TextNode.ACenter, text_fg=PiratesGuiGlobals.TextFG2, text_shadow=PiratesGuiGlobals.TextShadow, text_font=PiratesGlobals.getPirateOutlineFont(), pos=(0.25, 0, 0.44)) self.message = DirectLabel(parent=self, relief=None, text=avName, text_scale=PiratesGuiGlobals.TextScaleLarge, text_align=TextNode.ACenter, text_fg=(0.9, 1, 0.9, 1), text_shadow=PiratesGuiGlobals.TextShadow, text_wordwrap=11, pos=(0.25, 0, 0.345), textMayChange=1) self.avocateMessage = DirectLabel(parent=self, relief=None, text=OTPLocalizer.GuildMemberGMMessage % avName, text_scale=PiratesGuiGlobals.TextScaleLarge, text_align=TextNode.ALeft, text_fg=(0.9, 1, 0.9, 1), text_shadow=PiratesGuiGlobals.TextShadow, text_wordwrap=11, pos=(0.05, 0, 0.345), textMayChange=1) self.avocateMessage.hide() if rank in (GUILDRANK_MEMBER, GUILDRANK_VETERAN): topButtonText = OTPLocalizer.GuildMemberPromote topButtonCommand = self.__handleMakeOfficer else: topButtonText = OTPLocalizer.GuildMemberDemoteInvite topButtonCommand = self.__handleMakeVeteran if rank in (GUILDRANK_OFFICER, GUILDRANK_VETERAN): bottomButtonText = OTPLocalizer.GuildMemberDemote bottomButtonCommand = self.__handleMakeMember else: bottomButtonText = OTPLocalizer.GuildMemberPromoteInvite bottomButtonCommand = self.__handleMakeVeteran self.bTopEditButton = GuildMemberButton(text=topButtonText, command=topButtonCommand) self.bTopEditButton.reparentTo(self) self.bTopEditButton.setPos(0.2, 0, 0.26) self.bBottomEditButton = GuildMemberButton(text=bottomButtonText, command=bottomButtonCommand) self.bBottomEditButton.reparentTo(self) self.bBottomEditButton.setPos(0.2, 0, 0.19) if self.canpromote: self.bTopEditButton.show() self.bBottomEditButton.show() else: self.bTopEditButton.hide() self.bBottomEditButton.hide() self.bKick = GuildMemberButton(text=OTPLocalizer.GuildMemberKick, command=self.__handleKick) self.bKick.reparentTo(self) self.bKick.setPos(0.2, 0, 0.12) if not self.cankick: self.bKick.hide() self.bCancel = GuildMemberButton(text=OTPLocalizer.GuildMemberCancel, command=self.__handleCancel) self.bCancel.reparentTo(self) self.bCancel.setPos(0.2, 0, -0.08) self.bAvocate = GuildMemberButton(text=OTPLocalizer.GuildMemberGM, command=self.__handleAvocatePopup) self.bAvocate.reparentTo(self) self.bAvocate.setPos(0.2, 0, 0.02) if localAvatar.getGuildRank() == GUILDRANK_GM: self.bAvocate.show() else: self.bAvocate.hide() self.bAvocateConfrim = GuildMemberButtonYesNo(text=OTPLocalizer.GuildMemberGMConfirm, command=self.__handleAvocate) self.bAvocateConfrim.reparentTo(self) self.bAvocateConfrim.setPos(0.05, 0, -0.08) self.bAvocateConfrim.hide() self.bAvocateCancel = GuildMemberButtonYesNo(text=OTPLocalizer.GuildMemberCancel, command=self.__handleAvocateCancel) self.bAvocateCancel.reparentTo(self) self.bAvocateCancel.setPos(0.35, 0, -0.08) self.bAvocateCancel.hide() self.accept('guildMemberUpdated', self.determineOptions) return def destroy(self): if hasattr(self, 'destroyed'): return self.destroyed = 1 self.ignoreAll() DirectFrame.destroy(self) def __handleMakeOfficer(self): base.cr.guildManager.changeRank(self.avId, GUILDRANK_OFFICER) def __handleMakeVeteran(self): base.cr.guildManager.changeRank(self.avId, GUILDRANK_VETERAN) def __handleMakeMember(self): base.cr.guildManager.changeRank(self.avId, GUILDRANK_MEMBER) def __handleKick(self): base.cr.guildManager.removeMember(self.avId) self.destroy() def __handleCancel(self): self.destroy() def __handleAvocatePopup(self): self.bTopEditButton.hide() self.bBottomEditButton.hide() self.bKick.hide() self.bCancel.hide() self.bAvocate.hide() self.bAvocateConfrim.show() self.bAvocateCancel.show() self.avocateMessage.show() self.message.hide() def __handleAvocateCancel(self): if self.canpromote: self.bTopEditButton.show() self.bBottomEditButton.show() else: self.bTopEditButton.hide() self.bBottomEditButton.hide() self.bKick.show() self.bCancel.show() if base.cr.guildManager.getRank(localAvatar.doId) == GUILDRANK_GM: self.bAvocate.show() else: self.bAvocate.hide() self.bAvocateConfrim.hide() self.bAvocateCancel.hide() self.avocateMessage.hide() self.message.show() def __handleAvocate(self): base.cr.guildManager.changeRankAvocate(self.avId) self.destroy() def determineOptions(self, avId): if avId != self.avId and avId != localAvatar.doId: return if not base.cr.guildManager.isInGuild(avId): self.destroy() return self.canpromote, self.candemote, self.cankick = base.cr.guildManager.getOptionsFor(avId) rank = base.cr.guildManager.getRank(self.avId) self.__handleAvocateCancel() if self.canpromote: if rank in (GUILDRANK_MEMBER, GUILDRANK_VETERAN): topButtonText = OTPLocalizer.GuildMemberPromote topButtonCommand = self.__handleMakeOfficer else: topButtonText = OTPLocalizer.GuildMemberDemoteInvite topButtonCommand = self.__handleMakeVeteran if rank in (GUILDRANK_OFFICER, GUILDRANK_VETERAN): bottomButtonText = OTPLocalizer.GuildMemberDemote bottomButtonCommand = self.__handleMakeMember else: bottomButtonText = OTPLocalizer.GuildMemberPromoteInvite bottomButtonCommand = self.__handleMakeVeteran self.bTopEditButton.configure(text=topButtonText, command=topButtonCommand) self.bBottomEditButton.configure(text=bottomButtonText, command=bottomButtonCommand) if self.canpromote: self.bTopEditButton.show() self.bBottomEditButton.show() else: self.bTopEditButton.hide() self.bBottomEditButton.hide() if self.cankick: self.bKick.show() else: self.bKick.hide()
412
0.792269
1
0.792269
game-dev
MEDIA
0.745837
game-dev
0.879272
1
0.879272
Dimbreath/AzurLaneData
8,779
zh-TW/model/proxy/settingsproxy.lua
slot0 = class("SettingsProxy", pm.Proxy) function slot0.onRegister(slot0) slot0._isBgmEnble = PlayerPrefs.GetInt("ShipSkinBGM", 1) > 0 slot0._ShowBg = PlayerPrefs.GetInt("disableBG", 1) > 0 slot0._ShowLive2d = PlayerPrefs.GetInt("disableLive2d", 1) > 0 slot0._selectedShipId = PlayerPrefs.GetInt("playerShipId") slot0._backyardFoodRemind = PlayerPrefs.GetString("backyardRemind") slot0._userAgreement = PlayerPrefs.GetInt("userAgreement", 0) > 0 slot0._showMaxLevelHelp = PlayerPrefs.GetInt("maxLevelHelp", 0) > 0 slot0.nextTipAoutBattleTime = PlayerPrefs.GetInt("AutoBattleTip", 0) slot0._setFlagShip = PlayerPrefs.GetInt("setFlagShip", 0) > 0 slot0._screenRatio = PlayerPrefs.GetFloat("SetScreenRatio", ADAPT_TARGET) NotchAdapt.CheckNotchRatio = slot0._screenRatio slot0.nextTipActBossExchangeTicket = nil slot0:resetEquipSceneIndex() slot0._isShowCollectionHelp = PlayerPrefs.GetInt("collection_Help", 0) > 0 slot0.lastRequestVersionTime = nil end function slot0.GetDockYardLockBtnFlag(slot0) if not slot0.dockYardLockFlag then slot0.dockYardLockFlag = PlayerPrefs.GetInt("DockYardLockFlag" .. getProxy(PlayerProxy):getRawData().id, 0) > 0 end return slot0.dockYardLockFlag end function slot0.SetDockYardLockBtnFlag(slot0, slot1) if slot0.dockYardLockFlag ~= slot1 then PlayerPrefs.SetInt("DockYardLockFlag" .. getProxy(PlayerProxy):getRawData().id, slot1 and 1 or 0) PlayerPrefs.Save() end end function slot0.GetDockYardLevelBtnFlag(slot0) if not slot0.dockYardLevelFlag then slot0.dockYardLevelFlag = PlayerPrefs.GetInt("DockYardLevelFlag" .. getProxy(PlayerProxy):getRawData().id, 0) > 0 end return slot0.dockYardLevelFlag end function slot0.SetDockYardLevelBtnFlag(slot0, slot1) if slot0.dockYardLevelFlag ~= slot1 then PlayerPrefs.SetInt("DockYardLevelFlag" .. getProxy(PlayerProxy):getRawData().id, slot1 and 1 or 0) PlayerPrefs.Save() end end function slot0.IsShowCollectionHelp(slot0) return slot0._isShowCollectionHelp end function slot0.SetCollectionHelpFlag(slot0, slot1) if slot0._isShowCollectionHelp ~= slot1 then slot0._isShowCollectionHelp = slot1 PlayerPrefs.SetInt("collection_Help", slot1 and 1 or 0) PlayerPrefs.Save() end end function slot0.IsBGMEnable(slot0) return slot0._isBgmEnble end function slot0.SetBgmFlag(slot0, slot1) if slot0._isBgmEnble ~= slot1 then slot0._isBgmEnble = slot1 PlayerPrefs.SetInt("ShipSkinBGM", slot1 and 1 or 0) PlayerPrefs.Save() end end function slot0.getSkinPosSetting(slot0, slot1) if PlayerPrefs.HasKey(tostring(slot1) .. "_scale") then return PlayerPrefs.GetFloat(tostring(slot1) .. "_x", 0), PlayerPrefs.GetFloat(tostring(slot1) .. "_y", 0), PlayerPrefs.GetFloat(tostring(slot1) .. "_scale", 1) else return nil end end function slot0.setSkinPosSetting(slot0, slot1, slot2, slot3, slot4) PlayerPrefs.SetFloat(tostring(slot1) .. "_x", slot2) PlayerPrefs.SetFloat(tostring(slot1) .. "_y", slot3) PlayerPrefs.SetFloat(tostring(slot1) .. "_scale", slot4) PlayerPrefs.Save() end function slot0.resetSkinPosSetting(slot0, slot1) PlayerPrefs.DeleteKey(tostring(slot1) .. "_x") PlayerPrefs.DeleteKey(tostring(slot1) .. "_y") PlayerPrefs.DeleteKey(tostring(slot1) .. "_scale") PlayerPrefs.Save() end function slot0.getCharacterSetting(slot0, slot1, slot2) return PlayerPrefs.GetInt(tostring(slot1) .. "_" .. slot2, 1) > 0 end function slot0.setCharacterSetting(slot0, slot1, slot2, slot3) PlayerPrefs.SetInt(tostring(slot1) .. "_" .. slot2, slot3 and 1 or 0) PlayerPrefs.Save() end function slot0.getCurrentSecretaryIndex(slot0) if PlayerPrefs.GetInt("currentSecretaryIndex", 1) > #getProxy(PlayerProxy):getData().characters then slot0:setCurrentSecretaryIndex(1) return 1 else return slot1 end end function slot0.rotateCurrentSecretaryIndex(slot0) if #getProxy(PlayerProxy):getData().characters < PlayerPrefs.GetInt("currentSecretaryIndex", 1) + 1 then slot1 = 1 end slot0:setCurrentSecretaryIndex(slot1) return slot1 end function slot0.setCurrentSecretaryIndex(slot0, slot1) PlayerPrefs.SetInt("currentSecretaryIndex", slot1) PlayerPrefs.Save() end function slot0.SetFlagShip(slot0, slot1) if slot0._setFlagShip ~= slot1 then slot0._setFlagShip = slot1 PlayerPrefs.SetInt("setFlagShip", slot1 and 1 or 0) PlayerPrefs.Save() end end function slot0.GetSetFlagShip(slot0) return slot0._setFlagShip end function slot0.getUserAgreement(slot0) return slot0._userAgreement end function slot0.setUserAgreement(slot0) if not slot0._userAgreement then PlayerPrefs.SetInt("userAgreement", 1) PlayerPrefs.Save() slot0._userAgreement = true end end function slot0.IsLive2dEnable(slot0) return slot0._ShowLive2d end function slot0.IsBGEnable(slot0) return slot0._ShowBg end function slot0.SetSelectedShipId(slot0, slot1) if slot0._selectedShipId ~= slot1 then slot0._selectedShipId = slot1 PlayerPrefs.SetInt("playerShipId", slot1) PlayerPrefs.Save() end end function slot0.GetSelectedShipId(slot0) return slot0._selectedShipId end function slot0.setEquipSceneIndex(slot0, slot1) slot0._equipSceneIndex = slot1 end function slot0.getEquipSceneIndex(slot0) return slot0._equipSceneIndex end function slot0.resetEquipSceneIndex(slot0) slot0._equipSceneIndex = StoreHouseConst.WARP_TO_MATERIAL end function slot0.setActivityLayerIndex(slot0, slot1) slot0._activityLayerIndex = slot1 end function slot0.getActivityLayerIndex(slot0) return slot0._activityLayerIndex end function slot0.resetActivityLayerIndex(slot0) slot0._activityLayerIndex = 1 end function slot0.setBackyardRemind(slot0) if slot0._backyardFoodRemind ~= tostring(GetZeroTime()) then PlayerPrefs.SetString("backyardRemind", slot1) PlayerPrefs.Save() slot0._backyardFoodRemind = slot1 end end function slot0.getBackyardRemind(slot0) if not slot0._backyardFoodRemind or slot0._backyardFoodRemind == "" then return 0 else return tonumber(slot0._backyardFoodRemind) end end function slot0.getMaxLevelHelp(slot0) return slot0._showMaxLevelHelp end function slot0.setMaxLevelHelp(slot0, slot1) if slot0._showMaxLevelHelp ~= slot1 then slot0._showMaxLevelHelp = slot1 PlayerPrefs.SetInt("maxLevelHelp", slot1 and 1 or 0) PlayerPrefs.Save() end end function slot0.setStopBuildSpeedupRemind(slot0) slot0.isStopBuildSpeedupReamind = true end function slot0.getStopBuildSpeedupRemind(slot0) return slot0.isStopBuildSpeedupReamind end function slot0.checkReadHelp(slot0, slot1) if not getProxy(PlayerProxy):getData() then return true end if slot1 == "help_backyard" then return true elseif pg.SeriesGuideMgr.GetInstance():isEnd() then slot4 = PlayerPrefs.GetInt(slot1, 0) return PlayerPrefs.GetInt(slot1, 0) > 0 end return true end function slot0.recordReadHelp(slot0, slot1) PlayerPrefs.SetInt(slot1, 1) PlayerPrefs.Save() end function slot0.clearAllReadHelp(slot0) PlayerPrefs.DeleteKey("tactics_lesson_system_introduce") PlayerPrefs.DeleteKey("help_shipinfo_equip") PlayerPrefs.DeleteKey("help_shipinfo_detail") PlayerPrefs.DeleteKey("help_shipinfo_intensify") PlayerPrefs.DeleteKey("help_shipinfo_upgrate") PlayerPrefs.DeleteKey("help_backyard") PlayerPrefs.DeleteKey("has_entered_class") PlayerPrefs.DeleteKey("help_commander_info") PlayerPrefs.DeleteKey("help_commander_play") PlayerPrefs.DeleteKey("help_commander_ability") end function slot0.setAoutBattleTip(slot0) slot1 = GetZeroTime() slot0.nextTipAoutBattleTime = slot1 PlayerPrefs.SetInt("AutoBattleTip", slot1) PlayerPrefs.Save() end function slot0.isTipAutoBattle(slot0) return slot0.nextTipAoutBattleTime < pg.TimeMgr.GetInstance():GetServerTime() end function slot0.setActBossExchangeTicketTip(slot0, slot1) slot0.nextTipActBossExchangeTicket = slot1 end function slot0.isTipActBossExchangeTicket(slot0) return slot0.nextTipActBossExchangeTicket end function slot0.SetScreenRatio(slot0, slot1) if slot0._screenRatio ~= slot1 then slot0._screenRatio = slot1 PlayerPrefs.SetFloat("SetScreenRatio", slot1) PlayerPrefs.Save() end end function slot0.GetScreenRatio(slot0) return slot0._screenRatio end function slot0.CheckLargeScreen(slot0) return Screen.width / Screen.height > 2 end function slot0.IsShowBeatMonseterNianCurtain(slot0) return tonumber(PlayerPrefs.GetString("HitMonsterNianLayer2020" .. getProxy(PlayerProxy):getRawData().id, "0")) < pg.TimeMgr.GetInstance():GetServerTime() end function slot0.SetBeatMonseterNianFlag(slot0) PlayerPrefs.SetString("HitMonsterNianLayer2020" .. getProxy(PlayerProxy):getRawData().id, GetZeroTime()) PlayerPrefs.Save() end function slot0.CheckNeedUserAgreement(slot0) if PLATFORM_CODE == PLATFORM_KR then return false elseif PLATFORM_CODE == PLATFORM_CH then return false end return true end return slot0
412
0.615037
1
0.615037
game-dev
MEDIA
0.895107
game-dev
0.87414
1
0.87414
cocos2d/cocos2d-x
2,894
tests/performance-tests/Classes/tests/PerformanceScenarioTest.h
/**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef __PERFORMANCE_SCENARIO_TEST_H__ #define __PERFORMANCE_SCENARIO_TEST_H__ #include "BaseTest.h" DEFINE_TEST_SUITE(PerformceScenarioTests); class ScenarioTest : public TestCase { public: CREATE_FUNC(ScenarioTest); virtual bool init() override; virtual std::string title() const override; virtual void performTests(); void onTouchesMoved(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* event) ; static cocos2d::Scene* scene(); virtual void onEnter() override; virtual void onExit() override; virtual void update(float dt) override; void beginStat(float dt); void endStat(float dt); void doAutoTest(); private: void addNewSprites(int num); void removeSprites(); void addParticles(int num); void removeParticles(); void addParticleSystem(int num); void removeParticleSystem(); private: static int _initParticleNum; static int _parStepNum; static int _initSpriteNum; static int _spriteStepNum; static int _initParsysNum; static int _parsysStepNum; cocos2d::TMXTiledMap* _map1; cocos2d::TMXTiledMap* _map2; cocos2d::MenuItemToggle* _itemToggle; cocos2d::Vector<cocos2d::Sprite*> _spriteArray; cocos2d::Vector<cocos2d::ParticleSystemQuad*> _parsysArray; cocos2d::Label* _spriteLabel; cocos2d::Label* _particleLabel; cocos2d::Label* _parsysLabel; int _particleNumber; bool isStating; int autoTestIndex; int statCount; float totalStatTime; float minFrameRate; float maxFrameRate; }; #endif
412
0.822908
1
0.822908
game-dev
MEDIA
0.587974
game-dev,graphics-rendering
0.512205
1
0.512205
glKarin/com.n0n3m4.diii4a
1,241
Q3E/src/main/jni/source/game/client/baseanimatedtextureproxy.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef BASEANIMATEDTEXTUREPROXY #define BASEANIMATEDTEXTUREPROXY #include "materialsystem/imaterialproxy.h" class IMaterial; class IMaterialVar; #pragma warning (disable : 4100) class CBaseAnimatedTextureProxy : public IMaterialProxy { public: CBaseAnimatedTextureProxy(); virtual ~CBaseAnimatedTextureProxy(); virtual bool Init( IMaterial *pMaterial, KeyValues *pKeyValues ); virtual void OnBind( void *pC_BaseEntity ); virtual void Release( void ) { delete this; } virtual IMaterial *GetMaterial(); protected: // derived classes must implement this; it returns the time // that the animation began virtual float GetAnimationStartTime( void* pBaseEntity ) = 0; // Derived classes may implement this if they choose; // this method is called whenever the animation wraps... virtual void AnimationWrapped( void* pBaseEntity ) {} protected: void Cleanup(); IMaterialVar *m_AnimatedTextureVar; IMaterialVar *m_AnimatedTextureFrameNumVar; float m_FrameRate; bool m_WrapAnimation; }; #endif // BASEANIMATEDTEXTUREPROXY
412
0.924837
1
0.924837
game-dev
MEDIA
0.554367
game-dev
0.58262
1
0.58262
mouredev/roadmap-retos-programacion
5,383
Roadmap/32 - BATALLA DEADPOOL Y WOLVERINE/java/Josegs95.java
import java.util.Random; import java.util.Scanner; public class Josegs95 { public static void main(String[] args) { new Josegs95().battleSim(); } private Superhero deadpool; private Superhero wolverine; final Scanner sc = new Scanner(System.in); private Random rnd = new Random(); public void battleSim(){ // System.out.println("---Opciones---"); // System.out.println("1. Empezar la batalla"); // System.out.println("2. Salir del programa"); try(sc){ // app: while(true){ // System.out.print("Introduzca la opción que desee: "); // String option = sc.nextLine().strip(); // switch (option){ // case "1": // initSuperheros(); // battle(); // break; // case "2": // System.out.println("Saliendo de la aplicación..."); // break; // default: // System.out.println("Opción inválida."); // } // } initSuperheros(); battle(); } } private void initSuperheros(){ deadpool = new Superhero("Deadpool", askSuperheroHp("Deadpool"), 10, 100, 25); wolverine = new Superhero("Wolverine", askSuperheroHp("Wolverine"), 10, 120, 20); } private void battle(){ Random rnd = new Random(); Superhero first; Superhero last; int turn = 1; while(true){ System.out.println(); System.out.println("Turno: " + turn++); System.out.println(deadpool); System.out.println(wolverine); if (rnd.nextBoolean()){ first = deadpool; last = wolverine; } else{ first = wolverine; last = deadpool; } if (attack(first, last) || attack(last, first)) break; try{ Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } private boolean attack(Superhero attacker, Superhero defender){ if (attacker.isStunned()){ System.out.println(attacker.getName() + " está regenerandose y no puede atacar"); attacker.setStunned(false); return false; } Integer damage = rnd.nextInt(attacker.getATK_MIN(), attacker.getATK_MAX() + 1); if (rnd.nextInt(100) <= defender.getEvasion()){ System.out.println(defender.getName() + " esquivó el ataque de " + attacker.getName()); return false; } System.out.println(attacker.getName() + " hizo " + damage + " puntos de " + "daño a " + defender.getName()); defender.takeDamage(damage); if (!defender.isAlive()){ System.out.println("\n" + attacker); System.out.println(defender); System.out.println("¡" + attacker.getName() + " es el ganador!"); return true; } if (damage == attacker.getATK_MAX()){ defender.setStunned(true); } return false; } private Integer askSuperheroHp(String name){ boolean validOption = false; Integer value = -1; while (!validOption){ System.out.print("Introduzca la vida inicial de " + name + ": "); String input = sc.nextLine(); try{ value = Integer.parseInt(input); validOption = true; } catch (NumberFormatException e){ System.out.println("Error. Introduzca un número entero por favor"); } } return value; } public class Superhero{ final private Integer HP_MAX; final private Integer ATK_MIN; final private Integer ATK_MAX; final private Integer EVASION; private String name; private Integer hp; private boolean stunned; public Superhero(String name, Integer hp, Integer atkMin, Integer atkMax, Integer evasion){ HP_MAX = hp; ATK_MIN = atkMin; ATK_MAX = atkMax; EVASION = evasion; this.name = name; this.hp = HP_MAX; stunned = false; } public void takeDamage(Integer damage){ if (damage > hp) hp = 0; else hp -= damage; } public String getName() { return name; } public Integer getHp() { return hp; } public Integer getEvasion() { return EVASION; } public Integer getATK_MIN() { return ATK_MIN; } public Integer getATK_MAX() { return ATK_MAX; } public boolean isStunned() { return stunned; } public void setStunned(boolean stunned) { this.stunned = stunned; } public boolean isAlive(){ return hp > 0; } @Override public String toString() { return name + "(" + hp + "/" + HP_MAX + ")"; } } }
412
0.826905
1
0.826905
game-dev
MEDIA
0.96111
game-dev
0.929208
1
0.929208
layabox/LayaAir-v1
7,951
plugins/debugtool/src/laya/debug/view/nodeInfo/NodeUtils.as
package laya.debug.view.nodeInfo { import laya.debug.tools.ClassTool; import laya.debug.tools.StringTool; import laya.debug.tools.WalkTools; import laya.debug.view.nodeInfo.views.ObjectInfoView; import laya.display.Graphics; import laya.display.Node; import laya.display.Sprite; import laya.maths.GrahamScan; import laya.maths.Point; import laya.maths.Rectangle; /** * ... * @author ww */ public class NodeUtils { public function NodeUtils() { } public static const defaultKeys:Array = ["x", "y", "width", "height"]; public static function getFilterdTree(sprite:Sprite, keys:Array):Object { if (!keys) keys = defaultKeys; var me:Object; me = {}; var key:String; var i:int, len:int; len = keys.length; for (i = 0; i < len; i++) { key = keys[i]; me[key] = sprite[key]; } var cList:Array; var tChild:Sprite; cList = sprite._childs; len = cList.length; var mClist:Array; mClist = []; for (i = 0; i < len; i++) { tChild = cList[i]; mClist.push(getFilterdTree(tChild, keys)); } me.childs = mClist; return me; } public static function getPropertyDesO(tValue:*, keys:Array):Object { if (!keys) keys = defaultKeys; var rst:Object = {}; if (tValue is Object) { rst.label = "" + ClassTool.getNodeClassAndName(tValue); } else { rst.label = "" + tValue; } rst.type = ""; rst.path = tValue; rst.childs = []; rst.isDirectory = false; var key:String; var i:int, len:int; var tChild:Object; if (tValue is Node) { rst.des = ClassTool.getNodeClassAndName(tValue); rst.isDirectory = true; len = keys.length; for (i = 0; i < len; i++) { key = keys[i]; tChild = getPropertyDesO(tValue[key], keys); if (tValue.hasOwnProperty(key)) { tChild.label = "" + key + ":" + tChild.des; } else { tChild.label = "" + key + ":" + ObjectInfoView.getNodeValue(tValue, key); } rst.childs.push(tChild); } key = "_childs"; tChild = getPropertyDesO(tValue[key], keys); tChild.label = "" + key + ":" + tChild.des; tChild.isChilds = true; rst.childs.push(tChild); } else if (tValue is Array) { rst.des = "Array[" + (tValue as Array).length + "]"; rst.isDirectory = true; var tList:Array; tList = tValue as Array; len = tList.length; for (i = 0; i < len; i++) { tChild = getPropertyDesO(tList[i], keys); tChild.label = "" + i + ":" + tChild.des; rst.childs.push(tChild); } } else if (tValue is Object) { rst.des = ClassTool.getNodeClassAndName(tValue); rst.isDirectory = true; for (key in tValue) { tChild = getPropertyDesO(tValue[key], keys); tChild.label = "" + key + ":" + tChild.des; rst.childs.push(tChild); } } else { rst.des = "" + tValue; } rst.hasChild = rst.childs.length > 0; return rst; } public static function adptShowKeys(keys:Array):Array { var i:int, len:int; len = keys.length; for (i = len - 1; i >= 0; i--) { keys[i] = StringTool.trimSide(keys[i]); if (keys[i].length < 1) { keys.splice(i, 1); } } return keys; } public static function getNodeTreeData(sprite:Sprite, keys:Array):Array { adptShowKeys(keys); var treeO:Object; treeO = getPropertyDesO(sprite, keys); //trace("treeO:", treeO); var treeArr:Array; treeArr = []; getTreeArr(treeO, treeArr); return treeArr; } public static function getTreeArr(treeO:Object, arr:Array, add:Boolean = true):void { if (add) arr.push(treeO); var tArr:Array = treeO.childs; var i:int, len:int = tArr.length; for (i = 0; i < len; i++) { if (!add) { tArr[i].nodeParent = null; } else { tArr[i].nodeParent = treeO; } if (tArr[i].isDirectory) { getTreeArr(tArr[i], arr); } else { arr.push(tArr[i]); } } } public static function traceStage():void { trace(getFilterdTree(Laya.stage, null)); trace("treeArr:", getNodeTreeData(Laya.stage, null)); } public static function getNodeCount(node:Sprite,visibleRequire:Boolean=false):int { if (visibleRequire) { if (!node.visible) return 0; } var rst:int; rst = 1; var i:int, len:int; var cList:Array; cList = node._childs; len = cList.length; for (i = 0; i < len; i++) { rst += getNodeCount(cList[i],visibleRequire); } return rst; } public static function getGVisible(node:Sprite):Boolean { while (node) { if (!node.visible) return false; node = node.parent as Sprite; } return true; } public static function getGAlpha(node:Sprite):Number { var rst:Number; rst = 1; while (node) { rst *= node.alpha; node = node.parent as Sprite; } return rst; } public static function getGPos(node:Sprite):Point { var point:Point; point=new Point(); node.localToGlobal(point); return point; } public static function getGRec(node:Sprite):Rectangle { var pointList:Array; pointList = node._getBoundPointsM(true); if (!pointList || pointList.length < 1) return Rectangle.TEMP.setTo(0,0,0,0); pointList = GrahamScan.pListToPointList(pointList, true); WalkTools.walkArr(pointList, node.localToGlobal, node); pointList = GrahamScan.pointListToPlist(pointList); var _disBoundRec:Rectangle; _disBoundRec = Rectangle._getWrapRec(pointList, _disBoundRec); return _disBoundRec; } public static function getGGraphicRec(node:Sprite):Rectangle { var pointList:Array; pointList = node.getGraphicBounds()._getBoundPoints(); if (!pointList || pointList.length < 1) return Rectangle.TEMP.setTo(0,0,0,0); pointList = GrahamScan.pListToPointList(pointList, true); WalkTools.walkArr(pointList, node.localToGlobal, node); pointList = GrahamScan.pointListToPlist(pointList); var _disBoundRec:Rectangle; _disBoundRec = Rectangle._getWrapRec(pointList, _disBoundRec); return _disBoundRec; } public static function getNodeCmdCount(node:Sprite):int { var rst:int; if (node.graphics) { if (node.graphics.cmds) { rst = node.graphics.cmds.length; } else { if (node.graphics._one) { rst = 1; } else { rst = 0; } } } else { rst = 0; } return rst; } public static function getNodeCmdTotalCount(node:Sprite):int { var rst:int; var i:int, len:int; var cList:Array; cList = node._childs; len = cList.length; rst = getNodeCmdCount(node); for (i = 0; i < len; i++) { rst += getNodeCmdTotalCount(cList[i]); } return rst; } public static function getRenderNodeCount(node:Sprite):int { if (node.cacheAs != "none") return 1; var rst:int; var i:int, len:int; var cList:Array; cList = node._childs; len = cList.length; rst = 1; for (i = 0; i < len; i++) { rst += getRenderNodeCount(cList[i]); } return rst; } public static function getReFreshRenderNodeCount(node:Sprite):int { var rst:int; var i:int, len:int; var cList:Array; cList = node._childs; len = cList.length; rst = 1; for (i = 0; i < len; i++) { rst += getRenderNodeCount(cList[i]); } return rst; } private static var g:Graphics; public static function showCachedSpriteRecs():void { g = DebugInfoLayer.I.graphicLayer.graphics; g.clear(); WalkTools.walkTarget(Laya.stage, drawCachedBounds, null); } private static function drawCachedBounds(sprite:Sprite):void { if (sprite.cacheAs == "none") return; if (DebugInfoLayer.I.isDebugItem(sprite)) return; var rec:Rectangle; rec = getGRec(sprite); g.drawRect(rec.x, rec.y, rec.width, rec.height, null, "#0000ff", 2); } } }
412
0.738056
1
0.738056
game-dev
MEDIA
0.447063
game-dev
0.865136
1
0.865136
mamontov-cpp/saddy-graphics-engine-2d
1,753
src/keymouseconditions.cpp
#include "keymouseconditions.h" bool sad::KeyHoldCondition::check(const sad::input::AbstractEvent & e) { const sad::input::KeyEvent & ke = static_cast<const sad::input::KeyEvent &>(e); return ke.Key == m_key; } void sad::KeyHoldCondition::setKey(sad::KeyboardKey key) { m_key = key; } sad::input::AbstractHandlerCondition * sad::KeyHoldCondition::clone() { return new sad::KeyHoldCondition(m_key); } sad::SpecialKeyHoldCondition::SpecialKeyHoldCondition(sad::SpecialKey key) : m_key(key) { } bool sad::SpecialKeyHoldCondition::check(const sad::input::AbstractEvent & e) { const sad::input::KeyEvent & ke = static_cast<const sad::input::KeyEvent &>(e); sad::input::KeyEvent & k = const_cast<sad::input::KeyEvent &>(ke); bool result = false; switch(m_key) { case sad::SpecialKey::HoldsControl: result = k.CtrlHeld; break; case sad::SpecialKey::HoldsAlt: result = k.AltHeld; break; case sad::SpecialKey::HoldsShift: result = k.ShiftHeld; break; } return result; } void sad::SpecialKeyHoldCondition::setKey(sad::SpecialKey key) { m_key = key; } sad::input::AbstractHandlerCondition* sad::SpecialKeyHoldCondition::clone() { sad::SpecialKeyHoldCondition* result = new sad::SpecialKeyHoldCondition(m_key); return result; } bool sad::MouseButtonHoldCondition::check(const sad::input::AbstractEvent & e) { const sad::input::MouseEvent & ke = static_cast<const sad::input::MouseEvent &>(e); return ke.Button == m_button; } void sad::MouseButtonHoldCondition::setButton(sad::MouseButton button) { m_button = button; } sad::input::AbstractHandlerCondition * sad::MouseButtonHoldCondition::clone() { return new sad::MouseButtonHoldCondition(m_button); }
412
0.813186
1
0.813186
game-dev
MEDIA
0.575889
game-dev,desktop-app
0.905671
1
0.905671
minecraft-dotnet/Substrate
1,086
SubstrateCS/Source/Entities/EntityBoat.cs
using System; using System.Collections.Generic; using System.Text; namespace Substrate.Entities { using Substrate.Nbt; public class EntityBoat : TypedEntity { public static readonly SchemaNodeCompound BoatSchema = TypedEntity.Schema.MergeInto(new SchemaNodeCompound("") { new SchemaNodeString("id", TypeId), }); public static string TypeId { get { return "Boat"; } } protected EntityBoat (string id) : base(id) { } public EntityBoat () : this(TypeId) { } public EntityBoat (TypedEntity e) : base(e) { } #region INBTObject<Entity> Members public override bool ValidateTree (TagNode tree) { return new NbtVerifier(tree, BoatSchema).Verify(); } #endregion #region ICopyable<Entity> Members public override TypedEntity Copy () { return new EntityBoat(this); } #endregion } }
412
0.782831
1
0.782831
game-dev
MEDIA
0.689631
game-dev
0.625758
1
0.625758
malaybaku/VMagicMirror
6,280
VMagicMirror/Assets/Baku/VMagicMirror/Scripts/MediaPipeTracker/AvatarControl/MediaPipeTrackerBodyOffset.cs
using DG.Tweening; using UnityEngine; using Zenject; using R3; namespace Baku.VMagicMirror.MediaPipeTracker { //TODO: ITickableに書き直せそう /// <summary> MediaPipeのトラッキング結果を体全体の位置オフセットとして反映するやつ </summary> /// <remarks> /// 実際にトラッキングしているのは頭部の姿勢 /// </remarks> public class MediaPipeTrackerBodyOffset : MonoBehaviour { private const float TrackingLostWaitTime = 0.5f; private const float TweenDuration = 0.5f; [Tooltip("受け取った値の適用スケール。割と小さい方がいいかも")] [SerializeField] private Vector3 applyScale = new(0.3f, 0.3f, 0.3f); //NOTE: 移動量もフレーバー程度ということで小さめに。 [SerializeField] private Vector3 applyMin = new(-0.05f, -0.05f, -0.02f); [SerializeField] private Vector3 applyMax = new(0.05f, 0.05f, 0.02f); //NOTE: この場合もxの比率は1.0にはせず、代わりに首回転にもとづく胴体の回転で並進が載るのに頼る [SerializeField] private Vector3 applyScaleWhenNoHandTrack = new(0.8f, 1f, 0.6f); [SerializeField] private Vector3 applyMinWhenNoHandTrack = new(-0.2f, -0.2f, -0.1f); [SerializeField] private Vector3 applyMaxWhenNoHandTrack = new(0.2f, 0.2f, 0.1f); [SerializeField] private float lerpFactor = 18f; [Tooltip("トラッキングロス時にゆっくり原点に戻すために使うLerpFactor")] [SerializeField] private float lerpFactorOnLost = 3f; [Tooltip("接続が持続しているあいだ、徐々にLerpFactorを引き上げるのに使う値")] [SerializeField] private float lerpFactorBlendDuration = 1f; [SerializeField] private bool useBiQuadFilter = true; [SerializeField] private float positionFilterCutOffFrequency = 2.5f; private FaceControlConfiguration _config; //private ExternalTrackerDataSource _externalTracker; private MediaPipeKinematicSetter _mediaPipeKinematicSetter; private CurrentFramerateChecker _framerateChecker; private readonly BiQuadFilterVector3 _positionFilter = new(); private Vector3 _scale = Vector3.zero; private Vector3 _min = Vector3.zero; private Vector3 _max = Vector3.zero; private Sequence _sequence = null; private float _currentLerpFactor; [Inject] public void Initialize( FaceControlConfiguration config, MediaPipeKinematicSetter mediaPipeKinematicSetter, CurrentFramerateChecker framerateChecker) { _config = config; _mediaPipeKinematicSetter = mediaPipeKinematicSetter; _framerateChecker = framerateChecker; _framerateChecker.CurrentFramerate .Subscribe(frameRate => _positionFilter.SetUpAsLowPassFilter(frameRate, positionFilterCutOffFrequency)) .AddTo(this); } public Vector3 BodyOffset { get; private set; } private bool _noHandTrackMode = false; public bool NoHandTrackMode { get => _noHandTrackMode; set { if (_noHandTrackMode == value) { return; } _noHandTrackMode = value; _sequence?.Kill(); _sequence = DOTween.Sequence() .Append(DOTween.To( () => _scale, v => _scale = v, value ? applyScaleWhenNoHandTrack : applyScale, TweenDuration )) .Join(DOTween.To( () => _min, v => _min = v, value ? applyMinWhenNoHandTrack : applyMin, TweenDuration )) .Join(DOTween.To( () => _max, v => _max = v, value ? applyMaxWhenNoHandTrack : applyMax, TweenDuration )); _sequence.Play(); } } private void Start() { //初期状態は手下げモードじゃないため、それ用のパラメータを入れておく _scale = applyScale; _min = applyMin; _max = applyMax; //lerpFactorは接続の信頼性に応じて上がっていく _currentLerpFactor = lerpFactorOnLost; } private void Update() { if (_config.HeadMotionControlModeValue != FaceControlModes.WebCamHighPower) { BodyOffset = Vector3.zero; _positionFilter.ResetValue(Vector3.zero); return; } var isHeadTracked = _mediaPipeKinematicSetter.TryGetHeadPose(out var headPose) || !_mediaPipeKinematicSetter.IsHeadPoseLostEnoughLong(); var offset = headPose.position; var goal = isHeadTracked ? new Vector3( Mathf.Clamp(offset.x * _scale.x, _min.x, _max.x), Mathf.Clamp(offset.y * _scale.y, _min.y, _max.y), Mathf.Clamp(offset.z * _scale.z, _min.z, _max.z) ) : Vector3.zero; if (useBiQuadFilter) { if (isHeadTracked) { BodyOffset = _positionFilter.Update(goal); } else { // ロス時に戻す動作はゆっくりにする BodyOffset = Vector3.Lerp(BodyOffset, goal, lerpFactorOnLost * Time.deltaTime); _positionFilter.ResetValue(goal); } } else { if (isHeadTracked) { var addedLerp = _currentLerpFactor + (lerpFactor - lerpFactorOnLost) * Time.deltaTime / lerpFactorBlendDuration; _currentLerpFactor = Mathf.Min(addedLerp, lerpFactor); } else { //ロスったら一番遅いとこまでリセットし、やり直してもらう _currentLerpFactor = lerpFactorOnLost; } BodyOffset = Vector3.Lerp(BodyOffset, goal, _currentLerpFactor * Time.deltaTime); } } } }
412
0.845886
1
0.845886
game-dev
MEDIA
0.678064
game-dev
0.619378
1
0.619378
kunitoki/yup
3,673
thirdparty/rive/include/rive/generated/shapes/paint/linear_gradient_base.hpp
#ifndef _RIVE_LINEAR_GRADIENT_BASE_HPP_ #define _RIVE_LINEAR_GRADIENT_BASE_HPP_ #include "rive/container_component.hpp" #include "rive/core/field_types/core_double_type.hpp" namespace rive { class LinearGradientBase : public ContainerComponent { protected: typedef ContainerComponent Super; public: static const uint16_t typeKey = 22; /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. bool isTypeOf(uint16_t typeKey) const override { switch (typeKey) { case LinearGradientBase::typeKey: case ContainerComponentBase::typeKey: case ComponentBase::typeKey: return true; default: return false; } } uint16_t coreType() const override { return typeKey; } static const uint16_t startXPropertyKey = 42; static const uint16_t startYPropertyKey = 33; static const uint16_t endXPropertyKey = 34; static const uint16_t endYPropertyKey = 35; static const uint16_t opacityPropertyKey = 46; protected: float m_StartX = 0.0f; float m_StartY = 0.0f; float m_EndX = 0.0f; float m_EndY = 0.0f; float m_Opacity = 1.0f; public: inline float startX() const { return m_StartX; } void startX(float value) { if (m_StartX == value) { return; } m_StartX = value; startXChanged(); } inline float startY() const { return m_StartY; } void startY(float value) { if (m_StartY == value) { return; } m_StartY = value; startYChanged(); } inline float endX() const { return m_EndX; } void endX(float value) { if (m_EndX == value) { return; } m_EndX = value; endXChanged(); } inline float endY() const { return m_EndY; } void endY(float value) { if (m_EndY == value) { return; } m_EndY = value; endYChanged(); } inline float opacity() const { return m_Opacity; } void opacity(float value) { if (m_Opacity == value) { return; } m_Opacity = value; opacityChanged(); } Core* clone() const override; void copy(const LinearGradientBase& object) { m_StartX = object.m_StartX; m_StartY = object.m_StartY; m_EndX = object.m_EndX; m_EndY = object.m_EndY; m_Opacity = object.m_Opacity; ContainerComponent::copy(object); } bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { switch (propertyKey) { case startXPropertyKey: m_StartX = CoreDoubleType::deserialize(reader); return true; case startYPropertyKey: m_StartY = CoreDoubleType::deserialize(reader); return true; case endXPropertyKey: m_EndX = CoreDoubleType::deserialize(reader); return true; case endYPropertyKey: m_EndY = CoreDoubleType::deserialize(reader); return true; case opacityPropertyKey: m_Opacity = CoreDoubleType::deserialize(reader); return true; } return ContainerComponent::deserialize(propertyKey, reader); } protected: virtual void startXChanged() {} virtual void startYChanged() {} virtual void endXChanged() {} virtual void endYChanged() {} virtual void opacityChanged() {} }; } // namespace rive #endif
412
0.872266
1
0.872266
game-dev
MEDIA
0.511459
game-dev,desktop-app
0.585507
1
0.585507
kettingpowered/Ketting-1-20-x
15,246
src/main/java/net/minecraftforge/common/TierSortingRegistry.java
/* * Copyright (c) Forge Development LLC and contributors * SPDX-License-Identifier: LGPL-2.1-only */ package net.minecraftforge.common; import com.google.common.collect.*; import com.google.common.graph.ElementOrder; import com.google.common.graph.GraphBuilder; import com.google.common.graph.MutableGraph; import com.google.gson.*; import it.unimi.dsi.fastutil.booleans.BooleanConsumer; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.packs.resources.PreparableReloadListener; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.SimplePreparableReloadListener; import net.minecraft.tags.BlockTags; import net.minecraft.tags.TagKey; import net.minecraft.util.GsonHelper; import net.minecraft.util.profiling.ProfilerFiller; import net.minecraft.world.item.DiggerItem; import net.minecraft.world.item.Tier; import net.minecraft.world.item.Tiers; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ClientPlayerNetworkEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.fml.loading.FMLEnvironment; import net.minecraftforge.fml.loading.toposort.TopologicalSort; import net.minecraftforge.network.NetworkDirection; import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.PacketDistributor; import net.minecraftforge.network.simple.SimpleChannel; import net.minecraftforge.server.ServerLifecycleHooks; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.util.*; import java.util.function.Supplier; import java.util.stream.Collectors; public class TierSortingRegistry { private static final Logger LOGGER = LogManager.getLogger(); private static final ResourceLocation ITEM_TIER_ORDERING_JSON = new ResourceLocation("forge", "item_tier_ordering.json"); /** * Registers a tier into the tier sorting registry. * @param tier The tier to register * @param name The name to use internally for dependency resolution * @param after List of tiers to place this tier after (the tiers in the list will be considered lesser tiers) * @param before List of tiers to place this tier before (the tiers in the list will be considered better tiers) */ public static synchronized Tier registerTier(Tier tier, ResourceLocation name, List<Object> after, List<Object> before) { if (tiers.containsKey(name)) throw new IllegalStateException("Duplicate tier name " + name); processTier(tier, name, after, before); hasCustomTiers = true; return tier; } /** * Returns the list of tiers in the order defined by the dependencies. * This list will remain valid * @return An unmodifiable list of tiers ordered lesser to greater */ public static List<Tier> getSortedTiers() { return sortedTiersUnmodifiable; } /** * Returns the tier associated with a name, if registered into the sorting system. * @param name The name to look up * @return The tier, or null if not registered */ @Nullable public static Tier byName(ResourceLocation name) { return tiers.get(name); } /** * Returns the name associated with a tier, if the tier is registered into the sorting system. * @param tier The tier to look up * @return The name for the tier, or null if not registered */ @Nullable public static ResourceLocation getName(Tier tier) { return tiers.inverse().get(tier); } /** * Queries if a tier should be evaluated using the sorting system, by calling isCorrectTierForDrops * @param tier The tier to query * @return True if isCorrectTierForDrops should be called for the tier */ public static boolean isTierSorted(Tier tier) { return getName(tier) != null; } /** * Queries if a tier is high enough to be able to get drops for the given blockstate. * @param tier The tier to look up * @param state The state to test against * @return True if the tier is good enough */ public static boolean isCorrectTierForDrops(Tier tier, BlockState state) { if (!isTierSorted(tier)) return isCorrectTierVanilla(tier, state); for (int x = sortedTiers.indexOf(tier) + 1; x < sortedTiers.size(); x++) { TagKey<Block> tag = sortedTiers.get(x).getTag(); if (tag != null && state.is(tag)) return false; } return true; } /** * Helper to query all tiers that are lower than the given tier * @param tier The tier * @return All the lower tiers */ public static List<Tier> getTiersLowerThan(Tier tier) { if (!isTierSorted(tier)) return List.of(); return sortedTiers.stream().takeWhile(t -> t != tier).toList(); } // ===================== PRIVATE INTERNAL STUFFS BELOW THIS LINE ===================== /** * Fallback for when a tier isn't in the registry, copy of the logic in {@link DiggerItem#isCorrectToolForDrops} */ private static boolean isCorrectTierVanilla(Tier tier, BlockState state) { int i = tier.getLevel(); if (i < 3 && state.is(BlockTags.NEEDS_DIAMOND_TOOL)) { return false; } else if (i < 2 && state.is(BlockTags.NEEDS_IRON_TOOL)) { return false; } else if (i < 1 && state.is(BlockTags.NEEDS_STONE_TOOL)) { return false; } return true; } private static void processTier(Tier tier, ResourceLocation name, List<Object> afters, List<Object> befores) { tiers.put(name, tier); for(Object after : afters) { ResourceLocation other = getTierName(after); edges.put(other, name); } for(Object before : befores) { ResourceLocation other = getTierName(before); edges.put(name, other); } } private static ResourceLocation getTierName(Object entry) { if (entry instanceof String s) return new ResourceLocation(s); if (entry instanceof ResourceLocation rl) return rl; if (entry instanceof Tier t) return Objects.requireNonNull(getName(t), "Can't have sorting dependencies for tiers not registered in the TierSortingRegistry"); throw new IllegalStateException("Invalid object type passed into the tier dependencies " + entry.getClass()); } private static boolean hasCustomTiers = false; private static final BiMap<ResourceLocation, Tier> tiers = HashBiMap.create(); private static final Multimap<ResourceLocation, ResourceLocation> edges = HashMultimap.create(); private static final Multimap<ResourceLocation, ResourceLocation> vanillaEdges = HashMultimap.create(); static { var wood = new ResourceLocation("wood"); var stone = new ResourceLocation("stone"); var iron = new ResourceLocation("iron"); var diamond = new ResourceLocation("diamond"); var netherite = new ResourceLocation("netherite"); var gold = new ResourceLocation("gold"); processTier(Tiers.WOOD, wood, List.of(), List.of()); processTier(Tiers.GOLD, gold, List.of(wood), List.of(stone)); processTier(Tiers.STONE, stone, List.of(wood), List.of(iron)); processTier(Tiers.IRON, iron, List.of(stone), List.of(diamond)); processTier(Tiers.DIAMOND, diamond, List.of(iron), List.of(netherite)); processTier(Tiers.NETHERITE, netherite, List.of(diamond), List.of()); vanillaEdges.putAll(edges); } private static final List<Tier> sortedTiers = new ArrayList<>(); private static final List<Tier> sortedTiersUnmodifiable = Collections.unmodifiableList(sortedTiers); private static final ResourceLocation CHANNEL_NAME = new ResourceLocation("forge:tier_sorting"); private static final String PROTOCOL_VERSION = "1.0"; private static final SimpleChannel SYNC_CHANNEL = NetworkRegistry.newSimpleChannel( CHANNEL_NAME, () -> "1.0", versionFromServer -> PROTOCOL_VERSION.equals(versionFromServer) || (allowVanilla() && NetworkRegistry.ACCEPTVANILLA.equals(versionFromServer)), versionFromClient -> PROTOCOL_VERSION.equals(versionFromClient) || (allowVanilla() && NetworkRegistry.ACCEPTVANILLA.equals(versionFromClient)) ); static boolean allowVanilla() { return !hasCustomTiers; } /*package private*/ static void init() { SYNC_CHANNEL.registerMessage(0, SyncPacket.class, SyncPacket::encode, TierSortingRegistry::receive, TierSortingRegistry::handle, Optional.of(NetworkDirection.PLAY_TO_CLIENT)); MinecraftForge.EVENT_BUS.addListener(TierSortingRegistry::playerLoggedIn); if (FMLEnvironment.dist == Dist.CLIENT) ClientEvents.init(); } /*package private*/ static PreparableReloadListener getReloadListener() { return new SimplePreparableReloadListener<JsonObject>() { final Gson gson = (new GsonBuilder()).create(); @NotNull @Override protected JsonObject prepare(@NotNull ResourceManager resourceManager, ProfilerFiller p) { Optional<Resource> res = resourceManager.getResource(ITEM_TIER_ORDERING_JSON); if (res.isEmpty()) return new JsonObject(); try (Reader reader = res.get().openAsReader()) { return gson.fromJson(reader, JsonObject.class); } catch (IOException e) { LOGGER.error("Could not read Tier sorting file " + ITEM_TIER_ORDERING_JSON, e); return new JsonObject(); } } @Override protected void apply(@NotNull JsonObject data, @NotNull ResourceManager resourceManager, ProfilerFiller p) { try { if (data.size() > 0) { JsonArray order = GsonHelper.getAsJsonArray(data, "order"); List<Tier> customOrder = new ArrayList<>(); for (JsonElement entry : order) { ResourceLocation id = new ResourceLocation(entry.getAsString()); Tier tier = byName(id); if (tier == null) throw new IllegalStateException("Tier not found with name " + id); customOrder.add(tier); } List<Tier> missingTiers = tiers.values().stream().filter(tier -> !customOrder.contains(tier)).toList(); if (missingTiers.size() > 0) throw new IllegalStateException("Tiers missing from the ordered list: " + missingTiers.stream().map(tier -> Objects.toString(TierSortingRegistry.getName(tier))).collect(Collectors.joining(", "))); setTierOrder(customOrder); return; } } catch(Exception e) { LOGGER.error("Error parsing Tier sorting file " + ITEM_TIER_ORDERING_JSON, e); } recalculateItemTiers(); } }; } @SuppressWarnings("UnstableApiUsage") private static void recalculateItemTiers() { final MutableGraph<Tier> graph = GraphBuilder.directed().nodeOrder(ElementOrder.<Tier>insertion()).build(); for(Tier tier : tiers.values()) { graph.addNode(tier); } edges.forEach((key, value) -> { if (tiers.containsKey(key) && tiers.containsKey(value)) graph.putEdge(tiers.get(key), tiers.get(value)); }); List<Tier> tierList = TopologicalSort.topologicalSort(graph, null); setTierOrder(tierList); } private static void setTierOrder(List<Tier> tierList) { runInServerThreadIfPossible(hasServer -> { sortedTiers.clear(); sortedTiers.addAll(tierList); if(hasServer) syncToAll(); }); } private static void runInServerThreadIfPossible(BooleanConsumer runnable) { MinecraftServer server = ServerLifecycleHooks.getCurrentServer(); if (server != null) server.execute(() -> runnable.accept(true)); else runnable.accept(false); } private static void syncToAll() { for(ServerPlayer serverPlayer : ServerLifecycleHooks.getCurrentServer().getPlayerList().getPlayers()) { syncToPlayer(serverPlayer); } } private static void playerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { if (event.getEntity() instanceof ServerPlayer serverPlayer) { syncToPlayer(serverPlayer); } } private static void syncToPlayer(ServerPlayer serverPlayer) { if (SYNC_CHANNEL.isRemotePresent(serverPlayer.connection.connection) && !serverPlayer.connection.connection.isMemoryConnection()) { SYNC_CHANNEL.send(PacketDistributor.PLAYER.with(() -> serverPlayer), new SyncPacket(sortedTiers.stream().map(TierSortingRegistry::getName).toList())); } } private static SyncPacket receive(FriendlyByteBuf buffer) { int count = buffer.readVarInt(); List<ResourceLocation> list = new ArrayList<>(); for(int i=0;i<count;i++) list.add(buffer.readResourceLocation()); return new SyncPacket(list); } private static void handle(SyncPacket packet, Supplier<NetworkEvent.Context> context) { setTierOrder(packet.tiers.stream().map(TierSortingRegistry::byName).toList()); context.get().setPacketHandled(true); } private record SyncPacket(List<ResourceLocation> tiers) { private void encode(FriendlyByteBuf buffer) { buffer.writeVarInt(tiers.size()); for(ResourceLocation loc : tiers) buffer.writeResourceLocation(loc); } } private static class ClientEvents { public static void init() { MinecraftForge.EVENT_BUS.addListener(ClientEvents::clientLogInToServer); } private static void clientLogInToServer(ClientPlayerNetworkEvent.LoggingIn event) { if (event.getConnection() == null || !event.getConnection().isMemoryConnection()) recalculateItemTiers(); } } }
412
0.903508
1
0.903508
game-dev
MEDIA
0.977529
game-dev
0.919884
1
0.919884
UCLA-VAST/AutoBridge
4,542
archive/benchmarks/Stencil/5PE/constraint_ref.tcl
puts "applying partitioning constraints generated by the Context Sensitive HLS Solver" write_checkpoint ./before_opt_design.dcp -force startgroup create_pblock pblock_X0_Y0 resize_pblock pblock_X0_Y0 -add CLOCKREGION_X0Y0:CLOCKREGION_X3Y3 endgroup startgroup create_pblock pblock_X1_Y0 resize_pblock pblock_X1_Y0 -add CLOCKREGION_X5Y0:CLOCKREGION_X6Y3 endgroup startgroup create_pblock pblock_X0_Y1 resize_pblock pblock_X0_Y1 -add CLOCKREGION_X0Y4:CLOCKREGION_X3Y7 endgroup startgroup create_pblock pblock_X1_Y1 resize_pblock pblock_X1_Y1 -add CLOCKREGION_X4Y4:CLOCKREGION_X6Y7 endgroup startgroup create_pblock pblock_X0_Y2 resize_pblock pblock_X0_Y2 -add CLOCKREGION_X0Y8:CLOCKREGION_X3Y11 endgroup startgroup create_pblock pblock_X1_Y2 resize_pblock pblock_X1_Y2 -add CLOCKREGION_X4Y8:CLOCKREGION_X6Y11 endgroup startgroup create_pblock pblock_X0_Y3 resize_pblock pblock_X0_Y3 -add CLOCKREGION_X0Y12:CLOCKREGION_X3Y15 endgroup startgroup create_pblock pblock_X1_Y3 resize_pblock pblock_X1_Y3 -add CLOCKREGION_X5Y12:CLOCKREGION_X6Y15 endgroup add_cells_to_pblock [get_pblocks pblock_X0_Y0] [get_cells -hierarchical -regexp { (.*/)?compute_0 (.*/)?load_0 }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X0_Y1] [get_cells -hierarchical -regexp { (.*/)?compute_1 }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X1_Y2] [get_cells -hierarchical -regexp { (.*/)?compute_2 }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X0_Y3] [get_cells -hierarchical -regexp { (.*/)?compute_4 (.*/)?store_0 }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X1_Y3] [get_cells -hierarchical -regexp { (.*/)?compute_3 }] -clear_locs add_cells_to_pblock [get_pblocks pblock_dynamic_SLR3] [get_cells -hierarchical -regexp { (.*/)?jacobi2d_kernel_control_s_axi_U }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X0_Y0] [get_cells -hierarchical -regexp { (.*/)?input_stream_0_0 (.*/)?input_stream_0_1 (.*/)?input_stream_0_2 (.*/)?input_stream_0_3 (.*/)?output_stream_0_0/inst.*0.*unit (.*/)?output_stream_0_1/inst.*0.*unit (.*/)?output_stream_0_2/inst.*0.*unit (.*/)?output_stream_0_3/inst.*0.*unit }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X0_Y1] [get_cells -hierarchical -regexp { (.*/)?output_stream_0_0/inst.*1.*unit (.*/)?output_stream_0_1/inst.*1.*unit (.*/)?output_stream_0_2/inst.*1.*unit (.*/)?output_stream_0_3/inst.*1.*unit (.*/)?output_stream_1_0/inst.*0.*unit (.*/)?output_stream_1_1/inst.*0.*unit (.*/)?output_stream_1_2/inst.*0.*unit (.*/)?output_stream_1_3/inst.*0.*unit }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X0_Y2] [get_cells -hierarchical -regexp { (.*/)?output_stream_1_0/inst.*1.*unit (.*/)?output_stream_1_0/inst.*2.*unit (.*/)?output_stream_1_1/inst.*1.*unit (.*/)?output_stream_1_1/inst.*2.*unit (.*/)?output_stream_1_2/inst.*1.*unit (.*/)?output_stream_1_2/inst.*2.*unit (.*/)?output_stream_1_3/inst.*1.*unit (.*/)?output_stream_1_3/inst.*2.*unit }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X1_Y2] [get_cells -hierarchical -regexp { (.*/)?output_stream_1_0/inst.*3.*unit (.*/)?output_stream_1_1/inst.*3.*unit (.*/)?output_stream_1_2/inst.*3.*unit (.*/)?output_stream_1_3/inst.*3.*unit (.*/)?output_stream_2_0/inst.*0.*unit (.*/)?output_stream_2_1/inst.*0.*unit (.*/)?output_stream_2_2/inst.*0.*unit (.*/)?output_stream_2_3/inst.*0.*unit }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X0_Y3] [get_cells -hierarchical -regexp { (.*/)?output_stream_4_0 (.*/)?output_stream_4_1 (.*/)?output_stream_4_2 (.*/)?output_stream_4_3 (.*/)?output_stream_3_0/inst.*1.*unit (.*/)?output_stream_3_1/inst.*1.*unit (.*/)?output_stream_3_2/inst.*1.*unit (.*/)?output_stream_3_3/inst.*1.*unit }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X1_Y3] [get_cells -hierarchical -regexp { (.*/)?output_stream_2_0/inst.*1.*unit (.*/)?output_stream_2_1/inst.*1.*unit (.*/)?output_stream_2_2/inst.*1.*unit (.*/)?output_stream_2_3/inst.*1.*unit (.*/)?output_stream_3_0/inst.*0.*unit (.*/)?output_stream_3_1/inst.*0.*unit (.*/)?output_stream_3_2/inst.*0.*unit (.*/)?output_stream_3_3/inst.*0.*unit }] -clear_locs delete_pblocks [get_pblocks pblock_X1_Y0] delete_pblocks [get_pblocks pblock_X1_Y1]
412
0.923733
1
0.923733
game-dev
MEDIA
0.307491
game-dev
0.934449
1
0.934449
Aussiemon/Darktide-Source-Code
49,816
dialogues/generated/mission_vo_cm_habs_remake.lua
-- chunkname: @dialogues/generated/mission_vo_cm_habs_remake.lua return function () define_rule({ category = "conversations_prio_0", database = "mission_vo_cm_habs_remake", name = "info_extraction_response", response = "info_extraction_response", wwise_route = 0, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "level_hab_block_collapse", }, }, }, on_done = {}, heard_speak_routing = { target = "players", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "conversations_prio_0", database = "mission_vo_cm_habs_remake", name = "level_hab_block_apartments", response = "level_hab_block_apartments", wwise_route = 0, criterias = { { "query_context", "concept", OP.EQ, "look_at", }, { "query_context", "look_at_tag", OP.EQ, "hab_block_apartment", }, { "query_context", "distance", OP.GT, 1, }, { "query_context", "distance", OP.LT, 17, }, { "user_context", "enemies_close", OP.LT, 50, }, { "faction_memory", "", OP.TIMEDIFF, OP.GT, 20, }, { "faction_memory", "level_hab_block_apartments", OP.EQ, 0, }, }, on_done = { { "faction_memory", "", OP.TIMESET, }, { "faction_memory", "level_hab_block_apartments", OP.ADD, 1, }, }, heard_speak_routing = { target = "players", }, }) define_rule({ category = "conversations_prio_1", database = "mission_vo_cm_habs_remake", name = "level_hab_block_apartments_response", response = "level_hab_block_apartments_response", wwise_route = 0, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "user_context", "friends_close", OP.GTEQ, 0, }, { "user_context", "enemies_close", OP.LT, 50, }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "level_hab_block_apartments", }, }, { "faction_memory", "level_hab_block_apartments_response", OP.TIMEDIFF, OP.GT, 60, }, }, on_done = { { "faction_memory", "level_hab_block_apartments_response", OP.TIMESET, }, }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "player_prio_0", database = "mission_vo_cm_habs_remake", name = "level_hab_block_collapse", response = "level_hab_block_collapse", wwise_route = 0, criterias = { { "query_context", "concept", OP.EQ, "generic_mission_vo", }, { "query_context", "trigger_id", OP.EQ, "level_hab_block_collapse", }, { "faction_memory", "level_hab_block_collapse", OP.EQ, 0, }, }, on_done = { { "faction_memory", "level_hab_block_collapse", OP.ADD, 1, }, }, heard_speak_routing = { target = "players", }, }) define_rule({ category = "conversations_prio_1", database = "mission_vo_cm_habs_remake", name = "level_hab_block_corpse", response = "level_hab_block_corpse", wwise_route = 0, criterias = { { "query_context", "concept", OP.EQ, "look_at", }, { "query_context", "look_at_tag", OP.EQ, "level_hab_block_corpse", }, { "query_context", "distance", OP.GT, 1, }, { "query_context", "distance", OP.LT, 17, }, { "user_context", "enemies_close", OP.LT, 50, }, { "faction_memory", "level_hab_block_corpse", OP.TIMEDIFF, OP.GT, 20, }, { "faction_memory", "level_hab_block_corpse", OP.EQ, 0, }, }, on_done = { { "faction_memory", "level_hab_block_corpse", OP.TIMESET, }, { "faction_memory", "level_hab_block_corpse", OP.ADD, 1, }, }, heard_speak_routing = { target = "mission_giver_default", }, }) define_rule({ category = "conversations_prio_1", database = "mission_vo_cm_habs_remake", name = "level_hab_block_security", response = "level_hab_block_security", wwise_route = 0, criterias = { { "query_context", "concept", OP.EQ, "look_at", }, { "query_context", "look_at_tag", OP.EQ, "level_hab_block_security", }, { "user_context", "threat_level", OP.EQ, "low", }, { "query_context", "distance", OP.GT, 1, }, { "query_context", "distance", OP.LT, 17, }, { "user_context", "enemies_close", OP.LT, 10, }, { "faction_memory", "level_hab_block_security_last_seen", OP.TIMEDIFF, OP.GT, 20, }, { "faction_memory", "level_hab_block_security", OP.EQ, 0, }, }, on_done = { { "faction_memory", "level_hab_block_security_last_seen", OP.TIMESET, }, { "faction_memory", "level_hab_block_security", OP.ADD, 1, }, }, heard_speak_routing = { target = "players", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_block_entrance_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_block_entrance_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_block_entrance_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", "enginseer", "enemy_wolfer_adjutant", }, }, { "faction_memory", "mission_habs_redux_block_entrance_a", OP.EQ, 0, }, }, on_done = { { "faction_memory", "mission_habs_redux_block_entrance_a", OP.ADD, 1, }, }, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_block_entrance_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_block_entrance_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_block_entrance_a", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "tertium_noble", "shipmistress", "enemy_nemesis_wolfer", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_block_entrance_c", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_block_entrance_c", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_block_entrance_b", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "boon_vendor", "enginseer", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_escape_conversation_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_escape_conversation_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_escape_conversation_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "tertium_noble", "shipmistress", "enemy_nemesis_wolfer", }, }, { "faction_memory", "mission_habs_redux_escape_conversation_a", OP.EQ, 0, }, }, on_done = { { "faction_memory", "mission_habs_redux_escape_conversation_a", OP.ADD, 1, }, }, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_escape_conversation_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_escape_conversation_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_escape_conversation_a", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "boon_vendor", "enginseer", "enemy_wolfer_adjutant", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_escape_conversation_c", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_escape_conversation_c", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_escape_conversation_b", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "tertium_noble", "shipmistress", "sergeant", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_escape_conversation_c_sergeant_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_escape_conversation_c_sergeant_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "sound_event", OP.SET_INCLUDES, args = { "loc_enemy_wolfer_adjutant_c__mission_habs_redux_escape_conversation_b_01", "loc_enemy_wolfer_adjutant_c__mission_habs_redux_escape_conversation_b_02", "loc_enemy_wolfer_adjutant_d__mission_habs_redux_escape_conversation_b_01", "loc_enemy_wolfer_adjutant_d__mission_habs_redux_escape_conversation_b_02", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", }, }, }, on_done = {}, heard_speak_routing = { target = "disabled", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_escape_conversation_d", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_escape_conversation_d", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_escape_conversation_c", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_first_scan_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_first_scan_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_first_scan_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", "shipmistress", }, }, { "faction_memory", "mission_habs_redux_first_scan_a", OP.EQ, 0, }, }, on_done = { { "faction_memory", "mission_habs_redux_first_scan_a", OP.ADD, 1, }, }, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_first_scan_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_first_scan_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_first_scan_a", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "enginseer", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_first_scan_complete_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_first_scan_complete_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_first_scan_complete_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "boon_vendor", "enginseer", "sergeant", }, }, { "faction_memory", "mission_habs_redux_first_scan_complete_a", OP.EQ, 0, }, }, on_done = { { "faction_memory", "mission_habs_redux_first_scan_complete_a", OP.ADD, 1, }, }, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_first_scan_complete_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_first_scan_complete_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_first_scan_complete_a", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", "shipmistress", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_first_scan_complete_b_sergeant_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_first_scan_complete_b_sergeant_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "sound_event", OP.SET_INCLUDES, args = { "loc_boon_vendor_a__mission_habs_redux_first_scan_complete_a_01", "loc_boon_vendor_a__mission_habs_redux_first_scan_complete_a_02", "loc_boon_vendor_a__mission_habs_redux_first_scan_complete_a_03", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", }, }, }, on_done = {}, heard_speak_routing = { target = "disabled", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_market_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_market_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_market_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "boon_vendor", "enginseer", "enemy_wolfer_adjutant", }, }, { "faction_memory", "mission_habs_redux_market_a", OP.EQ, 0, }, }, on_done = { { "faction_memory", "mission_habs_redux_market_a", OP.ADD, 1, }, }, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_market_approach_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_market_approach_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_market_approach_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "boon_vendor", "enginseer", "sergeant", }, }, { "faction_memory", "mission_habs_redux_market_approach_a", OP.EQ, 0, }, }, on_done = { { "faction_memory", "mission_habs_redux_market_approach_a", OP.ADD, 1, }, }, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_market_approach_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_market_approach_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_market_approach_a", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "tertium_noble", "shipmistress", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_market_approach_c", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_market_approach_c", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_market_approach_b", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", "enginseer", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_market_approach_c_sergeant_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_market_approach_c_sergeant_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "sound_event", OP.SET_INCLUDES, args = { "loc_tertium_noble_a__mission_habs_redux_market_approach_b_01", "loc_tertium_noble_a__mission_habs_redux_market_approach_b_02", "loc_tertium_noble_a__mission_habs_redux_market_approach_b_03", "loc_tertium_noble_b__mission_habs_redux_market_approach_b_01", "loc_tertium_noble_b__mission_habs_redux_market_approach_b_02", "loc_tertium_noble_b__mission_habs_redux_market_approach_b_03", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", }, }, }, on_done = {}, heard_speak_routing = { target = "disabled", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_market_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_market_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_market_a", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "tertium_noble", "shipmistress", "enemy_nemesis_wolfer", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_market_c", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_market_c", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_market_b", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "boon_vendor", "enginseer", "sergeant", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_market_c_sergeant_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_market_c_sergeant_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "sound_event", OP.SET_INCLUDES, args = { "loc_enemy_nemesis_wolfer_a__mission_habs_redux_market_b_01", "loc_enemy_nemesis_wolfer_a__mission_habs_redux_market_b_02", "loc_enemy_nemesis_wolfer_a__mission_habs_redux_market_b_03", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", }, }, }, on_done = {}, heard_speak_routing = { target = "disabled", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_neglect_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_neglect_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_neglect_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "tertium_noble", "shipmistress", "sergeant", }, }, { "faction_memory", "mission_habs_redux_neglect_a", OP.EQ, 0, }, }, on_done = { { "faction_memory", "mission_habs_redux_neglect_a", OP.ADD, 1, }, }, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_neglect_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_neglect_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_neglect_a", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "boon_vendor", "enginseer", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_neglect_c", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_neglect_c", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_neglect_b", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "shipmistress", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_poison_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_poison_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_poison_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "tertium_noble", "shipmistress", "sergeant", }, }, { "faction_memory", "mission_habs_redux_poison_a", OP.EQ, 0, }, }, on_done = { { "faction_memory", "mission_habs_redux_poison_a", OP.ADD, 1, }, }, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_poison_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_poison_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_poison_a", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "boon_vendor", "enginseer", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_poison_complete_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_poison_complete_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_poison_complete_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", "enginseer", }, }, { "faction_memory", "mission_habs_redux_poison_complete_a", OP.EQ, 0, }, }, on_done = { { "faction_memory", "mission_habs_redux_poison_complete_a", OP.ADD, 1, }, }, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_poison_complete_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_poison_complete_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_poison_complete_a", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "shipmistress", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_poison_jam_clear_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_poison_jam_clear_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_poison_jam_clear_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", "enginseer", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_poison_jammed_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_poison_jammed_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_poison_jammed_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", "enginseer", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_poison_survive_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_poison_survive_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_poison_survive_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", "enginseer", "enemy_nemesis_wolfer", }, }, { "faction_memory", "mission_habs_redux_poison_survive_a", OP.EQ, 0, }, }, on_done = { { "faction_memory", "mission_habs_redux_poison_survive_a", OP.ADD, 1, }, }, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_post_airlock_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_post_airlock_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_post_airlock_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", "enginseer", "enemy_nemesis_wolfer", }, }, { "faction_memory", "mission_habs_redux_post_airlock_a", OP.EQ, 0, }, }, on_done = { { "faction_memory", "mission_habs_redux_post_airlock_a", OP.ADD, 1, }, }, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_post_airlock_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_post_airlock_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_post_airlock_a", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "tertium_noble", "shipmistress", "enemy_wolfer_adjutant", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_post_airlock_c", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_post_airlock_c", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_post_airlock_b", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "enginseer", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_post_airlock_c_sergeant_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_post_airlock_c_sergeant_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "sound_event", OP.SET_INCLUDES, args = { "loc_enemy_wolfer_adjutant_c__mission_habs_redux_roof_airlock_b_01", "loc_enemy_wolfer_adjutant_c__mission_habs_redux_roof_airlock_b_02", "loc_enemy_wolfer_adjutant_d__mission_habs_redux_roof_airlock_b_01", "loc_enemy_wolfer_adjutant_d__mission_habs_redux_roof_airlock_b_02", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", }, }, }, on_done = {}, heard_speak_routing = { target = "disabled", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_quarantine_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_quarantine_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_quarantine_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", "shipmistress", }, }, { "faction_memory", "mission_habs_redux_quarantine_a", OP.EQ, 0, }, }, on_done = { { "faction_memory", "mission_habs_redux_quarantine_a", OP.ADD, 1, }, }, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_roof_airlock_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_roof_airlock_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_roof_airlock_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "tertium_noble", "shipmistress", "enemy_wolfer_adjutant", }, }, { "faction_memory", "mission_habs_redux_roof_airlock_a", OP.EQ, 0, }, }, on_done = { { "faction_memory", "mission_habs_redux_roof_airlock_a", OP.ADD, 1, }, }, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_roof_airlock_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_roof_airlock_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_roof_airlock_a", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "enginseer", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_roof_airlock_b_sergeant_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_roof_airlock_b_sergeant_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "sound_event", OP.SET_INCLUDES, args = { "loc_tertium_noble_a__mission_habs_redux_roof_airlock_a_01", "loc_tertium_noble_a__mission_habs_redux_roof_airlock_a_02", "loc_tertium_noble_a__mission_habs_redux_roof_airlock_a_03", "loc_tertium_noble_b__mission_habs_redux_roof_airlock_a_01", "loc_tertium_noble_b__mission_habs_redux_roof_airlock_a_02", "loc_tertium_noble_b__mission_habs_redux_roof_airlock_a_03", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", }, }, }, on_done = {}, heard_speak_routing = { target = "disabled", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_roof_airlock_b_sergeant_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_roof_airlock_b_sergeant_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "sound_event", OP.SET_INCLUDES, args = { "loc_enemy_wolfer_adjutant_c__mission_habs_redux_roof_airlock_a_01", "loc_enemy_wolfer_adjutant_c__mission_habs_redux_roof_airlock_a_02", "loc_enemy_wolfer_adjutant_d__mission_habs_redux_roof_airlock_a_01", "loc_enemy_wolfer_adjutant_d__mission_habs_redux_roof_airlock_a_02", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", }, }, }, on_done = {}, heard_speak_routing = { target = "disabled", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_roof_airlock_c", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_roof_airlock_c", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_roof_airlock_b", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "shipmistress", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_start_zone_a", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_start_zone_a", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "mission_info", }, { "query_context", "trigger_id", OP.EQ, "mission_habs_redux_start_zone_a", }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "tertium_noble", "enginseer", "enemy_wolfer_adjutant", }, }, { "faction_memory", "mission_habs_redux_start_zone_a", OP.EQ, 0, }, }, on_done = { { "faction_memory", "mission_habs_redux_start_zone_a", OP.ADD, 1, }, }, heard_speak_routing = { target = "mission_givers", }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_start_zone_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_start_zone_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_start_zone_a", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "boon_vendor", "shipmistress", "enemy_nemesis_wolfer", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_start_zone_c", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_start_zone_c", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_start_zone_b", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "tertium_noble", "enginseer", "sergeant", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_givers", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_start_zone_c_sergeant_b", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_start_zone_c_sergeant_b", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "sound_event", OP.SET_INCLUDES, args = { "loc_enemy_nemesis_wolfer_a__mission_habs_redux_start_zone_b_01", "loc_enemy_nemesis_wolfer_a__mission_habs_redux_start_zone_b_02", "loc_enemy_nemesis_wolfer_a__mission_habs_redux_start_zone_b_03", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", }, }, }, on_done = {}, heard_speak_routing = { target = "players", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_start_zone_d", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_start_zone_d", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_start_zone_c", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "boon_vendor", "shipmistress", }, }, }, on_done = {}, heard_speak_routing = { target = "all", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "vox_prio_0", concurrent_wwise_event = "play_vox_static_loop", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_start_zone_e", post_wwise_event = "play_radio_static_end", pre_wwise_event = "play_radio_static_start", response = "mission_habs_redux_start_zone_e", wwise_route = 1, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_start_zone_d", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "sergeant", }, }, }, on_done = {}, heard_speak_routing = { target = "players", }, on_pre_rule_execution = { delay_vo = { duration = 0.2, }, }, }) define_rule({ category = "conversations_prio_0", database = "mission_vo_cm_habs_remake", name = "mission_habs_redux_start_zone_response", response = "mission_habs_redux_start_zone_response", wwise_route = 0, criterias = { { "query_context", "concept", OP.EQ, "heard_speak", }, { "query_context", "dialogue_name", OP.SET_INCLUDES, args = { "mission_habs_redux_start_zone_c_sergeant_b", "mission_habs_redux_start_zone_d", "mission_habs_redux_start_zone_e", }, }, { "user_context", "class_name", OP.SET_INCLUDES, args = { "ogryn", "psyker", "veteran", "zealot", }, }, }, on_done = {}, heard_speak_routing = { target = "mission_giver_default_class", }, on_pre_rule_execution = { delay_vo = { duration = 0.3, }, }, }) end
412
0.909953
1
0.909953
game-dev
MEDIA
0.915114
game-dev
0.692621
1
0.692621
Sandrem/FlyCasual
1,845
Assets/Scripts/Model/Content/SecondEdition/Standard/Pilots/Empire/TIELnFighter/MaulerMithel.cs
using BoardTools; using Content; using System.Collections.Generic; using Upgrade; namespace Ship { namespace SecondEdition.TIELnFighter { public class MaulerMithel : TIELnFighter { public MaulerMithel() : base() { PilotInfo = new PilotCardInfo25 ( "\"Mauler\" Mithel", "Black Two", Faction.Imperial, 5, 3, 4, isLimited: true, abilityType: typeof(Abilities.SecondEdition.MaulerMithelAbility), extraUpgradeIcons: new List<UpgradeType> { UpgradeType.Talent, UpgradeType.Cannon }, tags: new List<Tags> { Tags.Tie }, seImageNumber: 80 ); } } } } namespace Abilities.SecondEdition { public class MaulerMithelAbility : GenericAbility { public override void ActivateAbility() { HostShip.AfterGotNumberOfAttackDice += MaulerMithelPilotAbility; } public override void DeactivateAbility() { HostShip.AfterGotNumberOfAttackDice -= MaulerMithelPilotAbility; } private void MaulerMithelPilotAbility(ref int result) { ShotInfo shotInformation = new ShotInfo(Combat.Attacker, Combat.Defender, Combat.ChosenWeapon); if (shotInformation.Range == 1) { Messages.ShowInfo(HostShip.PilotInfo.PilotName + " is within range 1 of his target, he rolls +1 attack die"); result++; } } } }
412
0.832776
1
0.832776
game-dev
MEDIA
0.934344
game-dev
0.622315
1
0.622315
plantuml/plantuml
2,990
src/main/java/net/sourceforge/plantuml/preproc/EvalBoolean.java
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2024, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * PlantUML 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. * * PlantUML 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * * Original Author: Arnaud Roques * * */ package net.sourceforge.plantuml.preproc; // http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form public class EvalBoolean { private final String str; private int pos = -1; private char ch; private final Truth truth; public EvalBoolean(String str, Truth truth) { this.str = str; this.truth = truth; } private void nextChar() { pos++; if (pos < str.length()) { ch = str.charAt(pos); } else { ch = '\0'; } } private boolean eat(char charToEat) { while (ch == ' ') { nextChar(); } if (ch == charToEat) { nextChar(); return true; } return false; } private boolean parseExpression() { boolean x = parseTerm(); while (true) { if (eat('|')) { eat('|'); x = x | parseTerm(); } else { return x; } } } private boolean parseTerm() { boolean x = parseFactor(); while (true) { if (eat('&')) { eat('&'); x = x & parseFactor(); } else { return x; } } } private boolean parseFactor() { if (eat('!')) { return !(parseFactor()); } final boolean x; final int startPos = pos; if (eat('(')) { x = parseExpression(); eat(')'); } else if (isIdentifier()) { while (isIdentifier()) { nextChar(); } final String func = str.substring(startPos, pos); x = truth.isTrue(func); } else { throw new IllegalArgumentException("Unexpected: " + (char) ch); } return x; } private boolean isIdentifier() { return ch == '_' || ch == '$' || Character.isLetterOrDigit(ch); } public boolean eval() { nextChar(); final boolean x = parseExpression(); if (pos < str.length()) { throw new IllegalArgumentException("Unexpected: " + (char) ch); } return x; } }
412
0.539395
1
0.539395
game-dev
MEDIA
0.52824
game-dev
0.833662
1
0.833662
Rz-C/Mohist
3,296
src/main/java/org/bukkit/craftbukkit/v1_20_R1/inventory/CraftMetaArmorStand.java
package org.bukkit.craftbukkit.v1_20_R1.inventory; import com.google.common.collect.ImmutableMap.Builder; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import java.util.Map; @DelegateDeserialization(CraftMetaItem.SerializableMeta.class) public class CraftMetaArmorStand extends CraftMetaItem { static final ItemMetaKey ENTITY_TAG = new ItemMetaKey("EntityTag", "entity-tag"); CompoundTag entityTag; CraftMetaArmorStand(CraftMetaItem meta) { super(meta); if (!(meta instanceof CraftMetaArmorStand)) { return; } CraftMetaArmorStand armorStand = (CraftMetaArmorStand) meta; this.entityTag = armorStand.entityTag; } CraftMetaArmorStand(CompoundTag tag) { super(tag); if (tag.contains(ENTITY_TAG.NBT)) { entityTag = tag.getCompound(ENTITY_TAG.NBT).copy(); } } CraftMetaArmorStand(Map<String, Object> map) { super(map); } @Override void deserializeInternal(CompoundTag tag, Object context) { super.deserializeInternal(tag, context); if (tag.contains(ENTITY_TAG.NBT)) { entityTag = tag.getCompound(ENTITY_TAG.NBT); } } @Override void serializeInternal(Map<String, Tag> internalTags) { if (entityTag != null && !entityTag.isEmpty()) { internalTags.put(ENTITY_TAG.NBT, entityTag); } } @Override void applyToItem(CompoundTag tag) { super.applyToItem(tag); if (entityTag != null) { tag.put(ENTITY_TAG.NBT, entityTag); } } @Override boolean applicableTo(Material type) { return type == Material.ARMOR_STAND; } @Override boolean isEmpty() { return super.isEmpty() && isArmorStandEmpty(); } boolean isArmorStandEmpty() { return !(entityTag != null); } @Override boolean equalsCommon(CraftMetaItem meta) { if (!super.equalsCommon(meta)) { return false; } if (meta instanceof CraftMetaArmorStand) { CraftMetaArmorStand that = (CraftMetaArmorStand) meta; return entityTag != null ? that.entityTag != null && this.entityTag.equals(that.entityTag) : entityTag == null; } return true; } @Override boolean notUncommon(CraftMetaItem meta) { return super.notUncommon(meta) && (meta instanceof CraftMetaArmorStand || isArmorStandEmpty()); } @Override int applyHash() { final int original; int hash = original = super.applyHash(); if (entityTag != null) { hash = 73 * hash + entityTag.hashCode(); } return original != hash ? CraftMetaArmorStand.class.hashCode() ^ hash : hash; } @Override Builder<String, Object> serialize(Builder<String, Object> builder) { super.serialize(builder); return builder; } @Override public CraftMetaArmorStand clone() { CraftMetaArmorStand clone = (CraftMetaArmorStand) super.clone(); if (entityTag != null) { clone.entityTag = entityTag.copy(); } return clone; } }
412
0.832737
1
0.832737
game-dev
MEDIA
0.991801
game-dev
0.847729
1
0.847729
HbmMods/Hbm-s-Nuclear-Tech-GIT
13,375
src/main/java/com/hbm/inventory/gui/GuiInfoContainer.java
package com.hbm.inventory.gui; import java.util.*; import codechicken.nei.VisiblityData; import codechicken.nei.api.INEIGuiHandler; import codechicken.nei.api.TaggedInventoryArea; import com.hbm.inventory.SlotPattern; import com.hbm.inventory.container.ContainerBase; import com.hbm.packet.PacketDispatcher; import com.hbm.packet.toserver.NBTControlPacket; import cpw.mods.fml.common.Optional; import net.minecraft.nbt.NBTTagCompound; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import com.hbm.items.ModItems; import com.hbm.items.machine.ItemMachineUpgrade.UpgradeType; import com.hbm.lib.RefStrings; import com.hbm.tileentity.IUpgradeInfoProvider; import com.hbm.util.BobMathUtil; import com.hbm.util.i18n.I18nUtil; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; @Optional.Interface(iface = "codechicken.nei.api.INEIGuiHandler", modid = "NotEnoughItems") public abstract class GuiInfoContainer extends GuiContainer implements INEIGuiHandler { static final ResourceLocation guiUtil = new ResourceLocation(RefStrings.MODID + ":textures/gui/gui_utility.png"); public GuiInfoContainer(Container p_i1072_1_) { super(p_i1072_1_); } public void drawElectricityInfo(GuiInfoContainer gui, int mouseX, int mouseY, int x, int y, int width, int height, long power, long maxPower) { if(x <= mouseX && x + width > mouseX && y < mouseY && y + height >= mouseY) gui.drawInfo(new String[] { BobMathUtil.getShortNumber(power) + "/" + BobMathUtil.getShortNumber(maxPower) + "HE" }, mouseX, mouseY); } public void drawCustomInfoStat(int mouseX, int mouseY, int x, int y, int width, int height, int tPosX, int tPosY, String... text) { drawCustomInfoStat(mouseX, mouseY, x, y, width, height, tPosX, tPosY, Arrays.asList(text)); } public void drawCustomInfoStat(int mouseX, int mouseY, int x, int y, int width, int height, int tPosX, int tPosY, List text) { if(x <= mouseX && x + width > mouseX && y < mouseY && y + height >= mouseY) this.func_146283_a(text, tPosX, tPosY); } public void drawInfo(String[] text, int x, int y) { this.func_146283_a(Arrays.asList(text), x, y); } /** Automatically grabs upgrade info out of the tile entity if it's a IUpgradeInfoProvider and crams the available info into a list for display. Automation, yeah! */ public List<String> getUpgradeInfo(TileEntity tile) { List<String> lines = new ArrayList(); if(tile instanceof IUpgradeInfoProvider) { IUpgradeInfoProvider provider = (IUpgradeInfoProvider) tile; lines.add(I18nUtil.resolveKey("upgrade.gui.title")); for(UpgradeType type : UpgradeType.values()) { if(provider.canProvideInfo(type, 0, false)) { int maxLevel = provider.getValidUpgrades().get(type); switch(type) { case SPEED: lines.add(I18nUtil.resolveKey("upgrade.gui.speed", maxLevel)); break; case POWER: lines.add(I18nUtil.resolveKey("upgrade.gui.power", maxLevel)); break; case EFFECT: lines.add(I18nUtil.resolveKey("upgrade.gui.effectiveness", maxLevel)); break; case AFTERBURN: lines.add(I18nUtil.resolveKey("upgrade.gui.afterburner", maxLevel)); break; case OVERDRIVE: lines.add(I18nUtil.resolveKey("upgrade.gui.overdrive", maxLevel)); break; default: break; } } } } return lines; } @Deprecated public void drawCustomInfo(GuiInfoContainer gui, int mouseX, int mouseY, int x, int y, int width, int height, String[] text) { if(x <= mouseX && x + width > mouseX && y < mouseY && y + height >= mouseY) this.func_146283_a(Arrays.asList(text), mouseX, mouseY); } public void drawInfoPanel(int x, int y, int width, int height, int type) { Minecraft.getMinecraft().getTextureManager().bindTexture(guiUtil); switch(type) { case 0: drawTexturedModalRect(x, y, 0, 0, 8, 8); break; //Small blue I case 1: drawTexturedModalRect(x, y, 0, 8, 8, 8); break; //Small green I case 2: drawTexturedModalRect(x, y, 8, 0, 16, 16); break; //Large blue I case 3: drawTexturedModalRect(x, y, 24, 0, 16, 16); break; //Large green I case 4: drawTexturedModalRect(x, y, 0, 16, 8, 8); break; //Small red ! case 5: drawTexturedModalRect(x, y, 0, 24, 8, 8); break; //Small yellow ! case 6: drawTexturedModalRect(x, y, 8, 16, 16, 16); break; //Large red ! case 7: drawTexturedModalRect(x, y, 24, 16, 16, 16); break; //Large yellow ! case 8: drawTexturedModalRect(x, y, 0, 32, 8, 8); break; //Small blue * case 9: drawTexturedModalRect(x, y, 0, 40, 8, 8); break; //Small grey * case 10: drawTexturedModalRect(x, y, 8, 32, 16, 16); break; //Large blue * case 11: drawTexturedModalRect(x, y, 24, 32, 16, 16); break; //Large grey * } } protected boolean isMouseOverSlot(Slot slot, int x, int y) { return this.func_146978_c(slot.xDisplayPosition, slot.yDisplayPosition, 16, 16, x, y); } //whoever made this private on the super deserves to eat a bowl of wasps public Slot getSlotAtPosition(int p_146975_1_, int p_146975_2_) { for (int k = 0; k < this.inventorySlots.inventorySlots.size(); ++k) { Slot slot = (Slot)this.inventorySlots.inventorySlots.get(k); if (this.isMouseOverSlot(slot, p_146975_1_, p_146975_2_)) { return slot; } } return null; } protected boolean checkClick(int x, int y, int left, int top, int sizeX, int sizeY) { return guiLeft + left <= x && guiLeft + left + sizeX > x && guiTop + top < y && guiTop + top + sizeY >= y; } /* Getters for external use of the GUI's rect rendering, such as NumberDisplay */ public int getGuiTop() { return this.guiTop; } public int getGuiLeft() { return this.guiLeft; } public float getZLevel() { return this.zLevel; } public void setZLevel(float level) { this.zLevel = level; } public RenderItem getItemRenderer() { return this.itemRender; } public FontRenderer getFontRenderer() { return this.fontRendererObj; } /** Draws item with label, excludes all the GL state setup */ protected void drawItemStack(ItemStack stack, int x, int y, String label) { GL11.glTranslatef(0.0F, 0.0F, 32.0F); this.zLevel = 200.0F; itemRender.zLevel = 200.0F; FontRenderer font = null; if(stack != null) font = stack.getItem().getFontRenderer(stack); if(font == null) font = fontRendererObj; itemRender.renderItemAndEffectIntoGUI(font, this.mc.getTextureManager(), stack, x, y); itemRender.renderItemOverlayIntoGUI(font, this.mc.getTextureManager(), stack, x, y, label); this.zLevel = 0.0F; itemRender.zLevel = 0.0F; } public static final ItemStack TEMPLATE_FOLDER = new ItemStack(ModItems.template_folder); /** Standardsized item rendering from GUIScreenRecipeSelector */ public void renderItem(ItemStack stack, int x, int y) { renderItem(stack, x, y, 100F); } public void renderItem(ItemStack stack, int x, int y, float layer) { FontRenderer font = stack.getItem().getFontRenderer(stack); if(font == null) font = fontRendererObj; GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); RenderHelper.enableGUIStandardItemLighting(); OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) 240 / 1.0F, (float) 240 / 1.0F); GL11.glEnable(GL12.GL_RESCALE_NORMAL); itemRender.zLevel = layer; itemRender.renderItemAndEffectIntoGUI(font, this.mc.getTextureManager(), stack, guiLeft + x, guiTop + y); itemRender.zLevel = 0.0F; GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glDisable(GL11.GL_LIGHTING); } protected void drawStackText(List lines, int x, int y, FontRenderer font) { if(!lines.isEmpty()) { GL11.glDisable(GL12.GL_RESCALE_NORMAL); RenderHelper.disableStandardItemLighting(); GL11.glDisable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_DEPTH_TEST); int height = 0; int longestline = 0; Iterator iterator = lines.iterator(); while(iterator.hasNext()) { Object[] line = (Object[]) iterator.next(); int lineWidth = 0; boolean hasStack = false; for(Object o : line) { if(o instanceof String) { lineWidth += font.getStringWidth((String) o); } else { lineWidth += 18; hasStack = true; } } if(hasStack) { height += 18; } else { height += 10; } if(lineWidth > longestline) { longestline = lineWidth; } } int minX = x + 12; int minY = y - 12; if(minX + longestline > this.width) { minX -= 28 + longestline; } if(minY + height + 6 > this.height) { minY = this.height - height - 6; } this.zLevel = 400.0F; itemRender.zLevel = 400.0F; //int j1 = -267386864; int colorBg = 0xF0100010; this.drawGradientRect(minX - 3, minY - 4, minX + longestline + 3, minY - 3, colorBg, colorBg); this.drawGradientRect(minX - 3, minY + height + 3, minX + longestline + 3, minY + height + 4, colorBg, colorBg); this.drawGradientRect(minX - 3, minY - 3, minX + longestline + 3, minY + height + 3, colorBg, colorBg); this.drawGradientRect(minX - 4, minY - 3, minX - 3, minY + height + 3, colorBg, colorBg); this.drawGradientRect(minX + longestline + 3, minY - 3, minX + longestline + 4, minY + height + 3, colorBg, colorBg); //int k1 = 1347420415; int color0 = 0x505000FF; //int l1 = (k1 & 16711422) >> 1 | k1 & -16777216; int color1 = (color0 & 0xFEFEFE) >> 1 | color0 & 0xFF000000; this.drawGradientRect(minX - 3, minY - 3 + 1, minX - 3 + 1, minY + height + 3 - 1, color0, color1); this.drawGradientRect(minX + longestline + 2, minY - 3 + 1, minX + longestline + 3, minY + height + 3 - 1, color0, color1); this.drawGradientRect(minX - 3, minY - 3, minX + longestline + 3, minY - 3 + 1, color0, color0); this.drawGradientRect(minX - 3, minY + height + 2, minX + longestline + 3, minY + height + 3, color1, color1); for(int index = 0; index < lines.size(); ++index) { Object[] line = (Object[]) lines.get(index); int indent = 0; boolean hasStack = false; for(Object o : line) { if(!(o instanceof String)) { hasStack = true; } } for(Object o : line) { if(o instanceof String) { font.drawStringWithShadow((String) o, minX + indent, minY + (hasStack ? 4 : 0), -1); indent += font.getStringWidth((String) o) + 2; } else { ItemStack stack = (ItemStack) o; GL11.glColor3f(1F, 1F, 1F); if(stack.stackSize == 0) { this.drawGradientRect(minX + indent - 1, minY - 1, minX + indent + 17, minY + 17, 0xffff0000, 0xffff0000); this.drawGradientRect(minX + indent, minY, minX + indent + 16, minY + 16, 0xffb0b0b0, 0xffb0b0b0); } GL11.glEnable(GL11.GL_DEPTH_TEST); RenderHelper.enableGUIStandardItemLighting(); GL11.glEnable(GL12.GL_RESCALE_NORMAL); itemRender.renderItemAndEffectIntoGUI(this.fontRendererObj, this.mc.getTextureManager(), stack, minX + indent, minY); itemRender.renderItemOverlayIntoGUI(this.fontRendererObj, this.mc.getTextureManager(), stack, minX + indent, minY, null); RenderHelper.disableStandardItemLighting(); GL11.glDisable(GL11.GL_DEPTH_TEST); indent += 18; } } if(index == 0) { minY += 2; } minY += hasStack ? 18 : 10; } this.zLevel = 0.0F; itemRender.zLevel = 0.0F; GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_DEPTH_TEST); RenderHelper.enableStandardItemLighting(); GL11.glEnable(GL12.GL_RESCALE_NORMAL); } } public void click() { mc.getSoundHandler().playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F)); } ///NEI drag and drop support @Override @Optional.Method(modid = "NotEnoughItems") public boolean handleDragNDrop(GuiContainer gui, int x, int y, ItemStack stack, int button) { if(gui instanceof GuiInfoContainer && stack != null){ Slot slot = getSlotAtPosition(x,y); if(slot instanceof SlotPattern){ if(inventorySlots instanceof ContainerBase) { NBTTagCompound tag = new NBTTagCompound(); tag.setInteger("slot", slot.slotNumber); NBTTagCompound item = new NBTTagCompound(); stack.writeToNBT(item); tag.setTag("stack", item); TileEntity te = (TileEntity) ((ContainerBase) inventorySlots).tile; PacketDispatcher.wrapper.sendToServer(new NBTControlPacket(tag, te.xCoord, te.yCoord, te.zCoord)); return true; } } } return false; } //all credits for impl to GTNH's EnderCore fork @Override @Optional.Method(modid = "NotEnoughItems") public boolean hideItemPanelSlot(GuiContainer gc, int x, int y, int w, int h) { return false; } @Override @Optional.Method(modid = "NotEnoughItems") public VisiblityData modifyVisiblity(GuiContainer gc, VisiblityData vd) { return vd; } @Override @Optional.Method(modid = "NotEnoughItems") public Iterable<Integer> getItemSpawnSlots(GuiContainer gc, ItemStack is) { return null; } @Override @Optional.Method(modid = "NotEnoughItems") public List<TaggedInventoryArea> getInventoryAreas(GuiContainer gc) { return Collections.emptyList(); } }
412
0.918249
1
0.918249
game-dev
MEDIA
0.667914
game-dev,graphics-rendering
0.969046
1
0.969046
CalamityTeam/CalamityModPublic
4,187
UI/DebuffSystem/BestiaryDebuffInfo.cs
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.GameContent.Bestiary; using Terraria.GameContent.UI.Elements; using Terraria.Localization; using Terraria.ModLoader; using Terraria.UI; namespace CalamityMod.UI.DebuffSystem { public class BestiaryDebuffInfo : IBestiaryInfoElement { public string[] elements; public BestiaryDebuffInfo(string[] elements) { this.elements = elements; } public UIElement ProvideUIElement(BestiaryUICollectionInfo info) { // Don't show debuff info until stats are unlocked if (info.UnlockState < BestiaryEntryUnlockState.CanShowStats_2) { return null; } // The main background panel UIPanel backgroundPanel = new UIPanel(Main.Assets.Request<Texture2D>("Images/UI/Bestiary/Stat_Panel"), null, 12, 7) { Width = new StyleDimension(-11f, 1f), Height = new StyleDimension(180f, 0f), BackgroundColor = new Color(43, 56, 101), BorderColor = Color.Transparent, Left = new StyleDimension(2.5f, 0f), PaddingLeft = 4f, PaddingRight = 4f }; // The title of the panel UIText titleText = new UIText(CalamityUtils.GetTextValue("UI.DebuffSystem.Title"), 1f) { HAlign = 0f, VAlign = 0f, Width = StyleDimension.FromPixelsAndPercent(0f, 1f), Height = StyleDimension.FromPixelsAndPercent(0f, 1f), IsWrapped = true }; backgroundPanel.Append(titleText); // Add all five elements to the panel, each one below the previous for (int i = 0; i < 5; i++) { string path = "CalamityMod/UI/DebuffSystem/"; switch (i) { case 0: path += "Heat"; break; case 1: path += "Sickness"; break; case 2: path += "Cold"; break; case 3: path += "Electricity"; break; case 4: path += "Water"; break; } path += "DebuffType"; float topPos = 0.2f + i * 0.175f; // Icon UIImage elementImage = new UIImage(ModContent.Request<Texture2D>(path)) { HAlign = 0f, VAlign = 0f, Width = StyleDimension.FromPixelsAndPercent(0f, 1f), Height = StyleDimension.FromPixelsAndPercent(0f, 1f), Top = new StyleDimension(0f, topPos - 0.0525f), Left = new StyleDimension(8f, 0f), ImageScale = 0.8f, }; backgroundPanel.Append(elementImage); // Text UIText elementText = new UIText(Language.GetText(elements[i]), 0.8f) { HAlign = 0f, VAlign = 0f, Width = StyleDimension.FromPixelsAndPercent(0f, 1f), Height = StyleDimension.FromPixelsAndPercent(0f, 1f), Top = new StyleDimension(0f, topPos), Left = new StyleDimension(0f, 0.05f), }; backgroundPanel.Append(elementText); } // Summarize the debuff resistance system when hovering over the panel backgroundPanel.OnUpdate += ElementDescription; return backgroundPanel; } public static void ElementDescription(UIElement uelement) { if (uelement.IsMouseHovering) { Main.instance.MouseText(CalamityUtils.GetTextValue("UI.DebuffSystem.Description"), 0, 0); } } } }
412
0.718027
1
0.718027
game-dev
MEDIA
0.925615
game-dev
0.771327
1
0.771327
ProjectEQ/projecteqquests
4,794
snlair/Alej_Leraji.lua
-- items: 68298 local turned_in_seal = false local tool_count = 0 local function update_flag(client) local sewers_flag = tonumber(eq.get_data(client:CharacterID() .. "-god_sewers")) or 0 local snlair_key = string.format("%s-god_snlair", client:CharacterID()) if sewers_flag < 3 then eq.set_data(snlair_key, "T") client:Message(MT.Yellow, "You have gained a temporary character flag! Seek the High Priest's Scribe to find out more information.") else eq.set_data(snlair_key, "1") client:Message(MT.Yellow, "You have gained a character flag! All of High Priest Diru's tasks have been completed. He will now tell you who to talk to for passage through the mountains.") end end function event_spawn(e) e.self:SetSpecialAbility(SpecialAbility.immune_melee, 1) e.self:SetSpecialAbility(SpecialAbility.immune_magic, 1) e.self:SetSpecialAbility(SpecialAbility.immune_aggro, 1) e.self:SetSpecialAbility(SpecialAbility.immune_aggro_on, 1) e.self:SetSpecialAbility(SpecialAbility.no_harm_from_client, 1) eq.set_timer("appearance", 1000) eq.spawn_condition("snlair", eq.get_zone_instance_id(), 1, 1) -- default mobs inside tool rooms end function event_say(e) if e.message:findi("hail") then if not turned_in_seal then eq.get_entity_list():MessageClose(e.self, true, 100, MT.SayEcho, "Alej Leraji in a raspy, tired voice says, 'Who are you? What are you doing here?'") else eq.get_entity_list():MessageClose(e.self, true, 100, MT.SayEcho, "Alej Leraji says, 'Please hurry and [" .. eq.say_link("find my three stone shaping tools") .. "], there isn't time to waste!'") end elseif e.message:findi("found(.*)stone shaping tool") then if tool_count == 0 then eq.get_entity_list():MessageClose(e.self, true, 100, MT.SayEcho, "Alej Leraji says, 'I don't see any tools. Please acquire my three tools so I can escape this collapsed prison!'") elseif tool_count == 1 then eq.get_entity_list():MessageClose(e.self, true, 100, MT.SayEcho, "Alej Leraji says, 'You are missing two of my tools. Please acquire them so I can escape this stony bastille!'") elseif tool_count == 2 then eq.get_entity_list():MessageClose(e.self, true, 100, MT.SayEcho, "Alej Leraji says, 'You only need one more tool. Please acquire it before there is no time left!'") elseif tool_count == 3 then eq.get_entity_list():MessageClose(e.self, true, 100, MT.SayEcho, "Alej Leraji uses his stone shaping tools to lessen the grasp the stone prison had on his body. In an extremely hasty motion he leaps from under the rocks. Alej Leraji tells you, 'Thank you for helping me out of this situation. For a while I thought I was going to be joining the rest of the spirits here an in eternal slumber, but that is not the case now. Thank you! .' A burst of light flashes before your eyes and Alej disappears.") local client_list = eq.get_entity_list():GetClientList() for client in client_list.entries do if client.valid then update_flag(client) end end eq.depop() end end end function event_timer(e) if e.timer == "appearance" then eq.stop_timer("appearance") e.self:SetAppearance(3) elseif e.timer == "fail_warn" then eq.zone_emote(MT.Red, "Alej Leraji shouts, 'Please hurry, I do not know how much longer I can hold on underneath these rocks!'") eq.stop_timer("fail_warn") eq.set_timer("fail_event", 10 * 60 * 1000) -- 10 minutes elseif e.timer == "fail_event" then eq.zone_emote(MT.Red, "With his very last breath Alej shouts, 'My time is up, I'm beginning to feel my life wither. Thank you for trying friends, if only there was more time.'") eq.stop_timer("fail_event") eq.depop() end end function event_trade(e) local item_lib = require("items") if item_lib.check_turn_in(e.trade, {item1 = 68298}) then -- Item: Seal of the Nihil High Priest turned_in_seal = true eq.get_entity_list():MessageClose(e.self, true, 100, MT.SayEcho, "Alej Leraji looks at the clay seal and with a tired breath says, 'I see you have the seal, you are trustworthy. I need your help, for I don't know if I can survive much longer. I will need my stone shaping tools to get me out of this rocky prison. Please tell me when you [" .. eq.say_link("find my three stone shaping tools") .. "] and make haste! I left them in the water wheel room, the cocoon room, and the entrance to this section of the sewers. I have little time left.'") eq.spawn2(286104, 0, 0, 10, 10, 10, 0) -- NPC: #lair_trigger (spawns event tool room mobs) eq.set_timer("fail_warn", 50 * 60 * 1000) -- 50 minutes end item_lib.return_items(e.self, e.other, e.trade) end function event_signal(e) if e.signal == 1 then tool_count = tool_count + 1 end end
412
0.96625
1
0.96625
game-dev
MEDIA
0.934112
game-dev
0.967787
1
0.967787
eliheuer/bezy
2,608
src/geometry/point.rs
//! Point and entity management for glyph editing //! //! This module provides the core structures for working with individual points //! and entities within a glyph's outline. use crate::core::state::font_data::PointTypeData; use bevy::prelude::*; use kurbo::Point; /// A point in a glyph's outline that can be edited #[derive(Component, Debug, Clone, PartialEq)] pub struct EditPoint { pub position: Point, // Position in glyph coordinate space pub point_type: PointTypeData, // Point type (move, line, curve, etc.) } impl EditPoint { /// Creates a new editable point #[allow(dead_code)] pub fn new(position: Point, point_type: PointTypeData) -> Self { Self { position, point_type, } } } /// Unique identifier for entities in a glyph (points, guides, components) #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect)] pub struct EntityId { parent: u32, // The parent path or component ID index: u16, // The index within the parent kind: EntityKind, // The type of entity this ID refers to } /// The different types of entities that can exist in a glyph #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect)] pub enum EntityKind { Point, // A point in a contour path Guide, // A guide line for alignment Component, // A component reference to another glyph } impl EntityId { /// Creates an entity ID for a point in a specific contour #[allow(dead_code)] pub fn point(parent: u32, index: u16) -> Self { Self { parent, index, kind: EntityKind::Point, } } /// Creates an entity ID for a guide #[allow(dead_code)] pub fn guide(index: u16) -> Self { Self { parent: 0, index, kind: EntityKind::Guide, } } /// Gets the parent container ID #[allow(dead_code)] pub fn parent(&self) -> u32 { self.parent } /// Gets the index within the parent container #[allow(dead_code)] pub fn index(&self) -> u16 { self.index } /// Checks if this entity is a guide #[allow(dead_code)] pub fn is_guide(&self) -> bool { self.kind == EntityKind::Guide } /// Checks if this entity is a point #[allow(dead_code)] pub fn is_point(&self) -> bool { self.kind == EntityKind::Point } /// Checks if this entity is a component #[allow(dead_code)] pub fn is_component(&self) -> bool { self.kind == EntityKind::Component } }
412
0.801479
1
0.801479
game-dev
MEDIA
0.403283
game-dev
0.690971
1
0.690971
EphemeralSpace/ephemeral-space
5,478
Content.Shared/RetractableItemAction/RetractableItemActionSystem.cs
using Content.Shared.Actions; using Content.Shared.Cuffs; using Content.Shared.Hands; using Content.Shared.Hands.EntitySystems; using Content.Shared.Interaction.Components; using Content.Shared.Inventory; using Content.Shared.Popups; using Robust.Shared.Audio.Systems; using Robust.Shared.Containers; namespace Content.Shared.RetractableItemAction; /// <summary> /// System for handling retractable items, such as armblades. /// </summary> public sealed class RetractableItemActionSystem : EntitySystem { [Dependency] private readonly SharedHandsSystem _hands = default!; [Dependency] private readonly SharedContainerSystem _containers = default!; [Dependency] private readonly SharedAudioSystem _audio = default!; [Dependency] private readonly SharedActionsSystem _actions = default!; [Dependency] private readonly SharedPopupSystem _popups = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<RetractableItemActionComponent, MapInitEvent>(OnActionInit); SubscribeLocalEvent<RetractableItemActionComponent, OnRetractableItemActionEvent>(OnRetractableItemAction); SubscribeLocalEvent<ActionRetractableItemComponent, ComponentShutdown>(OnActionSummonedShutdown); Subs.SubscribeWithRelay<ActionRetractableItemComponent, HeldRelayedEvent<TargetHandcuffedEvent>>(OnItemHandcuffed, inventory: false); } private void OnActionInit(Entity<RetractableItemActionComponent> ent, ref MapInitEvent args) { _containers.EnsureContainer<Container>(ent, RetractableItemActionComponent.ContainerId); PopulateActionItem(ent.Owner); } private void OnRetractableItemAction(Entity<RetractableItemActionComponent> ent, ref OnRetractableItemActionEvent args) { if (_hands.GetActiveHand(args.Performer) is not { } activeHand) return; if (_actions.GetAction(ent.Owner) is not { } action) return; if (action.Comp.AttachedEntity == null) return; if (ent.Comp.ActionItemUid == null) return; // Don't allow to summon an item if holding an unremoveable item unless that item is summoned by the action. if (_hands.GetActiveItem(ent.Owner) != null && !_hands.IsHolding(args.Performer, ent.Comp.ActionItemUid) && !_hands.CanDropHeld(args.Performer, activeHand, false)) { _popups.PopupClient(Loc.GetString("retractable-item-hand-cannot-drop"), args.Performer, args.Performer); return; } if (_hands.IsHolding(args.Performer, ent.Comp.ActionItemUid)) { RetractRetractableItem(args.Performer, ent.Comp.ActionItemUid.Value, ent.Owner); } else { SummonRetractableItem(args.Performer, ent.Comp.ActionItemUid.Value, activeHand, ent.Owner); } args.Handled = true; } private void OnActionSummonedShutdown(Entity<ActionRetractableItemComponent> ent, ref ComponentShutdown args) { if (_actions.GetAction(ent.Comp.SummoningAction) is not { } action) return; if (!TryComp<RetractableItemActionComponent>(action, out var retract) || retract.ActionItemUid != ent.Owner) return; // If the item is somehow destroyed, re-add it to the action. PopulateActionItem(action.Owner); } private void OnItemHandcuffed(Entity<ActionRetractableItemComponent> ent, ref HeldRelayedEvent<TargetHandcuffedEvent> args) { if (_actions.GetAction(ent.Comp.SummoningAction) is not { } action) return; if (action.Comp.AttachedEntity == null) return; if (_hands.GetActiveHand(action.Comp.AttachedEntity.Value) is not { }) return; RetractRetractableItem(action.Comp.AttachedEntity.Value, ent, action.Owner); } private void PopulateActionItem(Entity<RetractableItemActionComponent?> ent) { if (!Resolve(ent.Owner, ref ent.Comp, false) || TerminatingOrDeleted(ent)) return; if (!PredictedTrySpawnInContainer(ent.Comp.SpawnedPrototype, ent.Owner, RetractableItemActionComponent.ContainerId, out var summoned)) return; ent.Comp.ActionItemUid = summoned.Value; // Mark the unremovable item so it can be added back into the action. var summonedComp = AddComp<ActionRetractableItemComponent>(summoned.Value); summonedComp.SummoningAction = ent.Owner; Dirty(summoned.Value, summonedComp); Dirty(ent); } private void RetractRetractableItem(EntityUid holder, EntityUid item, Entity<RetractableItemActionComponent?> action) { if (!Resolve(action, ref action.Comp, false)) return; RemComp<UnremoveableComponent>(item); var container = _containers.GetContainer(action, RetractableItemActionComponent.ContainerId); _containers.Insert(item, container); _audio.PlayPredicted(action.Comp.RetractSounds, holder, holder); } private void SummonRetractableItem(EntityUid holder, EntityUid item, string hand, Entity<RetractableItemActionComponent?> action) { if (!Resolve(action, ref action.Comp, false)) return; _hands.TryForcePickup(holder, item, hand, checkActionBlocker: false); _audio.PlayPredicted(action.Comp.SummonSounds, holder, holder); EnsureComp<UnremoveableComponent>(item); } }
412
0.950041
1
0.950041
game-dev
MEDIA
0.993789
game-dev
0.912649
1
0.912649
JohnMasen/ChakraCore.NET
2,342
source/ChakraCore.NET.Timer/JSTimer.cs
using System; using ChakraCore.NET.API; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace ChakraCore.NET.Timer { public class JSTimer :ServiceConsumerBase { SortedDictionary<Guid, Tuple<Action, CancellationTokenSource>> list = new SortedDictionary<Guid, Tuple<Action, CancellationTokenSource>>(); public JSTimer(IServiceNode parentNode) : base(parentNode, "JSTimer") { } public Guid SetInterval(Action callback,int delay) { CancellationTokenSource source = new CancellationTokenSource(); Guid id = addCallback(callback, source); Task.Factory.StartNew(async() => { while (true) { try { await Task.Delay(delay, source.Token); callback(); } catch (OperationCanceledException) { return; } catch (Exception) { throw; } } },source.Token); return id; } public void ClearInterval(Guid id) { releaseCallback(id); } public void SetTimeout(Action callback,int delay) { Task.Factory.StartNew(async() => { await Task.Delay(delay); callback(); }); } private void releaseCallback(Guid id) { if (!list.ContainsKey(id)) { return;//ignore the request if id does not exists } list[id].Item2.Cancel();//cancel the interval loop list.Remove(id); } private Guid addCallback(Action value, CancellationTokenSource source) { Guid result = Guid.NewGuid(); list.Add(result, new Tuple<Action, CancellationTokenSource>(value, source)); return result; } public void ReleaseAll() { foreach (var item in list) { item.Value.Item2.Cancel(); } } } }
412
0.883341
1
0.883341
game-dev
MEDIA
0.743689
game-dev
0.963298
1
0.963298
Emudofus/Dofus
2,723
com/ankamagames/jerakine/managers/PerformanceManager.as
package com.ankamagames.jerakine.managers { import com.ankamagames.jerakine.utils.display.StageShareManager; import flash.events.Event; import flash.utils.getTimer; public class PerformanceManager { public static const CRITICAL:int = 0; public static const LIMITED:int = 1; public static const NORMAL:int = 2; public static var optimize:Boolean = false; public static var performance:int = NORMAL;//2 public static const BASE_FRAMERATE:int = 50; public static var maxFrameRate:int = BASE_FRAMERATE;//50 public static var frameDuration:Number = (1000 / maxFrameRate); private static var _totalFrames:int = 0; private static var _framesTime:int = 0; private static var _lastTime:int = 0; public static function init(lowQualityEnabled:Boolean):void { optimize = lowQualityEnabled; if (optimize) { setFrameRate(50); }; StageShareManager.stage.addEventListener(Event.ENTER_FRAME, onEnterFrame); } public static function setFrameRate(frameRate:int):void { maxFrameRate = frameRate; frameDuration = (1000 / maxFrameRate); StageShareManager.stage.frameRate = maxFrameRate; } private static function onEnterFrame(e:Event):void { var optimalCondition:int; var _local_5:int; var LAST:int = performance; var time:int = getTimer(); if ((_totalFrames % 21) == 0) { optimalCondition = (frameDuration * 20); if (_framesTime < (optimalCondition * 1.05)) { performance = NORMAL; } else { if (_framesTime < (optimalCondition * 1.15)) { performance = LIMITED; } else { performance = CRITICAL; }; }; _framesTime = 0; } else { _local_5 = (time - _lastTime); if (_local_5 < frameDuration) { _local_5 = frameDuration; }; _framesTime = (_framesTime + _local_5); if (_local_5 > (2 * frameDuration)) { performance = CRITICAL; }; }; _totalFrames++; _lastTime = time; } } }//package com.ankamagames.jerakine.managers
412
0.73201
1
0.73201
game-dev
MEDIA
0.694447
game-dev
0.86428
1
0.86428
DanceManiac/Advanced-X-Ray-Public
4,700
SourcesAXR/xrGameCS/ui/UICDkey.cpp
#include "stdafx.h" #include "UICDkey.h" #include "UILines.h" #include "../../xrEngine/line_edit_control.h" #include "../MainMenu.h" #include "UIColorAnimatorWrapper.h" #include "../../xrEngine/xr_IOConsole.h" #include "../RegistryFuncs.h" #include "../../xrGameSpy/xrGameSpy_MainDefs.h" #include "player_name_modifyer.h" extern string64 gsCDKey; CUICDkey::CUICDkey() { m_view_access = false; CreateCDKeyEntry(); SetCurrentValue(); } void CUICDkey::Show( bool status ) { inherited::Show( status ); SetCurrentValue(); } void CUICDkey::OnFocusLost() { inherited::OnFocusLost(); if(m_bInputFocus) { m_bInputFocus = false; GetMessageTarget()->SendMessage(this,EDIT_TEXT_COMMIT,NULL); } SaveValue(); } void CUICDkey::Draw() { LPCSTR edt_str = ec().str_edit(); u32 edt_size = xr_strlen( edt_str ); if ( edt_size == 0 ) { m_view_access = true; } //inherited::Draw(); Frect rect; GetAbsoluteRect (rect); Fvector2 out; out.y = (m_wndSize.y - m_pLines->m_pFont->CurrentHeight_())/2.0f; out.x = 0.0f; m_pLines->m_pFont->SetColor (m_pLines->GetTextColor()); Fvector2 pos; pos.set (rect.left+out.x, rect.top+out.y); UI().ClientToScreenScaled (pos); string64 xx_str = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; edt_size = xr_strlen( edt_str ); if ( edt_size > 63 ) { edt_size = 63; } xx_str[edt_size] = 0; string64 xx_str1 = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; LPCSTR edt_str1 = ec().str_before_cursor(); u32 edt_size1 = xr_strlen( edt_str1 ); if ( edt_size1 > 63 ) { edt_size1 = 63; } xx_str1[edt_size1] = 0; if ( m_bInputFocus ) { LPCSTR res = ( m_view_access )? edt_str : xx_str; LPCSTR res1 = ( m_view_access )? edt_str1 : xx_str1; m_pLines->m_pFont->Out ( pos.x, pos.y, "%s", CMainMenu::AddHyphens( res ) ); float _h = m_pLines->m_pFont->CurrentHeight_(); UI().ClientToScreenScaledHeight(_h); out.y = rect.top + (m_wndSize.y - _h)/2.0f; float w_tmp = 0.0f; int i = (int)xr_strlen( res1 ); w_tmp = m_pLines->m_pFont->SizeOf_( res1 ); UI().ClientToScreenScaledWidth( w_tmp ); out.x = rect.left + w_tmp; w_tmp = m_pLines->m_pFont->SizeOf_("-"); UI().ClientToScreenScaledWidth( w_tmp ); if(i>3) out.x += w_tmp; if(i>7) out.x += w_tmp; if(i>11) out.x += w_tmp; UI().ClientToScreenScaled (out); m_pLines->m_pFont->Out (out.x, out.y, "_"); } else { m_pLines->m_pFont->Out(pos.x, pos.y, "%s" , CMainMenu::AddHyphens(xx_str) ); } m_pLines->m_pFont->OnRender(); } LPCSTR CUICDkey::GetText() { return CMainMenu::AddHyphens(inherited::GetText()); } void CUICDkey::SetCurrentValue() { string512 CDKeyStr; CDKeyStr[0] = 0; GetCDKey_FromRegistry(CDKeyStr); inherited::SetText( CMainMenu::DelHyphens(CDKeyStr) ); } void CUICDkey::SaveValue() { CUIOptionsItem::SaveValue(); strcpy_s( gsCDKey, sizeof(gsCDKey), CMainMenu::AddHyphens(inherited::GetText()) ); WriteCDKey_ToRegistry( gsCDKey ); if ( MainMenu()->IsCDKeyIsValid() ) { m_view_access = false; } } bool CUICDkey::IsChanged() { string512 tmpCDKeyStr; GetCDKey_FromRegistry(tmpCDKeyStr); return 0 != xr_strcmp(tmpCDKeyStr, inherited::GetText()); } void CUICDkey::CreateCDKeyEntry() { } //================================================================= void CUIMPPlayerName::OnFocusLost() { inherited::OnFocusLost(); if ( m_bInputFocus ) { m_bInputFocus = false; GetMessageTarget()->SendMessage(this, EDIT_TEXT_COMMIT, NULL); } string64 name; strcpy_s( name, GetText() ); string256 new_name; modify_player_name(name, new_name); WritePlayerName_ToRegistry( new_name ); } // ------------------------------------------------------------------------------------------------- void GetCDKey_FromRegistry(char* cdkey) { ReadRegistry_StrValue(REGISTRY_VALUE_GSCDKEY, cdkey); if ( xr_strlen(cdkey) > 64 ) { cdkey[64] = 0; } } void WriteCDKey_ToRegistry(LPSTR cdkey) { if ( xr_strlen(cdkey) > 64 ) { cdkey[64] = 0; } WriteRegistry_StrValue(REGISTRY_VALUE_GSCDKEY, cdkey); } void GetPlayerName_FromRegistry(char* name, u32 const name_size) { string256 new_name; if (!ReadRegistry_StrValue(REGISTRY_VALUE_USERNAME, name)) { name[0] = 0; Msg( "! Player name registry key (%s) not found !", REGISTRY_VALUE_USERNAME ); return; } if ( xr_strlen(name) > 17 ) { name[17] = 0; } if ( xr_strlen(name) == 0 ) { Msg( "! Player name in registry is empty! (%s)", REGISTRY_VALUE_USERNAME ); } modify_player_name(name, new_name); strncpy_s(name, name_size, new_name, 17); } void WritePlayerName_ToRegistry(LPSTR name) { if ( xr_strlen(name) > 17 ) { name[17] = 0; } WriteRegistry_StrValue(REGISTRY_VALUE_USERNAME, name); }
412
0.962991
1
0.962991
game-dev
MEDIA
0.509043
game-dev,desktop-app
0.938004
1
0.938004
gamingdotme/opensource-casino-v10
42,991
casino/app/Games/HotTwentyAM/SlotSettings.php
<?php namespace VanguardLTE\Games\HotTwentyAM { class SlotSettings { public $playerId = null; public $splitScreen = null; public $reelStrip1 = null; public $reelStrip2 = null; public $reelStrip3 = null; public $reelStrip4 = null; public $reelStrip5 = null; public $reelStrip6 = null; public $reelStripBonus1 = null; public $reelStripBonus2 = null; public $reelStripBonus3 = null; public $reelStripBonus4 = null; public $reelStripBonus5 = null; public $reelStripBonus6 = null; public $slotId = ''; public $slotDBId = ''; public $Line = null; public $scaleMode = null; public $numFloat = null; public $gameLine = null; public $Bet = null; public $isBonusStart = null; public $Balance = null; public $SymbolGame = null; public $GambleType = null; public $lastEvent = null; public $Jackpots = []; public $keyController = null; public $slotViewState = null; public $hideButtons = null; public $slotReelsConfig = null; public $slotFreeCount = null; public $slotFreeMpl = null; public $slotWildMpl = null; public $slotExitUrl = null; public $slotBonus = null; public $slotBonusType = null; public $slotScatterType = null; public $slotGamble = null; public $Paytable = []; public $slotSounds = []; private $jpgs = null; private $Bank = null; private $Percent = null; private $WinLine = null; private $WinGamble = null; private $Bonus = null; private $shop_id = null; public $currency = null; public $user = null; public $game = null; public $shop = null; public $jpgPercentZero = false; public $count_balance = null; public function __construct($sid, $playerId) { $this->slotId = $sid; $this->playerId = $playerId; $user = \VanguardLTE\User::lockForUpdate()->find($this->playerId); $this->user = $user; $this->shop_id = $user->shop_id; $gamebank = \VanguardLTE\GameBank::where(['shop_id' => $this->shop_id])->lockForUpdate()->get(); $game = \VanguardLTE\Game::where([ 'name' => $this->slotId, 'shop_id' => $this->shop_id ])->lockForUpdate()->first(); $this->shop = \VanguardLTE\Shop::find($this->shop_id); $this->game = $game; $this->MaxWin = $this->shop->max_win; if( $game->stat_in > 0 ) { $this->currentRTP = $game->stat_out / $game->stat_in * 100; } else { $this->currentRTP = 0; } $this->increaseRTP = 1; $this->CurrentDenom = $this->game->denomination; $this->scaleMode = 0; $this->numFloat = 0; $this->Paytable['SYM_0'] = [ 0, 0, 0, 40, 400, 1000 ]; $this->Paytable['SYM_1'] = [ 0, 0, 0, 20, 80, 400 ]; $this->Paytable['SYM_2'] = [ 0, 0, 0, 20, 40, 200 ]; $this->Paytable['SYM_3'] = [ 0, 0, 0, 20, 40, 200 ]; $this->Paytable['SYM_4'] = [ 0, 0, 0, 10, 20, 100 ]; $this->Paytable['SYM_5'] = [ 0, 0, 0, 10, 20, 100 ]; $this->Paytable['SYM_6'] = [ 0, 0, 0, 10, 20, 100 ]; $this->Paytable['SYM_7'] = [ 0, 0, 0, 5, 20, 500 ]; $reel = new GameReel(); foreach( [ 'reelStrip1', 'reelStrip2', 'reelStrip3', 'reelStrip4', 'reelStrip5', 'reelStrip6' ] as $reelStrip ) { if( count($reel->reelsStrip[$reelStrip]) ) { $this->$reelStrip = $reel->reelsStrip[$reelStrip]; } } $this->keyController = [ '13' => 'uiButtonSpin,uiButtonSkip', '49' => 'uiButtonInfo', '50' => 'uiButtonCollect', '51' => 'uiButtonExit2', '52' => 'uiButtonLinesMinus', '53' => 'uiButtonLinesPlus', '54' => 'uiButtonBetMinus', '55' => 'uiButtonBetPlus', '56' => 'uiButtonGamble', '57' => 'uiButtonRed', '48' => 'uiButtonBlack', '189' => 'uiButtonAuto', '187' => 'uiButtonSpin' ]; $this->slotReelsConfig = [ [ 425, 142, 3 ], [ 669, 142, 3 ], [ 913, 142, 3 ], [ 1157, 142, 3 ], [ 1401, 142, 3 ] ]; $this->slotBonusType = 1; $this->slotScatterType = 0; $this->splitScreen = false; $this->slotBonus = false; $this->slotGamble = true; $this->slotFastStop = 1; $this->slotExitUrl = '/'; $this->slotWildMpl = 1; $this->GambleType = 1; $this->slotFreeCount = 0; $this->slotFreeMpl = 3; $this->slotViewState = ($game->slotViewState == '' ? 'Normal' : $game->slotViewState); $this->hideButtons = []; $this->jpgs = \VanguardLTE\JPG::where('shop_id', $this->shop_id)->lockForUpdate()->get(); $this->Line = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; $this->gameLine = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]; $this->Bet = explode(',', $game->bet); if( $this->Bet[0] < 0.01 ) { foreach( $this->Bet as &$bt ) { $bt = $bt * 10; } } $this->Balance = $user->balance; $this->SymbolGame = [ '0', '1', 2, 3, 4, 5, 6, 7 ]; $this->Bank = $game->get_gamebank(); $this->Percent = $this->shop->percent; $this->WinGamble = $game->rezerv; $this->slotDBId = $game->id; $this->slotCurrency = $user->shop->currency; $this->count_balance = $user->count_balance; if( $user->address > 0 && $user->count_balance == 0 ) { $this->Percent = 0; $this->jpgPercentZero = true; } else if( $user->count_balance == 0 ) { $this->Percent = 100; } if( !isset($this->user->session) || strlen($this->user->session) <= 0 ) { $this->user->session = serialize([]); } $this->gameData = unserialize($this->user->session); if( count($this->gameData) > 0 ) { foreach( $this->gameData as $key => $vl ) { if( $vl['timelife'] <= time() ) { unset($this->gameData[$key]); } } } if( !isset($this->game->advanced) || strlen($this->game->advanced) <= 0 ) { $this->game->advanced = serialize([]); } $this->gameDataStatic = unserialize($this->game->advanced); $this->gameDataStatic = unserialize($this->game->advanced); if( count($this->gameDataStatic) > 0 ) { foreach( $this->gameDataStatic as $key => $vl ) { if( $vl['timelife'] <= time() ) { unset($this->gameDataStatic[$key]); } } } } public function is_active() { if( $this->game && $this->shop && $this->user && (!$this->game->view || $this->shop->is_blocked || $this->user->is_blocked || $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED) ) { \VanguardLTE\Session::where('user_id', $this->user->id)->delete(); $this->user->update(['remember_token' => null]); return false; } if( !$this->game->view ) { return false; } if( $this->shop->is_blocked ) { return false; } if( $this->user->is_blocked ) { return false; } if( $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED ) { return false; } return true; } public function SetGameData($key, $value) { $timeLife = 86400; $this->gameData[$key] = [ 'timelife' => time() + $timeLife, 'payload' => $value ]; } public function GetGameData($key) { if( isset($this->gameData[$key]) ) { return $this->gameData[$key]['payload']; } else { return 0; } } public function FormatFloat($num) { $str0 = explode('.', $num); if( isset($str0[1]) ) { if( strlen($str0[1]) > 4 ) { return round($num * 100) / 100; } else if( strlen($str0[1]) > 2 ) { return floor($num * 100) / 100; } else { return $num; } } else { return $num; } } public function SaveGameData() { $this->user->session = serialize($this->gameData); $this->user->save(); } public function CheckBonusWin() { $allRateCnt = 0; $allRate = 0; foreach( $this->Paytable as $vl ) { foreach( $vl as $vl2 ) { if( $vl2 > 0 ) { $allRateCnt++; $allRate += $vl2; break; } } } return $allRate / $allRateCnt; } public function GetRandomPay() { $allRate = []; foreach( $this->Paytable as $vl ) { foreach( $vl as $vl2 ) { if( $vl2 > 0 ) { $allRate[] = $vl2; } } } shuffle($allRate); if( $this->game->stat_in < ($this->game->stat_out + ($allRate[0] * $this->AllBet)) ) { $allRate[0] = 0; } return $allRate[0]; } public function HasGameDataStatic($key) { if( isset($this->gameDataStatic[$key]) ) { return true; } else { return false; } } public function SaveGameDataStatic() { $this->game->advanced = serialize($this->gameDataStatic); $this->game->save(); $this->game->refresh(); } public function SetGameDataStatic($key, $value) { $timeLife = 86400; $this->gameDataStatic[$key] = [ 'timelife' => time() + $timeLife, 'payload' => $value ]; } public function GetGameDataStatic($key) { if( isset($this->gameDataStatic[$key]) ) { return $this->gameDataStatic[$key]['payload']; } else { return 0; } } public function HasGameData($key) { if( isset($this->gameData[$key]) ) { return true; } else { return false; } } public function HexFormat($num) { $str = strlen(dechex($num)) . dechex($num); return $str; } public function FormatReelStrips($pf) { $resultReelStrips = ''; foreach( [ 'reelStrip' . $pf . '1', 'reelStrip' . $pf . '2', 'reelStrip' . $pf . '3', 'reelStrip' . $pf . '4', 'reelStrip' . $pf . '5', 'reelStrip' . $pf . '6' ] as $reelStrip ) { if( $this->$reelStrip != '' ) { $data = $this->$reelStrip; foreach( $data as &$item ) { $item = str_replace('"', '', $item); $item = trim($item); $item = dechex($item); } $rLength = dechex(count($data)); $resultReelStrips .= (strlen($rLength) . $rLength . implode('', $data)); } } return $resultReelStrips; } public function GetRandomReels() { $reelsPos1 = rand(0, count($this->reelStrip1) - 1); $reelsPos2 = rand(0, count($this->reelStrip2) - 1); $reelsPos3 = rand(0, count($this->reelStrip3) - 1); $reelsPos4 = rand(0, count($this->reelStrip4) - 1); $reelsPos5 = rand(0, count($this->reelStrip5) - 1); return $this->HexFormat($reelsPos1) . $this->HexFormat($reelsPos2) . $this->HexFormat($reelsPos3) . $this->HexFormat($reelsPos4) . $this->HexFormat($reelsPos5); } public function GetHistory() { $history = \VanguardLTE\GameLog::whereRaw('game_id=? and user_id=? ORDER BY id DESC LIMIT 10', [ $this->slotDBId, $this->playerId ])->get(); $this->lastEvent = 'NULL'; foreach( $history as $log ) { $tmpLog = json_decode($log->str); if( $tmpLog->responseEvent != 'gambleResult' ) { $this->lastEvent = $log->str; break; } } if( isset($tmpLog) ) { return $tmpLog; } else { return 'NULL'; } } public function UpdateJackpots($bet) { $bet = $bet * $this->CurrentDenom; $count_balance = $this->count_balance; $jsum = []; $payJack = 0; for( $i = 0; $i < count($this->jpgs); $i++ ) { if( $count_balance == 0 || $this->jpgPercentZero ) { $jsum[$i] = $this->jpgs[$i]->balance; } else if( $count_balance < $bet ) { $jsum[$i] = $count_balance / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance; } else { $jsum[$i] = $bet / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance; } if( $this->jpgs[$i]->get_pay_sum() < $jsum[$i] && $this->jpgs[$i]->get_pay_sum() > 0 ) { if( $this->jpgs[$i]->user_id && $this->jpgs[$i]->user_id != $this->user->id ) { } else { $payJack = $this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom; $jsum[$i] = $jsum[$i] - $this->jpgs[$i]->get_pay_sum(); $this->SetBalance($this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom); if( $this->jpgs[$i]->get_pay_sum() > 0 ) { \VanguardLTE\StatGame::create([ 'user_id' => $this->playerId, 'balance' => $this->Balance * $this->CurrentDenom, 'bet' => 0, 'win' => $this->jpgs[$i]->get_pay_sum(), 'game' => $this->game->name . ' JPG ' . $this->jpgs[$i]->id, 'in_game' => 0, 'in_jpg' => 0, 'in_profit' => 0, 'shop_id' => $this->shop_id, 'date_time' => \Carbon\Carbon::now() ]); } } $i++; } $this->jpgs[$i]->balance = $jsum[$i]; $this->jpgs[$i]->save(); if( $this->jpgs[$i]->balance < $this->jpgs[$i]->get_min('start_balance') ) { $summ = $this->jpgs[$i]->get_start_balance(); if( $summ > 0 ) { $this->jpgs[$i]->add_jpg('add', $summ); } } } if( $payJack > 0 ) { $payJack = sprintf('%01.2f', $payJack); $this->Jackpots['jackPay'] = $payJack; } } public function GetBank($slotState = '') { if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' ) { $slotState = 'bonus'; } else { $slotState = ''; } $game = $this->game; $this->Bank = $game->get_gamebank($slotState); return $this->Bank / $this->CurrentDenom; } public function GetPercent() { return $this->Percent; } public function GetCountBalanceUser() { return $this->user->count_balance; } public function InternalErrorSilent($errcode) { $strLog = ''; $strLog .= "\n"; $strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}'); $strLog .= "\n"; $strLog .= ' ############################################### '; $strLog .= "\n"; $slg = ''; if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') ) { $slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log'); } file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog); } public function InternalError($errcode) { $strLog = ''; $strLog .= "\n"; $strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}'); $strLog .= "\n"; $strLog .= ' ############################################### '; $strLog .= "\n"; $slg = ''; if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') ) { $slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log'); } file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog); exit( '' ); } public function SetBank($slotState = '', $sum, $slotEvent = '') { if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' ) { $slotState = 'bonus'; } else { $slotState = ''; } if( $this->GetBank($slotState) + $sum < 0 ) { $this->InternalError('Bank_ ' . $sum . ' CurrentBank_ ' . $this->GetBank($slotState) . ' CurrentState_ ' . $slotState . ' Trigger_ ' . ($this->GetBank($slotState) + $sum)); } $sum = $sum * $this->CurrentDenom; $game = $this->game; $bankBonusSum = 0; if( $sum > 0 && $slotEvent == 'bet' ) { $this->toGameBanks = 0; $this->toSlotJackBanks = 0; $this->toSysJackBanks = 0; $this->betProfit = 0; $prc = $this->GetPercent(); $prc_b = 10; if( $prc <= $prc_b ) { $prc_b = 0; } $count_balance = $this->count_balance; $gameBet = $sum / $this->GetPercent() * 100; if( $count_balance < $gameBet && $count_balance > 0 ) { $firstBid = $count_balance; $secondBid = $gameBet - $firstBid; if( isset($this->betRemains0) ) { $secondBid = $this->betRemains0; } $bankSum = $firstBid / 100 * $this->GetPercent(); $sum = $bankSum + $secondBid; $bankBonusSum = $firstBid / 100 * $prc_b; } else if( $count_balance > 0 ) { $bankBonusSum = $gameBet / 100 * $prc_b; } for( $i = 0; $i < count($this->jpgs); $i++ ) { if( !$this->jpgPercentZero ) { if( $count_balance < $gameBet && $count_balance > 0 ) { $this->toSlotJackBanks += ($count_balance / 100 * $this->jpgs[$i]->percent); } else if( $count_balance > 0 ) { $this->toSlotJackBanks += ($gameBet / 100 * $this->jpgs[$i]->percent); } } } $this->toGameBanks = $sum; $this->betProfit = $gameBet - $this->toGameBanks - $this->toSlotJackBanks - $this->toSysJackBanks; } if( $sum > 0 ) { $this->toGameBanks = $sum; } if( $bankBonusSum > 0 ) { $sum -= $bankBonusSum; $game->set_gamebank($bankBonusSum, 'inc', 'bonus'); } if( $sum == 0 && $slotEvent == 'bet' && isset($this->betRemains) ) { $sum = $this->betRemains; } $game->set_gamebank($sum, 'inc', $slotState); $game->save(); return $game; } public function SetBalance($sum, $slotEvent = '') { if( $this->GetBalance() + $sum < 0 ) { $this->InternalError('Balance_ ' . $sum); } $sum = $sum * $this->CurrentDenom; if( $sum < 0 && $slotEvent == 'bet' ) { $user = $this->user; if( $user->count_balance == 0 ) { $remains = []; $this->betRemains = 0; $sm = abs($sum); if( $user->address < $sm && $user->address > 0 ) { $remains[] = $sm - $user->address; } for( $i = 0; $i < count($remains); $i++ ) { if( $this->betRemains < $remains[$i] ) { $this->betRemains = $remains[$i]; } } } if( $user->count_balance > 0 && $user->count_balance < abs($sum) ) { $remains0 = []; $sm = abs($sum); $tmpSum = $sm - $user->count_balance; $this->betRemains0 = $tmpSum; if( $user->address > 0 ) { $this->betRemains0 = 0; if( $user->address < $tmpSum && $user->address > 0 ) { $remains0[] = $tmpSum - $user->address; } for( $i = 0; $i < count($remains0); $i++ ) { if( $this->betRemains0 < $remains0[$i] ) { $this->betRemains0 = $remains0[$i]; } } } } $sum0 = abs($sum); if( $user->count_balance == 0 ) { $sm = abs($sum); if( $user->address < $sm && $user->address > 0 ) { $user->address = 0; } else if( $user->address > 0 ) { $user->address -= $sm; } } else if( $user->count_balance > 0 && $user->count_balance < $sum0 ) { $sm = $sum0 - $user->count_balance; if( $user->address < $sm && $user->address > 0 ) { $user->address = 0; } else if( $user->address > 0 ) { $user->address -= $sm; } } $this->user->count_balance = $this->user->updateCountBalance($sum, $this->count_balance); $this->user->count_balance = $this->FormatFloat($this->user->count_balance); } $this->user->increment('balance', $sum); $this->user->balance = $this->FormatFloat($this->user->balance); $this->user->save(); return $this->user; } public function GetBalance() { $user = $this->user; $this->Balance = $user->balance / $this->CurrentDenom; return $this->Balance; } public function SaveLogReport($spinSymbols, $bet, $lines, $win, $slotState) { $reportName = $this->slotId . ' ' . $slotState; if( $slotState == 'freespin' ) { $reportName = $this->slotId . ' FG'; } else if( $slotState == 'bet' ) { $reportName = $this->slotId . ''; } else if( $slotState == 'slotGamble' ) { $reportName = $this->slotId . ' DG'; } $game = $this->game; if( $slotState == 'bet' ) { $this->user->update_level('bet', $bet * $lines * $this->CurrentDenom); } if( $slotState != 'freespin' ) { $game->increment('stat_in', $bet * $lines * $this->CurrentDenom); } $game->increment('stat_out', $win * $this->CurrentDenom); $game->tournament_stat($slotState, $this->user->id, $bet * $lines * $this->CurrentDenom, $win * $this->CurrentDenom); $this->user->update(['last_bid' => \Carbon\Carbon::now()]); if( !isset($this->betProfit) ) { $this->betProfit = 0; $this->toGameBanks = 0; $this->toSlotJackBanks = 0; $this->toSysJackBanks = 0; } if( !isset($this->toGameBanks) ) { $this->toGameBanks = 0; } $this->game->increment('bids'); $this->game->refresh(); $gamebank = \VanguardLTE\GameBank::where(['shop_id' => $game->shop_id])->first(); if( $gamebank ) { list($slotsBank, $bonusBank, $fishBank, $tableBank, $littleBank) = \VanguardLTE\Lib\Banker::get_all_banks($game->shop_id); } else { $slotsBank = $game->get_gamebank('', 'slots'); $bonusBank = $game->get_gamebank('bonus', 'bonus'); $fishBank = $game->get_gamebank('', 'fish'); $tableBank = $game->get_gamebank('', 'table_bank'); $littleBank = $game->get_gamebank('', 'little'); } $totalBank = $slotsBank + $bonusBank + $fishBank + $tableBank + $littleBank; \VanguardLTE\GameLog::create([ 'game_id' => $this->slotDBId, 'user_id' => $this->playerId, 'ip' => $_SERVER['REMOTE_ADDR'], 'str' => $spinSymbols, 'shop_id' => $this->shop_id ]); \VanguardLTE\StatGame::create([ 'user_id' => $this->playerId, 'balance' => $this->Balance * $this->CurrentDenom, 'bet' => $bet * $lines * $this->CurrentDenom, 'win' => $win * $this->CurrentDenom, 'game' => $reportName, 'in_game' => $this->toGameBanks, 'in_jpg' => $this->toSlotJackBanks, 'in_profit' => $this->betProfit, 'denomination' => $this->CurrentDenom, 'shop_id' => $this->shop_id, 'slots_bank' => (double)$slotsBank, 'bonus_bank' => (double)$bonusBank, 'fish_bank' => (double)$fishBank, 'table_bank' => (double)$tableBank, 'little_bank' => (double)$littleBank, 'total_bank' => (double)$totalBank, 'date_time' => \Carbon\Carbon::now() ]); } public function GetSpinSettings($garantType = 'bet', $bet, $lines) { $curField = 10; switch( $lines ) { case 10: $curField = 10; break; case 9: case 8: $curField = 9; break; case 7: case 6: $curField = 7; break; case 5: case 4: $curField = 5; break; case 3: case 2: $curField = 3; break; case 1: $curField = 1; break; default: $curField = 10; break; } if( $garantType != 'bet' ) { $pref = '_bonus'; } else { $pref = ''; } $this->AllBet = $bet * $lines; $linesPercentConfigSpin = $this->game->get_lines_percent_config('spin'); $linesPercentConfigBonus = $this->game->get_lines_percent_config('bonus'); $currentPercent = $this->shop->percent; $currentSpinWinChance = 0; $currentBonusWinChance = 0; $percentLevel = ''; foreach( $linesPercentConfigSpin['line' . $curField . $pref] as $k => $v ) { $l = explode('_', $k); $l0 = $l[0]; $l1 = $l[1]; if( $l0 <= $currentPercent && $currentPercent <= $l1 ) { $percentLevel = $k; break; } } $currentSpinWinChance = $linesPercentConfigSpin['line' . $curField . $pref][$percentLevel]; $currentBonusWinChance = $linesPercentConfigBonus['line' . $curField . $pref][$percentLevel]; $RtpControlCount = 200; if( !$this->HasGameDataStatic('SpinWinLimit') ) { $this->SetGameDataStatic('SpinWinLimit', 0); } if( !$this->HasGameDataStatic('RtpControlCount') ) { $this->SetGameDataStatic('RtpControlCount', $RtpControlCount); } if( $this->game->stat_in > 0 ) { $rtpRange = $this->game->stat_out / $this->game->stat_in * 100; } else { $rtpRange = 0; } if( $this->GetGameDataStatic('RtpControlCount') == 0 ) { if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 ) { $this->SetGameDataStatic('SpinWinLimit', rand(25, 50)); } if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 ) { $currentBonusWinChance = 5000; $currentSpinWinChance = 20; $this->MaxWin = rand(1, 5); if( $rtpRange < ($currentPercent - 1) ) { $this->SetGameDataStatic('SpinWinLimit', 0); $this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1); } } } else if( $this->GetGameDataStatic('RtpControlCount') < 0 ) { if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 ) { $this->SetGameDataStatic('SpinWinLimit', rand(25, 50)); } $this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1); if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 ) { $currentBonusWinChance = 5000; $currentSpinWinChance = 10; $this->MaxWin = rand(1, 5); if( $rtpRange < ($currentPercent - 1) ) { $this->SetGameDataStatic('SpinWinLimit', 0); } } if( $this->GetGameDataStatic('RtpControlCount') < (-1 * $RtpControlCount) && $currentPercent - 1 <= $rtpRange && $rtpRange <= ($currentPercent + 2) ) { $this->SetGameDataStatic('RtpControlCount', $RtpControlCount); } } else { $this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1); } $bonusWin = rand(1, $currentBonusWinChance); $spinWin = rand(1, $currentSpinWinChance); $return = [ 'none', 0 ]; if( $bonusWin == 1 && $this->slotBonus ) { $this->isBonusStart = true; $garantType = 'bonus'; $winLimit = $this->GetBank($garantType); $return = [ 'bonus', $winLimit ]; if( $this->game->stat_in < ($this->CheckBonusWin() * $bet + $this->game->stat_out) || $winLimit < ($this->CheckBonusWin() * $bet) ) { $return = [ 'none', 0 ]; } } else if( $spinWin == 1 ) { $winLimit = $this->GetBank($garantType); $return = [ 'win', $winLimit ]; } if( $garantType == 'bet' && $this->GetBalance() <= (2 / $this->CurrentDenom) ) { $randomPush = rand(1, 10); if( $randomPush == 1 ) { $winLimit = $this->GetBank(''); $return = [ 'win', $winLimit ]; } } return $return; } public function GetRandomScatterPos($rp) { $rpResult = []; for( $i = 0; $i < count($rp); $i++ ) { if( $rp[$i] == '12' ) { if( isset($rp[$i + 1]) && isset($rp[$i - 1]) ) { array_push($rpResult, $i); } if( isset($rp[$i - 1]) && isset($rp[$i - 2]) ) { array_push($rpResult, $i - 1); } if( isset($rp[$i + 1]) && isset($rp[$i + 2]) ) { array_push($rpResult, $i + 1); } } } shuffle($rpResult); if( !isset($rpResult[0]) ) { $rpResult[0] = rand(2, count($rp) - 3); } return $rpResult[0]; } public function GetGambleSettings() { $spinWin = rand(1, $this->WinGamble); return $spinWin; } public function GetReelStrips($winType, $slotEvent) { $game = $this->game; if( $slotEvent == 'freespin' ) { $reel = new GameReel(); $fArr = $reel->reelsStripBonus; foreach( [ 'reelStrip1', 'reelStrip2', 'reelStrip3', 'reelStrip4', 'reelStrip5', 'reelStrip6' ] as $reelStrip ) { $curReel = array_shift($fArr); if( count($curReel) ) { $this->$reelStrip = $curReel; } } } if( $winType != 'bonus' ) { $prs = []; foreach( [ 'reelStrip1', 'reelStrip2', 'reelStrip3', 'reelStrip4', 'reelStrip5', 'reelStrip6' ] as $index => $reelStrip ) { if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 ) { $prs[$index + 1] = mt_rand(0, count($this->$reelStrip) - 3); } } } else { $reelsId = []; foreach( [ 'reelStrip1', 'reelStrip2', 'reelStrip3', 'reelStrip4', 'reelStrip5', 'reelStrip6' ] as $index => $reelStrip ) { if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 ) { $prs[$index + 1] = $this->GetRandomScatterPos($this->$reelStrip); $reelsId[] = $index + 1; } } $scattersCnt = rand(3, count($reelsId)); shuffle($reelsId); for( $i = 0; $i < count($reelsId); $i++ ) { if( $i < $scattersCnt ) { $prs[$reelsId[$i]] = $this->GetRandomScatterPos($this->{'reelStrip' . $reelsId[$i]}); } else { $prs[$reelsId[$i]] = rand(0, count($this->{'reelStrip' . $reelsId[$i]}) - 3); } } } $reel = [ 'rp' => [] ]; foreach( $prs as $index => $value ) { $key = $this->{'reelStrip' . $index}; $cnt = count($key); $key[-1] = $key[$cnt - 1]; $key[$cnt] = $key[0]; $reel['reel' . $index][0] = $key[$value - 1]; $reel['reel' . $index][1] = $key[$value]; $reel['reel' . $index][2] = $key[$value + 1]; $reel['reel' . $index][3] = ''; $reel['rp'][] = $value; } return $reel; } } }
412
0.611611
1
0.611611
game-dev
MEDIA
0.711969
game-dev
0.841891
1
0.841891
bark-simulator/bark
1,250
bark/world/evaluation/ltl/label_functions/behind_of_label_function.cpp
// Copyright (c) 2019 fortiss GmbH // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "behind_of_label_function.hpp" #include "bark/commons/transformation/frenet.hpp" #include "bark/world/observed_world.hpp" using bark::commons::transformation::FrenetPosition; bool bark::world::evaluation::BehindOfLabelFunction::EvaluateAgent( const bark::world::ObservedWorld& observed_world, const AgentPtr& other_agent) const { const auto ego_agent = observed_world.GetEgoAgent(); const auto ego_lane = observed_world.GetLaneCorridor(); if (other_agent) { const auto other_lane = other_agent->GetRoadCorridor()->GetCurrentLaneCorridor( other_agent->GetCurrentPosition()); if (!ego_lane || !other_lane) { return false; } else { FrenetPosition f_ego(ego_agent->GetCurrentPosition(), other_lane->GetCenterLine()); FrenetPosition f_other(other_agent->GetCurrentPosition(), other_lane->GetCenterLine()); return ((f_other.lon - other_agent->GetShape().rear_dist_) >= (f_ego.lon + ego_agent->GetShape().front_dist_)); } } return false; }
412
0.868899
1
0.868899
game-dev
MEDIA
0.679136
game-dev
0.663881
1
0.663881
cmss13-devs/cmss13
1,916
maps/shuttles/escape_shuttle_w.dmm
//MAP CONVERTED BY dmm2tgm.py THIS HEADER COMMENT PREVENTS RECONVERSION, DO NOT REMOVE "b" = ( /turf/closed/shuttle/escapepod{ icon_state = "wall8" }, /area/shuttle/escape_pod) "e" = ( /turf/closed/shuttle/escapepod{ icon_state = "wall6" }, /area/shuttle/escape_pod) "g" = ( /obj/docking_port/mobile/crashable/escape_shuttle/w, /turf/closed/shuttle/escapepod{ icon_state = "wall9" }, /area/shuttle/escape_pod) "j" = ( /turf/closed/shuttle/escapepod{ icon_state = "wall7" }, /area/shuttle/escape_pod) "o" = ( /turf/closed/shuttle/escapepod{ icon_state = "wall3" }, /area/shuttle/escape_pod) "p" = ( /turf/closed/shuttle/escapepod{ icon_state = "wall2" }, /area/shuttle/escape_pod) "r" = ( /obj/structure/machinery/cryopod/evacuation, /turf/open/shuttle/escapepod/floor4, /area/shuttle/escape_pod) "A" = ( /turf/open/shuttle/escapepod/floor0/north, /area/shuttle/escape_pod) "B" = ( /turf/closed/shuttle/escapepod{ icon_state = "wall10" }, /area/shuttle/escape_pod) "F" = ( /turf/closed/shuttle/escapepod{ icon_state = "wall1" }, /area/shuttle/escape_pod) "G" = ( /turf/closed/shuttle/escapepod{ icon_state = "wall4" }, /area/shuttle/escape_pod) "N" = ( /obj/structure/machinery/computer/shuttle/escape_pod_panel{ pixel_y = 30 }, /turf/open/shuttle/escapepod/floor2, /area/shuttle/escape_pod) "O" = ( /turf/open/shuttle/escapepod/north, /area/shuttle/escape_pod) "P" = ( /turf/closed/shuttle/escapepod{ icon_state = "wall13" }, /area/shuttle/escape_pod) "S" = ( /obj/structure/machinery/door/airlock/evacuation{ name = "\improper Evacuation Airlock PL-3" }, /turf/open/floor/almayer/test_floor4, /area/shuttle/escape_pod) "T" = ( /obj/structure/machinery/cryopod/evacuation, /obj/structure/sign/safety/cryo{ pixel_x = 36 }, /turf/open/shuttle/escapepod/floor4, /area/shuttle/escape_pod) (1,1,1) = {" P B S B g "} (2,1,1) = {" F N O A b "} (3,1,1) = {" p r T r j "} (4,1,1) = {" o G G G e "}
412
0.682243
1
0.682243
game-dev
MEDIA
0.820344
game-dev
0.548152
1
0.548152
magefree/mage
1,412
Mage.Sets/src/mage/cards/i/IntrepidRabbit.java
package mage.cards.i; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.effects.common.continuous.BoostTargetEffect; import mage.abilities.keyword.OffspringAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.target.common.TargetControlledCreaturePermanent; import java.util.UUID; /** * @author TheElk801 */ public final class IntrepidRabbit extends CardImpl { public IntrepidRabbit(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{W}"); this.subtype.add(SubType.RABBIT); this.subtype.add(SubType.SOLDIER); this.power = new MageInt(3); this.toughness = new MageInt(2); // Offspring {1} this.addAbility(new OffspringAbility("{1}")); // When this creature enters, target creature you control gets +1/+1 until end of turn. Ability ability = new EntersBattlefieldTriggeredAbility(new BoostTargetEffect(1, 1)); ability.addTarget(new TargetControlledCreaturePermanent()); this.addAbility(ability); } private IntrepidRabbit(final IntrepidRabbit card) { super(card); } @Override public IntrepidRabbit copy() { return new IntrepidRabbit(this); } }
412
0.911428
1
0.911428
game-dev
MEDIA
0.967746
game-dev
0.986914
1
0.986914
blorbb/leptos-mview
5,810
tests/slots.rs
use leptos::{either::Either, prelude::*}; use leptos_mview::mview; use utils::{check_str, Contains}; mod utils; // same example as the one given in the #[slot] proc macro documentation. #[test] fn test_example() { #[slot] struct HelloSlot { #[prop(optional)] children: Option<Children>, } #[component] fn HelloComponent(hello_slot: HelloSlot) -> impl IntoView { if let Some(children) = hello_slot.children { Either::Left((children)().into_view()) } else { Either::Right(().into_view()) } } view! { <HelloComponent> <HelloSlot slot>"Hello, World!"</HelloSlot> </HelloComponent> }; let r = mview! { HelloComponent { slot:HelloSlot { "Hello, World!" } } }; check_str(r, "Hello, World!"); } // https://github.com/leptos-rs/leptos/blob/main/examples/slots/src/lib.rs #[slot] struct Then { children: ChildrenFn, } #[slot] struct ElseIf { #[prop(into)] cond: Signal<bool>, children: ChildrenFn, } #[slot] struct Fallback { children: ChildrenFn, } #[component] fn SlotIf( #[prop(into)] cond: Signal<bool>, then: Then, #[prop(optional)] else_if: Vec<ElseIf>, #[prop(optional)] fallback: Option<Fallback>, ) -> impl IntoView { move || { if cond.get() { Either::Left((then.children)().into_view()) } else if let Some(else_if) = else_if.iter().find(|i| i.cond.get()) { Either::Left((else_if.children)().into_view()) } else if let Some(fallback) = &fallback { Either::Left((fallback.children)().into_view()) } else { Either::Right(().into_view()) } } } #[test] pub fn multiple_slots() { for (count, ans) in [(0, "even"), (5, "x5"), (45, "x5"), (9, "odd"), (7, "x7")] { let is_even = count % 2 == 0; let is_div5 = count % 5 == 0; let is_div7 = count % 7 == 0; let r = mview! { SlotIf cond={is_even} { slot:Then { "even" } slot:ElseIf cond={is_div5} { "x5" } slot:ElseIf cond={is_div7} { "x7" } slot:Fallback { "odd" } } }; check_str(r, ans); } } #[test] pub fn accept_multiple_use_single() { // else_if takes Vec<ElseIf>, check if just giving a single one // (which should just pass a single ElseIf instead of a vec) // still works let r = mview! { SlotIf cond=false { slot:Then { "no!" } slot:ElseIf cond=true { "yes!" } slot:Fallback { "absolutely not" } } }; check_str(r, "yes!"); } #[test] pub fn optional_slots() { let no_other = mview! { SlotIf cond=true { slot:Then { "yay!" } } }; check_str(no_other, "yay!"); let no_fallback = mview! { div { SlotIf cond=false { slot:Then { "not here" } slot:ElseIf cond=false { "not this either" } } } }; check_str(no_fallback, "></div>") } #[component] fn ChildThenIf( #[prop(into)] cond: Signal<bool>, children: ChildrenFn, #[prop(default=vec![])] else_if: Vec<ElseIf>, #[prop(optional)] fallback: Option<Fallback>, ) -> impl IntoView { move || { if cond.get() { Either::Left((children)().into_view()) } else if let Some(else_if) = else_if.iter().find(|i| i.cond.get()) { Either::Left((else_if.children)().into_view()) } else if let Some(fallback) = &fallback { Either::Left((fallback.children)().into_view()) } else { Either::Right(().into_view()) } } } #[test] fn children_and_slots() { let then = mview! { ChildThenIf cond=true { "here" slot:ElseIf cond=true { "not :(" } } }; check_str( then, Contains::AllOfNoneOf([["here"].as_slice(), ["not :("].as_slice()]), ); let elseif = mview! { div { ChildThenIf cond=false { "not :(" slot:ElseIf cond=true { "yes!" } } } }; check_str( elseif, Contains::AllOfNoneOf([["yes!"].as_slice(), ["not :("].as_slice()]), ); let mixed = mview! { div { ChildThenIf cond=true { "here 1" slot:ElseIf cond=false { "not this" } "here 2" span { "here 3" } slot:ElseIf cond=true { "still not here" } ChildThenIf cond=false { "nested not here" slot:Fallback { "nested is here!" } } slot:Fallback { "this one is not present" } "yet another shown" } } }; check_str( mixed, Contains::AllOfNoneOf([ [ "here 1", "here 2", "<span>here 3</span>", "nested is here!", "yet another shown", ] .as_slice(), [ "not this", "still not here", "nested not here", "this one is not present", ] .as_slice(), ]), ); } #[test] fn clone_in_slot() { let notcopy = String::new(); _ = mview! { ChildThenIf cond=true { "yes" slot:Fallback { ChildThenIf cond=true { "no" slot:Fallback clone:notcopy { {notcopy.clone()} } } } } }; }
412
0.558107
1
0.558107
game-dev
MEDIA
0.485057
game-dev
0.695064
1
0.695064
KhronosGroup/UnityGLTF
1,833
Editor/Scripts/Interactivity/VisualScriptingExport/UnitExporters/Transform/Transform_TransformPointUnitExport.cs
using System; using System.Linq; using Unity.VisualScripting; using UnityEditor; using UnityEngine; using UnityGLTF.Interactivity.Export; using UnityGLTF.Interactivity.Schema; namespace UnityGLTF.Interactivity.VisualScripting.Export { public class Transform_TransformPointUnitExport : IUnitExporter { public Type unitType { get => typeof(InvokeMember); } [InitializeOnLoadMethod] private static void Register() { InvokeUnitExport.RegisterInvokeExporter(typeof(Transform), nameof(Transform.TransformPoint), new Transform_TransformPointUnitExport()); } public bool InitializeInteractivityNodes(UnitExporter unitExporter) { var invokeUnit = unitExporter.unit as InvokeMember; TransformHelpers.GetWorldPointFromLocalPoint(unitExporter, out var targetRef, out var localPointSocket, out var worldPointSocket); targetRef.MapToInputPort(invokeUnit.target); if (invokeUnit.valueInputs.Count > 2) { var combine = unitExporter.CreateNode<Math_Combine3Node>(); combine.ValueIn(Math_Combine3Node.IdValueA).MapToInputPort(invokeUnit.valueInputs["%x"]); combine.ValueIn(Math_Combine3Node.IdValueB).MapToInputPort(invokeUnit.valueInputs["%y"]); combine.ValueIn(Math_Combine3Node.IdValueC).MapToInputPort(invokeUnit.valueInputs["%z"]); localPointSocket.ConnectToSource(combine.FirstValueOut()); } else localPointSocket.MapToInputPort(invokeUnit.valueInputs["%position"]); worldPointSocket.MapToPort(invokeUnit.result); unitExporter.ByPassFlow(invokeUnit.enter, invokeUnit.exit); return true; } } }
412
0.842471
1
0.842471
game-dev
MEDIA
0.811965
game-dev
0.897788
1
0.897788
akhuting/gms083
2,827
src/main/resources/scripts/event/3rdJob_bowman.js
/* This file is part of the HeavenMS MapleStory Server Copyleft (L) 2016 - 2019 RonanLana This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @Author Ronan * 3rd Job Event - Bowman **/ importPackage(Packages.tools); var entryMap = 108010100; var exitMap = 105040305; var minMapId = 108010100; var maxMapId = 108010101; var eventTime = 20; //20 minutes var lobbyRange = [0, 7]; function setLobbyRange() { return lobbyRange; } function init() { em.setProperty("noEntry","false"); } function setup(level, lobbyid) { var eim = em.newInstance("3rdJob_bowman_" + lobbyid); eim.setProperty("level", level); eim.setProperty("boss", "0"); return eim; } function playerEntry(eim, player) { eim.getInstanceMap(maxMapId).resetPQ(1); player.changeMap(entryMap, 0); em.setProperty("noEntry","true"); player.getClient().announce(MaplePacketCreator.getClock(eventTime * 60)); eim.startEventTimer(eventTime * 60000); } function playerUnregistered(eim, player) {} function playerExit(eim, player) { eim.unregisterPlayer(player); eim.dispose(); em.setProperty("noEntry","false"); } function scheduledTimeout(eim) { var player = eim.getPlayers().get(0); playerExit(eim, eim.getPlayers().get(0)); player.changeMap(exitMap); } function playerDisconnected(eim, player) { playerExit(eim, player); } function clear(eim) { var player = eim.getPlayers().get(0); eim.unregisterPlayer(player); player.changeMap(exitMap); eim.dispose(); em.setProperty("noEntry","false"); } function changedMap(eim, chr, mapid) { if(mapid < minMapId || mapid > maxMapId) playerExit(eim, chr); } function monsterKilled(mob, eim) {} function monsterValue(eim, mobId) { return 1; } function allMonstersDead(eim) {} function cancelSchedule() {} function dispose() {} // ---------- FILLER FUNCTIONS ---------- function disbandParty(eim, player) {} function afterSetup(eim) {} function changedLeader(eim, leader) {} function leftParty(eim, player) {} function clearPQ(eim) {}
412
0.694963
1
0.694963
game-dev
MEDIA
0.88432
game-dev
0.856245
1
0.856245
TeamLapen/Vampirism
5,197
src/main/java/de/teamlapen/vampirism/core/ModEffects.java
package de.teamlapen.vampirism.core; import de.teamlapen.vampirism.REFERENCE; import de.teamlapen.vampirism.api.VReference; import de.teamlapen.vampirism.api.entity.factions.IFaction; import de.teamlapen.vampirism.effects.*; import net.minecraft.core.registries.Registries; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectCategory; import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.neoforged.bus.api.IEventBus; import net.neoforged.neoforge.registries.DeferredHolder; import net.neoforged.neoforge.registries.DeferredRegister; /** * Handles all potion registrations and reference. */ public class ModEffects { public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(Registries.MOB_EFFECT, REFERENCE.MODID); public static final DeferredHolder<MobEffect, MobEffect> SANGUINARE = EFFECTS.register("sanguinare", () -> new SanguinareEffect(MobEffectCategory.NEUTRAL, 0x6A0888)); public static final DeferredHolder<MobEffect, MobEffect> SATURATION = EFFECTS.register("saturation", () -> new VampirismEffect(MobEffectCategory.BENEFICIAL, 0xDCFF00)); public static final DeferredHolder<MobEffect, MobEffect> SUNSCREEN = EFFECTS.register("sunscreen", () -> new VampirismEffect(MobEffectCategory.BENEFICIAL, 0xFFF100).addAttributeModifier(ModAttributes.SUNDAMAGE, ModEffects.SUNSCREEN.getId(), -0.5, AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL)); public static final DeferredHolder<MobEffect, MobEffect> DISGUISE_AS_VAMPIRE = EFFECTS.register("disguise_as_vampire", () -> new VampirismEffect(MobEffectCategory.NEUTRAL, 0x999900)); public static final DeferredHolder<MobEffect, MobEffect> FIRE_PROTECTION = EFFECTS.register("fire_protection", () -> new VampirismEffect(MobEffectCategory.BENEFICIAL, 14981690)); public static final DeferredHolder<MobEffect, MobEffect> GARLIC = EFFECTS.register("garlic", () -> new VampirismEffect(MobEffectCategory.HARMFUL, 0xFFFFFF)); public static final DeferredHolder<MobEffect, MobEffect> POISON = EFFECTS.register("poison", () -> new VampirismPoisonEffect(0x4E9331)); public static final DeferredHolder<MobEffect, MobEffect> FREEZE = EFFECTS.register("freeze", FreezeEffect::new); public static final DeferredHolder<MobEffect, MobEffect> NEONATAL = EFFECTS.register("neonatal", () -> new VampirismEffect(MobEffectCategory.NEUTRAL, 0xFFBBBB).addAttributeModifier(Attributes.ATTACK_DAMAGE, ModEffects.NEONATAL.getId(), -0.15, AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL).addAttributeModifier(Attributes.MOVEMENT_SPEED, ModEffects.NEONATAL.getId(), -0.15, AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL)); public static final DeferredHolder<MobEffect, MobEffect> OBLIVION = EFFECTS.register("oblivion", OblivionEffect::new); public static final DeferredHolder<MobEffect, MobEffect> ARMOR_REGENERATION = EFFECTS.register("armor_regeneration", () -> new VampirismEffect(MobEffectCategory.NEUTRAL, 0xD17642)); public static final DeferredHolder<MobEffect, MobEffect> BAD_OMEN_HUNTER = EFFECTS.register("bad_omen_hunter", () -> new BadOmenEffect() { @Override public IFaction<?> getFaction() { return VReference.HUNTER_FACTION; } }); public static final DeferredHolder<MobEffect, MobEffect> BAD_OMEN_VAMPIRE = EFFECTS.register("bad_omen_vampire", () -> new BadOmenEffect() { @Override public IFaction<?> getFaction() { return VReference.VAMPIRE_FACTION; } }); public static final DeferredHolder<MobEffect, MobEffect> LORD_SPEED = EFFECTS.register("lord_speed", () -> new VampirismEffect(MobEffectCategory.BENEFICIAL, 0xffffff).addAttributeModifier(Attributes.MOVEMENT_SPEED, ModEffects.LORD_SPEED.getId(), 0.07F, AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL)); public static final DeferredHolder<MobEffect, MobEffect> LORD_ATTACK_SPEED = EFFECTS.register("lord_attack_speed", () -> new VampirismEffect(MobEffectCategory.BENEFICIAL, 0xffffff).addAttributeModifier(Attributes.ATTACK_SPEED, ModEffects.LORD_ATTACK_SPEED.getId(), 0.05F, AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL)); public static final DeferredHolder<MobEffect, MobEffect> NO_BLOOD = EFFECTS.register("no_blood", () -> new VampirismEffect(MobEffectCategory.HARMFUL, 0x191919) .addAttributeModifier(Attributes.MOVEMENT_SPEED, ModEffects.NO_BLOOD.getId(), -0.4F, AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL) .addAttributeModifier(Attributes.ATTACK_SPEED, ModEffects.NO_BLOOD.getId(), -0.3F, AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL) .addAttributeModifier(ModAttributes.SUNDAMAGE, ModEffects.NO_BLOOD.getId(), 0.2, AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL) .addAttributeModifier(Attributes.ARMOR_TOUGHNESS, ModEffects.NO_BLOOD.getId(), -0.4, AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL) .addAttributeModifier(Attributes.ARMOR, ModEffects.NO_BLOOD.getId(), -0.2, AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL) ); static void register(IEventBus bus) { EFFECTS.register(bus); } }
412
0.823765
1
0.823765
game-dev
MEDIA
0.953559
game-dev
0.868698
1
0.868698
NeoAxis/SDK
1,492
Project/Src/WinFormsMultiViewAppExample/SplashForm.cs
// Copyright (C) NeoAxis Group Ltd. This is part of NeoAxis 3D Engine SDK. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using Engine.Renderer; namespace WinFormsMultiViewAppExample { public partial class SplashForm : Form { static SplashForm instance; float time; bool allowClose; public static SplashForm Instance { get { return instance; } } public SplashForm( Image image ) { instance = this; InitializeComponent(); Size = image.Size; BackgroundImage = image; } public bool AllowClose { get { return allowClose; } set { if( value && !allowClose ) timer1.Start(); allowClose = value; } } private void timer1_Tick( object sender, EventArgs e ) { time += (float)timer1.Interval / 1000.0f; bool allowAlpha = false; { if( RenderSystem.Instance != null && RenderSystem.Instance.IsDirect3D() ) { if( RenderSystem.Instance.GPUIsGeForce() || RenderSystem.Instance.GPUIsRadeon() ) allowAlpha = true; } } float opacity = 1.0f; if( allowAlpha ) { if( time > 0 ) opacity = ( 1.0f - time ) / 1; if( opacity < 0 ) opacity = 0; } if( Opacity != opacity ) Opacity = opacity; if( time > 1 ) { timer1.Stop(); Close(); } } private void SplashForm_FormClosed( object sender, FormClosedEventArgs e ) { instance = null; } } }
412
0.741785
1
0.741785
game-dev
MEDIA
0.561211
game-dev,graphics-rendering
0.891871
1
0.891871
Apress/beg-iphone-dev-w-swift-3
2,616
17_AllSource/TextShooter/TextShooter/EnemyNode.swift
// // EnemyNode.swift // TextShooter // // Created by Molly Maskrey on 7/21/16. // Copyright © 2016 Apress Inc. All rights reserved. // import SpriteKit class EnemyNode: SKNode { override init() { super.init() name = "Enemy \(self)" initNodeGraph() initPhysicsBody() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func friendlyBumpFrom(_ node: SKNode) { physicsBody!.affectedByGravity = true } override func receiveAttacker(_ attacker: SKNode, contact: SKPhysicsContact) { physicsBody!.affectedByGravity = true let force = vectorMultiply(attacker.physicsBody!.velocity, contact.collisionImpulse) let myContact = scene!.convert(contact.contactPoint, to: self) physicsBody!.applyForce(force, at: myContact) let path = Bundle.main.path(forResource: "MissileExplosion", ofType: "sks") let explosion = NSKeyedUnarchiver.unarchiveObject(withFile: path!) as! SKEmitterNode explosion.numParticlesToEmit = 20 explosion.position = contact.contactPoint scene!.addChild(explosion) run(SKAction.playSoundFileNamed("enemyHit.wav", waitForCompletion: false)) } private func initNodeGraph() { let topRow = SKLabelNode(fontNamed: "Courier-Bold") topRow.fontColor = SKColor.brown topRow.fontSize = 20 topRow.text = "x x" topRow.position = CGPoint(x: 0, y: 15) addChild(topRow) let middleRow = SKLabelNode(fontNamed: "Courier-Bold") middleRow.fontColor = SKColor.brown middleRow.fontSize = 20 middleRow.text = "x" addChild(middleRow) let bottomRow = SKLabelNode(fontNamed: "Courier-Bold") bottomRow.fontColor = SKColor.brown bottomRow.fontSize = 20 bottomRow.text = "x x" bottomRow.position = CGPoint(x: 0, y: -15) addChild(bottomRow) } private func initPhysicsBody() { let body = SKPhysicsBody(rectangleOf: CGSize(width: 40, height: 40)) body.affectedByGravity = false body.categoryBitMask = EnemyCategory body.contactTestBitMask = PlayerCategory | EnemyCategory body.mass = 0.2 body.angularDamping = 0 body.linearDamping = 0 body.fieldBitMask = 0 physicsBody = body } }
412
0.830225
1
0.830225
game-dev
MEDIA
0.919344
game-dev
0.826822
1
0.826822
HPI-Information-Systems/metanome-algorithms
1,261
dcfinder/src/main/java/de/metanome/algorithms/dcfinder/helpers/BitSetTranslator.java
package de.metanome.algorithms.dcfinder.helpers; import java.util.Collection; import java.util.Set; import java.util.stream.Collectors; import ch.javasoft.bitset.IBitSet; import ch.javasoft.bitset.LongBitSet; public class BitSetTranslator { private Integer[] indexes; public BitSetTranslator(Integer[] indexes) { this.indexes = indexes; } public IBitSet bitsetRetransform(IBitSet bitset) { IBitSet valid = LongBitSet.FACTORY.create(); // TODO: check trivial for (int i = bitset.nextSetBit(0); i >= 0; i = bitset.nextSetBit(i + 1)) { valid.set(indexes[i].intValue()); } return valid; } public int retransform(int i) { return indexes[i].intValue(); } public IBitSet bitsetTransform(IBitSet bitset) { IBitSet bitset2 = LongBitSet.FACTORY.create(); for (Integer i : indexes) { if (bitset.get(indexes[i.intValue()].intValue())) { bitset2.set(i.intValue()); } } return bitset2; } public Collection<IBitSet> transform(Collection<IBitSet> bitsets) { return bitsets.stream().map(bitset -> bitsetTransform(bitset)).collect(Collectors.toList()); } public Collection<IBitSet> retransform(Set<IBitSet> bitsets) { return bitsets.stream().map(bitset -> bitsetRetransform(bitset)).collect(Collectors.toList()); } }
412
0.562382
1
0.562382
game-dev
MEDIA
0.180542
game-dev
0.705334
1
0.705334
amethyst/rustrogueliketutorial
12,155
chapter-57a-spatial/src/map_builders/prefab_builder/mod.rs
use super::{InitialMapBuilder, MetaMapBuilder, BuilderMap, TileType, Position}; use rltk::RandomNumberGenerator; pub mod prefab_levels; pub mod prefab_sections; pub mod prefab_rooms; use std::collections::HashSet; #[derive(PartialEq, Copy, Clone)] #[allow(dead_code)] pub enum PrefabMode { RexLevel{ template : &'static str }, Constant{ level : prefab_levels::PrefabLevel }, Sectional{ section : prefab_sections::PrefabSection }, RoomVaults } #[allow(dead_code)] pub struct PrefabBuilder { mode: PrefabMode } impl MetaMapBuilder for PrefabBuilder { fn build_map(&mut self, rng: &mut rltk::RandomNumberGenerator, build_data : &mut BuilderMap) { self.build(rng, build_data); } } impl InitialMapBuilder for PrefabBuilder { #[allow(dead_code)] fn build_map(&mut self, rng: &mut rltk::RandomNumberGenerator, build_data : &mut BuilderMap) { self.build(rng, build_data); } } impl PrefabBuilder { #[allow(dead_code)] pub fn new() -> Box<PrefabBuilder> { Box::new(PrefabBuilder{ mode : PrefabMode::RoomVaults, }) } #[allow(dead_code)] pub fn rex_level(template : &'static str) -> Box<PrefabBuilder> { Box::new(PrefabBuilder{ mode : PrefabMode::RexLevel{ template }, }) } #[allow(dead_code)] pub fn constant(level : prefab_levels::PrefabLevel) -> Box<PrefabBuilder> { Box::new(PrefabBuilder{ mode : PrefabMode::Constant{ level }, }) } #[allow(dead_code)] pub fn sectional(section : prefab_sections::PrefabSection) -> Box<PrefabBuilder> { Box::new(PrefabBuilder{ mode : PrefabMode::Sectional{ section }, }) } #[allow(dead_code)] pub fn vaults() -> Box<PrefabBuilder> { Box::new(PrefabBuilder{ mode : PrefabMode::RoomVaults, }) } fn build(&mut self, rng : &mut RandomNumberGenerator, build_data : &mut BuilderMap) { match self.mode { PrefabMode::RexLevel{template} => self.load_rex_map(&template, build_data), PrefabMode::Constant{level} => self.load_ascii_map(&level, build_data), PrefabMode::Sectional{section} => self.apply_sectional(&section, rng, build_data), PrefabMode::RoomVaults => self.apply_room_vaults(rng, build_data) } build_data.take_snapshot(); } fn char_to_map(&mut self, ch : char, idx: usize, build_data : &mut BuilderMap) { match ch { ' ' => build_data.map.tiles[idx] = TileType::Floor, '#' => build_data.map.tiles[idx] = TileType::Wall, '@' => { let x = idx as i32 % build_data.map.width; let y = idx as i32 / build_data.map.width; build_data.map.tiles[idx] = TileType::Floor; build_data.starting_position = Some(Position{ x:x as i32, y:y as i32 }); } '>' => build_data.map.tiles[idx] = TileType::DownStairs, 'g' => { build_data.map.tiles[idx] = TileType::Floor; build_data.spawn_list.push((idx, "Goblin".to_string())); } 'o' => { build_data.map.tiles[idx] = TileType::Floor; build_data.spawn_list.push((idx, "Orc".to_string())); } '^' => { build_data.map.tiles[idx] = TileType::Floor; build_data.spawn_list.push((idx, "Bear Trap".to_string())); } '%' => { build_data.map.tiles[idx] = TileType::Floor; build_data.spawn_list.push((idx, "Rations".to_string())); } '!' => { build_data.map.tiles[idx] = TileType::Floor; build_data.spawn_list.push((idx, "Health Potion".to_string())); } _ => { rltk::console::log(format!("Unknown glyph loading map: {}", (ch as u8) as char)); } } } #[allow(dead_code)] fn load_rex_map(&mut self, path: &str, build_data : &mut BuilderMap) { let xp_file = rltk::rex::XpFile::from_resource(path).unwrap(); for layer in &xp_file.layers { for y in 0..layer.height { for x in 0..layer.width { let cell = layer.get(x, y).unwrap(); if x < build_data.map.width as usize && y < build_data.map.height as usize { let idx = build_data.map.xy_idx(x as i32, y as i32); // We're doing some nasty casting to make it easier to type things like '#' in the match self.char_to_map(cell.ch as u8 as char, idx, build_data); } } } } } fn read_ascii_to_vec(template : &str) -> Vec<char> { let mut string_vec : Vec<char> = template.chars().filter(|a| *a != '\r' && *a !='\n').collect(); for c in string_vec.iter_mut() { if *c as u8 == 160u8 { *c = ' '; } } string_vec } #[allow(dead_code)] fn load_ascii_map(&mut self, level: &prefab_levels::PrefabLevel, build_data : &mut BuilderMap) { let string_vec = PrefabBuilder::read_ascii_to_vec(level.template); let mut i = 0; for ty in 0..level.height { for tx in 0..level.width { if tx < build_data.map.width as usize && ty < build_data.map.height as usize { let idx = build_data.map.xy_idx(tx as i32, ty as i32); if i < string_vec.len() { self.char_to_map(string_vec[i], idx, build_data); } } i += 1; } } } fn apply_previous_iteration<F>(&mut self, mut filter: F, _rng: &mut RandomNumberGenerator, build_data : &mut BuilderMap) where F : FnMut(i32, i32) -> bool { let width = build_data.map.width; build_data.spawn_list.retain(|(idx, _name)| { let x = *idx as i32 % width; let y = *idx as i32 / width; filter(x, y) }); build_data.take_snapshot(); } #[allow(dead_code)] fn apply_sectional(&mut self, section : &prefab_sections::PrefabSection, rng: &mut RandomNumberGenerator, build_data : &mut BuilderMap) { use prefab_sections::*; let string_vec = PrefabBuilder::read_ascii_to_vec(section.template); // Place the new section let chunk_x; match section.placement.0 { HorizontalPlacement::Left => chunk_x = 0, HorizontalPlacement::Center => chunk_x = (build_data.map.width / 2) - (section.width as i32 / 2), HorizontalPlacement::Right => chunk_x = (build_data.map.width-1) - section.width as i32 } let chunk_y; match section.placement.1 { VerticalPlacement::Top => chunk_y = 0, VerticalPlacement::Center => chunk_y = (build_data.map.height / 2) - (section.height as i32 / 2), VerticalPlacement::Bottom => chunk_y = (build_data.map.height-1) - section.height as i32 } // Build the map self.apply_previous_iteration(|x,y| { x < chunk_x || x > (chunk_x + section.width as i32) || y < chunk_y || y > (chunk_y + section.height as i32) }, rng, build_data); let mut i = 0; for ty in 0..section.height { for tx in 0..section.width { if tx > 0 && tx < build_data.map.width as usize -1 && ty < build_data.map.height as usize -1 && ty > 0 { let idx = build_data.map.xy_idx(tx as i32 + chunk_x, ty as i32 + chunk_y); if i < string_vec.len() { self.char_to_map(string_vec[i], idx, build_data); } } i += 1; } } build_data.take_snapshot(); } fn apply_room_vaults(&mut self, rng : &mut RandomNumberGenerator, build_data : &mut BuilderMap) { use prefab_rooms::*; // Apply the previous builder, and keep all entities it spawns (for now) self.apply_previous_iteration(|_x,_y| true, rng, build_data); // Do we want a vault at all? let vault_roll = rng.roll_dice(1, 6) + build_data.map.depth; if vault_roll < 4 { return; } // Note that this is a place-holder and will be moved out of this function let master_vault_list = vec![TOTALLY_NOT_A_TRAP, CHECKERBOARD, SILLY_SMILE]; // Filter the vault list down to ones that are applicable to the current depth let mut possible_vaults : Vec<&PrefabRoom> = master_vault_list .iter() .filter(|v| { build_data.map.depth >= v.first_depth && build_data.map.depth <= v.last_depth }) .collect(); if possible_vaults.is_empty() { return; } // Bail out if there's nothing to build let n_vaults = i32::min(rng.roll_dice(1, 3), possible_vaults.len() as i32); let mut used_tiles : HashSet<usize> = HashSet::new(); for _i in 0..n_vaults { let vault_index = if possible_vaults.len() == 1 { 0 } else { (rng.roll_dice(1, possible_vaults.len() as i32)-1) as usize }; let vault = possible_vaults[vault_index]; // We'll make a list of places in which the vault could fit let mut vault_positions : Vec<Position> = Vec::new(); let mut idx = 0usize; loop { let x = (idx % build_data.map.width as usize) as i32; let y = (idx / build_data.map.width as usize) as i32; // Check that we won't overflow the map if x > 1 && (x+vault.width as i32) < build_data.map.width-2 && y > 1 && (y+vault.height as i32) < build_data.map.height-2 { let mut possible = true; for ty in 0..vault.height as i32 { for tx in 0..vault.width as i32 { let idx = build_data.map.xy_idx(tx + x, ty + y); if build_data.map.tiles[idx] != TileType::Floor { possible = false; } if used_tiles.contains(&idx) { possible = false; } } } if possible { vault_positions.push(Position{ x,y }); break; } } idx += 1; if idx >= build_data.map.tiles.len()-1 { break; } } if !vault_positions.is_empty() { let pos_idx = if vault_positions.len()==1 { 0 } else { (rng.roll_dice(1, vault_positions.len() as i32)-1) as usize }; let pos = &vault_positions[pos_idx]; let chunk_x = pos.x; let chunk_y = pos.y; let width = build_data.map.width; // The borrow checker really doesn't like it let height = build_data.map.height; // when we access `self` inside the `retain` build_data.spawn_list.retain(|e| { let idx = e.0 as i32; let x = idx % width; let y = idx / height; x < chunk_x || x > chunk_x + vault.width as i32 || y < chunk_y || y > chunk_y + vault.height as i32 }); let string_vec = PrefabBuilder::read_ascii_to_vec(vault.template); let mut i = 0; for ty in 0..vault.height { for tx in 0..vault.width { let idx = build_data.map.xy_idx(tx as i32 + chunk_x, ty as i32 + chunk_y); if i < string_vec.len() { self.char_to_map(string_vec[i], idx, build_data); } used_tiles.insert(idx); i += 1; } } build_data.take_snapshot(); possible_vaults.remove(vault_index); } } } }
412
0.921408
1
0.921408
game-dev
MEDIA
0.916216
game-dev
0.92682
1
0.92682
qnpiiz/rich-2.0
16,595
src/main/java/net/minecraft/world/Explosion.java
package net.minecraft.world; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.mojang.datafixers.util.Pair; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.Set; import javax.annotation.Nullable; import net.minecraft.block.AbstractFireBlock; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.enchantment.ProtectionEnchantment; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.item.ItemEntity; import net.minecraft.entity.item.TNTEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.projectile.ProjectileEntity; import net.minecraft.fluid.FluidState; import net.minecraft.item.ItemStack; import net.minecraft.loot.LootContext; import net.minecraft.loot.LootParameters; import net.minecraft.particles.ParticleTypes; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.DamageSource; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvents; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.RayTraceContext; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.vector.Vector3d; import net.minecraft.world.server.ServerWorld; public class Explosion { private static final ExplosionContext DEFAULT_CONTEXT = new ExplosionContext(); private final boolean causesFire; private final Explosion.Mode mode; private final Random random = new Random(); private final World world; private final double x; private final double y; private final double z; @Nullable private final Entity exploder; private final float size; private final DamageSource damageSource; private final ExplosionContext context; private final List<BlockPos> affectedBlockPositions = Lists.newArrayList(); private final Map<PlayerEntity, Vector3d> playerKnockbackMap = Maps.newHashMap(); public Explosion(World worldIn, @Nullable Entity entityIn, double x, double y, double z, float size, List<BlockPos> affectedPositions) { this(worldIn, entityIn, x, y, z, size, false, Explosion.Mode.DESTROY, affectedPositions); } public Explosion(World worldIn, @Nullable Entity exploderIn, double xIn, double yIn, double zIn, float sizeIn, boolean causesFireIn, Explosion.Mode modeIn, List<BlockPos> affectedBlockPositionsIn) { this(worldIn, exploderIn, xIn, yIn, zIn, sizeIn, causesFireIn, modeIn); this.affectedBlockPositions.addAll(affectedBlockPositionsIn); } public Explosion(World worldIn, @Nullable Entity exploderIn, double xIn, double yIn, double zIn, float sizeIn, boolean causesFireIn, Explosion.Mode modeIn) { this(worldIn, exploderIn, (DamageSource)null, (ExplosionContext)null, xIn, yIn, zIn, sizeIn, causesFireIn, modeIn); } public Explosion(World world, @Nullable Entity exploder, @Nullable DamageSource source, @Nullable ExplosionContext context, double x, double y, double z, float size, boolean causesFire, Explosion.Mode mode) { this.world = world; this.exploder = exploder; this.size = size; this.x = x; this.y = y; this.z = z; this.causesFire = causesFire; this.mode = mode; this.damageSource = source == null ? DamageSource.causeExplosionDamage(this) : source; this.context = context == null ? this.getEntityExplosionContext(exploder) : context; } private ExplosionContext getEntityExplosionContext(@Nullable Entity entity) { return (ExplosionContext)(entity == null ? DEFAULT_CONTEXT : new EntityExplosionContext(entity)); } public static float getBlockDensity(Vector3d explosionVector, Entity entity) { AxisAlignedBB axisalignedbb = entity.getBoundingBox(); double d0 = 1.0D / ((axisalignedbb.maxX - axisalignedbb.minX) * 2.0D + 1.0D); double d1 = 1.0D / ((axisalignedbb.maxY - axisalignedbb.minY) * 2.0D + 1.0D); double d2 = 1.0D / ((axisalignedbb.maxZ - axisalignedbb.minZ) * 2.0D + 1.0D); double d3 = (1.0D - Math.floor(1.0D / d0) * d0) / 2.0D; double d4 = (1.0D - Math.floor(1.0D / d2) * d2) / 2.0D; if (!(d0 < 0.0D) && !(d1 < 0.0D) && !(d2 < 0.0D)) { int i = 0; int j = 0; for (float f = 0.0F; f <= 1.0F; f = (float)((double)f + d0)) { for (float f1 = 0.0F; f1 <= 1.0F; f1 = (float)((double)f1 + d1)) { for (float f2 = 0.0F; f2 <= 1.0F; f2 = (float)((double)f2 + d2)) { double d5 = MathHelper.lerp((double)f, axisalignedbb.minX, axisalignedbb.maxX); double d6 = MathHelper.lerp((double)f1, axisalignedbb.minY, axisalignedbb.maxY); double d7 = MathHelper.lerp((double)f2, axisalignedbb.minZ, axisalignedbb.maxZ); Vector3d vector3d = new Vector3d(d5 + d3, d6, d7 + d4); if (entity.world.rayTraceBlocks(new RayTraceContext(vector3d, explosionVector, RayTraceContext.BlockMode.COLLIDER, RayTraceContext.FluidMode.NONE, entity)).getType() == RayTraceResult.Type.MISS) { ++i; } ++j; } } } return (float)i / (float)j; } else { return 0.0F; } } /** * Does the first part of the explosion (destroy blocks) */ public void doExplosionA() { Set<BlockPos> set = Sets.newHashSet(); int i = 16; for (int j = 0; j < 16; ++j) { for (int k = 0; k < 16; ++k) { for (int l = 0; l < 16; ++l) { if (j == 0 || j == 15 || k == 0 || k == 15 || l == 0 || l == 15) { double d0 = (double)((float)j / 15.0F * 2.0F - 1.0F); double d1 = (double)((float)k / 15.0F * 2.0F - 1.0F); double d2 = (double)((float)l / 15.0F * 2.0F - 1.0F); double d3 = Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2); d0 = d0 / d3; d1 = d1 / d3; d2 = d2 / d3; float f = this.size * (0.7F + this.world.rand.nextFloat() * 0.6F); double d4 = this.x; double d6 = this.y; double d8 = this.z; for (float f1 = 0.3F; f > 0.0F; f -= 0.22500001F) { BlockPos blockpos = new BlockPos(d4, d6, d8); BlockState blockstate = this.world.getBlockState(blockpos); FluidState fluidstate = this.world.getFluidState(blockpos); Optional<Float> optional = this.context.getExplosionResistance(this, this.world, blockpos, blockstate, fluidstate); if (optional.isPresent()) { f -= (optional.get() + 0.3F) * 0.3F; } if (f > 0.0F && this.context.canExplosionDestroyBlock(this, this.world, blockpos, blockstate, f)) { set.add(blockpos); } d4 += d0 * (double)0.3F; d6 += d1 * (double)0.3F; d8 += d2 * (double)0.3F; } } } } } this.affectedBlockPositions.addAll(set); float f2 = this.size * 2.0F; int k1 = MathHelper.floor(this.x - (double)f2 - 1.0D); int l1 = MathHelper.floor(this.x + (double)f2 + 1.0D); int i2 = MathHelper.floor(this.y - (double)f2 - 1.0D); int i1 = MathHelper.floor(this.y + (double)f2 + 1.0D); int j2 = MathHelper.floor(this.z - (double)f2 - 1.0D); int j1 = MathHelper.floor(this.z + (double)f2 + 1.0D); List<Entity> list = this.world.getEntitiesWithinAABBExcludingEntity(this.exploder, new AxisAlignedBB((double)k1, (double)i2, (double)j2, (double)l1, (double)i1, (double)j1)); Vector3d vector3d = new Vector3d(this.x, this.y, this.z); for (int k2 = 0; k2 < list.size(); ++k2) { Entity entity = list.get(k2); if (!entity.isImmuneToExplosions()) { double d12 = (double)(MathHelper.sqrt(entity.getDistanceSq(vector3d)) / f2); if (d12 <= 1.0D) { double d5 = entity.getPosX() - this.x; double d7 = (entity instanceof TNTEntity ? entity.getPosY() : entity.getPosYEye()) - this.y; double d9 = entity.getPosZ() - this.z; double d13 = (double)MathHelper.sqrt(d5 * d5 + d7 * d7 + d9 * d9); if (d13 != 0.0D) { d5 = d5 / d13; d7 = d7 / d13; d9 = d9 / d13; double d14 = (double)getBlockDensity(vector3d, entity); double d10 = (1.0D - d12) * d14; entity.attackEntityFrom(this.getDamageSource(), (float)((int)((d10 * d10 + d10) / 2.0D * 7.0D * (double)f2 + 1.0D))); double d11 = d10; if (entity instanceof LivingEntity) { d11 = ProtectionEnchantment.getBlastDamageReduction((LivingEntity)entity, d10); } entity.setMotion(entity.getMotion().add(d5 * d11, d7 * d11, d9 * d11)); if (entity instanceof PlayerEntity) { PlayerEntity playerentity = (PlayerEntity)entity; if (!playerentity.isSpectator() && (!playerentity.isCreative() || !playerentity.abilities.isFlying)) { this.playerKnockbackMap.put(playerentity, new Vector3d(d5 * d10, d7 * d10, d9 * d10)); } } } } } } } /** * Does the second part of the explosion (sound, particles, drop spawn) */ public void doExplosionB(boolean spawnParticles) { if (this.world.isRemote) { this.world.playSound(this.x, this.y, this.z, SoundEvents.ENTITY_GENERIC_EXPLODE, SoundCategory.BLOCKS, 4.0F, (1.0F + (this.world.rand.nextFloat() - this.world.rand.nextFloat()) * 0.2F) * 0.7F, false); } boolean flag = this.mode != Explosion.Mode.NONE; if (spawnParticles) { if (!(this.size < 2.0F) && flag) { this.world.addParticle(ParticleTypes.EXPLOSION_EMITTER, this.x, this.y, this.z, 1.0D, 0.0D, 0.0D); } else { this.world.addParticle(ParticleTypes.EXPLOSION, this.x, this.y, this.z, 1.0D, 0.0D, 0.0D); } } if (flag) { ObjectArrayList<Pair<ItemStack, BlockPos>> objectarraylist = new ObjectArrayList<>(); Collections.shuffle(this.affectedBlockPositions, this.world.rand); for (BlockPos blockpos : this.affectedBlockPositions) { BlockState blockstate = this.world.getBlockState(blockpos); Block block = blockstate.getBlock(); if (!blockstate.isAir()) { BlockPos blockpos1 = blockpos.toImmutable(); this.world.getProfiler().startSection("explosion_blocks"); if (block.canDropFromExplosion(this) && this.world instanceof ServerWorld) { TileEntity tileentity = block.isTileEntityProvider() ? this.world.getTileEntity(blockpos) : null; LootContext.Builder lootcontext$builder = (new LootContext.Builder((ServerWorld)this.world)).withRandom(this.world.rand).withParameter(LootParameters.field_237457_g_, Vector3d.copyCentered(blockpos)).withParameter(LootParameters.TOOL, ItemStack.EMPTY).withNullableParameter(LootParameters.BLOCK_ENTITY, tileentity).withNullableParameter(LootParameters.THIS_ENTITY, this.exploder); if (this.mode == Explosion.Mode.DESTROY) { lootcontext$builder.withParameter(LootParameters.EXPLOSION_RADIUS, this.size); } blockstate.getDrops(lootcontext$builder).forEach((stack) -> { handleExplosionDrops(objectarraylist, stack, blockpos1); }); } this.world.setBlockState(blockpos, Blocks.AIR.getDefaultState(), 3); block.onExplosionDestroy(this.world, blockpos, this); this.world.getProfiler().endSection(); } } for (Pair<ItemStack, BlockPos> pair : objectarraylist) { Block.spawnAsEntity(this.world, pair.getSecond(), pair.getFirst()); } } if (this.causesFire) { for (BlockPos blockpos2 : this.affectedBlockPositions) { if (this.random.nextInt(3) == 0 && this.world.getBlockState(blockpos2).isAir() && this.world.getBlockState(blockpos2.down()).isOpaqueCube(this.world, blockpos2.down())) { this.world.setBlockState(blockpos2, AbstractFireBlock.getFireForPlacement(this.world, blockpos2)); } } } } private static void handleExplosionDrops(ObjectArrayList<Pair<ItemStack, BlockPos>> dropPositionArray, ItemStack stack, BlockPos pos) { int i = dropPositionArray.size(); for (int j = 0; j < i; ++j) { Pair<ItemStack, BlockPos> pair = dropPositionArray.get(j); ItemStack itemstack = pair.getFirst(); if (ItemEntity.canMergeStacks(itemstack, stack)) { ItemStack itemstack1 = ItemEntity.mergeStacks(itemstack, stack, 16); dropPositionArray.set(j, Pair.of(itemstack1, pair.getSecond())); if (stack.isEmpty()) { return; } } } dropPositionArray.add(Pair.of(stack, pos)); } public DamageSource getDamageSource() { return this.damageSource; } public Map<PlayerEntity, Vector3d> getPlayerKnockbackMap() { return this.playerKnockbackMap; } @Nullable /** * Returns either the entity that placed the explosive block, the entity that caused the explosion or null. */ public LivingEntity getExplosivePlacedBy() { if (this.exploder == null) { return null; } else if (this.exploder instanceof TNTEntity) { return ((TNTEntity)this.exploder).getTntPlacedBy(); } else if (this.exploder instanceof LivingEntity) { return (LivingEntity)this.exploder; } else { if (this.exploder instanceof ProjectileEntity) { Entity entity = ((ProjectileEntity)this.exploder).func_234616_v_(); if (entity instanceof LivingEntity) { return (LivingEntity)entity; } } return null; } } public void clearAffectedBlockPositions() { this.affectedBlockPositions.clear(); } public List<BlockPos> getAffectedBlockPositions() { return this.affectedBlockPositions; } public static enum Mode { NONE, BREAK, DESTROY; } }
412
0.881412
1
0.881412
game-dev
MEDIA
0.96297
game-dev
0.949475
1
0.949475
microsoft/MixedReality-SpectatorView
2,268
src/SpectatorView.Unity/Assets/SpatialAlignment/Scripts/Common/SpatialCoordinateUnityBase.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Numerics; namespace Microsoft.MixedReality.SpatialAlignment { /// <summary> /// Helper base class for implementations of <see cref="ISpatialCoordinate"/>. /// </summary> /// <typeparam name="TKey">The type of Id for this coordinate.</typeparam> public abstract class SpatialCoordinateUnityBase<TKey> : SpatialCoordinateBase<TKey> { protected UnityEngine.Matrix4x4 worldMatrix = UnityEngine.Matrix4x4.identity; public SpatialCoordinateUnityBase(TKey id) : base(id) { } public sealed override Vector3 CoordinateToWorldSpace(Vector3 vector) => CoordinateToWorldSpace(vector.AsUnityVector()).AsNumericsVector(); public sealed override Quaternion CoordinateToWorldSpace(Quaternion quaternion) => CoordinateToWorldSpace(quaternion.AsUnityQuaternion()).AsNumericsQuaternion(); public sealed override Vector3 WorldToCoordinateSpace(Vector3 vector) => WorldToCoordinateSpace(vector.AsUnityVector()).AsNumericsVector(); public sealed override Quaternion WorldToCoordinateSpace(Quaternion quaternion) => WorldToCoordinateSpace(quaternion.AsUnityQuaternion()).AsNumericsQuaternion(); protected void SetCoordinateWorldTransform(UnityEngine.Vector3 worldPosition, UnityEngine.Quaternion worldRotation) { worldMatrix = UnityEngine.Matrix4x4.TRS(worldPosition, worldRotation, UnityEngine.Vector3.one); } /// <inheritdoc /> protected virtual UnityEngine.Vector3 CoordinateToWorldSpace(UnityEngine.Vector3 vector) => worldMatrix.MultiplyPoint(vector); /// <inheritdoc /> protected virtual UnityEngine.Quaternion CoordinateToWorldSpace(UnityEngine.Quaternion quaternion) => worldMatrix.rotation * quaternion; /// <inheritdoc /> protected virtual UnityEngine.Vector3 WorldToCoordinateSpace(UnityEngine.Vector3 vector) => worldMatrix.inverse.MultiplyPoint(vector); /// <inheritdoc /> protected virtual UnityEngine.Quaternion WorldToCoordinateSpace(UnityEngine.Quaternion quaternion) => worldMatrix.inverse.rotation * quaternion; } }
412
0.523994
1
0.523994
game-dev
MEDIA
0.726421
game-dev
0.51105
1
0.51105
typedb/typedb-driver
1,689
docs/modules/ROOT/partials/c/concept/roleplayer.adoc
[#_methods_concept_roleplayer] === roleplayer [#_Struct_RolePlayer] ==== Struct RolePlayer A pair representing the concept and the role it plays in a relation. The result of relation_get_role_players(Transaction*, Concept*) [#_Struct_RolePlayerIterator] ==== Struct RolePlayerIterator An iterator over ``RolePlayer`` pairs returned by relation_get_role_players(Transaction*, Concept*) [#_role_player_drop] ==== role_player_drop [source,cpp] ---- void role_player_drop(struct RolePlayer* role_player) ---- Frees the native rust ``RolePlayer`` object [caption=""] .Returns `void` [#_role_player_get_player] ==== role_player_get_player [source,cpp] ---- struct Concept* role_player_get_player(const struct RolePlayer* role_player) ---- Returns the ``Concept`` which plays the role in the ``RolePlayer`` [caption=""] .Returns `struct Concept*` [#_role_player_get_role_type] ==== role_player_get_role_type [source,cpp] ---- struct Concept* role_player_get_role_type(const struct RolePlayer* role_player) ---- Returns the role-type played by the ``RolePlayer`` [caption=""] .Returns `struct Concept*` [#_role_player_iterator_drop] ==== role_player_iterator_drop [source,cpp] ---- void role_player_iterator_drop(struct RolePlayerIterator* it) ---- Frees the native rust ``RolePlayerIterator`` object [caption=""] .Returns `void` [#_role_player_iterator_next] ==== role_player_iterator_next [source,cpp] ---- struct RolePlayer* role_player_iterator_next(struct RolePlayerIterator* it) ---- Forwards the ``RolePlayerIterator`` and returns the next ``RolePlayer`` if it exists, or null if there are no more elements. [caption=""] .Returns `struct RolePlayer*`
412
0.671108
1
0.671108
game-dev
MEDIA
0.953622
game-dev
0.578344
1
0.578344
CordyJ/Open-NiCad
1,733
tests/regression/systems/cs/Castle-SourceCode/Tools/NVelocity/src/NVelocity/Commons/Collections/StringTokenizer.cs
namespace Commons.Collections { using System; using System.Collections; public class StringTokenizer { private ArrayList elements; private string source; //The tokenizer uses the default delimiter set: the space character, the tab character, the newline character, and the carriage-return character private string delimiters = " \t\n\r"; public StringTokenizer(string source) { elements = new ArrayList(); elements.AddRange(source.Split(delimiters.ToCharArray())); RemoveEmptyStrings(); this.source = source; } public StringTokenizer(string source, string delimiters) { elements = new ArrayList(); this.delimiters = delimiters; elements.AddRange(source.Split(this.delimiters.ToCharArray())); RemoveEmptyStrings(); this.source = source; } public int Count { get { return (elements.Count); } } public virtual bool HasMoreTokens() { return (elements.Count > 0); } public virtual string NextToken() { string result; if (source == "") { throw new Exception(); } else { elements = new ArrayList(); elements.AddRange(source.Split(delimiters.ToCharArray())); RemoveEmptyStrings(); result = (string) elements[0]; elements.RemoveAt(0); source = source.Replace(result, ""); source = source.TrimStart(delimiters.ToCharArray()); return result; } } public string NextToken(string delimiters) { this.delimiters = delimiters; return NextToken(); } private void RemoveEmptyStrings() { //VJ++ does not treat empty strings as tokens for(int index = 0; index < elements.Count; index++) if ((string) elements[index] == "") { elements.RemoveAt(index); index--; } } } }
412
0.85448
1
0.85448
game-dev
MEDIA
0.246362
game-dev
0.96242
1
0.96242
Ogmo-Editor-3/OgmoEditor3-CE
3,263
src/util/Calc.hx
package util; class Calc { public static var DTR:Float = Math.PI / 180; public static var RTD:Float = 180 / Math.PI; public static function clamp(num:Float, min:Float, max:Float):Float { return Math.max(Math.min(num, max), min); } public static function snap(num:Float, interval:Float, ?offset:Float):Float { if (offset == null) offset = 0; return Math.round((num - offset) / interval) * interval + offset; } public static function snapCeil(num:Float, interval:Float, ?offset:Float):Float { if (offset == null) offset = 0; return Math.ceil((num - offset) / interval) * interval + offset; } public static function snapFloor(num:Float, interval:Float, ?offset:Float):Float { if (offset == null) offset = 0; return Math.floor((num - offset) / interval) * interval + offset; } public static function sign(num:Float):Int { if (num < 0) return -1; else if (num > 0) return 1; else return 0; } public static function cloneArray<T>(array:Array<T>):Array<T> { return array.slice(0); } public static function createArray2D<T>(lengthA:Int, lengthB:Int, val:T):Array<Array<T>> { var ret:Array<Array<T>> = []; for (i in 0...lengthA) { var row:Array<T> = []; for (j in 0...lengthB) row.push(val); ret.push(row); } return ret; } public static function cloneArray2D<T>(array:Array<Array<T>>):Array<Array<T>> { var ret:Array<Array<T>> = []; for (i in 0...array.length) ret.push(Calc.cloneArray(array[i])); return ret; } public static function bresenham(x1:Int, y1:Int, x2:Int, y2:Int):Array<Vector> { // TODO - check this out? -01010111 // Not 100% sure if this is foolproof, might infinite loop sometimes? -kp // returns an array of points for now -kp var points:Array<Vector> = []; /* Haxe has Ints :) -01010111 // Use ints only for this, I think? -kp x1 = Math.round(x1); x2 = Math.round(x2); y1 = Math.round(y1); y2 = Math.round(y2);*/ // Bresenham's Algorithm var dx:Float = Math.abs(x2 - x1); var dy:Float = Math.abs(y2 - y1); var sx:Int = (x1 < x2) ? 1 : -1; var sy:Int = (y1 < y2) ? 1 : -1; var err:Float = dx - dy; while (true) { points.push(new Vector(x1, y1)); if (x1 == x2 && y1 == y2) break; var e2:Float = err * 2; if (e2 > -dy) { err -= dy; x1 += sx; } if (e2 < dx) { err += dx; y1 += sy; } } return points; } public static function angleTo(from:Vector, to:Vector):Float { return Math.atan2(to.y - from.y, to.x - from.x); } public static function wrapAngle(angle:Float):Float { while (angle < -Math.PI) angle += Math.PI * 2; while (angle > Math.PI) angle -= Math.PI * 2; return angle; } public static function angleDiff(a:Float, b:Float):Float { return Calc.wrapAngle(b - a); } public static function angleLerp(a:Float, b:Float, t:Float):Float { return a + Calc.angleDiff(a, b) * t; } public static function angleApproach(from:Float, to:Float, max:Float):Float { return from + Calc.clamp(Calc.angleDiff(from, to), -max, max); } public static function roundTo( number:Float, precision:Int):Float { var num = number; num = num * Math.pow(10, precision); num = Math.round( num ) / Math.pow(10, precision); return num; } }
412
0.796347
1
0.796347
game-dev
MEDIA
0.438156
game-dev,graphics-rendering
0.919795
1
0.919795
alexkulya/pandaria_5.4.8
34,094
src/server/scripts/Pandaria/Scenarios/BrewingStorm/brewing_storm.cpp
/* * This file is part of the Pandaria 5.4.8 Project. See THANKS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "GameObjectAI.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "GridNotifiers.h" #include "brewing_storm.h" enum Spells { SPELL_BLANSHES_BOOMER_BREW_POWER_BAR = 112038, SPELL_LIGHTNING_IMPACT = 111544, // triggered by lightning channel SPELL_ON_FIRE = 111995, // impale kegs SPELL_BREW = 112040, // cosmetic brew bubbles... SPELL_LIGHTNING_CHANNEL = 111828, SPELL_EXTINGUISHING = 111961, SPELL_BLANCHES_ELIXIR_OF_REPLENISHMENT = 114663, SPELL_HONORARY_BREWMASTER_KEG = 136288, SPELL_BOOMER_BREW_STRIKE_BUTTON = 115101, // at 3td chapter SPELL_BOOMER_BREW_STRIKE = 115058, SPELL_VILETONGUE_STING = 127280, SPELL_LEAPING_CLEAVE = 132247, SPELL_TORCH_TOSS = 141771, SPELL_WIND_SLASH = 131594, SPELL_WIND_SLASH_AUR = 131596, SPELL_SWAMP_SMASH = 115013, SPELL_EARTH_SHATTERING = 122142, SPELL_BLANCHES_ELEXIR_EFF = 121951, SPELL_PERFECT_POUR_ACHIEV = 114876, SPELL_PARTY_OF_SIX_ACHIEV = 127411, }; enum Events { EVENT_PREPARE_TO_STORM = 1, EVENT_LIGHTNING_ROD, EVENT_VILETONGUE_SAUROKS, EVENT_CHAPTER_2_PREPARE, EVENT_ESCORT, EVENT_TORCH_TOSS, EVENT_BLANCHE_POTION, EVENT_BREATHING, EVENT_TOSS, EVENT_WIND_SLASH, EVENT_SWAMP_SMASH, EVENT_EARTH_SHATTERING, }; enum Yells { TALK_INTRO, TALK_KEGS, TALK_LIGHTNING_STRIKE, TALK_SAUROKS, TALK_STORM, TALK_POTION_ANN, TALK_LIGHTNING_HIT_PLAYER, TALK_CHAPTER_2_PREPARE, TALK_CHAPTER_2_OUTRO, TALK_CHAPTER_2_BEGUN, TALK_SAUROKS_AT_HIGH_CLIFF, TALK_PLAYER_LOW, TALK_AT_CLIFF, TALK_AT_WALL_CLIFF, TALK_JOKE, TALK_BREATHING, TALK_READY_TO_MOVE, TALK_CHAPTER_THREE_INTRO, TALK_CHAPTER_THREE_BEGIN, TALK_BOOMERS_BREW_ANN, TALK_BOROKHALA_INTRO, TALK_BOROKHALA_LOW, TALK_SCENARIO_END, }; // Brewmaster Blanche 58740 class npc_brewmaster_blanche : public CreatureScript { public: npc_brewmaster_blanche() : CreatureScript("npc_brewmaster_blanche") { } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) { ClearGossipMenuFor(player); switch (action) { case GOSSIP_ACTION_INFO_DEF + 1: creature->AI()->DoAction(ACTION_MAKE_BOOMERS_BREW); creature->RemoveFlag(UNIT_FIELD_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); break; case GOSSIP_ACTION_INFO_DEF + 2: creature->AI()->DoAction(ACTION_ROAD_TO_THUNDERPAW); creature->RemoveFlag(UNIT_FIELD_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); break; case GOSSIP_ACTION_INFO_DEF + 3: creature->AI()->DoAction(ACTION_SAVE_THUNDERPAW_REFUGE); creature->RemoveFlag(UNIT_FIELD_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); break; } CloseGossipMenuFor(player); return true; } bool OnGossipHello(Player* player, Creature* creature) { if (InstanceScript* instance = creature->GetInstanceScript()) { if (instance->GetData(DATA_MAKE_BOOMERS_BREW) < DONE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, TEXT_CHAPTER_MAKE_BOOMERS_BREW, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); if (instance->GetData(DATA_ROAD_TO_THUNDERPAW) < DONE && instance->GetData(DATA_ROAD_TO_THUNDERPAW - 1) == DONE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, TEXT_CHAPTER_ROAD_TO_THUNDERPAW, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); if (instance->GetData(DATA_SAVE_THUNDERPAW_REFUGE) < DONE && instance->GetData(DATA_SAVE_THUNDERPAW_REFUGE - 1) == DONE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, TEXT_CHAPTER_SAVE_THUNDERPAW_REFUGE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); } SendGossipMenuFor(player, player->GetGossipTextId(creature), creature->GetGUID()); return true; } struct npc_brewmaster_blancheAI : public ScriptedAI { npc_brewmaster_blancheAI(Creature* creature) : ScriptedAI(creature), summons(me) { } SummonList summons; EventMap events, nonCombatEvents; InstanceScript* instance; uint32 wp; bool SayRoods, SaySauroks, SayBrewBar; bool inSecondStage; uint32 sauroksCount; uint32 allowAchiev; uint32 partyofSix; bool hasLaunched; void IsSummonedBy(Unit* summoner) override { } void InitializeAI() override { wp = 0; sauroksCount = 0; allowAchiev = 1; partyofSix = 1; SayRoods = false; SaySauroks = false; SayBrewBar = false; inSecondStage = false; hasLaunched = false; instance = me->GetInstanceScript(); me->SetFlag(UNIT_FIELD_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); Reset(); } void Reset() override { me->GetMap()->SetWorldState(WORLDSTATE_PERFECT_POUR, 1); me->GetMap()->SetWorldState(WORLDSTATE_PARTY_OF_SIX, 1); // controlled by spells me->SetWalk(false); } void DoAction(int32 actionId) override { switch (actionId) { case ACTION_MAKE_BOOMERS_BREW: Talk(TALK_INTRO); SendBoomersBrewBarToPlayers(); me->RemoveFlag(UNIT_FIELD_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); nonCombatEvents.ScheduleEvent(EVENT_PREPARE_TO_STORM, 4500); nonCombatEvents.ScheduleEvent(EVENT_BLANCHE_POTION, urand(49 * IN_MILLISECONDS, 59 * IN_MILLISECONDS)); break; case ACTION_BREW_POWER: SendBoomersBrewBarToPlayers(true); break; case ACTION_CHAPTER_ONE_COMPLETED: SendBoomersBrewBarToPlayers(false, true); nonCombatEvents.Reset(); Talk(TALK_CHAPTER_2_PREPARE); Talk(TALK_CHAPTER_2_OUTRO); if (instance) instance->SetData(DATA_MAKE_BOOMERS_BREW, DONE); nonCombatEvents.ScheduleEvent(EVENT_CHAPTER_2_PREPARE, 8000); break; case ACTION_ROAD_TO_THUNDERPAW: if (hasLaunched) break; hasLaunched = true; //Talk() me->SetFlag(UNIT_FIELD_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); sauroksCount = 0; nonCombatEvents.ScheduleEvent(EVENT_ESCORT, 2000); break; case ACTION_SAVE_THUNDERPAW_REFUGE: //Talk(); me->SetFlag(UNIT_FIELD_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); nonCombatEvents.ScheduleEvent(EVENT_ESCORT, 2500); break; } } void JustSummoned(Creature* summon) override { summons.Summon(summon); if (!inSecondStage) return; sauroksCount++; } void SummonedCreatureDies(Creature* summon, Unit* /*killer*/) override { if (!inSecondStage) return; sauroksCount--; } uint32 GetData(uint32 type) const override { switch (type) { case TYPE_HIT_BY_ROAD: return allowAchiev; case TYPE_PARTY_OF_SIX: return partyofSix; } return 0; } void SetData(uint32 type, uint32 data) override { switch (type) { case TYPE_HIT_BY_ROAD: allowAchiev = data; break; case TYPE_PARTY_OF_SIX: partyofSix = data; break; } } void MovementInform(uint32 type, uint32 pointId) override { if (type != POINT_MOTION_TYPE) return; wp++; switch (pointId) { case 6: if (Creature* SkirmisherStalker = GetClosestCreatureWithEntry(me, NPC_VILETONGUE_STALKER, 35.0f, true)) SkirmisherStalker->AI()->DoAction(ACTION_VILETONGUE_AT_GROUND); if (Creature* raiderStalker = ObjectAccessor::GetCreature(*me, SelectAnyStalkerGUID(NPC_VILETONGUE_VEHICLE))) raiderStalker->AI()->DoAction(ACTION_VILETONGUE_AT_HILL); Talk(TALK_SAUROKS_AT_HIGH_CLIFF); nonCombatEvents.ScheduleEvent(EVENT_ESCORT, 5000); break; case 14: Talk(TALK_AT_CLIFF); if (Creature* SkirmisherStalker = GetClosestCreatureWithEntry(me, NPC_VILETONGUE_STALKER, 35.0f, true)) SkirmisherStalker->AI()->DoAction(ACTION_VILETONGUE_AT_GROUND); me->SetFacingTo(abs(me->GetOrientation() + M_PI / 2)); nonCombatEvents.ScheduleEvent(EVENT_ESCORT, 5000); break; case 15: if (Creature* SkirmisherStalker = GetClosestCreatureWithEntry(me, NPC_VILETONGUE_STALKER, 35.0f, true)) SkirmisherStalker->AI()->DoAction(ACTION_VILETONGUE_AT_GROUND); Talk(TALK_AT_WALL_CLIFF); nonCombatEvents.ScheduleEvent(EVENT_ESCORT, 5000); break; case 16: if (Creature* SkirmisherStalker = GetClosestCreatureWithEntry(me, NPC_VILETONGUE_STALKER, 35.0f, true)) SkirmisherStalker->AI()->DoAction(ACTION_VILETONGUE_AT_HILL); Talk(TALK_JOKE); nonCombatEvents.ScheduleEvent(EVENT_ESCORT, 5000); break; case 18: Talk(TALK_BREATHING); nonCombatEvents.ScheduleEvent(EVENT_BREATHING, 7.5 * IN_MILLISECONDS); break; case 34: me->SetFlag(UNIT_FIELD_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); Talk(TALK_CHAPTER_THREE_BEGIN); Talk(TALK_BOOMERS_BREW_ANN); if (instance) { instance->DoCastSpellOnPlayers(SPELL_BOOMER_BREW_STRIKE_BUTTON); instance->SetData(DATA_ROAD_TO_THUNDERPAW, DONE); } break; default: nonCombatEvents.ScheduleEvent(EVENT_ESCORT, urand(100, 200)); break; } } void EnterEvadeMode() override { ScriptedAI::EnterEvadeMode(); } void UpdateAI(uint32 diff) override { nonCombatEvents.Update(diff); if (HasChapterOneCompleted()) DoAction(ACTION_CHAPTER_ONE_COMPLETED); while (uint32 eventId = nonCombatEvents.ExecuteEvent()) { switch (eventId) { case EVENT_PREPARE_TO_STORM: Talk(TALK_KEGS); BrewOnKegs(); nonCombatEvents.ScheduleEvent(EVENT_LIGHTNING_ROD, 5000); nonCombatEvents.ScheduleEvent(EVENT_VILETONGUE_SAUROKS, urand(9000, 12000)); break; case EVENT_LIGHTNING_ROD: if (!SayRoods) { SayRoods = true; Talk(TALK_LIGHTNING_STRIKE); } if (Creature* selectedRod = ObjectAccessor::GetCreature(*me, SelectAnyStalkerGUID(NPC_LIGHTNING_ROD))) selectedRod->CastSpell(selectedRod, SPELL_LIGHTNING_CHANNEL, false); nonCombatEvents.ScheduleEvent(EVENT_LIGHTNING_ROD, urand(8000, 14000)); break; case EVENT_VILETONGUE_SAUROKS: if (!SaySauroks) { SaySauroks = true; Talk(TALK_SAUROKS); } if (Creature* SkirmisherStalker = GetClosestCreatureWithEntry(me, NPC_VILETONGUE_STALKER, 35.0f, true)) SkirmisherStalker->AI()->DoAction(ACTION_VILETONGUE_AT_GROUND); if (Creature* raiderStalker = ObjectAccessor::GetCreature(*me, SelectAnyStalkerGUID(NPC_VILETONGUE_VEHICLE))) raiderStalker->AI()->DoAction(ACTION_VILETONGUE_AT_HILL); if (instance && instance->GetData(DATA_MAKE_BOOMERS_BREW) < DONE) nonCombatEvents.ScheduleEvent(EVENT_VILETONGUE_SAUROKS, urand(35000, 40000)); break; case EVENT_CHAPTER_2_PREPARE: Talk(TALK_CHAPTER_2_BEGUN); me->SetFlag(UNIT_FIELD_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); nonCombatEvents.ScheduleEvent(EVENT_BLANCHE_POTION, urand(49 * IN_MILLISECONDS, 59 * IN_MILLISECONDS)); DoCast(me, SPELL_HONORARY_BREWMASTER_KEG); inSecondStage = true; break; case EVENT_ESCORT: if (sauroksCount) { nonCombatEvents.RescheduleEvent(EVENT_ESCORT, 1 * IN_MILLISECONDS); break; } me->GetMotionMaster()->MovementExpired(); if (wp < 35) me->GetMotionMaster()->MovePoint(wp, BlancheWaypoints[wp]); break; case EVENT_BLANCHE_POTION: if (Player* pItr = me->FindNearestPlayer(100.0f)) DoCast(pItr, SPELL_BLANCHES_ELIXIR_OF_REPLENISHMENT); Talk(TALK_POTION_ANN); nonCombatEvents.ScheduleEvent(EVENT_BLANCHE_POTION, urand(49 * IN_MILLISECONDS, 59 * IN_MILLISECONDS)); break; case EVENT_BREATHING: Talk(TALK_READY_TO_MOVE); nonCombatEvents.ScheduleEvent(EVENT_ESCORT, 1.5 * IN_MILLISECONDS); break; } } if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } private: void SendBoomersBrewBarToPlayers(bool update = false, bool remove = false) { std::list<Player*> PlayersInScenario; GetPlayerListInGrid(PlayersInScenario, me, 150.0f); for (auto&& itr : PlayersInScenario) if (!itr->HasAura(SPELL_BLANSHES_BOOMER_BREW_POWER_BAR)) me->AddAura(SPELL_BLANSHES_BOOMER_BREW_POWER_BAR, itr); if (update) for (auto&& itr : PlayersInScenario) if (itr->GetPower(POWER_ALTERNATE_POWER) < 100) itr->SetPower(POWER_ALTERNATE_POWER, itr->GetPower(POWER_ALTERNATE_POWER) + 5); if (remove) for (auto&& itr : PlayersInScenario) if (itr->HasAura(SPELL_BLANSHES_BOOMER_BREW_POWER_BAR)) itr->RemoveAura(SPELL_BLANSHES_BOOMER_BREW_POWER_BAR); } bool HasChapterOneCompleted() { if (Player* itr = me->FindNearestPlayer(100.0f)) // we need check anyone player { if (!SayBrewBar && (itr->GetPower(POWER_ALTERNATE_POWER) > 50)) { SayBrewBar = true; Talk(TALK_STORM); } if (itr->GetPower(POWER_ALTERNATE_POWER) == 100) return true; } return false; } uint64 SelectAnyStalkerGUID(uint32 npc_entry) { std::list<Creature*> StalkerList; GetCreatureListWithEntryInGrid(StalkerList, me, npc_entry, 30.0f); if (StalkerList.empty()) return 0; return Trinity::Containers::SelectRandomContainerElement(StalkerList)->GetGUID(); } void BrewOnKegs() { std::list<Creature*> BrewKegs; GetCreatureListWithEntryInGrid(BrewKegs, me, NPC_BREWKEG, 150.0f); for (auto&& itr : BrewKegs) itr->AI()->DoAction(ACTION_MAKE_BOOMERS_BREW); } }; CreatureAI* GetAI(Creature* creature) const override { return new npc_brewmaster_blancheAI(creature); } }; // Viletongue`s Saurok 58738, 58737 struct npc_viletongue_sauroks : public ScriptedAI { npc_viletongue_sauroks(Creature* creature) : ScriptedAI(creature) { } EventMap events, nonCombatEvents; bool poisoned; void Reset() override { events.Reset(); } void EnterCombat(Unit* who) override { if (who) DoCast(who, SPELL_LEAPING_CLEAVE); } void MovementInform(uint32 type, uint32 pointId) override { if (pointId == EVENT_JUMP) { me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_PACIFIED); me->SetInCombatWithZone(); events.ScheduleEvent(EVENT_TORCH_TOSS, urand(5000, 15000)); } } void DamageTaken(Unit* attacker, uint32& damage) override { if (me->GetEntry() == NPC_VILETONGUE_SKIRMISHER && !poisoned && HealthBelowPct(50)) { poisoned = true; if (attacker) me->CastSpell(attacker, SPELL_VILETONGUE_STING, false); } } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { if (eventId == EVENT_TORCH_TOSS) { if (Unit* vict = me->GetVictim()) DoCast(vict, SPELL_TORCH_TOSS); events.ScheduleEvent(EVENT_TORCH_TOSS, urand(5000, 15000)); } break; } DoMeleeAttackIfReady(); } }; // BrewKeg 58916 struct npc_brewkeg : public ScriptedAI { npc_brewkeg(Creature* creature) : ScriptedAI(creature) { } EventMap events, nonCombatEvents; void OnSpellClick(Unit* clicker, bool& /*result*/) override { if (!me->HasAura(SPELL_ON_FIRE)) return; clicker->CastSpell(me, SPELL_EXTINGUISHING, false); } void DoAction(int32 actionId) override { if (actionId == ACTION_MAKE_BOOMERS_BREW) nonCombatEvents.ScheduleEvent(EVENT_PREPARE_TO_STORM, urand(1000, 5500)); } void UpdateAI(uint32 diff) override { nonCombatEvents.Update(diff); while (uint32 eventId = nonCombatEvents.ExecuteEvent()) { if (eventId == EVENT_PREPARE_TO_STORM) DoCast(me, SPELL_BREW); break; } } }; // Viletongue`s stalker 59635, 59650 struct npc_viletongue_stalker : public ScriptedAI { npc_viletongue_stalker(Creature* creature) : ScriptedAI(creature) { } void Reset() override { me->SetDisplayId(me->GetCreatureTemplate()->Modelid2); } void DoAction(int32 actionId) override { switch (actionId) { case ACTION_VILETONGUE_AT_GROUND: for (uint8 i = 0; i < 2; i++) { if (Creature* blanche = ObjectAccessor::GetCreature(*me, me->GetInstanceScript() ? me->GetInstanceScript()->GetData64(NPC_BREWMASTER_BLANCHE) : 0)) if (Creature* raider = blanche->SummonCreature(NPC_VILETONGUE_RAIDER, me->GetPositionX() + frand(-3.0f, 5.0f), me->GetPositionY() + frand(-2.0f, 3.0f), me->GetPositionZ(), me->GetOrientation(), TEMPSUMMON_MANUAL_DESPAWN)) raider->SetInCombatWithZone(); } break; case ACTION_VILETONGUE_AT_HILL: for (uint8 i = 0; i < 2; i++) { if (Creature* blanche = ObjectAccessor::GetCreature(*me, me->GetInstanceScript() ? me->GetInstanceScript()->GetData64(NPC_BREWMASTER_BLANCHE) : 0)) { if (Creature* skirmisher = blanche->SummonCreature(NPC_VILETONGUE_SKIRMISHER, me->GetPositionX() + frand(-2.0f, 2.0f), me->GetPositionY() + frand(-1.0f, 1.0f), me->GetPositionZ(), me->GetOrientation(), TEMPSUMMON_MANUAL_DESPAWN)) { skirmisher->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_PACIFIED); skirmisher->GetMotionMaster()->MoveJump(CalculateGroundPos(me->GetPosition(), skirmisher->GetGUID()), 8.0f, 15.0f, EVENT_JUMP); } } } break; } } void UpdateAI(uint32 diff) override { } private: Position pos; // Main method for calculate position for jump into ground from hill // diff between stalker that`ll spawn creature and current location around 7-8y Position CalculateGroundPos(Position cur, uint64 viletongueGUID) { float x = 0, y = 0, z = 4.5f, o = cur.GetOrientation(); if (Creature* viletongue = ObjectAccessor::GetCreature(*me, viletongueGUID)) GetPositionWithDistInOrientation(viletongue, 8.0f + frand(-0.5f, 2.0f), o, x, y); pos.Relocate(x, y, cur.GetPositionZ() + z, o); return pos; } }; // Borokhula the Destroyer 58739 struct npc_borokhula_the_destroyer : public ScriptedAI { npc_borokhula_the_destroyer(Creature* creature) : ScriptedAI(creature) { } InstanceScript* instance; EventMap events; float x, y; bool SayAtLow; void InitializeAI() override { me->setActive(true); x = 0.0f; y = 0.0f; instance = me->GetInstanceScript(); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_PACIFIED); Reset(); } void Reset() override { SayAtLow = false; events.Reset(); } void EnterCombat(Unit* /*who*/) override { events.ScheduleEvent(EVENT_SWAMP_SMASH, urand(3 * IN_MILLISECONDS, 8 * IN_MILLISECONDS)); events.ScheduleEvent(EVENT_EARTH_SHATTERING, urand(12 * IN_MILLISECONDS, 15 * IN_MILLISECONDS)); } void DoAction(int32 actionId) override { if (actionId == ACTION_BOROKHULA_INIT) { GetPositionWithDistInOrientation(me, 25.0f, me->GetOrientation(), x, y); me->GetMotionMaster()->MoveJump(x, y, 450.77f, 20.0f, 20.0f, EVENT_JUMP); } } void MovementInform(uint32 type, uint32 pointId) override { if (pointId == EVENT_JUMP) { me->SetHomePosition(*me); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_PACIFIED); me->SetInCombatWithZone(); if (Creature* blanche = ObjectAccessor::GetCreature(*me, instance ? instance->GetData64(NPC_BREWMASTER_BLANCHE) : 0)) blanche->AI()->Talk(TALK_BOROKHALA_INTRO); } } void DamageTaken(Unit* /*attacker*/, uint32& /*damage*/) override { if (!SayAtLow && HealthBelowPct(70)) { SayAtLow = true; if (Creature* Blanche = ObjectAccessor::GetCreature(*me, instance ? instance->GetData64(NPC_BREWMASTER_BLANCHE) : 0)) Blanche->AI()->Talk(TALK_BOROKHALA_LOW); } } void JustDied(Unit* killer) override { if (instance) { instance->SetData(DATA_SAVE_THUNDERPAW_REFUGE, DONE); if (Creature* blanche = ObjectAccessor::GetCreature(*me, instance->GetData64(NPC_BREWMASTER_BLANCHE))) { blanche->AI()->Talk(TALK_SCENARIO_END); if (blanche->AI()->GetData(TYPE_HIT_BY_ROAD)) instance->DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, SPELL_PERFECT_POUR_ACHIEV); if (blanche->AI()->GetData(TYPE_PARTY_OF_SIX)) instance->DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, SPELL_PARTY_OF_SIX_ACHIEV); } } } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_SWAMP_SMASH: if (Unit* vict = me->GetVictim()) DoCast(vict, SPELL_SWAMP_SMASH); events.ScheduleEvent(EVENT_SWAMP_SMASH, urand(7.5 * IN_MILLISECONDS, 13.5 * IN_MILLISECONDS)); break; case EVENT_EARTH_SHATTERING: DoCast(me, SPELL_EARTH_SHATTERING); events.ScheduleEvent(EVENT_EARTH_SHATTERING, urand(15 * IN_MILLISECONDS, 20 * IN_MILLISECONDS)); break; } } DoMeleeAttackIfReady(); } }; // Viletongue Decimator 71353 struct npc_viletongue_decimator : public ScriptedAI { npc_viletongue_decimator(Creature* creature) : ScriptedAI(creature), summons(me) { } EventMap events; SummonList summons; void Reset() override { events.Reset(); summons.DespawnAll(); } void EnterCombat(Unit* /*who*/) override { events.ScheduleEvent(EVENT_TORCH_TOSS, urand(7 * IN_MILLISECONDS, 10 * IN_MILLISECONDS)); events.ScheduleEvent(EVENT_WIND_SLASH, 5 * IN_MILLISECONDS); } void JustSummoned(Creature* summon) override { summons.Summon(summon); summon->CastSpell(summon, SPELL_WIND_SLASH_AUR, true); summon->GetMotionMaster()->MoveRandom(3.5f); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_TORCH_TOSS: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, NonTankTargetSelector(me))) DoCast(target, SPELL_TORCH_TOSS); else if (Unit* target = me->GetVictim()) DoCast(target, SPELL_TORCH_TOSS); events.ScheduleEvent(EVENT_TORCH_TOSS, urand(7 * IN_MILLISECONDS, 10 * IN_MILLISECONDS)); break; case EVENT_WIND_SLASH: DoCast(me, SPELL_WIND_SLASH); events.ScheduleEvent(EVENT_WIND_SLASH, 12.5 * IN_MILLISECONDS); break; } } DoMeleeAttackIfReady(); } }; // lightning impact 111544 class spell_brewing_storm_lightning_impact : public SpellScript { PrepareSpellScript(spell_brewing_storm_lightning_impact); void HandleDummy(SpellEffIndex /*effIndex*/) { if (Creature* target = GetHitCreature()) { target->CastSpell(target, SPELL_ON_FIRE, true); if (Creature* Blanche = ObjectAccessor::GetCreature(*GetCaster(), GetCaster()->GetInstanceScript() ? GetCaster()->GetInstanceScript()->GetData64(NPC_BREWMASTER_BLANCHE) : 0)) Blanche->GetAI()->DoAction(ACTION_BREW_POWER); } else if (Player* target = GetHitPlayer()) if (Creature* blanche = ObjectAccessor::GetCreature(*target, target->GetInstanceScript() ? target->GetInstanceScript()->GetData64(NPC_BREWMASTER_BLANCHE) : 0)) blanche->AI()->SetData(TYPE_HIT_BY_ROAD, 0); } void FilterTargets(std::list<WorldObject*>& targets) { targets.remove_if([=](WorldObject* target) { return (target->GetEntry() != NPC_BREWKEG && !target->ToPlayer()) || target && target->ToUnit() && target->ToUnit()->HasAura(SPELL_ON_FIRE); }); uint32 affectedCount = urand(1, 2); if (targets.size() > affectedCount) Trinity::Containers::RandomResizeList(targets, affectedCount); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_brewing_storm_lightning_impact::HandleDummy, EFFECT_1, SPELL_EFFECT_SCHOOL_DAMAGE); OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_brewing_storm_lightning_impact::FilterTargets, EFFECT_1, TARGET_UNIT_SRC_AREA_ENTRY); } }; // lightning channel 111828 class spell_brewing_storm_lightning_channel : public AuraScript { PrepareAuraScript(spell_brewing_storm_lightning_channel) void HandleAuraEffectRemove(AuraEffect const* aurEff, AuraEffectHandleModes mode) { if (Unit* owner = GetOwner()->ToUnit()) owner->CastSpell(owner, SPELL_LIGHTNING_IMPACT, false); } void Register() override { OnEffectRemove += AuraEffectRemoveFn(spell_brewing_storm_lightning_channel::HandleAuraEffectRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); } }; // Boomer Brew Strike 115058 class spell_boomer_brew_strike : public SpellScript { PrepareSpellScript(spell_boomer_brew_strike); void HandleDummy(SpellEffIndex /*effIndex*/) { if (Unit* target = GetHitUnit()) if (target->HasAura(SPELL_BOOMER_BREW_STRIKE) && target->GetEntry() != NPC_BOROKHULA_THE_DESTROYER) GetCaster()->Kill(target); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_boomer_brew_strike::HandleDummy, EFFECT_0, SPELL_EFFECT_APPLY_AURA); } }; // 340. Summoned by 114663 - Blanche`s Elexir class sat_blanches_elexir : public IAreaTriggerAura { bool CheckTriggering(WorldObject* triggering) override { return triggering && triggering->ToPlayer() && triggering->ToPlayer()->IsAlive(); } void OnTriggeringApply(WorldObject* triggering) override { if (Player* itr = triggering->ToPlayer()) itr->CastSpell(itr, SPELL_BLANCHES_ELEXIR_EFF, true); } void OnTriggeringRemove(WorldObject* triggering) override { if (Player* itr = triggering->ToPlayer()) itr->RemoveAurasDueToSpell(SPELL_BLANCHES_ELEXIR_EFF); } }; void AddSC_brewing_storm_scenario() { new npc_brewmaster_blanche(); new creature_script<npc_viletongue_sauroks>("npc_viletongue_sauroks"); new creature_script<npc_brewkeg>("npc_brewkeg"); new creature_script<npc_viletongue_stalker>("npc_viletongue_stalker"); new creature_script<npc_borokhula_the_destroyer>("npc_borokhula_the_destroyer"); new creature_script<npc_viletongue_decimator>("npc_viletongue_decimator"); new spell_script<spell_brewing_storm_lightning_impact>("spell_brewing_storm_lightning_impact"); new aura_script<spell_brewing_storm_lightning_channel>("spell_brewing_storm_lightning_channel"); new spell_script<spell_boomer_brew_strike>("spell_boomer_brew_strike"); new atrigger_script<sat_blanches_elexir>("sat_blanches_elexir"); }
412
0.977295
1
0.977295
game-dev
MEDIA
0.981363
game-dev
0.976622
1
0.976622
Goob-Station/Goob-Station-MRP
8,985
Content.Server/Arcade/BlockGame/BlockGame.Pieces.cs
using Content.Shared.Arcade; using System.Linq; namespace Content.Server.Arcade.BlockGame; public sealed partial class BlockGame { /// <summary> /// The set of types of game pieces that exist. /// Used as templates when creating pieces for the game. /// </summary> private readonly BlockGamePieceType[] _allBlockGamePieces; /// <summary> /// The set of types of game pieces that exist. /// Used to generate the templates used when creating pieces for the game. /// </summary> private enum BlockGamePieceType { I, L, LInverted, S, SInverted, T, O } /// <summary> /// The set of possible rotations for the game pieces. /// </summary> private enum BlockGamePieceRotation { North, East, South, West } /// <summary> /// A static extension for the rotations that allows rotating through the possible rotations. /// </summary> private static BlockGamePieceRotation Next(BlockGamePieceRotation rotation, bool inverted) { return rotation switch { BlockGamePieceRotation.North => inverted ? BlockGamePieceRotation.West : BlockGamePieceRotation.East, BlockGamePieceRotation.East => inverted ? BlockGamePieceRotation.North : BlockGamePieceRotation.South, BlockGamePieceRotation.South => inverted ? BlockGamePieceRotation.East : BlockGamePieceRotation.West, BlockGamePieceRotation.West => inverted ? BlockGamePieceRotation.South : BlockGamePieceRotation.North, _ => throw new ArgumentOutOfRangeException(nameof(rotation), rotation, null) }; } /// <summary> /// A static extension for the rotations that allows rotating through the possible rotations. /// </summary> private struct BlockGamePiece { /// <summary> /// Where all of the blocks that make up this piece are located relative to the origin of the piece. /// </summary> public Vector2i[] Offsets; /// <summary> /// The color of all of the blocks that make up this piece. /// </summary> private BlockGameBlock.BlockGameBlockColor _gameBlockColor; /// <summary> /// Whether or not the block should be able to rotate about its origin. /// </summary> public bool CanSpin; /// <summary> /// Generates a list of the positions of each block comprising this game piece in worldspace. /// </summary> /// <param name="center">The position of the game piece in worldspace.</param> /// <param name="rotation">The rotation of the game piece in worldspace.</param> public readonly Vector2i[] Positions(Vector2i center, BlockGamePieceRotation rotation) { return RotatedOffsets(rotation).Select(v => center + v).ToArray(); } /// <summary> /// Gets the relative position of each block comprising this piece given a rotation. /// </summary> /// <param name="rotation">The rotation to be applied to the local position of the blocks in this piece.</param> private readonly Vector2i[] RotatedOffsets(BlockGamePieceRotation rotation) { var rotatedOffsets = (Vector2i[]) Offsets.Clone(); //until i find a better algo var amount = rotation switch { BlockGamePieceRotation.North => 0, BlockGamePieceRotation.East => 1, BlockGamePieceRotation.South => 2, BlockGamePieceRotation.West => 3, _ => 0 }; for (var i = 0; i < amount; i++) { for (var j = 0; j < rotatedOffsets.Length; j++) { rotatedOffsets[j] = rotatedOffsets[j].Rotate90DegreesAsOffset(); } } return rotatedOffsets; } /// <summary> /// Gets a list of all of the blocks comprising this piece in worldspace. /// </summary> /// <param name="center">The position of the game piece in worldspace.</param> /// <param name="rotation">The rotation of the game piece in worldspace.</param> public readonly BlockGameBlock[] Blocks(Vector2i center, BlockGamePieceRotation rotation) { var positions = Positions(center, rotation); var result = new BlockGameBlock[positions.Length]; var i = 0; foreach (var position in positions) { result[i++] = position.ToBlockGameBlock(_gameBlockColor); } return result; } /// <summary> /// Gets a list of all of the blocks comprising this piece in worldspace. /// Used to generate the held piece/next piece preview images. /// </summary> public readonly BlockGameBlock[] BlocksForPreview() { var xOffset = 0; var yOffset = 0; foreach (var offset in Offsets) { if (offset.X < xOffset) xOffset = offset.X; if (offset.Y < yOffset) yOffset = offset.Y; } return Blocks(new Vector2i(-xOffset, -yOffset), BlockGamePieceRotation.North); } /// <summary> /// Generates a game piece for a given type of game piece. /// See <see cref="BlockGamePieceType"/> for the available options. /// </summary> /// <param name="type">The type of game piece to generate.</param> public static BlockGamePiece GetPiece(BlockGamePieceType type) { //switch statement, hardcoded offsets return type switch { BlockGamePieceType.I => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(0, 0), new Vector2i(0, 1), new Vector2i(0, 2), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.LightBlue, CanSpin = true }, BlockGamePieceType.L => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(0, 0), new Vector2i(0, 1), new Vector2i(1, 1), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Orange, CanSpin = true }, BlockGamePieceType.LInverted => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(0, 0), new Vector2i(-1, 1), new Vector2i(0, 1), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Blue, CanSpin = true }, BlockGamePieceType.S => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(1, -1), new Vector2i(-1, 0), new Vector2i(0, 0), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Green, CanSpin = true }, BlockGamePieceType.SInverted => new BlockGamePiece { Offsets = new[] { new Vector2i(-1, -1), new Vector2i(0, -1), new Vector2i(0, 0), new Vector2i(1, 0), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Red, CanSpin = true }, BlockGamePieceType.T => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(-1, 0), new Vector2i(0, 0), new Vector2i(1, 0), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Purple, CanSpin = true }, BlockGamePieceType.O => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(1, -1), new Vector2i(0, 0), new Vector2i(1, 0), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Yellow, CanSpin = false }, _ => new BlockGamePiece { Offsets = new[] { new Vector2i(0, 0) } }, }; } } }
412
0.933326
1
0.933326
game-dev
MEDIA
0.925601
game-dev
0.56281
1
0.56281
Sembiance/dexvert
1,864
blender/addons/io_scene_niftools/dependencies/nifgen/formats/nif/bitflagss/NxClothFlag.py
from nifgen.bitfield import BasicBitfield from nifgen.bitfield import BitfieldMember from nifgen.formats.nif.basic import Uint class NxClothFlag(BasicBitfield): __name__ = 'NxClothFlag' _storage = Uint PRESSURE = 2 ** 0 STATIC = 2 ** 1 DISABLE_COLLISION = 2 ** 2 SELFCOLLISION = 2 ** 3 VISUALIZATION = 2 ** 4 GRAVITY = 2 ** 5 BENDING = 2 ** 6 BENDING_ORTHO = 2 ** 7 DAMPING = 2 ** 8 COLLISION_TWOWAY = 2 ** 9 TRIANGLE_COLLISION = 2 ** 11 TEARABLE = 2 ** 12 HARDWARE = 2 ** 13 COMDAMPING = 2 ** 14 VALIDBOUNDS = 2 ** 15 FLUID_COLLISION = 2 ** 16 DISABLE_DYNAMIC_CCD = 2 ** 17 ADHERE = 2 ** 18 pressure = BitfieldMember(pos=0, mask=0x1, return_type=bool) static = BitfieldMember(pos=1, mask=0x2, return_type=bool) disable_collision = BitfieldMember(pos=2, mask=0x4, return_type=bool) selfcollision = BitfieldMember(pos=3, mask=0x8, return_type=bool) visualization = BitfieldMember(pos=4, mask=0x10, return_type=bool) gravity = BitfieldMember(pos=5, mask=0x20, return_type=bool) bending = BitfieldMember(pos=6, mask=0x40, return_type=bool) bending_ortho = BitfieldMember(pos=7, mask=0x80, return_type=bool) damping = BitfieldMember(pos=8, mask=0x100, return_type=bool) collision_twoway = BitfieldMember(pos=9, mask=0x200, return_type=bool) triangle_collision = BitfieldMember(pos=11, mask=0x800, return_type=bool) tearable = BitfieldMember(pos=12, mask=0x1000, return_type=bool) hardware = BitfieldMember(pos=13, mask=0x2000, return_type=bool) comdamping = BitfieldMember(pos=14, mask=0x4000, return_type=bool) validbounds = BitfieldMember(pos=15, mask=0x8000, return_type=bool) fluid_collision = BitfieldMember(pos=16, mask=0x10000, return_type=bool) disable_dynamic_ccd = BitfieldMember(pos=17, mask=0x20000, return_type=bool) adhere = BitfieldMember(pos=18, mask=0x40000, return_type=bool) def set_defaults(self): pass
412
0.952514
1
0.952514
game-dev
MEDIA
0.658211
game-dev
0.649944
1
0.649944
pmret/papermario
19,102
src/world/area_omo/omo_14/npc.c
#include "omo_14.h" #include "effects.h" #include "sprite/player.h" API_CALLABLE(N(SurroundPlayer)) { PlayerStatus* playerStatus = &gPlayerStatus; Npc* npc = get_npc_unsafe(script->owner1.enemy->npcID); f32 goalPosX = playerStatus->pos.x + ((playerStatus->colliderDiameter + npc->collisionDiameter) * 0.5f * sin_deg((npc->npcID * 360.0f) / 10.0f)); f32 goalPosZ = playerStatus->pos.z - ((playerStatus->colliderDiameter + npc->collisionDiameter) * 0.5f * cos_deg((npc->npcID * 360.0f) / 10.0f)); f32 dist = dist2D(npc->pos.x, npc->pos.z, goalPosX, goalPosZ); if (npc->moveSpeed < dist) { if (npc->flags & NPC_FLAG_COLLDING_WITH_WORLD) { if (npc->yaw < 180.0f) { npc->yaw = npc->pos.z > 0.0f ? 45.0f : 135.0f; } else { npc->yaw = npc->pos.z > 0.0f ? 315.0f : 225.0f; } } else { npc->yaw = atan2(npc->pos.x, npc->pos.z, goalPosX, goalPosZ); } npc_move_heading(npc, npc->moveSpeed, npc->yaw); } else { npc->yaw = atan2(npc->pos.x, npc->pos.z, playerStatus->pos.x, playerStatus->pos.z); } if (script->varTableF[11] == playerStatus->pos.x && script->varTableF[13] == playerStatus->pos.z) { if (dist < 20.0f) { script->varTable[14]++; } else { script->varTable[14] = 0; } } script->varTableF[11] = playerStatus->pos.x; script->varTableF[12] = playerStatus->pos.y; script->varTableF[13] = playerStatus->pos.z; return ApiStatus_DONE2; } API_CALLABLE(N(SimpleMoveNPC)) { Bytecode* args = script->ptrReadPos; Npc* npc = get_npc_unsafe(script->owner1.enemy->npcID); f32 x = evt_get_float_variable(script, *args++); f32 z = evt_get_float_variable(script, *args++); if (npc->moveSpeed < dist2D(npc->pos.x, npc->pos.z, x, z)) { if (npc->flags & NPC_FLAG_COLLDING_WITH_WORLD) { if (npc->yaw < 180.0f) { npc->yaw = npc->pos.z > 0.0f ? 45.0f : 135.0f; } else { npc->yaw = npc->pos.z > 0.0f ? 315.0f : 225.0f; } } else { npc->yaw = atan2(npc->pos.x, npc->pos.z, x, z); } npc_move_heading(npc, npc->moveSpeed, npc->yaw); } return ApiStatus_DONE2; } API_CALLABLE(N(GetActingPartner)) { if (gPartnerStatus.partnerActionState != PARTNER_ACTION_NONE) { script->varTable[9] = gPartnerStatus.actingPartner; } else { script->varTable[9] = -1; } return ApiStatus_DONE2; } API_CALLABLE(N(IsPartnerWatt)) { if (gPartnerStatus.actingPartner == PARTNER_WATT) { script->varTable[1] = true; } else { script->varTable[1] = false; } return ApiStatus_DONE2; } #include "world/common/enemy/ShyGuy_Stationary.inc.c" Vec2i N(CrowdChaseGoalPositions)[] = { { 200, 0 }, { 210, -10 }, { 210, 10 }, { 220, -20 }, { 220, 0 }, { 220, 20 }, { 230, 30 }, { 230, 10 }, { 230, 0 }, { 230, 10 }, { 230, 30 }, }; EvtScript N(EVS_NpcIdle_ShyGuy_Loner) = { SetF(LVarA, Float(3.5 / DT)) Set(AF_OMO_11, false) Call(SetNpcSpeed, NPC_SELF, LVarA) Label(0) Call(GetSelfVar, 0, LVar0) Switch(LVar0) CaseEq(0) Call(GetPlayerPos, LVar2, LVar3, LVar4) IfGt(LVar2, -210) Call(N(GetActingPartner)) Set(MV_ActingPartner, LVar9) Switch(LVar9) CaseEq(-1) Call(SetNpcSpeed, NPC_SELF, LVarA) Call(N(SurroundPlayer)) IfGt(LVarE, 30) Call(SetNpcJumpscale, NPC_SELF, Float(1.0)) Call(GetPlayerPos, LVar0, LVar1, LVar2) IfEq(LVar1, 0) Call(PlaySound, SOUND_MASTER_SMACK) Call(NpcJump0, NPC_SELF, LVar0, LVar1, LVar2, 10 * DT) Thread Call(ShakeCam, CAM_DEFAULT, 1, 4, Float(1.0)) EndThread Wait(3 * DT) Call(SetPlayerAnimation, ANIM_Mario1_PanicRun) Call(SetPlayerJumpscale, Float(1.0)) Call(PlaySound, SOUND_MASTER_PUNCH) Call(PlayerJump1, LVar0, LVar1, LVar2, 15 * DT) Call(SetPlayerAnimation, ANIM_Mario1_Idle) Else Call(GetNpcPos, NPC_SELF, LVar3, LVar4, LVar5) Call(NpcJump0, NPC_SELF, LVar3, LVar4, LVar5, 10 * DT) EndIf Set(LVarE, 0) EndIf CaseEq(PARTNER_WATT) UseBuf(Ref(N(CrowdChaseGoalPositions))) BufRead2(LVar3, LVar4) Call(GetNpcPos, NPC_SELF, LVar0, LVar1, LVar2) IfLt(LVar0, 180) Call(GetSelfVar, 1, LVar9) IfNe(LVar9, 6) Call(GetNpcPos, NPC_SELF, LVar0, LVar1, LVar2) Call(SetNpcJumpscale, NPC_SELF, Float(1.0)) Call(NpcJump0, NPC_SELF, LVar0, 0, LVar2, 15 * DT) EndIf IfEq(AF_OMO_11, false) Set(AF_OMO_11, true) EndIf UseBuf(Ref(N(CrowdChaseGoalPositions))) BufRead2(LVar1, LVar2) Call(SetNpcSpeed, NPC_SELF, Float(4.0 / DT)) Call(N(SimpleMoveNPC), LVar3, LVar4) Else Call(GetPlayerPos, LVar0, LVar1, LVar2) IfLt(LVar0, 150) Call(SetNpcJumpscale, NPC_SELF, Float(1.0)) Call(NpcJump0, NPC_SELF, LVar3, 0, LVar4, 15 * DT) Wait(30 * DT) Else Call(DisablePlayerInput, true) Call(SetNpcJumpscale, NPC_SELF, Float(1.0)) Call(NpcJump0, NPC_SELF, LVar3, 0, LVar4, 15 * DT) Wait(30 * DT) Call(DisablePlayerInput, false) EndIf Call(SetSelfVar, 0, 1) EndIf CaseEq(PARTNER_BOW) Call(GetPlayerPos, LVar2, LVar3, LVar4) IfLt(LVar2, 30) Call(N(SimpleMoveNPC), 200, 0) Else Call(N(SimpleMoveNPC), -150, 0) EndIf EndSwitch Set(LVar9, MV_ActingPartner) Call(SetSelfVar, 1, LVar9) Else Call(N(SimpleMoveNPC), 200, 0) EndIf CaseEq(1) Call(GetPlayerPos, LVar2, LVar3, LVar4) IfLt(LVar2, 150) Call(N(GetActingPartner)) IfNe(LVar9, 6) Call(SetSelfVar, 0, 0) EndIf Else Call(DisablePlayerInput, true) Call(SpeakToPlayer, NPC_SELF, -1, -1, 5, MSG_CH4_005D) Call(GetNpcPos, NPC_SELF, LVar0, LVar1, LVar2) Call(SetNpcJumpscale, NPC_SELF, Float(1.0)) Call(NpcJump0, NPC_SELF, LVar0, 0, LVar2, 15 * DT) Call(SetNpcSpeed, NPC_SELF, Float(4.0 / DT)) Call(NpcMoveTo, NPC_SELF, 230, 0, 0) Call(SetNpcSpeed, NPC_SELF, LVarA) Set(LVar0, 1) Loop(10) Call(SetNpcVar, LVar0, 0, 2) Add(LVar0, 1) EndLoop Wait(45 * DT) Call(StopSound, SOUND_LOOP_SHY_GUY_CROWD_1) Call(SpeakToPlayer, NPC_SELF, -1, -1, 5, MSG_CH4_005E) Thread Call(ShakeCam, CAM_DEFAULT, 0, 10, Float(1.0)) EndThread Call(PlaySoundAtCollider, COLLIDER_tt1, SOUND_TROMP_CRASH, SOUND_SPACE_DEFAULT) PlayEffect(EFFECT_BOMBETTE_BREAKING, 0, 37, 37, 1, 10, 30) Call(EnableModel, MODEL_o821, true) Loop(10) Call(EnableModel, MODEL_o823, true) Call(EnableModel, MODEL_o828, true) Wait(1) Call(EnableModel, MODEL_o823, false) Call(EnableModel, MODEL_o828, false) Wait(1) EndLoop Call(ModifyColliderFlags, MODIFY_COLLIDER_FLAGS_SET_BITS, COLLIDER_tt1, COLLIDER_FLAGS_UPPER_MASK) Wait(40 * DT) Call(InterpNpcYaw, NPC_SELF, 270, 0) Wait(20 * DT) Call(SetNpcSpeed, NPC_SELF, Float(4.0)) Call(NpcMoveTo, NPC_SELF, 300, 0, 0) Set(GB_StoryProgress, STORY_CH4_OPENED_GENERAL_GUY_ROOM) Wait(30 * DT) Call(DisablePlayerInput, false) Call(RemoveNpc, NPC_SELF) EndIf EndSwitch Wait(1) Goto(0) Return End }; EvtScript N(EVS_NpcIdle_ShyGuy_Crowd) = { Call(RandInt, 15, LVarA) Add(LVarA, 20) DivF(LVarA, Float(10.0 * DT)) Call(SetNpcSpeed, NPC_SELF, LVarA) Label(0) Call(GetSelfVar, 0, LVar0) Switch(LVar0) CaseEq(0) Call(GetPlayerPos, LVar2, LVar3, LVar4) IfGt(LVar2, -210) Call(N(GetActingPartner)) Set(MV_ActingPartner, LVar9) Switch(LVar9) CaseEq(-1) Call(SetNpcSpeed, NPC_SELF, LVarA) Call(N(SurroundPlayer)) IfGt(LVarE, 30) Call(SetNpcJumpscale, NPC_SELF, Float(1.0)) Call(GetPlayerPos, LVar0, LVar1, LVar2) IfEq(LVar1, 0) Call(NpcJump0, NPC_SELF, LVar0, LVar1, LVar2, 10 * DT) Else Call(GetNpcPos, NPC_SELF, LVar3, LVar4, LVar5) Call(NpcJump0, NPC_SELF, LVar3, LVar4, LVar5, 10 * DT) EndIf Set(LVarE, 0) EndIf CaseEq(PARTNER_WATT) Call(GetSelfVar, 1, LVar9) Call(GetNpcPos, NPC_SELF, LVar0, LVar1, LVar2) IfNe(LVar9, 6) Call(SetNpcJumpscale, NPC_SELF, Float(1.0)) Call(NpcJump0, NPC_SELF, LVar0, 0, LVar2, 15 * DT) EndIf Call(GetSelfNpcID, LVar5) UseBuf(Ref(N(CrowdChaseGoalPositions))) Loop(LVar5) BufRead2(LVar3, LVar4) EndLoop IfEq(LVar0, LVarF) Set(LVar3, LVar0) Add(LVar3, 10) Set(LVar4, 50) EndIf Set(LVarF, LVar0) Call(SetNpcSpeed, NPC_SELF, Float(7.0 / DT)) Call(N(SimpleMoveNPC), LVar3, LVar4) Call(GetNpcVar, NPC_ShyGuy_01, 0, LVar0) IfEq(LVar0, 1) Call(SetSelfVar, 0, 1) EndIf CaseEq(PARTNER_BOW) Call(GetPlayerPos, LVar2, LVar3, LVar4) IfLt(LVar2, 30) Call(N(SimpleMoveNPC), 200, 0) Else Call(N(SimpleMoveNPC), -150, 0) EndIf EndSwitch Set(LVar9, MV_ActingPartner) Call(SetSelfVar, 1, LVar9) Else Call(N(SimpleMoveNPC), 200, 0) EndIf CaseEq(1) Call(GetPlayerPos, LVar0, LVar1, LVar2) Call(RandInt, 360, LVar0) Call(InterpNpcYaw, NPC_SELF, LVar0, 0) Call(RandInt, 20 * DT, LVar0) Add(LVar0, 1) Wait(LVar0) Call(InterpNpcYaw, NPC_SELF, 90, 0) Call(GetNpcPos, NPC_SELF, LVar0, LVar1, LVar2) Call(SetNpcJumpscale, NPC_SELF, 2) Call(NpcJump0, NPC_SELF, LVar0, LVar1, LVar2, 12 * DT) Call(GetSelfVar, 0, LVar0) IfEq(LVar0, 1) Call(N(GetActingPartner)) IfNe(LVar9, 6) Call(SetSelfVar, 0, 0) EndIf EndIf CaseEq(2) Call(RandInt, 15 * DT, LVar0) Add(LVar0, 1) Wait(LVar0) Call(InterpNpcYaw, NPC_SELF, 90, 0) Call(GetNpcPos, NPC_SELF, LVar0, LVar1, LVar2) Call(SetNpcJumpscale, NPC_SELF, Float(1.0)) Call(NpcJump0, NPC_SELF, 235, LVar1, LVar2, 20 * DT * DT) Wait(30 * DT) Call(SetSelfVar, 0, 3) CaseEq(3) Call(SetNpcFlagBits, NPC_SELF, NPC_FLAG_IGNORE_WORLD_COLLISION, true) Call(SetNpcSpeed, NPC_SELF, Float(4.0 / DT)) Call(NpcMoveTo, NPC_SELF, 235, 0, 0) Call(NpcMoveTo, NPC_SELF, 300, 0, 0) Call(RemoveNpc, NPC_SELF) EndSwitch Wait(1) Goto(0) Return End }; EvtScript N(EVS_NpcInit_ShyGuy_Loner) = { IfLt(GB_StoryProgress, STORY_CH4_OPENED_GENERAL_GUY_ROOM) Call(BindNpcIdle, NPC_SELF, Ref(N(EVS_NpcIdle_ShyGuy_Loner))) Call(SetNpcPos, NPC_SELF, 120, 0, 0) Call(SetNpcAnimation, NPC_SELF, ANIM_ShyGuy_Red_Anim02) Else Call(RemoveNpc, NPC_SELF) EndIf Return End }; Vec3i N(CrowdInitialPositions)[] = { { 150, 0, -100 }, { 150, 0, -50 }, { 150, 0, 0 }, { 150, 0, 50 }, { 150, 0, 100 }, { 180, 0, -100 }, { 180, 0, -50 }, { 180, 0, 0 }, { 180, 0, 50 }, { 180, 0, 100 }, }; EvtScript N(EVS_NpcInit_ShyGuy_Crowd) = { Call(BindNpcIdle, NPC_SELF, Ref(N(EVS_NpcIdle_ShyGuy_Crowd))) IfLt(GB_StoryProgress, STORY_CH4_OPENED_GENERAL_GUY_ROOM) Call(GetSelfNpcID, LVar0) Sub(LVar0, 0) UseBuf(Ref(N(CrowdInitialPositions))) Loop(LVar0) BufRead3(LVar1, LVar2, LVar3) EndLoop Call(SetNpcPos, NPC_SELF, LVar1, LVar2, LVar3) Call(SetNpcAnimation, NPC_SELF, ANIM_ShyGuy_Red_Anim02) Else Call(RemoveNpc, NPC_SELF) EndIf Return End }; NpcData N(NpcData_ShyGuy_Loner) = { .id = NPC_ShyGuy_01, .pos = { NPC_DISPOSE_LOCATION }, .yaw = 270, .init = &N(EVS_NpcInit_ShyGuy_Loner), .settings = &N(NpcSettings_ShyGuy_Stationary), .flags = ENEMY_FLAG_PASSIVE | ENEMY_FLAG_IGNORE_WORLD_COLLISION | ENEMY_FLAG_IGNORE_PLAYER_COLLISION, .drops = NO_DROPS, .animations = RED_SHY_GUY_ANIMS, }; NpcData N(NpcData_ShyGuy_Crowd)[] = { { .id = NPC_ShyGuy_02, .pos = { NPC_DISPOSE_LOCATION }, .yaw = 270, .init = &N(EVS_NpcInit_ShyGuy_Crowd), .settings = &N(NpcSettings_ShyGuy_Stationary), .flags = ENEMY_FLAG_PASSIVE | ENEMY_FLAG_IGNORE_PLAYER_COLLISION, .drops = NO_DROPS, .animations = RED_SHY_GUY_ANIMS, }, { .id = NPC_ShyGuy_03, .pos = { NPC_DISPOSE_LOCATION }, .yaw = 270, .init = &N(EVS_NpcInit_ShyGuy_Crowd), .settings = &N(NpcSettings_ShyGuy_Stationary), .flags = ENEMY_FLAG_PASSIVE | ENEMY_FLAG_IGNORE_PLAYER_COLLISION, .drops = NO_DROPS, .animations = RED_SHY_GUY_ANIMS, }, { .id = NPC_ShyGuy_04, .pos = { NPC_DISPOSE_LOCATION }, .yaw = 270, .init = &N(EVS_NpcInit_ShyGuy_Crowd), .settings = &N(NpcSettings_ShyGuy_Stationary), .flags = ENEMY_FLAG_PASSIVE | ENEMY_FLAG_IGNORE_PLAYER_COLLISION, .drops = NO_DROPS, .animations = RED_SHY_GUY_ANIMS, }, { .id = NPC_ShyGuy_05, .pos = { NPC_DISPOSE_LOCATION }, .yaw = 270, .init = &N(EVS_NpcInit_ShyGuy_Crowd), .settings = &N(NpcSettings_ShyGuy_Stationary), .flags = ENEMY_FLAG_PASSIVE | ENEMY_FLAG_IGNORE_PLAYER_COLLISION, .drops = NO_DROPS, .animations = RED_SHY_GUY_ANIMS, }, { .id = NPC_ShyGuy_06, .pos = { NPC_DISPOSE_LOCATION }, .yaw = 270, .init = &N(EVS_NpcInit_ShyGuy_Crowd), .settings = &N(NpcSettings_ShyGuy_Stationary), .flags = ENEMY_FLAG_PASSIVE | ENEMY_FLAG_IGNORE_PLAYER_COLLISION, .drops = NO_DROPS, .animations = RED_SHY_GUY_ANIMS, }, { .id = NPC_ShyGuy_07, .pos = { NPC_DISPOSE_LOCATION }, .yaw = 270, .init = &N(EVS_NpcInit_ShyGuy_Crowd), .settings = &N(NpcSettings_ShyGuy_Stationary), .flags = ENEMY_FLAG_PASSIVE | ENEMY_FLAG_IGNORE_PLAYER_COLLISION, .drops = NO_DROPS, .animations = RED_SHY_GUY_ANIMS, }, { .id = NPC_ShyGuy_08, .pos = { NPC_DISPOSE_LOCATION }, .yaw = 270, .init = &N(EVS_NpcInit_ShyGuy_Crowd), .settings = &N(NpcSettings_ShyGuy_Stationary), .flags = ENEMY_FLAG_PASSIVE | ENEMY_FLAG_IGNORE_PLAYER_COLLISION, .drops = NO_DROPS, .animations = RED_SHY_GUY_ANIMS, }, { .id = NPC_ShyGuy_09, .pos = { NPC_DISPOSE_LOCATION }, .yaw = 270, .init = &N(EVS_NpcInit_ShyGuy_Crowd), .settings = &N(NpcSettings_ShyGuy_Stationary), .flags = ENEMY_FLAG_PASSIVE | ENEMY_FLAG_IGNORE_PLAYER_COLLISION, .drops = NO_DROPS, .animations = RED_SHY_GUY_ANIMS, }, { .id = NPC_ShyGuy_10, .pos = { NPC_DISPOSE_LOCATION }, .yaw = 270, .init = &N(EVS_NpcInit_ShyGuy_Crowd), .settings = &N(NpcSettings_ShyGuy_Stationary), .flags = ENEMY_FLAG_PASSIVE | ENEMY_FLAG_IGNORE_PLAYER_COLLISION, .drops = NO_DROPS, .animations = RED_SHY_GUY_ANIMS, }, { .id = NPC_ShyGuy_11, .pos = { NPC_DISPOSE_LOCATION }, .yaw = 270, .init = &N(EVS_NpcInit_ShyGuy_Crowd), .settings = &N(NpcSettings_ShyGuy_Stationary), .flags = ENEMY_FLAG_PASSIVE | ENEMY_FLAG_IGNORE_PLAYER_COLLISION, .drops = NO_DROPS, .animations = RED_SHY_GUY_ANIMS, }, }; NpcGroupList N(DefaultNPCs) = { NPC_GROUP(N(NpcData_ShyGuy_Loner)), NPC_GROUP(N(NpcData_ShyGuy_Crowd)), {} };
412
0.965042
1
0.965042
game-dev
MEDIA
0.940813
game-dev
0.820716
1
0.820716
gideros/gideros
11,750
plugins/iad/source/iOS/iad.mm
/* This code is MIT licensed, see http://www.opensource.org/licenses/mit-license.php (C) 2010 - 2012 Gideros Mobile */ #include "gideros.h" #include "lua.h" #include "lauxlib.h" #import <iAd/iAd.h> // some Lua helper functions #ifndef abs_index #define abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : lua_gettop(L) + (i) + 1) #endif static void luaL_newweaktable(lua_State *L, const char *mode) { lua_newtable(L); // create table for instance list lua_pushstring(L, mode); lua_setfield(L, -2, "__mode"); // set as weak-value table lua_pushvalue(L, -1); // duplicate table lua_setmetatable(L, -2); // set itself as metatable } static void luaL_rawgetptr(lua_State *L, int idx, void *ptr) { idx = abs_index(L, idx); lua_pushlightuserdata(L, ptr); lua_rawget(L, idx); } static void luaL_rawsetptr(lua_State *L, int idx, void *ptr) { idx = abs_index(L, idx); lua_pushlightuserdata(L, ptr); lua_insert(L, -2); lua_rawset(L, idx); } /* we have two tables: 1.strong (table -> boolean) show -> add, hide - > remove to disable GC for visible banners 2. weak (ptr -> table) to access table from pointer */ static char keyStrong = ' '; static char keyWeak = ' '; static const char *BANNER_ACTION_BEGIN = "bannerActionBegin"; static const char *BANNER_ACTION_FINISHED = "bannerActionFinished"; static const char *BANNER_AD_LOADED = "bannerAdLoaded"; static const char *BANNER_AD_FAILED = "bannerAdFailed"; static const char *TOP = "top"; static const char *BOTTOM = "bottom"; static const char *PORTRAIT = "portrait"; static const char *LANDSCAPE = "landscape"; const int kTOP = 0; const int kBOTTOM = 1; const int kPORTRAIT = 0; const int kLANDSCAPE = 1; /* require "iad" iad.isAvailable() local banner = iad.Banner.new(iad.Banner.TOP, iad.Banner.PORTRAIT) banner:addEventListener(Event.BANNER_ACTION_BEGIN, ...) banner:addEventListener(Event.BANNER_ACTION_FINISHED, ...) banner:addEventListener(Event.BANNER_AD_LOADED, ...) banner:addEventListener(Event.BANNER_AD_FAILED, ...) banner:show() banner:hide() banner:setAlignment(iad.Banner.BOTTOM) */ static bool isiAdAvailable() { return NSClassFromString(@"ADBannerView") != nil; } static NSString *getContentSizeIdentifierPortrait() { return ADBannerContentSizeIdentifierPortrait; } static NSString *getContentSizeIdentifierLandscape() { return ADBannerContentSizeIdentifierLandscape; } class Banner; @interface BannerDelegate : NSObject<ADBannerViewDelegate> { } - (id)initWithBanner:(Banner *)banner; @property (nonatomic, assign) Banner *banner; @end class Banner : public GEventDispatcherProxy { public: Banner(lua_State *L, int alignment, int orientation) : L(L) { alignment_ = alignment; orientation_ = orientation; view_ = [[ADBannerView alloc] initWithFrame:CGRectZero]; if (orientation_ == kPORTRAIT) view_.currentContentSizeIdentifier = getContentSizeIdentifierPortrait(); else view_.currentContentSizeIdentifier = getContentSizeIdentifierLandscape(); delegate_ = [[BannerDelegate alloc] initWithBanner:this]; view_.delegate = delegate_; showWhenAvailable_ = false; } virtual ~Banner() { view_.delegate = nil; delegate_.banner = NULL; [view_ cancelBannerViewAction]; [view_ removeFromSuperview]; view_=nil; delegate_=nil; } void show() { showWhenAvailable_ = true; if (view_.bannerLoaded) { if (view_.superview == nil) { UIViewController *viewController = g_getRootViewController(); [viewController.view addSubview:view_]; } updateFramePosition(); } } void hide() { showWhenAvailable_ = false; [view_ removeFromSuperview]; } void setAlignment(int alignment) { alignment_ = alignment; if (view_.superview != nil) updateFramePosition(); } bool isBannerLoaded() const { return view_.bannerLoaded; } void adLoaded() { if (showWhenAvailable_) show(); dispatchEvent(BANNER_AD_LOADED, NULL, NULL); } void actionBegin(BOOL willLeaveApplication) { dispatchEvent(BANNER_ACTION_BEGIN, NULL, &willLeaveApplication); } void actionFinished() { dispatchEvent(BANNER_ACTION_FINISHED, NULL, NULL); } void adFailed(NSError *error) { [view_ removeFromSuperview]; dispatchEvent(BANNER_AD_FAILED, error, NULL); } void dispatchEvent(const char *type, NSError *error, BOOL *willLeaveApplication) { luaL_rawgetptr(L, LUA_REGISTRYINDEX, &keyWeak); luaL_rawgetptr(L, -1, this); if (lua_isnil(L, -1)) { lua_pop(L, 2); return; } lua_getfield(L, -1, "dispatchEvent"); lua_pushvalue(L, -2); lua_getglobal(L, "Event"); lua_getfield(L, -1, "new"); lua_remove(L, -2); lua_pushstring(L, type); lua_call(L, 1, 1); if (error) { lua_pushinteger(L, error.code); lua_setfield(L, -2, "errorCode"); lua_pushstring(L, [error.localizedDescription UTF8String]); lua_setfield(L, -2, "errorDescription"); } if (willLeaveApplication) { lua_pushboolean(L, *willLeaveApplication); lua_setfield(L, -2, "willLeaveApplication"); } if (lua_pcall(L, 2, 0, 0) != 0) g_error(L, lua_tostring(L, -1)); lua_pop(L, 2); } void updateFramePosition() { CGRect frame = view_.frame; if (alignment_ == kTOP) { frame.origin = CGPointMake(0, 0); } else { int height; CGRect screenRect = [[UIScreen mainScreen] bounds]; if (UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])) height = screenRect.size.height; else height = screenRect.size.width; if (orientation_ == kPORTRAIT) { CGSize size = [ADBannerView sizeFromBannerContentSizeIdentifier:getContentSizeIdentifierPortrait()]; frame.origin = CGPointMake(0, height - size.height); } else { CGSize size = [ADBannerView sizeFromBannerContentSizeIdentifier:getContentSizeIdentifierLandscape()]; frame.origin = CGPointMake(0, height - size.height); } } view_.frame = frame; } private: lua_State *L; bool showWhenAvailable_; BannerDelegate *delegate_; ADBannerView *view_; int alignment_; int orientation_; }; @implementation BannerDelegate @synthesize banner = banner_; - (id)initWithBanner:(Banner *)banner { if (self = [super init]) { banner_ = banner; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil]; [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; } return self; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil]; [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications]; [super dealloc]; } - (void)orientationDidChange:(NSNotification *)notification { if (banner_) banner_->updateFramePosition(); } - (void)bannerViewWillLoadAd:(ADBannerView *)banner { } - (void)bannerViewDidLoadAd:(ADBannerView *)banner { if (banner_) banner_->adLoaded(); } - (BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave { if (banner_) banner_->actionBegin(willLeave); return YES; } - (void)bannerViewActionDidFinish:(ADBannerView *)banner { if (banner_) banner_->actionFinished(); } - (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error { if (banner_) banner_->adFailed(error); } @end static int create(lua_State *L) { if (!isiAdAvailable()) return luaL_error(L, "iAd framework is not available."); int alignment; const char *alignmentstr = luaL_checkstring(L, 1); if (strcmp(alignmentstr, TOP) == 0) alignment = kTOP; else if (strcmp(alignmentstr, BOTTOM) == 0) alignment = kBOTTOM; else return luaL_error(L, "Parameter 'alignment' must be one of the accepted values."); int orientation; const char *orientationstr = luaL_checkstring(L, 2); if (strcmp(orientationstr, PORTRAIT) == 0) orientation = kPORTRAIT; else if (strcmp(orientationstr, LANDSCAPE) == 0) orientation = kLANDSCAPE; else return luaL_error(L, "Parameter 'orientation' must be one of the accepted values."); Banner *banner = new Banner(L, alignment, orientation); g_pushInstance(L, "iad.Banner", banner->object()); luaL_rawgetptr(L, LUA_REGISTRYINDEX, &keyWeak); lua_pushvalue(L, -2); luaL_rawsetptr(L, -2, banner); lua_pop(L, 1); return 1; } static int destruct(lua_State *L) { void *ptr = *(void**)lua_touserdata(L, 1); GReferenced *object = static_cast<GReferenced*>(ptr); Banner *banner = static_cast<Banner*>(object->proxy()); banner->unref(); return 0; } static Banner *getBannerInstance(lua_State *L, int index) { GReferenced *object = static_cast<GReferenced*>(g_getInstance(L, "iad.Banner", index)); Banner *banner = static_cast<Banner*>(object->proxy()); return banner; } static int show(lua_State *L) { Banner *banner = getBannerInstance(L, 1); banner->show(); luaL_rawgetptr(L, LUA_REGISTRYINDEX, &keyStrong); lua_pushvalue(L, 1); lua_pushboolean(L, 1); lua_settable(L, -3); lua_pop(L, 1); return 0; } static int hide(lua_State *L) { Banner *banner = getBannerInstance(L, 1); banner->hide(); luaL_rawgetptr(L, LUA_REGISTRYINDEX, &keyStrong); lua_pushvalue(L, 1); lua_pushnil(L); lua_settable(L, -3); lua_pop(L, 1); return 0; } static int setAlignment(lua_State *L) { Banner *banner = getBannerInstance(L, 1); int alignment; const char *alignmentstr = luaL_checkstring(L, 2); if (strcmp(alignmentstr, TOP) == 0) alignment = kTOP; else if (strcmp(alignmentstr, BOTTOM) == 0) alignment = kBOTTOM; else return luaL_error(L, "Parameter 'alignment' must be one of the accepted values."); banner->setAlignment(alignment); return 0; } static int isBannerLoaded(lua_State* L) { Banner *banner = getBannerInstance(L, 1); lua_pushboolean(L, banner->isBannerLoaded()); return 1; } static int isAvailable(lua_State *L) { lua_pushboolean(L, isiAdAvailable()); return 1; } static int loader(lua_State *L) { const luaL_Reg functionlist[] = { {"show", show}, {"hide", hide}, {"setAlignment", setAlignment}, {"isBannerLoaded", isBannerLoaded}, {NULL, NULL}, }; g_createClass(L, "iad.Banner", "EventDispatcher", create, destruct, functionlist); lua_newtable(L); luaL_rawsetptr(L, LUA_REGISTRYINDEX, &keyStrong); luaL_newweaktable(L, "v"); luaL_rawsetptr(L, LUA_REGISTRYINDEX, &keyWeak); lua_getglobal(L, "Event"); lua_pushstring(L, BANNER_ACTION_BEGIN); lua_setfield(L, -2, "BANNER_ACTION_BEGIN"); lua_pushstring(L, BANNER_ACTION_FINISHED); lua_setfield(L, -2, "BANNER_ACTION_FINISHED"); lua_pushstring(L, BANNER_AD_LOADED); lua_setfield(L, -2, "BANNER_AD_LOADED"); lua_pushstring(L, BANNER_AD_FAILED); lua_setfield(L, -2, "BANNER_AD_FAILED"); lua_pop(L, 1); lua_getglobal(L, "iad"); lua_getfield(L, -1, "Banner"); lua_pushstring(L, TOP); lua_setfield(L, -2, "TOP"); lua_pushstring(L, BOTTOM); lua_setfield(L, -2, "BOTTOM"); lua_pushstring(L, PORTRAIT); lua_setfield(L, -2, "PORTRAIT"); lua_pushstring(L, LANDSCAPE); lua_setfield(L, -2, "LANDSCAPE"); lua_pop(L, 2); lua_getglobal(L, "iad"); lua_pushcfunction(L, isAvailable); lua_setfield(L, -2, "isAvailable"); return 1; } static void g_initializePlugin(lua_State* L) { lua_getglobal(L, "package"); lua_getfield(L, -1, "preload"); lua_pushcfunction(L, loader); lua_setfield(L, -2, "iad"); lua_pop(L, 2); } static void g_deinitializePlugin(lua_State *L) { } REGISTER_PLUGIN("iAd", "1.0")
412
0.881872
1
0.881872
game-dev
MEDIA
0.26339
game-dev
0.918342
1
0.918342
daydayasobi/TowerDefense-TEngine-Demo
4,149
Packages/YooAsset/Runtime/FileSystem/BundleResult/AssetBundleResult/Operation/AssetBundleLoadSubAssetsOperation.cs
using UnityEngine; namespace YooAsset { internal class AssetBundleLoadSubAssetsOperation : FSLoadSubAssetsOperation { protected enum ESteps { None, CheckBundle, LoadAsset, CheckResult, Done, } private readonly PackageBundle _packageBundle; private readonly AssetBundle _assetBundle; private readonly AssetInfo _assetInfo; private AssetBundleRequest _request; private ESteps _steps = ESteps.None; public AssetBundleLoadSubAssetsOperation(PackageBundle packageBundle, AssetBundle assetBundle, AssetInfo assetInfo) { _packageBundle = packageBundle; _assetBundle = assetBundle; _assetInfo = assetInfo; } internal override void InternalStart() { _steps = ESteps.CheckBundle; } internal override void InternalUpdate() { if (_steps == ESteps.None || _steps == ESteps.Done) return; if (_steps == ESteps.CheckBundle) { if (_assetBundle == null) { _steps = ESteps.Done; Error = $"The bundle {_packageBundle.BundleName} has been destroyed due to unity engine bugs !"; Status = EOperationStatus.Failed; return; } _steps = ESteps.LoadAsset; } if (_steps == ESteps.LoadAsset) { if (IsWaitForAsyncComplete) { if (_assetInfo.AssetType == null) Result = _assetBundle.LoadAssetWithSubAssets(_assetInfo.AssetPath); else Result = _assetBundle.LoadAssetWithSubAssets(_assetInfo.AssetPath, _assetInfo.AssetType); } else { if (_assetInfo.AssetType == null) _request = _assetBundle.LoadAssetWithSubAssetsAsync(_assetInfo.AssetPath); else _request = _assetBundle.LoadAssetWithSubAssetsAsync(_assetInfo.AssetPath, _assetInfo.AssetType); } _steps = ESteps.CheckResult; } if (_steps == ESteps.CheckResult) { if (_request != null) { if (IsWaitForAsyncComplete) { // 强制挂起主线程(注意:该操作会很耗时) YooLogger.Warning("Suspend the main thread to load unity asset."); Result = _request.allAssets; } else { Progress = _request.progress; if (_request.isDone == false) return; Result = _request.allAssets; } } if (Result == null) { string error; if (_assetInfo.AssetType == null) error = $"Failed to load sub assets : {_assetInfo.AssetPath} AssetType : null AssetBundle : {_packageBundle.BundleName}"; else error = $"Failed to load sub assets : {_assetInfo.AssetPath} AssetType : {_assetInfo.AssetType} AssetBundle : {_packageBundle.BundleName}"; YooLogger.Error(error); _steps = ESteps.Done; Error = error; Status = EOperationStatus.Failed; } else { _steps = ESteps.Done; Status = EOperationStatus.Succeed; } } } internal override void InternalWaitForAsyncComplete() { while (true) { if (ExecuteWhileDone()) { _steps = ESteps.Done; break; } } } } }
412
0.768071
1
0.768071
game-dev
MEDIA
0.932943
game-dev
0.764018
1
0.764018
moai/moai-dev
9,419
src/moai-sim/MOAIParticleState.cpp
// Copyright (c) 2010-2017 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <moai-sim/MOAIDeck.h> #include <moai-sim/MOAIParticleForce.h> #include <moai-sim/MOAIParticlePlugin.h> #include <moai-sim/MOAIParticleScript.h> #include <moai-sim/MOAIParticleState.h> #include <moai-sim/MOAIParticleSystem.h> class MOAIDataBuffer; //================================================================// // local //================================================================// //----------------------------------------------------------------// /** @lua clearForces @text Removes all particle forces from the state. @in MOAIParticleState self @out nil */ int MOAIParticleState::_clearForces ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIParticleState, "U" ) self->ClearForces (); return 0; } //----------------------------------------------------------------// /** @lua pushForce @text Adds a force to the state. @in MOAIParticleState self @in MOAIParticleForce force @out nil */ int MOAIParticleState::_pushForce ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIParticleState, "UU" ) MOAIParticleForce* force = state.GetLuaObject < MOAIParticleForce >( 2, true ); if ( force ) { self->PushForce ( *force ); } return 0; } //----------------------------------------------------------------// /** @lua setDamping @text Sets damping for particle physics model. @in MOAIParticleState self @in number damping @out nil */ int MOAIParticleState::_setDamping ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIParticleState, "UN" ) self->mDamping = state.GetValue < float >( 2, 0.0f ); return 0; } //----------------------------------------------------------------// /** @lua setInitScript @text Sets the particle script to use for initializing new particles. @in MOAIParticleState self @opt MOAIParticleScript script @out nil */ int MOAIParticleState::_setInitScript ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIParticleState, "U" ) MOAIParticleScript* init = state.GetLuaObject < MOAIParticleScript >( 2, true ); if ( init ) { init->Compile (); } self->mInit.Set ( *self, init ); return 0; } //----------------------------------------------------------------// /** @lua setMass @text Sets range of masses (chosen randomly) for particles initialized by the state. @in MOAIParticleState self @in number minMass @opt number maxMass Default value is minMass. @out nil */ int MOAIParticleState::_setMass ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIParticleState, "UN" ) float m0 = state.GetValue < float >( 2, 0.0f ); float m1 = state.GetValue < float >( 3, m0 ); self->mMassRange [ 0 ] = m0; self->mMassRange [ 1 ] = m1; return 0; } //----------------------------------------------------------------// /** @lua setNext @text Sets the next state (if any). @in MOAIParticleState self @opt MOAIParticleState next Default value is nil. @out nil */ int MOAIParticleState::_setNext ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIParticleState, "U" ) self->mNext.Set ( *self, state.GetLuaObject < MOAIParticleState >( 2, true )); return 0; } //----------------------------------------------------------------// /** @lua setPlugin @text Sets the particle plugin to use for initializing and updating particles. @in MOAIParticleState self @opt MOAIParticlePlugin plugin @out nil */ int MOAIParticleState::_setPlugin ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIParticleState, "U" ) self->mPlugin.Set ( *self, state.GetLuaObject < MOAIParticlePlugin >( 2, true )); return 0; } //----------------------------------------------------------------// /** @lua setRenderScript @text Sets the particle script to use for rendering particles. @in MOAIParticleState self @opt MOAIParticleScript script @out nil */ int MOAIParticleState::_setRenderScript ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIParticleState, "U" ) MOAIParticleScript* render = state.GetLuaObject < MOAIParticleScript >( 2, true ); if ( render ) { render->Compile (); } self->mRender.Set ( *self, render ); return 0; } //----------------------------------------------------------------// /** @lua setTerm @text Sets range of terms (chosen randomly) for particles initialized by the state. @in MOAIParticleState self @in number minTerm @opt number maxTerm Default value is minTerm. @out nil */ int MOAIParticleState::_setTerm ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIParticleState, "UN" ) float t0 = state.GetValue < float >( 2, 0.0f ); float t1 = state.GetValue < float >( 3, t0 ); self->mTermRange [ 0 ] = t0; self->mTermRange [ 1 ] = t1; return 0; } //================================================================// // MOAIParticleState //================================================================// //----------------------------------------------------------------// void MOAIParticleState::ClearForces () { while ( this->mForces.Count ()) { ForceNode* forceNode = this->mForces.Head (); this->mForces.PopFront (); this->LuaRelease ( forceNode->Data ()); delete forceNode; } } //----------------------------------------------------------------// void MOAIParticleState::GatherForces ( ZLVec3D& loc, ZLVec3D& velocity, float mass, float step ) { ZLVec3D result; ZLVec3D acceleration ( 0.0f, 0.0f, 0.0f ); ZLVec3D offset ( 0.0f, 0.0f, 0.0f ); ForceNode* forceNode = this->mForces.Head (); for ( ; forceNode; forceNode = forceNode->Next ()) { MOAIParticleForce* particleForce = forceNode->Data (); particleForce->Eval ( loc, mass, acceleration, offset ); } velocity.mX += acceleration.mX * step; velocity.mY += acceleration.mY * step; velocity.Scale ( ZLFloat::Clamp ( 1.0f - ( this->mDamping * step ), 0.0f, 1.0f )); loc.mX += ( velocity.mX + offset.mX ) * step; loc.mY += ( velocity.mY + offset.mY ) * step; } //----------------------------------------------------------------// void MOAIParticleState::InitParticle ( MOAIParticleSystem& system, MOAIParticle& particle ) { if ( this->mInit ) { this->mInit->Run ( system, particle, 0.0f, 0.0f ); } MOAIParticlePlugin* plugin = this->mPlugin; if ( plugin ) { plugin->OnInit ( particle.mData, &particle.mData [ MOAIParticle::TOTAL_PARTICLE_REG ]); } particle.mAge = 0.0f; particle.mTerm = ZLFloat::Rand ( this->mTermRange [ 0 ], this->mTermRange [ 1 ]); particle.mMass = ZLFloat::Rand ( this->mMassRange [ 0 ], this->mMassRange [ 1 ]); particle.mState = this; } //----------------------------------------------------------------// MOAIParticleState::MOAIParticleState () : mDamping ( 0.0f ) { RTTI_BEGIN RTTI_EXTEND ( MOAILuaObject ) RTTI_END this->mMassRange [ 0 ] = 1.0f; this->mMassRange [ 1 ] = 1.0f; this->mTermRange [ 0 ] = 1.0f; this->mTermRange [ 1 ] = 1.0f; } //----------------------------------------------------------------// MOAIParticleState::~MOAIParticleState () { this->ClearForces (); this->mInit.Set ( *this, 0 ); this->mRender.Set ( *this, 0 ); this->mPlugin.Set ( *this, 0 ); this->mNext.Set ( *this, 0 ); } //----------------------------------------------------------------// void MOAIParticleState::PushForce ( MOAIParticleForce& force ) { this->LuaRetain ( &force ); ForceNode* forceNode = new ForceNode (); forceNode->Data ( &force ); this->mForces.PushBack ( *forceNode ); } //----------------------------------------------------------------// void MOAIParticleState::RegisterLuaClass ( MOAILuaState& state ) { UNUSED ( state ); } //----------------------------------------------------------------// void MOAIParticleState::RegisterLuaFuncs ( MOAILuaState& state ) { luaL_Reg regTable [] = { { "clearForces", _clearForces }, { "pushForce", _pushForce }, { "setDamping", _setDamping }, { "setInitScript", _setInitScript }, { "setMass", _setMass }, { "setPlugin", _setPlugin }, { "setNext", _setNext }, { "setRenderScript", _setRenderScript }, { "setTerm", _setTerm }, { NULL, NULL } }; luaL_register ( state, 0, regTable ); } //----------------------------------------------------------------// void MOAIParticleState::ProcessParticle ( MOAIParticleSystem& system, MOAIParticle& particle, float step ) { float t0 = particle.mAge / particle.mTerm; particle.mAge += step; if ( particle.mAge > particle.mTerm ) { particle.mAge = particle.mTerm; } float t1 = particle.mAge / particle.mTerm; float* r = particle.mData; ZLVec3D loc; ZLVec3D vel; loc.mX = r [ MOAIParticle::PARTICLE_X ]; loc.mY = r [ MOAIParticle::PARTICLE_Y ]; loc.mZ = 0.0f; vel.mX = r [ MOAIParticle::PARTICLE_DX ]; vel.mY = r [ MOAIParticle::PARTICLE_DY ]; vel.mZ = 0.0f; this->GatherForces ( loc, vel, particle.mMass, step ); r [ MOAIParticle::PARTICLE_X ] = loc.mX; r [ MOAIParticle::PARTICLE_Y ] = loc.mY; r [ MOAIParticle::PARTICLE_DX ] = vel.mX; r [ MOAIParticle::PARTICLE_DY ] = vel.mY; if ( this->mRender ) { this->mRender->Run ( system, particle, t0, t1 ); } MOAIParticlePlugin* plugin = this->mPlugin; if ( plugin ) { AKUParticleSprite sprite; plugin->OnRender ( particle.mData, &particle.mData [ MOAIParticle::TOTAL_PARTICLE_REG ], &sprite, t0, t1, particle.mTerm ); system.PushSprite ( sprite ); } if ( particle.mAge >= particle.mTerm ) { if ( this->mNext ) { this->mNext->InitParticle ( system, particle ); } else { particle.mState = 0; } } }
412
0.92166
1
0.92166
game-dev
MEDIA
0.914901
game-dev
0.965452
1
0.965452
mayao11/PracticalGameAI
1,618
AI_Enemy3_Behavior/Assets/Behavior Designer/Runtime/Basic Tasks/Rigidbody/AddForce.cs
using UnityEngine; namespace BehaviorDesigner.Runtime.Tasks.Basic.UnityRigidbody { [RequiredComponent(typeof(Rigidbody))] [TaskCategory("Basic/Rigidbody")] [TaskDescription("Applies a force to the rigidbody. Returns Success.")] public class AddForce : Action { [Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")] public SharedGameObject targetGameObject; [Tooltip("The amount of force to apply")] public SharedVector3 force; [Tooltip("The type of force")] public ForceMode forceMode = ForceMode.Force; // cache the rigidbody component private Rigidbody rigidbody; private GameObject prevGameObject; public override void OnStart() { var currentGameObject = GetDefaultGameObject(targetGameObject.Value); if (currentGameObject != prevGameObject) { rigidbody = currentGameObject.GetComponent<Rigidbody>(); prevGameObject = currentGameObject; } } public override TaskStatus OnUpdate() { if (rigidbody == null) { Debug.LogWarning("Rigidbody is null"); return TaskStatus.Failure; } rigidbody.AddForce(force.Value, forceMode); return TaskStatus.Success; } public override void OnReset() { targetGameObject = null; if (force != null) { force.Value = Vector3.zero; } forceMode = ForceMode.Force; } } }
412
0.633656
1
0.633656
game-dev
MEDIA
0.978099
game-dev
0.839471
1
0.839471
ixray-team/ixray-1.6-stcop
3,741
src/xrGame/ui/UICellItem.h
#pragma once #include "../../xrUI/Widgets/UIStatic.h" #include "../../xrUI/Widgets/UIDialogWnd.h" class CUIDragItem; class CUIDragDropListEx; class CUICellItem; class CUIProgressBar; class ICustomDrawCellItem { public: virtual ~ICustomDrawCellItem () {}; virtual void OnDraw (CUICellItem* cell) = 0; }; class ICustomDrawDragItem { public: virtual ~ICustomDrawDragItem () {}; virtual void OnDraw (CUIDragItem* drag_item) = 0; }; class CUICellItem :public CUIStatic { private: typedef CUIStatic inherited; protected: xr_vector<CUICellItem*> m_childs; CUIDragDropListEx* m_pParentList; CUIProgressBar* m_pConditionState; Ivector2 m_grid_size; ICustomDrawCellItem* m_custom_draw; int m_accelerator; CUIStatic* m_text; CUIStatic* m_upgrade; Fvector2 m_upgrade_pos; CUIStatic* m_custom_text; Fvector2 m_custom_text_pos; CUIStatic* m_custom_mark; Fvector2 m_custom_mark_pos; virtual void UpdateItemText (); void init (); public: CUICellItem (); virtual ~CUICellItem (); virtual bool OnKeyboardAction (int dik, EUIMessages keyboard_action); virtual bool OnMouseAction (float x, float y, EUIMessages mouse_action); virtual void Draw (); virtual void Update (); void UpdateCustomMarksAndText(); virtual void OnAfterChild (CUIDragDropListEx* parent_list) {}; u32 ChildsCount (); void PushChild (CUICellItem*); CUICellItem* PopChild (CUICellItem*); CUICellItem* Child (u32 idx) {return m_childs[idx];}; bool HasChild (CUICellItem* item); virtual bool EqualTo (CUICellItem* itm); IC const Ivector2& GetGridSize () {return m_grid_size;}; //size in grid IC void SetAccelerator (int dik) {m_accelerator=dik;}; IC int GetAccelerator () const {return m_accelerator;}; virtual CUIDragItem* CreateDragItem (); CUIDragDropListEx* OwnerList () {return m_pParentList;} void SetOwnerList (CUIDragDropListEx* p); void UpdateConditionProgressBar(); void SetCustomDraw (ICustomDrawCellItem* c); void Mark (bool status); CUIStatic& get_ui_text () const { return *m_text; } virtual bool IsHelper () { return false; } virtual void SetIsHelper (bool is_helper) { ; } virtual CUIWindow* ui_cast_window() { return this; } virtual CUIStatic* ui_cast_static() { return this; } virtual CUICellItem* ui_cast_cell_item() { return this; } public: static CUICellItem* m_mouse_selected_item; void* m_pData; int m_index; u32 m_drawn_frame; bool m_b_destroy_childs; bool m_selected; bool m_select_armament; bool m_select_equipped; bool m_cur_mark; bool m_has_upgrade; bool m_with_custom_text; bool m_with_custom_mark; }; class CUIDragItem: public CUIWindow, public pureRender, public pureFrame { typedef CUIWindow inherited; CUIStatic m_static; CUICellItem* m_pParent; Fvector2 m_pos_offset; CUIDragDropListEx* m_back_list; ICustomDrawDragItem* m_custom_draw; public: CUIDragItem(CUICellItem* parent); virtual void Init(const ui_shader& sh, const Frect& rect, const Frect& text_rect); virtual ~CUIDragItem(); void SetCustomDraw (ICustomDrawDragItem* c); CUIStatic* wnd () {return &m_static;} virtual bool OnMouseAction (float x, float y, EUIMessages mouse_action); virtual void Draw (); virtual void OnRender (); virtual void _BCL OnFrame (); CUICellItem* ParentItem () {return m_pParent;} void SetBackList (CUIDragDropListEx*l); CUIDragDropListEx* BackList () {return m_back_list;} Fvector2 GetPosition (); };
412
0.902594
1
0.902594
game-dev
MEDIA
0.422102
game-dev
0.574488
1
0.574488
wirechat/wirechat
2,202
src/Livewire/Concerns/ModalComponent.php
<?php namespace Wirechat\Wirechat\Livewire\Concerns; use Livewire\Component; abstract class ModalComponent extends Component { public bool $forceClose = false; public int $skipModals = 0; public bool $destroySkipped = false; public function destroySkippedModals(): self { $this->destroySkipped = true; return $this; } public function skipPreviousModals($count = 1, $destroy = false): self { $this->skipPreviousModal($count, $destroy); return $this; } public function skipPreviousModal($count = 1, $destroy = false): self { $this->skipModals = $count; $this->destroySkipped = $destroy; return $this; } public function forceClose(): self { $this->forceClose = true; return $this; } public function closeWirechatModal(): void { $this->dispatch('closeWirechatModal', force: $this->forceClose, skipPreviousModals: $this->skipModals, destroySkipped: $this->destroySkipped); } public function closeChatDrawer(): void { $this->dispatch('closeChatDrawer', force: $this->forceClose, skipPreviousModals: $this->skipModals, destroySkipped: $this->destroySkipped); } public function closeModalWithEvents(array $events): void { $this->emitModalEvents($events); // $this->closeModal(); $this->closeWirechatModal(); $this->closeChatDrawer(); } public static function modalAttributes(): array { return [ 'closeOnEscape' => true, 'closeOnEscapeIsForceful' => false, 'dispatchCloseEvent' => false, 'destroyOnClose' => false, 'closeOnClickAway' => true, ]; } private function emitModalEvents(array $events): void { foreach ($events as $component => $event) { if (is_array($event)) { [$event, $params] = $event; } if (is_numeric($component)) { $this->dispatch($event, ...$params ?? []); } else { $this->dispatch($event, ...$params ?? [])->to($component); } } } }
412
0.861648
1
0.861648
game-dev
MEDIA
0.934601
game-dev
0.888569
1
0.888569
lzk228/space-axolotl-14
2,694
Content.Server/Lightning/Components/LightningTargetComponent.cs
using Content.Server.Tesla.EntitySystems; using Content.Shared.Explosion; using Content.Shared.FixedPoint; using Robust.Shared.Prototypes; namespace Content.Server.Lightning.Components; /// <summary> /// This component allows the lightning system to select a given entity as the target of a lightning strike. /// It also determines the priority of selecting this target, and the behavior of the explosion. Used for tesla. /// </summary> [RegisterComponent, Access(typeof(LightningSystem), typeof(LightningTargetSystem))] public sealed partial class LightningTargetComponent : Component { /// <summary> /// The probability that this target will not be ignored by a lightning strike. This is necessary for Tesla's balance. /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public float HitProbability = 1f; /// <summary> /// Priority level for selecting a lightning target. /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public int Priority; /// <summary> /// Lightning has a number of bounces into neighboring targets. /// This number controls how many bounces the lightning bolt has left after hitting that target. /// At high values, the lightning will not travel farther than that entity. /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public int LightningResistance = 1; //by default, reduces the number of bounces from this target by 1 // BOOM PART /// <summary> /// Will the entity explode after being struck by lightning? /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public bool LightningExplode = true; /// <summary> /// The explosion prototype to spawn /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public ProtoId<ExplosionPrototype> ExplosionPrototype = "Default"; /// <summary> /// The total amount of intensity an explosion can achieve /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public float TotalIntensity = 25f; /// <summary> /// How quickly does the explosion's power slope? Higher = smaller area and more concentrated damage, lower = larger area and more spread out damage /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public float Dropoff = 2f; /// <summary> /// How much intensity can be applied per tile? /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public float MaxTileIntensity = 5f; /// <summary> /// how much structural damage the object takes from a lightning strike /// </summary> [DataField] public FixedPoint2 DamageFromLightning = 1; }
412
0.749302
1
0.749302
game-dev
MEDIA
0.885766
game-dev
0.629663
1
0.629663
remmintan/minefortress
2,592
src/main/java/org/minefortress/mixins/renderer/gui/worldcreator/FortressCreateWorldScreenMixin.java
package org.minefortress.mixins.renderer.gui.worldcreator; import com.mojang.serialization.Lifecycle; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.screen.world.CreateWorldScreen; import net.minecraft.client.gui.screen.world.WorldCreator; import net.minecraft.server.integrated.IntegratedServerLoader; import net.minecraft.text.Text; import net.minecraft.world.SaveProperties; import net.remmintan.mods.minefortress.core.interfaces.IFortressGamemodeHolder; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(CreateWorldScreen.class) public abstract class FortressCreateWorldScreenMixin extends Screen { @Shadow public abstract WorldCreator getWorldCreator(); protected FortressCreateWorldScreenMixin(Text title) { super(title); } @Inject(method = "init", at = @At("HEAD")) public void init(CallbackInfo ci) { this.getWorldCreator().setGameMode(WorldCreator.Mode.DEBUG); } @Redirect(method = "createLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/integrated/IntegratedServerLoader;tryLoad(Lnet/minecraft/client/MinecraftClient;Lnet/minecraft/client/gui/screen/world/CreateWorldScreen;Lcom/mojang/serialization/Lifecycle;Ljava/lang/Runnable;Z)V")) private void tryLoad(MinecraftClient client, CreateWorldScreen parent, Lifecycle lifecycle, Runnable loader, boolean bypassWarnings) { // bypassing the warning screen IntegratedServerLoader.tryLoad(client, parent, lifecycle, loader, true); } @ModifyArg(method = "startServer", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/integrated/IntegratedServerLoader;start(Lnet/minecraft/world/level/storage/LevelStorage$Session;Lnet/minecraft/server/DataPackContents;Lnet/minecraft/registry/CombinedDynamicRegistries;Lnet/minecraft/world/SaveProperties;)V")) public SaveProperties updateLevelPropsBeforeStartingAServer(SaveProperties props) { final var worldCreator = this.getWorldCreator(); if (props instanceof IFortressGamemodeHolder wcProps && worldCreator instanceof IFortressGamemodeHolder creator) { wcProps.set_fortressGamemode(creator.get_fortressGamemode()); } return props; } }
412
0.929105
1
0.929105
game-dev
MEDIA
0.992941
game-dev
0.79977
1
0.79977
anjo76/angelscript
1,598
sdk/samples/game/source/scriptmgr.h
#ifndef SCRIPTMGR_H #define SCRIPTMGR_H #include <string> #include <vector> #include <angelscript.h> #include "../../../add_on/scripthandle/scripthandle.h" class CGameObj; class CScriptMgr { public: CScriptMgr(); ~CScriptMgr(); int Init(); asIScriptObject *CreateController(const std::string &type, CGameObj *obj); void CallOnThink(asIScriptObject *object); void CallOnMessage(asIScriptObject *object, CScriptHandle &msg, CGameObj *caller); bool hasCompileErrors; protected: void MessageCallback(const asSMessageInfo &msg); asIScriptContext *PrepareContextFromPool(asIScriptFunction *func); void ReturnContextToPool(asIScriptContext *ctx); int ExecuteCall(asIScriptContext *ctx); struct SController { SController() : type(0), factoryFunc(0), onThinkMethod(0), onMessageMethod(0) {} std::string module; asITypeInfo *type; asIScriptFunction *factoryFunc; asIScriptFunction *onThinkMethod; asIScriptFunction *onMessageMethod; }; SController *GetControllerScript(const std::string &type); asIScriptEngine *engine; // Our pool of script contexts. This is used to avoid allocating // the context objects all the time. The context objects are quite // heavy weight and should be shared between function calls. std::vector<asIScriptContext *> contexts; // This is the cache of function ids etc that we use to avoid having // to search for the function ids everytime we need to call a function. // The search is quite time consuming and should only be done once. std::vector<SController *> controllers; }; extern CScriptMgr *scriptMgr; #endif
412
0.803637
1
0.803637
game-dev
MEDIA
0.300491
game-dev
0.634777
1
0.634777
Arius-Scripts/ars_ambulancejob
3,967
modules/compatibility/frameworks/esx/server.lua
local ESX = GetResourceState('es_extended'):find('start') and exports['es_extended']:getSharedObject() or nil if not ESX then return end Framework = {} local useOxInventory = lib.load("config").useOxInventory local ox_inventory = useOxInventory and exports.ox_inventory function Framework.removeAccountMoney(target, account, amount) local xPlayer = ESX.GetPlayerFromId(target) if not xPlayer then return end xPlayer.removeAccountMoney(account, amount) end function Framework.hasJob(target, jobs) local xPlayer = ESX.GetPlayerFromId(target) if not xPlayer then return end if type(jobs) == "table" then for index, jobName in pairs(jobs) do if xPlayer.job.name == jobName then return true end end else return xPlayer.job.name == jobs end return false end function Framework.playerJob(target) local xPlayer = ESX.GetPlayerFromId(target) if not xPlayer then return end return xPlayer.job.name end function Framework.updateStatus(data) local xPlayer = ESX.GetPlayerFromId(data.target) MySQL.update('UPDATE users SET is_dead = ? WHERE identifier = ?', { data.status, xPlayer.identifier }) if not player[data.target] then player[data.target] = {} end player[data.target].isDead = data.status if data.status == true then player[data.target].killedBy = data.killedBy end end function Framework.getPlayerName(target) local xPlayer = ESX.GetPlayerFromId(target) if not xPlayer then return end return xPlayer.getName() end function Framework.getDeathStatus(target) local xPlayer = ESX.GetPlayerFromId(target) if not xPlayer then return end local isDead = MySQL.scalar.await('SELECT `is_dead` FROM `users` WHERE `identifier` = ? LIMIT 1', { xPlayer.identifier }) local data = { isDead = isDead } return data end function Framework.addItem(target, item, amount) if ox_inventory then return ox_inventory:AddItem(target, item, amount) end local xPlayer = ESX.GetPlayerFromId(target) if not xPlayer then return end return xPlayer.addInventoryItem(item, amount) end function Framework.removeItem(target, item, amount) if ox_inventory then return ox_inventory:RemoveItem(target, item, amount) end local xPlayer = ESX.GetPlayerFromId(target) if not xPlayer then return end return xPlayer.removeInventoryItem(item, amount) end function Framework.wipeInventory(target, keep) if ox_inventory then return ox_inventory:ClearInventory(target, keep) end local xPlayer = ESX.GetPlayerFromId(target) if not xPlayer then return end for _, item in pairs(xPlayer.inventory) do local found = false for index, keepItem in pairs(keep) do if string.lower(item.name) == string.lower(keepItem) then found = true break end end if item.count > 0 and not found then xPlayer.setInventoryItem(item.name, 0) end end end local medicBagItem = lib.load("config").medicBagItem local emsJobs = lib.load("config").emsJobs local tabletItem = lib.load("config").tabletItem ESX.RegisterUsableItem(medicBagItem, function(source, a, b) if not Framework.hasJob(source, emsJobs) then return end TriggerClientEvent("ars_ambulancejob:placeMedicalBag", source) end) ESX.RegisterUsableItem(tabletItem, function(source, a, b) if not Framework.hasJob(source, emsJobs) then return end TriggerClientEvent("ars_ambulancejob:openDistressCalls", source) end) if GetResourceState('esx_society'):find('start') then CreateThread(function() for k, v in pairs(emsJobs) do TriggerEvent('esx_society:registerSociety', v, v, 'society_' .. v, 'society_' .. v, 'society_' .. v, { type = 'public' }) end end) else print("^6[Warning] > ^7 esx_society ^6needs to be started") end
412
0.926155
1
0.926155
game-dev
MEDIA
0.868178
game-dev
0.914541
1
0.914541
danoon2/Boxedwine
4,625
lib/sdl1/docs/html/guideeventexamples.html
<HTML ><HEAD ><TITLE >Event Examples</TITLE ><META NAME="GENERATOR" CONTENT="Modular DocBook HTML Stylesheet Version 1.76b+ "><LINK REL="HOME" TITLE="SDL Library Documentation" HREF="index.html"><LINK REL="UP" TITLE="Examples" HREF="guideexamples.html"><LINK REL="PREVIOUS" TITLE="Examples" HREF="guideexamples.html"><LINK REL="NEXT" TITLE="Audio Examples" HREF="guideaudioexamples.html"></HEAD ><BODY CLASS="SECT1" BGCOLOR="#FFF8DC" TEXT="#000000" LINK="#0000ee" VLINK="#551a8b" ALINK="#ff0000" ><DIV CLASS="NAVHEADER" ><TABLE SUMMARY="Header navigation table" WIDTH="100%" BORDER="0" CELLPADDING="0" CELLSPACING="0" ><TR ><TH COLSPAN="3" ALIGN="center" >SDL Library Documentation</TH ></TR ><TR ><TD WIDTH="10%" ALIGN="left" VALIGN="bottom" ><A HREF="guideexamples.html" ACCESSKEY="P" >Prev</A ></TD ><TD WIDTH="80%" ALIGN="center" VALIGN="bottom" >Chapter 4. Examples</TD ><TD WIDTH="10%" ALIGN="right" VALIGN="bottom" ><A HREF="guideaudioexamples.html" ACCESSKEY="N" >Next</A ></TD ></TR ></TABLE ><HR ALIGN="LEFT" WIDTH="100%"></DIV ><DIV CLASS="SECT1" ><H1 CLASS="SECT1" ><A NAME="GUIDEEVENTEXAMPLES" ></A >Event Examples</H1 ><P ></P ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="AEN375" ></A >Filtering and Handling Events</H2 ><P ><PRE CLASS="PROGRAMLISTING" >#include &#60;stdio.h&#62; #include &#60;stdlib.h&#62; #include "SDL.h" /* This function may run in a separate event thread */ int FilterEvents(const SDL_Event *event) { static int boycott = 1; /* This quit event signals the closing of the window */ if ( (event-&#62;type == SDL_QUIT) &#38;&#38; boycott ) { printf("Quit event filtered out -- try again.\n"); boycott = 0; return(0); } if ( event-&#62;type == SDL_MOUSEMOTION ) { printf("Mouse moved to (%d,%d)\n", event-&#62;motion.x, event-&#62;motion.y); return(0); /* Drop it, we've handled it */ } return(1); } int main(int argc, char *argv[]) { SDL_Event event; /* Initialize the SDL library (starts the event loop) */ if ( SDL_Init(SDL_INIT_VIDEO) &#60; 0 ) { fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); exit(1); } /* Clean up on exit, exit on window close and interrupt */ atexit(SDL_Quit); /* Ignore key events */ SDL_EventState(SDL_KEYDOWN, SDL_IGNORE); SDL_EventState(SDL_KEYUP, SDL_IGNORE); /* Filter quit and mouse motion events */ SDL_SetEventFilter(FilterEvents); /* The mouse isn't much use unless we have a display for reference */ if ( SDL_SetVideoMode(640, 480, 8, 0) == NULL ) { fprintf(stderr, "Couldn't set 640x480x8 video mode: %s\n", SDL_GetError()); exit(1); } /* Loop waiting for ESC+Mouse_Button */ while ( SDL_WaitEvent(&#38;event) &#62;= 0 ) { switch (event.type) { case SDL_ACTIVEEVENT: { if ( event.active.state &#38; SDL_APPACTIVE ) { if ( event.active.gain ) { printf("App activated\n"); } else { printf("App iconified\n"); } } } break; case SDL_MOUSEBUTTONDOWN: { Uint8 *keys; keys = SDL_GetKeyState(NULL); if ( keys[SDLK_ESCAPE] == SDL_PRESSED ) { printf("Bye bye...\n"); exit(0); } printf("Mouse button pressed\n"); } break; case SDL_QUIT: { printf("Quit requested, quitting.\n"); exit(0); } break; } } /* This should never happen */ printf("SDL_WaitEvent error: %s\n", SDL_GetError()); exit(1); }</PRE ></P ></DIV ></DIV ><DIV CLASS="NAVFOOTER" ><HR ALIGN="LEFT" WIDTH="100%"><TABLE SUMMARY="Footer navigation table" WIDTH="100%" BORDER="0" CELLPADDING="0" CELLSPACING="0" ><TR ><TD WIDTH="33%" ALIGN="left" VALIGN="top" ><A HREF="guideexamples.html" ACCESSKEY="P" >Prev</A ></TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A HREF="index.html" ACCESSKEY="H" >Home</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" ><A HREF="guideaudioexamples.html" ACCESSKEY="N" >Next</A ></TD ></TR ><TR ><TD WIDTH="33%" ALIGN="left" VALIGN="top" >Examples</TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A HREF="guideexamples.html" ACCESSKEY="U" >Up</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" >Audio Examples</TD ></TR ></TABLE ></DIV ></BODY ></HTML >
412
0.581216
1
0.581216
game-dev
MEDIA
0.579114
game-dev
0.717599
1
0.717599
ProjectIgnis/CardScripts
1,817
official/c36569343.lua
--紅炎の騎士 --Brushfire Knight local s,id=GetID() function s.initial_effect(c) --send to grave local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_TOGRAVE) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1,id) e1:SetCode(EVENT_TO_GRAVE) e1:SetCondition(s.tgcon1) e1:SetTarget(s.tgtg) e1:SetOperation(s.tgop1) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(id,0)) e2:SetCategory(CATEGORY_TOGRAVE) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e2:SetCountLimit(1,id) e2:SetCode(EVENT_TO_GRAVE) e2:SetCondition(s.tgcon2) e2:SetTarget(s.tgtg) e2:SetOperation(s.tgop2) c:RegisterEffect(e2) end function s.cfilter(c,tp) return c:IsControler(tp) and c:IsReason(REASON_DESTROY) and c:IsAttribute(ATTRIBUTE_FIRE) end function s.tgcon1(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(s.cfilter,1,nil,tp) end function s.tgtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK) end function s.tgop1(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsFacedown() or not c:IsRelateToEffect(e) then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,s.tgfilter,tp,LOCATION_DECK,0,1,1,nil) if #g>0 then Duel.SendtoGrave(g,REASON_EFFECT) end end function s.tgcon2(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsReason(REASON_DESTROY) end function s.tgfilter(c) return c:IsMonster() and c:IsAttribute(ATTRIBUTE_FIRE) and c:IsAbleToGrave() end function s.tgop2(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,s.tgfilter,tp,LOCATION_DECK,0,1,1,nil) if #g>0 then Duel.SendtoGrave(g,REASON_EFFECT) end end
412
0.914642
1
0.914642
game-dev
MEDIA
0.796277
game-dev
0.97653
1
0.97653
narknon/FF7R2UProj
2,450
Source/EndGame/Public/EndMobSwitchingVolume.h
#pragma once #include "CoreMinimal.h" #include "UObject/NoExportTypes.h" #include "UObject/NoExportTypes.h" #include "GameFramework/Actor.h" #include "EEndAiMoveType.h" #include "EEndMobMoveDirectionType.h" #include "Templates/SubclassOf.h" #include "EndMobSwitchingVolume.generated.h" class AEndMobPrefabActor; class UEndAssetDataAsset; UCLASS(Blueprintable) class AEndMobSwitchingVolume : public AActor { GENERATED_BODY() public: protected: UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bOverrideAiMoveType; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) EEndAiMoveType OverrideAiMoveType; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bOverrideMoveDirectionType; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) EEndMobMoveDirectionType OverrideMoveDirectionType; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bBindToMobPrefab; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TSubclassOf<AEndMobPrefabActor> MobPrefabClass; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bStopBeforeBind; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bLookAt; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) FName LookAtTargetPointName; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bSetLocationWork; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) FName LocationWorkID; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 LocationWorkValue; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) FTransform BoxRelativeTransform; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) FBox AABB; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) FTransform PrefabRelativeTransform; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TArray<TSoftObjectPtr<UEndAssetDataAsset>> MobMotionPacks; public: AEndMobSwitchingVolume(const FObjectInitializer& ObjectInitializer); };
412
0.902105
1
0.902105
game-dev
MEDIA
0.877442
game-dev
0.578434
1
0.578434
tanersener/mobile-ffmpeg
28,771
src/sdl/src/video/directfb/SDL_DirectFB_events.c
/* Simple DirectMedia Layer Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.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. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_DIRECTFB /* Handle the event stream, converting DirectFB input events into SDL events */ #include "SDL_DirectFB_video.h" #include "SDL_DirectFB_window.h" #include "SDL_DirectFB_modes.h" #include "SDL_syswm.h" #include "../../events/SDL_mouse_c.h" #include "../../events/SDL_keyboard_c.h" #include "../../events/SDL_windowevents_c.h" #include "../../events/SDL_events_c.h" #include "../../events/scancodes_linux.h" #include "../../events/scancodes_xfree86.h" #include "SDL_DirectFB_events.h" #if USE_MULTI_API #define SDL_SendMouseMotion_ex(w, id, relative, x, y, p) SDL_SendMouseMotion(w, id, relative, x, y, p) #define SDL_SendMouseButton_ex(w, id, state, button) SDL_SendMouseButton(w, id, state, button) #define SDL_SendKeyboardKey_ex(id, state, scancode) SDL_SendKeyboardKey(id, state, scancode) #define SDL_SendKeyboardText_ex(id, text) SDL_SendKeyboardText(id, text) #else #define SDL_SendMouseMotion_ex(w, id, relative, x, y, p) SDL_SendMouseMotion(w, id, relative, x, y) #define SDL_SendMouseButton_ex(w, id, state, button) SDL_SendMouseButton(w, id, state, button) #define SDL_SendKeyboardKey_ex(id, state, scancode) SDL_SendKeyboardKey(state, scancode) #define SDL_SendKeyboardText_ex(id, text) SDL_SendKeyboardText(text) #endif typedef struct _cb_data cb_data; struct _cb_data { DFB_DeviceData *devdata; int sys_ids; int sys_kbd; }; /* The translation tables from a DirectFB keycode to a SDL keysym */ static SDL_Scancode oskeymap[256]; static SDL_Keysym *DirectFB_TranslateKey(_THIS, DFBWindowEvent * evt, SDL_Keysym * keysym, Uint32 *unicode); static SDL_Keysym *DirectFB_TranslateKeyInputEvent(_THIS, DFBInputEvent * evt, SDL_Keysym * keysym, Uint32 *unicode); static void DirectFB_InitOSKeymap(_THIS, SDL_Scancode * keypmap, int numkeys); static int DirectFB_TranslateButton(DFBInputDeviceButtonIdentifier button); static void UnicodeToUtf8( Uint16 w , char *utf8buf) { unsigned char *utf8s = (unsigned char *) utf8buf; if ( w < 0x0080 ) { utf8s[0] = ( unsigned char ) w; utf8s[1] = 0; } else if ( w < 0x0800 ) { utf8s[0] = 0xc0 | (( w ) >> 6 ); utf8s[1] = 0x80 | (( w ) & 0x3f ); utf8s[2] = 0; } else { utf8s[0] = 0xe0 | (( w ) >> 12 ); utf8s[1] = 0x80 | (( ( w ) >> 6 ) & 0x3f ); utf8s[2] = 0x80 | (( w ) & 0x3f ); utf8s[3] = 0; } } static void FocusAllMice(_THIS, SDL_Window *window) { #if USE_MULTI_API SDL_DFB_DEVICEDATA(_this); int index; for (index = 0; index < devdata->num_mice; index++) SDL_SetMouseFocus(devdata->mouse_id[index], id); #else SDL_SetMouseFocus(window); #endif } static void FocusAllKeyboards(_THIS, SDL_Window *window) { #if USE_MULTI_API SDL_DFB_DEVICEDATA(_this); int index; for (index = 0; index < devdata->num_keyboard; index++) SDL_SetKeyboardFocus(index, id); #else SDL_SetKeyboardFocus(window); #endif } static void MotionAllMice(_THIS, int x, int y) { #if USE_MULTI_API SDL_DFB_DEVICEDATA(_this); int index; for (index = 0; index < devdata->num_mice; index++) { SDL_Mouse *mouse = SDL_GetMouse(index); mouse->x = mouse->last_x = x; mouse->y = mouse->last_y = y; /* SDL_SendMouseMotion(devdata->mouse_id[index], 0, x, y, 0); */ } #endif } static int KbdIndex(_THIS, int id) { SDL_DFB_DEVICEDATA(_this); int index; for (index = 0; index < devdata->num_keyboard; index++) { if (devdata->keyboard[index].id == id) return index; } return -1; } static int ClientXY(DFB_WindowData * p, int *x, int *y) { int cx, cy; cx = *x; cy = *y; cx -= p->client.x; cy -= p->client.y; if (cx < 0 || cy < 0) return 0; if (cx >= p->client.w || cy >= p->client.h) return 0; *x = cx; *y = cy; return 1; } static void ProcessWindowEvent(_THIS, SDL_Window *sdlwin, DFBWindowEvent * evt) { SDL_DFB_DEVICEDATA(_this); SDL_DFB_WINDOWDATA(sdlwin); SDL_Keysym keysym; Uint32 unicode; char text[SDL_TEXTINPUTEVENT_TEXT_SIZE]; if (evt->clazz == DFEC_WINDOW) { switch (evt->type) { case DWET_BUTTONDOWN: if (ClientXY(windata, &evt->x, &evt->y)) { if (!devdata->use_linux_input) { SDL_SendMouseMotion_ex(sdlwin, devdata->mouse_id[0], 0, evt->x, evt->y, 0); SDL_SendMouseButton_ex(sdlwin, devdata->mouse_id[0], SDL_PRESSED, DirectFB_TranslateButton (evt->button)); } else { MotionAllMice(_this, evt->x, evt->y); } } break; case DWET_BUTTONUP: if (ClientXY(windata, &evt->x, &evt->y)) { if (!devdata->use_linux_input) { SDL_SendMouseMotion_ex(sdlwin, devdata->mouse_id[0], 0, evt->x, evt->y, 0); SDL_SendMouseButton_ex(sdlwin, devdata->mouse_id[0], SDL_RELEASED, DirectFB_TranslateButton (evt->button)); } else { MotionAllMice(_this, evt->x, evt->y); } } break; case DWET_MOTION: if (ClientXY(windata, &evt->x, &evt->y)) { if (!devdata->use_linux_input) { if (!(sdlwin->flags & SDL_WINDOW_INPUT_GRABBED)) SDL_SendMouseMotion_ex(sdlwin, devdata->mouse_id[0], 0, evt->x, evt->y, 0); } else { /* relative movements are not exact! * This code should limit the number of events sent. * However it kills MAME axis recognition ... */ static int cnt = 0; if (1 && ++cnt > 20) { MotionAllMice(_this, evt->x, evt->y); cnt = 0; } } if (!(sdlwin->flags & SDL_WINDOW_MOUSE_FOCUS)) SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_ENTER, 0, 0); } break; case DWET_KEYDOWN: if (!devdata->use_linux_input) { DirectFB_TranslateKey(_this, evt, &keysym, &unicode); /* printf("Scancode %d %d %d\n", keysym.scancode, evt->key_code, evt->key_id); */ SDL_SendKeyboardKey_ex(0, SDL_PRESSED, keysym.scancode); if (SDL_EventState(SDL_TEXTINPUT, SDL_QUERY)) { SDL_zero(text); UnicodeToUtf8(unicode, text); if (*text) { SDL_SendKeyboardText_ex(0, text); } } } break; case DWET_KEYUP: if (!devdata->use_linux_input) { DirectFB_TranslateKey(_this, evt, &keysym, &unicode); SDL_SendKeyboardKey_ex(0, SDL_RELEASED, keysym.scancode); } break; case DWET_POSITION: if (ClientXY(windata, &evt->x, &evt->y)) { SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_MOVED, evt->x, evt->y); } break; case DWET_POSITION_SIZE: if (ClientXY(windata, &evt->x, &evt->y)) { SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_MOVED, evt->x, evt->y); } /* fall throught */ case DWET_SIZE: /* FIXME: what about < 0 */ evt->w -= (windata->theme.right_size + windata->theme.left_size); evt->h -= (windata->theme.top_size + windata->theme.bottom_size + windata->theme.caption_size); SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_RESIZED, evt->w, evt->h); break; case DWET_CLOSE: SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_CLOSE, 0, 0); break; case DWET_GOTFOCUS: DirectFB_SetContext(_this, sdlwin); FocusAllKeyboards(_this, sdlwin); SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_FOCUS_GAINED, 0, 0); break; case DWET_LOSTFOCUS: SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0); FocusAllKeyboards(_this, 0); break; case DWET_ENTER: /* SDL_DirectFB_ReshowCursor(_this, 0); */ FocusAllMice(_this, sdlwin); /* FIXME: when do we really enter ? */ if (ClientXY(windata, &evt->x, &evt->y)) MotionAllMice(_this, evt->x, evt->y); SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_ENTER, 0, 0); break; case DWET_LEAVE: SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_LEAVE, 0, 0); FocusAllMice(_this, 0); /* SDL_DirectFB_ReshowCursor(_this, 1); */ break; default: ; } } else printf("Event Clazz %d\n", evt->clazz); } static void ProcessInputEvent(_THIS, DFBInputEvent * ievt) { SDL_DFB_DEVICEDATA(_this); SDL_Keysym keysym; int kbd_idx; Uint32 unicode; char text[SDL_TEXTINPUTEVENT_TEXT_SIZE]; if (!devdata->use_linux_input) { if (ievt->type == DIET_AXISMOTION) { if ((devdata->grabbed_window != NULL) && (ievt->flags & DIEF_AXISREL)) { if (ievt->axis == DIAI_X) SDL_SendMouseMotion_ex(devdata->grabbed_window, ievt->device_id, 1, ievt->axisrel, 0, 0); else if (ievt->axis == DIAI_Y) SDL_SendMouseMotion_ex(devdata->grabbed_window, ievt->device_id, 1, 0, ievt->axisrel, 0); } } } else { static int last_x, last_y; switch (ievt->type) { case DIET_AXISMOTION: if (ievt->flags & DIEF_AXISABS) { if (ievt->axis == DIAI_X) last_x = ievt->axisabs; else if (ievt->axis == DIAI_Y) last_y = ievt->axisabs; if (!(ievt->flags & DIEF_FOLLOW)) { #if USE_MULTI_API SDL_Mouse *mouse = SDL_GetMouse(ievt->device_id); SDL_Window *window = SDL_GetWindowFromID(mouse->focus); #else SDL_Window *window = devdata->grabbed_window; #endif if (window) { DFB_WindowData *windata = (DFB_WindowData *) window->driverdata; int x, y; windata->dfbwin->GetPosition(windata->dfbwin, &x, &y); SDL_SendMouseMotion_ex(window, ievt->device_id, 0, last_x - (x + windata->client.x), last_y - (y + windata->client.y), 0); } else { SDL_SendMouseMotion_ex(window, ievt->device_id, 0, last_x, last_y, 0); } } } else if (ievt->flags & DIEF_AXISREL) { if (ievt->axis == DIAI_X) SDL_SendMouseMotion_ex(devdata->grabbed_window, ievt->device_id, 1, ievt->axisrel, 0, 0); else if (ievt->axis == DIAI_Y) SDL_SendMouseMotion_ex(devdata->grabbed_window, ievt->device_id, 1, 0, ievt->axisrel, 0); } break; case DIET_KEYPRESS: kbd_idx = KbdIndex(_this, ievt->device_id); DirectFB_TranslateKeyInputEvent(_this, ievt, &keysym, &unicode); /* printf("Scancode %d %d %d\n", keysym.scancode, evt->key_code, evt->key_id); */ SDL_SendKeyboardKey_ex(kbd_idx, SDL_PRESSED, keysym.scancode); if (SDL_EventState(SDL_TEXTINPUT, SDL_QUERY)) { SDL_zero(text); UnicodeToUtf8(unicode, text); if (*text) { SDL_SendKeyboardText_ex(kbd_idx, text); } } break; case DIET_KEYRELEASE: kbd_idx = KbdIndex(_this, ievt->device_id); DirectFB_TranslateKeyInputEvent(_this, ievt, &keysym, &unicode); SDL_SendKeyboardKey_ex(kbd_idx, SDL_RELEASED, keysym.scancode); break; case DIET_BUTTONPRESS: if (ievt->buttons & DIBM_LEFT) SDL_SendMouseButton_ex(devdata->grabbed_window, ievt->device_id, SDL_PRESSED, 1); if (ievt->buttons & DIBM_MIDDLE) SDL_SendMouseButton_ex(devdata->grabbed_window, ievt->device_id, SDL_PRESSED, 2); if (ievt->buttons & DIBM_RIGHT) SDL_SendMouseButton_ex(devdata->grabbed_window, ievt->device_id, SDL_PRESSED, 3); break; case DIET_BUTTONRELEASE: if (!(ievt->buttons & DIBM_LEFT)) SDL_SendMouseButton_ex(devdata->grabbed_window, ievt->device_id, SDL_RELEASED, 1); if (!(ievt->buttons & DIBM_MIDDLE)) SDL_SendMouseButton_ex(devdata->grabbed_window, ievt->device_id, SDL_RELEASED, 2); if (!(ievt->buttons & DIBM_RIGHT)) SDL_SendMouseButton_ex(devdata->grabbed_window, ievt->device_id, SDL_RELEASED, 3); break; default: break; /* please gcc */ } } } void DirectFB_PumpEventsWindow(_THIS) { SDL_DFB_DEVICEDATA(_this); DFBInputEvent ievt; SDL_Window *w; for (w = devdata->firstwin; w != NULL; w = w->next) { SDL_DFB_WINDOWDATA(w); DFBWindowEvent evt; while (windata->eventbuffer->GetEvent(windata->eventbuffer, DFB_EVENT(&evt)) == DFB_OK) { if (!DirectFB_WM_ProcessEvent(_this, w, &evt)) { /* Send a SDL_SYSWMEVENT if the application wants them */ if (SDL_GetEventState(SDL_SYSWMEVENT) == SDL_ENABLE) { SDL_SysWMmsg wmmsg; SDL_VERSION(&wmmsg.version); wmmsg.subsystem = SDL_SYSWM_DIRECTFB; wmmsg.msg.dfb.event.window = evt; SDL_SendSysWMEvent(&wmmsg); } ProcessWindowEvent(_this, w, &evt); } } } /* Now get relative events in case we need them */ while (devdata->events->GetEvent(devdata->events, DFB_EVENT(&ievt)) == DFB_OK) { if (SDL_GetEventState(SDL_SYSWMEVENT) == SDL_ENABLE) { SDL_SysWMmsg wmmsg; SDL_VERSION(&wmmsg.version); wmmsg.subsystem = SDL_SYSWM_DIRECTFB; wmmsg.msg.dfb.event.input = ievt; SDL_SendSysWMEvent(&wmmsg); } ProcessInputEvent(_this, &ievt); } } void DirectFB_InitOSKeymap(_THIS, SDL_Scancode * keymap, int numkeys) { int i; /* Initialize the DirectFB key translation table */ for (i = 0; i < numkeys; ++i) keymap[i] = SDL_SCANCODE_UNKNOWN; keymap[DIKI_A - DIKI_UNKNOWN] = SDL_SCANCODE_A; keymap[DIKI_B - DIKI_UNKNOWN] = SDL_SCANCODE_B; keymap[DIKI_C - DIKI_UNKNOWN] = SDL_SCANCODE_C; keymap[DIKI_D - DIKI_UNKNOWN] = SDL_SCANCODE_D; keymap[DIKI_E - DIKI_UNKNOWN] = SDL_SCANCODE_E; keymap[DIKI_F - DIKI_UNKNOWN] = SDL_SCANCODE_F; keymap[DIKI_G - DIKI_UNKNOWN] = SDL_SCANCODE_G; keymap[DIKI_H - DIKI_UNKNOWN] = SDL_SCANCODE_H; keymap[DIKI_I - DIKI_UNKNOWN] = SDL_SCANCODE_I; keymap[DIKI_J - DIKI_UNKNOWN] = SDL_SCANCODE_J; keymap[DIKI_K - DIKI_UNKNOWN] = SDL_SCANCODE_K; keymap[DIKI_L - DIKI_UNKNOWN] = SDL_SCANCODE_L; keymap[DIKI_M - DIKI_UNKNOWN] = SDL_SCANCODE_M; keymap[DIKI_N - DIKI_UNKNOWN] = SDL_SCANCODE_N; keymap[DIKI_O - DIKI_UNKNOWN] = SDL_SCANCODE_O; keymap[DIKI_P - DIKI_UNKNOWN] = SDL_SCANCODE_P; keymap[DIKI_Q - DIKI_UNKNOWN] = SDL_SCANCODE_Q; keymap[DIKI_R - DIKI_UNKNOWN] = SDL_SCANCODE_R; keymap[DIKI_S - DIKI_UNKNOWN] = SDL_SCANCODE_S; keymap[DIKI_T - DIKI_UNKNOWN] = SDL_SCANCODE_T; keymap[DIKI_U - DIKI_UNKNOWN] = SDL_SCANCODE_U; keymap[DIKI_V - DIKI_UNKNOWN] = SDL_SCANCODE_V; keymap[DIKI_W - DIKI_UNKNOWN] = SDL_SCANCODE_W; keymap[DIKI_X - DIKI_UNKNOWN] = SDL_SCANCODE_X; keymap[DIKI_Y - DIKI_UNKNOWN] = SDL_SCANCODE_Y; keymap[DIKI_Z - DIKI_UNKNOWN] = SDL_SCANCODE_Z; keymap[DIKI_0 - DIKI_UNKNOWN] = SDL_SCANCODE_0; keymap[DIKI_1 - DIKI_UNKNOWN] = SDL_SCANCODE_1; keymap[DIKI_2 - DIKI_UNKNOWN] = SDL_SCANCODE_2; keymap[DIKI_3 - DIKI_UNKNOWN] = SDL_SCANCODE_3; keymap[DIKI_4 - DIKI_UNKNOWN] = SDL_SCANCODE_4; keymap[DIKI_5 - DIKI_UNKNOWN] = SDL_SCANCODE_5; keymap[DIKI_6 - DIKI_UNKNOWN] = SDL_SCANCODE_6; keymap[DIKI_7 - DIKI_UNKNOWN] = SDL_SCANCODE_7; keymap[DIKI_8 - DIKI_UNKNOWN] = SDL_SCANCODE_8; keymap[DIKI_9 - DIKI_UNKNOWN] = SDL_SCANCODE_9; keymap[DIKI_F1 - DIKI_UNKNOWN] = SDL_SCANCODE_F1; keymap[DIKI_F2 - DIKI_UNKNOWN] = SDL_SCANCODE_F2; keymap[DIKI_F3 - DIKI_UNKNOWN] = SDL_SCANCODE_F3; keymap[DIKI_F4 - DIKI_UNKNOWN] = SDL_SCANCODE_F4; keymap[DIKI_F5 - DIKI_UNKNOWN] = SDL_SCANCODE_F5; keymap[DIKI_F6 - DIKI_UNKNOWN] = SDL_SCANCODE_F6; keymap[DIKI_F7 - DIKI_UNKNOWN] = SDL_SCANCODE_F7; keymap[DIKI_F8 - DIKI_UNKNOWN] = SDL_SCANCODE_F8; keymap[DIKI_F9 - DIKI_UNKNOWN] = SDL_SCANCODE_F9; keymap[DIKI_F10 - DIKI_UNKNOWN] = SDL_SCANCODE_F10; keymap[DIKI_F11 - DIKI_UNKNOWN] = SDL_SCANCODE_F11; keymap[DIKI_F12 - DIKI_UNKNOWN] = SDL_SCANCODE_F12; keymap[DIKI_ESCAPE - DIKI_UNKNOWN] = SDL_SCANCODE_ESCAPE; keymap[DIKI_LEFT - DIKI_UNKNOWN] = SDL_SCANCODE_LEFT; keymap[DIKI_RIGHT - DIKI_UNKNOWN] = SDL_SCANCODE_RIGHT; keymap[DIKI_UP - DIKI_UNKNOWN] = SDL_SCANCODE_UP; keymap[DIKI_DOWN - DIKI_UNKNOWN] = SDL_SCANCODE_DOWN; keymap[DIKI_CONTROL_L - DIKI_UNKNOWN] = SDL_SCANCODE_LCTRL; keymap[DIKI_CONTROL_R - DIKI_UNKNOWN] = SDL_SCANCODE_RCTRL; keymap[DIKI_SHIFT_L - DIKI_UNKNOWN] = SDL_SCANCODE_LSHIFT; keymap[DIKI_SHIFT_R - DIKI_UNKNOWN] = SDL_SCANCODE_RSHIFT; keymap[DIKI_ALT_L - DIKI_UNKNOWN] = SDL_SCANCODE_LALT; keymap[DIKI_ALT_R - DIKI_UNKNOWN] = SDL_SCANCODE_RALT; keymap[DIKI_META_L - DIKI_UNKNOWN] = SDL_SCANCODE_LGUI; keymap[DIKI_META_R - DIKI_UNKNOWN] = SDL_SCANCODE_RGUI; keymap[DIKI_SUPER_L - DIKI_UNKNOWN] = SDL_SCANCODE_APPLICATION; keymap[DIKI_SUPER_R - DIKI_UNKNOWN] = SDL_SCANCODE_APPLICATION; /* FIXME:Do we read hyper keys ? * keymap[DIKI_HYPER_L - DIKI_UNKNOWN] = SDL_SCANCODE_APPLICATION; * keymap[DIKI_HYPER_R - DIKI_UNKNOWN] = SDL_SCANCODE_APPLICATION; */ keymap[DIKI_TAB - DIKI_UNKNOWN] = SDL_SCANCODE_TAB; keymap[DIKI_ENTER - DIKI_UNKNOWN] = SDL_SCANCODE_RETURN; keymap[DIKI_SPACE - DIKI_UNKNOWN] = SDL_SCANCODE_SPACE; keymap[DIKI_BACKSPACE - DIKI_UNKNOWN] = SDL_SCANCODE_BACKSPACE; keymap[DIKI_INSERT - DIKI_UNKNOWN] = SDL_SCANCODE_INSERT; keymap[DIKI_DELETE - DIKI_UNKNOWN] = SDL_SCANCODE_DELETE; keymap[DIKI_HOME - DIKI_UNKNOWN] = SDL_SCANCODE_HOME; keymap[DIKI_END - DIKI_UNKNOWN] = SDL_SCANCODE_END; keymap[DIKI_PAGE_UP - DIKI_UNKNOWN] = SDL_SCANCODE_PAGEUP; keymap[DIKI_PAGE_DOWN - DIKI_UNKNOWN] = SDL_SCANCODE_PAGEDOWN; keymap[DIKI_CAPS_LOCK - DIKI_UNKNOWN] = SDL_SCANCODE_CAPSLOCK; keymap[DIKI_NUM_LOCK - DIKI_UNKNOWN] = SDL_SCANCODE_NUMLOCKCLEAR; keymap[DIKI_SCROLL_LOCK - DIKI_UNKNOWN] = SDL_SCANCODE_SCROLLLOCK; keymap[DIKI_PRINT - DIKI_UNKNOWN] = SDL_SCANCODE_PRINTSCREEN; keymap[DIKI_PAUSE - DIKI_UNKNOWN] = SDL_SCANCODE_PAUSE; keymap[DIKI_KP_EQUAL - DIKI_UNKNOWN] = SDL_SCANCODE_KP_EQUALS; keymap[DIKI_KP_DECIMAL - DIKI_UNKNOWN] = SDL_SCANCODE_KP_PERIOD; keymap[DIKI_KP_0 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_0; keymap[DIKI_KP_1 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_1; keymap[DIKI_KP_2 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_2; keymap[DIKI_KP_3 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_3; keymap[DIKI_KP_4 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_4; keymap[DIKI_KP_5 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_5; keymap[DIKI_KP_6 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_6; keymap[DIKI_KP_7 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_7; keymap[DIKI_KP_8 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_8; keymap[DIKI_KP_9 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_9; keymap[DIKI_KP_DIV - DIKI_UNKNOWN] = SDL_SCANCODE_KP_DIVIDE; keymap[DIKI_KP_MULT - DIKI_UNKNOWN] = SDL_SCANCODE_KP_MULTIPLY; keymap[DIKI_KP_MINUS - DIKI_UNKNOWN] = SDL_SCANCODE_KP_MINUS; keymap[DIKI_KP_PLUS - DIKI_UNKNOWN] = SDL_SCANCODE_KP_PLUS; keymap[DIKI_KP_ENTER - DIKI_UNKNOWN] = SDL_SCANCODE_KP_ENTER; keymap[DIKI_QUOTE_LEFT - DIKI_UNKNOWN] = SDL_SCANCODE_GRAVE; /* TLDE */ keymap[DIKI_MINUS_SIGN - DIKI_UNKNOWN] = SDL_SCANCODE_MINUS; /* AE11 */ keymap[DIKI_EQUALS_SIGN - DIKI_UNKNOWN] = SDL_SCANCODE_EQUALS; /* AE12 */ keymap[DIKI_BRACKET_LEFT - DIKI_UNKNOWN] = SDL_SCANCODE_RIGHTBRACKET; /* AD11 */ keymap[DIKI_BRACKET_RIGHT - DIKI_UNKNOWN] = SDL_SCANCODE_LEFTBRACKET; /* AD12 */ keymap[DIKI_BACKSLASH - DIKI_UNKNOWN] = SDL_SCANCODE_BACKSLASH; /* BKSL */ keymap[DIKI_SEMICOLON - DIKI_UNKNOWN] = SDL_SCANCODE_SEMICOLON; /* AC10 */ keymap[DIKI_QUOTE_RIGHT - DIKI_UNKNOWN] = SDL_SCANCODE_APOSTROPHE; /* AC11 */ keymap[DIKI_COMMA - DIKI_UNKNOWN] = SDL_SCANCODE_COMMA; /* AB08 */ keymap[DIKI_PERIOD - DIKI_UNKNOWN] = SDL_SCANCODE_PERIOD; /* AB09 */ keymap[DIKI_SLASH - DIKI_UNKNOWN] = SDL_SCANCODE_SLASH; /* AB10 */ keymap[DIKI_LESS_SIGN - DIKI_UNKNOWN] = SDL_SCANCODE_NONUSBACKSLASH; /* 103rd */ } static SDL_Keysym * DirectFB_TranslateKey(_THIS, DFBWindowEvent * evt, SDL_Keysym * keysym, Uint32 *unicode) { SDL_DFB_DEVICEDATA(_this); int kbd_idx = 0; /* Window events lag the device source KbdIndex(_this, evt->device_id); */ DFB_KeyboardData *kbd = &devdata->keyboard[kbd_idx]; keysym->scancode = SDL_SCANCODE_UNKNOWN; if (kbd->map && evt->key_code >= kbd->map_adjust && evt->key_code < kbd->map_size + kbd->map_adjust) keysym->scancode = kbd->map[evt->key_code - kbd->map_adjust]; if (keysym->scancode == SDL_SCANCODE_UNKNOWN || devdata->keyboard[kbd_idx].is_generic) { if (evt->key_id - DIKI_UNKNOWN < SDL_arraysize(oskeymap)) keysym->scancode = oskeymap[evt->key_id - DIKI_UNKNOWN]; else keysym->scancode = SDL_SCANCODE_UNKNOWN; } *unicode = (DFB_KEY_TYPE(evt->key_symbol) == DIKT_UNICODE) ? evt->key_symbol : 0; if (*unicode == 0 && (evt->key_symbol > 0 && evt->key_symbol < 255)) *unicode = evt->key_symbol; return keysym; } static SDL_Keysym * DirectFB_TranslateKeyInputEvent(_THIS, DFBInputEvent * evt, SDL_Keysym * keysym, Uint32 *unicode) { SDL_DFB_DEVICEDATA(_this); int kbd_idx = KbdIndex(_this, evt->device_id); DFB_KeyboardData *kbd = &devdata->keyboard[kbd_idx]; keysym->scancode = SDL_SCANCODE_UNKNOWN; if (kbd->map && evt->key_code >= kbd->map_adjust && evt->key_code < kbd->map_size + kbd->map_adjust) keysym->scancode = kbd->map[evt->key_code - kbd->map_adjust]; if (keysym->scancode == SDL_SCANCODE_UNKNOWN || devdata->keyboard[kbd_idx].is_generic) { if (evt->key_id - DIKI_UNKNOWN < SDL_arraysize(oskeymap)) keysym->scancode = oskeymap[evt->key_id - DIKI_UNKNOWN]; else keysym->scancode = SDL_SCANCODE_UNKNOWN; } *unicode = (DFB_KEY_TYPE(evt->key_symbol) == DIKT_UNICODE) ? evt->key_symbol : 0; if (*unicode == 0 && (evt->key_symbol > 0 && evt->key_symbol < 255)) *unicode = evt->key_symbol; return keysym; } static int DirectFB_TranslateButton(DFBInputDeviceButtonIdentifier button) { switch (button) { case DIBI_LEFT: return 1; case DIBI_MIDDLE: return 2; case DIBI_RIGHT: return 3; default: return 0; } } static DFBEnumerationResult EnumKeyboards(DFBInputDeviceID device_id, DFBInputDeviceDescription desc, void *callbackdata) { cb_data *cb = callbackdata; DFB_DeviceData *devdata = cb->devdata; #if USE_MULTI_API SDL_Keyboard keyboard; #endif SDL_Keycode keymap[SDL_NUM_SCANCODES]; if (!cb->sys_kbd) { if (cb->sys_ids) { if (device_id >= 0x10) return DFENUM_OK; } else { if (device_id < 0x10) return DFENUM_OK; } } else { if (device_id != DIDID_KEYBOARD) return DFENUM_OK; } if ((desc.caps & DIDTF_KEYBOARD)) { #if USE_MULTI_API SDL_zero(keyboard); SDL_AddKeyboard(&keyboard, devdata->num_keyboard); #endif devdata->keyboard[devdata->num_keyboard].id = device_id; devdata->keyboard[devdata->num_keyboard].is_generic = 0; if (!strncmp("X11", desc.name, 3)) { devdata->keyboard[devdata->num_keyboard].map = xfree86_scancode_table2; devdata->keyboard[devdata->num_keyboard].map_size = SDL_arraysize(xfree86_scancode_table2); devdata->keyboard[devdata->num_keyboard].map_adjust = 8; } else { devdata->keyboard[devdata->num_keyboard].map = linux_scancode_table; devdata->keyboard[devdata->num_keyboard].map_size = SDL_arraysize(linux_scancode_table); devdata->keyboard[devdata->num_keyboard].map_adjust = 0; } SDL_DFB_LOG("Keyboard %d - %s\n", device_id, desc.name); SDL_GetDefaultKeymap(keymap); #if USE_MULTI_API SDL_SetKeymap(devdata->num_keyboard, 0, keymap, SDL_NUM_SCANCODES); #else SDL_SetKeymap(0, keymap, SDL_NUM_SCANCODES); #endif devdata->num_keyboard++; if (cb->sys_kbd) return DFENUM_CANCEL; } return DFENUM_OK; } void DirectFB_InitKeyboard(_THIS) { SDL_DFB_DEVICEDATA(_this); cb_data cb; DirectFB_InitOSKeymap(_this, &oskeymap[0], SDL_arraysize(oskeymap)); devdata->num_keyboard = 0; cb.devdata = devdata; if (devdata->use_linux_input) { cb.sys_kbd = 0; cb.sys_ids = 0; SDL_DFB_CHECK(devdata->dfb-> EnumInputDevices(devdata->dfb, EnumKeyboards, &cb)); if (devdata->num_keyboard == 0) { cb.sys_ids = 1; SDL_DFB_CHECK(devdata->dfb->EnumInputDevices(devdata->dfb, EnumKeyboards, &cb)); } } else { cb.sys_kbd = 1; SDL_DFB_CHECK(devdata->dfb->EnumInputDevices(devdata->dfb, EnumKeyboards, &cb)); } } void DirectFB_QuitKeyboard(_THIS) { /* SDL_DFB_DEVICEDATA(_this); */ } #endif /* SDL_VIDEO_DRIVER_DIRECTFB */
412
0.907113
1
0.907113
game-dev
MEDIA
0.303481
game-dev
0.938531
1
0.938531
beyond-aion/aion-server
1,202
game-server/src/com/aionemu/gameserver/questEngine/handlers/models/KillSpawnedData.java
package com.aionemu.gameserver.questEngine.handlers.models; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import com.aionemu.gameserver.questEngine.QuestEngine; import com.aionemu.gameserver.questEngine.handlers.template.KillSpawned; /** * @author vlog, Bobobear, Pad */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "KillSpawnedData", propOrder = "monster") public class KillSpawnedData extends MonsterHuntData { @XmlElement(name = "monster") protected List<Monster> monster; @Override public void register(QuestEngine questEngine) { questEngine.addQuestHandler(new KillSpawned(id, startNpcIds, endNpcIds, monster)); } @Override public Set<Integer> getAlternativeNpcs(int npcId) { for (Monster m : monster) { List<Integer> npcIds = m.getNpcIds(); if (npcIds != null && npcIds.size() > 1 && npcIds.contains(npcId)) return npcIds.stream().filter(id -> id != npcId).collect(Collectors.toSet()); } return super.getAlternativeNpcs(npcId); } }
412
0.897842
1
0.897842
game-dev
MEDIA
0.898055
game-dev
0.771493
1
0.771493
OpenNefia/OpenNefia
7,339
Mods/OpenNefia.LecchoTorte/DamagePopups/DamagePopupsTileLayer.cs
using OpenNefia.Content.MapVisibility; using OpenNefia.Core.IoC; using OpenNefia.Core.Maps; using OpenNefia.Core.Maths; using OpenNefia.Core.Prototypes; using OpenNefia.Core.Random; using OpenNefia.Core.Rendering; using OpenNefia.Core.Rendering.TileDrawLayers; using OpenNefia.Core.UI; using OpenNefia.Content.Prototypes; using System.Collections.Generic; using OpenNefia.Content.UI; using OpenNefia.Content.UI.Element; using OpenNefia.Core.Configuration; using OpenNefia.Core.Game; using OpenNefia.Core.GameObjects; using OpenNefia.Core.Graphics; using OpenNefia.Core.Utility; namespace OpenNefia.LecchoTorte.DamagePopups { public class DamagePopup { public static readonly FontSpec DefaultFont = new(16, 16, color: UiColors.TextWhite, bgColor: UiColors.TextBlack); public string Text { get; set; } = string.Empty; public Color Color { get; set; } = Color.White; public Color ShadowColor { get; set; } = Color.Black; public FontSpec Font { get; set; } = DefaultFont; public IAssetInstance? Icon { get; set; } } [RegisterTileLayer(renderAfter: new[] { typeof(ShadowTileLayer) })] public sealed class DamagePopupsTileLayer : BaseTileLayer { [Dependency] private readonly ICoords _coords = default!; [Dependency] private readonly IConfigurationManager _config = default!; [Dependency] private readonly IEntityManager _entityMan = default!; [Dependency] private readonly IGameSessionManager _gameSession = default!; [Dependency] private readonly IGraphics _graphics = default!; [Dependency] private readonly IMapManager _mapManager = default!; private const int MaxDamagePopups = 20; private Queue<DamagePopupInstance> _popups = new(); private Dictionary<EntityUid, Queue<DamagePopupInstance>> _popupsPerEntity = new(); private sealed class DamagePopupInstance { public DamagePopup DamagePopup { get; set; } public Vector2 ScreenPosition { get; set; } public EntityUid? Entity { get; set; } public float Frame { get; set; } public UiText UiText { get; set; } = new(); public int YOffset { get; set; } } public override void Initialize() { _popups.Clear(); } public void AddDamagePopup(DamagePopup popup, MapCoordinates coords) { if (_mapManager.ActiveMap?.Id != coords.MapId) return; if (_popups.Count > MaxDamagePopups) _popups.Dequeue(); _popups.Enqueue(new DamagePopupInstance() { DamagePopup = popup, ScreenPosition = (_coords.TileToScreen(coords.Position) - (0, _coords.TileSize.Y / 2)) * _coords.TileScale, Frame = 0f, UiText = new UiTextShadowed(popup.Font, popup.Text) }); } public void AddDamagePopup(DamagePopup popup, EntityUid uid) { var spatial = _entityMan.GetComponent<SpatialComponent>(uid); var coords = spatial.MapPosition; if (_mapManager.ActiveMap?.Id != coords.MapId) return; if (_popups.Count > MaxDamagePopups) _popups.Dequeue(); foreach (var popupInst in _popups) { popupInst.ScreenPosition = (popupInst.ScreenPosition.X, popupInst.ScreenPosition.Y - popupInst.DamagePopup.Font.Size * _coords.TileScale); } var popupInstance = new DamagePopupInstance() { DamagePopup = popup, ScreenPosition = (_coords.TileToScreen(coords.Position) - (0, _coords.TileSize.Y / 2)) * _coords.TileScale, Frame = 0f, UiText = new UiTextShadowed(popup.Font, popup.Text), Entity = uid }; _popups.Enqueue(popupInstance); var perEntity = _popupsPerEntity.GetOrInsertNew(uid); popupInstance.YOffset = perEntity.Count; perEntity.Enqueue(popupInstance); } public void ClearDamagePopups() { _popups.Clear(); } private const float MaxFrame = 80f; public override void Update(float dt) { foreach (var popup in _popups) { popup.Frame += dt * 50f; var alpha = MathF.Min(OutQuint(1f - (popup.Frame / MaxFrame), 0f, 1f, 1f), 1f); popup.DamagePopup.Color = popup.DamagePopup.Color.WithAlphaF(alpha); popup.DamagePopup.ShadowColor = popup.DamagePopup.ShadowColor.WithAlphaF(alpha); } while (_popups.TryPeek(out var popup) && popup.Frame > MaxFrame) { var instance = _popups.Dequeue(); if (instance.Entity != null) { var perEntity = _popupsPerEntity[instance.Entity.Value]; perEntity.Dequeue(); foreach (var other in perEntity) { other.YOffset--; } } } } private static float OutQuint(float t, float b, float c, float d) { t = t / d - 1f; return c * (MathF.Pow(t, 5f) + 1f) + b; } public override void Draw() { foreach (var popup in _popups) { var yOffset = 0; if (_entityMan.IsAlive(popup.Entity)) { var spatial = _entityMan.GetComponent<SpatialComponent>(popup.Entity.Value); // TODO support fractional positions popup.ScreenPosition = _coords.TileToScreen(spatial.MapPosition.Position) * _coords.TileScale; if (_popupsPerEntity.TryGetValue(popup.Entity.Value, out var perEntity)) { yOffset = perEntity.Count - popup.YOffset; } } var pos = popup.ScreenPosition; popup.UiText.Color = popup.DamagePopup.Color; popup.UiText.BgColor = popup.DamagePopup.ShadowColor; popup.UiText.SetPreferredSize(); pos += new Vector2(X - (popup.UiText.TextWidth / 2) + (_coords.TileSize.X * _coords.TileScale) / 2f, Y - (popup.UiText.Height / 2f) - popup.Frame - (yOffset * popup.UiText.Height) + (_coords.TileSize.Y * _coords.TileScale) / 2f); if (popup.DamagePopup.Icon != null) { var icon = popup.DamagePopup.Icon; var iconHeight = icon.PixelWidth; var textHeight = popup.UiText.PixelHeight; var ratio = textHeight / iconHeight; Love.Graphics.SetColor(Color.White.WithAlphaB(popup.DamagePopup.Color.AByte)); popup.DamagePopup.Icon.DrawUnscaled(pos.X - icon.PixelWidth - (icon.PixelWidth * ratio) / 4, pos.Y + (icon.PixelHeight * ratio) / 8, icon.PixelWidth * ratio, icon.PixelHeight * ratio); } popup.UiText.SetPosition(pos.X, pos.Y); popup.UiText.Draw(); } } } }
412
0.898757
1
0.898757
game-dev
MEDIA
0.815557
game-dev
0.95978
1
0.95978
fortressforever/fortressforever
8,680
dlls/ff/ff_grenade_napalmlet.cpp
#include "cbase.h" #include "ff_grenade_base.h" #include "ff_grenade_napalmlet.h" #include "ff_utils.h" #include "ff_player.h" //ConVar ffdev_nap_bonusdamage_burn1("ffdev_nap_bonusdamage_burn1", "0", FCVAR_REPLICATED | FCVAR_CHEAT); #define NAP_BONUSDAMAGE_BURN1 0 //ffdev_nap_bonusdamage_burn1.GetInt() //ConVar ffdev_nap_bonusdamage_burn2("ffdev_nap_bonusdamage_burn2", "1", FCVAR_REPLICATED | FCVAR_CHEAT); #define NAP_BONUSDAMAGE_BURN2 1 //ffdev_nap_bonusdamage_burn2.GetInt() //ConVar ffdev_nap_bonusdamage_burn3("ffdev_nap_bonusdamage_burn3", "2", FCVAR_REPLICATED | FCVAR_CHEAT); #define NAP_BONUSDAMAGE_BURN3 2 //ffdev_nap_bonusdamage_burn3.GetInt() //ConVar burn_standon_ng("ffdev_burn_standon_ng", "7.0", 0, "Damage you take when standing on a burning napalmlet"); //ConVar ffdev_nap_flamesize("ffdev_nap_flamesize", "30.0", 0, "Napalmlet flame size"); #define FFDEV_NAP_FLAMESIZE 30.0f //ffdev_nap_flamesize.GetFloat() // 50.0f //ConVar nap_burn_radius("ffdev_nap_burn_radius","70.0",FCVAR_FF_FFDEV,"Burn radius of a napalmlet."); #define NAP_BURN_RADIUS 70.0f //nap_burn_radius.GetFloat() //98.0f //ConVar ffdev_nap_burnamount("ffdev_nap_burnamount", "10.0", 0, "Napalmlet burn increase per tick, 100 is a full burn level"); #define FFDEV_NAPALM_BURNAMOUNT 10.0f //ffdev_nap_burnamount.GetFloat() // 50.0f //ConVar ffdev_nap_height("ffdev_nap_height", "70.0", 0, "Napalmlet maximum burn height above the ground"); #define FFDEV_NAP_HEIGHT 70.0f //ffdev_nap_height.GetFloat() // 50.0f #define BURN_STANDON_NG 2 BEGIN_DATADESC( CFFGrenadeNapalmlet ) DEFINE_THINKFUNC( FlameThink ), END_DATADESC() LINK_ENTITY_TO_CLASS( ff_grenade_napalmlet, CFFGrenadeNapalmlet ); PRECACHE_WEAPON_REGISTER( ff_grenade_napalmlet ); void CFFGrenadeNapalmlet::UpdateOnRemove( void ) { StopSound( "General.BurningFlesh" ); StopSound( "General.BurningObject" ); BaseClass::UpdateOnRemove(); } //----------------------------------------------------------------------------- // Purpose: Precache assets //----------------------------------------------------------------------------- void CFFGrenadeNapalmlet::Precache ( void ) { PrecacheModel( NAPALMLET_MODEL ); BaseClass::Precache(); } //----------------------------------------------------------------------------- // Purpose: Spawn //----------------------------------------------------------------------------- void CFFGrenadeNapalmlet::Spawn( void ) { BaseClass::Spawn(); SetModel ( NAPALMLET_MODEL ); SetAbsAngles( QAngle( 0, 0, 0 ) ); SetSolidFlags( FSOLID_TRIGGER | FSOLID_NOT_STANDABLE ); SetMoveType( MOVETYPE_FLYGRAVITY, MOVECOLLIDE_FLY_CUSTOM ); SetSolid( SOLID_BBOX ); SetCollisionGroup( COLLISION_GROUP_DEBRIS ); SetSize( Vector ( -5, -5, -5 ), Vector ( 5, 5, 5 ) ); SetThink( &CFFGrenadeNapalmlet::FlameThink ); SetNextThink( gpGlobals->curtime ); SetEffects(EF_NOSHADOW); m_pFlame = CEntityFlame::Create( this, false ); if (m_pFlame) { m_pFlame->SetLifetime( m_flBurnTime ); AddFlag( FL_ONFIRE ); SetEffectEntity( m_pFlame ); m_pFlame->SetSize( FFDEV_NAP_FLAMESIZE ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFFGrenadeNapalmlet::ResolveFlyCollisionCustom( trace_t &trace, Vector &vecVelocity ) { //Assume all surfaces have the same elasticity float flSurfaceElasticity = 1.0; //Don't bounce off of players with perfect elasticity if( trace.m_pEnt && trace.m_pEnt->IsPlayer() ) { flSurfaceElasticity = 0.3; } // if its breakable glass and we kill it, don't bounce. // give some damage to the glass, and if it breaks, pass // through it. bool breakthrough = false; if( trace.m_pEnt && FClassnameIs( trace.m_pEnt, "func_breakable" ) ) { breakthrough = true; } if( trace.m_pEnt && FClassnameIs( trace.m_pEnt, "func_breakable_surf" ) ) { breakthrough = true; } if (breakthrough) { CTakeDamageInfo info( this, GetOwnerEntity(), 10, DMG_CLUB ); trace.m_pEnt->DispatchTraceAttack( info, GetAbsVelocity(), &trace ); ApplyMultiDamage(); if( trace.m_pEnt->m_iHealth <= 0 ) { // slow our flight a little bit Vector vel = GetAbsVelocity(); vel *= 0.4; SetAbsVelocity( vel ); return; } } float flTotalElasticity = GetElasticity() * flSurfaceElasticity; flTotalElasticity = clamp( flTotalElasticity, 0.0f, 0.9f ); // NOTE: A backoff of 2.0f is a reflection Vector vecAbsVelocity; PhysicsClipVelocity( GetAbsVelocity(), trace.plane.normal, vecAbsVelocity, 2.0f ); vecAbsVelocity *= flTotalElasticity; // Get the total velocity (player + conveyors, etc.) VectorAdd( vecAbsVelocity, GetBaseVelocity(), vecVelocity ); float flSpeedSqr = DotProduct( vecVelocity, vecVelocity ); // Stop if on ground. if ( trace.plane.normal.z > 0.7f ) // Floor { // Verify that we have an entity. CBaseEntity *pEntity = trace.m_pEnt; Assert( pEntity ); SetAbsVelocity( vecAbsVelocity ); if ( flSpeedSqr < ( 30 * 30 ) ) { if ( pEntity->IsStandable() ) { SetGroundEntity( pEntity ); } // Reset velocities. SetAbsVelocity( vec3_origin ); SetLocalAngularVelocity( vec3_angle ); } else { Vector vecDelta = GetBaseVelocity() - vecAbsVelocity; Vector vecBaseDir = GetBaseVelocity(); VectorNormalize( vecBaseDir ); float flScale = vecDelta.Dot( vecBaseDir ); VectorScale( vecAbsVelocity, ( 1.0f - trace.fraction ) * gpGlobals->frametime, vecVelocity ); VectorMA( vecVelocity, ( 1.0f - trace.fraction ) * gpGlobals->frametime, GetBaseVelocity() * flScale, vecVelocity ); PhysicsPushEntity( vecVelocity, &trace ); } } else { // If we get *too* slow, we'll stick without ever coming to rest because // we'll get pushed down by gravity faster than we can escape from the wall. if ( flSpeedSqr < ( 30 * 30 ) ) { // Reset velocities. SetAbsVelocity( vec3_origin ); SetLocalAngularVelocity( vec3_angle ); } else { SetAbsVelocity( vecAbsVelocity ); } } } //----------------------------------------------------------------------------- // Purpose: Burninate the players //----------------------------------------------------------------------------- void CFFGrenadeNapalmlet::FlameThink() { // Remove if we've reached the end of our fuse if( gpGlobals->curtime > m_flBurnTime ) { UTIL_Remove(this); return; } // Bug #0001664: Pyro napalm flames in water shouldnt exist if( GetWaterLevel() != 0 ) { UTIL_Remove(this); return; } Vector vecSrc = GetAbsOrigin(); vecSrc.z += 1; CBaseEntity *pEntity = NULL; for( CEntitySphereQuery sphere( vecSrc, NAP_BURN_RADIUS ); ( pEntity = sphere.GetCurrentEntity() ) != NULL; sphere.NextEntity() ) { if( !pEntity ) continue; // Bug #0000269: Napalm through walls. // Mulch: if we hit water w/ the trace, abort too! trace_t tr; UTIL_TraceLine(GetAbsOrigin(), pEntity->GetAbsOrigin(), MASK_SOLID_BRUSHONLY | CONTENTS_WATER, this, COLLISION_GROUP_DEBRIS, &tr); if (tr.fraction < 1.0f) continue; // Bug #0000270: Napalm grenade burn radius reaches unrealisticly high. float height = tr.startpos.z - tr.endpos.z; if (height < -FFDEV_NAP_HEIGHT || height > FFDEV_NAP_HEIGHT) continue; // Don't damage if entity is more than feet deep in water if( pEntity->GetWaterLevel() >= 2 ) continue; switch( pEntity->Classify() ) { case CLASS_PLAYER: { CFFPlayer *pPlayer = ToFFPlayer( pEntity ); if( !pPlayer ) continue; if (g_pGameRules->FCanTakeDamage(pPlayer, GetOwnerEntity())) { int damage = BURN_STANDON_NG + CalculateBonusBurnDamage(pPlayer->GetBurnLevel()); pPlayer->TakeDamage( CTakeDamageInfo( this, GetOwnerEntity(), damage, DMG_BURN ) ); pPlayer->IncreaseBurnLevel ( FFDEV_NAPALM_BURNAMOUNT ); } } break; case CLASS_SENTRYGUN: case CLASS_MANCANNON://Adding napalm damage to jumppad -GreenMushy case CLASS_DISPENSER: { if (g_pGameRules->FCanTakeDamage( pEntity, GetOwnerEntity())) pEntity->TakeDamage( CTakeDamageInfo( this, GetOwnerEntity(), BURN_STANDON_NG, DMG_BURN ) ); } default: break; } } SetNextThink( gpGlobals->curtime + 0.25f ); } //---------------------------------------------------------------------------- // Purpose: Calculate the bonus damage for the napalmlet based on the players current burn level //---------------------------------------------------------------------------- int CFFGrenadeNapalmlet::CalculateBonusBurnDamage(int burnLevel) { if (burnLevel <100) { return NAP_BONUSDAMAGE_BURN1; } if (burnLevel <200) { return NAP_BONUSDAMAGE_BURN2; } return NAP_BONUSDAMAGE_BURN3; }
412
0.925527
1
0.925527
game-dev
MEDIA
0.946202
game-dev
0.834521
1
0.834521
SkriptLang/Skript
3,794
src/main/java/ch/njol/skript/lang/function/ScriptFunction.java
package ch.njol.skript.lang.function; import ch.njol.skript.classes.ClassInfo; import ch.njol.skript.config.SectionNode; import ch.njol.skript.lang.*; import ch.njol.skript.lang.parser.ParserInstance; import ch.njol.skript.lang.util.SimpleEvent; import ch.njol.skript.variables.HintManager; import ch.njol.skript.variables.Variables; import org.bukkit.event.Event; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.skriptlang.skript.lang.script.Script; public class ScriptFunction<T> extends Function<T> implements ReturnHandler<T> { private final Trigger trigger; private boolean returnValueSet; private T @Nullable [] returnValues; private String @Nullable [] returnKeys; /** * @deprecated use {@link ScriptFunction#ScriptFunction(Signature, SectionNode)} instead. */ @Deprecated(since = "2.9.0", forRemoval = true) public ScriptFunction(Signature<T> sign, Script script, SectionNode node) { this(sign, node); } public ScriptFunction(Signature<T> sign, SectionNode node) { super(sign); Functions.currentFunction = this; HintManager hintManager = ParserInstance.get().getHintManager(); try { hintManager.enterScope(false); for (Parameter<?> parameter : sign.getParameters()) { String hintName = parameter.name(); if (!parameter.isSingleValue()) { hintName += Variable.SEPARATOR + "*"; } hintManager.set(hintName, parameter.type()); } trigger = loadReturnableTrigger(node, "function " + sign.getName(), new SimpleEvent()); } finally { hintManager.exitScope(); Functions.currentFunction = null; } trigger.setLineNumber(node.getLine()); } // REMIND track possible types of local variables (including undefined variables) (consider functions, commands, and EffChange) - maybe make a general interface for this purpose // REM: use patterns, e.g. {_a%b%} is like "a.*", and thus subsequent {_axyz} may be set and of that type. @Override public T @Nullable [] execute(FunctionEvent<?> event, Object[][] params) { Parameter<?>[] parameters = getSignature().getParameters(); for (int i = 0; i < parameters.length; i++) { Parameter<?> parameter = parameters[i]; Object[] val = params[i]; if (parameter.single && val.length > 0) { Variables.setVariable(parameter.name(), val[0], event, true); } else { for (Object value : val) { KeyedValue<?> keyedValue = (KeyedValue<?>) value; Variables.setVariable(parameter.name() + "::" + keyedValue.key(), keyedValue.value(), event, true); } } } trigger.execute(event); ClassInfo<T> returnType = getReturnType(); return returnType != null ? returnValues : null; } @Override public @NotNull String @Nullable [] returnedKeys() { return returnKeys; } /** * @deprecated Use {@link ScriptFunction#returnValues(Event, Expression)} instead. */ @Deprecated(since = "2.9.0", forRemoval = true) @ApiStatus.Internal public final void setReturnValue(@Nullable T[] values) { assert !returnValueSet; returnValueSet = true; this.returnValues = values; } @Override public boolean resetReturnValue() { returnValueSet = false; returnValues = null; returnKeys = null; return true; } @Override public final void returnValues(Event event, Expression<? extends T> value) { assert !returnValueSet; returnValueSet = true; this.returnValues = value.getArray(event); if (KeyProviderExpression.canReturnKeys(value)) this.returnKeys = ((KeyProviderExpression<?>) value).getArrayKeys(event); } @Override public final boolean isSingleReturnValue() { return isSingle(); } @Override public final @Nullable Class<? extends T> returnValueType() { return getReturnType() != null ? getReturnType().getC() : null; } }
412
0.933256
1
0.933256
game-dev
MEDIA
0.277731
game-dev
0.948944
1
0.948944