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
Code-A2Z/jarvis
4,270
src/apps/pages/programs/Games/hangman.py
import random import streamlit as st HANGMAN_FIGURES = [ """ ------ | | O | /|\\ | / \\ | | ========= """, """ ------ | | O | /|\\ | / | | ========= """, """ ------ | | O | /|\\ | | | ========= """, """ ------ | | O | /| | | | ========= """, """ ------ | | O | | | | | ========= """, """ ------ | | O | | | | ========= """, """ ------ | | | | | | ========= """, ] def get_new_word(): words = [ "python", "hangman", "programming", "developer", "keyboard", "algorithm", "function", "variable", "iteration", "debugging", "constant", "indentation", "machine learning", "backend", "frontend", "deep learning", "tensorflow", "blockchain", "quantum", "data science", ] return random.choice(words) def initialize_game_state(): # Initializes or resets the game state by defining necessary session variables. st.session_state.word = get_new_word() st.session_state.guessed_word = ["_"] * len(st.session_state.word) st.session_state.guessed_letters = set() st.session_state.attempts = 6 st.session_state.game_over = False st.session_state.message = "Welcome to Hangman Game!" st.session_state.guess = "" st.session_state.play_again_triggered = False st.session_state.hint_used = False def check_guess(guess): # Validates the guess and updates the game state accordingly. if not guess or len(guess) != 1 or not guess.isalpha(): return "Please enter a single alphabetic letter." if guess in st.session_state.guessed_letters: return f"You already guessed '{guess}'. Try a different letter." st.session_state.guessed_letters.add(guess) if guess in st.session_state.word: for i, letter in enumerate(st.session_state.word): if letter == guess: st.session_state.guessed_word[i] = guess return f"Good job! '{guess}' is in the word." else: st.session_state.attempts -= 1 return f"Wrong guess! You have {st.session_state.attempts} attempts left." def give_hint(): # Provides a hint by revealing a random letter in the word. if not st.session_state.hint_used: hint_letter = random.choice([letter for letter in st.session_state.word if letter != "_"]) for i, letter in enumerate(st.session_state.word): if letter == hint_letter: st.session_state.guessed_word[i] = hint_letter st.session_state.hint_used = True return f"Here's your hint: The letter '{hint_letter}' is in the word." else: return "You've already used your hint." def hangman(): st.title("Hangman Game") if "word" not in st.session_state: initialize_game_state() st.write(st.session_state.message) st.write("Word:", " ".join(st.session_state.guessed_word)) st.code(HANGMAN_FIGURES[st.session_state.attempts], language="text") if not st.session_state.game_over: st.session_state.guess = st.text_input("Guess a letter:", value=st.session_state.guess, key="guess_input").lower() if st.button("Submit Guess"): st.session_state.message = check_guess(st.session_state.guess) st.session_state.guess = "" if "_" not in st.session_state.guessed_word: st.session_state.message = f"\nCongratulations! You've guessed the word correctly: {st.session_state.word}" st.session_state.game_over = True elif st.session_state.attempts == 0: st.session_state.message = f"\nYou've run out of attempts! The word was: {st.session_state.word}" st.session_state.game_over = True if st.button("Get a Hint"): hint_message = give_hint() st.session_state.message = hint_message if st.session_state.game_over and st.session_state.play_again_triggered or st.button("Play Again"): st.session_state.play_again_triggered = True initialize_game_state()
0
0.510987
1
0.510987
game-dev
MEDIA
0.426648
game-dev,web-frontend
0.614619
1
0.614619
JukeboxMC/JukeboxMC
1,628
JukeboxMC-Server/src/main/kotlin/org/jukeboxmc/server/block/behavior/BlockFlowerPot.kt
package org.jukeboxmc.server.block.behavior import org.cloudburstmc.nbt.NbtMap import org.jukeboxmc.api.Identifier import org.jukeboxmc.api.block.FlowerPot import org.jukeboxmc.api.block.data.BlockFace import org.jukeboxmc.api.blockentity.BlockEntity import org.jukeboxmc.api.blockentity.BlockEntityType import org.jukeboxmc.api.math.Vector import org.jukeboxmc.server.block.JukeboxBlock import org.jukeboxmc.server.extensions.toByte import org.jukeboxmc.server.item.JukeboxItem import org.jukeboxmc.server.player.JukeboxPlayer import org.jukeboxmc.server.world.JukeboxWorld class BlockFlowerPot(identifier: Identifier, blockStates: NbtMap?) : JukeboxBlock(identifier, blockStates), FlowerPot { override fun placeBlock( player: JukeboxPlayer, world: JukeboxWorld, blockPosition: Vector, placePosition: Vector, clickedPosition: Vector, itemInHand: JukeboxItem, blockFace: BlockFace ): Boolean { val block = world.getBlock(placePosition) if (block is BlockWater && block.getLiquidDepth() == 0) { world.setBlock(placePosition, block, 1, false) } BlockEntity.create(BlockEntityType.FLOWERPOT, this)?.spawn() return super.placeBlock(player, world, blockPosition, placePosition, clickedPosition, itemInHand, blockFace) } override fun isUpdate(): Boolean { return this.getBooleanState("update_bit") } override fun setUpdate(value: Boolean): FlowerPot { return this.setState("update_bit", value.toByte()) } override fun getWaterLoggingLevel(): Int { return 1 } }
0
0.797634
1
0.797634
game-dev
MEDIA
0.890058
game-dev
0.640478
1
0.640478
mafaca/UtinyRipper
1,200
uTinyRipperCore/Parser/Classes/AudioMixerSnapshot.cs
using System.Collections.Generic; using uTinyRipper.YAML; using uTinyRipper.Converters; using uTinyRipper.Classes.Misc; namespace uTinyRipper.Classes { #warning TODO: not implemented public sealed class AudioMixerSnapshot : NamedObject { public AudioMixerSnapshot(AssetInfo assetInfo) : base(assetInfo) { } public override void Read(AssetReader reader) { base.Read(reader); AudioMixer.Read(reader); SnapshotID.Read(reader); } public override IEnumerable<PPtr<Object>> FetchDependencies(DependencyContext context) { foreach (PPtr<Object> asset in base.FetchDependencies(context)) { yield return asset; } yield return context.FetchDependency(AudioMixer, AudioMixerName); } protected override YAMLMappingNode ExportYAMLRoot(IExportContainer container) { YAMLMappingNode node = base.ExportYAMLRoot(container); node.Add(AudioMixerName, AudioMixer.ExportYAML(container)); node.Add(SnapshotIDName, SnapshotID.ExportYAML(container)); return node; } public const string AudioMixerName = "m_AudioMixer"; public const string SnapshotIDName = "m_SnapshotID"; public PPtr<AudioMixer> AudioMixer; public UnityGUID SnapshotID; } }
0
0.95695
1
0.95695
game-dev
MEDIA
0.829604
game-dev
0.886945
1
0.886945
mokkkk/MhdpColiseumDatapacksComponents
3,991
mhdp_core/data/mhdp_items/function/weapons/short_sword/type_tec/7_bash_1/main.mcfunction
#> mhdp_items:weapons/short_sword/type_tec/7_bash_1/main # # 盾攻撃 メイン処理 # # @within function mhdp_items:weapons/great_sword/type_tec/main # 操作表示 execute if score @s Wpn.GeneralTimer matches 1 run function mhdp_items:core/util/item_modify_custom_name {Name:"盾攻撃コンボ・1"} # タイマー増加 scoreboard players add @s Wpn.GeneralTimer 1 execute if entity @s[tag=!Ply.Weapon.HisStop] run scoreboard players add @s Wpn.AnimationTimer 1 # アニメーション演出 execute if score @s Wpn.AnimationTimer matches 3 run playsound entity.player.attack.sweep master @a[tag=!Ply.State.IsSilent] ~ ~ ~ 2 0.8 execute if score @s Wpn.AnimationTimer matches 1 run function mhdp_items:weapons/short_sword/type_tec/7_bash_1/animation_0 execute if score @s Wpn.AnimationTimer matches 3 run function mhdp_items:weapons/short_sword/type_tec/7_bash_1/animation_1 execute if score @s Wpn.AnimationTimer matches 4 run function mhdp_items:weapons/short_sword/type_tec/7_bash_1/animation_2 execute if score @s Wpn.AnimationTimer matches 5 run function mhdp_items:weapons/short_sword/type_tec/7_bash_1/animation_3 execute if score @s Wpn.AnimationTimer matches 7 run function mhdp_items:weapons/short_sword/type_tec/7_bash_1/animation_4 execute if score @s Wpn.AnimationTimer matches 4 positioned ~ ~1.65 ~ positioned ^ ^ ^1.2 run function mhdp_items:weapons/short_sword/type_tec/7_bash_1/particle # 攻撃 execute if score @s Wpn.GeneralTimer matches 4 run function mhdp_items:weapons/short_sword/type_tec/7_bash_1/attack # 演出 execute if entity @s[tag=!Ply.Option.DisableCameraEffect] if score @s Wpn.GeneralTimer matches 1..3 run tp @s ~ ~ ~ ~-1 ~ execute if entity @s[tag=!Ply.Option.DisableCameraEffect] if score @s Wpn.GeneralTimer matches 4..7 run tp @s ~ ~ ~ ~1.3 ~ # 移動制限 execute if score @s Wpn.GeneralTimer matches 1 run function api:weapon_operation/attribute_movestop execute if score @s Wpn.GeneralTimer matches 7 run function api:weapon_operation/attribute_moveslow execute if score @s Wpn.GeneralTimer matches 1 run tag @s add Ply.Weapon.NoMoveJump # 移動 execute if score @s Wpn.GeneralTimer matches 3 run scoreboard players set $strength player_motion.api.launch 3000 execute if score @s Wpn.GeneralTimer matches 3 rotated ~ 0 run function player_motion:api/launch_looking # 先行入力 execute if entity @s[tag=Ply.Ope.StartUsingEnderEye.NotSneak] if score @s Wpn.GeneralTimer matches 3..12 run function mhdp_items:core/buffering/a execute if entity @s[tag=Ply.Ope.StartDoubleJump] if score @s Wpn.GeneralTimer matches 3..12 run function mhdp_items:core/buffering/jump execute if entity @s[tag=Ply.Ope.UsedSneakingEnderEye.Short] if score @s Wpn.GeneralTimer matches 3..12 run function mhdp_items:core/buffering/d execute if entity @s[tag=Ply.Ope.UsedSneakingEnderEye.Long] if score @s Wpn.GeneralTimer matches 3..12 run function mhdp_items:core/buffering/f # 遷移 # スニーク+ジャンプ時:バックステップに移行 execute if entity @s[tag=Ply.Ope.IsSneaking,tag=Ply.Ope.StartKeyJump] if score @s Wpn.GeneralTimer matches 9.. run function mhdp_items:weapons/short_sword/type_tec/12_backstep/start # 右クリック:バックナックルに移行 execute if entity @s[tag=Ply.Ope.Buffering.A] if score @s Wpn.GeneralTimer matches 9.. run function mhdp_items:weapons/short_sword/type_tec/8_bash_2/start # 同時押し:回転斬りに移行 execute if entity @s[tag=Ply.Ope.Buffering.D] if score @s Wpn.GeneralTimer matches 9.. run function mhdp_items:weapons/short_sword/type_tec/10_spin/start # 同時押し長押し:溜め斬り落としに移行 execute if entity @s[tag=Ply.Ope.Buffering.F] if score @s Wpn.GeneralTimer matches 9.. run function mhdp_items:weapons/short_sword/type_tec/27_charge_spear/start # ジャンプ回避 execute if entity @s[tag=Ply.Ope.Buffering.Jump] if score @s Wpn.GeneralTimer matches 9.. run function mhdp_items:weapons/short_sword/util/move_jump # 終了 execute if score @s Wpn.GeneralTimer matches 13.. run function mhdp_items:weapons/short_sword/type_tec/7_bash_1/end
0
0.925055
1
0.925055
game-dev
MEDIA
0.963639
game-dev
0.93105
1
0.93105
hushuangshaung/HSSFramework
1,264
Assets/Scripts/Base/PatchLogic/FsmNode/FsmUpdatePackageManifest.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UniFramework.Machine; using YooAsset; public class FsmUpdatePackageManifest : IStateNode { private StateMachine _machine; void IStateNode.OnCreate(StateMachine machine) { _machine = machine; } void IStateNode.OnEnter() { PatchEventDefine.PatchStepsChange.SendEventMessage("更新资源清单!"); InitHelper.Instance.StartCoroutine(UpdateManifest()); } void IStateNode.OnUpdate() { } void IStateNode.OnExit() { } private IEnumerator UpdateManifest() { var packageName = (string)_machine.GetBlackboardValue("PackageName"); var packageVersion = (string)_machine.GetBlackboardValue("PackageVersion"); var package = YooAssets.GetPackage(packageName); var operation = package.UpdatePackageManifestAsync(packageVersion); yield return operation; if (operation.Status != EOperationStatus.Succeed) { Debug.LogWarning(operation.Error); PatchEventDefine.PackageManifestUpdateFailed.SendEventMessage(); yield break; } else { _machine.ChangeState<FsmCreateDownloader>(); } } }
0
0.779575
1
0.779575
game-dev
MEDIA
0.616027
game-dev
0.824206
1
0.824206
Godofcong-1/erArk
20,260
Script/Design/pregnancy.py
import math import random from types import FunctionType from Script.Core import ( cache_control, game_path_config, game_type, get_text, ) from Script.Design import ( character_handle, game_time, handle_premise, talk, attr_calculation ) from Script.UI.Moudle import draw from Script.UI.Panel import achievement_panel, sp_event_panel from Script.Config import game_config, normal_config game_path = game_path_config.game_path cache: game_type.Cache = cache_control.cache """ 游戏缓存数据 """ _: FunctionType = get_text._ """ 翻译api """ window_width: int = normal_config.config_normal.text_width """ 窗体宽度 """ width = normal_config.config_normal.text_width """ 屏幕宽度 """ def get_fertilization_rate(character_id: int): """ 根据当前V精液量计算受精概率 """ character_data: game_type.Character = cache.character_data[character_id] pl_character_data: game_type.Character = cache.character_data[0] draw_text = "" semen_count = character_data.dirty.body_semen[7][1] semen_level = character_data.dirty.body_semen[7][2] now_reproduction = character_data.pregnancy.reproduction_period # 基础概率 now_rate = math.pow(semen_count / 1000,2) * 100 + semen_level * 5 # 事前避孕药修正 if character_data.h_state.body_item[11][1]: now_rate = 0 if game_time.judge_date_big_or_small(cache.game_time,character_data.h_state.body_item[11][2]): character_data.h_state.body_item[11][1] = False # 事后避孕药修正 if character_data.h_state.body_item[12][1]: now_rate = 0 character_data.h_state.body_item[12][1] = False if semen_count > 0: # 如果避孕的话绘制信息 if now_rate == 0: draw_text += _("\n在避孕药的影响下,{0}的精子无法受精\n").format(pl_character_data.name) # 其他修正 else: # 生理周期修正 now_rate *= game_config.config_reproduction_period[now_reproduction].type # 排卵促进药 if character_data.h_state.body_item[10][1]: new_rate = min(100, now_rate * 5) draw_text += _("\n在排卵促进药的影响下,怀孕概率由{0}上升到了{1}%\n").format(character_data.pregnancy.fertilization_rate, new_rate) character_data.pregnancy.fertilization_rate = new_rate character_data.h_state.body_item[10][1] = False # 排卵催眠 if character_data.hypnosis.force_ovulation: new_rate = min(100, now_rate * 5) draw_text += _("\n在催眠-强制排卵的影响下,怀孕概率由{0}上升到了{1}%\n").format(character_data.pregnancy.fertilization_rate, new_rate) character_data.pregnancy.fertilization_rate = new_rate character_data.hypnosis.force_ovulation = False # 浓厚精液 if pl_character_data.talent[33] == 1: new_rate = min(100, now_rate * 2) draw_text += _("\n在浓厚精液的影响下,怀孕概率由{0}上升到了{1}%\n").format(character_data.pregnancy.fertilization_rate, new_rate) character_data.pregnancy.fertilization_rate = new_rate # 保留两位小数 now_rate = round(now_rate,2) character_data.pregnancy.fertilization_rate = now_rate def check_fertilization(character_id: int): """ 根据受精概率并判断是否受精 """ character_data: game_type.Character = cache.character_data[character_id] draw_text = "" # 仅在排卵日进行判定 if character_data.pregnancy.reproduction_period != 5: return 0 # 清空小穴和子宫的当前精液量 for body_cid in [6, 7]: character_data.dirty.body_semen[body_cid][1] = 0 character_data.dirty.body_semen[body_cid][2] = 0 # 消除强制排卵状态 if character_data.hypnosis.force_ovulation: character_data.hypnosis.force_ovulation = False # 如果当前已受精,则跳过判断 for i in {20,21,22}: if character_data.talent[i] == 1: character_data.pregnancy.fertilization_rate = 0 return 0 # 只判断有受精可能的 if character_data.pregnancy.fertilization_rate: # 如果未初潮,则无法受精并触发对话 if character_data.talent[6] == 1: draw_text += _("\n因为{0}还没有迎来初潮,所以精子只能在阴道内徒劳地寻找不存在的卵子,无法完成受精\n").format(character_data.name) # 种族是机械的则需要判断是否有生育模组 elif character_data.race == 2 and character_data.talent[171] == 0: character_data.pregnancy.fertilization_rate = 0 draw_text += _("\n{0}是机械体,且未安装生育模组,无法受精\n").format(character_data.name) # 正常情况下可以受精 else: # 由随机数判断是否受精 if random.randint(1,100) <= character_data.pregnancy.fertilization_rate: draw_text += "\n※※※※※※※※※\n" draw_text += _("\n博士的精子与{0}的卵子结合,成功在子宫里着床了\n").format(character_data.name) draw_text += _("\n{0}获得了[受精]\n").format(character_data.name) draw_text += "\n※※※※※※※※※\n" character_data.talent[20] = 1 character_data.pregnancy.fertilization_time = cache.game_time # 判断是否是无意识妊娠 if character_data.pregnancy.unconscious_fertilization: character_data.talent[35] = 1 draw_text += _("\n{0}从未在有意识下被中出过,因此不会意识到自己已经怀孕了\n").format(character_data.name) draw_text += _("\n{0}获得了[无意识妊娠]\n").format(character_data.name) draw_text += "\n※※※※※※※※※\n" # 触发受精的二段行动 character_data.second_behavior["fertilization"] = 1 else: if character_data.h_state.body_item[11][1] or character_data.h_state.body_item[12][1]: draw_text += _("\n在避孕药的影响下——") draw_text += _("\n精子在{0}的阴道中游荡,但未能成功受精\n").format(character_data.name) character_data.second_behavior["fertilization_failed"] = 1 character_data.pregnancy.fertilization_rate = 0 else: if character_data.h_state.body_item[11][1] or character_data.h_state.body_item[12][1]: draw_text += _("\n在避孕药的影响下——\n精子在{0}的阴道中游荡,但未能成功受精\n").format(character_data.name) # 绘制输出 talk.must_show_talk_check(character_id) now_draw = draw.WaitDraw() now_draw.width = window_width now_draw.text = draw_text now_draw.draw() # 结算成就 if character_data.talent[20]: # 破处当天受精 if handle_premise.handle_first_sex_in_today(character_id): achievement_panel.achievement_flow(_("生育"), 706) # 育儿中的角色受精怀孕 if character_data.talent[24]: achievement_panel.achievement_flow(_("生育"), 708) def check_pregnancy(character_id: int): """ 判断是否由受精变为怀孕 """ character_data: game_type.Character = cache.character_data[character_id] # 需要已经是受精状态 if character_data.talent[20]: # 计算经过的天数 start_date = cache.game_time end_date = character_data.pregnancy.fertilization_time past_day = (start_date - end_date).days # 90天在游戏内实际体验是30天 if past_day >= 90: character_data.talent[20] = 0 character_data.talent[21] = 1 character_data.talent[26] = 1 character_data.talent[27] = 1 # 根据罩杯大小修改乳汁上限 for talent_id in [121,122,123,124,125]: if character_data.talent[talent_id]: character_data.pregnancy.milk_max = 150 + (talent_id - 121) * 40 break character_data.second_behavior["pregnancy"] = 1 talk.must_show_talk_check(character_id) draw_text = "\n※※※※※※※※※\n" draw_text += _("\n随着怀孕的进程,{0}挺起了大肚子,隆起的曲线下是正在孕育的新生命\n").format(character_data.name) draw_text += _("\n{0}有孕在身,将会暂停工作和部分娱乐\n").format(character_data.name) draw_text += _("\n{0}从[受精]转变为[妊娠]\n").format(character_data.name) draw_text += _("\n{0}获得了[孕肚]\n").format(character_data.name) draw_text += _("\n{0}获得了[泌乳]\n").format(character_data.name) draw_text += "\n※※※※※※※※※\n" now_draw = draw.WaitDraw() now_draw.width = window_width now_draw.text = draw_text now_draw.draw() def check_near_born(character_id: int): """ 判断是否开始临盆 """ character_data: game_type.Character = cache.character_data[character_id] # 需要已经是妊娠状态 if character_data.talent[21]: # 计算经过的天数 start_date = cache.game_time end_date = character_data.pregnancy.fertilization_time past_day = (start_date - end_date).days # 从受精开始算,标准妊娠时间是265天 if past_day >= 260: # 清零污浊结构体 character_data.dirty = attr_calculation.get_dirty_reset(character_data.dirty) # 赋予对应素质和二段行动 character_data.talent[21] = 0 character_data.talent[22] = 1 character_data.second_behavior["parturient"] = 1 talk.must_show_talk_check(character_id) draw_text = "\n※※※※※※※※※\n" draw_text += _("\n随着怀孕的进程,{0}临近生产,即将诞下爱的结晶\n").format(character_data.name) draw_text += _("\n{0}在临盆期内会一直躺在医疗部住院区的病床上,多去陪陪她,静候生产的来临吧\n").format(character_data.name) draw_text += _("\n{0}从[妊娠]转变为[临盆]\n").format(character_data.name) draw_text += "\n※※※※※※※※※\n" now_draw = draw.WaitDraw() now_draw.width = window_width now_draw.text = draw_text now_draw.draw() def check_born(character_id: int): """ 判断是否开始生产 """ character_data: game_type.Character = cache.character_data[character_id] # 需要已经是临盆状态 if character_data.talent[22]: # 计算经过的天数 start_date = cache.game_time end_date = character_data.pregnancy.fertilization_time past_day = (start_date - end_date).days - 260 # 每过一天+20%几率判断是否生产 now_rate = past_day * 20 # print(f"debug {character_data.name}进入生产检测,当前生产几率为{now_rate}%") if random.randint(1,100) <= now_rate: draw_panel = sp_event_panel.Born_Panel(character_id) draw_panel.draw() def check_rearing(character_id: int): """ 判断是否开始育儿 """ character_data: game_type.Character = cache.character_data[character_id] # 需要已经是产后状态 if character_data.talent[23]: # 计算经过的天数 child_id = character_data.relationship.child_id_list[-1] child_character_data: game_type.Character = cache.character_data[child_id] start_date = cache.game_time end_date = child_character_data.pregnancy.born_time past_day = (start_date - end_date).days # if past_day >= 2: character_data.talent[23] = 0 character_data.talent[24] = 1 character_data.second_behavior["rearing"] = 1 talk.must_show_talk_check(character_id) draw_text = "\n※※※※※※※※※\n" draw_text += _("\n{0}的产后休息结束了\n").format(character_data.name) draw_text += _("\n{0}接下来的行动重心会以照顾{1}为主\n").format(character_data.name, child_character_data.name) draw_text += _("\n{0}从[产后]转变为[育儿]\n").format(character_data.name) draw_text += "\n※※※※※※※※※\n" now_draw = draw.WaitDraw() now_draw.width = window_width now_draw.text = draw_text now_draw.draw() def check_rearing_complete(character_id: int): """ 判断是否完成育儿 """ character_data: game_type.Character = cache.character_data[character_id] # 需要已经是育儿状态 if character_data.talent[24]: # 计算经过的天数 child_id = character_data.relationship.child_id_list[-1] child_character_data: game_type.Character = cache.character_data[child_id] start_date = cache.game_time end_date = child_character_data.pregnancy.born_time past_day = (start_date - end_date).days # 90天在游戏内实际体验是30天 if past_day >= 90: character_data.talent[24] = 0 character_data.talent[27] = 0 character_handle.get_new_character(child_id) character_data.second_behavior["rearing_complete"] = 1 talk.must_show_talk_check(character_id) child_character_data.talent[101] = 0 child_character_data.talent[102] = 1 child_character_data.work.work_type = 152 draw_text = "\n※※※※※※※※※\n" draw_text += _("\n在{0}的悉心照料下,{1}顺利长大了\n").format(character_data.name, child_character_data.name) draw_text += _("\n{0}完成了育儿行动,开始回到正常的工作生活中来\n").format(character_data.name) draw_text += _("\n{0}能够初步独立了,在长大成人之前会一直在教育区上课学习\n").format(child_character_data.name) if len(cache.rhodes_island.all_work_npc_set[151]) == 0: draw_text += _("\n当前教育区没有进行授课工作的老师,请尽快安排一名干员负责教师工作\n") draw_text += _("\n{0}失去了[育儿]\n").format(character_data.name) draw_text += _("\n{0}失去了[泌乳]\n").format(character_data.name) draw_text += _("\n{0}从[婴儿]成长为了[幼女]\n").format(child_character_data.name) draw_text += _("\n{0}成为了一名准干员\n").format(child_character_data.name) draw_text += "\n※※※※※※※※※\n" now_draw = draw.WaitDraw() now_draw.width = window_width now_draw.text = draw_text now_draw.draw() def check_grow_to_loli(character_id: int): """ 判断是否成长为萝莉 """ character_data: game_type.Character = cache.character_data[character_id] # 需要是女儿,而且已经是幼女状态 if character_data.relationship.father_id == 0 and character_data.talent[102]: # 计算经过的天数 start_date = cache.game_time end_date = character_data.pregnancy.born_time past_day = (start_date - end_date).days # 在幼女后又过了两个月 if past_day >= 270: character_data.second_behavior["child_to_loli"] = 1 talk.must_show_talk_check(character_id) character_data.talent[102] = 0 character_data.talent[103] = 1 character_data.talent[6] = 0 chest_grow_text = chest_grow(character_id) draw_text = "\n※※※※※※※※※\n" draw_text += _("\n{0}的身体渐渐成长,开始进入青春期,在第二性征发育的同时,也迎来了第一次的初潮\n").format(character_data.name) draw_text += _("\n{0}从[幼女]成长为了[萝莉]\n").format(character_data.name) draw_text += _("\n{0}失去了[未初潮]\n").format(character_data.name) draw_text += chest_grow_text draw_text += _("\n{0}可以参加上课以外的工作了\n").format(character_data.name) draw_text += "\n※※※※※※※※※\n" now_draw = draw.WaitDraw() now_draw.width = window_width now_draw.text = draw_text now_draw.draw() def check_grow_to_girl(character_id: int): """ 判断是否成长为少女 """ character_data: game_type.Character = cache.character_data[character_id] # 需要是女儿,而且已经是萝莉状态 if character_data.relationship.father_id == 0 and character_data.talent[103]: # 计算经过的天数 start_date = cache.game_time end_date = character_data.pregnancy.born_time past_day = (start_date - end_date).days # 在萝莉后又过了两个月 if past_day >= 450: character_data.second_behavior["loli_to_girl"] = 1 talk.must_show_talk_check(character_id) character_data.talent[103] = 0 character_data.talent[104] = 1 character_data.talent[7] = 0 chest_grow_text = chest_grow(character_id) body_part_grow_text = body_part_grow(character_id) draw_text = "\n※※※※※※※※※\n" draw_text += _("\n{0}的身体完全长成,迎来了自己的成人礼,成为了一位亭亭玉立的少女\n").format(character_data.name) draw_text += _("\n{0}从[萝莉]成长为了[少女]\n").format(character_data.name) draw_text += _("\n{0}失去了[未成年]\n").format(character_data.name) draw_text += chest_grow_text draw_text += body_part_grow_text draw_text += _("\n{0}可以进行正常的工作了\n").format(character_data.name) draw_text += "\n※※※※※※※※※\n" now_draw = draw.WaitDraw() now_draw.width = window_width now_draw.text = draw_text now_draw.draw() def check_all_pregnancy(character_id: int): """ 进行受精怀孕的全流程检查 \n\n包括刷新受精概率、是否受精、是否由受精变为怀孕、是否结束怀孕 """ get_fertilization_rate(character_id) check_fertilization(character_id) check_pregnancy(character_id) check_near_born(character_id) check_born(character_id) check_rearing(character_id) check_rearing_complete(character_id) check_grow_to_loli(character_id) check_grow_to_girl(character_id) def update_reproduction_period(character_id: int): """ 刷新生理周期 """ character_data: game_type.Character = cache.character_data[character_id] now_reproduction = character_data.pregnancy.reproduction_period if now_reproduction == 6: character_data.pregnancy.reproduction_period = 0 else: character_data.pregnancy.reproduction_period += 1 def chest_grow(character_id: int,print_flag = False): """ 进行胸部生长判定 """ character_data: game_type.Character = cache.character_data[character_id] mom_id = character_data.relationship.mother_id mom_character_data: game_type.Character = cache.character_data[mom_id] # 获得本人的旧胸部大小和母亲的胸部大小 for i in {121,122,123,124,125}: if character_data.talent[i]: old_chest_id = i if mom_character_data.talent[i]: mom_chest_id = i # 跳过机械 if mom_character_data.race == 2: return "" # 用随机数计算生长,可能长3、长2或者长1,母亲胸部越大生长比例就越高 # 母亲胸部0时从长0~长3生长比例是 0.6 0.25 0.1 0.05,母亲胸部6时反过来 randow_grow = random.randint(1,100) grow_rate = mom_chest_id - 121 grow_0 = 60 - 11 * grow_rate grow_1 = 25 - 3 *grow_rate grow_2 = 10 + 3 *grow_rate if randow_grow > grow_0 + grow_1 + grow_2: new_chest_id = min(old_chest_id + 3 ,125) elif randow_grow > grow_0 + grow_1: new_chest_id = min(old_chest_id + 2 ,125) elif randow_grow > grow_0 : new_chest_id = min(old_chest_id + 1 ,125) else: new_chest_id = old_chest_id # 把旧的胸部素质换成新的 character_data.talent[old_chest_id] = 0 character_data.talent[new_chest_id] = 1 # 根据flag判定是否要绘制输出 old_name = game_config.config_talent[old_chest_id].name new_name = game_config.config_talent[new_chest_id].name now_draw = draw.WaitDraw() now_draw.width = window_width if new_chest_id != old_chest_id: now_text = _("\n{0}的胸部从[{1}]成长为了[{2}]\n").format(character_data.name, old_name, new_name) else: now_text = _("\n{0}的胸部依旧保持在[{1}]没有成长\n").format(character_data.name, old_name) if print_flag: now_draw.text = now_text now_draw.draw() # 返回胸部成长情况的文本 return now_text def body_part_grow(character_id: int,print_flag = False): """ 进行除胸部外其他部位的生长判定 """ character_data: game_type.Character = cache.character_data[character_id] mom_id = character_data.relationship.mother_id mom_character_data: game_type.Character = cache.character_data[mom_id] now_text = "" # 跳过机械 if mom_character_data.race == 2: return now_text old_talent_id_list, new_talent_id_list = [], [] # 获得本人的臀部大小和母亲的臀部大小 for i in {126,127,128,129,130,131,132}: if character_data.talent[i]: old_talent_id_list.append(i) if mom_character_data.talent[i]: new_talent_id_list.append(i) # 把旧的素质换成新的 for old_talent_id in old_talent_id_list: character_data.talent[old_talent_id] = 0 for new_talent_id in new_talent_id_list: character_data.talent[new_talent_id] = 1 # 如果新旧列表长度不一致则报错 if len(old_talent_id_list) != len(new_talent_id_list): error_text = _("\nerror {0}的身体部位成长时新旧素质列表长度不一致,母亲为{1},旧列表{2},新列表{3}\n").format(character_data.name, mom_character_data.name, old_talent_id_list, new_talent_id_list) raise ValueError(error_text) # 根据flag判定是否要绘制输出 for i in range(len(old_talent_id_list)): old_talent_id = old_talent_id_list[i] new_talent_id = new_talent_id_list[i] old_name = game_config.config_talent[old_talent_id].name new_name = game_config.config_talent[new_talent_id].name now_draw = draw.WaitDraw() now_draw.width = window_width if new_talent_id != old_talent_id: now_text += _("\n{0}的[{1}]成长为了[{2}]\n").format(character_data.name, old_name, new_name) if print_flag: now_draw.text = now_text now_draw.draw() # 返回成长情况的文本 return now_text
0
0.56348
1
0.56348
game-dev
MEDIA
0.376126
game-dev
0.801216
1
0.801216
Planimeter/hl2sb-src
43,629
src/public/filesystem_init.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //============================================================================= #undef PROTECTED_THINGS_ENABLE #undef PROTECT_FILEIO_FUNCTIONS #ifndef POSIX #undef fopen #endif #if defined( _WIN32 ) && !defined( _X360 ) #include <windows.h> #include <direct.h> #include <io.h> #include <process.h> #elif defined( POSIX ) #include <unistd.h> #define _chdir chdir #define _access access #endif #include <stdio.h> #include <sys/stat.h> #include "tier1/strtools.h" #include "tier1/utlbuffer.h" #include "filesystem_init.h" #include "tier0/icommandline.h" #include "KeyValues.h" #include "appframework/IAppSystemGroup.h" #include "tier1/smartptr.h" #if defined( _X360 ) #include "xbox\xbox_win32stubs.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> #if !defined( _X360 ) #define GAMEINFO_FILENAME "gameinfo.txt" #else // The .xtx file is a TCR requirement, as .txt files cannot live on the DVD. // The .xtx file only exists outside the zips (same as .txt and is made during the image build) and is read to setup the search paths. // So all other code should be able to safely expect gameinfo.txt after the zip is mounted as the .txt file exists inside the zips. // The .xtx concept is private and should only have to occurr here. As a safety measure, if the .xtx file is not found // a retry is made with the original .txt name #define GAMEINFO_FILENAME "gameinfo.xtx" #endif #define GAMEINFO_FILENAME_ALTERNATE "gameinfo.txt" static char g_FileSystemError[256]; static bool s_bUseVProjectBinDir = false; static FSErrorMode_t g_FileSystemErrorMode = FS_ERRORMODE_VCONFIG; // Call this to use a bin directory relative to VPROJECT void FileSystem_UseVProjectBinDir( bool bEnable ) { s_bUseVProjectBinDir = bEnable; } // This class lets you modify environment variables, and it restores the original value // when it goes out of scope. class CTempEnvVar { public: CTempEnvVar( const char *pVarName ) { m_bRestoreOriginalValue = true; m_pVarName = pVarName; const char *pValue = NULL; #ifdef _WIN32 // Use GetEnvironmentVariable instead of getenv because getenv doesn't pick up changes // to the process environment after the DLL was loaded. char szBuf[ 4096 ]; if ( GetEnvironmentVariable( m_pVarName, szBuf, sizeof( szBuf ) ) != 0) { pValue = szBuf; } #else // LINUX BUG: see above pValue = getenv( pVarName ); #endif if ( pValue ) { m_bExisted = true; m_OriginalValue.SetSize( Q_strlen( pValue ) + 1 ); memcpy( m_OriginalValue.Base(), pValue, m_OriginalValue.Count() ); } else { m_bExisted = false; } } ~CTempEnvVar() { if ( m_bRestoreOriginalValue ) { // Restore the original value. if ( m_bExisted ) { SetValue( "%s", m_OriginalValue.Base() ); } else { ClearValue(); } } } void SetRestoreOriginalValue( bool bRestore ) { m_bRestoreOriginalValue = bRestore; } int GetValue(char *pszBuf, int nBufSize ) { if ( !pszBuf || ( nBufSize <= 0 ) ) return 0; #ifdef _WIN32 // Use GetEnvironmentVariable instead of getenv because getenv doesn't pick up changes // to the process environment after the DLL was loaded. return GetEnvironmentVariable( m_pVarName, pszBuf, nBufSize ); #else // LINUX BUG: see above const char *pszOut = getenv( m_pVarName ); if ( !pszOut ) { *pszBuf = '\0'; return 0; } Q_strncpy( pszBuf, pszOut, nBufSize ); return Q_strlen( pszBuf ); #endif } void SetValue( const char *pValue, ... ) { char valueString[4096]; va_list marker; va_start( marker, pValue ); Q_vsnprintf( valueString, sizeof( valueString ), pValue, marker ); va_end( marker ); #ifdef WIN32 char str[4096]; Q_snprintf( str, sizeof( str ), "%s=%s", m_pVarName, valueString ); _putenv( str ); #else setenv( m_pVarName, valueString, 1 ); #endif } void ClearValue() { #ifdef WIN32 char str[512]; Q_snprintf( str, sizeof( str ), "%s=", m_pVarName ); _putenv( str ); #else setenv( m_pVarName, "", 1 ); #endif } private: bool m_bRestoreOriginalValue; const char *m_pVarName; bool m_bExisted; CUtlVector<char> m_OriginalValue; }; class CSteamEnvVars { public: CSteamEnvVars() : m_SteamAppId( "SteamAppId" ), m_SteamUserPassphrase( "SteamUserPassphrase" ), m_SteamAppUser( "SteamAppUser" ), m_Path( "path" ) { } void SetRestoreOriginalValue_ALL( bool bRestore ) { m_SteamAppId.SetRestoreOriginalValue( bRestore ); m_SteamUserPassphrase.SetRestoreOriginalValue( bRestore ); m_SteamAppUser.SetRestoreOriginalValue( bRestore ); m_Path.SetRestoreOriginalValue( bRestore ); } CTempEnvVar m_SteamAppId; CTempEnvVar m_SteamUserPassphrase; CTempEnvVar m_SteamAppUser; CTempEnvVar m_Path; }; // ---------------------------------------------------------------------------------------------------- // // Helpers. // ---------------------------------------------------------------------------------------------------- // void Q_getwd( char *out, int outSize ) { #if defined( _WIN32 ) || defined( WIN32 ) _getcwd( out, outSize ); Q_strncat( out, "\\", outSize, COPY_ALL_CHARACTERS ); #else getcwd( out, outSize ); strcat( out, "/" ); #endif Q_FixSlashes( out ); } // ---------------------------------------------------------------------------------------------------- // // Module interface. // ---------------------------------------------------------------------------------------------------- // CFSSearchPathsInit::CFSSearchPathsInit() { m_pDirectoryName = NULL; m_pLanguage = NULL; m_ModPath[0] = 0; m_bMountHDContent = m_bLowViolence = false; } CFSSteamSetupInfo::CFSSteamSetupInfo() { m_pDirectoryName = NULL; m_bOnlyUseDirectoryName = false; m_bSteam = false; m_bToolsMode = true; m_bNoGameInfo = false; } CFSLoadModuleInfo::CFSLoadModuleInfo() { m_pFileSystemDLLName = NULL; m_pFileSystem = NULL; m_pModule = NULL; } CFSMountContentInfo::CFSMountContentInfo() { m_bToolsMode = true; m_pDirectoryName = NULL; m_pFileSystem = NULL; } const char *FileSystem_GetLastErrorString() { return g_FileSystemError; } KeyValues* ReadKeyValuesFile( const char *pFilename ) { // Read in the gameinfo.txt file and null-terminate it. FILE *fp = fopen( pFilename, "rb" ); if ( !fp ) return NULL; CUtlVector<char> buf; fseek( fp, 0, SEEK_END ); buf.SetSize( ftell( fp ) + 1 ); fseek( fp, 0, SEEK_SET ); fread( buf.Base(), 1, buf.Count()-1, fp ); fclose( fp ); buf[buf.Count()-1] = 0; KeyValues *kv = new KeyValues( "" ); if ( !kv->LoadFromBuffer( pFilename, buf.Base() ) ) { kv->deleteThis(); return NULL; } return kv; } static bool Sys_GetExecutableName( char *out, int len ) { #if defined( _WIN32 ) if ( !::GetModuleFileName( ( HINSTANCE )GetModuleHandle( NULL ), out, len ) ) { return false; } #else if ( CommandLine()->GetParm(0) ) { Q_MakeAbsolutePath( out, len, CommandLine()->GetParm(0) ); } else { return false; } #endif return true; } bool FileSystem_GetExecutableDir( char *exedir, int exeDirLen ) { exedir[0] = 0; if ( s_bUseVProjectBinDir ) { const char *pProject = GetVProjectCmdLineValue(); if ( !pProject ) { // Check their registry. pProject = getenv( GAMEDIR_TOKEN ); } if ( pProject ) { Q_snprintf( exedir, exeDirLen, "%s%c..%cbin", pProject, CORRECT_PATH_SEPARATOR, CORRECT_PATH_SEPARATOR ); return true; } return false; } if ( !Sys_GetExecutableName( exedir, exeDirLen ) ) return false; Q_StripFilename( exedir ); if ( IsX360() ) { // The 360 can have its exe and dlls reside on different volumes // use the optional basedir as the exe dir if ( CommandLine()->FindParm( "-basedir" ) ) { strcpy( exedir, CommandLine()->ParmValue( "-basedir", "" ) ); } } Q_FixSlashes( exedir ); // Return the bin directory as the executable dir if it's not in there // because that's really where we're running from... char ext[MAX_PATH]; Q_StrRight( exedir, 4, ext, sizeof( ext ) ); if ( ext[0] != CORRECT_PATH_SEPARATOR || Q_stricmp( ext+1, "bin" ) != 0 ) { Q_strncat( exedir, CORRECT_PATH_SEPARATOR_S, exeDirLen, COPY_ALL_CHARACTERS ); Q_strncat( exedir, "bin", exeDirLen, COPY_ALL_CHARACTERS ); Q_FixSlashes( exedir ); } return true; } static bool FileSystem_GetBaseDir( char *baseDir, int baseDirLen ) { if ( FileSystem_GetExecutableDir( baseDir, baseDirLen ) ) { Q_StripFilename( baseDir ); return true; } return false; } void LaunchVConfig() { #if defined( _WIN32 ) && !defined( _X360 ) char vconfigExe[MAX_PATH]; FileSystem_GetExecutableDir( vconfigExe, sizeof( vconfigExe ) ); Q_AppendSlash( vconfigExe, sizeof( vconfigExe ) ); Q_strncat( vconfigExe, "vconfig.exe", sizeof( vconfigExe ), COPY_ALL_CHARACTERS ); char *argv[] = { vconfigExe, "-allowdebug", NULL }; _spawnv( _P_NOWAIT, vconfigExe, argv ); #elif defined( _X360 ) Msg( "Launching vconfig.exe not supported\n" ); #endif } const char* GetVProjectCmdLineValue() { return CommandLine()->ParmValue( "-vproject", CommandLine()->ParmValue( "-game" ) ); } FSReturnCode_t SetupFileSystemError( bool bRunVConfig, FSReturnCode_t retVal, const char *pMsg, ... ) { va_list marker; va_start( marker, pMsg ); Q_vsnprintf( g_FileSystemError, sizeof( g_FileSystemError ), pMsg, marker ); va_end( marker ); Warning( "%s\n", g_FileSystemError ); // Run vconfig? // Don't do it if they specifically asked for it not to, or if they manually specified a vconfig with -game or -vproject. if ( bRunVConfig && g_FileSystemErrorMode == FS_ERRORMODE_VCONFIG && !CommandLine()->FindParm( CMDLINEOPTION_NOVCONFIG ) && !GetVProjectCmdLineValue() ) { LaunchVConfig(); } if ( g_FileSystemErrorMode == FS_ERRORMODE_AUTO || g_FileSystemErrorMode == FS_ERRORMODE_VCONFIG ) { Error( "%s\n", g_FileSystemError ); } return retVal; } FSReturnCode_t LoadGameInfoFile( const char *pDirectoryName, KeyValues *&pMainFile, KeyValues *&pFileSystemInfo, KeyValues *&pSearchPaths ) { // If GameInfo.txt exists under pBaseDir, then this is their game directory. // All the filesystem mappings will be in this file. char gameinfoFilename[MAX_PATH]; Q_strncpy( gameinfoFilename, pDirectoryName, sizeof( gameinfoFilename ) ); Q_AppendSlash( gameinfoFilename, sizeof( gameinfoFilename ) ); Q_strncat( gameinfoFilename, GAMEINFO_FILENAME, sizeof( gameinfoFilename ), COPY_ALL_CHARACTERS ); Q_FixSlashes( gameinfoFilename ); pMainFile = ReadKeyValuesFile( gameinfoFilename ); if ( IsX360() && !pMainFile ) { // try again Q_strncpy( gameinfoFilename, pDirectoryName, sizeof( gameinfoFilename ) ); Q_AppendSlash( gameinfoFilename, sizeof( gameinfoFilename ) ); Q_strncat( gameinfoFilename, GAMEINFO_FILENAME_ALTERNATE, sizeof( gameinfoFilename ), COPY_ALL_CHARACTERS ); Q_FixSlashes( gameinfoFilename ); pMainFile = ReadKeyValuesFile( gameinfoFilename ); } if ( !pMainFile ) { return SetupFileSystemError( true, FS_MISSING_GAMEINFO_FILE, "%s is missing.", gameinfoFilename ); } pFileSystemInfo = pMainFile->FindKey( "FileSystem" ); if ( !pFileSystemInfo ) { pMainFile->deleteThis(); return SetupFileSystemError( true, FS_INVALID_GAMEINFO_FILE, "%s is not a valid format.", gameinfoFilename ); } // Now read in all the search paths. pSearchPaths = pFileSystemInfo->FindKey( "SearchPaths" ); if ( !pSearchPaths ) { pMainFile->deleteThis(); return SetupFileSystemError( true, FS_INVALID_GAMEINFO_FILE, "%s is not a valid format.", gameinfoFilename ); } return FS_OK; } static void FileSystem_AddLoadedSearchPath( CFSSearchPathsInit &initInfo, const char *pPathID, const char *fullLocationPath, bool bLowViolence ) { // Check for mounting LV game content in LV builds only if ( V_stricmp( pPathID, "game_lv" ) == 0 ) { // Not in LV build, don't mount if ( !initInfo.m_bLowViolence ) return; // Mount, as a game path pPathID = "game"; } // Check for mounting HD game content if enabled if ( V_stricmp( pPathID, "game_hd" ) == 0 ) { // Not in LV build, don't mount if ( !initInfo.m_bMountHDContent ) return; // Mount, as a game path pPathID = "game"; } // Special processing for ordinary game folders if ( V_stristr( fullLocationPath, ".vpk" ) == NULL && Q_stricmp( pPathID, "game" ) == 0 ) { if ( CommandLine()->FindParm( "-tempcontent" ) != 0 ) { char szPath[MAX_PATH]; Q_snprintf( szPath, sizeof(szPath), "%s_tempcontent", fullLocationPath ); initInfo.m_pFileSystem->AddSearchPath( szPath, pPathID, PATH_ADD_TO_TAIL ); } } if ( initInfo.m_pLanguage && Q_stricmp( initInfo.m_pLanguage, "english" ) && V_strstr( fullLocationPath, "_english" ) != NULL ) { char szPath[MAX_PATH]; char szLangString[MAX_PATH]; // Need to add a language version of this path first Q_snprintf( szLangString, sizeof(szLangString), "_%s", initInfo.m_pLanguage); V_StrSubst( fullLocationPath, "_english", szLangString, szPath, sizeof( szPath ), true ); initInfo.m_pFileSystem->AddSearchPath( szPath, pPathID, PATH_ADD_TO_TAIL ); } initInfo.m_pFileSystem->AddSearchPath( fullLocationPath, pPathID, PATH_ADD_TO_TAIL ); } static int SortStricmp( char * const * sz1, char * const * sz2 ) { return V_stricmp( *sz1, *sz2 ); } FSReturnCode_t FileSystem_LoadSearchPaths( CFSSearchPathsInit &initInfo ) { if ( !initInfo.m_pFileSystem || !initInfo.m_pDirectoryName ) return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_LoadSearchPaths: Invalid parameters specified." ); KeyValues *pMainFile, *pFileSystemInfo, *pSearchPaths; FSReturnCode_t retVal = LoadGameInfoFile( initInfo.m_pDirectoryName, pMainFile, pFileSystemInfo, pSearchPaths ); if ( retVal != FS_OK ) return retVal; // All paths except those marked with |gameinfo_path| are relative to the base dir. char baseDir[MAX_PATH]; if ( !FileSystem_GetBaseDir( baseDir, sizeof( baseDir ) ) ) return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetBaseDir failed." ); // The MOD directory is always the one that contains gameinfo.txt Q_strncpy( initInfo.m_ModPath, initInfo.m_pDirectoryName, sizeof( initInfo.m_ModPath ) ); #define GAMEINFOPATH_TOKEN "|gameinfo_path|" #define BASESOURCEPATHS_TOKEN "|all_source_engine_paths|" const char *pszExtraSearchPath = CommandLine()->ParmValue( "-insert_search_path" ); if ( pszExtraSearchPath ) { CUtlStringList vecPaths; V_SplitString( pszExtraSearchPath, ",", vecPaths ); FOR_EACH_VEC( vecPaths, idxExtraPath ) { char szAbsSearchPath[MAX_PATH]; Q_StripPrecedingAndTrailingWhitespace( vecPaths[ idxExtraPath ] ); V_MakeAbsolutePath( szAbsSearchPath, sizeof( szAbsSearchPath ), vecPaths[ idxExtraPath ], baseDir ); V_FixSlashes( szAbsSearchPath ); if ( !V_RemoveDotSlashes( szAbsSearchPath ) ) Error( "Bad -insert_search_path - Can't resolve pathname for '%s'", szAbsSearchPath ); V_StripTrailingSlash( szAbsSearchPath ); FileSystem_AddLoadedSearchPath( initInfo, "GAME", szAbsSearchPath, false ); FileSystem_AddLoadedSearchPath( initInfo, "MOD", szAbsSearchPath, false ); } } bool bLowViolence = initInfo.m_bLowViolence; for ( KeyValues *pCur=pSearchPaths->GetFirstValue(); pCur; pCur=pCur->GetNextValue() ) { const char *pLocation = pCur->GetString(); const char *pszBaseDir = baseDir; if ( Q_stristr( pLocation, GAMEINFOPATH_TOKEN ) == pLocation ) { pLocation += strlen( GAMEINFOPATH_TOKEN ); pszBaseDir = initInfo.m_pDirectoryName; } else if ( Q_stristr( pLocation, BASESOURCEPATHS_TOKEN ) == pLocation ) { // This is a special identifier that tells it to add the specified path for all source engine versions equal to or prior to this version. // So in Orange Box, if they specified: // |all_source_engine_paths|hl2 // it would add the ep2\hl2 folder and the base (ep1-era) hl2 folder. // // We need a special identifier in the gameinfo.txt here because the base hl2 folder exists in different places. // In the case of a game or a Steam-launched dedicated server, all the necessary prior engine content is mapped in with the Steam depots, // so we can just use the path as-is. pLocation += strlen( BASESOURCEPATHS_TOKEN ); } CUtlStringList vecFullLocationPaths; char szAbsSearchPath[MAX_PATH]; V_MakeAbsolutePath( szAbsSearchPath, sizeof( szAbsSearchPath ), pLocation, pszBaseDir ); // Now resolve any ./'s. V_FixSlashes( szAbsSearchPath ); if ( !V_RemoveDotSlashes( szAbsSearchPath ) ) Error( "FileSystem_AddLoadedSearchPath - Can't resolve pathname for '%s'", szAbsSearchPath ); V_StripTrailingSlash( szAbsSearchPath ); // Don't bother doing any wildcard expansion unless it has wildcards. This avoids the weird // thing with xxx_dir.vpk files being referred to simply as xxx.vpk. if ( V_stristr( pLocation, "?") == NULL && V_stristr( pLocation, "*") == NULL ) { vecFullLocationPaths.CopyAndAddToTail( szAbsSearchPath ); } else { FileFindHandle_t findHandle = NULL; const char *pszFoundShortName = initInfo.m_pFileSystem->FindFirst( szAbsSearchPath, &findHandle ); if ( pszFoundShortName ) { do { // We only know how to mount VPK's and directories if ( pszFoundShortName[0] != '.' && ( initInfo.m_pFileSystem->FindIsDirectory( findHandle ) || V_stristr( pszFoundShortName, ".vpk" ) ) ) { char szAbsName[MAX_PATH]; V_ExtractFilePath( szAbsSearchPath, szAbsName, sizeof( szAbsName ) ); V_AppendSlash( szAbsName, sizeof(szAbsName) ); V_strcat_safe( szAbsName, pszFoundShortName ); vecFullLocationPaths.CopyAndAddToTail( szAbsName ); // Check for a common mistake if ( !V_stricmp( pszFoundShortName, "materials" ) || !V_stricmp( pszFoundShortName, "maps" ) || !V_stricmp( pszFoundShortName, "resource" ) || !V_stricmp( pszFoundShortName, "scripts" ) || !V_stricmp( pszFoundShortName, "sound" ) || !V_stricmp( pszFoundShortName, "models" ) ) { char szReadme[MAX_PATH]; V_ExtractFilePath( szAbsSearchPath, szReadme, sizeof( szReadme ) ); V_AppendSlash( szReadme, sizeof(szReadme) ); V_strcat_safe( szReadme, "readme.txt" ); Error( "Tried to add %s as a search path.\n" "\nThis is probably not what you intended.\n" "\nCheck %s for more info\n", szAbsName, szReadme ); } } pszFoundShortName = initInfo.m_pFileSystem->FindNext( findHandle ); } while ( pszFoundShortName ); initInfo.m_pFileSystem->FindClose( findHandle ); } // Sort alphabetically. Also note that this will put // all the xxx_000.vpk packs just before the corresponding // xxx_dir.vpk vecFullLocationPaths.Sort( SortStricmp ); // Now for any _dir.vpk files, remove the _nnn.vpk ones. int idx = vecFullLocationPaths.Count()-1; while ( idx > 0 ) { char szTemp[ MAX_PATH ]; V_strcpy_safe( szTemp, vecFullLocationPaths[ idx ] ); --idx; char *szDirVpk = V_stristr( szTemp, "_dir.vpk" ); if ( szDirVpk != NULL ) { *szDirVpk = '\0'; while ( idx >= 0 ) { char *pszPath = vecFullLocationPaths[ idx ]; if ( V_stristr( pszPath, szTemp ) != pszPath ) break; delete pszPath; vecFullLocationPaths.Remove( idx ); --idx; } } } } // Parse Path ID list CUtlStringList vecPathIDs; V_SplitString( pCur->GetName(), "+", vecPathIDs ); FOR_EACH_VEC( vecPathIDs, idxPathID ) { Q_StripPrecedingAndTrailingWhitespace( vecPathIDs[ idxPathID ] ); } // Mount them. FOR_EACH_VEC( vecFullLocationPaths, idxLocation ) { FOR_EACH_VEC( vecPathIDs, idxPathID ) { FileSystem_AddLoadedSearchPath( initInfo, vecPathIDs[ idxPathID ], vecFullLocationPaths[ idxLocation ], bLowViolence ); } } } pMainFile->deleteThis(); // Also, mark specific path IDs as "by request only". That way, we won't waste time searching in them // when people forget to specify a search path. initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "executable_path", true ); initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "gamebin", true ); initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "download", true ); initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "mod", true ); initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "game_write", true ); initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "mod_write", true ); #ifdef _DEBUG // initInfo.m_pFileSystem->PrintSearchPaths(); #endif return FS_OK; } bool DoesFileExistIn( const char *pDirectoryName, const char *pFilename ) { char filename[MAX_PATH]; Q_strncpy( filename, pDirectoryName, sizeof( filename ) ); Q_AppendSlash( filename, sizeof( filename ) ); Q_strncat( filename, pFilename, sizeof( filename ), COPY_ALL_CHARACTERS ); Q_FixSlashes( filename ); bool bExist = ( _access( filename, 0 ) == 0 ); return ( bExist ); } namespace { SuggestGameInfoDirFn_t & GetSuggestGameInfoDirFn( void ) { static SuggestGameInfoDirFn_t s_pfnSuggestGameInfoDir = NULL; return s_pfnSuggestGameInfoDir; } }; // `anonymous` namespace SuggestGameInfoDirFn_t SetSuggestGameInfoDirFn( SuggestGameInfoDirFn_t pfnNewFn ) { SuggestGameInfoDirFn_t &rfn = GetSuggestGameInfoDirFn(); SuggestGameInfoDirFn_t pfnOldFn = rfn; rfn = pfnNewFn; return pfnOldFn; } static FSReturnCode_t TryLocateGameInfoFile( char *pOutDir, int outDirLen, bool bBubbleDir ) { // Retain a copy of suggested path for further attempts CArrayAutoPtr < char > spchCopyNameBuffer( new char [ outDirLen ] ); Q_strncpy( spchCopyNameBuffer.Get(), pOutDir, outDirLen ); spchCopyNameBuffer[ outDirLen - 1 ] = 0; // Make appropriate slashes ('/' - Linux style) for ( char *pchFix = spchCopyNameBuffer.Get(), *pchEnd = pchFix + outDirLen; pchFix < pchEnd; ++ pchFix ) { if ( '\\' == *pchFix ) { *pchFix = '/'; } } // Have a look in supplied path do { if ( DoesFileExistIn( pOutDir, GAMEINFO_FILENAME ) ) { return FS_OK; } if ( IsX360() && DoesFileExistIn( pOutDir, GAMEINFO_FILENAME_ALTERNATE ) ) { return FS_OK; } } while ( bBubbleDir && Q_StripLastDir( pOutDir, outDirLen ) ); // Make an attempt to resolve from "content -> game" directory Q_strncpy( pOutDir, spchCopyNameBuffer.Get(), outDirLen ); pOutDir[ outDirLen - 1 ] = 0; if ( char *pchContentFix = Q_stristr( pOutDir, "/content/" ) ) { sprintf( pchContentFix, "/game/" ); memmove( pchContentFix + 6, pchContentFix + 9, pOutDir + outDirLen - (pchContentFix + 9) ); // Try in the mapped "game" directory do { if ( DoesFileExistIn( pOutDir, GAMEINFO_FILENAME ) ) { return FS_OK; } if ( IsX360() && DoesFileExistIn( pOutDir, GAMEINFO_FILENAME_ALTERNATE ) ) { return FS_OK; } } while ( bBubbleDir && Q_StripLastDir( pOutDir, outDirLen ) ); } // Could not find it here return FS_MISSING_GAMEINFO_FILE; } FSReturnCode_t LocateGameInfoFile( const CFSSteamSetupInfo &fsInfo, char *pOutDir, int outDirLen ) { // Engine and Hammer don't want to search around for it. if ( fsInfo.m_bOnlyUseDirectoryName ) { if ( !fsInfo.m_pDirectoryName ) return SetupFileSystemError( false, FS_MISSING_GAMEINFO_FILE, "bOnlyUseDirectoryName=1 and pDirectoryName=NULL." ); bool bExists = DoesFileExistIn( fsInfo.m_pDirectoryName, GAMEINFO_FILENAME ); if ( IsX360() && !bExists ) { bExists = DoesFileExistIn( fsInfo.m_pDirectoryName, GAMEINFO_FILENAME_ALTERNATE ); } if ( !bExists ) { if ( IsX360() && CommandLine()->FindParm( "-basedir" ) ) { char basePath[MAX_PATH]; strcpy( basePath, CommandLine()->ParmValue( "-basedir", "" ) ); Q_AppendSlash( basePath, sizeof( basePath ) ); Q_strncat( basePath, fsInfo.m_pDirectoryName, sizeof( basePath ), COPY_ALL_CHARACTERS ); if ( DoesFileExistIn( basePath, GAMEINFO_FILENAME ) ) { Q_strncpy( pOutDir, basePath, outDirLen ); return FS_OK; } if ( IsX360() && DoesFileExistIn( basePath, GAMEINFO_FILENAME_ALTERNATE ) ) { Q_strncpy( pOutDir, basePath, outDirLen ); return FS_OK; } } return SetupFileSystemError( true, FS_MISSING_GAMEINFO_FILE, "Setup file '%s' doesn't exist in subdirectory '%s'.\nCheck your -game parameter or VCONFIG setting.", GAMEINFO_FILENAME, fsInfo.m_pDirectoryName ); } Q_strncpy( pOutDir, fsInfo.m_pDirectoryName, outDirLen ); return FS_OK; } // First, check for overrides on the command line or environment variables. const char *pProject = GetVProjectCmdLineValue(); if ( pProject ) { if ( DoesFileExistIn( pProject, GAMEINFO_FILENAME ) ) { Q_MakeAbsolutePath( pOutDir, outDirLen, pProject ); return FS_OK; } if ( IsX360() && DoesFileExistIn( pProject, GAMEINFO_FILENAME_ALTERNATE ) ) { Q_MakeAbsolutePath( pOutDir, outDirLen, pProject ); return FS_OK; } if ( IsX360() && CommandLine()->FindParm( "-basedir" ) ) { char basePath[MAX_PATH]; strcpy( basePath, CommandLine()->ParmValue( "-basedir", "" ) ); Q_AppendSlash( basePath, sizeof( basePath ) ); Q_strncat( basePath, pProject, sizeof( basePath ), COPY_ALL_CHARACTERS ); if ( DoesFileExistIn( basePath, GAMEINFO_FILENAME ) ) { Q_strncpy( pOutDir, basePath, outDirLen ); return FS_OK; } if ( DoesFileExistIn( basePath, GAMEINFO_FILENAME_ALTERNATE ) ) { Q_strncpy( pOutDir, basePath, outDirLen ); return FS_OK; } } if ( fsInfo.m_bNoGameInfo ) { // fsInfo.m_bNoGameInfo is set by the Steam dedicated server, before it knows which mod to use. // Steam dedicated server doesn't need a gameinfo.txt, because we'll ask which mod to use, even if // -game is supplied on the command line. Q_strncpy( pOutDir, "", outDirLen ); return FS_OK; } else { // They either specified vproject on the command line or it's in their registry. Either way, // we don't want to continue if they've specified it but it's not valid. goto ShowError; } } if ( fsInfo.m_bNoGameInfo ) { Q_strncpy( pOutDir, "", outDirLen ); return FS_OK; } // Ask the application if it can provide us with a game info directory { bool bBubbleDir = true; SuggestGameInfoDirFn_t pfnSuggestGameInfoDirFn = GetSuggestGameInfoDirFn(); if ( pfnSuggestGameInfoDirFn && ( * pfnSuggestGameInfoDirFn )( &fsInfo, pOutDir, outDirLen, &bBubbleDir ) && FS_OK == TryLocateGameInfoFile( pOutDir, outDirLen, bBubbleDir ) ) return FS_OK; } // Try to use the environment variable / registry if ( ( pProject = getenv( GAMEDIR_TOKEN ) ) != NULL && ( Q_MakeAbsolutePath( pOutDir, outDirLen, pProject ), 1 ) && FS_OK == TryLocateGameInfoFile( pOutDir, outDirLen, false ) ) return FS_OK; if ( IsPC() ) { Warning( "Warning: falling back to auto detection of vproject directory.\n" ); // Now look for it in the directory they passed in. if ( fsInfo.m_pDirectoryName ) Q_MakeAbsolutePath( pOutDir, outDirLen, fsInfo.m_pDirectoryName ); else Q_MakeAbsolutePath( pOutDir, outDirLen, "." ); if ( FS_OK == TryLocateGameInfoFile( pOutDir, outDirLen, true ) ) return FS_OK; // Use the CWD Q_getwd( pOutDir, outDirLen ); if ( FS_OK == TryLocateGameInfoFile( pOutDir, outDirLen, true ) ) return FS_OK; } ShowError: return SetupFileSystemError( true, FS_MISSING_GAMEINFO_FILE, "Unable to find %s. Solutions:\n\n" "1. Read http://www.valve-erc.com/srcsdk/faq.html#NoGameDir\n" "2. Run vconfig to specify which game you're working on.\n" "3. Add -game <path> on the command line where <path> is the directory that %s is in.\n", GAMEINFO_FILENAME, GAMEINFO_FILENAME ); } bool DoesPathExistAlready( const char *pPathEnvVar, const char *pTestPath ) { // Fix the slashes in the input arguments. char correctedPathEnvVar[8192], correctedTestPath[MAX_PATH]; Q_strncpy( correctedPathEnvVar, pPathEnvVar, sizeof( correctedPathEnvVar ) ); Q_FixSlashes( correctedPathEnvVar ); pPathEnvVar = correctedPathEnvVar; Q_strncpy( correctedTestPath, pTestPath, sizeof( correctedTestPath ) ); Q_FixSlashes( correctedTestPath ); if ( strlen( correctedTestPath ) > 0 && PATHSEPARATOR( correctedTestPath[strlen(correctedTestPath)-1] ) ) correctedTestPath[ strlen(correctedTestPath) - 1 ] = 0; pTestPath = correctedTestPath; const char *pCurPos = pPathEnvVar; while ( 1 ) { const char *pTestPos = Q_stristr( pCurPos, pTestPath ); if ( !pTestPos ) return false; // Ok, we found pTestPath in the path, but it's only valid if it's followed by an optional slash and a semicolon. pTestPos += strlen( pTestPath ); if ( pTestPos[0] == 0 || pTestPos[0] == ';' || (PATHSEPARATOR( pTestPos[0] ) && pTestPos[1] == ';') ) return true; // Advance our marker.. pCurPos = pTestPos; } } FSReturnCode_t SetSteamInstallPath( char *steamInstallPath, int steamInstallPathLen, CSteamEnvVars &steamEnvVars, bool bErrorsAsWarnings ) { if ( IsConsole() ) { // consoles don't use steam return FS_MISSING_STEAM_DLL; } if ( IsPosix() ) return FS_OK; // under posix the content does not live with steam.dll up the path, rely on the environment already being set by steam // Start at our bin directory and move up until we find a directory with steam.dll in it. char executablePath[MAX_PATH]; if ( !FileSystem_GetExecutableDir( executablePath, sizeof( executablePath ) ) ) { if ( bErrorsAsWarnings ) { Warning( "SetSteamInstallPath: FileSystem_GetExecutableDir failed.\n" ); return FS_INVALID_PARAMETERS; } else { return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetExecutableDir failed." ); } } Q_strncpy( steamInstallPath, executablePath, steamInstallPathLen ); #ifdef WIN32 const char *pchSteamDLL = "steam" DLL_EXT_STRING; #elif defined(POSIX) // under osx the bin lives in the bin/ folder, so step back one Q_StripLastDir( steamInstallPath, steamInstallPathLen ); const char *pchSteamDLL = "libsteam" DLL_EXT_STRING; #else #error #endif while ( 1 ) { // Ignore steamapp.cfg here in case they're debugging. We still need to know the real steam path so we can find their username. // find if ( DoesFileExistIn( steamInstallPath, pchSteamDLL ) && !DoesFileExistIn( steamInstallPath, "steamapp.cfg" ) ) break; if ( !Q_StripLastDir( steamInstallPath, steamInstallPathLen ) ) { if ( bErrorsAsWarnings ) { Warning( "Can't find %s relative to executable path: %s.\n", pchSteamDLL, executablePath ); return FS_MISSING_STEAM_DLL; } else { return SetupFileSystemError( false, FS_MISSING_STEAM_DLL, "Can't find %s relative to executable path: %s.", pchSteamDLL, executablePath ); } } } // Also, add the install path to their PATH environment variable, so filesystem_steam.dll can get to steam.dll. char szPath[ 8192 ]; steamEnvVars.m_Path.GetValue( szPath, sizeof( szPath ) ); if ( !DoesPathExistAlready( szPath, steamInstallPath ) ) { #ifdef WIN32 #define PATH_SEP ";" #else #define PATH_SEP ":" #endif steamEnvVars.m_Path.SetValue( "%s%s%s", szPath, PATH_SEP, steamInstallPath ); } return FS_OK; } FSReturnCode_t GetSteamCfgPath( char *steamCfgPath, int steamCfgPathLen ) { steamCfgPath[0] = 0; char executablePath[MAX_PATH]; if ( !FileSystem_GetExecutableDir( executablePath, sizeof( executablePath ) ) ) { return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetExecutableDir failed." ); } Q_strncpy( steamCfgPath, executablePath, steamCfgPathLen ); while ( 1 ) { if ( DoesFileExistIn( steamCfgPath, "steam.cfg" ) ) break; if ( !Q_StripLastDir( steamCfgPath, steamCfgPathLen) ) { // the file isnt found, thats ok, its not mandatory return FS_OK; } } Q_AppendSlash( steamCfgPath, steamCfgPathLen ); Q_strncat( steamCfgPath, "steam.cfg", steamCfgPathLen, COPY_ALL_CHARACTERS ); return FS_OK; } void SetSteamAppUser( KeyValues *pSteamInfo, const char *steamInstallPath, CSteamEnvVars &steamEnvVars ) { // Always inherit the Steam user if it's already set, since it probably means we (or the // the app that launched us) were launched from Steam. char appUser[MAX_PATH]; if ( steamEnvVars.m_SteamAppUser.GetValue( appUser, sizeof( appUser ) ) ) return; const char *pTempAppUser = NULL; if ( pSteamInfo && (pTempAppUser = pSteamInfo->GetString( "SteamAppUser", NULL )) != NULL ) { Q_strncpy( appUser, pTempAppUser, sizeof( appUser ) ); } else { // They don't have SteamInfo.txt, or it's missing SteamAppUser. Try to figure out the user // by looking in <steam install path>\config\SteamAppData.vdf. char fullFilename[MAX_PATH]; Q_strncpy( fullFilename, steamInstallPath, sizeof( fullFilename ) ); Q_AppendSlash( fullFilename, sizeof( fullFilename ) ); Q_strncat( fullFilename, "config\\SteamAppData.vdf", sizeof( fullFilename ), COPY_ALL_CHARACTERS ); KeyValues *pSteamAppData = ReadKeyValuesFile( fullFilename ); if ( !pSteamAppData || (pTempAppUser = pSteamAppData->GetString( "AutoLoginUser", NULL )) == NULL ) { Error( "Can't find steam app user info." ); } Q_strncpy( appUser, pTempAppUser, sizeof( appUser ) ); pSteamAppData->deleteThis(); } Q_strlower( appUser ); steamEnvVars.m_SteamAppUser.SetValue( "%s", appUser ); } void SetSteamUserPassphrase( KeyValues *pSteamInfo, CSteamEnvVars &steamEnvVars ) { // Always inherit the passphrase if it's already set, since it probably means we (or the // the app that launched us) were launched from Steam. char szPassPhrase[ MAX_PATH ]; if ( steamEnvVars.m_SteamUserPassphrase.GetValue( szPassPhrase, sizeof( szPassPhrase ) ) ) return; // SteamUserPassphrase. const char *pStr; if ( pSteamInfo && (pStr = pSteamInfo->GetString( "SteamUserPassphrase", NULL )) != NULL ) { steamEnvVars.m_SteamUserPassphrase.SetValue( "%s", pStr ); } } FSReturnCode_t SetupSteamStartupEnvironment( KeyValues *pFileSystemInfo, const char *pGameInfoDirectory, CSteamEnvVars &steamEnvVars ) { // Ok, we're going to run Steam. See if they have SteamInfo.txt. If not, we'll try to deduce what we can. char steamInfoFile[MAX_PATH]; Q_strncpy( steamInfoFile, pGameInfoDirectory, sizeof( steamInfoFile ) ); Q_AppendSlash( steamInfoFile, sizeof( steamInfoFile ) ); Q_strncat( steamInfoFile, "steaminfo.txt", sizeof( steamInfoFile ), COPY_ALL_CHARACTERS ); KeyValues *pSteamInfo = ReadKeyValuesFile( steamInfoFile ); char steamInstallPath[MAX_PATH]; FSReturnCode_t ret = SetSteamInstallPath( steamInstallPath, sizeof( steamInstallPath ), steamEnvVars, false ); if ( ret != FS_OK ) return ret; SetSteamAppUser( pSteamInfo, steamInstallPath, steamEnvVars ); SetSteamUserPassphrase( pSteamInfo, steamEnvVars ); if ( pSteamInfo ) pSteamInfo->deleteThis(); return FS_OK; } FSReturnCode_t FileSystem_SetBasePaths( IFileSystem *pFileSystem ) { pFileSystem->RemoveSearchPaths( "EXECUTABLE_PATH" ); char executablePath[MAX_PATH]; if ( !FileSystem_GetExecutableDir( executablePath, sizeof( executablePath ) ) ) return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetExecutableDir failed." ); pFileSystem->AddSearchPath( executablePath, "EXECUTABLE_PATH" ); if ( !FileSystem_GetBaseDir( executablePath, sizeof( executablePath ) ) ) return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetBaseDir failed." ); pFileSystem->AddSearchPath( executablePath, "BASE_PATH" ); return FS_OK; } //----------------------------------------------------------------------------- // Returns the name of the file system DLL to use //----------------------------------------------------------------------------- FSReturnCode_t FileSystem_GetFileSystemDLLName( char *pFileSystemDLL, int nMaxLen, bool &bSteam ) { bSteam = false; // Inside of here, we don't have a filesystem yet, so we have to assume that the filesystem_stdio or filesystem_steam // is in this same directory with us. char executablePath[MAX_PATH]; if ( !FileSystem_GetExecutableDir( executablePath, sizeof( executablePath ) ) ) return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetExecutableDir failed." ); // Assume we'll use local files Q_snprintf( pFileSystemDLL, nMaxLen, "%s%cfilesystem_stdio" DLL_EXT_STRING, executablePath, CORRECT_PATH_SEPARATOR ); #if !defined( _X360 ) // Use filsystem_steam if it exists? #if defined( OSX ) || defined( LINUX ) struct stat statBuf; #endif if ( #if defined( OSX ) || defined( LINUX ) stat( pFileSystemDLL, &statBuf ) != 0 #else _access( pFileSystemDLL, 0 ) != 0 #endif ) { Q_snprintf( pFileSystemDLL, nMaxLen, "%s%cfilesystem_steam" DLL_EXT_STRING, executablePath, CORRECT_PATH_SEPARATOR ); bSteam = true; } #endif return FS_OK; } //----------------------------------------------------------------------------- // Sets up the steam.dll install path in our PATH env var (so you can then just // LoadLibrary() on filesystem_steam.dll without having to copy steam.dll anywhere special ) //----------------------------------------------------------------------------- FSReturnCode_t FileSystem_SetupSteamInstallPath() { CSteamEnvVars steamEnvVars; char steamInstallPath[MAX_PATH]; FSReturnCode_t ret = SetSteamInstallPath( steamInstallPath, sizeof( steamInstallPath ), steamEnvVars, true ); steamEnvVars.m_Path.SetRestoreOriginalValue( false ); // We want to keep the change to the path going forward. return ret; } //----------------------------------------------------------------------------- // Sets up the steam environment + gets back the gameinfo.txt path //----------------------------------------------------------------------------- FSReturnCode_t FileSystem_SetupSteamEnvironment( CFSSteamSetupInfo &fsInfo ) { // First, locate the directory with gameinfo.txt. FSReturnCode_t ret = LocateGameInfoFile( fsInfo, fsInfo.m_GameInfoPath, sizeof( fsInfo.m_GameInfoPath ) ); if ( ret != FS_OK ) return ret; // This is so that processes spawned by this application will have the same VPROJECT #ifdef WIN32 char pEnvBuf[MAX_PATH+32]; Q_snprintf( pEnvBuf, sizeof(pEnvBuf), "%s=%s", GAMEDIR_TOKEN, fsInfo.m_GameInfoPath ); _putenv( pEnvBuf ); #else setenv( GAMEDIR_TOKEN, fsInfo.m_GameInfoPath, 1 ); #endif CSteamEnvVars steamEnvVars; if ( fsInfo.m_bSteam ) { if ( fsInfo.m_bToolsMode ) { // Now, load gameinfo.txt (to make sure it's there) KeyValues *pMainFile, *pFileSystemInfo, *pSearchPaths; ret = LoadGameInfoFile( fsInfo.m_GameInfoPath, pMainFile, pFileSystemInfo, pSearchPaths ); if ( ret != FS_OK ) return ret; // If filesystem_stdio.dll is missing or -steam is specified, then load filesystem_steam.dll. // There are two command line parameters for Steam: // 1) -steam (runs Steam in remote filesystem mode; requires Steam backend) // 2) -steamlocal (runs Steam in local filesystem mode (all content off HDD) // Setup all the environment variables related to Steam so filesystem_steam.dll knows how to initialize Steam. ret = SetupSteamStartupEnvironment( pFileSystemInfo, fsInfo.m_GameInfoPath, steamEnvVars ); if ( ret != FS_OK ) return ret; steamEnvVars.m_SteamAppId.SetRestoreOriginalValue( false ); // We want to keep the change to the path going forward. // We're done with main file pMainFile->deleteThis(); } else if ( fsInfo.m_bSetSteamDLLPath ) { // This is used by the engine to automatically set the path to their steam.dll when running the engine, // so they can debug it without having to copy steam.dll up into their hl2.exe folder. char steamInstallPath[MAX_PATH]; ret = SetSteamInstallPath( steamInstallPath, sizeof( steamInstallPath ), steamEnvVars, true ); steamEnvVars.m_Path.SetRestoreOriginalValue( false ); // We want to keep the change to the path going forward. } } return FS_OK; } //----------------------------------------------------------------------------- // Loads the file system module //----------------------------------------------------------------------------- FSReturnCode_t FileSystem_LoadFileSystemModule( CFSLoadModuleInfo &fsInfo ) { // First, locate the directory with gameinfo.txt. FSReturnCode_t ret = FileSystem_SetupSteamEnvironment( fsInfo ); if ( ret != FS_OK ) return ret; // Now that the environment is setup, load the filesystem module. if ( !Sys_LoadInterface( fsInfo.m_pFileSystemDLLName, FILESYSTEM_INTERFACE_VERSION, &fsInfo.m_pModule, (void**)&fsInfo.m_pFileSystem ) ) { return SetupFileSystemError( false, FS_UNABLE_TO_INIT, "Can't load %s.", fsInfo.m_pFileSystemDLLName ); } if ( !fsInfo.m_pFileSystem->Connect( fsInfo.m_ConnectFactory ) ) return SetupFileSystemError( false, FS_UNABLE_TO_INIT, "%s IFileSystem::Connect failed.", fsInfo.m_pFileSystemDLLName ); if ( fsInfo.m_pFileSystem->Init() != INIT_OK ) return SetupFileSystemError( false, FS_UNABLE_TO_INIT, "%s IFileSystem::Init failed.", fsInfo.m_pFileSystemDLLName ); return FS_OK; } //----------------------------------------------------------------------------- // Mounds a particular steam cache //----------------------------------------------------------------------------- FSReturnCode_t FileSystem_MountContent( CFSMountContentInfo &mountContentInfo ) { // This part is Steam-only. if ( mountContentInfo.m_pFileSystem->IsSteam() ) { return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "Should not be using filesystem_steam anymore!" ); // // Find out the "extra app id". This is for tools, which want to mount a base app's filesystem // // like HL2, then mount the SDK content (tools materials and models, etc) in addition. // int nExtraAppId = -1; // if ( mountContentInfo.m_bToolsMode ) // { // // !FIXME! Here we need to mount the tools content (VPK's) in some way...? // } // // // Set our working directory temporarily so Steam can remember it. // // This is what Steam strips off absolute filenames like c:\program files\valve\steam\steamapps\username\sourcesdk // // to get to the relative part of the path. // char baseDir[MAX_PATH], oldWorkingDir[MAX_PATH]; // if ( !FileSystem_GetBaseDir( baseDir, sizeof( baseDir ) ) ) // return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetBaseDir failed." ); // // Q_getwd( oldWorkingDir, sizeof( oldWorkingDir ) ); // _chdir( baseDir ); // // // Filesystem_tools needs to add dependencies in here beforehand. // FilesystemMountRetval_t retVal = mountContentInfo.m_pFileSystem->MountSteamContent( nExtraAppId ); // // _chdir( oldWorkingDir ); // // if ( retVal != FILESYSTEM_MOUNT_OK ) // return SetupFileSystemError( true, FS_UNABLE_TO_INIT, "Unable to mount Steam content in the file system" ); } return FileSystem_SetBasePaths( mountContentInfo.m_pFileSystem ); } void FileSystem_SetErrorMode( FSErrorMode_t errorMode ) { g_FileSystemErrorMode = errorMode; } void FileSystem_ClearSteamEnvVars() { CSteamEnvVars envVars; // Change the values and don't restore the originals. envVars.m_SteamAppId.SetValue( "" ); envVars.m_SteamUserPassphrase.SetValue( "" ); envVars.m_SteamAppUser.SetValue( "" ); envVars.SetRestoreOriginalValue_ALL( false ); } //----------------------------------------------------------------------------- // Adds the platform folder to the search path. //----------------------------------------------------------------------------- void FileSystem_AddSearchPath_Platform( IFileSystem *pFileSystem, const char *szGameInfoPath ) { char platform[MAX_PATH]; Q_strncpy( platform, szGameInfoPath, MAX_PATH ); Q_StripTrailingSlash( platform ); Q_strncat( platform, "/../platform", MAX_PATH, MAX_PATH ); pFileSystem->AddSearchPath( platform, "PLATFORM" ); }
0
0.991352
1
0.991352
game-dev
MEDIA
0.4018
game-dev
0.897594
1
0.897594
quiverteam/Engine
3,246
src/game/server/basegrenade_concussion.cpp
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "baseentity.h" #include "basegrenade_shared.h" #include "soundent.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" class CBaseGrenadeConcussion : public CBaseGrenade { DECLARE_DATADESC(); public: DECLARE_CLASS( CBaseGrenadeConcussion, CBaseGrenade ); void Spawn( void ); void Precache( void ); void FallThink(void); void ExplodeConcussion( CBaseEntity *pOther ); protected: static int m_nTrailSprite; }; int CBaseGrenadeConcussion::m_nTrailSprite = 0; LINK_ENTITY_TO_CLASS( npc_concussiongrenade, CBaseGrenadeConcussion ); BEGIN_DATADESC( CBaseGrenadeConcussion ) DEFINE_THINKFUNC( FallThink ), DEFINE_ENTITYFUNC( ExplodeConcussion ), END_DATADESC() void CBaseGrenadeConcussion::FallThink(void) { if (!IsInWorld()) { Remove( ); return; } CSoundEnt::InsertSound ( SOUND_DANGER, GetAbsOrigin() + GetAbsVelocity() * 0.5, GetAbsVelocity().Length( ), 0.2 ); SetNextThink( gpGlobals->curtime + random->RandomFloat(0.05, 0.1) ); if (GetWaterLevel() != 0) { SetAbsVelocity( GetAbsVelocity() * 0.5 ); } Vector pos = GetAbsOrigin() + Vector(random->RandomFloat(-4, 4), random->RandomFloat(-4, 4), random->RandomFloat(-4, 4)); CPVSFilter filter( GetAbsOrigin() ); te->Sprite( filter, 0.0, &pos, m_nTrailSprite, random->RandomFloat(0.5, 0.8), 200 ); } // // Contact grenade, explode when it touches something // void CBaseGrenadeConcussion::ExplodeConcussion( CBaseEntity *pOther ) { trace_t tr; Vector vecSpot;// trace starts here! Vector velDir = GetAbsVelocity(); VectorNormalize( velDir ); vecSpot = GetAbsOrigin() - velDir * 32; UTIL_TraceLine( vecSpot, vecSpot + velDir * 64, MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr ); Explode( &tr, DMG_BLAST ); } void CBaseGrenadeConcussion::Spawn( void ) { // point sized, solid, bouncing SetMoveType( MOVETYPE_FLYGRAVITY, MOVECOLLIDE_FLY_BOUNCE ); SetSolid( SOLID_BBOX ); SetCollisionGroup( COLLISION_GROUP_PROJECTILE ); SetModel( "models/weapons/w_grenade.mdl" ); // BUG: wrong model UTIL_SetSize(this, vec3_origin, vec3_origin); // contact grenades arc lower SetGravity( UTIL_ScaleForGravity( 400 ) ); // use a lower gravity for grenades to make them easier to see QAngle angles; VectorAngles(GetAbsVelocity(), angles ); SetLocalAngles( angles ); m_nRenderFX = kRenderFxGlowShell; SetRenderColor( 200, 200, 20, 255 ); // make NPCs afaid of it while in the air SetThink( &CBaseGrenadeConcussion::FallThink ); SetNextThink( gpGlobals->curtime ); // Tumble in air QAngle vecAngVel( random->RandomFloat ( -100, -500 ), 0, 0 ); SetLocalAngularVelocity( vecAngVel ); // Explode on contact SetTouch( &CBaseGrenadeConcussion::ExplodeConcussion ); m_flDamage = 80; // Allow player to blow this puppy up in the air m_takedamage = DAMAGE_YES; } void CBaseGrenadeConcussion::Precache( void ) { BaseClass::Precache( ); PrecacheModel("models/weapons/w_grenade.mdl"); m_nTrailSprite = PrecacheModel("sprites/twinkle01.vmt"); }
0
0.965061
1
0.965061
game-dev
MEDIA
0.959947
game-dev
0.877275
1
0.877275
oracle/oci-java-sdk
5,290
bmc-common/src/main/java/com/oracle/bmc/model/RegionSchema.java
/** * Copyright (c) 2016, 2025, Oracle and/or its affiliates. All rights reserved. * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. */ package com.oracle.bmc.model; /** Class representing RegionSchema blob that can be used for parsing out region info details. */ public final class RegionSchema { private final String realmKey; private final String realmDomainComponent; private final String regionKey; private final String regionIdentifier; /** check if region schema is valid * */ public static boolean isValid(final RegionSchema regionSchema) { if (regionSchema.getRealmKey() == null || regionSchema.getRealmDomainComponent() == null || regionSchema.getRegionIdentifier() == null || regionSchema.getRegionKey() == null) { return false; } if (regionSchema.getRealmKey() != null && regionSchema.getRealmKey().isEmpty()) { return false; } if (regionSchema.getRegionIdentifier() != null && regionSchema.getRegionIdentifier().isEmpty()) { return false; } if (regionSchema.getRealmDomainComponent() != null && regionSchema.getRealmDomainComponent().isEmpty()) { return false; } if (regionSchema.getRegionKey() != null && regionSchema.getRegionKey().isEmpty()) { return false; } return true; } @java.beans.ConstructorProperties({ "realmKey", "realmDomainComponent", "regionKey", "regionIdentifier" }) public RegionSchema( final String realmKey, final String realmDomainComponent, final String regionKey, final String regionIdentifier) { this.realmKey = realmKey; this.realmDomainComponent = realmDomainComponent; this.regionKey = regionKey; this.regionIdentifier = regionIdentifier; } public String getRealmKey() { return this.realmKey; } public String getRealmDomainComponent() { return this.realmDomainComponent; } public String getRegionKey() { return this.regionKey; } public String getRegionIdentifier() { return this.regionIdentifier; } @java.lang.Override public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof RegionSchema)) return false; final RegionSchema other = (RegionSchema) o; final java.lang.Object this$realmKey = this.getRealmKey(); final java.lang.Object other$realmKey = other.getRealmKey(); if (this$realmKey == null ? other$realmKey != null : !this$realmKey.equals(other$realmKey)) return false; final java.lang.Object this$realmDomainComponent = this.getRealmDomainComponent(); final java.lang.Object other$realmDomainComponent = other.getRealmDomainComponent(); if (this$realmDomainComponent == null ? other$realmDomainComponent != null : !this$realmDomainComponent.equals(other$realmDomainComponent)) return false; final java.lang.Object this$regionKey = this.getRegionKey(); final java.lang.Object other$regionKey = other.getRegionKey(); if (this$regionKey == null ? other$regionKey != null : !this$regionKey.equals(other$regionKey)) return false; final java.lang.Object this$regionIdentifier = this.getRegionIdentifier(); final java.lang.Object other$regionIdentifier = other.getRegionIdentifier(); if (this$regionIdentifier == null ? other$regionIdentifier != null : !this$regionIdentifier.equals(other$regionIdentifier)) return false; return true; } @java.lang.Override public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $realmKey = this.getRealmKey(); result = result * PRIME + ($realmKey == null ? 43 : $realmKey.hashCode()); final java.lang.Object $realmDomainComponent = this.getRealmDomainComponent(); result = result * PRIME + ($realmDomainComponent == null ? 43 : $realmDomainComponent.hashCode()); final java.lang.Object $regionKey = this.getRegionKey(); result = result * PRIME + ($regionKey == null ? 43 : $regionKey.hashCode()); final java.lang.Object $regionIdentifier = this.getRegionIdentifier(); result = result * PRIME + ($regionIdentifier == null ? 43 : $regionIdentifier.hashCode()); return result; } @java.lang.Override public java.lang.String toString() { return "RegionSchema(realmKey=" + this.getRealmKey() + ", realmDomainComponent=" + this.getRealmDomainComponent() + ", regionKey=" + this.getRegionKey() + ", regionIdentifier=" + this.getRegionIdentifier() + ")"; } }
0
0.791565
1
0.791565
game-dev
MEDIA
0.32886
game-dev
0.937708
1
0.937708
OpenGATE/Gate
6,317
source/geometry/src/GateTrapMessenger.cc
/*---------------------- Copyright (C): OpenGATE Collaboration This software is distributed under the terms of the GNU Lesser General Public Licence (LGPL) See LICENSE.md for further details ----------------------*/ #include "GateTrapMessenger.hh" #include "G4UIdirectory.hh" #include "G4UIcmdWithAString.hh" #include "G4UIcmdWithAnInteger.hh" #include "G4UIcmdWithADoubleAndUnit.hh" #include "G4UIcmdWith3VectorAndUnit.hh" #include "G4UIcmdWithoutParameter.hh" #include "GateTrap.hh" class GateVolumeMessenger; //---------------------------------------------------------------------------------------------------------- GateTrapMessenger::GateTrapMessenger(GateTrap *itsCreator) :GateVolumeMessenger(itsCreator) { G4String cmdName; cmdName = GetDirectoryName()+"geometry/setDz"; TrapDzCmd = new G4UIcmdWithADoubleAndUnit(cmdName.c_str(),this); TrapDzCmd->SetGuidance("Set Dz of Trap."); TrapDzCmd->SetParameterName("Dz",false); TrapDzCmd->SetRange("Dz>0."); TrapDzCmd->SetUnitCategory("Length"); cmdName = GetDirectoryName()+"geometry/setTheta"; TrapThetaCmd = new G4UIcmdWithADoubleAndUnit(cmdName.c_str(),this); TrapThetaCmd->SetGuidance("Set Theta of Trap."); TrapThetaCmd->SetParameterName("Theta",false); TrapThetaCmd->SetUnitCategory("Angle"); cmdName = GetDirectoryName()+"geometry/setPhi"; TrapPhiCmd = new G4UIcmdWithADoubleAndUnit(cmdName.c_str(),this); TrapPhiCmd->SetGuidance("Set Phi of Trap."); TrapPhiCmd->SetParameterName("Phi",false); TrapPhiCmd->SetUnitCategory("Angle"); cmdName = GetDirectoryName()+"geometry/setDy1"; TrapDy1Cmd = new G4UIcmdWithADoubleAndUnit(cmdName.c_str(),this); TrapDy1Cmd->SetGuidance("Set Dy1 of Trap."); TrapDy1Cmd->SetParameterName("Dy1",false); TrapDy1Cmd->SetRange("Dy1>0."); TrapDy1Cmd->SetUnitCategory("Length"); cmdName = GetDirectoryName()+"geometry/setDx1"; TrapDx1Cmd = new G4UIcmdWithADoubleAndUnit(cmdName.c_str(),this); TrapDx1Cmd->SetGuidance("Set Dx1 of Trap."); TrapDx1Cmd->SetParameterName("Dx1",false); TrapDx1Cmd->SetRange("Dx1>0."); TrapDx1Cmd->SetUnitCategory("Length"); cmdName = GetDirectoryName()+"geometry/setDx2"; TrapDx2Cmd = new G4UIcmdWithADoubleAndUnit(cmdName.c_str(),this); TrapDx2Cmd->SetGuidance("Set Dx2 of Trap."); TrapDx2Cmd->SetParameterName("Dx2",false); TrapDx2Cmd->SetRange("Dx2>0."); TrapDx2Cmd->SetUnitCategory("Length"); cmdName = GetDirectoryName()+"geometry/setAlp1"; TrapAlp1Cmd = new G4UIcmdWithADoubleAndUnit(cmdName.c_str(),this); TrapAlp1Cmd->SetGuidance("Set Alp1 of Trap."); TrapAlp1Cmd->SetParameterName("Alp1",false); TrapAlp1Cmd->SetUnitCategory("Angle"); cmdName = GetDirectoryName()+"geometry/setDy2"; TrapDy2Cmd = new G4UIcmdWithADoubleAndUnit(cmdName.c_str(),this); TrapDy2Cmd->SetGuidance("Set Dy2 of Trap."); TrapDy2Cmd->SetParameterName("Dy2",false); TrapDy2Cmd->SetRange("Dy2>0."); TrapDy2Cmd->SetUnitCategory("Length"); cmdName = GetDirectoryName()+"geometry/setDx3"; TrapDx3Cmd = new G4UIcmdWithADoubleAndUnit(cmdName.c_str(),this); TrapDx3Cmd->SetGuidance("Set Dx3 of Trap."); TrapDx3Cmd->SetParameterName("Dx3",false); TrapDx3Cmd->SetRange("Dx3>0."); TrapDx3Cmd->SetUnitCategory("Length"); cmdName = GetDirectoryName()+"geometry/setDx4"; TrapDx4Cmd = new G4UIcmdWithADoubleAndUnit(cmdName.c_str(),this); TrapDx4Cmd->SetGuidance("Set Dx4 of Trap."); TrapDx4Cmd->SetParameterName("Dx4",false); TrapDx4Cmd->SetRange("Dx4>0."); TrapDx4Cmd->SetUnitCategory("Length"); cmdName = GetDirectoryName()+"geometry/setAlp2"; TrapAlp2Cmd = new G4UIcmdWithADoubleAndUnit(cmdName.c_str(),this); TrapAlp2Cmd->SetGuidance("Set Alp2 of Trap."); TrapAlp2Cmd->SetParameterName("Alp2",false); TrapAlp2Cmd->SetUnitCategory("Angle"); } //---------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------- GateTrapMessenger::~GateTrapMessenger() { delete TrapDzCmd; delete TrapThetaCmd; delete TrapPhiCmd; delete TrapDy1Cmd; delete TrapDx1Cmd; delete TrapDx2Cmd; delete TrapAlp1Cmd; delete TrapDy2Cmd; delete TrapDx3Cmd; delete TrapDx4Cmd; delete TrapAlp2Cmd; } //---------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------- void GateTrapMessenger::SetNewValue(G4UIcommand* command,G4String newValue) { if( command == TrapDzCmd ) { GetTrapCreator()->SetTrapDz(TrapDzCmd->GetNewDoubleValue(newValue)); /*TellGeometryToRebuild();*/} else if( command==TrapThetaCmd ) { GetTrapCreator()->SetTrapTheta(TrapThetaCmd->GetNewDoubleValue(newValue)); /*TellGeometryToRebuild();*/} else if( command==TrapPhiCmd ) { GetTrapCreator()->SetTrapPhi(TrapPhiCmd->GetNewDoubleValue(newValue)); /*TellGeometryToRebuild();*/} else if( command==TrapDy1Cmd ) { GetTrapCreator()->SetTrapDy1(TrapDy1Cmd->GetNewDoubleValue(newValue)); /*TellGeometryToRebuild();*/} else if( command==TrapDx1Cmd ) { GetTrapCreator()->SetTrapDx1(TrapDx1Cmd->GetNewDoubleValue(newValue)); /*TellGeometryToRebuild();*/} else if( command==TrapDx2Cmd ) { GetTrapCreator()->SetTrapDx2(TrapDx2Cmd->GetNewDoubleValue(newValue)); /*TellGeometryToRebuild();*/} else if( command==TrapAlp1Cmd ) { GetTrapCreator()->SetTrapAlp1(TrapAlp1Cmd->GetNewDoubleValue(newValue)); /*TellGeometryToRebuild();*/} else if( command==TrapDy2Cmd ) { GetTrapCreator()->SetTrapDy2(TrapDy2Cmd->GetNewDoubleValue(newValue)); /*TellGeometryToRebuild();*/} else if( command==TrapDx3Cmd ) { GetTrapCreator()->SetTrapDx3(TrapDx3Cmd->GetNewDoubleValue(newValue)); /*TellGeometryToRebuild();*/} else if( command==TrapDx4Cmd ) { GetTrapCreator()->SetTrapDx4(TrapDx4Cmd->GetNewDoubleValue(newValue)); /*TellGeometryToRebuild();*/} else if( command==TrapAlp2Cmd ) { GetTrapCreator()->SetTrapAlp2(TrapAlp2Cmd->GetNewDoubleValue(newValue)); /*TellGeometryToRebuild();*/} else GateVolumeMessenger::SetNewValue(command,newValue); } //----------------------------------------------------------------------------------------------------------
0
0.793427
1
0.793427
game-dev
MEDIA
0.381567
game-dev
0.935535
1
0.935535
PunishXIV/WrathCombo
16,291
WrathCombo/Combos/PvE/MNK/MNK.cs
using WrathCombo.Core; using WrathCombo.CustomComboNS; using static WrathCombo.Combos.PvE.MNK.Config; namespace WrathCombo.Combos.PvE; internal partial class MNK : Melee { internal class MNK_ST_SimpleMode : CustomCombo { protected internal override Preset Preset => Preset.MNK_ST_SimpleMode; protected override uint Invoke(uint actionID) { if (actionID is not (Bootshine or LeapingOpo)) return actionID; if (UseMeditationST()) return OriginalHook(SteeledMeditation); if (UseFormshift()) return FormShift; if (ContentSpecificActions.TryGet(out uint contentAction)) return contentAction; // OGCDs if (CanWeave() && InCombat()) { if (UseBrotherhood()) return Brotherhood; if (UseRoF()) return RiddleOfFire; if (UsePerfectBalanceST()) return PerfectBalance; if (UseRoW()) return RiddleOfWind; if (UseChakraST()) return OriginalHook(SteeledMeditation); if (Role.CanSecondWind(25)) return Role.SecondWind; if (Role.CanBloodBath(40)) return Role.Bloodbath; } // GCDs if (HasStatusEffect(Buffs.FormlessFist)) return OpoOpo is 0 ? DragonKick : OriginalHook(Bootshine); // Masterful Blitz if (UseMasterfulBlitz()) return OriginalHook(MasterfulBlitz); if (UseWindsReply()) return WindsReply; if (UseFiresReply()) return FiresReply; // Perfect Balance or Standard Beast Chakras return DoPerfectBalanceComboST(ref actionID) ? actionID : DetermineCoreAbility(actionID, true); } } internal class MNK_AOE_SimpleMode : CustomCombo { protected internal override Preset Preset => Preset.MNK_AOE_SimpleMode; protected override uint Invoke(uint actionID) { if (actionID is not (ArmOfTheDestroyer or ShadowOfTheDestroyer)) return actionID; if (UseMeditationAoE()) return OriginalHook(InspiritedMeditation); if (UseFormshift()) return FormShift; if (ContentSpecificActions.TryGet(out uint contentAction)) return contentAction; // OGCD's if (CanWeave() && InCombat()) { if (UseBrotherhood()) return Brotherhood; if (UseRoF()) return RiddleOfFire; if (UsePerfectBalanceAoE()) return PerfectBalance; if (UseRoW()) return RiddleOfWind; if (UseChakraAoE()) return OriginalHook(InspiritedMeditation); if (Role.CanSecondWind(25)) return Role.SecondWind; if (Role.CanBloodBath(40)) return Role.Bloodbath; } // Masterful Blitz if (UseMasterfulBlitz()) return OriginalHook(MasterfulBlitz); if (HasStatusEffect(Buffs.FiresRumination) && !HasStatusEffect(Buffs.PerfectBalance) && !HasStatusEffect(Buffs.FormlessFist) && !JustUsed(RiddleOfFire, 4)) return FiresReply; if (HasStatusEffect(Buffs.WindsRumination) && !HasStatusEffect(Buffs.PerfectBalance) && (GetCooldownRemainingTime(RiddleOfFire) > 5 || HasStatusEffect(Buffs.RiddleOfFire))) return WindsReply; // Perfect Balance if (DoPerfectBalanceComboAoE(ref actionID)) return actionID; // Monk Rotation if (HasStatusEffect(Buffs.OpoOpoForm)) return OriginalHook(ArmOfTheDestroyer); if (HasStatusEffect(Buffs.RaptorForm)) { if (LevelChecked(FourPointFury)) return FourPointFury; if (LevelChecked(TwinSnakes)) return TwinSnakes; } if (HasStatusEffect(Buffs.CoeurlForm) && LevelChecked(Rockbreaker)) return Rockbreaker; return actionID; } } internal class MNK_ST_AdvancedMode : CustomCombo { protected internal override Preset Preset => Preset.MNK_ST_AdvancedMode; protected override uint Invoke(uint actionID) { if (actionID is not (Bootshine or LeapingOpo)) return actionID; if (IsEnabled(Preset.MNK_STUseOpener) && Opener().FullOpener(ref actionID)) return Opener().OpenerStep >= 9 && CanWeave() && Chakra >= 5 ? TheForbiddenChakra : actionID; if (IsEnabled(Preset.MNK_STUseMeditation) && UseMeditationST()) return OriginalHook(SteeledMeditation); if (IsEnabled(Preset.MNK_STUseFormShift) && UseFormshift()) return FormShift; if (ContentSpecificActions.TryGet(out uint contentAction)) return contentAction; // OGCDs if (CanWeave() && M6SReady && InCombat()) { if (IsEnabled(Preset.MNK_STUseBuffs)) { if (IsEnabled(Preset.MNK_STUseBrotherhood) && UseBrotherhood() && (MNK_ST_BrotherhoodBossOption == 0 || InBossEncounter())) return Brotherhood; if (IsEnabled(Preset.MNK_STUseROF) && UseRoF() && (MNK_ST_RiddleOfFireBossOption == 0 || InBossEncounter())) return RiddleOfFire; } if (IsEnabled(Preset.MNK_STUsePerfectBalance) && UsePerfectBalanceST()) return PerfectBalance; if (IsEnabled(Preset.MNK_STUseBuffs) && IsEnabled(Preset.MNK_STUseROW) && UseRoW() && (MNK_ST_RiddleOfWindBossOption == 0 || InBossEncounter())) return RiddleOfWind; if (IsEnabled(Preset.MNK_STUseTheForbiddenChakra) && UseChakraST()) return OriginalHook(SteeledMeditation); if (IsEnabled(Preset.MNK_ST_Feint) && Role.CanFeint() && RaidWideCasting()) return Role.Feint; if (IsEnabled(Preset.MNK_ST_UseRoE) && (UseRoE() || MNK_ST_EarthsReply && UseEarthsReply())) return OriginalHook(RiddleOfEarth); if (IsEnabled(Preset.MNK_ST_UseMantra) && UseMantra()) return Mantra; if (IsEnabled(Preset.MNK_ST_ComboHeals)) { if (Role.CanSecondWind(MNK_ST_SecondWindHPThreshold)) return Role.SecondWind; if (Role.CanBloodBath(MNK_ST_BloodbathHPThreshold)) return Role.Bloodbath; } if (IsEnabled(Preset.MNK_ST_StunInterupt) && RoleActions.Melee.CanLegSweep()) return Role.LegSweep; } // GCDs if (HasStatusEffect(Buffs.FormlessFist)) return OpoOpo is 0 ? DragonKick : OriginalHook(Bootshine); // Masterful Blitz if (IsEnabled(Preset.MNK_STUseMasterfulBlitz) && UseMasterfulBlitz()) return OriginalHook(MasterfulBlitz); if (IsEnabled(Preset.MNK_STUseBuffs)) { if (IsEnabled(Preset.MNK_STUseWindsReply) && UseWindsReply()) return WindsReply; if (IsEnabled(Preset.MNK_STUseFiresReply) && UseFiresReply()) return FiresReply; } // Perfect Balance or Standard Beast Chakras return DoPerfectBalanceComboST(ref actionID) ? actionID : DetermineCoreAbility(actionID, IsEnabled(Preset.MNK_STUseTrueNorth)); } } internal class MNK_AOE_AdvancedMode : CustomCombo { protected internal override Preset Preset => Preset.MNK_AOE_AdvancedMode; protected override uint Invoke(uint actionID) { if (actionID is not (ArmOfTheDestroyer or ShadowOfTheDestroyer)) return actionID; if (IsEnabled(Preset.MNK_AoEUseMeditation) && UseMeditationAoE()) return OriginalHook(InspiritedMeditation); if (IsEnabled(Preset.MNK_AoEUseFormShift) && UseFormshift()) return FormShift; if (ContentSpecificActions.TryGet(out uint contentAction)) return contentAction; // OGCD's if (CanWeave() && M6SReady && InCombat()) { if (IsEnabled(Preset.MNK_AoEUseBuffs)) { if (IsEnabled(Preset.MNK_AoEUseBrotherhood) && UseBrotherhood() && GetTargetHPPercent() >= MNK_AoE_BrotherhoodHPThreshold) return Brotherhood; if (IsEnabled(Preset.MNK_AoEUseROF) && UseRoF() && GetTargetHPPercent() >= MNK_AoE_RiddleOfFireHPTreshold) return RiddleOfFire; } if (IsEnabled(Preset.MNK_AoEUsePerfectBalance) && UsePerfectBalanceAoE()) return PerfectBalance; if (IsEnabled(Preset.MNK_AoEUseBuffs) && IsEnabled(Preset.MNK_AoEUseROW) && UseRoW() && GetTargetHPPercent() >= MNK_AoE_RiddleOfWindHPTreshold) return RiddleOfWind; if (IsEnabled(Preset.MNK_AoEUseHowlingFist) && UseChakraAoE()) return OriginalHook(InspiritedMeditation); if (IsEnabled(Preset.MNK_AoE_ComboHeals)) { if (Role.CanSecondWind(MNK_AoE_SecondWindHPThreshold)) return Role.SecondWind; if (Role.CanBloodBath(MNK_AoE_BloodbathHPThreshold)) return Role.Bloodbath; } if (IsEnabled(Preset.MNK_AoE_StunInterupt) && RoleActions.Melee.CanLegSweep()) return Role.LegSweep; } // Masterful Blitz if (IsEnabled(Preset.MNK_AoEUseMasterfulBlitz) && UseMasterfulBlitz()) return OriginalHook(MasterfulBlitz); if (IsEnabled(Preset.MNK_AoEUseBuffs)) { if (IsEnabled(Preset.MNK_AoEUseFiresReply) && HasStatusEffect(Buffs.FiresRumination) && !HasStatusEffect(Buffs.FormlessFist) && !HasStatusEffect(Buffs.PerfectBalance) && !JustUsed(RiddleOfFire, 4)) return FiresReply; if (IsEnabled(Preset.MNK_AoEUseWindsReply) && HasStatusEffect(Buffs.WindsRumination) && !HasStatusEffect(Buffs.PerfectBalance) && (GetCooldownRemainingTime(RiddleOfFire) > 5 || HasStatusEffect(Buffs.RiddleOfFire))) return WindsReply; } // Perfect Balance if (DoPerfectBalanceComboAoE(ref actionID)) return actionID; // Monk Rotation if (HasStatusEffect(Buffs.OpoOpoForm)) return OriginalHook(ArmOfTheDestroyer); if (HasStatusEffect(Buffs.RaptorForm)) { if (LevelChecked(FourPointFury)) return FourPointFury; if (LevelChecked(TwinSnakes)) return TwinSnakes; } if (HasStatusEffect(Buffs.CoeurlForm) && LevelChecked(Rockbreaker)) return Rockbreaker; return actionID; } } internal class MNK_BeastChakras : CustomCombo { protected internal override Preset Preset => Preset.MNK_ST_BeastChakras; protected override uint Invoke(uint actionID) { if (actionID is not (Bootshine or LeapingOpo or TrueStrike or RisingRaptor or SnapPunch or PouncingCoeurl)) return actionID; if (MNK_BasicCombo[0] && actionID is Bootshine or LeapingOpo) return OpoOpo is 0 && LevelChecked(DragonKick) ? DragonKick : OriginalHook(Bootshine); if (MNK_BasicCombo[1] && actionID is TrueStrike or RisingRaptor) return Raptor is 0 && LevelChecked(TwinSnakes) ? TwinSnakes : OriginalHook(TrueStrike); if (MNK_BasicCombo[2] && actionID is SnapPunch or PouncingCoeurl) return Coeurl is 0 && LevelChecked(Demolish) ? Demolish : OriginalHook(SnapPunch); return actionID; } } internal class MNK_Retarget_Thunderclap : CustomCombo { protected internal override Preset Preset => Preset.MNK_Retarget_Thunderclap; protected override uint Invoke(uint actionID) { if (actionID is not Thunderclap) return actionID; return MNK_Thunderclap_FieldMouseover ? Thunderclap.Retarget(SimpleTarget.UIMouseOverTarget ?? SimpleTarget.ModelMouseOverTarget ?? SimpleTarget.HardTarget, true) : Thunderclap.Retarget(SimpleTarget.UIMouseOverTarget ?? SimpleTarget.HardTarget, true); } } internal class MNK_PerfectBalance : CustomCombo { protected internal override Preset Preset => Preset.MNK_PerfectBalance; protected override uint Invoke(uint actionID) { if (actionID is not PerfectBalance) return actionID; return OriginalHook(MasterfulBlitz) != MasterfulBlitz && LevelChecked(MasterfulBlitz) ? OriginalHook(MasterfulBlitz) : actionID; } } internal class MNK_Brotherhood_Riddle : CustomCombo { protected internal override Preset Preset => Preset.MNK_Brotherhood_Riddle; protected override uint Invoke(uint actionID) { if (actionID is not (Brotherhood or RiddleOfFire)) return actionID; return actionID switch { Brotherhood when MNK_BH_RoF == 0 && ActionReady(RiddleOfFire) && IsOnCooldown(Brotherhood) => OriginalHook(RiddleOfFire), RiddleOfFire when MNK_BH_RoF == 1 && ActionReady(Brotherhood) && IsOnCooldown(RiddleOfFire) => Brotherhood, var _ => actionID }; } } internal class MNK_PerfectBalanceProtection : CustomCombo { protected internal override Preset Preset => Preset.MNK_PerfectBalanceProtection; protected override uint Invoke(uint actionID) { if (actionID is not PerfectBalance) return actionID; return HasStatusEffect(Buffs.PerfectBalance) && LevelChecked(PerfectBalance) ? All.SavageBlade : actionID; } } }
0
0.913522
1
0.913522
game-dev
MEDIA
0.808838
game-dev
0.970432
1
0.970432
cgfarmer4/TheConductor
6,829
TheConductor_Unity/Assets/SteamVR/Extras/SteamVR_TrackedController.cs
//======= Copyright (c) Valve Corporation, All rights reserved. =============== using UnityEngine; using Valve.VR; public struct ClickedEventArgs { public uint controllerIndex; public uint flags; public float padX, padY; } public delegate void ClickedEventHandler(object sender, ClickedEventArgs e); public class SteamVR_TrackedController : MonoBehaviour { public uint controllerIndex; public VRControllerState_t controllerState; public bool triggerPressed = false; public bool steamPressed = false; public bool menuPressed = false; public bool padPressed = false; public bool padTouched = false; public bool gripped = false; public event ClickedEventHandler MenuButtonClicked; public event ClickedEventHandler MenuButtonUnclicked; public event ClickedEventHandler TriggerClicked; public event ClickedEventHandler TriggerUnclicked; public event ClickedEventHandler SteamClicked; public event ClickedEventHandler PadClicked; public event ClickedEventHandler PadUnclicked; public event ClickedEventHandler PadTouched; public event ClickedEventHandler PadUntouched; public event ClickedEventHandler Gripped; public event ClickedEventHandler Ungripped; // Use this for initialization protected virtual void Start() { if (this.GetComponent<SteamVR_TrackedObject>() == null) { gameObject.AddComponent<SteamVR_TrackedObject>(); } if (controllerIndex != 0) { this.GetComponent<SteamVR_TrackedObject>().index = (SteamVR_TrackedObject.EIndex)controllerIndex; if (this.GetComponent<SteamVR_RenderModel>() != null) { this.GetComponent<SteamVR_RenderModel>().index = (SteamVR_TrackedObject.EIndex)controllerIndex; } } else { controllerIndex = (uint)this.GetComponent<SteamVR_TrackedObject>().index; } } public void SetDeviceIndex(int index) { this.controllerIndex = (uint)index; } public virtual void OnTriggerClicked(ClickedEventArgs e) { if (TriggerClicked != null) TriggerClicked(this, e); } public virtual void OnTriggerUnclicked(ClickedEventArgs e) { if (TriggerUnclicked != null) TriggerUnclicked(this, e); } public virtual void OnMenuClicked(ClickedEventArgs e) { if (MenuButtonClicked != null) MenuButtonClicked(this, e); } public virtual void OnMenuUnclicked(ClickedEventArgs e) { if (MenuButtonUnclicked != null) MenuButtonUnclicked(this, e); } public virtual void OnSteamClicked(ClickedEventArgs e) { if (SteamClicked != null) SteamClicked(this, e); } public virtual void OnPadClicked(ClickedEventArgs e) { if (PadClicked != null) PadClicked(this, e); } public virtual void OnPadUnclicked(ClickedEventArgs e) { if (PadUnclicked != null) PadUnclicked(this, e); } public virtual void OnPadTouched(ClickedEventArgs e) { if (PadTouched != null) PadTouched(this, e); } public virtual void OnPadUntouched(ClickedEventArgs e) { if (PadUntouched != null) PadUntouched(this, e); } public virtual void OnGripped(ClickedEventArgs e) { if (Gripped != null) Gripped(this, e); } public virtual void OnUngripped(ClickedEventArgs e) { if (Ungripped != null) Ungripped(this, e); } // Update is called once per frame protected virtual void Update() { var system = OpenVR.System; if (system != null && system.GetControllerState(controllerIndex, ref controllerState, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VRControllerState_t)))) { ulong trigger = controllerState.ulButtonPressed & (1UL << ((int)EVRButtonId.k_EButton_SteamVR_Trigger)); if (trigger > 0L && !triggerPressed) { triggerPressed = true; ClickedEventArgs e; e.controllerIndex = controllerIndex; e.flags = (uint)controllerState.ulButtonPressed; e.padX = controllerState.rAxis0.x; e.padY = controllerState.rAxis0.y; OnTriggerClicked(e); } else if (trigger == 0L && triggerPressed) { triggerPressed = false; ClickedEventArgs e; e.controllerIndex = controllerIndex; e.flags = (uint)controllerState.ulButtonPressed; e.padX = controllerState.rAxis0.x; e.padY = controllerState.rAxis0.y; OnTriggerUnclicked(e); } ulong grip = controllerState.ulButtonPressed & (1UL << ((int)EVRButtonId.k_EButton_Grip)); if (grip > 0L && !gripped) { gripped = true; ClickedEventArgs e; e.controllerIndex = controllerIndex; e.flags = (uint)controllerState.ulButtonPressed; e.padX = controllerState.rAxis0.x; e.padY = controllerState.rAxis0.y; OnGripped(e); } else if (grip == 0L && gripped) { gripped = false; ClickedEventArgs e; e.controllerIndex = controllerIndex; e.flags = (uint)controllerState.ulButtonPressed; e.padX = controllerState.rAxis0.x; e.padY = controllerState.rAxis0.y; OnUngripped(e); } ulong pad = controllerState.ulButtonPressed & (1UL << ((int)EVRButtonId.k_EButton_SteamVR_Touchpad)); if (pad > 0L && !padPressed) { padPressed = true; ClickedEventArgs e; e.controllerIndex = controllerIndex; e.flags = (uint)controllerState.ulButtonPressed; e.padX = controllerState.rAxis0.x; e.padY = controllerState.rAxis0.y; OnPadClicked(e); } else if (pad == 0L && padPressed) { padPressed = false; ClickedEventArgs e; e.controllerIndex = controllerIndex; e.flags = (uint)controllerState.ulButtonPressed; e.padX = controllerState.rAxis0.x; e.padY = controllerState.rAxis0.y; OnPadUnclicked(e); } ulong menu = controllerState.ulButtonPressed & (1UL << ((int)EVRButtonId.k_EButton_ApplicationMenu)); if (menu > 0L && !menuPressed) { menuPressed = true; ClickedEventArgs e; e.controllerIndex = controllerIndex; e.flags = (uint)controllerState.ulButtonPressed; e.padX = controllerState.rAxis0.x; e.padY = controllerState.rAxis0.y; OnMenuClicked(e); } else if (menu == 0L && menuPressed) { menuPressed = false; ClickedEventArgs e; e.controllerIndex = controllerIndex; e.flags = (uint)controllerState.ulButtonPressed; e.padX = controllerState.rAxis0.x; e.padY = controllerState.rAxis0.y; OnMenuUnclicked(e); } pad = controllerState.ulButtonTouched & (1UL << ((int)EVRButtonId.k_EButton_SteamVR_Touchpad)); if (pad > 0L && !padTouched) { padTouched = true; ClickedEventArgs e; e.controllerIndex = controllerIndex; e.flags = (uint)controllerState.ulButtonPressed; e.padX = controllerState.rAxis0.x; e.padY = controllerState.rAxis0.y; OnPadTouched(e); } else if (pad == 0L && padTouched) { padTouched = false; ClickedEventArgs e; e.controllerIndex = controllerIndex; e.flags = (uint)controllerState.ulButtonPressed; e.padX = controllerState.rAxis0.x; e.padY = controllerState.rAxis0.y; OnPadUntouched(e); } } } }
0
0.917586
1
0.917586
game-dev
MEDIA
0.861708
game-dev
0.732038
1
0.732038
OversizedSunCoreDev/Barrage
1,907
Source/JoltPhysics/Jolt/Core/STLTempAllocator.h
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics) // SPDX-FileCopyrightText: 2021 Jorrit Rouwe // SPDX-License-Identifier: MIT #pragma once #include <Jolt/Core/TempAllocator.h> JPH_NAMESPACE_BEGIN /// STL allocator that wraps around TempAllocator template <typename T> class STLTempAllocator { public: using value_type = T; /// Pointer to type using pointer = T *; using const_pointer = const T *; /// Reference to type. /// Can be removed in C++20. using reference = T &; using const_reference = const T &; using size_type = size_t; using difference_type = ptrdiff_t; /// The allocator is not stateless (depends on the temp allocator) using is_always_equal = std::false_type; /// Constructor inline STLTempAllocator(TempAllocator &inAllocator) : mAllocator(inAllocator) { } /// Constructor from other allocator template <typename T2> inline explicit STLTempAllocator(const STLTempAllocator<T2> &inRHS) : mAllocator(inRHS.GetAllocator()) { } /// Allocate memory inline pointer allocate(size_type inN) { return pointer(mAllocator.Allocate(uint(inN * sizeof(value_type)))); } /// Free memory inline void deallocate(pointer inPointer, size_type inN) { mAllocator.Free(inPointer, uint(inN * sizeof(value_type))); } /// Allocators are not-stateless, assume if allocator address matches that the allocators are the same inline bool operator == (const STLTempAllocator<T> &inRHS) const { return &mAllocator == &inRHS.mAllocator; } inline bool operator != (const STLTempAllocator<T> &inRHS) const { return &mAllocator != &inRHS.mAllocator; } /// Converting to allocator for other type template <typename T2> struct rebind { using other = STLTempAllocator<T2>; }; /// Get our temp allocator TempAllocator & GetAllocator() const { return mAllocator; } private: TempAllocator & mAllocator; }; JPH_NAMESPACE_END
0
0.929916
1
0.929916
game-dev
MEDIA
0.530996
game-dev
0.917835
1
0.917835
kaosat-dev/Blenvy
12,990
tools/blenvy/blueprints/blueprints_scan.py
from types import SimpleNamespace import bpy from .blueprint import Blueprint # blueprints: any collection with either # - an instance # - marked as asset # - with the "auto_export" flag # https://blender.stackexchange.com/questions/167878/how-to-get-all-collections-of-the-current-scene def blueprints_scan(level_scenes, library_scenes, settings): blueprints = {} blueprints_from_objects = {} blueprint_name_from_instances = {} collections = [] # level scenes blueprint_instances_per_level_scene = {} internal_collection_instances = {} external_collection_instances = {} # meh def add_object_to_collection_instances(collection_name, object, internal=True): collection_category = internal_collection_instances if internal else external_collection_instances if not collection_name in collection_category.keys(): #print("ADDING INSTANCE OF", collection_name, "object", object.name, "categ", collection_category) collection_category[collection_name] = [] #.append(collection_name) collection_category[collection_name].append(object) for scene in level_scenes:# should it only be level scenes ? what about collection instances inside other scenes ? for object in scene.objects: #print("object", object.name) if object.instance_type == 'COLLECTION': collection = object.instance_collection collection_name = object.instance_collection.name #print(" from collection:", collection_name) collection_from_library = False for library_scene in library_scenes: # should be only in library scenes collection_from_library = library_scene.user_of_id(collection) > 0 # TODO: also check if it is an imported asset if collection_from_library: break add_object_to_collection_instances(collection_name=collection_name, object=object, internal = collection_from_library) # experiment with custom properties from assets stored in other blend files """if not collection_from_library: for property_name in object.keys(): print("stuff", property_name) for property_name in collection.keys(): print("OTHER", property_name)""" # blueprints[collection_name].instances.append(object) # FIXME: this only account for direct instances of blueprints, not for any nested blueprint inside a blueprint if scene.name not in blueprint_instances_per_level_scene.keys(): blueprint_instances_per_level_scene[scene.name] = {} if collection_name not in blueprint_instances_per_level_scene[scene.name].keys(): blueprint_instances_per_level_scene[scene.name][collection_name] = [] blueprint_instances_per_level_scene[scene.name][collection_name].append(object) blueprint_name_from_instances[object] = collection_name """# add any indirect ones # FIXME: needs to be recursive, either here or above for nested_blueprint in blueprints[collection_name].nested_blueprints: if not nested_blueprint in blueprint_instances_per_level_scene[scene.name]: blueprint_instances_per_level_scene[scene.name].append(nested_blueprint)""" for collection in bpy.data.collections: #print("collection", collection, collection.name_full, "users", collection.users) collection_from_library = False defined_in_scene = None for scene in library_scenes: # should be only in library scenes collection_from_library = scene.user_of_id(collection) > 0 if collection_from_library: defined_in_scene = scene break if not collection_from_library: continue if ( 'AutoExport' in collection and collection['AutoExport'] == True # get marked collections or collection.asset_data is not None # or if you have marked collections as assets you can auto export them too or collection.name in list(internal_collection_instances.keys()) # or if the collection has an instance in one of the level scenes ): blueprint = Blueprint(collection.name) blueprint.local = True blueprint.marked = 'AutoExport' in collection and collection['AutoExport'] == True or collection.asset_data is not None blueprint.objects = [object.name for object in collection.all_objects if not object.instance_type == 'COLLECTION'] # inneficient, double loop blueprint.nested_blueprints = [object.instance_collection.name for object in collection.all_objects if object.instance_type == 'COLLECTION'] # FIXME: not precise enough, aka "what is a blueprint" blueprint.collection = collection blueprint.instances = internal_collection_instances[collection.name] if collection.name in internal_collection_instances else [] blueprint.scene = defined_in_scene blueprints[collection.name] = blueprint # add nested collections to internal/external_collection instances # FIXME: inneficient, third loop over all_objects for object in collection.all_objects: if object.instance_type == 'COLLECTION': add_object_to_collection_instances(collection_name=object.instance_collection.name, object=object, internal = blueprint.local) # now create reverse lookup , so you can find the collection from any of its contained objects for object in collection.all_objects: blueprints_from_objects[object.name] = blueprint#collection.name # collections.append(collection) # EXTERNAL COLLECTIONS: add any collection that has an instance in the level scenes, but is not present in any of the scenes (IE NON LOCAL/ EXTERNAL) for collection_name in external_collection_instances: collection = bpy.data.collections[collection_name] blueprint = Blueprint(collection.name) blueprint.local = False blueprint.marked = True #external ones are always marked, as they have to have been marked in their original file #'AutoExport' in collection and collection['AutoExport'] == True blueprint.objects = [object.name for object in collection.all_objects if not object.instance_type == 'COLLECTION'] # inneficient, double loop blueprint.nested_blueprints = [object.instance_collection.name for object in collection.all_objects if object.instance_type == 'COLLECTION'] # FIXME: not precise enough, aka "what is a blueprint" blueprint.collection = collection blueprint.instances = external_collection_instances[collection.name] if collection.name in external_collection_instances else [] blueprints[collection.name] = blueprint #print("EXTERNAL COLLECTION", collection, dict(collection)) # add nested collections to internal/external_collection instances # FIXME: inneficient, third loop over all_objects """for object in collection.all_objects: if object.instance_type == 'COLLECTION': add_object_to_collection_instances(collection_name=object.instance_collection.name, object=object, internal = blueprint.local)""" # now create reverse lookup , so you can find the collection from any of its contained objects for object in collection.all_objects: blueprints_from_objects[object.name] = blueprint#collection.name # then add any nested collections at root level (so we can have a flat list, regardless of nesting) # TODO: do this recursively for blueprint_name in list(blueprints.keys()): parent_blueprint = blueprints[blueprint_name] for nested_blueprint_name in parent_blueprint.nested_blueprints: if not nested_blueprint_name in blueprints.keys(): collection = bpy.data.collections[nested_blueprint_name] blueprint = Blueprint(collection.name) blueprint.local = parent_blueprint.local blueprint.objects = [object.name for object in collection.all_objects if not object.instance_type == 'COLLECTION'] # inneficient, double loop blueprint.nested_blueprints = [object.instance_collection.name for object in collection.all_objects if object.instance_type == 'COLLECTION'] # FIXME: not precise enough, aka "what is a blueprint" blueprint.collection = collection blueprint.instances = external_collection_instances[collection.name] if collection.name in external_collection_instances else [] blueprint.scene = parent_blueprint.scene if parent_blueprint.local else None blueprints[collection.name] = blueprint # now create reverse lookup , so you can find the collection from any of its contained objects for object in collection.all_objects: blueprints_from_objects[object.name] = blueprint#collection.name blueprints = dict(sorted(blueprints.items())) '''print("BLUEPRINTS") for blueprint_name in blueprints: print(" ", blueprints[blueprint_name]) """print("BLUEPRINTS LOOKUP") print(blueprints_from_objects)""" print("BLUEPRINT INSTANCES PER MAIN SCENE") print(blueprint_instances_per_level_scene)''' """changes_test = {'Library': { 'Blueprint1_mesh': bpy.data.objects['Blueprint1_mesh'], 'Fox_mesh': bpy.data.objects['Fox_mesh'], 'External_blueprint2_Cylinder': bpy.data.objects['External_blueprint2_Cylinder']} } # which level scene has been impacted by this # does one of the level scenes contain an INSTANCE of an impacted blueprint for scene in level_scenes: changed_objects = list(changes_test["Library"].keys()) # just a hack for testing #bluprint_instances_in_scene = blueprint_instances_per_level_scene[scene.name] #print("instances per scene", bluprint_instances_in_scene, "changed_objects", changed_objects) changed_blueprints_with_instances_in_scene = [blueprints_from_objects[changed] for changed in changed_objects if changed in blueprints_from_objects] print("changed_blueprints_with_instances_in_scene", changed_blueprints_with_instances_in_scene) level_needs_export = len(changed_blueprints_with_instances_in_scene) > 0 if level_needs_export: print("level needs export", scene.name) for scene in library_scenes: changed_objects = list(changes_test[scene.name].keys()) changed_blueprints = [blueprints_from_objects[changed] for changed in changed_objects if changed in blueprints_from_objects] # we only care about local blueprints/collections changed_local_blueprints = [blueprint_name for blueprint_name in changed_blueprints if blueprint_name in blueprints.keys() and blueprints[blueprint_name].local] print("changed blueprints", changed_local_blueprints)""" # additional helper data structures for lookups etc blueprints_per_name = blueprints blueprints = [] # flat list internal_blueprints = [] external_blueprints = [] blueprints_per_scenes = {} blueprint_instances_per_library_scene = {} for blueprint in blueprints_per_name.values(): blueprints.append(blueprint) if blueprint.local: internal_blueprints.append(blueprint) if blueprint.scene: if not blueprint.scene.name in blueprints_per_scenes: blueprints_per_scenes[blueprint.scene.name] = [] blueprints_per_scenes[blueprint.scene.name].append(blueprint.name) # meh else: external_blueprints.append(blueprint) # we also need to have blueprint instances for data = { "blueprints": blueprints, "blueprints_per_name": blueprints_per_name, "blueprint_names": list(blueprints_per_name.keys()), "blueprints_from_objects": blueprints_from_objects, "internal_blueprints": internal_blueprints, "external_blueprints": external_blueprints, "blueprints_per_scenes": blueprints_per_scenes, "blueprint_instances_per_level_scene": blueprint_instances_per_level_scene, "blueprint_instances_per_library_scene": blueprint_instances_per_library_scene, # not sure about these two "internal_collection_instances": internal_collection_instances, "external_collection_instances": external_collection_instances, "blueprint_name_from_instances": blueprint_name_from_instances } return SimpleNamespace(**data)
0
0.562736
1
0.562736
game-dev
MEDIA
0.489163
game-dev
0.755213
1
0.755213
00-Evan/shattered-pixel-dungeon-gdx
3,261
core/src/com/shatteredpixel/shatteredpixeldungeon/windows/WndChallenges.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.windows; import com.shatteredpixel.shatteredpixeldungeon.Challenges; import com.shatteredpixel.shatteredpixeldungeon.SPDSettings; import com.shatteredpixel.shatteredpixeldungeon.ShatteredPixelDungeon; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene; import com.shatteredpixel.shatteredpixeldungeon.ui.CheckBox; import com.shatteredpixel.shatteredpixeldungeon.ui.IconButton; import com.shatteredpixel.shatteredpixeldungeon.ui.Icons; import com.shatteredpixel.shatteredpixeldungeon.ui.RenderedTextBlock; import com.shatteredpixel.shatteredpixeldungeon.ui.Window; import java.util.ArrayList; public class WndChallenges extends Window { private static final int WIDTH = 120; private static final int TTL_HEIGHT = 18; private static final int BTN_HEIGHT = 18; private static final int GAP = 1; private boolean editable; private ArrayList<CheckBox> boxes; public WndChallenges( int checked, boolean editable ) { super(); this.editable = editable; RenderedTextBlock title = PixelScene.renderTextBlock( Messages.get(this, "title"), 12 ); title.hardlight( TITLE_COLOR ); title.setPos( (WIDTH - title.width()) / 2, (TTL_HEIGHT - title.height()) / 2 ); PixelScene.align(title); add( title ); boxes = new ArrayList<>(); float pos = TTL_HEIGHT; for (int i=0; i < Challenges.NAME_IDS.length; i++) { final String challenge = Challenges.NAME_IDS[i]; CheckBox cb = new CheckBox( Messages.get(Challenges.class, challenge) ); cb.checked( (checked & Challenges.MASKS[i]) != 0 ); cb.active = editable; if (i > 0) { pos += GAP; } cb.setRect( 0, pos, WIDTH-16, BTN_HEIGHT ); add( cb ); boxes.add( cb ); IconButton info = new IconButton(Icons.get(Icons.INFO)){ @Override protected void onClick() { super.onClick(); ShatteredPixelDungeon.scene().add( new WndMessage(Messages.get(Challenges.class, challenge+"_desc")) ); } }; info.setRect(cb.right(), pos, 16, BTN_HEIGHT); add(info); pos = cb.bottom(); } resize( WIDTH, (int)pos ); } @Override public void onBackPressed() { if (editable) { int value = 0; for (int i=0; i < boxes.size(); i++) { if (boxes.get( i ).checked()) { value |= Challenges.MASKS[i]; } } SPDSettings.challenges( value ); } super.onBackPressed(); } }
0
0.875407
1
0.875407
game-dev
MEDIA
0.887663
game-dev
0.942389
1
0.942389
ProjectIgnis/CardScripts
1,586
rush/c160320003.lua
--E・HERO サンダー・ジャイアント --Elemental HERO Thunder Giant (Rush) --Scripted by YoshiDuels local s,id=GetID() function s.initial_effect(c) --Fusion Material c:AddMustBeFusionSummoned() c:EnableReviveLimit() Fusion.AddProcMix(c,true,true,20721928,84327329) --Destroy 1 face-up monster on the field local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCost(s.cost) e1:SetTarget(s.target) e1:SetOperation(s.operation) c:RegisterEffect(e1) end function s.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,nil) end end function s.filter(c,atk) return c:IsMonster() and c:IsFaceup() and c:GetBaseAttack()<atk and not c:IsMaximumModeSide() end function s.target(e,tp,eg,ep,ev,re,r,rp,chk) local dg=Duel.GetMatchingGroup(s.filter,tp,LOCATION_MZONE,LOCATION_MZONE,nil,e:GetHandler():GetAttack()) if chk==0 then return #dg>0 end Duel.SetOperationInfo(0,CATEGORY_DESTROY,dg,1,0,0) end function s.operation(e,tp,eg,ep,ev,re,r,rp) --Requirement Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,1,nil) Duel.SendtoGrave(g,REASON_COST) --Effect local dg=Duel.GetMatchingGroup(s.filter,tp,LOCATION_MZONE,LOCATION_MZONE,nil,e:GetHandler():GetAttack()) if #dg>0 then local sg=dg:Select(tp,1,1,nil) sg=sg:AddMaximumCheck() Duel.HintSelection(sg) Duel.Destroy(sg,REASON_EFFECT) end end
0
0.905565
1
0.905565
game-dev
MEDIA
0.994805
game-dev
0.959893
1
0.959893
D2R-BMBot/D2R-BMBot
27,477
Bots/Chaos.cs
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using static MapAreaStruc; public class Chaos { Form1 Form1_0; //##################################################### //##################################################### //Special Run Variable public bool FastChaos = false; //##################################################### //##################################################### public int CurrentStep = 0; public bool ScriptDone = false; public bool DetectedBoss = false; public Position EntrancePos = new Position { X = 7796, Y = 5561 }; public Position DiabloSpawnPos = new Position { X = 7794, Y = 5294 }; //7800,5286 public Position TPPos = new Position { X = 7760, Y = 5305 }; public Position CurrentSealPos = new Position { X = 0, Y = 0 }; public DateTime StartTimeUniqueBossWaiting = DateTime.Now; public bool TimeSetForWaitingUniqueBoss = false; public int TryCountWaitingUniqueBoss = 0; public int BufferPathFindingMoveSize = 0; public int SealType = 0; public bool MovedToTPPos = false; public bool CastedAtSeis = false; public bool FastChaosPopingSeals = false; public void SetForm1(Form1 form1_1) { Form1_0 = form1_1; } public void ResetVars() { CurrentStep = 0; ScriptDone = false; DetectedBoss = false; TimeSetForWaitingUniqueBoss = false; TryCountWaitingUniqueBoss = 0; StartTimeUniqueBossWaiting = DateTime.Now; MovedToTPPos = false; CastedAtSeis = false; FastChaosPopingSeals = false; } public void DetectCurrentStep() { if ((Enums.Area)Form1_0.PlayerScan_0.levelNo == Enums.Area.RiverOfFlame) CurrentStep = 1; if ((Enums.Area)Form1_0.PlayerScan_0.levelNo == Enums.Area.ChaosSanctuary) CurrentStep = 3; } public void RunScript() { Form1_0.Town_0.ScriptTownAct = 4; //set to town act 4 when running this script if (!Form1_0.Running || !Form1_0.GameStruc_0.IsInGame()) { ScriptDone = true; return; } if (Form1_0.Town_0.GetInTown()) { Form1_0.SetGameStatus("GO TO WP"); CurrentStep = 0; Form1_0.Town_0.GoToWPArea(4, 2); } else { if (CurrentStep == 0) { Form1_0.SetGameStatus("DOING CHAOS"); Form1_0.Battle_0.CastDefense(); //Form1_0.WaitDelay(15); if (Form1_0.PlayerScan_0.levelNo == (int)Enums.Area.RiverOfFlame) { CurrentStep++; } else if (Form1_0.PlayerScan_0.levelNo == (int)Enums.Area.ChaosSanctuary) { CurrentStep = 3; } else { DetectCurrentStep(); if (CurrentStep == 0) { Form1_0.Town_0.FastTowning = false; Form1_0.Town_0.GoToTown(); } } } if (CurrentStep == 1) { //#### if (Form1_0.PlayerScan_0.levelNo == (int)Enums.Area.ChaosSanctuary) { CurrentStep++; return; } //#### //Form1_0.PathFinding_0.MoveToNextArea(Enums.Area.ChaosSanctuary); //Form1_0.PathFinding_0.MoveToThisPos(EntrancePos); //CurrentStep++; Position MidPos = new Position { X = 7800, Y = 5761 }; if (Form1_0.Mover_0.MoveToLocation(MidPos.X, MidPos.Y)) { Form1_0.Town_0.TPSpawned = false; CurrentStep++; } } if (CurrentStep == 2) { //#### if (Form1_0.PlayerScan_0.levelNo == (int)Enums.Area.ChaosSanctuary) { CurrentStep++; return; } //#### if (Form1_0.Mover_0.MoveToLocation(EntrancePos.X, EntrancePos.Y)) { if (Form1_0.PublicGame && !Form1_0.Town_0.TPSpawned) Form1_0.Town_0.SpawnTP(); if (!Form1_0.Town_0.TPSpawned) Form1_0.Battle_0.CastDefense(); Form1_0.Town_0.TPSpawned = false; BufferPathFindingMoveSize = Form1_0.PathFinding_0.AcceptMoveOffset; Form1_0.PathFinding_0.AcceptMoveOffset = 25; //default 15 CurrentStep++; } } if (CurrentStep == 3) { if (Form1_0.PlayerScan_0.levelNo != (int)Enums.Area.ChaosSanctuary) { CurrentStep--; return; } CurrentSealPos = Form1_0.MapAreaStruc_0.GetPositionOfObject("object", "DiabloSeal5", (int)Enums.Area.ChaosSanctuary, new List<int>()); if (Form1_0.PlayerScan_0.xPosFinal >= (CurrentSealPos.X - 5) && Form1_0.PlayerScan_0.xPosFinal <= (CurrentSealPos.X + 5) && Form1_0.PlayerScan_0.yPosFinal >= (CurrentSealPos.Y - 5) && Form1_0.PlayerScan_0.yPosFinal <= (CurrentSealPos.Y + 5)) { int InteractCount = 0; while (InteractCount < 3) { Form1_0.Battle_0.DoBattleScript(5); Form1_0.PathFinding_0.MoveToObject("DiabloSeal5"); Form1_0.WaitDelay(10); InteractCount++; } //###### //KILL VIZIER if (!TimeSetForWaitingUniqueBoss) { StartTimeUniqueBossWaiting = DateTime.Now; TimeSetForWaitingUniqueBoss = true; } if (CurrentSealPos.Y == 5275) SealType = 1; else SealType = 2; if (SealType == 1) Form1_0.PathFinding_0.MoveToThisPos(new Position { X = 7691, Y = 5292 }, 4, true); else Form1_0.PathFinding_0.MoveToThisPos(new Position { X = 7695, Y = 5316 }, 4, true); Form1_0.SetGameStatus("WAITING VIZIER " + (TryCountWaitingUniqueBoss + 1) + "/1"); bool UniqueDetected = Form1_0.MobsStruc_0.GetMobs("getSuperUniqueName", "Grand Vizier of Chaos", false, 200, new List<long>()); while (!UniqueDetected && (DateTime.Now - StartTimeUniqueBossWaiting).TotalSeconds < CharConfig.ChaosWaitingSealBossDelay) { UniqueDetected = Form1_0.MobsStruc_0.GetMobs("getSuperUniqueName", "Grand Vizier of Chaos", false, 200, new List<long>()); Form1_0.PlayerScan_0.GetPositions(); Form1_0.overlayForm.UpdateOverlay(); Form1_0.GameStruc_0.CheckChickenGameTime(); Form1_0.ItemsStruc_0.GetItems(true); Form1_0.Potions_0.CheckIfWeUsePotion(); Form1_0.Battle_0.DoBattleScript(10); //### Form1_0.Battle_0.SetSkills(); Form1_0.Battle_0.CastSkillsNoMove(); //### Application.DoEvents(); } if (!UniqueDetected) { TimeSetForWaitingUniqueBoss = false; CurrentStep++; } else { Form1_0.SetGameStatus("KILLING VIZIER"); if (Form1_0.MobsStruc_0.GetMobs("getSuperUniqueName", "Grand Vizier of Chaos", false, 200, new List<long>())) { if (Form1_0.MobsStruc_0.MobsHP > 0) { Form1_0.Battle_0.RunBattleScriptOnThisMob("getSuperUniqueName", "Grand Vizier of Chaos", new List<long>()); } else { TimeSetForWaitingUniqueBoss = false; CurrentStep++; } } else { TimeSetForWaitingUniqueBoss = false; CurrentStep++; } } } else { if (Form1_0.PlayerScan_0.xPosFinal >= (TPPos.X - 5) && Form1_0.PlayerScan_0.xPosFinal <= (TPPos.X + 5) && Form1_0.PlayerScan_0.yPosFinal >= (TPPos.Y - 5) && Form1_0.PlayerScan_0.yPosFinal <= (TPPos.Y + 5)) { if (Form1_0.PublicGame && !Form1_0.Town_0.TPSpawned) Form1_0.Town_0.SpawnTP(); if (!FastChaos && !FastChaosPopingSeals) Form1_0.Battle_0.CastDefense(); Form1_0.InventoryStruc_0.DumpBadItemsOnGround(); MovedToTPPos = true; Form1_0.PathFinding_0.MoveToObject("DiabloSeal5", 4, true); } else { if (!MovedToTPPos) Form1_0.PathFinding_0.MoveToThisPos(TPPos, 4, true); else Form1_0.PathFinding_0.MoveToObject("DiabloSeal5", 4, true); } } } if (CurrentStep == 4) { CurrentSealPos = Form1_0.MapAreaStruc_0.GetPositionOfObject("object", "DiabloSeal4", (int)Enums.Area.ChaosSanctuary, new List<int>()); if (Form1_0.PlayerScan_0.xPosFinal >= (CurrentSealPos.X - 5) && Form1_0.PlayerScan_0.xPosFinal <= (CurrentSealPos.X + 5) && Form1_0.PlayerScan_0.yPosFinal >= (CurrentSealPos.Y - 5) && Form1_0.PlayerScan_0.yPosFinal <= (CurrentSealPos.Y + 5)) { int InteractCount = 0; while (InteractCount < 3) { Form1_0.Battle_0.DoBattleScript(5); Form1_0.PathFinding_0.MoveToObject("DiabloSeal4"); Form1_0.WaitDelay(10); InteractCount++; } CurrentStep++; } else { Form1_0.PathFinding_0.MoveToObject("DiabloSeal4", 4, true); } } if (CurrentStep == 5) { CurrentSealPos = Form1_0.MapAreaStruc_0.GetPositionOfObject("object", "DiabloSeal3", (int)Enums.Area.ChaosSanctuary, new List<int>()); if (Form1_0.PlayerScan_0.xPosFinal >= (CurrentSealPos.X - 5) && Form1_0.PlayerScan_0.xPosFinal <= (CurrentSealPos.X + 5) && Form1_0.PlayerScan_0.yPosFinal >= (CurrentSealPos.Y - 5) && Form1_0.PlayerScan_0.yPosFinal <= (CurrentSealPos.Y + 5)) { int InteractCount = 0; while (InteractCount < 3) { Form1_0.Battle_0.DoBattleScript(5); Form1_0.PathFinding_0.MoveToObject("DiabloSeal3"); Form1_0.WaitDelay(10); InteractCount++; } if (!CastedAtSeis) { CastedAtSeis = true; Form1_0.Battle_0.CastDefense(); } //###### //KILL LORD DE SEIS if (!TimeSetForWaitingUniqueBoss) { StartTimeUniqueBossWaiting = DateTime.Now; TimeSetForWaitingUniqueBoss = true; } if (CurrentSealPos.X == 7773) SealType = 1; else SealType = 2; if (SealType == 1) { Form1_0.PathFinding_0.MoveToThisPos(new Position { X = 7794, Y = 5227 }, 4, true); //NTM_MoveTo(108, 7797, 5201); //for (int i = 0; i < 3; i += 1) NTM_TeleportTo(7794, 5227); } else Form1_0.PathFinding_0.MoveToThisPos(new Position { X = 7798, Y = 5186 }, 4, true); Form1_0.SetGameStatus("WAITING LORD DE SEIS " + (TryCountWaitingUniqueBoss + 1) + "/1"); bool UniqueDetected = Form1_0.MobsStruc_0.GetMobs("getSuperUniqueName", "Lord De Seis", false, 200, new List<long>()); while (!UniqueDetected && (DateTime.Now - StartTimeUniqueBossWaiting).TotalSeconds < CharConfig.ChaosWaitingSealBossDelay) { UniqueDetected = Form1_0.MobsStruc_0.GetMobs("getSuperUniqueName", "Lord De Seis", false, 200, new List<long>()); Form1_0.PlayerScan_0.GetPositions(); Form1_0.overlayForm.UpdateOverlay(); Form1_0.GameStruc_0.CheckChickenGameTime(); Form1_0.ItemsStruc_0.GetItems(true); Form1_0.Potions_0.CheckIfWeUsePotion(); Form1_0.Battle_0.DoBattleScript(10); //### Form1_0.Battle_0.SetSkills(); Form1_0.Battle_0.CastSkillsNoMove(); //### Application.DoEvents(); } if (!UniqueDetected) { //Form1_0.Battle_0.CastDefense(); Form1_0.InventoryStruc_0.DumpBadItemsOnGround(); TimeSetForWaitingUniqueBoss = false; CurrentStep++; } else { Form1_0.SetGameStatus("KILLING LORD DE SEIS"); if (Form1_0.MobsStruc_0.GetMobs("getSuperUniqueName", "Lord De Seis", false, 200, new List<long>())) { if (Form1_0.MobsStruc_0.MobsHP > 0) { Form1_0.Battle_0.RunBattleScriptOnThisMob("getSuperUniqueName", "Lord De Seis", new List<long>()); } else { Form1_0.Battle_0.CastDefense(); Form1_0.InventoryStruc_0.DumpBadItemsOnGround(); TimeSetForWaitingUniqueBoss = false; CurrentStep++; } } else { TimeSetForWaitingUniqueBoss = false; CurrentStep++; } } //###### } else { Form1_0.PathFinding_0.MoveToObject("DiabloSeal3", 4, true); } } if (CurrentStep == 6) { CurrentSealPos = Form1_0.MapAreaStruc_0.GetPositionOfObject("object", "DiabloSeal2", (int)Enums.Area.ChaosSanctuary, new List<int>()); if (Form1_0.PlayerScan_0.xPosFinal >= (CurrentSealPos.X - 5) && Form1_0.PlayerScan_0.xPosFinal <= (CurrentSealPos.X + 5) && Form1_0.PlayerScan_0.yPosFinal >= (CurrentSealPos.Y - 5) && Form1_0.PlayerScan_0.yPosFinal <= (CurrentSealPos.Y + 5)) { int InteractCount = 0; while (InteractCount < 3) { Form1_0.Battle_0.DoBattleScript(5); Form1_0.PathFinding_0.MoveToObject("DiabloSeal2"); Form1_0.WaitDelay(10); InteractCount++; } CurrentStep++; } else { Form1_0.PathFinding_0.MoveToObject("DiabloSeal2", 4, true); } } if (CurrentStep == 7) { CurrentSealPos = Form1_0.MapAreaStruc_0.GetPositionOfObject("object", "DiabloSeal1", (int)Enums.Area.ChaosSanctuary, new List<int>()); if (Form1_0.PlayerScan_0.xPosFinal >= (CurrentSealPos.X - 5) && Form1_0.PlayerScan_0.xPosFinal <= (CurrentSealPos.X + 5) && Form1_0.PlayerScan_0.yPosFinal >= (CurrentSealPos.Y - 5) && Form1_0.PlayerScan_0.yPosFinal <= (CurrentSealPos.Y + 5)) { int InteractCount = 0; while (InteractCount < 3) { Form1_0.Battle_0.DoBattleScript(5); Form1_0.PathFinding_0.MoveToObject("DiabloSeal1"); Form1_0.WaitDelay(10); InteractCount++; } //###### //KILL INFECTOR if (!TimeSetForWaitingUniqueBoss) { StartTimeUniqueBossWaiting = DateTime.Now; TimeSetForWaitingUniqueBoss = true; } if (CurrentSealPos.X == 7893) SealType = 1; else SealType = 2; if (SealType == 1) SealType = 1; // temp else Form1_0.PathFinding_0.MoveToThisPos(new Position { X = 7933, Y = 5299 }, 4, true); Form1_0.SetGameStatus("WAITING INFECTOR " + (TryCountWaitingUniqueBoss + 1) + "/1"); bool UniqueDetected = Form1_0.MobsStruc_0.GetMobs("getSuperUniqueName", "Winged Death", false, 200, new List<long>()); while (!UniqueDetected && (DateTime.Now - StartTimeUniqueBossWaiting).TotalSeconds < CharConfig.ChaosWaitingSealBossDelay) { UniqueDetected = Form1_0.MobsStruc_0.GetMobs("getSuperUniqueName", "Winged Death", false, 200, new List<long>()); Form1_0.PlayerScan_0.GetPositions(); Form1_0.overlayForm.UpdateOverlay(); Form1_0.GameStruc_0.CheckChickenGameTime(); Form1_0.ItemsStruc_0.GetItems(true); Form1_0.Potions_0.CheckIfWeUsePotion(); Form1_0.Battle_0.DoBattleScript(10); //### Form1_0.Battle_0.SetSkills(); Form1_0.Battle_0.CastSkillsNoMove(); //### Application.DoEvents(); } if (!UniqueDetected) { Form1_0.InventoryStruc_0.DumpBadItemsOnGround(); TimeSetForWaitingUniqueBoss = false; CurrentStep++; } else { Form1_0.SetGameStatus("KILLING INFECTOR"); if (Form1_0.MobsStruc_0.GetMobs("getSuperUniqueName", "Winged Death", false, 200, new List<long>())) { if (Form1_0.MobsStruc_0.MobsHP > 0) { Form1_0.Battle_0.RunBattleScriptOnThisMob("getSuperUniqueName", "Winged Death", new List<long>()); } else { Form1_0.InventoryStruc_0.DumpBadItemsOnGround(); TimeSetForWaitingUniqueBoss = false; CurrentStep++; } } else { Form1_0.InventoryStruc_0.DumpBadItemsOnGround(); TimeSetForWaitingUniqueBoss = false; CurrentStep++; } } //###### } else { Form1_0.PathFinding_0.MoveToObject("DiabloSeal1", 4, true); } } if (CurrentStep == 8) { if (Form1_0.PathFinding_0.MoveToThisPos(DiabloSpawnPos, 4, true)) { //Form1_0.PathFinding_0.MoveToThisPos(DiabloSpawnPos, 4, true); if (!FastChaos) Form1_0.Battle_0.CastDefense(); CurrentStep++; } } if (CurrentStep == 9) { Form1_0.Potions_0.CanUseSkillForRegen = false; Form1_0.SetGameStatus("KILLING DIABLO"); //############# bool DetectedDiablo = Form1_0.MobsStruc_0.GetMobs("getBossName", "Diablo", false, 200, new List<long>()); DateTime StartTime = DateTime.Now; TimeSpan TimeSinceDetecting = DateTime.Now - StartTime; while (!DetectedDiablo && TimeSinceDetecting.TotalSeconds < 13) { Form1_0.SetGameStatus("WAITING DETECTING DIABLO"); DetectedDiablo = Form1_0.MobsStruc_0.GetMobs("getBossName", "Diablo", false, 200, new List<long>()); TimeSinceDetecting = DateTime.Now - StartTime; //cast attack during this waiting time /*Form1_0.Battle_0.SetSkills(); Form1_0.Battle_0.CastSkills();*/ Form1_0.ItemsStruc_0.GetItems(true); //############# Form1_0.Potions_0.CheckIfWeUsePotion(); if (!Form1_0.GameStruc_0.IsInGame() || !Form1_0.Running) { Form1_0.overlayForm.ResetMoveToLocation(); return; } } if (TimeSinceDetecting.TotalSeconds >= 13) { Form1_0.MobsStruc_0.DetectThisMob("getBossName", "Diablo", false, 200, new List<long>()); Form1_0.method_1("Waited too long for Diablo repoping the seals!", Color.OrangeRed); FastChaosPopingSeals = true; CurrentStep = 3; return; } if (Form1_0.MobsStruc_0.GetMobs("getBossName", "Diablo", false, 200, new List<long>())) { Form1_0.SetGameStatus("KILLING DIABLO"); if (Form1_0.MobsStruc_0.MobsHP > 0) { DetectedBoss = true; Form1_0.Battle_0.RunBattleScriptOnThisMob("getBossName", "Diablo", new List<long>()); } else { if (!DetectedBoss) { Form1_0.method_1("Diablo not detected!", Color.Red); Form1_0.Battle_0.DoBattleScript(15); } Form1_0.PathFinding_0.AcceptMoveOffset = BufferPathFindingMoveSize; if (Form1_0.Battle_0.EndBossBattle()) ScriptDone = true; return; //Form1_0.LeaveGame(true); } } else { Form1_0.method_1("Diablo not detected!", Color.Red); Form1_0.Battle_0.DoBattleScript(15); //baal not detected... Form1_0.ItemsStruc_0.GetItems(true); if (Form1_0.MobsStruc_0.GetMobs("getBossName", "Diablo", false, 200, new List<long>())) return; //redetect baal? Form1_0.ItemsStruc_0.GrabAllItemsForGold(); if (Form1_0.MobsStruc_0.GetMobs("getBossName", "Diablo", false, 200, new List<long>())) return; //redetect baal? Form1_0.Potions_0.CanUseSkillForRegen = true; Form1_0.PathFinding_0.AcceptMoveOffset = BufferPathFindingMoveSize; if (Form1_0.Battle_0.EndBossBattle()) ScriptDone = true; return; //Form1_0.LeaveGame(true); } } } } static int[] FindBestPosition(int playerX, int playerY, List<int[]> monsterPositions, int maxDisplacement) { // Create a list to store all possible positions around the player List<int[]> possiblePositions = new List<int[]>(); // Generate all possible positions within the maximum displacement range for (int x = playerX - maxDisplacement; x <= playerX + maxDisplacement; x++) { for (int y = playerY - maxDisplacement; y <= playerY + maxDisplacement; y++) { // Calculate the distance between the player and the current position double distance = Math.Sqrt(Math.Pow(playerX - x, 2) + Math.Pow(playerY - y, 2)); // Check if the distance is within the maximum displacement and the position is not occupied by a monster if (distance <= maxDisplacement && !IsMonsterPosition(x, y, monsterPositions)) { //possiblePositions.Add(Tuple.Create(x, y)); possiblePositions.Add(new int[2] { x, y }); } } } // Find the closest position among the possible positions //int[] bestPosition = Tuple.Create(playerX, playerY); int[] bestPosition = new int[2] { playerX, playerY }; double closestDistance = double.MaxValue; foreach (var position in possiblePositions) { double distance = Math.Sqrt(Math.Pow(playerX - position[0], 2) + Math.Pow(playerY - position[1], 2)); if (distance < closestDistance) { closestDistance = distance; bestPosition = position; } } return bestPosition; } static bool IsMonsterPosition(int x, int y, List<int[]> monsterPositions) { foreach (var monsterPosition in monsterPositions) { if (monsterPosition[0] >= x - 8 && monsterPosition[0] <= x + 8 && monsterPosition[1] >= y - 8 && monsterPosition[1] <= y + 8) { return true; } } return false; } }
0
0.916168
1
0.916168
game-dev
MEDIA
0.860582
game-dev
0.76558
1
0.76558
AionGermany/aion-germany
3,459
AL-Game-5.8/src/com/aionemu/gameserver/skillengine/effect/SignetBurstEffect.java
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. */ package com.aionemu.gameserver.skillengine.effect; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import com.aionemu.gameserver.controllers.attack.AttackUtil; import com.aionemu.gameserver.skillengine.action.DamageType; import com.aionemu.gameserver.skillengine.model.Effect; /** * @author ATracer, kecimis */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SignetBurstEffect") public class SignetBurstEffect extends DamageEffect { @XmlAttribute protected int signetlvl; @XmlAttribute protected String signet; @Override public void calculate(Effect effect) { Effect signetEffect = effect.getEffected().getEffectController().getAnormalEffect(signet); if (!super.calculate(effect, DamageType.MAGICAL)) { if (signetEffect != null) { signetEffect.endEffect(); } return; } int valueWithDelta = value + delta * effect.getSkillLevel(); int critAddDmg = this.critAddDmg2 + this.critAddDmg1 * effect.getSkillLevel(); if (signetEffect == null) { valueWithDelta *= 0.05f; effect.setLaunchSubEffect(false); AttackUtil.calculateMagicalSkillResult(effect, valueWithDelta, null, getElement(), true, true, false, getMode(), this.critProbMod2, critAddDmg, shared, false); } else { int level = signetEffect.getSkillLevel(); if (level < 3) { // why is 3 not 5? tmp fix effect.setSubEffectAborted(true); } effect.setSignetBurstedCount(level); switch (level) { case 1: valueWithDelta *= 0.2f; break; case 2: valueWithDelta *= 0.5f; break; case 3: valueWithDelta *= 1.0f; break; case 4: valueWithDelta *= 1.2f; break; case 5: valueWithDelta *= 1.5f; break; } /** * custom bonuses for magical accurancy according to rune level and effector level follows same logic as * damage */ int accmod = 0; int mAccurancy = effect.getEffector().getGameStats().getMAccuracy().getCurrent(); switch (level) { case 1: accmod = (int) (-10.8f * mAccurancy); break; case 2: accmod = (int) (-10.5f * mAccurancy); break; case 3: accmod = 0; break; case 4: accmod = (int) (13.5f * mAccurancy); break; case 5: accmod = (int) (18.5f * mAccurancy); break; } effect.setAccModBoost(accmod); effect.setLaunchSubEffect(true); AttackUtil.calculateMagicalSkillResult(effect, valueWithDelta, null, getElement(), true, true, false, getMode(), this.critProbMod2, critAddDmg, shared, false); if (signetEffect != null) { signetEffect.endEffect(); } } } }
0
0.888493
1
0.888493
game-dev
MEDIA
0.848611
game-dev
0.976109
1
0.976109
exmex/KingdomRushFrontiers
5,311
cocos2d/external/Box2D/include/Box2D/Common/b2Settings.h
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef B2_SETTINGS_H #define B2_SETTINGS_H #include <stddef.h> #include <assert.h> #include <float.h> #if !defined(NDEBUG) #define b2DEBUG #endif #define B2_NOT_USED(x) ((void)(x)) #define b2Assert(A) assert(A) typedef signed char int8; typedef signed short int16; typedef signed int int32; typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned int uint32; typedef float float32; typedef double float64; #define b2_maxFloat FLT_MAX #define b2_epsilon FLT_EPSILON #define b2_pi 3.14159265359f /// @file /// Global tuning constants based on meters-kilograms-seconds (MKS) units. /// // Collision /// The maximum number of contact points between two convex shapes. Do /// not change this value. #define b2_maxManifoldPoints 2 /// The maximum number of vertices on a convex polygon. You cannot increase /// this too much because b2BlockAllocator has a maximum object size. #define b2_maxPolygonVertices 8 /// This is used to fatten AABBs in the dynamic tree. This allows proxies /// to move by a small amount without triggering a tree adjustment. /// This is in meters. #define b2_aabbExtension 0.1f /// This is used to fatten AABBs in the dynamic tree. This is used to predict /// the future position based on the current displacement. /// This is a dimensionless multiplier. #define b2_aabbMultiplier 2.0f /// A small length used as a collision and constraint tolerance. Usually it is /// chosen to be numerically significant, but visually insignificant. #define b2_linearSlop 0.005f /// A small angle used as a collision and constraint tolerance. Usually it is /// chosen to be numerically significant, but visually insignificant. #define b2_angularSlop (2.0f / 180.0f * b2_pi) /// The radius of the polygon/edge shape skin. This should not be modified. Making /// this smaller means polygons will have an insufficient buffer for continuous collision. /// Making it larger may create artifacts for vertex collision. #define b2_polygonRadius (2.0f * b2_linearSlop) /// Maximum number of sub-steps per contact in continuous physics simulation. #define b2_maxSubSteps 8 // Dynamics /// Maximum number of contacts to be handled to solve a TOI impact. #define b2_maxTOIContacts 32 /// A velocity threshold for elastic collisions. Any collision with a relative linear /// velocity below this threshold will be treated as inelastic. #define b2_velocityThreshold 1.0f /// The maximum linear position correction used when solving constraints. This helps to /// prevent overshoot. #define b2_maxLinearCorrection 0.2f /// The maximum angular position correction used when solving constraints. This helps to /// prevent overshoot. #define b2_maxAngularCorrection (8.0f / 180.0f * b2_pi) /// The maximum linear velocity of a body. This limit is very large and is used /// to prevent numerical problems. You shouldn't need to adjust this. #define b2_maxTranslation 2.0f #define b2_maxTranslationSquared (b2_maxTranslation * b2_maxTranslation) /// The maximum angular velocity of a body. This limit is very large and is used /// to prevent numerical problems. You shouldn't need to adjust this. #define b2_maxRotation (0.5f * b2_pi) #define b2_maxRotationSquared (b2_maxRotation * b2_maxRotation) /// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so /// that overlap is removed in one time step. However using values close to 1 often lead /// to overshoot. #define b2_baumgarte 0.2f #define b2_toiBaugarte 0.75f // Sleep /// The time that a body must be still before it will go to sleep. #define b2_timeToSleep 0.5f /// A body cannot sleep if its linear velocity is above this tolerance. #define b2_linearSleepTolerance 0.01f /// A body cannot sleep if its angular velocity is above this tolerance. #define b2_angularSleepTolerance (2.0f / 180.0f * b2_pi) // Memory Allocation /// Implement this function to use your own memory allocator. void* b2Alloc(int32 size); /// If you implement b2Alloc, you should also implement this function. void b2Free(void* mem); /// Logging function. void b2Log(const char* string, ...); /// Version numbering scheme. /// See http://en.wikipedia.org/wiki/Software_versioning struct b2Version { int32 major; ///< significant changes int32 minor; ///< incremental changes int32 revision; ///< bug fixes }; /// Current version. extern b2Version b2_version; #endif
0
0.87551
1
0.87551
game-dev
MEDIA
0.833183
game-dev
0.762537
1
0.762537
KoshakMineDEV/Lumi
10,414
src/main/java/cn/nukkit/network/protocol/CraftingDataPacket.java
package cn.nukkit.network.protocol; import cn.nukkit.recipe.descriptor.DefaultDescriptor; import cn.nukkit.recipe.descriptor.ItemDescriptor; import cn.nukkit.recipe.descriptor.ItemTagDescriptor; import cn.nukkit.recipe.impl.data.RecipeUnlockingRequirement; import cn.nukkit.item.Item; import cn.nukkit.item.material.tags.ItemTags; import cn.nukkit.recipe.*; import cn.nukkit.recipe.impl.*; import lombok.ToString; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * @author Nukkit Project Team */ @ToString public class CraftingDataPacket extends DataPacket { public static final byte NETWORK_ID = ProtocolInfo.CRAFTING_DATA_PACKET; public static final String CRAFTING_TAG_CRAFTING_TABLE = "crafting_table"; public static final String CRAFTING_TAG_CARTOGRAPHY_TABLE = "cartography_table"; public static final String CRAFTING_TAG_STONECUTTER = "stonecutter"; public static final String CRAFTING_TAG_FURNACE = "furnace"; public static final String CRAFTING_TAG_CAMPFIRE = "campfire"; public static final String CRAFTING_TAG_BLAST_FURNACE = "blast_furnace"; public static final String CRAFTING_TAG_SMOKER = "smoker"; public static final String CRAFTING_TAG_SMITHING_TABLE = "smithing_table"; private List<Recipe> entries = new ArrayList<>(); private final List<BrewingRecipe> brewingEntries = new ArrayList<>(); private final List<ContainerRecipe> containerEntries = new ArrayList<>(); public boolean cleanRecipes = true; public void addShapelessRecipe(ShapelessRecipe... recipe) { for(ShapelessRecipe shapelessRecipe : recipe) { if (shapelessRecipe.isValidRecipe(protocol)) { this.entries.add(shapelessRecipe); } } } public void addShapedRecipe(ShapedRecipe... recipe) { for(ShapedRecipe shapedRecipe : recipe) { if (shapedRecipe.isValidRecipe(protocol)) { this.entries.add(shapedRecipe); } } } public void addFurnaceRecipe(FurnaceRecipe... recipe) { Collections.addAll(entries, recipe); } public void addBrewingRecipe(BrewingRecipe... recipe) { Collections.addAll(brewingEntries, recipe); } public void addMultiRecipe(MultiRecipe... recipe) { Collections.addAll(entries, recipe); } public void addContainerRecipe(ContainerRecipe... recipe) { Collections.addAll(containerEntries, recipe); } @Override public DataPacket clean() { entries = new ArrayList<>(); return super.clean(); } @Override public void decode() { } @Override public void encode() { this.reset(); this.putUnsignedVarInt(protocol >= ProtocolInfo.v1_20_0_23 ? entries.size() + 1 : entries.size());//1.20.0+ 有额外的smithing_trim for (Recipe recipe : entries) { this.putVarInt(recipe.getType().getNetworkType(protocol)); switch (recipe.getType()) { case SHAPELESS: ShapelessRecipe shapeless = (ShapelessRecipe) recipe; this.putString(shapeless.getRecipeId()); Collection<ItemDescriptor> ingredients = shapeless.getIngredientList(); this.putUnsignedVarInt(ingredients.size()); for (ItemDescriptor ingredient : ingredients) { ingredient.putRecipe(this, protocol); } this.putUnsignedVarInt(1); // Results length this.putSlot(protocol, shapeless.getResult(), protocol >= ProtocolInfo.v1_16_100); this.putUUID(shapeless.getId()); if (protocol >= 354) { this.putString(CRAFTING_TAG_CRAFTING_TABLE); if (protocol >= 361) { this.putVarInt(shapeless.getPriority()); if (protocol >= 407) { if (protocol >= ProtocolInfo.v1_21_0) { this.writeRequirement(shapeless); } this.putUnsignedVarInt(shapeless.getNetworkId()); } } } break; case SMITHING_TRANSFORM: SmithingRecipe smithing = (SmithingRecipe) recipe; this.putString(smithing.getRecipeId()); new DefaultDescriptor(smithing.getTemplate()).putRecipe(this, protocol); new DefaultDescriptor(smithing.getEquipment()).putRecipe(this, protocol); new DefaultDescriptor(smithing.getIngredient()).putRecipe(this, protocol); this.putSlot(protocol, smithing.getResult(), true); this.putString(CRAFTING_TAG_SMITHING_TABLE); this.putUnsignedVarInt(smithing.getNetworkId()); break; case SHAPED: ShapedRecipe shaped = (ShapedRecipe) recipe; if (protocol >= 361) { this.putString(shaped.getRecipeId()); } this.putVarInt(shaped.getWidth()); this.putVarInt(shaped.getHeight()); for (int z = 0; z < shaped.getHeight(); ++z) { for (int x = 0; x < shaped.getWidth(); ++x) { shaped.getIngredient(x, z).putRecipe(this, protocol); } } List<Item> outputs = new ArrayList<>(); outputs.add(shaped.getResult()); outputs.addAll(shaped.getExtraResults()); this.putUnsignedVarInt(outputs.size()); for (Item output : outputs) { this.putSlot(protocol, output, protocol >= ProtocolInfo.v1_16_100); } this.putUUID(shaped.getId()); if (protocol >= 354) { this.putString(CRAFTING_TAG_CRAFTING_TABLE); if (protocol >= 361) { this.putVarInt(shaped.getPriority()); if (this.protocol >= ProtocolInfo.v1_20_80) { this.putBoolean(shaped.isAssumeSymetry()); } if (protocol >= 407) { if (protocol >= ProtocolInfo.v1_21_0) { this.writeRequirement(shaped); } this.putUnsignedVarInt(shaped.getNetworkId()); } } } break; case FURNACE: case FURNACE_DATA: FurnaceRecipe furnace = (FurnaceRecipe) recipe; Item input = furnace.getInput(); this.putVarInt(input.getId()); if (recipe.getType() == RecipeType.FURNACE_DATA) { this.putVarInt(input.getDamage()); } this.putSlot(protocol, furnace.getResult(), protocol >= ProtocolInfo.v1_16_100); if (protocol >= 354) { this.putString(CRAFTING_TAG_FURNACE); } break; case MULTI: if (protocol >= ProtocolInfo.v1_16_0) { // ?? this.putUUID(((MultiRecipe) recipe).getId()); this.putUnsignedVarInt(((MultiRecipe) recipe).getNetworkId()); break; } } } // Identical smithing_trim recipe sent by BDS that uses tag-descriptors, as the client seems to ignore the // approach of using many default-descriptors (which we do for smithing_transform) this.putVarInt(RecipeType.SMITHING_TRIM.getNetworkType(protocol)); this.putString("minecraft:smithing_armor_trim"); new ItemTagDescriptor(ItemTags.TRIM_TEMPLATES, "minecraft:trim_templates").putRecipe(this, protocol); new ItemTagDescriptor(ItemTags.TRIMMABLE_ARMORS, "minecraft:trimmable_armors").putRecipe(this, protocol); new ItemTagDescriptor(ItemTags.TRIM_MATERIALS, "minecraft:trim_materials").putRecipe(this, protocol); this.putString(CRAFTING_TAG_SMITHING_TABLE); this.putUnsignedVarInt(1); if (protocol >= 388) { this.putUnsignedVarInt(this.brewingEntries.size()); for (BrewingRecipe recipe : brewingEntries) { if (protocol >= 407) { this.putVarInt(recipe.getInput().getNetworkId(protocol)); } this.putVarInt(recipe.getInput().getDamage()); this.putVarInt(recipe.getIngredient().getNetworkId(protocol)); if (protocol >= 407) { this.putVarInt(recipe.getIngredient().getDamage()); this.putVarInt(recipe.getResult().getNetworkId(protocol)); } this.putVarInt(recipe.getResult().getDamage()); } this.putUnsignedVarInt(this.containerEntries.size()); for (ContainerRecipe recipe : containerEntries) { this.putVarInt(recipe.getInput().getNetworkId(protocol)); this.putVarInt(recipe.getIngredient().getNetworkId(protocol)); this.putVarInt(recipe.getResult().getNetworkId(protocol)); } if (protocol >= ProtocolInfo.v1_17_30) { this.putUnsignedVarInt(0); // Material reducers size } } this.putBoolean(cleanRecipes); } @Override public byte pid() { return NETWORK_ID; } protected void writeRequirement(CraftingRecipe recipe) { this.putByte((byte) recipe.getRequirement().getContext().ordinal()); if (recipe.getRequirement().getContext().equals(RecipeUnlockingRequirement.UnlockingContext.NONE)) { this.putArray(recipe.getRequirement().getIngredients(), (ingredient) -> new DefaultDescriptor(ingredient).putRecipe(this, protocol)); } } }
0
0.897665
1
0.897665
game-dev
MEDIA
0.927829
game-dev,networking
0.911029
1
0.911029
magefree/mage
1,503
Mage.Sets/src/mage/cards/t/ToralfsDisciple.java
package mage.cards.t; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.AttacksTriggeredAbility; import mage.abilities.effects.common.ConjureCardEffect; import mage.abilities.effects.common.ShuffleLibrarySourceEffect; import mage.abilities.keyword.HasteAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Zone; import java.util.UUID; /** * @author TheElk801 */ public final class ToralfsDisciple extends CardImpl { public ToralfsDisciple(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{R}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.WARRIOR); this.power = new MageInt(3); this.toughness = new MageInt(3); // Haste this.addAbility(HasteAbility.getInstance()); // Whenever Toralf's Disciple attacks, conjure four cards named Lightning Bolt into your library, then shuffle. Ability ability = new AttacksTriggeredAbility(new ConjureCardEffect( "Lightning Bolt", Zone.LIBRARY, 4 )); ability.addEffect(new ShuffleLibrarySourceEffect().setText(", then shuffle")); this.addAbility(ability); } private ToralfsDisciple(final ToralfsDisciple card) { super(card); } @Override public ToralfsDisciple copy() { return new ToralfsDisciple(this); } }
0
0.822154
1
0.822154
game-dev
MEDIA
0.971436
game-dev
0.978607
1
0.978607
chipmunk-rb/chipmunk
21,045
ext/chipmunk/rb_cpSpace.c
/* Copyright (c) 2007 Scott Lembcke * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stdlib.h> #include "chipmunk.h" #include "ruby.h" #include "rb_chipmunk.h" static ID id_call; static ID id_begin; static ID id_pre_solve; static ID id_post_solve; static ID id_separate; VALUE c_cpSpace; #define SPACE_GETSET_FUNCS(member) \ static VALUE rb_cpSpace_get_ ## member(VALUE self) \ { return rb_float_new(SPACE(self)->member);} \ static VALUE rb_cpSpace_set_ ## member(VALUE self, VALUE value) \ { SPACE(self)->member = NUM2DBL(value); return value;} SPACE_GETSET_FUNCS(collisionBias) SPACE_GETSET_FUNCS(collisionSlop) // TODO this needs to be uint not float SPACE_GETSET_FUNCS(collisionPersistence) static VALUE rb_cpSpaceAlloc(VALUE klass) { cpSpace *space = cpSpaceAlloc(); VALUE rbSpace = Data_Wrap_Struct(klass, NULL, cpSpaceFree, space); space->data = (void*)rbSpace; return rbSpace; } static VALUE rb_cpSpaceInitialize(VALUE self) { cpSpace *space = SPACE(self); cpSpaceInit(space); // These might as well be in one shared hash. rb_iv_set(self, "@static_shapes", rb_ary_new()); rb_iv_set(self, "@active_shapes", rb_ary_new()); rb_iv_set(self, "@bodies", rb_ary_new()); rb_iv_set(self, "@constraints", rb_ary_new()); rb_iv_set(self, "@blocks", rb_hash_new()); rb_iv_set(self, "@post_step_blocks", rb_hash_new()); return self; } static VALUE rb_cpSpaceGetSleepTimeThreshold(VALUE self) { return INT2NUM(SPACE(self)->sleepTimeThreshold); } static VALUE rb_cpSpaceSetSleepTimeThreshold(VALUE self, VALUE val) { SPACE(self)->sleepTimeThreshold = NUM2UINT(val); return val; } static VALUE rb_cpSpaceGetIdleSpeedThreshold(VALUE self) { return UINT2NUM(SPACE(self)->idleSpeedThreshold); } static VALUE rb_cpSpaceSetIdleSpeedThreshold(VALUE self, VALUE val) { SPACE(self)->idleSpeedThreshold = NUM2INT(val); return val; } static VALUE rb_cpSpaceGetIterations(VALUE self) { return INT2NUM(SPACE(self)->iterations); } static VALUE rb_cpSpaceSetIterations(VALUE self, VALUE val) { SPACE(self)->iterations = NUM2INT(val); return val; } static VALUE rb_cpSpaceGetDamping(VALUE self) { return rb_float_new(SPACE(self)->damping); } static VALUE rb_cpSpaceSetDamping(VALUE self, VALUE val) { SPACE(self)->damping = NUM2DBL(val); return val; } static VALUE rb_cpSpaceGetContactGraphEnabled(VALUE self) { return CP_INT_BOOL(SPACE(self)->enableContactGraph); } static VALUE rb_cpSpaceSetContactGraphEnabled(VALUE self, VALUE val) { SPACE(self)->enableContactGraph = CP_BOOL_INT(val); return val; } static VALUE rb_cpSpaceGetGravity(VALUE self) { return VWRAP(self, &SPACE(self)->gravity); } static VALUE rb_cpSpaceSetGravity(VALUE self, VALUE val) { SPACE(self)->gravity = *VGET(val); return val; } static int doNothingCallback(cpArbiter *arb, cpSpace *space, void *data) { return 0; } // We need this as rb_obj_method_arity is not in 1.8.7 int rb_obj_method_arity(VALUE self, ID id) { VALUE metho; VALUE arity; if(id == id_call) { metho = self; } else { metho = rb_funcall(self, rb_intern("method"), 1, ID2SYM(id)); } arity = rb_funcall(metho, rb_intern("arity"), 0, 0); return NUM2INT(arity); } // This callback function centralizes all collision callbacks. // it also adds flexibility by changing theway the callback is called on the // arity of the callback block or method. With arity0, no args are pased, // with arity 1, the arbiter, // with arity 2, body_a and body_b, // with arity 3 or more -> body_a, body_b, arbiter static int do_callback(void * data, ID method, cpArbiter *arb) { int res = 0; CP_ARBITER_GET_SHAPES(arb, a, b); VALUE object = (VALUE) data; VALUE va = (VALUE)a->data; VALUE vb = (VALUE)b->data; VALUE varb = ARBWRAP(arb); int arity = rb_obj_method_arity(object, method); switch(arity) { case 0: return CP_BOOL_INT(rb_funcall(object, method, 0)); case 1: return CP_BOOL_INT(rb_funcall(object, method, 1, varb)); case 2: return CP_BOOL_INT(rb_funcall(object, method, 2, va, vb)); case 3: default: return CP_BOOL_INT(rb_funcall(object, method, 3, va, vb, varb)); } // we never get here return res; } static int compatibilityCallback(cpArbiter *arb, cpSpace *space, void *data) { return do_callback(data, id_call, arb); } static int beginCallback(cpArbiter *arb, cpSpace *space, void *data) { return do_callback(data, id_begin, arb); } static int preSolveCallback(cpArbiter *arb, cpSpace *space, void *data) { return do_callback(data, id_pre_solve, arb); } static void postSolveCallback(cpArbiter *arb, cpSpace *space, void *data) { do_callback(data, id_post_solve, arb); } static void separateCallback(cpArbiter *arb, cpSpace *space, void *data) { do_callback(data, id_separate, arb); } static int respondsTo(VALUE obj, ID method) { VALUE value = rb_funcall(obj, rb_intern("respond_to?"), 1, ID2SYM(method)); return RTEST(value); } static VALUE rb_cpSpaceAddCollisionHandler(int argc, VALUE *argv, VALUE self) { VALUE a, b, obj, block; obj = 0; rb_scan_args(argc, argv, "21&", &a, &b, &obj, &block); VALUE id_a = rb_obj_id(a); VALUE id_b = rb_obj_id(b); VALUE blocks = rb_iv_get(self, "@blocks"); if(RTEST(obj) && RTEST(block)) { rb_raise(rb_eArgError, "Cannot specify both a handler object and a block."); } else if(RTEST(block)) { cpSpaceAddCollisionHandler( SPACE(self), NUM2ULONG(id_a), NUM2ULONG(id_b), NULL, compatibilityCallback, NULL, NULL, (void *)block ); rb_hash_aset(blocks, rb_ary_new3(2, id_a, id_b), block); } else if(RTEST(obj)) { cpSpaceAddCollisionHandler( SPACE(self), NUM2ULONG(id_a), NUM2ULONG(id_b), (respondsTo(obj, id_begin) ? beginCallback : NULL), (respondsTo(obj, id_pre_solve) ? preSolveCallback : NULL), (respondsTo(obj, id_post_solve) ? postSolveCallback : NULL), (respondsTo(obj, id_separate) ? separateCallback : NULL), (void *)obj ); rb_hash_aset(blocks, rb_ary_new3(2, id_a, id_b), obj); } else { cpSpaceAddCollisionHandler( SPACE(self), NUM2ULONG(id_a), NUM2ULONG(id_b), NULL, doNothingCallback, NULL, NULL, NULL ); } return Qnil; } static VALUE rb_cpSpaceRemoveCollisionHandler(VALUE self, VALUE a, VALUE b) { VALUE id_a = rb_obj_id(a); VALUE id_b = rb_obj_id(b); cpSpaceRemoveCollisionHandler(SPACE(self), NUM2ULONG(id_a), NUM2ULONG(id_b)); VALUE blocks = rb_iv_get(self, "@blocks"); rb_hash_delete(blocks, rb_ary_new3(2, id_a, id_b)); return Qnil; } static VALUE rb_cpSpaceSetDefaultCollisionHandler(int argc, VALUE *argv, VALUE self) { VALUE obj, block; rb_scan_args(argc, argv, "01&", &obj, &block); if(RTEST(obj) && RTEST(block)) { rb_raise(rb_eArgError, "Cannot specify both a handler object and a block."); } else if(RTEST(block)) { cpSpaceSetDefaultCollisionHandler( SPACE(self), NULL, compatibilityCallback, NULL, NULL, (void *)block ); rb_hash_aset(rb_iv_get(self, "@blocks"), ID2SYM(rb_intern("default")), block); } else if(RTEST(obj)) { cpSpaceSetDefaultCollisionHandler( SPACE(self), (respondsTo(obj, id_begin) ? beginCallback : NULL), (respondsTo(obj, id_pre_solve) ? preSolveCallback : NULL), (respondsTo(obj, id_post_solve) ? postSolveCallback : NULL), (respondsTo(obj, id_separate) ? separateCallback : NULL), (void *)obj ); rb_hash_aset(rb_iv_get(self, "@blocks"), ID2SYM(rb_intern("default")), obj); } else { cpSpaceSetDefaultCollisionHandler( SPACE(self), NULL, doNothingCallback, NULL, NULL, NULL ); } return Qnil; } static void poststepCallback(cpSpace *space, void *obj, void *data) { rb_funcall((VALUE)data, id_call, 2, (VALUE)space->data, (VALUE)obj); } static VALUE rb_cpSpaceAddPostStepCallback(int argc, VALUE *argv, VALUE self) { VALUE obj, block; VALUE blocks = rb_iv_get(self, "@post_step_blocks"); rb_scan_args(argc, argv, "10&", &obj, &block); if(!RTEST(block)) { rb_raise(rb_eArgError, "Cannot omit the block."); } rb_hash_aset(blocks, obj, block); cpSpaceAddPostStepCallback(SPACE(self), poststepCallback, (void *) obj, (void *) block); return self; } static VALUE rb_cpSpaceAddShape(VALUE self, VALUE shape) { cpSpaceAddShape(SPACE(self), SHAPE(shape)); rb_ary_push(rb_iv_get(self, "@active_shapes"), shape); return shape; } static VALUE rb_cpSpaceAddStaticShape(VALUE self, VALUE shape) { cpSpaceAddStaticShape(SPACE(self), SHAPE(shape)); rb_ary_push(rb_iv_get(self, "@static_shapes"), shape); return shape; } static VALUE rb_cpSpaceAddBody(VALUE self, VALUE body) { cpSpaceAddBody(SPACE(self), BODY(body)); rb_ary_push(rb_iv_get(self, "@bodies"), body); return body; } static VALUE rb_cpSpaceAddConstraint(VALUE self, VALUE constraint) { cpSpaceAddConstraint(SPACE(self), CONSTRAINT(constraint)); rb_ary_push(rb_iv_get(self, "@constraints"), constraint); return constraint; } static VALUE rb_cpSpaceRemoveShape(VALUE self, VALUE shape) { VALUE ok = rb_ary_delete(rb_iv_get(self, "@active_shapes"), shape); if(!(NIL_P(ok))) cpSpaceRemoveShape(SPACE(self), SHAPE(shape)); return ok; } static VALUE rb_cpSpaceRemoveStaticShape(VALUE self, VALUE shape) { VALUE ok = rb_ary_delete(rb_iv_get(self, "@static_shapes"), shape); if(!(NIL_P(ok))) cpSpaceRemoveStaticShape(SPACE(self), SHAPE(shape)); return ok; } static VALUE rb_cpSpaceRemoveBody(VALUE self, VALUE body) { VALUE ok = rb_ary_delete(rb_iv_get(self, "@bodies"), body); if(!(NIL_P(ok))) cpSpaceRemoveBody(SPACE(self), BODY(body)); return ok; } static VALUE rb_cpSpaceRemoveConstraint(VALUE self, VALUE constraint) { VALUE ok = rb_ary_delete(rb_iv_get(self, "@constraints"), constraint); if(!(NIL_P(ok))) cpSpaceRemoveConstraint(SPACE(self), CONSTRAINT(constraint)); return ok; } static VALUE rb_cpSpaceResizeStaticHash(VALUE self, VALUE dim, VALUE count) { rb_raise(rb_eArgError, "resize_static_hash is obsolete"); return Qnil; /* cpSpaceResizeStaticHash(SPACE(self), NUM2DBL(dim), NUM2INT(count)); return Qnil; */ } static VALUE rb_cpSpaceResizeActiveHash(VALUE self, VALUE dim, VALUE count) { rb_raise(rb_eArgError, "resize_active_hash is obsolete"); return Qnil; /* cpSpaceResizeActiveHash(SPACE(self), NUM2DBL(dim), NUM2INT(count)); return Qnil; */ } static VALUE rb_cpSpaceReindexStatic(VALUE self) { cpSpaceReindexStatic(SPACE(self)); return Qnil; } static VALUE rb_cpSpaceReindexShape(VALUE self, VALUE shape) { cpSpaceReindexShape(SPACE(self), SHAPE(shape)); return Qnil; } static unsigned int get_layers(VALUE layers) { if (NIL_P(layers)) return ~0; return NUM2ULONG(layers); } static unsigned int get_group(VALUE group) { if (NIL_P(group)) return 0; return NUM2ULONG(group); } static void pointQueryCallback(cpShape *shape, VALUE block) { rb_funcall(block, id_call, 1, (VALUE)shape->data); } static VALUE rb_cpSpacePointQuery(int argc, VALUE *argv, VALUE self) { VALUE point, layers, group, block; rb_scan_args(argc, argv, "12&", &point, &layers, &group, &block); cpSpacePointQuery( SPACE(self), *VGET(point), get_layers(layers), get_group(group), (cpSpacePointQueryFunc)pointQueryCallback, (void *)block ); return Qnil; } static VALUE rb_cpSpacePointQueryFirst(int argc, VALUE *argv, VALUE self) { VALUE point, layers, group; rb_scan_args(argc, argv, "12", &point, &layers, &group); cpShape *shape = cpSpacePointQueryFirst( SPACE(self), *VGET(point), get_layers(layers), get_group(group) ); return (shape ? (VALUE)shape->data : Qnil); } static void segmentQueryCallback(cpShape *shape, cpFloat t, cpVect n, VALUE block) { rb_funcall(block, id_call, 3, (VALUE)shape->data, rb_float_new(t), VNEW(n)); } static VALUE rb_cpSpaceSegmentQuery(int argc, VALUE *argv, VALUE self) { VALUE a, b, layers, group, block; rb_scan_args(argc, argv, "22&", &a, &b, &layers, &group, &block); cpSpaceSegmentQuery( SPACE(self), *VGET(a), *VGET(b), get_layers(layers), get_group(group), (cpSpaceSegmentQueryFunc)segmentQueryCallback, (void *)block ); return Qnil; } static VALUE rb_cpSpaceSegmentQueryFirst(int argc, VALUE *argv, VALUE self) { VALUE a, b, layers, group, block; cpSegmentQueryInfo info = { NULL, 1.0f, cpvzero}; rb_scan_args(argc, argv, "22&", &a, &b, &layers, &group, &block); cpSpaceSegmentQueryFirst(SPACE(self), *VGET(a), *VGET(b), get_layers(layers), get_group(group), &info); // contrary to the standard chipmunk bindings, we also return a // struct here with then needed values. if(info.shape) { return rb_cpSegmentQueryInfoNew((VALUE)info.shape->data, rb_float_new(info.t), VNEW(info.n)); } return Qnil; } static void bbQueryCallback(cpShape *shape, VALUE block) { rb_funcall(block, id_call, 1, (VALUE)shape->data); } /* Bounding box query. */ static VALUE rb_cpSpaceBBQuery(int argc, VALUE *argv, VALUE self) { VALUE bb, layers, group, block; unsigned int l = ~0; unsigned int g = 0; rb_scan_args(argc, argv, "12&", &bb, &layers, &group, &block); if (!NIL_P(layers)) l = NUM2ULONG(layers); if (!NIL_P(group)) g = NUM2ULONG(group); cpSpaceBBQuery( SPACE(self), *BBGET(bb), l, g, (cpSpaceBBQueryFunc)bbQueryCallback, (void *)block ); return Qnil; } static void shapeQueryCallback(cpShape *shape, cpContactPointSet *points, VALUE block) { rb_funcall(block, id_call, 1, (VALUE)shape->data); } /* Shape query. */ static VALUE rb_cpSpaceShapeQuery(int argc, VALUE *argv, VALUE self) { VALUE shape, block; rb_scan_args(argc, argv, "1&", &shape, &block); cpSpaceShapeQuery( SPACE(self), SHAPE(shape), (cpSpaceShapeQueryFunc)shapeQueryCallback, (void *)block ); return Qnil; } static VALUE rb_cpSpaceStep(VALUE self, VALUE dt) { cpSpaceStep(SPACE(self), NUM2DBL(dt)); rb_iv_set(self, "@post_step_blocks", rb_hash_new()); return Qnil; } static VALUE rb_cpSpaceActivateShapesTouchingShape(VALUE self, VALUE shape) { cpSpaceActivateShapesTouchingShape(SPACE(self), SHAPE(shape)); return self; } /** in chipmunk 6 static VALUE rb_cpSpaceUseSpatialHash(VALUE self, VALUE dim, VALUE count) { cpSpaceUseSpatialHash(SPACE(self), NUM2DBL(dim), NUM2INT(count)); return Qnil; } */ void Init_cpSpace(void) { id_call = rb_intern("call"); id_begin = rb_intern("begin"); id_pre_solve = rb_intern("pre_solve"); id_post_solve = rb_intern("post_solve"); id_separate = rb_intern("separate"); c_cpSpace = rb_define_class_under(m_Chipmunk, "Space", rb_cObject); rb_define_alloc_func(c_cpSpace, rb_cpSpaceAlloc); rb_define_method(c_cpSpace, "initialize", rb_cpSpaceInitialize, 0); rb_define_method(c_cpSpace, "iterations", rb_cpSpaceGetIterations, 0); rb_define_method(c_cpSpace, "iterations=", rb_cpSpaceSetIterations, 1); rb_define_method(c_cpSpace, "gravity", rb_cpSpaceGetGravity, 0); rb_define_method(c_cpSpace, "gravity=", rb_cpSpaceSetGravity, 1); rb_define_method(c_cpSpace, "add_collision_func", rb_cpSpaceAddCollisionHandler, -1); rb_define_method(c_cpSpace, "add_collision_handler", rb_cpSpaceAddCollisionHandler, -1); rb_define_method(c_cpSpace, "on_collision", rb_cpSpaceAddCollisionHandler, -1); rb_define_method(c_cpSpace, "remove_collision_func", rb_cpSpaceRemoveCollisionHandler, 2); rb_define_method(c_cpSpace, "remove_collision_handler", rb_cpSpaceRemoveCollisionHandler, 2); rb_define_method(c_cpSpace, "remove_collision", rb_cpSpaceRemoveCollisionHandler, 2); rb_define_method(c_cpSpace, "set_default_collision_func", rb_cpSpaceSetDefaultCollisionHandler, -1); rb_define_method(c_cpSpace, "set_default_collision_handler", rb_cpSpaceSetDefaultCollisionHandler, -1); rb_define_method(c_cpSpace, "on_default_collision", rb_cpSpaceSetDefaultCollisionHandler, -1); rb_define_method(c_cpSpace, "add_post_step_callback", rb_cpSpaceAddPostStepCallback, -1); rb_define_method(c_cpSpace, "on_post_step", rb_cpSpaceAddPostStepCallback, -1); rb_define_method(c_cpSpace, "collision_bias", rb_cpSpace_get_collisionBias, 0); rb_define_method(c_cpSpace, "collision_bias=", rb_cpSpace_set_collisionBias, 1); rb_define_method(c_cpSpace, "collision_slop", rb_cpSpace_get_collisionSlop, 0); rb_define_method(c_cpSpace, "collision_slop=", rb_cpSpace_set_collisionSlop, 1); rb_define_method(c_cpSpace, "collision_persistence", rb_cpSpace_get_collisionPersistence, 0); rb_define_method(c_cpSpace, "collision_persistence=", rb_cpSpace_set_collisionPersistence, 1); rb_define_method(c_cpSpace, "add_shape", rb_cpSpaceAddShape, 1); rb_define_method(c_cpSpace, "add_static_shape", rb_cpSpaceAddStaticShape, 1); rb_define_method(c_cpSpace, "add_body", rb_cpSpaceAddBody, 1); rb_define_method(c_cpSpace, "add_constraint", rb_cpSpaceAddConstraint, 1); rb_define_method(c_cpSpace, "remove_shape", rb_cpSpaceRemoveShape, 1); rb_define_method(c_cpSpace, "remove_static_shape", rb_cpSpaceRemoveStaticShape, 1); rb_define_method(c_cpSpace, "remove_body", rb_cpSpaceRemoveBody, 1); rb_define_method(c_cpSpace, "remove_constraint", rb_cpSpaceRemoveConstraint, 1); rb_define_method(c_cpSpace, "resize_static_hash", rb_cpSpaceResizeStaticHash, 2); rb_define_method(c_cpSpace, "resize_active_hash", rb_cpSpaceResizeActiveHash, 2); rb_define_method(c_cpSpace, "reindex_static", rb_cpSpaceReindexStatic, 0); rb_define_method(c_cpSpace, "reindex_shape", rb_cpSpaceReindexShape, 1); rb_define_method(c_cpSpace, "point_query", rb_cpSpacePointQuery, -1); rb_define_method(c_cpSpace, "point_query_first", rb_cpSpacePointQueryFirst, -1); rb_define_method(c_cpSpace, "shape_point_query", rb_cpSpacePointQueryFirst, -1); rb_define_method(c_cpSpace, "segment_query", rb_cpSpaceSegmentQuery, -1); rb_define_method(c_cpSpace, "segment_query_first", rb_cpSpaceSegmentQueryFirst, -1); rb_define_method(c_cpSpace, "bb_query", rb_cpSpaceBBQuery, -1); rb_define_method(c_cpSpace, "shape_query", rb_cpSpaceShapeQuery, -1); rb_define_method(c_cpSpace, "step", rb_cpSpaceStep, 1); rb_define_method(c_cpSpace, "sleep_time_threshold=", rb_cpSpaceSetSleepTimeThreshold, 1); rb_define_method(c_cpSpace, "sleep_time_threshold", rb_cpSpaceGetSleepTimeThreshold, 0); rb_define_method(c_cpSpace, "idle_speed_threshold=", rb_cpSpaceSetIdleSpeedThreshold, 1); rb_define_method(c_cpSpace, "idle_speed_threshold", rb_cpSpaceGetIdleSpeedThreshold, 0); // also define slghtly less verbose API rb_define_method(c_cpSpace, "sleep_time=", rb_cpSpaceSetSleepTimeThreshold, 1); rb_define_method(c_cpSpace, "sleep_time", rb_cpSpaceGetSleepTimeThreshold, 0); rb_define_method(c_cpSpace, "idle_speed=", rb_cpSpaceSetIdleSpeedThreshold, 1); rb_define_method(c_cpSpace, "idle_speed", rb_cpSpaceGetIdleSpeedThreshold, 0); rb_define_method(c_cpSpace, "damping", rb_cpSpaceGetDamping, 0); rb_define_method(c_cpSpace, "damping=", rb_cpSpaceSetDamping, 1); rb_define_method(c_cpSpace, "contact_graph_enabled", rb_cpSpaceGetContactGraphEnabled, 0); rb_define_method(c_cpSpace, "contact_graph_enabled=", rb_cpSpaceSetContactGraphEnabled, 1); rb_define_method(c_cpSpace, "activate_shapes_touching_shape", rb_cpSpaceActivateShapesTouchingShape, 1); // this is nicer, though :) rb_define_method(c_cpSpace, "activate_touching", rb_cpSpaceActivateShapesTouchingShape, 1); }
0
0.723925
1
0.723925
game-dev
MEDIA
0.507259
game-dev,graphics-rendering
0.87106
1
0.87106
ProjectIgnis/CardScripts
3,121
unofficial/c511001603.lua
--琰魔竜王 レッド・デーモン・カラミティ (Manga) --Hot Red Dragon Archfiend King Calamity (Manga) Duel.EnableUnofficialProc(PROC_CANNOT_BATTLE_INDES) local s,id=GetID() function s.initial_effect(c) --synchro summon c:EnableReviveLimit() Synchro.AddProcedure(c,nil,2,2,Synchro.NonTunerEx(Card.IsType,TYPE_SYNCHRO),1,1) --damage local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_DAMAGE) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetCode(EVENT_BATTLE_DESTROYING) e1:SetCondition(s.damcon) e1:SetTarget(s.damtg) e1:SetOperation(s.damop) c:RegisterEffect(e1) --special summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(id,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_DESTROYED) e2:SetTarget(s.sptg) e2:SetOperation(s.spop) c:RegisterEffect(e2) --always Battle destroy local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD) e3:SetCode(EFFECT_CANNOT_BATTLE_INDES) e3:SetRange(LOCATION_MZONE) e3:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE) e3:SetValue(1) c:RegisterEffect(e3) --double tuner local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e4:SetCode(EFFECT_MULTIPLE_TUNERS) c:RegisterEffect(e4) end s.synchro_nt_required=1 s.listed_names={39765958} function s.damcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local bc=c:GetBattleTarget() return c:IsRelateToBattle() and bc:IsMonster() end function s.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local c=e:GetHandler() local bc=c:GetBattleTarget() local dam=bc:GetAttack() if dam<0 then dam=0 end Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(dam) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,dam) end function s.damop(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 function s.filter(c,e,tp) return c:IsCode(39765958) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE) end function s.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,s.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) if #g>0 and Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) then local ge=Duel.GetMatchingGroup(Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,nil) local tc=ge:GetFirst() while tc do local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_DISABLE) e1:SetReset(RESET_EVENT|RESETS_STANDARD) tc:RegisterEffect(e1) local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_DISABLE_EFFECT) e2:SetReset(RESET_EVENT|RESETS_STANDARD) tc:RegisterEffect(e2) tc=ge:GetNext() end end end
0
0.862837
1
0.862837
game-dev
MEDIA
0.993043
game-dev
0.907634
1
0.907634
simdsoft/yasio
7,111
1k/extensions.ps1
# The System.Version compare not relex: [Version]'1.0' -eq [Version]'1.0.0' == false # So provide a spec VersionEx make [VersionEx]'1.0' -eq [VersionEx]'1.0.0' == true available if (-not ([System.Management.Automation.PSTypeName]'System.VersionEx').Type) { $code_str = @" namespace System { public sealed class VersionEx : ICloneable, IComparable { int _Major = 0; int _Minor = 0; int _Build = 0; int _Revision = 0; public int Minor { get { return _Major; } } public int Major { get { return _Minor; } } public int Build { get { return _Build; } } public int Revision { get { return _Revision; } } int DefaultFormatFieldCount { get { return (_Build > 0 || _Revision > 0) ? (_Revision > 0 ? 4 : 3) : 2; } } public VersionEx() { } public VersionEx(string version) { var v = Parse(version); _Major = v.Major; _Minor = v.Minor; _Build = v.Build; _Revision = v.Revision; } public VersionEx(System.Version version) { _Major = version.Major; _Minor = version.Minor; _Build = Math.Max(version.Build, 0); _Revision = Math.Max(version.Revision, 0); } public VersionEx(int major, int minor, int build, int revision) { _Major = major; _Minor = minor; _Build = build; _Revision = revision; } public static VersionEx Parse(string input) { var versionNums = input.Split('.'); int major = 0; int minor = 0; int build = 0; int revision = 0; for (int i = 0; i < versionNums.Length; ++i) { switch (i) { case 0: major = int.Parse(versionNums[i]); break; case 1: minor = int.Parse(versionNums[i]); break; case 2: build = int.Parse(versionNums[i]); break; case 3: revision = int.Parse(versionNums[i]); break; } } return new VersionEx(major, minor, build, revision); } public static bool TryParse(string input, out VersionEx result) { try { result = VersionEx.Parse(input); return true; } catch (Exception) { result = null; return false; } } public object Clone() { return new VersionEx(Major, Minor, Build, Revision); } public int CompareTo(object obj) { if (obj is VersionEx) { return CompareTo((VersionEx)obj); } else if (obj is Version) { var rhs = (Version)obj; return _Major != rhs.Major ? (_Major > rhs.Major ? 1 : -1) : _Minor != rhs.Minor ? (_Minor > rhs.Minor ? 1 : -1) : _Build != rhs.Build ? (_Build > rhs.Build ? 1 : -1) : _Revision != rhs.Revision ? (_Revision > rhs.Revision ? 1 : -1) : 0; } else return 1; } public int CompareTo(VersionEx obj) { return ReferenceEquals(obj, this) ? 0 : ReferenceEquals(obj, null) ? 1 : _Major != obj._Major ? (_Major > obj._Major ? 1 : -1) : _Minor != obj._Minor ? (_Minor > obj._Minor ? 1 : -1) : _Build != obj._Build ? (_Build > obj._Build ? 1 : -1) : _Revision != obj._Revision ? (_Revision > obj._Revision ? 1 : -1) : 0; } public bool Equals(VersionEx obj) { return CompareTo(obj) == 0; } public override bool Equals(object obj) { return CompareTo(obj) == 0; } public override string ToString() { return ToString(DefaultFormatFieldCount); } public string ToString(int fieldCount) { switch (fieldCount) { case 2: return string.Format("{0}.{1}", _Major, _Minor); case 3: return string.Format("{0}.{1}.{2}", _Major, _Minor, _Build); case 4: return string.Format("{0}.{1}.{2}.{3}", _Major, _Minor, _Build, _Revision); default: return "0.0.0.0"; } } public override int GetHashCode() { // Let's assume that most version numbers will be pretty small and just // OR some lower order bits together. int accumulator = 0; accumulator |= (_Major & 0x0000000F) << 28; accumulator |= (_Minor & 0x000000FF) << 20; accumulator |= (_Build & 0x000000FF) << 12; accumulator |= (_Revision & 0x00000FFF); return accumulator; } public static bool operator ==(VersionEx v1, VersionEx v2) { return v1.Equals(v2); } public static bool operator !=(VersionEx v1, VersionEx v2) { return !v1.Equals(v2); } public static bool operator <(VersionEx v1, VersionEx v2) { return v1.CompareTo(v2) < 0; } public static bool operator >(VersionEx v1, VersionEx v2) { return v1.CompareTo(v2) > 0; } public static bool operator <=(VersionEx v1, VersionEx v2) { return v1.CompareTo(v2) <= 0; } public static bool operator >=(VersionEx v1, VersionEx v2) { return v1.CompareTo(v2) >= 0; } } public static class ExtensionMethods { public static string TrimLast(this Management.Automation.PSObject thiz, string separator) { var str = thiz.BaseObject as string; var index = str.LastIndexOf(separator); if (index != -1) return str.Substring(0, index); return str; } } } "@ Add-Type -TypeDefinition $code_str $TrimLastMethod = [ExtensionMethods].GetMethod('TrimLast') Update-TypeData -TypeName System.String -MemberName TrimLast -MemberType CodeMethod -Value $TrimLastMethod } function ConvertFrom-Props { param( [Parameter(Mandatory=$true)] $InputObject ) $props = @{} foreach($_ in $InputObject) { if ($_ -match "^#.*$") { continue } if ($_ -match "^(.+?)\s*=\s*(.*)$") { $key = $matches[1].Trim() $value = $matches[2].Trim() $props[$key] = $value } } return $props }
0
0.778862
1
0.778862
game-dev
MEDIA
0.321561
game-dev
0.954392
1
0.954392
mini2Dx/mini2Dx
3,443
core/src/main/java/org/mini2Dx/core/collections/LruIntMap.java
/******************************************************************************* * Copyright 2020 See AUTHORS file * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.mini2Dx.core.collections; import org.mini2Dx.gdx.utils.IntIntMap; import org.mini2Dx.gdx.utils.IntMap; /** * Extends {@link IntMap} to implement least-recently used capabilities. * Once the specified maximum capacity is reached, * the key that has been used the least is removed from the map. * * @param <V> The value type */ public class LruIntMap<V> extends IntMap<V> { public static final int DEFAULT_MAX_CAPACITY = 128; private final int maxCapacity; private final IntIntMap accessCounter = new IntIntMap(); public LruIntMap() { super(); maxCapacity = DEFAULT_MAX_CAPACITY; } public LruIntMap(int initialCapacity) { this(initialCapacity, DEFAULT_MAX_CAPACITY); } public LruIntMap(int initialCapacity, float loadFactor) { this(initialCapacity, DEFAULT_MAX_CAPACITY, loadFactor); } public LruIntMap(IntMap<? extends V> map) { this(map, DEFAULT_MAX_CAPACITY); } public LruIntMap(int initialCapacity, int maxCapacity) { super(initialCapacity); this.maxCapacity = maxCapacity; } public LruIntMap(int initialCapacity, int maxCapacity, float loadFactor) { super(initialCapacity, loadFactor); this.maxCapacity = maxCapacity; } public LruIntMap(IntMap<? extends V> map, int maxCapacity) { super(map); this.maxCapacity = maxCapacity; } @Override public V put(int key, V value) { while(super.size >= maxCapacity) { purge(); } final V result = super.put(key, value); accessCounter.getAndIncrement(key, -1, 1); return result; } @Override public void putAll(IntMap<? extends V> map) { while(super.size >= maxCapacity) { purge(); } super.putAll(map); } @Override public V get(int key) { final V result = super.get(key); accessCounter.getAndIncrement(key, 0, 1); return result; } @Override public V get(int key, V defaultValue) { final V result = super.get(key, defaultValue); accessCounter.getAndIncrement(key, 0, 1); return result; } @Override public V remove(int key) { final V result = super.remove(key); accessCounter.remove(key, -1); return result; } @Override public void clear() { super.clear(); accessCounter.clear(); } private void purge() { int smallestKey = 0; int smallestCount = Integer.MAX_VALUE; IntIntMap.Keys keys = accessCounter.keys(); while(keys.hasNext) { final int key = keys.next(); final int count = accessCounter.get(key, 0); if(count < smallestCount) { smallestKey = key; smallestCount = count; } } remove(smallestKey); } /** * Returns the maximum number of keys that can be stored in the {@link LruIntMap} * @return Defaults to 128 */ public int getMaxCapacity() { return maxCapacity; } }
0
0.841389
1
0.841389
game-dev
MEDIA
0.361545
game-dev
0.954588
1
0.954588
stonne-simulator/stonne
43,564
pytorch-frontend/third_party/protobuf/src/google/protobuf/map.h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This file defines the map container and its helpers to support protobuf maps. // // The Map and MapIterator types are provided by this header file. // Please avoid using other types defined here, unless they are public // types within Map or MapIterator, such as Map::value_type. #ifndef GOOGLE_PROTOBUF_MAP_H__ #define GOOGLE_PROTOBUF_MAP_H__ #include <initializer_list> #include <iterator> #include <limits> // To support Visual Studio 2008 #include <set> #include <utility> #include <google/protobuf/stubs/common.h> #include <google/protobuf/arena.h> #include <google/protobuf/generated_enum_util.h> #include <google/protobuf/map_type_handler.h> #include <google/protobuf/stubs/hash.h> #ifdef SWIG #error "You cannot SWIG proto headers" #endif #include <google/protobuf/port_def.inc> namespace google { namespace protobuf { template <typename Key, typename T> class Map; class MapIterator; template <typename Enum> struct is_proto_enum; namespace internal { template <typename Derived, typename Key, typename T, WireFormatLite::FieldType key_wire_type, WireFormatLite::FieldType value_wire_type, int default_enum_value> class MapFieldLite; template <typename Derived, typename Key, typename T, WireFormatLite::FieldType key_wire_type, WireFormatLite::FieldType value_wire_type, int default_enum_value> class MapField; template <typename Key, typename T> class TypeDefinedMapFieldBase; class DynamicMapField; class GeneratedMessageReflection; } // namespace internal // This is the class for Map's internal value_type. Instead of using // std::pair as value_type, we use this class which provides us more control of // its process of construction and destruction. template <typename Key, typename T> class MapPair { public: typedef const Key first_type; typedef T second_type; MapPair(const Key& other_first, const T& other_second) : first(other_first), second(other_second) {} explicit MapPair(const Key& other_first) : first(other_first), second() {} MapPair(const MapPair& other) : first(other.first), second(other.second) {} ~MapPair() {} // Implicitly convertible to std::pair of compatible types. template <typename T1, typename T2> operator std::pair<T1, T2>() const { return std::pair<T1, T2>(first, second); } const Key first; T second; private: friend class Arena; friend class Map<Key, T>; }; // Map is an associative container type used to store protobuf map // fields. Each Map instance may or may not use a different hash function, a // different iteration order, and so on. E.g., please don't examine // implementation details to decide if the following would work: // Map<int, int> m0, m1; // m0[0] = m1[0] = m0[1] = m1[1] = 0; // assert(m0.begin()->first == m1.begin()->first); // Bug! // // Map's interface is similar to std::unordered_map, except that Map is not // designed to play well with exceptions. template <typename Key, typename T> class Map { public: typedef Key key_type; typedef T mapped_type; typedef MapPair<Key, T> value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef size_t size_type; typedef hash<Key> hasher; Map() : arena_(NULL), default_enum_value_(0) { Init(); } explicit Map(Arena* arena) : arena_(arena), default_enum_value_(0) { Init(); } Map(const Map& other) : arena_(NULL), default_enum_value_(other.default_enum_value_) { Init(); insert(other.begin(), other.end()); } Map(Map&& other) noexcept : Map() { if (other.arena_) { *this = other; } else { swap(other); } } Map& operator=(Map&& other) noexcept { if (this != &other) { if (arena_ != other.arena_) { *this = other; } else { swap(other); } } return *this; } template <class InputIt> Map(const InputIt& first, const InputIt& last) : arena_(NULL), default_enum_value_(0) { Init(); insert(first, last); } ~Map() { clear(); if (arena_ == NULL) { delete elements_; } } private: void Init() { elements_ = Arena::Create<InnerMap>(arena_, 0u, hasher(), Allocator(arena_)); } // re-implement std::allocator to use arena allocator for memory allocation. // Used for Map implementation. Users should not use this class // directly. template <typename U> class MapAllocator { public: typedef U value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; MapAllocator() : arena_(NULL) {} explicit MapAllocator(Arena* arena) : arena_(arena) {} template <typename X> MapAllocator(const MapAllocator<X>& allocator) : arena_(allocator.arena()) {} pointer allocate(size_type n, const void* /* hint */ = 0) { // If arena is not given, malloc needs to be called which doesn't // construct element object. if (arena_ == NULL) { return static_cast<pointer>(::operator new(n * sizeof(value_type))); } else { return reinterpret_cast<pointer>( Arena::CreateArray<uint8>(arena_, n * sizeof(value_type))); } } void deallocate(pointer p, size_type n) { if (arena_ == NULL) { #if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation) ::operator delete(p, n * sizeof(value_type)); #else (void)n; ::operator delete(p); #endif } } #if __cplusplus >= 201103L && !defined(GOOGLE_PROTOBUF_OS_APPLE) && \ !defined(GOOGLE_PROTOBUF_OS_NACL) && \ !defined(GOOGLE_PROTOBUF_OS_EMSCRIPTEN) template <class NodeType, class... Args> void construct(NodeType* p, Args&&... args) { // Clang 3.6 doesn't compile static casting to void* directly. (Issue // #1266) According C++ standard 5.2.9/1: "The static_cast operator shall // not cast away constness". So first the maybe const pointer is casted to // const void* and after the const void* is const casted. new (const_cast<void*>(static_cast<const void*>(p))) NodeType(std::forward<Args>(args)...); } template <class NodeType> void destroy(NodeType* p) { p->~NodeType(); } #else void construct(pointer p, const_reference t) { new (p) value_type(t); } void destroy(pointer p) { p->~value_type(); } #endif template <typename X> struct rebind { typedef MapAllocator<X> other; }; template <typename X> bool operator==(const MapAllocator<X>& other) const { return arena_ == other.arena_; } template <typename X> bool operator!=(const MapAllocator<X>& other) const { return arena_ != other.arena_; } // To support Visual Studio 2008 size_type max_size() const { // parentheses around (std::...:max) prevents macro warning of max() return (std::numeric_limits<size_type>::max)(); } // To support gcc-4.4, which does not properly // support templated friend classes Arena* arena() const { return arena_; } private: typedef void DestructorSkippable_; Arena* const arena_; }; // InnerMap's key type is Key and its value type is value_type*. We use a // custom class here and for Node, below, to ensure that k_ is at offset 0, // allowing safe conversion from pointer to Node to pointer to Key, and vice // versa when appropriate. class KeyValuePair { public: KeyValuePair(const Key& k, value_type* v) : k_(k), v_(v) {} const Key& key() const { return k_; } Key& key() { return k_; } value_type* value() const { return v_; } value_type*& value() { return v_; } private: Key k_; value_type* v_; }; typedef MapAllocator<KeyValuePair> Allocator; // InnerMap is a generic hash-based map. It doesn't contain any // protocol-buffer-specific logic. It is a chaining hash map with the // additional feature that some buckets can be converted to use an ordered // container. This ensures O(lg n) bounds on find, insert, and erase, while // avoiding the overheads of ordered containers most of the time. // // The implementation doesn't need the full generality of unordered_map, // and it doesn't have it. More bells and whistles can be added as needed. // Some implementation details: // 1. The hash function has type hasher and the equality function // equal_to<Key>. We inherit from hasher to save space // (empty-base-class optimization). // 2. The number of buckets is a power of two. // 3. Buckets are converted to trees in pairs: if we convert bucket b then // buckets b and b^1 will share a tree. Invariant: buckets b and b^1 have // the same non-NULL value iff they are sharing a tree. (An alternative // implementation strategy would be to have a tag bit per bucket.) // 4. As is typical for hash_map and such, the Keys and Values are always // stored in linked list nodes. Pointers to elements are never invalidated // until the element is deleted. // 5. The trees' payload type is pointer to linked-list node. Tree-converting // a bucket doesn't copy Key-Value pairs. // 6. Once we've tree-converted a bucket, it is never converted back. However, // the items a tree contains may wind up assigned to trees or lists upon a // rehash. // 7. The code requires no C++ features from C++11 or later. // 8. Mutations to a map do not invalidate the map's iterators, pointers to // elements, or references to elements. // 9. Except for erase(iterator), any non-const method can reorder iterators. class InnerMap : private hasher { public: typedef value_type* Value; InnerMap(size_type n, hasher h, Allocator alloc) : hasher(h), num_elements_(0), seed_(Seed()), table_(NULL), alloc_(alloc) { n = TableSize(n); table_ = CreateEmptyTable(n); num_buckets_ = index_of_first_non_null_ = n; } ~InnerMap() { if (table_ != NULL) { clear(); Dealloc<void*>(table_, num_buckets_); } } private: enum { kMinTableSize = 8 }; // Linked-list nodes, as one would expect for a chaining hash table. struct Node { KeyValuePair kv; Node* next; }; // This is safe only if the given pointer is known to point to a Key that is // part of a Node. static Node* NodePtrFromKeyPtr(Key* k) { return reinterpret_cast<Node*>(k); } static Key* KeyPtrFromNodePtr(Node* node) { return &node->kv.key(); } // Trees. The payload type is pointer to Key, so that we can query the tree // with Keys that are not in any particular data structure. When we insert, // though, the pointer is always pointing to a Key that is inside a Node. struct KeyCompare { bool operator()(const Key* n0, const Key* n1) const { return *n0 < *n1; } }; typedef typename Allocator::template rebind<Key*>::other KeyPtrAllocator; typedef std::set<Key*, KeyCompare, KeyPtrAllocator> Tree; typedef typename Tree::iterator TreeIterator; // iterator and const_iterator are instantiations of iterator_base. template <typename KeyValueType> struct iterator_base { typedef KeyValueType& reference; typedef KeyValueType* pointer; // Invariants: // node_ is always correct. This is handy because the most common // operations are operator* and operator-> and they only use node_. // When node_ is set to a non-NULL value, all the other non-const fields // are updated to be correct also, but those fields can become stale // if the underlying map is modified. When those fields are needed they // are rechecked, and updated if necessary. iterator_base() : node_(NULL), m_(NULL), bucket_index_(0) {} explicit iterator_base(const InnerMap* m) : m_(m) { SearchFrom(m->index_of_first_non_null_); } // Any iterator_base can convert to any other. This is overkill, and we // rely on the enclosing class to use it wisely. The standard "iterator // can convert to const_iterator" is OK but the reverse direction is not. template <typename U> explicit iterator_base(const iterator_base<U>& it) : node_(it.node_), m_(it.m_), bucket_index_(it.bucket_index_) {} iterator_base(Node* n, const InnerMap* m, size_type index) : node_(n), m_(m), bucket_index_(index) {} iterator_base(TreeIterator tree_it, const InnerMap* m, size_type index) : node_(NodePtrFromKeyPtr(*tree_it)), m_(m), bucket_index_(index) { // Invariant: iterators that use buckets with trees have an even // bucket_index_. GOOGLE_DCHECK_EQ(bucket_index_ % 2, 0u); } // Advance through buckets, looking for the first that isn't empty. // If nothing non-empty is found then leave node_ == NULL. void SearchFrom(size_type start_bucket) { GOOGLE_DCHECK(m_->index_of_first_non_null_ == m_->num_buckets_ || m_->table_[m_->index_of_first_non_null_] != NULL); node_ = NULL; for (bucket_index_ = start_bucket; bucket_index_ < m_->num_buckets_; bucket_index_++) { if (m_->TableEntryIsNonEmptyList(bucket_index_)) { node_ = static_cast<Node*>(m_->table_[bucket_index_]); break; } else if (m_->TableEntryIsTree(bucket_index_)) { Tree* tree = static_cast<Tree*>(m_->table_[bucket_index_]); GOOGLE_DCHECK(!tree->empty()); node_ = NodePtrFromKeyPtr(*tree->begin()); break; } } } reference operator*() const { return node_->kv; } pointer operator->() const { return &(operator*()); } friend bool operator==(const iterator_base& a, const iterator_base& b) { return a.node_ == b.node_; } friend bool operator!=(const iterator_base& a, const iterator_base& b) { return a.node_ != b.node_; } iterator_base& operator++() { if (node_->next == NULL) { TreeIterator tree_it; const bool is_list = revalidate_if_necessary(&tree_it); if (is_list) { SearchFrom(bucket_index_ + 1); } else { GOOGLE_DCHECK_EQ(bucket_index_ & 1, 0u); Tree* tree = static_cast<Tree*>(m_->table_[bucket_index_]); if (++tree_it == tree->end()) { SearchFrom(bucket_index_ + 2); } else { node_ = NodePtrFromKeyPtr(*tree_it); } } } else { node_ = node_->next; } return *this; } iterator_base operator++(int /* unused */) { iterator_base tmp = *this; ++*this; return tmp; } // Assumes node_ and m_ are correct and non-NULL, but other fields may be // stale. Fix them as needed. Then return true iff node_ points to a // Node in a list. If false is returned then *it is modified to be // a valid iterator for node_. bool revalidate_if_necessary(TreeIterator* it) { GOOGLE_DCHECK(node_ != NULL && m_ != NULL); // Force bucket_index_ to be in range. bucket_index_ &= (m_->num_buckets_ - 1); // Common case: the bucket we think is relevant points to node_. if (m_->table_[bucket_index_] == static_cast<void*>(node_)) return true; // Less common: the bucket is a linked list with node_ somewhere in it, // but not at the head. if (m_->TableEntryIsNonEmptyList(bucket_index_)) { Node* l = static_cast<Node*>(m_->table_[bucket_index_]); while ((l = l->next) != NULL) { if (l == node_) { return true; } } } // Well, bucket_index_ still might be correct, but probably // not. Revalidate just to be sure. This case is rare enough that we // don't worry about potential optimizations, such as having a custom // find-like method that compares Node* instead of const Key&. iterator_base i(m_->find(*KeyPtrFromNodePtr(node_), it)); bucket_index_ = i.bucket_index_; return m_->TableEntryIsList(bucket_index_); } Node* node_; const InnerMap* m_; size_type bucket_index_; }; public: typedef iterator_base<KeyValuePair> iterator; typedef iterator_base<const KeyValuePair> const_iterator; iterator begin() { return iterator(this); } iterator end() { return iterator(); } const_iterator begin() const { return const_iterator(this); } const_iterator end() const { return const_iterator(); } void clear() { for (size_type b = 0; b < num_buckets_; b++) { if (TableEntryIsNonEmptyList(b)) { Node* node = static_cast<Node*>(table_[b]); table_[b] = NULL; do { Node* next = node->next; DestroyNode(node); node = next; } while (node != NULL); } else if (TableEntryIsTree(b)) { Tree* tree = static_cast<Tree*>(table_[b]); GOOGLE_DCHECK(table_[b] == table_[b + 1] && (b & 1) == 0); table_[b] = table_[b + 1] = NULL; typename Tree::iterator tree_it = tree->begin(); do { Node* node = NodePtrFromKeyPtr(*tree_it); typename Tree::iterator next = tree_it; ++next; tree->erase(tree_it); DestroyNode(node); tree_it = next; } while (tree_it != tree->end()); DestroyTree(tree); b++; } } num_elements_ = 0; index_of_first_non_null_ = num_buckets_; } const hasher& hash_function() const { return *this; } static size_type max_size() { return static_cast<size_type>(1) << (sizeof(void**) >= 8 ? 60 : 28); } size_type size() const { return num_elements_; } bool empty() const { return size() == 0; } iterator find(const Key& k) { return iterator(FindHelper(k).first); } const_iterator find(const Key& k) const { return find(k, NULL); } bool contains(const Key& k) const { return find(k) != end(); } // In traditional C++ style, this performs "insert if not present." std::pair<iterator, bool> insert(const KeyValuePair& kv) { std::pair<const_iterator, size_type> p = FindHelper(kv.key()); // Case 1: key was already present. if (p.first.node_ != NULL) return std::make_pair(iterator(p.first), false); // Case 2: insert. if (ResizeIfLoadIsOutOfRange(num_elements_ + 1)) { p = FindHelper(kv.key()); } const size_type b = p.second; // bucket number Node* node = Alloc<Node>(1); alloc_.construct(&node->kv, kv); iterator result = InsertUnique(b, node); ++num_elements_; return std::make_pair(result, true); } // The same, but if an insertion is necessary then the value portion of the // inserted key-value pair is left uninitialized. std::pair<iterator, bool> insert(const Key& k) { std::pair<const_iterator, size_type> p = FindHelper(k); // Case 1: key was already present. if (p.first.node_ != NULL) return std::make_pair(iterator(p.first), false); // Case 2: insert. if (ResizeIfLoadIsOutOfRange(num_elements_ + 1)) { p = FindHelper(k); } const size_type b = p.second; // bucket number Node* node = Alloc<Node>(1); typedef typename Allocator::template rebind<Key>::other KeyAllocator; KeyAllocator(alloc_).construct(&node->kv.key(), k); iterator result = InsertUnique(b, node); ++num_elements_; return std::make_pair(result, true); } Value& operator[](const Key& k) { KeyValuePair kv(k, Value()); return insert(kv).first->value(); } void erase(iterator it) { GOOGLE_DCHECK_EQ(it.m_, this); typename Tree::iterator tree_it; const bool is_list = it.revalidate_if_necessary(&tree_it); size_type b = it.bucket_index_; Node* const item = it.node_; if (is_list) { GOOGLE_DCHECK(TableEntryIsNonEmptyList(b)); Node* head = static_cast<Node*>(table_[b]); head = EraseFromLinkedList(item, head); table_[b] = static_cast<void*>(head); } else { GOOGLE_DCHECK(TableEntryIsTree(b)); Tree* tree = static_cast<Tree*>(table_[b]); tree->erase(*tree_it); if (tree->empty()) { // Force b to be the minimum of b and b ^ 1. This is important // only because we want index_of_first_non_null_ to be correct. b &= ~static_cast<size_type>(1); DestroyTree(tree); table_[b] = table_[b + 1] = NULL; } } DestroyNode(item); --num_elements_; if (PROTOBUF_PREDICT_FALSE(b == index_of_first_non_null_)) { while (index_of_first_non_null_ < num_buckets_ && table_[index_of_first_non_null_] == NULL) { ++index_of_first_non_null_; } } } private: const_iterator find(const Key& k, TreeIterator* it) const { return FindHelper(k, it).first; } std::pair<const_iterator, size_type> FindHelper(const Key& k) const { return FindHelper(k, NULL); } std::pair<const_iterator, size_type> FindHelper(const Key& k, TreeIterator* it) const { size_type b = BucketNumber(k); if (TableEntryIsNonEmptyList(b)) { Node* node = static_cast<Node*>(table_[b]); do { if (IsMatch(*KeyPtrFromNodePtr(node), k)) { return std::make_pair(const_iterator(node, this, b), b); } else { node = node->next; } } while (node != NULL); } else if (TableEntryIsTree(b)) { GOOGLE_DCHECK_EQ(table_[b], table_[b ^ 1]); b &= ~static_cast<size_t>(1); Tree* tree = static_cast<Tree*>(table_[b]); Key* key = const_cast<Key*>(&k); typename Tree::iterator tree_it = tree->find(key); if (tree_it != tree->end()) { if (it != NULL) *it = tree_it; return std::make_pair(const_iterator(tree_it, this, b), b); } } return std::make_pair(end(), b); } // Insert the given Node in bucket b. If that would make bucket b too big, // and bucket b is not a tree, create a tree for buckets b and b^1 to share. // Requires count(*KeyPtrFromNodePtr(node)) == 0 and that b is the correct // bucket. num_elements_ is not modified. iterator InsertUnique(size_type b, Node* node) { GOOGLE_DCHECK(index_of_first_non_null_ == num_buckets_ || table_[index_of_first_non_null_] != NULL); // In practice, the code that led to this point may have already // determined whether we are inserting into an empty list, a short list, // or whatever. But it's probably cheap enough to recompute that here; // it's likely that we're inserting into an empty or short list. iterator result; GOOGLE_DCHECK(find(*KeyPtrFromNodePtr(node)) == end()); if (TableEntryIsEmpty(b)) { result = InsertUniqueInList(b, node); } else if (TableEntryIsNonEmptyList(b)) { if (PROTOBUF_PREDICT_FALSE(TableEntryIsTooLong(b))) { TreeConvert(b); result = InsertUniqueInTree(b, node); GOOGLE_DCHECK_EQ(result.bucket_index_, b & ~static_cast<size_type>(1)); } else { // Insert into a pre-existing list. This case cannot modify // index_of_first_non_null_, so we skip the code to update it. return InsertUniqueInList(b, node); } } else { // Insert into a pre-existing tree. This case cannot modify // index_of_first_non_null_, so we skip the code to update it. return InsertUniqueInTree(b, node); } // parentheses around (std::min) prevents macro expansion of min(...) index_of_first_non_null_ = (std::min)(index_of_first_non_null_, result.bucket_index_); return result; } // Helper for InsertUnique. Handles the case where bucket b is a // not-too-long linked list. iterator InsertUniqueInList(size_type b, Node* node) { node->next = static_cast<Node*>(table_[b]); table_[b] = static_cast<void*>(node); return iterator(node, this, b); } // Helper for InsertUnique. Handles the case where bucket b points to a // Tree. iterator InsertUniqueInTree(size_type b, Node* node) { GOOGLE_DCHECK_EQ(table_[b], table_[b ^ 1]); // Maintain the invariant that node->next is NULL for all Nodes in Trees. node->next = NULL; return iterator( static_cast<Tree*>(table_[b])->insert(KeyPtrFromNodePtr(node)).first, this, b & ~static_cast<size_t>(1)); } // Returns whether it did resize. Currently this is only used when // num_elements_ increases, though it could be used in other situations. // It checks for load too low as well as load too high: because any number // of erases can occur between inserts, the load could be as low as 0 here. // Resizing to a lower size is not always helpful, but failing to do so can // destroy the expected big-O bounds for some operations. By having the // policy that sometimes we resize down as well as up, clients can easily // keep O(size()) = O(number of buckets) if they want that. bool ResizeIfLoadIsOutOfRange(size_type new_size) { const size_type kMaxMapLoadTimes16 = 12; // controls RAM vs CPU tradeoff const size_type hi_cutoff = num_buckets_ * kMaxMapLoadTimes16 / 16; const size_type lo_cutoff = hi_cutoff / 4; // We don't care how many elements are in trees. If a lot are, // we may resize even though there are many empty buckets. In // practice, this seems fine. if (PROTOBUF_PREDICT_FALSE(new_size >= hi_cutoff)) { if (num_buckets_ <= max_size() / 2) { Resize(num_buckets_ * 2); return true; } } else if (PROTOBUF_PREDICT_FALSE(new_size <= lo_cutoff && num_buckets_ > kMinTableSize)) { size_type lg2_of_size_reduction_factor = 1; // It's possible we want to shrink a lot here... size() could even be 0. // So, estimate how much to shrink by making sure we don't shrink so // much that we would need to grow the table after a few inserts. const size_type hypothetical_size = new_size * 5 / 4 + 1; while ((hypothetical_size << lg2_of_size_reduction_factor) < hi_cutoff) { ++lg2_of_size_reduction_factor; } size_type new_num_buckets = std::max<size_type>( kMinTableSize, num_buckets_ >> lg2_of_size_reduction_factor); if (new_num_buckets != num_buckets_) { Resize(new_num_buckets); return true; } } return false; } // Resize to the given number of buckets. void Resize(size_t new_num_buckets) { GOOGLE_DCHECK_GE(new_num_buckets, kMinTableSize); void** const old_table = table_; const size_type old_table_size = num_buckets_; num_buckets_ = new_num_buckets; table_ = CreateEmptyTable(num_buckets_); const size_type start = index_of_first_non_null_; index_of_first_non_null_ = num_buckets_; for (size_type i = start; i < old_table_size; i++) { if (TableEntryIsNonEmptyList(old_table, i)) { TransferList(old_table, i); } else if (TableEntryIsTree(old_table, i)) { TransferTree(old_table, i++); } } Dealloc<void*>(old_table, old_table_size); } void TransferList(void* const* table, size_type index) { Node* node = static_cast<Node*>(table[index]); do { Node* next = node->next; InsertUnique(BucketNumber(*KeyPtrFromNodePtr(node)), node); node = next; } while (node != NULL); } void TransferTree(void* const* table, size_type index) { Tree* tree = static_cast<Tree*>(table[index]); typename Tree::iterator tree_it = tree->begin(); do { Node* node = NodePtrFromKeyPtr(*tree_it); InsertUnique(BucketNumber(**tree_it), node); } while (++tree_it != tree->end()); DestroyTree(tree); } Node* EraseFromLinkedList(Node* item, Node* head) { if (head == item) { return head->next; } else { head->next = EraseFromLinkedList(item, head->next); return head; } } bool TableEntryIsEmpty(size_type b) const { return TableEntryIsEmpty(table_, b); } bool TableEntryIsNonEmptyList(size_type b) const { return TableEntryIsNonEmptyList(table_, b); } bool TableEntryIsTree(size_type b) const { return TableEntryIsTree(table_, b); } bool TableEntryIsList(size_type b) const { return TableEntryIsList(table_, b); } static bool TableEntryIsEmpty(void* const* table, size_type b) { return table[b] == NULL; } static bool TableEntryIsNonEmptyList(void* const* table, size_type b) { return table[b] != NULL && table[b] != table[b ^ 1]; } static bool TableEntryIsTree(void* const* table, size_type b) { return !TableEntryIsEmpty(table, b) && !TableEntryIsNonEmptyList(table, b); } static bool TableEntryIsList(void* const* table, size_type b) { return !TableEntryIsTree(table, b); } void TreeConvert(size_type b) { GOOGLE_DCHECK(!TableEntryIsTree(b) && !TableEntryIsTree(b ^ 1)); typename Allocator::template rebind<Tree>::other tree_allocator(alloc_); Tree* tree = tree_allocator.allocate(1); // We want to use the three-arg form of construct, if it exists, but we // create a temporary and use the two-arg construct that's known to exist. // It's clunky, but the compiler should be able to generate more-or-less // the same code. tree_allocator.construct(tree, Tree(KeyCompare(), KeyPtrAllocator(alloc_))); // Now the tree is ready to use. size_type count = CopyListToTree(b, tree) + CopyListToTree(b ^ 1, tree); GOOGLE_DCHECK_EQ(count, tree->size()); table_[b] = table_[b ^ 1] = static_cast<void*>(tree); } // Copy a linked list in the given bucket to a tree. // Returns the number of things it copied. size_type CopyListToTree(size_type b, Tree* tree) { size_type count = 0; Node* node = static_cast<Node*>(table_[b]); while (node != NULL) { tree->insert(KeyPtrFromNodePtr(node)); ++count; Node* next = node->next; node->next = NULL; node = next; } return count; } // Return whether table_[b] is a linked list that seems awfully long. // Requires table_[b] to point to a non-empty linked list. bool TableEntryIsTooLong(size_type b) { const size_type kMaxLength = 8; size_type count = 0; Node* node = static_cast<Node*>(table_[b]); do { ++count; node = node->next; } while (node != NULL); // Invariant: no linked list ever is more than kMaxLength in length. GOOGLE_DCHECK_LE(count, kMaxLength); return count >= kMaxLength; } size_type BucketNumber(const Key& k) const { // We inherit from hasher, so one-arg operator() provides a hash function. size_type h = (*const_cast<InnerMap*>(this))(k); return (h + seed_) & (num_buckets_ - 1); } bool IsMatch(const Key& k0, const Key& k1) const { return std::equal_to<Key>()(k0, k1); } // Return a power of two no less than max(kMinTableSize, n). // Assumes either n < kMinTableSize or n is a power of two. size_type TableSize(size_type n) { return n < static_cast<size_type>(kMinTableSize) ? static_cast<size_type>(kMinTableSize) : n; } // Use alloc_ to allocate an array of n objects of type U. template <typename U> U* Alloc(size_type n) { typedef typename Allocator::template rebind<U>::other alloc_type; return alloc_type(alloc_).allocate(n); } // Use alloc_ to deallocate an array of n objects of type U. template <typename U> void Dealloc(U* t, size_type n) { typedef typename Allocator::template rebind<U>::other alloc_type; alloc_type(alloc_).deallocate(t, n); } void DestroyNode(Node* node) { alloc_.destroy(&node->kv); Dealloc<Node>(node, 1); } void DestroyTree(Tree* tree) { typename Allocator::template rebind<Tree>::other tree_allocator(alloc_); tree_allocator.destroy(tree); tree_allocator.deallocate(tree, 1); } void** CreateEmptyTable(size_type n) { GOOGLE_DCHECK(n >= kMinTableSize); GOOGLE_DCHECK_EQ(n & (n - 1), 0); void** result = Alloc<void*>(n); memset(result, 0, n * sizeof(result[0])); return result; } // Return a randomish value. size_type Seed() const { size_type s = static_cast<size_type>(reinterpret_cast<uintptr_t>(this)); #if defined(__x86_64__) && defined(__GNUC__) && \ !defined(GOOGLE_PROTOBUF_NO_RDTSC) uint32 hi, lo; asm("rdtsc" : "=a"(lo), "=d"(hi)); s += ((static_cast<uint64>(hi) << 32) | lo); #endif return s; } size_type num_elements_; size_type num_buckets_; size_type seed_; size_type index_of_first_non_null_; void** table_; // an array with num_buckets_ entries Allocator alloc_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(InnerMap); }; // end of class InnerMap public: // Iterators class const_iterator { typedef typename InnerMap::const_iterator InnerIt; public: typedef std::forward_iterator_tag iterator_category; typedef typename Map::value_type value_type; typedef ptrdiff_t difference_type; typedef const value_type* pointer; typedef const value_type& reference; const_iterator() {} explicit const_iterator(const InnerIt& it) : it_(it) {} const_reference operator*() const { return *it_->value(); } const_pointer operator->() const { return &(operator*()); } const_iterator& operator++() { ++it_; return *this; } const_iterator operator++(int) { return const_iterator(it_++); } friend bool operator==(const const_iterator& a, const const_iterator& b) { return a.it_ == b.it_; } friend bool operator!=(const const_iterator& a, const const_iterator& b) { return !(a == b); } private: InnerIt it_; }; class iterator { typedef typename InnerMap::iterator InnerIt; public: typedef std::forward_iterator_tag iterator_category; typedef typename Map::value_type value_type; typedef ptrdiff_t difference_type; typedef value_type* pointer; typedef value_type& reference; iterator() {} explicit iterator(const InnerIt& it) : it_(it) {} reference operator*() const { return *it_->value(); } pointer operator->() const { return &(operator*()); } iterator& operator++() { ++it_; return *this; } iterator operator++(int) { return iterator(it_++); } // Allow implicit conversion to const_iterator. operator const_iterator() const { return const_iterator(typename InnerMap::const_iterator(it_)); } friend bool operator==(const iterator& a, const iterator& b) { return a.it_ == b.it_; } friend bool operator!=(const iterator& a, const iterator& b) { return !(a == b); } private: friend class Map; InnerIt it_; }; iterator begin() { return iterator(elements_->begin()); } iterator end() { return iterator(elements_->end()); } const_iterator begin() const { return const_iterator(iterator(elements_->begin())); } const_iterator end() const { return const_iterator(iterator(elements_->end())); } const_iterator cbegin() const { return begin(); } const_iterator cend() const { return end(); } // Capacity size_type size() const { return elements_->size(); } bool empty() const { return size() == 0; } // Element access T& operator[](const key_type& key) { value_type** value = &(*elements_)[key]; if (*value == NULL) { *value = CreateValueTypeInternal(key); internal::MapValueInitializer<is_proto_enum<T>::value, T>::Initialize( (*value)->second, default_enum_value_); } return (*value)->second; } const T& at(const key_type& key) const { const_iterator it = find(key); GOOGLE_CHECK(it != end()) << "key not found: " << key; return it->second; } T& at(const key_type& key) { iterator it = find(key); GOOGLE_CHECK(it != end()) << "key not found: " << key; return it->second; } // Lookup size_type count(const key_type& key) const { const_iterator it = find(key); GOOGLE_DCHECK(it == end() || key == it->first); return it == end() ? 0 : 1; } const_iterator find(const key_type& key) const { return const_iterator(iterator(elements_->find(key))); } iterator find(const key_type& key) { return iterator(elements_->find(key)); } bool contains(const Key& key) const { return elements_->contains(key); } std::pair<const_iterator, const_iterator> equal_range( const key_type& key) const { const_iterator it = find(key); if (it == end()) { return std::pair<const_iterator, const_iterator>(it, it); } else { const_iterator begin = it++; return std::pair<const_iterator, const_iterator>(begin, it); } } std::pair<iterator, iterator> equal_range(const key_type& key) { iterator it = find(key); if (it == end()) { return std::pair<iterator, iterator>(it, it); } else { iterator begin = it++; return std::pair<iterator, iterator>(begin, it); } } // insert std::pair<iterator, bool> insert(const value_type& value) { std::pair<typename InnerMap::iterator, bool> p = elements_->insert(value.first); if (p.second) { p.first->value() = CreateValueTypeInternal(value); } return std::pair<iterator, bool>(iterator(p.first), p.second); } template <class InputIt> void insert(InputIt first, InputIt last) { for (InputIt it = first; it != last; ++it) { iterator exist_it = find(it->first); if (exist_it == end()) { operator[](it->first) = it->second; } } } void insert(std::initializer_list<value_type> values) { insert(values.begin(), values.end()); } // Erase and clear size_type erase(const key_type& key) { iterator it = find(key); if (it == end()) { return 0; } else { erase(it); return 1; } } iterator erase(iterator pos) { if (arena_ == NULL) delete pos.operator->(); iterator i = pos++; elements_->erase(i.it_); return pos; } void erase(iterator first, iterator last) { while (first != last) { first = erase(first); } } void clear() { erase(begin(), end()); } // Assign Map& operator=(const Map& other) { if (this != &other) { clear(); insert(other.begin(), other.end()); } return *this; } void swap(Map& other) { if (arena_ == other.arena_) { std::swap(default_enum_value_, other.default_enum_value_); std::swap(elements_, other.elements_); } else { // TODO(zuguang): optimize this. The temporary copy can be allocated // in the same arena as the other message, and the "other = copy" can // be replaced with the fast-path swap above. Map copy = *this; *this = other; other = copy; } } // Access to hasher. Currently this returns a copy, but it may // be modified to return a const reference in the future. hasher hash_function() const { return elements_->hash_function(); } private: // Set default enum value only for proto2 map field whose value is enum type. void SetDefaultEnumValue(int default_enum_value) { default_enum_value_ = default_enum_value; } value_type* CreateValueTypeInternal(const Key& key) { if (arena_ == NULL) { return new value_type(key); } else { value_type* value = reinterpret_cast<value_type*>( Arena::CreateArray<uint8>(arena_, sizeof(value_type))); Arena::CreateInArenaStorage(const_cast<Key*>(&value->first), arena_); Arena::CreateInArenaStorage(&value->second, arena_); const_cast<Key&>(value->first) = key; return value; } } value_type* CreateValueTypeInternal(const value_type& value) { if (arena_ == NULL) { return new value_type(value); } else { value_type* p = reinterpret_cast<value_type*>( Arena::CreateArray<uint8>(arena_, sizeof(value_type))); Arena::CreateInArenaStorage(const_cast<Key*>(&p->first), arena_); Arena::CreateInArenaStorage(&p->second, arena_); const_cast<Key&>(p->first) = value.first; p->second = value.second; return p; } } Arena* arena_; int default_enum_value_; InnerMap* elements_; friend class Arena; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; template <typename Derived, typename K, typename V, internal::WireFormatLite::FieldType key_wire_type, internal::WireFormatLite::FieldType value_wire_type, int default_enum_value> friend class internal::MapFieldLite; }; } // namespace protobuf } // namespace google #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_MAP_H__
0
0.995081
1
0.995081
game-dev
MEDIA
0.438365
game-dev
0.952023
1
0.952023
SimulaVR/godot-haskell
9,794
src/Godot/Core/ResourcePreloader.hs
{-# LANGUAGE DerivingStrategies, GeneralizedNewtypeDeriving, TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.ResourcePreloader (Godot.Core.ResourcePreloader._get_resources, Godot.Core.ResourcePreloader._set_resources, Godot.Core.ResourcePreloader.add_resource, Godot.Core.ResourcePreloader.get_resource, Godot.Core.ResourcePreloader.get_resource_list, Godot.Core.ResourcePreloader.has_resource, Godot.Core.ResourcePreloader.remove_resource, Godot.Core.ResourcePreloader.rename_resource) where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.Node() instance NodeProperty ResourcePreloader "resources" Array 'False where nodeProperty = (_get_resources, wrapDroppingSetter _set_resources, Nothing) {-# NOINLINE bindResourcePreloader__get_resources #-} bindResourcePreloader__get_resources :: MethodBind bindResourcePreloader__get_resources = unsafePerformIO $ withCString "ResourcePreloader" $ \ clsNamePtr -> withCString "_get_resources" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr _get_resources :: (ResourcePreloader :< cls, Object :< cls) => cls -> IO Array _get_resources cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindResourcePreloader__get_resources (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ResourcePreloader "_get_resources" '[] (IO Array) where nodeMethod = Godot.Core.ResourcePreloader._get_resources {-# NOINLINE bindResourcePreloader__set_resources #-} bindResourcePreloader__set_resources :: MethodBind bindResourcePreloader__set_resources = unsafePerformIO $ withCString "ResourcePreloader" $ \ clsNamePtr -> withCString "_set_resources" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr _set_resources :: (ResourcePreloader :< cls, Object :< cls) => cls -> Array -> IO () _set_resources cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindResourcePreloader__set_resources (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ResourcePreloader "_set_resources" '[Array] (IO ()) where nodeMethod = Godot.Core.ResourcePreloader._set_resources {-# NOINLINE bindResourcePreloader_add_resource #-} -- | Adds a resource to the preloader with the given @name@. If a resource with the given @name@ already exists, the new resource will be renamed to "@name@ N" where N is an incrementing number starting from 2. bindResourcePreloader_add_resource :: MethodBind bindResourcePreloader_add_resource = unsafePerformIO $ withCString "ResourcePreloader" $ \ clsNamePtr -> withCString "add_resource" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Adds a resource to the preloader with the given @name@. If a resource with the given @name@ already exists, the new resource will be renamed to "@name@ N" where N is an incrementing number starting from 2. add_resource :: (ResourcePreloader :< cls, Object :< cls) => cls -> GodotString -> Resource -> IO () add_resource cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindResourcePreloader_add_resource (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ResourcePreloader "add_resource" '[GodotString, Resource] (IO ()) where nodeMethod = Godot.Core.ResourcePreloader.add_resource {-# NOINLINE bindResourcePreloader_get_resource #-} -- | Returns the resource associated to @name@. bindResourcePreloader_get_resource :: MethodBind bindResourcePreloader_get_resource = unsafePerformIO $ withCString "ResourcePreloader" $ \ clsNamePtr -> withCString "get_resource" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns the resource associated to @name@. get_resource :: (ResourcePreloader :< cls, Object :< cls) => cls -> GodotString -> IO Resource get_resource cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindResourcePreloader_get_resource (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ResourcePreloader "get_resource" '[GodotString] (IO Resource) where nodeMethod = Godot.Core.ResourcePreloader.get_resource {-# NOINLINE bindResourcePreloader_get_resource_list #-} -- | Returns the list of resources inside the preloader. bindResourcePreloader_get_resource_list :: MethodBind bindResourcePreloader_get_resource_list = unsafePerformIO $ withCString "ResourcePreloader" $ \ clsNamePtr -> withCString "get_resource_list" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns the list of resources inside the preloader. get_resource_list :: (ResourcePreloader :< cls, Object :< cls) => cls -> IO PoolStringArray get_resource_list cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindResourcePreloader_get_resource_list (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ResourcePreloader "get_resource_list" '[] (IO PoolStringArray) where nodeMethod = Godot.Core.ResourcePreloader.get_resource_list {-# NOINLINE bindResourcePreloader_has_resource #-} -- | Returns @true@ if the preloader contains a resource associated to @name@. bindResourcePreloader_has_resource :: MethodBind bindResourcePreloader_has_resource = unsafePerformIO $ withCString "ResourcePreloader" $ \ clsNamePtr -> withCString "has_resource" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns @true@ if the preloader contains a resource associated to @name@. has_resource :: (ResourcePreloader :< cls, Object :< cls) => cls -> GodotString -> IO Bool has_resource cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindResourcePreloader_has_resource (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ResourcePreloader "has_resource" '[GodotString] (IO Bool) where nodeMethod = Godot.Core.ResourcePreloader.has_resource {-# NOINLINE bindResourcePreloader_remove_resource #-} -- | Removes the resource associated to @name@ from the preloader. bindResourcePreloader_remove_resource :: MethodBind bindResourcePreloader_remove_resource = unsafePerformIO $ withCString "ResourcePreloader" $ \ clsNamePtr -> withCString "remove_resource" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Removes the resource associated to @name@ from the preloader. remove_resource :: (ResourcePreloader :< cls, Object :< cls) => cls -> GodotString -> IO () remove_resource cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindResourcePreloader_remove_resource (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ResourcePreloader "remove_resource" '[GodotString] (IO ()) where nodeMethod = Godot.Core.ResourcePreloader.remove_resource {-# NOINLINE bindResourcePreloader_rename_resource #-} -- | Renames a resource inside the preloader from @name@ to @newname@. bindResourcePreloader_rename_resource :: MethodBind bindResourcePreloader_rename_resource = unsafePerformIO $ withCString "ResourcePreloader" $ \ clsNamePtr -> withCString "rename_resource" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Renames a resource inside the preloader from @name@ to @newname@. rename_resource :: (ResourcePreloader :< cls, Object :< cls) => cls -> GodotString -> GodotString -> IO () rename_resource cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindResourcePreloader_rename_resource (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ResourcePreloader "rename_resource" '[GodotString, GodotString] (IO ()) where nodeMethod = Godot.Core.ResourcePreloader.rename_resource
0
0.898868
1
0.898868
game-dev
MEDIA
0.416087
game-dev
0.870709
1
0.870709
rehlds/ReGameDLL_CS
6,371
regamedll/game_shared/bot/improv.h
/* * * 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 * * In addition, as a special exception, the author gives permission to * link the code of this program with the Half-Life Game Engine ("HL * Engine") and Modified Game Libraries ("MODs") developed by Valve, * L.L.C ("Valve"). You must obey the GNU General Public License in all * respects for all of the code used other than the HL Engine and MODs * from Valve. If you modify this file, you may extend this exception * to your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. * */ #pragma once class CBaseEntity; class CNavLadder; // Improv-specific events class IImprovEvent { public: virtual void OnMoveToSuccess(const Vector &goal) {}; // invoked when an improv reaches its MoveTo goal enum MoveToFailureType { FAIL_INVALID_PATH = 0, FAIL_STUCK, FAIL_FELL_OFF, }; virtual void OnMoveToFailure(const Vector &goal, MoveToFailureType reason) {}; // invoked when an improv fails to reach a MoveTo goal virtual void OnInjury(float amount) {}; // invoked when the improv is injured }; // The Improv interface definition // An "Improv" is an improvisational actor that simulates the // behavor of a human in an unscripted, "make it up as you go" manner. class CImprov: public IImprovEvent { public: virtual ~CImprov() {}; virtual bool IsAlive() const = 0; // return true if this improv is alive virtual void MoveTo(const Vector &goal) = 0; // move improv towards far-away goal (pathfind) virtual void LookAt(const Vector &target) = 0; // define desired view target virtual void ClearLookAt() = 0; // remove view goal virtual void FaceTo(const Vector &goal) = 0; // orient body towards goal virtual void ClearFaceTo() = 0; // remove body orientation goal virtual bool IsAtMoveGoal(float error = 20.0f) const = 0; // return true if improv is standing on its movement goal virtual bool HasLookAt() const = 0; // return true if improv has a look at goal virtual bool HasFaceTo() const = 0; // return true if improv has a face to goal virtual bool IsAtFaceGoal() const = 0; // return true if improv is facing towards its face goal virtual bool IsFriendInTheWay(const Vector &goalPos) const = 0; // return true if a friend is blocking our line to the given goal position virtual bool IsFriendInTheWay(CBaseEntity *myFriend, const Vector &goalPos) const = 0; // return true if the given friend is blocking our line to the given goal position virtual void MoveForward() = 0; virtual void MoveBackward() = 0; virtual void StrafeLeft() = 0; virtual void StrafeRight() = 0; virtual bool Jump() = 0; virtual void Crouch() = 0; virtual void StandUp() = 0; // "un-crouch" virtual void TrackPath(const Vector &pathGoal, float deltaT) = 0; // move along path by following "pathGoal" virtual void StartLadder(const CNavLadder *ladder, enum NavTraverseType how, const Vector *approachPos, const Vector *departPos) = 0; // invoked when a ladder is encountered while following a path virtual bool TraverseLadder(const CNavLadder *ladder, enum NavTraverseType how, const Vector *approachPos, const Vector *departPos, float deltaT) = 0; // traverse given ladder virtual bool GetSimpleGroundHeightWithFloor(const Vector *pos, float *height, Vector *normal = nullptr) = 0; // find "simple" ground height, treating current nav area as part of the floor virtual void Run() = 0; virtual void Walk() = 0; virtual void Stop() = 0; virtual float GetMoveAngle() const = 0; // return direction of movement virtual float GetFaceAngle() const = 0; // return direction of view virtual const Vector &GetFeet() const = 0; // return position of "feet" - point below centroid of improv at feet level virtual const Vector &GetCentroid() const = 0; virtual const Vector &GetEyes() const = 0; virtual bool IsRunning() const = 0; virtual bool IsWalking() const = 0; virtual bool IsStopped() const = 0; virtual bool IsCrouching() const = 0; virtual bool IsJumping() const = 0; virtual bool IsUsingLadder() const = 0; virtual bool IsOnGround() const = 0; virtual bool IsMoving() const = 0; // if true, improv is walking, crawling, running somewhere virtual bool CanRun() const = 0; virtual bool CanCrouch() const = 0; virtual bool CanJump() const = 0; virtual bool IsVisible(const Vector &pos, bool testFOV = false) const = 0; // return true if improv can see position virtual bool IsPlayerLookingAtMe(CBasePlayer *pOther, float cosTolerance = 0.95f) const = 0; // return true if 'other' is looking right at me virtual CBasePlayer *IsAnyPlayerLookingAtMe(int team = 0, float cosTolerance = 0.95f) const = 0; // return player on given team that is looking right at me (team == 0 means any team), NULL otherwise virtual CBasePlayer *GetClosestPlayerByTravelDistance(int team = 0, float *range = nullptr) const = 0; // return actual travel distance to closest player on given team (team == 0 means any team) virtual CNavArea *GetLastKnownArea() const = 0; virtual void OnUpdate(float deltaT) = 0; // a less frequent, full update 'tick' virtual void OnUpkeep(float deltaT) = 0; // a frequent, lightweight update 'tick' virtual void OnReset() = 0; // reset improv to initial state virtual void OnGameEvent(GameEventType event, CBaseEntity *pEntity, CBaseEntity *pOther) = 0; // invoked when an event occurs in the game virtual void OnTouch(CBaseEntity *pOther) = 0; // "other" has touched us };
0
0.784364
1
0.784364
game-dev
MEDIA
0.854034
game-dev
0.617418
1
0.617418
phoboslab/Quakespasm-Rift
4,098
Windows/SDL/include/SDL_keyboard.h
/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL_keyboard.h * Include file for SDL keyboard event handling */ #ifndef _SDL_keyboard_h #define _SDL_keyboard_h #include "SDL_stdinc.h" #include "SDL_error.h" #include "SDL_keysym.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** Keysym structure * * - The scancode is hardware dependent, and should not be used by general * applications. If no hardware scancode is available, it will be 0. * * - The 'unicode' translated character is only available when character * translation is enabled by the SDL_EnableUNICODE() API. If non-zero, * this is a UNICODE character corresponding to the keypress. If the * high 9 bits of the character are 0, then this maps to the equivalent * ASCII character: * @code * char ch; * if ( (keysym.unicode & 0xFF80) == 0 ) { * ch = keysym.unicode & 0x7F; * } else { * An international character.. * } * @endcode */ typedef struct SDL_keysym { Uint8 scancode; /**< hardware specific scancode */ SDLKey sym; /**< SDL virtual keysym */ SDLMod mod; /**< current key modifiers */ Uint16 unicode; /**< translated character */ } SDL_keysym; /** This is the mask which refers to all hotkey bindings */ #define SDL_ALL_HOTKEYS 0xFFFFFFFF /* Function prototypes */ /** * Enable/Disable UNICODE translation of keyboard input. * * This translation has some overhead, so translation defaults off. * * @param[in] enable * If 'enable' is 1, translation is enabled. * If 'enable' is 0, translation is disabled. * If 'enable' is -1, the translation state is not changed. * * @return It returns the previous state of keyboard translation. */ extern DECLSPEC int SDLCALL SDL_EnableUNICODE(int enable); #define SDL_DEFAULT_REPEAT_DELAY 500 #define SDL_DEFAULT_REPEAT_INTERVAL 30 /** * Enable/Disable keyboard repeat. Keyboard repeat defaults to off. * * @param[in] delay * 'delay' is the initial delay in ms between the time when a key is * pressed, and keyboard repeat begins. * * @param[in] interval * 'interval' is the time in ms between keyboard repeat events. * * If 'delay' is set to 0, keyboard repeat is disabled. */ extern DECLSPEC int SDLCALL SDL_EnableKeyRepeat(int delay, int interval); extern DECLSPEC void SDLCALL SDL_GetKeyRepeat(int *delay, int *interval); /** * Get a snapshot of the current state of the keyboard. * Returns an array of keystates, indexed by the SDLK_* syms. * Usage: * @code * Uint8 *keystate = SDL_GetKeyState(NULL); * if ( keystate[SDLK_RETURN] ) //... \<RETURN> is pressed. * @endcode */ extern DECLSPEC Uint8 * SDLCALL SDL_GetKeyState(int *numkeys); /** * Get the current key modifier state */ extern DECLSPEC SDLMod SDLCALL SDL_GetModState(void); /** * Set the current key modifier state. * This does not change the keyboard state, only the key modifier flags. */ extern DECLSPEC void SDLCALL SDL_SetModState(SDLMod modstate); /** * Get the name of an SDL virtual keysym */ extern DECLSPEC char * SDLCALL SDL_GetKeyName(SDLKey key); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_keyboard_h */
0
0.768215
1
0.768215
game-dev
MEDIA
0.868192
game-dev
0.51834
1
0.51834
kettingpowered/Ketting-1-20-x
1,383
src/main/java/org/bukkit/event/block/BlockMultiPlaceEvent.java
package org.bukkit.event.block; import com.google.common.collect.ImmutableList; import java.util.List; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; /** * Fired when a single block placement action of a player triggers the * creation of multiple blocks(e.g. placing a bed block). The block returned * by {@link #getBlockPlaced()} and its related methods is the block where * the placed block would exist if the placement only affected a single * block. */ public class BlockMultiPlaceEvent extends BlockPlaceEvent { private final List<BlockState> states; public BlockMultiPlaceEvent(@NotNull List<BlockState> states, @NotNull Block clicked, @NotNull ItemStack itemInHand, @NotNull Player thePlayer, boolean canBuild) { super(states.get(0).getBlock(), states.get(0), clicked, itemInHand, thePlayer, canBuild); this.states = ImmutableList.copyOf(states); } /** * Gets a list of blockstates for all blocks which were replaced by the * placement of the new blocks. Most of these blocks will just have a * Material type of AIR. * * @return immutable list of replaced BlockStates */ @NotNull public List<BlockState> getReplacedBlockStates() { return states; } }
0
0.876531
1
0.876531
game-dev
MEDIA
0.98183
game-dev
0.801902
1
0.801902
EB-wilson/Singularity
7,675
src/singularity/world/blocks/liquid/ClusterConduit.java
package singularity.world.blocks.liquid; import arc.Core; import arc.func.Boolf; import arc.graphics.Color; import arc.graphics.g2d.Draw; import arc.graphics.g2d.TextureRegion; import arc.math.Mathf; import arc.math.geom.Geometry; import arc.math.geom.Point2; import arc.scene.ui.layout.Table; import arc.struct.Seq; import arc.util.Eachable; import arc.util.Nullable; import mindustry.Vars; import mindustry.content.Blocks; import mindustry.entities.units.BuildPlan; import mindustry.gen.Building; import mindustry.graphics.Drawf; import mindustry.input.Placement; import mindustry.type.Liquid; import mindustry.world.Block; import mindustry.world.Tile; import mindustry.world.blocks.distribution.ItemBridge; import mindustry.world.blocks.liquid.LiquidJunction; import mindustry.world.meta.BlockGroup; import mindustry.world.modules.LiquidModule; public class ClusterConduit extends MultLiquidBlock{ public final int timerFlow = timers++; public Color botColor = Color.valueOf("565656"); public TextureRegion cornerRegion; public TextureRegion[] botRegions; public TextureRegion capRegion, arrow; public @Nullable Block junctionReplacement, bridgeReplacement; public ClusterConduit(String name){ super(name); rotate = true; solid = false; floating = true; conveyorPlacement = true; noUpdateDisabled = true; canOverdrive = false; group = BlockGroup.liquids; } @Override public void load(){ super.load(); botRegions = new TextureRegion[conduitAmount]; for(int i=0; i<conduitAmount; i++){ botRegions[i] = Core.atlas.find(name + "_bottom_" + i); } capRegion = Core.atlas.find(name + "_cap"); arrow = Core.atlas.find(name + "_arrow"); cornerRegion = Core.atlas.find(name + "_corner"); } @Override public void init(){ super.init(); if(junctionReplacement == null) junctionReplacement = Blocks.liquidJunction; if(bridgeReplacement == null || !(bridgeReplacement instanceof ItemBridge)) bridgeReplacement = Blocks.bridgeConduit; } @Override public void drawPlanConfigTop(BuildPlan req, Eachable<BuildPlan> list){ boolean corner = cornerIng(req, list); if(corner){ Draw.rect(cornerRegion, req.drawx(), req.drawy()); Draw.rect(arrow, req.drawx(), req.drawy(), req.rotation * 90); } else{ Draw.color(botColor); Draw.alpha(0.5f); for(int i = 0; i < conduitAmount; i++){ Draw.rect(botRegions[i], req.drawx(), req.drawy(), req.rotation*90); } Draw.color(); Draw.rect(region, req.drawx(), req.drawy(), req.rotation*90); } } protected boolean cornerIng(BuildPlan req, Eachable<BuildPlan> list){ if(req.tile() == null) return false; boolean[] result = {false}; list.each(other -> { if(other.breaking || other == req) return; for(Point2 point : Geometry.d4){ int x = req.x + point.x, y = req.y + point.y; if(x >= other.x -(other.block.size - 1) / 2 && x <= other.x + (other.block.size / 2) && y >= other.y -(other.block.size - 1) / 2 && y <= other.y + (other.block.size / 2)){ if(Vars.world.tile(other.x + Geometry.d4(other.rotation).x, other.y + Geometry.d4(other.rotation).y) == req.tile()){ result[0] |= other.rotation != req.rotation && Vars.world.tile(req.x + Geometry.d4(req.rotation).x, req.y + Geometry.d4(req.rotation).y) != other.tile(); } } } }); return result[0]; } @Override public Block getReplacement(BuildPlan req, Seq<BuildPlan> requests){ if(junctionReplacement == null) return this; Boolf<Point2> cont = p -> requests.contains(o -> o.x == req.x + p.x && o.y == req.y + p.y && o.rotation == req.rotation && (req.block instanceof ClusterConduit || req.block instanceof LiquidJunction)); return cont.get(Geometry.d4(req.rotation)) && cont.get(Geometry.d4(req.rotation - 2)) && req.tile() != null && req.tile().block() instanceof ClusterConduit && Mathf.mod(req.build().rotation - req.rotation, 2) == 1 ? junctionReplacement : this; } @Override public void handlePlacementLine(Seq<BuildPlan> plans){ if(bridgeReplacement == null) return; Placement.calculateBridges(plans, (ItemBridge)bridgeReplacement); } @Override public TextureRegion[] icons(){ return new TextureRegion[]{Core.atlas.find("conduit-bottom"), region}; } public class ClusterConduitBuild extends MultLiquidBuild{ public boolean capped, isCorner; @Override public void draw(){ if(isCorner){ Draw.rect(cornerRegion, x, y); Draw.rect(arrow, x, y, rotation*90); } else{ for(int i=0; i<conduitAmount; i++){ Draw.color(botColor); Draw.rect(botRegions[i], x, y, rotation*90); Drawf.liquid(botRegions[i], x, y, liquidsBuffer[i].smoothCurrent/liquidCapacity, liquidsBuffer[i].current().color, rotation*90); } Draw.rect(region, x, y, rotation*90); if(capped && capRegion.found()) Draw.rect(capRegion, x, y, rotdeg()); } } @Override public void onProximityUpdate(){ super.onProximityUpdate(); Building next = front(); capped = next == null || next.team != team || !next.block.hasLiquids; for(Building other: proximity){ isCorner |= other.block instanceof ClusterConduit && other.nearby(other.rotation) == this && other.rotation != rotation && nearby(rotation) != other; } } @Override public void updateTile(){ super.updateTile(); if(anyLiquid() && timer(timerFlow, 1)){ moveLiquidForward(false, null); noSleep(); }else{ sleep(); } } @Override public void display(Table table){ super.display(table); } @Override public boolean conduitAccept(MultLiquidBuild source, int index, Liquid liquid){ return super.conduitAccept(source, index, liquid) && (source.block instanceof ClusterConduit || source.tile.absoluteRelativeTo(tile.x, tile.y) == rotation); } @Override public float moveLiquidForward(boolean leaks, Liquid liquid){ Tile next = tile.nearby(rotation); if(next == null || next.build == null) return 0; Building dest = next.build.getLiquidDestination(this, liquid); float flow = 0; for(int i=0; i<liquidsBuffer.length; i++){ LiquidModule liquids = liquidsBuffer[i]; if(dest instanceof MultLiquidBuild mu && mu.shouldClusterMove(this)){ flow += moveLiquid(mu, i, liquids.current()); } else if(dest != null){ this.liquids = liquids; flow += moveLiquid(dest, liquids.current()); this.liquids = cacheLiquids; } } return flow; } @Override public float moveLiquid(Building next, Liquid liquid){ next = next.getLiquidDestination(this, liquid); if(next instanceof MultLiquidBuild mu && mu.shouldClusterMove(this)){ float f = 0; for(int index=0; index<liquidsBuffer.length; index++){ if(liquidsBuffer[index] == liquids && mu.conduitAccept(this, index, liquidsBuffer[index].current())){ f += moveLiquid(mu, index, liquidsBuffer[index].current()); } } if (f > 0) return f; } return super.moveLiquid(next, liquid); } @Override public boolean acceptLiquid(Building source, Liquid liquid){ return super.acceptLiquid(source, liquid) && (tile == null || source.tile.absoluteRelativeTo(tile.x, tile.y) == rotation); } } }
0
0.94331
1
0.94331
game-dev
MEDIA
0.656033
game-dev,graphics-rendering
0.975284
1
0.975284
iniside/Velesarc
1,402
ArcX/ArcAI/Source/ArcAI/ArcMassActorPlayAnimMontage.h
#pragma once #include "MassActorSubsystem.h" #include "MassStateTreeTypes.h" #include "ArcMassActorPlayAnimMontage.generated.h" class UAnimMontage; USTRUCT() struct FArcMassActorPlayAnimMontageInstanceData { GENERATED_BODY() /** Delay before the task ends. Default (0 or any negative) will run indefinitely, so it requires a transition in the state tree to stop it. */ UPROPERTY(EditAnywhere, Category = Parameter) TObjectPtr<UAnimMontage> AnimMontage; }; /** * Stop, and stand on current navmesh location */ USTRUCT(meta = (DisplayName = "Arc Mass Actor Play Anim Montage")) struct FArcMassActorPlayAnimMontageTask : public FMassStateTreeTaskBase { GENERATED_BODY() using FInstanceDataType = FArcMassActorPlayAnimMontageInstanceData; public: FArcMassActorPlayAnimMontageTask(); protected: virtual bool Link(FStateTreeLinker& Linker) override; virtual void GetDependencies(UE::MassBehavior::FStateTreeDependencyBuilder& Builder) const override; virtual const UStruct* GetInstanceDataType() const override { return FInstanceDataType::StaticStruct(); } virtual EStateTreeRunStatus EnterState(FStateTreeExecutionContext& Context, const FStateTreeTransitionResult& Transition) const override; //virtual EStateTreeRunStatus Tick(FStateTreeExecutionContext& Context, const float DeltaTime) const override; TStateTreeExternalDataHandle<FMassActorFragment> MassActorFragment; };
0
0.899632
1
0.899632
game-dev
MEDIA
0.950893
game-dev
0.582108
1
0.582108
LanternPowered/Lantern
2,924
src/main/java/org/lanternpowered/server/data/value/mutable/LanternItemValue.java
/* * This file is part of LanternServer, licensed under the MIT License (MIT). * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.lanternpowered.server.data.value.mutable; import static com.google.common.base.Preconditions.checkNotNull; import org.lanternpowered.server.data.value.immutable.ImmutableLanternItemValue; import org.spongepowered.api.data.key.Key; import org.spongepowered.api.data.value.BaseValue; import org.spongepowered.api.data.value.immutable.ImmutableValue; import org.spongepowered.api.data.value.mutable.Value; import org.spongepowered.api.item.inventory.ItemStack; import java.util.function.Function; public class LanternItemValue extends LanternValue<ItemStack> { public LanternItemValue(Key<? extends BaseValue<ItemStack>> key, ItemStack defaultValue) { super(key, defaultValue.copy()); } public LanternItemValue(Key<? extends BaseValue<ItemStack>> key, ItemStack defaultValue, ItemStack actualValue) { super(key, defaultValue.copy(), actualValue.copy()); } @Override public ItemStack get() { return super.get().copy(); } @Override public Value<ItemStack> set(ItemStack value) { return super.set(value.copy()); } @Override public Value<ItemStack> transform(Function<ItemStack, ItemStack> function) { this.actualValue = checkNotNull(checkNotNull(function).apply(this.actualValue)).copy(); return this; } @Override public ImmutableValue<ItemStack> asImmutable() { return new ImmutableLanternItemValue(getKey(), getDefault(), get()); } @Override public LanternItemValue copy() { return new LanternItemValue(getKey(), getDefault(), getActualValue()); } }
0
0.730672
1
0.730672
game-dev
MEDIA
0.895043
game-dev
0.703452
1
0.703452
BG-Software-LLC/SuperiorSkyblock2
5,368
src/main/java/com/bgsoftware/superiorskyblock/core/menu/impl/MenuIslandBank.java
package com.bgsoftware.superiorskyblock.core.menu.impl; import com.bgsoftware.common.annotations.Nullable; import com.bgsoftware.superiorskyblock.api.island.Island; import com.bgsoftware.superiorskyblock.api.menu.layout.MenuLayout; import com.bgsoftware.superiorskyblock.api.menu.view.MenuView; import com.bgsoftware.superiorskyblock.api.world.GameSound; import com.bgsoftware.superiorskyblock.api.wrappers.SuperiorPlayer; import com.bgsoftware.superiorskyblock.core.io.MenuParserImpl; import com.bgsoftware.superiorskyblock.core.menu.AbstractMenu; import com.bgsoftware.superiorskyblock.core.menu.MenuIdentifiers; import com.bgsoftware.superiorskyblock.core.menu.MenuParseResult; import com.bgsoftware.superiorskyblock.core.menu.MenuPatternSlots; import com.bgsoftware.superiorskyblock.core.menu.button.impl.BankCustomDepositButton; import com.bgsoftware.superiorskyblock.core.menu.button.impl.BankCustomWithdrawButton; import com.bgsoftware.superiorskyblock.core.menu.button.impl.BankDepositButton; import com.bgsoftware.superiorskyblock.core.menu.button.impl.BankWithdrawButton; import com.bgsoftware.superiorskyblock.core.menu.button.impl.OpenBankLogsButton; import com.bgsoftware.superiorskyblock.core.menu.view.IslandMenuView; import com.bgsoftware.superiorskyblock.core.menu.view.args.IslandViewArgs; import org.bukkit.configuration.file.YamlConfiguration; import java.util.List; public class MenuIslandBank extends AbstractMenu<IslandMenuView, IslandViewArgs> { private MenuIslandBank(MenuParseResult<IslandMenuView> parseResult) { super(MenuIdentifiers.MENU_ISLAND_BANK, parseResult); } @Override protected IslandMenuView createViewInternal(SuperiorPlayer superiorPlayer, IslandViewArgs args, @Nullable MenuView<?, ?> previousMenuView) { return new IslandMenuView(superiorPlayer, previousMenuView, this, args); } public void refreshViews(Island island) { refreshViews(view -> view.getIsland().equals(island)); } @Nullable public static MenuIslandBank createInstance() { MenuParseResult<IslandMenuView> menuParseResult = MenuParserImpl.getInstance().loadMenu("island-bank.yml", null); if (menuParseResult == null) { return null; } MenuPatternSlots menuPatternSlots = menuParseResult.getPatternSlots(); YamlConfiguration cfg = menuParseResult.getConfig(); MenuLayout.Builder<IslandMenuView> patternBuilder = menuParseResult.getLayoutBuilder(); if (cfg.isConfigurationSection("items")) { for (String itemChar : cfg.getConfigurationSection("items").getKeys(false)) { if (cfg.contains("items." + itemChar + ".bank-action")) { List<Integer> slots = menuPatternSlots.getSlots(itemChar); if (slots.isEmpty()) { continue; } GameSound successSound = MenuParserImpl.getInstance().getSound(cfg.getConfigurationSection("sounds." + itemChar + ".success-sound")); GameSound failSound = MenuParserImpl.getInstance().getSound(cfg.getConfigurationSection("sounds." + itemChar + ".fail-sound")); if (cfg.isDouble("items." + itemChar + ".bank-action.withdraw")) { double withdrawPercentage = cfg.getDouble("items." + itemChar + ".bank-action.withdraw"); if (withdrawPercentage <= 0) { patternBuilder.mapButtons(slots, new BankCustomWithdrawButton.Builder() .setFailSound(failSound).setSuccessSound(successSound)); } else { patternBuilder.mapButtons(slots, new BankWithdrawButton.Builder(withdrawPercentage) .setFailSound(failSound).setSuccessSound(successSound)); } } else if (cfg.isList("items." + itemChar + ".bank-action.withdraw")) { List<String> withdrawCommands = cfg.getStringList("items." + itemChar + ".bank-action.withdraw"); patternBuilder.mapButtons(slots, new BankWithdrawButton.Builder(withdrawCommands) .setFailSound(failSound).setSuccessSound(successSound)); } else if (cfg.contains("items." + itemChar + ".bank-action.deposit")) { double depositPercentage = cfg.getDouble("items." + itemChar + ".bank-action.deposit"); if (depositPercentage <= 0) { patternBuilder.mapButtons(slots, new BankCustomDepositButton.Builder() .setFailSound(failSound).setSuccessSound(successSound)); } else { patternBuilder.mapButtons(slots, new BankDepositButton.Builder(depositPercentage) .setFailSound(failSound).setSuccessSound(successSound)); } } } } } patternBuilder.mapButtons(MenuParserImpl.getInstance().parseButtonSlots(cfg, "logs", menuPatternSlots), new OpenBankLogsButton.Builder()); return new MenuIslandBank(menuParseResult); } }
0
0.89021
1
0.89021
game-dev
MEDIA
0.649475
game-dev,desktop-app
0.956535
1
0.956535
FamroFexl/Circumnavigate
1,827
src/main/java/com/fexl/circumnavigate/options/DimensionWrappingSettings.java
/* * SPDX-License-Identifier: AGPL-3.0-only */ package com.fexl.circumnavigate.options; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; import com.mojang.serialization.codecs.RecordCodecBuilder; public record DimensionWrappingSettings(int xChunkBoundMin, int xChunkBoundMax, int zChunkBoundMin, int zChunkBoundMax, Axis shiftAxis, int shiftAmount, boolean useWrappedWorldGen) { public static final Codec<DimensionWrappingSettings> CODEC = RecordCodecBuilder.create( instance -> instance.group( Codec.INT.fieldOf("XChunkBoundMin").forGetter(DimensionWrappingSettings::xChunkBoundMin), Codec.INT.fieldOf("XChunkBoundMax").forGetter(DimensionWrappingSettings::xChunkBoundMax), Codec.INT.fieldOf("ZChunkBoundMin").forGetter(DimensionWrappingSettings::zChunkBoundMin), Codec.INT.fieldOf("ZChunkBoundMax").forGetter(DimensionWrappingSettings::zChunkBoundMax), Axis.CODEC.fieldOf("ShiftAxis").forGetter(DimensionWrappingSettings::shiftAxis), Codec.INT.fieldOf("ShiftAmount").forGetter(DimensionWrappingSettings::shiftAmount), Codec.BOOL.fieldOf("UseWrappedWorldGen").forGetter(DimensionWrappingSettings::useWrappedWorldGen) ) .apply(instance, instance.stable(DimensionWrappingSettings::new)) ); public DimensionWrappingSettings(int bounds) { this(-Math.abs(bounds), Math.abs(bounds), -Math.abs(bounds), Math.abs(bounds), Axis.X, 0, false); } public enum Axis { X, Z; public static final Codec<DimensionWrappingSettings.Axis> CODEC = Codec.STRING.comapFlatMap( axis -> { try { return DataResult.success(DimensionWrappingSettings.Axis.valueOf(axis)); } catch (IllegalArgumentException e) { return DataResult.error(() -> "\"" + axis + "\" is not an axis!"); } }, DimensionWrappingSettings.Axis::toString ); } }
0
0.678969
1
0.678969
game-dev
MEDIA
0.195004
game-dev
0.599664
1
0.599664
ChengF3ng233/Untitled
5,982
src/main/java/net/minecraft/world/gen/layer/GenLayerHills.java
package net.minecraft.world.gen.layer; import net.minecraft.world.biome.BiomeGenBase; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class GenLayerHills extends GenLayer { private static final Logger logger = LogManager.getLogger(); private final GenLayer field_151628_d; public GenLayerHills(long p_i45479_1_, GenLayer p_i45479_3_, GenLayer p_i45479_4_) { super(p_i45479_1_); this.parent = p_i45479_3_; this.field_151628_d = p_i45479_4_; } /** * Returns a list of integer values generated by this layer. These may be interpreted as temperatures, rainfall * amounts, or biomeList[] indices based on the particular GenLayer subclass. */ public int[] getInts(int areaX, int areaY, int areaWidth, int areaHeight) { int[] aint = this.parent.getInts(areaX - 1, areaY - 1, areaWidth + 2, areaHeight + 2); int[] aint1 = this.field_151628_d.getInts(areaX - 1, areaY - 1, areaWidth + 2, areaHeight + 2); int[] aint2 = IntCache.getIntCache(areaWidth * areaHeight); for (int i = 0; i < areaHeight; ++i) { for (int j = 0; j < areaWidth; ++j) { this.initChunkSeed(j + areaX, i + areaY); int k = aint[j + 1 + (i + 1) * (areaWidth + 2)]; int l = aint1[j + 1 + (i + 1) * (areaWidth + 2)]; boolean flag = (l - 2) % 29 == 0; if (k > 255) { logger.debug("old! {}", k); } if (k != 0 && l >= 2 && (l - 2) % 29 == 1 && k < 128) { if (BiomeGenBase.getBiome(k + 128) != null) { aint2[j + i * areaWidth] = k + 128; } else { aint2[j + i * areaWidth] = k; } } else if (this.nextInt(3) != 0 && !flag) { aint2[j + i * areaWidth] = k; } else { int i1 = k; if (k == BiomeGenBase.desert.biomeID) { i1 = BiomeGenBase.desertHills.biomeID; } else if (k == BiomeGenBase.forest.biomeID) { i1 = BiomeGenBase.forestHills.biomeID; } else if (k == BiomeGenBase.birchForest.biomeID) { i1 = BiomeGenBase.birchForestHills.biomeID; } else if (k == BiomeGenBase.roofedForest.biomeID) { i1 = BiomeGenBase.plains.biomeID; } else if (k == BiomeGenBase.taiga.biomeID) { i1 = BiomeGenBase.taigaHills.biomeID; } else if (k == BiomeGenBase.megaTaiga.biomeID) { i1 = BiomeGenBase.megaTaigaHills.biomeID; } else if (k == BiomeGenBase.coldTaiga.biomeID) { i1 = BiomeGenBase.coldTaigaHills.biomeID; } else if (k == BiomeGenBase.plains.biomeID) { if (this.nextInt(3) == 0) { i1 = BiomeGenBase.forestHills.biomeID; } else { i1 = BiomeGenBase.forest.biomeID; } } else if (k == BiomeGenBase.icePlains.biomeID) { i1 = BiomeGenBase.iceMountains.biomeID; } else if (k == BiomeGenBase.jungle.biomeID) { i1 = BiomeGenBase.jungleHills.biomeID; } else if (k == BiomeGenBase.ocean.biomeID) { i1 = BiomeGenBase.deepOcean.biomeID; } else if (k == BiomeGenBase.extremeHills.biomeID) { i1 = BiomeGenBase.extremeHillsPlus.biomeID; } else if (k == BiomeGenBase.savanna.biomeID) { i1 = BiomeGenBase.savannaPlateau.biomeID; } else if (biomesEqualOrMesaPlateau(k, BiomeGenBase.mesaPlateau_F.biomeID)) { i1 = BiomeGenBase.mesa.biomeID; } else if (k == BiomeGenBase.deepOcean.biomeID && this.nextInt(3) == 0) { int j1 = this.nextInt(2); if (j1 == 0) { i1 = BiomeGenBase.plains.biomeID; } else { i1 = BiomeGenBase.forest.biomeID; } } if (flag && i1 != k) { if (BiomeGenBase.getBiome(i1 + 128) != null) { i1 += 128; } else { i1 = k; } } if (i1 == k) { aint2[j + i * areaWidth] = k; } else { int k2 = aint[j + 1 + (i + 1 - 1) * (areaWidth + 2)]; int k1 = aint[j + 1 + 1 + (i + 1) * (areaWidth + 2)]; int l1 = aint[j + 1 - 1 + (i + 1) * (areaWidth + 2)]; int i2 = aint[j + 1 + (i + 1 + 1) * (areaWidth + 2)]; int j2 = 0; if (biomesEqualOrMesaPlateau(k2, k)) { ++j2; } if (biomesEqualOrMesaPlateau(k1, k)) { ++j2; } if (biomesEqualOrMesaPlateau(l1, k)) { ++j2; } if (biomesEqualOrMesaPlateau(i2, k)) { ++j2; } if (j2 >= 3) { aint2[j + i * areaWidth] = i1; } else { aint2[j + i * areaWidth] = k; } } } } } return aint2; } }
0
0.558756
1
0.558756
game-dev
MEDIA
0.77591
game-dev
0.839645
1
0.839645
eldexterr/ttyd64
140,660
map/src/dgb_08.mscr
% Script File: dgb_08.mscr % Decoded from: 0 to 6E30 (dgb_08) #define .NpcID:WorldClubba_00 00 #define .NpcID:WorldClubba_01 01 #define .NpcID:WorldClubba_02 02 #define .NpcID:WorldClubba_03 03 #define .NpcID:WorldClubba_04 04 #define .NpcID:WorldClubba_05 05 #define .NpcID:WorldClubba_06 06 #define .NpcID:Sentinel_07 07 #define .NpcID:Sentinel_08 08 #define .NpcID:WorldTubba_09 09 #define .NpcID:WorldClubba_11 0B #new:Function $Function_80240000 { 0: ADDIU SP, SP, FFB8 4: SW S5, 24 (SP) 8: COPY S5, A0 C: SW RA, 2C (SP) 10: SW S6, 28 (SP) 14: SW S4, 20 (SP) 18: SW S3, 1C (SP) 1C: SW S2, 18 (SP) 20: SW S1, 14 (SP) 24: SW S0, 10 (SP) 28: SDC1 F24, 40 (SP) 2C: SDC1 F22, 38 (SP) 30: SDC1 F20, 30 (SP) 34: LW S3, 148 (S5) 38: LH A0, 8 (S3) 3C: JAL ~Func:get_npc_unsafe 40: COPY S6, A1 44: COPY S4, V0 48: SW R0, 74 (S5) 4C: LWC1 F24, 38 (S4) 50: LWC1 F22, 40 (S4) 54: CLEAR S2 58: SW R0, 78 (S5) 5C: LW V1, D0 (S3) 60: LW V0, 0 (V1) 64: LIF F20, 32639.0 70: BLEZ V0, .oD4 74: COPY S0, S2 78: COPY S1, S2 .o7C 7C: ADDU V0, S1, V1 80: MOV.S F12, F24 84: LWC1 F4, 4 (V0) 88: CVT.S.W F4, F4 8C: MFC1 A2, F4 90: LWC1 F4, C (V0) 94: CVT.S.W F4, F4 98: MFC1 A3, F4 9C: JAL ~Func:dist2D A0: MOV.S F14, F22 A4: C.LT.S F0, F20 A8: NOP AC: BC1F .oBC B0: ADDIU S1, S1, C B4: MOV.S F20, F0 B8: SW S2, 78 (S5) .oBC BC: LW V1, D0 (S3) C0: ADDIU S0, S0, 1 C4: LW V0, 0 (V1) C8: SLT V0, S0, V0 CC: BNE V0, R0, .o7C D0: ADDIU S2, S2, 1 .oD4 D4: LW V0, CC (S3) D8: LW V0, 4 (V0) DC: SW V0, 28 (S4) E0: LW V0, D0 (S3) E4: LW V0, 7C (V0) E8: BGEZ V0, .oFC EC: NOP F0: LWC1 F0, 0 (S6) F4: BEQ R0, R0, .o11C F8: SWC1 F0, 18 (S4) .oFC FC: LAD F2, $ConstDouble_80246A00 104: MTC1 V0, F0 108: NOP 10C: CVT.D.W F0, F0 110: DIV.D F0, F0, F2 114: CVT.S.D F0, F0 118: SWC1 F0, 18 (S4) .o11C 11C: LI V0, 1 120: SW V0, 70 (S5) 124: LW RA, 2C (SP) 128: LW S6, 28 (SP) 12C: LW S5, 24 (SP) 130: LW S4, 20 (SP) 134: LW S3, 1C (SP) 138: LW S2, 18 (SP) 13C: LW S1, 14 (SP) 140: LW S0, 10 (SP) 144: LDC1 F24, 40 (SP) 148: LDC1 F22, 38 (SP) 14C: LDC1 F20, 30 (SP) 150: JR RA 154: ADDIU SP, SP, 48 } #new:Function $Function_80240158 { 0: ADDIU SP, SP, FFA8 4: SW S2, 38 (SP) 8: COPY S2, A0 C: SW RA, 44 (SP) 10: SW S4, 40 (SP) 14: SW S3, 3C (SP) 18: SW S1, 34 (SP) 1C: SW S0, 30 (SP) 20: SDC1 F22, 50 (SP) 24: SDC1 F20, 48 (SP) 28: LW S1, 148 (S2) 2C: COPY S3, A1 30: LH A0, 8 (S1) 34: JAL ~Func:get_npc_unsafe 38: COPY S4, A2 3C: LW V1, 14 (S3) 40: BLTZ V1, .o104 44: COPY S0, V0 48: LW V0, 74 (S2) 4C: BGTZ V0, .o100 50: ADDIU V0, V0, FFFF 54: COPY A0, S4 58: SW V1, 74 (S2) 5C: SW R0, 10 (SP) 60: LW A2, C (S3) 64: LW A3, 10 (S3) 68: JAL 800490B4 6C: COPY A1, S1 70: BEQ V0, R0, .oF8 74: CLEAR A0 78: COPY A1, S0 7C: CLEAR A2 80: LH V1, A8 (S0) 84: LIF F0, 1.0 8C: LIF F2, 2.0 94: LIF F4, -20.0 9C: LI V0, F A0: SW V0, 1C (SP) A4: MTC1 V1, F6 A8: NOP AC: CVT.S.W F6, F6 B0: MFC1 A3, F6 B4: ADDIU V0, SP, 28 B8: SW V0, 20 (SP) BC: SWC1 F0, 10 (SP) C0: SWC1 F2, 14 (SP) C4: JAL ~Func:fx_emote C8: SWC1 F4, 18 (SP) CC: COPY A0, S0 D0: LI A1, 2F4 D4: JAL ~Func:ai_enemy_play_sound D8: LUI A2, 20 DC: LW V0, 18 (S1) E0: LHU V0, 2A (V0) E4: ANDI V0, V0, 1 E8: BNE V0, R0, .o27C EC: LI V0, A F0: BEQ R0, R0, .o27C F4: LI V0, C .oF8 F8: LW V0, 74 (S2) FC: ADDIU V0, V0, FFFF .o100 100: SW V0, 74 (S2) .o104 104: LH V0, 8C (S0) 108: BNE V0, R0, .o280 10C: NOP 110: LWC1 F0, 18 (S0) 114: LIF F3, 2.25 11C: MTC1 R0, F2 120: CVT.D.S F0, F0 124: C.LT.D F0, F2 128: NOP 12C: BC1F .o13C 130: COPY A0, S0 134: BEQ R0, R0, .o140 138: CLEAR A1 .o13C 13C: LI A1, 1 .o140 140: JAL 8003D660 144: NOP 148: LWC1 F12, 38 (S0) 14C: LW V1, 78 (S2) 150: LWC1 F14, 40 (S0) 154: SLL V0, V1, 1 158: ADDU V0, V0, V1 15C: LW V1, D0 (S1) 160: SLL V0, V0, 2 164: ADDU V0, V0, V1 168: LWC1 F22, 4 (V0) 16C: CVT.S.W F22, F22 170: LWC1 F20, C (V0) 174: CVT.S.W F20, F20 178: MFC1 A2, F22 17C: MFC1 A3, F20 180: JAL ~Func:atan2 184: NOP 188: LW A1, 18 (S0) 18C: MFC1 A2, F0 190: COPY A0, S0 194: JAL ~Func:npc_move_heading 198: SW A2, C (S0) 19C: LWC1 F12, 38 (S0) 1A0: LWC1 F14, 40 (S0) 1A4: MFC1 A2, F22 1A8: MFC1 A3, F20 1AC: JAL ~Func:dist2D 1B0: NOP 1B4: LWC1 F2, 18 (S0) 1B8: C.LE.S F0, F2 1BC: NOP 1C0: BC1F .o280 1C4: LI A0, 3E8 1C8: LI V0, 2 1CC: JAL ~Func:rand_int 1D0: SW V0, 70 (S2) 1D4: LI V1, 55555556 1DC: MULT V0, V1 1E0: SRA A0, V0, 1F 1E4: MFHI T0 1E8: SUBU A0, T0, A0 1EC: SLL V1, A0, 1 1F0: ADDU V1, V1, A0 1F4: SUBU V0, V0, V1 1F8: ADDIU V1, V0, 2 1FC: SW V1, 74 (S2) 200: LW V0, 2C (S3) 204: BLEZ V0, .o22C 208: LI V0, 4 20C: LW V0, 4 (S3) 210: BLEZ V0, .o22C 214: LI V0, 4 218: LW V0, 8 (S3) 21C: BLEZ V0, .o22C 220: LI V0, 4 224: BNE V1, R0, .o230 228: NOP .o22C 22C: SW V0, 70 (S2) .o230 230: JAL ~Func:rand_int 234: LI A0, 2710 238: LI V1, 51EB851F 240: MULT V0, V1 244: SRA V1, V0, 1F 248: MFHI T0 24C: SRA A0, T0, 5 250: SUBU A0, A0, V1 254: SLL V1, A0, 1 258: ADDU V1, V1, A0 25C: SLL V1, V1, 3 260: ADDU V1, V1, A0 264: SLL V1, V1, 2 268: LW A0, 4 (S3) 26C: SUBU V0, V0, V1 270: SLT V0, V0, A0 274: BEQ V0, R0, .o280 278: LI V0, 4 .o27C 27C: SW V0, 70 (S2) .o280 280: LW RA, 44 (SP) 284: LW S4, 40 (SP) 288: LW S3, 3C (SP) 28C: LW S2, 38 (SP) 290: LW S1, 34 (SP) 294: LW S0, 30 (SP) 298: LDC1 F22, 50 (SP) 29C: LDC1 F20, 48 (SP) 2A0: JR RA 2A4: ADDIU SP, SP, 58 } #new:Function $Function_80240400 { 0: ADDIU SP, SP, FFD8 4: SW S3, 1C (SP) 8: COPY S3, A0 C: SW RA, 20 (SP) 10: SW S2, 18 (SP) 14: SW S1, 14 (SP) 18: SW S0, 10 (SP) 1C: LW S2, 148 (S3) 20: LH A0, 8 (S2) 24: JAL ~Func:get_npc_unsafe 28: COPY S1, A1 2C: LW A0, 8 (S1) 30: COPY S0, V0 34: SRL V1, A0, 1F 38: ADDU A0, A0, V1 3C: SRA A0, A0, 1 40: JAL ~Func:rand_int 44: ADDIU A0, A0, 1 48: LW V1, 8 (S1) 4C: LI A0, B4 50: SRL A1, V1, 1F 54: ADDU V1, V1, A1 58: SRA V1, V1, 1 5C: ADDU V1, V1, V0 60: JAL ~Func:rand_int 64: SH V1, 8E (S0) 68: LWC1 F12, C (S0) 6C: MTC1 V0, F0 70: NOP 74: CVT.S.W F0, F0 78: ADD.S F12, F12, F0 7C: LIF F0, 90.0 84: JAL ~Func:clamp_angle 88: SUB.S F12, F12, F0 8C: SWC1 F0, C (S0) 90: LW V0, CC (S2) 94: LW V0, 0 (V0) 98: SW V0, 28 (S0) 9C: LI V0, 3 A0: SW V0, 70 (S3) A4: LW RA, 20 (SP) A8: LW S3, 1C (SP) AC: LW S2, 18 (SP) B0: LW S1, 14 (SP) B4: LW S0, 10 (SP) B8: JR RA BC: ADDIU SP, SP, 28 } #new:Function $Function_802404C0 { 0: ADDIU SP, SP, FFB8 4: SW S4, 40 (SP) 8: COPY S4, A0 C: SW RA, 44 (SP) 10: SW S3, 3C (SP) 14: SW S2, 38 (SP) 18: SW S1, 34 (SP) 1C: SW S0, 30 (SP) 20: LW S1, 148 (S4) 24: COPY S2, A1 28: LH A0, 8 (S1) 2C: JAL ~Func:get_npc_unsafe 30: COPY S3, A2 34: LW V1, 14 (S2) 38: BLTZ V1, .o100 3C: COPY S0, V0 40: COPY A0, S3 44: SW R0, 10 (SP) 48: LW A2, 24 (S2) 4C: LW A3, 28 (S2) 50: JAL 800490B4 54: COPY A1, S1 58: BEQ V0, R0, .o100 5C: CLEAR A0 60: COPY A1, S0 64: CLEAR A2 68: LH V1, A8 (S0) 6C: LIF F0, 1.0 74: LIF F2, 2.0 7C: LIF F4, -20.0 84: LI V0, F 88: SW V0, 1C (SP) 8C: MTC1 V1, F6 90: NOP 94: CVT.S.W F6, F6 98: MFC1 A3, F6 9C: ADDIU V0, SP, 28 A0: SW V0, 20 (SP) A4: SWC1 F0, 10 (SP) A8: SWC1 F2, 14 (SP) AC: JAL ~Func:fx_emote B0: SWC1 F4, 18 (SP) B4: LAW V0, 800F7B30 BC: LWC1 F12, 38 (S0) C0: LWC1 F14, 40 (S0) C4: LW A2, 28 (V0) C8: JAL ~Func:atan2 CC: LW A3, 30 (V0) D0: COPY A0, S0 D4: LI A1, 2F4 D8: LUI A2, 20 DC: JAL ~Func:ai_enemy_play_sound E0: SWC1 F0, C (A0) E4: LW V0, 18 (S1) E8: LHU V0, 2A (V0) EC: ANDI V0, V0, 1 F0: BNE V0, R0, .o198 F4: LI V0, A F8: BEQ R0, R0, .o198 FC: LI V0, C .o100 100: LH V0, 8C (S0) 104: BNE V0, R0, .o19C 108: NOP 10C: LHU V0, 8E (S0) 110: ADDIU V0, V0, FFFF 114: SH V0, 8E (S0) 118: SLL V0, V0, 10 11C: BNE V0, R0, .o19C 120: NOP 124: LW V0, 74 (S4) 128: ADDIU V0, V0, FFFF 12C: BEQ V0, R0, .o194 130: SW V0, 74 (S4) 134: LW V0, 18 (S1) 138: LHU V0, 2A (V0) 13C: ANDI V0, V0, 10 140: BNE V0, R0, .o160 144: NOP 148: LWC1 F0, C (S0) 14C: LIF F12, 180.0 154: JAL ~Func:clamp_angle 158: ADD.S F12, F0, F12 15C: SWC1 F0, C (S0) .o160 160: LW A0, 8 (S2) 164: SRL V0, A0, 1F 168: ADDU A0, A0, V0 16C: SRA A0, A0, 1 170: JAL ~Func:rand_int 174: ADDIU A0, A0, 1 178: LW V1, 8 (S2) 17C: SRL A0, V1, 1F 180: ADDU V1, V1, A0 184: SRA V1, V1, 1 188: ADDU V1, V1, V0 18C: BEQ R0, R0, .o19C 190: SH V1, 8E (S0) .o194 194: LI V0, 4 .o198 198: SW V0, 70 (S4) .o19C 19C: LW RA, 44 (SP) 1A0: LW S4, 40 (SP) 1A4: LW S3, 3C (SP) 1A8: LW S2, 38 (SP) 1AC: LW S1, 34 (SP) 1B0: LW S0, 30 (SP) 1B4: JR RA 1B8: ADDIU SP, SP, 48 } #new:Function $Function_8024067C { 0: ADDIU SP, SP, FFE0 4: SW S1, 14 (SP) 8: COPY S1, A0 C: SW RA, 1C (SP) 10: SW S2, 18 (SP) 14: SW S0, 10 (SP) 18: LW S0, 148 (S1) 1C: LH A0, 8 (S0) 20: JAL ~Func:get_npc_unsafe 24: COPY S2, A1 28: LW V1, 78 (S1) 2C: ADDIU V1, V1, 1 30: SW V1, 78 (S1) 34: LW A0, D0 (S0) 38: LW A0, 0 (A0) 3C: SLT V1, V1, A0 40: BNE V1, R0, .o4C 44: COPY A1, V0 48: SW R0, 78 (S1) .o4C 4C: LW V0, CC (S0) 50: LW V0, 4 (V0) 54: SW V0, 28 (A1) 58: LW V0, D0 (S0) 5C: LW V0, 7C (V0) 60: BGEZ V0, .o74 64: NOP 68: LWC1 F0, 0 (S2) 6C: BEQ R0, R0, .o94 70: SWC1 F0, 18 (A1) .o74 74: LAD F2, $ConstDouble_80246A08 7C: MTC1 V0, F0 80: NOP 84: CVT.D.W F0, F0 88: DIV.D F0, F0, F2 8C: CVT.S.D F0, F0 90: SWC1 F0, 18 (A1) .o94 94: LI V0, 1 98: SW V0, 70 (S1) 9C: LW RA, 1C (SP) A0: LW S2, 18 (SP) A4: LW S1, 14 (SP) A8: LW S0, 10 (SP) AC: JR RA B0: ADDIU SP, SP, 20 } #new:Function $Function_80240730 { 0: ADDIU SP, SP, FFE0 4: SW S1, 14 (SP) 8: COPY S1, A0 C: SW RA, 18 (SP) 10: SW S0, 10 (SP) 14: LW S0, 148 (S1) 18: JAL ~Func:get_npc_unsafe 1C: LH A0, 8 (S0) 20: LW V1, CC (S0) 24: LIF F4, 10.0 2C: LIF F0, 2.0 34: LWC1 F2, 3C (V0) 38: LW A0, 10 (V1) 3C: LW V1, 0 (V0) 40: SWC1 F4, 1C (V0) 44: SWC1 F0, 14 (V0) 48: SWC1 F2, 64 (V0) 4C: ORI V1, V1, 800 50: SW V1, 0 (V0) 54: SW A0, 28 (V0) 58: LI V0, B 5C: SW V0, 70 (S1) 60: LW RA, 18 (SP) 64: LW S1, 14 (SP) 68: LW S0, 10 (SP) 6C: JR RA 70: ADDIU SP, SP, 20 } #new:Function $Function_802407A4 { 0: ADDIU SP, SP, FFE8 4: SW S0, 10 (SP) 8: COPY S0, A0 C: SW RA, 14 (SP) 10: LW V0, 148 (S0) 14: JAL ~Func:get_npc_unsafe 18: LH A0, 8 (V0) 1C: COPY A0, V0 20: LWC1 F2, 3C (A0) 24: LWC1 F0, 1C (A0) 28: ADD.S F2, F2, F0 2C: LWC1 F4, 14 (A0) 30: SUB.S F0, F0, F4 34: LWC1 F4, 64 (A0) 38: C.LT.S F4, F2 3C: SWC1 F2, 3C (A0) 40: BC1T .o68 44: SWC1 F0, 1C (A0) 48: LW V0, 0 (A0) 4C: LI V1, F7FF 50: SWC1 F4, 3C (A0) 54: SW R0, 1C (A0) 58: AND V0, V0, V1 5C: SW V0, 0 (A0) 60: LI V0, C 64: SW V0, 70 (S0) .o68 68: LW RA, 14 (SP) 6C: LW S0, 10 (SP) 70: JR RA 74: ADDIU SP, SP, 18 } #new:Function $Function_8024081C { 0: ADDIU SP, SP, FFD0 4: SW S3, 1C (SP) 8: COPY S3, A0 C: SW RA, 20 (SP) 10: SW S2, 18 (SP) 14: SW S1, 14 (SP) 18: SW S0, 10 (SP) 1C: SDC1 F20, 28 (SP) 20: LW S1, 148 (S3) 24: LH A0, 8 (S1) 28: JAL ~Func:get_npc_unsafe 2C: COPY S0, A1 30: LW A0, 20 (S0) 34: COPY S2, V0 38: SRL V1, A0, 1F 3C: ADDU A0, A0, V1 40: SRA A0, A0, 1 44: JAL ~Func:rand_int 48: ADDIU A0, A0, 1 4C: LW V1, 20 (S0) 50: LWC1 F12, 38 (S2) 54: SRL A0, V1, 1F 58: ADDU V1, V1, A0 5C: SRA V1, V1, 1 60: ADDU V1, V1, V0 64: SH V1, 8E (S2) 68: LW V0, CC (S1) 6C: LWC1 F14, 40 (S2) 70: LW V0, C (V0) 74: SW V0, 28 (S2) 78: LWC1 F0, 18 (S0) 7C: LAW V0, 800F7B30 84: SWC1 F0, 18 (S2) 88: LW A2, 28 (V0) 8C: JAL ~Func:atan2 90: LW A3, 30 (V0) 94: MOV.S F20, F0 98: LWC1 F12, C (S2) 9C: JAL ~Func:get_clamped_angle_diff A0: MOV.S F14, F20 A4: MOV.S F2, F0 A8: LW V0, 1C (S0) AC: ABS.S F0, F2 B0: MTC1 V0, F4 B4: NOP B8: CVT.S.W F4, F4 BC: C.LT.S F4, F0 C0: NOP C4: BC1F .oFC C8: NOP CC: MTC1 R0, F0 D0: LWC1 F20, C (S2) D4: C.LT.S F2, F0 D8: NOP DC: BC1F .oF8 E0: SUBU V0, R0, V0 E4: MTC1 V0, F0 E8: NOP EC: CVT.S.W F0, F0 F0: BEQ R0, R0, .oFC F4: ADD.S F20, F20, F0 .oF8 F8: ADD.S F20, F20, F4 .oFC FC: JAL ~Func:clamp_angle 100: MOV.S F12, F20 104: LI V0, D 108: SWC1 F0, C (S2) 10C: SW V0, 70 (S3) 110: LW RA, 20 (SP) 114: LW S3, 1C (SP) 118: LW S2, 18 (SP) 11C: LW S1, 14 (SP) 120: LW S0, 10 (SP) 124: LDC1 F20, 28 (SP) 128: JR RA 12C: ADDIU SP, SP, 30 } #new:Function $Function_8024094C { 0: ADDIU SP, SP, FFB8 4: SW S3, 3C (SP) 8: COPY S3, A0 C: SW RA, 40 (SP) 10: SW S2, 38 (SP) 14: SW S1, 34 (SP) 18: SW S0, 30 (SP) 1C: LW S2, 148 (S3) 20: COPY S1, A1 24: LH A0, 8 (S2) 28: JAL ~Func:get_npc_unsafe 2C: COPY S0, A2 30: COPY A0, S0 34: COPY A1, S2 38: LI V1, 1 3C: SW V1, 10 (SP) 40: LW A2, 24 (S1) 44: LW A3, 28 (S1) 48: JAL 800490B4 4C: COPY S0, V0 50: BNE V0, R0, .oCC 54: COPY A0, S0 58: LI A0, 2 5C: COPY A1, S0 60: CLEAR A2 64: LH V1, A8 (S0) 68: LIF F0, 1.0 70: LIF F2, 2.0 78: LIF F4, -20.0 80: LI V0, F 84: SW V0, 1C (SP) 88: MTC1 V1, F6 8C: NOP 90: CVT.S.W F6, F6 94: MFC1 A3, F6 98: ADDIU V0, SP, 28 9C: SW V0, 20 (SP) A0: SWC1 F0, 10 (SP) A4: SWC1 F2, 14 (SP) A8: JAL ~Func:fx_emote AC: SWC1 F4, 18 (SP) B0: LW V0, CC (S2) B4: LW V1, 0 (V0) B8: LI V0, 19 BC: SH V0, 8E (S0) C0: LI V0, E C4: BEQ R0, R0, .o100 C8: SW V1, 28 (S0) .oCC CC: JAL 8003D660 D0: LI A1, 1 D4: LW A1, 18 (S0) D8: LW A2, C (S0) DC: JAL ~Func:npc_move_heading E0: COPY A0, S0 E4: LH V0, 8E (S0) E8: LHU V1, 8E (S0) EC: BLEZ V0, .oFC F0: ADDIU V0, V1, FFFF F4: BEQ R0, R0, .o104 F8: SH V0, 8E (S0) .oFC FC: LI V0, C .o100 100: SW V0, 70 (S3) .o104 104: LW RA, 40 (SP) 108: LW S3, 3C (SP) 10C: LW S2, 38 (SP) 110: LW S1, 34 (SP) 114: LW S0, 30 (SP) 118: JR RA 11C: ADDIU SP, SP, 48 } #new:Function $Function_80240A6C { 0: ADDIU SP, SP, FFE0 4: SW S1, 14 (SP) 8: COPY S1, A0 C: SW RA, 18 (SP) 10: SW S0, 10 (SP) 14: LW S0, 148 (S1) 18: JAL ~Func:get_npc_unsafe 1C: LH A0, 8 (S0) 20: LHU V1, 8E (V0) 24: ADDIU V1, V1, FFFF 28: SH V1, 8E (V0) 2C: SLL V1, V1, 10 30: BNE V1, R0, .o54 34: NOP 38: LW V0, B0 (S0) 3C: ANDI V0, V0, 80 40: BEQ V0, R0, .o50 44: LI V0, F 48: BEQ R0, R0, .o54 4C: SW V0, 70 (S1) .o50 50: SW R0, 70 (S1) .o54 54: LW RA, 18 (SP) 58: LW S1, 14 (SP) 5C: LW S0, 10 (SP) 60: JR RA 64: ADDIU SP, SP, 20 } #new:Function $Function_80240AD4 { 0: ADDIU SP, SP, FFE0 4: SW S1, 14 (SP) 8: COPY S1, A0 C: SW RA, 1C (SP) 10: SW S2, 18 (SP) 14: SW S0, 10 (SP) 18: LW S0, 148 (S1) 1C: LH A0, 8 (S0) 20: JAL ~Func:get_npc_unsafe 24: COPY S2, A1 28: LW V1, D0 (S0) 2C: LW A0, 78 (S1) 30: LW V1, 0 (V1) 34: SLT V1, A0, V1 38: BEQ V1, R0, .o88 3C: COPY A2, V0 40: SLL V0, A0, 1 44: ADDU V0, V0, A0 48: SLL A1, V0, 2 .o4C 4C: LW V1, D0 (S0) 50: LWC1 F2, 3C (A2) 54: ADDU V0, A1, V1 58: LWC1 F0, 8 (V0) 5C: CVT.S.W F0, F0 60: C.LE.S F0, F2 64: NOP 68: BC1FL .o78 6C: ADDIU A0, A0, 1 70: BEQ R0, R0, .o88 74: SW A0, 78 (S1) .o78 78: LW V0, 0 (V1) 7C: SLT V0, A0, V0 80: BNE V0, R0, .o4C 84: ADDIU A1, A1, C .o88 88: LWC1 F0, 0 (S2) 8C: SWC1 F0, 18 (A2) 90: LW V0, CC (S0) 94: LW V0, 4 (V0) 98: SW V0, 28 (A2) 9C: LI V0, 1 A0: SW R0, 74 (S1) A4: SW V0, 70 (S1) A8: LW RA, 1C (SP) AC: LW S2, 18 (SP) B0: LW S1, 14 (SP) B4: LW S0, 10 (SP) B8: JR RA BC: ADDIU SP, SP, 20 } #new:Function $Function_80240B94 { 0: ADDIU SP, SP, FF98 4: SW S4, 58 (SP) 8: COPY S4, A0 C: SW RA, 60 (SP) 10: SW S5, 5C (SP) 14: SW S3, 54 (SP) 18: SW S2, 50 (SP) 1C: SW S1, 4C (SP) 20: SW S0, 48 (SP) 24: LW S1, 148 (S4) 28: LH A0, 8 (S1) 2C: JAL ~Func:get_npc_unsafe 30: COPY S0, A1 34: LW V1, C (S4) 38: COPY A0, S4 3C: LW A1, 0 (V1) 40: JAL ~Func:get_variable 44: COPY S2, V0 48: SW R0, 18 (SP) 4C: LW V1, D0 (S1) 50: LW V1, 94 (V1) 54: SW V1, 1C (SP) 58: LW V1, D0 (S1) 5C: LW V1, 80 (V1) 60: SW V1, 20 (SP) 64: LW V1, D0 (S1) 68: LW V1, 88 (V1) 6C: SW V1, 24 (SP) 70: LW V1, D0 (S1) 74: LW V1, 8C (V1) 78: ADDIU S5, SP, 18 7C: SW V1, 28 (SP) 80: LW V1, D0 (S1) 84: LIF F0, 65.0 8C: LW V1, 90 (V1) 90: COPY S3, V0 94: SWC1 F0, 30 (SP) 98: SH R0, 34 (SP) 9C: BNE S0, R0, .oB4 A0: SW V1, 2C (SP) A4: LW V0, B0 (S1) A8: ANDI V0, V0, 4 AC: BEQ V0, R0, .o1C0 B0: NOP .oB4 B4: LI A0, F7FF B8: SW R0, 70 (S4) BC: SH R0, 8E (S2) C0: LW V0, CC (S1) C4: LW V1, 0 (S2) C8: LW V0, 0 (V0) CC: AND V1, V1, A0 D0: SW V1, 0 (S2) D4: SW V0, 28 (S2) D8: LW V0, D0 (S1) DC: LW V0, 98 (V0) E0: BNEL V0, R0, .oF8 E4: LI V0, FDFF E8: ORI V0, V1, 200 EC: LI V1, FFF7 F0: BEQ R0, R0, .o100 F4: AND V0, V0, V1 .oF8 F8: AND V0, V1, V0 FC: ORI V0, V0, 8 .o100 100: SW V0, 0 (S2) 104: LW V0, B0 (S1) 108: ANDI V0, V0, 4 10C: BEQ V0, R0, .o130 110: LI V0, 63 114: SW V0, 70 (S4) 118: SW R0, 74 (S4) 11C: LW V0, B0 (S1) 120: LI V1, FFFB 124: AND V0, V0, V1 128: BEQ R0, R0, .o15C 12C: SW V0, B0 (S1) .o130 130: LW V0, 0 (S1) 134: LUI V1, 4000 138: AND V0, V0, V1 13C: BEQ V0, R0, .o15C 140: LUI V1, BFFF 144: LI V0, C 148: SW V0, 70 (S4) 14C: LW V0, 0 (S1) 150: ORI V1, V1, FFFF 154: AND V0, V0, V1 158: SW V0, 0 (S1) .o15C 15C: ADDIU A1, SP, 38 160: ADDIU A2, SP, 3C 164: LWC1 F0, 38 (S2) 168: LH V0, A8 (S2) 16C: LIF F4, 100.0 174: MTC1 V0, F6 178: NOP 17C: CVT.S.W F6, F6 180: ADDIU V0, SP, 44 184: SWC1 F0, 38 (SP) 188: LWC1 F0, 3C (S2) 18C: LWC1 F2, 40 (S2) 190: ADD.S F0, F0, F6 194: SWC1 F4, 44 (SP) 198: SWC1 F2, 40 (SP) 19C: SWC1 F0, 3C (SP) 1A0: SW V0, 10 (SP) 1A4: LW A0, 80 (S2) 1A8: JAL ~Func:npc_raycast_down_sides 1AC: ADDIU A3, SP, 40 1B0: BEQ V0, R0, .o1C0 1B4: NOP 1B8: LWC1 F0, 3C (SP) 1BC: SWC1 F0, 3C (S2) .o1C0 1C0: LW V1, 70 (S4) 1C4: SLTIU V0, V1, 64 1C8: BEQ V0, R0, .o2D4 1CC: SLL V0, V1, 2 1D0: LTW V0, V0 ($JumpTable_80246A10) 1DC: JR V0 1E0: NOP % LBL: from $JumpTable_80246A10 , entry 0` 1E4: COPY A0, S4 1E8: COPY A1, S3 1EC: JAL $Function_80240000 1F0: COPY A2, S5 % LBL: from $JumpTable_80246A10 , entry 1` 1F4: COPY A0, S4 1F8: COPY A1, S3 1FC: JAL $Function_80240158 200: COPY A2, S5 204: BEQ R0, R0, .o2D4 208: NOP % LBL: from $JumpTable_80246A10 , entry 2` 20C: COPY A0, S4 210: COPY A1, S3 214: JAL $Function_80240400 218: COPY A2, S5 % LBL: from $JumpTable_80246A10 , entry 3` 21C: COPY A0, S4 220: COPY A1, S3 224: JAL $Function_802404C0 228: COPY A2, S5 22C: BEQ R0, R0, .o2D4 230: NOP % LBL: from $JumpTable_80246A10 , entry 4` 234: COPY A0, S4 238: COPY A1, S3 23C: JAL $Function_8024067C 240: COPY A2, S5 244: BEQ R0, R0, .o2D4 248: NOP % LBL: from $JumpTable_80246A10 , entry 10` 24C: COPY A0, S4 250: COPY A1, S3 254: JAL $Function_80240730 258: COPY A2, S5 % LBL: from $JumpTable_80246A10 , entry 11` 25C: COPY A0, S4 260: COPY A1, S3 264: JAL $Function_802407A4 268: COPY A2, S5 26C: BEQ R0, R0, .o2D4 270: NOP % LBL: from $JumpTable_80246A10 , entry 12` 274: COPY A0, S4 278: COPY A1, S3 27C: JAL $Function_8024081C 280: COPY A2, S5 % LBL: from $JumpTable_80246A10 , entry 13` 284: COPY A0, S4 288: COPY A1, S3 28C: JAL $Function_8024094C 290: COPY A2, S5 294: BEQ R0, R0, .o2D4 298: NOP % LBL: from $JumpTable_80246A10 , entry 14` 29C: COPY A0, S4 2A0: COPY A1, S3 2A4: JAL $Function_80240A6C 2A8: COPY A2, S5 2AC: BEQ R0, R0, .o2D4 2B0: NOP % LBL: from $JumpTable_80246A10 , entry 15` 2B4: COPY A0, S4 2B8: COPY A1, S3 2BC: JAL $Function_80240AD4 2C0: COPY A2, S5 2C4: BEQ R0, R0, .o2D4 2C8: NOP % LBL: from $JumpTable_80246A10 , entry 99` 2CC: JAL 8004A73C 2D0: COPY A0, S4 % LBL: from $JumpTable_80246A10 , entry 98` .o2D4 2D4: LW RA, 60 (SP) 2D8: LW S5, 5C (SP) 2DC: LW S4, 58 (SP) 2E0: LW S3, 54 (SP) 2E4: LW S2, 50 (SP) 2E8: LW S1, 4C (SP) 2EC: LW S0, 48 (SP) 2F0: CLEAR V0 2F4: JR RA 2F8: ADDIU SP, SP, 68 } #new:Function $Function_80240E90 { 0: ADDIU SP, SP, FFE0 4: SW S1, 14 (SP) 8: COPY S1, A0 C: SW RA, 18 (SP) 10: SW S0, 10 (SP) 14: LW S0, 148 (S1) 18: JAL ~Func:get_npc_unsafe 1C: LH A0, 8 (S0) 20: LI V1, 1 24: COPY A0, V0 28: SW V1, 6C (S0) 2C: LH V0, 8C (A0) 30: BNE V0, R0, .o58 34: LI V0, 2 38: LHU V1, 72 (S0) 3C: SW V0, 6C (S0) 40: SH V1, 8E (A0) 44: LW V0, CC (S0) 48: LW V0, 20 (V0) 4C: SW V0, 28 (A0) 50: LI V0, 1F 54: SW V0, 70 (S1) .o58 58: LW RA, 18 (SP) 5C: LW S1, 14 (SP) 60: LW S0, 10 (SP) 64: JR RA 68: ADDIU SP, SP, 20 } #new:Function $Function_80240EFC { 0: ADDIU SP, SP, FFE0 4: SW S1, 14 (SP) 8: COPY S1, A0 C: SW RA, 18 (SP) 10: SW S0, 10 (SP) 14: LW S0, 148 (S1) 18: JAL ~Func:get_npc_unsafe 1C: LH A0, 8 (S0) 20: COPY A0, V0 24: LHU V0, 8E (A0) 28: ADDIU V0, V0, FFFF 2C: SH V0, 8E (A0) 30: SLL V0, V0, 10 34: BGTZ V0, .o5C 38: LI V0, 3 3C: LHU V1, 76 (S0) 40: SW V0, 6C (S0) 44: SH V1, 8E (A0) 48: LW V0, CC (S0) 4C: LW V0, 24 (V0) 50: SW V0, 28 (A0) 54: LI V0, 20 58: SW V0, 70 (S1) .o5C 5C: LW RA, 18 (SP) 60: LW S1, 14 (SP) 64: LW S0, 10 (SP) 68: JR RA 6C: ADDIU SP, SP, 20 } #new:Function $Function_80240F6C { 0: ADDIU SP, SP, FFC0 4: SW S1, 34 (SP) 8: COPY S1, A0 C: SW RA, 38 (SP) 10: SW S0, 30 (SP) 14: LW S0, 148 (S1) 18: JAL ~Func:get_npc_unsafe 1C: LH A0, 8 (S0) 20: COPY A1, V0 24: LHU V0, 8E (A1) 28: ADDIU V0, V0, FFFF 2C: SH V0, 8E (A1) 30: SLL V0, V0, 10 34: BGTZ V0, .oC4 38: LI V0, 4 3C: LW V1, CC (S0) 40: SW V0, 6C (S0) 44: LW V0, 0 (V1) 48: SW V0, 28 (A1) 4C: LHU V0, 7A (S0) 50: SH V0, 8E (A1) 54: LW V0, 78 (S0) 58: SLTI V0, V0, 8 5C: BNE V0, R0, .oC0 60: LI V0, 21 64: LI A0, 3 68: ADDIU V1, SP, 28 6C: LH A3, A8 (A1) 70: LIF F0, 1.0 78: LIF F2, 2.0 80: LIF F4, -20.0 88: MTC1 A3, F6 8C: NOP 90: CVT.S.W F6, F6 94: SWC1 F0, 10 (SP) 98: SWC1 F2, 14 (SP) 9C: SWC1 F4, 18 (SP) A0: LW V0, 78 (S0) A4: MFC1 A3, F6 A8: CLEAR A2 AC: SW V1, 20 (SP) B0: ADDIU V0, V0, FFFF B4: JAL ~Func:fx_emote B8: SW V0, 1C (SP) BC: LI V0, 21 .oC0 C0: SW V0, 70 (S1) .oC4 C4: LW RA, 38 (SP) C8: LW S1, 34 (SP) CC: LW S0, 30 (SP) D0: JR RA D4: ADDIU SP, SP, 40 } #new:Function $Function_80241044 { 0: ADDIU SP, SP, FFE0 4: SW S1, 14 (SP) 8: COPY S1, A0 C: SW RA, 18 (SP) 10: SW S0, 10 (SP) 14: LW S0, 148 (S1) 18: JAL ~Func:get_npc_unsafe 1C: LH A0, 8 (S0) 20: LHU V1, 8E (V0) 24: ADDIU V1, V1, FFFF 28: SH V1, 8E (V0) 2C: SLL V1, V1, 10 30: BGTZ V1, .o40 34: LI V0, C 38: SW R0, 6C (S0) 3C: SW V0, 70 (S1) .o40 40: LW RA, 18 (SP) 44: LW S1, 14 (SP) 48: LW S0, 10 (SP) 4C: JR RA 50: ADDIU SP, SP, 20 } #new:Function $Function_80241098 { 0: ADDIU SP, SP, FFD0 4: SW RA, 24 (SP) 8: SW S4, 20 (SP) C: SW S3, 1C (SP) 10: SW S2, 18 (SP) 14: SW S1, 14 (SP) 18: SW S0, 10 (SP) 1C: SDC1 F20, 28 (SP) 20: LW S0, 148 (A0) 24: LH A0, 8 (S0) 28: JAL ~Func:get_npc_unsafe 2C: LI S1, 1 30: LH A0, 8 (S0) 34: COPY S0, V0 38: LA A1, 800B1D80 40: LAH V1, 8009A634 48: ADDU A0, A0, S1 4C: SLL V0, V1, 2 50: ADDU V0, V0, V1 54: SLL V0, V0, 2 58: SUBU V0, V0, V1 5C: SLL V1, V0, 3 60: ADDU V0, V0, V1 64: SLL V0, V0, 3 68: JAL ~Func:get_enemy 6C: ADDU S2, V0, A1 70: LA S4, 800F7B30 78: LWC1 F12, 38 (S0) 7C: LW V1, 0 (S4) 80: LWC1 F14, 40 (S0) 84: LW A2, 28 (V1) 88: LW A3, 30 (V1) 8C: JAL ~Func:dist2D 90: COPY S3, V0 94: LWC1 F2, 74 (S3) 98: CVT.S.W F2, F2 9C: C.LT.S F2, F0 A0: NOP A4: BC1TL .oAC A8: CLEAR S1 .oAC AC: LWC1 F12, 6C (S2) B0: LWC1 F14, C (S0) B4: LIF F20, 270.0 BC: JAL ~Func:get_clamped_angle_diff C0: NOP C4: JAL ~Func:clamp_angle C8: MOV.S F12, F0 CC: LAD F2, $ConstDouble_80246BA0 D4: CVT.D.S F0, F0 D8: C.LT.D F0, F2 DC: NOP E0: BC1F .oF0 E4: NOP E8: LIF F20, 90.0 .oF0 F0: LWC1 F12, 38 (S0) F4: LW V0, 0 (S4) F8: LWC1 F14, 40 (S0) FC: LW A2, 28 (V0) 100: JAL ~Func:atan2 104: LW A3, 30 (V0) 108: MOV.S F12, F20 10C: JAL ~Func:get_clamped_angle_diff 110: MOV.S F14, F0 114: LWC1 F2, 78 (S3) 118: CVT.S.W F2, F2 11C: ABS.S F0, F0 120: C.LT.S F2, F0 124: NOP 128: BC1TL .o130 12C: CLEAR S1 .o130 130: LW V0, 0 (S4) 134: LWC1 F0, 3C (S0) 138: LWC1 F2, 2C (V0) 13C: LH V0, A8 (S0) 140: SUB.S F0, F0, F2 144: MTC1 V0, F2 148: NOP 14C: CVT.D.W F2, F2 150: ADD.D F2, F2, F2 154: ABS.S F0, F0 158: CVT.D.S F0, F0 15C: C.LE.D F2, F0 160: NOP 164: BC1TL .o16C 168: CLEAR S1 .o16C 16C: LAB V1, 8010EBB3 174: LI V0, 9 178: BEQL V1, V0, .o180 17C: CLEAR S1 .o180 180: LI V0, 7 184: BEQL V1, V0, .o18C 188: CLEAR S1 .o18C 18C: COPY V0, S1 190: LW RA, 24 (SP) 194: LW S4, 20 (SP) 198: LW S3, 1C (SP) 19C: LW S2, 18 (SP) 1A0: LW S1, 14 (SP) 1A4: LW S0, 10 (SP) 1A8: LDC1 F20, 28 (SP) 1AC: JR RA 1B0: ADDIU SP, SP, 30 } #new:Function $Function_8024124C { 0: ADDIU SP, SP, FFD0 4: SW S4, 28 (SP) 8: COPY S4, A0 C: SW RA, 2C (SP) 10: SW S3, 24 (SP) 14: SW S2, 20 (SP) 18: SW S1, 1C (SP) 1C: SW S0, 18 (SP) 20: LW S1, 148 (S4) 24: LH A0, 8 (S1) 28: JAL ~Func:get_npc_unsafe 2C: COPY S0, A1 30: BNE S0, R0, .o48 34: COPY S2, V0 38: LW V0, B0 (S1) 3C: ANDI V0, V0, 4 40: BEQ V0, R0, .o98 44: NOP .o48 48: SW R0, 70 (S4) 4C: LW V0, 0 (S2) 50: LUI V1, 1F30 54: SH R0, 8E (S2) 58: ORI V0, V0, 102 5C: SW V0, 0 (S2) 60: LW V0, 0 (S1) 64: LIF F0, -1000.0 6C: OR V0, V0, V1 70: SW V0, 0 (S1) 74: SW R0, 38 (S2) 78: SWC1 F0, 3C (S2) 7C: SW R0, 40 (S2) 80: LW V1, B0 (S1) 84: ANDI V0, V1, 4 88: BEQ V0, R0, .o98 8C: LI V0, FFFB 90: AND V0, V1, V0 94: SW V0, B0 (S1) .o98 98: LW S3, 70 (S4) 9C: BEQ S3, R0, .oB4 A0: LI V0, 1 A4: BEQ S3, V0, .o1C8 A8: NOP AC: BEQ R0, R0, .o23C B0: NOP .oB4 B4: LH A0, 8 (S1) B8: JAL ~Func:get_enemy BC: ADDIU A0, A0, FFFF C0: COPY S0, V0 C4: JAL ~Func:get_npc_unsafe C8: LH A0, 8 (S0) CC: LI V1, 1 D0: COPY S3, V0 D4: SB V1, 7 (S1) D8: LW V1, 6C (S0) DC: LI V0, 3 E0: BNE V1, V0, .o23C E4: NOP E8: LW A1, A8 (S1) EC: BEQ A1, R0, .oFC F0: COPY A0, S3 F4: JAL ~Func:ai_enemy_play_sound F8: CLEAR A2 .oFC FC: ADDIU A0, SP, 10 100: LWC1 F8, 70 (S1) 104: CVT.S.W F8, F8 108: LWC1 F2, 34 (S3) 10C: LIF F0, 270.0 114: MFC1 A2, F8 118: SUB.S F0, F0, F2 11C: LWC1 F6, 38 (S3) 120: LWC1 F4, 40 (S3) 124: MFC1 A3, F0 128: ADDIU A1, SP, 14 12C: SWC1 F6, 10 (SP) 130: JAL ~Func:add_vec2D_polar 134: SWC1 F4, 14 (SP) 138: LWC1 F0, 10 (SP) 13C: TRUNC.W.S F8, F0 140: MFC1 V0, F8 144: SWC1 F0, 38 (S2) 148: SH V0, 10 (S1) 14C: LWC1 F0, 3C (S3) 150: LWC1 F2, 6C (S1) 154: CVT.S.W F2, F2 158: ADD.S F0, F0, F2 15C: LAW V1, 800F7B30 164: SWC1 F0, 3C (S2) 168: LWC1 F2, 14 (SP) 16C: TRUNC.W.S F8, F0 170: MFC1 V0, F8 174: NOP 178: SH V0, 12 (S1) 17C: TRUNC.W.S F8, F2 180: MFC1 V0, F8 184: SWC1 F2, 40 (S2) 188: SH V0, 14 (S1) 18C: LW A2, 28 (V1) 190: LW A3, 30 (V1) 194: LWC1 F12, 38 (S2) 198: JAL ~Func:atan2 19C: LWC1 F14, 40 (S2) 1A0: LUI V1, E0EF 1A4: SWC1 F0, C (S2) 1A8: LW V0, 0 (S1) 1AC: ORI V1, V1, FFFF 1B0: AND V0, V0, V1 1B4: SW V0, 0 (S1) 1B8: LI V0, 1 1BC: SH R0, 8E (S2) 1C0: BEQ R0, R0, .o23C 1C4: SW V0, 70 (S4) .o1C8 1C8: LH A0, 8 (S1) 1CC: JAL ~Func:get_enemy 1D0: ADDIU A0, A0, FFFF 1D4: COPY S0, V0 1D8: JAL ~Func:get_npc_unsafe 1DC: LH A0, 8 (S0) 1E0: LHU V0, 8E (S2) 1E4: ADDIU V0, V0, 1 1E8: SH V0, 8E (S2) 1EC: SLL V0, V0, 10 1F0: LW V1, 7C (S1) 1F4: SRA V0, V0, 10 1F8: SLT V0, V0, V1 1FC: BEQL V0, R0, .o204 200: SB R0, 7 (S1) .o204 204: LW V1, 6C (S0) 208: LI V0, 4 20C: BNE V1, V0, .o23C 210: LUI V0, 1F10 214: LW V1, 0 (S1) 218: LIF F0, -1000.0 220: OR V1, V1, V0 224: SW V1, 0 (S1) 228: SW R0, 38 (S2) 22C: SWC1 F0, 3C (S2) 230: SW R0, 40 (S2) 234: SB S3, 7 (S1) 238: SW R0, 70 (S4) .o23C 23C: LW RA, 2C (SP) 240: LW S4, 28 (SP) 244: LW S3, 24 (SP) 248: LW S2, 20 (SP) 24C: LW S1, 1C (SP) 250: LW S0, 18 (SP) 254: CLEAR V0 258: JR RA 25C: ADDIU SP, SP, 30 } #new:Function $Function_802414AC { 0: ADDIU SP, SP, FFB0 4: SW S2, 38 (SP) 8: COPY S2, A0 C: SW RA, 48 (SP) 10: SW S5, 44 (SP) 14: SW S4, 40 (SP) 18: SW S3, 3C (SP) 1C: SW S1, 34 (SP) 20: SW S0, 30 (SP) 24: LW S1, 148 (S2) 28: LH A0, 8 (S1) 2C: JAL ~Func:get_npc_unsafe 30: COPY S0, A1 34: LW V1, C (S2) 38: COPY A0, S2 3C: LW A1, 0 (V1) 40: JAL ~Func:get_variable 44: COPY S5, V0 48: SW R0, 10 (SP) 4C: LW V1, D0 (S1) 50: LW V1, 30 (V1) 54: SW V1, 14 (SP) 58: LW V1, D0 (S1) 5C: LW V1, 1C (V1) 60: SW V1, 18 (SP) 64: LW V1, D0 (S1) 68: LW V1, 24 (V1) 6C: SW V1, 1C (SP) 70: LW V1, D0 (S1) 74: LW V1, 28 (V1) 78: ADDIU S4, SP, 10 7C: SW V1, 20 (SP) 80: LW V1, D0 (S1) 84: LIF F0, 65.0 8C: LW V1, 2C (V1) 90: COPY S3, V0 94: SWC1 F0, 28 (SP) 98: SH R0, 2C (SP) 9C: BNE S0, R0, .oB4 A0: SW V1, 24 (SP) A4: LW V0, B0 (S1) A8: ANDI V0, V0, 4 AC: BEQ V0, R0, .o130 B0: NOP .oB4 B4: LI A0, F7FF B8: SW R0, 70 (S2) BC: SH R0, 8E (S5) C0: LW V0, CC (S1) C4: LW V1, 0 (S5) C8: LW V0, 0 (V0) CC: AND V1, V1, A0 D0: SW V1, 0 (S5) D4: SW V0, 28 (S5) D8: LW V0, D0 (S1) DC: LW V0, 34 (V0) E0: BNEL V0, R0, .oF8 E4: LI V0, FDFF E8: ORI V0, V1, 200 EC: LI V1, FFF7 F0: BEQ R0, R0, .o100 F4: AND V0, V0, V1 .oF8 F8: AND V0, V1, V0 FC: ORI V0, V0, 8 .o100 100: SW V0, 0 (S5) 104: LW V0, B0 (S1) 108: ANDI V0, V0, 4 10C: BEQ V0, R0, .o12C 110: LI V0, 63 114: SW V0, 70 (S2) 118: SW R0, 74 (S2) 11C: LW V0, B0 (S1) 120: LI V1, FFFB 124: AND V0, V0, V1 128: SW V0, B0 (S1) .o12C 12C: SW R0, 6C (S1) .o130 130: LW V0, 70 (S2) 134: SLTI V0, V0, 1E 138: BEQ V0, R0, .o160 13C: NOP 140: LW V0, 6C (S1) 144: BNE V0, R0, .o160 148: NOP 14C: JAL $Function_80241098 150: COPY A0, S2 154: BEQ V0, R0, .o160 158: LI V0, 1E 15C: SW V0, 70 (S2) .o160 160: LW V1, 70 (S2) 164: SLTIU V0, V1, 64 168: BEQ V0, R0, .o28C 16C: SLL V0, V1, 2 170: LTW V0, V0 ($JumpTable_80246BA8) 17C: JR V0 180: NOP % LBL: from $JumpTable_80246BA8 , entry 0` 184: COPY A0, S2 188: COPY A1, S3 18C: JAL 800495A0 190: COPY A2, S4 % LBL: from $JumpTable_80246BA8 , entry 1` 194: COPY A0, S2 198: COPY A1, S3 19C: JAL 800496B8 1A0: COPY A2, S4 1A4: BEQ R0, R0, .o28C 1A8: NOP % LBL: from $JumpTable_80246BA8 , entry 2` 1AC: COPY A0, S2 1B0: COPY A1, S3 1B4: JAL 80049B44 1B8: COPY A2, S4 % LBL: from $JumpTable_80246BA8 , entry 3` 1BC: COPY A0, S2 1C0: COPY A1, S3 1C4: JAL 80049C04 1C8: COPY A2, S4 1CC: BEQ R0, R0, .o28C 1D0: NOP % LBL: from $JumpTable_80246BA8 , entry 10` 1D4: COPY A0, S2 1D8: COPY A1, S3 1DC: JAL 80049E3C 1E0: COPY A2, S4 % LBL: from $JumpTable_80246BA8 , entry 11` 1E4: COPY A0, S2 1E8: COPY A1, S3 1EC: JAL 80049ECC 1F0: COPY A2, S4 1F4: BEQ R0, R0, .o28C 1F8: NOP % LBL: from $JumpTable_80246BA8 , entry 12` 1FC: COPY A0, S2 200: COPY A1, S3 204: JAL 80049F7C 208: COPY A2, S4 % LBL: from $JumpTable_80246BA8 , entry 13` 20C: COPY A0, S2 210: COPY A1, S3 214: JAL 8004A124 218: COPY A2, S4 21C: BEQ R0, R0, .o28C 220: NOP % LBL: from $JumpTable_80246BA8 , entry 14` 224: COPY A0, S2 228: COPY A1, S3 22C: JAL 8004A3E8 230: COPY A2, S4 234: BEQ R0, R0, .o28C 238: NOP % LBL: from $JumpTable_80246BA8 , entry 30` 23C: JAL $Function_80240E90 240: COPY A0, S2 % LBL: from $JumpTable_80246BA8 , entry 31` 244: JAL $Function_80240EFC 248: COPY A0, S2 24C: LW V1, 70 (S2) 250: LI V0, 20 254: BNE V1, V0, .o28C 258: NOP % LBL: from $JumpTable_80246BA8 , entry 32` 25C: JAL $Function_80240F6C 260: COPY A0, S2 264: LW V1, 70 (S2) 268: LI V0, 21 26C: BNE V1, V0, .o28C 270: NOP % LBL: from $JumpTable_80246BA8 , entry 33` 274: JAL $Function_80241044 278: COPY A0, S2 27C: BEQ R0, R0, .o28C 280: NOP % LBL: from $JumpTable_80246BA8 , entry 99` 284: JAL 8004A73C 288: COPY A0, S2 % LBL: from $JumpTable_80246BA8 , entry 98` .o28C 28C: LW RA, 48 (SP) 290: LW S5, 44 (SP) 294: LW S4, 40 (SP) 298: LW S3, 3C (SP) 29C: LW S2, 38 (SP) 2A0: LW S1, 34 (SP) 2A4: LW S0, 30 (SP) 2A8: CLEAR V0 2AC: JR RA 2B0: ADDIU SP, SP, 50 } #new:Function $Function_80241760 { 0: ADDIU SP, SP, FFC8 4: SW S3, 2C (SP) 8: COPY S3, A0 C: SW RA, 30 (SP) 10: SW S2, 28 (SP) 14: SW S1, 24 (SP) 18: SW S0, 20 (SP) 1C: LW S1, 148 (S3) 20: LH A0, 8 (S1) 24: JAL ~Func:get_npc_unsafe 28: COPY S2, A1 2C: LW A0, 4 (S2) 30: COPY S0, V0 34: SRL V1, A0, 1F 38: ADDU A0, A0, V1 3C: SRA A0, A0, 1 40: JAL ~Func:rand_int 44: ADDIU A0, A0, 1 48: LW V1, 4 (S2) 4C: SRL A0, V1, 1F 50: ADDU V1, V1, A0 54: SRA V1, V1, 1 58: ADDU V1, V1, V0 5C: SH V1, 8E (S0) 60: LW V1, D0 (S1) 64: LWC1 F0, 40 (S0) 68: LWC1 F4, 0 (V1) 6C: CVT.S.W F4, F4 70: LWC1 F2, 8 (V1) 74: CVT.S.W F2, F2 78: SWC1 F0, 10 (SP) 7C: LW V0, D0 (S1) 80: MFC1 A2, F2 84: LWC1 F0, C (V0) 88: CVT.S.W F0, F0 8C: SWC1 F0, 14 (SP) 90: LW V0, D0 (S1) 94: MFC1 A1, F4 98: LWC1 F0, 10 (V0) 9C: CVT.S.W F0, F0 A0: SWC1 F0, 18 (SP) A4: LW A0, 18 (V1) A8: JAL ~Func:is_point_within_region AC: LW A3, 38 (S0) B0: BEQ V0, R0, .oEC B4: NOP B8: LW V0, D0 (S1) BC: LWC1 F12, 38 (S0) C0: LWC1 F14, 40 (S0) C4: LWC1 F6, 0 (V0) C8: CVT.S.W F6, F6 CC: MFC1 A2, F6 D0: LWC1 F6, 8 (V0) D4: CVT.S.W F6, F6 D8: MFC1 A3, F6 DC: JAL ~Func:atan2 E0: NOP E4: BEQ R0, R0, .o11C E8: SWC1 F0, C (S0) .oEC EC: JAL ~Func:rand_int F0: LI A0, 3C F4: LWC1 F12, C (S0) F8: MTC1 V0, F0 FC: NOP 100: CVT.S.W F0, F0 104: ADD.S F12, F12, F0 108: LIF F0, 30.0 110: JAL ~Func:clamp_angle 114: SUB.S F12, F12, F0 118: SWC1 F0, C (S0) .o11C 11C: LW V0, CC (S1) 120: LW V0, 4 (V0) 124: SW V0, 28 (S0) 128: SW R0, 74 (S3) 12C: LW V0, D0 (S1) 130: LW V0, 14 (V0) 134: BGEZ V0, .o148 138: NOP 13C: LWC1 F0, 0 (S2) 140: BEQ R0, R0, .o168 144: SWC1 F0, 18 (S0) .o148 148: LAD F2, $ConstDouble_80246D38 150: MTC1 V0, F0 154: NOP 158: CVT.D.W F0, F0 15C: DIV.D F0, F0, F2 160: CVT.S.D F0, F0 164: SWC1 F0, 18 (S0) .o168 168: LWC1 F0, 3C (S0) 16C: LIF F3, 3.390625 174: MTC1 R0, F2 178: CVT.D.S F0, F0 17C: MUL.D F0, F0, F2 180: NOP 184: LI V0, 1 188: TRUNC.W.D F6, F0 18C: SWC1 F6, 7C (S1) 190: SW V0, 70 (S3) 194: LW RA, 30 (SP) 198: LW S3, 2C (SP) 19C: LW S2, 28 (SP) 1A0: LW S1, 24 (SP) 1A4: LW S0, 20 (SP) 1A8: JR RA 1AC: ADDIU SP, SP, 38 } #new:Function $Function_80241910 { 0: ADDIU SP, SP, FF80 4: SW S3, 4C (SP) 8: COPY S3, A0 C: SW RA, 58 (SP) 10: SW S5, 54 (SP) 14: SW S4, 50 (SP) 18: SW S2, 48 (SP) 1C: SW S1, 44 (SP) 20: SW S0, 40 (SP) 24: SDC1 F26, 78 (SP) 28: SDC1 F24, 70 (SP) 2C: SDC1 F22, 68 (SP) 30: SDC1 F20, 60 (SP) 34: LW S1, 148 (S3) 38: COPY S2, A1 3C: LH A0, 8 (S1) 40: JAL ~Func:get_npc_unsafe 44: COPY S5, A2 48: COPY S0, V0 4C: CLEAR S4 50: LWC1 F4, 7C (S1) 54: CVT.S.W F4, F4 58: LWC1 F2, 88 (S1) 5C: CVT.S.W F2, F2 60: CVT.D.S F2, F2 64: CVT.D.S F4, F4 68: LWC1 F0, 3C (S0) 6C: LIF F7, 3.390625 74: MTC1 R0, F6 78: CVT.D.S F0, F0 7C: MUL.D F0, F0, F6 80: NOP 84: LI V0, 1 88: LW A0, 6C (S1) 8C: DIV.D F2, F2, F6 90: CVT.S.D F2, F2 94: DIV.D F4, F4, F6 98: CVT.S.D F20, F4 9C: ANDI V1, A0, 11 A0: TRUNC.W.D F8, F0 A4: SWC1 F8, 7C (S1) A8: LWC1 F0, 78 (S1) AC: CVT.S.W F0, F0 B0: CVT.D.S F0, F0 B4: DIV.D F0, F0, F6 B8: CVT.S.D F26, F0 BC: LWC1 F0, 70 (S1) C0: CVT.S.W F0, F0 C4: CVT.D.S F0, F0 C8: DIV.D F0, F0, F6 CC: CVT.S.D F22, F0 D0: BNE V1, V0, .o168 D4: ADD.S F24, F26, F2 D8: LW V0, 0 (S0) DC: ANDI V0, V0, 8 E0: BEQ V0, R0, .o108 E4: ADDIU A1, SP, 28 E8: LWC1 F0, 3C (S0) EC: SUB.S F0, F24, F0 F0: C.LT.S F22, F0 F4: NOP F8: BC1F .o168 FC: ORI V0, A0, 10 100: BEQ R0, R0, .o168 104: SW V0, 6C (S1) .o108 108: ADDIU A2, SP, 2C 10C: LWC1 F0, 38 (S0) 110: LWC1 F2, 3C (S0) 114: LWC1 F4, 40 (S0) 118: LIF F6, 1000.0 120: ADDIU V0, SP, 34 124: SWC1 F0, 28 (SP) 128: SWC1 F2, 2C (SP) 12C: SWC1 F4, 30 (SP) 130: SWC1 F6, 34 (SP) 134: SW V0, 10 (SP) 138: LW A0, 80 (S0) 13C: JAL ~Func:npc_raycast_down_sides 140: ADDIU A3, SP, 30 144: LWC1 F0, 34 (SP) 148: SUB.S F0, F26, F0 14C: C.LT.S F22, F0 150: NOP 154: BC1F .o168 158: NOP 15C: LW V0, 6C (S1) 160: ORI V0, V0, 10 164: SW V0, 6C (S1) .o168 168: LW V0, 6C (S1) 16C: LI V1, 11 170: ANDI V0, V0, 11 174: BNE V0, V1, .o25C 178: NOP 17C: LW V0, 0 (S0) 180: ANDI V0, V0, 8 184: BEQ V0, R0, .o1B0 188: MOV.S F4, F24 18C: SUB.S F2, F24, F20 190: LAD F0, $ConstDouble_80246D40 198: CVT.D.S F2, F2 19C: MUL.D F2, F2, F0 1A0: NOP 1A4: CVT.D.S F0, F20 1A8: BEQ R0, R0, .o214 1AC: ADD.D F0, F0, F2 .o1B0 1B0: ADDIU A1, SP, 28 1B4: ADDIU A2, SP, 2C 1B8: LWC1 F0, 38 (S0) 1BC: LWC1 F2, 40 (S0) 1C0: LIF F4, 1000.0 1C8: ADDIU V0, SP, 34 1CC: SWC1 F20, 2C (SP) 1D0: SWC1 F0, 28 (SP) 1D4: SWC1 F2, 30 (SP) 1D8: SWC1 F4, 34 (SP) 1DC: SW V0, 10 (SP) 1E0: LW A0, 80 (S0) 1E4: JAL ~Func:npc_raycast_down_sides 1E8: ADDIU A3, SP, 30 1EC: LWC1 F4, 2C (SP) 1F0: ADD.S F4, F4, F26 1F4: SUB.S F2, F4, F20 1F8: LAD F0, $ConstDouble_80246D48 200: CVT.D.S F2, F2 204: MUL.D F2, F2, F0 208: NOP 20C: CVT.D.S F0, F20 210: ADD.D F0, F0, F2 .o214 214: CVT.S.D F0, F0 218: SWC1 F0, 3C (S0) 21C: LWC1 F0, 3C (S0) 220: SUB.S F0, F4, F0 224: LIF F3, 1.875 22C: MTC1 R0, F2 230: ABS.S F0, F0 234: CVT.D.S F0, F0 238: C.LT.D F0, F2 23C: NOP 240: BC1F .o31C 244: LI V1, FFEF 248: SWC1 F4, 3C (S0) 24C: LW V0, 6C (S1) 250: AND V0, V0, V1 254: BEQ R0, R0, .o31C 258: SW V0, 6C (S1) .o25C 25C: LW V0, 70 (S1) 260: BLEZ V0, .o31C 264: NOP 268: LWC1 F12, 74 (S1) 26C: JAL ~Func:sin_deg 270: CVT.S.W F12, F12 274: LW V0, 0 (S0) 278: ANDI V0, V0, 8 27C: BEQ V0, R0, .o28C 280: MOV.S F20, F0 284: BEQ R0, R0, .o2CC 288: CLEAR V0 .o28C 28C: ADDIU A1, SP, 28 290: ADDIU A2, SP, 2C 294: LWC1 F0, 38 (S0) 298: LWC1 F2, 3C (S0) 29C: LWC1 F4, 40 (S0) 2A0: LIF F6, 1000.0 2A8: ADDIU V0, SP, 34 2AC: SWC1 F0, 28 (SP) 2B0: SWC1 F2, 2C (SP) 2B4: SWC1 F4, 30 (SP) 2B8: SWC1 F6, 34 (SP) 2BC: SW V0, 10 (SP) 2C0: LW A0, 80 (S0) 2C4: JAL ~Func:npc_raycast_down_sides 2C8: ADDIU A3, SP, 30 .o2CC 2CC: BEQ V0, R0, .o2EC 2D0: NOP 2D4: MUL.S F2, F20, F22 2D8: NOP 2DC: LWC1 F0, 2C (SP) 2E0: ADD.S F0, F0, F26 2E4: BEQ R0, R0, .o2F8 2E8: ADD.S F0, F0, F2 .o2EC 2EC: MUL.S F0, F20, F22 2F0: NOP 2F4: ADD.S F0, F24, F0 .o2F8 2F8: SWC1 F0, 3C (S0) 2FC: LW V0, 74 (S1) 300: ADDIU V0, V0, A 304: MTC1 V0, F12 308: NOP 30C: JAL ~Func:clamp_angle 310: CVT.S.W F12, F12 314: TRUNC.W.S F8, F0 318: SWC1 F8, 74 (S1) .o31C 31C: LW V0, 90 (S1) 320: BGTZ V0, .o44C 324: ADDIU V0, V0, FFFF 328: LW V1, 14 (S2) 32C: BLTZ V1, .o450 330: NOP 334: LW V0, 74 (S3) 338: BGTZ V0, .o444 33C: ADDIU V0, V0, FFFF 340: SW V1, 74 (S3) 344: LH V0, A8 (S0) 348: LWC1 F2, 3C (S0) 34C: MTC1 V0, F0 350: NOP 354: CVT.S.W F0, F0 358: ADD.S F2, F2, F0 35C: LIF F1, 2.5625 364: MTC1 R0, F0 368: LAW V0, 800F7B30 370: CVT.D.S F2, F2 374: ADD.D F2, F2, F0 378: LWC1 F0, 2C (V0) 37C: CVT.D.S F0, F0 380: C.LT.D F0, F2 384: NOP 388: BC1F .o43C 38C: COPY A0, S5 390: SW R0, 10 (SP) 394: LW A2, C (S2) 398: LW A3, 10 (S2) 39C: JAL 800490B4 3A0: COPY A1, S1 3A4: BEQ V0, R0, .o43C 3A8: CLEAR A0 3AC: COPY A1, S0 3B0: CLEAR A2 3B4: LI S2, C 3B8: LH V1, A8 (S0) 3BC: LIF F0, 1.0 3C4: LIF F2, 2.0 3CC: LIF F4, -20.0 3D4: MTC1 V1, F8 3D8: NOP 3DC: CVT.S.W F8, F8 3E0: MFC1 A3, F8 3E4: ADDIU V0, SP, 38 3E8: SW S2, 1C (SP) 3EC: SW V0, 20 (SP) 3F0: SWC1 F0, 10 (SP) 3F4: SWC1 F2, 14 (SP) 3F8: JAL ~Func:fx_emote 3FC: SWC1 F4, 18 (SP) 400: COPY A0, S0 404: LI A1, 2F4 408: LWC1 F0, 3C (A0) 40C: LUI A2, 20 410: JAL ~Func:ai_enemy_play_sound 414: SWC1 F0, 64 (A0) 418: LW V0, 18 (S1) 41C: LHU V0, 2A (V0) 420: ANDI V0, V0, 1 424: BEQ V0, R0, .o434 428: LI V0, A 42C: BEQ R0, R0, .o5F4 430: SW V0, 70 (S3) .o434 434: BEQ R0, R0, .o5F4 438: SW S2, 70 (S3) .o43C 43C: LW V0, 74 (S3) 440: ADDIU V0, V0, FFFF .o444 444: BEQ R0, R0, .o450 448: SW V0, 74 (S3) .o44C 44C: SW V0, 90 (S1) .o450 450: LW V1, D0 (S1) 454: LWC1 F0, 40 (S0) 458: LWC1 F2, 0 (V1) 45C: CVT.S.W F2, F2 460: LWC1 F4, 8 (V1) 464: CVT.S.W F4, F4 468: SWC1 F0, 10 (SP) 46C: LW V0, D0 (S1) 470: MFC1 A1, F2 474: LWC1 F0, C (V0) 478: CVT.S.W F0, F0 47C: SWC1 F0, 14 (SP) 480: LW V0, D0 (S1) 484: MFC1 A2, F4 488: LWC1 F0, 10 (V0) 48C: CVT.S.W F0, F0 490: SWC1 F0, 18 (SP) 494: LW A0, 18 (V1) 498: JAL ~Func:is_point_within_region 49C: LW A3, 38 (S0) 4A0: BEQ V0, R0, .o50C 4A4: NOP 4A8: LW A2, 38 (S0) 4AC: LW V0, D0 (S1) 4B0: LW A3, 40 (S0) 4B4: LWC1 F12, 0 (V0) 4B8: CVT.S.W F12, F12 4BC: LWC1 F14, 8 (V0) 4C0: JAL ~Func:dist2D 4C4: CVT.S.W F14, F14 4C8: LWC1 F2, 18 (S0) 4CC: C.LT.S F2, F0 4D0: NOP 4D4: BC1F .o50C 4D8: SWC1 F0, 34 (SP) 4DC: LWC1 F12, 38 (S0) 4E0: LW V0, D0 (S1) 4E4: LWC1 F14, 40 (S0) 4E8: LWC1 F8, 0 (V0) 4EC: CVT.S.W F8, F8 4F0: MFC1 A2, F8 4F4: LWC1 F8, 8 (V0) 4F8: CVT.S.W F8, F8 4FC: MFC1 A3, F8 500: JAL ~Func:atan2 504: LI S4, 1 508: SWC1 F0, C (S0) .o50C 50C: LW V0, D0 (S1) 510: LW V1, C (V0) 514: LW V0, 10 (V0) 518: OR V1, V1, V0 51C: OR V1, V1, S4 520: BEQ V1, R0, .o544 524: NOP 528: LH V0, 8C (S0) 52C: BNE V0, R0, .o5F4 530: NOP 534: LW A1, 18 (S0) 538: LW A2, C (S0) 53C: JAL ~Func:npc_move_heading 540: COPY A0, S0 .o544 544: LWC1 F0, 3C (S0) 548: LIF F3, 3.390625 550: MTC1 R0, F2 554: CVT.D.S F0, F0 558: MUL.D F0, F0, F2 55C: NOP 560: TRUNC.W.D F8, F0 564: SWC1 F8, 7C (S1) 568: LW V0, 4 (S2) 56C: BLEZ V0, .o5F4 570: NOP 574: LH V0, 8E (S0) 578: LHU V1, 8E (S0) 57C: BLEZ V0, .o594 580: ADDIU V0, V1, FFFF 584: SH V0, 8E (S0) 588: SLL V0, V0, 10 58C: BGTZ V0, .o5F4 590: NOP .o594 594: LI A0, 3E8 598: LI V0, 2 59C: JAL ~Func:rand_int 5A0: SW V0, 70 (S3) 5A4: LI V1, 55555556 5AC: MULT V0, V1 5B0: SRA A0, V0, 1F 5B4: MFHI T0 5B8: SUBU A0, T0, A0 5BC: SLL V1, A0, 1 5C0: ADDU V1, V1, A0 5C4: SUBU V0, V0, V1 5C8: ADDIU V1, V0, 2 5CC: SW V1, 74 (S3) 5D0: LW V0, 2C (S2) 5D4: BLEZL V0, .o5F4 5D8: SW R0, 70 (S3) 5DC: LW V0, 8 (S2) 5E0: BLEZ V0, .o5F0 5E4: SLTI V0, V1, 3 5E8: BEQ V0, R0, .o5F4 5EC: NOP .o5F0 5F0: SW R0, 70 (S3) .o5F4 5F4: LW RA, 58 (SP) 5F8: LW S5, 54 (SP) 5FC: LW S4, 50 (SP) 600: LW S3, 4C (SP) 604: LW S2, 48 (SP) 608: LW S1, 44 (SP) 60C: LW S0, 40 (SP) 610: LDC1 F26, 78 (SP) 614: LDC1 F24, 70 (SP) 618: LDC1 F22, 68 (SP) 61C: LDC1 F20, 60 (SP) 620: JR RA 624: ADDIU SP, SP, 80 } #new:Function $Function_80241F38 { 0: ADDIU SP, SP, FFD8 4: SW S3, 1C (SP) 8: COPY S3, A0 C: SW RA, 20 (SP) 10: SW S2, 18 (SP) 14: SW S1, 14 (SP) 18: SW S0, 10 (SP) 1C: LW S2, 148 (S3) 20: LH A0, 8 (S2) 24: JAL ~Func:get_npc_unsafe 28: COPY S1, A1 2C: LW A0, 8 (S1) 30: COPY S0, V0 34: SRL V1, A0, 1F 38: ADDU A0, A0, V1 3C: SRA A0, A0, 1 40: JAL ~Func:rand_int 44: ADDIU A0, A0, 1 48: LW V1, 8 (S1) 4C: LI A0, B4 50: SRL A1, V1, 1F 54: ADDU V1, V1, A1 58: SRA V1, V1, 1 5C: ADDU V1, V1, V0 60: JAL ~Func:rand_int 64: SH V1, 8E (S0) 68: LWC1 F12, C (S0) 6C: MTC1 V0, F0 70: NOP 74: CVT.S.W F0, F0 78: ADD.S F12, F12, F0 7C: LIF F0, 90.0 84: JAL ~Func:clamp_angle 88: SUB.S F12, F12, F0 8C: SWC1 F0, C (S0) 90: LW V0, CC (S2) 94: LW V0, 0 (V0) 98: SW V0, 28 (S0) 9C: LI V0, 3 A0: SW V0, 70 (S3) A4: LW RA, 20 (SP) A8: LW S3, 1C (SP) AC: LW S2, 18 (SP) B0: LW S1, 14 (SP) B4: LW S0, 10 (SP) B8: JR RA BC: ADDIU SP, SP, 28 } #new:Function $Function_80241FF8 { 0: ADDIU SP, SP, FF88 4: SW S3, 4C (SP) 8: COPY S3, A0 C: SW RA, 54 (SP) 10: SW S4, 50 (SP) 14: SW S2, 48 (SP) 18: SW S1, 44 (SP) 1C: SW S0, 40 (SP) 20: SDC1 F26, 70 (SP) 24: SDC1 F24, 68 (SP) 28: SDC1 F22, 60 (SP) 2C: SDC1 F20, 58 (SP) 30: LW S1, 148 (S3) 34: COPY S2, A1 38: LH A0, 8 (S1) 3C: JAL ~Func:get_npc_unsafe 40: COPY S4, A2 44: COPY S0, V0 48: LWC1 F0, 78 (S1) 4C: CVT.S.W F0, F0 50: CVT.D.S F0, F0 54: LIF F3, 3.390625 5C: MTC1 R0, F2 60: LH V0, 8E (S0) 64: LHU V1, 8E (S0) 68: DIV.D F0, F0, F2 6C: CVT.S.D F24, F0 70: LWC1 F0, 88 (S1) 74: CVT.S.W F0, F0 78: CVT.D.S F0, F0 7C: DIV.D F0, F0, F2 80: CVT.S.D F0, F0 84: BLEZ V0, .o94 88: ADD.S F26, F24, F0 8C: ADDIU V0, V1, FFFF 90: SH V0, 8E (S0) .o94 94: LW V0, 70 (S1) 98: BLEZ V0, .o16C 9C: NOP A0: LWC1 F12, 74 (S1) A4: CVT.S.W F12, F12 A8: MTC1 V0, F0 AC: NOP B0: CVT.S.W F0, F0 B4: CVT.D.S F0, F0 B8: DIV.D F0, F0, F2 BC: JAL ~Func:sin_deg C0: CVT.S.D F22, F0 C4: LW V0, 0 (S0) C8: ANDI V0, V0, 8 CC: BEQ V0, R0, .oDC D0: MOV.S F20, F0 D4: BEQ R0, R0, .o11C D8: CLEAR V0 .oDC DC: ADDIU A1, SP, 28 E0: ADDIU A2, SP, 2C E4: LWC1 F0, 38 (S0) E8: LWC1 F2, 3C (S0) EC: LWC1 F4, 40 (S0) F0: LIF F6, 1000.0 F8: ADDIU V0, SP, 34 FC: SWC1 F0, 28 (SP) 100: SWC1 F2, 2C (SP) 104: SWC1 F4, 30 (SP) 108: SWC1 F6, 34 (SP) 10C: SW V0, 10 (SP) 110: LW A0, 80 (S0) 114: JAL ~Func:npc_raycast_down_sides 118: ADDIU A3, SP, 30 .o11C 11C: BEQ V0, R0, .o13C 120: NOP 124: MUL.S F2, F20, F22 128: NOP 12C: LWC1 F0, 2C (SP) 130: ADD.S F0, F0, F24 134: BEQ R0, R0, .o148 138: ADD.S F0, F0, F2 .o13C 13C: MUL.S F0, F20, F22 140: NOP 144: ADD.S F0, F26, F0 .o148 148: SWC1 F0, 3C (S0) 14C: LW V0, 74 (S1) 150: ADDIU V0, V0, A 154: MTC1 V0, F12 158: NOP 15C: JAL ~Func:clamp_angle 160: CVT.S.W F12, F12 164: TRUNC.W.S F8, F0 168: SWC1 F8, 74 (S1) .o16C 16C: LW V0, 90 (S1) 170: BGTZ V0, .o274 174: ADDIU V0, V0, FFFF 178: LH V0, A8 (S0) 17C: LWC1 F0, 3C (S0) 180: MTC1 V0, F2 184: NOP 188: CVT.S.W F2, F2 18C: LAW V0, 800F7B30 194: ADD.S F0, F0, F2 198: LIF F5, 2.5625 1A0: MTC1 R0, F4 1A4: LWC1 F2, 2C (V0) 1A8: CVT.D.S F0, F0 1AC: ADD.D F0, F0, F4 1B0: CVT.D.S F2, F2 1B4: C.LT.D F2, F0 1B8: NOP 1BC: BC1F .o278 1C0: COPY A0, S4 1C4: LI V0, 1 1C8: SW V0, 10 (SP) 1CC: LW A2, 24 (S2) 1D0: LW A3, 28 (S2) 1D4: JAL 800490B4 1D8: COPY A1, S1 1DC: BEQ V0, R0, .o278 1E0: CLEAR A0 1E4: COPY A1, S0 1E8: CLEAR A2 1EC: LI S2, C 1F0: LH V1, A8 (S0) 1F4: LIF F0, 1.0 1FC: LIF F2, 2.0 204: LIF F4, -20.0 20C: MTC1 V1, F8 210: NOP 214: CVT.S.W F8, F8 218: MFC1 A3, F8 21C: ADDIU V0, SP, 38 220: SW S2, 1C (SP) 224: SW V0, 20 (SP) 228: SWC1 F0, 10 (SP) 22C: SWC1 F2, 14 (SP) 230: JAL ~Func:fx_emote 234: SWC1 F4, 18 (SP) 238: COPY A0, S0 23C: LI A1, 2F4 240: LWC1 F0, 3C (A0) 244: LUI A2, 20 248: JAL ~Func:ai_enemy_play_sound 24C: SWC1 F0, 64 (A0) 250: LW V0, 18 (S1) 254: LHU V0, 2A (V0) 258: ANDI V0, V0, 1 25C: BEQ V0, R0, .o26C 260: LI V0, A 264: BEQ R0, R0, .o314 268: SW V0, 70 (S3) .o26C 26C: BEQ R0, R0, .o314 270: SW S2, 70 (S3) .o274 274: SW V0, 90 (S1) .o278 278: LH V0, 8C (S0) 27C: BNE V0, R0, .o314 280: NOP 284: LH V0, 8E (S0) 288: BGTZ V0, .o314 28C: NOP 290: LW V0, 74 (S3) 294: ADDIU V0, V0, FFFF 298: BLEZ V0, .o310 29C: SW V0, 74 (S3) 2A0: LW V0, 18 (S1) 2A4: LHU V0, 2A (V0) 2A8: ANDI V0, V0, 10 2AC: BNE V0, R0, .o2CC 2B0: NOP 2B4: LWC1 F0, C (S0) 2B8: LIF F12, 180.0 2C0: JAL ~Func:clamp_angle 2C4: ADD.S F12, F0, F12 2C8: SWC1 F0, C (S0) .o2CC 2CC: JAL ~Func:rand_int 2D0: LI A0, 3E8 2D4: LI V1, 2E8BA2E9 2DC: MULT V0, V1 2E0: SRA V1, V0, 1F 2E4: MFHI T0 2E8: SRA A0, T0, 1 2EC: SUBU A0, A0, V1 2F0: SLL V1, A0, 1 2F4: ADDU V1, V1, A0 2F8: SLL V1, V1, 2 2FC: SUBU V1, V1, A0 300: SUBU V0, V0, V1 304: ADDIU V0, V0, 5 308: BEQ R0, R0, .o314 30C: SH V0, 8E (S0) .o310 310: SW R0, 70 (S3) .o314 314: LW RA, 54 (SP) 318: LW S4, 50 (SP) 31C: LW S3, 4C (SP) 320: LW S2, 48 (SP) 324: LW S1, 44 (SP) 328: LW S0, 40 (SP) 32C: LDC1 F26, 70 (SP) 330: LDC1 F24, 68 (SP) 334: LDC1 F22, 60 (SP) 338: LDC1 F20, 58 (SP) 33C: JR RA 340: ADDIU SP, SP, 78 } % Origin: HEURISTIC #new:Function $Function_8024233C { 0: ADDIU SP, SP, FFE0 4: SW S2, 18 (SP) 8: COPY S2, A0 C: SW RA, 1C (SP) 10: SW S1, 14 (SP) 14: SW S0, 10 (SP) 18: LW S1, 148 (S2) 1C: JAL ~Func:get_npc_unsafe 20: LH A0, 8 (S1) 24: COPY S0, V0 28: LAW V0, 800F7B30 30: LWC1 F12, 38 (S0) 34: LWC1 F14, 40 (S0) 38: SH R0, 8E (S0) 3C: LW A2, 28 (V0) 40: JAL ~Func:atan2 44: LW A3, 30 (V0) 48: SWC1 F0, C (S0) 4C: LW V0, CC (S1) 50: LW V0, 20 (V0) 54: SW V0, 28 (S0) 58: LI V0, B 5C: SW V0, 70 (S2) 60: LW RA, 1C (SP) 64: LW S2, 18 (SP) 68: LW S1, 14 (SP) 6C: LW S0, 10 (SP) 70: JR RA 74: ADDIU SP, SP, 20 } % Origin: HEURISTIC #new:Function $Function_802423B4 { 0: ADDIU SP, SP, FFE8 4: SW S0, 10 (SP) 8: COPY S0, A0 C: SW RA, 14 (SP) 10: LW V0, 148 (S0) 14: JAL ~Func:get_npc_unsafe 18: LH A0, 8 (V0) 1C: LHU V1, 8E (V0) 20: LWC1 F0, 3C (V0) 24: ADDIU A0, V1, 1 28: SLL V1, V1, 10 2C: SRA V1, V1, E 30: SH A0, 8E (V0) 34: LTF F2, V1 ($FloatTable_80244460) 40: LH V1, 8E (V0) 44: ADD.S F0, F0, F2 48: SLTI V1, V1, 5 4C: BNE V1, R0, .o5C 50: SWC1 F0, 3C (V0) 54: LI V0, C 58: SW V0, 70 (S0) .o5C 5C: LW RA, 14 (SP) 60: LW S0, 10 (SP) 64: JR RA 68: ADDIU SP, SP, 18 } % Origin: HEURISTIC #new:Function $Function_80242420 { 0: ADDIU SP, SP, FFD8 4: SW S3, 1C (SP) 8: COPY S3, A0 C: SW RA, 20 (SP) 10: SW S2, 18 (SP) 14: SW S1, 14 (SP) 18: SW S0, 10 (SP) 1C: LW S2, 148 (S3) 20: LH A0, 8 (S2) 24: JAL ~Func:get_npc_unsafe 28: COPY S0, A1 2C: COPY S1, V0 30: LWC1 F2, 80 (S2) 34: CVT.S.W F2, F2 38: CVT.D.S F2, F2 3C: LWC1 F0, 84 (S2) 40: CVT.S.W F0, F0 44: CVT.D.S F0, F0 48: LIF F5, 3.390625 50: MTC1 R0, F4 54: LW V0, CC (S2) 58: LWC1 F12, 38 (S1) 5C: LWC1 F14, 40 (S1) 60: DIV.D F2, F2, F4 64: CVT.S.D F2, F2 68: DIV.D F0, F0, F4 6C: LW V0, 20 (V0) 70: CVT.S.D F0, F0 74: SWC1 F2, 1C (S1) 78: SWC1 F0, 14 (S1) 7C: SW V0, 28 (S1) 80: LWC1 F0, 18 (S0) 84: LAW V0, 800F7B30 8C: SWC1 F0, 18 (S1) 90: LW A2, 28 (V0) 94: JAL ~Func:atan2 98: LW A3, 30 (V0) 9C: SWC1 F0, C (S1) A0: LW V0, 18 (S2) A4: SW R0, 74 (S2) A8: LHU V0, 2A (V0) AC: ANDI V0, V0, 2 B0: BEQ V0, R0, .oC8 B4: LI V0, 3 B8: SH V0, 8E (S1) BC: LI V0, D C0: BEQ R0, R0, .o118 C4: SW V0, 70 (S3) .oC8 C8: LI V1, 1 CC: LI V0, E D0: SH V1, 8E (S1) D4: SW V0, 70 (S3) D8: LWC1 F0, 38 (S1) DC: TRUNC.W.S F6, F0 E0: MFC1 V0, F6 E4: NOP E8: SH V0, 10 (S2) EC: LWC1 F0, 3C (S1) F0: TRUNC.W.S F6, F0 F4: MFC1 V0, F6 F8: NOP FC: SH V0, 12 (S2) 100: LWC1 F0, 40 (S1) 104: SB V1, 7 (S2) 108: TRUNC.W.S F6, F0 10C: MFC1 V0, F6 110: NOP 114: SH V0, 14 (S2) .o118 118: LW RA, 20 (SP) 11C: LW S3, 1C (SP) 120: LW S2, 18 (SP) 124: LW S1, 14 (SP) 128: LW S0, 10 (SP) 12C: JR RA 130: ADDIU SP, SP, 28 } % Origin: HEURISTIC #new:Function $Function_80242554 { 0: ADDIU SP, SP, FFE8 4: SW S0, 10 (SP) 8: COPY S0, A0 C: SW RA, 14 (SP) 10: LW V0, 148 (S0) 14: JAL ~Func:get_npc_unsafe 18: LH A0, 8 (V0) 1C: COPY A0, V0 20: LH V0, 8E (A0) 24: LHU V1, 8E (A0) 28: BLEZ V0, .o40 2C: ADDIU V0, V1, FFFF 30: SH V0, 8E (A0) 34: SLL V0, V0, 10 38: BGTZ V0, .o54 3C: NOP .o40 40: LH V0, 8C (A0) 44: BNE V0, R0, .o54 48: LI V0, E 4C: SH R0, 8E (A0) 50: SW V0, 70 (S0) .o54 54: LW RA, 14 (SP) 58: LW S0, 10 (SP) 5C: JR RA 60: ADDIU SP, SP, 18 } % Origin: HEURISTIC #new:Function $Function_802425B8 { 0: ADDIU SP, SP, FFB0 4: SW S2, 30 (SP) 8: COPY S2, A0 C: SW RA, 38 (SP) 10: SW S3, 34 (SP) 14: SW S1, 2C (SP) 18: SW S0, 28 (SP) 1C: SDC1 F22, 48 (SP) 20: SDC1 F20, 40 (SP) 24: LW S1, 148 (S2) 28: LH A0, 8 (S1) 2C: JAL ~Func:get_npc_unsafe 30: COPY S3, A1 34: COPY S0, V0 38: COPY A0, S0 3C: LWC1 F2, 88 (S1) 40: CVT.S.W F2, F2 44: CVT.D.S F2, F2 48: LWC1 F4, 1C (S0) 4C: LWC1 F0, 14 (S0) 50: LW A1, 18 (S0) 54: ADD.S F4, F4, F0 58: LW A2, C (S0) 5C: LWC1 F0, 78 (S1) 60: CVT.S.W F0, F0 64: SWC1 F4, 1C (S0) 68: LIF F5, 3.390625 70: MTC1 R0, F4 74: CVT.D.S F0, F0 78: DIV.D F0, F0, F4 7C: CVT.S.D F20, F0 80: DIV.D F2, F2, F4 84: JAL ~Func:npc_move_heading 88: CVT.S.D F22, F2 8C: LWC1 F4, 1C (S0) 90: MTC1 R0, F2 94: MTC1 R0, F3 98: CVT.D.S F0, F4 9C: C.LE.D F2, F0 A0: NOP A4: BC1F .o168 A8: NOP AC: LWC1 F0, 3C (S0) B0: ADD.S F0, F0, F4 B4: SWC1 F0, 3C (S0) B8: LW V0, CC (S1) BC: LW V0, 24 (V0) C0: SW V0, 28 (S0) C4: SB R0, 7 (S1) C8: LW V0, 0 (S0) CC: ANDI V0, V0, 8 D0: BNE V0, R0, .o118 D4: CLEAR V0 D8: ADDIU A1, SP, 18 DC: ADDIU A2, SP, 1C E0: LWC1 F0, 38 (S0) E4: LWC1 F2, 3C (S0) E8: LWC1 F4, 40 (S0) EC: LIF F6, 1000.0 F4: ADDIU V0, SP, 24 F8: SWC1 F0, 18 (SP) FC: SWC1 F2, 1C (SP) 100: SWC1 F4, 20 (SP) 104: SWC1 F6, 24 (SP) 108: SW V0, 10 (SP) 10C: LW A0, 80 (S0) 110: JAL ~Func:npc_raycast_down_sides 114: ADDIU A3, SP, 20 .o118 118: BEQ V0, R0, .o148 11C: NOP 120: LWC1 F0, 1C (SP) 124: ADD.S F2, F0, F20 128: LWC1 F0, 3C (S0) 12C: C.LE.S F2, F0 130: NOP 134: BC1F .o36C 138: NOP 13C: SWC1 F2, 3C (S0) 140: BEQ R0, R0, .o36C 144: SW R0, 70 (S2) .o148 148: LWC1 F2, 3C (S0) 14C: LWC1 F0, 64 (S0) 150: C.LE.S F0, F2 154: NOP 158: BC1TL .o36C 15C: SW R0, 70 (S2) 160: BEQ R0, R0, .o36C 164: NOP .o168 168: C.LT.D F0, F2 16C: NOP 170: BC1F .o36C 174: NOP 178: LHU V0, 8E (S0) 17C: ADDIU V0, V0, 1 180: SH V0, 8E (S0) 184: SLL V0, V0, 10 188: LW V1, 20 (S3) 18C: SRA V0, V0, 10 190: SLT V0, V0, V1 194: BNE V0, R0, .o230 198: NOP 19C: LWC1 F12, 38 (S0) 1A0: LWC1 F14, 40 (S0) 1A4: LAW V0, 800F7B30 1AC: SH R0, 8E (S0) 1B0: LW A2, 28 (V0) 1B4: JAL ~Func:atan2 1B8: LW A3, 30 (V0) 1BC: MOV.S F20, F0 1C0: LWC1 F12, C (S0) 1C4: JAL ~Func:get_clamped_angle_diff 1C8: MOV.S F14, F20 1CC: MOV.S F2, F0 1D0: LW V0, 1C (S3) 1D4: ABS.S F0, F2 1D8: MTC1 V0, F4 1DC: NOP 1E0: CVT.S.W F4, F4 1E4: C.LT.S F4, F0 1E8: NOP 1EC: BC1F .o224 1F0: NOP 1F4: MTC1 R0, F0 1F8: LWC1 F20, C (S0) 1FC: C.LT.S F2, F0 200: NOP 204: BC1F .o220 208: SUBU V0, R0, V0 20C: MTC1 V0, F0 210: NOP 214: CVT.S.W F0, F0 218: BEQ R0, R0, .o224 21C: ADD.S F20, F20, F0 .o220 220: ADD.S F20, F20, F4 .o224 224: JAL ~Func:clamp_angle 228: MOV.S F12, F20 22C: SWC1 F0, C (S0) .o230 230: LW V0, 0 (S0) 234: ANDI V0, V0, 8 238: BEQ V0, R0, .o264 23C: ADDIU A1, SP, 18 240: LWC1 F2, 3C (S0) 244: LWC1 F0, 1C (S0) 248: ADD.S F2, F2, F0 24C: C.LT.S F2, F22 250: NOP 254: BC1FL .o36C 258: SWC1 F2, 3C (S0) 25C: BEQ R0, R0, .o368 260: SWC1 F22, 3C (S0) .o264 264: LWC1 F0, 38 (S0) 268: ADDIU A2, SP, 1C 26C: SWC1 F0, 18 (SP) 270: LH V0, A8 (S0) 274: LWC1 F0, 1C (S0) 278: LWC1 F4, 3C (S0) 27C: MTC1 V0, F2 280: NOP 284: CVT.S.W F2, F2 288: ABS.S F0, F0 28C: ADD.S F0, F0, F2 290: LWC1 F6, 40 (S0) 294: ADDIU V0, SP, 24 298: ADD.S F4, F4, F2 29C: LIF F3, 2.5625 2A4: MTC1 R0, F2 2A8: CVT.D.S F0, F0 2AC: ADD.D F0, F0, F2 2B0: SWC1 F6, 20 (SP) 2B4: SWC1 F4, 1C (SP) 2B8: CVT.S.D F0, F0 2BC: SWC1 F0, 24 (SP) 2C0: SW V0, 10 (SP) 2C4: LW A0, 80 (S0) 2C8: JAL ~Func:npc_raycast_down_sides 2CC: ADDIU A3, SP, 20 2D0: BEQ V0, R0, .o328 2D4: NOP 2D8: LH V0, A8 (S0) 2DC: LWC1 F4, 1C (S0) 2E0: MTC1 V0, F0 2E4: NOP 2E8: CVT.S.W F0, F0 2EC: ABS.S F2, F4 2F0: ADD.S F0, F0, F2 2F4: LWC1 F2, 24 (SP) 2F8: C.LE.S F2, F0 2FC: NOP 300: BC1F .o318 304: NOP 308: LWC1 F0, 1C (SP) 30C: SW R0, 1C (S0) 310: BEQ R0, R0, .o36C 314: SWC1 F0, 3C (S0) .o318 318: LWC1 F0, 3C (S0) 31C: ADD.S F0, F0, F4 320: BEQ R0, R0, .o36C 324: SWC1 F0, 3C (S0) .o328 328: LWC1 F6, 3C (S0) 32C: LH V0, A8 (S0) 330: SUB.S F2, F6, F22 334: MTC1 V0, F0 338: NOP 33C: CVT.S.W F0, F0 340: ADD.S F2, F2, F0 344: LWC1 F4, 1C (S0) 348: ABS.S F0, F4 34C: C.LT.S F0, F2 350: NOP 354: BC1FL .o36C 358: SW R0, 1C (S0) 35C: ADD.S F0, F6, F4 360: BEQ R0, R0, .o36C 364: SWC1 F0, 3C (S0) .o368 368: SW R0, 1C (S0) .o36C 36C: LW RA, 38 (SP) 370: LW S3, 34 (SP) 374: LW S2, 30 (SP) 378: LW S1, 2C (SP) 37C: LW S0, 28 (SP) 380: LDC1 F22, 48 (SP) 384: LDC1 F20, 40 (SP) 388: JR RA 38C: ADDIU SP, SP, 50 } #new:Function $Function_80242948 { 0: ADDIU SP, SP, FFC8 4: SW S0, 28 (SP) 8: COPY S0, A1 C: SW S1, 2C (SP) 10: COPY S1, A2 14: SW RA, 34 (SP) 18: SW S2, 30 (SP) 1C: SW R0, 70 (S1) 20: LW V1, 0 (A0) 24: LI V0, FDFF 28: SH R0, 8E (A0) 2C: AND V1, V1, V0 30: ORI A1, V1, 800 34: SW A1, 0 (A0) 38: LW V0, D0 (S0) 3C: LW V0, 34 (V0) 40: BEQ V0, R0, .o50 44: COPY S2, A3 48: BEQ R0, R0, .o58 4C: ORI V0, V1, 808 .o50 50: LI V0, FFF7 54: AND V0, A1, V0 .o58 58: SW V0, 0 (A0) 5C: ADDIU V0, SP, 24 60: ADDIU A1, SP, 18 64: LWC1 F0, 38 (A0) 68: LWC1 F2, 3C (A0) 6C: LWC1 F4, 40 (A0) 70: LIF F6, 1000.0 78: ADDIU A2, SP, 1C 7C: SWC1 F0, 18 (SP) 80: SWC1 F2, 1C (SP) 84: SWC1 F4, 20 (SP) 88: SWC1 F6, 24 (SP) 8C: SW V0, 10 (SP) 90: LW A0, 80 (A0) 94: JAL ~Func:npc_raycast_down_sides 98: ADDIU A3, SP, 20 9C: LWC1 F2, 24 (SP) A0: LIF F5, 3.390625 A8: MTC1 R0, F4 AC: CVT.D.S F2, F2 B0: MUL.D F2, F2, F4 B4: NOP B8: LWC1 F0, 1C (SP) BC: CVT.D.S F0, F0 C0: MUL.D F0, F0, F4 C4: NOP C8: LIF F5, 1.75 D0: MTC1 R0, F4 D4: NOP D8: ADD.D F2, F2, F4 DC: SW R0, 74 (S0) E0: ADD.D F0, F0, F4 E4: SW R0, 90 (S0) E8: TRUNC.W.D F8, F2 EC: SWC1 F8, 78 (S0) F0: TRUNC.W.D F8, F0 F4: SWC1 F8, 88 (S0) F8: LW V0, 14 (S2) FC: SW V0, 74 (S1) 100: LW V0, B0 (S0) 104: ORI V0, V0, 10 108: SW V0, B0 (S0) 10C: LW RA, 34 (SP) 110: LW S2, 30 (SP) 114: LW S1, 2C (SP) 118: LW S0, 28 (SP) 11C: JR RA 120: ADDIU SP, SP, 38 } % Origin: HEURISTIC #new:Function $Function_80242A6C { 0: ADDIU SP, SP, FFB0 4: SW S4, 40 (SP) 8: COPY S4, A0 C: SW RA, 48 (SP) 10: SW S5, 44 (SP) 14: SW S3, 3C (SP) 18: SW S2, 38 (SP) 1C: SW S1, 34 (SP) 20: SW S0, 30 (SP) 24: LW S2, 148 (S4) 28: LH A0, 8 (S2) 2C: LW S0, C (S4) 30: JAL ~Func:get_npc_unsafe 34: COPY S1, A1 38: COPY A0, S4 3C: LW A1, 0 (S0) 40: JAL ~Func:get_variable 44: COPY S5, V0 48: SW R0, 10 (SP) 4C: LW V1, D0 (S2) 50: LW V1, 30 (V1) 54: SW V1, 14 (SP) 58: LW V1, D0 (S2) 5C: LW V1, 1C (V1) 60: SW V1, 18 (SP) 64: LW V1, D0 (S2) 68: LW V1, 24 (V1) 6C: SW V1, 1C (SP) 70: LW V1, D0 (S2) 74: LW V1, 28 (V1) 78: ADDIU S3, SP, 10 7C: SW V1, 20 (SP) 80: LW V1, D0 (S2) 84: LIF F0, 120.0 8C: LW V1, 2C (V1) 90: COPY S0, V0 94: SWC1 F0, 28 (SP) 98: SH R0, 2C (SP) 9C: BEQ S1, R0, .oB8 A0: SW V1, 24 (SP) A4: COPY A0, S5 A8: COPY A1, S2 AC: COPY A2, S4 B0: JAL $Function_80242948 B4: COPY A3, S0 .oB8 B8: LI V0, FFFE BC: SB V0, AB (S5) C0: LW V1, B0 (S2) C4: ANDI V0, V1, 4 C8: BEQ V0, R0, .oE8 CC: NOP D0: LB V0, B4 (S2) D4: BNE V0, R0, .o1C8 D8: CLEAR V0 DC: LI V0, FFFB E0: AND V0, V1, V0 E4: SW V0, B0 (S2) .oE8 E8: LW V1, 70 (S4) EC: SLTIU V0, V1, F F0: BEQ V0, R0, .o1C4 F4: SLL V0, V1, 2 F8: LTW V0, V0 ($JumpTable_80246D50) 104: JR V0 108: NOP % LBL: from $JumpTable_80246D50 , entry 0` 10C: COPY A0, S4 110: COPY A1, S0 114: JAL $Function_80241760 118: COPY A2, S3 % LBL: from $JumpTable_80246D50 , entry 1` 11C: COPY A0, S4 120: COPY A1, S0 124: JAL $Function_80241910 128: COPY A2, S3 12C: BEQ R0, R0, .o1C8 130: CLEAR V0 % LBL: from $JumpTable_80246D50 , entry 2` 134: COPY A0, S4 138: COPY A1, S0 13C: JAL $Function_80241F38 140: COPY A2, S3 % LBL: from $JumpTable_80246D50 , entry 3` 144: COPY A0, S4 148: COPY A1, S0 14C: JAL $Function_80241FF8 150: COPY A2, S3 154: BEQ R0, R0, .o1C8 158: CLEAR V0 % LBL: from $JumpTable_80246D50 , entry 10` 15C: COPY A0, S4 160: COPY A1, S0 164: JAL $Function_8024233C 168: COPY A2, S3 % LBL: from $JumpTable_80246D50 , entry 11` 16C: COPY A0, S4 170: COPY A1, S0 174: JAL $Function_802423B4 178: COPY A2, S3 17C: BEQ R0, R0, .o1C8 180: CLEAR V0 % LBL: from $JumpTable_80246D50 , entry 12` 184: COPY A0, S4 188: COPY A1, S0 18C: JAL $Function_80242420 190: COPY A2, S3 194: BEQ R0, R0, .o1C8 198: CLEAR V0 % LBL: from $JumpTable_80246D50 , entry 13` 19C: COPY A0, S4 1A0: COPY A1, S0 1A4: JAL $Function_80242554 1A8: COPY A2, S3 1AC: BEQ R0, R0, .o1C8 1B0: CLEAR V0 % LBL: from $JumpTable_80246D50 , entry 14` 1B4: COPY A0, S4 1B8: COPY A1, S0 1BC: JAL $Function_802425B8 1C0: COPY A2, S3 % LBL: from $JumpTable_80246D50 , entry 9` .o1C4 1C4: CLEAR V0 .o1C8 1C8: LW RA, 48 (SP) 1CC: LW S5, 44 (SP) 1D0: LW S4, 40 (SP) 1D4: LW S3, 3C (SP) 1D8: LW S2, 38 (SP) 1DC: LW S1, 34 (SP) 1E0: LW S0, 30 (SP) 1E4: JR RA 1E8: ADDIU SP, SP, 50 } #new:Function $Function_80242C58 { 0: ADDIU SP, SP, FFD0 4: SW S3, 1C (SP) 8: COPY S3, A0 C: SW RA, 20 (SP) 10: SW S2, 18 (SP) 14: SW S1, 14 (SP) 18: SW S0, 10 (SP) 1C: SDC1 F20, 28 (SP) 20: LW S2, 148 (S3) 24: LH A0, 8 (S2) 28: JAL ~Func:get_npc_unsafe 2C: COPY S1, A1 30: COPY S0, V0 34: LHU V0, 8E (S0) 38: ADDIU V0, V0, FFFF 3C: SH V0, 8E (S0) 40: SLL V0, V0, 10 44: BGTZ V0, .o138 48: LUI V1, FFDF 4C: LW V0, 0 (S0) 50: ORI V1, V1, FFFF 54: AND V0, V0, V1 58: SW V0, 0 (S0) 5C: LW A0, 20 (S1) 60: SRL V0, A0, 1F 64: ADDU A0, A0, V0 68: SRA A0, A0, 1 6C: JAL ~Func:rand_int 70: ADDIU A0, A0, 1 74: LW V1, 20 (S1) 78: LWC1 F12, 38 (S0) 7C: SRL A0, V1, 1F 80: ADDU V1, V1, A0 84: SRA V1, V1, 1 88: ADDU V1, V1, V0 8C: SH V1, 8E (S0) 90: LW V0, CC (S2) 94: LWC1 F14, 40 (S0) 98: LW V0, 20 (V0) 9C: SW V0, 28 (S0) A0: LWC1 F0, 18 (S1) A4: LAW V0, 800F7B30 AC: SWC1 F0, 18 (S0) B0: LW A2, 28 (V0) B4: JAL ~Func:atan2 B8: LW A3, 30 (V0) BC: MOV.S F20, F0 C0: LWC1 F12, C (S0) C4: JAL ~Func:get_clamped_angle_diff C8: MOV.S F14, F20 CC: MOV.S F2, F0 D0: LW V0, 1C (S1) D4: ABS.S F0, F2 D8: MTC1 V0, F4 DC: NOP E0: CVT.S.W F4, F4 E4: C.LT.S F4, F0 E8: NOP EC: BC1F .o124 F0: NOP F4: MTC1 R0, F0 F8: LWC1 F20, C (S0) FC: C.LT.S F2, F0 100: NOP 104: BC1F .o120 108: SUBU V0, R0, V0 10C: MTC1 V0, F0 110: NOP 114: CVT.S.W F0, F0 118: BEQ R0, R0, .o124 11C: ADD.S F20, F20, F0 .o120 120: ADD.S F20, F20, F4 .o124 124: JAL ~Func:clamp_angle 128: MOV.S F12, F20 12C: LI V0, D 130: SWC1 F0, C (S0) 134: SW V0, 70 (S3) .o138 138: LW RA, 20 (SP) 13C: LW S3, 1C (SP) 140: LW S2, 18 (SP) 144: LW S1, 14 (SP) 148: LW S0, 10 (SP) 14C: LDC1 F20, 28 (SP) 150: JR RA 154: ADDIU SP, SP, 30 } #new:Function $Function_80242DB0 { 0: ADDIU SP, SP, FFD0 4: SW S3, 24 (SP) 8: COPY S3, A0 C: SW RA, 28 (SP) 10: SW S2, 20 (SP) 14: SW S1, 1C (SP) 18: SW S0, 18 (SP) 1C: LW S0, 148 (S3) 20: COPY S2, A1 24: LH A0, 8 (S0) 28: JAL ~Func:get_npc_unsafe 2C: COPY S1, A2 30: COPY A0, S1 34: COPY A1, S0 38: LI V1, 1 3C: SW V1, 10 (SP) 40: LW A2, 24 (S2) 44: LW A3, 28 (S2) 48: JAL 800490B4 4C: COPY S0, V0 50: BEQ V0, R0, .oE4 54: LI V0, 10 58: LW A1, 18 (S0) 5C: LW A2, C (S0) 60: JAL ~Func:npc_move_heading 64: COPY A0, S0 68: LAW V0, 800F7B30 70: LWC1 F12, 38 (S0) 74: LWC1 F14, 40 (S0) 78: LW A2, 28 (V0) 7C: JAL ~Func:dist2D 80: LW A3, 30 (V0) 84: LWC1 F2, 18 (S0) 88: LIF F5, 2.0625 90: MTC1 R0, F4 94: CVT.D.S F2, F2 98: MUL.D F2, F2, F4 9C: NOP A0: CVT.D.S F0, F0 A4: C.LE.D F0, F2 A8: NOP AC: BC1F .oBC B0: LI V0, E B4: BEQ R0, R0, .oE4 B8: SH R0, 8E (S0) .oBC BC: LHU V0, 8E (S0) C0: ADDIU V0, V0, FFFF C4: SH V0, 8E (S0) C8: SLL V0, V0, 10 CC: BGTZ V0, .oE8 D0: LUI V1, 20 D4: LW V0, 0 (S0) D8: OR V0, V0, V1 DC: SW V0, 0 (S0) E0: LI V0, C .oE4 E4: SW V0, 70 (S3) .oE8 E8: LW RA, 28 (SP) EC: LW S3, 24 (SP) F0: LW S2, 20 (SP) F4: LW S1, 1C (SP) F8: LW S0, 18 (SP) FC: JR RA 100: ADDIU SP, SP, 30 } #new:Function $Function_80242EB4 { 0: ADDIU SP, SP, FFD0 4: SW S3, 24 (SP) 8: COPY S3, A0 C: SW RA, 28 (SP) 10: SW S2, 20 (SP) 14: SW S1, 1C (SP) 18: SW S0, 18 (SP) 1C: LW S2, 148 (S3) 20: LH A0, 8 (S2) 24: JAL ~Func:get_npc_unsafe 28: LI S0, 7 2C: COPY S1, V0 .o30 30: LB V0, A4 (S1) 34: BEQL S0, V0, .o54 38: ADDIU S0, S0, 1 3C: JAL ~Func:get_enemy 40: COPY A0, S0 44: LW V0, 6C (V0) 48: ANDI V0, V0, 100 4C: BNE V0, R0, .oC4 50: ADDIU S0, S0, 1 .o54 54: SLTI V0, S0, 9 58: BNE V0, R0, .o30 5C: NOP 60: LW V0, 6C (S2) 64: LAW V1, 800F7B30 6C: ORI V0, V0, 100 70: SW V0, 6C (S2) 74: LWC1 F0, 28 (V1) 78: SWC1 F0, 38 (S1) 7C: LWC1 F0, 30 (V1) 80: SWC1 F0, 40 (S1) 84: LW V1, 6C (S2) 88: ANDI V0, V1, 1000 8C: BNE V0, R0, .o9C 90: LUI A0, 8000 94: ORI V0, V1, 1000 98: SW V0, 6C (S2) .o9C 9C: LWC1 F0, 40 (S1) A0: ORI A0, A0, 11 A4: SWC1 F0, 10 (SP) A8: LW A2, 38 (S1) AC: LW A3, 3C (S1) B0: JAL ~Func:sfx_play_sound_at_position B4: LI A1, 2 B8: LI V0, F BC: SH R0, 8E (S1) C0: SW V0, 70 (S3) .oC4 C4: LW RA, 28 (SP) C8: LW S3, 24 (SP) CC: LW S2, 20 (SP) D0: LW S1, 1C (SP) D4: LW S0, 18 (SP) D8: JR RA DC: ADDIU SP, SP, 30 } #new:Function $Function_80242F94 { 0: ADDIU SP, SP, FFB8 4: SW S4, 40 (SP) 8: COPY S4, A0 C: SW RA, 44 (SP) 10: SW S3, 3C (SP) 14: SW S2, 38 (SP) 18: SW S1, 34 (SP) 1C: SW S0, 30 (SP) 20: LW S3, 148 (S4) 24: COPY S0, A1 28: LH A0, 8 (S3) 2C: JAL ~Func:get_npc_unsafe 30: COPY S1, A2 34: LUI A0, 8000 38: COPY S2, V0 3C: LWC1 F0, 40 (S2) 40: ORI A0, A0, 11 44: SWC1 F0, 10 (SP) 48: LW A2, 38 (S2) 4C: LW A3, 3C (S2) 50: JAL ~Func:sfx_adjust_env_sound_pos 54: LI A1, 2 58: COPY A0, S1 5C: LI V0, 1 60: SW V0, 10 (SP) 64: LW A2, 24 (S0) 68: LW A3, 28 (S0) 6C: JAL 800490B4 70: COPY A1, S3 74: BNE V0, R0, .oA4 78: LUI A0, FFDF 7C: LW V0, 6C (S3) 80: LI V1, FEFF 84: AND V0, V0, V1 88: SW V0, 6C (S3) 8C: LW V0, 0 (S2) 90: ORI A0, A0, FFFF 94: SW R0, 48 (S2) 98: AND V0, V0, A0 9C: BEQ R0, R0, .o274 A0: SW V0, 0 (S2) .oA4 A4: LA S0, 800F7B30 AC: LWC1 F4, 48 (S2) B0: LIF F0, 25.0 B8: LW V0, 0 (S0) BC: ADD.S F4, F4, F0 C0: LWC1 F2, 28 (V0) C4: LIF F0, 2.0 CC: SWC1 F2, 38 (S2) D0: LWC1 F2, 30 (V0) D4: ADD.S F2, F2, F0 D8: LAD F6, $ConstDouble_80246D90 E0: CVT.D.S F0, F4 E4: C.LT.D F6, F0 E8: SWC1 F4, 48 (S2) EC: BC1F .o100 F0: SWC1 F2, 40 (S2) F4: SUB.D F0, F0, F6 F8: CVT.S.D F0, F0 FC: SWC1 F0, 48 (S2) .o100 100: LUI V0, B60B 104: LWC1 F0, 48 (S2) 108: ORI V0, V0, 60B7 10C: TRUNC.W.S F8, F0 110: MFC1 A0, F8 114: NOP 118: MULT A0, V0 11C: SRA V1, A0, 1F 120: MFHI T0 124: ADDU V0, T0, A0 128: SRA V0, V0, 7 12C: SUBU V0, V0, V1 130: SLL V1, V0, 1 134: ADDU V1, V1, V0 138: SLL V0, V1, 4 13C: SUBU V0, V0, V1 140: SLL V0, V0, 2 144: SUBU A0, A0, V0 148: SLL A0, A0, 10 14C: JAL ~Func:cosine 150: SRA A0, A0, 10 154: LIF F2, 56.0 15C: NOP 160: MUL.S F0, F0, F2 164: NOP 168: LI A1, 6 16C: LIF F2, 255.0 174: LI V0, FF 178: SUB.S F2, F2, F0 17C: SW V0, 14 (SP) 180: SW R0, 18 (SP) 184: TRUNC.W.S F8, F2 188: MFC1 A2, F8 18C: NOP 190: SW A2, 10 (SP) 194: LW A0, 24 (S2) 198: JAL 802DE894 19C: COPY A3, A2 1A0: ADDIU A1, SP, 20 1A4: ADDIU A2, SP, 24 1A8: LW V0, 0 (S0) 1AC: LIF F0, 1000.0 1B4: LWC1 F2, 28 (V0) 1B8: LWC1 F4, 2C (V0) 1BC: LWC1 F6, 30 (V0) 1C0: ADDIU V0, SP, 2C 1C4: SWC1 F0, 2C (SP) 1C8: SWC1 F2, 20 (SP) 1CC: SWC1 F4, 24 (SP) 1D0: SWC1 F6, 28 (SP) 1D4: SW V0, 10 (SP) 1D8: LW A0, 80 (S2) 1DC: JAL ~Func:npc_raycast_down_sides 1E0: ADDIU A3, SP, 28 1E4: LWC1 F4, 3C (S2) 1E8: LWC1 F0, 24 (SP) 1EC: SUB.S F0, F4, F0 1F0: LIF F3, 2.875 1F8: MTC1 R0, F2 1FC: ABS.S F0, F0 200: CVT.D.S F0, F0 204: C.LT.D F2, F0 208: NOP 20C: BC1F .o230 210: LUI V1, FFDF 214: LAD F2, $ConstDouble_80246D98 21C: CVT.D.S F0, F4 220: SUB.D F0, F0, F2 224: CVT.S.D F0, F0 228: BEQ R0, R0, .o27C 22C: SWC1 F0, 3C (S2) .o230 230: LW V0, 0 (S2) 234: ORI V1, V1, FFFF 238: SW R0, 48 (S2) 23C: AND V0, V0, V1 240: SW V0, 0 (S2) 244: LAB V1, 8010EBB3 24C: LI V0, 9 250: BEQ V1, V0, .o278 254: LI V0, 10 258: JAL ~Func:disable_player_input 25C: NOP 260: JAL ~Func:partner_disable_input 264: NOP 268: LI V0, 14 26C: BEQ R0, R0, .o278 270: SH R0, 8E (S2) .o274 274: LI V0, 10 .o278 278: SW V0, 70 (S4) .o27C 27C: LW RA, 44 (SP) 280: LW S4, 40 (SP) 284: LW S3, 3C (SP) 288: LW S2, 38 (SP) 28C: LW S1, 34 (SP) 290: LW S0, 30 (SP) 294: JR RA 298: ADDIU SP, SP, 48 } #new:Function $Function_80243230 { 0: ADDIU SP, SP, FFD0 4: SW S2, 28 (SP) 8: COPY S2, A0 C: SW RA, 2C (SP) 10: SW S1, 24 (SP) 14: SW S0, 20 (SP) 18: LW S0, 148 (S2) 1C: JAL ~Func:get_npc_unsafe 20: LH A0, 8 (S0) 24: LI A0, FEFF 28: COPY S1, V0 2C: CLEAR A1 30: LW V1, 6C (S0) 34: COPY A2, A1 38: AND V1, V1, A0 3C: SW V1, 6C (S0) 40: SW R0, 10 (SP) 44: SW R0, 14 (SP) 48: SW R0, 18 (SP) 4C: LW A0, 24 (S1) 50: JAL 802DE894 54: COPY A3, A1 58: LW V0, 6C (S0) 5C: ANDI V0, V0, 1000 60: BEQ V0, R0, .o84 64: NOP 68: LI A0, 80000011 6C: JAL ~Func:sfx_stop_sound 70: RESERVED 74: LW V0, 6C (S0) 78: LI V1, EFFF 7C: AND V0, V0, V1 80: SW V0, 6C (S0) .o84 84: LW V0, CC (S0) 88: LW V1, 24 (V0) 8C: LI V0, 14 90: SH V0, 8E (S1) 94: LI V0, 11 98: SW V1, 28 (S1) 9C: SW V0, 70 (S2) A0: LW RA, 2C (SP) A4: LW S2, 28 (SP) A8: LW S1, 24 (SP) AC: LW S0, 20 (SP) B0: JR RA B4: ADDIU SP, SP, 30 } #new:Function $Function_802432E8 { 0: ADDIU SP, SP, FFA8 4: SW S2, 48 (SP) 8: COPY S2, A0 C: SW RA, 4C (SP) 10: SW S1, 44 (SP) 14: SW S0, 40 (SP) 18: SDC1 F20, 50 (SP) 1C: LW S0, 148 (S2) 20: JAL ~Func:get_npc_unsafe 24: LH A0, 8 (S0) 28: ADDIU A1, SP, 28 2C: COPY S1, V0 30: ADDIU A2, SP, 2C 34: ADDIU A3, SP, 30 38: LWC1 F0, 3C (S1) 3C: LIF F3, 2.0625 44: MTC1 R0, F2 48: LWC1 F6, 38 (S1) 4C: CVT.D.S F0, F0 50: ADD.D F0, F0, F2 54: LIF F4, 1000.0 5C: LWC1 F2, 78 (S0) 60: CVT.S.W F2, F2 64: CVT.S.D F0, F0 68: SWC1 F0, 3C (S1) 6C: MOV.S F8, F0 70: LWC1 F0, 40 (S1) 74: ADDIU V0, SP, 34 78: SWC1 F0, 30 (SP) 7C: LIF F1, 3.390625 84: MTC1 R0, F0 88: CVT.D.S F2, F2 8C: SWC1 F6, 28 (SP) 90: SWC1 F4, 34 (SP) 94: SWC1 F8, 2C (SP) 98: SW V0, 10 (SP) 9C: LW A0, 80 (S1) A0: DIV.D F2, F2, F0 A4: JAL ~Func:npc_raycast_down_sides A8: CVT.S.D F20, F2 AC: LWC1 F0, 2C (SP) B0: ADD.S F0, F0, F20 B4: LWC1 F2, 3C (S1) B8: C.LT.S F2, F0 BC: NOP C0: BC1T .o164 C4: NOP C8: LW V0, D0 (S0) CC: LWC1 F12, 38 (S1) D0: LWC1 F14, 40 (S1) D4: LWC1 F10, 0 (V0) D8: CVT.S.W F10, F10 DC: MFC1 A2, F10 E0: LWC1 F10, 8 (V0) E4: CVT.S.W F10, F10 E8: MFC1 A3, F10 EC: JAL ~Func:atan2 F0: LI S0, A F4: LI A0, 2 F8: COPY A1, S1 FC: CLEAR A2 100: LWC1 F2, 2C (SP) 104: LH V0, A8 (S1) 108: SWC1 F0, C (S1) 10C: LIF F0, 1.0 114: LIF F4, 2.0 11C: LIF F6, -20.0 124: MTC1 V0, F10 128: NOP 12C: CVT.S.W F10, F10 130: ADD.S F2, F2, F20 134: MFC1 A3, F10 138: ADDIU V0, SP, 38 13C: SWC1 F2, 3C (S1) 140: SWC1 F0, 10 (SP) 144: SWC1 F4, 14 (SP) 148: SWC1 F6, 18 (SP) 14C: SW S0, 1C (SP) 150: JAL ~Func:fx_emote 154: SW V0, 20 (SP) 158: LI V0, 12 15C: SH S0, 8E (S1) 160: SW V0, 70 (S2) .o164 164: LW RA, 4C (SP) 168: LW S2, 48 (SP) 16C: LW S1, 44 (SP) 170: LW S0, 40 (SP) 174: LDC1 F20, 50 (SP) 178: JR RA 17C: ADDIU SP, SP, 58 } #new:Function $Function_80243468 { 0: ADDIU SP, SP, FFE8 4: SW S0, 10 (SP) 8: COPY S0, A0 C: SW RA, 14 (SP) 10: LW V0, 148 (S0) 14: JAL ~Func:get_npc_unsafe 18: LH A0, 8 (V0) 1C: LHU V1, 8E (V0) 20: ADDIU V1, V1, FFFF 24: SH V1, 8E (V0) 28: SLL V1, V1, 10 2C: BGTZ V1, .o38 30: LI V0, 1E 34: SW V0, 70 (S0) .o38 38: LW RA, 14 (SP) 3C: LW S0, 10 (SP) 40: JR RA 44: ADDIU SP, SP, 18 } #new:Function $Function_802434B0 { 0: ADDIU SP, SP, FFE8 4: SW S0, 10 (SP) 8: COPY S0, A0 C: SW RA, 14 (SP) 10: LW V0, 148 (S0) 14: JAL ~Func:get_npc_unsafe 18: LH A0, 8 (V0) 1C: COPY A0, V0 20: LHU V0, 8E (A0) 24: ADDIU V0, V0, 1 28: SH V0, 8E (A0) 2C: SLL V0, V0, 10 30: SRA V0, V0, 10 34: SLTI V0, V0, 3 38: BNE V0, R0, .o70 3C: LI V0, 9 40: LAB V1, 8010EBB3 48: BEQ V1, V0, .o58 4C: LI V0, 64 50: BEQ R0, R0, .o6C 54: SH R0, 8E (A0) .o58 58: JAL ~Func:enable_player_input 5C: NOP 60: JAL ~Func:partner_enable_input 64: NOP 68: LI V0, 10 .o6C 6C: SW V0, 70 (S0) .o70 70: LW RA, 14 (SP) 74: LW S0, 10 (SP) 78: JR RA 7C: ADDIU SP, SP, 18 } #new:Function $Function_80243530 { 0: ADDIU SP, SP, FFE0 4: SW S2, 18 (SP) 8: COPY S2, A0 C: SW RA, 1C (SP) 10: SW S1, 14 (SP) 14: SW S0, 10 (SP) 18: LW S0, 148 (S2) 1C: LH A0, 8 (S0) 20: JAL ~Func:get_npc_unsafe 24: COPY S1, A1 28: LUI A1, FFDF 2C: LW V1, 6C (S0) 30: LI A0, FEFF 34: AND V1, V1, A0 38: SW V1, 6C (S0) 3C: LW V1, 0 (V0) 40: ORI A1, A1, FFFF 44: AND V1, V1, A1 48: SW V1, 0 (V0) 4C: LWC1 F0, 0 (S1) 50: CVT.D.S F0, F0 54: ADD.D F0, F0, F0 58: CVT.S.D F0, F0 5C: SWC1 F0, 18 (V0) 60: SW R0, 74 (S0) 64: LWC1 F0, 3C (V0) 68: LIF F3, 3.390625 70: MTC1 R0, F2 74: CVT.D.S F0, F0 78: MUL.D F0, F0, F2 7C: NOP 80: LI V0, 1E 84: TRUNC.W.D F4, F0 88: SWC1 F4, 7C (S0) 8C: SW V0, 74 (S2) 90: LW RA, 1C (SP) 94: LW S2, 18 (SP) 98: LW S1, 14 (SP) 9C: LW S0, 10 (SP) A0: JR RA A4: ADDIU SP, SP, 20 } #new:Function $Function_802435D8 { 0: ADDIU SP, SP, FF88 4: SW S2, 48 (SP) 8: COPY S2, A0 C: SW RA, 54 (SP) 10: SW S4, 50 (SP) 14: SW S3, 4C (SP) 18: SW S1, 44 (SP) 1C: SW S0, 40 (SP) 20: SDC1 F26, 70 (SP) 24: SDC1 F24, 68 (SP) 28: SDC1 F22, 60 (SP) 2C: SDC1 F20, 58 (SP) 30: LW S0, 148 (S2) 34: COPY S3, A1 38: LH A0, 8 (S0) 3C: JAL ~Func:get_npc_unsafe 40: COPY S4, A2 44: COPY S1, V0 48: LWC1 F0, 38 (S1) 4C: LWC1 F2, 3C (S1) 50: LWC1 F4, 40 (S1) 54: LIF F6, 1000.0 5C: LWC1 F12, 74 (S0) 60: CVT.S.W F12, F12 64: SWC1 F0, 28 (SP) 68: SWC1 F2, 2C (SP) 6C: SWC1 F4, 30 (SP) 70: SWC1 F6, 34 (SP) 74: LWC1 F0, 78 (S0) 78: CVT.S.W F0, F0 7C: CVT.D.S F0, F0 80: LWC1 F2, 88 (S0) 84: CVT.S.W F2, F2 88: LIF F5, 3.390625 90: MTC1 R0, F4 94: CVT.D.S F2, F2 98: DIV.D F0, F0, F4 9C: CVT.S.D F26, F0 A0: DIV.D F2, F2, F4 A4: CVT.S.D F2, F2 A8: LWC1 F0, 70 (S0) AC: CVT.S.W F0, F0 B0: CVT.D.S F0, F0 B4: DIV.D F0, F0, F4 B8: CVT.S.D F22, F0 BC: JAL ~Func:sin_deg C0: ADD.S F24, F26, F2 C4: ADDIU A1, SP, 28 C8: ADDIU A2, SP, 2C CC: ADDIU A3, SP, 30 D0: ADDIU V0, SP, 34 D4: SW V0, 10 (SP) D8: LW A0, 80 (S1) DC: JAL ~Func:npc_raycast_down_sides E0: MOV.S F20, F0 E4: BEQ V0, R0, .o104 E8: NOP EC: MUL.S F2, F20, F22 F0: NOP F4: LWC1 F0, 2C (SP) F8: ADD.S F0, F0, F26 FC: BEQ R0, R0, .o110 100: ADD.S F0, F0, F2 .o104 104: MUL.S F0, F20, F22 108: NOP 10C: ADD.S F0, F24, F0 .o110 110: SWC1 F0, 3C (S1) 114: LW V0, 74 (S0) 118: ADDIU V0, V0, C 11C: MTC1 V0, F12 120: NOP 124: JAL ~Func:clamp_angle 128: CVT.S.W F12, F12 12C: TRUNC.W.S F8, F0 130: SWC1 F8, 74 (S0) 134: LW V0, 74 (S2) 138: BGTZ V0, .o218 13C: ADDIU V0, V0, FFFF 140: LW V0, 14 (S3) 144: SW V0, 74 (S2) 148: LWC1 F2, C (S3) 14C: LIF F5, 1.75 154: MTC1 R0, F4 158: CVT.D.S F2, F2 15C: MUL.D F2, F2, F4 160: NOP 164: LWC1 F0, 10 (S3) 168: CVT.D.S F0, F0 16C: MUL.D F0, F0, F4 170: NOP 174: COPY A0, S4 178: CVT.S.D F2, F2 17C: CVT.S.D F0, F0 180: MFC1 A2, F2 184: MFC1 A3, F0 188: COPY A1, S0 18C: JAL 800490B4 190: SW R0, 10 (SP) 194: BEQ V0, R0, .o210 198: CLEAR A0 19C: COPY A1, S1 1A0: CLEAR A2 1A4: LI S0, C 1A8: LH V1, A8 (S1) 1AC: LIF F0, 1.0 1B4: LIF F2, 2.0 1BC: LIF F4, -20.0 1C4: MTC1 V1, F8 1C8: NOP 1CC: CVT.S.W F8, F8 1D0: MFC1 A3, F8 1D4: ADDIU V0, SP, 38 1D8: SW S0, 1C (SP) 1DC: SW V0, 20 (SP) 1E0: SWC1 F0, 10 (SP) 1E4: SWC1 F2, 14 (SP) 1E8: JAL ~Func:fx_emote 1EC: SWC1 F4, 18 (SP) 1F0: COPY A0, S1 1F4: LI A1, 2F4 1F8: JAL ~Func:ai_enemy_play_sound 1FC: LUI A2, 20 200: LWC1 F0, 3C (S1) 204: SWC1 F0, 64 (S1) 208: BEQ R0, R0, .o2E8 20C: SW S0, 70 (S2) .o210 210: LW V0, 74 (S2) 214: ADDIU V0, V0, FFFF .o218 218: SW V0, 74 (S2) 21C: LH V0, 8C (S1) 220: BNE V0, R0, .o2E8 224: NOP 228: LWC1 F12, 38 (S1) 22C: LW V0, D0 (S0) 230: LWC1 F14, 40 (S1) 234: LWC1 F8, 0 (V0) 238: CVT.S.W F8, F8 23C: MFC1 A2, F8 240: LWC1 F8, 8 (V0) 244: CVT.S.W F8, F8 248: MFC1 A3, F8 24C: JAL ~Func:atan2 250: NOP 254: LW A1, 18 (S1) 258: MFC1 A2, F0 25C: COPY A0, S1 260: JAL ~Func:npc_move_heading 264: SW A2, C (S1) 268: LWC1 F12, 38 (S1) 26C: LW V0, D0 (S0) 270: LWC1 F14, 40 (S1) 274: LWC1 F8, 0 (V0) 278: CVT.S.W F8, F8 27C: MFC1 A2, F8 280: LWC1 F8, 8 (V0) 284: CVT.S.W F8, F8 288: MFC1 A3, F8 28C: JAL ~Func:dist2D 290: NOP 294: LWC1 F2, 18 (S1) 298: ADD.S F2, F2, F2 29C: C.LE.S F0, F2 2A0: NOP 2A4: BC1F .o2E8 2A8: SWC1 F0, 34 (SP) 2AC: JAL ~Func:rand_int 2B0: LI A0, 3E8 2B4: LI V1, 55555556 2BC: MULT V0, V1 2C0: LI V1, 2 2C4: SRA A0, V0, 1F 2C8: SW V1, 70 (S2) 2CC: MFHI T0 2D0: SUBU A0, T0, A0 2D4: SLL V1, A0, 1 2D8: ADDU V1, V1, A0 2DC: SUBU V0, V0, V1 2E0: ADDIU V0, V0, 2 2E4: SW V0, 74 (S2) .o2E8 2E8: LW RA, 54 (SP) 2EC: LW S4, 50 (SP) 2F0: LW S3, 4C (SP) 2F4: LW S2, 48 (SP) 2F8: LW S1, 44 (SP) 2FC: LW S0, 40 (SP) 300: LDC1 F26, 70 (SP) 304: LDC1 F24, 68 (SP) 308: LDC1 F22, 60 (SP) 30C: LDC1 F20, 58 (SP) 310: JR RA 314: ADDIU SP, SP, 78 } #new:Function $Function_802438F0 { 0: ADDIU SP, SP, FFA0 4: SW S4, 50 (SP) 8: COPY S4, A0 C: SW RA, 58 (SP) 10: SW S5, 54 (SP) 14: SW S3, 4C (SP) 18: SW S2, 48 (SP) 1C: SW S1, 44 (SP) 20: SW S0, 40 (SP) 24: LW S2, 148 (S4) 28: LH A0, 8 (S2) 2C: JAL ~Func:get_npc_unsafe 30: COPY S0, A1 34: LW V1, C (S4) 38: COPY A0, S4 3C: LW A1, 0 (V1) 40: JAL ~Func:get_variable 44: COPY S5, V0 48: SW R0, 20 (SP) 4C: LW V1, D0 (S2) 50: LW V1, 30 (V1) 54: SW V1, 24 (SP) 58: LW V1, D0 (S2) 5C: LW V1, 1C (V1) 60: SW V1, 28 (SP) 64: LW V1, D0 (S2) 68: LW V1, 24 (V1) 6C: SW V1, 2C (SP) 70: LW V1, D0 (S2) 74: LW V1, 28 (V1) 78: ADDIU S3, SP, 20 7C: SW V1, 30 (SP) 80: LW V1, D0 (S2) 84: LIF F0, 125.0 8C: LW V1, 2C (V1) 90: COPY S1, V0 94: SWC1 F0, 38 (SP) 98: SH R0, 3C (SP) 9C: BEQ S0, R0, .oBC A0: SW V1, 34 (SP) A4: SW R0, 70 (S4) A8: COPY A0, S5 AC: COPY A1, S2 B0: COPY A2, S4 B4: JAL $Function_80242948 B8: COPY A3, S1 .oBC BC: LW V1, 70 (S4) C0: SLTIU V0, V1, 20 C4: BEQ V0, R0, .o248 C8: SLL V0, V1, 2 CC: LTW V0, V0 ($JumpTable_80246DA0) D8: JR V0 DC: NOP % LBL: from $JumpTable_80246DA0 , entry 0` E0: COPY A0, S4 E4: COPY A1, S1 E8: JAL $Function_80241760 EC: COPY A2, S3 F0: CLEAR A1 F4: COPY A2, A1 F8: SW R0, 10 (SP) FC: SW R0, 14 (SP) 100: SW R0, 18 (SP) 104: LW A0, 24 (S5) 108: JAL 802DE894 10C: COPY A3, A1 % LBL: from $JumpTable_80246DA0 , entry 1` 110: COPY A0, S4 114: COPY A1, S1 118: JAL $Function_80241910 11C: COPY A2, S3 120: BEQ R0, R0, .o148 124: NOP % LBL: from $JumpTable_80246DA0 , entry 2` 128: COPY A0, S4 12C: COPY A1, S1 130: JAL $Function_80241F38 134: COPY A2, S3 % LBL: from $JumpTable_80246DA0 , entry 3` 138: COPY A0, S4 13C: COPY A1, S1 140: JAL $Function_80241FF8 144: COPY A2, S3 .o148 148: LW V1, 70 (S4) 14C: LI V0, C 150: BNE V1, V0, .o248 154: LI V0, 6 158: BEQ R0, R0, .o248 15C: SH V0, 8E (S5) % LBL: from $JumpTable_80246DA0 , entry 12` 160: COPY A0, S4 164: COPY A1, S1 168: JAL $Function_80242C58 16C: COPY A2, S3 170: LW V1, 70 (S4) 174: LI V0, D 178: BNE V1, V0, .o248 17C: NOP % LBL: from $JumpTable_80246DA0 , entry 13` 180: COPY A0, S4 184: COPY A1, S1 188: JAL $Function_80242DB0 18C: COPY A2, S3 190: BEQ R0, R0, .o248 194: NOP % LBL: from $JumpTable_80246DA0 , entry 14` 198: COPY A0, S4 19C: COPY A1, S1 1A0: JAL $Function_80242EB4 1A4: COPY A2, S3 1A8: LW V1, 70 (S4) 1AC: LI V0, F 1B0: BNE V1, V0, .o248 1B4: NOP % LBL: from $JumpTable_80246DA0 , entry 15` 1B8: COPY A0, S4 1BC: COPY A1, S1 1C0: JAL $Function_80242F94 1C4: COPY A2, S3 1C8: BEQ R0, R0, .o248 1CC: NOP % LBL: from $JumpTable_80246DA0 , entry 16` 1D0: COPY A0, S4 1D4: COPY A1, S1 1D8: JAL $Function_80243230 1DC: COPY A2, S3 % LBL: from $JumpTable_80246DA0 , entry 17` 1E0: COPY A0, S4 1E4: COPY A1, S1 1E8: JAL $Function_802432E8 1EC: COPY A2, S3 1F0: BEQ R0, R0, .o248 1F4: NOP % LBL: from $JumpTable_80246DA0 , entry 18` 1F8: COPY A0, S4 1FC: COPY A1, S1 200: JAL $Function_80243468 204: COPY A2, S3 208: BEQ R0, R0, .o248 20C: NOP % LBL: from $JumpTable_80246DA0 , entry 20` 210: COPY A0, S4 214: COPY A1, S1 218: JAL $Function_802434B0 21C: COPY A2, S3 220: BEQ R0, R0, .o248 224: NOP % LBL: from $JumpTable_80246DA0 , entry 30` 228: COPY A0, S4 22C: COPY A1, S1 230: JAL $Function_80243530 234: COPY A2, S3 % LBL: from $JumpTable_80246DA0 , entry 31` 238: COPY A0, S4 23C: COPY A1, S1 240: JAL $Function_802435D8 244: COPY A2, S3 % LBL: from $JumpTable_80246DA0 , entry 29` .o248 248: LW V0, 70 (S4) 24C: LW RA, 58 (SP) 250: LW S5, 54 (SP) 254: LW S4, 50 (SP) 258: LW S3, 4C (SP) 25C: LW S2, 48 (SP) 260: LW S1, 44 (SP) 264: LW S0, 40 (SP) 268: XORI V0, V0, 64 26C: SLTIU V0, V0, 1 270: SLL V0, V0, 1 274: JR RA 278: ADDIU SP, SP, 60 } #new:Function $Function_80243B6C { 0: ADDIU SP, SP, FFE8 4: SW RA, 10 (SP) 8: JAL ~Func:increment_status_menu_disabled C: NOP 10: LUI A1, 437F 14: JAL ~Func:set_screen_overlay_params_back 18: CLEAR A0 1C: LW RA, 10 (SP) 20: LI V0, 2 24: JR RA 28: ADDIU SP, SP, 18 } #new:Function $Function_80243B98 { 0: ADDIU SP, SP, FFE8 4: SW RA, 10 (SP) 8: JAL ~Func:get_enemy_safe C: LI A0, 9 10: BEQ V0, R0, .o6C 14: LI V0, 2 18: JAL ~Func:get_enemy 1C: LI A0, 9 20: LW A0, D0 (V0) 24: LI V1, 2 28: SW V1, 0 (A0) 2C: LW A0, D0 (V0) 30: LI V1, FE3E 34: SW V1, 4 (A0) 38: LW V1, D0 (V0) 3C: SW R0, 8 (V1) 40: LW V1, D0 (V0) 44: LI A1, AF 48: SW A1, C (V1) 4C: LW A0, D0 (V0) 50: LI V1, 12C 54: SW V1, 10 (A0) 58: LW V1, D0 (V0) 5C: SW R0, 14 (V1) 60: LW V1, D0 (V0) 64: LI V0, 2 68: SW A1, 18 (V1) .o6C 6C: LW RA, 10 (SP) 70: JR RA 74: ADDIU SP, SP, 18 } #new:Function $Function_80243C10 { 0: ADDIU SP, SP, FFE8 4: SW RA, 10 (SP) 8: JAL ~Func:get_enemy_safe C: LI A0, 9 10: BEQ V0, R0, .o34 14: LI V0, 2 18: JAL ~Func:get_enemy 1C: LI A0, 9 20: COPY A0, V0 24: LW V1, B0 (A0) 28: LI V0, 2 2C: ORI V1, V1, 80 30: SW V1, B0 (A0) .o34 34: LW RA, 10 (SP) 38: JR RA 3C: ADDIU SP, SP, 18 } #new:Function $Function_80243C50 { 0: ADDIU SP, SP, FFE8 4: SW RA, 10 (SP) 8: LW V0, 148 (A0) C: JAL ~Func:get_npc_unsafe 10: LH A0, 8 (V0) 14: COPY A0, V0 18: LI A1, 32F 1C: JAL ~Func:ai_enemy_play_sound 20: CLEAR A2 24: LW RA, 10 (SP) 28: LI V0, 2 2C: JR RA 30: ADDIU SP, SP, 18 } PADDING: 80243C84 to 80243C90 (00003C84 to 00003C90) 00000000 00000000 00000000 #new:EntryList $EntryList { ~Vec4f:Entry0 % -575.0 0.0 180.0 90.0 ~Vec4f:Entry1 % -575.0 210.0 180.0 90.0 } #new:Header $Header { [MainScript] $Script_Main [EntryList] $EntryList [EntryCount] 00000002 [Background] 00000000 [MapTattle] 001900C8 } #new:Script $Script_80243CF0 { 0: Switch *GB_StoryProgress C: Case < .Story:Ch3_TubbaWokeUp % FFFFFFE3 18: Call SetMusicTrack ( 00000000 .Song:TubbasManor 00000000 00000008 ) 34: Case < .Story:Ch3_DefeatedTubbaBlubba % FFFFFFF0 40: Call SetMusicTrack ( 00000000 .Song:TubbaEscape 00000000 00000008 ) 5C: Default 64: Call SetMusicTrack ( 00000000 .Song:TubbasManor 00000000 00000008 ) 80: EndSwitch 88: Return 90: End } PADDING: 80243D88 to 80243D90 (00003D88 to 00003D90) 00000000 00000000 #new:Script $Script_ExitDoubleDoor_80243D90 { 0: SetGroup 0000001B C: Call DisablePlayerInput ( .True ) 1C: Call UseDoorSounds ( .DoorSounds:Creaky ) 2C: Set *Var0 ~Entry:Entry0 3C: Set *Var1 ~Collider:deilittse 4C: Set *Var2 ~Model:o142 5C: Set *Var3 ~Model:o143 6C: Exec ExitDoubleDoor 78: Wait 17` 84: Call GotoMap ( $ASCII_802469F0 00000002 ) % dgb_01 98: Wait 100` A4: Return AC: End } #new:Script $Script_ExitDoubleDoor_80243E44 { 0: SetGroup 0000001B C: Call DisablePlayerInput ( .True ) 1C: Call UseDoorSounds ( .DoorSounds:Creaky ) 2C: Set *Var0 ~Entry:Entry1 3C: Set *Var1 ~Collider:deilittne 4C: Set *Var2 ~Model:o140 5C: Set *Var3 ~Model:o141 6C: Exec ExitDoubleDoor 78: Wait 17` 84: Call GotoMap ( $ASCII_802469F0 00000004 ) % dgb_01 98: Wait 100` A4: Return AC: End } #new:Script $Script_EnterDoubleDoor_80243EF8 { 0: Call UseDoorSounds ( .DoorSounds:Creaky ) 10: Call GetEntryID ( *Var0 ) 20: Switch *Var0 2C: Case == ~Entry:Entry0 38: Set *Var2 ~Model:o142 48: Set *Var3 ~Model:o143 58: ExecWait EnterDoubleDoor 64: Case == ~Entry:Entry1 70: Set *Var2 ~Model:o140 80: Set *Var3 ~Model:o141 90: ExecWait EnterDoubleDoor 9C: EndSwitch A4: Return AC: End } #new:Script_Main $Script_Main { 0: Set *GB_WorldLocation .Location:TubbasManor 10: Call SetSpriteShading ( .Shading:None ) 20: Call SetCamPerspective ( .Cam:Default 00000003 25` 16` 4096` ) 40: Call SetCamBGColor ( .Cam:Default 0` 0` 0` ) 5C: Call SetCamEnabled ( .Cam:Default .True ) 70: Switch *GB_StoryProgress 7C: Case < .Story:Ch3_TubbaSmashedTheBridges % FFFFFFE4 88: Call MakeNpcs ( .True $NpcGroupList_80246958 ) 9C: Case < .Story:Ch3_DefeatedTubbaBlubba % FFFFFFF0 A8: Call MakeNpcs ( .True $NpcGroupList_802469AC ) BC: Case < .Story:Ch6_ReturnedToToadTown % 3C C8: Call MakeNpcs ( .True $NpcGroupList_802469C4 ) DC: EndSwitch E4: ExecWait $Script_802469E0 F0: Bind $Script_ExitDoubleDoor_80243D90 .Trigger:WallPressA ~Collider:deilittse 00000001 00000000 10C: Bind $Script_ExitDoubleDoor_80243E44 .Trigger:WallPressA ~Collider:deilittne 00000001 00000000 128: Exec $Script_80243CF0 134: Exec $Script_EnterDoubleDoor_80243EF8 140: Return 148: End } PADDING: 802440FC to 80244100 (000040FC to 00004100) 00000000 #new:Unknown $???_80244100 { 40900000 00000000 00000000 432A0000 42B40000 00000001 4079999A 000000B4 00000002 432A0000 42B40000 00000001 } % Origin: HEURISTIC #new:Script $Script_80244130 { 0: Call $Function_80240B94 ( $???_80244100 ) 10: Return 18: End } MISSING: 80244150 to 8024417C (00004150 to 0000417C) 00000000 005A0041 00000000 00000000 80244130 80077F70 00000000 8007809C 00000000 00000000 000D0000 #new:NpcSettings $NpcSettings_8024417C { 00000000 005A0041 00000000 00000000 00000000 80077F70 00000000 8007809C 00000000 00000000 000D0000 } MISSING: 802441A8 to 802441D4 (000041A8 to 000041D4) 00000000 00180018 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 000D0000 #new:Script $Script_802441D4 { 0: Call GetBattleOutcome ( *Var0 ) 10: Switch *Var0 1C: Case == .Outcome:PlayerWon % 0 28: Call RemoveNpc ( .Npc:Self ) 38: Case == .Outcome:PlayerFled % 2 44: Call SetNpcPos ( .Npc:Self 0` -1000` 0` ) 60: Call 80045900 ( 00000001 ) 70: Case == .Outcome:EnemyFled % 3 7C: Call SetEnemyFlagBits ( .Npc:Self 00000010 00000001 ) 94: Call RemoveNpc ( .Npc:Self ) A4: EndSwitch AC: Return B4: End } #new:ExtraAnimationList $ExtraAnimationList_80244290 { 00390000 00390002 00390003 00390004 0039000C 00390007 00390008 00390011 00390012 FFFFFFFF } #new:ExtraAnimationList $ExtraAnimationList_802442B8 { 00390000 FFFFFFFF } #new:AISettings $AISettings_802442C0 { 1.5 % move speed 120` % move time 30` % wait time 85.0 % alert radius 65.0 5` 3.5 % chase speed 90` 12` 110.0 % chase radius 90.0 3` } #new:Script $Script_NpcAI_802442F0 { 0: Call SetSelfVar ( 00000000 00000000 ) 14: Call SetSelfVar ( 00000001 00000005 ) 28: Call SetSelfVar ( 00000002 00000008 ) 3C: Call SetSelfVar ( 00000003 0000000C ) 50: Call $Function_802414AC ( $AISettings_802442C0 ) 60: Return 68: End } #new:NpcSettings $NpcSettings_80244360 { 00000000 00240022 00000000 00000000 $Script_NpcAI_802442F0 80077F70 00000000 8007809C 00000000 00000000 000D0000 } #new:Script $Script_NpcAI_8024438C { 0: Call EnableNpcShadow ( .Npc:Self .False ) 14: Call SetSelfVar ( 00000000 00000004 ) 28: Call SetSelfVar ( 00000001 00000020 ) 3C: Call SetSelfVar ( 00000002 00000032 ) 50: Call SetSelfVar ( 00000003 00000020 ) 64: Call SetSelfVar ( 00000004 00000003 ) 78: Call SetSelfVar ( 0000000F 000020C5 ) 8C: Call $Function_8024124C ( ) 98: Return A0: End } #new:NpcSettings $NpcSettings_80244434 { 00000000 000E0012 00000000 00000000 $Script_NpcAI_8024438C 00000000 00000000 $Script_802441D4 00000000 00000000 000D0008 } % Origin: HEURISTIC #new:FloatTable $FloatTable_80244460 { 4.5 3.5 2.6 2.0 1.5 20.0 } #new:Script $Script_80244478 { 0: Call SetSelfEnemyFlagBits ( 3F100000 00000001 ) 14: Call SetNpcFlagBits ( .Npc:Self 00000D00 .True ) 2C: Return 34: End } #new:AISettings $AISettings_802444B4 { 1.5 % move speed 90` % move time 30` % wait time 240.0 % alert radius 0.0 1` 5.3 % chase speed 180` 1` 240.0 % chase radius 0.0 1` } #new:Script $Script_NpcAI_802444E4 { 0: Call SetSelfVar ( 00000000 00000000 ) 14: Call SetSelfVar ( 00000005 FFFFFD76 ) 28: Call SetSelfVar ( 00000006 0000001E ) 3C: Call SetSelfVar ( 00000001 00000258 ) 50: Call $Function_802438F0 ( $AISettings_802444B4 ) 60: Call DisablePlayerInput ( .True ) 70: Wait 2` 7C: Label 14 88: Call GetPlayerPos ( *Var0 *Var1 *Var2 ) A0: Call GetNpcPos ( .Npc:Self *Var3 *Var4 *Var5 ) BC: Call SetNpcPos ( .Npc:Self *Var0 *Var4 *Var2 ) D8: Call GetPlayerActionState ( *Var0 ) E8: If *Var0 != .ActionState:Idle % 0 F8: Wait 1` 104: Goto 14 110: EndIf 118: Call DisablePlayerPhysics ( .True ) 128: Call 802D2B6C ( ) 134: Call DisablePartnerAI ( 00000000 ) 144: SetGroup 00000000 150: Call SetTimeFreezeMode ( 00000001 ) 160: Call GetPlayerPos ( *Var0 *Var1 *Var2 ) 178: Add *Var1 00000014 188: Add *Var2 00000002 198: Call SetNpcPos ( .Npc:Self *Var0 *Var1 *Var2 ) 1B4: Call 80045838 ( FFFFFFFF 000002F7 00000000 ) 1CC: Call SetNpcAnimation ( .Npc:Self 00380008 ) 1E0: Wait 10` 1EC: Call SetPlayerAnimation ( 00080017 ) 1FC: Wait 10` 208: Call 80045838 ( FFFFFFFF 0000072E 00000000 ) 220: Thread 228: Loop 00000064 234: Call GetNpcPos ( .Npc:Self *Var0 *Var1 *Var2 ) 250: Add *Var1 00000001 260: Call SetNpcPos ( .Npc:Self *Var0 *Var1 *Var2 ) 27C: Call GetPlayerPos ( *Var0 *Var1 *Var2 ) 294: Add *Var1 00000001 2A4: Call SetPlayerPos ( *Var0 *Var1 *Var2 ) 2BC: Wait 1` 2C8: EndLoop 2D0: EndThread 2D8: Thread 2E0: Call SetNpcAnimation ( .Npc:Partner 00000108 ) 2F4: Call GetNpcPos ( .Npc:Partner *Var0 *Var1 *Var2 ) 310: Call NpcJump0 ( .Npc:Partner *Var0 *Var1 *Var2 10` ) 330: Call GetNpcPos ( .Npc:Partner *Var0 *Var1 *Var2 ) 34C: Call NpcJump0 ( .Npc:Partner *Var0 *Var1 *Var2 10` ) 36C: Call GetNpcPos ( .Npc:Partner *Var0 *Var1 *Var2 ) 388: Call NpcJump0 ( .Npc:Partner *Var0 *Var1 *Var2 10` ) 3A8: Call GetNpcPos ( .Npc:Partner *Var0 *Var1 *Var2 ) 3C4: Call NpcJump0 ( .Npc:Partner *Var0 *Var1 *Var2 10` ) 3E4: EndThread 3EC: Wait 30` 3F8: Call GotoMap ( $ASCII_80246E20 00000002 ) % dgb_00 40C: Wait 100` 418: Return 420: End } % Origin: HEURISTIC #new:Script $Script_8024490C { 0: Call GetOwnerEncounterTrigger ( *Var0 ) 10: Switch *Var0 1C: Case == .EncounterTrigger:None % 1 28: CaseOR == .EncounterTrigger:Jump % 2 34: CaseOR == .EncounterTrigger:Hammer % 4 40: CaseOR == .EncounterTrigger:Partner % 6 4C: Call GetSelfAnimationFromTable ( 00000007 *Var0 ) 60: ExecWait 800936DC 6C: EndCaseGroup 74: EndSwitch 7C: Return 84: End } % Origin: HEURISTIC #new:Script $Script_80244998 { 0: Call GetBattleOutcome ( *Var0 ) 10: Switch *Var0 1C: Case == .Outcome:PlayerWon % 0 28: Call DoNpcDefeat ( ) 34: Case == .Outcome:PlayerLost % 1 40: Case == .Outcome:PlayerFled % 2 4C: EndSwitch 54: Return 5C: End } #new:NpcSettings $NpcSettings_802449FC { 00000000 00260020 $Script_80244478 00000000 $Script_NpcAI_802444E4 00000000 00000000 00000000 00000000 00000000 00630000 } #new:NpcSettings $NpcSettings_80244A28 { 00000000 00180018 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00630000 } #new:Script $Script_Idle_80244A54 { 0: Loop C: Call GetPlayerPos ( *Var0 *Var1 *Var2 ) 24: If *Var0 >= FFFFFEA2 34: BreakLoop 3C: EndIf 44: Wait 1` 50: EndLoop 58: Set *GB_ARN_Tubba_MapID 00000008 68: Set *GB_StoryProgress .Story:Ch3_TubbaChasedMarioInHall 78: Call PlaySoundAtCollider ( ~Collider:deilittne .Sound:CreakyDoorOpen 00000000 ) 90: Call MakeLerp ( 00000000 00000050 0000000A .Easing:Linear ) AC: Loop B8: Call UpdateLerp ( ) C4: Call RotateModel ( ~Model:o140 *Var0 00000000 FFFFFFFF 00000000 ) E4: Call RotateModel ( ~Model:o141 *Var0 00000000 00000001 00000000 ) 104: Wait 1` 110: If *Var1 == 00000000 120: BreakLoop 128: EndIf 130: EndLoop 138: Call SetNpcAnimation ( .NpcID:WorldTubba_09 006A000A ) 14C: Call SetNpcPos ( .Npc:Self -665` 210` 180` ) 168: Call SetNpcYaw ( .Npc:Self 90` ) 17C: Call NpcMoveTo ( .Npc:Self -530` 180` 30` ) 198: Thread 1A0: Wait 20` 1AC: Call MakeLerp ( 00000050 00000000 0000000A .Easing:Linear ) 1C8: Loop 1D4: Call UpdateLerp ( ) 1E0: Call RotateModel ( ~Model:o140 *Var0 00000000 FFFFFFFF 00000000 ) 200: Call RotateModel ( ~Model:o141 *Var0 00000000 00000001 00000000 ) 220: Wait 1` 22C: If *Var1 == 00000000 23C: BreakLoop 244: EndIf 24C: EndLoop 254: Call PlaySoundAtCollider ( ~Collider:deilittne .Sound:CreakyDoorClose 00000000 ) 26C: EndThread 274: Call NpcMoveTo ( .Npc:Self -500` 80` 10` ) 290: Call BindNpcAI ( .Npc:Self $Script_NpcAI_80244D7C ) 2A4: Return 2AC: End } #new:Script $Script_80244D08 { 0: Label A C: Call GetNpcPos ( .NpcID:WorldTubba_09 *Var0 *Var1 *Var2 ) 28: If *Var1 > 00000000 38: Wait 1` 44: Goto A 50: EndIf 58: Call $Function_80243B98 ( ) 64: Return 6C: End } #new:Script $Script_NpcAI_80244D7C { 0: Call $Function_80243C10 ( ) C: Exec $Script_80244D08 18: Thread 20: Loop 2C: Call PlaySoundAtNpc ( .Npc:Self 000020F6 00400000 ) 44: Call ShakeCam ( .Cam:Default 00000000 5` *Fixed[2.0] ) 60: Wait 5` 6C: Call PlaySoundAtNpc ( .Npc:Self 000020F6 00400000 ) 84: Call ShakeCam ( .Cam:Default 00000000 2` *Fixed[1.0] ) A0: Wait 8` AC: EndLoop B4: EndThread BC: Call $Function_80240B94 ( $???_80244100 ) CC: Return D4: End } #new:Script $Script_Defeat_80244E58 { 0: Call $Function_80243B6C ( ) C: Call GotoMap ( $ASCII_80246E28 00000002 ) % dgb_01 20: Wait 100` 2C: Return 34: End } #new:Script $Script_Init_80244E94 { 0: If *GB_StoryProgress < .Story:Ch3_TubbaSmashedTheBridges % FFFFFFE4 10: Call SetNpcPos ( .Npc:Self 0` -1000` 0` ) 2C: Call SetNpcFlagBits ( .Npc:Self 00000004 .True ) 44: Return 4C: EndIf 54: If *GB_StoryProgress >= .Story:Ch3_TubbaChasedMarioInFoyer % FFFFFFE6 64: Call SetNpcPos ( .Npc:Self 0` -1000` 0` ) 80: Call SetNpcFlagBits ( .Npc:Self 00000004 .True ) 98: Return A0: EndIf A8: Call SetNpcScale ( .Npc:Self *Fixed[1.25] *Fixed[1.25] *Fixed[1.25] ) C4: Call BindNpcDefeat ( .Npc:Self $Script_Defeat_80244E58 ) D8: Call GetEntryID ( *Var0 ) E8: Switch *Var0 F4: Case == ~Entry:Entry0 100: If *GB_ARN_Tubba_MapID != 00000008 110: Call SetNpcPos ( .Npc:Self 0` -1000` 0` ) 12C: Call SetNpcFlagBits ( .Npc:Self 00000004 .True ) 144: Else 14C: Call SetNpcPos ( .Npc:Self -130` 0` 200` ) 168: Call BindNpcIdle ( .Npc:Self $Script_NpcAI_80244D7C ) 17C: EndIf 184: Case == ~Entry:Entry1 190: If *GB_ARN_Tubba_MapID != 00000008 1A0: Call BindNpcIdle ( .Npc:Self $Script_Idle_80244A54 ) 1B4: Else 1BC: Call SetNpcPos ( .Npc:Self -130` 210` 80` ) 1D8: Call BindNpcIdle ( .Npc:Self $Script_NpcAI_80244D7C ) 1EC: EndIf 1F4: EndSwitch 1FC: Return 204: End } #new:NpcGroup $NpcGroup_802450A0 { .NpcID:NPC_WorldTubba_09 $NpcSettings_8024417C ~Vec3f:NPC_WorldTubba_09 % 0 -1000 0 00A40004 $Script_Init_80244E94 00000000 00000000 0000010E ~Items:5:SuperShroom:A ~HP:Standard:3 ~FP:Standard:2 ~CoinBonus:2:3 ~Movement:NPC_WorldTubba_09 ~AnimationTable:NPC_WorldTubba_09 % .Sprite:WorldTubba 00000001 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80245290 { .NpcID:NPC_WorldClubba_01 $NpcSettings_80244360 ~Vec3f:NPC_WorldClubba_01 % -250 0 135 00000400 00000000 00000000 00000000 0000005A ~Items:5:SuperShroom:A ~HP:Standard:3 ~FP:Standard:2 ~CoinBonus:2:3 ~Movement:NPC_WorldClubba_01 ~AnimationTable:NPC_WorldClubba_01 % .Sprite:WorldClubba 00000002 00000000 $ExtraAnimationList_80244290 00000000 % no tattle string % % $NpcGroup_80245290[1F0] .NpcID:NPC_WorldClubba_02 $NpcSettings_80244434 ~Vec3f:NPC_WorldClubba_02 % 0 -1000 0 00800D00 00000000 00000000 00000000 00000000 ~NoDrops ~Movement:NPC_WorldClubba_02 ~AnimationTable:NPC_WorldClubba_02 % .Sprite:WorldClubba 00000000 00000000 $ExtraAnimationList_802442B8 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80245670 { .NpcID:NPC_WorldClubba_03 $NpcSettings_80244360 ~Vec3f:NPC_WorldClubba_03 % 220 0 155 00000400 00000000 00000000 00000000 0000010E ~Items:5:SuperShroom:A ~HP:Standard:3 ~FP:Standard:2 ~CoinBonus:2:3 ~Movement:NPC_WorldClubba_03 ~AnimationTable:NPC_WorldClubba_03 % .Sprite:WorldClubba 00000002 00000000 $ExtraAnimationList_80244290 00000000 % no tattle string % % $NpcGroup_80245670[1F0] .NpcID:NPC_WorldClubba_04 $NpcSettings_80244434 ~Vec3f:NPC_WorldClubba_04 % 0 -1000 0 00800D00 00000000 00000000 00000000 00000000 ~NoDrops ~Movement:NPC_WorldClubba_04 ~AnimationTable:NPC_WorldClubba_04 % .Sprite:WorldClubba 00000000 00000000 $ExtraAnimationList_802442B8 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80245A50 { .NpcID:NPC_WorldClubba_05 $NpcSettings_80244360 ~Vec3f:NPC_WorldClubba_05 % 825 100 200 00000400 00000000 00000000 00000000 0000010E ~Items:5:SuperShroom:A ~HP:Standard:3 ~FP:Standard:2 ~CoinBonus:2:3 ~Movement:NPC_WorldClubba_05 ~AnimationTable:NPC_WorldClubba_05 % .Sprite:WorldClubba 00000003 00000000 $ExtraAnimationList_80244290 00000000 % no tattle string % % $NpcGroup_80245A50[1F0] .NpcID:NPC_WorldClubba_06 $NpcSettings_80244434 ~Vec3f:NPC_WorldClubba_06 % 0 -1000 0 00800D00 00000000 00000000 00000000 00000000 ~NoDrops ~Movement:NPC_WorldClubba_06 ~AnimationTable:NPC_WorldClubba_06 % .Sprite:WorldClubba 00000000 00000000 $ExtraAnimationList_802442B8 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80245E30 { .NpcID:NPC_Sentinel_07 $NpcSettings_802449FC ~Vec3f:NPC_Sentinel_07 % 75 310 85 00000400 00000000 00000000 00000000 0000005A ~NoDrops ~Movement:NPC_Sentinel_07 ~AnimationTable:NPC_Sentinel_07 % .Sprite:Sentinel 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80246020 { .NpcID:NPC_Sentinel_08 $NpcSettings_802449FC ~Vec3f:NPC_Sentinel_08 % -451 310 81 00000400 00000000 00000000 00000000 0000005A ~NoDrops ~Movement:NPC_Sentinel_08 ~AnimationTable:NPC_Sentinel_08 % .Sprite:Sentinel 00000000 00000000 00000000 00000000 % no tattle string } #new:Script $Script_Idle_80246210 { 0: Label 0 C: Call SetNpcAnimation ( .Npc:Self 00390007 ) 20: Wait 30` 2C: Loop 0000000F 38: Call $Function_80243C50 ( ) 44: Wait 60` 50: EndLoop 58: Call SetNpcAnimation ( .Npc:Self 0039000C ) 6C: Wait 20` 78: Call SetNpcAnimation ( .Npc:Self 00390007 ) 8C: Wait 30` 98: Loop 00000005 A4: Call $Function_80243C50 ( ) B0: Wait 60` BC: EndLoop C4: Call SetNpcAnimation ( .Npc:Self 0039000C ) D8: Wait 15` E4: Goto 0 F0: Return F8: End } #new:Script $Script_Interact_80246310 { 0: Call SetNpcAnimation ( .Npc:Self 00390008 ) 14: Call PlaySoundAtNpc ( .Npc:Self 000002F1 00000000 ) 2C: Wait 10` 38: Call SetNpcAnimation ( .Npc:Self 00390002 ) 4C: Wait 20` 58: Call GetNpcYaw ( .Npc:Self *Var0 ) 6C: Add *Var0 000000B4 7C: Call InterpNpcYaw ( .Npc:Self *Var0 0` ) 94: Wait 10` A0: Call GetNpcYaw ( .Npc:Self *Var0 ) B4: Add *Var0 000000B4 C4: Call InterpNpcYaw ( .Npc:Self *Var0 0` ) DC: Wait 25` E8: Call GetNpcYaw ( .Npc:Self *Var0 ) FC: Add *Var0 000000B4 10C: Call InterpNpcYaw ( .Npc:Self *Var0 0` ) 124: Wait 15` 130: Call NpcFacePlayer ( .Npc:Self 00000000 ) 144: Call SpeakToPlayer ( .Npc:Self 00390005 00390002 00000000 000E00F2 ) % Uh...huh? How long was I asleep? Where is everyone ... 164: Wait 10` 170: Call SetNpcAnimation ( .Npc:Self 00390006 ) 184: Wait 10` 190: Call SetNpcAnimation ( .Npc:Self 00390007 ) 1A4: Return 1AC: End } #new:Script $Script_Init_802464C4 { 0: Call SetNpcCollisionSize ( .Npc:Self 36` 30` ) 18: Call SetNpcAnimation ( .Npc:Self 00390007 ) 2C: Call BindNpcInteract ( .Npc:Self $Script_Interact_80246310 ) 40: Call BindNpcIdle ( .Npc:Self $Script_Idle_80246210 ) 54: Return 5C: End } #new:NpcGroup $NpcGroup_80246528 { .NpcID:NPC_WorldClubba_11 $NpcSettings_80244A28 ~Vec3f:NPC_WorldClubba_11 % 426 0 38 00600D01 $Script_Init_802464C4 00000000 00000000 0000010E ~NoDrops ~Movement:NPC_WorldClubba_11 ~AnimationTable:NPC_WorldClubba_11 % .Sprite:WorldClubba 00000002 00000000 00000000 001A00B6 % Everyone left while this Clubba was sleeping. He m ... } #new:Script $Script_Idle_80246718 { 0: Return 8: End } #new:Script $Script_Init_80246728 { 0: Call BindNpcIdle ( .Npc:Self $Script_Idle_80246718 ) 14: Call SetNpcPos ( .Npc:Self 0` -1000` 0` ) 30: Return 38: End } #new:NpcGroup $NpcGroup_80246768 { .NpcID:NPC_WorldClubba_00 $NpcSettings_80244360 ~Vec3f:NPC_WorldClubba_00 % -250 0 135 00000401 $Script_Init_80246728 00000000 00000000 0000005A ~Items:5:SuperShroom:A ~HP:Standard:3 ~FP:Standard:2 ~CoinBonus:2:3 ~Movement:NPC_WorldClubba_00 ~AnimationTable:NPC_WorldClubba_00 % .Sprite:WorldClubba 00000002 00000000 $ExtraAnimationList_80244290 00000000 % no tattle string } #new:NpcGroupList $NpcGroupList_80246958 { 00000001 $NpcGroup_80246768 0F020003 00000002 $NpcGroup_80245290 0F020003 00000002 $NpcGroup_80245670 0F020003 00000002 $NpcGroup_80245A50 0F030003 00000001 $NpcGroup_80245E30 00000000 00000001 $NpcGroup_80246020 00000000 00000000 00000000 00000000 } #new:NpcGroupList $NpcGroupList_802469AC { 00000001 $NpcGroup_802450A0 0F040001 00000000 00000000 00000000 } #new:NpcGroupList $NpcGroupList_802469C4 { 00000001 $NpcGroup_80246528 00000000 00000000 00000000 00000000 } PADDING: 802469DC to 802469E0 (000069DC to 000069E0) 00000000 #new:Script $Script_802469E0 { 0: Return 8: End } #new:ASCII $ASCII_802469F0 { "dgb_01" } PADDING: 802469F8 to 80246A00 (000069F8 to 00006A00) 00000000 00000000 #new:ConstDouble $ConstDouble_80246A00 { 32767.000000d } #new:ConstDouble $ConstDouble_80246A08 { 32767.000000d } #new:JumpTable $JumpTable_80246A10 { $Function_80240B94[1E4] $Function_80240B94[1F4] $Function_80240B94[20C] $Function_80240B94[21C] $Function_80240B94[234] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[24C] $Function_80240B94[25C] $Function_80240B94[274] $Function_80240B94[284] $Function_80240B94[29C] $Function_80240B94[2B4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2D4] $Function_80240B94[2CC] } #new:ConstDouble $ConstDouble_80246BA0 { 180.000000d } #new:JumpTable $JumpTable_80246BA8 { $Function_802414AC[184] $Function_802414AC[194] $Function_802414AC[1AC] $Function_802414AC[1BC] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[1D4] $Function_802414AC[1E4] $Function_802414AC[1FC] $Function_802414AC[20C] $Function_802414AC[224] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[23C] $Function_802414AC[244] $Function_802414AC[25C] $Function_802414AC[274] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[28C] $Function_802414AC[284] } #new:ConstDouble $ConstDouble_80246D38 { 32767.000000d } #new:ConstDouble $ConstDouble_80246D40 { 0.090000d } #new:ConstDouble $ConstDouble_80246D48 { 0.090000d } % Origin: HEURISTIC #new:JumpTable $JumpTable_80246D50 { $Function_80242A6C[10C] $Function_80242A6C[11C] $Function_80242A6C[134] $Function_80242A6C[144] $Function_80242A6C[1C4] $Function_80242A6C[1C4] $Function_80242A6C[1C4] $Function_80242A6C[1C4] $Function_80242A6C[1C4] $Function_80242A6C[1C4] $Function_80242A6C[15C] $Function_80242A6C[16C] $Function_80242A6C[184] $Function_80242A6C[19C] $Function_80242A6C[1B4] } PADDING: 80246D8C to 80246D90 (00006D8C to 00006D90) 00000000 #new:ConstDouble $ConstDouble_80246D90 { 360.000000d } #new:ConstDouble $ConstDouble_80246D98 { 1.800000d } #new:JumpTable $JumpTable_80246DA0 { $Function_802438F0[E0] $Function_802438F0[110] $Function_802438F0[128] $Function_802438F0[138] $Function_802438F0[248] $Function_802438F0[248] $Function_802438F0[248] $Function_802438F0[248] $Function_802438F0[248] $Function_802438F0[248] $Function_802438F0[248] $Function_802438F0[248] $Function_802438F0[160] $Function_802438F0[180] $Function_802438F0[198] $Function_802438F0[1B8] $Function_802438F0[1D0] $Function_802438F0[1E0] $Function_802438F0[1F8] $Function_802438F0[248] $Function_802438F0[210] $Function_802438F0[248] $Function_802438F0[248] $Function_802438F0[248] $Function_802438F0[248] $Function_802438F0[248] $Function_802438F0[248] $Function_802438F0[248] $Function_802438F0[248] $Function_802438F0[248] $Function_802438F0[228] $Function_802438F0[238] } #new:ASCII $ASCII_80246E20 { "dgb_00" } #new:ASCII $ASCII_80246E28 { "dgb_01" }
0
0.594263
1
0.594263
game-dev
MEDIA
0.220148
game-dev
0.755185
1
0.755185
OPENER-next/OpenStop
9,251
lib/models/element_variants/processed_relation.dart
part of 'base_element.dart'; /// Concrete implementation of [ProcessedElement] for OSM relations. /// See [ProcessedElement] for details. /// /// The geometry calculation requires adding all children/members in beforehand via `addChild`. class ProcessedRelation extends ProcessedElement<osmapi.OSMRelation, GeographicGeometry> with ChildElement, ParentElement { ProcessedRelation(super.element); /// Do not modify any of the members. Iterable<osmapi.OSMMember> get members => Iterable.castFrom(_osmElement.members); @override UnmodifiableSetView<ProcessedRelation> get parents => UnmodifiableSetView(_parents.cast<ProcessedRelation>()); @override void addParent(ProcessedRelation element) => super.addParent(element); @override void removeParent(ProcessedRelation element) => super.removeParent(element); /// All members that this relation references must be added before calling this via `addChild`. /// /// Note: Other relations that this relation might contain are currently ignored. /// /// For any relation other than of type "multipolygon" this will build a /// [GeographicCollection] which may not contain all elements of the relation, /// because its data may not be fetched entirely. /// This happens for example for large relations like the boundary of germany. /// /// This method throws for unresolvable relations: /// - for multipolygons when a child is missing /// - for other relations when all children are missing @override void calcGeometry() { if (tags['type'] == 'multipolygon') { _geometry = _fromMultipolygonRelation(); } else if (children.isNotEmpty) { _geometry = GeographicCollection([ for (final child in children) child.geometry, ]); } else { throw Exception( 'Geometry calculation failed because no children of relation $id have been loaded.', ); } } /// This algorithm is inspired by https://wiki.openstreetmap.org/wiki/Relation:multipolygon/Algorithm GeographicGeometry _fromMultipolygonRelation() { // assert that the provided ways are exactly the ones referenced by the relation. assert( _osmElement.members .where((member) => member.type == osmapi.OSMElementType.way) .every( (member) => _children.any( (element) => element is ProcessedWay && element.id == member.ref, ), ), 'OSM relation $id referenced ways that cannot be found in the provided way data set.', ); final outerClosedPolylines = <GeographicPolyline>[]; final innerClosedPolylines = <GeographicPolyline>[]; // Only extract ids where role is "inner", we will later assume that all ways/ids not extracted here have "outer". // This means that if a wrong role or nothing is set we will always fallback to "outer". // This assumption should also lead to a little performance boost. final innerWayIds = <int>{}; for (final member in _osmElement.members) { if (member.role == 'inner' && member.type == osmapi.OSMElementType.way) { innerWayIds.add(member.ref); } } // first step: ring grouping final nodePositionLookUp = <int, LatLng>{}; var wayList = _children.whereType<ProcessedWay>().map<osmapi.OSMWay>((way) { for (final node in way.children) { nodePositionLookUp[node.id] = node.geometry.center; } return way._osmElement; }).toList(); while (wayList.isNotEmpty) { final workingWay = wayList.removeLast(); final wayNodePool = _extractRingFromWays(wayList, workingWay); final accumulatedCoordinates = wayNodePool.nodeIds.map((id) { try { return nodePositionLookUp[id]!; } on TypeError { throw StateError('OSM node with id $id not found in the provided node data set.'); } }).toList(); final closedPolyline = GeographicPolyline(accumulatedCoordinates); // add polyline to the appropriate polyline set if (innerWayIds.contains(workingWay.id)) { innerClosedPolylines.add(closedPolyline); } else { outerClosedPolylines.add(closedPolyline); } wayList = wayNodePool.remainingWays; } // second step: polygon grouping final polygons = <GeographicPolygon>[]; // as long as there are outer polylines loop while (outerClosedPolylines.isNotEmpty) { // find first most inner polyline from outer polylines var currentPolygon = GeographicPolygon(outerShape: outerClosedPolylines.first); var outerPolylineIndex = 0; for (var i = 1; i < outerClosedPolylines.length; i++) { final polygon = GeographicPolygon(outerShape: outerClosedPolylines[i]); if (currentPolygon.enclosesPolygon(polygon)) { currentPolygon = polygon; outerPolylineIndex = i; } } // remove the current outer polyline from the collection outerClosedPolylines.removeAt(outerPolylineIndex); // find all inner polylines within the current outer polyline // remove them from the inner polyline collection and assign them to the current polygon for (var i = innerClosedPolylines.length - 1; i >= 0; i--) { if (currentPolygon.enclosesPolyline(innerClosedPolylines[i])) { currentPolygon.innerShapes.add( innerClosedPolylines.removeAt(i), ); } } polygons.add(currentPolygon); } if (polygons.length > 1) { return GeographicMultipolygon(polygons); } return polygons.single; } /// Extracts a ring (polygon) from the given ways starting with the initial way. /// This function connects ways that share an equal end/start point till a ring is formed. /// For cases where multiple ways connect at the same node this algorithm traverses all possible way-concatenations till a valid ring is found. /// It does this by creating a history of possible concatenations and backtracks if it couldn't find a valid ring. /// This is basically recursive but implemented in a non recursive way to mitigate any stack overflow. /// Throws an error if no ring could be built from the given ways _WayNodeIdPool _extractRingFromWays(List<osmapi.OSMWay> wayList, osmapi.OSMWay initialWay) { // this is used to keep a history which is required for backtracking the algorithm final workingWayHistory = ListQueue<Iterator<_WayNodeIdPool>>(); // add new way as initial history entry workingWayHistory.add( [_WayNodeIdPool(wayList, initialWay.nodeIds)].iterator, ); while (workingWayHistory.isNotEmpty) { while (workingWayHistory.last.moveNext()) { final lastEntry = workingWayHistory.last.current; final lastNodeId = lastEntry.nodeIds.last; final firstNodeId = workingWayHistory.first.current.nodeIds.first; // if ring is closed // TODO: Maybe add further checks/validation, for example if the ring is self-intersecting if (firstNodeId == lastNodeId) { // traverse the history and accumulate all nodes into a single iterable final nodes = workingWayHistory .map((historyEntry) => historyEntry.current.nodeIds) .expand((nodeIdList) => nodeIdList); return _WayNodeIdPool(lastEntry.remainingWays, nodes); } // take the current ring's end node id and find any connecting ways final potentialConnectingWays = _getConnectingWays(lastEntry.remainingWays, lastNodeId); // add all node ids of potential connecting ways to the history workingWayHistory.add(potentialConnectingWays.iterator); } workingWayHistory.removeLast(); } throw StateError('Ring extraction failed for OSM multipolygon relation.'); } /// Returns a lazy iterable with a list of node ids from each way that connects to the given node id. /// The node list order is already adjusted so that the first node will always connect to the given [nodeId]. /// Note: This means that the first original node is not included since it's equal to the given [nodeId]. Iterable<_WayNodeIdPool> _getConnectingWays(List<osmapi.OSMWay> wayList, int nodeId) sync* { // look for unassigned ways that start or end with the given node id for (var i = 0; i < wayList.length; i++) { final way = wayList[i]; // reverse node list depending on the node where the way connects // also ignore/filter the first node id since it's equal to the given [nodeId] if (way.nodeIds.last == nodeId) { // create a copy of the way list with all ways except the current way final subWayList = List.of(wayList)..removeAt(i); yield _WayNodeIdPool( subWayList, way.nodeIds.reversed.skip(1), ); } else if (way.nodeIds.first == nodeId) { // create a copy of the way list with all ways except the current way final subWayList = List.of(wayList)..removeAt(i); yield _WayNodeIdPool( subWayList, way.nodeIds.skip(1), ); } } } } class _WayNodeIdPool { final List<osmapi.OSMWay> remainingWays; final Iterable<int> nodeIds; _WayNodeIdPool(this.remainingWays, this.nodeIds); }
0
0.925217
1
0.925217
game-dev
MEDIA
0.261868
game-dev
0.973112
1
0.973112
FrictionalGames/HPL1Engine
24,603
sources/scene/World2D.cpp
/* * Copyright (C) 2006-2010 - Frictional Games * * This file is part of HPL1 Engine. * * HPL1 Engine 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. * * HPL1 Engine 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 HPL1 Engine. If not, see <http://www.gnu.org/licenses/>. */ #include "scene/World2D.h" #include "graphics/Graphics.h" #include "resources/Resources.h" #include "system/String.h" #include "math/Math.h" #include "math/MathTypes.h" #include "graphics/Mesh2d.h" #include "system/LowLevelSystem.h" #include "scene/Camera.h" #include "scene/TileMap.h" #include "scene/Node2D.h" #include "physics/Body2D.h" #include "physics/Collider2D.h" #include "scene/GridMap2D.h" #include "scene/Light2DPoint.h" #include "scene/ImageEntity.h" #include "impl/tinyXML/tinyxml.h" #include "resources/ParticleManager.h" #include "scene/SoundSource.h" #include "scene/Area2D.h" #include "system/Script.h" #include "resources/ScriptManager.h" #include "resources/FileSearcher.h" #include "graphics/ImageEntityData.h" #include "resources/TileSetManager.h" #include "system/MemoryManager.h" #include "graphics/Renderer2D.h" namespace hpl { ////////////////////////////////////////////////////////////////////////// // CONSTRUCTORS ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- cWorld2D::cWorld2D(tString asName,cGraphics *apGraphics,cResources *apResources,cSound* apSound, cCollider2D* apCollider) { mpGraphics = apGraphics; mpResources = apResources; mpSound = apSound; mpCollider = apCollider; mpRootNode = hplNew( cNode2D, () ); mpMapLights = NULL; mpMapImageEntities = NULL; mpMapBodies = NULL; mpTileMap = NULL; mpScript = NULL; msName=asName; mfLightZ=10; mAmbientColor=cColor(0,0); mlBodyIDCount =0; } //----------------------------------------------------------------------- cWorld2D::~cWorld2D() { if(mpTileMap)hplDelete(mpTileMap); if(mpMapLights)hplDelete(mpMapLights); if(mpMapImageEntities)hplDelete(mpMapImageEntities); if(mpMapBodies)hplDelete(mpMapBodies); if(mpMapParticles)hplDelete(mpMapParticles); if(mpMapAreas)hplDelete(mpMapAreas); tSoundSourceListIt it= mlstSoundSources.begin(); while(it != mlstSoundSources.end()) { hplDelete( *it); it++; } mlstSoundSources.clear(); if(mpScript){ mpResources->GetScriptManager()->Destroy(mpScript); } } //----------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////// // PUBLIC METHODS ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- void cWorld2D::Render(cCamera2D* apCamera) { mpTileMap->Render(apCamera); RenderImagesEntities(apCamera); RenderParticles(apCamera); } //----------------------------------------------------------------------- void cWorld2D::Update(float afTimeStep) { UpdateEntities(); UpdateBodies(); UpdateParticles(); UpdateSoundSources(); UpdateLights(); } //----------------------------------------------------------------------- cLight2DPoint* cWorld2D::CreateLightPoint(tString asName) { if(mpMapLights==NULL)return NULL; cLight2DPoint* pLight = hplNew( cLight2DPoint, (asName) ); mpMapLights->AddEntity(pLight); //Add the light to the base node awell... return pLight; } //----------------------------------------------------------------------- void cWorld2D::DestroyLight(iLight2D* apLight) { if(mpMapLights==NULL)return; mpMapLights->RemoveEntity(apLight); hplDelete(apLight); } //----------------------------------------------------------------------- cGridMap2D* cWorld2D::GetGridMapLights() { return mpMapLights; } //----------------------------------------------------------------------- iLight2D* cWorld2D::GetLight(const tString& asName) { tGrid2DObjectMap* pGridMap = mpMapLights->GetAllMap(); tGrid2DObjectMapIt it = pGridMap->begin(); for(;it!=pGridMap->end();it++) { cGrid2DObject* pObj = it->second; if(pObj->GetEntity()->GetName() == asName) { return static_cast<iLight2D*>(pObj->GetEntity()); } } return NULL; } //----------------------------------------------------------------------- cSoundSource* cWorld2D::CreateSoundSource(const tString& asName,const tString& asSoundName, bool abVolatile) { cSoundSource* pSoundSource = hplNew( cSoundSource, (asName,asSoundName,mpSound,abVolatile) ); mlstSoundSources.push_back(pSoundSource); return pSoundSource; } //----------------------------------------------------------------------- void cWorld2D::DestroySoundSource(cSoundSource* apSound) { mlstSoundSources.remove(apSound); hplDelete(apSound); } //----------------------------------------------------------------------- cImageEntity* cWorld2D::CreateImageEntity(tString asName,tString asDataName) { cImageEntity* pEntity = hplNew( cImageEntity, (asName, mpResources, mpGraphics) ); if(pEntity==NULL)return NULL; if(pEntity->LoadEntityData(asDataName)) { mpMapImageEntities->AddEntity(pEntity); } else { hplDelete(pEntity); } return pEntity; } //----------------------------------------------------------------------- void cWorld2D::DestroyImageEntity(cImageEntity* apEntity) { if(mpMapImageEntities==NULL)return; mpMapImageEntities->RemoveEntity(apEntity); hplDelete(apEntity); } //----------------------------------------------------------------------- cImageEntity* cWorld2D::GetImageEntity(const tString& asName) { tGrid2DObjectMap* pGridMap = mpMapImageEntities->GetAllMap(); tGrid2DObjectMapIt it = pGridMap->begin(); for(;it!=pGridMap->end();it++) { cGrid2DObject* pObj = it->second; if(pObj->GetEntity()->GetName() == asName) { return static_cast<cImageEntity*>(pObj->GetEntity()); } } return NULL; } //----------------------------------------------------------------------- iParticleSystem2D* cWorld2D::CreateParticleSystem(const tString& asName, const cVector3f& avSize) { /*iParticleSystem2D* pPS = mpResources->GetParticleManager()->CreatePS2D(asName, avSize); if(pPS == NULL){ Error("Couldn't create particle system '%s'\n",asName.c_str()); } mpMapParticles->AddEntity(pPS); return pPS;*/ return NULL; } //----------------------------------------------------------------------- void cWorld2D::DestroyParticleSystem(iParticleSystem2D* apPS) { /*if(apPS==NULL)return; mpMapParticles->RemoveEntity(apPS); hplDelete(apPS);*/ } //----------------------------------------------------------------------- cBody2D* cWorld2D::CreateBody2D(const tString& asName,cMesh2D *apMesh, cVector2f avSize) { cBody2D* pBody = hplNew( cBody2D, (asName,apMesh, avSize,mpCollider,mlBodyIDCount++) ); mpMapBodies->AddEntity(pBody); return pBody; } //----------------------------------------------------------------------- cArea2D* cWorld2D::GetArea(const tString& asName,const tString& asType) { tGrid2DObjectMap *GridMap = mpMapAreas->GetAllMap(); tGrid2DObjectMapIt it = GridMap->begin(); while(it != GridMap->end()) { cArea2D *pArea = static_cast<cArea2D *>( it->second->GetEntity() ); if(asName == "" || pArea->GetName() == asName) { if(asType == "" || pArea->GetType() == asType) { return pArea; } } it++; } return NULL; } //----------------------------------------------------------------------- bool cWorld2D::CreateFromFile(tString asFile) { //Load the document asFile = cString::SetFileExt(asFile,"hpl"); tString sPath = mpResources->GetFileSearcher()->GetFilePath(asFile); if(sPath==""){ FatalError("Couldn't find map '%s'!\n",asFile.c_str()); return false; } TiXmlDocument *pDoc = hplNew(TiXmlDocument, (sPath.c_str()) ); if(!pDoc->LoadFile()){ FatalError("Couldn't load map '%s'!\n",asFile.c_str()); return false; } //Load the script asFile = cString::SetFileExt(asFile,"hps"); mpScript = mpResources->GetScriptManager()->CreateScript(asFile); if(mpScript==NULL){ Error("Couldn't load script '%s'\n",asFile.c_str()); } TiXmlElement *pHplMapElem = pDoc->RootElement(); cVector2l vMapSize; msMapName = pHplMapElem->Attribute("Name"); vMapSize.x = cString::ToInt(pHplMapElem->Attribute("Width"),0); vMapSize.y = cString::ToInt(pHplMapElem->Attribute("Height"),0); float fTileSize = (float) cString::ToInt(pHplMapElem->Attribute("TileSize"),0); mfLightZ = cString::ToFloat(pHplMapElem->Attribute("LightZ"),0); mAmbientColor.r = cString::ToFloat(pHplMapElem->Attribute("AmbColR"),0)/255.0f; mAmbientColor.g = cString::ToFloat(pHplMapElem->Attribute("AmbColG"),0)/255.0f; mAmbientColor.b = cString::ToFloat(pHplMapElem->Attribute("AmbColB"),0)/255.0f; mAmbientColor.a = 0; //Log("Amb: %f : %f : %f : %f\n",mAmbientColor.r,mAmbientColor.g,mAmbientColor.b,mAmbientColor.a); mpGraphics->GetRenderer2D()->SetAmbientLight(mAmbientColor); mpGraphics->GetRenderer2D()->SetShadowZ(mfLightZ); //Set up data for objects. cVector2l vWorldSize = vMapSize*(int)fTileSize; mvWorldSize = cVector2f((float) vWorldSize.x,(float) vWorldSize.y ); mpMapLights = hplNew( cGridMap2D, (vWorldSize,cVector2l(200,200),cVector2l(5,5)) ); mpMapImageEntities = hplNew( cGridMap2D, (vWorldSize,cVector2l(150,150),cVector2l(5,5)) ); mpMapBodies = hplNew( cGridMap2D,(vWorldSize,cVector2l(150,150),cVector2l(5,5)) ); mpMapParticles = hplNew( cGridMap2D,(vWorldSize,cVector2l(300,300),cVector2l(3,3)) ); mpMapAreas = hplNew(cGridMap2D,(vWorldSize,cVector2l(300,300),cVector2l(3,3)) ); TiXmlElement* pHplMapChildElem = pHplMapElem->FirstChildElement(); while(pHplMapChildElem) { tString sChildName = pHplMapChildElem->Value(); ///////////////// /// LIGHTS ////// ///////////////// if(sChildName == "Lights") { TiXmlElement* pLightChildElem = pHplMapChildElem->FirstChildElement(); while(pLightChildElem) { cVector3f vPos; cColor Col(0,1); cLight2DPoint *pLight = CreateLightPoint(pLightChildElem->Attribute("Name")); vPos.x = cString::ToFloat(pLightChildElem->Attribute("X"),0); vPos.y = cString::ToFloat(pLightChildElem->Attribute("Y"),0); vPos.z = cString::ToFloat(pLightChildElem->Attribute("Z"),0); pLight->SetPosition(vPos); Col.r = cString::ToFloat(pLightChildElem->Attribute("ColR"),0)/255.0f; Col.g = cString::ToFloat(pLightChildElem->Attribute("ColG"),0)/255.0f; Col.b = cString::ToFloat(pLightChildElem->Attribute("ColB"),0)/255.0f; Col.a = cString::ToFloat(pLightChildElem->Attribute("Specular"),1); pLight->SetDiffuseColor(Col); pLight->SetFarAttenuation(cString::ToFloat(pLightChildElem->Attribute("Radius"),0)); pLight->SetActive(cString::ToBool(pLightChildElem->Attribute("Active"),true)); /*LOad some more stuff*/ pLight->SetAffectMaterial(cString::ToBool(pLightChildElem->Attribute("AffectMaterial"),true)); pLight->SetCastShadows(cString::ToBool(pLightChildElem->Attribute("CastShadows"),true)); pLightChildElem = pLightChildElem->NextSiblingElement(); } } //////////////////////// /// ENTITIES /////////// //////////////////////// else if(sChildName == "Entities") { TiXmlElement* pEntityElem = pHplMapChildElem->FirstChildElement(); while(pEntityElem) { tString sRenderType = cString::ToString(pEntityElem->Attribute("RenderType"),"Image"); if(sRenderType == "Image") { cImageEntity* pEntity = hplNew( cImageEntity,(cString::ToString( pEntityElem->Attribute("Name"),"Image"), mpResources, mpGraphics) ); //The the main data cVector3f vPos; vPos.x = cString::ToFloat(pEntityElem->Attribute("X"),0); vPos.y = cString::ToFloat(pEntityElem->Attribute("Y"),0); vPos.z = cString::ToFloat(pEntityElem->Attribute("Z"),0); pEntity->SetPosition(vPos); pEntity->SetActive(cString::ToBool(pEntityElem->Attribute("Active"),true)); if(pEntity->LoadData(pEntityElem)) { mpMapImageEntities->AddEntity(pEntity); iEntity2DLoader* pLoader = mpResources->GetEntity2DLoader( pEntity->GetEntityData()->GetType()); if(pLoader) { pLoader->Load(pEntity); } else { /*Maybe delete entity if no type found? */ } } else { hplDelete(pEntity); Error("Couldn't load data for entity '%s'!\n",pEntity->GetName().c_str()); } } else { FatalError("No other Render mode for entity exist!!"); } pEntityElem = pEntityElem->NextSiblingElement(); } } ///////////////////////////// /// SOUND SOURCES /////////// ///////////////////////////// else if(sChildName == "SoundSources") { TiXmlElement* pSoundElem = pHplMapChildElem->FirstChildElement(); while(pSoundElem) { cSoundSource *pSound = hplNew( cSoundSource,( cString::ToString(pSoundElem->Attribute("Name"),""), cString::ToString(pSoundElem->Attribute("SoundName"),""), mpSound,false)); pSound->LoadData(pSoundElem); mlstSoundSources.push_back(pSound); pSoundElem = pSoundElem->NextSiblingElement(); } } ///////////////////////////// /// PARTICLE SYSTEMS /////////// ///////////////////////////// /*else if(sChildName == "ParticleSystems") { TiXmlElement* pPartElem = pHplMapChildElem->FirstChildElement(); while(pPartElem) { iParticleSystem2D* pPS; tString sName = cString::ToString(pPartElem->Attribute("Name"),""); tString sPartName = cString::ToString(pPartElem->Attribute("PartName"),""); cVector3f vSize; cVector3f vPos; vSize.x = cString::ToFloat(pPartElem->Attribute("SizeX"),0); vSize.y = cString::ToFloat(pPartElem->Attribute("SizeY"),0); vSize.z = cString::ToFloat(pPartElem->Attribute("SizeZ"),0); vPos.x = cString::ToFloat(pPartElem->Attribute("X"),0); vPos.y = cString::ToFloat(pPartElem->Attribute("Y"),0); vPos.z = cString::ToFloat(pPartElem->Attribute("Z"),0); pPS = mpResources->GetParticleManager()->CreatePS2D(sPartName,vSize); if(pPS==NULL){ Error("Couldn't load particle system '%s'!\n",sPartName.c_str()); } else { pPS->SetName(sName); pPS->SetPosition(vPos); mpMapParticles->AddEntity(pPS); } pPartElem = pPartElem->NextSiblingElement(); } }*/ ///////////////////////////// /// AREAS /////////////////// ///////////////////////////// else if(sChildName == "Areas") { TiXmlElement* pAreaElem = pHplMapChildElem->FirstChildElement(); while(pAreaElem) { cArea2D* pArea; tString sName = cString::ToString(pAreaElem->Attribute("Name"),""); tString sAreaType = cString::ToString(pAreaElem->Attribute("AreaType"),""); cVector3f vPos; vPos.x = cString::ToFloat(pAreaElem->Attribute("X"),0); vPos.y = cString::ToFloat(pAreaElem->Attribute("Y"),0); vPos.z = cString::ToFloat(pAreaElem->Attribute("Z"),0); pArea = hplNew( cArea2D, (sName, sAreaType,mpCollider) ); pArea->LoadData(pAreaElem); pArea->SetName(sName); pArea->SetPosition(vPos); if(pArea->GetType() != "Script") { iArea2DLoader *pAreaLoader = mpResources->GetArea2DLoader(pArea->GetType()); if(pAreaLoader) { pAreaLoader->Load(pArea); } } mpMapAreas->AddEntity(pArea); pAreaElem = pAreaElem->NextSiblingElement(); } } ///////////////// /// TILEMAP ///// ///////////////// else if(sChildName == "TileMap") { mpTileMap = hplNew( cTileMap, (vMapSize,fTileSize,mpGraphics, mpResources) ); int lShadowLayer = cString::ToInt(pHplMapChildElem->Attribute("ShadowLayer"),0); TiXmlElement* pTileMapChildElem = pHplMapChildElem->FirstChildElement(); while(pTileMapChildElem) { tString sTileMapChildName = pTileMapChildElem->Value(); //Log("Tilemap: %s\n",sTileMapChildName.c_str()); //////////////////////// /// TILE SETS ////////// //////////////////////// if(sTileMapChildName=="TileSets") { TiXmlElement* pTileSetChildElem = pTileMapChildElem->FirstChildElement(); while(pTileSetChildElem) { tString sName = pTileSetChildElem->Attribute("Name"); cTileSet *pTileSet = mpResources->GetTileSetManager()->CreateTileSet(sName); mpTileMap->AddTileSet(pTileSet); pTileSetChildElem = pTileSetChildElem->NextSiblingElement(); } } //////////////////////// /// TILE LAYERS //////// /////////////////////// else if(sTileMapChildName=="Layers") { //Log("Layers\n"); TiXmlElement* pLayerChildElem = pTileMapChildElem->FirstChildElement(); while(pLayerChildElem) { //Log("Layer Children\n"); if(pLayerChildElem->Attribute("Width")==NULL)FatalError("Can't Load Width\n"); int lW = cString::ToInt(pLayerChildElem->Attribute("Width"),0); if(pLayerChildElem->Attribute("Height")==NULL)FatalError("Can't Load Height\n"); int lH = cString::ToInt(pLayerChildElem->Attribute("Height"),0); bool bCollide = cString::ToBool(pLayerChildElem->Attribute("Collide"),true); bool bLit = cString::ToBool(pLayerChildElem->Attribute("Lit"),true); float fZ = cString::ToFloat(pLayerChildElem->Attribute("Z"),0); cTileLayer *pTileLayer = hplNew( cTileLayer, (lW,lH, bCollide,bLit,eTileLayerType_Normal) ); pTileLayer->SetZ(fZ); mpTileMap->AddTileLayerFront(pTileLayer); //// THE TILES //////// TiXmlElement* pTileRowElem = pLayerChildElem->FirstChildElement(); int lRowCount=0; while(pTileRowElem) { //Log("Tile Row: "); int lColCount=0; tString sData = pTileRowElem->Attribute("Data"); int lDataCount =0; while(lDataCount<(int)sData.length()) { cTile* pTile = hplNew( cTile,(NULL,eTileRotation_0, cVector3f((float)lColCount*fTileSize,(float)lRowCount*fTileSize,fZ), cVector2f(fTileSize,fTileSize),NULL) ); lDataCount = LoadTileData(pTile, &sData, lDataCount); if(pTile->GetTileData()){ //Create the collision mesh if(pTileLayer->HasCollision()) { cCollisionMesh2D *pCollMesh=NULL; cTileDataNormal* pTData; pTData = static_cast<cTileDataNormal*>(pTile->GetTileData()); if(pTData->GetCollideMesh()) { pCollMesh = pTData->GetCollideMesh()->CreateCollisonMesh( cVector2f(pTile->GetPosition().x, pTile->GetPosition().y), cVector2f(2), pTile->GetAngle()); } pTile->SetCollisionMesh(pCollMesh); } //Add tile to the layer pTileLayer->SetTile(lColCount, lRowCount,pTile); } else { hplDelete(pTile); } lColCount++; } //Log("\n"); lRowCount++; pTileRowElem = pTileRowElem->NextSiblingElement(); } pLayerChildElem = pLayerChildElem->NextSiblingElement(); } } pTileMapChildElem = pTileMapChildElem->NextSiblingElement(); } //Set the inverse shadow layer. mpTileMap->SetShadowLayer(mpTileMap->GetTileLayerNum()-lShadowLayer-1); } pHplMapChildElem = pHplMapChildElem->NextSiblingElement(); } hplDelete(pDoc); return true; } //----------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////// // PRIVATE METHODS ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- void cWorld2D::UpdateSoundSources() { tSoundSourceListIt it= mlstSoundSources.begin(); while(it != mlstSoundSources.end()) { (*it)->UpdateLogic(0); if((*it)->IsDead()) { it = mlstSoundSources.erase(it); } else { it++; } } } //----------------------------------------------------------------------- void cWorld2D::UpdateParticles() { /*tGrid2DObjectMapIt it = mpMapParticles->GetAllMap()->begin(); while(it != mpMapParticles->GetAllMap()->end()) { iParticleSystem2D *pEntity = static_cast<iParticleSystem2D*>(it->second->GetEntity()); pEntity->UpdateLogic(0); it++; //Check if the system is alive, else destroy if(pEntity->IsDead()){ DestroyParticleSystem(pEntity); } }*/ } //----------------------------------------------------------------------- void cWorld2D::RenderParticles(cCamera2D* apCamera) { /*cRect2f ClipRect; apCamera->GetClipRect(ClipRect); iGridMap2DIt* pEntityIt = mpMapParticles->GetRectIterator(ClipRect); while(pEntityIt->HasNext()) { iParticleSystem2D* pEntity = static_cast<iParticleSystem2D*>(pEntityIt->Next()); pEntity->Render(); } hplDelete(pEntityIt);*/ } //----------------------------------------------------------------------- void cWorld2D::UpdateEntities() { tGrid2DObjectMapIt it = mpMapImageEntities->GetAllMap()->begin(); while(it != mpMapImageEntities->GetAllMap()->end()) { iEntity2D *pEntity = static_cast<cImageEntity*>(it->second->GetEntity()); if(pEntity->IsActive()) pEntity->UpdateLogic(0); it++; } } //----------------------------------------------------------------------- void cWorld2D::UpdateBodies() { tGrid2DObjectMapIt it = mpMapBodies->GetAllMap()->begin(); while(it != mpMapBodies->GetAllMap()->end()) { cBody2D *pBody = static_cast<cBody2D*>(it->second->GetEntity()); if(pBody->IsActive()) pBody->UpdateLogic(0); it++; } } //----------------------------------------------------------------------- void cWorld2D::UpdateLights() { tGrid2DObjectMapIt it = mpMapLights->GetAllMap()->begin(); while(it != mpMapLights->GetAllMap()->end()) { iLight2D *pLight = static_cast<iLight2D*>(it->second->GetEntity()); if(pLight->IsActive()) pLight->UpdateLogic(0); it++; } } //----------------------------------------------------------------------- void cWorld2D::RenderImagesEntities(cCamera2D* apCamera) { cRect2f ClipRect; apCamera->GetClipRect(ClipRect); iGridMap2DIt* pEntityIt = mpMapImageEntities->GetRectIterator(ClipRect); while(pEntityIt->HasNext()) { cImageEntity* pEntity = static_cast<cImageEntity*>(pEntityIt->Next()); if(pEntity->IsActive()) { pEntity->Render(); } } hplDelete(pEntityIt); } //----------------------------------------------------------------------- int cWorld2D::LoadTileData(cTile *apTile,tString* asData,int alStart) { int lCount = alStart; int lStart = lCount; int lValType =0; int lSet; int lNum; while(true) { if(asData->c_str()[lCount] == ':' || asData->c_str()[lCount]=='|') { if(lStart != lCount) { tString sVal = asData->substr(lStart, lCount - lStart); int lVal = cString::ToInt(sVal.c_str(),-1); cTileSet *pSet=NULL; cTileDataNormal *pData = NULL; switch(lValType) { case 0: lSet = lVal; break; case 1: lNum = lVal; if(lSet<0)break; if(lNum<0)break; pSet = mpTileMap->GetTileSet(lSet); if(pSet==NULL)FatalError("Error getting tileset%d\n",lSet); pData = static_cast<cTileDataNormal*>(pSet->Get(lNum)); apTile->SetTileData(pData); break; case 2: apTile->SetAngle((eTileRotation)lVal);break; case 3: apTile->SetFlags(eTileFlag_Breakable); } lValType++; } if(asData->c_str()[lCount]=='|'){ /*if(apTile->GetTileData()) Log("%d,%d,%d|",lSet,lNum,apTile->GetAngle()); else Log("N|");*/ break; } lStart = lCount+1; } lCount++; } return lCount+1; } //----------------------------------------------------------------------- }
0
0.963634
1
0.963634
game-dev
MEDIA
0.612794
game-dev,graphics-rendering
0.982421
1
0.982421
Sol-Client/client
8,003
src/main/java/io/github/solclient/client/mod/impl/hud/crosshair/CrosshairEditorComponent.java
/* * Sol Client - an open source Minecraft client * Copyright (C) 2021-2023 TheKodeToad and Contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package io.github.solclient.client.mod.impl.hud.crosshair; import java.util.*; import org.apache.logging.log4j.*; import org.lwjgl.input.Keyboard; import org.lwjgl.nanovg.NanoVG; import com.replaymod.lib.de.johni0702.minecraft.gui.container.GuiScreen; import com.replaymod.recording.gui.GuiSavingReplay; import io.github.solclient.client.ui.Theme; import io.github.solclient.client.ui.component.*; import io.github.solclient.client.ui.component.controller.AlignedBoundsController; import io.github.solclient.client.ui.component.impl.*; import io.github.solclient.client.util.*; import io.github.solclient.client.util.cursors.SystemCursors; import io.github.solclient.client.util.data.*; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.util.Window; public final class CrosshairEditorComponent extends Component { private static final Logger LOGGER = LogManager.getLogger(); private static final int SCALE = 11; private final PixelMatrix pixels; private int historyCursor; private List<BitSet> history = new ArrayList<>(); public CrosshairEditorComponent(CrosshairOption option) { pixels = option.getValue(); add(new PixelMatrixComponent(), new AlignedBoundsController(Alignment.CENTRE, Alignment.START)); add(new ButtonComponent("", Theme.button(), Theme.fg()).withIcon("copy").width(20).onClick((info, button) -> { if (button != 0) return false; MinecraftUtils.playClickSound(true); copy(); return true; }), new AlignedBoundsController(Alignment.CENTRE, Alignment.END, (component, defaultBounds) -> defaultBounds.offset(-25, 0))); add(new ButtonComponent("", Theme.button(), Theme.fg()).withIcon("paste").width(20).onClick((info, button) -> { if (button != 0) return false; MinecraftUtils.playClickSound(true); paste(); return true; }), new AlignedBoundsController(Alignment.CENTRE, Alignment.END, (component, defaultBounds) -> defaultBounds.offset(0, 0))); add(new ButtonComponent("", Theme.button(), Theme.fg()).withIcon("clear").width(20).onClick((info, button) -> { if (button != 0) return false; MinecraftUtils.playClickSound(true); pixels.clear(); pushToFront(); saveToHistory(); return true; }), new AlignedBoundsController(Alignment.CENTRE, Alignment.END, (component, defaultBounds) -> defaultBounds.offset(25, 0))); saveToHistory(); } private void copy() { try { Screen.setClipboard(LCCH.stringify(pixels)); pushToFront(); saveToHistory(); } catch (Throwable error) { LOGGER.error("Failed to convert to LCCH", error); } } private void paste() { try { LCCH.parse(Screen.getClipboard(), pixels); pushToFront(); saveToHistory(); } catch (Throwable error) { LOGGER.error("Failed to load from LCCH", error); } } private void navigateHistory(boolean forwards) { if (forwards) historyCursor--; else historyCursor++; if (historyCursor < 0) historyCursor = 0; if (historyCursor >= history.size()) historyCursor = history.size() - 1; pixels.setPixels((BitSet) history.get(history.size() - 1 - historyCursor).clone()); } private void saveToHistory() { if (history.isEmpty() || !history.get(history.size() - 1).equals(pixels.getPixels())) history.add((BitSet) pixels.getPixels().clone()); } private void pushToFront() { if (historyCursor != 0) { history.subList(history.size() - historyCursor, history.size()).clear(); historyCursor = 0; } } private final class PixelMatrixComponent extends Component { // prevent instant input private boolean leftMouseDown; private boolean rightMouseDown; private int lastGridX = -1, lastGridY = -1; @Override public void render(ComponentRenderInfo info) { if (isHovered()) setCursor(SystemCursors.CROSSHAIR); for (int y = 0; y < pixels.getHeight(); y++) { for (int x = 0; x < pixels.getWidth(); x++) { Colour colour; if (pixels.get(x, y)) colour = Colour.WHITE; else { boolean square = x % 2 == 0; if (y % 2 == 0) square = !square; colour = square ? Theme.getCurrent().transparent1 : Theme.getCurrent().transparent2; } NanoVG.nvgBeginPath(nvg); NanoVG.nvgFillColor(nvg, colour.nvg()); NanoVG.nvgRect(nvg, x * SCALE, y * SCALE, SCALE, SCALE); NanoVG.nvgFill(nvg); if (info.relativeMouseX() >= x * SCALE && info.relativeMouseX() < x * SCALE + SCALE && info.relativeMouseY() >= y * SCALE && info.relativeMouseY() < y * SCALE + SCALE) { if (x != lastGridX || y != lastGridY) { if (leftMouseDown) pixels.set(x, y); else if (rightMouseDown) pixels.clear(x, y); } NanoVG.nvgBeginPath(nvg); // single pixel float strokeWidth = 1F / new Window(mc).getScaleFactor(); NanoVG.nvgStrokeColor(nvg, pixels.get(x, y) ? Colour.BLACK.nvg() : Colour.WHITE.nvg()); NanoVG.nvgStrokeWidth(nvg, strokeWidth); NanoVG.nvgRect(nvg, x * SCALE + strokeWidth / 2, y * SCALE + strokeWidth / 2, SCALE - strokeWidth, SCALE - strokeWidth); NanoVG.nvgStroke(nvg); lastGridX = x; lastGridY = y; } // draw centre marker if (x == pixels.getWidth() / 2 && y == pixels.getHeight() / 2) { NanoVG.nvgBeginPath(nvg); NanoVG.nvgFillColor(nvg, pixels.get(x, y) ? Colour.BLACK.nvg() : Colour.WHITE.nvg()); NanoVG.nvgCircle(nvg, x * SCALE + SCALE / 2F, y * SCALE + SCALE / 2F, 2); NanoVG.nvgFill(nvg); } } } super.render(info); } @Override public boolean mouseClicked(ComponentRenderInfo info, int button) { lastGridX = -1; lastGridY = -1; pushToFront(); if (button == 0) leftMouseDown = true; else if (button == 1) rightMouseDown = true; return true; } @Override public boolean mouseReleasedAnywhere(ComponentRenderInfo info, int button, boolean inside) { if (button == 0) leftMouseDown = false; else if (button == 1) rightMouseDown = false; else return false; // you have some friends. down there v (they // have the same hobbies and interests, oh // they're also clones. that's cool!) if (leftMouseDown || rightMouseDown) return false; saveToHistory(); return false; } @Override public boolean keyPressed(ComponentRenderInfo info, int keyCode, char character) { if (keyCode == Keyboard.KEY_DELETE) { pixels.clear(); pushToFront(); saveToHistory(); return true; } else if (Screen.hasControlDown()) { if (keyCode == Keyboard.KEY_C) { copy(); return true; } else if (keyCode == Keyboard.KEY_V) { paste(); return true; } else if (history != null && history.size() > 1) { if (keyCode == Keyboard.KEY_Z) { navigateHistory(Screen.hasShiftDown()); return true; } else if (keyCode == Keyboard.KEY_Y) { navigateHistory(true); return true; } } } return super.keyPressed(info, keyCode, character); } @Override protected Rectangle getDefaultBounds() { return Rectangle.ofDimensions(pixels.getWidth() * SCALE, pixels.getHeight() * SCALE); } } @Override protected Rectangle getDefaultBounds() { return Rectangle.ofDimensions(230, 190); } }
0
0.957511
1
0.957511
game-dev
MEDIA
0.768692
game-dev,desktop-app
0.981725
1
0.981725
neoforged/NeoForge
2,255
src/main/java/net/neoforged/neoforge/registries/datamaps/DataMapValueRemover.java
/* * Copyright (c) NeoForged and contributors * SPDX-License-Identifier: LGPL-2.1-only */ package net.neoforged.neoforge.registries.datamaps; import com.mojang.datafixers.util.Either; import com.mojang.serialization.Codec; import java.util.Optional; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceKey; import net.minecraft.tags.TagKey; /** * An interface used to remove values from registry data maps. This allows "decomposing" the data * and removing only a specific part of it (like a specific key in the case of {@linkplain java.util.Map map-based} data). * * @param <T> the data type * @param <R> the type of the registry this remover is for * @apiNote This is only useful for {@link AdvancedDataMapType}. */ @FunctionalInterface public interface DataMapValueRemover<R, T> { /** * Remove the entry specified in this remover from the {@code value}. * * @param value the data to remove. Do <b>NOT</b> mutate this object. You should return copies instead, * if you need to * @param registry the registry * @param source the source of the data * @param object the object to remove the data from * @return the remainder. If an {@link Optional#empty() empty optional}, the value will be removed * completely. Otherwise, this method returns the new value of the attached data. */ Optional<T> remove(T value, Registry<R> registry, Either<TagKey<R>, ResourceKey<R>> source, R object); /** * A remover that completely removes the value. * * @param <T> the type of the data * @param <R> the registry type */ class Default<T, R> implements DataMapValueRemover<R, T> { public static final Default<?, ?> INSTANCE = new Default<>(); public static <T, R> Default<T, R> defaultRemover() { return (Default<T, R>) INSTANCE; } public static <T, R> Codec<Default<T, R>> codec() { return Codec.unit(defaultRemover()); } private Default() {} @Override public Optional<T> remove(T value, Registry<R> registry, Either<TagKey<R>, ResourceKey<R>> source, R object) { return Optional.empty(); } } }
0
0.712456
1
0.712456
game-dev
MEDIA
0.363412
game-dev
0.5214
1
0.5214
localcc/PalworldModdingKit
1,119
Source/Pal/Public/PalMapObjectTreasureBoxSalvageParameterComponent.h
#pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "Templates/SubclassOf.h" #include "PalMapObjectTreasureBoxSalvageParameterComponent.generated.h" class UPalUserWidgetOverlayUI; UCLASS(Blueprintable, ClassGroup=Custom, meta=(BlueprintSpawnableComponent)) class PAL_API UPalMapObjectTreasureBoxSalvageParameterComponent : public UActorComponent { GENERATED_BODY() public: UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float GaugeStartPercent; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float GaugeEndPercent; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float GaugeRangePercent; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float CursorPercentSpeed; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TSubclassOf<UPalUserWidgetOverlayUI> SalvageGameUIClass; UPalMapObjectTreasureBoxSalvageParameterComponent(const FObjectInitializer& ObjectInitializer); };
0
0.891513
1
0.891513
game-dev
MEDIA
0.844183
game-dev
0.58843
1
0.58843
JackHopkins/factorio-learning-environment
1,396
tests/actions/test_inspect_inventory.py
import pytest from fle.env.entities import Position from fle.env.game_types import Prototype @pytest.fixture() def game(configure_game): return configure_game( inventory={ "coal": 50, "iron-chest": 1, "iron-plate": 5, }, merge=True, all_technologies_researched=False, ) def test_inspect_inventory(game): assert game.inspect_inventory().get(Prototype.Coal, 0) == 50 inventory = game.inspect_inventory() coal_count = inventory[Prototype.Coal] assert coal_count != 0 chest = game.place_entity(Prototype.IronChest, position=Position(x=0, y=0)) chest = game.insert_item(Prototype.Coal, chest, quantity=5) chest_inventory = game.inspect_inventory(entity=chest) chest_coal_count = chest_inventory[Prototype.Coal] assert chest_coal_count == 5 def test_inspect_assembling_machine_inventory(game): machine = game.place_entity( Prototype.AssemblingMachine1, position=Position(x=0, y=0) ) game.set_entity_recipe(machine, Prototype.IronGearWheel) game.insert_item(Prototype.IronPlate, machine, quantity=5) chest_inventory = game.inspect_inventory(entity=machine) iron_count = chest_inventory[Prototype.IronPlate] assert iron_count == 5 def test_print_inventory(game): inventory = game.inspect_inventory() game.print(inventory) assert True
0
0.707637
1
0.707637
game-dev
MEDIA
0.978621
game-dev,testing-qa
0.552719
1
0.552719
daleao/sdv
1,437
Professions/Framework/Integrations/SveIntegration.cs
namespace DaLion.Professions.Framework.Integrations; #region using directives using DaLion.Professions.Framework.Events.Player.Warped; using DaLion.Shared.Attributes; using DaLion.Shared.Extensions.SMAPI; using DaLion.Shared.Integrations; #endregion using directives /// <summary>Initializes a new instance of the <see cref="SveIntegration"/> class.</summary> [ModRequirement("FlashShifter.StardewValleyExpandedCP")] [UsedImplicitly] internal sealed class SveIntegration() : ModIntegration<SveIntegration>(ModHelper.ModRegistry) { /// <summary>Gets a value indicating whether the <c>DisableGaldoranTheme</c> config setting is enabled.</summary> internal bool DisabeGaldoranTheme => this.IsLoaded && (ModHelper.ReadContentPackConfig("FlashShifter.StardewValleyExpandedCP")?.Value<bool?>("DisableGaldoranTheme") ?? false); /// <summary>Gets a value indicating whether the <c>UseGaldoranThemeAllTimes</c> config setting is enabled.</summary> internal bool UseGaldoranThemeAllTimes => this.IsLoaded && (ModHelper.ReadContentPackConfig("FlashShifter.StardewValleyExpandedCP")?.Value<bool?>("UseGaldoranThemeAllTimes") ?? false); protected override bool RegisterImpl() { if (!this.IsLoaded) { return false; } EventManager.Enable<SveWarpedEvent>(); Log.D("Registered the Stardew Valley Expanded integration."); return true; } }
0
0.895927
1
0.895927
game-dev
MEDIA
0.815471
game-dev
0.840777
1
0.840777
shxzu/Simp
5,813
src/main/java/net/minecraft/item/ItemBucket.java
package net.minecraft.item; import net.minecraft.block.Block; import net.minecraft.block.BlockLiquid; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.stats.StatList; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; public class ItemBucket extends Item { private final Block isFull; public ItemBucket(Block containedBlock) { this.maxStackSize = 1; this.isFull = containedBlock; this.setCreativeTab(CreativeTabs.tabMisc); } public ItemStack onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn) { boolean flag = this.isFull == Blocks.air; MovingObjectPosition movingobjectposition = this.getMovingObjectPositionFromPlayer(worldIn, playerIn, flag); if (movingobjectposition == null) { return itemStackIn; } else { if (movingobjectposition.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { BlockPos blockpos = movingobjectposition.getBlockPos(); if (!worldIn.isBlockModifiable(playerIn, blockpos)) { return itemStackIn; } if (flag) { if (!playerIn.canPlayerEdit(blockpos.offset(movingobjectposition.sideHit), movingobjectposition.sideHit, itemStackIn)) { return itemStackIn; } IBlockState iblockstate = worldIn.getBlockState(blockpos); Material material = iblockstate.getBlock().getMaterial(); if (material == Material.water && iblockstate.getValue(BlockLiquid.LEVEL).intValue() == 0) { worldIn.setBlockToAir(blockpos); playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); return this.fillBucket(itemStackIn, playerIn, Items.water_bucket); } if (material == Material.lava && iblockstate.getValue(BlockLiquid.LEVEL).intValue() == 0) { worldIn.setBlockToAir(blockpos); playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); return this.fillBucket(itemStackIn, playerIn, Items.lava_bucket); } } else { if (this.isFull == Blocks.air) { return new ItemStack(Items.bucket); } BlockPos blockpos1 = blockpos.offset(movingobjectposition.sideHit); if (!playerIn.canPlayerEdit(blockpos1, movingobjectposition.sideHit, itemStackIn)) { return itemStackIn; } if (this.tryPlaceContainedLiquid(worldIn, blockpos1) && !playerIn.capabilities.isCreativeMode) { playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); return new ItemStack(Items.bucket); } } } return itemStackIn; } } private ItemStack fillBucket(ItemStack emptyBuckets, EntityPlayer player, Item fullBucket) { if (player.capabilities.isCreativeMode) { return emptyBuckets; } else if (--emptyBuckets.stackSize <= 0) { return new ItemStack(fullBucket); } else { if (!player.inventory.addItemStackToInventory(new ItemStack(fullBucket))) { player.dropPlayerItemWithRandomChoice(new ItemStack(fullBucket, 1, 0), false); } return emptyBuckets; } } public boolean tryPlaceContainedLiquid(World worldIn, BlockPos pos) { if (this.isFull == Blocks.air) { return false; } else { Material material = worldIn.getBlockState(pos).getBlock().getMaterial(); boolean flag = !material.isSolid(); if (!worldIn.isAirBlock(pos) && !flag) { return false; } else { if (worldIn.provider.doesWaterVaporize() && this.isFull == Blocks.flowing_water) { int i = pos.getX(); int j = pos.getY(); int k = pos.getZ(); worldIn.playSoundEffect((float)i + 0.5F, (float)j + 0.5F, (float)k + 0.5F, "random.fizz", 0.5F, 2.6F + (worldIn.rand.nextFloat() - worldIn.rand.nextFloat()) * 0.8F); for (int l = 0; l < 8; ++l) { worldIn.spawnParticle(EnumParticleTypes.SMOKE_LARGE, (double)i + Math.random(), (double)j + Math.random(), (double)k + Math.random(), 0.0D, 0.0D, 0.0D); } } else { if (!worldIn.isRemote && flag && !material.isLiquid()) { worldIn.destroyBlock(pos, true); } worldIn.setBlockState(pos, this.isFull.getDefaultState(), 3); } return true; } } } }
0
0.845007
1
0.845007
game-dev
MEDIA
0.998706
game-dev
0.982827
1
0.982827
mpirnat/dndme
1,677
dndme/commands/damage_combatant.py
from dndme.commands import Command from dndme.commands.defeat_monster import DefeatMonster class DamageCombatant(Command): keywords = ["damage", "hurt", "hit"] help_text = """{keyword} {divider} Summary: Apply damage to one or more combatants. Usage: {keyword} <combatant1> [<combatant2> ...] <number> Examples: {keyword} Frodo 10 {keyword} Frodo Merry Pippin 10 {keyword} orc* 5 """ def get_suggestions(self, words): combat = self.game.combat names_already_chosen = words[1:] return sorted(set(combat.combatant_names) - set(names_already_chosen)) def do_command(self, *args): if len(args) < 2: print("Need a target and an amount of HP.") return try: amount = int(args[-1]) except ValueError: print("Need an amount of HP.") return combat = self.game.combat targets = combat.get_targets(args[:-1]) if not targets: print(f"No targets found from `{args[:-1]}`") return for target in targets: target.cur_hp -= amount print( f"Okay; damaged {target.name}. " f"Now: {target.cur_hp}/{target.max_hp}" ) self.game.changed = True if target.name in combat.monsters and target.cur_hp == 0: if ( self.session.prompt( f"{target.name} reduced to 0 HP--" "mark as defeated? [Y]: " ) or "y" ).lower() != "y": continue DefeatMonster.do_command(self, target.name)
0
0.694185
1
0.694185
game-dev
MEDIA
0.405378
game-dev
0.939843
1
0.939843
FlaxEngine/FlaxEngine
3,644
Source/Engine/Physics/Collisions.cs
// Copyright (c) Wojciech Figat. All rights reserved. using System; using System.Collections; using System.Collections.Generic; namespace FlaxEngine { /// <summary> /// Contains a collision information passed to the OnCollisionEnter/OnCollisionExit events. /// </summary> unsafe partial struct Collision : IEnumerable<ContactPoint> { private class ContactsEnumerator : IEnumerator<ContactPoint> { private Collision _c; private int _index; public ContactsEnumerator(ref Collision c) { _c = c; _index = 0; } public bool MoveNext() { if (_index == _c.ContactsCount - 1) return false; _index++; return true; } public void Reset() { _index = 0; } ContactPoint IEnumerator<ContactPoint>.Current { get { if (_index == _c.ContactsCount) throw new InvalidOperationException("Enumeration ended."); fixed (ContactPoint* ptr = &_c.Contacts0) return ptr[_index]; } } public object Current { get { if (_index == _c.ContactsCount) throw new InvalidOperationException("Enumeration ended."); fixed (ContactPoint* ptr = &_c.Contacts0) return ptr[_index]; } } public void Dispose() { _c = new Collision(); } } /// <summary> /// The contacts locations. /// </summary> /// <remarks> /// This property allocates an array of contact points. /// </remarks> public ContactPoint[] Contacts { get { var result = new ContactPoint[ContactsCount]; fixed (ContactPoint* ptr = &Contacts0) { for (int i = 0; i < ContactsCount; i++) result[i] = ptr[i]; } return result; } } /// <summary> /// The relative linear velocity of the two colliding objects. /// </summary> /// <remarks> /// Can be used to detect stronger collisions. /// </remarks> public Vector3 RelativeVelocity { get { Vector3.Subtract(ref ThisVelocity, ref OtherVelocity, out var result); return result; } } /// <summary> /// The first collider (this instance). It may be null if this actor is not the <see cref="Collider"/> (eg. <see cref="Terrain"/>). /// </summary> public Collider ThisCollider => ThisActor as Collider; /// <summary> /// The second collider (other instance). It may be null if this actor is not the <see cref="Collider"/> (eg. <see cref="Terrain"/>). /// </summary> public Collider OtherCollider => OtherActor as Collider; /// <inheritdoc /> IEnumerator<ContactPoint> IEnumerable<ContactPoint>.GetEnumerator() { return new ContactsEnumerator(ref this); } /// <inheritdoc /> IEnumerator IEnumerable.GetEnumerator() { return new ContactsEnumerator(ref this); } } }
0
0.887455
1
0.887455
game-dev
MEDIA
0.74159
game-dev
0.899167
1
0.899167
lzk228/space-axolotl-14
3,717
Content.Shared/Movement/Systems/SharedMoverController.Relay.cs
using Content.Shared.ActionBlocker; using Content.Shared.Movement.Components; namespace Content.Shared.Movement.Systems; public abstract partial class SharedMoverController { private void InitializeRelay() { SubscribeLocalEvent<RelayInputMoverComponent, ComponentShutdown>(OnRelayShutdown); SubscribeLocalEvent<MovementRelayTargetComponent, ComponentShutdown>(OnTargetRelayShutdown); SubscribeLocalEvent<MovementRelayTargetComponent, AfterAutoHandleStateEvent>(OnAfterRelayTargetState); SubscribeLocalEvent<RelayInputMoverComponent, AfterAutoHandleStateEvent>(OnAfterRelayState); } private void OnAfterRelayTargetState(Entity<MovementRelayTargetComponent> entity, ref AfterAutoHandleStateEvent args) { PhysicsSystem.UpdateIsPredicted(entity.Owner); } private void OnAfterRelayState(Entity<RelayInputMoverComponent> entity, ref AfterAutoHandleStateEvent args) { PhysicsSystem.UpdateIsPredicted(entity.Owner); } /// <summary> /// Sets the relay entity and marks the component as dirty. This only exists because people have previously /// forgotten to Dirty(), so fuck you, you have to use this method now. /// </summary> public void SetRelay(EntityUid uid, EntityUid relayEntity) { if (uid == relayEntity) { Log.Error($"An entity attempted to relay movement to itself. Entity:{ToPrettyString(uid)}"); return; } var component = EnsureComp<RelayInputMoverComponent>(uid); if (component.RelayEntity == relayEntity) return; if (TryComp(component.RelayEntity, out MovementRelayTargetComponent? oldTarget)) { oldTarget.Source = EntityUid.Invalid; RemComp(component.RelayEntity, oldTarget); PhysicsSystem.UpdateIsPredicted(component.RelayEntity); } var targetComp = EnsureComp<MovementRelayTargetComponent>(relayEntity); if (TryComp(targetComp.Source, out RelayInputMoverComponent? oldRelay)) { oldRelay.RelayEntity = EntityUid.Invalid; RemComp(targetComp.Source, oldRelay); PhysicsSystem.UpdateIsPredicted(targetComp.Source); } PhysicsSystem.UpdateIsPredicted(uid); PhysicsSystem.UpdateIsPredicted(relayEntity); component.RelayEntity = relayEntity; targetComp.Source = uid; Dirty(uid, component); Dirty(relayEntity, targetComp); _blocker.UpdateCanMove(uid); } private void OnRelayShutdown(Entity<RelayInputMoverComponent> entity, ref ComponentShutdown args) { PhysicsSystem.UpdateIsPredicted(entity.Owner); PhysicsSystem.UpdateIsPredicted(entity.Comp.RelayEntity); if (TryComp<InputMoverComponent>(entity.Comp.RelayEntity, out var inputMover)) SetMoveInput((entity.Comp.RelayEntity, inputMover), MoveButtons.None); if (Timing.ApplyingState) return; if (TryComp(entity.Comp.RelayEntity, out MovementRelayTargetComponent? target) && target.LifeStage <= ComponentLifeStage.Running) RemComp(entity.Comp.RelayEntity, target); _blocker.UpdateCanMove(entity.Owner); } private void OnTargetRelayShutdown(Entity<MovementRelayTargetComponent> entity, ref ComponentShutdown args) { PhysicsSystem.UpdateIsPredicted(entity.Owner); PhysicsSystem.UpdateIsPredicted(entity.Comp.Source); if (Timing.ApplyingState) return; if (TryComp(entity.Comp.Source, out RelayInputMoverComponent? relay) && relay.LifeStage <= ComponentLifeStage.Running) RemComp(entity.Comp.Source, relay); } }
0
0.960951
1
0.960951
game-dev
MEDIA
0.955575
game-dev
0.987641
1
0.987641
akarnokd/ThePlanetCrafterMods
2,773
FeatMultiplayer/MessageTypes/MessageTerraformState.cs
using SpaceCraft; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FeatMultiplayer.MessageTypes { internal class MessageTerraformState : MessageBase { internal float oxygen; internal float heat; internal float pressure; internal float plants; internal float insects; internal float animals; internal int tokens; internal int tokensAllTime; internal static bool TryParse(string str, out MessageTerraformState mts) { if (MessageHelper.TryParseMessage("TerraformState|", str, 9, out var parameters)) { try { mts = new MessageTerraformState(); mts.oxygen = float.Parse(parameters[1], CultureInfo.InvariantCulture); mts.heat = float.Parse(parameters[2], CultureInfo.InvariantCulture); mts.pressure = float.Parse(parameters[3], CultureInfo.InvariantCulture); mts.plants = float.Parse(parameters[4], CultureInfo.InvariantCulture); mts.insects = float.Parse(parameters[5], CultureInfo.InvariantCulture); mts.animals = float.Parse(parameters[6], CultureInfo.InvariantCulture); mts.tokens = int.Parse(parameters[7]); mts.tokensAllTime = int.Parse(parameters[8]); return true; } catch (Exception ex) { Plugin.LogError(ex); } } mts = null; return false; } public override string GetString() { return "TerraformState|" + oxygen.ToString(CultureInfo.InvariantCulture) + "|" + heat.ToString(CultureInfo.InvariantCulture) + "|" + pressure.ToString(CultureInfo.InvariantCulture) + "|" + plants.ToString(CultureInfo.InvariantCulture) + "|" + insects.ToString(CultureInfo.InvariantCulture) + "|" + animals.ToString(CultureInfo.InvariantCulture) + "|" + tokens + "|" + tokensAllTime + "\n"; } /// <summary> /// Returns the Terraformation Index derived from the components. /// </summary> /// <returns>the Terraformation Index derived from the components.</returns> public float GetTi() { return oxygen + heat + pressure + plants + insects + animals; } public float GetBiomass() { return plants + insects + animals; } } }
0
0.54326
1
0.54326
game-dev
MEDIA
0.743231
game-dev
0.504022
1
0.504022
thindil/steamsky
17,739
src/trades.nim
# Copyright 2023-2025 Bartek thindil Jasicki # # This file is part of Steam Sky. # # Steam Sky 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. # # Steam Sky 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 Steam Sky. If not, see <http://www.gnu.org/licenses/>. ## Provides code related to trading with NPC, in bases and ships like buying or ## selling items. import std/[math, strutils, tables] import contracts import bases, basescargo, basestypes, crewinventory, game, game2, items, maps, messages, ships, shipscargo, shipscrew, types, utils proc generateTraderCargo*(protoIndex: Positive) {.raises: [ KeyError], tags: [], contractual.} = ## Generate the list of items for trade. ## ## * protoIndex - the index of the ship's prototype from which the cargo will ## be generated require: protoShipsList.hasKey(key = protoIndex) body: var traderShip: ShipRecord = createShip(protoIndex = protoIndex, name = "", x = playerShip.skyX, y = playerShip.skyY, speed = fullStop) traderCargo = @[] for item in traderShip.cargo: traderCargo.add(y = BaseCargo(protoIndex: item.protoIndex, amount: item.amount, durability: defaultItemDurability, price: itemsList[item.protoIndex].price, quality: getQuality())) var cargoAmount: Natural = if traderShip.crew.len < 5: getRandom(min = 1, max = 3) elif traderShip.crew.len < 10: getRandom(min = 1, max = 5) else: getRandom(min = 1, max = 10) while cargoAmount > 0: var itemAmount: Positive = if traderShip.crew.len < 5: getRandom(min = 1, max = 100) elif traderShip.crew.len < 10: getRandom(min = 1, max = 500) else: getRandom(min = 1, max = 1000) itemIndex: Natural = getRandom(min = 1, max = itemsList.len) newItemIndex: Natural = 0 for i in 1..itemsList.len: itemIndex.dec if itemIndex == 0: newItemIndex = i break let quality: ObjectQuality = getQuality() cargoItemIndex: int = findItem(inventory = traderShip.cargo, protoIndex = newItemIndex, itemQuality = quality) if cargoItemIndex > -1: traderCargo[cargoItemIndex].amount += itemAmount traderShip.cargo[cargoItemIndex].amount += itemAmount else: if freeCargo(amount = 0 - (itemsList[newItemIndex].weight * itemAmount)) > -1: traderCargo.add(y = BaseCargo(protoIndex: newItemIndex, amount: itemAmount, durability: defaultItemDurability, price: itemsList[ newItemIndex].price, quality: quality)) traderShip.cargo.add(y = InventoryData(protoIndex: newItemIndex, amount: itemAmount, durability: defaultItemDurability, name: "", price: 0, quality: quality)) else: cargoAmount = 1 cargoAmount.dec proc sellItems*(itemIndex: Natural; amount: string) {.raises: [ NoTraderError, NoFreeCargoError, NoMoneyInBaseError, KeyError, ValueError, IOError, Exception], tags: [WriteIOEffect, RootEffect], contractual.} = ## Sell the selected item from the player's ship cargo to the trader ## ## * itemIndex - the index of the item in the player's ship cargo ## * amount - the amount of the item to sell require: itemIndex < playerShip.cargo.len body: let traderIndex: int = findMember(order = talk) if traderIndex == -1: raise newException(exceptn = NoTraderError, message = "") let baseIndex: ExtendedBasesRange = skyMap[playerShip.skyX][playerShip.skyY].baseIndex protoIndex: Natural = playerShip.cargo[itemIndex].protoIndex var baseItemIndex: int = -1 if baseIndex > 0: baseItemIndex = findBaseCargo(protoIndex = protoIndex, quality = playerShip.cargo[itemIndex].quality) else: for index, item in traderCargo: if item.protoIndex == protoIndex: baseItemIndex = index break var price: Natural = 0 if baseItemIndex == -1: price = getPrice(baseType = skyBases[baseIndex].baseType, itemIndex = protoIndex, quality = normal) else: price = if baseIndex > 0: skyBases[baseIndex].cargo[baseItemIndex].price else: traderCargo[baseItemIndex].price let eventIndex: int = skyMap[playerShip.skyX][playerShip.skyY].eventIndex if eventIndex > -1 and eventsList[eventIndex].eType == doublePrice and eventsList[eventIndex].itemIndex == protoIndex: price *= 2 let sellAmount: Positive = amount.parseInt var profit: Natural = price * sellAmount if playerShip.cargo[itemIndex].durability < 100: profit = (profit.float * (playerShip.cargo[itemIndex].durability.float / 100.0)).int countPrice(price = price, traderIndex = traderIndex, reduce = false) for index, member in playerShip.crew: if member.payment[2] == 0: continue if profit < 1: updateMorale(ship = playerShip, memberIndex = index, value = getRandom( min = -25, max = -5)) addMessage(message = member.name & " is sad because doesn't get own part of profit.", mType = tradeMessage, color = red) profit = 0 continue profit -= (profit.float * (member.payment[2].float / 100.0)).int if profit < 1: if profit < 0: updateMorale(ship = playerShip, memberIndex = index, value = getRandom(min = -12, max = -2)) addMessage(message = member.name & " is sad because doesn't get own part of profit.", mType = tradeMessage, color = red) profit = 0 if freeCargo(amount = itemsList[protoIndex].weight * sellAmount) - profit < 0: raise newException(exceptn = NoFreeCargoError, message = "") let itemName: string = itemsList[protoIndex].name if baseIndex > 0: if profit > skyBases[baseIndex].cargo[0].amount: raise newException(exceptn = NoMoneyInBaseError, message = itemName) updateBaseCargo(protoIndex = protoIndex, amount = sellAmount, durability = playerShip.cargo[itemIndex].durability, quality = playerShip.cargo[itemIndex].quality) else: if profit > traderCargo[0].amount: raise newException(exceptn = NoMoneyInBaseError, message = itemName) var cargoAdded: bool = false for item in traderCargo.mitems: if item.protoIndex == protoIndex and item.durability == playerShip.cargo[itemIndex].durability: item.amount += sellAmount cargoAdded = true break if not cargoAdded: traderCargo.add(y = BaseCargo(protoIndex: protoIndex, amount: sellAmount, durability: playerShip.cargo[itemIndex].durability, price: itemsList[protoIndex].price, quality: playerShip.cargo[itemIndex].quality)) updateCargo(ship = playerShip, cargoIndex = itemIndex, amount = -sellAmount, price = playerShip.cargo[itemIndex].price, quality = playerShip.cargo[itemIndex].quality) updateCargo(ship = playerShip, protoIndex = moneyIndex, amount = profit, quality = normal) if baseIndex > 0: updateBaseCargo(protoIndex = moneyIndex, amount = -profit, quality = normal) gainRep(baseIndex = baseIndex, points = 1) if itemsList[protoIndex].reputation > skyBases[ baseIndex].reputation.level: gainRep(baseIndex = baseIndex, points = 1) else: traderCargo[0].amount -= profit gainExp(amount = 1, skillNumber = talkingSkill, crewIndex = traderIndex) let gain: int = profit - (sellAmount * price) addMessage(message = "You sold " & $sellAmount & " " & itemName & " for " & $profit & " " & moneyName & "." & (if gain == 0: "" else: " You " & ( if gain > 0: "gain " else: "lost ") & $(gain.abs) & " " & moneyName & " compared to the base price."), mType = tradeMessage) if baseIndex > 0 and eventIndex > -1: eventsList[eventIndex].time += 5 updateGame(minutes = 5) proc buyItems*(baseItemIndex: Natural; amount: string) {.raises: [ NoTraderError, NoFreeCargoError, NoMoneyError, NotEnoughMoneyError, KeyError, ValueError, IOError, Exception], tags: [WriteIOEffect, RootEffect], contractual.} = ## Buy the selected item from the trader ## ## * baseItemIndex - the index of the item to buy in the trader's cargo ## * amount - the amount of the item to buy let traderIndex: int = findMember(order = talk) if traderIndex == -1: raise newException(exceptn = NoTraderError, message = "") let baseIndex: ExtendedBasesRange = skyMap[playerShip.skyX][playerShip.skyY].baseIndex eventIndex: int = skyMap[playerShip.skyX][playerShip.skyY].eventIndex var itemIndex, price: Natural = 0 itemName: string = "" if baseIndex > 0: itemIndex = skyBases[baseIndex].cargo[baseItemIndex].protoIndex itemName = itemsList[itemIndex].name price = skyBases[baseIndex].cargo[baseItemIndex].price if eventIndex > -1 and eventsList[eventIndex].eType == doublePrice and eventsList[eventIndex].itemIndex == itemIndex: price *= 2 else: itemIndex = traderCargo[baseItemIndex].protoIndex itemName = itemsList[itemIndex].name price = traderCargo[baseItemIndex].price let buyAmount: Positive = amount.parseInt var cost: Natural = buyAmount * price countPrice(price = cost, traderIndex = traderIndex) if freeCargo(amount = cost - (itemsList[itemIndex].weight * buyAmount)) < 0: raise newException(exceptn = NoFreeCargoError, message = "") let moneyAmount: Natural = moneyAmount(inventory = playerShip.cargo) if moneyAmount == 0: raise newException(exceptn = NoMoneyError, message = itemName) if cost > moneyAmount: raise newException(exceptn = NotEnoughMoneyError, message = itemName) updateMoney(memberIndex = -1, amount = -cost, quality = any) if baseIndex > 0: updateBaseCargo(protoIndex = moneyIndex, amount = cost, quality = normal) else: traderCargo[0].amount += cost if baseIndex > 0: updateCargo(ship = playerShip, protoIndex = itemIndex, amount = buyAmount, durability = skyBases[baseIndex].cargo[baseItemIndex].durability, price = price, quality = skyBases[baseIndex].cargo[baseItemIndex].quality) updateBaseCargo(cargoIndex = baseItemIndex.cint, amount = -buyAmount, durability = skyBases[baseIndex].cargo[baseItemIndex].durability, quality = skyBases[baseIndex].cargo[baseItemIndex].quality) gainRep(baseIndex = baseIndex, points = 1) else: updateCargo(ship = playerShip, protoIndex = itemIndex, amount = buyAmount, durability = traderCargo[baseItemIndex].durability, price = price, quality = skyBases[baseIndex].cargo[baseItemIndex].quality) traderCargo[baseItemIndex].amount -= buyAmount if traderCargo[baseItemIndex].amount == 0: traderCargo.delete(i = baseItemIndex) gainExp(amount = 1, skillNumber = talkingSkill, crewIndex = traderIndex) let gain: int = (buyAmount * price) - cost addMessage(message = "You bought " & $buyAmount & " " & itemName & " for " & $cost & " " & moneyName & "." & (if gain == 0: "" else: "You " & ( if gain > 0: "gain " else: "lost ") & $(gain.abs) & " " & moneyName & " compared to the base price."), mType = tradeMessage) if baseIndex == 0 and eventIndex > -1: eventsList[eventIndex].time += 5 updateGame(minutes = 5) proc getTradeData*(iIndex: int): tuple[protoIndex, maxSellAmount, maxBuyAmount, price: int; quality: ObjectQuality] {.raises: [KeyError], tags: [], contractual.} = ## Get the data related to the item during trading ## ## * iIndex - the index of the item which data will be get. If positive, the ## item is in the player's ship's cargo, negative in the trader's ## cargo. ## ## Returns tuple with trade data: proto index of the item, max amount of item ## to sell, max amount item to buy, its price and quality result = (-1, 0, 0, 0, normal) var baseCargoIndex, cargoIndex: int = -1 if iIndex < 0: baseCargoIndex = iIndex.abs else: cargoIndex = iIndex if cargoIndex > playerShip.cargo.high: return let baseIndex: int = skyMap[playerShip.skyX][playerShip.skyY].baseIndex if baseIndex == 0 and baseCargoIndex > traderCargo.high: return elif baseIndex > 0 and baseCargoIndex > skyBases[baseIndex].cargo.high: return if iIndex < 0: if baseIndex == 0: result.quality = traderCargo[baseCargoIndex].quality else: result.quality = skyBases[baseIndex].cargo[baseCargoIndex].quality else: result.quality = playerShip.cargo[cargoIndex].quality var itemIndex: int = iIndex if cargoIndex > -1: result.protoIndex = playerShip.cargo[cargoIndex].protoIndex else: result.protoIndex = (if baseIndex == 0: traderCargo[ baseCargoIndex].protoIndex else: skyBases[baseIndex].cargo[ baseCargoIndex].protoIndex) let baseType: string = (if baseIndex > 0: skyBases[baseIndex].baseType else: "0") if iIndex > -1: baseCargoIndex = findBaseCargo(protoIndex = result.protoIndex, durability = playerShip.cargo[cargoIndex].durability, quality = result.quality) if baseCargoIndex > -1: result.price = (if baseIndex > 0: skyBases[baseIndex].cargo[ baseCargoIndex].price else: traderCargo[baseCargoIndex].price) else: result.price = getPrice(baseType = baseType, itemIndex = result.protoIndex, quality = result.quality) else: itemIndex = findItem(inventory = playerShip.cargo, protoIndex = result.protoIndex, durability = (if baseIndex > 0: skyBases[ baseIndex].cargo[ baseCargoIndex].durability else: traderCargo[ baseCargoIndex].durability), itemQuality = result.quality) result.price = (if baseIndex > 0: skyBases[baseIndex].cargo[ baseCargoIndex].price else: traderCargo[baseCargoIndex].price) if itemIndex > -1: result.maxSellAmount = playerShip.cargo[itemIndex].amount var maxPrice: Natural = result.maxSellAmount * result.price countPrice(price = maxPrice, traderIndex = findMember(order = talk), reduce = false) if baseIndex > 0 and maxPrice > skyBases[baseIndex].cargo[0].amount: result.maxSellAmount = (result.maxSellAmount.float * (skyBases[baseIndex].cargo[ 0].amount.float / maxPrice.float)).floor.int elif baseIndex == 0 and maxPrice > traderCargo[0].amount: result.maxSellAmount = (result.maxSellAmount.float * (traderCargo[0].amount.float / maxPrice.float)).floor.int maxPrice = result.maxSellAmount * result.price if maxPrice > 0: countPrice(price = maxPrice, traderIndex = findMember(order = talk), reduce = false) var weight: int = freeCargo(amount = (itemsList[result.protoIndex].weight * result.maxSellAmount) - maxPrice) while weight < 0: result.maxSellAmount = (result.maxSellAmount.float * ((maxPrice + weight).float / maxPrice.float)).floor.int if result.maxSellAmount < 1: break maxPrice = result.maxSellAmount * result.price countPrice(price = maxPrice, traderIndex = findMember(order = talk), reduce = false) weight = freeCargo(amount = (itemsList[result.protoIndex].weight * result.maxSellAmount) - maxPrice) if baseIndex > 0 and countFreeCargo(baseIndex = baseIndex) == 0 and baseCargoIndex == -1: result.maxSellAmount = 0 let moneyAmount: Natural = moneyAmount(inventory = playerShip.cargo) if baseCargoIndex > -1 and moneyAmount > 0 and ((baseIndex > -1 and isBuyable(baseType = baseType, itemIndex = result.protoIndex)) or baseIndex == 0): result.maxBuyAmount = (moneyAmount / result.price).int var maxPrice: Natural = result.maxBuyAmount * result.price if result.maxBuyAmount > 0: countPrice(price = maxPrice, traderIndex = findMember(order = talk)) if maxPrice < result.maxBuyAmount * result.price: result.maxBuyAmount = (result.maxBuyAmount.float * ((result.maxBuyAmount.float * result.price.float) / maxPrice.float)).floor.int if baseIndex > 0 and result.maxBuyAmount > skyBases[baseIndex].cargo[ baseCargoIndex].amount: result.maxBuyAmount = skyBases[baseIndex].cargo[baseCargoIndex].amount elif baseIndex == 0 and result.maxBuyAmount > traderCargo[ baseCargoIndex].amount: result.maxBuyAmount = traderCargo[baseCargoIndex].amount maxPrice = result.maxBuyAmount * result.price countPrice(price = maxPrice, traderIndex = findMember(order = talk)) var weight: int = freeCargo(amount = maxPrice - (itemsList[ result.protoIndex].weight * result.maxBuyAmount)) while weight < 0: result.maxBuyAmount = result.maxBuyAmount + (weight / itemsList[ result.protoIndex].weight).int - 1 if result.maxBuyAmount < 0: result.maxBuyAmount = 0 if result.maxBuyAmount == 0: break maxPrice = result.maxBuyAmount * result.price countPrice(price = maxPrice, traderIndex = findMember(order = talk)) weight = freeCargo(amount = maxPrice - (itemsList[ result.protoIndex].weight * result.maxBuyAmount)) if itemIndex == -1: itemIndex = -(baseCargoIndex)
0
0.686316
1
0.686316
game-dev
MEDIA
0.77343
game-dev
0.861764
1
0.861764
FreeCol/freecol
6,321
src/net/sf/freecol/common/networking/FeatureChangeMessage.java
/** * Copyright (C) 2002-2024 The FreeCol Team * * This file is part of FreeCol. * * FreeCol 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. * * FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.common.networking; import java.util.ArrayList; import java.util.List; import javax.xml.stream.XMLStreamException; import net.sf.freecol.client.FreeColClient; import net.sf.freecol.common.io.FreeColXMLReader; import net.sf.freecol.common.model.Ability; import net.sf.freecol.common.model.FreeColGameObject; import net.sf.freecol.common.model.FreeColObject; import net.sf.freecol.common.model.Game; import net.sf.freecol.common.model.HistoryEvent; import net.sf.freecol.common.model.LastSale; import net.sf.freecol.common.model.ModelMessage; import net.sf.freecol.common.model.Modifier; import net.sf.freecol.server.FreeColServer; import net.sf.freecol.server.ai.AIPlayer; /** * The message sent when to add or remove a feature. */ public class FeatureChangeMessage extends ObjectMessage { public static final String TAG = "featureChange"; private static final String ADD_TAG = "add"; private static final String ID_TAG = FreeColObject.ID_ATTRIBUTE_TAG; /** * Create a new {@code FeatureChangeMessage} for the game object * and feature. * * @param fcgo The parent {@code FreeColGameObject} to manipulate. * @param fco The {@code FreeColObject} to add or remove. * @param add If true the object is added. */ public FeatureChangeMessage(FreeColGameObject fcgo, FreeColObject fco, boolean add) { super(TAG, ID_TAG, fcgo.getId(), ADD_TAG, String.valueOf(add)); appendChild(fco); } /** * Create a new {@code FeatureChangeMessage} from a stream. * * @param game The {@code Game} this message belongs to. * @param xr The {@code FreeColXMLReader} to read from. * @exception XMLStreamException if there is a problem reading the stream. */ public FeatureChangeMessage(Game game, FreeColXMLReader xr) throws XMLStreamException { super(TAG, xr, ID_TAG, ADD_TAG); List<FreeColObject> fcos = new ArrayList<>(); FreeColXMLReader.ReadScope rs = xr.replaceScope(FreeColXMLReader.ReadScope.NOINTERN); try { // Defend against colliding identifiers, so do *not* just call // xr.readFreeColObject. while (xr.moreTags()) { String tag = xr.getLocalName(); FreeColObject fco = null; if (Ability.TAG.equals(tag)) { fco = new Ability(game.getSpecification()); fco.readFromXML(xr); } else if (Modifier.TAG.equals(tag)) { fco = new Modifier(game.getSpecification()); fco.readFromXML(xr); } else if (HistoryEvent.TAG.equals(tag)) { fco = new HistoryEvent(); fco.readFromXML(xr); } else if (LastSale.TAG.equals(tag)) { fco = new LastSale(); fco.readFromXML(xr); } else if (ModelMessage.TAG.equals(tag)) { fco = new ModelMessage(); fco.readFromXML(xr); } else { expected("Feature", tag); } fcos.add(fco); xr.expectTag(tag); } xr.expectTag(TAG); setChildren(fcos); } finally { xr.replaceScope(rs); } } /** * Get the parent object identifier. * * @return The parent identifier. */ private String getParentId() { return getStringAttribute(ID_TAG); } /** * Get the parent object to add/remove to. * * @param game The {@code Game} to look in. * @return The parent {@code FreeColGameObject}. */ private FreeColGameObject getParent(Game game) { return game.getFreeColGameObject(getParentId()); } /** * Get the add/remove state. * * @return True if the child object should be added to the parent. */ private boolean getAdd() { return getBooleanAttribute(ADD_TAG, Boolean.FALSE); } /** * {@inheritDoc} */ @Override public MessagePriority getPriority() { return Message.MessagePriority.OWNED; } /** * {@inheritDoc} */ @Override public boolean merge(Message message) { if (message instanceof FeatureChangeMessage) { FeatureChangeMessage other = (FeatureChangeMessage)message; if (getParentId().equals(other.getParentId()) && getAdd() == other.getAdd()) { appendChildren(other.getChildren()); return true; } } return false; } /** * {@inheritDoc} */ @Override public void aiHandler(FreeColServer freeColServer, AIPlayer aiPlayer) { // Ignored } /** * {@inheritDoc} */ @Override public void clientHandler(FreeColClient freeColClient) { final Game game = freeColClient.getGame(); final FreeColGameObject parent = getParent(game); final List<FreeColObject> children = getChildren(); final boolean add = getAdd(); if (parent == null) { logger.warning("featureChange with null parent."); return; } if (children.isEmpty()) { logger.warning("featureChange with no children."); return; } igc(freeColClient).featureChangeHandler(parent, children, add); clientGeneric(freeColClient); } }
0
0.846607
1
0.846607
game-dev
MEDIA
0.353707
game-dev
0.919713
1
0.919713
FoxMCTeam/TenacityRecode-master
2,966
src/java/net/minecraft/entity/ai/EntityMoveHelper.java
package net.minecraft.entity.ai; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.util.MathHelper; public class EntityMoveHelper { /** The EntityLiving that is being moved */ protected EntityLiving entity; protected double posX; protected double posY; protected double posZ; /** The speed at which the entity should move */ protected double speed; protected boolean update; public EntityMoveHelper(EntityLiving entitylivingIn) { this.entity = entitylivingIn; this.posX = entitylivingIn.posX; this.posY = entitylivingIn.posY; this.posZ = entitylivingIn.posZ; } public boolean isUpdating() { return this.update; } public double getSpeed() { return this.speed; } /** * Sets the speed and location to move to */ public void setMoveTo(double x, double y, double z, double speedIn) { this.posX = x; this.posY = y; this.posZ = z; this.speed = speedIn; this.update = true; } public void onUpdateMoveHelper() { this.entity.setMoveForward(0.0F); if (this.update) { this.update = false; int i = MathHelper.floor_double(this.entity.getEntityBoundingBox().minY + 0.5D); double d0 = this.posX - this.entity.posX; double d1 = this.posZ - this.entity.posZ; double d2 = this.posY - (double)i; double d3 = d0 * d0 + d2 * d2 + d1 * d1; if (d3 >= 2.500000277905201E-7D) { float f = (float)(MathHelper.atan2(d1, d0) * 180.0D / Math.PI) - 90.0F; this.entity.rotationYaw = this.limitAngle(this.entity.rotationYaw, f, 30.0F); this.entity.setAIMoveSpeed((float)(this.speed * this.entity.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getAttributeValue())); if (d2 > 0.0D && d0 * d0 + d1 * d1 < 1.0D) { this.entity.getJumpHelper().setJumping(); } } } } /** * Limits the given angle to a upper and lower limit. */ protected float limitAngle(float p_75639_1_, float p_75639_2_, float p_75639_3_) { float f = MathHelper.wrapAngleTo180_float(p_75639_2_ - p_75639_1_); if (f > p_75639_3_) { f = p_75639_3_; } if (f < -p_75639_3_) { f = -p_75639_3_; } float f1 = p_75639_1_ + f; if (f1 < 0.0F) { f1 += 360.0F; } else if (f1 > 360.0F) { f1 -= 360.0F; } return f1; } public double getX() { return this.posX; } public double getY() { return this.posY; } public double getZ() { return this.posZ; } }
0
0.876495
1
0.876495
game-dev
MEDIA
0.648355
game-dev
0.951007
1
0.951007
mattgodbolt/reddog
6,129
dreamcast/reddog/game/strats/mine_popdown.dst
LOCALFLOAT RandomCreation LOCALINT MineHeight define FIVESECS 300 define ENDCHASERANGE 60 define CHARGERANGE 30 define INNERSTOPRANGE 10 define ACTIVERANGE 200 define ACTIVATEPROXIMITY 40 STATE Init MineHeight = 0 RandomCreation = 0 MyFlag = MyFlag | LOWCOLL | STRATCOLL | ENEMY | HOVERMOVE | NOTEXPLODE | TARGETABLE | NODISP IF (!PNode) OBJECT> ENEMIES\A00AERIALMINE MyFlag = MyFlag | AGGRESSIVE ENDIF RegisterCollision() TRIGSET>SpecularMadness EVERY 1 health = 20.0 TRIGSET>Shot WHENDEAD IF (MyPath) InitPath() ENDIF // AddOmniLight (0, 0, 10.0, 20, 30) // SetLightColour (0, 0.0, 1.0, 0.0) IF (HasActivation(0)) STAT>ActivationPointTrigger ELSEIF STAT>RandomCheck ENDIF ENDSTATE LOCALFLOAT SPECAMOUNT TRIGGER SpecularMadness UpdateTrigFlag(TRIG_ALWAYS_RUN) IF ((MyFlag & HITSTRAT) AND (CollWithFlag & BULLETTYPE)) SPECAMOUNT = 1.0 ENDIF IF (SPECAMOUNT > 0) MyFlag2 = MyFlag2 | SPECULAR SetSpecularColour(0, SPECAMOUNT,SPECAMOUNT,SPECAMOUNT) SPECAMOUNT = SPECAMOUNT - 0.1 ELSE SPECAMOUNT = 0 MyFlag2 = MyFlag2 & LNOT(SPECULAR) ENDIF TRIGFIN ENDTRIGGER STATE ActivationPointTrigger IF (PlayerNearActivationXY(0)) STAT>LiftToWayHeight ENDIF ENDSTATE STATE RandomCheck RandomCreation = RandRange(0.0, 1.0) IF (RandomCreation > 0.8) Delete() ELSE RandomCreation = RandRange(0.0, 5.0) RandomCreation = RandomCreation + 20 WHILE (!NearPlayerXY(RandomCreation)) MyFlag = MyFlag ENDWHILE STAT>LiftToWayHeight ENDIF ENDSTATE STATE Patrol IF ((MyFlag & HOLDING) OR (MyFlag & DEFENSIVE)) MyFlag = MyFlag | RELVELCALC WHILE (!PlayerNearActivationXY(0)) IF ((MyPath) AND (!(MyFlag & DEFENSIVE))) IF (NearCheckPosXY(1.0)) IF (LastWay()) ResetPath() ELSE GetNextWay() ENDIF ENDIF TowardWay(0.05,0.05) MoveY(0.5) ENDIF ENDWHILE MyFlag = MyFlag & LNOT(RELVELCALC) ENDIF charged = 0 Countdown = 0 trans = 0.5 IF (MyFlag & DEFENSIVE) //GetNextWay() STAT>LiftToWayHeight ELSE IF (MyFlag & AGGRESSIVE) STAT>CheckPath ENDIF STAT>ChasePlayer ENDIF ENDSTATE STATE CheckPath IF (MyPath) WHILE (1) IF (NearCheckPosXY(1.0)) IF (LastWay()) STAT>ChasePlayer ENDIF GetNextWay() ENDIF TowardWay(0.05,0.05) MoveY(0.5) ENDWHILE ENDIF STAT>ChasePlayer ENDSTATE STATE LiftToWayHeight MyFlag = MyFlag & LNOT(RELVELCALC) MyFlag = MyFlag & LNOT(NODISP) // WHILE (!LastWay()) // // WHILE (!NearCheckPosZ(0.0)) // // distz = FABS(z - CheckZ) / 10.0 // // IF (distz < 0.01) // distz = 0.01 // ENDIF // // // IF (distz > 0.48) // distz = 0.48 // ENDIF // // // IF (z < CheckZ) // absspeedz = absspeedz + distz // ELSE // absspeedz = absspeedz - distz // ENDIF // ENDWHILE // // GetNextWay() // // ENDWHILE WHILE (MineHeight < 18) MoveZ (-0.3) MineHeight = MineHeight + 1 ENDWHILE STAT>ChasePlayer ENDSTATE LOCALINT SameLevel LOCALINT SameLevelCount LOCALINT SameUp LOCALINT Countdown LOCALINT charged LOCALFLOAT dist LOCALFLOAT distx LOCALFLOAT disty LOCALFLOAT distz //CHASING THE PLAYER STATE ChasePlayer // STAT>Kill IF (!(MyFlag & AGGRESSIVE)) IF (!NearPlayerXY(ACTIVERANGE)) STAT>TimeOut ENDIF ENDIF IF (NearPlayer(CHARGERANGE)) // MyFlag2 = MyFlag2 | TARGETTED // MyFlag2 = MyFlag2 | SPECULAR | TRANSLUCENT charged = 1 ENDIF AvoidStrats(3.0) IF (charged) // Yaw(0.028) Yaw(0.088) ELSE Yaw(0.015) ENDIF distx = (DogX - x) disty = (DogY - y) dist = (distx * distx) + (disty * disty) dist = FSQRT(dist) distx = distx / dist disty = disty / dist IF (distx < 0) IF (distx < -0.28) distx = -0.28 ENDIF ELSE IF (distx > 0.28) distx = 0.28 ENDIF ENDIF IF (disty < 0) IF (disty < -0.28) disty = -0.28 ENDIF ELSE IF (disty > 0.28) disty = 0.28 ENDIF ENDIF absspeedx = absspeedx + distx absspeedy = absspeedy + disty // absspeedy = absspeedy * 0.8 // absspeedx = absspeedx * 0.8 distz = FABS(z - DogZ) IF (!SameLevel) IF (distz < 2.0) SameLevelCount = 0 SameLevel = 1 SameUp = 1 ELSE SameLevel = 0 ENDIF distz = distz / 50.0 IF (distz < 0.01) distz = 0.01 ENDIF IF (distz > 0.08) distz = 0.08 ENDIF IF (z < DogZ) absspeedz = absspeedz + distz ELSE absspeedz = absspeedz - distz ENDIF ELSE IF (distz > 12.0) SameLevel = 0 ELSE IF (SameUp) distz = 0.04 ELSE distz = -0.04 ENDIF SameLevelCount = SameLevelCount + 1 IF (SameLevelCount > 15) SameUp = !SameUp SameLevelCount = 0 ENDIF absspeedz = absspeedz + distz ENDIF ENDIF IF (charged) trans = trans + 0.08 IF (trans > 1.0) trans = 0 ENDIF IF ((Countdown > FIVESECS)) STAT>Kill ELSE IF (NearPlayer(INNERSTOPRANGE)) STAT>Kill ELSE Countdown = Countdown + 1 ENDIF ENDIF ENDIF ENDSTATE STATE TimeOut IF (MyFlag & AGGRESSIVE) STAT> ChasePlayer ENDIF IF (NearPlayer(ACTIVATEPROXIMITY)) STAT>ChasePlayer ENDIF ENDSTATE STATE Kill Yaw(0.128) distz = FABS(z - DogZ) WHILE (FABS(distz) > 3.0) distx = (DogX - x) disty = (DogY - y) dist = (distx * distx) + (disty * disty) dist = FSQRT(dist) distx = distx / dist disty = disty / dist IF (distx < 0) IF (distx < -0.28) distx = -0.28 ENDIF ELSE IF (distx > 0.28) distx = 0.28 ENDIF ENDIF IF (disty < 0) IF (disty < -0.28) disty = -0.28 ENDIF ELSE IF (disty > 0.28) disty = 0.28 ENDIF ENDIF absspeedx = absspeedx + distx absspeedy = absspeedy + disty distz = (z - DogZ) IF (z < DogZ) absspeedz = absspeedz + 0.11 ELSE absspeedz = absspeedz - 0.11 ENDIF ENDWHILE trans = 0.9 MakeFrags (0.1, 24) MyVar = 1.0 CREATE SPAWN_BLASTEXP 0, 0, 0, 0, 0, 0, 0 TRIGSTOP DESTROYME SPAWN_EXPLODINGBITS ENDSTATE STATE Shot // adrelanin = adrelanin + 0.2 MyVar = 1.0 CREATE SPAWN_BLASTEXP 0, 0, 0, 0, 0, 0, 0 Delete() // TRIGSTOP ENDSTATE
0
0.710675
1
0.710675
game-dev
MEDIA
0.904674
game-dev
0.954717
1
0.954717
AirFoundation/Naven-NoAuth
16,765
src/main/java/net/optifine/shaders/gui/GuiShaders.java
package net.optifine.shaders.gui; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraft.client.settings.GameSettings; import net.minecraft.src.Config; import net.optifine.Lang; import net.optifine.gui.GuiScreenOF; import net.optifine.gui.TooltipManager; import net.optifine.gui.TooltipProviderEnumShaderOptions; import net.optifine.shaders.Shaders; import net.optifine.shaders.ShadersTex; import net.optifine.shaders.config.EnumShaderOption; import org.lwjgl.Sys; import java.io.File; import java.io.IOException; import java.net.URI; public class GuiShaders extends GuiScreenOF { protected GuiScreen parentGui; protected String screenTitle = "Shaders"; private final TooltipManager tooltipManager = new TooltipManager(this, new TooltipProviderEnumShaderOptions()); private int updateTimer = -1; private GuiSlotShaders shaderList; private boolean saved = false; private static final float[] QUALITY_MULTIPLIERS = new float[]{0.5F, 0.6F, 0.6666667F, 0.75F, 0.8333333F, 0.9F, 1.0F, 1.1666666F, 1.3333334F, 1.5F, 1.6666666F, 1.8F, 2.0F}; private static final String[] QUALITY_MULTIPLIER_NAMES = new String[]{"0.5x", "0.6x", "0.66x", "0.75x", "0.83x", "0.9x", "1x", "1.16x", "1.33x", "1.5x", "1.66x", "1.8x", "2x"}; private static final float QUALITY_MULTIPLIER_DEFAULT = 1.0F; private static final float[] HAND_DEPTH_VALUES = new float[]{0.0625F, 0.125F, 0.25F}; private static final String[] HAND_DEPTH_NAMES = new String[]{"0.5x", "1x", "2x"}; private static final float HAND_DEPTH_DEFAULT = 0.125F; public static final int EnumOS_UNKNOWN = 0; public static final int EnumOS_WINDOWS = 1; public static final int EnumOS_OSX = 2; public static final int EnumOS_SOLARIS = 3; public static final int EnumOS_LINUX = 4; public GuiShaders(GuiScreen par1GuiScreen, GameSettings par2GameSettings) { this.parentGui = par1GuiScreen; } public void initGui() { this.screenTitle = I18n.format("of.options.shadersTitle"); if (Shaders.shadersConfig == null) { Shaders.loadConfig(); } int i = 120; int j = 20; int k = this.width - i - 10; int l = 30; int i1 = 20; int j1 = this.width - i - 20; this.shaderList = new GuiSlotShaders(this, j1, this.height, l, this.height - 50, 16); this.shaderList.registerScrollButtons(7, 8); this.buttonList.add(new GuiButtonEnumShaderOption(EnumShaderOption.ANTIALIASING, k, 0 + l, i, j)); this.buttonList.add(new GuiButtonEnumShaderOption(EnumShaderOption.NORMAL_MAP, k, i1 + l, i, j)); this.buttonList.add(new GuiButtonEnumShaderOption(EnumShaderOption.SPECULAR_MAP, k, 2 * i1 + l, i, j)); this.buttonList.add(new GuiButtonEnumShaderOption(EnumShaderOption.RENDER_RES_MUL, k, 3 * i1 + l, i, j)); this.buttonList.add(new GuiButtonEnumShaderOption(EnumShaderOption.SHADOW_RES_MUL, k, 4 * i1 + l, i, j)); this.buttonList.add(new GuiButtonEnumShaderOption(EnumShaderOption.HAND_DEPTH_MUL, k, 5 * i1 + l, i, j)); this.buttonList.add(new GuiButtonEnumShaderOption(EnumShaderOption.OLD_HAND_LIGHT, k, 6 * i1 + l, i, j)); this.buttonList.add(new GuiButtonEnumShaderOption(EnumShaderOption.OLD_LIGHTING, k, 7 * i1 + l, i, j)); int k1 = Math.min(150, j1 / 2 - 10); int l1 = j1 / 4 - k1 / 2; int i2 = this.height - 25; this.buttonList.add(new GuiButton(201, l1, i2, k1 - 22 + 1, j, Lang.get("of.options.shaders.shadersFolder"))); this.buttonList.add(new GuiButtonDownloadShaders(210, l1 + k1 - 22 - 1, i2)); this.buttonList.add(new GuiButton(202, j1 / 4 * 3 - k1 / 2, this.height - 25, k1, j, I18n.format("gui.done"))); this.buttonList.add(new GuiButton(203, k, this.height - 25, i, j, Lang.get("of.options.shaders.shaderOptions"))); this.updateButtons(); } public void updateButtons() { boolean flag = Config.isShaders(); for (GuiButton guibutton : this.buttonList) { if (guibutton.id != 201 && guibutton.id != 202 && guibutton.id != 210 && guibutton.id != EnumShaderOption.ANTIALIASING.ordinal()) { guibutton.enabled = flag; } } } public void handleMouseInput() throws IOException { super.handleMouseInput(); this.shaderList.handleMouseInput(); } protected void actionPerformed(GuiButton button) { this.actionPerformed(button, false); } protected void actionPerformedRightClick(GuiButton button) { this.actionPerformed(button, true); } private void actionPerformed(GuiButton button, boolean rightClick) { if (button.enabled) { if (!(button instanceof GuiButtonEnumShaderOption)) { if (!rightClick) { switch (button.id) { case 201: switch (getOSType()) { case 1: String s = String.format("cmd.exe /C start \"Open file\" \"%s\"", Shaders.shaderPacksDir.getAbsolutePath()); try { Runtime.getRuntime().exec(s); return; } catch (IOException ioexception) { ioexception.printStackTrace(); break; } case 2: try { Runtime.getRuntime().exec(new String[]{"/usr/bin/open", Shaders.shaderPacksDir.getAbsolutePath()}); return; } catch (IOException ioexception1) { ioexception1.printStackTrace(); } } boolean flag = false; try { Class oclass1 = Class.forName("java.awt.Desktop"); Object object1 = oclass1.getMethod("getDesktop", new Class[0]).invoke(null); oclass1.getMethod("browse", new Class[]{URI.class}).invoke(object1, (new File(this.mc.mcDataDir, "shaderpacks")).toURI()); } catch (Throwable throwable1) { throwable1.printStackTrace(); flag = true; } if (flag) { Config.dbg("Opening via system class!"); Sys.openURL("file://" + Shaders.shaderPacksDir.getAbsolutePath()); } break; case 202: Shaders.storeConfig(); this.saved = true; this.mc.displayGuiScreen(this.parentGui); break; case 203: GuiShaderOptions guishaderoptions = new GuiShaderOptions(this, Config.getGameSettings()); Config.getMinecraft().displayGuiScreen(guishaderoptions); break; case 210: try { Class<?> oclass = Class.forName("java.awt.Desktop"); Object object = oclass.getMethod("getDesktop", new Class[0]).invoke(null); oclass.getMethod("browse", new Class[]{URI.class}).invoke(object, new URI("http://optifine.net/shaderPacks")); } catch (Throwable throwable) { throwable.printStackTrace(); } case 204: case 205: case 206: case 207: case 208: case 209: default: this.shaderList.actionPerformed(button); } } } else { GuiButtonEnumShaderOption guibuttonenumshaderoption = (GuiButtonEnumShaderOption) button; switch (guibuttonenumshaderoption.getEnumShaderOption()) { case ANTIALIASING: Shaders.nextAntialiasingLevel(!rightClick); if (this.hasShiftDown()) { Shaders.configAntialiasingLevel = 0; } Shaders.uninit(); break; case NORMAL_MAP: Shaders.configNormalMap = !Shaders.configNormalMap; if (this.hasShiftDown()) { Shaders.configNormalMap = true; } Shaders.uninit(); this.mc.scheduleResourcesRefresh(); break; case SPECULAR_MAP: Shaders.configSpecularMap = !Shaders.configSpecularMap; if (this.hasShiftDown()) { Shaders.configSpecularMap = true; } Shaders.uninit(); this.mc.scheduleResourcesRefresh(); break; case RENDER_RES_MUL: Shaders.configRenderResMul = this.getNextValue(Shaders.configRenderResMul, QUALITY_MULTIPLIERS, QUALITY_MULTIPLIER_DEFAULT, !rightClick, this.hasShiftDown()); Shaders.uninit(); Shaders.scheduleResize(); break; case SHADOW_RES_MUL: Shaders.configShadowResMul = this.getNextValue(Shaders.configShadowResMul, QUALITY_MULTIPLIERS, QUALITY_MULTIPLIER_DEFAULT, !rightClick, this.hasShiftDown()); Shaders.uninit(); Shaders.scheduleResizeShadow(); break; case HAND_DEPTH_MUL: Shaders.configHandDepthMul = this.getNextValue(Shaders.configHandDepthMul, HAND_DEPTH_VALUES, HAND_DEPTH_DEFAULT, !rightClick, this.hasShiftDown()); Shaders.uninit(); break; case OLD_HAND_LIGHT: Shaders.configOldHandLight.nextValue(!rightClick); if (this.hasShiftDown()) { Shaders.configOldHandLight.resetValue(); } Shaders.uninit(); break; case OLD_LIGHTING: Shaders.configOldLighting.nextValue(!rightClick); if (this.hasShiftDown()) { Shaders.configOldLighting.resetValue(); } Shaders.updateBlockLightLevel(); Shaders.uninit(); this.mc.scheduleResourcesRefresh(); break; case TWEAK_BLOCK_DAMAGE: Shaders.configTweakBlockDamage = !Shaders.configTweakBlockDamage; break; case CLOUD_SHADOW: Shaders.configCloudShadow = !Shaders.configCloudShadow; break; case TEX_MIN_FIL_B: Shaders.configTexMinFilB = (Shaders.configTexMinFilB + 1) % 3; Shaders.configTexMinFilN = Shaders.configTexMinFilS = Shaders.configTexMinFilB; button.displayString = "Tex Min: " + Shaders.texMinFilDesc[Shaders.configTexMinFilB]; ShadersTex.updateTextureMinMagFilter(); break; case TEX_MAG_FIL_N: Shaders.configTexMagFilN = (Shaders.configTexMagFilN + 1) % 2; button.displayString = "Tex_n Mag: " + Shaders.texMagFilDesc[Shaders.configTexMagFilN]; ShadersTex.updateTextureMinMagFilter(); break; case TEX_MAG_FIL_S: Shaders.configTexMagFilS = (Shaders.configTexMagFilS + 1) % 2; button.displayString = "Tex_s Mag: " + Shaders.texMagFilDesc[Shaders.configTexMagFilS]; ShadersTex.updateTextureMinMagFilter(); break; case SHADOW_CLIP_FRUSTRUM: Shaders.configShadowClipFrustrum = !Shaders.configShadowClipFrustrum; button.displayString = "ShadowClipFrustrum: " + toStringOnOff(Shaders.configShadowClipFrustrum); ShadersTex.updateTextureMinMagFilter(); } guibuttonenumshaderoption.updateButtonText(); } } } public void onGuiClosed() { super.onGuiClosed(); if (!this.saved) { Shaders.storeConfig(); } } public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); this.shaderList.drawScreen(mouseX, mouseY, partialTicks); if (this.updateTimer <= 0) { this.shaderList.updateList(); this.updateTimer += 20; } this.drawCenteredString(this.fontRendererObj, this.screenTitle + " ", this.width / 2, 15, 16777215); String s = "OpenGL: " + Shaders.glVersionString + ", " + Shaders.glVendorString + ", " + Shaders.glRendererString; int i = this.fontRendererObj.getStringWidth(s); if (i < this.width - 5) { this.drawCenteredString(this.fontRendererObj, s, this.width / 2, this.height - 40, 8421504); } else { this.drawString(this.fontRendererObj, s, 5, this.height - 40, 8421504); } super.drawScreen(mouseX, mouseY, partialTicks); this.tooltipManager.drawTooltips(mouseX, mouseY, this.buttonList); } public void updateScreen() { super.updateScreen(); --this.updateTimer; } public Minecraft getMc() { return this.mc; } public void drawCenteredString(String text, int x, int y, int color) { this.drawCenteredString(this.fontRendererObj, text, x, y, color); } public static String toStringOnOff(boolean value) { String s = Lang.getOn(); String s1 = Lang.getOff(); return value ? s : s1; } public static String toStringAa(int value) { return value == 2 ? "FXAA 2x" : (value == 4 ? "FXAA 4x" : Lang.getOff()); } public static String toStringValue(float val, float[] values, String[] names) { int i = getValueIndex(val, values); return names[i]; } private float getNextValue(float val, float[] values, float valDef, boolean forward, boolean reset) { if (reset) { return valDef; } else { int i = getValueIndex(val, values); if (forward) { ++i; if (i >= values.length) { i = 0; } } else { --i; if (i < 0) { i = values.length - 1; } } return values[i]; } } public static int getValueIndex(float val, float[] values) { for (int i = 0; i < values.length; ++i) { float f = values[i]; if (f >= val) { return i; } } return values.length - 1; } public static String toStringQuality(float val) { return toStringValue(val, QUALITY_MULTIPLIERS, QUALITY_MULTIPLIER_NAMES); } public static String toStringHandDepth(float val) { return toStringValue(val, HAND_DEPTH_VALUES, HAND_DEPTH_NAMES); } public static int getOSType() { String s = System.getProperty("os.name").toLowerCase(); return s.contains("win") ? 1 : (s.contains("mac") ? 2 : (s.contains("solaris") ? 3 : (s.contains("sunos") ? 3 : (s.contains("linux") ? 4 : (s.contains("unix") ? 4 : 0))))); } public boolean hasShiftDown() { return isShiftKeyDown(); } }
0
0.918435
1
0.918435
game-dev
MEDIA
0.780626
game-dev
0.976527
1
0.976527
Gaby-Station/Gaby-Station
7,130
Content.Shared/_DV/CosmicCult/SharedMonumentSystem.cs
using Content.Shared._DV.CosmicCult; using Content.Shared._DV.CosmicCult.Components; using Content.Shared._DV.CosmicCult.Prototypes; using Content.Shared.Actions; using Content.Shared.Movement.Components; using Content.Shared.Nutrition.Components; using Content.Shared.UserInterface; using Robust.Shared.Map.Components; using Robust.Shared.Physics.Events; using Robust.Shared.Prototypes; using Robust.Shared.Spawners; using Robust.Shared.GameObjects; using Robust.Shared.Timing; namespace Content.Shared._DV.CosmicCult; public abstract class SharedMonumentSystem : EntitySystem { [Dependency] private readonly IComponentFactory _componentFactory = default!; [Dependency] private readonly IGameTiming _timing = default!; [Dependency] private readonly IPrototypeManager _prototype = default!; [Dependency] private readonly SharedActionsSystem _actions = default!; [Dependency] private readonly SharedAppearanceSystem _appearance = default!; [Dependency] private readonly SharedCosmicCultSystem _cosmicCult = default!; [Dependency] private readonly SharedMapSystem _map = default!; [Dependency] private readonly SharedUserInterfaceSystem _ui = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<MonumentComponent, BoundUIOpenedEvent>(OnUIOpened); SubscribeLocalEvent<MonumentComponent, GlyphSelectedMessage>(OnGlyphSelected); SubscribeLocalEvent<MonumentComponent, GlyphRemovedMessage>(OnGlyphRemove); SubscribeLocalEvent<MonumentComponent, InfluenceSelectedMessage>(OnInfluenceSelected); SubscribeLocalEvent<MonumentOnDespawnComponent, TimedDespawnEvent>(OnTimedDespawn); SubscribeLocalEvent<MonumentCollisionComponent, PreventCollideEvent>(OnPreventCollide); SubscribeLocalEvent<MonumentGlyphComponent, EntityTerminatingEvent>(OnGlyphTerminating); } private void OnGlyphTerminating(EntityUid uid, MonumentGlyphComponent component, ref EntityTerminatingEvent args) { if (TryComp<MonumentComponent>(component.Monument, out var monument) && monument.CurrentGlyph == uid) { monument.CurrentGlyph = null; Dirty(component.Monument, monument); } } private void OnTimedDespawn(Entity<MonumentOnDespawnComponent> ent, ref TimedDespawnEvent args) { if (!TryComp(ent, out TransformComponent? xform)) return; var monument = Spawn(ent.Comp.Prototype, xform.Coordinates); var evt = new CosmicCultAssociateRuleEvent(ent, monument); RaiseLocalEvent(ref evt); } public override void Update(float frameTime) { base.Update(frameTime); var query = EntityQueryEnumerator<MonumentTransformingComponent>(); while (query.MoveNext(out var uid, out var comp)) { if (_timing.CurTime < comp.EndTime) continue; _appearance.SetData(uid, MonumentVisuals.Transforming, false); RemComp<MonumentTransformingComponent>(uid); } } /// <summary> /// Ensures that Cultists can't walk through The Monument and allows non-cultists to walk through the space. /// </summary> private void OnPreventCollide(EntityUid uid, MonumentCollisionComponent comp, ref PreventCollideEvent args) { if (!_cosmicCult.EntitySeesCult(args.OtherEntity) && !comp.HasCollision) args.Cancelled = true; } private void OnUIOpened(Entity<MonumentComponent> ent, ref BoundUIOpenedEvent args) { if (!_ui.IsUiOpen(ent.Owner, MonumentKey.Key)) return; if (ent.Comp.Enabled && _cosmicCult.EntityIsCultist(args.Actor)) _ui.SetUiState(ent.Owner, MonumentKey.Key, new MonumentBuiState(ent.Comp)); else _ui.CloseUi(ent.Owner, MonumentKey.Key); //close the UI if the monument isn't available } #region UI listeners private void OnGlyphSelected(Entity<MonumentComponent> ent, ref GlyphSelectedMessage args) { ent.Comp.SelectedGlyph = args.GlyphProtoId; if (!_prototype.TryIndex(args.GlyphProtoId, out var proto)) return; var xform = Transform(ent); if (!TryComp<MapGridComponent>(xform.GridUid, out var grid)) return; var localTile = _map.GetTileRef(xform.GridUid.Value, grid, xform.Coordinates); var targetIndices = localTile.GridIndices + new Vector2i(0, -1); if (ent.Comp.CurrentGlyph is not null) QueueDel(ent.Comp.CurrentGlyph); var glyphEnt = Spawn(proto.Entity, _map.ToCenterCoordinates(xform.GridUid.Value, targetIndices, grid)); var glyphComp = AddComp<MonumentGlyphComponent>(glyphEnt); glyphComp.Monument = ent; ent.Comp.CurrentGlyph = glyphEnt; var evt = new CosmicCultAssociateRuleEvent(ent, glyphEnt); RaiseLocalEvent(ref evt); _ui.SetUiState(ent.Owner, MonumentKey.Key, new MonumentBuiState(ent.Comp)); } private void OnGlyphRemove(Entity<MonumentComponent> ent, ref GlyphRemovedMessage args) { if (ent.Comp.CurrentGlyph is not null) QueueDel(ent.Comp.CurrentGlyph); _ui.SetUiState(ent.Owner, MonumentKey.Key, new MonumentBuiState(ent.Comp)); } private void OnInfluenceSelected(Entity<MonumentComponent> ent, ref InfluenceSelectedMessage args) { if (!_prototype.TryIndex(args.InfluenceProtoId, out var proto) || !TryComp<ActivatableUIComponent>(ent, out var uiComp) || !TryComp<CosmicCultComponent>(args.Actor, out var cultComp)) return; if (cultComp.EntropyBudget < proto.Cost || cultComp.OwnedInfluences.Contains(proto) || args.Actor == null) return; cultComp.OwnedInfluences.Add(proto); if (proto.InfluenceType == "influence-type-active") { var actionEnt = _actions.AddAction(args.Actor, proto.Action); cultComp.ActionEntities.Add(actionEnt); } else if (proto.InfluenceType == "influence-type-passive") { UnlockPassive(args.Actor, proto); //Not unlocking an action? call the helper function to add the influence's passive effects } cultComp.EntropyBudget -= proto.Cost; Dirty(args.Actor, cultComp); //force an update to make sure that the client has the correct set of owned abilities _ui.SetUiState(ent.Owner, MonumentKey.Key, new MonumentBuiState(ent.Comp)); } #endregion private void UnlockPassive(EntityUid cultist, InfluencePrototype proto) { if (proto.Add != null) { foreach (var reg in proto.Add.Values) { var compType = reg.Component.GetType(); if (HasComp(cultist, compType)) continue; AddComp(cultist, _componentFactory.GetComponent(compType)); } } if (proto.Remove != null) { foreach (var reg in proto.Remove.Values) { RemComp(cultist, reg.Component.GetType()); } } } }
0
0.816186
1
0.816186
game-dev
MEDIA
0.972739
game-dev
0.823173
1
0.823173
blendogames/thirtyflightsofloving
15,582
missionpack/m_q1ogre.c
/* ============================================================================== QUAKE OGRE ============================================================================== */ #include "g_local.h" #include "m_q1ogre.h" static int sound_pain; static int sound_death; static int sound_gib; static int sound_idle; static int sound_idle2; static int sound_wake; static int sound_shoot; static int sound_saw; static int sound_drag; #define GRENADE_VELOCITY 632.4555320337 void ogre_check_refire (edict_t *self); void ogre_attack (edict_t *self); void ogre_idle_sound1 (edict_t *self) { if (random() < 0.2) gi.sound (self, CHAN_VOICE, sound_idle, 1, ATTN_IDLE, 0); } void ogre_idle_sound2 (edict_t *self) { if (random() < 0.2) gi.sound (self, CHAN_VOICE, sound_idle2, 1, ATTN_IDLE, 0); } void ogre_sight (edict_t *self, edict_t *other) { gi.sound (self, CHAN_VOICE, sound_wake, 1, ATTN_NORM, 0); ogre_attack (self); } void ogre_drag_sound (edict_t *self) { //if (anglemod(self->s.angles[YAW]) != self->ideal_yaw) if (random() < 0.2) gi.sound (self, CHAN_VOICE, sound_drag, 1, ATTN_IDLE, 0); } void ogre_stand (edict_t *self); mframe_t ogre_frames_stand [] = { ai_stand, 0, NULL, ai_stand, 0, NULL, ai_stand, 0, NULL, ai_stand, 0, NULL, ai_stand, 0, ogre_idle_sound1, ai_stand, 0, NULL, ai_stand, 0, NULL, ai_stand, 0, NULL, ai_stand, 0, NULL, }; mmove_t ogre_move_stand = {FRAME_stand1, FRAME_stand9, ogre_frames_stand, ogre_stand}; void ogre_stand (edict_t *self) { self->monsterinfo.currentmove = &ogre_move_stand; } mframe_t ogre_frames_walk [] = { ai_walk, 3, NULL, ai_walk, 2, NULL, ai_walk, 2, ogre_idle_sound1, ai_walk, 2, NULL, ai_walk, 2, NULL, ai_walk, 6, ogre_drag_sound, ai_walk, 3, NULL, ai_walk, 2, NULL, ai_walk, 3, NULL, ai_walk, 1, NULL, ai_walk, 2, NULL, ai_walk, 3, NULL, ai_walk, 3, NULL, ai_walk, 3, NULL, ai_walk, 3, NULL, ai_walk, 4, NULL }; mmove_t ogre_move_walk = {FRAME_walk1, FRAME_walk16, ogre_frames_walk, NULL}; void ogre_walk (edict_t *self) { self->monsterinfo.currentmove = &ogre_move_walk; } mframe_t ogre_frames_run [] = { ai_run, 9, NULL, ai_run, 12, NULL, ai_run, 8, NULL, ai_run, 22, NULL, ai_run, 16, NULL, ai_run, 4, NULL, ai_run, 13, ogre_attack, ai_run, 24, NULL }; mmove_t ogre_move_run = {FRAME_run1, FRAME_run8, ogre_frames_run, NULL}; void ogre_run (edict_t *self) { if (self->monsterinfo.aiflags & AI_STAND_GROUND) self->monsterinfo.currentmove = &ogre_move_stand; else self->monsterinfo.currentmove = &ogre_move_run; } mframe_t ogre_frames_pain1 [] = { ai_move, -3, NULL, ai_move, 1, NULL, ai_move, 1, NULL, ai_move, 0, NULL, ai_move, 1, NULL }; mmove_t ogre_move_pain1 = {FRAME_pain1, FRAME_pain5, ogre_frames_pain1, ogre_run}; mframe_t ogre_frames_pain2 [] = { ai_move, -1,NULL, ai_move, 0, NULL, ai_move, 1, NULL }; mmove_t ogre_move_pain2 = {FRAME_painb1, FRAME_painb3, ogre_frames_pain2, ogre_run}; mframe_t ogre_frames_pain3 [] = { ai_move, -3, NULL, ai_move, 1, NULL, ai_move, 1, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 1, NULL }; mmove_t ogre_move_pain3 = {FRAME_painc1, FRAME_painc6, ogre_frames_pain3, ogre_run}; mframe_t ogre_frames_pain4 [] = { ai_move, -3, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 1, NULL, ai_move, 1, NULL, ai_move, 0, NULL }; mmove_t ogre_move_pain4 = {FRAME_paind1, FRAME_paind16, ogre_frames_pain4, ogre_run}; mframe_t ogre_frames_pain5 [] = { ai_move, -3, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 1, NULL, ai_move, 1, NULL, ai_move, 0, NULL, }; mmove_t ogre_move_pain5 = {FRAME_paine1, FRAME_paine15, ogre_frames_pain5, ogre_run}; void ogre_pain (edict_t *self, edict_t *other, float kick, int damage) { float r; if (level.time < self->pain_debounce_time) return; r = random(); if (self->health > 0) gi.sound (self, CHAN_VOICE, sound_pain, 1, ATTN_NORM, 0); if (r < 0.25) { self->pain_debounce_time = level.time + 1; self->monsterinfo.currentmove = &ogre_move_pain1; } else if (r < 0.5) { self->pain_debounce_time = level.time + 1; self->monsterinfo.currentmove = &ogre_move_pain2; } else if (r < 0.75) { self->pain_debounce_time = level.time + 1; self->monsterinfo.currentmove = &ogre_move_pain3; } else if (r < 0.88) { self->pain_debounce_time = level.time + 2; self->monsterinfo.currentmove = &ogre_move_pain4; } else { self->pain_debounce_time = level.time + 2; self->monsterinfo.currentmove = &ogre_move_pain5; } } void ogre_droprockets (edict_t *self) { edict_t *backpack; if (self->health <= self->gib_health) return; backpack = Drop_Q1Backpack (self, FindItemByClassname("ammo_grenades"), 2); /* backpack = Drop_Item(self, FindItemByClassname("item_q1_backpack")); backpack->item = FindItemByClassname("ammo_grenades"); // backpack->item = FindItemByClassname("ammo_rockets"); backpack->count = 2; backpack->touch = Touch_Item; backpack->nextthink = level.time + 1800; backpack->think = G_FreeEdict; */ self->gib_health = -10000; } void ogre_dead (edict_t *self) { VectorSet (self->mins, -16, -16, -24); VectorSet (self->maxs, 16, 16, -8); self->movetype = MOVETYPE_TOSS; self->svflags |= SVF_DEADMONSTER; self->nextthink = 0; gi.linkentity (self); } mframe_t ogre_frames_death1 [] = { ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, ogre_droprockets, ai_move, -7, NULL, ai_move, -3, NULL, ai_move, -5, NULL, ai_move, 8, NULL, ai_move, 6, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL }; mmove_t ogre_move_death1 = {FRAME_death1, FRAME_death14, ogre_frames_death1, ogre_dead}; mframe_t ogre_frames_death2 [] = { ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, ogre_droprockets, ai_move, -7, NULL, ai_move, -3, NULL, ai_move, -5, NULL, ai_move, 8, NULL, ai_move, 6, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL, ai_move, 0, NULL }; mmove_t ogre_move_death2 = {FRAME_bdeath1, FRAME_bdeath10, ogre_frames_death2, ogre_dead}; void ogre_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point) { int n; // check for gib if ( (self->health <= self->gib_health) && !(self->spawnflags & SF_MONSTER_NOGIB) ) { gi.sound (self, CHAN_VOICE|CHAN_RELIABLE, sound_gib, 1, ATTN_NORM, 0); // if dead body, don't drop pack when gibbed // if (self->deadflag != DEAD_DEAD) // ogre_droprockets(self); for (n = 0; n < 2; n++) ThrowGib (self, "models/objects/q1gibs/q1gib1/tris.md2", 0, 0, damage, GIB_ORGANIC); for (n = 0; n < 4; n++) ThrowGib (self, "models/objects/q1gibs/q1gib3/tris.md2", 0, 0, damage, GIB_ORGANIC); ThrowHead (self, "models/monsters/q1ogre/head/tris.md2", 0, 0, damage, GIB_ORGANIC); self->deadflag = DEAD_DEAD; return; } if (self->deadflag == DEAD_DEAD) return; // regular death gi.sound (self, CHAN_VOICE, sound_death, 1, ATTN_NORM, 0); self->deadflag = DEAD_DEAD; self->takedamage = DAMAGE_YES; if (random() < 0.5) self->monsterinfo.currentmove = &ogre_move_death1; else self->monsterinfo.currentmove = &ogre_move_death2; } void ogre_grenade_fire (edict_t *self) { vec3_t start, target; vec3_t forward, right, aim; // vec_t monster_speed; AngleVectors (self->s.angles, forward, right, NULL); G_ProjectSource (self->s.origin, monster_flash_offset[MZ2_GUNNER_GRENADE_1], forward, right, start); // project enemy back a bit and target there VectorCopy (self->enemy->s.origin, target); // if (range(self,self->enemy) > RANGE_MID) VectorMA (target, -0.1, self->enemy->velocity, target); if (range(self,self->enemy) > RANGE_MID) target[2] += self->enemy->viewheight; else target[2] += self->enemy->viewheight*0.8; #if 0 if (self->enemy) { float range; VectorSubtract (target, self->s.origin, aim); range = VectorLength (aim); // aim at enemy's feet if he's at same elevation or lower, otherwise aim at origin VectorCopy (self->enemy->s.origin, target); if (self->enemy->absmin[2] <= self->absmax[2]) target[2] = self->enemy->absmin[2]; // Lazarus fog reduction of accuracy if ( self->monsterinfo.visibility < FOG_CANSEEGOOD ) { target[0] += crandom() * 640 * (FOG_CANSEEGOOD - self->monsterinfo.visibility); target[1] += crandom() * 640 * (FOG_CANSEEGOOD - self->monsterinfo.visibility); target[2] += crandom() * 320 * (FOG_CANSEEGOOD - self->monsterinfo.visibility); } // lead target... 20, 35, 50, 65 chance of leading if ( random() < (0.2 + skill->value * 0.15) ) { float dist, time; VectorSubtract (target, start, aim); dist = VectorLength (aim); time = dist / GRENADE_VELOCITY; // Not correct, but better than nothin' VectorMA (target, time, self->enemy->velocity, target); } } AimGrenade (self, start, target, GRENADE_VELOCITY, aim, false); // Lazarus - take into account (sort of) feature of adding shooter's velocity to // grenade velocity monster_speed = VectorLength(self->velocity); if (monster_speed > 0) { vec3_t v1; vec_t delta; VectorCopy (self->velocity, v1); VectorNormalize (v1); delta = -monster_speed / GRENADE_VELOCITY; VectorMA (aim, delta, v1, aim); VectorNormalize (aim); } #else VectorSubtract (target, start, aim); VectorNormalize (aim); #endif gi.WriteByte (svc_muzzleflash); gi.WriteShort (self-g_edicts); gi.WriteByte (MZ_MACHINEGUN | 128); gi.multicast (self->s.origin, MULTICAST_PVS); gi.sound (self, CHAN_WEAPON|CHAN_RELIABLE, sound_shoot, 1.0, ATTN_NORM, 0); q1_fire_grenade (self, start, aim, 40, 600, 2.5, 80); // q1_fire_grenade (self, start, aim, 40, GRENADE_VELOCITY, 2.5, 80); } ////////////// // Skid - add Gib fall off void ogre_swing_left (edict_t *self) { vec3_t aim; VectorSet (aim, MELEE_DISTANCE, self->mins[0], 8); fire_hit (self, aim, ((random() + random() + random()) * 4), 100); } void ogre_swing_right (edict_t *self) { vec3_t aim; VectorSet (aim, MELEE_DISTANCE, self->maxs[0], 8); fire_hit (self, aim, ((random() + random() + random()) * 4), 100); } void ogre_smash (edict_t *self) { vec3_t aim; VectorSet (aim, MELEE_DISTANCE, self->mins[0], 8); if (fire_hit (self, aim, (25 + (rand() %5)), 100)) gi.sound (self, CHAN_WEAPON, sound_saw, 1, ATTN_NORM, 0); } void ogre_check_refire (edict_t *self) { if (!self->enemy || !self->enemy->inuse || self->enemy->health <= 0) return; if ( (skill->value == 3) || (range(self, self->enemy) == RANGE_MELEE)) { if (random() > 0.5) self->monsterinfo.nextframe = FRAME_swing1; else self->monsterinfo.nextframe = FRAME_smash1; } else ogre_attack(self); } /*static*/ void ogre_sawswingsound (edict_t *self) { gi.sound (self, CHAN_WEAPON, sound_saw, 1, ATTN_NORM, 0); } mframe_t ogre_frames_swing [] = { ai_charge, 0, NULL, ai_charge, 0, ogre_sawswingsound, ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, ogre_swing_right, ai_charge, 0, NULL, ai_charge, 0, ogre_sawswingsound, ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, ogre_swing_left, ai_charge, 0, NULL, ai_charge, 0, ogre_check_refire }; mmove_t ogre_move_swing_attack = {FRAME_swing1, FRAME_swing14, ogre_frames_swing, ogre_run}; mframe_t ogre_frames_smash [] = { ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, ogre_smash, ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, ogre_check_refire }; mmove_t ogre_move_smash_attack = {FRAME_smash1, FRAME_smash14, ogre_frames_smash, ogre_run}; mframe_t ogre_frames_attack_grenade [] = { ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, NULL, ai_charge, 0, ogre_grenade_fire, ai_charge, 0, NULL, ai_charge, 0, NULL // ogre_attack }; mmove_t ogre_move_attack_grenade = {FRAME_shoot1, FRAME_shoot6, ogre_frames_attack_grenade, ogre_run}; void ogre_attack (edict_t *self) { int r; if (!self->enemy) return; r = range(self, self->enemy); if (r == RANGE_MELEE) { self->monsterinfo.currentmove = &ogre_move_swing_attack; } else if (visible(self,self->enemy) && infront(self, self->enemy) && (r < RANGE_FAR) && !(self->monsterinfo.aiflags & AI_SOUND_TARGET)) { self->monsterinfo.currentmove = &ogre_move_attack_grenade; } else self->monsterinfo.currentmove = &ogre_move_run; } // // SPAWN // /*QUAKED monster_q1_ogre (1 .5 0) (-20 -20 -24) (20 20 32) Ambush Trigger_Spawn Sight GoodGuy NoGib model="models/monsters/q1ogre/tris.md2" */ void SP_monster_q1_ogre (edict_t *self) { if (deathmatch->value) { G_FreeEdict (self); return; } sound_pain = gi.soundindex ("q1ogre/ogpain1.wav"); sound_death = gi.soundindex ("q1ogre/ogdth.wav"); sound_gib = gi.soundindex ("q1player/udeath.wav"); sound_idle = gi.soundindex ("q1ogre/ogidle.wav"); sound_idle2 = gi.soundindex ("q1ogre/ogidle2.wav"); sound_wake = gi.soundindex ("q1ogre/ogwake.wav"); sound_shoot = gi.soundindex ("q1weapons/grenade.wav"); sound_saw = gi.soundindex ("q1ogre/ogsawatk.wav"); sound_drag = gi.soundindex ("q1ogre/ogdrag.wav"); // precache backpack gi.modelindex ("models/items/q1backpack/tris.md2"); // gi.soundindex ("q1weapons/lock4.wav"); // precache gibs gi.modelindex ("models/monsters/q1ogre/head/tris.md2"); gi.modelindex ("models/objects/q1gibs/q1gib1/tris.md2"); gi.modelindex ("models/objects/q1gibs/q1gib3/tris.md2"); // precache grenade q1_grenade_precache (); self->movetype = MOVETYPE_STEP; self->solid = SOLID_BBOX; // Lazarus: special purpose skins if ( self->style ) { PatchMonsterModel("models/monsters/q1ogre/tris.md2"); self->s.skinnum = self->style; } self->s.modelindex = gi.modelindex ("models/monsters/q1ogre/tris.md2"); VectorSet (self->mins, -20, -20, -24); //16 16 VectorSet (self->maxs, 20, 20, 32); //16 16 if (!self->health) self->health = 200; if (!self->gib_health) self->gib_health = -80; if (!self->mass) self->mass = 400; self->pain = ogre_pain; self->die = ogre_die; self->flags |= FL_Q1_MONSTER; self->monsterinfo.stand = ogre_stand; self->monsterinfo.walk = ogre_walk; self->monsterinfo.run = ogre_run; self->monsterinfo.dodge = NULL; self->monsterinfo.attack = ogre_attack; self->monsterinfo.melee = ogre_check_refire; self->monsterinfo.sight = ogre_sight; self->monsterinfo.search = ogre_stand; if (!self->monsterinfo.flies) self->monsterinfo.flies = 0.75; // Lazarus if (self->powerarmor) { if (self->powerarmortype == 1) self->monsterinfo.power_armor_type = POWER_ARMOR_SCREEN; else self->monsterinfo.power_armor_type = POWER_ARMOR_SHIELD; self->monsterinfo.power_armor_power = self->powerarmor; } self->common_name = "Ogre"; self->class_id = ENTITY_MONSTER_Q1_OGRE; gi.linkentity (self); self->monsterinfo.currentmove = &ogre_move_stand; if (self->health < 0) { mmove_t *deathmoves[] = {&ogre_move_death1, &ogre_move_death2, NULL}; M_SetDeath (self, (mmove_t **)&deathmoves); } self->monsterinfo.scale = MODEL_SCALE; walkmonster_start (self); }
0
0.797342
1
0.797342
game-dev
MEDIA
0.991062
game-dev
0.785043
1
0.785043
sergiobd/ViveTrackerUtilities
18,721
Assets/SteamVR/InteractionSystem/Core/Scripts/Util.cs
//======= Copyright (c) Valve Corporation, All rights reserved. =============== // // Purpose: Utility functions used in several places // //============================================================================= using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; namespace Valve.VR.InteractionSystem { //------------------------------------------------------------------------- public static class Util { public const float FeetToMeters = 0.3048f; public const float FeetToCentimeters = 30.48f; public const float InchesToMeters = 0.0254f; public const float InchesToCentimeters = 2.54f; public const float MetersToFeet = 3.28084f; public const float MetersToInches = 39.3701f; public const float CentimetersToFeet = 0.0328084f; public const float CentimetersToInches = 0.393701f; public const float KilometersToMiles = 0.621371f; public const float MilesToKilometers = 1.60934f; //------------------------------------------------- // Remap num from range 1 to range 2 //------------------------------------------------- public static float RemapNumber( float num, float low1, float high1, float low2, float high2 ) { return low2 + ( num - low1 ) * ( high2 - low2 ) / ( high1 - low1 ); } //------------------------------------------------- public static float RemapNumberClamped( float num, float low1, float high1, float low2, float high2 ) { return Mathf.Clamp( RemapNumber( num, low1, high1, low2, high2 ), Mathf.Min( low2, high2 ), Mathf.Max( low2, high2 ) ); } //------------------------------------------------- public static float Approach( float target, float value, float speed ) { float delta = target - value; if ( delta > speed ) value += speed; else if ( delta < -speed ) value -= speed; else value = target; return value; } //------------------------------------------------- public static Vector3 BezierInterpolate3( Vector3 p0, Vector3 c0, Vector3 p1, float t ) { Vector3 p0c0 = Vector3.Lerp( p0, c0, t ); Vector3 c0p1 = Vector3.Lerp( c0, p1, t ); return Vector3.Lerp( p0c0, c0p1, t ); } //------------------------------------------------- public static Vector3 BezierInterpolate4( Vector3 p0, Vector3 c0, Vector3 c1, Vector3 p1, float t ) { Vector3 p0c0 = Vector3.Lerp( p0, c0, t ); Vector3 c0c1 = Vector3.Lerp( c0, c1, t ); Vector3 c1p1 = Vector3.Lerp( c1, p1, t ); Vector3 x = Vector3.Lerp( p0c0, c0c1, t ); Vector3 y = Vector3.Lerp( c0c1, c1p1, t ); //Debug.DrawRay(p0, Vector3.forward); //Debug.DrawRay(c0, Vector3.forward); //Debug.DrawRay(c1, Vector3.forward); //Debug.DrawRay(p1, Vector3.forward); //Gizmos.DrawSphere(p0c0, 0.5F); //Gizmos.DrawSphere(c0c1, 0.5F); //Gizmos.DrawSphere(c1p1, 0.5F); //Gizmos.DrawSphere(x, 0.5F); //Gizmos.DrawSphere(y, 0.5F); return Vector3.Lerp( x, y, t ); } //------------------------------------------------- public static Vector3 Vector3FromString( string szString ) { string[] szParseString = szString.Substring( 1, szString.Length - 1 ).Split( ',' ); float x = float.Parse( szParseString[0] ); float y = float.Parse( szParseString[1] ); float z = float.Parse( szParseString[2] ); Vector3 vReturn = new Vector3( x, y, z ); return vReturn; } //------------------------------------------------- public static Vector2 Vector2FromString( string szString ) { string[] szParseString = szString.Substring( 1, szString.Length - 1 ).Split( ',' ); float x = float.Parse( szParseString[0] ); float y = float.Parse( szParseString[1] ); Vector3 vReturn = new Vector2( x, y ); return vReturn; } //------------------------------------------------- public static float Normalize( float value, float min, float max ) { float normalizedValue = ( value - min ) / ( max - min ); return normalizedValue; } //------------------------------------------------- public static Vector3 Vector2AsVector3( Vector2 v ) { return new Vector3( v.x, 0.0f, v.y ); } //------------------------------------------------- public static Vector2 Vector3AsVector2( Vector3 v ) { return new Vector2( v.x, v.z ); } //------------------------------------------------- public static float AngleOf( Vector2 v ) { float fDist = v.magnitude; if ( v.y >= 0.0f ) { return Mathf.Acos( v.x / fDist ); } else { return Mathf.Acos( -v.x / fDist ) + Mathf.PI; } } //------------------------------------------------- public static float YawOf( Vector3 v ) { float fDist = v.magnitude; if ( v.z >= 0.0f ) { return Mathf.Acos( v.x / fDist ); } else { return Mathf.Acos( -v.x / fDist ) + Mathf.PI; } } //------------------------------------------------- public static void Swap<T>( ref T lhs, ref T rhs ) { T temp = lhs; lhs = rhs; rhs = temp; } //------------------------------------------------- public static void Shuffle<T>( T[] array ) { for ( int i = array.Length - 1; i > 0; i-- ) { int r = UnityEngine.Random.Range( 0, i ); Swap( ref array[i], ref array[r] ); } } //------------------------------------------------- public static void Shuffle<T>( List<T> list ) { for ( int i = list.Count - 1; i > 0; i-- ) { int r = UnityEngine.Random.Range( 0, i ); T temp = list[i]; list[i] = list[r]; list[r] = temp; } } //------------------------------------------------- public static int RandomWithLookback( int min, int max, List<int> history, int historyCount ) { int index = UnityEngine.Random.Range( min, max - history.Count ); for ( int i = 0; i < history.Count; i++ ) { if ( index >= history[i] ) { index++; } } history.Add( index ); if ( history.Count > historyCount ) { history.RemoveRange( 0, history.Count - historyCount ); } return index; } //------------------------------------------------- public static Transform FindChild( Transform parent, string name ) { if ( parent.name == name ) return parent; foreach ( Transform child in parent ) { var found = FindChild( child, name ); if ( found != null ) return found; } return null; } //------------------------------------------------- public static bool IsNullOrEmpty<T>( T[] array ) { if ( array == null ) return true; if ( array.Length == 0 ) return true; return false; } //------------------------------------------------- public static bool IsValidIndex<T>( T[] array, int i ) { if ( array == null ) return false; return ( i >= 0 ) && ( i < array.Length ); } //------------------------------------------------- public static bool IsValidIndex<T>( List<T> list, int i ) { if ( list == null || list.Count == 0 ) return false; return ( i >= 0 ) && ( i < list.Count ); } //------------------------------------------------- public static int FindOrAdd<T>( List<T> list, T item ) { int index = list.IndexOf( item ); if ( index == -1 ) { list.Add( item ); index = list.Count - 1; } return index; } //------------------------------------------------- public static List<T> FindAndRemove<T>( List<T> list, System.Predicate<T> match ) { List<T> retVal = list.FindAll( match ); list.RemoveAll( match ); return retVal; } //------------------------------------------------- public static T FindOrAddComponent<T>( GameObject gameObject ) where T : Component { T component = gameObject.GetComponent<T>(); if ( component ) return component; return gameObject.AddComponent<T>(); } //------------------------------------------------- public static void FastRemove<T>( List<T> list, int index ) { list[index] = list[list.Count - 1]; list.RemoveAt( list.Count - 1 ); } //------------------------------------------------- public static void ReplaceGameObject<T, U>( T replace, U replaceWith ) where T : MonoBehaviour where U : MonoBehaviour { replace.gameObject.SetActive( false ); replaceWith.gameObject.SetActive( true ); } //------------------------------------------------- public static void SwitchLayerRecursively( Transform transform, int fromLayer, int toLayer ) { if ( transform.gameObject.layer == fromLayer ) transform.gameObject.layer = toLayer; int childCount = transform.childCount; for ( int i = 0; i < childCount; i++ ) { SwitchLayerRecursively( transform.GetChild( i ), fromLayer, toLayer ); } } //------------------------------------------------- public static void DrawCross( Vector3 origin, Color crossColor, float size ) { Vector3 line1Start = origin + ( Vector3.right * size ); Vector3 line1End = origin - ( Vector3.right * size ); Debug.DrawLine( line1Start, line1End, crossColor ); Vector3 line2Start = origin + ( Vector3.up * size ); Vector3 line2End = origin - ( Vector3.up * size ); Debug.DrawLine( line2Start, line2End, crossColor ); Vector3 line3Start = origin + ( Vector3.forward * size ); Vector3 line3End = origin - ( Vector3.forward * size ); Debug.DrawLine( line3Start, line3End, crossColor ); } //------------------------------------------------- public static void ResetTransform( Transform t, bool resetScale = true ) { t.localPosition = Vector3.zero; t.localRotation = Quaternion.identity; if ( resetScale ) { t.localScale = new Vector3( 1f, 1f, 1f ); } } //------------------------------------------------- public static Vector3 ClosestPointOnLine( Vector3 vA, Vector3 vB, Vector3 vPoint ) { var vVector1 = vPoint - vA; var vVector2 = ( vB - vA ).normalized; var d = Vector3.Distance( vA, vB ); var t = Vector3.Dot( vVector2, vVector1 ); if ( t <= 0 ) return vA; if ( t >= d ) return vB; var vVector3 = vVector2 * t; var vClosestPoint = vA + vVector3; return vClosestPoint; } //------------------------------------------------- public static void AfterTimer( GameObject go, float _time, System.Action callback, bool trigger_if_destroyed_early = false ) { AfterTimer_Component afterTimer_component = go.AddComponent<AfterTimer_Component>(); afterTimer_component.Init( _time, callback, trigger_if_destroyed_early ); } //------------------------------------------------- public static void SendPhysicsMessage( Collider collider, string message, SendMessageOptions sendMessageOptions ) { Rigidbody rb = collider.attachedRigidbody; if ( rb && rb.gameObject != collider.gameObject ) { rb.SendMessage( message, sendMessageOptions ); } collider.SendMessage( message, sendMessageOptions ); } //------------------------------------------------- public static void SendPhysicsMessage( Collider collider, string message, object arg, SendMessageOptions sendMessageOptions ) { Rigidbody rb = collider.attachedRigidbody; if ( rb && rb.gameObject != collider.gameObject ) { rb.SendMessage( message, arg, sendMessageOptions ); } collider.SendMessage( message, arg, sendMessageOptions ); } //------------------------------------------------- public static void IgnoreCollisions( GameObject goA, GameObject goB ) { Collider[] goA_colliders = goA.GetComponentsInChildren<Collider>(); Collider[] goB_colliders = goB.GetComponentsInChildren<Collider>(); if ( goA_colliders.Length == 0 || goB_colliders.Length == 0 ) { return; } foreach ( Collider cA in goA_colliders ) { foreach ( Collider cB in goB_colliders ) { if ( cA.enabled && cB.enabled ) { Physics.IgnoreCollision( cA, cB, true ); } } } } //------------------------------------------------- public static IEnumerator WrapCoroutine( IEnumerator coroutine, System.Action onCoroutineFinished ) { while ( coroutine.MoveNext() ) { yield return coroutine.Current; } onCoroutineFinished(); } //------------------------------------------------- public static Color ColorWithAlpha( this Color color, float alpha ) { color.a = alpha; return color; } //------------------------------------------------- // Exits the application if running standalone, or stops playback if running in the editor. //------------------------------------------------- public static void Quit() { #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #else // NOTE: The recommended call for exiting a Unity app is UnityEngine.Application.Quit(), but as // of 5.1.0f3 this was causing the application to crash. The following works without crashing: System.Diagnostics.Process.GetCurrentProcess().Kill(); #endif } //------------------------------------------------- // Truncate floats to the specified # of decimal places when you want easier-to-read numbers without clamping to an int //------------------------------------------------- public static decimal FloatToDecimal( float value, int decimalPlaces = 2 ) { return Math.Round( (decimal)value, decimalPlaces ); } //------------------------------------------------- public static T Median<T>( this IEnumerable<T> source ) { if ( source == null ) { throw new ArgumentException( "Argument cannot be null.", "source" ); } int count = source.Count(); if ( count == 0 ) { throw new InvalidOperationException( "Enumerable must contain at least one element." ); } return source.OrderBy( x => x ).ElementAt( count / 2 ); } //------------------------------------------------- public static void ForEach<T>( this IEnumerable<T> source, Action<T> action ) { if ( source == null ) { throw new ArgumentException( "Argument cannot be null.", "source" ); } foreach ( T value in source ) { action( value ); } } //------------------------------------------------- // In some cases Unity/C# don't correctly interpret the newline control character (\n). // This function replaces every instance of "\\n" with the actual newline control character. //------------------------------------------------- public static string FixupNewlines( string text ) { bool newLinesRemaining = true; while ( newLinesRemaining ) { int CIndex = text.IndexOf( "\\n" ); if ( CIndex == -1 ) { newLinesRemaining = false; } else { text = text.Remove( CIndex - 1, 3 ); text = text.Insert( CIndex - 1, "\n" ); } } return text; } //------------------------------------------------- #if ( UNITY_5_4 ) public static float PathLength( NavMeshPath path ) #else public static float PathLength( UnityEngine.AI.NavMeshPath path ) #endif { if ( path.corners.Length < 2 ) return 0; Vector3 previousCorner = path.corners[0]; float lengthSoFar = 0.0f; int i = 1; while ( i < path.corners.Length ) { Vector3 currentCorner = path.corners[i]; lengthSoFar += Vector3.Distance( previousCorner, currentCorner ); previousCorner = currentCorner; i++; } return lengthSoFar; } //------------------------------------------------- public static bool HasCommandLineArgument( string argumentName ) { string[] args = System.Environment.GetCommandLineArgs(); for ( int i = 0; i < args.Length; i++ ) { if ( args[i].Equals( argumentName ) ) { return true; } } return false; } //------------------------------------------------- public static int GetCommandLineArgValue( string argumentName, int nDefaultValue ) { string[] args = System.Environment.GetCommandLineArgs(); for ( int i = 0; i < args.Length; i++ ) { if ( args[i].Equals( argumentName ) ) { if ( i == ( args.Length - 1 ) ) // Last arg, return default { return nDefaultValue; } return System.Int32.Parse( args[i + 1] ); } } return nDefaultValue; } //------------------------------------------------- public static float GetCommandLineArgValue( string argumentName, float flDefaultValue ) { string[] args = System.Environment.GetCommandLineArgs(); for ( int i = 0; i < args.Length; i++ ) { if ( args[i].Equals( argumentName ) ) { if ( i == ( args.Length - 1 ) ) // Last arg, return default { return flDefaultValue; } return (float)Double.Parse( args[i + 1] ); } } return flDefaultValue; } //------------------------------------------------- public static void SetActive( GameObject gameObject, bool active ) { if ( gameObject != null ) { gameObject.SetActive( active ); } } //------------------------------------------------- // The version of Path.Combine() included with Unity can only combine two paths. // This version mimics the modern .NET version, which allows for any number of // paths to be combined. //------------------------------------------------- public static string CombinePaths( params string[] paths ) { if ( paths.Length == 0 ) { return ""; } else { string combinedPath = paths[0]; for ( int i = 1; i < paths.Length; i++ ) { combinedPath = Path.Combine( combinedPath, paths[i] ); } return combinedPath; } } } //------------------------------------------------------------------------- //Component used by the static AfterTimer function //------------------------------------------------------------------------- [System.Serializable] public class AfterTimer_Component : MonoBehaviour { private System.Action callback; private float triggerTime; private bool timerActive = false; private bool triggerOnEarlyDestroy = false; //------------------------------------------------- public void Init( float _time, System.Action _callback, bool earlydestroy ) { triggerTime = _time; callback = _callback; triggerOnEarlyDestroy = earlydestroy; timerActive = true; StartCoroutine( Wait() ); } //------------------------------------------------- private IEnumerator Wait() { yield return new WaitForSeconds( triggerTime ); timerActive = false; callback.Invoke(); Destroy( this ); } //------------------------------------------------- void OnDestroy() { if ( timerActive ) { //If the component or its GameObject get destroyed before the timer is complete, clean up StopCoroutine( Wait() ); timerActive = false; if ( triggerOnEarlyDestroy ) { callback.Invoke(); } } } } }
0
0.825343
1
0.825343
game-dev
MEDIA
0.810742
game-dev,graphics-rendering
0.939345
1
0.939345
hawkthorne/hawkthorne-journey
38,493
src/inventory.lua
----------------------------------------------------------------------- -- inventory.lua -- Manages the player's currently held items ----------------------------------------------------------------------- local app = require 'app' local anim8 = require 'vendor/anim8' local sound = require 'vendor/TEsound' local camera = require 'camera' local debugger = require 'debugger' local json = require 'hawk/json' local GS = require 'vendor/gamestate' local fonts = require 'fonts' local utils = require 'utils' local recipes = require 'items/recipes' local tooltip = require 'tooltip' local Item = require 'items/item' local controls = require('inputcontroller').get() local Inventory = {} Inventory.__index = Inventory --Load in all the sprites we're going to be using. local sprite = love.graphics.newImage('images/inventory/inventory.png') local scrollSprite = love.graphics.newImage('images/inventory/scrollbar.png') local selectionSprite = love.graphics.newImage('images/inventory/selectionBadge.png') local selectionCraftingSprite = love.graphics.newImage('images/inventory/selectioncraftingannex.png') local curWeaponSelect = love.graphics.newImage('images/inventory/selectedweapon.png') local craftingAnnexSprite = love.graphics.newImage('images/inventory/craftingannex.png') craftingAnnexSprite:setFilter('nearest', 'nearest') selectionSprite:setFilter('nearest', 'nearest') sprite:setFilter('nearest', 'nearest') scrollSprite:setFilter('nearest','nearest') --The animation grids for different animations. local animGrid = anim8.newGrid(100, 125, sprite:getDimensions()) local scrollGrid = anim8.newGrid(5,40, scrollSprite:getDimensions()) local craftingGrid = anim8.newGrid(75, 29, craftingAnnexSprite:getDimensions()) --- -- Creates a new inventory -- @return inventory function Inventory.new( player ) local inventory = {} setmetatable(inventory, Inventory) inventory.player = player inventory.tooltip = tooltip:new() --These variables keep track of whether the inventory is open, and whether the crafting annex is open. inventory.visible = false inventory.craftingVisible = false --These flags keep track of whether certain keys were down the last time we checked. This is necessary to only do actions once when the player presses something. inventory.openKeyWasDown = false inventory.rightKeyWasDown = false inventory.leftKeyWasDown = false inventory.upKeyWasDown = false inventory.downKeyWasDown = false inventory.selectKeyWasDown = false inventory.tooltipAnnexKeyWasDown = false inventory.pageList = { consumables = {'materials','details'}, materials = {'weapons','consumables'}, weapons = {'scrolls','materials'}, scrolls = {'armors','weapons'}, armors = {'keys', 'scrolls'}, keys = {'details','armors'}, details = {'consumables','keys'}, } --Each key's value is a table with this format: {nextpage, previouspage} inventory.pages = {} --These are the pages in the inventory that hold items for i in pairs(inventory.pageList) do inventory.pages[i] = {} end inventory.currentPageName = 'materials' --Initial inventory page inventory.cursorPos = {x=0,y=0} --The position of the cursor. inventory.selectedWeaponIndex = 1 --The index of the item on the weapons page that is selected as the current weapon. inventory.selectedArmorIndices = {primary = -1, secondary = -1} inventory.animState = 'closed' --The current animation state. --These are all the different states of the crafting box and their respective animations. inventory.animations = { opening = anim8.newAnimation('once', animGrid('1-5,1'),0.05), --The box is currently opening open = anim8.newAnimation('once', animGrid('6,1'), 1), --The box is open. closing = anim8.newAnimation('once', animGrid('1-5,1'),0.02), --The box is currently closing. closed = anim8.newAnimation('once', animGrid('1,1'),1) --The box is fully closed. Strictly speaking, this animation is not necessary as the box is invisible when in this state. } inventory.animations['closing'].direction = -1 --Sort of a hack, these two lines allow the closing animation to be the same as the opening animation, but reversed. inventory.animations['closing'].position = 5 inventory.scrollAnimations = { anim8.newAnimation('once', scrollGrid('1,1'),1), anim8.newAnimation('once', scrollGrid('2,1'),1), anim8.newAnimation('once', scrollGrid('3,1'),1), anim8.newAnimation('once', scrollGrid('4,1'),1) } --The animations for the scroll bar. inventory.scrollbar = 1 inventory.pageLength = 14 --This is all pretty much identical to the corresponding lines for the main inventory, but applies to the crafting annex. inventory.craftingState = 'closing' inventory.craftingAnimations = { opening = anim8.newAnimation('once', craftingGrid('1-6,1'),0.04), open = anim8.newAnimation('once', craftingGrid('6,1'), 1), closing = anim8.newAnimation('once', craftingGrid('1-6,1'),0.06) } inventory.craftingAnimations['closing'].direction = -1 inventory.craftingAnimations['closing'].position = 6 inventory.currentIngredients = {a = nil, b = nil} --The index of the currently selected ingredients. Equivalent to {}, but here for clarity. return inventory end --- -- Updates the inventory with player input -- @param dt the delta time for updating the animation. -- @return nil function Inventory:update( dt ) if not self.visible then return end --Update the animations self:animation():update(dt) self:craftingAnimation():update(dt) self:animUpdate() end --- -- Finishes animations -- @return nil function Inventory:animUpdate() --If we're finished with an animation, then in some cases that means we should move to the next one. if self:animation().status == "finished" then if self.animState == "closing" then self:animation():gotoFrame(5) self:animation():pause() self.visible = false self.animState = 'closed' self.cursorPos = {x=0,y=0} self.scrollbar = 1 self.player.freeze = false elseif self.animState == "opening" then self:animation():gotoFrame(1) self:animation():pause() self.animState = 'open' end end if self:craftingAnimation().status == "finished" then if self.craftingState == "closing" then self:craftingAnimation():gotoFrame(5) self:craftingAnimation():pause() self.craftingVisible = false elseif self.craftingState == "opening" then self:craftingAnimation():gotoFrame(1) self:craftingAnimation():pause() self.craftingState = "open" end end end --- -- Gets the inventory's animation -- @return animation function Inventory:animation() assert(self.animations[self.animState], "State " .. self.animState .. " does not have a corresponding animation!") return self.animations[self.animState] end --- -- Gets the crafting annex's animation -- @return the crafting annex's animation function Inventory:craftingAnimation() return self.craftingAnimations[self.craftingState] end --- -- Draws the inventory to the screen -- @param playerPosition the coordinates to draw offset from -- @return nil function Inventory:draw( playerPosition ) if not self.visible then return end --The default position of the inventory local pos = {x=playerPosition.x - (animGrid.frameWidth + 6),y=playerPosition.y - (animGrid.frameHeight - 22)} --Adjust the default position to be on the screen, and off the HUD. local hud_right = camera.x + 130 local hud_top = camera.y + 60 if pos.x < 0 then pos.x = playerPosition.x + --[[width of player--]] 48 + 6 end if pos.x < hud_right and pos.y < hud_top then pos.y = hud_top end if pos.y < 0 then pos.y = 0 end --Draw the main body of the inventory screen self:animation():draw(sprite, pos.x, pos.y) --Only draw other elements if the inventory is fully open if (self:isOpen()) then --Draw the name of the window fonts.set('small') love.graphics.print('Item', pos.x + 9, pos.y + 8) if self.currentPageName ~= 'armors' then love.graphics.print(self.currentPageName:gsub("^%l", string.upper), pos.x + 18, pos.y + 21, 0, 0.9, 0.9) else love.graphics.print('armor', pos.x + 18, pos.y + 21, 0, 0.9, 0.9) end if self:currentPage()[self:slotIndex(self.cursorPos)] then local jump = controls:getKey("JUMP") tastyjump = fonts.tasty.new('press {{peach}}' .. jump .. '{{white}} to view information', pos.x + 9, pos.y + 103, 90, love.graphics.getFont(), fonts.colors) tastyjump:draw() end --Draw the crafting annex, if it's open if self.craftingVisible then self:craftingAnimation():draw(craftingAnnexSprite, pos.x + 97, pos.y + 42) end --Draw the scroll bar self.scrollAnimations[self.scrollbar]:draw(scrollSprite, pos.x + 8, pos.y + 43) --Stands for first frame position, indicates the position of the first item slot (top left) on screen local ffPos = {x=pos.x + 29,y=pos.y + 30} --Draw the white border around the currently selected slot if self.cursorPos.x < 2 then --If the cursor is in the main inventory section, draw this way love.graphics.draw(selectionSprite, love.graphics.newQuad(0,0,selectionSprite:getWidth(),selectionSprite:getHeight(),selectionSprite:getWidth(),selectionSprite:getHeight()), (ffPos.x-17) + self.cursorPos.x * 38, ffPos.y + self.cursorPos.y * 18) else --Otherwise, we're in the crafting annex, so draw this way. love.graphics.draw(selectionCraftingSprite, love.graphics.newQuad(0,0,selectionCraftingSprite:getWidth(), selectionCraftingSprite:getHeight(), selectionCraftingSprite:getWidth(), selectionCraftingSprite:getHeight()), ffPos.x + (self.cursorPos.x - 3) * 19 + 101, ffPos.y + 18) end --Draw all the items in their respective slots for i=0,7 do local scrollIndex = i + ((self.scrollbar - 1) * 2) + 1 local indexDisplay = debugger.on and scrollIndex or nil if self:currentPage()[scrollIndex] then local slotPos = self:slotPosition(i) local item = self:currentPage()[scrollIndex] if self.currentIngredients.a ~= scrollIndex and self.currentIngredients.b ~= scrollIndex then item:draw({x=slotPos.x+ffPos.x,y=slotPos.y + ffPos.y}, indexDisplay) end end end --Draw the crafting window if self.craftingVisible then if self.currentIngredients.a then local item = self.currentIngredients.a item:draw({x=ffPos.x + 102,y= ffPos.y + 19}) end if self.currentIngredients.b then local item = self.currentIngredients.b item:draw({x=ffPos.x + 121,y= ffPos.y + 19}) end --Draw the result of a valid recipe if self.currentIngredients.a and self.currentIngredients.b then local result = self:findResult(self.currentIngredients.a, self.currentIngredients.b) if result then local resultFolder = string.lower(result.type)..'s' local itemNode = require ('items/' .. resultFolder .. '/' .. result.name) -- this ugly hack shouldn't be necessary, but for whatever reason -- the type can be overriden by the subtype of the item, so we set type by directory instead if itemNode.directory == 'weapons/' then itemNode.type = 'weapon' end local item = Item.new(itemNode) item:draw({x=ffPos.x + 83, y=ffPos.y + 19}) end end end --Draw the tooltip window if self.tooltip.visible and self:currentPage()[self:slotIndex(self.cursorPos)] and not self.craftingVisible then local slotIndex = self:slotIndex(self.cursorPos) local item = nil if self.cursorPos.x < 2 then item = self.pages[self.currentPageName][slotIndex] --TODO: add tooltip back in for crafting annex --[[ elseif self.cursorPos.x == 2 and self.currentIngredients.a and self.currentIngredients.b then local result = self:findResult(self.currentIngredients.a, self.currentIngredients.b) if result then item = require ('items/' .. result.type .. 's/' .. result.name) end elseif self.cursorPos.x == 3 and self.currentIngredients.a then item = require ('items/' .. self.currentIngredients.a.type .. 's/' .. self.currentIngredients.a.name) elseif self.cursorPos.x == 4 and self.currentIngredients.b then item = require ('items/' .. self.currentIngredients.b.type .. 's/' .. self.currentIngredients.b.name) ]]-- else return end self.tooltip:draw(pos.x + 100, pos.y, item, "inventory") end --If we're on the weapons screen, then draw a green border around the currently selected index, unless it's out of view. if self.currentPageName == 'weapons' and self.selectedWeaponIndex <= self.pageLength then local lowestVisibleIndex = (self.scrollbar - 1 )* 2 + 1 local weaponPosition = self.selectedWeaponIndex - lowestVisibleIndex if self.selectedWeaponIndex >= lowestVisibleIndex and self.selectedWeaponIndex < lowestVisibleIndex + 8 then love.graphics.draw(curWeaponSelect, love.graphics.newQuad(0,0, curWeaponSelect:getWidth(), curWeaponSelect:getHeight(), curWeaponSelect:getWidth(), curWeaponSelect:getHeight()), self:slotPosition(weaponPosition).x + ffPos.x - 2, self:slotPosition(weaponPosition).y + ffPos.y - 2) end end if self.currentPageName == 'scrolls' and self.selectedWeaponIndex >= self.pageLength then local lowestVisibleIndex = (self.scrollbar - 1 )* 2 + 1 local index = self.selectedWeaponIndex - self.pageLength local scrollPosition = index - lowestVisibleIndex if index >= lowestVisibleIndex and index < lowestVisibleIndex + 8 then love.graphics.draw(curWeaponSelect, love.graphics.newQuad(0,0, curWeaponSelect:getWidth(), curWeaponSelect:getHeight(), curWeaponSelect:getWidth(), curWeaponSelect:getHeight()), self:slotPosition(scrollPosition).x + ffPos.x - 2, self:slotPosition(scrollPosition).y + ffPos.y - 2) end end for key, index in pairs(self.selectedArmorIndices) do if self.currentPageName == 'armors' and index <= self.pageLength then local lowestVisibleIndex = (self.scrollbar - 1 )* 2 + 1 local armorPosition = index - lowestVisibleIndex if index >= lowestVisibleIndex and index < lowestVisibleIndex + 8 then love.graphics.draw(curWeaponSelect, love.graphics.newQuad(0,0, curWeaponSelect:getWidth(), curWeaponSelect:getHeight(), curWeaponSelect:getWidth(), curWeaponSelect:getHeight()), self:slotPosition(armorPosition).x + ffPos.x - 2, self:slotPosition(armorPosition).y + ffPos.y - 2) end end end end fonts.revert() -- Changes back to old font end --- -- Compiles item stats as string -- @return item stats as string function Inventory:getItemStats( item ) local itemStats = "" if item.subtype ~= nil and item.subtype ~= "item" then itemStats = itemStats .. "{{white}}\ntype: {{teal}}" .. item.subtype end if item.damage ~= nil and item.damage ~= "nil" then itemStats = itemStats .. "{{white}}\ndamage: {{red}}" .. tostring(item.damage) end if item.defense ~= nil and item.defense ~= "nil" then itemStats = itemStats .. "{{white}}\ndefense: {{blue_light}}" .. tostring(item.defense) end if item.special_damage ~= nil and item.special_damage ~= "nil" then itemStats = itemStats .. "{{white}}\nspecial: {{red}}" .. item.special_damage end return itemStats end --- -- Handles player input while in the inventory -- @return nil function Inventory:keypressed( button ) local keys = { UP = self.up, DOWN = self.down, RIGHT = self.right, LEFT = self.left, SELECT = self.close, START = self.close, INTERACT = self.drop, ATTACK = self.select, JUMP = self.tooltipAnnex } if self:isOpen() and keys[button] then keys[button](self) end end --- -- Opens the inventory. -- @return nil function Inventory:open() self.player.controlState:inventory() self.visible = true self.animState = 'opening' self:animation():resume() end --- -- Opens the crafting annex -- @return nil function Inventory:craftingOpen() self.craftingVisible = true self.craftingState = 'opening' self:craftingAnimation():resume() end -- Opens the tooltip annex -- @return nil function Inventory:tooltipAnnexOpen() if self:currentPage()[self:slotIndex(self.cursorPos)] then self.tooltip:open() end end --- -- Determines whether the inventory is currently open -- @return bool function Inventory:isOpen() return self.animState == 'open' end --- -- Begins closing the players inventory -- @return nil function Inventory:close() self.player.controlState:standard() self:craftingClose() self.tooltip:shut() self.pageNext = self.animState self.animState = 'closing' self:animation():resume() end --- -- Begins closing the crafting annex -- @return nil function Inventory:craftingClose() self.craftingState = 'closing' self:craftingAnimation():resume() if self.currentIngredients.a then self:addItem(self.currentIngredients.a, false) end if self.currentIngredients.b then self:addItem(self.currentIngredients.b, false) end self.currentIngredients = {} end --- -- Moves the cursor right -- @return nil function Inventory:right() if self.cursorPos.x > 1 then self.cursorPos.y = 1 end local maxX = self.craftingVisible and 4 or 1 if self.cursorPos.x < maxX then self.cursorPos.x = self.cursorPos.x + 1 else self:switchPage(1) self.cursorPos.x = 0 end end --- -- Moves the cursor left -- @return nil function Inventory:left() if self.cursorPos.x > 1 then self.cursorPos.y = 1 end if self.cursorPos.x > 0 then self.cursorPos.x = self.cursorPos.x - 1 else self:switchPage(2) self.cursorPos.x = 1 end end --- -- Switches inventory pages -- @param direction 1 or 2 for next or previous page respectively -- @return nil function Inventory:switchPage( direction ) self:craftingClose() self.tooltip:shut() self.scrollbar = 1 local nextState = self.pageList[self.currentPageName][direction] assert(nextState, 'Inventory page switch error') self.currentPageName = nextState end --- -- Moves the cursor up -- @return nil function Inventory:up() if self.cursorPos.y == 0 then if self.scrollbar > 1 then self.scrollbar = self.scrollbar - 1 end return end self.cursorPos.y = self.cursorPos.y - 1 end --- -- Moves the cursor down -- @return nil function Inventory:down() if self.cursorPos.y == 3 then if self.scrollbar < 4 then self.scrollbar = self.scrollbar + 1 end return end self.cursorPos.y = self.cursorPos.y + 1 end --- -- Called when any items are added or removed from the player inventory -- @return nil function Inventory:changeItem() -- Check player inventory against all NPCs in the current level local level = GS.currentState() if level.nodes then for _,npc in pairs(level.nodes) do if npc.type == 'npc' then npc:checkInventory(self.player) end end end end function Inventory:dropItem(item, slotIndex, page) local level = GS.currentState() local itemProps = item.props if (itemProps.subtype == 'projectile' or itemProps.subtype == 'ammo') and item.type ~= 'scroll' then itemProps.type = 'projectile' itemProps.directory = 'weapons/' elseif item.type == 'scroll' then itemProps.type = tostring(item.type) itemProps.directory = tostring(item.type) .. 's/' end -- Don't show any box if the item is dropped if self.selectedArmorIndices[itemProps.subtype] == slotIndex then self.selectedArmorIndices[itemProps.subtype] = -1 self.player:selectArmor({defense = 0, subtype = itemProps.subtype}) end local NodeClass = require('/nodes/' .. itemProps.type) itemProps.width = itemProps.width or item.image:getWidth() itemProps.height = itemProps.height or item.image:getHeight() - 15 itemProps.x = self.player.position.x itemProps.y = self.player.position.y + (24 - itemProps.height) itemProps.properties = {foreground = false} local myNewNode = NodeClass.new(itemProps, level.collider) myNewNode.type = itemProps.type if myNewNode then -- Must set the quantity after creating the Node. myNewNode.quantity = item.quantity or 1 assert(myNewNode.draw, 'ERROR: ' .. myNewNode.name .. ' does not have a draw function!') level:addNode(myNewNode) assert(level:hasNode(myNewNode), 'ERROR: Drop function did not properly add ' .. myNewNode.name .. ' to the level!')--]] self:removeItem(slotIndex, page) if myNewNode.drop then myNewNode:drop(self.player) -- Throws the weapon when dropping it -- velocity.x is based off direction -- velocity.y is constant from being thrown upwards myNewNode.velocity = {x = (self.player.character.direction == 'left' and -1 or 1) * 100, y = -200, } end end end --- -- Drops the currently selected item and adds a node at the player's position. -- @return nil function Inventory:drop() if self.craftingState == 'open' or self.currentPageName == 'keys' then return end --Ignore dropping in the crafting annex and on the keys page. local slotIndex = self:slotIndex(self.cursorPos) if self.pages[self.currentPageName][slotIndex] then local item = self.pages[self.currentPageName][slotIndex] if item.name == 'quest' then return end -- Can't drop quests self:dropItem(item, slotIndex, self.currentPageName) sound.playSfx('click') end self:changeItem() end --- -- Adds an item to the player's inventory -- @param item the item to add -- @param sfx optional bool that toggles the 'pickup' sound -- @return bool representing successful add function Inventory:addItem(item, sfx, callback) local pageName = item.type .. 's' assert(self.pages[pageName], "Bad Item type! " .. item.type .. " is not a valid item type.") if self:tryMerge(item) then if sfx ~= false then sound.playSfx('pickup') end if callback then callback() end return true --If we had a complete successful merge with no remainders, there is no reason to add the item. end local slot = self:nextAvailableSlot(pageName) if not slot then if sfx ~= false then sound.playSfx('dbl_beep') end return false end self.pages[pageName][slot] = item if sfx ~= false then sound.playSfx('pickup') end self:changeItem() if callback then callback() end return true end --- -- Removes the item in the given slot -- @parameter slotIndex the index of the slot to remove from -- @parameter pageName the page where the item resides -- @return nil function Inventory:removeItem( slotIndex, pageName ) local item = self.pages[pageName][slotIndex] if self.player.currently_held and item and self.player.currently_held.name == item.name then self.player.currently_held:deselect() end self.pages[pageName][slotIndex] = nil self:changeItem() end --- -- Drops all inventory items -- @return nil function Inventory:dropAllItems() for page in pairs(self.pages) do for k,v in pairs(self.pages[page]) do self:dropItem(v, k, page) end end self:changeItem() end --- -- Removes all inventory items -- @return nil function Inventory:removeAllItems() for page in pairs(self.pages) do self.pages[page] = {} end self:changeItem() end --- -- Removes a certain amount of items from the player -- @parameter amount amount to remove -- @parameter itemToRemove the item to remove, for example: {name="bone", type="material"} -- @return nil function Inventory:removeManyItems(amount, itemToRemove) if amount == 0 then return end local count = self:count(itemToRemove) if amount > count then amount = count end for i = 1, amount do playerItem, pageIndex, slotIndex = self:search(itemToRemove) if self.pages[pageIndex][slotIndex].quantity > 1 then playerItem.quantity = playerItem.quantity - 1 elseif self.pages[pageIndex][slotIndex].quantity == 1 then self:removeItem(slotIndex, pageIndex) end end self:changeItem() end --- -- Finds the first available slot on the page. -- @param pageName the page to search -- @return index of first available inventory slot in pageName or nil if none available function Inventory:nextAvailableSlot( pageName ) local currentPage = self.pages[pageName] for i=1, self.pageLength do if currentPage[i] == nil then return i end end end --- -- Gets the position of a slot relative to the top left of the first slot -- @param slotIndex the index of the slot to find the position of -- @return the slot's x/y coordinates relative to ffPos function Inventory:slotPosition( slotIndex ) yPos = math.floor(slotIndex / 2) * 18 + 1 xPos = slotIndex % 2 * 38 + 1 return {x = xPos, y = yPos} end --- -- Gets the current page -- @return the current page function Inventory:currentPage() assert(self:isOpen(), "Inventory is closed, you cannot get the current page when inventory is closed.") local page = self.pages[self.currentPageName] assert(page, "Could not find page ".. self.currentPageName) return page end --- -- Searches the inventory for a key -- @return true if the player has the key or a 'master' key, else nil function Inventory:hasKey( keyName ) for slot,key in pairs(self.pages.keys) do if key.name == keyName or key.name == "master" then return true end end end function Inventory:hasDetail(detailName) for slot,detail in pairs(self.pages.details) do if detail.name == detailName then return true end end end function Inventory:hasMaterial( materialName ) for slot,material in pairs(self.pages.materials) do if material.name == materialName then return true end end end function Inventory:hasConsumable( consumableName ) for slot,consumable in pairs(self.pages.consumables) do if consumable.name == consumableName then return true end end end function Inventory:hasWeapon( weaponName ) for slot,weapon in pairs(self.pages.weapons) do if weapon.name == weaponName then return true end end end function Inventory:hasArmor( armorName ) for slot,armor in pairs(self.pages.armors) do if armor.name == armorName then return true end end end --- -- Gets the currently selected weapon -- @return the currently selected weapon function Inventory:currentWeapon() if self.selectedWeaponIndex <= self.pageLength then local selectedWeapon = self.pages.weapons[self.selectedWeaponIndex] return selectedWeapon elseif self.selectedWeaponIndex > self.pageLength then local selectedWeapon = self.pages.scrolls[self.selectedWeaponIndex - self.pageLength] return selectedWeapon end end --- -- Gets the index of a given cursor position -- @return the slot index corresponding to the position function Inventory:slotIndex( slotPosition ) return slotPosition.x + ((slotPosition.y + self.scrollbar - 1) * 2) + 1 end --- -- Handles the player selecting a slot in their inventory -- @return nil function Inventory:select() if self.currentPageName == 'weapons' then self:selectCurrentWeaponSlot() end if self.currentPageName == 'scrolls' then self:selectCurrentScrollSlot() end if self.currentPageName == 'armors' then self:selectCurrentArmorSlot() end if self.currentPageName == 'consumables' then self:consumeCurrentSlot() end if self.currentPageName == 'materials' then self:craftCurrentSlot() end end --- -- Handles the player selecting a slot in their inventory -- @return nil function Inventory:tooltipAnnex() if self.tooltip.visible then self.tooltip:shut() else self.tooltip:open() end end --- -- Selects the current slot as the selected weapon -- @return nil function Inventory:selectCurrentWeaponSlot() self.selectedWeaponIndex = self:slotIndex(self.cursorPos) local weapon = self.pages.weapons[self.selectedWeaponIndex] self.player:selectWeapon(weapon) self.player.doBasicAttack = false end --- -- Selects the current slot as the selected weapon -- @return nil function Inventory:selectCurrentScrollSlot() local index = self:slotIndex(self.cursorPos) self.selectedWeaponIndex = index + self.pageLength local scroll = self.pages.scrolls[index] self.player:selectWeapon(scroll) self.player.doBasicAttack = false end --- -- Selects the current slot as the selected armor -- @return nil function Inventory:selectCurrentArmorSlot() local index = self:slotIndex(self.cursorPos) local armor = self.pages.armors[index] if armor then self.selectedArmorIndices[armor.subtype] = index self.player:selectArmor(armor) end end --- -- Consumes the currently selected consumable -- @return nil function Inventory:consumeCurrentSlot() self.selectedConsumableIndex = self:slotIndex(self.cursorPos) local consumable = self.pages.consumables[self.selectedConsumableIndex] if consumable then consumable:use(self.player) sound.playSfx('confirm') end end -- DEEPCOPY -- This copies a table, used in crafting. I built this from bits and pieces from all over the web. function deepCopy(tableToCopy) -- Create new object local newTable = {} -- Go though all the elements and copy them for key,value in pairs(tableToCopy) do if type(value) == 'table' then value = utils.deepcopy(value) end newTable[key] = value end -- Set the metatable setmetatable(newTable,getmetatable(tableToCopy)) return newTable end --- -- Handles crafting screen interaction -- @return nil function Inventory:craftCurrentSlot() if not self.craftingVisible then --If the annex isn't open, open it. self:craftingOpen() end if self.cursorPos.x > 1 then --If we're already in the crafting annex, then we have some special behavior if self.cursorPos.x == 3 and self.currentIngredients.a then --If we're selecting the first ingredient, and it's not empty, then we remove it self:addItem(self.currentIngredients.a, false) self.currentIngredients.a = nil if self.currentIngredients.b then --If we're removing the first ingredient, and there is a second ingredient, remove it and move the item in b slot to a slot self.currentIngredients.a = self.currentIngredients.b self.currentIngredients.b = nil elseif self.currentIngredients.b == nil and self.tooltip.visible == false then self:craftingClose() self.cursorPos.x = 1 end end if self.cursorPos.x == 4 and self.currentIngredients.b then --If we're selecting the second ingredient, and it's not empty, then we remove it self:addItem(self.currentIngredients.b, false) self.currentIngredients.b = nil end if self.cursorPos.x == 2 and self.currentIngredients.a and self.currentIngredients.b then --If the craft button is selected with two ingredients, attempt to craft an item. local result = self:findResult(self.currentIngredients.a, self.currentIngredients.b) --We get the item that should result from the craft. if not result then return end --If there is no recipe for these items, do nothing. local resultFolder = string.lower(result.type)..'s' itemNode = require ('items/' .. resultFolder..'/'..result.name) local item = Item.new(itemNode) self.currentIngredients.a = nil self.currentIngredients.b = nil self.currentIngredients = {} self:addItem(item) self:craftingClose() self.cursorPos.x = 1 end return end if self.currentIngredients.b then return end --If we're already full, don't do anything if not self:currentPage()[self:slotIndex(self.cursorPos)] then return end --If we are selecting an empty slot, don't do anything if self.currentIngredients.a == self:slotIndex(self.cursorPos) or self.currentIngredients.b == self:slotIndex(self.cursorPos) then return end --If we already have the current item selected, don't do anything -- This takes one material off local selectedItem = self:currentPage()[self:slotIndex(self.cursorPos)] local moveItem = deepCopy(selectedItem) if selectedItem.quantity == 1 then self:currentPage()[self:slotIndex(self.cursorPos)] = nil else moveItem.quantity = 1 selectedItem.quantity = selectedItem.quantity - 1 end if not self.currentIngredients.a then self.currentIngredients.a = moveItem else self.currentIngredients.b = moveItem local craftitems = self.currentIngredients self.cursorPos.x = self:findResult(craftitems.a,craftitems.b) and 2 or 4 end end --- -- Finds the recipe, if one exists, for the given pair of items. If none exists return nil. -- @param a the first item's name -- @param b the second item's name -- @return the resulting item's filename, if one exists, or nil. function Inventory:findResult( a, b ) for i = 1, #recipes do local currentRecipe = recipes[i] if (currentRecipe[1].name == a.name and currentRecipe[2].name == b.name) or (currentRecipe[1].name == b.name and currentRecipe[2].name == a.name) then return currentRecipe[3] end end end --- -- Tries to select the next available weapon -- @return nil function Inventory:tryNextWeapon() local i = self.selectedWeaponIndex + 1 while i ~= self.selectedWeaponIndex do if self.pages.weapons[i] then self.selectedWeaponIndex = i break end if i < self.pageLength then i = i + 1 else i = 1 end end end --- -- Tries to merge the item with one that is already in the inventory. -- @return bool representing complete merger (true) or remainder (false) function Inventory:tryMerge( item ) for i,itemInSlot in pairs(self.pages[item.type ..'s']) do if itemInSlot and itemInSlot.name == item.name and itemInSlot.mergible and itemInSlot:mergible(item) then --This statement does a lot more than it seems. First of all, regardless of whether itemInSlot:merge(item) returns true or false, some merging is happening. If it returned false --then the item was partially merged, so we are getting the remainder of the item back to continue to try to merge it with other items. If it returned true, then we got a --complete merge, and we can stop looking right now. if itemInSlot:merge(item) then return true end end end return false end --- --Searches inventory for the first instance of "item" and returns that item. --@return the first item found, its page index value, and its slot index value. else, returns nil function Inventory:search( item ) local page = item.type .. "s" for i,itemInSlot in pairs(self.pages[page]) do if itemInSlot and itemInSlot.name == item.name then return itemInSlot, page, i end end return false end --- --Searches inventory and counts the total number of "item" --@return number of "item" in inventory function Inventory:count( item ) local count = 0 for i,itemInSlot in pairs(self.pages[item.type ..'s']) do if itemInSlot and itemInSlot.name == item.name then count = count + itemInSlot.quantity end end return count end --- -- Saves necessary inventory data to the gamesave object -- @param gamesave the gamesave object to save to -- @return nil function Inventory:save( gamesave ) gamesave:set('inventory', json.encode(self.pages)) gamesave:set('weapon_index', self.selectedWeaponIndex) gamesave:set('armor_indices', json.encode(self.selectedArmorIndices)) end --- -- Loads necessary inventory data from the gamesave object -- @param gamesave the gamesave object to load data from -- @return nil function Inventory:loadSaveData( gamesave ) local saved_inventory = gamesave:get( 'inventory' ) local weapon_idx = gamesave:get( 'weapon_index' ) self.selectedWeaponIndex = weapon_idx or 1 local armor_indices = gamesave:get( 'armor_indices' ) if not saved_inventory then return end -- Page numbers for key,value in pairs( json.decode( saved_inventory ) ) do -- Slot numbers for key2 , saved_item in pairs( value ) do -- saved_item will be the inventory item local ItemClass = require('items/item') local itemNode if saved_item.type == Item.types.ITEM_MATERIAL then itemNode = {type = saved_item.type, name = saved_item.name, MAX_ITEMS = saved_item.MaxItems, quantity = saved_item.quantity} elseif saved_item.type == Item.types.ITEM_WEAPON then itemNode = {type = saved_item.type, name = saved_item.name, subtype = saved_item.props.subtype, quantity = saved_item.quantity, MAX_ITEMS = saved_item.MaxItems} elseif saved_item.type == Item.types.ITEM_KEY then itemNode = {type = saved_item.type, name = saved_item.name} elseif saved_item.type == Item.types.ITEM_CONSUMABLE then itemNode = {type = saved_item.type, name = saved_item.name, MAX_ITEMS = saved_item.MaxItems, quantity = saved_item.quantity} elseif saved_item.type == Item.types.ITEM_SCROLL then itemNode = {type = saved_item.type, name = saved_item.name, MAX_ITEMS = saved_item.MaxItems, quantity = saved_item.quantity} elseif saved_item.type == Item.types.ITEM_ARMOR then itemNode = {type = saved_item.type, name = saved_item.name, subtype = saved_item.props.subtype, quantity = saved_item.quantity, MAX_ITEMS = saved_item.MaxItems} elseif saved_item.type == Item.types.ITEM_DETAIL then itemNode = {type = saved_item.type, name = saved_item.name, MAX_ITEMS = saved_item.MaxItems, quantity = saved_item.quantity} else print( "Warning: unhandled saved item type: " .. saved_item.type ) end -- If we have a valid item type if itemNode then local item = ItemClass.new(itemNode) if item then for propKey , propVal in pairs( saved_item ) do item[propKey] = propVal end self:addItem(item, false) else print( "Warning: unknown saved item: " .. itemNode.name) end end end end -- This won't be reached if the player has nothing saved in the inventory if armor_indices then for key, value in pairs( json.decode( armor_indices ) ) do local armor = self.pages.armors[value] if armor then self.selectedArmorIndices[key] = value self.player:selectArmor(armor) end end end end return Inventory
0
0.923199
1
0.923199
game-dev
MEDIA
0.969494
game-dev
0.910611
1
0.910611
Archy-X/AuraSkills
1,701
bukkit/src/main/java/dev/aurelium/auraskills/bukkit/ui/BukkitActionBarManager.java
package dev.aurelium.auraskills.bukkit.ui; import dev.aurelium.auraskills.api.trait.Traits; import dev.aurelium.auraskills.bukkit.user.BukkitUser; import dev.aurelium.auraskills.bukkit.util.AttributeCompat; import dev.aurelium.auraskills.common.AuraSkillsPlugin; import dev.aurelium.auraskills.common.ui.ActionBarManager; import dev.aurelium.auraskills.common.ui.UiProvider; import dev.aurelium.auraskills.common.user.User; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; public class BukkitActionBarManager extends ActionBarManager { public BukkitActionBarManager(AuraSkillsPlugin plugin, UiProvider uiProvider) { super(plugin, uiProvider); } @Override @NotNull public String getHp(User user) { Player player = ((BukkitUser) user).getPlayer(); if (player == null) return ""; return String.valueOf(Math.round(player.getHealth() * Traits.HP.optionDouble("action_bar_scaling", 1))); } @Override @NotNull public String getMaxHp(User user) { Player player = ((BukkitUser) user).getPlayer(); if (player == null) return ""; AttributeInstance attribute = player.getAttribute(AttributeCompat.maxHealth); if (attribute != null) { return String.valueOf(Math.round(attribute.getValue() * Traits.HP.optionDouble("action_bar_scaling", 1))); } return ""; } @Override @NotNull public String getWorldName(User user) { Player player = ((BukkitUser) user).getPlayer(); if (player != null) { return player.getWorld().getName(); } return ""; } }
0
0.797869
1
0.797869
game-dev
MEDIA
0.852351
game-dev
0.577803
1
0.577803
quiverteam/Engine
44,757
src/thirdparty/bullet/src/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.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. */ #include "btDiscreteDynamicsWorld.h" //collision detection #include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h" #include "BulletCollision/BroadphaseCollision/btSimpleBroadphase.h" #include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" #include "BulletCollision/CollisionShapes/btCollisionShape.h" #include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h" #include "LinearMath/btTransformUtil.h" #include "LinearMath/btQuickprof.h" //rigidbody & constraints #include "BulletDynamics/Dynamics/btRigidBody.h" #include "BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h" #include "BulletDynamics/ConstraintSolver/btContactSolverInfo.h" #include "BulletDynamics/ConstraintSolver/btTypedConstraint.h" #include "BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h" #include "BulletDynamics/ConstraintSolver/btHingeConstraint.h" #include "BulletDynamics/ConstraintSolver/btConeTwistConstraint.h" #include "BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.h" #include "BulletDynamics/ConstraintSolver/btSliderConstraint.h" #include "BulletDynamics/ConstraintSolver/btContactConstraint.h" #include "BulletDynamics/ConstraintSolver/btFixedConstraint.h" #include "LinearMath/btIDebugDraw.h" #include "BulletCollision/CollisionShapes/btSphereShape.h" #include "BulletDynamics/Dynamics/btActionInterface.h" #include "LinearMath/btQuickprof.h" #include "LinearMath/btMotionState.h" #include "LinearMath/btSerializer.h" #if 0 btAlignedObjectArray<btVector3> debugContacts; btAlignedObjectArray<btVector3> debugNormals; int startHit=2; int firstHit=startHit; #endif SIMD_FORCE_INLINE int btGetConstraintIslandId(const btTypedConstraint* lhs) { int islandId; const btCollisionObject& rcolObj0 = lhs->getRigidBodyA(); const btCollisionObject& rcolObj1 = lhs->getRigidBodyB(); islandId = rcolObj0.getIslandTag() >= 0 ? rcolObj0.getIslandTag() : rcolObj1.getIslandTag(); return islandId; } class btSortConstraintOnIslandPredicate { public: bool operator() ( const btTypedConstraint* lhs, const btTypedConstraint* rhs ) const { int rIslandId0, lIslandId0; rIslandId0 = btGetConstraintIslandId(rhs); lIslandId0 = btGetConstraintIslandId(lhs); return lIslandId0 < rIslandId0; } }; struct InplaceSolverIslandCallback : public btSimulationIslandManager::IslandCallback { btContactSolverInfo* m_solverInfo; btConstraintSolver* m_solver; btTypedConstraint** m_sortedConstraints; int m_numConstraints; btIDebugDraw* m_debugDrawer; btDispatcher* m_dispatcher; btAlignedObjectArray<btCollisionObject*> m_bodies; btAlignedObjectArray<btPersistentManifold*> m_manifolds; btAlignedObjectArray<btTypedConstraint*> m_constraints; InplaceSolverIslandCallback( btConstraintSolver* solver, btStackAlloc* stackAlloc, btDispatcher* dispatcher) :m_solverInfo(NULL), m_solver(solver), m_sortedConstraints(NULL), m_numConstraints(0), m_debugDrawer(NULL), m_dispatcher(dispatcher) { } InplaceSolverIslandCallback& operator=(InplaceSolverIslandCallback& other) { btAssert(0); (void)other; return *this; } SIMD_FORCE_INLINE void setup ( btContactSolverInfo* solverInfo, btTypedConstraint** sortedConstraints, int numConstraints, btIDebugDraw* debugDrawer) { btAssert(solverInfo); m_solverInfo = solverInfo; m_sortedConstraints = sortedConstraints; m_numConstraints = numConstraints; m_debugDrawer = debugDrawer; m_bodies.resize (0); m_manifolds.resize (0); m_constraints.resize (0); } virtual void processIsland(btCollisionObject** bodies, int numBodies, btPersistentManifold** manifolds, int numManifolds, int islandId) { if (islandId<0) { ///we don't split islands, so all constraints/contact manifolds/bodies are passed into the solver regardless the island id m_solver->solveGroup( bodies, numBodies, manifolds, numManifolds, &m_sortedConstraints[0], m_numConstraints,*m_solverInfo, m_debugDrawer, m_dispatcher); } else { //also add all non-contact constraints/joints for this island btTypedConstraint** startConstraint = 0; int numCurConstraints = 0; int i; //find the first constraint for this island for (i=0;i<m_numConstraints;i++) { if (btGetConstraintIslandId(m_sortedConstraints[i]) == islandId) { startConstraint = &m_sortedConstraints[i]; break; } } //count the number of constraints in this island for (;i<m_numConstraints;i++) { if (btGetConstraintIslandId(m_sortedConstraints[i]) == islandId) { numCurConstraints++; } } if (m_solverInfo->m_minimumSolverBatchSize <= 1) { m_solver->solveGroup(bodies, numBodies, manifolds, numManifolds, startConstraint, numCurConstraints, *m_solverInfo, m_debugDrawer, m_dispatcher); } else { for (i = 0; i < numBodies; i++) m_bodies.push_back(bodies[i]); for (i = 0; i < numManifolds; i++) m_manifolds.push_back(manifolds[i]); for (i = 0; i < numCurConstraints; i++) m_constraints.push_back(startConstraint[i]); if ((m_constraints.size() + m_manifolds.size()) > m_solverInfo->m_minimumSolverBatchSize) { processConstraints(); } else { //printf("deferred\n"); } } } } void processConstraints() { // This solves all islands in one batch btCollisionObject** bodies = m_bodies.size()? &m_bodies[0]:0; btPersistentManifold** manifold = m_manifolds.size()?&m_manifolds[0]:0; btTypedConstraint** constraints = m_constraints.size()?&m_constraints[0]:0; m_solver->solveGroup( bodies,m_bodies.size(),manifold, m_manifolds.size(),constraints, m_constraints.size() ,*m_solverInfo,m_debugDrawer,m_dispatcher); m_bodies.resize(0); m_manifolds.resize(0); m_constraints.resize(0); } }; btDiscreteDynamicsWorld::btDiscreteDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver, btCollisionConfiguration* collisionConfiguration) :btDynamicsWorld(dispatcher,pairCache,collisionConfiguration), m_sortedConstraints (), m_solverIslandCallback ( NULL ), m_constraintSolver(constraintSolver), m_gravity(0,-10,0), m_localTime(0), m_synchronizeAllMotionStates(false), m_applySpeculativeContactRestitution(false), m_profileTimings(0), m_fixedTimeStep(0), m_latencyMotionStateInterpolation(true) { void *mem = NULL; if (!m_constraintSolver) { mem = btAlignedAlloc(sizeof(btSequentialImpulseConstraintSolver),16); m_constraintSolver = new (mem) btSequentialImpulseConstraintSolver; m_ownsConstraintSolver = true; } else { m_ownsConstraintSolver = false; } mem = btAlignedAlloc(sizeof(btSimulationIslandManager),16); m_islandManager = new (mem) btSimulationIslandManager(); m_ownsIslandManager = true; mem = btAlignedAlloc(sizeof(InplaceSolverIslandCallback),16); m_solverIslandCallback = new (mem) InplaceSolverIslandCallback (m_constraintSolver, 0, dispatcher); } btDiscreteDynamicsWorld::~btDiscreteDynamicsWorld() { //only delete it when we created it if (m_ownsIslandManager) { m_islandManager->~btSimulationIslandManager(); btAlignedFree( m_islandManager); } if (m_solverIslandCallback) { m_solverIslandCallback->~InplaceSolverIslandCallback(); btAlignedFree(m_solverIslandCallback); } if (m_ownsConstraintSolver) { m_constraintSolver->~btConstraintSolver(); btAlignedFree(m_constraintSolver); } } void btDiscreteDynamicsWorld::saveKinematicState(btScalar timeStep) { ///would like to iterate over m_nonStaticRigidBodies, but unfortunately old API allows ///to switch status _after_ adding kinematic objects to the world ///fix it for Bullet 3.x release for (int i=0;i<m_collisionObjects.size();i++) { btCollisionObject* colObj = m_collisionObjects[i]; btRigidBody* body = btRigidBody::upcast(colObj); if (body && body->getActivationState() != ISLAND_SLEEPING) { if (body->isKinematicObject()) { //to calculate velocities next frame body->saveKinematicState(timeStep); } } } } void btDiscreteDynamicsWorld::debugDrawWorld() { BT_PROFILE("debugDrawWorld"); btCollisionWorld::debugDrawWorld(); if (!getDebugDrawer()) { return; } if (getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawConstraints | btIDebugDraw::DBG_DrawConstraintLimits)) { for(int i = getNumConstraints()-1; i>=0 ;i--) { btTypedConstraint* constraint = getConstraint(i); debugDrawConstraint(constraint); } } if (getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawAabb | btIDebugDraw::DBG_DrawNormals)) { int i; if (getDebugDrawer() && getDebugDrawer()->getDebugMode()) { for (i=0;i<m_actions.size();i++) { m_actions[i]->debugDraw(m_debugDrawer); } } } } void btDiscreteDynamicsWorld::clearForces() { ///@todo: iterate over awake simulation islands! for ( int i=0;i<m_nonStaticRigidBodies.size();i++) { btRigidBody* body = m_nonStaticRigidBodies[i]; //need to check if next line is ok //it might break backward compatibility (people applying forces on sleeping objects get never cleared and accumulate on wake-up body->clearForces(); } } ///apply gravity, call this once per timestep void btDiscreteDynamicsWorld::applyGravity() { ///@todo: iterate over awake simulation islands! for ( int i=0;i<m_nonStaticRigidBodies.size();i++) { btRigidBody* body = m_nonStaticRigidBodies[i]; if (body->isActive() && body->isMotionEnabled()) { body->applyGravity(); } } } void btDiscreteDynamicsWorld::synchronizeSingleMotionState(btRigidBody* body) { btAssert(body); if (body->getMotionState() && !body->isStaticOrKinematicObject() && body->isMotionEnabled()) { //we need to call the update at least once, even for sleeping objects //otherwise the 'graphics' transform never updates properly ///@todo: add 'dirty' flag //if (body->getActivationState() != ISLAND_SLEEPING) { btTransform interpolatedTransform; btTransformUtil::integrateTransform(body->getInterpolationWorldTransform(), body->getInterpolationLinearVelocity(), body->getInterpolationAngularVelocity(), (m_latencyMotionStateInterpolation && m_fixedTimeStep) ? m_localTime - m_fixedTimeStep : m_localTime * body->getHitFraction(), interpolatedTransform); body->getMotionState()->setWorldTransform(interpolatedTransform); } } } void btDiscreteDynamicsWorld::synchronizeMotionStates() { BT_PROFILE("synchronizeMotionStates"); if (m_synchronizeAllMotionStates) { //iterate over all collision objects for ( int i=0;i<m_collisionObjects.size();i++) { btCollisionObject* colObj = m_collisionObjects[i]; btRigidBody* body = btRigidBody::upcast(colObj); if (body) synchronizeSingleMotionState(body); } } else { //iterate over all active rigid bodies for ( int i=0;i<m_nonStaticRigidBodies.size();i++) { btRigidBody* body = m_nonStaticRigidBodies[i]; if (body->isActive()) synchronizeSingleMotionState(body); } } } int btDiscreteDynamicsWorld::stepSimulation(btScalar timeStep, int maxSubSteps, btScalar fixedTimeStep, int fixedSubSteps) { startProfiling(timeStep); BT_PROFILE("stepSimulation"); int numSimulationSubSteps = 0; if (maxSubSteps) { // fixed timestep with interpolation m_fixedTimeStep = fixedTimeStep; // Add timeStep to our local time. // If localTime exceeds fixedTimeStep, we can run a simulation step! Otherwise, interpolate // objects for game rendering. m_localTime += timeStep; if (m_localTime >= fixedTimeStep) { numSimulationSubSteps = int(m_localTime / fixedTimeStep); m_localTime -= numSimulationSubSteps * fixedTimeStep; // Subtract the amount of seconds we've simulated this frame... } } else { // variable timestep fixedTimeStep = timeStep; m_localTime = m_latencyMotionStateInterpolation ? 0 : timeStep; m_fixedTimeStep = 0; if (btFuzzyZero(timeStep)) { // Close enough to zero, so don't simulate. numSimulationSubSteps = 0; maxSubSteps = 0; } else { numSimulationSubSteps = 1; maxSubSteps = 1; } } //process some debugging flags if (getDebugDrawer()) { btIDebugDraw* debugDrawer = getDebugDrawer (); gDisableDeactivation = (debugDrawer->getDebugMode() & btIDebugDraw::DBG_NoDeactivation) != 0; } if (numSimulationSubSteps) { //clamp the number of substeps, to prevent simulation grinding spiralling down to a halt // Prevents some super small fixed timestep creating too many substeps int clampedSimulationSteps = (numSimulationSubSteps > maxSubSteps) ? maxSubSteps : numSimulationSubSteps; saveKinematicState(fixedTimeStep * clampedSimulationSteps); applyGravity(); for (int i = 0; i < clampedSimulationSteps; i++) { // number of substeps within the fixed step if (fixedSubSteps > 1) { btScalar step = fixedTimeStep / fixedSubSteps; for (int j = 0; j < fixedSubSteps; j++) { internalSingleStepSimulation(step); synchronizeMotionStates(); } } else { internalSingleStepSimulation(fixedTimeStep); synchronizeMotionStates(); } } } else { synchronizeMotionStates(); } clearForces(); #ifndef BT_NO_PROFILE CProfileManager::Increment_Frame_Counter(); #endif //BT_NO_PROFILE return numSimulationSubSteps; } void btDiscreteDynamicsWorld::internalSingleStepSimulation(btScalar timeStep) { BT_PROFILE("internalSingleStepSimulation"); if(0 != m_internalPreTickCallback) { (*m_internalPreTickCallback)(this, timeStep); } ///apply gravity, predict motion predictUnconstraintMotion(timeStep); btDispatcherInfo& dispatchInfo = getDispatchInfo(); dispatchInfo.m_timeStep = timeStep; dispatchInfo.m_stepCount = 0; dispatchInfo.m_debugDraw = getDebugDrawer(); createPredictiveContacts(timeStep); ///perform collision detection performDiscreteCollisionDetection(); // Setup and solve simulation islands calculateSimulationIslands(); // Solver information getSolverInfo().m_timeStep = timeStep; ///solve contact and other joint constraints solveConstraints(getSolverInfo()); ///integrate transforms integrateTransforms(timeStep); ///update vehicle simulation updateActions(timeStep); updateActivationState( timeStep ); if(0 != m_internalTickCallback) { (*m_internalTickCallback)(this, timeStep); } } void btDiscreteDynamicsWorld::setGravity(const btVector3& gravity) { m_gravity = gravity; for ( int i=0;i<m_nonStaticRigidBodies.size();i++) { btRigidBody* body = m_nonStaticRigidBodies[i]; if (body->isActive() && !(body->getFlags() &BT_DISABLE_WORLD_GRAVITY)) { body->setGravity(gravity); } } } btVector3 btDiscreteDynamicsWorld::getGravity () const { return m_gravity; } void btDiscreteDynamicsWorld::addCollisionObject(btCollisionObject* collisionObject, short int collisionFilterGroup, short int collisionFilterMask) { btCollisionWorld::addCollisionObject(collisionObject, collisionFilterGroup, collisionFilterMask); } void btDiscreteDynamicsWorld::removeCollisionObject(btCollisionObject* collisionObject) { // Activate any objects sharing a contact point with this object btOverlappingPairCache *pCache = m_broadphasePairCache->getOverlappingPairCache(); for (int i = 0; i < pCache->getNumOverlappingPairs(); i++) { btBroadphasePair &pair = pCache->getOverlappingPairArray()[i]; if (!pair.m_algorithm) continue; if (pair.m_pProxy0->m_clientObject == collisionObject || pair.m_pProxy1->m_clientObject == collisionObject) { // Inefficient because we really don't need the manifold array, but there isn't a getNumContactManifolds // Let's just hope the user isn't removing an object every frame, or prepare for malloc/free lag btManifoldArray arr; pair.m_algorithm->getAllContactManifolds(arr); if (arr.size() > 0) { btBroadphaseProxy *otherObj = collisionObject->getBroadphaseHandle() == pair.m_pProxy0 ? pair.m_pProxy1 : pair.m_pProxy0; ((btCollisionObject *)otherObj->m_clientObject)->activate(); } } } btRigidBody* body = btRigidBody::upcast(collisionObject); if (body) removeRigidBody(body); else btCollisionWorld::removeCollisionObject(collisionObject); } void btDiscreteDynamicsWorld::removeRigidBody(btRigidBody* body) { m_nonStaticRigidBodies.remove(body); btCollisionWorld::removeCollisionObject(body); } void btDiscreteDynamicsWorld::addRigidBody(btRigidBody* body) { if (!body->isStaticOrKinematicObject() && !(body->getFlags() &BT_DISABLE_WORLD_GRAVITY)) { body->setGravity(m_gravity); } if (body->getCollisionShape()) { if (!body->isStaticObject()) { m_nonStaticRigidBodies.push_back(body); } else { body->setActivationState(ISLAND_SLEEPING); } bool isDynamic = !(body->isStaticObject() || body->isKinematicObject()); short collisionFilterGroup = isDynamic? short(btBroadphaseProxy::DefaultFilter) : short(btBroadphaseProxy::StaticFilter); short collisionFilterMask = isDynamic? short(btBroadphaseProxy::AllFilter) : short(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter); addCollisionObject(body, collisionFilterGroup, collisionFilterMask); } } void btDiscreteDynamicsWorld::addRigidBody(btRigidBody* body, short group, short mask) { if (!body->isStaticOrKinematicObject() && !(body->getFlags() &BT_DISABLE_WORLD_GRAVITY)) { body->setGravity(m_gravity); } if (body->getCollisionShape()) { if (!body->isStaticObject()) { m_nonStaticRigidBodies.push_back(body); } else { body->setActivationState(ISLAND_SLEEPING); } addCollisionObject(body, group, mask); } } void btDiscreteDynamicsWorld::updateActions(btScalar timeStep) { BT_PROFILE("updateActions"); for ( int i=0;i<m_actions.size();i++) { m_actions[i]->updateAction( this, timeStep); } } void btDiscreteDynamicsWorld::updateActivationState(btScalar timeStep) { BT_PROFILE("updateActivationState"); for ( int i=0;i<m_nonStaticRigidBodies.size();i++) { btRigidBody* body = m_nonStaticRigidBodies[i]; if (body) { body->updateDeactivation(timeStep); if (body->wantsSleeping()) { if (body->isStaticOrKinematicObject()) { body->setActivationState(ISLAND_SLEEPING); } else { if (body->getActivationState() == ACTIVE_TAG) body->setActivationState( WANTS_DEACTIVATION ); else if (body->getActivationState() == ISLAND_SLEEPING) { body->setAngularVelocity(btVector3(0,0,0)); body->setLinearVelocity(btVector3(0,0,0)); } } } else { if (body->getActivationState() != DISABLE_DEACTIVATION) body->setActivationState( ACTIVE_TAG ); } } } } void btDiscreteDynamicsWorld::addConstraint(btTypedConstraint* constraint, bool disableCollisionsBetweenLinkedBodies) { m_constraints.push_back(constraint); if (disableCollisionsBetweenLinkedBodies) { constraint->getRigidBodyA().addConstraintRef(constraint); constraint->getRigidBodyB().addConstraintRef(constraint); } } void btDiscreteDynamicsWorld::removeConstraint(btTypedConstraint* constraint) { // If you hit this assert then the constraint has already been removed! btAssert(m_constraints.findLinearSearch(constraint) != m_constraints.size()); m_constraints.remove(constraint); constraint->getRigidBodyA().removeConstraintRef(constraint); constraint->getRigidBodyB().removeConstraintRef(constraint); } void btDiscreteDynamicsWorld::addAction(btActionInterface* action) { m_actions.push_back(action); } void btDiscreteDynamicsWorld::removeAction(btActionInterface* action) { m_actions.remove(action); } void btDiscreteDynamicsWorld::addVehicle(btActionInterface* vehicle) { addAction(vehicle); } void btDiscreteDynamicsWorld::removeVehicle(btActionInterface* vehicle) { removeAction(vehicle); } void btDiscreteDynamicsWorld::addCharacter(btActionInterface* character) { addAction(character); } void btDiscreteDynamicsWorld::removeCharacter(btActionInterface* character) { removeAction(character); } void btDiscreteDynamicsWorld::solveConstraints(btContactSolverInfo& solverInfo) { BT_PROFILE("solveConstraints"); m_sortedConstraints.resize( m_constraints.size()); int i; for (i=0;i<getNumConstraints();i++) { m_sortedConstraints[i] = m_constraints[i]; } // btAssert(0); m_sortedConstraints.quickSort(btSortConstraintOnIslandPredicate()); btTypedConstraint** constraintsPtr = getNumConstraints() ? &m_sortedConstraints[0] : 0; m_solverIslandCallback->setup(&solverInfo, constraintsPtr, m_sortedConstraints.size(), getDebugDrawer()); m_constraintSolver->prepareSolve(getCollisionWorld()->getNumCollisionObjects(), getCollisionWorld()->getDispatcher()->getNumManifolds()); /// solve all the constraints for this island m_islandManager->buildAndProcessIslands(getCollisionWorld()->getDispatcher(), getCollisionWorld(), m_solverIslandCallback); // Process any constraints on islands that weren't big enough to be processed on their own m_solverIslandCallback->processConstraints(); m_constraintSolver->allSolved(solverInfo, m_debugDrawer); } void btDiscreteDynamicsWorld::calculateSimulationIslands() { BT_PROFILE("calculateSimulationIslands"); getSimulationIslandManager()->updateActivationState(getCollisionWorld(), getCollisionWorld()->getDispatcher()); { //merge islands based on speculative contact manifolds too for (int i=0;i<this->m_predictiveManifolds.size();i++) { btPersistentManifold* manifold = m_predictiveManifolds[i]; const btCollisionObject* colObj0 = manifold->getBody0(); const btCollisionObject* colObj1 = manifold->getBody1(); if (((colObj0) && (!(colObj0)->isStaticOrKinematicObject())) && ((colObj1) && (!(colObj1)->isStaticOrKinematicObject()))) { getSimulationIslandManager()->getUnionFind().unite((colObj0)->getIslandTag(),(colObj1)->getIslandTag()); } } } { // Merge islands based on common constraints int i; int numConstraints = int(m_constraints.size()); for (i=0;i< numConstraints ; i++ ) { btTypedConstraint* constraint = m_constraints[i]; if (constraint->isEnabled()) { const btRigidBody* colObj0 = &constraint->getRigidBodyA(); const btRigidBody* colObj1 = &constraint->getRigidBodyB(); if (((colObj0) && (!(colObj0)->isStaticOrKinematicObject())) && ((colObj1) && (!(colObj1)->isStaticOrKinematicObject()))) { getSimulationIslandManager()->getUnionFind().unite((colObj0)->getIslandTag(),(colObj1)->getIslandTag()); } } } } //Store the island id in each body getSimulationIslandManager()->storeIslandActivationState(getCollisionWorld()); } class btClosestNotMeConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback { public: btCollisionObject* m_me; btScalar m_allowedPenetration; btOverlappingPairCache* m_pairCache; btDispatcher* m_dispatcher; public: btClosestNotMeConvexResultCallback (btCollisionObject* me, const btVector3& fromA, const btVector3& toA, btOverlappingPairCache* pairCache, btDispatcher* dispatcher) : btCollisionWorld::ClosestConvexResultCallback(fromA, toA), m_me(me), m_allowedPenetration(0.0f), m_pairCache(pairCache), m_dispatcher(dispatcher) { } virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace) { if (convexResult.m_hitCollisionObject == m_me) return 1.0f; //ignore result if there is no contact response if(!convexResult.m_hitCollisionObject->hasContactResponse()) return 1.0f; btVector3 linVelA, linVelB; linVelA = m_convexToWorld-m_convexFromWorld; linVelB = btVector3(0,0,0);//toB.getOrigin()-fromB.getOrigin(); btVector3 relativeVelocity = (linVelA-linVelB); //don't report time of impact for motion away from the contact normal (or causes minor penetration) if (convexResult.m_hitNormalLocal.dot(relativeVelocity)>=-m_allowedPenetration) return 1.f; return ClosestConvexResultCallback::addSingleResult (convexResult, normalInWorldSpace); } virtual bool needsCollision(btBroadphaseProxy* proxy0) const { //don't collide with itself if (proxy0->m_clientObject == m_me) return false; ///don't do CCD when the collision filters are not matching if (!ClosestConvexResultCallback::needsCollision(proxy0)) return false; // Check collide with if (!m_me->checkCollideWith((btCollisionObject *)proxy0->m_clientObject)) return false; btCollisionObject* otherObj = (btCollisionObject*) proxy0->m_clientObject; //call needsResponse, see http://code.google.com/p/bullet/issues/detail?id=179 if (m_dispatcher->needsResponse(m_me, otherObj)) { #if 0 ///don't do CCD when there are already contact points (touching contact/penetration) btAlignedObjectArray<btPersistentManifold*> manifoldArray; btBroadphasePair* collisionPair = m_pairCache->findPair(m_me->getBroadphaseHandle(), proxy0); if (collisionPair) { if (collisionPair->m_algorithm) { manifoldArray.resize(0); collisionPair->m_algorithm->getAllContactManifolds(manifoldArray); for (int j=0;j<manifoldArray.size();j++) { btPersistentManifold* manifold = manifoldArray[j]; if (manifold->getNumContacts()>0) return false; } } } #endif return true; } return false; } }; ///internal debugging variable. this value shouldn't be too high int gNumClampedCcdMotions=0; void btDiscreteDynamicsWorld::createPredictiveContacts(btScalar timeStep) { BT_PROFILE("createPredictiveContacts"); { BT_PROFILE("release predictive contact manifolds"); for (int i=0;i<m_predictiveManifolds.size();i++) { btPersistentManifold* manifold = m_predictiveManifolds[i]; this->m_dispatcher1->releaseManifold(manifold); } m_predictiveManifolds.clear(); } btTransform predictedTrans; for ( int i=0;i<m_nonStaticRigidBodies.size();i++) { btRigidBody* body = m_nonStaticRigidBodies[i]; body->setHitFraction(1.f); if (body->isActive() && (!body->isStaticOrKinematicObject())) { body->predictIntegratedTransform(timeStep, predictedTrans); btScalar squareMotion = (predictedTrans.getOrigin()-body->getWorldTransform().getOrigin()).length2(); if (0 && body->getCollisionShape()->isConvex() && getDispatchInfo().m_useContinuous && body->getCcdSquareMotionThreshold() && body->getCcdSquareMotionThreshold() < squareMotion) { BT_PROFILE("predictive convexSweepTest"); gNumClampedCcdMotions++; #ifdef PREDICTIVE_CONTACT_USE_STATIC_ONLY class StaticOnlyCallback : public btClosestNotMeConvexResultCallback { public: StaticOnlyCallback (btCollisionObject* me, const btVector3& fromA, const btVector3& toA, btOverlappingPairCache* pairCache, btDispatcher* dispatcher) : btClosestNotMeConvexResultCallback(me, fromA, toA, pairCache, dispatcher) { } virtual bool needsCollision(btBroadphaseProxy* proxy0) const { btCollisionObject* otherObj = (btCollisionObject*) proxy0->m_clientObject; if (!otherObj->isStaticOrKinematicObject()) return false; return btClosestNotMeConvexResultCallback::needsCollision(proxy0); } }; StaticOnlyCallback sweepResults(body, body->getWorldTransform().getOrigin(), predictedTrans.getOrigin(), getBroadphase()->getOverlappingPairCache(), getDispatcher()); #else btClosestNotMeConvexResultCallback sweepResults(body, body->getWorldTransform().getOrigin(), predictedTrans.getOrigin(), getBroadphase()->getOverlappingPairCache(), getDispatcher()); #endif //btConvexShape* convexShape = static_cast<btConvexShape*>(body->getCollisionShape()); btSphereShape tmpSphere(body->getCcdSweptSphereRadius());//btConvexShape* convexShape = static_cast<btConvexShape*>(body->getCollisionShape()); sweepResults.m_allowedPenetration=getDispatchInfo().m_allowedCcdPenetration; sweepResults.m_collisionFilterGroup = body->getBroadphaseProxy()->m_collisionFilterGroup; sweepResults.m_collisionFilterMask = body->getBroadphaseProxy()->m_collisionFilterMask; btTransform modifiedPredictedTrans = predictedTrans; modifiedPredictedTrans.setBasis(body->getWorldTransform().getBasis()); convexSweepTest(&tmpSphere, body->getWorldTransform(), modifiedPredictedTrans, sweepResults); if (sweepResults.hasHit()) { btVector3 distVec = (predictedTrans.getOrigin()-body->getWorldTransform().getOrigin())*sweepResults.m_closestHitFraction; btScalar distance = distVec.dot(-sweepResults.m_hitNormalWorld); btPersistentManifold* manifold = m_dispatcher1->getNewManifold(body, sweepResults.m_hitCollisionObject); m_predictiveManifolds.push_back(manifold); btVector3 worldPointB = body->getWorldTransform().getOrigin()+distVec; btVector3 localPointB = sweepResults.m_hitCollisionObject->getWorldTransform().inverse()*worldPointB; btManifoldPoint newPoint(btVector3(0,0,0), localPointB, sweepResults.m_hitNormalWorld, distance); int index = manifold->addManifoldPoint(newPoint, true); btManifoldPoint& pt = manifold->getContactPoint(index); pt.m_combinedRestitution = 0; pt.m_combinedFriction = btManifoldResult::calculateCombinedFriction(body, sweepResults.m_hitCollisionObject); pt.m_positionWorldOnA = body->getWorldTransform().getOrigin(); pt.m_positionWorldOnB = worldPointB; } } } } } void btDiscreteDynamicsWorld::integrateTransforms(btScalar timeStep) { BT_PROFILE("integrateTransforms"); btTransform predictedTrans; for (int i=0; i<m_nonStaticRigidBodies.size(); i++) { btRigidBody* body = m_nonStaticRigidBodies[i]; body->setHitFraction(1.f); if (body->isActive() && (!body->isStaticOrKinematicObject()) && body->isMotionEnabled()) { body->predictIntegratedTransform(timeStep, predictedTrans); btScalar squareMotion = (predictedTrans.getOrigin()-body->getWorldTransform().getOrigin()).length2(); if (0 && body->getCollisionShape()->isConvex() && getDispatchInfo().m_useContinuous && body->getCcdSquareMotionThreshold() && body->getCcdSquareMotionThreshold() < squareMotion) { BT_PROFILE("CCD motion clamping"); #ifdef USE_STATIC_ONLY class StaticOnlyCallback : public btClosestNotMeConvexResultCallback { public: StaticOnlyCallback (btCollisionObject* me, const btVector3& fromA, const btVector3& toA, btOverlappingPairCache* pairCache, btDispatcher* dispatcher) : btClosestNotMeConvexResultCallback(me, fromA, toA, pairCache, dispatcher) { } virtual bool needsCollision(btBroadphaseProxy* proxy0) const { btCollisionObject* otherObj = (btCollisionObject*) proxy0->m_clientObject; if (!otherObj->isStaticOrKinematicObject()) return false; return btClosestNotMeConvexResultCallback::needsCollision(proxy0); } }; StaticOnlyCallback sweepResults(body, body->getWorldTransform().getOrigin(), predictedTrans.getOrigin(), getBroadphase()->getOverlappingPairCache(), getDispatcher()); #else btClosestNotMeConvexResultCallback sweepResults(body, body->getWorldTransform().getOrigin(), predictedTrans.getOrigin(), getBroadphase()->getOverlappingPairCache(), getDispatcher()); #endif //btConvexShape* convexShape = static_cast<btConvexShape*>(body->getCollisionShape()); btSphereShape tmpSphere(body->getCcdSweptSphereRadius());//btConvexShape* convexShape = static_cast<btConvexShape*>(body->getCollisionShape()); sweepResults.m_allowedPenetration=getDispatchInfo().m_allowedCcdPenetration; sweepResults.m_collisionFilterGroup = body->getBroadphaseProxy()->m_collisionFilterGroup; sweepResults.m_collisionFilterMask = body->getBroadphaseProxy()->m_collisionFilterMask; btTransform modifiedPredictedTrans = predictedTrans; modifiedPredictedTrans.setBasis(body->getWorldTransform().getBasis()); convexSweepTest(&tmpSphere, body->getWorldTransform(), modifiedPredictedTrans, sweepResults); if (sweepResults.hasHit() && (sweepResults.m_closestHitFraction < 1.f)) { //printf("clamped integration to hit fraction = %f\n", fraction); body->setHitFraction(sweepResults.m_closestHitFraction); body->predictIntegratedTransform(timeStep*body->getHitFraction(), predictedTrans); body->setHitFraction(0.f); body->proceedToTransform(predictedTrans); #if 0 btVector3 linVel = body->getLinearVelocity(); btScalar maxSpeed = body->getCcdMotionThreshold()/getSolverInfo().m_timeStep; btScalar maxSpeedSqr = maxSpeed*maxSpeed; if (linVel.length2()>maxSpeedSqr) { linVel.normalize(); linVel*= maxSpeed; body->setLinearVelocity(linVel); btScalar ms2 = body->getLinearVelocity().length2(); body->predictIntegratedTransform(timeStep, predictedTrans); btScalar sm2 = (predictedTrans.getOrigin()-body->getWorldTransform().getOrigin()).length2(); btScalar smt = body->getCcdSquareMotionThreshold(); printf("sm2=%f\n", sm2); } #else //don't apply the collision response right now, it will happen next frame //if you really need to, you can uncomment next 3 lines. Note that is uses zero restitution. //btScalar appliedImpulse = 0.f; //btScalar depth = 0.f; //appliedImpulse = resolveSingleCollision(body, (btCollisionObject*)sweepResults.m_hitCollisionObject, sweepResults.m_hitPointWorld, sweepResults.m_hitNormalWorld, getSolverInfo(), depth); #endif continue; } } body->proceedToTransform(predictedTrans); } } ///this should probably be switched on by default, but it is not well tested yet if (m_applySpeculativeContactRestitution) { BT_PROFILE("apply speculative contact restitution"); for (int i=0;i<m_predictiveManifolds.size();i++) { btPersistentManifold* manifold = m_predictiveManifolds[i]; btRigidBody* body0 = btRigidBody::upcast((btCollisionObject*)manifold->getBody0()); btRigidBody* body1 = btRigidBody::upcast((btCollisionObject*)manifold->getBody1()); for (int p=0;p<manifold->getNumContacts();p++) { const btManifoldPoint& pt = manifold->getContactPoint(p); btScalar combinedRestitution = btManifoldResult::calculateCombinedRestitution(body0, body1); if (combinedRestitution>0 && pt.m_appliedImpulse != 0.f) //if (pt.getDistance()>0 && combinedRestitution>0 && pt.m_appliedImpulse != 0.f) { btVector3 imp = -pt.m_normalWorldOnB * pt.m_appliedImpulse* combinedRestitution; const btVector3& pos1 = pt.getPositionWorldOnA(); const btVector3& pos2 = pt.getPositionWorldOnB(); btVector3 rel_pos0 = pos1 - body0->getWorldTransform().getOrigin(); btVector3 rel_pos1 = pos2 - body1->getWorldTransform().getOrigin(); if (body0) body0->applyImpulse(imp, rel_pos0); if (body1) body1->applyImpulse(-imp, rel_pos1); } } } } } void btDiscreteDynamicsWorld::predictUnconstraintMotion(btScalar timeStep) { BT_PROFILE("predictUnconstraintMotion"); for ( int i=0;i<m_nonStaticRigidBodies.size();i++) { btRigidBody* body = m_nonStaticRigidBodies[i]; if (!body->isStaticOrKinematicObject()) { //don't integrate/update velocities here, it happens in the constraint solver body->applyDamping(timeStep); body->predictIntegratedTransform(timeStep, body->getInterpolationWorldTransform()); } } } void btDiscreteDynamicsWorld::startProfiling(btScalar timeStep) { (void)timeStep; #ifndef BT_NO_PROFILE CProfileManager::Reset(); #endif //BT_NO_PROFILE } void btDiscreteDynamicsWorld::debugDrawConstraint(btTypedConstraint* constraint) { bool drawFrames = (getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawConstraints) != 0; bool drawLimits = (getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawConstraintLimits) != 0; btScalar dbgDrawSize = constraint->getDbgDrawSize(); if(dbgDrawSize <= btScalar(0.f)) { return; } // TODO: Remove switch, move all drawing code to individual classes switch(constraint->getConstraintType()) { case POINT2POINT_CONSTRAINT_TYPE: { btPoint2PointConstraint* p2pC = (btPoint2PointConstraint*)constraint; btTransform tr; tr.setIdentity(); btVector3 pivot = p2pC->getPivotInA(); pivot = p2pC->getRigidBodyA().getCenterOfMassTransform() * pivot; tr.setOrigin(pivot); getDebugDrawer()->drawTransform(tr, dbgDrawSize); // that ideally should draw the same frame pivot = p2pC->getPivotInB(); pivot = p2pC->getRigidBodyB().getCenterOfMassTransform() * pivot; tr.setOrigin(pivot); if (drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize); } break; case HINGE_CONSTRAINT_TYPE: { btHingeConstraint* pHinge = (btHingeConstraint*)constraint; btTransform tr = pHinge->getRigidBodyA().getCenterOfMassTransform() * pHinge->getAFrame(); if (drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize); tr = pHinge->getRigidBodyB().getCenterOfMassTransform() * pHinge->getBFrame(); if (drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize); btScalar minAng = pHinge->getLowerLimit(); btScalar maxAng = pHinge->getUpperLimit(); if(minAng == maxAng) { break; } bool drawSect = true; if(minAng > maxAng) { minAng = btScalar(0.f); maxAng = SIMD_2_PI; drawSect = false; } if(drawLimits) { btVector3& center = tr.getOrigin(); btVector3 normal = tr.getBasis().getColumn(2); btVector3 axis = tr.getBasis().getColumn(0); getDebugDrawer()->drawArc(center, normal, axis, dbgDrawSize, dbgDrawSize, minAng, maxAng, btVector3(0,0,0), drawSect); } } break; case CONETWIST_CONSTRAINT_TYPE: { btConeTwistConstraint* pCT = (btConeTwistConstraint*)constraint; btTransform tr = pCT->getRigidBodyA().getCenterOfMassTransform() * pCT->getAFrame(); if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize); tr = pCT->getRigidBodyB().getCenterOfMassTransform() * pCT->getBFrame(); if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize); if(drawLimits) { //const btScalar length = btScalar(5); const btScalar length = dbgDrawSize; static int nSegments = 8*4; btScalar fAngleInRadians = btScalar(2.*3.1415926) * (btScalar)(nSegments-1)/btScalar(nSegments); btVector3 pPrev = pCT->GetPointForAngle(fAngleInRadians, length); pPrev = tr * pPrev; for (int i=0; i<nSegments; i++) { fAngleInRadians = btScalar(2.*3.1415926) * (btScalar)i/btScalar(nSegments); btVector3 pCur = pCT->GetPointForAngle(fAngleInRadians, length); pCur = tr * pCur; getDebugDrawer()->drawLine(pPrev, pCur, btVector3(0,0,0)); if (i%(nSegments/8) == 0) getDebugDrawer()->drawLine(tr.getOrigin(), pCur, btVector3(0,0,0)); pPrev = pCur; } btScalar tws = pCT->getTwistSpan(); btScalar twa = pCT->getTwistAngle(); bool useFrameB = (pCT->getRigidBodyB().getInvMass() > btScalar(0.f)); if(useFrameB) { tr = pCT->getRigidBodyB().getCenterOfMassTransform() * pCT->getBFrame(); } else { tr = pCT->getRigidBodyA().getCenterOfMassTransform() * pCT->getAFrame(); } btVector3 pivot = tr.getOrigin(); btVector3 normal = tr.getBasis().getColumn(0); btVector3 axis1 = tr.getBasis().getColumn(1); getDebugDrawer()->drawArc(pivot, normal, axis1, dbgDrawSize, dbgDrawSize, -twa-tws, -twa+tws, btVector3(0,0,0), true); } } break; default: constraint->debugDraw(getDebugDrawer()); break; } } void btDiscreteDynamicsWorld::setConstraintSolver(btConstraintSolver* solver) { if (m_ownsConstraintSolver) { btAlignedFree(m_constraintSolver); } m_ownsConstraintSolver = false; m_constraintSolver = solver; m_solverIslandCallback->m_solver = solver; } btConstraintSolver* btDiscreteDynamicsWorld::getConstraintSolver() { return m_constraintSolver; } int btDiscreteDynamicsWorld::getNumConstraints() const { return m_constraints.size(); } btTypedConstraint* btDiscreteDynamicsWorld::getConstraint(int index) { return m_constraints[index]; } const btTypedConstraint* btDiscreteDynamicsWorld::getConstraint(int index) const { return m_constraints[index]; } void btDiscreteDynamicsWorld::serializeRigidBodies(btSerializer* serializer) { int i; //serialize all collision objects for (i=0;i<m_collisionObjects.size();i++) { btCollisionObject* colObj = m_collisionObjects[i]; if (colObj->getInternalType() & btCollisionObject::CO_RIGID_BODY) { int len = colObj->calculateSerializeBufferSize(); btChunk* chunk = serializer->allocate(len,1); const char* structType = colObj->serialize(chunk->m_oldPtr, serializer); serializer->finalizeChunk(chunk, structType, BT_RIGIDBODY_CODE, colObj); } } for (i=0;i<m_constraints.size();i++) { btTypedConstraint* constraint = m_constraints[i]; int size = constraint->calculateSerializeBufferSize(); btChunk* chunk = serializer->allocate(size,1); const char* structType = constraint->serialize(chunk->m_oldPtr, serializer); serializer->finalizeChunk(chunk, structType, BT_CONSTRAINT_CODE, constraint); } } void btDiscreteDynamicsWorld::serializeDynamicsWorldInfo(btSerializer* serializer) { #ifdef BT_USE_DOUBLE_PRECISION int len = sizeof(btDynamicsWorldDoubleData); btChunk* chunk = serializer->allocate(len,1); btDynamicsWorldDoubleData* worldInfo = (btDynamicsWorldDoubleData*)chunk->m_oldPtr; #else//BT_USE_DOUBLE_PRECISION int len = sizeof(btDynamicsWorldFloatData); btChunk* chunk = serializer->allocate(len,1); btDynamicsWorldFloatData* worldInfo = (btDynamicsWorldFloatData*)chunk->m_oldPtr; #endif//BT_USE_DOUBLE_PRECISION memset(worldInfo ,0x00, len); m_gravity.serialize(worldInfo->m_gravity); worldInfo->m_solverInfo.m_tau = getSolverInfo().m_tau; worldInfo->m_solverInfo.m_damping = getSolverInfo().m_damping; worldInfo->m_solverInfo.m_friction = getSolverInfo().m_friction; worldInfo->m_solverInfo.m_timeStep = getSolverInfo().m_timeStep; worldInfo->m_solverInfo.m_restitution = getSolverInfo().m_restitution; worldInfo->m_solverInfo.m_maxErrorReduction = getSolverInfo().m_maxErrorReduction; worldInfo->m_solverInfo.m_sor = getSolverInfo().m_sor; worldInfo->m_solverInfo.m_erp = getSolverInfo().m_erp; worldInfo->m_solverInfo.m_erp2 = getSolverInfo().m_erp2; worldInfo->m_solverInfo.m_globalCfm = getSolverInfo().m_globalCfm; worldInfo->m_solverInfo.m_splitImpulsePenetrationThreshold = getSolverInfo().m_splitImpulsePenetrationThreshold; worldInfo->m_solverInfo.m_splitImpulseTurnErp = getSolverInfo().m_splitImpulseTurnErp; worldInfo->m_solverInfo.m_linearSlop = getSolverInfo().m_linearSlop; worldInfo->m_solverInfo.m_warmstartingFactor = getSolverInfo().m_warmstartingFactor; worldInfo->m_solverInfo.m_maxGyroscopicForce = getSolverInfo().m_maxGyroscopicForce; worldInfo->m_solverInfo.m_singleAxisRollingFrictionThreshold = getSolverInfo().m_singleAxisRollingFrictionThreshold; worldInfo->m_solverInfo.m_numIterations = getSolverInfo().m_numIterations; worldInfo->m_solverInfo.m_solverMode = getSolverInfo().m_solverMode; worldInfo->m_solverInfo.m_restingContactRestitutionThreshold = getSolverInfo().m_restingContactRestitutionThreshold; worldInfo->m_solverInfo.m_minimumSolverBatchSize = getSolverInfo().m_minimumSolverBatchSize; worldInfo->m_solverInfo.m_splitImpulse = getSolverInfo().m_splitImpulse; #ifdef BT_USE_DOUBLE_PRECISION const char* structType = "btDynamicsWorldDoubleData"; #else//BT_USE_DOUBLE_PRECISION const char* structType = "btDynamicsWorldFloatData"; #endif//BT_USE_DOUBLE_PRECISION serializer->finalizeChunk(chunk, structType, BT_DYNAMICSWORLD_CODE, worldInfo); } void btDiscreteDynamicsWorld::serialize(btSerializer* serializer) { serializer->startSerialization(); serializeDynamicsWorldInfo(serializer); serializeRigidBodies(serializer); serializeCollisionObjects(serializer); serializer->finishSerialization(); }
0
0.953207
1
0.953207
game-dev
MEDIA
0.982094
game-dev
0.969073
1
0.969073
wojciech-graj/doom-audio
6,053
src/p_ceilng.c
// // Copyright(C) 1993-1996 Id Software, Inc. // Copyright(C) 2005-2014 Simon Howard // // 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. // // DESCRIPTION: Ceiling aninmation (lowering, crushing, raising) // #include "z_zone.h" #include "doomdef.h" #include "p_local.h" #include "s_sound.h" // State. #include "doomstat.h" #include "r_state.h" // Data. #include "sounds.h" // // CEILINGS // ceiling_t* activeceilings[MAXCEILINGS]; // // T_MoveCeiling // void T_MoveCeiling (ceiling_t* ceiling) { result_e res; switch(ceiling->direction) { case 0: // IN STASIS break; case 1: // UP res = T_MovePlane(ceiling->sector, ceiling->speed, ceiling->topheight, false,1,ceiling->direction); if (!(leveltime&7)) { switch(ceiling->type) { case silentCrushAndRaise: break; default: S_StartSound(&ceiling->sector->soundorg, sfx_stnmov); // ? break; } } if (res == pastdest) { switch(ceiling->type) { case raiseToHighest: P_RemoveActiveCeiling(ceiling); break; case silentCrushAndRaise: S_StartSound(&ceiling->sector->soundorg, sfx_pstop); case fastCrushAndRaise: case crushAndRaise: ceiling->direction = -1; break; default: break; } } break; case -1: // DOWN res = T_MovePlane(ceiling->sector, ceiling->speed, ceiling->bottomheight, ceiling->crush,1,ceiling->direction); if (!(leveltime&7)) { switch(ceiling->type) { case silentCrushAndRaise: break; default: S_StartSound(&ceiling->sector->soundorg, sfx_stnmov); } } if (res == pastdest) { switch(ceiling->type) { case silentCrushAndRaise: S_StartSound(&ceiling->sector->soundorg, sfx_pstop); case crushAndRaise: ceiling->speed = CEILSPEED; case fastCrushAndRaise: ceiling->direction = 1; break; case lowerAndCrush: case lowerToFloor: P_RemoveActiveCeiling(ceiling); break; default: break; } } else // ( res != pastdest ) { if (res == crushed) { switch(ceiling->type) { case silentCrushAndRaise: case crushAndRaise: case lowerAndCrush: ceiling->speed = CEILSPEED / 8; break; default: break; } } } break; } } // // EV_DoCeiling // Move a ceiling up/down and all around! // int EV_DoCeiling ( line_t* line, ceiling_e type ) { int secnum; int rtn; sector_t* sec; ceiling_t* ceiling; secnum = -1; rtn = 0; // Reactivate in-stasis ceilings...for certain types. switch(type) { case fastCrushAndRaise: case silentCrushAndRaise: case crushAndRaise: P_ActivateInStasisCeiling(line); default: break; } while ((secnum = P_FindSectorFromLineTag(line,secnum)) >= 0) { sec = &sectors[secnum]; if (sec->specialdata) continue; // new door thinker rtn = 1; ceiling = Z_Malloc (sizeof(*ceiling), PU_LEVSPEC, 0); P_AddThinker (&ceiling->thinker); sec->specialdata = ceiling; ceiling->thinker.function.acp1 = (actionf_p1)T_MoveCeiling; ceiling->sector = sec; ceiling->crush = false; switch(type) { case fastCrushAndRaise: ceiling->crush = true; ceiling->topheight = sec->ceilingheight; ceiling->bottomheight = sec->floorheight + (8*FRACUNIT); ceiling->direction = -1; ceiling->speed = CEILSPEED * 2; break; case silentCrushAndRaise: case crushAndRaise: ceiling->crush = true; ceiling->topheight = sec->ceilingheight; case lowerAndCrush: case lowerToFloor: ceiling->bottomheight = sec->floorheight; if (type != lowerToFloor) ceiling->bottomheight += 8*FRACUNIT; ceiling->direction = -1; ceiling->speed = CEILSPEED; break; case raiseToHighest: ceiling->topheight = P_FindHighestCeilingSurrounding(sec); ceiling->direction = 1; ceiling->speed = CEILSPEED; break; } ceiling->tag = sec->tag; ceiling->type = type; P_AddActiveCeiling(ceiling); } return rtn; } // // Add an active ceiling // void P_AddActiveCeiling(ceiling_t* c) { int i; for (i = 0; i < MAXCEILINGS;i++) { if (activeceilings[i] == NULL) { activeceilings[i] = c; return; } } } // // Remove a ceiling's thinker // void P_RemoveActiveCeiling(ceiling_t* c) { int i; for (i = 0;i < MAXCEILINGS;i++) { if (activeceilings[i] == c) { activeceilings[i]->sector->specialdata = NULL; P_RemoveThinker (&activeceilings[i]->thinker); activeceilings[i] = NULL; break; } } } // // Restart a ceiling that's in-stasis // void P_ActivateInStasisCeiling(line_t* line) { int i; for (i = 0;i < MAXCEILINGS;i++) { if (activeceilings[i] && (activeceilings[i]->tag == line->tag) && (activeceilings[i]->direction == 0)) { activeceilings[i]->direction = activeceilings[i]->olddirection; activeceilings[i]->thinker.function.acp1 = (actionf_p1)T_MoveCeiling; } } } // // EV_CeilingCrushStop // Stop a ceiling from crushing! // int EV_CeilingCrushStop(line_t *line) { int i; int rtn; rtn = 0; for (i = 0;i < MAXCEILINGS;i++) { if (activeceilings[i] && (activeceilings[i]->tag == line->tag) && (activeceilings[i]->direction != 0)) { activeceilings[i]->olddirection = activeceilings[i]->direction; activeceilings[i]->thinker.function.acv = (actionf_v)NULL; activeceilings[i]->direction = 0; // in-stasis rtn = 1; } } return rtn; }
0
0.759342
1
0.759342
game-dev
MEDIA
0.761602
game-dev
0.984393
1
0.984393
PaintLab/PixelFarm
58,755
src/PixelFarm/BackEnd.MiniOpenTK/src/OpenTK/Audio/OpenAL/AL/EffectsExtension.cs
/* EfxFunctions.cs * C headers: \OpenAL 1.1 SDK\include\ "efx.h", "efx-creative.h", "Efx-Util.h" * Spec: Effects Extension Guide.pdf (bundled with OpenAL SDK) * Copyright (c) 2008 Christoph Brandtner and Stefanos Apostolopoulos * See license.txt for license details * http://www.OpenTK.net */ using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace OpenTK.Audio.OpenAL { /// <summary> /// Provides access to the OpenAL effects extension. /// </summary> public partial class EffectsExtension { /// <summary>(Helper) Selects the Effect type used by this Effect handle.</summary> /// <param name="eid">Effect id returned from a successful call to GenEffects.</param> /// <param name="type">Effect type.</param> [CLSCompliant(false)] public void BindEffect(uint eid, EfxEffectType type) { Imported_alEffecti(eid, EfxEffecti.EffectType, (int)type); } /// <summary>(Helper) Selects the Effect type used by this Effect handle.</summary> /// <param name="eid">Effect id returned from a successful call to GenEffects.</param> /// <param name="type">Effect type.</param> public void BindEffect(int eid, EfxEffectType type) { Imported_alEffecti((uint)eid, EfxEffecti.EffectType, (int)type); } /// <summary>(Helper) reroutes the output of a Source through a Filter.</summary> /// <param name="source">A valid Source handle.</param> /// <param name="filter">A valid Filter handle.</param> [CLSCompliant(false)] public void BindFilterToSource(uint source, uint filter) { AL.Source(source, ALSourcei.EfxDirectFilter, (int)filter); } /// <summary>(Helper) reroutes the output of a Source through a Filter.</summary> /// <param name="source">A valid Source handle.</param> /// <param name="filter">A valid Filter handle.</param> public void BindFilterToSource(int source, int filter) { AL.Source((uint)source, ALSourcei.EfxDirectFilter, (int)filter); } /// <summary>(Helper) Attaches an Effect to an Auxiliary Effect Slot.</summary> /// <param name="auxiliaryeffectslot">The slot handle to attach the Effect to.</param> /// <param name="effect">The Effect handle that is being attached.</param> [CLSCompliant(false)] public void BindEffectToAuxiliarySlot(uint auxiliaryeffectslot, uint effect) { AuxiliaryEffectSlot(auxiliaryeffectslot, EfxAuxiliaryi.EffectslotEffect, (int)effect); } /// <summary>(Helper) Attaches an Effect to an Auxiliary Effect Slot.</summary> /// <param name="auxiliaryeffectslot">The slot handle to attach the Effect to.</param> /// <param name="effect">The Effect handle that is being attached.</param> public void BindEffectToAuxiliarySlot(int auxiliaryeffectslot, int effect) { AuxiliaryEffectSlot((uint)auxiliaryeffectslot, EfxAuxiliaryi.EffectslotEffect, (int)effect); } /// <summary>(Helper) Reroutes a Source's output into an Auxiliary Effect Slot.</summary> /// <param name="source">The Source handle who's output is forwarded.</param> /// <param name="slot">The Auxiliary Effect Slot handle that receives input from the Source.</param> /// <param name="slotnumber">Every Source has only a limited number of slots it can feed buffer to. The number must stay below AlcContextAttributes.EfxMaxAuxiliarySends</param> /// <param name="filter">Filter handle to be attached between Source ouput and Auxiliary Slot input. Use 0 or EfxFilterType.FilterNull for no filter. </param> [CLSCompliant(false)] public void BindSourceToAuxiliarySlot(uint source, uint slot, int slotnumber, uint filter) { AL.Source(source, ALSource3i.EfxAuxiliarySendFilter, (int)slot, (int)slotnumber, (int)filter); } /// <summary>(Helper) Reroutes a Source's output into an Auxiliary Effect Slot.</summary> /// <param name="source">The Source handle who's output is forwarded.</param> /// <param name="slot">The Auxiliary Effect Slot handle that receives input from the Source.</param> /// <param name="slotnumber">Every Source has only a limited number of slots it can feed buffer to. The number must stay below AlcContextAttributes.EfxMaxAuxiliarySends</param> /// <param name="filter">Filter handle to be attached between Source ouput and Auxiliary Slot input. Use 0 or EfxFilterType.FilterNull for no filter. </param> public void BindSourceToAuxiliarySlot(int source, int slot, int slotnumber, int filter) { AL.Source((uint)source, ALSource3i.EfxAuxiliarySendFilter, (int)slot, (int)slotnumber, (int)filter); } //[CLSCompliant(false)] unsafe private delegate void Delegate_alGenEffects(int n, [Out] uint* effects); // typedef void (__cdecl *LPALGENEFFECTS)( ALsizei n, ALuint* effects ); //[CLSCompliant(false)] private Delegate_alGenEffects Imported_alGenEffects; /// <summary>The GenEffects function is used to create one or more Effect objects. An Effect object stores an effect type and a set of parameter values to control that Effect. In order to use an Effect it must be attached to an Auxiliary Effect Slot object</summary> /// <remarks>After creation an Effect has no type (EfxEffectType.Null), so before it can be used to store a set of parameters, the application must specify what type of effect should be stored in the object, using Effect() with EfxEffecti.</remarks> /// <param name="n">Number of Effects to be created.</param> /// <param name="effects">Pointer addressing sufficient memory to store n Effect object identifiers.</param> [CLSCompliant(false)] public void GenEffects(int n, out uint effects) { unsafe { fixed (uint* ptr = &effects) { Imported_alGenEffects(n, ptr); effects = *ptr; } } } /// <summary>The GenEffects function is used to create one or more Effect objects. An Effect object stores an effect type and a set of parameter values to control that Effect. In order to use an Effect it must be attached to an Auxiliary Effect Slot object</summary> /// <remarks>After creation an Effect has no type (EfxEffectType.Null), so before it can be used to store a set of parameters, the application must specify what type of effect should be stored in the object, using Effect() with EfxEffecti.</remarks> /// <param name="n">Number of Effects to be created.</param> /// <param name="effects">Pointer addressing sufficient memory to store n Effect object identifiers.</param> public void GenEffects(int n, out int effects) { unsafe { fixed (int* ptr = &effects) { Imported_alGenEffects(n, (uint*)ptr); effects = *ptr; } } } /// <summary>Generates one or more effect objects.</summary> /// <param name="n">Number of Effect object identifiers to generate.</param> /// <remarks> /// <para>The GenEffects function is used to create one or more Effect objects. An Effect object stores an effect type and a set of parameter values to control that Effect. In order to use an Effect it must be attached to an Auxiliary Effect Slot object.</para> /// <para>After creation an Effect has no type (EfxEffectType.Null), so before it can be used to store a set of parameters, the application must specify what type of effect should be stored in the object, using Effect() with EfxEffecti.</para> /// </remarks> public int[] GenEffects(int n) { if (n <= 0) { throw new ArgumentOutOfRangeException("n", "Must be higher than 0."); } int[] effects = new int[n]; GenEffects(n, out effects[0]); return effects; } /// <summary>Generates a single effect object.</summary> /// <returns>A handle to the generated effect object.</returns> /// <remarks> /// <para>The GenEffects function is used to create one or more Effect objects. An Effect object stores an effect type and a set of parameter values to control that Effect. In order to use an Effect it must be attached to an Auxiliary Effect Slot object.</para> /// <para>After creation an Effect has no type (EfxEffectType.Null), so before it can be used to store a set of parameters, the application must specify what type of effect should be stored in the object, using Effect() with EfxEffecti.</para> /// </remarks> public int GenEffect() { int temp; GenEffects(1, out temp); return temp; } /// <summary>Generates a single effect object.</summary> /// <param name="effect">A handle to the generated effect object.</param> [CLSCompliant(false)] public void GenEffect(out uint effect) { unsafe { fixed (uint* ptr = &effect) { Imported_alGenEffects(1, ptr); effect = *ptr; } } } //[CLSCompliant(false)] unsafe private delegate void Delegate_alDeleteEffects(int n, [In] uint* effects); // typedef void (__cdecl *LPALDELETEEFFECTS)( ALsizei n, ALuint* effects ); //[CLSCompliant(false)] private Delegate_alDeleteEffects Imported_alDeleteEffects; /// <summary>The DeleteEffects function is used to delete and free resources for Effect objects previously created with GenEffects.</summary> /// <param name="n">Number of Effects to be deleted.</param> /// <param name="effects">Pointer to n Effect object identifiers.</param> [CLSCompliant(false)] public void DeleteEffects(int n, ref uint effects) { unsafe { fixed (uint* ptr = &effects) { Imported_alDeleteEffects(n, ptr); } } } /// <summary>The DeleteEffects function is used to delete and free resources for Effect objects previously created with GenEffects.</summary> /// <param name="n">Number of Effects to be deleted.</param> /// <param name="effects">Pointer to n Effect object identifiers.</param> public void DeleteEffects(int n, ref int effects) { unsafe { fixed (int* ptr = &effects) { Imported_alDeleteEffects(n, (uint*)ptr); } } } /// <summary>The DeleteEffects function is used to delete and free resources for Effect objects previously created with GenEffects.</summary> /// <param name="effects">Pointer to n Effect object identifiers.</param> public void DeleteEffects(int[] effects) { if (effects == null) { throw new ArgumentNullException("effects"); } DeleteEffects(effects.Length, ref effects[0]); } /// <summary>The DeleteEffects function is used to delete and free resources for Effect objects previously created with GenEffects.</summary> /// <param name="effects">Pointer to n Effect object identifiers.</param> [CLSCompliant(false)] public void DeleteEffects(uint[] effects) { if (effects == null) { throw new ArgumentNullException("effects"); } DeleteEffects(effects.Length, ref effects[0]); } /// <summary>This function deletes one Effect only.</summary> /// <param name="effect">Pointer to an effect name/handle identifying the Effect Object to be deleted.</param> public void DeleteEffect(int effect) { DeleteEffects(1, ref effect); } /// <summary>This function deletes one Effect only.</summary> /// <param name="effect">Pointer to an effect name/handle identifying the Effect Object to be deleted.</param> [CLSCompliant(false)] public void DeleteEffect(ref uint effect) { unsafe { fixed (uint* ptr = &effect) { Imported_alDeleteEffects(1, ptr); } } } //[CLSCompliant(false)] private delegate bool Delegate_alIsEffect(uint eid); // typedef ALboolean (__cdecl *LPALISEFFECT)( ALuint eid ); //[CLSCompliant(false)] private Delegate_alIsEffect Imported_alIsEffect; /// <summary>The IsEffect function is used to determine if an object identifier is a valid Effect object.</summary> /// <param name="eid">Effect identifier to validate.</param> /// <returns>True if the identifier is a valid Effect, False otherwise.</returns> [CLSCompliant(false)] public bool IsEffect(uint eid) { return Imported_alIsEffect(eid); } /// <summary>The IsEffect function is used to determine if an object identifier is a valid Effect object.</summary> /// <param name="eid">Effect identifier to validate.</param> /// <returns>True if the identifier is a valid Effect, False otherwise.</returns> public bool IsEffect(int eid) { return Imported_alIsEffect((uint)eid); } //[CLSCompliant(false)] private delegate void Delegate_alEffecti(uint eid, EfxEffecti param, int value); // typedef void (__cdecl *LPALEFFECTI)( ALuint eid, ALenum param, ALint value); //[CLSCompliant(false)] private Delegate_alEffecti Imported_alEffecti; /// <summary>This function is used to set integer properties on Effect objects.</summary> /// <param name="eid">Effect object identifier.</param> /// <param name="param">Effect property to set.</param> /// <param name="value">Integer value.</param> [CLSCompliant(false)] public void Effect(uint eid, EfxEffecti param, int value) { Imported_alEffecti(eid, param, value); } /// <summary>This function is used to set integer properties on Effect objects.</summary> /// <param name="eid">Effect object identifier.</param> /// <param name="param">Effect property to set.</param> /// <param name="value">Integer value.</param> public void Effect(int eid, EfxEffecti param, int value) { Imported_alEffecti((uint)eid, param, value); } //[CLSCompliant(false)] private delegate void Delegate_alEffectf(uint eid, EfxEffectf param, float value); // typedef void (__cdecl *LPALEFFECTF)( ALuint eid, ALenum param, ALfloat value); //[CLSCompliant(false)] private Delegate_alEffectf Imported_alEffectf; /// <summary>This function is used to set floating-point properties on Effect objects.</summary> /// <param name="eid">Effect object identifier.</param> /// <param name="param">Effect property to set.</param> /// <param name="value">Floating-point value.</param> [CLSCompliant(false)] public void Effect(uint eid, EfxEffectf param, float value) { Imported_alEffectf(eid, param, value); } /// <summary>This function is used to set floating-point properties on Effect objects.</summary> /// <param name="eid">Effect object identifier.</param> /// <param name="param">Effect property to set.</param> /// <param name="value">Floating-point value.</param> public void Effect(int eid, EfxEffectf param, float value) { Imported_alEffectf((uint)eid, param, value); } //[CLSCompliant(false)] unsafe private delegate void Delegate_alEffectfv(uint eid, EfxEffect3f param, [In] float* values); // typedef void (__cdecl *LPALEFFECTFV)( ALuint eid, ALenum param, ALfloat* values ); //[CLSCompliant(false)] private Delegate_alEffectfv Imported_alEffectfv; /// <summary>This function is used to set 3 floating-point properties on Effect objects.</summary> /// <param name="eid">Effect object identifier.</param> /// <param name="param">Effect property to set.</param> /// <param name="values">Pointer to Math.Vector3.</param> [CLSCompliant(false)] public void Effect(uint eid, EfxEffect3f param, ref Vector3 values) { unsafe { fixed (float* ptr = &values.X) { Imported_alEffectfv(eid, param, ptr); } } } /// <summary>This function is used to set 3 floating-point properties on Effect objects.</summary> /// <param name="eid">Effect object identifier.</param> /// <param name="param">Effect property to set.</param> /// <param name="values">Pointer to Math.Vector3.</param> public void Effect(int eid, EfxEffect3f param, ref Vector3 values) { Effect((uint)eid, param, ref values); } //[CLSCompliant(false)] unsafe private delegate void Delegate_alGetEffecti(uint eid, EfxEffecti pname, [Out] int* value); // typedef void (__cdecl *LPALGETEFFECTI)( ALuint eid, ALenum pname, ALint* value ); //[CLSCompliant(false)] private Delegate_alGetEffecti Imported_alGetEffecti; /// <summary>This function is used to retrieve integer properties from Effect objects.</summary> /// <param name="eid">Effect object identifier.</param> /// <param name="pname">Effect property to retrieve.</param> /// <param name="value">Address where integer value will be stored.</param> [CLSCompliant(false)] public void GetEffect(uint eid, EfxEffecti pname, out int value) { unsafe { fixed (int* ptr = &value) { Imported_alGetEffecti(eid, pname, ptr); } } } /// <summary>This function is used to retrieve integer properties from Effect objects.</summary> /// <param name="eid">Effect object identifier.</param> /// <param name="pname">Effect property to retrieve.</param> /// <param name="value">Address where integer value will be stored.</param> public void GetEffect(int eid, EfxEffecti pname, out int value) { GetEffect((uint)eid, pname, out value); } //[CLSCompliant(false)] unsafe private delegate void Delegate_alGetEffectf(uint eid, EfxEffectf pname, [Out]float* value); // typedef void (__cdecl *LPALGETEFFECTF)( ALuint eid, ALenum pname, ALfloat* value ); //[CLSCompliant(false)] private Delegate_alGetEffectf Imported_alGetEffectf; /// <summary>This function is used to retrieve floating-point properties from Effect objects.</summary> /// <param name="eid">Effect object identifier.</param> /// <param name="pname">Effect property to retrieve.</param> /// <param name="value">Address where floating-point value will be stored.</param> [CLSCompliant(false)] public void GetEffect(uint eid, EfxEffectf pname, out float value) { unsafe { fixed (float* ptr = &value) { Imported_alGetEffectf(eid, pname, ptr); } } } /// <summary>This function is used to retrieve floating-point properties from Effect objects.</summary> /// <param name="eid">Effect object identifier.</param> /// <param name="pname">Effect property to retrieve.</param> /// <param name="value">Address where floating-point value will be stored.</param> public void GetEffect(int eid, EfxEffectf pname, out float value) { GetEffect((uint)eid, pname, out value); } //[CLSCompliant(false)] unsafe private delegate void Delegate_alGetEffectfv(uint eid, EfxEffect3f param, [Out] float* values); // typedef void (__cdecl *LPALGETEFFECTFV)( ALuint eid, ALenum pname, ALfloat* values ); //[CLSCompliant(false)] private Delegate_alGetEffectfv Imported_alGetEffectfv; /// <summary>This function is used to retrieve 3 floating-point properties from Effect objects.</summary> /// <param name="eid">Effect object identifier.</param> /// <param name="param">Effect property to retrieve.</param> /// <param name="values">A Math.Vector3 to hold the values.</param> [CLSCompliant(false)] public void GetEffect(uint eid, EfxEffect3f param, out Vector3 values) { unsafe { fixed (float* ptr = &values.X) { Imported_alGetEffectfv(eid, param, ptr); values.X = ptr[0]; values.Y = ptr[1]; values.Z = ptr[2]; } } } /// <summary>This function is used to retrieve 3 floating-point properties from Effect objects.</summary> /// <param name="eid">Effect object identifier.</param> /// <param name="param">Effect property to retrieve.</param> /// <param name="values">A Math.Vector3 to hold the values.</param> public void GetEffect(int eid, EfxEffect3f param, out Vector3 values) { GetEffect((uint)eid, param, out values); } // Not used: // typedef void (__cdecl *LPALEFFECTIV)( ALuint eid, ALenum param, ALint* values ); // typedef void (__cdecl *LPALGETEFFECTIV)( ALuint eid, ALenum pname, ALint* values ); //[CLSCompliant(false)] unsafe private delegate void Delegate_alGenFilters(int n, [Out] uint* filters); // typedef void (__cdecl *LPALGENFILTERS)( ALsizei n, ALuint* filters ); //[CLSCompliant(false)] private Delegate_alGenFilters Imported_alGenFilters; /// <summary>The GenFilters function is used to create one or more Filter objects. A Filter object stores a filter type and a set of parameter values to control that Filter. Filter objects can be attached to Sources as Direct Filters or Auxiliary Send Filters.</summary> /// <remarks>After creation a Filter has no type (EfxFilterType.Null), so before it can be used to store a set of parameters, the application must specify what type of filter should be stored in the object, using Filter() with EfxFilteri.</remarks> /// <param name="n">Number of Filters to be created.</param> /// <param name="filters">Pointer addressing sufficient memory to store n Filter object identifiers.</param> [CLSCompliant(false)] public void GenFilters(int n, out uint filters) { unsafe { fixed (uint* ptr = &filters) { Imported_alGenFilters(n, ptr); filters = *ptr; } } } /// <summary>The GenFilters function is used to create one or more Filter objects. A Filter object stores a filter type and a set of parameter values to control that Filter. Filter objects can be attached to Sources as Direct Filters or Auxiliary Send Filters.</summary> /// <remarks>After creation a Filter has no type (EfxFilterType.Null), so before it can be used to store a set of parameters, the application must specify what type of filter should be stored in the object, using Filter() with EfxFilteri.</remarks> /// <param name="n">Number of Filters to be created.</param> /// <param name="filters">Pointer addressing sufficient memory to store n Filter object identifiers.</param> public void GenFilters(int n, out int filters) { unsafe { fixed (int* ptr = &filters) { Imported_alGenFilters(n, (uint*)ptr); filters = *ptr; } } } /// <summary>The GenFilters function is used to create one or more Filter objects. A Filter object stores a filter type and a set of parameter values to control that Filter. Filter objects can be attached to Sources as Direct Filters or Auxiliary Send Filters.</summary> /// <remarks>After creation a Filter has no type (EfxFilterType.Null), so before it can be used to store a set of parameters, the application must specify what type of filter should be stored in the object, using Filter() with EfxFilteri.</remarks> /// <param name="n">Number of Filters to be created.</param> /// <returns>Pointer addressing sufficient memory to store n Filter object identifiers.</returns> public int[] GenFilters(int n) { if (n <= 0) { throw new ArgumentOutOfRangeException("n", "Must be higher than 0."); } int[] filters = new int[n]; GenFilters(filters.Length, out filters[0]); return filters; } /// <summary>This function generates only one Filter.</summary> /// <returns>Storage Int32 for the new filter name/handle.</returns> public int GenFilter() { int filter; GenFilters(1, out filter); return filter; } /// <summary>This function generates only one Filter.</summary> /// <param name="filter">Storage UInt32 for the new filter name/handle.</param> [CLSCompliant(false)] unsafe public void GenFilter(out uint filter) { unsafe { fixed (uint* ptr = &filter) { Imported_alGenFilters(1, ptr); filter = *ptr; } } } //[CLSCompliant(false)] unsafe private delegate void Delegate_alDeleteFilters(int n, [In] uint* filters); // typedef void (__cdecl *LPALDELETEFILTERS)( ALsizei n, ALuint* filters ); //[CLSCompliant(false)] private Delegate_alDeleteFilters Imported_alDeleteFilters; /// <summary>The DeleteFilters function is used to delete and free resources for Filter objects previously created with GenFilters.</summary> /// <param name="n">Number of Filters to be deleted.</param> /// <param name="filters">Pointer to n Filter object identifiers.</param> [CLSCompliant(false)] public void DeleteFilters(int n, ref uint filters) { unsafe { fixed (uint* ptr = &filters) { Imported_alDeleteFilters(n, ptr); } } } /// <summary>The DeleteFilters function is used to delete and free resources for Filter objects previously created with GenFilters.</summary> /// <param name="n">Number of Filters to be deleted.</param> /// <param name="filters">Pointer to n Filter object identifiers.</param> public void DeleteFilters(int n, ref int filters) { unsafe { fixed (int* ptr = &filters) { Imported_alDeleteFilters(n, (uint*)ptr); } } } /// <summary>This function deletes one Filter only.</summary> /// <param name="filters">Pointer to an filter name/handle identifying the Filter Object to be deleted.</param> [CLSCompliant(false)] public void DeleteFilters(uint[] filters) { if (filters == null) { throw new ArgumentNullException("filters"); } DeleteFilters(filters.Length, ref filters[0]); } /// <summary>This function deletes one Filter only.</summary> /// <param name="filters">Pointer to an filter name/handle identifying the Filter Object to be deleted.</param> public void DeleteFilters(int[] filters) { if (filters == null) { throw new ArgumentNullException("filters"); } DeleteFilters(filters.Length, ref filters[0]); } /// <summary>This function deletes one Filter only.</summary> /// <param name="filter">Pointer to an filter name/handle identifying the Filter Object to be deleted.</param> public void DeleteFilter(int filter) { DeleteFilters(1, ref filter); } /// <summary>This function deletes one Filter only.</summary> /// <param name="filter">Pointer to an filter name/handle identifying the Filter Object to be deleted.</param> [CLSCompliant(false)] public void DeleteFilter(ref uint filter) { unsafe { fixed (uint* ptr = &filter) { Imported_alDeleteFilters(1, ptr); } } } //[CLSCompliant(false)] private delegate bool Delegate_alIsFilter(uint fid); // typedef ALboolean (__cdecl *LPALISFILTER)( ALuint fid ); //[CLSCompliant(false)] private Delegate_alIsFilter Imported_alIsFilter; /// <summary>The IsFilter function is used to determine if an object identifier is a valid Filter object.</summary> /// <param name="fid">Effect identifier to validate.</param> /// <returns>True if the identifier is a valid Filter, False otherwise.</returns> [CLSCompliant(false)] public bool IsFilter(uint fid) { return Imported_alIsFilter(fid); } /// <summary>The IsFilter function is used to determine if an object identifier is a valid Filter object.</summary> /// <param name="fid">Effect identifier to validate.</param> /// <returns>True if the identifier is a valid Filter, False otherwise.</returns> public bool IsFilter(int fid) { return Imported_alIsFilter((uint)fid); } //[CLSCompliant(false)] private delegate void Delegate_alFilteri(uint fid, EfxFilteri param, int value); // typedef void (__cdecl *LPALFILTERI)( ALuint fid, ALenum param, ALint value ); //[CLSCompliant(false)] private Delegate_alFilteri Imported_alFilteri; /// <summary>This function is used to set integer properties on Filter objects.</summary> /// <param name="fid">Filter object identifier.</param> /// <param name="param">Effect property to set.</param> /// <param name="value">Integer value.</param> [CLSCompliant(false)] public void Filter(uint fid, EfxFilteri param, int value) { Imported_alFilteri(fid, param, value); } /// <summary>This function is used to set integer properties on Filter objects.</summary> /// <param name="fid">Filter object identifier.</param> /// <param name="param">Effect property to set.</param> /// <param name="value">Integer value.</param> public void Filter(int fid, EfxFilteri param, int value) { Imported_alFilteri((uint)fid, param, value); } //[CLSCompliant(false)] private delegate void Delegate_alFilterf(uint fid, EfxFilterf param, float value); // typedef void (__cdecl *LPALFILTERF)( ALuint fid, ALenum param, ALfloat value); //[CLSCompliant(false)] private Delegate_alFilterf Imported_alFilterf; /// <summary>This function is used to set floating-point properties on Filter objects.</summary> /// <param name="fid">Filter object identifier.</param> /// <param name="param">Effect property to set.</param> /// <param name="value">Floating-point value.</param> [CLSCompliant(false)] public void Filter(uint fid, EfxFilterf param, float value) { Imported_alFilterf(fid, param, value); } /// <summary>This function is used to set floating-point properties on Filter objects.</summary> /// <param name="fid">Filter object identifier.</param> /// <param name="param">Effect property to set.</param> /// <param name="value">Floating-point value.</param> public void Filter(int fid, EfxFilterf param, float value) { Imported_alFilterf((uint)fid, param, value); } //[CLSCompliant(false)] unsafe private delegate void Delegate_alGetFilteri(uint fid, EfxFilteri pname, [Out] int* value); // typedef void (__cdecl *LPALGETFILTERI)( ALuint fid, ALenum pname, ALint* value ); //[CLSCompliant(false)] private Delegate_alGetFilteri Imported_alGetFilteri; /// <summary>This function is used to retrieve integer properties from Filter objects.</summary> /// <param name="fid">Filter object identifier.</param> /// <param name="pname">Effect property to retrieve.</param> /// <param name="value">Address where integer value will be stored.</param> [CLSCompliant(false)] public void GetFilter(uint fid, EfxFilteri pname, out int value) { unsafe { fixed (int* ptr = &value) { Imported_alGetFilteri(fid, pname, ptr); } } } /// <summary>This function is used to retrieve integer properties from Filter objects.</summary> /// <param name="fid">Filter object identifier.</param> /// <param name="pname">Effect property to retrieve.</param> /// <param name="value">Address where integer value will be stored.</param> public void GetFilter(int fid, EfxFilteri pname, out int value) { GetFilter((uint)fid, pname, out value); } //[CLSCompliant(false)] unsafe private delegate void Delegate_alGetFilterf(uint fid, EfxFilterf pname, [Out] float* value); // typedef void (__cdecl *LPALGETFILTERF)( ALuint fid, ALenum pname, ALfloat* value ); //[CLSCompliant(false)] private Delegate_alGetFilterf Imported_alGetFilterf; /// <summary>This function is used to retrieve floating-point properties from Filter objects.</summary> /// <param name="fid">Filter object identifier.</param> /// <param name="pname">Effect property to retrieve.</param> /// <param name="value">Address where floating-point value will be stored.</param> [CLSCompliant(false)] public void GetFilter(uint fid, EfxFilterf pname, out float value) { unsafe { fixed (float* ptr = &value) { Imported_alGetFilterf(fid, pname, ptr); } } } /// <summary>This function is used to retrieve floating-point properties from Filter objects.</summary> /// <param name="fid">Filter object identifier.</param> /// <param name="pname">Effect property to retrieve.</param> /// <param name="value">Address where floating-point value will be stored.</param> public void GetFilter(int fid, EfxFilterf pname, out float value) { GetFilter((uint)fid, pname, out value); } // Not used: // typedef void (__cdecl *LPALFILTERIV)( ALuint fid, ALenum param, ALint* values ); // typedef void (__cdecl *LPALFILTERFV)( ALuint fid, ALenum param, ALfloat* values ); // typedef void (__cdecl *LPALGETFILTERIV)( ALuint fid, ALenum pname, ALint* values ); // typedef void (__cdecl *LPALGETFILTERFV)( ALuint fid, ALenum pname, ALfloat* values ); //[CLSCompliant(false)] unsafe private delegate void Delegate_alGenAuxiliaryEffectSlots(int n, [Out] uint* slots); // typedef void (__cdecl *LPALGENAUXILIARYEFFECTSLOTS)( ALsizei n, ALuint* slots ); //[CLSCompliant(false)] private Delegate_alGenAuxiliaryEffectSlots Imported_alGenAuxiliaryEffectSlots; /// <summary>The GenAuxiliaryEffectSlots function is used to create one or more Auxiliary Effect Slots. The number of slots that can be created will be dependant upon the Open AL device used.</summary> /// <remarks>An application should check the OpenAL error state after making this call to determine if the Effect Slot was successfully created. If the function call fails then none of the requested Effect Slots are created. A good strategy for creating any OpenAL object is to use a for-loop and generate one object each loop iteration and then check for an error condition. If an error is set then the loop can be broken and the application can determine if sufficient resources are available.</remarks> /// <param name="n">Number of Auxiliary Effect Slots to be created.</param> /// <param name="slots">Pointer addressing sufficient memory to store n Effect Slot object identifiers.</param> [CLSCompliant(false)] public void GenAuxiliaryEffectSlots(int n, out uint slots) { unsafe { fixed (uint* ptr = &slots) { Imported_alGenAuxiliaryEffectSlots(n, ptr); slots = *ptr; } } } /// <summary>The GenAuxiliaryEffectSlots function is used to create one or more Auxiliary Effect Slots. The number of slots that can be created will be dependant upon the Open AL device used.</summary> /// <remarks>An application should check the OpenAL error state after making this call to determine if the Effect Slot was successfully created. If the function call fails then none of the requested Effect Slots are created. A good strategy for creating any OpenAL object is to use a for-loop and generate one object each loop iteration and then check for an error condition. If an error is set then the loop can be broken and the application can determine if sufficient resources are available.</remarks> /// <param name="n">Number of Auxiliary Effect Slots to be created.</param> /// <param name="slots">Pointer addressing sufficient memory to store n Effect Slot object identifiers.</param> public void GenAuxiliaryEffectSlots(int n, out int slots) { unsafe { fixed (int* ptr = &slots) { Imported_alGenAuxiliaryEffectSlots(n, (uint*)ptr); slots = *ptr; } } } /// <summary>The GenAuxiliaryEffectSlots function is used to create one or more Auxiliary Effect Slots. The number of slots that can be created will be dependant upon the Open AL device used.</summary> /// <remarks>An application should check the OpenAL error state after making this call to determine if the Effect Slot was successfully created. If the function call fails then none of the requested Effect Slots are created. A good strategy for creating any OpenAL object is to use a for-loop and generate one object each loop iteration and then check for an error condition. If an error is set then the loop can be broken and the application can determine if sufficient resources are available.</remarks> /// <param name="n">Number of Auxiliary Effect Slots to be created.</param> /// <returns>Pointer addressing sufficient memory to store n Effect Slot object identifiers.</returns> public int[] GenAuxiliaryEffectSlots(int n) { if (n <= 0) { throw new ArgumentOutOfRangeException("n", "Must be higher than 0."); } int[] slots = new int[n]; GenAuxiliaryEffectSlots(slots.Length, out slots[0]); return slots; } /// <summary>This function generates only one Auxiliary Effect Slot.</summary> /// <returns>Storage Int32 for the new auxiliary effect slot name/handle.</returns> public int GenAuxiliaryEffectSlot() { int temp; GenAuxiliaryEffectSlots(1, out temp); return temp; } /// <summary>This function generates only one Auxiliary Effect Slot.</summary> /// <returns>Storage UInt32 for the new auxiliary effect slot name/handle.</returns> [CLSCompliant(false)] public void GenAuxiliaryEffectSlot(out uint slot) { unsafe { fixed (uint* ptr = &slot) { Imported_alGenAuxiliaryEffectSlots(1, ptr); slot = *ptr; } } } unsafe private delegate void Delegate_alDeleteAuxiliaryEffectSlots(int n, [In] uint* slots); // typedef void (__cdecl *LPALDELETEAUXILIARYEFFECTSLOTS)( ALsizei n, ALuint* slots ); private Delegate_alDeleteAuxiliaryEffectSlots Imported_alDeleteAuxiliaryEffectSlots; /// <summary>The DeleteAuxiliaryEffectSlots function is used to delete and free resources for Auxiliary Effect Slots previously created with GenAuxiliaryEffectSlots.</summary> /// <param name="n">Number of Auxiliary Effect Slots to be deleted.</param> /// <param name="slots">Pointer to n Effect Slot object identifiers.</param> [CLSCompliant(false)] public void DeleteAuxiliaryEffectSlots(int n, ref uint slots) { unsafe { fixed (uint* ptr = &slots) { Imported_alDeleteAuxiliaryEffectSlots(n, ptr); } } } /// <summary>The DeleteAuxiliaryEffectSlots function is used to delete and free resources for Auxiliary Effect Slots previously created with GenAuxiliaryEffectSlots.</summary> /// <param name="n">Number of Auxiliary Effect Slots to be deleted.</param> /// <param name="slots">Pointer to n Effect Slot object identifiers.</param> public void DeleteAuxiliaryEffectSlots(int n, ref int slots) { unsafe { fixed (int* ptr = &slots) { Imported_alDeleteAuxiliaryEffectSlots(n, (uint*)ptr); } } } /// <summary>The DeleteAuxiliaryEffectSlots function is used to delete and free resources for Auxiliary Effect Slots previously created with GenAuxiliaryEffectSlots.</summary> /// <param name="slots">Pointer to n Effect Slot object identifiers.</param> public void DeleteAuxiliaryEffectSlots(int[] slots) { if (slots == null) { throw new ArgumentNullException("slots"); } DeleteAuxiliaryEffectSlots(slots.Length, ref slots[0]); } /// <summary>This function deletes one AuxiliaryEffectSlot only.</summary> /// <param name="slots">Pointer to an auxiliary effect slot name/handle identifying the Auxiliary Effect Slot Object to be deleted.</param> [CLSCompliant(false)] public void DeleteAuxiliaryEffectSlots(uint[] slots) { if (slots == null) { throw new ArgumentNullException("slots"); } DeleteAuxiliaryEffectSlots(slots.Length, ref slots[0]); } /// <summary>This function deletes one AuxiliaryEffectSlot only.</summary> /// <param name="slot">Pointer to an auxiliary effect slot name/handle identifying the Auxiliary Effect Slot Object to be deleted.</param> public void DeleteAuxiliaryEffectSlot(int slot) { DeleteAuxiliaryEffectSlots(1, ref slot); } /// <summary>This function deletes one AuxiliaryEffectSlot only.</summary> /// <param name="slot">Pointer to an auxiliary effect slot name/handle identifying the Auxiliary Effect Slot Object to be deleted.</param> [CLSCompliant(false)] public void DeleteAuxiliaryEffectSlot(ref uint slot) { unsafe { fixed (uint* ptr = &slot) { Imported_alDeleteAuxiliaryEffectSlots(1, ptr); } } } //[CLSCompliant(false)] private delegate bool Delegate_alIsAuxiliaryEffectSlot(uint slot); // typedef ALboolean (__cdecl *LPALISAUXILIARYEFFECTSLOT)( ALuint slot ); //[CLSCompliant(false)] private Delegate_alIsAuxiliaryEffectSlot Imported_alIsAuxiliaryEffectSlot; /// <summary>The IsAuxiliaryEffectSlot function is used to determine if an object identifier is a valid Auxiliary Effect Slot object.</summary> /// <param name="slot">Effect Slot object identifier to validate.</param> /// <returns>True if the identifier is a valid Auxiliary Effect Slot, False otherwise.</returns> [CLSCompliant(false)] public bool IsAuxiliaryEffectSlot(uint slot) { return Imported_alIsAuxiliaryEffectSlot(slot); } /// <summary>The IsAuxiliaryEffectSlot function is used to determine if an object identifier is a valid Auxiliary Effect Slot object.</summary> /// <param name="slot">Effect Slot object identifier to validate.</param> /// <returns>True if the identifier is a valid Auxiliary Effect Slot, False otherwise.</returns> public bool IsAuxiliaryEffectSlot(int slot) { return Imported_alIsAuxiliaryEffectSlot((uint)slot); } //[CLSCompliant(false)] private delegate void Delegate_alAuxiliaryEffectSloti(uint asid, EfxAuxiliaryi param, int value); // typedef void (__cdecl *LPALAUXILIARYEFFECTSLOTI)( ALuint asid, ALenum param, ALint value ); //[CLSCompliant(false)] private Delegate_alAuxiliaryEffectSloti Imported_alAuxiliaryEffectSloti; /// <summary>This function is used to set integer properties on Auxiliary Effect Slot objects.</summary> /// <param name="asid">Auxiliary Effect Slot object identifier.</param> /// <param name="param">Auxiliary Effect Slot property to set.</param> /// <param name="value">Integer value.</param> [CLSCompliant(false)] public void AuxiliaryEffectSlot(uint asid, EfxAuxiliaryi param, int value) { Imported_alAuxiliaryEffectSloti(asid, param, value); } /// <summary>This function is used to set integer properties on Auxiliary Effect Slot objects.</summary> /// <param name="asid">Auxiliary Effect Slot object identifier.</param> /// <param name="param">Auxiliary Effect Slot property to set.</param> /// <param name="value">Integer value.</param> public void AuxiliaryEffectSlot(int asid, EfxAuxiliaryi param, int value) { Imported_alAuxiliaryEffectSloti((uint)asid, param, value); } //[CLSCompliant(false)] private delegate void Delegate_alAuxiliaryEffectSlotf(uint asid, EfxAuxiliaryf param, float value); // typedef void (__cdecl *LPALAUXILIARYEFFECTSLOTF)( ALuint asid, ALenum param, ALfloat value ); //[CLSCompliant(false)] private Delegate_alAuxiliaryEffectSlotf Imported_alAuxiliaryEffectSlotf; /// <summary>This function is used to set floating-point properties on Auxiliary Effect Slot objects.</summary> /// <param name="asid">Auxiliary Effect Slot object identifier.</param> /// <param name="param">Auxiliary Effect Slot property to set.</param> /// <param name="value">Floating-point value.</param> [CLSCompliant(false)] public void AuxiliaryEffectSlot(uint asid, EfxAuxiliaryf param, float value) { Imported_alAuxiliaryEffectSlotf(asid, param, value); } /// <summary>This function is used to set floating-point properties on Auxiliary Effect Slot objects.</summary> /// <param name="asid">Auxiliary Effect Slot object identifier.</param> /// <param name="param">Auxiliary Effect Slot property to set.</param> /// <param name="value">Floating-point value.</param> public void AuxiliaryEffectSlot(int asid, EfxAuxiliaryf param, float value) { Imported_alAuxiliaryEffectSlotf((uint)asid, param, value); } //[CLSCompliant(false)] unsafe private delegate void Delegate_alGetAuxiliaryEffectSloti(uint asid, EfxAuxiliaryi pname, [Out] int* value); // typedef void (__cdecl *LPALGETAUXILIARYEFFECTSLOTI)( ALuint asid, ALenum pname, ALint* value ); //[CLSCompliant(false)] private Delegate_alGetAuxiliaryEffectSloti Imported_alGetAuxiliaryEffectSloti; /// <summary>This function is used to retrieve integer properties on Auxiliary Effect Slot objects.</summary> /// <param name="asid">Auxiliary Effect Slot object identifier.</param> /// <param name="pname">Auxiliary Effect Slot property to retrieve.</param> /// <param name="value">Address where integer value will be stored.</param> [CLSCompliant(false)] public void GetAuxiliaryEffectSlot(uint asid, EfxAuxiliaryi pname, out int value) { unsafe { fixed (int* ptr = &value) { Imported_alGetAuxiliaryEffectSloti(asid, pname, ptr); } } } /// <summary>This function is used to retrieve integer properties on Auxiliary Effect Slot objects.</summary> /// <param name="asid">Auxiliary Effect Slot object identifier.</param> /// <param name="pname">Auxiliary Effect Slot property to retrieve.</param> /// <param name="value">Address where integer value will be stored.</param> public void GetAuxiliaryEffectSlot(int asid, EfxAuxiliaryi pname, out int value) { GetAuxiliaryEffectSlot((uint)asid, pname, out value); } //[CLSCompliant(false)] unsafe private delegate void Delegate_alGetAuxiliaryEffectSlotf(uint asid, EfxAuxiliaryf pname, [Out] float* value); // typedef void (__cdecl *LPALGETAUXILIARYEFFECTSLOTF)( ALuint asid, ALenum pname, ALfloat* value ); //[CLSCompliant(false)] private Delegate_alGetAuxiliaryEffectSlotf Imported_alGetAuxiliaryEffectSlotf; /// <summary>This function is used to retrieve floating properties on Auxiliary Effect Slot objects.</summary> /// <param name="asid">Auxiliary Effect Slot object identifier.</param> /// <param name="pname">Auxiliary Effect Slot property to retrieve.</param> /// <param name="value">Address where floating-point value will be stored.</param> [CLSCompliant(false)] public void GetAuxiliaryEffectSlot(uint asid, EfxAuxiliaryf pname, out float value) { unsafe { fixed (float* ptr = &value) { Imported_alGetAuxiliaryEffectSlotf(asid, pname, ptr); } } } /// <summary>This function is used to retrieve floating properties on Auxiliary Effect Slot objects.</summary> /// <param name="asid">Auxiliary Effect Slot object identifier.</param> /// <param name="pname">Auxiliary Effect Slot property to retrieve.</param> /// <param name="value">Address where floating-point value will be stored.</param> public void GetAuxiliaryEffectSlot(int asid, EfxAuxiliaryf pname, out float value) { GetAuxiliaryEffectSlot((uint)asid, pname, out value); } // Not used: // typedef void (__cdecl *LPALAUXILIARYEFFECTSLOTIV)( ALuint asid, ALenum param, ALint* values ); // typedef void (__cdecl *LPALAUXILIARYEFFECTSLOTFV)( ALuint asid, ALenum param, ALfloat* values ); // typedef void (__cdecl *LPALGETAUXILIARYEFFECTSLOTIV)( ALuint asid, ALenum pname, ALint* values ); // typedef void (__cdecl *LPALGETAUXILIARYEFFECTSLOTFV)( ALuint asid, ALenum pname, ALfloat* values ); /// <summary>Returns True if the EFX Extension has been found and could be initialized.</summary> public bool IsInitialized { get; } /// <summary> /// Constructs a new EffectsExtension instance. /// </summary> public EffectsExtension() { IsInitialized = false; if (AudioContext.CurrentContext == null) { throw new InvalidOperationException("AL.LoadAll() needs a current AudioContext."); } if (!AudioContext.CurrentContext.SupportsExtension("ALC_EXT_EFX")) { Debug.Print("EFX Extension (ALC_EXT_EFX) is not supported(AudioContext: {0}).", AudioContext.CurrentContext.ToString()); return; } // Console.WriteLine("ALC_EXT_EFX found. Efx can be used."); try { Imported_alGenEffects = (Delegate_alGenEffects)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGenEffects"), typeof(Delegate_alGenEffects)); Imported_alDeleteEffects = (Delegate_alDeleteEffects)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alDeleteEffects"), typeof(Delegate_alDeleteEffects)); Imported_alIsEffect = (Delegate_alIsEffect)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alIsEffect"), typeof(Delegate_alIsEffect)); Imported_alEffecti = (Delegate_alEffecti)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alEffecti"), typeof(Delegate_alEffecti)); Imported_alEffectf = (Delegate_alEffectf)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alEffectf"), typeof(Delegate_alEffectf)); Imported_alEffectfv = (Delegate_alEffectfv)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alEffectfv"), typeof(Delegate_alEffectfv)); Imported_alGetEffecti = (Delegate_alGetEffecti)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGetEffecti"), typeof(Delegate_alGetEffecti)); Imported_alGetEffectf = (Delegate_alGetEffectf)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGetEffectf"), typeof(Delegate_alGetEffectf)); Imported_alGetEffectfv = (Delegate_alGetEffectfv)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGetEffectfv"), typeof(Delegate_alGetEffectfv)); } catch (Exception e) { Debug.WriteLine("Failed to marshal Effect functions. " + e.ToString()); return; } // Console.WriteLine("Effect functions appear to be ok."); try { Imported_alGenFilters = (Delegate_alGenFilters)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGenFilters"), typeof(Delegate_alGenFilters)); Imported_alDeleteFilters = (Delegate_alDeleteFilters)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alDeleteFilters"), typeof(Delegate_alDeleteFilters)); Imported_alIsFilter = (Delegate_alIsFilter)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alIsFilter"), typeof(Delegate_alIsFilter)); Imported_alFilteri = (Delegate_alFilteri)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alFilteri"), typeof(Delegate_alFilteri)); Imported_alFilterf = (Delegate_alFilterf)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alFilterf"), typeof(Delegate_alFilterf)); Imported_alGetFilteri = (Delegate_alGetFilteri)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGetFilteri"), typeof(Delegate_alGetFilteri)); Imported_alGetFilterf = (Delegate_alGetFilterf)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGetFilterf"), typeof(Delegate_alGetFilterf)); } catch (Exception e) { Debug.WriteLine("Failed to marshal Filter functions. " + e.ToString()); return; } // Console.WriteLine("Filter functions appear to be ok."); try { Imported_alGenAuxiliaryEffectSlots = (Delegate_alGenAuxiliaryEffectSlots)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGenAuxiliaryEffectSlots"), typeof(Delegate_alGenAuxiliaryEffectSlots)); Imported_alDeleteAuxiliaryEffectSlots = (Delegate_alDeleteAuxiliaryEffectSlots)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alDeleteAuxiliaryEffectSlots"), typeof(Delegate_alDeleteAuxiliaryEffectSlots)); Imported_alIsAuxiliaryEffectSlot = (Delegate_alIsAuxiliaryEffectSlot)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alIsAuxiliaryEffectSlot"), typeof(Delegate_alIsAuxiliaryEffectSlot)); Imported_alAuxiliaryEffectSloti = (Delegate_alAuxiliaryEffectSloti)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alAuxiliaryEffectSloti"), typeof(Delegate_alAuxiliaryEffectSloti)); Imported_alAuxiliaryEffectSlotf = (Delegate_alAuxiliaryEffectSlotf)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alAuxiliaryEffectSlotf"), typeof(Delegate_alAuxiliaryEffectSlotf)); Imported_alGetAuxiliaryEffectSloti = (Delegate_alGetAuxiliaryEffectSloti)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGetAuxiliaryEffectSloti"), typeof(Delegate_alGetAuxiliaryEffectSloti)); Imported_alGetAuxiliaryEffectSlotf = (Delegate_alGetAuxiliaryEffectSlotf)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGetAuxiliaryEffectSlotf"), typeof(Delegate_alGetAuxiliaryEffectSlotf)); } catch (Exception e) { Debug.WriteLine("Failed to marshal AuxiliaryEffectSlot functions. " + e.ToString()); return; } // Console.WriteLine("Auxiliary Effect Slot functions appear to be ok."); // didn't return so far, everything went fine. IsInitialized = true; } } }
0
0.893798
1
0.893798
game-dev
MEDIA
0.235019
game-dev
0.643221
1
0.643221
Ludeon/RimWorld-ChineseSimplified
2,355
Ideology/DefInjected/QuestScriptDef/Script_RelicHunt.xml
<?xml version="1.0" encoding="UTF-8"?> <LanguageData> <!-- EN: <li>questDescription(classicMode==True)->You've learned that a valuable relic is nearby.\n\nThe [relic_name] is one of [relicGlobalCount] ancient objects venerated by many people. If you could collect it, you could build a reliquary to make your colonists happy and attract wealthy pilgrims.</li> <li>questDescription(classicMode==False)->You've learned that a relic of [ideo_name] is nearby.\n\nThe [relic_name] is an ancient object venerated by all [ideo_memberNamePlural]. If you could collect it, you could build a great reliquary to make [ideo_memberNamePlural] happy, attract wealthy pilgrims, and bring more people to [ideo_name].</li> <li>questDescriptionPartBeforeDiscovery->First, you need to find the [relic_name]. Watch for opportunities to gather information about it.</li> --> <RelicHunt.questDescriptionRules.rulesStrings> <li>questDescription(classicMode==True)->你已经知晓一个圣物就在附近。\n\n这个[relic_name]是所有被人们崇敬的[relicGlobalCount]圣物之一。如果你能寻获它, 你就可以建造一个巨型圣物展台供奉它, 能够使你的殖民者开心, 并吸引富有的朝圣者。</li> <li>questDescription(classicMode==False)->你已经知晓一个[ideo_name]的圣物就在附近。\n\n[relic_name]是被所有[ideo_memberNamePlural]崇拜的古物。 如果你能寻获它, 你就可以建造一个巨型圣物展台供奉它, 以便讨[ideo_memberNamePlural]欢心, 并吸引富有的朝圣者, 为[ideo_name]招揽更多信徒。</li> <li>questDescriptionPartBeforeDiscovery->首先,你需要找到[relic_name]。请多加留意有关获取圣物情报的机会。</li> </RelicHunt.questDescriptionRules.rulesStrings> <!-- EN: <li>questName->The [hunt] for the [item]</li> <li>questName->The [itemAdj] [item]</li> <li>questName(classicMode==False)->The [item] of [ideo_name]</li> <li>hunt->hunt</li> <li>hunt->search</li> <li>hunt->quest</li> <li>item(p=4)->[relic_name]</li> <li>item->relic</li> <li>item->artifact</li> <li>itemAdj->ancient</li> <li>itemAdj->revered</li> <li>itemAdj->venerated</li> --> <RelicHunt.questNameRules.rulesStrings> <li>questName->[hunt][item]行动</li> <li>questName->[itemAdj][item]</li> <li>questName(classicMode==False)->[ideo_name]的[item]</li> <li>hunt->寻找</li> <li>hunt->搜寻</li> <li>hunt->探寻</li> <li>item(p=4)->[relic_name]</li> <li>item->圣物</li> <li>item->神器</li> <li>itemAdj->古老的</li> <li>itemAdj->尊崇的</li> <li>itemAdj->被奉为至宝的</li> </RelicHunt.questNameRules.rulesStrings> </LanguageData>
0
0.708064
1
0.708064
game-dev
MEDIA
0.938683
game-dev
0.630369
1
0.630369
a1studmuffin/Cataclysm-DDA-Android
16,549
Android/jni/SDL2/src/video/android/SDL_androidkeyboard.c
/* Simple DirectMedia Layer Copyright (C) 1997-2016 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_ANDROID #include <android/log.h> #include "../../events/SDL_events_c.h" #include "SDL_androidkeyboard.h" #include "../../core/android/SDL_android.h" void Android_InitKeyboard(void) { SDL_Keycode keymap[SDL_NUM_SCANCODES]; /* Add default scancode to key mapping */ SDL_GetDefaultKeymap(keymap); SDL_SetKeymap(0, keymap, SDL_NUM_SCANCODES); } static SDL_Scancode Android_Keycodes[] = { SDL_SCANCODE_UNKNOWN, /* AKEYCODE_UNKNOWN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SOFT_LEFT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SOFT_RIGHT */ SDL_SCANCODE_AC_HOME, /* AKEYCODE_HOME */ SDL_SCANCODE_AC_BACK, /* AKEYCODE_BACK */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CALL */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_ENDCALL */ SDL_SCANCODE_0, /* AKEYCODE_0 */ SDL_SCANCODE_1, /* AKEYCODE_1 */ SDL_SCANCODE_2, /* AKEYCODE_2 */ SDL_SCANCODE_3, /* AKEYCODE_3 */ SDL_SCANCODE_4, /* AKEYCODE_4 */ SDL_SCANCODE_5, /* AKEYCODE_5 */ SDL_SCANCODE_6, /* AKEYCODE_6 */ SDL_SCANCODE_7, /* AKEYCODE_7 */ SDL_SCANCODE_8, /* AKEYCODE_8 */ SDL_SCANCODE_9, /* AKEYCODE_9 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STAR */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_POUND */ SDL_SCANCODE_UP, /* AKEYCODE_DPAD_UP */ SDL_SCANCODE_DOWN, /* AKEYCODE_DPAD_DOWN */ SDL_SCANCODE_LEFT, /* AKEYCODE_DPAD_LEFT */ SDL_SCANCODE_RIGHT, /* AKEYCODE_DPAD_RIGHT */ SDL_SCANCODE_SELECT, /* AKEYCODE_DPAD_CENTER */ SDL_SCANCODE_VOLUMEUP, /* AKEYCODE_VOLUME_UP */ SDL_SCANCODE_VOLUMEDOWN, /* AKEYCODE_VOLUME_DOWN */ SDL_SCANCODE_POWER, /* AKEYCODE_POWER */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CAMERA */ SDL_SCANCODE_CLEAR, /* AKEYCODE_CLEAR */ SDL_SCANCODE_A, /* AKEYCODE_A */ SDL_SCANCODE_B, /* AKEYCODE_B */ SDL_SCANCODE_C, /* AKEYCODE_C */ SDL_SCANCODE_D, /* AKEYCODE_D */ SDL_SCANCODE_E, /* AKEYCODE_E */ SDL_SCANCODE_F, /* AKEYCODE_F */ SDL_SCANCODE_G, /* AKEYCODE_G */ SDL_SCANCODE_H, /* AKEYCODE_H */ SDL_SCANCODE_I, /* AKEYCODE_I */ SDL_SCANCODE_J, /* AKEYCODE_J */ SDL_SCANCODE_K, /* AKEYCODE_K */ SDL_SCANCODE_L, /* AKEYCODE_L */ SDL_SCANCODE_M, /* AKEYCODE_M */ SDL_SCANCODE_N, /* AKEYCODE_N */ SDL_SCANCODE_O, /* AKEYCODE_O */ SDL_SCANCODE_P, /* AKEYCODE_P */ SDL_SCANCODE_Q, /* AKEYCODE_Q */ SDL_SCANCODE_R, /* AKEYCODE_R */ SDL_SCANCODE_S, /* AKEYCODE_S */ SDL_SCANCODE_T, /* AKEYCODE_T */ SDL_SCANCODE_U, /* AKEYCODE_U */ SDL_SCANCODE_V, /* AKEYCODE_V */ SDL_SCANCODE_W, /* AKEYCODE_W */ SDL_SCANCODE_X, /* AKEYCODE_X */ SDL_SCANCODE_Y, /* AKEYCODE_Y */ SDL_SCANCODE_Z, /* AKEYCODE_Z */ SDL_SCANCODE_COMMA, /* AKEYCODE_COMMA */ SDL_SCANCODE_PERIOD, /* AKEYCODE_PERIOD */ SDL_SCANCODE_LALT, /* AKEYCODE_ALT_LEFT */ SDL_SCANCODE_RALT, /* AKEYCODE_ALT_RIGHT */ SDL_SCANCODE_LSHIFT, /* AKEYCODE_SHIFT_LEFT */ SDL_SCANCODE_RSHIFT, /* AKEYCODE_SHIFT_RIGHT */ SDL_SCANCODE_TAB, /* AKEYCODE_TAB */ SDL_SCANCODE_SPACE, /* AKEYCODE_SPACE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SYM */ SDL_SCANCODE_WWW, /* AKEYCODE_EXPLORER */ SDL_SCANCODE_MAIL, /* AKEYCODE_ENVELOPE */ SDL_SCANCODE_RETURN, /* AKEYCODE_ENTER */ SDL_SCANCODE_BACKSPACE, /* AKEYCODE_DEL */ SDL_SCANCODE_GRAVE, /* AKEYCODE_GRAVE */ SDL_SCANCODE_MINUS, /* AKEYCODE_MINUS */ SDL_SCANCODE_EQUALS, /* AKEYCODE_EQUALS */ SDL_SCANCODE_LEFTBRACKET, /* AKEYCODE_LEFT_BRACKET */ SDL_SCANCODE_RIGHTBRACKET, /* AKEYCODE_RIGHT_BRACKET */ SDL_SCANCODE_BACKSLASH, /* AKEYCODE_BACKSLASH */ SDL_SCANCODE_SEMICOLON, /* AKEYCODE_SEMICOLON */ SDL_SCANCODE_APOSTROPHE, /* AKEYCODE_APOSTROPHE */ SDL_SCANCODE_SLASH, /* AKEYCODE_SLASH */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_AT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NUM */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_HEADSETHOOK */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_FOCUS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PLUS */ SDL_SCANCODE_MENU, /* AKEYCODE_MENU */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NOTIFICATION */ SDL_SCANCODE_AC_SEARCH, /* AKEYCODE_SEARCH */ SDL_SCANCODE_AUDIOPLAY, /* AKEYCODE_MEDIA_PLAY_PAUSE */ SDL_SCANCODE_AUDIOSTOP, /* AKEYCODE_MEDIA_STOP */ SDL_SCANCODE_AUDIONEXT, /* AKEYCODE_MEDIA_NEXT */ SDL_SCANCODE_AUDIOPREV, /* AKEYCODE_MEDIA_PREVIOUS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_REWIND */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_FAST_FORWARD */ SDL_SCANCODE_MUTE, /* AKEYCODE_MUTE */ SDL_SCANCODE_PAGEUP, /* AKEYCODE_PAGE_UP */ SDL_SCANCODE_PAGEDOWN, /* AKEYCODE_PAGE_DOWN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PICTSYMBOLS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SWITCH_CHARSET */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_A */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_B */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_C */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_X */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_Y */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_Z */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_L1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_R1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_L2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_R2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_THUMBL */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_THUMBR */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_START */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_SELECT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_MODE */ SDL_SCANCODE_ESCAPE, /* AKEYCODE_ESCAPE */ SDL_SCANCODE_DELETE, /* AKEYCODE_FORWARD_DEL */ SDL_SCANCODE_LCTRL, /* AKEYCODE_CTRL_LEFT */ SDL_SCANCODE_RCTRL, /* AKEYCODE_CTRL_RIGHT */ SDL_SCANCODE_CAPSLOCK, /* AKEYCODE_CAPS_LOCK */ SDL_SCANCODE_SCROLLLOCK, /* AKEYCODE_SCROLL_LOCK */ SDL_SCANCODE_LGUI, /* AKEYCODE_META_LEFT */ SDL_SCANCODE_RGUI, /* AKEYCODE_META_RIGHT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_FUNCTION */ SDL_SCANCODE_PRINTSCREEN, /* AKEYCODE_SYSRQ */ SDL_SCANCODE_PAUSE, /* AKEYCODE_BREAK */ SDL_SCANCODE_HOME, /* AKEYCODE_MOVE_HOME */ SDL_SCANCODE_END, /* AKEYCODE_MOVE_END */ SDL_SCANCODE_INSERT, /* AKEYCODE_INSERT */ SDL_SCANCODE_AC_FORWARD, /* AKEYCODE_FORWARD */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_PLAY */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_PAUSE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_CLOSE */ SDL_SCANCODE_EJECT, /* AKEYCODE_MEDIA_EJECT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_RECORD */ SDL_SCANCODE_F1, /* AKEYCODE_F1 */ SDL_SCANCODE_F2, /* AKEYCODE_F2 */ SDL_SCANCODE_F3, /* AKEYCODE_F3 */ SDL_SCANCODE_F4, /* AKEYCODE_F4 */ SDL_SCANCODE_F5, /* AKEYCODE_F5 */ SDL_SCANCODE_F6, /* AKEYCODE_F6 */ SDL_SCANCODE_F7, /* AKEYCODE_F7 */ SDL_SCANCODE_F8, /* AKEYCODE_F8 */ SDL_SCANCODE_F9, /* AKEYCODE_F9 */ SDL_SCANCODE_F10, /* AKEYCODE_F10 */ SDL_SCANCODE_F11, /* AKEYCODE_F11 */ SDL_SCANCODE_F12, /* AKEYCODE_F12 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NUM_LOCK */ SDL_SCANCODE_KP_0, /* AKEYCODE_NUMPAD_0 */ SDL_SCANCODE_KP_1, /* AKEYCODE_NUMPAD_1 */ SDL_SCANCODE_KP_2, /* AKEYCODE_NUMPAD_2 */ SDL_SCANCODE_KP_3, /* AKEYCODE_NUMPAD_3 */ SDL_SCANCODE_KP_4, /* AKEYCODE_NUMPAD_4 */ SDL_SCANCODE_KP_5, /* AKEYCODE_NUMPAD_5 */ SDL_SCANCODE_KP_6, /* AKEYCODE_NUMPAD_6 */ SDL_SCANCODE_KP_7, /* AKEYCODE_NUMPAD_7 */ SDL_SCANCODE_KP_8, /* AKEYCODE_NUMPAD_8 */ SDL_SCANCODE_KP_9, /* AKEYCODE_NUMPAD_9 */ SDL_SCANCODE_KP_DIVIDE, /* AKEYCODE_NUMPAD_DIVIDE */ SDL_SCANCODE_KP_MULTIPLY, /* AKEYCODE_NUMPAD_MULTIPLY */ SDL_SCANCODE_KP_MINUS, /* AKEYCODE_NUMPAD_SUBTRACT */ SDL_SCANCODE_KP_PLUS, /* AKEYCODE_NUMPAD_ADD */ SDL_SCANCODE_KP_PERIOD, /* AKEYCODE_NUMPAD_DOT */ SDL_SCANCODE_KP_COMMA, /* AKEYCODE_NUMPAD_COMMA */ SDL_SCANCODE_KP_ENTER, /* AKEYCODE_NUMPAD_ENTER */ SDL_SCANCODE_KP_EQUALS, /* AKEYCODE_NUMPAD_EQUALS */ SDL_SCANCODE_KP_LEFTPAREN, /* AKEYCODE_NUMPAD_LEFT_PAREN */ SDL_SCANCODE_KP_RIGHTPAREN, /* AKEYCODE_NUMPAD_RIGHT_PAREN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_VOLUME_MUTE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_INFO */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CHANNEL_UP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CHANNEL_DOWN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_ZOOM_IN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_ZOOM_OUT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_WINDOW */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_GUIDE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_DVR */ SDL_SCANCODE_AC_BOOKMARKS, /* AKEYCODE_BOOKMARK */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CAPTIONS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SETTINGS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_POWER */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STB_POWER */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STB_INPUT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_AVR_POWER */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_AVR_INPUT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PROG_RED */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PROG_GREEN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PROG_YELLOW */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PROG_BLUE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_APP_SWITCH */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_3 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_4 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_5 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_6 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_7 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_8 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_9 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_10 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_11 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_12 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_13 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_14 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_15 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_16 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_LANGUAGE_SWITCH */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MANNER_MODE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_3D_MODE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CONTACTS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CALENDAR */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MUSIC */ SDL_SCANCODE_CALCULATOR, /* AKEYCODE_CALCULATOR */ SDL_SCANCODE_LANG5, /* AKEYCODE_ZENKAKU_HANKAKU */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_EISU */ SDL_SCANCODE_INTERNATIONAL5, /* AKEYCODE_MUHENKAN */ SDL_SCANCODE_INTERNATIONAL4, /* AKEYCODE_HENKAN */ SDL_SCANCODE_LANG3, /* AKEYCODE_KATAKANA_HIRAGANA */ SDL_SCANCODE_INTERNATIONAL3, /* AKEYCODE_YEN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_RO */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_KANA */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_ASSIST */ SDL_SCANCODE_BRIGHTNESSDOWN, /* AKEYCODE_BRIGHTNESS_DOWN */ SDL_SCANCODE_BRIGHTNESSUP, /* AKEYCODE_BRIGHTNESS_UP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_AUDIO_TRACK */ SDL_SCANCODE_SLEEP, /* AKEYCODE_SLEEP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_WAKEUP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PAIRING */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_TOP_MENU */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_11 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_12 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_LAST_CHANNEL */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_DATA_SERVICE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_VOICE_ASSIST */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_RADIO_SERVICE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_TELETEXT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_NUMBER_ENTRY */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_TERRESTRIAL_ANALOG */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_TERRESTRIAL_DIGITAL */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_SATELLITE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_SATELLITE_BS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_SATELLITE_CS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_SATELLITE_SERVICE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_NETWORK */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_ANTENNA_CABLE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_HDMI_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_HDMI_2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_HDMI_3 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_HDMI_4 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_COMPOSITE_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_COMPOSITE_2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_COMPONENT_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_COMPONENT_2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_VGA_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_AUDIO_DESCRIPTION */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_ZOOM_MODE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_CONTENTS_MENU */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_MEDIA_CONTEXT_MENU */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_TIMER_PROGRAMMING */ SDL_SCANCODE_HELP, /* AKEYCODE_HELP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NAVIGATE_PREVIOUS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NAVIGATE_NEXT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NAVIGATE_IN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NAVIGATE_OUT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STEM_PRIMARY */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STEM_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STEM_2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STEM_3 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_DPAD_UP_LEFT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_DPAD_DOWN_LEFT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_DPAD_UP_RIGHT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_DPAD_DOWN_RIGHT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_SKIP_FORWARD */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_SKIP_BACKWARD */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_STEP_FORWARD */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_STEP_BACKWARD */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SOFT_SLEEP */ SDL_SCANCODE_CUT, /* AKEYCODE_CUT */ SDL_SCANCODE_COPY, /* AKEYCODE_COPY */ SDL_SCANCODE_PASTE, /* AKEYCODE_PASTE */ }; static SDL_Scancode TranslateKeycode(int keycode) { SDL_Scancode scancode = SDL_SCANCODE_UNKNOWN; if (keycode < SDL_arraysize(Android_Keycodes)) { scancode = Android_Keycodes[keycode]; } if (scancode == SDL_SCANCODE_UNKNOWN) { __android_log_print(ANDROID_LOG_INFO, "SDL", "Unknown keycode %d", keycode); } return scancode; } int Android_OnKeyDown(int keycode) { return SDL_SendKeyboardKey(SDL_PRESSED, TranslateKeycode(keycode)); } int Android_OnKeyUp(int keycode) { return SDL_SendKeyboardKey(SDL_RELEASED, TranslateKeycode(keycode)); } SDL_bool Android_HasScreenKeyboardSupport(_THIS) { return SDL_TRUE; } SDL_bool Android_IsScreenKeyboardShown(_THIS, SDL_Window * window) { return SDL_IsTextInputActive(); } void Android_StartTextInput(_THIS) { SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; Android_JNI_ShowTextInput(&videodata->textRect); } void Android_StopTextInput(_THIS) { Android_JNI_HideTextInput(); } void Android_SetTextInputRect(_THIS, SDL_Rect *rect) { SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; if (!rect) { SDL_InvalidParamError("rect"); return; } videodata->textRect = *rect; } #endif /* SDL_VIDEO_DRIVER_ANDROID */ /* vi: set ts=4 sw=4 expandtab: */
0
0.83267
1
0.83267
game-dev
MEDIA
0.711024
game-dev
0.614693
1
0.614693
TCreopargh/GreedyCraft
23,431
scripts/contenttweaker/tconstruct/armor_traits.zs
/* * This script is created for the GreedyCraft modpack by TCreopargh. * You may NOT use this script in any other publicly distributed modpack without my permission. */ #loader contenttweaker #modloaded tconstruct #modloaded conarm #priority 2601 #no_fix_recipe_book import crafttweaker.player.IPlayer; import crafttweaker.entity.IEntityLivingBase; import crafttweaker.damage.IDamageSource; import crafttweaker.entity.IEntityMob; import crafttweaker.entity.IEntity; import crafttweaker.item.IItemStack; import crafttweaker.data.IData; import crafttweaker.item.IIngredient; import crafttweaker.liquid.ILiquidStack; import crafttweaker.game.IGame; import mods.ctutils.utils.Math; import mods.contenttweaker.tconstruct.Material; import mods.contenttweaker.tconstruct.MaterialBuilder; import mods.contenttweaker.Fluid; import mods.contenttweaker.VanillaFactory; import mods.contenttweaker.Color; import mods.contenttweaker.conarm.ArmorTraitBuilder; import mods.contenttweaker.conarm.ArmorTrait; import mods.contenttweaker.conarm.ArmorTraitDataRepresentation; import mods.conarm.utils.IArmorModifications; import mods.zenutils.I18n; // Calculates what the effect of one piece of armor should be // Many traits are implemented to bethe effect of 4 pieces of armor stacked together; This turns them into what the effect of a single armor piece should be. // Special thanks to BDWSSBB function calcSingleArmor(reduction as float) as float { // Bounds check to be safe var reduct = reduction; if (reduct > 1.0f) { reduct = 1.0f; } else if (reduct < 0.0f) { reduct = 0.0f; } return pow(1.0 - reduct as double, 0.25) as float; } val warmTrait = ArmorTraitBuilder.create("warm"); warmTrait.color = Color.fromHex("2196f3").getIntColor(); warmTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.warmTrait.name"); warmTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.warmTrait.desc"); warmTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { var reduction = 0.0f; if (!isNull(player) && player.world.getBiome(player.position).isSnowyBiome) { reduction += 0.05f; if (player.world.raining) { reduction += 0.025f; } } return newDamage * (1.0f - reduction as float) as float; }; warmTrait.register(); val fortifiedTrait = ArmorTraitBuilder.create("fortified"); fortifiedTrait.color = Color.fromHex("bbbbbb").getIntColor(); fortifiedTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.fortifiedTrait.name"); fortifiedTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.fortifiedTrait.desc"); fortifiedTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { if (source.isProjectile()) { return (newDamage * 0.85f) as float; } return newDamage; }; fortifiedTrait.register(); val infernoTrait = ArmorTraitBuilder.create("inferno"); infernoTrait.color = Color.fromHex("ff5722").getIntColor(); infernoTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.infernoTrait.name"); infernoTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.infernoTrait.desc"); infernoTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { if (!isNull(source.getTrueSource()) && source.getTrueSource() instanceof IEntityLivingBase) { var attacker as IEntity = source.getTrueSource(); if (Math.random() < 0.2) { attacker.setFire(8); } } return newDamage; }; infernoTrait.register(); val cryonicTrait = ArmorTraitBuilder.create("cryonic"); cryonicTrait.color = Color.fromHex("00e5ff").getIntColor(); cryonicTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.cryonicTrait.name"); cryonicTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.cryonicTrait.desc"); cryonicTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { if (!isNull(source.getTrueSource()) && source.getTrueSource() instanceof IEntityLivingBase) { var attacker as IEntityLivingBase = source.getTrueSource(); if (Math.random() < 0.2) { attacker.addPotionEffect(<potion:minecraft:slowness>.makePotionEffect(200, 2, false, false)); } } return newDamage; }; cryonicTrait.register(); val knowledgefulTrait = ArmorTraitBuilder.create("knowledgeful"); knowledgefulTrait.color = Color.fromHex("76ff03").getIntColor(); knowledgefulTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.knowledgefulTrait.name"); knowledgefulTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.knowledgefulTrait.desc"); knowledgefulTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { var reduction = 0.0f; if (!isNull(player)) { var xp = player.xp as float; if(xp > 300.0f) { xp = 300.0f; } reduction = (xp / 300.0f) as float * 0.36f; } return newDamage * calcSingleArmor(reduction as float) as float; }; knowledgefulTrait.register(); val visionTrait = ArmorTraitBuilder.create("vision"); visionTrait.color = Color.fromHex("ffeb3b").getIntColor(); visionTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.visionTrait.name"); visionTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.visionTrait.desc"); visionTrait.onAbility = function(trait, level, world, player) { if (!isNull(player)) { player.addPotionEffect(<potion:minecraft:night_vision>.makePotionEffect(330, 2, false, false)); } }; visionTrait.register(); val tidalForceTrait = ArmorTraitBuilder.create("tidal_force"); tidalForceTrait.color = Color.fromHex("69f0ae").getIntColor(); tidalForceTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.tidalForceTrait.name"); tidalForceTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.tidalForceTrait.desc"); tidalForceTrait.onAbility = function(trait, level, world, player) { if (!isNull(player)) { player.addPotionEffect(<potion:minecraft:water_breathing>.makePotionEffect(25, 2, false, false)); } }; tidalForceTrait.register(); val spartanTrait = ArmorTraitBuilder.create("spartan"); spartanTrait.color = Color.fromHex("fdd835").getIntColor(); spartanTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.spartanTrait.name"); spartanTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.spartanTrait.desc"); spartanTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { var reduction = 0.0f; if ((player.health as float / player.maxHealth as float) as float < 0.33f) { reduction = 0.3f + (1.0f - player.health as float / (player.maxHealth as float * 0.33f)) * 0.45f; } return newDamage * calcSingleArmor(reduction as float) as float; }; spartanTrait.register(); val crystalTrait = ArmorTraitBuilder.create("crystal_force"); crystalTrait.color = Color.fromHex("18ffff").getIntColor(); crystalTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.crystalTrait.name"); crystalTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.crystalTrait.desc"); crystalTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { var damagePercent as float = 1.0f; if (armor.maxDamage != 0) { var dmg as float = 0.0f + armor.damage as float; var maxDmg as float = 0.0f + armor.maxDamage as float; var durabilityPercent as float = 1.0f - (dmg as float / maxDmg as float) as float; damagePercent = (1.05f - (durabilityPercent as float * 0.12f) as float); } return (newDamage * damagePercent) as float; }; crystalTrait.register(); val secondLifeTrait = ArmorTraitBuilder.create("second_life"); secondLifeTrait.color = Color.fromHex("4caf50").getIntColor(); secondLifeTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.secondLifeTrait.name"); secondLifeTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.secondLifeTrait.desc"); secondLifeTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { if (!isNull(player) && damage < player.maxHealth && !source.isDamageAbsolute()) { if (damage > player.health && Math.random() < 0.05) { evt.cancel(); player.addPotionEffect(<potion:minecraft:absorption>.makePotionEffect(200, 3, false, false)); player.addPotionEffect(<potion:minecraft:regeneration>.makePotionEffect(100, 3, false, false)); player.addPotionEffect(<potion:minecraft:resistance>.makePotionEffect(45, 4, false, false)); return 0.0f; } } return newDamage; }; secondLifeTrait.register(); val perfectionistTrait = ArmorTraitBuilder.create("perfectionist"); perfectionistTrait.color = Color.fromHex("00c853").getIntColor(); perfectionistTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.perfectionistTrait.name"); perfectionistTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.perfectionistTrait.desc"); perfectionistTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { if (!isNull(player) && newDamage > 5.0) { return (Math.round(newDamage / 5.0) as float * 5.0f) as float; } return newDamage as float; }; perfectionistTrait.register(); val gambleTrait = ArmorTraitBuilder.create("gamble"); gambleTrait.color = Color.fromHex("fdd835").getIntColor(); gambleTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.gambleTrait.name"); gambleTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.gambleTrait.desc"); gambleTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { if (Math.random() < 0.05) { return newDamage * 2.0f; } if (Math.random() < 0.25) { return (newDamage / 2.0f) as float; } return newDamage; }; gambleTrait.register(); val firstGuardTrait = ArmorTraitBuilder.create("first_guard"); firstGuardTrait.color = Color.fromHex("f44336").getIntColor(); firstGuardTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.firstGuardTrait.name"); firstGuardTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.firstGuardTrait.desc"); firstGuardTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { if (!isNull(player) && (player.maxHealth - player.health) as float < 1.0f) { return (newDamage * 0.84f) as float; } return newDamage; }; firstGuardTrait.register(); val levelingdefenseTrait = ArmorTraitBuilder.create("levelingdefense"); levelingdefenseTrait.color = Color.fromHex("7e57c2").getIntColor(); levelingdefenseTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.levelingdefenseTrait.name"); levelingdefenseTrait.addItem(<ore:plateHonor>); levelingdefenseTrait.maxLevel = 1; levelingdefenseTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.levelingdefenseTrait.desc"); levelingdefenseTrait.extraInfo = function(thisTrait, item, tag) { if (isNull(tag) || isNull(tag.memberGet("Modifiers"))) { return [] as string[]; } var modifiers = tag.memberGet("Modifiers") as IData; var armorLevel = {} as IData; if (modifiers.asString().contains("leveling_armor")) { for i in 0 to modifiers.length { var current as IData = modifiers[i]; if (current.asString().contains("leveling_armor")) { armorLevel = current; break; } } } var multiplier as float = 0.0f; if (!isNull(armorLevel.memberGet("level"))) { var level = armorLevel.memberGet("level").asInt() as int; multiplier += 0.025f * level as float; if (multiplier > 0.5f) { multiplier = 0.5f + (multiplier as float - 1.0f) / 4.0f; } } var percentage as int = Math.round((1.0f - (1.0f / (multiplier + 1.0f))) * 100.0f) as int; var desc as string[] = [I18n.format("greedycraft.armor_trait.tooltip.damage_reduction", "" + calcSingleArmor(percentage))]; return desc; }; levelingdefenseTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { var modifiers = armor.tag.memberGet("Modifiers") as IData; var armorLevel = {} as IData; if (modifiers.asString().contains("leveling_armor")) { for i in 0 to modifiers.length { var current as IData = modifiers[i]; if (current.asString().contains("leveling_armor")) { armorLevel = current; break; } } } var multiplier as float = 0.0f; if (!isNull(armorLevel.memberGet("level"))) { var level = armorLevel.memberGet("level").asInt() as int; while(level > 0) { level -= 1; multiplier += 0.05f; } if (multiplier > 1.0f) { multiplier = 1.0f + (multiplier - 1.0f) / 4.0f; } } // Thanks BDWSSBB for fixing this formula val reduction = 1.0f - 1.0f / (multiplier + 1.0f); return newDamage as float * calcSingleArmor(reduction); }; levelingdefenseTrait.register(); val luckyTrait = ArmorTraitBuilder.create("lucky"); luckyTrait.color = Color.fromHex("00e676").getIntColor(); luckyTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.luckyTrait.name"); luckyTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.luckyTrait.desc"); luckyTrait.onAbility = function(trait, level, world, player) { if (!isNull(player)) { player.addPotionEffect(<potion:minecraft:luck>.makePotionEffect(25, 0, false, false)); } }; luckyTrait.register(); val purifyingTrait = ArmorTraitBuilder.create("purifying"); purifyingTrait.color = Color.fromHex("eeeeee").getIntColor(); purifyingTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.purifyingTrait.name"); purifyingTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.purifyingTrait.desc"); purifyingTrait.onAbility = function(trait, level, world, player) { if (!isNull(player)) { if (player.isPotionActive(<potion:minecraft:wither>)) { player.removePotionEffect(<potion:minecraft:wither>); } } }; purifyingTrait.register(); val milkyTrait = ArmorTraitBuilder.create("milky"); milkyTrait.color = Color.fromHex("ffffff").getIntColor(); milkyTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.milkyTrait.name"); milkyTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.milkyTrait.desc"); milkyTrait.onAbility = function(trait, level, world, player) { if (!isNull(player)) { if (world.getWorldTime() as long % 18000 == 0) { player.clearActivePotions(); } } }; milkyTrait.register(); val poopTrait = ArmorTraitBuilder.create("poopy"); poopTrait.color = Color.fromHex("6d4c41").getIntColor(); poopTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.poopTrait.name"); poopTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.poopTrait.desc"); poopTrait.onAbility = function(trait, level, world, player) { if (!isNull(player)) { player.addPotionEffect(<potion:minecraft:nausea>.makePotionEffect(25, 0, false, false)); } }; poopTrait.register(); val trueDefenseTrait = ArmorTraitBuilder.create("true_defense"); trueDefenseTrait.color = Color.fromHex("33ffff").getIntColor(); trueDefenseTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.trueDefenseTrait.name"); trueDefenseTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.trueDefenseTrait.desc"); trueDefenseTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { if (!isNull(player) && source.isDamageAbsolute()) { return (newDamage as float * 0.9f) as float; } return newDamage as float; }; trueDefenseTrait.register(); val holdGroundTrait = ArmorTraitBuilder.create("hold_ground"); holdGroundTrait.color = Color.fromHex("f44336").getIntColor(); holdGroundTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.holdGroundTrait.name"); holdGroundTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.holdGroundTrait.desc"); holdGroundTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { if (!isNull(player) && player.isSneaking) { return (newDamage as float * 0.92f) as float; } return newDamage as float; }; holdGroundTrait.onKnockback = function(trait, armor, player, evt) { if (!isNull(player) && player.isSneaking) { evt.cancel(); } }; holdGroundTrait.register(); val motionTrait = ArmorTraitBuilder.create("motion"); motionTrait.color = Color.fromHex("ffee58").getIntColor(); motionTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.motionTrait.name"); motionTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.motionTrait.desc"); motionTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { if (!isNull(player) && player.isSprinting) { return (newDamage as float * 0.93f) as float; } return newDamage as float; }; motionTrait.onKnockback = function(trait, armor, player, evt) { if (!isNull(player) && player.isSprinting) { evt.strength = (evt.strength * 1.4) as float; } }; motionTrait.register(); val kungfuTrait = ArmorTraitBuilder.create("kungfu"); kungfuTrait.color = Color.fromHex("ffc107").getIntColor(); kungfuTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.kungfuTrait.name"); kungfuTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.kungfuTrait.desc"); kungfuTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { if (!isNull(player) && !isNull(source.getTrueSource()) && source.getTrueSource() instanceof IEntityLivingBase) { var attacker as IEntityLivingBase = source.getTrueSource(); if (attacker.isChild) { return (newDamage * 1.125f) as float; } } if (!isNull(player) && !source.isDamageAbsolute()) { if (Math.random() < 0.04) { player.addPotionEffect(<potion:minecraft:speed>.makePotionEffect(100, 3, false, false)); evt.cancel(); return 0.0f; } } return newDamage as float; }; kungfuTrait.register(); val thronyTrait = ArmorTraitBuilder.create("throny"); thronyTrait.color = Color.fromHex("4caf50").getIntColor(); thronyTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.thronyTrait.name"); thronyTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.thronyTrait.desc"); thronyTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { if (!isNull(player)) { if (!isNull(source.getTrueSource()) && source.getTrueSource() instanceof IEntityLivingBase) { var attacker as IEntityLivingBase = source.getTrueSource(); var newSource as IDamageSource = IDamageSource.createThornsDamage(player); var dmg as float = damage * 0.025f; if (dmg > 10.0f) { dmg = 10.0f; } attacker.attackEntityFrom(newSource, dmg); } } return newDamage as float; }; thronyTrait.register(); val enduranceTrait = ArmorTraitBuilder.create("endurance"); enduranceTrait.color = Color.fromHex("3f51b5").getIntColor(); enduranceTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.enduranceTrait.name"); enduranceTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.enduranceTrait.desc"); enduranceTrait.onHurt = function(trait, armor, player, source, damage, newDamage, evt) { if (!isNull(player)) { if (newDamage < (player.maxHealth * 0.05f) as float) { return newDamage * 0.8f as float; } } return newDamage as float; }; enduranceTrait.register(); val vaccineTrait = ArmorTraitBuilder.create("vaccine"); vaccineTrait.color = Color.fromHex("00ffcc").getIntColor(); vaccineTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.vaccineTrait.name"); vaccineTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.vaccineTrait.desc"); vaccineTrait.onAbility = function(trait, level, world, player) { if (!isNull(player)) { if(player.isPotionActive(<potion:abyssalcraft:cplague>)) { player.removePotionEffect(<potion:abyssalcraft:cplague>); } } }; vaccineTrait.register(); val strongVaccineTrait = ArmorTraitBuilder.create("strong_vaccine"); strongVaccineTrait.color = Color.fromHex("00ffcc").getIntColor(); strongVaccineTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.strongVaccineTrait.name"); strongVaccineTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.strongVaccineTrait.desc"); strongVaccineTrait.onAbility = function(trait, level, world, player) { if (!isNull(player)) { if(player.isPotionActive(<potion:abyssalcraft:cplague>)) { player.removePotionEffect(<potion:abyssalcraft:cplague>); } if(player.isPotionActive(<potion:abyssalcraft:dplague>)) { player.removePotionEffect(<potion:abyssalcraft:dplague>); } } }; strongVaccineTrait.register(); val warpDrainTrait = ArmorTraitBuilder.create("warp_drain"); warpDrainTrait.color = Color.fromHex("ab47bc").getIntColor(); warpDrainTrait.localizedName = game.localize("greedycraft.tconstruct.armor_trait.warpDrainTrait.name"); warpDrainTrait.localizedDescription = game.localize("greedycraft.tconstruct.armor_trait.warpDrainTrait.desc"); warpDrainTrait.onAbility = function(trait, level, world, player) { if (!isNull(player)) { if(world.getWorldTime() as long % 18000 == 0) { var success = false; if(player.warpNormal > 0 && Math.random() < 0.25) { player.warpNormal -= 1; success = true; } else if(player.warpTemporary > 0) { player.warpTemporary -= 1; success = true; } if(success) { val random = Math.random(); if(random < 0.2) { player.addPotionEffect(<potion:minecraft:speed>.makePotionEffect(240, 2, false, false)); } else if(random < 0.4) { player.addPotionEffect(<potion:minecraft:strength>.makePotionEffect(200, 2, false, false)); } else if(random < 0.6) { player.addPotionEffect(<potion:minecraft:resistance>.makePotionEffect(200, 1, false, false)); } else if(random < 0.8) { player.addPotionEffect(<potion:minecraft:jump_boost>.makePotionEffect(200, 2, false, false)); } else { player.addPotionEffect(<potion:minecraft:haste>.makePotionEffect(200, 2, false, false)); } } } } }; warpDrainTrait.register();
0
0.964098
1
0.964098
game-dev
MEDIA
0.99076
game-dev
0.975139
1
0.975139
stcarrez/ada-util
8,918
src/base/events/util-events-timers.adb
----------------------------------------------------------------------- -- util-events-timers -- Timer list management -- Copyright (C) 2017, 2022 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- SPDX-License-Identifier: Apache-2.0 ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; package body Util.Events.Timers is use type Ada.Real_Time.Time; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Events.Timers"); procedure Free is new Ada.Unchecked_Deallocation (Object => Timer_Node, Name => Timer_Node_Access); -- ----------------------- -- Repeat the timer. -- ----------------------- procedure Repeat (Event : in out Timer_Ref; In_Time : in Ada.Real_Time.Time_Span) is Timer : constant Timer_Node_Access := Event.Value; begin if Timer /= null and then Timer.List /= null then Timer.List.Add (Timer, Timer.Deadline + In_Time); end if; end Repeat; -- ----------------------- -- Cancel the timer. -- ----------------------- procedure Cancel (Event : in out Timer_Ref) is begin if Event.Value /= null and then Event.Value.List /= null then Event.Value.List.all.Cancel (Event.Value); Event.Value.List := null; end if; end Cancel; -- ----------------------- -- Check if the timer is ready to be executed. -- ----------------------- function Is_Scheduled (Event : in Timer_Ref) return Boolean is begin return Event.Value /= null and then Event.Value.List /= null; end Is_Scheduled; -- ----------------------- -- Returns the deadline time for the timer execution. -- Returns Time'Last if the timer is not scheduled. -- ----------------------- function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time is begin return (if Event.Value /= null then Event.Value.Deadline else Ada.Real_Time.Time_Last); end Time_Of_Event; -- ----------------------- -- Set a timer to be called at the given time. -- ----------------------- procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; At_Time : in Ada.Real_Time.Time) is Timer : Timer_Node_Access := Event.Value; begin if Timer = null then Event.Value := new Timer_Node; Timer := Event.Value; end if; Timer.Handler := Handler; -- Cancel the timer if it is part of another timer manager. if Timer.List /= null and then Timer.List /= List.Manager'Unchecked_Access then Timer.List.Cancel (Timer); end if; -- Update the timer. Timer.List := List.Manager'Unchecked_Access; List.Manager.Add (Timer, At_Time); end Set_Timer; -- ----------------------- -- Set a timer to be called after the given time span. -- ----------------------- procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; In_Time : in Ada.Real_Time.Time_Span) is begin List.Set_Timer (Handler, Event, Ada.Real_Time.Clock + In_Time); end Set_Timer; -- ----------------------- -- Process the timer handlers that have passed the deadline and return the next -- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers -- that are called by operation. The default is not limited. -- ----------------------- procedure Process (List : in out Timer_List; Timeout : out Ada.Real_Time.Time; Max_Count : in Natural := Natural'Last) is Timer : Timer_Ref; Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; begin for Count in 1 .. Max_Count loop List.Manager.Find_Next (Now, Timeout, Timer); exit when Timer.Value = null; begin Timer.Value.Handler.Time_Handler (Timer); exception when E : others => Timer_List'Class (List).Error (Timer.Value.Handler, E); end; Timer.Finalize; end loop; end Process; -- ----------------------- -- Procedure called when a timer handler raises an exception. -- The default operation reports an error in the logs. This procedure can be -- overridden to implement specific error handling. -- ----------------------- procedure Error (List : in out Timer_List; Handler : in Timer_Access; E : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (List, Handler); begin Log.Error ("Timer handler raised an exception", E, True); end Error; overriding procedure Adjust (Object : in out Timer_Ref) is begin if Object.Value /= null then Util.Concurrent.Counters.Increment (Object.Value.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Timer_Ref) is Is_Zero : Boolean; begin if Object.Value /= null then Util.Concurrent.Counters.Decrement (Object.Value.Counter, Is_Zero); if Is_Zero then Free (Object.Value); else Object.Value := null; end if; end if; end Finalize; protected body Timer_Manager is procedure Remove (Timer : in Timer_Node_Access) is begin if List = Timer then List := Timer.Next; Timer.Prev := null; if List /= null then List.Prev := null; end if; elsif Timer.Prev /= null then Timer.Prev.Next := Timer.Next; Timer.Next.Prev := Timer.Prev; else return; end if; Timer.Next := null; Timer.Prev := null; Timer.List := null; end Remove; -- ----------------------- -- Add a timer. -- ----------------------- procedure Add (Timer : in Timer_Node_Access; Deadline : in Ada.Real_Time.Time) is Current : Timer_Node_Access := List; Prev : Timer_Node_Access; begin Util.Concurrent.Counters.Increment (Timer.Counter); if Timer.List /= null then Remove (Timer); end if; Timer.Deadline := Deadline; while Current /= null loop if Current.Deadline > Deadline then if Prev = null then List := Timer; else Prev.Next := Timer; end if; Timer.Next := Current; Current.Prev := Timer; return; end if; Prev := Current; Current := Current.Next; end loop; if Prev = null then List := Timer; Timer.Prev := null; else Prev.Next := Timer; Timer.Prev := Prev; end if; Timer.Next := null; end Add; -- ----------------------- -- Cancel a timer. -- ----------------------- procedure Cancel (Timer : in out Timer_Node_Access) is Is_Zero : Boolean; begin if Timer.List = null then return; end if; Remove (Timer); Util.Concurrent.Counters.Decrement (Timer.Counter, Is_Zero); if Is_Zero then Free (Timer); end if; end Cancel; -- ----------------------- -- Find the next timer to be executed before the given time or return the next deadline. -- ----------------------- procedure Find_Next (Before : in Ada.Real_Time.Time; Deadline : out Ada.Real_Time.Time; Timer : in out Timer_Ref) is begin if List = null then Deadline := Ada.Real_Time.Time_Last; elsif List.Deadline < Before then Timer.Value := List; List := List.Next; if List /= null then List.Prev := null; Deadline := List.Deadline; else Deadline := Ada.Real_Time.Time_Last; end if; else Deadline := List.Deadline; end if; end Find_Next; end Timer_Manager; overriding procedure Finalize (Object : in out Timer_List) is Timer : Timer_Ref; Timeout : Ada.Real_Time.Time; begin loop Object.Manager.Find_Next (Ada.Real_Time.Time_Last, Timeout, Timer); exit when Timer.Value = null; Timer.Finalize; end loop; end Finalize; end Util.Events.Timers;
0
0.965869
1
0.965869
game-dev
MEDIA
0.231868
game-dev
0.967556
1
0.967556
libRocket/libRocket
6,729
Source/Core/Python/EventListener.cpp
/* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include "precompiled.h" #include "EventListener.h" #include "../../../Include/Rocket/Core/Python/Utilities.h" #include "EventWrapper.h" #include "ElementDocumentWrapper.h" namespace Rocket { namespace Core { namespace Python { EventListener::EventListener(PyObject* object) { callable = NULL; element = NULL; global_namespace = NULL; if (PyCallable_Check(object)) { // Its a callable, store it callable = object; Py_INCREF(callable); // Now look up the global namespace for the function/method PyObject* func_globals = NULL; // Methods have an im_func attribute that contains the function details PyObject* im_func = PyObject_GetAttrString(callable, "im_func"); if (!im_func) { PyErr_Clear(); // Functions just have a func_globals directly func_globals = PyObject_GetAttrString(callable, "func_globals"); } else { func_globals = PyObject_GetAttrString(im_func, "func_globals"); Py_DECREF(im_func); } if (func_globals) { // Keep a reference to func_globals, global_namespace tracks a reference global_namespace = func_globals; } else { // Otherwise clear the error, we'll resort to using the document namespace PyErr_Clear(); } } else if (PyString_Check(object)) { // Its a string, we need to compile it source_code = PyString_AsString(object); } else { // Unknown, log an error Log::Message(Rocket::Core::Log::LT_ERROR, "Failed to initialise python based event listener. Unknown python object type, should be a callable or a string."); } } EventListener::EventListener(const Rocket::Core::String& code, Element* context) { callable = NULL; element = context; global_namespace = NULL; // Load the code for this listener source_code = code; } EventListener::~EventListener() { if (callable) Py_DECREF(callable); if (global_namespace) Py_DECREF(global_namespace); } void EventListener::ProcessEvent(Event& event) { // If we've got nothing to do, abort if (!callable && source_code.Empty()) return; // Do we need to compile the code? if (!callable && !source_code.Empty()) { // Attempt to compile the code if (!Compile()) return; } PyObject* py_namespace = GetGlobalNamespace(); // Store current globals PyObject* old_event = PyDict_GetItemString(py_namespace, "event"); PyObject* old_self = PyDict_GetItemString(py_namespace, "self"); PyObject* old_document = PyDict_GetItemString(py_namespace, "document"); // Clear any pending errors (KeyErrors if they didn't exist) PyErr_Clear(); // Increase the ref to store the old values locally Py_XINCREF(old_event); Py_XINCREF(old_self); Py_XINCREF(old_document); // Set up the new expected globals PyDict_SetItemString(py_namespace, "event", Rocket::Core::Python::Utilities::MakeObject(&event).ptr()); PyDict_SetItemString(py_namespace, "self", Rocket::Core::Python::Utilities::MakeObject(element).ptr()); // Call the bound function PyObject* result = NULL; try { result = PyObject_CallObject(callable, NULL); } catch (python::error_already_set&) { } // Check error conditions if (result) { Py_DECREF(result); } else { Rocket::Core::Python::Utilities::PrintError(true); } // Remove the globals PyDict_DelItemString(py_namespace, "document"); PyDict_DelItemString(py_namespace, "self"); PyDict_DelItemString(py_namespace, "event"); // Restore old events if necessary if (old_event) { PyDict_SetItemString(py_namespace, "event", old_event); Py_DECREF(old_event); } if (old_self) { PyDict_SetItemString(py_namespace, "self", old_self); Py_DECREF(old_self); } if (old_document) { PyDict_SetItemString(py_namespace, "document", old_document); Py_DECREF(old_document); } } void EventListener::OnAttach(Element* _element) { if (!element) element = _element; } void EventListener::OnDetach(Element* /*element*/) { delete this; } bool EventListener::Compile() { Rocket::Core::String function_name(64, "Event_%x", this); Rocket::Core::String function_code(64, "def %s():", function_name.CString()); Rocket::Core::StringList lines; Rocket::Core::StringUtilities::ExpandString(lines, source_code, ';'); for (size_t i = 0; i < lines.size(); i++) { // Python doesn't handle \r's, strip em and indent the code correctly function_code += Rocket::Core::String(1024, "\n\t%s", lines[i].CString()).Replace("\r", ""); } ROCKET_ASSERT(element != NULL); PyObject* py_namespace = GetGlobalNamespace(); // Add our function to the namespace PyObject* result = PyRun_String(function_code.CString(), Py_file_input, py_namespace, py_namespace); if (!result) { Rocket::Core::Python::Utilities::PrintError(); return false; } Py_DECREF(result); // Get a handle to our function callable = PyDict_GetItemString(py_namespace, function_name.CString()); Py_INCREF(callable); return true; } PyObject* EventListener::GetGlobalNamespace() { if (global_namespace) { return global_namespace; } ElementDocumentWrapper* document = dynamic_cast< ElementDocumentWrapper* >(element->GetOwnerDocument()); if (!document) { Log::Message(Rocket::Core::Log::LT_ERROR, "Failed to find python accessible document for element %s, unable to create event. Did you create a context/document before initialising RocketPython?", element->GetAddress().CString()); return NULL; } global_namespace = document->GetModuleNamespace(); Py_INCREF(global_namespace); return global_namespace; } } } }
0
0.620281
1
0.620281
game-dev
MEDIA
0.167265
game-dev
0.705747
1
0.705747
edgegamers/Jailbreak
1,066
lang/Jailbreak.English/LastRequest/RPSLocale.cs
using CounterStrikeSharp.API.Core; using Jailbreak.Formatting.Base; using Jailbreak.Formatting.Views.LastRequest; namespace Jailbreak.English.LastRequest; public class RPSLocale : LastRequestLocale, ILRRPSLocale { public IView PlayerMadeChoice(CCSPlayerController player) { return new SimpleView { PREFIX, player, "made their choice." }; } public IView BothPlayersMadeChoice() { return new SimpleView { PREFIX, "Both players rocked, papered, and scissored! (ew)" }; } public IView Tie() { return new SimpleView { PREFIX, "It's a tie! Let's go again!" }; } public IView Results(CCSPlayerController guard, CCSPlayerController prisoner, int guardPick, int prisonerPick) { return new SimpleView { PREFIX, "Results:", guard, "picked", toRPS(guardPick), "and", prisoner, "picked", toRPS(prisonerPick) }; } private string toRPS(int pick) { return pick switch { 0 => "Rock", 1 => "Paper", 2 => "Scissors", _ => "Unknown" }; } }
0
0.671269
1
0.671269
game-dev
MEDIA
0.817552
game-dev
0.617076
1
0.617076
dogballs/cattle-bity
1,579
src/gameObjects/terrain/BrickTerrainTile.ts
import { BoxCollider, Sprite, SpritePainter } from '../../core'; import { GameUpdateArgs, Tag } from '../../game'; import { TerrainType } from '../../terrain'; import * as config from '../../config'; import { TerrainTile } from '../TerrainTile'; // Movement collision tags are defined in BrickSuperTerrainTile. // Bullet collsion tags are defined here. export class BrickTerrainTile extends TerrainTile { public type = TerrainType.Brick; public collider = new BoxCollider(this); public zIndex = config.BRICK_TILE_Z_INDEX; public readonly tags = [Tag.Wall, Tag.Brick]; public readonly painter = new SpritePainter(); protected sprites: Sprite[]; constructor() { super(config.BRICK_TILE_SIZE, config.BRICK_TILE_SIZE); } public destroy(): void { super.destroy(); this.collider.unregister(); } protected setup({ collisionSystem, spriteLoader }: GameUpdateArgs): void { collisionSystem.register(this.collider); this.sprites = spriteLoader.loadList(this.getSpriteIds()); this.painter.sprite = this.getSpriteByPosition(); } protected update(): void { this.collider.update(); } protected getSpriteIds(): string[] { return ['terrain.brick.1', 'terrain.brick.2']; } protected getSpriteByPosition(): Sprite { const horizontalIndex = Math.floor(this.position.x / config.BRICK_TILE_SIZE) % 2; const verticalIndex = Math.floor(this.position.y / config.BRICK_TILE_SIZE) % 2; const index = (horizontalIndex + verticalIndex) % 2; const sprite = this.sprites[index]; return sprite; } }
0
0.820083
1
0.820083
game-dev
MEDIA
0.977578
game-dev
0.759162
1
0.759162
setuppf/GameBookServer
3,314
12_02_move/src/libs/libserver/system_manager.cpp
#include "system_manager.h" #include "create_component.h" #include "message_system.h" #include "entity_system.h" #include "update_system.h" #include "console_thread_component.h" #include "object_pool_collector.h" #include "timer_component.h" #include <thread> SystemManager::SystemManager() { _pEntitySystem = new EntitySystem(this); _pMessageSystem = new MessageSystem(this); _pUpdateSystem = new UpdateSystem(); _systems.emplace_back(_pUpdateSystem); //_systems.emplace_back(new DependenceSystem()); //_systems.emplace_back(new StartSystem()); // gen random seed ߳ID std::stringstream strStream; strStream << std::this_thread::get_id(); std::string idstr = strStream.str(); std::seed_seq seed1(idstr.begin(), idstr.end()); std::minstd_rand0 generator(seed1); _pRandomEngine = new std::default_random_engine(generator()); _pPoolCollector = new DynamicObjectPoolCollector(this); } void SystemManager::InitComponent(ThreadType threadType) { _pEntitySystem->AddComponent<TimerComponent>(); _pEntitySystem->AddComponent<CreateComponentC>(); _pEntitySystem->AddComponent<ConsoleThreadComponent>(threadType); } void SystemManager::Update() { #if LOG_TRACE_COMPONENT_OPEN CheckBegin(); #endif _pPoolCollector->Update(); #if LOG_TRACE_COMPONENT_OPEN CheckPoint("pool"); #endif _pEntitySystem->Update(); #if LOG_TRACE_COMPONENT_OPEN CheckPoint("entity"); #endif _pMessageSystem->Update(_pEntitySystem); #if LOG_TRACE_COMPONENT_OPEN CheckPoint("message"); #endif for (auto iter = _systems.begin(); iter != _systems.end(); ++iter) { auto pSys = (*iter); pSys->Update(_pEntitySystem); #if LOG_TRACE_COMPONENT_OPEN CheckPoint(pSys->GetTypeName()); #endif } } void SystemManager::Dispose() { for (auto one : _systems) { one->Dispose(); delete one; } _systems.clear(); delete _pRandomEngine; _pRandomEngine = nullptr; _pMessageSystem->Dispose(); delete _pMessageSystem; _pMessageSystem = nullptr; _pEntitySystem->Dispose(); delete _pEntitySystem; _pEntitySystem = nullptr; // ֮ǰһUpdateuseеĶصFree _pPoolCollector->Update(); _pPoolCollector->Dispose(); delete _pPoolCollector; _pPoolCollector = nullptr; } std::default_random_engine* SystemManager::GetRandomEngine() const { return _pRandomEngine; } void SystemManager::AddSystem(const std::string& name) { auto pObj = ComponentFactory<>::GetInstance()->Create(nullptr, name, 0); if (pObj == nullptr) { LOG_ERROR("failed to create system."); return; } System* pSystem = static_cast<System*>(pObj); if (pSystem == nullptr) { LOG_ERROR("failed to create system."); return; } LOG_DEBUG("create system. name:" << name.c_str() << " thread id:" << std::this_thread::get_id()); _systems.emplace_back(pSystem); } MessageSystem* SystemManager::GetMessageSystem() const { return _pMessageSystem; } EntitySystem* SystemManager::GetEntitySystem() const { return _pEntitySystem; } UpdateSystem* SystemManager::GetUpdateSystem() const { return _pUpdateSystem; } DynamicObjectPoolCollector* SystemManager::GetPoolCollector() const { return _pPoolCollector; }
0
0.980745
1
0.980745
game-dev
MEDIA
0.547082
game-dev
0.966496
1
0.966496
fehaar/FFWD
1,981
Tests/Unity.Tests/Assets/FFWD/FFWD_PolygonCollider.cs
using UnityEngine; using System.Collections; [ExecuteInEditMode] public class FFWD_PolygonCollider : MonoBehaviour { public enum Plane2d { XY, XZ, YZ } public bool isTrigger; public Plane2d plane2d = Plane2d.XZ; [ContentSerializerIgnore] public bool snapToPlane = false; public Vector2[] relativePoints; void OnDrawGizmosSelected() { if (relativePoints != null && relativePoints.Length > 1) { Gizmos.color = Color.green; for (int i = 1; i < relativePoints.Length; i++) { Gizmos.DrawLine(transform.position + convertPoint(relativePoints[i - 1]), transform.position + convertPoint(relativePoints[i])); } Gizmos.DrawLine(transform.position + convertPoint(relativePoints[relativePoints.Length - 1]), transform.position + convertPoint(relativePoints[0])); Gizmos.DrawSphere(transform.position, 0.5f); } else { Gizmos.color = Color.red; Gizmos.DrawSphere(transform.position, 1f); } } public Vector3 convertPoint(Vector2 point) { switch (plane2d) { case Plane2d.XY: return new Vector3(point.x, point.y, 0); case Plane2d.XZ: return new Vector3(point.x, 0, point.y); case Plane2d.YZ: return new Vector3(0, point.x, point.y); } return Vector3.zero; } public Vector2 convertPoint(Vector3 point) { switch (plane2d) { case Plane2d.XY: return new Vector2(point.x, point.y); case Plane2d.XZ: return new Vector2(point.x, point.z); case Plane2d.YZ: return new Vector2(point.y, point.z); } return Vector2.zero; } void Update() { if (snapToPlane) { Vector3 newPos = transform.position; switch (plane2d) { case Plane2d.XY: newPos.z = 0; break; case Plane2d.XZ: newPos.y = 0; break; case Plane2d.YZ: newPos.x = 0; break; } if (transform.position != newPos) { transform.position = newPos; } } } }
0
0.895791
1
0.895791
game-dev
MEDIA
0.769011
game-dev,graphics-rendering
0.992397
1
0.992397
magmafoundation/Magma-Neo
4,454
src/main/java/org/bukkit/event/block/CauldronLevelChangeEvent.java
package org.bukkit.event.block; import com.google.common.base.Preconditions; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.data.BlockData; import org.bukkit.block.data.Levelled; import org.bukkit.entity.Entity; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class CauldronLevelChangeEvent extends BlockEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean cancelled; // private final Entity entity; private final ChangeReason reason; private final BlockState newState; public CauldronLevelChangeEvent(@NotNull Block block, @Nullable Entity entity, @NotNull ChangeReason reason, @NotNull BlockState newBlock) { super(block); this.entity = entity; this.reason = reason; this.newState = newBlock; } /** * Get entity which did this. May be null. * * @return acting entity */ @Nullable public Entity getEntity() { return entity; } @NotNull public ChangeReason getReason() { return reason; } /** * Gets the new state of the cauldron. * * @return The block state of the block that will be changed */ @NotNull public BlockState getNewState() { return newState; } /** * Gets the old level of the cauldron. * * @return old level * @see #getBlock() * @deprecated not all cauldron contents are Levelled */ @Deprecated public int getOldLevel() { BlockData oldBlock = getBlock().getBlockData(); return (oldBlock instanceof Levelled) ? ((Levelled) oldBlock).getLevel() : ((oldBlock.getMaterial() == Material.CAULDRON) ? 0 : 3); } /** * Gets the new level of the cauldron. * * @return new level * @see #getNewState() * @deprecated not all cauldron contents are Levelled */ @Deprecated public int getNewLevel() { BlockData newBlock = newState.getBlockData(); return (newBlock instanceof Levelled) ? ((Levelled) newBlock).getLevel() : ((newBlock.getMaterial() == Material.CAULDRON) ? 0 : 3); } /** * Sets the new level of the cauldron. * * @param newLevel new level * @see #getNewState() * @deprecated not all cauldron contents are Levelled */ @Deprecated public void setNewLevel(int newLevel) { Preconditions.checkArgument(0 <= newLevel && newLevel <= 3, "Cauldron level out of bounds 0 <= %s <= 3", newLevel); if (newLevel == 0) { newState.setType(Material.CAULDRON); } else if (newState.getBlockData() instanceof Levelled) { ((Levelled) newState.getBlockData()).setLevel(newLevel); } else { // Error, non-levellable block } } @Override public boolean isCancelled() { return cancelled; } @Override public void setCancelled(boolean cancelled) { this.cancelled = cancelled; } @NotNull @Override public HandlerList getHandlers() { return handlers; } @NotNull public static HandlerList getHandlerList() { return handlers; } public enum ChangeReason { /** * Player emptying the cauldron by filling their bucket. */ BUCKET_FILL, /** * Player filling the cauldron by emptying their bucket. */ BUCKET_EMPTY, /** * Player emptying the cauldron by filling their bottle. */ BOTTLE_FILL, /** * Player filling the cauldron by emptying their bottle. */ BOTTLE_EMPTY, /** * Player cleaning their banner. */ BANNER_WASH, /** * Player cleaning their armor. */ ARMOR_WASH, /** * Player cleaning a shulker box. */ SHULKER_WASH, /** * Entity being extinguished. */ EXTINGUISH, /** * Evaporating due to biome dryness. */ EVAPORATE, /** * Filling due to natural fluid sources, eg rain or dripstone. */ NATURAL_FILL, /** * Unknown. */ UNKNOWN } }
0
0.821521
1
0.821521
game-dev
MEDIA
0.969516
game-dev
0.945566
1
0.945566
GTNewHorizons/GT5-Unofficial
38,169
src/main/java/kubatech/tileentity/gregtech/multiblock/eigbuckets/EIGIC2Bucket.java
package kubatech.tileentity.gregtech.multiblock.eigbuckets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.block.BlockLiquid; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; import com.gtnewhorizon.gtnhlib.util.data.ImmutableBlockMeta; import gregtech.api.GregTechAPI; import gregtech.api.enums.ItemList; import gregtech.api.util.GTUtility; import gregtech.common.ores.OreInfo; import gregtech.common.ores.OreManager; import ic2.api.crops.CropCard; import ic2.api.crops.Crops; import ic2.core.Ic2Items; import ic2.core.crop.CropStickreed; import ic2.core.crop.IC2Crops; import ic2.core.crop.TileEntityCrop; import kubatech.api.eig.EIGBucket; import kubatech.api.eig.EIGDropTable; import kubatech.api.eig.IEIGBucketFactory; import kubatech.tileentity.gregtech.multiblock.MTEExtremeIndustrialGreenhouse; public class EIGIC2Bucket extends EIGBucket { public final static IEIGBucketFactory factory = new EIGIC2Bucket.Factory(); private static final String NBT_IDENTIFIER = "IC2"; private static final int REVISION_NUMBER = 0; // region crop simulation variables private final static int NUMBER_OF_DROPS_TO_SIMULATE = 1000; // nutrient factors /** * Set to true if you want to assume the crop is on wet farmland for a +2 bonus to nutrients */ private static final boolean IS_ON_WET_FARMLAND = true; /** * The amount of water stored in the crop stick when hydration is turned on. bounds of 0 to 200 inclusive */ private static final int WATER_STORAGE_VALUE = 200; // nutrient factors /** * The number of blocks of dirt we assume are under. Subtract 1 if we have a block under our crop. bounds of 0 to 3, * inclusive */ private static final int NUMBER_OF_DIRT_BLOCKS_UNDER = 0; /** * The amount of fertilizer stored in the crop stick bounds of 0 to 200, inclusive */ private static final int FERTILIZER_STORAGE_VALUE = 0; // air quality factors /** * How many blocks in a 3x3 area centered on the crop do not contain solid blocks or other crops. Max value is 8 * because the crop always counts itself. bound of 0-8 inclusive */ private static final int CROP_OBSTRUCTION_VALUE = 5; /** * Being able to see the sky gives a +2 bonus to the air quality */ private static final boolean CROP_CAN_SEE_SKY = false; // endregion crop simulation variables public static class Factory implements IEIGBucketFactory { @Override public String getNBTIdentifier() { return NBT_IDENTIFIER; } @Override public EIGBucket tryCreateBucket(MTEExtremeIndustrialGreenhouse greenhouse, ItemStack input) { // Check if input is a seed. if (!ItemList.IC2_Crop_Seeds.isStackEqual(input, true, true)) return null; if (!input.hasTagCompound()) return null; // Validate that stat nbt data exists. NBTTagCompound nbt = input.getTagCompound(); if (!(nbt.hasKey("growth") && nbt.hasKey("gain") && nbt.hasKey("resistance"))) return null; CropCard cc = IC2Crops.instance.getCropCard(input); if (cc == null) return null; return new EIGIC2Bucket(greenhouse, input); } @Override public EIGBucket restore(NBTTagCompound nbt) { return new EIGIC2Bucket(nbt); } } public final boolean useNoHumidity; /** * The average amount of growth cycles needed to reach maturity. */ private double growthTime = 0; private EIGDropTable drops = new EIGDropTable(); private boolean isValid = false; /** * Used to migrate old EIG greenhouse slots to the new bucket system, needs custom handling as to not void the * support blocks. * * @implNote DOES NOT VALIDATE THE CONTENTS OF THE BUCKET, YOU'LL HAVE TO REVALIDATE WHEN THE WORLD IS LOADED. * * @param seed The item stack for the item that served as the seed before * @param count The number of seed in the bucket * @param supportBlock The block that goes under the bucket * @param useNoHumidity Whether to use no humidity in growth speed calculations. */ public EIGIC2Bucket(ItemStack seed, int count, ItemStack supportBlock, boolean useNoHumidity) { super(seed, count, supportBlock == null ? null : new ItemStack[] { supportBlock }); this.useNoHumidity = useNoHumidity; // revalidate me this.isValid = false; } private EIGIC2Bucket(MTEExtremeIndustrialGreenhouse greenhouse, ItemStack seed) { super(seed, 1, null); this.useNoHumidity = greenhouse.isInNoHumidityMode(); this.recalculateDrops(greenhouse); } private EIGIC2Bucket(NBTTagCompound nbt) { super(nbt); this.useNoHumidity = nbt.getBoolean("useNoHumidity"); // If the invalid key exists then drops and growth time haven't been saved if (!nbt.hasKey("invalid")) { this.drops = new EIGDropTable(nbt, "drops"); this.growthTime = nbt.getDouble("growthTime"); this.isValid = nbt.getInteger("version") == REVISION_NUMBER && this.growthTime > 0 && !this.drops.isEmpty(); } } @Override public NBTTagCompound save() { NBTTagCompound nbt = super.save(); nbt.setBoolean("useNoHumidity", this.useNoHumidity); if (this.isValid) { nbt.setTag("drops", this.drops.save()); nbt.setDouble("growthTime", this.growthTime); } else { nbt.setBoolean("invalid", true); } nbt.setInteger("version", REVISION_NUMBER); return nbt; } @Override protected String getNBTIdentifier() { return NBT_IDENTIFIER; } @Override public void addProgress(double multiplier, EIGDropTable tracker) { // abort early if the bucket is invalid if (!this.isValid()) return; // else apply drops to tracker double growthPercent = multiplier / (this.growthTime * TileEntityCrop.tickRate); if (this.drops != null) { this.drops.addTo(tracker, this.seedCount * growthPercent); } } @Override protected void getAdditionalInfoData(StringBuilder sb) { sb.append(" | ") .append(StatCollector.translateToLocal("kubatech.infodata.bucket.humidity")) .append(" "); sb.append(this.useNoHumidity ? "Off" : "On"); } @Override public boolean revalidate(MTEExtremeIndustrialGreenhouse greenhouse) { this.recalculateDrops(greenhouse); return this.isValid(); } @Override public boolean isValid() { return super.isValid() && this.isValid; } /** * (Re-)calculates the pre-generated drop table for this bucket. * * @param greenhouse The {@link MTEExtremeIndustrialGreenhouse} that contains this bucket. */ public void recalculateDrops(MTEExtremeIndustrialGreenhouse greenhouse) { this.isValid = false; World world = greenhouse.getBaseMetaTileEntity() .getWorld(); int[] abc = new int[] { 0, -2, 3 }; int[] xyz = new int[] { 0, 0, 0 }; greenhouse.getExtendedFacing() .getWorldOffset(abc, xyz); xyz[0] += greenhouse.getBaseMetaTileEntity() .getXCoord(); xyz[1] += greenhouse.getBaseMetaTileEntity() .getYCoord(); xyz[2] += greenhouse.getBaseMetaTileEntity() .getZCoord(); boolean cheating = false; FakeTileEntityCrop crop; try { if (world.getBlock(xyz[0], xyz[1] - 2, xyz[2]) != GregTechAPI.sBlockCasings4 || world.getBlockMetadata(xyz[0], xyz[1] - 2, xyz[2]) != 1) { // no cheating = true; return; } // instantiate the TE in which we grow the seed. crop = new FakeTileEntityCrop(this, greenhouse, xyz); if (!crop.isValid) return; CropCard cc = crop.getCrop(); // region can grow checks // Check if we can put the current block under the soil. if (this.supportItems != null && this.supportItems.length == 1 && this.supportItems[0] != null) { if (!setBlock(this.supportItems[0], xyz[0], xyz[1] - 2, xyz[2], world)) { return; } // update nutrients if we need a block under. crop.updateNutrientsForBlockUnder(); } // Check if the crop has a chance to die in the current environment if (calcAvgGrowthRate(crop, cc, 0) < 0) return; // Check if the crop has a chance to grow in the current environment. if (calcAvgGrowthRate(crop, cc, 6) <= 0) return; ItemStack blockInputStackToConsume = null; if (!crop.canMature()) { // If the block we have in storage no longer functions, we are no longer valid, the seed and block // should be ejected if possible. if (this.supportItems != null) return; // assume we need a block under the farmland/fertilized dirt and update nutrients accordingly crop.updateNutrientsForBlockUnder(); // Try to find the needed block in the inputs boolean canGrow = false; ArrayList<ItemStack> inputs = greenhouse.getStoredInputs(); for (ItemStack potentialBlock : inputs) { // if the input can't be placed in the world skip to the next input if (potentialBlock == null || potentialBlock.stackSize <= 0) continue; if (!setBlock(potentialBlock, xyz[0], xyz[1] - 2, xyz[2], world)) continue; // check if the crop can grow with the block under it. if (!crop.canMature()) continue; // If we don't have enough blocks to consume, abort. if (this.seedCount > potentialBlock.stackSize) return; canGrow = true; blockInputStackToConsume = potentialBlock; // Don't consume the block just yet, we do that once everything is valid. ItemStack newSupport = potentialBlock.copy(); newSupport.stackSize = 1; this.supportItems = new ItemStack[] { newSupport }; break; } if (!canGrow) return; } // check if the crop does a block under check and try to put a requested block if possible if (this.supportItems == null) { // some crops get increased outputs if a specific block is under them. cc.getGain(crop); if (crop.hasRequestedBlockUnder()) { ArrayList<ItemStack> inputs = greenhouse.getStoredInputs(); boolean keepLooking = !inputs.isEmpty(); if (keepLooking && !crop.reqBlockOreDict.isEmpty()) { oreDictLoop: for (String reqOreDictName : crop.reqBlockOreDict) { if (reqOreDictName == null || OreDictionary.doesOreNameExist(reqOreDictName)) continue; int oreId = OreDictionary.getOreID(reqOreDictName); for (ItemStack potentialBlock : inputs) { if (potentialBlock == null || potentialBlock.stackSize <= 0) continue; for (int inputOreId : OreDictionary.getOreIDs(potentialBlock)) { if (inputOreId != oreId) continue; blockInputStackToConsume = potentialBlock; // Don't consume the block just yet, we do that once everything is valid. ItemStack newSupport = potentialBlock.copy(); newSupport.stackSize = 1; this.supportItems = new ItemStack[] { newSupport }; keepLooking = false; crop.updateNutrientsForBlockUnder(); break oreDictLoop; } } } } if (keepLooking && !crop.reqBlockSet.isEmpty()) { blockLoop: for (Block reqBlock : crop.reqBlockSet) { if (reqBlock == null || reqBlock instanceof BlockLiquid) continue; for (ItemStack potentialBlockStack : inputs) { // TODO: figure out a way to handle liquid block requirements // water lilly looks for water and players don't really have access to those. if (potentialBlockStack == null || potentialBlockStack.stackSize <= 0) continue; // check if it places a block that is equal to the the one we are looking for Block inputBlock = Block.getBlockFromItem(potentialBlockStack.getItem()); if (inputBlock != reqBlock) continue; blockInputStackToConsume = potentialBlockStack; // Don't consume the block just yet, we do that once everything is valid. ItemStack newSupport = potentialBlockStack.copy(); newSupport.stackSize = 1; this.supportItems = new ItemStack[] { newSupport }; crop.updateNutrientsForBlockUnder(); break blockLoop; } } } } } // check if the crop can be harvested at its max size // Eg: the Eating plant cannot be harvested at its max size of 6, only 4 or 5 can crop.setSize((byte) cc.maxSize()); if (!cc.canBeHarvested(crop)) return; // endregion can grow checks // region drop rate calculations // PRE CALCULATE DROP RATES // TODO: Add better loot table handling for crops like red wheat // berries, etc. EIGDropTable drops = new EIGDropTable(); // Multiply drop sizes by the average number drop rounds per harvest. double avgDropRounds = getRealAverageDropRounds(crop, cc); double avgStackIncrease = getRealAverageDropIncrease(crop, cc); HashMap<Integer, Integer> sizeAfterHarvestFrequencies = new HashMap<>(); for (int i = 0; i < NUMBER_OF_DROPS_TO_SIMULATE; i++) { // try generating some loot drop ItemStack drop = cc.getGain(crop); if (drop == null || drop.stackSize <= 0) continue; sizeAfterHarvestFrequencies.merge((int) cc.getSizeAfterHarvest(crop), 1, Integer::sum); // Merge the new drop with the current loot table. double avgAmount = (drop.stackSize + avgStackIncrease) * avgDropRounds; drops.addDrop(drop, avgAmount / NUMBER_OF_DROPS_TO_SIMULATE); } if (drops.isEmpty()) return; // endregion drop rate calculations // region growth time calculation // Just doing average(ceil(stageGrowth/growthSpeed)) isn't good enough it's off by as much as 20% double avgGrowthCyclesToHarvest = calcRealAvgGrowthRate(crop, cc, sizeAfterHarvestFrequencies); if (avgGrowthCyclesToHarvest <= 0) { return; } // endregion growth time calculation // Consume new under block if necessary if (blockInputStackToConsume != null) blockInputStackToConsume.stackSize -= this.seedCount; // We are good return success this.growthTime = avgGrowthCyclesToHarvest; this.drops = drops; this.isValid = true; } catch (Exception e) { e.printStackTrace(System.err); } finally { // always reset the world to it's original state if (!cheating) world.setBlock(xyz[0], xyz[1] - 2, xyz[2], GregTechAPI.sBlockCasings4, 1, 0); // world.setBlockToAir(xyz[0], xyz[1], xyz[2]); } } /** * Attempts to place a block in the world, used for testing crop viability and drops. * * @param stack The {@link ItemStack} to place. * @param x The x coordinate at which to place the block. * @param y The y coordinate at which to place the block. * @param z The z coordinate at which to place the block. * @param world The world in which to place the block. * @return true of a block was placed. */ private static boolean setBlock(ItemStack stack, int x, int y, int z, World world) { Item item = stack.getItem(); Block b = Block.getBlockFromItem(item); if (b == Blocks.air || !(item instanceof ItemBlock)) return false; short tDamage = (short) item.getDamage(stack); try (OreInfo<?> info = OreManager.getOreInfo(b, tDamage)) { if (info != null) { info.isNatural = true; ImmutableBlockMeta oreBlock = OreManager.getAdapter(info) .getBlock(info); world.setBlock(x, y, z, oreBlock.getBlock(), oreBlock.getBlockMeta(), 3); if (oreBlock.matches(world.getBlock(x, y, z), world.getBlockMetadata(x, y, z))) return true; } } world.setBlock(x, y, z, b, tDamage, 0); return true; } // region drop rate calculations /** * Calculates the average number of separate item drops to be rolled per harvest using information obtained by * decompiling IC2. * * @see TileEntityCrop#harvest_automated(boolean) * @param te The {@link TileEntityCrop} holding the crop * @param cc The {@link CropCard} of the seed * @return The average number of drops to computer per harvest */ private static double getRealAverageDropRounds(TileEntityCrop te, CropCard cc) { // this should be ~99.995% accurate double chance = (double) cc.dropGainChance() * GTUtility.powInt(1.03, te.getGain()); // this is essentially just performing an integration using the composite trapezoidal rule. double min = -10, max = 10; int steps = 10000; double stepSize = (max - min) / steps; double sum = 0; for (int k = 1; k <= steps - 1; k++) { sum += getWeightedDropChance(min + k * stepSize, chance); } double minVal = getWeightedDropChance(min, chance); double maxVal = getWeightedDropChance(max, chance); return stepSize * ((minVal + maxVal) / 2 + sum); } /** * Evaluates the value of y for a standard normal distribution * * @param x The value of x to evaluate * @return The value of y */ private static double stdNormDistr(double x) { return Math.exp(-0.5 * (x * x)) / SQRT2PI; } private static final double SQRT2PI = Math.sqrt(2.0d * Math.PI); /** * Calculates the weighted drop chance using * * @param x The value rolled by nextGaussian * @param chance the base drop chance * @return the weighted drop chance */ private static double getWeightedDropChance(double x, double chance) { return Math.max(0L, Math.round(x * chance * 0.6827d + chance)) * stdNormDistr(x); } /** * Calculates the average drop of the stack size caused by seed's gain using information obtained by decompiling * IC2. * * @see TileEntityCrop#harvest_automated(boolean) * @param te The {@link TileEntityCrop} holding the crop * @param cc The {@link CropCard} of the seed * @return The average number of drops to computer per harvest */ private static double getRealAverageDropIncrease(TileEntityCrop te, CropCard cc) { // yes gain has the amazing ability to sometimes add 1 to your stack size! return (te.getGain() + 1) / 100.0d; } // endregion drop rate calculations // region growth time approximation /** * Calculates the average number growth cycles needed for a crop to grow to maturity. * * @see EIGIC2Bucket#calcAvgGrowthRate(TileEntityCrop, CropCard, int) * @param te The {@link TileEntityCrop} holding the crop * @param cc The {@link CropCard} of the seed * @return The average growth rate as a floating point number */ private static double calcRealAvgGrowthRate(TileEntityCrop te, CropCard cc, HashMap<Integer, Integer> sizeAfterHarvestFrequencies) { // Compute growth speeds. int[] growthSpeeds = new int[7]; for (int i = 0; i < 7; i++) growthSpeeds[i] = calcAvgGrowthRate(te, cc, i); // if it's stick reed, we know what the distribution should look like if (cc.getClass() == CropStickreed.class) { sizeAfterHarvestFrequencies.clear(); sizeAfterHarvestFrequencies.put(1, 1); sizeAfterHarvestFrequencies.put(2, 1); sizeAfterHarvestFrequencies.put(3, 1); } // Get the duration of all growth stages int[] growthDurations = new int[cc.maxSize()]; // , index 0 is assumed to be 0 since stage 0 is usually impossible. // The frequency table should prevent stage 0 from having an effect on the result. growthDurations[0] = 0; // stage 0 doesn't usually exist. for (byte i = 1; i < growthDurations.length; i++) { te.setSize(i); growthDurations[i] = cc.growthDuration(te); } return calcRealAvgGrowthRate(growthSpeeds, growthDurations, sizeAfterHarvestFrequencies); } /** * Calculates the average number growth cycles needed for a crop to grow to maturity. * * @implNote This method is entirely self-contained and can therefore be unit tested. * * @param growthSpeeds The speeds at which the crop can grow. * @param stageGoals The total to reach for each stage * @param startStageFrequency How often the growth starts from a given stage * @return The average growth rate as a floating point number */ public static double calcRealAvgGrowthRate(int[] growthSpeeds, int[] stageGoals, HashMap<Integer, Integer> startStageFrequency) { // taking out the zero rolls out of the calculation tends to make the math more accurate for lower speeds. int[] nonZeroSpeeds = Arrays.stream(growthSpeeds) .filter(x -> x > 0) .toArray(); int zeroRolls = growthSpeeds.length - nonZeroSpeeds.length; if (zeroRolls >= growthSpeeds.length) return -1; // compute stage lengths and stage frequencies double[] avgCyclePerStage = new double[stageGoals.length]; double[] normalizedStageFrequencies = new double[stageGoals.length]; long frequenciesSum = startStageFrequency.values() .parallelStream() .mapToInt(x -> x) .sum(); for (int i = 0; i < stageGoals.length; i++) { avgCyclePerStage[i] = calcAvgCyclesToGoal(nonZeroSpeeds, stageGoals[i]); normalizedStageFrequencies[i] = startStageFrequency.getOrDefault(i, 0) * stageGoals.length / (double) frequenciesSum; } // Compute multipliers based on how often the growth starts at a given rate. double[] frequencyMultipliers = new double[avgCyclePerStage.length]; Arrays.fill(frequencyMultipliers, 1.0d); conv1DAndCopyToSignal( frequencyMultipliers, normalizedStageFrequencies, new double[avgCyclePerStage.length], 0, frequencyMultipliers.length, 0); // apply multipliers to length for (int i = 0; i < avgCyclePerStage.length; i++) avgCyclePerStage[i] *= frequencyMultipliers[i]; // lengthen average based on number of 0 rolls. double average = Arrays.stream(avgCyclePerStage) .average() .orElse(-1); if (average <= 0) return -1; if (zeroRolls > 0) { average = average / nonZeroSpeeds.length * growthSpeeds.length; } // profit return average; } /** * Computes the average number of rolls of an N sided fair dice with irregular number progressions needed to surpass * a given total. * * @param speeds The speeds at which the crop grows. * @param goal The total to match or surpass. * @return The average number of rolls of speeds to meet or surpass the goal. */ private static double calcAvgCyclesToGoal(int[] speeds, int goal) { // even if the goal is 0, it will always take at least 1 cycle. if (goal <= 0) return 1; double mult = 1.0d; int goalCap = speeds[speeds.length - 1] * 1000; if (goal > goalCap) { mult = (double) goal / goalCap; goal = goalCap; } // condition start signal double[] signal = new double[goal]; Arrays.fill(signal, 0); signal[0] = 1; // Create kernel out of our growth speeds double[] kernel = tabulate(speeds, 1.0d / speeds.length); double[] convolutionTarget = new double[signal.length]; // Perform convolutions on the signal until it's too weak to be recognised. double p, avgRolls = 1; int iterNo = 0; // 1e-1 is a threshold, you can increase it for to increase the accuracy of the output. // 1e-1 is already accurate enough that any value beyond that is unwarranted. int min = speeds[0]; int max = speeds[speeds.length - 1]; do { avgRolls += p = conv1DAndCopyToSignal(signal, kernel, convolutionTarget, min, max, iterNo); iterNo += 1; } while (p >= 1e-1 / goal); return avgRolls * mult; } /** * Creates an array that corresponds to the amount of times a number appears in a list. * <p> * Ex: {1,2,3,4} -> {0,1,1,1,1}, {0,2,2,4} -> {1,0,2,0,1} * * @param bin The number list to tabulate * @param multiplier A multiplier to apply the output list * @return The number to tabulate */ private static double[] tabulate(int[] bin, double multiplier) { double[] ret = new double[bin[bin.length - 1] + 1]; Arrays.fill(ret, 0); for (int i : bin) ret[i] += multiplier; return ret; } /** * Computes a 1D convolution of a signal and stores the results in the signal array. Essentially performs `X <- * convolve(X,rev(Y))[1:length(X)]` in R * * @param signal The signal to apply the convolution to. * @param kernel The kernel to compute with. * @param fixedLengthTarget A memory optimisation so we don't just create a ton of arrays since we overwrite it. * Should be the same length as the signal. */ private static double conv1DAndCopyToSignal(double[] signal, double[] kernel, double[] fixedLengthTarget, int minValue, int maxValue, int iterNo) { // for a 1d convolution we would usually use kMax = signal.length + kernel.length - 1 // but since we are directly applying our result to our signal, there is no reason to compute // values where k > signal.length. // we could probably run this loop in parallel. double sum = 0; int maxK = Math.min(signal.length, (iterNo + 1) * maxValue + 1); int startAt = Math.min(signal.length, minValue * (iterNo + 1)); int k = Math.max(0, startAt - kernel.length); for (; k < startAt; k++) fixedLengthTarget[k] = 0; for (; k < maxK; k++) { // I needs to be a valid index of the kernel. fixedLengthTarget[k] = 0; for (int i = Math.max(0, k - kernel.length + 1); i <= k; i++) { double v = signal[i] * kernel[k - i]; sum += v; fixedLengthTarget[k] += v; } } System.arraycopy(fixedLengthTarget, 0, signal, 0, signal.length); return sum; } /** * Calculates the average growth rate of an ic2 crop using information obtained though decompiling IC2. Calls to * random functions have been either replaced with customisable values or boundary tests. * * @see TileEntityCrop#calcGrowthRate() * @param te The {@link TileEntityCrop} holding the crop * @param cc The {@link CropCard} of the seed * @param rngRoll The role for the base rng * @return The amounts of growth point added to the growth progress in average every growth tick */ private static int calcAvgGrowthRate(TileEntityCrop te, CropCard cc, int rngRoll) { // the original logic uses IC2.random.nextInt(7) int base = 3 + rngRoll + te.getGrowth(); int need = Math.max(0, (cc.tier() - 1) * 4 + te.getGrowth() + te.getGain() + te.getResistance()); int have = cc.weightInfluences(te, te.getHumidity(), te.getNutrients(), te.getAirQuality()) * 5; if (have >= need) { // The crop has a good enough environment to grow normally return base * (100 + (have - need)) / 100; } else { // this only happens if we don't have enough // resources to grow properly. int neg = (need - have) * 4; if (neg > 100) { // a crop with a resistance 31 will never die since the original // checks for `IC2.random.nextInt(32) > this.statResistance` // so assume that the crop will eventually die if it doesn't // have maxed out resistance stats. 0 means no growth this tick // -1 means the crop dies. return te.getResistance() >= 31 ? 0 : -1; } // else apply neg to base return Math.max(0, base * (100 - neg) / 100); } } // endregion growth time approximation // region deterministic environmental calculations /** * Calculates the humidity at the location of the controller using information obtained by decompiling IC2. Returns * 0 if the greenhouse is in no humidity mode. * * @see EIGIC2Bucket#IS_ON_WET_FARMLAND * @see EIGIC2Bucket#WATER_STORAGE_VALUE * @see TileEntityCrop#updateHumidity() * @param greenhouse The {@link MTEExtremeIndustrialGreenhouse} that holds the seed. * @return The humidity environmental value at the controller's location. */ public static byte getHumidity(MTEExtremeIndustrialGreenhouse greenhouse, boolean useNoHumidity) { if (useNoHumidity) return 0; int value = Crops.instance.getHumidityBiomeBonus( greenhouse.getBaseMetaTileEntity() .getBiome()); if (IS_ON_WET_FARMLAND) value += 2; // we add 2 if we have more than 5 water in storage if (WATER_STORAGE_VALUE >= 5) value += 2; // add 1 for every 25 water stored (max of 200 value += (WATER_STORAGE_VALUE + 24) / 25; return (byte) value; } /** * Calculates the nutrient value at the location of the controller using information obtained by decompiling IC2 * * @see EIGIC2Bucket#NUMBER_OF_DIRT_BLOCKS_UNDER * @see EIGIC2Bucket#FERTILIZER_STORAGE_VALUE * @see TileEntityCrop#updateNutrients() * @param greenhouse The {@link MTEExtremeIndustrialGreenhouse} that holds the seed. * @return The nutrient environmental value at the controller's location. */ public static byte getNutrients(MTEExtremeIndustrialGreenhouse greenhouse) { int value = Crops.instance.getNutrientBiomeBonus( greenhouse.getBaseMetaTileEntity() .getBiome()); value += NUMBER_OF_DIRT_BLOCKS_UNDER; value += (FERTILIZER_STORAGE_VALUE + 19) / 20; return (byte) value; } /** * Calculates the air quality at the location of the controller bucket using information obtained by decompiling IC2 * * @see EIGIC2Bucket#CROP_OBSTRUCTION_VALUE * @see EIGIC2Bucket#CROP_CAN_SEE_SKY * @see TileEntityCrop#updateAirQuality() * @param greenhouse The {@link MTEExtremeIndustrialGreenhouse} that holds the seed. * @return The air quality environmental value at the controller's location. */ public static byte getAirQuality(MTEExtremeIndustrialGreenhouse greenhouse) { // clamp height bonus to 0-4, use the height of the crop itself // TODO: check if we want to add the extra +2 for the actual height of the crop stick in the EIG. int value = Math.max( 0, Math.min( 4, (greenhouse.getBaseMetaTileEntity() .getYCoord() - 64) / 15)); // min value of fresh is technically 8 since the crop itself will count as an obstruction at xOff = 0, zOff = 0 value += CROP_OBSTRUCTION_VALUE / 2; // you get a +2 bonus for being able to see the sky if (CROP_CAN_SEE_SKY) value += 2; return (byte) value; } // endregion deterministic environmental calculations private static class FakeTileEntityCrop extends TileEntityCrop { private boolean isValid; public Set<Block> reqBlockSet = new HashSet<>(); public Set<String> reqBlockOreDict = new HashSet<>(); private int lightLevel = 15; public FakeTileEntityCrop(EIGIC2Bucket bucket, MTEExtremeIndustrialGreenhouse greenhouse, int[] xyz) { super(); this.isValid = false; this.ticker = 1; // put seed in crop stick CropCard cc = Crops.instance.getCropCard(bucket.seed); this.setCrop(cc); NBTTagCompound nbt = bucket.seed.getTagCompound(); this.setGrowth(nbt.getByte("growth")); this.setGain(nbt.getByte("gain")); this.setResistance(nbt.getByte("resistance")); this.setWorldObj( greenhouse.getBaseMetaTileEntity() .getWorld()); this.xCoord = xyz[0]; this.yCoord = xyz[1]; this.zCoord = xyz[2]; this.blockType = Block.getBlockFromItem(Ic2Items.crop.getItem()); this.blockMetadata = 0; this.waterStorage = bucket.useNoHumidity ? 0 : WATER_STORAGE_VALUE; this.humidity = EIGIC2Bucket.getHumidity(greenhouse, bucket.useNoHumidity); this.nutrientStorage = FERTILIZER_STORAGE_VALUE; this.nutrients = EIGIC2Bucket.getNutrients(greenhouse); this.airQuality = EIGIC2Bucket.getAirQuality(greenhouse); this.isValid = true; } public boolean canMature() { CropCard cc = this.getCrop(); this.size = cc.maxSize() - 1; // try with a high light level this.lightLevel = 15; if (cc.canGrow(this)) return true; // and then with a low light level. this.lightLevel = 9; return cc.canGrow(this); } @Override public boolean isBlockBelow(Block reqBlock) { this.reqBlockSet.add(reqBlock); return super.isBlockBelow(reqBlock); } @Override public boolean isBlockBelow(String oreDictionaryName) { this.reqBlockOreDict.add(oreDictionaryName); return super.isBlockBelow(oreDictionaryName); } // region environment simulation @Override public int getLightLevel() { // 9 should allow most light dependent crops to grow // the only exception I know of the eating plant which checks return this.lightLevel; } @Override public byte getHumidity() { return this.humidity; } @Override public byte updateHumidity() { return this.humidity; } @Override public byte getNutrients() { return this.nutrients; } @Override public byte updateNutrients() { return this.nutrients; } @Override public byte getAirQuality() { return this.airQuality; } @Override public byte updateAirQuality() { return this.nutrients; } // endregion environment simulation /** * Updates the nutrient value based on the fact tha the crop needs a block under it. */ public void updateNutrientsForBlockUnder() { // -1 because the farm land is included in the root check. if ((this.getCrop() .getrootslength(this) - 1 - NUMBER_OF_DIRT_BLOCKS_UNDER) <= 0 && this.nutrients > 0) { this.nutrients--; } } /** * Checks if the crop stick has requested a block to be under it yet. * * @return true if a block under check was made. */ public boolean hasRequestedBlockUnder() { return !this.reqBlockSet.isEmpty() || !this.reqBlockOreDict.isEmpty(); } } }
0
0.884332
1
0.884332
game-dev
MEDIA
0.953854
game-dev
0.867313
1
0.867313
lua9520/source-engine-2018-cstrike15_src
3,943
engine/MapReslistGenerator.h
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #ifndef MAPRESLISTGENERATOR_H #define MAPRESLISTGENERATOR_H #ifdef _WIN32 #pragma once #endif #include "filesystem.h" #include "utlvector.h" #include "utlsymbol.h" #include "utlstring.h" // Map list creation // Map entry struct maplist_map_t { char name[64]; }; // General purpose maplist generator. // aMaps: Utlvector you'd like filled with the maps. // bUseMapListFile: true if you want to use a maplist file, vs parsing the maps directory or using +map // pMapFile: If you're using a maplist file, this should be the filename of it // pSystemMsg: Used to preface and debug messages // iCurrentMap: The map in the list to begin at. Handles the -startmap parameter for you. bool BuildGeneralMapList( CUtlVector<maplist_map_t> *aMaps, bool bUseMapListFile, const char *pMapFile, char *pSystemMsg, int *iCurrentMap ); // initialization void MapReslistGenerator_Init(); void MapReslistGenerator_Shutdown(); void MapReslistGenerator_BuildMapList(); //----------------------------------------------------------------------------- // Purpose: Handles collating lists of resources on level load // Used to generate reslists for steam //----------------------------------------------------------------------------- class CMapReslistGenerator { public: CMapReslistGenerator(); // initializes the object to enable reslist generation void EnableReslistGeneration( bool usemaplistfile ); // starts the reslist generation (starts cycling maps) void StartReslistGeneration(); void BuildMapList(); void Shutdown(); // call every frame if we're enabled, just so that the next map can be triggered at the right time void RunFrame(); // returns true if reslist generation is enabled bool IsEnabled() { return m_bLoggingEnabled; } bool IsLoggingToMap() { return m_bLoggingEnabled && !m_bLogToEngineList; } bool IsCreatingForXbox(); // call to mark level load/end void OnLevelLoadStart(const char *levelName); void OnLevelLoadEnd(); void OnLevelShutdown(); void OnPlayerSpawn(); void OnFullyConnected(); // call to mark resources as being precached void OnResourcePrecached(const char *relativePathFileName); void OnModelPrecached(const char *relativePathFileName); void OnSoundPrecached(const char *relativePathFileName); char const *LogPrefix(); void EnableDeletionsTracking(); void TrackDeletions( const char *fullPathFileName ); bool ShouldRebuildCaches(); char const *GetResListDirectory() const; void SetAutoQuit( bool bState ); private: static void TrackDeletionsLoggingFunc(const char *fullPathFileName, const char *options); static void FileSystemLoggingFunc(const char *fullPathFileName, const char *options); void OnResourcePrecachedFullPath(const char *fullPathFileName); void BuildEngineLogFromReslist(); void LogToEngineReslist( char const *pLine ); void WriteMapLog(); void SetPrefix( char const *mapname ); void SpewTrackedDeletionsLog(); void DoQuit(); bool m_bTrackingDeletions; bool m_bLoggingEnabled; bool m_bUsingMapList; bool m_bRestartOnTransition; bool m_bCreatingForXbox; // true for engine, false for map bool m_bLogToEngineList; bool m_bAutoQuit; // list of all maps to scan CUtlVector<maplist_map_t> m_Maps; int m_iCurrentMap; float m_flNextMapRunTime; CUtlSymbolTable m_AlreadyWrittenFileNames; int m_iPauseTimeBetweenMaps; char m_szPrefix[64]; char m_szLevelName[MAX_PATH]; CUtlSymbolTable m_DeletionList; CUtlRBTree< CUtlSymbol > m_DeletionListWarnings; CUtlSymbolTable m_DeletionListWarningsSymbols; CUtlRBTree< CUtlString, int > m_MapLog; CUtlRBTree< CUtlString, int > m_EngineLog; CUtlString m_sResListDir; }; // singleton accessor CMapReslistGenerator &MapReslistGenerator(); #endif // MAPRESLISTGENERATOR_H
0
0.993195
1
0.993195
game-dev
MEDIA
0.799894
game-dev
0.752606
1
0.752606
supernova-ws/SuperNova
4,449
includes/includes/flt_mission_recycle.php
<?php use Fleet\DbFleetStatic; use Planet\DBStaticPlanet; /** * MissionCaseRecycling.php * * @version 1.0 * @copyright 2008 By Chlorel for XNova */ function flt_mission_recycle(&$mission_data) { $fleet_row = &$mission_data['fleet']; $destination_planet = &$mission_data['dst_planet']; if(!$fleet_row) { return CACHE_NOTHING; } if(!isset($destination_planet['id'])) { // doquery("UPDATE {{fleets}} SET `fleet_mess` = 1 WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1;"); DbFleetStatic::fleet_send_back($mission_data['fleet']); return CACHE_FLEET; } global $lang; $RecyclerCapacity = 0; $OtherFleetCapacity = 0; $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']); foreach($fleet_array as $unit_id => $unit_count) { if(in_array($unit_id, sn_get_groups('fleet'))) { $capacity = get_unit_param($unit_id, P_CAPACITY) * $unit_count; if(in_array($unit_id, sn_get_groups('flt_recyclers'))) { $RecyclerCapacity += $capacity; } else { $OtherFleetCapacity += $capacity; } } } $IncomingFleetGoods = $fleet_row["fleet_resource_metal"] + $fleet_row["fleet_resource_crystal"] + $fleet_row["fleet_resource_deuterium"]; if($IncomingFleetGoods > $OtherFleetCapacity) { $RecyclerCapacity -= ($IncomingFleetGoods - $OtherFleetCapacity); } if(($destination_planet["debris_metal"] + $destination_planet["debris_crystal"]) <= $RecyclerCapacity) { $RecycledGoods["metal"] = $destination_planet["debris_metal"]; $RecycledGoods["crystal"] = $destination_planet["debris_crystal"]; } else { if (($destination_planet["debris_metal"] > $RecyclerCapacity / 2) AND ($destination_planet["debris_crystal"] > $RecyclerCapacity / 2)) { $RecycledGoods["metal"] = $RecyclerCapacity / 2; $RecycledGoods["crystal"] = $RecyclerCapacity / 2; } else { if ($destination_planet["debris_metal"] > $destination_planet["debris_crystal"]) { $RecycledGoods["crystal"] = $destination_planet["debris_crystal"]; if ($destination_planet["debris_metal"] > ($RecyclerCapacity - $RecycledGoods["crystal"])) { $RecycledGoods["metal"] = $RecyclerCapacity - $RecycledGoods["crystal"]; } else { $RecycledGoods["metal"] = $destination_planet["debris_metal"]; } } else { $RecycledGoods["metal"] = $destination_planet["debris_metal"]; if ($destination_planet["debris_crystal"] > ($RecyclerCapacity - $RecycledGoods["metal"])) { $RecycledGoods["crystal"] = $RecyclerCapacity - $RecycledGoods["metal"]; } else { $RecycledGoods["crystal"] = $destination_planet["debris_crystal"]; } } } } $NewCargo['Metal'] = $fleet_row["fleet_resource_metal"] + $RecycledGoods["metal"]; $NewCargo['Crystal'] = $fleet_row["fleet_resource_crystal"] + $RecycledGoods["crystal"]; $NewCargo['Deuterium'] = $fleet_row["fleet_resource_deuterium"]; DBStaticPlanet::db_planet_set_by_gspt($fleet_row['fleet_end_galaxy'], $fleet_row['fleet_end_system'], $fleet_row['fleet_end_planet'], PT_PLANET, "`debris_metal` = `debris_metal` - '{$RecycledGoods['metal']}', `debris_crystal` = `debris_crystal` - '{$RecycledGoods['crystal']}'" ); $Message = sprintf( $lang['sys_recy_gotten'], HelperString::numberFloorAndFormat($RecycledGoods["metal"]), $lang['Metal'], HelperString::numberFloorAndFormat($RecycledGoods["crystal"]), $lang['Crystal'] ); msg_send_simple_message ( $fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_RECYCLE, $lang['sys_mess_spy_control'], $lang['sys_recy_report'], $Message); // $QryUpdateFleet = "UPDATE {{fleets}} SET `fleet_mess` = 1,`fleet_resource_metal` = '{$NewCargo['Metal']}',`fleet_resource_crystal` = '{$NewCargo['Crystal']}',`fleet_resource_deuterium` = '{$NewCargo['Deuterium']}' "; // $QryUpdateFleet .= "WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;"; // doquery( $QryUpdateFleet); $fleet_set = array( 'fleet_mess' => 1, 'fleet_resource_metal' => $NewCargo['Metal'], 'fleet_resource_crystal' => $NewCargo['Crystal'], 'fleet_resource_deuterium' => $NewCargo['Deuterium'], ); DbFleetStatic::fleet_update_set($fleet_row['fleet_id'], $fleet_set); return CACHE_FLEET | CACHE_PLANET_DST; }
0
0.933482
1
0.933482
game-dev
MEDIA
0.690022
game-dev
0.82338
1
0.82338
awgil/ffxiv_bossmod
7,595
BossMod/Modules/Endwalker/DeepDungeon/EurekaOrthos/D80ProtoKaliya.cs
namespace BossMod.Endwalker.DeepDungeon.EurekaOrthos.D80ProtoKaliya; public enum OID : uint { Boss = 0x3D18, Helper = 0x233C, WeaponsDrone = 0x3D19, // R2.000, x0 (spawn during fight) } public enum AID : uint { AetheromagnetismPull = 31430, // Helper->player, no cast, single-target AetheromagnetismPush = 31431, // Helper->player, no cast, single-target AutoCannons = 31432, // 3D19->self, 4.0s cast, range 41+R width 5 rect Resonance = 31422, // Boss->player, 5.0s cast, range 12 ?-degree cone Barofield = 31427, // Boss->self, 3.0s cast, single-target NerveGasRing = 32930, // Helper->self, 7.2s cast, range ?-30 donut CentralizedNerveGas = 32933, // Helper->self, 5.3s cast, range 25+R 120-degree cone LeftwardNerveGas = 32934, // Helper->self, 5.3s cast, range 25+R 180-degree cone RightwardNerveGas = 32935, // Helper->self, 5.3s cast, range 25+R 180-degree cone NanosporeJet = 31429, // Boss->self, 5.0s cast, range 100 circle } public enum TetherID : uint { Magnet = 38, // _Gen_WeaponsDrone->player } public enum SID : uint { Barofield = 3420, // none->Boss, extra=0x0 PositiveChargeDrone = 3416, // none->_Gen_WeaponsDrone, extra=0x0 NegativeChargeDrone = 3417, // none->_Gen_WeaponsDrone, extra=0x0 PositiveChargePlayer = 3418, // none->player, extra=0x0 NegativeChargePlayer = 3419, // none->player, extra=0x0 } class Aetheromagnetism(BossModule module) : Components.Knockback(module, ignoreImmunes: true) { private enum Charge { None, Neg, Pos } private readonly Source?[] _sources = new Source?[4]; public override IEnumerable<Source> Sources(int slot, Actor actor) => Utils.ZeroOrOne(_sources[slot]); private static (Charge Charge, DateTime Expire) GetCharge(Actor actor) { foreach (var st in actor.Statuses) switch ((SID)st.ID) { case SID.NegativeChargeDrone: case SID.NegativeChargePlayer: return (Charge.Neg, st.ExpireAt + TimeSpan.FromSeconds(1.1)); case SID.PositiveChargePlayer: case SID.PositiveChargeDrone: return (Charge.Pos, st.ExpireAt + TimeSpan.FromSeconds(1.1)); } return (Charge.None, default); } public override void OnTethered(Actor source, ActorTetherInfo tether) { if (tether.ID == (uint)TetherID.Magnet) { if (!Raid.TryFindSlot(tether.Target, out var slot)) return; var target = Raid[slot]!; var (from, to) = (GetCharge(source), GetCharge(target)); if (from.Charge == Charge.None || to.Charge == Charge.None) return; _sources[slot] = new(source.Position, 10, to.Expire, Kind: from.Charge == to.Charge ? Kind.AwayFromOrigin : Kind.TowardsOrigin); } } public override void OnEventCast(Actor caster, ActorCastEvent spell) { if ((AID)spell.Action.ID is AID.AetheromagnetismPull or AID.AetheromagnetismPush) { if (Raid.TryFindSlot(spell.MainTargetID, out var slot)) _sources[slot] = null; } } public override void AddAIHints(int slot, Actor actor, PartyRolesConfig.Assignment assignment, AIHints hints) { if (_sources[slot] is not { } source) return; var attract = source.Kind == Kind.TowardsOrigin; var barofield = ShapeContains.Circle(Module.PrimaryActor.Position, 5); var arena = ShapeContains.InvertedCircle(Module.PrimaryActor.Position, 8); var cannons = Module.Enemies(OID.WeaponsDrone).Select(d => ShapeContains.Rect(d.Position, d.Rotation, 50, 0, 2.5f)); var all = ShapeContains.Union([barofield, arena, .. cannons]); var bossPos = Module.PrimaryActor.Position; hints.AddForbiddenZone(p => { var dir = (p - source.Origin).Normalized(); var kb = attract ? -dir : dir; // prevent KB through death zone in center if (Intersect.RayCircle(p, kb, bossPos, 5) < 1000) return true; return all(p + kb * 10); }, source.Activation); } } class Barofield(BossModule module) : Components.GenericAOEs(module, AID.Barofield) { private DateTime activation = DateTime.MinValue; public override IEnumerable<AOEInstance> ActiveAOEs(int slot, Actor actor) { if (activation > DateTime.MinValue) yield return new AOEInstance(new AOEShapeCircle(5), Module.PrimaryActor.Position, default, activation); } public override void OnCastStarted(Actor caster, ActorCastInfo spell) { if ((AID)spell.Action.ID is AID.Barofield or AID.NanosporeJet) activation = Module.CastFinishAt(spell); } public override void OnStatusGain(Actor actor, ActorStatus status) { if (status.ID == (uint)SID.Barofield) activation = WorldState.CurrentTime; } public override void OnStatusLose(Actor actor, ActorStatus status) { if (status.ID == (uint)SID.Barofield) activation = DateTime.MinValue; } } class Resonance(BossModule module) : Components.BaitAwayCast(module, AID.Resonance, new AOEShapeCone(12, 45.Degrees())); class RightwardNerveGas(BossModule module) : Components.StandardAOEs(module, AID.RightwardNerveGas, new AOEShapeCone(25, 90.Degrees())); class LeftwardNerveGas(BossModule module) : Components.StandardAOEs(module, AID.LeftwardNerveGas, new AOEShapeCone(25, 90.Degrees())); class CentralizedNerveGas(BossModule module) : Components.StandardAOEs(module, AID.CentralizedNerveGas, new AOEShapeCone(25, 60.Degrees())); class AutoCannons(BossModule module) : Components.StandardAOEs(module, AID.AutoCannons, new AOEShapeRect(45, 2.5f)) { private Aetheromagnetism? _knockback; public override void AddAIHints(int slot, Actor actor, PartyRolesConfig.Assignment assignment, AIHints hints) { _knockback ??= Module.FindComponent<Aetheromagnetism>(); foreach (var kb in _knockback?.Sources(slot, actor) ?? []) if ((kb.Activation - WorldState.CurrentTime).TotalSeconds < 5) return; base.AddAIHints(slot, actor, assignment, hints); } } class NerveGasRing(BossModule module) : Components.StandardAOEs(module, AID.NerveGasRing, new AOEShapeDonut(8, 100)) { private Aetheromagnetism? _knockback; public override void AddAIHints(int slot, Actor actor, PartyRolesConfig.Assignment assignment, AIHints hints) { _knockback ??= Module.FindComponent<Aetheromagnetism>(); foreach (var _ in _knockback?.Sources(slot, actor) ?? []) return; base.AddAIHints(slot, actor, assignment, hints); } } class D80ProtoKaliyaStates : StateMachineBuilder { public D80ProtoKaliyaStates(BossModule module) : base(module) { TrivialPhase() .ActivateOnEnter<AutoCannons>() .ActivateOnEnter<CentralizedNerveGas>() .ActivateOnEnter<RightwardNerveGas>() .ActivateOnEnter<LeftwardNerveGas>() .ActivateOnEnter<Resonance>() .ActivateOnEnter<Barofield>() .ActivateOnEnter<Aetheromagnetism>() .ActivateOnEnter<NerveGasRing>(); } } [ModuleInfo(BossModuleInfo.Maturity.Contributed, GroupType = BossModuleInfo.GroupType.CFC, GroupID = 904, NameID = 12247)] public class D80ProtoKaliya(WorldState ws, Actor primary) : BossModule(ws, primary, new(-600, -300), new ArenaBoundsCircle(20));
0
0.913072
1
0.913072
game-dev
MEDIA
0.972891
game-dev
0.937512
1
0.937512
spartanoah/acrimony-client
8,121
net/minecraft/util/CombatTracker.java
/* * Decompiled with CFR 0.153-SNAPSHOT (d6f6758-dirty). */ package net.minecraft.util; import com.google.common.collect.Lists; import java.util.List; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.CombatEntry; import net.minecraft.util.DamageSource; import net.minecraft.util.IChatComponent; public class CombatTracker { private final List<CombatEntry> combatEntries = Lists.newArrayList(); private final EntityLivingBase fighter; private int field_94555_c; private int field_152775_d; private int field_152776_e; private boolean field_94552_d; private boolean field_94553_e; private String field_94551_f; public CombatTracker(EntityLivingBase fighterIn) { this.fighter = fighterIn; } public void func_94545_a() { this.func_94542_g(); if (this.fighter.isOnLadder()) { Block block = this.fighter.worldObj.getBlockState(new BlockPos(this.fighter.posX, this.fighter.getEntityBoundingBox().minY, this.fighter.posZ)).getBlock(); if (block == Blocks.ladder) { this.field_94551_f = "ladder"; } else if (block == Blocks.vine) { this.field_94551_f = "vines"; } } else if (this.fighter.isInWater()) { this.field_94551_f = "water"; } } public void trackDamage(DamageSource damageSrc, float healthIn, float damageAmount) { this.reset(); this.func_94545_a(); CombatEntry combatentry = new CombatEntry(damageSrc, this.fighter.ticksExisted, healthIn, damageAmount, this.field_94551_f, this.fighter.fallDistance); this.combatEntries.add(combatentry); this.field_94555_c = this.fighter.ticksExisted; this.field_94553_e = true; if (combatentry.isLivingDamageSrc() && !this.field_94552_d && this.fighter.isEntityAlive()) { this.field_94552_d = true; this.field_152776_e = this.field_152775_d = this.fighter.ticksExisted; this.fighter.sendEnterCombat(); } } public IChatComponent getDeathMessage() { IChatComponent ichatcomponent; if (this.combatEntries.size() == 0) { return new ChatComponentTranslation("death.attack.generic", this.fighter.getDisplayName()); } CombatEntry combatentry = this.func_94544_f(); CombatEntry combatentry1 = this.combatEntries.get(this.combatEntries.size() - 1); IChatComponent ichatcomponent1 = combatentry1.getDamageSrcDisplayName(); Entity entity = combatentry1.getDamageSrc().getEntity(); if (combatentry != null && combatentry1.getDamageSrc() == DamageSource.fall) { IChatComponent ichatcomponent2 = combatentry.getDamageSrcDisplayName(); if (combatentry.getDamageSrc() != DamageSource.fall && combatentry.getDamageSrc() != DamageSource.outOfWorld) { if (!(ichatcomponent2 == null || ichatcomponent1 != null && ichatcomponent2.equals(ichatcomponent1))) { ItemStack itemstack1; Entity entity1 = combatentry.getDamageSrc().getEntity(); ItemStack itemStack = itemstack1 = entity1 instanceof EntityLivingBase ? ((EntityLivingBase)entity1).getHeldItem() : null; ichatcomponent = itemstack1 != null && itemstack1.hasDisplayName() ? new ChatComponentTranslation("death.fell.assist.item", this.fighter.getDisplayName(), ichatcomponent2, itemstack1.getChatComponent()) : new ChatComponentTranslation("death.fell.assist", this.fighter.getDisplayName(), ichatcomponent2); } else if (ichatcomponent1 != null) { ItemStack itemstack; ItemStack itemStack = itemstack = entity instanceof EntityLivingBase ? ((EntityLivingBase)entity).getHeldItem() : null; ichatcomponent = itemstack != null && itemstack.hasDisplayName() ? new ChatComponentTranslation("death.fell.finish.item", this.fighter.getDisplayName(), ichatcomponent1, itemstack.getChatComponent()) : new ChatComponentTranslation("death.fell.finish", this.fighter.getDisplayName(), ichatcomponent1); } else { ichatcomponent = new ChatComponentTranslation("death.fell.killer", this.fighter.getDisplayName()); } } else { ichatcomponent = new ChatComponentTranslation("death.fell.accident." + this.func_94548_b(combatentry), this.fighter.getDisplayName()); } } else { ichatcomponent = combatentry1.getDamageSrc().getDeathMessage(this.fighter); } return ichatcomponent; } public EntityLivingBase func_94550_c() { EntityLivingBase entitylivingbase = null; EntityPlayer entityplayer = null; float f = 0.0f; float f1 = 0.0f; for (CombatEntry combatentry : this.combatEntries) { if (combatentry.getDamageSrc().getEntity() instanceof EntityPlayer && (entityplayer == null || combatentry.func_94563_c() > f1)) { f1 = combatentry.func_94563_c(); entityplayer = (EntityPlayer)combatentry.getDamageSrc().getEntity(); } if (!(combatentry.getDamageSrc().getEntity() instanceof EntityLivingBase) || entitylivingbase != null && !(combatentry.func_94563_c() > f)) continue; f = combatentry.func_94563_c(); entitylivingbase = (EntityLivingBase)combatentry.getDamageSrc().getEntity(); } if (entityplayer != null && f1 >= f / 3.0f) { return entityplayer; } return entitylivingbase; } private CombatEntry func_94544_f() { CombatEntry combatentry = null; CombatEntry combatentry1 = null; int i = 0; float f = 0.0f; for (int j = 0; j < this.combatEntries.size(); ++j) { CombatEntry combatentry3; CombatEntry combatentry2 = this.combatEntries.get(j); CombatEntry combatEntry = combatentry3 = j > 0 ? this.combatEntries.get(j - 1) : null; if ((combatentry2.getDamageSrc() == DamageSource.fall || combatentry2.getDamageSrc() == DamageSource.outOfWorld) && combatentry2.getDamageAmount() > 0.0f && (combatentry == null || combatentry2.getDamageAmount() > f)) { combatentry = j > 0 ? combatentry3 : combatentry2; f = combatentry2.getDamageAmount(); } if (combatentry2.func_94562_g() == null || combatentry1 != null && !(combatentry2.func_94563_c() > (float)i)) continue; combatentry1 = combatentry2; } if (f > 5.0f && combatentry != null) { return combatentry; } if (i > 5 && combatentry1 != null) { return combatentry1; } return null; } private String func_94548_b(CombatEntry p_94548_1_) { return p_94548_1_.func_94562_g() == null ? "generic" : p_94548_1_.func_94562_g(); } public int func_180134_f() { return this.field_94552_d ? this.fighter.ticksExisted - this.field_152775_d : this.field_152776_e - this.field_152775_d; } private void func_94542_g() { this.field_94551_f = null; } public void reset() { int i; int n = i = this.field_94552_d ? 300 : 100; if (this.field_94553_e && (!this.fighter.isEntityAlive() || this.fighter.ticksExisted - this.field_94555_c > i)) { boolean flag = this.field_94552_d; this.field_94553_e = false; this.field_94552_d = false; this.field_152776_e = this.fighter.ticksExisted; if (flag) { this.fighter.sendEndCombat(); } this.combatEntries.clear(); } } public EntityLivingBase getFighter() { return this.fighter; } }
0
0.888667
1
0.888667
game-dev
MEDIA
0.990762
game-dev
0.964727
1
0.964727
Goobwabber/MultiplayerCore
1,654
MultiplayerCore/Patches/DataModelBinderPatch.cs
using HarmonyLib; using MultiplayerCore.Objects; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using Zenject; namespace MultiplayerCore.Patches { [HarmonyPatch(typeof(LobbyDataModelInstaller), nameof(LobbyDataModelInstaller.InstallBindings))] internal class DataModelBinderPatch { private static readonly MethodInfo _rootMethod = typeof(ConcreteBinderNonGeneric).GetMethod(nameof(ConcreteBinderNonGeneric.To), Array.Empty<Type>()); private static readonly MethodInfo _playersDataModelAttacher = SymbolExtensions.GetMethodInfo(() => PlayersDataModelAttacher(null!)); private static readonly MethodInfo _playersDataModelMethod = _rootMethod.MakeGenericMethod(new Type[] { typeof(LobbyPlayersDataModel) }); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var codes = instructions.ToList(); for (int i = 0; i < codes.Count; i++) { if (codes[i].opcode == OpCodes.Callvirt) { if (codes[i].Calls(_playersDataModelMethod)) { CodeInstruction newCode = new CodeInstruction(OpCodes.Callvirt, _playersDataModelAttacher); codes[i] = newCode; } } } return codes.AsEnumerable(); } private static FromBinderNonGeneric PlayersDataModelAttacher(ConcreteBinderNonGeneric contract) { return contract.To<MpPlayersDataModel>(); } } }
0
0.614724
1
0.614724
game-dev
MEDIA
0.526953
game-dev
0.660047
1
0.660047
LeoMinecraftModding/eternal-starlight
1,917
common/src/main/java/cn/leolezury/eternalstarlight/common/block/CrystalfleurVineBlock.java
package cn.leolezury.eternalstarlight.common.block; import cn.leolezury.eternalstarlight.common.registry.ESBlocks; import com.mojang.serialization.MapCodec; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.RandomSource; import net.minecraft.world.level.block.state.BlockState; public class CrystalfleurVineBlock extends SimpleMultifaceBlock { public static final MapCodec<CrystalfleurVineBlock> CODEC = simpleCodec(CrystalfleurVineBlock::new); public CrystalfleurVineBlock(Properties properties) { super(properties); } @Override protected MapCodec<CrystalfleurVineBlock> codec() { return CODEC; } @Override public void performBonemeal(ServerLevel level, RandomSource randomSource, BlockPos pos, BlockState state) { super.performBonemeal(level, randomSource, pos, state); if (randomSource.nextInt(8) == 0) { for (Direction direction : Direction.values()) { BlockPos relativePos = pos.relative(direction); BlockState relativeState = level.getBlockState(relativePos); if (relativeState.is(ESBlocks.RED_STARLIGHT_CRYSTAL_CLUSTER.get()) && randomSource.nextBoolean()) { level.setBlockAndUpdate(relativePos, ESBlocks.BLOOMING_RED_STARLIGHT_CRYSTAL_CLUSTER.get().withPropertiesOf(relativeState)); } else if (relativeState.is(ESBlocks.BLUE_STARLIGHT_CRYSTAL_CLUSTER.get()) && randomSource.nextBoolean()) { level.setBlockAndUpdate(relativePos, ESBlocks.BLOOMING_BLUE_STARLIGHT_CRYSTAL_CLUSTER.get().withPropertiesOf(relativeState)); } else if (relativeState.isAir()) { BlockState flowerState = randomSource.nextBoolean() ? ESBlocks.RED_CRYSTALFLEUR.get().defaultBlockState() : ESBlocks.BLUE_CRYSTALFLEUR.get().defaultBlockState(); if (flowerState.canSurvive(level, relativePos)) { level.setBlockAndUpdate(relativePos, flowerState); } } } } } }
0
0.887413
1
0.887413
game-dev
MEDIA
0.872993
game-dev
0.938203
1
0.938203
Gakuto1112/SenkoSan
1,791
scripts/actions/cloth_cleaning.lua
---@class ClothCleaning 雑巾がけのアニメーションを制御するクラス ClothCleaning = General.instance({ ---雑巾がけアニメーションを再生する。 play = function (self) AnimationAction.play(self) sounds:playSound(CompatibilityUtils:checkSound("minecraft:entity.item.pickup"), player:getPos(), 1, 0.5) Sleeve.Moving = false Arms.hideHeldItem(true) end, ---雑巾がけアニメーションを停止する。 stop = function (self) AnimationAction.stop(self) sounds:playSound(CompatibilityUtils:checkSound("minecraft:entity.item.pickup"), player:getPos(), 1, 0.5) Sleeve.Moving = true end, ---アニメーション再生中に毎チック実行される関数 onAnimationTick = function (self) AnimationAction.onAnimationTick(self) if self.AnimationCount == 90 then models.models.cloth_cleaning.Stain:setVisible(false) elseif self.AnimationCount == 40 then FaceParts.setEmotion("CLOSED", "CLOSED", "OPENED", 40, true) local playerPos = player:getPos() sounds:playSound(CompatibilityUtils:checkSound("minecraft:entity.player.levelup"), playerPos, 1, 1.5) for _ = 1, 30 do particles:newParticle(CompatibilityUtils:checkParticle("minecraft:happy_villager"), playerPos:copy():add((math.random() - 0.5) * 4, (math.random() - 0.5) * 4 + 1, (math.random() - 0.5) * 4)) end end end }, AnimationAction, function () ---@diagnostic disable-next-line: undefined-field return BroomCleaning:checkAction() end, {models.models.main.Avatar.UpperBody.Arms.RightArm.RightArmBottom.ClothRAB, models.models.cloth_cleaning.Stain}, {models.models.main.Avatar.UpperBody.Arms.RightArm.RightArmBottom.ClothRAB, models.models.cloth_cleaning.Stain}, animations["models.main"]["cloth_cleaning"], {animations["models.cloth_cleaning"]["cloth_cleaning"], animations["models.costume_maid_a"]["cloth_cleaning"], animations["models.costume_maid_b"]["cloth_cleaning"]}, 40) return ClothCleaning
0
0.619903
1
0.619903
game-dev
MEDIA
0.936791
game-dev
0.506688
1
0.506688
Sduibek/fixtsrc
5,655
SCRIPTS/CHILDRN1.SSL
procedure start; procedure add_party; procedure update_party; procedure remove_party; procedure Lighting; procedure Darkness; procedure Invasion; export variable Master_Ptr; export variable Red_Door_Ptr; export variable Black_Door_Ptr; export variable Laura_Ptr; export variable Shop_Ptr; export variable Shopkeeper_Ptr; export variable signal_mutants; variable party_elevation; variable dude_start_hex; variable player_elevation; variable cur_count; variable prev_count; export variable Ian_ptr; export variable Dog_ptr; export variable Tycho_ptr; export variable Katja_ptr; export variable Tandi_ptr; procedure start begin if (script_action == 15) then begin//map_enter_p_proc (or "map_init") called when entering from World Map, on green "exit" grids, SOME ladders, doesn't appear to call on elevators or manholes call Lighting; set_global_var(77, 2); if metarule(14, 0) then begin display_msg(message_str(194, 110)); end player_elevation := elevation(dude_obj); if (global_var(32) == 0) then begin override_map_start(100, 102, 0, 5); end else begin if (global_var(32) == 2) then begin override_map_start(100, 86, 0, 2); end else begin if (global_var(32) == 1) then begin override_map_start(99, 113, 1, 5); end else begin if (global_var(32) == 3) then begin override_map_start(96, 63, 1, 1); end else begin if (global_var(32) == 4) then begin override_map_start(85, 63, 1, 4); end else begin override_map_start(100, 102, 0, 5); end end end end end call add_party; end else begin if (script_action == 23) then begin//map_update_p_proc -- called every dozen seconds or so, & additionally on certain events (exit dialog, end combat, load map, etc) call Lighting; if (elevation(dude_obj) == 1) then begin set_global_var(600, 1); end call update_party; end else begin if (script_action == 16) then begin//map_exit_p_proc (also appears as "remove_party"!) - called on red exit grids call remove_party; end end end end procedure Lighting begin variable LVar0 := 0; LVar0 := game_time_hour; if ((LVar0 >= 600) and (LVar0 < 700)) then begin set_light_level(LVar0 - 600 + 40); end else begin if ((LVar0 >= 700) and (LVar0 < 1800)) then begin set_light_level(100); end else begin if ((LVar0 >= 1800) and (LVar0 < 1900)) then begin set_light_level(100 - (LVar0 - 1800)); end else begin set_light_level(40); end end end end procedure Darkness begin set_light_level(40); end procedure add_party begin if global_var(26) == 5 then begin if Tandi_ptr != 0 then begin critter_add_trait(Tandi_ptr, 1, 6, 0); party_add(Tandi_ptr); end end if global_var(118) == 2 then begin if Ian_ptr != 0 then begin critter_add_trait(Ian_ptr, 1, 6, 0); party_add(Ian_ptr); end end if global_var(5) then begin if Dog_ptr != 0 then begin critter_add_trait(Dog_ptr, 1, 6, 0); party_add(Dog_ptr); end end if global_var(121) == 2 then begin if Tycho_ptr != 0 then begin critter_add_trait(Tycho_ptr, 1, 6, 0); party_add(Tycho_ptr); end end if global_var(244) == 2 then begin if Katja_ptr != 0 then begin critter_add_trait(Katja_ptr, 1, 6, 0); party_add(Katja_ptr); end end end procedure update_party begin if party_elevation != elevation(dude_obj) then begin party_elevation := elevation(dude_obj); if global_var(118) == 2 then begin if Ian_ptr != 0 then begin move_to(Ian_ptr, tile_num_in_direction(tile_num(dude_obj), 1, 2), elevation(dude_obj)); end end if global_var(5) then begin if Dog_ptr != 0 then begin move_to(Dog_ptr, tile_num_in_direction(tile_num(dude_obj), 0, 1), elevation(dude_obj)); end end if global_var(121) == 2 then begin if Tycho_ptr != 0 then begin move_to(Tycho_ptr, tile_num_in_direction(tile_num(dude_obj), 3, 2), elevation(dude_obj)); end end if global_var(244) == 2 then begin if Katja_ptr != 0 then begin move_to(Katja_ptr, tile_num_in_direction(tile_num(dude_obj), 3, 1), elevation(dude_obj)); end end if global_var(26) == 5 then begin if Tandi_ptr != 0 then begin move_to(Tandi_ptr, tile_num_in_direction(tile_num(dude_obj), 4, 1), elevation(dude_obj)); end end end end procedure remove_party begin if (global_var(118) == 2) then begin set_global_var(118, 2); end if (global_var(5)) then begin set_global_var(5, 1); end if (global_var(121) == 2) then begin set_global_var(121, 2); end if (global_var(244) == 2) then begin set_global_var(244, 2); end if (global_var(26) == 5) then begin end end procedure Invasion begin if (global_var(18) == 0) then begin if (global_var(149) <= (game_time / (10 * 60 * 60 * 24))) then begin set_global_var(13, 1); end if (global_var(150) <= (game_time / (10 * 60 * 60 * 24))) then begin set_global_var(14, 1); end if (global_var(151) <= (game_time / (10 * 60 * 60 * 24))) then begin set_global_var(16, 1); set_global_var(583, 0); set_global_var(584, 0); set_global_var(585, 0); set_global_var(586, 0); end if (global_var(152) <= (game_time / (10 * 60 * 60 * 24))) then begin set_global_var(15, 1); end if (global_var(153) <= (game_time / (10 * 60 * 60 * 24))) then begin set_global_var(12, 1); end if (global_var(154) <= (game_time / (10 * 60 * 60 * 24))) then begin set_global_var(11, 1); play_gmovie(7);//------ Vault 13 is invaded by mutants and killed. You lose. metarule(13, 0); end if (global_var(148) <= (game_time / (10 * 60 * 60 * 24))) then begin set_global_var(7, 1); end end end
0
0.724624
1
0.724624
game-dev
MEDIA
0.932733
game-dev
0.883719
1
0.883719
Razor12911/xtool
78,164
contrib/mORMot/SyNode/SyNode.pas
/// SyNode - server-side JavaScript execution using the SpiderMonkey 45/52 // library with nodeJS modules support // - this unit is a part of the freeware Synopse framework, // licensed under a MPL/GPL/LGPL tri-license; version 1.18 unit SyNode; { This file is part of Synopse framework. Synopse framework. Copyright (C) 2022 Arnaud Bouchez Synopse Informatique - http://synopse.info SyNode for mORMot Copyright (C) 2022 Pavel Mashlyakovsky & Vadim Orel pavel.mash at gmail.com Some ideas taken from http://code.google.com/p/delphi-javascript http://delphi.mozdev.org/javascript_bridge/ *** BEGIN LICENSE BLOCK ***** Version: MPL 1.1/GPL 2.0/LGPL 2.1 The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code is Pavel Mashlyakovsky. Portions created by the Initial Developer are Copyright (C) 2022 the Initial Developer. All Rights Reserved. Contributor(s): - Arnaud Bouchez - Vadim Orel - Pavel Mashlyakovsky - win2014 - Geogre - ssoftpro Alternatively, the contents of this file may be used under the terms of either the GNU General Public License Version 2 or later (the "GPL"), or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the MPL, the GPL or the LGPL. ***** END LICENSE BLOCK ***** Version 1.18 - initial release. Use SpiderMonkey 45 - x64 support added - move a Worker classes from UnityBase to SyNode Allow to create and communicate with a threads from JavaScript - implement nodeJS Buffer - improved compartibility with nodeJS utils - add a `process.version` - implement a setTimeout/setInverval/setImmediate etc. - SpiderMonkey 52 (x32 & x64) support ( SM52 condition should be defined ) - VSCode debugging support via [vscode-firefox-debug](https://github.com/hbenl/vscode-firefox-debug) adapter Thanks to George for patch - JS `process` now instance of EventEmitter - JS Engine will emit `exit` event on destroy as in node } {$I Synopse.inc} // define HASINLINE CPU32 CPU64 OWNNORMTOUPPER {$I SyNode.inc} // define SM_DEBUG CONSIDER_TIME_IN_Z {$IFDEF CORE_MODULES_IN_RES} {$R 'core_modules.res' 'core_modules.rc'} {$ENDIF} interface uses {$ifndef FPC} Windows, ShLwApi, // for older Delphi versions download this file from JEDI library {$else} LazFileUtils, dynlibs, {$endif} {$ifdef ISDELPHIXE2}System.SysUtils,{$else}SysUtils,{$endif} Classes, {$ifndef LVCL} Contnrs, {$endif} {$ifdef ISDELPHIXE2} System.Rtti, {$endif} Variants, SynCommons, SynLog, SpiderMonkey, NSPRAPI, SyNodeProto, mORMot, SynCrtSock, SyNodeBinding_worker; const /// default stack growning size STACK_CHUNK_SIZE: Cardinal = 8192; type {$M+} TSMEngineManager = class; {$M-} TSMEngine = class; TSMEngineClass = class of TSMEngine; /// implements a ThreadSafe JavaScript engine // - use TSMEngineManager.ThreadSafeEngine to retrieve the Engine instance // corresponding to the current thread, in multithread application // - contains JSRuntime + JSContext (to be ready for new SpiderMonkey version where // context and runtime is the same) // - contains also one "global" JavaScript object. From script it is // accessible via "global." (in browser, this is the "window." object) // - set SpiderMonkey error reporter and store last SpiderMonkey error in // LastError property TSMEngine = class private fPrivateDataForDebugger: Pointer; fNameForDebug: RawUTF8; fDoInteruptInOwnThread: TThreadMethod; {$IFNDEF SM52} fRt: PJSRuntime; {$ENDIF} fcomp: PJSCompartment; fStringFinalizer: JSStringFinalizer; fManager: TSMEngineManager; fGlobalObject: PJSRootedObject; // gloal._timerLoop function used to emulate setTimeout/setInterval // event loop. Implemented in WindowsTimer.js FGlobalTimerLoopFunc: PJSRootedValue; fGlobalObjectDbg: PJSRootedObject; fEngineContentVersion: Cardinal; fThreadID: TThreadID; fLastErrorMsg: string; fLastErrorNum: integer; fLastErrorFileName: RawUTF8; fLastErrorLine: integer; fLastErrorStackTrace: SynUnicode; fErrorExist: boolean; fThreadData: pointer; fDllModulesUnInitProcList: TList; fNeverExpire: boolean; fWebAppRootDir: RawUTF8; /// called from SpiderMonkey callback. Do not raise exception here // instead use CheckJSError metod after JSAPI compile/evaluate call {$IFDEF SM52} procedure DoProcessJSError(report: PJSErrorReport); virtual; {$ELSE} procedure DoProcessJSError(errMsg: PCChar; report: PJSErrorReport); virtual; {$ENDIF} /// called from SpiderMonkey callback. It used for interrupt execution of script // when it executes too long function DoProcessOperationCallback: Boolean; virtual; procedure SetPrivateDataForDebugger(const Value: Pointer); protected fCx: PJSContext; // used by Watchdog thread state. See js.cpp fTimeOutAborted: Boolean; fTimedOut: Boolean; fWatchdogLock: PRLock; fWatchdogWakeup: PRCondVar; fWatchdogThread: PRThread; fWatchdogHasTimeout: Boolean; fWatchdogTimeout: Int64; fSleepWakeup: PRCondVar; fTimeoutValue: integer; fCreatedAtTick: Int64; function ScheduleWatchdog(t: integer): Boolean; procedure KillWatchdog; function InitWatchdog: boolean; procedure SetTimeoutValue(const Value: Integer); public /// create one threadsafe JavaScript Engine instance // - initialize internal JSRuntime, JSContext, and global objects and // standard JavaScript classes // - do not create Engine directly via this constructor, but instead call // TSMEngineManager.ThreadSafeEngine constructor Create(aManager: TSMEngineManager); virtual; /// finalize the JavaScript engine instance destructor Destroy; override; /// reference to TSMEngineManager own this engine property Manager: TSMEngineManager read FManager; /// thread specific data - pointer to any structure, passed into ThreadSafeEngine call // used to access a thread-details in the native functions // as TsmEngive(cx.PrivateData).ThreadData property ThreadData: pointer read FThreadData; procedure SetThreadData(pThreadData: pointer); /// check if last call to JSAPI compile/eval fucntion was successful // - raise ESMException if any error occurred // - put error description to SynSMLog procedure CheckJSError(res: Boolean); /// clear last JavaScript error // - called before every evaluate() function call procedure ClearLastError; /// trigger Garbage Collection // - all unrooted things (JSString, JSObject, VSVal) will be released procedure GarbageCollect; /// Offer the JavaScript engine an opportunity to perform garbage collection if needed // - Tries to determine whether garbage collection in would free up enough // memory to be worth the amount of time it would take. If so, it performs // some garbage collection // - Frequent calls are safe and will not cause the application to spend a // lot of time doing redundant garbage collection work procedure MaybeGarbageCollect; /// evaluate a JavaScript script in the global scope // - if exception raised in script - raise Delphi ESMException // - on success returns last executed expression statement processed // in the script as a variant // - JavaScript equivalent to // ! eval(script) procedure Evaluate(const script: SynUnicode; const scriptName: RawUTF8; lineNo: Cardinal; out result: jsval); overload; procedure Evaluate(const script: SynUnicode; const scriptName: RawUTF8; lineNo: Cardinal); overload; /// evaluate script embadedd into application resources procedure EvaluateRes(const ResName: string; out result: jsval); /// evaluate a JavaScript script as Module // - if exception raised in script - raise Delphi ESMException // - JavaScript equivalent to import of ES6 function EvaluateModule(const scriptName: RawUTF8): jsval; /// run method of object // - if exception raised in script - raise Delphi ESMException // - on success returns function result // - JavaScript equivalent to // ! obj.funcName(args[0], args[1]...) function CallObjectFunction(obj: PJSRootedObject; funcName: PCChar; const args: array of jsval): jsval; /// The same as CallObjectFunction but accept funcVal insteadof fuction name // a little bit faster when CallObjectFunction function CallObjectFunctionVal(obj: PJSRootedObject; const funcVal: PJSRootedValue; const args: array of jsval): jsval; /// access to the associated global object as low-level PJSRootedObject property GlobalObject: PJSRootedObject read FGlobalObject; /// access to the associated global object for debugging as low-level PJSRootedObject property GlobalObjectDbg: PJSRootedObject read FGlobalObjectDbg; /// access to the associated execution context property cx: PJSContext read fCx; {$IFNDEF SM52} /// access to the associated execution runtime property rt: PJSRuntime read frt; {$ENDIF} /// access to the associated execution compartment property comp: PJSCompartment read fcomp; /// internal version number of engine scripts // - used in TSMEngine.ThreadSafeEngine to determine if context is up to // date, in order to trigger on-the-fly reload of scripts without the need // if restarting the application // - caller must change this parameter value e.g. in case of changes in // the scripts folder in an HTTP server property EngineContentVersion: Cardinal read FEngineContentVersion; /// last error message triggered during JavaScript execution property LastErrorMsg: string read FLastErrorMsg; /// last error source code line number triggered during JavaScript execution property LastErrorLine: integer read FLastErrorLine; /// last error file name triggered during JavaScript execution property LastErrorFileName: RawUTF8 read FLastErrorFileName; /// TRUE if an error was triggered during JavaScript execution property ErrorExist: boolean read FErrorExist; /// notifies a WatchDog timeout property TimeOutAborted: boolean read FTimeOutAborted; /// define a WatchDog timeout interval (in seconds) // - is set to -1 by default, i.e. meaning no execution timeout property TimeOutValue: Integer read fTimeoutValue write SetTimeoutValue default -1; /// If `true` engine will never expire property NeverExpire: boolean read FNeverExpire write FNeverExpire; /// Define a Delphi class as JS class (prototype), so it can be created via new: // engine.defineClass(TmyObject, TSMNewRTTIProtoObject); // and in JS // var myObj = new TmyObject(); // - Class will be exposed in the aParent javaScript object, if aParent is omitted - in the global object // - AProto parameter can be a TSMCustomProtoObject descendant (TSMSimpleRTTIProtoObject, TSMNewRTTIProtoObject) // WARNING - possible prototypes count is limited to 255 - JSCLASS_GLOBAL_SLOT_COUNT = 76 for SM45, // so it is better to use a bindings, add where a native functions and wrap it in class into the JavaScript // see `fs.js` for sample. function defineClass(AForClass: TClass; AProto: TSMCustomProtoObjectClass; aParent: PJSRootedObject = nil): TSMCustomProtoObject; /// Add a set of classes with the same delphi binding implementation: // engine.defineClasses([TubEntity, TubDomain, TubEntityAttribute], TSMNewRTTIProtoObject); procedure defineClasses(const AClasses: array of TClass; AProto: TSMCustomProtoObjectClass; aParent: PJSRootedObject = nil); /// define JS object for enumeratin type // for TMyEnum = (etA, etB); will create in JS aObj.TMyEnum = {etA: 0, etB: 1); procedure defineEnum(ti: PTypeInfo; aObj: PJSRootedObject); /// Cancel current execution JavaScript. // This procedure can be called from other script // if AWithException paramener is thue, will raise a // ESMException with message LONG_SCRIPT_EXECUTION procedure CancelExecution(AWithException: boolean = true); procedure DefineProcessBinding; procedure DefineNodeProcess; procedure DefineModuleLoader; /// Used by debugger property PrivateDataForDebugger: Pointer read FPrivateDataForDebugger write SetPrivateDataForDebugger; /// Name of this engine. Will be shown in debugger for indentify this engine property nameForDebug: RawUTF8 read fnameForDebug; /// root path for current web app engine context property webAppRootDir: RawUTF8 read fWebAppRootDir; /// Handler hor debugger. Called from debugger thread when debugger need // call rt.InterruptCallback(cx) in engine''s thread // this method must wake up the engine's thread and thread must // execute rt.InterruptCallback(cx) for this engine property doInteruptInOwnThread: TThreadMethod read fDoInteruptInOwnThread write fDoInteruptInOwnThread; end; /// prototype of SpideMonkey notification callback method TEngineEvent = procedure(const Engine: TSMEngine) of object; /// event of getting engine name or web app root path TEngineNameEvent = function(const Engine: TSMEngine): RawUTF8 of object; /// event for loading dll module TDllModuleEvent = procedure(Handle: HMODULE) of object; /// event for adding values to process.binding TSMProcessBindingHandler = function(const Engine: TSMEngine; const bindingNamespaceName: SynUnicode): jsval; TDllModuleInitProc = function(cx: PJSContext; exports_: PJSRootedObject; require: PJSRootedObject; module: PJSRootedObject; __filename: PWideChar; __dirname: PWideChar): boolean; cdecl; TDllModuleUnInitProc = function: boolean; cdecl; TDllModuleRec = record init: TDllModuleInitProc; unInit: TDllModuleUnInitProc; end; PDllModuleRec = ^TDllModuleRec; /// main access point to the SpiderMonkey per-thread scripting engines // - allow thread-safe access to an internal per-thread TSMEngine instance list // - contains runtime-level properties shared between thread-safe engines // - you can create several TSMEngineManager instances, if you need several // separate scripting instances // - set OnNewEngine callback to initialize each TSMEngine, when a new thread // is accessed, and tune per-engine memory allocation via MaxPerEngineMemory // and MaxRecursionDepth // - get the current per-thread TSMEngine instance via ThreadSafeEngine method TSMEngineManager = class private FMaxPerEngineMemory: Cardinal; FMaxNurseryBytes: Cardinal; FMaxRecursionDepth: Cardinal; FEnginePool: TSynObjectListLocked; FRemoteDebuggerThread: TThread; FContentVersion: Cardinal; FOnNewEngine: TEngineEvent; FOnDebuggerInit: TEngineEvent; FOnGetName: TEngineNameEvent; FOnGetWebAppRootPath: TEngineNameEvent; FOnDebuggerConnected: TEngineEvent; FOnDllModuleLoaded: TDllModuleEvent; {$ifdef ISDELPHIXE2} FRttiCx: TRttiContext; {$endif} FEngineClass: TSMEngineClass; /// List of loaded dll modules FDllModules: TRawUTF8List; /// Path to core modules FCoreModulesPath: RawUTF8; FEngineExpireTimeOutTicks: Int64; FWorkersManager: TJSWorkersManager; function GetEngineExpireTimeOutMinutes: cardinal; procedure SetEngineExpireTimeOutMinutes(const minutes: cardinal); procedure SetMaxPerEngineMemory(AMaxMem: Cardinal); procedure SetMaxNurseryBytes(AMaxNurseryBytes: Cardinal); protected grandParent: TSMEngine; /// Release a javaScript engine for specified thread procedure ReleaseEngineForThread(aThreadID: TThreadID); /// returns -1 if none was defined yet // - this method is not protected via the global FEngineCS mutex/lock function ThreadEngineIndex(ThreadID: TThreadID): Integer; /// returns nil if none was defined yet function CurrentThreadEngine: TSMEngine; /// called when a new Engine is created // - this default implementation will run the OnNewEngine callback (if any) procedure DoOnNewEngine(const Engine: TSMEngine); virtual; function getPauseDebuggerOnFirstStep: boolean; procedure setPauseDebuggerOnFirstStep(const Value: boolean); function evalDllModule(cx: PJSContext; module: PJSRootedObject; const filename: RawUTF8): TDllModuleUnInitProc; /// Get handler of process.binding function GetBinding(const Name: RawUTF8): TSMProcessBindingHandler; public /// initialize the SpiderMonkey scripting engine // aCoreModulesPath can be empty in case core modules are embadded // as resources (CORE_MODULES_IN_RES is defined) constructor Create(const aCoreModulesPath: RawUTF8; aEngineClass: TSMEngineClass = nil); virtual; /// finalize the SpiderMonkey scripting engine destructor Destroy; override; /// Add a binding namespace - a set of native functions exposed to the JavaScript engine // - we recommend not to use it directly in the businnes logic, // but create a JavaScript module and wrap a binding function by the JavaScript // see how `fs` binding from SyNodeBinding_fs unit is wrapped by `SyNode\core_modules\node_modules\fs.js` class procedure RegisterBinding(const Name: RawUTF8; const handler: TSMProcessBindingHandler); /// get or create one Engine associated with current running thread // pThreadData is a pointer to any structure relative to this thread // accessible via TsmEngine.ThreadData function ThreadSafeEngine(pThreadData: pointer): TSMEngine; /// method to be called when a thread is about to be finished // - you can call this method just before a thread is finished to ensure // that the associated scripting Engine will be released // - could be used e.g. in a try...finally block inside a TThread.Execute // overriden method procedure ReleaseCurrentThreadEngine; /// returns nil if none was defined yet function EngineForThread(ThreadID: TTHreadID): TSMEngine; /// internal version of the script files // - used in TSMEngine.ThreadSafeEngine to determine if context is up to // date, in order to trigger on-the-fly reload of scripts without the need // if restarting the application property ContentVersion: Cardinal read FContentVersion write FContentVersion; /// lock/mutex used for thread-safe access to the TSMEngine list procedure Lock; procedure UnLock; {$ifdef ISDELPHIXE2} /// for defining JS object based on New RTTI we need a single TRttiContext // in other case we got AV if used from DLL property RttiCx: TRttiContext read FRttiCx; {$endif} /// Start/stop debugger listening on selected port // - expects the port to be specified as Ansi string, e.g. '1234' // - you can optionally specify a server address to bind to, e.g. // '1.2.3.4:1234' // - debugger create a dedicated thread where it listen to a requests // from a remote debug UI procedure startDebugger(const port: SockString = '6000'); procedure stopDebugger; /// Write text as console log to current thread Engine's debugger (if exists) procedure debuggerLog(const Text: RawUTF8); /// when debugger connected to new engine this Engine must pause on first step property pauseDebuggerOnFirstStep: boolean read getPauseDebuggerOnFirstStep write setPauseDebuggerOnFirstStep; /// Workers manager property WorkersManager: TJSWorkersManager read FWorkersManager; /// Delete all started worker threads procedure ClearWorkers; published /// max amount of memory (in bytes) for a single SpiderMonkey instance // - this parameter will be set only at Engine start, i.e. it must be set // BEFORE any call to ThreadSafeEngine // - default is 32 MB property MaxPerEngineMemory: Cardinal read FMaxPerEngineMemory write SetMaxPerEngineMemory default 32*1024*1024; // Nursery size in bytes // - default is 16 MB property MaxNurseryBytes: Cardinal read FMaxNurseryBytes write SetMaxNurseryBytes default 16*1024*1024; /// maximum expected recursion depth for JavaScript functions // - to avoid out of memory situation in functions like // ! function f(){ f() }; // - default is 32, but you can specify some higher value property MaxRecursionDepth: Cardinal read FMaxRecursionDepth write FMaxRecursionDepth default 32; /// specify a maximum lifetime period after which JavaScript Engine will // be recreated, to avoid potential JavaScript memory leak (variables in global, // closures circle, etc.) // - 0 by default - mean no expire timeout // In case engine must never expire - set the NeverExpire property of engine manually property EngineExpireTimeOutMinutes: cardinal read GetEngineExpireTimeOutMinutes write SetEngineExpireTimeOutMinutes default 0; /// Path to synode core modules. // Not used in case core modules are embadded as resources (CORE_MODULES_IN_RES is defined) property CoreModulesPath: RawUTF8 read FCoreModulesPath; /// event triggered every time a new Engine is created // event trigered before OnDebuggerInit and OnNewEngine events // Result og this method is Engine's name for debug property OnGetName: TEngineNameEvent read FOnGetName write FOnGetName; /// event triggered every time a new Engine is created // event trigered before OnDebuggerInit and OnNewEngine events // Result og this method is Engine's web app root path property OnGetWebAppRootPath: TEngineNameEvent read FOnGetWebAppRootPath write FOnGetWebAppRootPath; /// event triggered every time a internal debugger process connected to Engine // - event trigered in debugger's compartment // - here your code can change the initial state of the debugger property OnDebuggerInit: TEngineEvent read FOnDebuggerInit write FOnDebuggerInit; /// event triggered every time a new Engine is created // - here your code can change the initial state of the Engine property OnNewEngine: TEngineEvent read FOnNewEngine write FOnNewEngine; /// event triggered every time a new remote debugger(Firefox) connect to Engine // - Warning!!! event trigered in debugger's communication thread(not thread of Engine) // so you cannot use Engine's Javascript in this method, but only Engine's properties property OnDebuggerConnected: TEngineEvent read FOnDebuggerConnected write FOnDebuggerConnected; /// event triggered every time a new dll module is loaded // - here you code can customize dll module or call some functions from dll property OnDllModuleLoaded: TDllModuleEvent read FOnDllModuleLoaded write FOnDllModuleLoaded; end; {$M-} function SyNodeBinding_modules(const Engine: TSMEngine; const bindingNamespaceName: SynUnicode): jsval; var /// define the TSynLog class used for logging for all our SynSM related units // - you may override it with TSQLLog, if available from mORMot.pas // - since not all exceptions are handled specificaly by this unit, you // may better use a common TSynLog class for the whole application or module SynSMLog: TSynLogClass=TSynLog; LONG_SCRIPT_EXECUTION: string = 'Script runs for too long. Terminating'; /// check is AFileName is relative path, and if true - transform it to absolute from ABaseDir // if ACheckResultInsideBase = true the perform check of result path is under ABaseDir. If not - return ''; // In any case will concatenates any relative path elements and replace '/' by '\' under Windows function RelToAbs(const ABaseDir, AFileName: TFileName; ACheckResultInsideBase: boolean = false): TFileName; implementation uses {$IFNDEF MSWINDOWS} Errors, SynFPCLinux, {$ENDIF} SyNodeRemoteDebugger, SyNodeBinding_fs {used by other core modules}, SyNodeBinding_const, SyNodeBinding_buffer, SyNodeBinding_util, SyNodeBinding_uv, synodebinding_os; const jsglobal_class: JSClass = (name: 'global'; flags: JSCLASS_GLOBAL_FLAGS or JSCLASS_HAS_PRIVATE or (255 shl JSCLASS_RESERVED_SLOTS_SHIFT); ); var GlobalSyNodeBindingHandlers: TRawUTF8List; /// handle errors from JavaScript. Just call DoProcessJSError of corresponding TSMEngine // to set TSMEngine error properties {$IFDEF SM52} procedure WarningReporter(cx: PJSContext; report: PJSErrorReport); cdecl; begin TSMEngine(cx.PrivateData).DoProcessJSError(report) end; {$ELSE} procedure ErrorReporter(cx: PJSContext; pErrMsg: PCChar; report: PJSErrorReport); cdecl; begin TSMEngine(cx.PrivateData).DoProcessJSError(pErrMsg, report) end; {$ENDIF} function OperationCallback(cx: PJSContext): Boolean; cdecl; begin Result := TSMEngine(cx.PrivateData).DoProcessOperationCallback; end; { TSMEngine } // do nothing here procedure ExternalStringFinalizer(fin: PJSStringFinalizer; chars: PCChar16); cdecl; begin {} end; function process_binding(cx: PJSContext; argc: uintN; var vp: JSArgRec): Boolean; cdecl; const USAGE = 'usage: binding(scope: String)'; var Eng: TSMEngine; in_argv: PjsvalVector; bindingNS: SynUnicode; res: jsval; handler: TSMProcessBindingHandler; FBindingObject: PJSRootedObject; begin Eng := TObject(cx.PrivateData) as TSMEngine; try in_argv := vp.argv; if (argc <> 1) or not (in_argv[0].isString) then raise ESMException.Create(USAGE); bindingNS := in_argv[0].asJSString.ToSynUnicode(cx); FBindingObject := cx.NewRootedObject(vp.calleObject); try if FBindingObject.ptr <> nil then begin res := FBindingObject.ptr.GetPropValue(cx, bindingNS); if res.isVoid then begin handler := Eng.Manager.GetBinding(SynUnicodeToUtf8(bindingNS)); if Assigned(handler) then begin res := handler(eng, bindingNS); if not res.isVoid then begin FBindingObject.ptr.DefineUCProperty(cx, bindingNS, res); end; end else raise ESMException.CreateFmt('Invalid binding namespace "%s"',[bindingNS]); end; end else res.SetNull; finally cx.FreeRootedObject(FBindingObject); end; vp.rval := res; Result := True; except on E: Exception do begin Result := False; vp.rval := JSVAL_VOID; JSError(cx, E); end; end; end; constructor TSMEngine.Create(aManager: TSMEngineManager); const gMaxStackSize = 128 * sizeof(size_t) * 1024; var {$IFDEF SM52} cOpts: PJSContextOptions; {$ELSE} rOpts: PJSRuntimeOptions; {$ENDIF} fpu: IUnknown; begin fpu := TSynFPUException.ForLibraryCode; if aManager = nil then raise ESMException.Create('No manager provided'); FCreatedAtTick := GetTickCount64; FManager := aManager; FEngineContentVersion := FManager.ContentVersion; {$IFDEF SM52} // TODO - solve problem of destroying parent engine before slave and uncomment a code below // this will save up to 20% of RAM - some internal structures of SM Engines will be reused // between threads // if aManager.grandParent <> nil then // fCx := PJSContext(nil).CreateNew(FManager.MaxPerEngineMemory, $01000000, aManager.grandParent.cx) // else fCx := PJSContext(nil).CreateNew(FManager.MaxPerEngineMemory, $01000000, nil); if fCx = nil then raise ESMException.Create('Create context: out of memory'); {$IFNDEF CPUX64} // This check does not always work correctly under 64-bit configurations. Need more investigation to understand the problem fCx.SetNativeStackQuota(gMaxStackSize); {$ENDIF} fCx.GCParameter[JSGC_MAX_BYTES] := FManager.MaxPerEngineMemory; // MPV as Mozilla recommend in https://bugzilla.mozilla.org/show_bug.cgi?id=950044 //TODO - USE JS_SetGCParametersBasedOnAvailableMemory for SM32 and override JSGC_MAX_MALLOC_BYTES if (FManager.MaxPerEngineMemory >= 512 * 1024 * 1024) then begin fCx.GCParameter[JSGC_MAX_MALLOC_BYTES] := 96 * 1024 * 1024; fCx.GCParameter[JSGC_SLICE_TIME_BUDGET] := 30; fCx.GCParameter[JSGC_HIGH_FREQUENCY_TIME_LIMIT] := 1000; fCx.GCParameter[JSGC_HIGH_FREQUENCY_HIGH_LIMIT] := 500; fCx.GCParameter[JSGC_HIGH_FREQUENCY_LOW_LIMIT] := 100; fCx.GCParameter[JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX] := 300; fCx.GCParameter[JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN] := 150; fCx.GCParameter[JSGC_LOW_FREQUENCY_HEAP_GROWTH] := 150; fCx.GCParameter[JSGC_HIGH_FREQUENCY_TIME_LIMIT] := 1500; fCx.GCParameter[JSGC_HIGH_FREQUENCY_TIME_LIMIT] := 1500; fCx.GCParameter[JSGC_HIGH_FREQUENCY_TIME_LIMIT] := 1500; fCx.GCParameter[JSGC_ALLOCATION_THRESHOLD] := 30; // fCx.GCParameter[JSGC_DECOMMIT_THRESHOLD] := 32; // fCx.GCParameter[JSGC_MODE] := uint32(JSGC_MODE_COMPARTMENT); fCx.GCParameter[JSGC_MODE] := uint32(JSGC_MODE_INCREMENTAL); end else begin fCx.GCParameter[JSGC_MAX_MALLOC_BYTES] := 6 * 1024 * 1024; //MPV in PREV realisation - FManager.MaxPerEngineMemory div 2; we got a memory overuse fCx.GCParameter[JSGC_MODE] := uint32(JSGC_MODE_INCREMENTAL); end; {$ELSE} frt := PJSRuntime(nil).New(FManager.MaxPerEngineMemory, $01000000, nil); if frt = nil then raise ESMException.Create('Create runtime: out of memory'); fRt.SetNativeStackQuota(gMaxStackSize); fRt.GCParameter[JSGC_MAX_BYTES] := FManager.MaxPerEngineMemory; // MPV as Mozilla recommend in https://bugzilla.mozilla.org/show_bug.cgi?id=950044 //TODO - USE JS_SetGCParametersBasedOnAvailableMemory for SM32 and override JSGC_MAX_MALLOC_BYTES if (FManager.MaxPerEngineMemory >= 512 * 1024 * 1024) then begin fRt.GCParameter[JSGC_MAX_MALLOC_BYTES] := 96 * 1024 * 1024; fRt.GCParameter[JSGC_SLICE_TIME_BUDGET] := 30; fRt.GCParameter[JSGC_HIGH_FREQUENCY_TIME_LIMIT] := 1000; fRt.GCParameter[JSGC_HIGH_FREQUENCY_HIGH_LIMIT] := 500; fRt.GCParameter[JSGC_HIGH_FREQUENCY_LOW_LIMIT] := 100; fRt.GCParameter[JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX] := 300; fRt.GCParameter[JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN] := 150; fRt.GCParameter[JSGC_LOW_FREQUENCY_HEAP_GROWTH] := 150; fRt.GCParameter[JSGC_HIGH_FREQUENCY_TIME_LIMIT] := 1500; fRt.GCParameter[JSGC_HIGH_FREQUENCY_TIME_LIMIT] := 1500; fRt.GCParameter[JSGC_HIGH_FREQUENCY_TIME_LIMIT] := 1500; fRt.GCParameter[JSGC_ALLOCATION_THRESHOLD] := 30; fRt.GCParameter[JSGC_DECOMMIT_THRESHOLD] := 32; fRt.GCParameter[JSGC_MODE] := uint32(JSGC_MODE_COMPARTMENT); end else begin fRt.GCParameter[JSGC_MAX_MALLOC_BYTES] := 6 * 1024 * 1024; //MPV in PREV realisation - FManager.MaxPerEngineMemory div 2; we got a memory overuse fRt.GCParameter[JSGC_MODE] := uint32(JSGC_MODE_INCREMENTAL); end; fCx := rt.NewContext(STACK_CHUNK_SIZE); if fCx = nil then raise ESMException.Create('JSContext create'); {$ENDIF} {$IFDEF SM52} cOpts := cx.Options; cOpts.Baseline := True; cOpts.Ion := True; cOpts.AsmJS := True; {$ELSE} // You must set jsoBaseLine,jsoTypeInference,jsoIon for the enabling ION // ION is disabled without these options rOpts := rt.Options; rOpts.Baseline := True; rOpts.Ion := True; rOpts.AsmJS := True; {$ENDIF} fStringFinalizer.finalize := ExternalStringFinalizer; cx.PrivateData := self; {$IFDEF SM52} // not working for errors // TODO: implement log warnings if needed // fCx.WarningReporter := WarningReporter; {$ELSE} fRt.ErrorReporter := ErrorReporter; {$ENDIF} FGlobalObject := cx.NewRootedObject(cx.NewGlobalObject(@jsglobal_class)); if FGlobalObject.ptr = nil then raise ESMException.Create('Create global object'); fcomp := cx.EnterCompartment(FGlobalObject.ptr); if not cx.InitStandardClasses(FGlobalObject.ptr) then raise ESMException.Create('InitStandardClasses failure'); if not cx.InitCTypesClass(FGlobalObject.ptr) then raise ESMException.Create('InitCTypesClass failure'); // if not cx.InitReflectParse(FGlobalObject.ptr) then // raise ESMException.Create('InitReflectParse failure'); if not cx.InitModuleClasses(FGlobalObject.ptr) then raise ESMException.Create('InitModuleClasses failure'); FGlobalObject.ptr.DefineProperty(cx, 'global', FGlobalObject.ptr.ToJSValue, JSPROP_ENUMERATE or JSPROP_PERMANENT or JSPROP_READONLY, nil, nil); fTimeoutValue := -1; if not InitWatchdog then raise ESMException.Create('InitWatchDog failure'); {$IFDEF SM52} fcx.AddInterruptCallback(OperationCallback); {$ELSE} fRt.InterruptCallback := OperationCallback; {$ENDIF} FDllModulesUnInitProcList := TList.Create; DefineProcessBinding; DefineNodeProcess; DefineModuleLoader; EvaluateModule('synode.js'); FGlobalTimerLoopFunc := cx.NewRootedValue(FGlobalObject.ptr.GetPropValue(cx, '_timerLoop')); FGlobalObjectDbg := cx.NewRootedObject(cx.NewGlobalObject(@jsglobal_class)); end; procedure TSMEngine.defineEnum(ti: PTypeInfo; aObj: PJSRootedObject); begin SyNodeProto.defineEnum(cx, ti, aObj); end; procedure TSMEngine.DefineModuleLoader; var ModuleLoaderPath: TFileName; script: SynUnicode; rval: jsval; begin {$IFDEF CORE_MODULES_IN_RES} EvaluateRes('MODULELOADER.JS', rval); {$ELSE} ModuleLoaderPath := RelToAbs(UTF8ToString(FManager.coreModulesPath) , 'ModuleLoader.js'); script := AnyTextFileToSynUnicode(ModuleLoaderPath); if script = '' then raise ESMException.Create('File not found ' + ModuleLoaderPath); Evaluate(script, 'ModuleLoader.js', 1, rval); {$ENDIF} end; procedure TSMEngine.DefineNodeProcess; var process: PJSRootedObject; env: PJSRootedObject; FStartupPath: TFileName; {$IFDEF FPC} I, Cnt: Integer; EnvStr: AnsiString; Parts: array of AnsiString; {$ELSE} L: PtrInt; EnvBlock, P, pEq: PChar; strName, strVal: SynUnicode; {$ENDIF} begin process := cx.NewRootedObject(FGlobalObject.ptr.GetPropValue(cx, 'process').asObject); env := cx.NewRootedObject(cx.NewObject(nil)); try process.ptr.defineProperty(cx, 'binPath', cx.NewJSString(ExeVersion.ProgramFilePath).ToJSVal, JSPROP_ENUMERATE or JSPROP_PERMANENT or JSPROP_READONLY); process.ptr.defineProperty(cx, 'execPath', cx.NewJSString(ExeVersion.ProgramFileName).ToJSVal, JSPROP_ENUMERATE or JSPROP_PERMANENT or JSPROP_READONLY); FStartupPath := GetCurrentDir + {$IFDEF FPC}DirectorySeparator{$ELSE}'\'{$ENDIF}; if FStartupPath = '' then FStartupPath := ExeVersion.ProgramFilePath; process.ptr.defineProperty(cx, 'startupPath', cx.NewJSString(StringToSynUnicode(FStartupPath)).ToJSVal, JSPROP_ENUMERATE or JSPROP_PERMANENT or JSPROP_READONLY); {$IFDEF FPC} Cnt := GetEnvironmentVariableCount; for I := 1 to Cnt do begin EnvStr := GetEnvironmentString(I); Parts := EnvStr.Split('=', TStringSplitOptions.ExcludeEmpty); if (Length(Parts) = 2) and (Trim(Parts[0]) <> '') then begin env.ptr.DefineUCProperty(cx, StringToSynUnicode(Trim(Parts[0])), cx.NewJSString(Trim(Parts[1])).ToJSVal, JSPROP_ENUMERATE or JSPROP_PERMANENT or JSPROP_READONLY, nil, nil); end end; {$ELSE} EnvBlock := GetEnvironmentStrings; try P := EnvBlock; while P^<>#0 do begin {$ifdef UNICODE} L := StrLenW(P); {$else} L := StrLen(P); {$endif} if (L>0) and (P^<>'=') then begin pEq := StrScan(P, '='); if pEq <> nil then begin SetString(strName, p, pEq-P); SetString(strVal, pEq+1, {$ifdef UNICODE}StrLenW{$else}StrLen{$endif}(pEq+1)); env.ptr.DefineUCProperty(cx, Pointer(strName), Length(strName), cx.NewJSString(strVal).ToJSVal, JSPROP_ENUMERATE or JSPROP_PERMANENT or JSPROP_READONLY, nil, nil); end; end; inc(P,L+1); end; finally FreeEnvironmentStrings(EnvBlock); end; {$ENDIF} process.ptr.defineProperty(cx, 'env', env.ptr.ToJSValue, JSPROP_ENUMERATE or JSPROP_PERMANENT or JSPROP_READONLY); {$IFDEF MSWINDOWS} process.ptr.defineProperty(cx, 'platform', cx.NewJSString('win32').ToJSVal); {$ELSE} process.ptr.defineProperty(cx, 'platform', cx.NewJSString('nix').ToJSVal); {$ENDIF} {$IFDEF CPU64} process.ptr.defineProperty(cx, 'arch', cx.NewJSString('x64').ToJSVal); {$ELSE} process.ptr.defineProperty(cx, 'arch', cx.NewJSString('x32').ToJSVal); {$ENDIF} with ExeVersion.Version do process.ptr.DefineProperty(cx, 'version', cx.NewJSString('v' + IntToString(Major)+'.'+IntToString(Minor) + '.' + IntToString(Release)).ToJSVal); finally cx.FreeRootedObject(env); cx.FreeRootedObject(process); end; end; procedure TSMEngine.DefineProcessBinding; var process: PJSRootedObject; global: PJSRootedObject; begin process := cx.NewRootedObject(cx.NewObject(nil)); global := cx.NewRootedObject(cx.CurrentGlobalOrNull); try process.ptr.DefineFunction(cx, 'binding', process_binding, 1); global.ptr.DefineProperty(cx, 'process', process.ptr.ToJSValue, JSPROP_ENUMERATE or JSPROP_PERMANENT or JSPROP_READONLY, nil, nil); finally cx.FreeRootedObject(global); cx.FreeRootedObject(process); end; end; destructor TSMEngine.Destroy; var unInitProc: TDllModuleUnInitProc; process: PJSRootedObject; procExitCodeVal: jsval; begin try process := cx.NewRootedObject(GlobalObject.ptr.GetPropValue(cx,'process').asObject); try process.ptr.SetProperty(cx, '_exiting', SimpleVariantToJSval(cx, true)); if process.ptr.HasProperty(cx, 'emit') then CallObjectFunction(process, 'emit', [cx.NewJSString('exit').ToJSVal]) else raise Exception.Create('`process` initialized incorrectly (dont have `emit` method)'); procExitCodeVal := process.ptr.GetPropValue(cx, 'exitCode'); if procExitCodeVal.isInteger then ExitCode := procExitCodeVal.asInteger; finally cx.FreeRootedObject(process); end; except on E: Exception do begin ExitCode := 1; end; end; if Manager.FRemoteDebuggerThread <> nil then begin TSMRemoteDebuggerThread(Manager.FRemoteDebuggerThread).stopDebugCurrentThread(Self); end; while FDllModulesUnInitProcList.Count > 0 do begin unInitProc := FDllModulesUnInitProcList[FDllModulesUnInitProcList.Count - 1]; FDllModulesUnInitProcList.Delete(FDllModulesUnInitProcList.Count - 1); unInitProc(); end; FDllModulesUnInitProcList.Free; inherited Destroy; if FGlobalTimerLoopFunc <> nil then cx.FreeRootedValue(FGlobalTimerLoopFunc); if FGlobalObjectDbg <> nil then cx.FreeRootedObject(FGlobalObjectDbg); if FGlobalObject <> nil then cx.FreeRootedObject(FGlobalObject); with TSynFPUException.ForLibraryCode do begin cx.LeaveCompartment(comp); if FThreadID=GetCurrentThreadId then cx^.Destroy; // SM 45 expects the context to be released in the same thread KillWatchdog; {$IFNDEF SM52} if FThreadID=GetCurrentThreadId then rt^.Destroy; {$ENDIF} end; end; {$IFDEF SM52} procedure TSMEngine.DoProcessJSError(report: PJSErrorReport); {$ELSE} procedure TSMEngine.DoProcessJSError(errMsg: PCChar; report: PJSErrorReport); {$ENDIF} var exc: jsval; exObj: PJSRootedObject; begin if {$IFDEF SM52}(report = nil) or {$ENDIF}(report.flags = JSREPORT_WARNING) then Exit; FErrorExist := True; if report^.filename = nil then FLastErrorFileName := '<>' else FLastErrorFileName := CurrentAnsiConvert.AnsiBufferToRawUTF8( report^.filename,StrLen(pointer(report^.filename))); FLastErrorLine := report^.lineno; FLastErrorNum := report^.errorNumber; {$IFDEF SM52} FLastErrorMsg := Utf8ToString(FormatUTF8('%', [report^.message_])); {$ELSE} if report^.ucmessage=nil then FLastErrorMsg := Utf8ToString(FormatUTF8('%', [errMsg])) else SetString(FLastErrorMsg, PWideChar(report^.ucmessage), StrLenW(PWideChar(report^.ucmessage))); {$ENDIF} FLastErrorStackTrace := ''; if ( cx.GetPendingException(exc)) then begin if exc.isObject then begin exObj := cx.NewRootedObject(exc.asObject); exObj.ptr.GetProperty(cx, 'stack', exc); if (not exc.isVoid) and (exc.isString) then FLastErrorStackTrace := exc.asJSString.ToSynUnicode(cx); cx.FreeRootedObject(exObj); end; end; (* // This situation is possible when application are run from the IDE // and stop on the breakpoint. // When we evaluate some js script with errors(like call JS_Stringify // for global object) this function will be called. // If breakpoint is set between ClearLastError and CheckJSError we get // FErrorExist value is equivalent true, but script have no error if DebugHook=0 then try CheckJSError(JS_FALSE); finally FErrorExist := false; end; *) end; procedure TSMEngine.CheckJSError(res: Boolean); var exc: jsval; {$IFDEF SM52} excObj: PJSRootedObject; {$ENDIF} rep: PJSErrorReport; R: RawUTF8; begin {$IFDEF SM52} if JS_IsExceptionPending(fCx) and JS_GetPendingException(cx, exc) then begin if exc.isObject then begin excObj := cx.NewRootedObject(exc.asObject); try rep := JS_ErrorFromException(cx, excObj.ptr); if (rep <> nil) and (rep.flags = JSREPORT_WARNING) then exit; // Error inheritance (assert.AssertionError for example) // will return an nil as a rep, so we need to examine a exc object FErrorExist := True; excObj.ptr.GetProperty(cx, 'fileName', exc); if (not exc.isVoid) and (exc.isString) then FLastErrorFileName := exc.asJSString.ToUTF8(fCx); excObj.ptr.GetProperty(cx, 'lineNumber', exc); if (not exc.isVoid) then begin if (exc.isString) then begin // error line is in format line:char (123:16) R := exc.asJSString.ToUTF8(fCx); FLastErrorLine := GetInteger(pointer(R)); end else if (exc.isInteger) then FLastErrorLine := exc.asInteger end; excObj.ptr.GetProperty(cx, 'message', exc); if (not exc.isVoid) and (exc.isString) then FLastErrorMsg := exc.asJSString.ToString(fCx); excObj.ptr.GetProperty(cx, 'stack', exc); if (not exc.isVoid) and (exc.isString) then FLastErrorStackTrace := exc.asJSString.ToSynUnicode(fCx); if (rep <> nil) then FLastErrorNum := rep^.errorNumber else begin excObj.ptr.GetProperty(cx, 'errorNumber', exc); if (not exc.isVoid) and (exc.isInteger) then FLastErrorNum := exc.asInteger else FLastErrorNum := 0; end; finally cx.FreeRootedObject(excObj); end; end else if exc.isString then begin FErrorExist := True; FLastErrorFileName := '<betterToThrowErrorInsteadOfPlainValue>'; FLastErrorMsg := exc.asJSString.ToString(fCx); FLastErrorStackTrace := ''; FLastErrorNum := 0; end else begin FErrorExist := True; FLastErrorFileName := '<betterToThrowError>'; FLastErrorMsg := 'code throw a plain value instead of Error (or error like) object'; FLastErrorStackTrace := ''; FLastErrorNum := 0; end; raise ESMException.CreateWithTrace(FLastErrorFileName, FLastErrorNum, FLastErrorLine, FLastErrorMsg, FLastErrorStackTrace); end; {$ENDIF} if (FTimeOutAborted and (FLastErrorMsg <> '')) or FErrorExist then begin raise ESMException.CreateWithTrace(FLastErrorFileName, FLastErrorNum, FLastErrorLine, FLastErrorMsg, FLastErrorStackTrace); end; if not res and not FTimeOutAborted then begin raise ESMException.CreateWithTrace(FLastErrorFileName, 0, FLastErrorLine, 'Error compiling script', ''); end; end; procedure TSMEngine.ClearLastError; begin fcx.ClearPendingException; FErrorExist := False; FTimeOutAborted := False; fTimedOut := False; end; procedure TSMEngine.GarbageCollect; begin {$IFDEF SM52} cx.GC; {$ELSE} rt.GC; {$ENDIF} end; procedure TSMEngine.MaybeGarbageCollect; begin cx.MaybeGC; end; { TSMEngineManager } class procedure TSMEngineManager.RegisterBinding(const Name: RawUTF8; const handler: TSMProcessBindingHandler); begin if GlobalSyNodeBindingHandlers = nil then GlobalSyNodeBindingHandlers := TRawUTF8List.Create(false); GlobalSyNodeBindingHandlers.AddObject(Name, TObject(@handler)); end; function TSMEngineManager.GetBinding(const Name: RawUTF8): TSMProcessBindingHandler; var obj: TObject; handler: TSMProcessBindingHandler absolute obj; begin obj := GlobalSyNodeBindingHandlers.GetObjectFrom(Name); result := handler; end; function TSMEngineManager.GetEngineExpireTimeOutMinutes: cardinal; begin result := fEngineExpireTimeOutTicks div 60000; end; procedure TSMEngineManager.ClearWorkers; begin FWorkersManager.Free; FWorkersManager := TJSWorkersManager.Create; end; constructor TSMEngineManager.Create(const aCoreModulesPath: RawUTF8; aEngineClass: TSMEngineClass = nil); begin FMaxPerEngineMemory := 32*1024*1024; FMaxRecursionDepth := 32; FEnginePool := TSynObjectListLocked.Create(true); if aEngineClass <> nil then FEngineClass := aEngineClass else FEngineClass := TSMEngine; {$ifdef ISDELPHIXE2} FRttiCx := TRttiContext.Create(); {$endif} FDllModules := TRawUTF8List.Create(); FCoreModulesPath := aCoreModulesPath; FWorkersManager := TJSWorkersManager.Create; end; procedure TSMEngineManager.SetMaxPerEngineMemory(AMaxMem: Cardinal); begin if aMaxMem<STACK_CHUNK_SIZE*MaxRecursionDepth then raise ESMException.CreateFmt( 'Per engine memory must be >= STACK_CHUNK_SIZE*%d, i.e. %d', [MaxRecursionDepth,STACK_CHUNK_SIZE*MaxRecursionDepth]); FMaxPerEngineMemory := AMaxMem; end; procedure TSMEngineManager.SetEngineExpireTimeOutMinutes(const minutes: cardinal); begin fEngineExpireTimeOutTicks := minutes * 60000; end; procedure TSMEngineManager.SetMaxNurseryBytes(AMaxNurseryBytes: Cardinal); begin FMaxNurseryBytes := AMaxNurseryBytes; end; function TSMEngineManager.ThreadEngineIndex(ThreadID: TThreadID): Integer; begin if self <> nil then for result := 0 to FEnginePool.Count-1 do if TSMEngine(FEnginePool.List[result]).fThreadID=ThreadID then exit; result := -1; end; destructor TSMEngineManager.Destroy; var dllModule: PDllModuleRec; i: Integer; begin FWorkersManager.Free; FWorkersManager := nil; stopDebugger; if FEnginePool.Count>0 then raise ESMException.Create('There are unreleased engines'); FEnginePool.Free; for I := 0 to FDllModules.Count - 1 do begin dllModule := PDllModuleRec(FDllModules.Objects[i]); Dispose(dllModule); end; FDllModules.Free; inherited; {$ifdef ISDELPHIXE2} FRttiCx.Free; {$endif} end; procedure TSMEngineManager.DoOnNewEngine(const Engine: TSMEngine); begin if Assigned(FOnNewEngine) then begin Engine.cx.BeginRequest(); try FOnNewEngine(Engine); finally Engine.cx.EndRequest; end; end; end; function TSMEngineManager.EngineForThread(ThreadID: TThreadID): TSMEngine; var i: integer; begin FEnginePool.Safe.Lock; try i := ThreadEngineIndex(ThreadID); if i < 0 then result := nil else result := FEnginePool.List[i]; finally FEnginePool.Safe.UnLock; end; end; function TSMEngineManager.evalDllModule(cx: PJSContext; module: PJSRootedObject; const filename: RawUTF8): TDllModuleUnInitProc; var dirname: TFileName; exports_V: jsval; exports_: PJSRootedObject; require_V: jsval; require: PJSRootedObject; __filename: PWideChar; __dirname: PWideChar; fHandle: HMODULE; ModuleRec: PDllModuleRec; const EXPORTS_NAME: AnsiString = 'exports'; REQUIRE_NAME: AnsiString = 'require'; INIT_PROC_NAME = 'InitPlugin'; UNINIT_PROC_NAME = 'UnInitPlugin'; begin Lock; try cx.BeginRequest; try dirname := ExtractFilePath(UTF8ToString(filename)) ; ModuleRec := PDllModuleRec(FDllModules.GetObjectFrom(filename)); if ModuleRec = nil then begin fHandle := {$IFDEF FPC}dynlibs.{$ENDIF}SafeLoadLibrary(UTF8ToString(filename)); if fHandle=0 then raise ESMException.CreateFmt('Unable to load %s (%s)', [filename, {$ifdef FPC}GetLoadErrorStr{$else}SysErrorMessage(GetLastError){$endif}]); new(ModuleRec); ModuleRec.init := GetProcAddress(fHandle, INIT_PROC_NAME); if not Assigned(ModuleRec.init) then begin FreeLibrary(fHandle); Dispose(ModuleRec); raise ESMException.CreateFmt('Invalid %s: missing %s',[filename, INIT_PROC_NAME]); end; if Assigned(OnDllModuleLoaded) then OnDllModuleLoaded(fHandle); ModuleRec.unInit := GetProcAddress(fHandle, UNINIT_PROC_NAME); FDllModules.AddObject(filename, TObject(ModuleRec)); end; __filename := Pointer(filename); __dirname := Pointer(dirname); if module.ptr.GetProperty(cx, pointer(EXPORTS_NAME), exports_V) then exports_ := cx.NewRootedObject(exports_V.asObject) else exports_ := cx.NewRootedObject(nil); try if module.ptr.GetProperty(cx, pointer(REQUIRE_NAME), require_V) then require := cx.NewRootedObject(require_V.asObject) else require := cx.NewRootedObject(nil); try if not ModuleRec.init(cx, exports_, require, module, __filename, __dirname) then begin try RaiseLastOSError; except on E: Exception do begin E.Message := format('require %s failed:',[ ExtractFileName(UTF8ToString(filename))])+E.Message; raise; end; end; end; finally cx.FreeRootedObject(require); end; finally cx.FreeRootedObject(exports_); end; //TODO: Store all evaled libs and call UnInit on destroy engine finally cx.EndRequest; end; finally UnLock; end; Result := ModuleRec.unInit; end; function TSMEngineManager.getPauseDebuggerOnFirstStep: boolean; begin if FRemoteDebuggerThread<> nil then begin result := TSMRemoteDebuggerThread(FRemoteDebuggerThread).NeedPauseOnFirstStep; end else result := false; end; function TSMEngineManager.ThreadSafeEngine(pThreadData: pointer): TSMEngine; var i: integer; ThreadID: TThreadID; begin FEnginePool.Safe.Lock; try ThreadID := GetCurrentThreadId; i := ThreadEngineIndex(ThreadID); // inlined CurrentThreadEngine if i<0 then result := nil else begin result := FEnginePool.List[i]; if (pThreadData) <> nil then result.SetThreadData(pThreadData); end; if result<>nil then begin // memorize a thread data for possible engine recreation if pThreadData = nil then pThreadData := result.ThreadData; if result.EngineContentVersion=Self.ContentVersion then begin if Result.NeverExpire or (FEngineExpireTimeOutTicks = 0) or (GetTickCount64 - Result.fCreatedAtTick < FEngineExpireTimeOutTicks ) then // return existing Engine corresponding to the current thread exit else begin // content expired -> force recreate thread Engine {$ifdef SM_DEBUG} SynSMLog.Add.Log(sllDebug, 'Drop SpiderMonkey Engine for thread % - timeout expired', ThreadID); {$endif} ReleaseEngineForThread(ThreadID); end; end else begin // content version changed -> force recreate thread Engine {$ifdef SM_DEBUG} SynSMLog.Add.Log(sllDebug, 'Drop SpiderMonkey Engine for thread % - modification found', ThreadID); {$endif} ReleaseEngineForThread(ThreadID); end; end; // here result=nil or to be ignored (just dropped) {$ifdef SM_DEBUG} SynSMLog.Add.Log(sllDebug, 'Create new JavaScript Engine for thread %', ThreadID); {$endif} Result := FEngineClass.Create(Self); if grandParent = nil then grandParent := Result; if (pThreadData <> nil) then Result.SetThreadData(pThreadData); if WorkersManager.curThreadIsWorker then Result.fnameForDebug := WorkersManager.getCurrentWorkerThreadName else if Assigned(OnGetName) then Result.fnameForDebug := OnGetName(Result); if Assigned(OnGetWebAppRootPath) then Result.fWebAppRootDir := OnGetWebAppRootPath(Result) else Result.fWebAppRootDir := StringToUTF8(ExeVersion.ProgramFilePath); result.fThreadID := ThreadID; FEnginePool.Add(result); finally FEnginePool.Safe.UnLock; end; if FRemoteDebuggerThread <> nil then TSMRemoteDebuggerThread(FRemoteDebuggerThread).startDebugCurrentThread(result); if WorkersManager.curThreadIsWorker then Result.doInteruptInOwnThread := WorkersManager.DoInteruptInOwnThreadhandlerForCurThread; DoOnNewEngine(Result); end; procedure TSMEngineManager.Lock; begin FEnginePool.Safe.Lock; end; procedure TSMEngineManager.UnLock; begin FEnginePool.Safe.UnLock; end; procedure TSMEngineManager.ReleaseEngineForThread(aThreadID: TThreadID); var i: integer; begin FEnginePool.Safe.Lock; try i := ThreadEngineIndex(aThreadID); if i>=0 then begin (TObject(FEnginePool[i]) as TSMEngine).GarbageCollect; FEnginePool.Delete(i); end; finally FEnginePool.Safe.UnLock; end; end; procedure TSMEngineManager.ReleaseCurrentThreadEngine; begin ReleaseEngineForThread(GetCurrentThreadId); end; function TSMEngineManager.CurrentThreadEngine: TSMEngine; var i: integer; begin FEnginePool.Safe.Lock; try i := ThreadEngineIndex(GetCurrentThreadId); if i < 0 then result := nil else result := FEnginePool.List[i]; finally FEnginePool.Safe.UnLock; end; end; procedure TSMEngineManager.debuggerLog(const Text: RawUTF8); begin if FRemoteDebuggerThread<> nil then begin TSMRemoteDebuggerThread(FRemoteDebuggerThread).doLog(Text); end; end; procedure TSMEngineManager.setPauseDebuggerOnFirstStep(const Value: boolean); begin if FRemoteDebuggerThread<> nil then begin TSMRemoteDebuggerThread(FRemoteDebuggerThread).NeedPauseOnFirstStep := Value; end end; procedure TSMEngineManager.startDebugger(const port: SockString = '6000'); begin FRemoteDebuggerThread := TSMRemoteDebuggerThread.Create(self, port); inc(FContentVersion); end; procedure TSMEngineManager.stopDebugger; begin if FRemoteDebuggerThread <> nil then begin TSMRemoteDebuggerThread(FRemoteDebuggerThread).SetTerminated; FRemoteDebuggerThread := nil; end; end; function StringReplaceChars(const Source: String; OldChar, NewChar: Char): String; var i,j,n: integer; begin if (OldChar<>NewChar) and (Source<>'') then begin n := length(Source); for i := 0 to n-1 do if PChar(pointer(Source))[i]=OldChar then begin SetString(result,PChar(pointer(Source)),n); for j := i to n-1 do if PChar(pointer(result))[j]=OldChar then PChar(pointer(result))[j] := NewChar; exit; end; end; result := Source; end; function RelToAbs(const ABaseDir, AFileName: TFileName; ACheckResultInsideBase: boolean = false): TFileName; var {$IFNDEF FPC} aBase, aTail: PChar; localBase, localTail: TFileName; {$ELSE} aBase: TFileName; {$ENDIF} begin {$IFNDEF FPC} if AFileName <> '' then begin if PathIsRelative(PChar(AFileName)) then begin localTail := AFileName; localBase := ABaseDir; end else begin localTail := ''; localBase := AFileName; end; end else begin localTail := ''; localBase := ABaseDir; end; localBase := StringReplaceChars(localBase, '/', '\');; localTail := StringReplaceChars(localTail, '/', '\'); aBase := PChar(LocalBase); aTail := PChar(localTail); SetLength(Result, MAX_PATH); // PathCombine do not understand '/', so we raplace '/' -> '\' above if PathCombine(@Result[1], aBase, aTail) = nil then Result := '' else SetLength(Result, {$ifdef UNICODE}StrLenW{$else}StrLen{$endif}(@Result[1])); if ACheckResultInsideBase and ((length(Result) < length(ABaseDir)) or (length(ABaseDir)=0) or (StrLIComp(PChar(@Result[1]), @localBase[1], length(localBase)) <> 0)) then Result := '' {$ELSE} { aBase := GetForcedPathDelims(ABaseDir); if AFileName <> '' then begin aTail := GetForcedPathDelims(AFileName); if FilenameIsAbsolute(aTail) then begin localTail := ''; localBase := aBase; end else begin localTail := aTail; localBase := aBase; end; end else begin localTail := ''; localBase := aBase; end; Result := CreateAbsolutePath(localTail, localBase); } aBase := ExpandFileName(ABaseDir); Result := ExpandFileNameUTF8(AFileName, aBase); if ACheckResultInsideBase and ((Length(Result) < Length(aBase)) or (Length(aBase)=0) or (StrCompL(PUtf8Char(Result), PUtf8Char(aBase), length(aBase), 0) <> 0)) then //{ not Result.StartsWith(aBase, false))} not compiled in fpc 3.1.1 Result := '' {$ENDIF} end; function TSMEngine.DoProcessOperationCallback: Boolean; begin Result := not fTimedOut; end; // Remove #13 characters from script(change it to #32) // Spidermonkey debugger crashes when `...`(new ES6 strings) contains #13#10 procedure remChar13FromScript(const Script: SynUnicode); {$IFDEF HASINLINE}inline;{$ENDIF} var c: PWideChar; i: Integer; begin c := pointer(script); for I := 1 to Length(script) do begin if (c^ = #13) then c^ := ' '; Inc(c); end; end; // get a pointer to a file embadded as a UNICODE resource and it length in chars function getResCharsAndLength(const ResName: string; out pRes: pointer; out resLength: LongWord): boolean; var HResInfo: THandle; HGlobal: THandle; Instance: THandle; begin Instance := HInstance; HResInfo := FindResource(Instance,PChar(ResName),PChar(10)); //RC_DATA if HResInfo=0 then exit(false); HGlobal := LoadResource(Instance,HResInfo); if HGlobal=0 then exit(false); pRes := LockResource(HGlobal); resLength := SizeofResource(Instance,HResInfo) div 2; Result := resLength > 0; end; procedure TSMEngine.EvaluateRes(const ResName: string; out result: jsval); var r: Boolean; opts: PJSCompileOptions; isFirst: Boolean; pScript: pointer; scriptLength: LongWord; rval: jsval; begin with TSynFPUException.ForLibraryCode do begin ClearLastError; ScheduleWatchdog(fTimeoutValue); isFirst := not cx.IsRunning; opts := cx.NewCompileOptions; opts.filename := Pointer(ResName); if not getResCharsAndLength(ResName, pScript, scriptLength) then raise ESMException.CreateUTF8('Resource "%" not found', [ResName]); r := cx.EvaluateUCScript(opts, pScript, scriptLength, result); cx.FreeCompileOptions(opts); if r and isFirst and GlobalObject.ptr.HasProperty(cx, '_timerLoop') then r := GlobalObject.ptr.CallFunctionName(cx, '_timerLoop', 0, nil, rval); if not r then r := false; ScheduleWatchdog(-1); CheckJSError(r); end; end; procedure TSMEngine.Evaluate(const script: SynUnicode; const scriptName: RawUTF8; lineNo: Cardinal; out result: jsval); var r: Boolean; opts: PJSCompileOptions; isFirst: Boolean; rval: jsval; begin with TSynFPUException.ForLibraryCode do begin ClearLastError; ScheduleWatchdog(fTimeoutValue); isFirst := not cx.IsRunning; opts := cx.NewCompileOptions; opts.filename := Pointer(scriptName); remChar13FromScript(script); r := cx.EvaluateUCScript( opts, pointer(script), length(script), result); cx.FreeCompileOptions(opts); if r and isFirst and GlobalObject.ptr.HasProperty(cx, '_timerLoop') then r := GlobalObject.ptr.CallFunctionName(cx, '_timerLoop', 0, nil, rval); if not r then r := false; ScheduleWatchdog(-1); CheckJSError(r); end; end; procedure TSMEngine.Evaluate(const script: SynUnicode; const scriptName: RawUTF8; lineNo: Cardinal); var jsvalue: jsval; begin Evaluate(script, scriptName, lineNo, jsvalue); end; function TSMEngine.EvaluateModule(const scriptName: RawUTF8): jsval; var global: PJSRootedObject; reflect: jsval; moduleLoader: PJSRootedObject; begin global := cx.NewRootedObject(cx.CurrentGlobalOrNull); reflect := global.ptr.GetPropValue(cx, 'Reflect'); moduleLoader := cx.NewRootedObject(reflect.asObject.GetPropValue(cx, 'Loader').asObject); try result := CallObjectFunction(moduleLoader, 'import', [cx.NewJSString(scriptName).ToJSVal]) finally cx.FreeRootedObject(moduleLoader); cx.FreeRootedObject(global); end; end; function TSMEngine.CallObjectFunctionVal(obj: PJSRootedObject; const funcVal: PJSRootedValue; const args: array of jsval): jsval; var r: Boolean; isFirst: Boolean; rval: jsval; global: PJSRootedObject; begin with TSynFPUException.ForLibraryCode do begin ClearLastError; ScheduleWatchdog(fTimeoutValue); isFirst := not cx.IsRunning; r := obj.ptr.CallFunctionValue(cx, funcVal.ptr, high(args) + 1, @args[0], Result); if r and isFirst then begin global := cx.NewRootedObject(cx.CurrentGlobalOrNull); try if FGlobalTimerLoopFunc <> nil then r := global.ptr.CallFunctionValue(cx, FGlobalTimerLoopFunc.ptr, 0, nil, rval); finally cx.FreeRootedObject(global); end; end; ScheduleWatchdog(-1); CheckJSError(r); end; end; function TSMEngine.CallObjectFunction(obj: PJSRootedObject; funcName: PCChar; const args: array of jsval): jsval; var r: Boolean; isFirst: Boolean; rval: jsval; global: PJSRootedObject; begin with TSynFPUException.ForLibraryCode do begin ClearLastError; ScheduleWatchdog(fTimeoutValue); isFirst := not cx.IsRunning; r := obj.ptr.CallFunctionName(cx, funcName, high(args) + 1, @args[0], Result); if r and isFirst then begin global := cx.NewRootedObject(cx.CurrentGlobalOrNull); try if FGlobalTimerLoopFunc <> nil then r := global.ptr.CallFunctionValue(cx, FGlobalTimerLoopFunc.ptr, 0, nil, rval); finally cx.FreeRootedObject(global); end; end; ScheduleWatchdog(-1); CheckJSError(r); end; end; procedure TSMEngine.CancelExecution(AWithException: boolean = true); begin fTimedOut := True; FTimeOutAborted := True; if AWithException then begin FErrorExist := True; FLastErrorFileName := '<>'; FLastErrorLine := 0; FLastErrorNum := 0; FLastErrorMsg := LONG_SCRIPT_EXECUTION; end; {$IFDEF SM52} cx.RequestInterruptCallback; {$ELSE} rt.RequestInterruptCallback; {$ENDIF} end; function TSMEngine.InitWatchdog: boolean; begin Assert(not Assigned(fWatchdogThread)); fWatchdogLock := PR_NewLock; if Assigned(fWatchdogLock) then begin fWatchdogWakeup := PR_NewCondVar(fWatchdogLock); if Assigned(fWatchdogWakeup) then begin fSleepWakeup := PR_NewCondVar(fWatchdogLock); if Assigned(fSleepWakeup) then begin result := True; exit; end; PR_DestroyCondVar(fWatchdogWakeup); end; end; result := False; end; procedure TSMEngine.KillWatchdog; var thread: PRThread; begin PR_Lock(fWatchdogLock); thread := fWatchdogThread; if Assigned(thread) then begin // The watchdog thread is running, tell it to terminate waking it up // if necessary. fWatchdogThread := nil; PR_NotifyCondVar(fWatchdogWakeup); end; PR_Unlock(fWatchdogLock); if Assigned(thread) then PR_JoinThread(thread); PR_DestroyCondVar(fSleepWakeup); PR_DestroyCondVar(fWatchdogWakeup); PR_DestroyLock(fWatchdogLock); end; function IsBefore( t1, t2: int64): Boolean; begin Result := int32(t1 - t2) < 0; end; procedure WatchdogMain(arg: pointer); cdecl; var eng: TSMEngine; {$IFDEF SM52} cx: PJSContext; {$ELSE} rt: PJSRuntime; {$ENDIF} now_: int64; sleepDuration: PRIntervalTime; status: PRStatus; begin PR_SetCurrentThreadName('JS Watchdog'); eng := TSMEngine(arg); {$IFDEF SM52} cx := eng.cx; {$ELSE} rt := eng.rt; {$ENDIF} PR_Lock(eng.fWatchdogLock); while Assigned(eng.fWatchdogThread) do begin {$IFDEF SM52} now_ := cx.NowMs; {$ELSE} now_ := rt.NowMs; {$ENDIF} if (eng.fWatchdogHasTimeout and not IsBefore(now_, eng.fWatchdogTimeout)) then begin // The timeout has just expired. Trigger the operation callback outside the lock eng.fWatchdogHasTimeout := false; PR_Unlock(eng.fWatchdogLock); eng.CancelExecution; PR_Lock(eng.fWatchdogLock); // Wake up any threads doing sleep PR_NotifyAllCondVar(eng.fSleepWakeup); end else begin if (eng.fWatchdogHasTimeout) then begin // Time hasn't expired yet. Simulate an operation callback // which doesn't abort execution. {$IFDEF SM52} cx.RequestInterruptCallback; {$ELSE} rt.RequestInterruptCallback; {$ENDIF} end; sleepDuration := PR_INTERVAL_NO_TIMEOUT; if (eng.fWatchdogHasTimeout) then sleepDuration := PR_TicksPerSecond() div 10; status := PR_WaitCondVar(eng.fWatchdogWakeup, sleepDuration); Assert(status = PR_SUCCESS); end end; PR_Unlock(eng.fWatchdogLock); end; function TSMEngine.ScheduleWatchdog(t: integer): Boolean; var interval: Int64; timeout: Int64; begin if (t <= 0) then begin PR_Lock(fWatchdogLock); fWatchdogHasTimeout := false; PR_Unlock(fWatchdogLock); result := true; exit; end; interval := int64(t * PRMJ_USEC_PER_SEC); {$IFDEF SM52} timeout := cx.NowMs + interval; {$ELSE} timeout := rt.NowMs + interval; {$ENDIF} PR_Lock(fWatchdogLock); if not Assigned(fWatchdogThread) then begin Assert(not fWatchdogHasTimeout); fWatchdogThread := PR_CreateThread(PR_USER_THREAD, @WatchdogMain, Self, PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); if not Assigned(fWatchdogThread) then begin PR_Unlock(fWatchdogLock); Result := false; Exit; end end else if (not fWatchdogHasTimeout or IsBefore(timeout, fWatchdogTimeout)) then PR_NotifyCondVar(fWatchdogWakeup); fWatchdogHasTimeout := true; fWatchdogTimeout := timeout; PR_Unlock(fWatchdogLock); Result := true; end; procedure TSMEngine.SetPrivateDataForDebugger(const Value: Pointer); begin FPrivateDataForDebugger := Value; end; function TSMEngine.defineClass(AForClass: TClass; AProto: TSMCustomProtoObjectClass; aParent: PJSRootedObject=nil): TSMCustomProtoObject; begin if aParent = nil then aParent := GlobalObject; result := SyNodeProto.defineClass(cx, AForClass, AProto, aParent); end; procedure TSMEngine.defineClasses(const AClasses: array of TClass; AProto: TSMCustomProtoObjectClass; aParent: PJSRootedObject=nil); var i: Integer; begin for i := 0 to high(AClasses) do defineClass(AClasses[i], AProto); end; procedure TSMEngine.SetThreadData(pThreadData: pointer); begin FThreadData := pThreadData; end; procedure TSMEngine.SetTimeoutValue(const Value: Integer); begin if fTimeoutValue = Value then exit; fTimeoutValue := Value; ScheduleWatchdog(fTimeoutValue); end; // Bindings // synode function synode_parseModule(cx: PJSContext; argc: uintN; var vp: JSArgRec): Boolean; cdecl; var in_argv: PjsvalVector; Script: SynUnicode; FileName: RawUTF8; global: PJSRootedObject; options: PJSCompileOptions; res: PJSRootedObject; const USAGE = 'usage parseModule(source, [path]: String): ModuleObject'; begin try in_argv := vp.argv; if (argc=0) or not in_argv[0].IsString or ((argc > 1) and not in_argv[1].IsString) then raise ESMException.Create(USAGE); Script := in_argv[0].asJSString.ToSynUnicode(cx); FileName := ''; if argc > 1 then FileName := in_argv[1].asJSString.ToUTF8(cx); if FileName = '' then FileName := 'no file'; global := cx.NewRootedObject(cx.CurrentGlobalOrNull); try options := cx.NewCompileOptions; options.filename := Pointer(FileName); res := cx.NewRootedObject(cx.CompileModule(global.ptr, options, Pointer(Script), Length(Script))); result := res <> nil; if result then vp.rval := res.ptr.ToJSValue; cx.FreeRootedObject(res); cx.FreeCompileOptions(options); finally cx.FreeRootedObject(global); end; except on E: Exception do begin Result := False; vp.rval := JSVAL_VOID; JSError(cx, E); end; end; end; {$IFDEF CORE_MODULES_IN_RES} /// Parse and evaluate module stored in resources function synode_parseModuleRes(cx: PJSContext; argc: uintN; var vp: JSArgRec): Boolean; cdecl; var in_argv: PjsvalVector; ResName: string; FileName: RawUTF8; global: PJSRootedObject; options: PJSCompileOptions; res: PJSRootedObject; pScript: pointer; scriptLength: LongWord; const USAGE = 'usage parseModuleRes(resourceName, [path]: String): ModuleObject'; begin try in_argv := vp.argv; if (argc=0) or not in_argv[0].IsString or ((argc > 1) and not in_argv[1].IsString) then raise ESMException.Create(USAGE); ResName := in_argv[0].asJSString.ToString(cx); if not getResCharsAndLength(ResName, pScript, scriptLength) then raise ESMException.CreateUTF8('Resource "%" not found', [ResName]); FileName := ''; if argc > 1 then FileName := in_argv[1].asJSString.ToUTF8(cx); if FileName = '' then FileName := ResName; global := cx.NewRootedObject(cx.CurrentGlobalOrNull); try options := cx.NewCompileOptions; options.filename := Pointer(FileName); res := cx.NewRootedObject(cx.CompileModule(global.ptr, options, pScript, scriptLength)); result := res <> nil; if result then vp.rval := res.ptr.ToJSValue; cx.FreeRootedObject(res); cx.FreeCompileOptions(options); finally cx.FreeRootedObject(global); end; except on E: Exception do begin Result := False; vp.rval := JSVAL_VOID; JSError(cx, E); end; end; end; {$endif} function synode_setModuleResolveHook(cx: PJSContext; argc: uintN; var vp: JSArgRec): Boolean; cdecl; var in_argv: PjsvalVector; ro: PJSRootedObject; begin try in_argv := vp.argv; result := (argc > 0) and (in_argv[0].isObject); if Result then begin ro := cx.NewRootedObject(in_argv[0].asObject); try Result := ro.ptr.isFunction(cx); if Result then cx.SetModuleResolveHook(ro.ptr); finally cx.FreeRootedObject(ro); end; end; except on E: Exception do begin Result := False; vp.rval := JSVAL_VOID; JSError(cx, E); end; end; end; function synode_runInThisContext(cx: PJSContext; argc: uintN; var vp: JSArgRec): Boolean; cdecl; const USAGE = 'usage: runInThisContext(script, [fileName]: string)'; var in_argv: PjsvalVector; res: jsval; Script: SynUnicode; FileName: RawUTF8; opts: PJSCompileOptions; begin try in_argv := vp.argv; if (argc < 1) or not in_argv[0].isString or ((argc >1) and not in_argv[1].isString) then raise ESMException.Create(USAGE); Script := in_argv[0].asJSString.ToSynUnicode(cx); FileName := ''; if argc > 1 then FileName := in_argv[1].asJSString.ToUTF8(cx); if FileName = '' then FileName := 'no file'; cx.BeginRequest; try opts := cx.NewCompileOptions; opts.filename := Pointer(FileName); remChar13FromScript(Script); Result := cx.EvaluateUCScript(opts, Pointer(Script), Length(Script), res); cx.FreeCompileOptions(opts); if Result then vp.rval := res; finally cx.EndRequest; end; vp.rval := res; except on E: Exception do begin Result := False; vp.rval := JSVAL_VOID; JSError(cx, E); end; end; end; {$IFDEF CORE_MODULES_IN_RES} /// Compile and execute a script from named resource function synode_runInThisContextRes(cx: PJSContext; argc: uintN; var vp: JSArgRec): Boolean; cdecl; const USAGE = 'usage: runResInThisContextRes(resourceName, [fileName]: string)'; var in_argv: PjsvalVector; res: jsval; ResName: string; pScript: pointer; scriptLength: LongWord; FileName: RawUTF8; opts: PJSCompileOptions; begin try in_argv := vp.argv; if (argc < 1) or not in_argv[0].isString or ((argc >1) and not in_argv[1].isString) then raise ESMException.Create(USAGE); ResName := in_argv[0].asJSString.ToString(cx); if not getResCharsAndLength(ResName, pScript, scriptLength) then raise ESMException.CreateUTF8('Resource "%" not found', [ResName]); FileName := ''; if argc > 1 then FileName := in_argv[1].asJSString.ToUTF8(cx); if FileName = '' then FileName := ResName; cx.BeginRequest; try opts := cx.NewCompileOptions; opts.filename := Pointer(FileName); Result := cx.EvaluateUCScript(opts, pScript, scriptLength, res); cx.FreeCompileOptions(opts); if Result then vp.rval := res; finally cx.EndRequest; end; vp.rval := res; except on E: Exception do begin Result := False; vp.rval := JSVAL_VOID; JSError(cx, E); end; end; end; {$ENDIF} function synode_loadDll(cx: PJSContext; argc: uintN; var vp: jsargRec): Boolean; cdecl; const USAGE = 'usage: loadDll(module:Object , filename: String)'; var Eng: TSMEngine; in_argv: PjsvalVector; res: jsval; filename: RawUTF8; module: PJSRootedObject; uninitProc: TDllModuleUnInitProc; begin Eng := TObject(cx.PrivateData) as TSMEngine; try in_argv := vp.argv; if (argc < 2) or not (in_argv[0].isObject) or not (in_argv[1].isString) then raise ESMException.Create(USAGE); filename := in_argv[1].asJSString.ToUTF8(cx); module := cx.NewRootedObject(in_argv[0].asObject); try uninitProc := Eng.FManager.evalDllModule(cx, module, filename); if Assigned(uninitProc) then Eng.FDllModulesUnInitProcList.Add(@uninitProc); finally cx.FreeRootedObject(module); end; res := JSVAL_NULL; vp.rval := res; Result := True; except on E: Exception do begin Result := False; vp.rval := JSVAL_VOID; JSError(cx, E); end; end; end; function SyNodeBinding_modules(const Engine: TSMEngine; const bindingNamespaceName: SynUnicode): jsval; var obj: PJSRootedObject; cx: PJSContext; {$IFDEF CORE_MODULES_IN_RES} val: jsval; {$endif} begin cx := Engine.cx; obj := cx.NewRootedObject(cx.NewObject(nil)); try obj.ptr.DefineFunction(cx, 'parseModule', synode_parseModule, 2, JSPROP_READONLY or JSPROP_PERMANENT); obj.ptr.DefineFunction(cx, 'setModuleResolveHook', synode_setModuleResolveHook, 1, JSPROP_READONLY or JSPROP_PERMANENT); obj.ptr.DefineFunction(cx, 'runInThisContext', synode_runInThisContext, 2, JSPROP_READONLY or JSPROP_PERMANENT); obj.ptr.DefineFunction(cx, 'loadDll', synode_loadDll, 2, JSPROP_READONLY or JSPROP_PERMANENT); {$IFDEF CORE_MODULES_IN_RES} val.asBoolean := true; obj.ptr.DefineProperty(cx, '_coreModulesInRes', val, JSPROP_READONLY or JSPROP_PERMANENT); obj.ptr.DefineFunction(cx, 'parseModuleRes', synode_parseModuleRes, 2, JSPROP_READONLY or JSPROP_PERMANENT); obj.ptr.DefineFunction(cx, 'runInThisContextRes', synode_runInThisContextRes, 2, JSPROP_READONLY or JSPROP_PERMANENT); {$ENDIF} obj.ptr.DefineProperty(cx, 'coreModulesPath', cx.NewJSString(Engine.Manager.CoreModulesPath).ToJSVal, JSPROP_READONLY or JSPROP_PERMANENT); Result := obj.ptr.ToJSValue; finally cx.FreeRootedObject(obj); end; end; /// sleep X ms function synode_sleep(cx: PJSContext; argc: uintN; var vp: JSArgRec): Boolean; cdecl; var in_argv: PjsvalVector; interval: int64; engine: TSMEngine; const USAGE = 'usage: sleep(module: Number)'; begin try in_argv := vp.argv; if (argc < 1) or not in_argv[0].isNumber then raise ESMException.Create(USAGE); engine := TSMEngine(cx.PrivateData); if in_argv[0].isInteger then interval := in_argv[0].asInteger else interval := Trunc(in_argv[0].asDouble); while not engine.TimeOutAborted and (interval > 0) do begin Sleep(100); interval := interval - 100; end; Result := True; except on E: Exception do begin Result := False; vp.rval := JSVAL_VOID; JSError(cx, E); end; end; end; function SyNodeBinding_syNode(const Engine: TSMEngine; const bindingNamespaceName: SynUnicode): jsval; var obj: PJSRootedObject; cx: PJSContext; begin cx := Engine.cx; obj := cx.NewRootedObject(cx.NewObject(nil)); try obj.ptr.DefineFunction(cx, 'sleep', synode_sleep, 1, JSPROP_READONLY or JSPROP_PERMANENT); Result := obj.ptr.ToJSValue; finally cx.FreeRootedObject(obj); end; end; initialization TSMEngineManager.RegisterBinding('modules', SyNodeBinding_modules); TSMEngineManager.RegisterBinding('syNode', SyNodeBinding_syNode); finalization FreeAndNil(GlobalSyNodeBindingHandlers); end.
0
0.972857
1
0.972857
game-dev
MEDIA
0.24176
game-dev
0.846757
1
0.846757
hk-modding/api
1,856
Assembly-CSharp/Patches/MenuSelectable.cs
using System; using MonoMod; using UnityEngine.EventSystems; // ReSharper disable All #pragma warning disable 1591, 0108, 0169, 0649, 0626 namespace Modding.Patches { [MonoModPatch("UnityEngine.UI.MenuSelectable")] public class MenuSelectable : UnityEngine.UI.MenuSelectable { public Action<MenuSelectable> customCancelAction { get; set; } public extern void orig_OnCancel(BaseEventData eventData); public void OnCancel(BaseEventData eventData) { if ((CancelAction)this.cancelAction == CancelAction.CustomCancelAction && this.customCancelAction != null) { this.ForceDeselect(); customCancelAction(this); this.PlayCancelSound(); return; } orig_OnCancel(eventData); } } public static class MenuSelectableExt { public static void SetDynamicMenuCancel( this UnityEngine.UI.MenuSelectable ms, MenuScreen to ) { ms.cancelAction = (GlobalEnums.CancelAction)CancelAction.CustomCancelAction; (ms as MenuSelectable).customCancelAction = (self) => { var uim = (UIManager)global::UIManager.instance; uim.StartMenuAnimationCoroutine(uim.GoToDynamicMenu(to)); }; } } [MonoModPatch("GlobalEnums.CancelAction")] public enum CancelAction { DoNothing, GoToMainMenu, GoToOptionsMenu, GoToVideoMenu, GoToPauseMenu, LeaveOptionsMenu, GoToExitPrompt, GoToProfileMenu, GoToControllerMenu, ApplyRemapGamepadSettings, ApplyAudioSettings, ApplyVideoSettings, ApplyGameSettings, ApplyKeyboardSettings, CustomCancelAction } }
0
0.692055
1
0.692055
game-dev
MEDIA
0.90486
game-dev
0.643665
1
0.643665
gta-reversed/gta-reversed
4,437
source/game_sa/Buoyancy.h
#pragma once #include "Matrix.h" #include "Vector.h" class CEntity; class CPhysical; class CVehicle; // original name, our previous name eBuoyancyPointState enum class tWaterLevel : int32 { COMPLETELY_ABOVE_WATER = 0x0, COLLIDING_WITH_WATER = 0x1, COMPLETELY_UNDER_WATER = 0x2, }; struct CBuoyancyCalcStruct { float fCurrentAverageContribution; float fNewPointContribution; CVector vecCurOffsetTurnPoint; float fAddedDistToWaterSurface; bool bBuoyancyDataSummed; }; VALIDATE_SIZE(CBuoyancyCalcStruct, 0x1C); class cBuoyancy { public: CVector m_vecPos; // Position of the entity which buoyancy is being calculated CMatrix m_EntityMatrix; // Matrix of the entity which buoyancy is being calculated uint32 pad; CVector m_vecInitialZPos; // Holds some info about current entity, only ever used to retrieve its Z coordinate, which is already stored in m_vecPos field float m_fWaterLevel; // Z coordinate of water at entity position float m_fUnkn2; // 104 float m_fBuoyancy; // 108 CVector m_vecBoundingMax; // Max bounding of the entity, doesn't necessarily match its collision as it's modified a bit CVector m_vecBoundingMin; // Min bounding of the entity, doesn't necessarily match its collision as it's modified a bit float m_fNumCheckedPoints; // How many points have been checked to calculate the buoyancy force, 9 points are checked at most for entity, used to keep track of incremental // average calculation uint32 field_8C; uint32 field_90; uint32 field_94; bool m_bInWater; // Is entity in water? uint8 field_99; uint8 field_9A; uint8 field_9B; CVector m_vecCenterOffset; // Offset from min bounding to the center CVector m_vecNormalizedCenterOffset; // Same as m_vecCenterOffset, but scaled by longest component so it's 1.0F in the longest direction uint32 field_B4; bool m_bFlipUnknVector; // Should the currently calculated move force be inverted? (multiplied by -1.0F in the calculations) uint8 field_B9; bool m_bProcessingBoat; // Are we currently checking buoyancy of a boat? uint8 field_BB; // 187 float m_fEntityWaterImmersion; // How much of the entity is immersed in water, [0:1] where 0 means entity is out of water, and 1 means that entity is completely submerged in // water CVector m_vecTurnPoint; // Calculated buoyancy move force uint32 field_CC; // 204 static float& fPointVolMultiplier; static CBuoyancyCalcStruct& calcStruct; static float(*afBoatVolumeDistributionSpeed)[3]; // 3x3 array of buoyancy modifiers for speedboats static float(*afBoatVolumeDistributionDinghy)[3]; // 3x3 array of buoyancy modifiers for small boats static float(*afBoatVolumeDistributionSail)[3]; // 3x3 array of buoyancy modifiers for sailboats static float(*afBoatVolumeDistribution)[3]; // 3x3 array of buoyancy modifiers for other boats static float(*afBoatVolumeDistributionCat)[3]; // Catamaran volume distribution, unused in game, as there is no matching vehicle public: static void InjectHooks(); cBuoyancy() = default; // 0x6C2740 ~cBuoyancy() = default; // 0x6C2B80 bool ProcessBuoyancy(CPhysical* entity, float fBuoyancy, CVector* vecTurnSpeed, CVector* buoyancy); bool ProcessBuoyancyBoat(CVehicle* vehicle, float fBuoyancy, CVector* vecBuoyancyTurnPoint, CVector* vecBuoyancyForce, bool bUnderwater); bool CalcBuoyancyForce(CPhysical* entity, CVector* vecTurnSpeed, CVector* buoyancy); void PreCalcSetup(CPhysical* entity, float fBuoyancy); void AddSplashParticles(CPhysical* entity, CVector vecFrom, CVector vecTo, CVector vecSplashDir, uint8 bReduceParticleSize); void SimpleCalcBuoyancy(CPhysical* entity); float SimpleSumBuoyancyData(CVector* vecPointRelativeToSurface, tWaterLevel ePointState); void FindWaterLevel(const CVector& vecInitialZPos, CVector* outVecOffset, tWaterLevel* outInWaterState); void FindWaterLevelNorm(const CVector& vecInitialZPos, CVector* outVecOffset, tWaterLevel* outInWaterState, CVector* outVecNormal); }; VALIDATE_SIZE(cBuoyancy, 0xD0); extern cBuoyancy& mod_Buoyancy;
0
0.705831
1
0.705831
game-dev
MEDIA
0.796921
game-dev
0.514352
1
0.514352
Hotrian/OpenVRDesktopDisplayPortal
20,193
Assets/HOTK/Example Content/UI Scripts/DropdownSaveLoadController.cs
using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; using Valve.VR; [RequireComponent(typeof(Dropdown))] public class DropdownSaveLoadController : MonoBehaviour { public HOTK_Overlay OverlayToSave; public OffsetMatchSlider XSlider; public OffsetMatchSlider YSlider; public OffsetMatchSlider ZSlider; public RotationMatchSlider RXSlider; public RotationMatchSlider RYSlider; public RotationMatchSlider RZSlider; public DropdownMatchEnumOptions DeviceDropdown; public DropdownMatchEnumOptions PointDropdown; public DropdownMatchEnumOptions AnimationDropdown; public InputField AlphaStartField; public InputField AlphaEndField; public InputField AlphaSpeedField; public InputField ScaleStartField; public InputField ScaleEndField; public InputField ScaleSpeedField; public InputField AlphaDodgeField; public InputField ScaleDodgeField; public InputField AlphaNoneField; public InputField ScaleNoneField; public InputField DodgeXField; public InputField DodgeYField; public InputField DodgeSpeedField; public Button SaveButton; public Button LoadButton; public Button DeleteButton; public Text DeleteButtonText; public EventTrigger DeleteButtonTriggers; public InputField SaveName; public Button SaveNewButton; public Button CancelNewButton; public HSVPickerPortalScript ColorPicker; public Dropdown Dropdown { get { return _dropdown ?? (_dropdown = GetComponent<Dropdown>()); } } private Dropdown _dropdown; private static string NewString = "New.."; public void OnEnable() { if (PortalSettingsSaver.CurrentProgramSettings == null) PortalSettingsSaver.LoadProgramSettings(); ReloadOptions(); if (PortalSettingsSaver.CurrentProgramSettings != null && !string.IsNullOrEmpty(PortalSettingsSaver.CurrentProgramSettings.LastProfile)) OnLoadPressed(true); } private void ReloadOptions() { Dropdown.ClearOptions(); var strings = new List<string> { NewString }; strings.AddRange(PortalSettingsSaver.SavedProfiles.Select(config => config.Key)); Dropdown.AddOptions(strings); // If no settings loaded yet, select "New" if (string.IsNullOrEmpty(PortalSettingsSaver.Current)) { Dropdown.value = 0; OnValueChanges(); } else // If settings are loaded, try and select the current settings { for (var i = 0; i < Dropdown.options.Count; i++) { if (Dropdown.options[i].text != PortalSettingsSaver.Current) continue; Dropdown.value = i; OnValueChanges(); break; } } } private bool _savingNew; public void OnValueChanges() { CancelConfirmingDelete(); if (_savingNew) { Dropdown.interactable = false; SaveName.interactable = true; CancelNewButton.interactable = true; DeleteButton.interactable = false; LoadButton.interactable = false; SaveButton.interactable = false; } else { Dropdown.interactable = true; SaveName.interactable = false; SaveNewButton.interactable = false; CancelNewButton.interactable = false; if (Dropdown.options[Dropdown.value].text == NewString) { DeleteButton.interactable = false; LoadButton.interactable = false; SaveButton.interactable = true; } else { DeleteButton.interactable = true; LoadButton.interactable = true; SaveButton.interactable = true; } } } public void OnLoadPressed(bool startup = false) // Loads an existing save { if (startup) HOTK_TrackedDeviceManager.Instance.FindControllers(); CancelConfirmingDelete(); PortalSettings settings; if (!PortalSettingsSaver.SavedProfiles.TryGetValue(Dropdown.options[Dropdown.value].text, out settings)) return; Debug.Log(startup ? "Loading last used settings " + Dropdown.options[Dropdown.value].text : "Loading saved settings " + Dropdown.options[Dropdown.value].text); PortalSettingsSaver.Current = Dropdown.options[Dropdown.value].text; if (!startup) PortalSettingsSaver.SaveProgramSettings(); if (settings.SaveFileVersion < 2) { if (settings.Device == HOTK_Overlay.AttachmentDevice.Screen || settings.Device == HOTK_Overlay.AttachmentDevice.World) settings.Z += 1; if (settings.Device == HOTK_Overlay.AttachmentDevice.Screen) settings.ScreenOffsetPerformed = true; settings.OutlineDefaultR = 0f; settings.OutlineDefaultG = 0f; settings.OutlineDefaultB = 0f; settings.OutlineDefaultA = 0f; settings.OutlineAimingR = 1f; settings.OutlineAimingG = 0f; settings.OutlineAimingB = 0f; settings.OutlineAimingA = 1f; settings.OutlineTouchingR = 0f; settings.OutlineTouchingG = 1f; settings.OutlineTouchingB = 0f; settings.OutlineTouchingA = 1f; settings.OutlineScalingR = 0f; settings.OutlineScalingG = 0f; settings.OutlineScalingB = 1f; settings.OutlineScalingA = 1f; settings.SaveFileVersion = 2; } if (settings.SaveFileVersion == 2) { settings.Backside = DesktopPortalController.BacksideTexture.Blue; settings.SaveFileVersion = 3; } if (settings.SaveFileVersion == 3) { settings.GrabEnabled = true; settings.ScaleEnabled = true; settings.SaveFileVersion = 4; } if (settings.SaveFileVersion == 4) { settings.HapticsEnabled = true; settings.SaveFileVersion = 5; } if (settings.SaveFileVersion == 5) { settings.DodgeOffsetX = 2f; settings.DodgeOffsetY = 0f; settings.DodgeOffsetSpeed = 0.1f; settings.SaveFileVersion = 6; } DesktopPortalController.Instance.ScreenOffsetPerformed = settings.ScreenOffsetPerformed; // Recenter XYZ Sliders XSlider.Slider.minValue = settings.X - 2f; XSlider.Slider.maxValue = settings.X + 2f; YSlider.Slider.minValue = settings.Y - 2f; YSlider.Slider.maxValue = settings.Y + 2f; ZSlider.Slider.minValue = settings.Z - 2f; ZSlider.Slider.maxValue = settings.Z + 2f; XSlider.Slider.value = settings.X; YSlider.Slider.value = settings.Y; ZSlider.Slider.value = settings.Z; // Disable Rotation sliders so only one call to update the overlay occurs RXSlider.IgnoreNextUpdate(); RYSlider.IgnoreNextUpdate(); RZSlider.IgnoreNextUpdate(); RXSlider.Slider.value = settings.RX; RYSlider.Slider.value = settings.RY; RZSlider.Slider.value = settings.RZ; RXSlider.OnSliderChanged(); RYSlider.OnSliderChanged(); RZSlider.OnSliderChanged(); if (RXSlider.RotationField != null) RXSlider.RotationField.SetSafeValue(settings.RX); if (RYSlider.RotationField != null) RYSlider.RotationField.SetSafeValue(settings.RY); if (RZSlider.RotationField != null) RZSlider.RotationField.SetSafeValue(settings.RZ); // Swap Selected Controllers when Saved Controller is absent and the other Controller is present DeviceDropdown.SetToOption(((settings.Device == HOTK_Overlay.AttachmentDevice.LeftController && HOTK_TrackedDeviceManager.Instance.LeftIndex == OpenVR.k_unTrackedDeviceIndexInvalid && HOTK_TrackedDeviceManager.Instance.RightIndex != OpenVR.k_unTrackedDeviceIndexInvalid) ? HOTK_Overlay.AttachmentDevice.RightController : // Left Controller not found but Right Controller found. Use Right Controller. ((settings.Device == HOTK_Overlay.AttachmentDevice.RightController && HOTK_TrackedDeviceManager.Instance.RightIndex == OpenVR.k_unTrackedDeviceIndexInvalid && HOTK_TrackedDeviceManager.Instance.LeftIndex != OpenVR.k_unTrackedDeviceIndexInvalid) ? HOTK_Overlay.AttachmentDevice.LeftController : // Right Controller not found but Left Controller found. Use Left Controller. settings.Device)).ToString()); // Use Device setting otherwise PointDropdown.SetToOption(settings.Point.ToString()); AnimationDropdown.SetToOption(settings.Animation.ToString()); AlphaStartField.text = settings.AlphaStart.ToString(); AlphaEndField.text = settings.AlphaEnd.ToString(); AlphaSpeedField.text = settings.AlphaSpeed.ToString(); ScaleStartField.text = settings.ScaleStart.ToString(); ScaleEndField.text = settings.ScaleEnd.ToString(); ScaleSpeedField.text = settings.ScaleSpeed.ToString(); AlphaDodgeField.text = settings.AlphaStart.ToString(); ScaleDodgeField.text = settings.ScaleStart.ToString(); AlphaNoneField.text = settings.AlphaStart.ToString(); ScaleNoneField.text = settings.ScaleStart.ToString(); DodgeXField.text = settings.DodgeOffsetX.ToString(); DodgeYField.text = settings.DodgeOffsetY.ToString(); DodgeSpeedField.text = settings.DodgeOffsetSpeed.ToString(); AlphaStartField.onEndEdit.Invoke(""); AlphaEndField.onEndEdit.Invoke(""); AlphaSpeedField.onEndEdit.Invoke(""); ScaleStartField.onEndEdit.Invoke(""); ScaleEndField.onEndEdit.Invoke(""); ScaleSpeedField.onEndEdit.Invoke(""); AlphaDodgeField.onEndEdit.Invoke(""); ScaleDodgeField.onEndEdit.Invoke(""); AlphaNoneField.onEndEdit.Invoke(""); ScaleNoneField.onEndEdit.Invoke(""); DodgeXField.onEndEdit.Invoke(""); DodgeYField.onEndEdit.Invoke(""); DodgeSpeedField.onEndEdit.Invoke(""); DesktopPortalController.Instance.OutlineColorDefault = new Color(settings.OutlineDefaultR, settings.OutlineDefaultG, settings.OutlineDefaultB, settings.OutlineDefaultA); DesktopPortalController.Instance.OutlineColorAiming = new Color(settings.OutlineAimingR, settings.OutlineAimingG, settings.OutlineAimingB, settings.OutlineAimingA); DesktopPortalController.Instance.OutlineColorTouching = new Color(settings.OutlineTouchingR, settings.OutlineTouchingG, settings.OutlineTouchingB, settings.OutlineTouchingA); DesktopPortalController.Instance.OutlineColorScaling = new Color(settings.OutlineScalingR, settings.OutlineScalingG, settings.OutlineScalingB, settings.OutlineScalingA); DesktopPortalController.Instance.CurrentBacksideTexture = settings.Backside; DesktopPortalController.Instance.GrabEnabledToggle.isOn = settings.GrabEnabled; DesktopPortalController.Instance.ScaleEnabledToggle.isOn = settings.ScaleEnabled; DesktopPortalController.Instance.HapticsEnabledToggle.isOn = settings.HapticsEnabled; ColorPicker.LoadButtonColors(); } private bool _confirmingDelete; private string _deleteTextDefault = "Delete the selected profile."; private string _deleteTextConfirm = "Really Delete?"; public void OnDeleteButtonTooltip(bool forced = false) { if (_confirmingDelete) { if (forced || TooltipController.Instance.GetTooltipText() == _deleteTextDefault) TooltipController.Instance.SetTooltipText(_deleteTextConfirm); } else { if (forced || TooltipController.Instance.GetTooltipText() == _deleteTextConfirm) TooltipController.Instance.SetTooltipText(_deleteTextDefault); } } public void CancelConfirmingDelete() { _confirmingDelete = false; DeleteButtonText.color = new Color(0.196f, 0.196f, 0.196f, 1f); OnDeleteButtonTooltip(); } public void OnDeletePressed() { if (!_confirmingDelete) { _confirmingDelete = true; DeleteButtonText.color = Color.red; OnDeleteButtonTooltip(); } else { PortalSettingsSaver.DeleteProfile(Dropdown.options[Dropdown.value].text); CancelConfirmingDelete(); if (PortalSettingsSaver.SavedProfiles.Count == 0) PortalSettingsSaver.LoadDefaultProfiles(); ReloadOptions(); } } /// <summary> /// Overwrite an existing save, or save a new one /// </summary> public void OnSavePressed() { CancelConfirmingDelete(); if (Dropdown.options[Dropdown.value].text == NewString) // Start creating a new save { _savingNew = true; OnValueChanges(); } else // Overwrite an existing save { PortalSettings settings; if (!PortalSettingsSaver.SavedProfiles.TryGetValue(Dropdown.options[Dropdown.value].text, out settings)) return; Debug.Log("Overwriting saved settings " + Dropdown.options[Dropdown.value].text); settings.SaveFileVersion = PortalSettings.CurrentSaveVersion; settings.X = OverlayToSave.AnchorOffset.x; settings.Y = OverlayToSave.AnchorOffset.y; settings.Z = OverlayToSave.AnchorOffset.z; settings.RX = RXSlider.Slider.value; settings.RY = RYSlider.Slider.value; settings.RZ = RZSlider.Slider.value; settings.Device = OverlayToSave.AnchorDevice; settings.Point = OverlayToSave.AnchorPoint; settings.Animation = OverlayToSave.AnimateOnGaze; settings.AlphaStart = OverlayToSave.Alpha; settings.AlphaEnd = OverlayToSave.Alpha2; settings.AlphaSpeed = OverlayToSave.AlphaSpeed; settings.ScaleStart = OverlayToSave.Scale; settings.ScaleEnd = OverlayToSave.Scale2; settings.ScaleSpeed = OverlayToSave.ScaleSpeed; settings.ScreenOffsetPerformed = DesktopPortalController.Instance.ScreenOffsetPerformed; settings.OutlineDefaultR = DesktopPortalController.Instance.OutlineColorDefault.r; settings.OutlineDefaultG = DesktopPortalController.Instance.OutlineColorDefault.g; settings.OutlineDefaultB = DesktopPortalController.Instance.OutlineColorDefault.b; settings.OutlineDefaultA = DesktopPortalController.Instance.OutlineColorDefault.a; settings.OutlineAimingR = DesktopPortalController.Instance.OutlineColorAiming.r; settings.OutlineAimingG = DesktopPortalController.Instance.OutlineColorAiming.g; settings.OutlineAimingB = DesktopPortalController.Instance.OutlineColorAiming.b; settings.OutlineAimingA = DesktopPortalController.Instance.OutlineColorAiming.a; settings.OutlineTouchingR = DesktopPortalController.Instance.OutlineColorTouching.r; settings.OutlineTouchingG = DesktopPortalController.Instance.OutlineColorTouching.g; settings.OutlineTouchingB = DesktopPortalController.Instance.OutlineColorTouching.b; settings.OutlineTouchingA = DesktopPortalController.Instance.OutlineColorTouching.a; settings.OutlineScalingR = DesktopPortalController.Instance.OutlineColorScaling.r; settings.OutlineScalingG = DesktopPortalController.Instance.OutlineColorScaling.g; settings.OutlineScalingB = DesktopPortalController.Instance.OutlineColorScaling.b; settings.OutlineScalingA = DesktopPortalController.Instance.OutlineColorScaling.a; settings.Backside = DesktopPortalController.Instance.CurrentBacksideTexture; settings.GrabEnabled = DesktopPortalController.Instance.GrabEnabledToggle.isOn; settings.ScaleEnabled = DesktopPortalController.Instance.ScaleEnabledToggle.isOn; settings.HapticsEnabled = DesktopPortalController.Instance.HapticsEnabledToggle.isOn; settings.DodgeOffsetX = OverlayToSave.DodgeGazeOffset.x; settings.DodgeOffsetY = OverlayToSave.DodgeGazeOffset.y; settings.DodgeOffsetSpeed = OverlayToSave.DodgeGazeSpeed; PortalSettingsSaver.SaveProfiles(); } } public void OnSaveNewPressed() { if (string.IsNullOrEmpty(SaveName.text) || PortalSettingsSaver.SavedProfiles.ContainsKey(SaveName.text)) return; _savingNew = false; Debug.Log("Adding saved settings " + SaveName.text); PortalSettingsSaver.SavedProfiles.Add(SaveName.text, ConvertToPortalSettings(OverlayToSave)); PortalSettingsSaver.SaveProfiles(); PortalSettingsSaver.Current = SaveName.text; SaveName.text = ""; ReloadOptions(); } /// <summary> /// Create a new Save /// </summary> private PortalSettings ConvertToPortalSettings(HOTK_Overlay o) // Create a new save state { return new PortalSettings() { SaveFileVersion = PortalSettings.CurrentSaveVersion, X = o.AnchorOffset.x, Y = o.AnchorOffset.y, Z = o.AnchorOffset.z, RX = o.transform.eulerAngles.x, RY = o.transform.eulerAngles.y, RZ = o.transform.eulerAngles.z, Device = o.AnchorDevice, Point = o.AnchorPoint, Animation = o.AnimateOnGaze, AlphaStart = o.Alpha, AlphaEnd = o.Alpha2, AlphaSpeed = o.AlphaSpeed, ScaleStart = o.Scale, ScaleEnd = o.Scale2, ScaleSpeed = o.ScaleSpeed, ScreenOffsetPerformed = DesktopPortalController.Instance.ScreenOffsetPerformed, OutlineDefaultR = DesktopPortalController.Instance.OutlineColorDefault.r, OutlineDefaultG = DesktopPortalController.Instance.OutlineColorDefault.g, OutlineDefaultB = DesktopPortalController.Instance.OutlineColorDefault.b, OutlineDefaultA = DesktopPortalController.Instance.OutlineColorDefault.a, OutlineAimingR = DesktopPortalController.Instance.OutlineColorAiming.r, OutlineAimingG = DesktopPortalController.Instance.OutlineColorAiming.g, OutlineAimingB = DesktopPortalController.Instance.OutlineColorAiming.b, OutlineAimingA = DesktopPortalController.Instance.OutlineColorAiming.a, OutlineTouchingR = DesktopPortalController.Instance.OutlineColorTouching.r, OutlineTouchingG = DesktopPortalController.Instance.OutlineColorTouching.g, OutlineTouchingB = DesktopPortalController.Instance.OutlineColorTouching.b, OutlineTouchingA = DesktopPortalController.Instance.OutlineColorTouching.a, OutlineScalingR = DesktopPortalController.Instance.OutlineColorScaling.r, OutlineScalingG = DesktopPortalController.Instance.OutlineColorScaling.g, OutlineScalingB = DesktopPortalController.Instance.OutlineColorScaling.b, OutlineScalingA = DesktopPortalController.Instance.OutlineColorScaling.a, Backside = DesktopPortalController.Instance.CurrentBacksideTexture, GrabEnabled = DesktopPortalController.Instance.GrabEnabledToggle.isOn, ScaleEnabled = DesktopPortalController.Instance.ScaleEnabledToggle.isOn, HapticsEnabled = DesktopPortalController.Instance.HapticsEnabledToggle.isOn, DodgeOffsetX = o.DodgeGazeOffset.x, DodgeOffsetY = o.DodgeGazeOffset.y, DodgeOffsetSpeed = o.DodgeGazeSpeed, }; } public void OnCancelNewPressed() { _savingNew = false; SaveName.text = ""; OnValueChanges(); } public void OnSaveNameChanged() { if (string.IsNullOrEmpty(SaveName.text) || SaveName.text == NewString) { SaveNewButton.interactable = false; } else { SaveNewButton.interactable = true; } } }
0
0.910305
1
0.910305
game-dev
MEDIA
0.499132
game-dev,desktop-app
0.959654
1
0.959654
mokkkk/MhdpColiseumDatapacksComponents
1,952
mhdp_monster_valk/data/mhdp_monster_valk/function/core/damage/reaction/arm_r.mcfunction
#> mhdp_monster_valk:core/damage/reaction/arm_r # # 怯みリアクション 右足 # # @within function mhdp_monster_valk:core/damage/damage # 共通処理 # スコアリセット scoreboard players operation @s Mns.Valk.ArmR.Damage = @s Mns.Valk.ArmR.Damage.Max # カウンター増加 scoreboard players add @s Mns.Valk.ArmR.Damage.Count 1 # 部位破壊処理 execute if entity @s[tag=!Mns.Break.Arm.R] run function mhdp_monster_valk:core/damage/reaction/arm_r_break # アニメーション再生処理 # 麻痺・ダウン・スタン時以外 execute unless entity @s[tag=!Mns.State.IsParalysis,tag=!Mns.State.IsDown,tag=!Mns.State.IsStun] run return 0 # アニメーション再生 execute if score @s Mns.Valk.ArmR.Damage.Count matches ..2 run function animated_java:valk_aj/animations/lance_damage_body_r/tween {duration:1, to_frame: 0} execute if score @s Mns.Valk.ArmR.Damage.Count matches 3.. run function animated_java:valk_aj/animations/lance_damage_down_r/tween {duration:1, to_frame: 0} execute if entity @s[tag=Mns.State.IsFlying,tag=!Mns.Temp.IsDamaged] run function mhdp_monster_valk:core/damage/reaction/flying # ダウン時間設定 scoreboard players set @s Mns.General.DownCount 2 execute if score @s Mns.Valk.ArmR.Damage.Count matches 3.. run scoreboard players set @s Mns.General.DownCount 5 # 演出 playsound entity.item.break master @a[tag=!Ply.State.IsSilent] ~ ~ ~ 2 0.5 playsound entity.item.break master @a[tag=!Ply.State.IsSilent] ~ ~ ~ 2 0.5 # アニメーションタグ消去 function mhdp_monsters:core/util/other/remove_animation_tag # 状態設定 execute if score @s Mns.Valk.ArmR.Damage.Count matches 3.. run tag @s add Mns.State.IsDown tag @s remove Mns.State.IsDisableAngerSpeed # モデル変更 function mhdp_monster_valk:core/util/models/model_interrupt # 終了 execute if score @s Mns.Valk.ArmR.Damage.Count matches 3.. run scoreboard players set @s Mns.Valk.ArmR.Damage.Count 0 function mhdp_monster_valk:core/damage/reaction/general
0
0.873806
1
0.873806
game-dev
MEDIA
0.981515
game-dev
0.57815
1
0.57815
hairibar/Hairibar.Ragdoll
3,568
Core/Runtime/Core/RagdollBone.cs
using System.Collections.Generic; using UnityEngine; namespace Hairibar.Ragdoll { public class RagdollBone { public PowerSetting PowerSetting { get => _powerSetting; set { PowerSetting oldValue = _powerSetting; _powerSetting = value; if (oldValue != value) { OnPowerSettingChanged?.Invoke(oldValue, value); } } } public delegate void OnPowerSettingChangedHandler(PowerSetting previousSetting, PowerSetting newSetting); public event OnPowerSettingChangedHandler OnPowerSettingChanged; public BoneName Name { get; } public bool IsRoot { get; } public Transform Transform { get; } public Rigidbody Rigidbody { get; } public ConfigurableJoint Joint { get; } public IEnumerable<Collider> Colliders { get; } public Quaternion StartingJointRotation { get; } PowerSetting _powerSetting = PowerSetting.Kinematic; #region Initialization internal RagdollBone(BoneName name, Transform transform, Rigidbody rigidbody, ConfigurableJoint joint, bool isRoot) { Name = name; Transform = transform; Rigidbody = rigidbody; Joint = joint; IsRoot = isRoot; Colliders = GatherColliders(); ConfigureJoint(); StartingJointRotation = GetStartingJointRotation(); } Collider[] GatherColliders() { List<Collider> colliders = new List<Collider>(); GatherCollidersAtTransform(Transform); VisitChildren(Transform); return colliders.ToArray(); void GatherCollidersAtTransform(Transform transform) { colliders.AddRange(transform.GetComponents<Collider>()); } void VisitChildren(Transform parent) { for (int i = 0; i < parent.childCount; i++) { Transform child = parent.GetChild(i); bool isItsOwnBone = child.GetComponent<ConfigurableJoint>(); if (!isItsOwnBone) { GatherCollidersAtTransform(child); VisitChildren(child); } } } } void ConfigureJoint() { Joint.configuredInWorldSpace = IsRoot; Joint.rotationDriveMode = RotationDriveMode.Slerp; } Quaternion GetStartingJointRotation() { return Joint.configuredInWorldSpace ? Transform.rotation : Transform.localRotation; } #endregion /// <summary> /// At OnEnable(), joints do some weird re-configuring. This method, if called from OnEnable(), deals with that. /// </summary> internal void ResetJointAxisOnEnable() { // https://forum.unity.com/threads/hinge-joint-limits-resets-on-activate-object.483481/#post-5713138 Quaternion originalRotation = Transform.localRotation; Transform.localRotation = StartingJointRotation; Joint.axis = Joint.axis; // Yes, this is intentional. The axis setter triggers some calculations that we need. Transform.localRotation = originalRotation; } public override string ToString() { return Name.ToString(); } } }
0
0.977136
1
0.977136
game-dev
MEDIA
0.943331
game-dev
0.953716
1
0.953716
Raven-APlus/RavenAPlus
14,987
src/main/java/keystrokesmod/module/impl/combat/KillAuraV2.java
package keystrokesmod.module.impl.combat; import akka.japi.Pair; import keystrokesmod.event.PostMotionEvent; import keystrokesmod.event.PreMotionEvent; import keystrokesmod.event.RotationEvent; import keystrokesmod.mixins.impl.client.KeyBindingAccessor; import keystrokesmod.module.Module; import keystrokesmod.module.ModuleManager; import keystrokesmod.module.impl.other.RotationHandler; import keystrokesmod.module.impl.other.SlotHandler; import keystrokesmod.module.impl.player.Blink; import keystrokesmod.module.impl.world.AntiBot; import keystrokesmod.module.setting.impl.ButtonSetting; import keystrokesmod.module.setting.impl.ModeSetting; import keystrokesmod.module.setting.impl.SliderSetting; import keystrokesmod.module.setting.utils.ModeOnly; import keystrokesmod.utility.*; import keystrokesmod.utility.aim.AimSimulator; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemSword; import net.minecraft.network.play.client.*; import net.minecraft.potion.Potion; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.MovingObjectPosition; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class KillAuraV2 extends Module { private int cps; private int targetIndex = 0; private float lastYaw; private float lastPitch; public static boolean aiming; public static boolean blocking; public static boolean wasBlocking; public static EntityLivingBase target; private final TimerUtil attackTimer = new TimerUtil(); private final TimerUtil switchTimer = new TimerUtil(); public static final List<EntityLivingBase> targets = new ArrayList<>(); private final ButtonSetting targetPlayer = new ButtonSetting("Players", true); private final ButtonSetting targetAnimals = new ButtonSetting("Animals", false); private final ButtonSetting targetMobs = new ButtonSetting("Mobs", false); private final ButtonSetting targetInvisible = new ButtonSetting("Invisible", false); private final ModeSetting mode = new ModeSetting("Mode", new String[]{"Single", "Switch"}, 0); public final SliderSetting switchDelay = new SliderSetting("Switch delay",200,0,1000,50, new ModeOnly(mode, 1)); private final SliderSetting rotationSpeed = new SliderSetting("Rotation speed", 20, 2, 20, 0.1); private final ModeSetting rotationMode = new ModeSetting("Rotation mode", new String[]{"Instant", "Nearest"}, 0); private final ModeSetting moveFixMode = new ModeSetting("MoveFix mode", RotationHandler.MoveFix.MODES, 2); private final ButtonSetting autoBlock = new ButtonSetting("AutoBlock", false); private final ModeSetting autoBlockMode = new ModeSetting("AutoBlock mode", new String[]{"Fake", "Watchdog", "GrimAC 1.8", "GrimAC 1.12"}, 0, autoBlock::isToggled); private final ButtonSetting fixNoSlowFlag = new ButtonSetting("Fix NoSlow flag", false, () -> autoBlock.isToggled() && autoBlockMode.getInput() == 1); private final ModeSetting sortMode = new ModeSetting("Sort Mode", new String[]{"Distance", "Hurt Time", "Health", "Armor"}, 0, autoBlock::isToggled); private final SliderSetting minCPS = new SliderSetting("Min CPS", 10, 1, 20, 1); private final SliderSetting maxCPS = new SliderSetting("Max CPS", 20, 1, 20, 1); private final SliderSetting preAimRange = new SliderSetting("PreAim range", 3.5, 3, 10, 0.1); public static final SliderSetting attackRange = new SliderSetting("Attack range", 3, 3, 6, 0.1); private static final ButtonSetting ThroughWalls = new ButtonSetting("Through walls", false); private final ButtonSetting RayCast = new ButtonSetting("Ray cast", true); private int autoBlock$watchdog$blockingTime = 0; private final AimSimulator aimSimulator = new AimSimulator(); public KillAuraV2() { super("KillAuraV2", category.experimental); this.registerSetting(mode, switchDelay, minCPS, maxCPS, rotationMode, moveFixMode, rotationSpeed, autoBlock, autoBlockMode, fixNoSlowFlag, preAimRange, attackRange, sortMode, ThroughWalls, RayCast, targetPlayer, targetAnimals, targetMobs, targetInvisible); } @Override public String getInfo() { return this.mode.getOptions()[(int) this.mode.getInput()]; } @Override public void guiUpdate() { Utils.correctValue(minCPS, maxCPS); Utils.correctValue(attackRange, preAimRange); } private void attack() { if (target != null && mc.currentScreen == null) { if (RayCast.isToggled()) { final MovingObjectPosition hitResult = RotationUtils.rayCastStrict(RotationHandler.getRotationYaw(), RotationHandler.getRotationPitch(), (float) attackRange.getInput()); if (hitResult.typeOfHit != MovingObjectPosition.MovingObjectType.ENTITY || hitResult.entityHit != target) return; } this.attackEntity(target); if (mc.thePlayer.fallDistance > 0.0f && !mc.thePlayer.onGround && !mc.thePlayer.isOnLadder() && !mc.thePlayer.isInWater() && !mc.thePlayer.isPotionActive(Potion.blindness) && mc.thePlayer.ridingEntity == null) { mc.thePlayer.onCriticalHit(target); } // EnchantmentHelper#getModifierForCreature() if (EnchantmentHelper.func_152377_a(mc.thePlayer.getHeldItem(), target.getCreatureAttribute()) > 0.0f) { mc.thePlayer.onEnchantmentCritical(target); PacketUtils.sendPacket(new C0APacketAnimation()); } } } private void attackEntity(final Entity target) { Utils.attackEntity(target, true); this.attackTimer.reset(); } @Override public void onDisable() { target = null; targets.clear(); aiming = false; blocking = false; if (wasBlocking) { int autoBlock = (int) this.autoBlockMode.getInput(); switch (autoBlock) { case 2: // grim 1.8 case 3: // grim 1.12 ((KeyBindingAccessor) mc.gameSettings.keyBindUseItem).setPressed(false); break; case 1: // watchdog PacketUtils.sendPacket(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN)); break; } } wasBlocking = false; autoBlock$watchdog$blockingTime = 0; } @SubscribeEvent public void onRotation(RotationEvent event) { if (minCPS.getInput() > maxCPS.getInput()) { minCPS.setValue(minCPS.getInput() - 1); } if (ModuleManager.scaffold.isEnabled()) return; if (Blink.isBlinking()) return; if (ModuleManager.autoGapple != null && ModuleManager.autoGapple.disableKillAura.isToggled() && ModuleManager.autoGapple.working) { return; } // Gets all entities in specified range, sorts them using your specified sort mode, and adds them to target list this.sortTargets(); if (target == null) { lastYaw = event.getYaw(); lastPitch = event.getPitch(); } aiming = !targets.isEmpty(); blocking = autoBlock.isToggled() && aiming && Utils.holdingSword(); if (aiming) { switch ((int) mode.getInput()) { case 0: if (!targets.isEmpty()) { target = targets.get(0); } else { target = null; } break; case 1: if (switchTimer.hasTimeElapsed((int) switchDelay.getInput(), true)) { targetIndex = (targetIndex + 1) % targets.size(); } if (targetIndex < targets.size()) { target = targets.get(targetIndex); } else { target = null; } break; } float yaw = RotationHandler.getRotationYaw(); float pitch = RotationHandler.getRotationPitch(); final double minRotationSpeed = this.rotationSpeed.getInput(); final double maxRotationSpeed = this.rotationSpeed.getInput(); final float rotationSpeed = (float) Utils.randomizeDouble(minRotationSpeed, maxRotationSpeed); switch ((int) rotationMode.getInput()) { case 0: if (target != null) { aimSimulator.setNearest(false, 1); Pair<Float, Float> aimResult = aimSimulator.getRotation(target); yaw = aimResult.first(); pitch = aimResult.second(); } break; case 1: if (target != null) { aimSimulator.setNearest(true, 1.0); Pair<Float, Float> aimResult = aimSimulator.getRotation(target); yaw = aimResult.first(); pitch = aimResult.second(); } } if (rotationSpeed == this.rotationSpeed.getMax()) { event.setYaw(lastYaw = yaw); event.setPitch(lastPitch = pitch); } else { event.setYaw(lastYaw = AimSimulator.rotMove(yaw, lastYaw, rotationSpeed)); event.setPitch(lastPitch = AimSimulator.rotMove(pitch, lastPitch, rotationSpeed)); } event.setMoveFix(RotationHandler.MoveFix.values()[(int) moveFixMode.getInput()]); if (aimSimulator.getHitPos().distanceTo(Utils.getEyePos()) > attackRange.getInput()) return; if (attackTimer.hasTimeElapsed(cps, true)) { final int maxValue = (int) ((minCPS.getMax() - maxCPS.getInput()) * 5.0); final int minValue = (int) ((minCPS.getMax() - minCPS.getInput()) * 5.0); cps = Utils.randomizeInt(minValue, maxValue); attack(); } } else { attackTimer.reset(); target = null; } } @SubscribeEvent public void onPreMotion(PreMotionEvent event) { int autoBlock = (int) autoBlockMode.getInput(); if (blocking) { switch (autoBlock) { case 0: // fake break; case 1: // watchdog if (autoBlock$watchdog$blockingTime < 10 || !fixNoSlowFlag.isToggled()) { PacketUtils.sendPacket(new C02PacketUseEntity(target, C02PacketUseEntity.Action.INTERACT)); PacketUtils.sendPacket(new C08PacketPlayerBlockPlacement(mc.thePlayer.getHeldItem())); wasBlocking = true; autoBlock$watchdog$blockingTime++; } else { if (wasBlocking) { PacketUtils.sendPacket(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN)); } wasBlocking = false; autoBlock$watchdog$blockingTime = 0; } break; case 3: // grim 1.12 if (SlotHandler.getHeldItem() != null && mc.thePlayer.getHeldItem().getItem() instanceof ItemSword) { PacketUtils.sendPacket(new C0FPacketConfirmTransaction(Utils.randomizeInt(0, 2147483647), (short) Utils.randomizeInt(0, -32767), true)); PacketUtils.sendPacket(new C0APacketAnimation()); mc.playerController.sendUseItem(mc.thePlayer, mc.theWorld, mc.thePlayer.getHeldItem()); wasBlocking = true; } break; } } else if (wasBlocking && autoBlock == 2 || autoBlock == 3) { ((KeyBindingAccessor) mc.gameSettings.keyBindUseItem).setPressed(false); wasBlocking = false; } else if (wasBlocking && autoBlock == 1) { PacketUtils.sendPacketNoEvent(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN)); wasBlocking = false; } } @SubscribeEvent public void onPostMotion(PostMotionEvent event) { if (blocking) { if ((int) autoBlockMode.getInput() == 2) { // Grim 1.8 mc.playerController.sendUseItem(mc.thePlayer, mc.theWorld, SlotHandler.getHeldItem()); } } } public void sortTargets() { targets.clear(); for (Entity entity : mc.theWorld.getLoadedEntityList()) { if (entity instanceof EntityLivingBase) { EntityLivingBase entityLivingBase = (EntityLivingBase) entity; if (mc.thePlayer.getDistanceToEntity(entity) <= preAimRange.getInput() && isValid(entity) && mc.thePlayer != entityLivingBase && !Utils.isFriended(entityLivingBase.getName()) && !AntiBot.isBot(entity)) { targets.add(entityLivingBase); } } } switch ((int) sortMode.getInput()) { case 0: // Distance targets.sort(Comparator.comparingDouble(mc.thePlayer::getDistanceToEntity)); break; case 1: // Hurt Time targets.sort(Comparator.comparingInt(entity -> entity.hurtTime)); break; case 2: // Health targets.sort(Comparator.comparingDouble(EntityLivingBase::getHealth)); break; case 3: // Armor targets.sort(Comparator.comparingInt(EntityLivingBase::getTotalArmorValue)); break; } } public boolean isValid(Entity entity) { if (entity instanceof EntityPlayer && targetPlayer.isToggled() && !entity.isInvisible() && mc.thePlayer.canEntityBeSeen(entity)) return true; if (entity instanceof EntityPlayer && targetInvisible.isToggled() && entity.isInvisible()) return true; if(entity instanceof EntityPlayer && ThroughWalls.isToggled() && !mc.thePlayer.canEntityBeSeen(entity)) return true; if (entity instanceof EntityAnimal && targetAnimals.isToggled()) return true; if (entity instanceof EntityMob && targetMobs.isToggled()) return true; return entity.isInvisible() && targetInvisible.isToggled(); } }
0
0.969044
1
0.969044
game-dev
MEDIA
0.958998
game-dev
0.987482
1
0.987482
2006-Scape/2006Scape
1,676
2006Scape Server/src/main/java/com/rs2/game/objects/impl/OpenObject.java
package com.rs2.game.objects.impl; import com.rs2.GameEngine; import com.rs2.game.objects.ObjectDefaults; import com.rs2.game.objects.Objects; import com.rs2.game.players.Player; import com.rs2.world.clip.Region; /** * Feb 17, 2018 : 6:44:26 AM * OpenObject.java * * @author Andrew (Mr Extremez) */ public class OpenObject { /** * Object old * Object new */ private static final int[][] OBJECT_DATA = { { 375, 378 }, { 6910, 378 }, { 3193, 3194 }, { 2693, 3194 }, { 388, 389 }, { 350, 351 }, { 348, 349 }, { 5622, 5623 }, { 2612, 2613 }, { 352, 353 }, { 398, 399 }, { 376, 379 } }; public static void interactObject(Player player, int objectType) { for (final int[] element : OBJECT_DATA) { if (objectType == element[0]) { GameEngine.objectHandler.placeObject(new Objects(element[1], player.objectX, player.objectY, player.getH(), ObjectDefaults.getObjectFace(player, objectType), 10, 0)); Region.addObject(element[1], player.objectX, player.objectY, player.getH(), ObjectDefaults.getObjectFace(player, objectType), 10, false); player.startAnimation(832); } else if (objectType == element[1]) { GameEngine.objectHandler.placeObject(new Objects(element[0], player.objectX, player.objectY, player.getH(), ObjectDefaults.getObjectFace(player, objectType), 10, 0)); Region.addObject(element[0], player.objectX, player.objectY, player.getH(), ObjectDefaults.getObjectFace(player, objectType), 10, false); player.startAnimation(832); } } } }
0
0.516771
1
0.516771
game-dev
MEDIA
0.803969
game-dev
0.825877
1
0.825877
haoran1062/so101-autogen
13,886
src/scene/object_loader.py
# -*- coding: utf-8 -*- """ Object Loader - Manages the loading of objects into the scene. """ import os import numpy as np from typing import Dict, Any, List, Optional import logging # Isaac Sim imports from isaacsim.core.api import World from isaacsim.core.prims import RigidPrim from isaacsim.core.utils.stage import add_reference_to_stage from isaacsim.core.prims import SingleRigidPrim import omni.usd from pxr import Sdf, Gf, UsdGeom from .random_generator import RandomPositionGenerator # Virtual plate object class for placement detection when the actual USD is unavailable. class VirtualPlateObject: """A virtual plate object for placement detection when the actual USD is not available.""" def __init__(self, position, radius=0.1, height=0.02): self.position = np.array(position) self.radius = radius self.height = height self.name = "virtual_plate_object" print(f"🍽️ Virtual plate object initialized: Position {self.position.tolist()}, Radius {self.radius}m, Height {self.height}m") def get_world_pose(self): """Returns the position and an identity quaternion.""" return self.position, np.array([1.0, 0.0, 0.0, 0.0]) # Position and identity quaternion def set_world_pose(self, position, orientation=np.array([1.0, 0.0, 0.0, 0.0])): """Sets the world pose - supports position reset.""" self.position = np.array(position) print(f"🍽️ Virtual plate position updated: [{self.position[0]:.4f}, {self.position[1]:.4f}, {self.position[2]:.4f}]") def get_linear_velocity(self): """Returns a zero velocity vector, indicating it is stationary.""" return np.array([0.0, 0.0, 0.0]) class ObjectLoader: """ Object Loader Loads oranges and the plate into the scene, following the methodology of the original main script. """ def __init__(self, config: Dict[str, Any], project_root: str): """ Initializes the ObjectLoader. Args: config: Scene configuration. project_root: The root path of the project. """ self.config = config self.project_root = project_root # Orange configuration oranges_config = config.get('scene', {}).get('oranges', {}) self.orange_models = oranges_config.get('models', ["Orange001", "Orange002", "Orange003"]) self.orange_usd_paths = oranges_config.get('usd_paths', [ "assets/objects/Orange001/Orange001.usd", "assets/objects/Orange002/Orange002.usd", "assets/objects/Orange003/Orange003.usd" ]) self.orange_count = oranges_config.get('count', 3) self.orange_mass = oranges_config.get('physics', {}).get('mass', 0.15) # Plate configuration plate_config = config.get('scene', {}).get('plate', {}) self.plate_usd_path = plate_config.get('usd_path', 'assets/objects/Plate/Plate.usd') self.plate_position = plate_config.get('position', [0.25, -0.15, 0.1]) self.plate_scale = plate_config.get('scale', 1.0) self.use_virtual_plate = plate_config.get('use_virtual', True) self.virtual_plate_config = plate_config.get('virtual_config', {}) # Random position generator generation_config = oranges_config.get('generation', {}) self.position_generator = RandomPositionGenerator(generation_config) # Store loaded objects self.orange_objects = {} self.orange_reset_positions = {} self.plate_object = None print(f"✅ Object Loader initialized.") print(f" Number of oranges: {self.orange_count}") print(f" Orange models: {self.orange_models}") print(f" Plate position: {self.plate_position}") print(f" Using virtual plate: {self.use_virtual_plate}") def load_orange(self, world: World, usd_path: str, prim_path: str, position: List[float], name: str, mass: float = 0.15): """ Loads a single orange into the scene. """ full_usd_path = os.path.join(self.project_root, usd_path) if not os.path.exists(full_usd_path): print(f"❌ Orange USD file not found: {full_usd_path}") return None try: print(f"🔧 Loading orange USD: {full_usd_path}") # Step 1: Load the USD to the stage add_reference_to_stage(usd_path=full_usd_path, prim_path=prim_path) print(f"✅ Orange USD loaded to stage: {prim_path}") # Step 2: Add as a SingleRigidPrim orange = world.scene.add( SingleRigidPrim( prim_path=prim_path, name=name, position=position, mass=mass # 150g mass for the orange ) ) print(f"✅ Orange loaded successfully: {name} at position {position} with mass {mass}kg") return orange except Exception as e: print(f"❌ Failed to load orange {name}: {e}") import traceback print(f"Detailed error: {traceback.format_exc()}") return None def load_oranges(self, world: World) -> Dict[str, Any]: """ Loads all oranges into the scene. """ try: print(f"🍊 Loading {self.orange_count} oranges for the grasp test...") # Generate random positions print(f"🎲 Generating {self.orange_count} random positions for oranges...") random_positions = self.position_generator.generate_random_orange_positions(self.orange_count) # Ensure at least 3 positions are set for compatibility orange1_reset_pos = random_positions[0] if len(random_positions) > 0 else [0.2, 0.1, 0.1] orange2_reset_pos = random_positions[1] if len(random_positions) > 1 else [0.25, 0.15, 0.1] orange3_reset_pos = random_positions[2] if len(random_positions) > 2 else [0.15, 0.05, 0.1] positions = [orange1_reset_pos, orange2_reset_pos, orange3_reset_pos] for i, pos in enumerate(positions[:3]): print(f"🍊 Orange {i+1} random position: [{pos[0]:.3f}, {pos[1]:.3f}, {pos[2]:.3f}]") # Load the oranges orange_objects = {} orange_reset_positions = {} for i in range(min(self.orange_count, len(self.orange_usd_paths))): usd_path = self.orange_usd_paths[i] model_name = self.orange_models[i] prim_path = f"/World/orange{i+1}" object_name = f"orange{i+1}_object" position = positions[i] # Load using the helper function orange = self.load_orange(world, usd_path, prim_path, position, object_name, self.orange_mass) if orange is not None: orange_objects[object_name] = orange orange_reset_positions[object_name] = position print(f"✅ Orange loaded: {object_name}") self.orange_objects = orange_objects self.orange_reset_positions = orange_reset_positions return { 'objects': orange_objects, 'reset_positions': orange_reset_positions } except Exception as e: print(f"❌ Failed to load oranges: {e}") import traceback print(f"Detailed error: {traceback.format_exc()}") return {'objects': {}, 'reset_positions': {}} def load_plate(self, world: World) -> Optional[Any]: """ Loads the plate into the scene. """ try: print("📦 Loading the plate...") # Create a virtual plate object for placement detection. print("🔧 Creating a virtual plate object for placement detection...") # Use plate position from the configuration. virtual_config = self.virtual_plate_config plate_center = virtual_config.get('position', [0.25, -0.15, 0.005]) plate_radius = virtual_config.get('radius', 0.1) plate_height = virtual_config.get('height', 0.02) plate_object = VirtualPlateObject(plate_center, plate_radius, plate_height) print(f"✅ Virtual plate object created: Position {plate_center}, Radius {plate_radius}m, Height {plate_height}m") # If the actual plate USD file exists, attempt to load it. full_plate_usd_path = os.path.join(self.project_root, self.plate_usd_path) if os.path.exists(full_plate_usd_path): try: print(f"🔧 Attempting to load actual plate USD: {full_plate_usd_path}") # Step 1: Load the USD to the stage. add_reference_to_stage(usd_path=full_plate_usd_path, prim_path="/World/plate") print("✅ Plate USD loaded to stage.") # Step 2: Set the scale. stage = omni.usd.get_context().get_stage() plate_prim = stage.GetPrimAtPath("/World/plate") if plate_prim.IsValid(): xformable = UsdGeom.Xformable(plate_prim) existing_ops = xformable.GetOrderedXformOps() scale_op = None for op in existing_ops: if op.GetOpName() == "xformOp:scale": scale_op = op break if scale_op is None: scale_op = xformable.AddScaleOp() scale_op.Set(Gf.Vec3f(self.plate_scale, self.plate_scale, self.plate_scale)) print(f"✅ Plate scale set to: {self.plate_scale}") # Step 3: Add as a SingleRigidPrim. actual_plate = world.scene.add( SingleRigidPrim( prim_path="/World/plate", name="plate_object", position=plate_center, # Use the corrected position mass=0.5 ) ) # If the actual plate is loaded successfully, use it. plate_object = actual_plate print(f"✅ Actual plate loaded: Position {plate_center}, Scale {self.plate_scale}") except Exception as e: print(f"❌ Failed to load actual plate: {e}") import traceback print(f"Detailed error: {traceback.format_exc()}") print("🔄 Continuing with the virtual plate object.") else: print(f"⚠️ Plate USD file not found: {full_plate_usd_path}") print("🔄 Using virtual plate object for placement detection.") self.plate_object = plate_object return plate_object except Exception as e: print(f"❌ Failed to load plate: {e}") import traceback print(f"Detailed error: {traceback.format_exc()}") return None def regenerate_orange_positions(self, world: World): """ Regenerates random positions for the oranges. """ if not self.orange_objects: print("⚠️ No orange objects to reposition.") return print("🔄 Regenerating orange positions...") # Generate new orange positions. print("🎲 Generating new positions for the oranges.") new_positions = self.position_generator.generate_random_orange_positions(len(self.orange_objects)) # Move oranges to their new positions. repositioned_count = 0 for i, (name, orange_obj) in enumerate(self.orange_objects.items()): if i < len(new_positions) and orange_obj is not None: try: new_pos = new_positions[i] orange_obj.set_world_pose( position=np.array(new_pos), orientation=np.array([1.0, 0.0, 0.0, 0.0]) ) orange_obj.set_linear_velocity(np.array([0.0, 0.0, 0.0])) orange_obj.set_angular_velocity(np.array([0.0, 0.0, 0.0])) # Update the reset position. self.orange_reset_positions[name] = new_pos print(f"✅ {name} moved to new random position: [{new_pos[0]:.3f}, {new_pos[1]:.3f}, {new_pos[2]:.3f}]") repositioned_count += 1 except Exception as e: print(f"❌ Failed to update position for {name}: {e}") print(f"🎲 Random repositioning complete. Successfully moved {repositioned_count} oranges.") def get_orange_objects(self) -> Dict[str, Any]: """Gets the dictionary of orange objects.""" return self.orange_objects def get_orange_reset_positions(self) -> Dict[str, List[float]]: """Gets the dictionary of orange reset positions.""" return self.orange_reset_positions def get_plate_object(self) -> Any: """Gets the plate object.""" return self.plate_object
0
0.736155
1
0.736155
game-dev
MEDIA
0.189928
game-dev
0.895789
1
0.895789
OpenApoc/OpenApoc
4,735
tools/extractors/extract_unit_animation_pack_egg.cpp
#include "framework/data.h" #include "framework/framework.h" #include "game/state/gamestate.h" #include "game/state/rules/battle/battleunitanimationpack.h" #include "game/state/shared/agent.h" #include "tools/extractors/extractors.h" namespace OpenApoc { sp<BattleUnitAnimationPack::AnimationEntry> makeUpEggAnimationEntry(int from, int count, int fromB, int countB, Vec2<int> offsetEgg, Vec2<int> offsetTube, bool first = false) { auto e = mksp<BattleUnitAnimationPack::AnimationEntry>(); bool noHead = count == 0; Vec2<int> offset; if (noHead) { from = fromB; count = countB; } for (int i = 0; i < count; i++) { e->frames.push_back(BattleUnitAnimationPack::AnimationEntry::Frame()); for (int j = 1; j <= (noHead ? 1 : 2); j++) { int part_idx = j; int frame = from + i; auto part_type = BattleUnitAnimationPack::AnimationEntry::Frame::UnitImagePart::Shadow; switch (part_idx) { case 1: offset = offsetEgg; part_type = BattleUnitAnimationPack::AnimationEntry::Frame::UnitImagePart::Body; frame = fromB + i; while (frame >= fromB + countB) { frame -= countB; } break; case 2: offset = offsetTube; part_type = BattleUnitAnimationPack::AnimationEntry::Frame::UnitImagePart::Helmet; break; default: LogError("If you reached this then OpenApoc programmers made a mistake"); return e; } e->frames[i].unit_image_draw_order.push_back(part_type); e->frames[i].unit_image_parts[part_type] = BattleUnitAnimationPack::AnimationEntry::Frame::InfoBlock( frame, offset.x, (j == 2 ? (first ? -4 : 9) : 0) + offset.y); } } e->is_overlay = false; e->frame_count = e->frames.size(); e->units_per_100_frames = 100; return e; } void extractAnimationPackEggInternal(sp<BattleUnitAnimationPack> p, bool first) { static const std::map<Vec2<int>, int> offset_dir_map = { {{0, -1}, 4}, {{1, -1}, 5}, {{1, 0}, 6}, {{1, 1}, 7}, {{0, 1}, 0}, {{-1, 1}, 1}, {{-1, 0}, 2}, {{-1, -1}, 3}, }; for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { // 0, 0 facing does not exist if (x == 0 && y == 0) continue; // Standing state: p->standart_animations[{ItemWieldMode::None, HandState::AtEase, MovementState::None, BodyState::Standing}][{x, y}] = makeUpEggAnimationEntry(offset_dir_map.at({x, y}), 1, first ? 0 : 1, 1, {0, 0}, first ? Vec2<int>{0, 4} : Vec2<int>{-12, -8}, first); // Aiming state: p->standart_animations[{ItemWieldMode::None, HandState::Aiming, MovementState::None, BodyState::Standing}][{x, y}] = makeUpEggAnimationEntry(offset_dir_map.at({x, y}), 1, first ? 0 : 1, 1, {0, 0}, first ? Vec2<int>{0, 4} : Vec2<int>{-12, -8}, first); // Firing state: p->standart_animations[{ItemWieldMode::None, HandState::Firing, MovementState::None, BodyState::Standing}][{x, y}] = makeUpEggAnimationEntry(offset_dir_map.at({x, y}), 1, first ? 0 : 1, 1, {0, 0}, first ? Vec2<int>{0, 4} : Vec2<int>{-12, -8}, first); // Dying state: p->body_state_animations[{ItemWieldMode::None, HandState::AtEase, MovementState::None, BodyState::Standing, BodyState::Dead}][{x, y}] = makeUpEggAnimationEntry(0, 0, first ? 2 : 9, 7, {0, 0}, {0, 0}); p->body_state_animations[{ItemWieldMode::None, HandState::AtEase, MovementState::None, BodyState::Downed, BodyState::Dead}][{x, y}] = makeUpEggAnimationEntry(0, 0, first ? 2 : 9, 7, {0, 0}, {0, 0}); // Dead state: p->standart_animations[{ItemWieldMode::None, HandState::AtEase, MovementState::None, BodyState::Dead}][{x, y}] = makeUpEggAnimationEntry(0, 0, first ? 8 : 15, 1, {0, 0}, {0, 0}); // Downed state: (same as standing) p->standart_animations[{ItemWieldMode::None, HandState::AtEase, MovementState::None, BodyState::Downed}][{x, y}] = makeUpEggAnimationEntry(offset_dir_map.at({x, y}), 1, first ? 0 : 1, 1, {0, 0}, first ? Vec2<int>{0, 4} : Vec2<int>{-12, -8}, first); } } } void InitialGameStateExtractor::extractAnimationPackEgg(sp<BattleUnitAnimationPack> p, bool first) const { extractAnimationPackEggInternal(p, first); } } // namespace OpenApoc
0
0.688491
1
0.688491
game-dev
MEDIA
0.967821
game-dev
0.950801
1
0.950801
Goob-Station/Goob-Station-MRP
2,631
Content.Server/Anomaly/Components/AnomalousParticleComponent.cs
using Content.Shared.Anomaly; using Content.Shared.Anomaly.Components; namespace Content.Server.Anomaly.Components; /// <summary> /// This is used for projectiles which affect anomalies through colliding with them. /// </summary> [RegisterComponent, Access(typeof(SharedAnomalySystem))] public sealed partial class AnomalousParticleComponent : Component { /// <summary> /// The type of particle that the projectile /// imbues onto the anomaly on contact. /// </summary> [DataField(required: true)] public AnomalousParticleType ParticleType; /// <summary> /// The fixture that's checked on collision. /// </summary> [DataField] public string FixtureId = "projectile"; /// <summary> /// The amount that the <see cref="AnomalyComponent.Severity"/> increases by when hit /// of an anomalous particle of <seealso cref="AnomalyComponent.SeverityParticleType"/>. /// </summary> [DataField] public float SeverityPerSeverityHit = 0.025f; /// <summary> /// The amount that the <see cref="AnomalyComponent.Stability"/> increases by when hit /// of an anomalous particle of <seealso cref="AnomalyComponent.DestabilizingParticleType"/>. /// </summary> [DataField] public float StabilityPerDestabilizingHit = 0.04f; /// <summary> /// The amount that the <see cref="AnomalyComponent.Stability"/> increases by when hit /// of an anomalous particle of <seealso cref="AnomalyComponent.DestabilizingParticleType"/>. /// </summary> [DataField] public float HealthPerWeakeningeHit = -0.05f; /// <summary> /// The amount that the <see cref="AnomalyComponent.Stability"/> increases by when hit /// of an anomalous particle of <seealso cref="AnomalyComponent.DestabilizingParticleType"/>. /// </summary> [DataField] public float StabilityPerWeakeningeHit = -0.1f; /// <summary> /// If this is true then the particle will always affect the stability of the anomaly. /// </summary> [DataField] public bool DestabilzingOverride = false; /// <summary> /// If this is true then the particle will always affect the weakeness of the anomaly. /// </summary> [DataField] public bool WeakeningOverride = false; /// <summary> /// If this is true then the particle will always affect the severity of the anomaly. /// </summary> [DataField] public bool SeverityOverride = false; /// <summary> /// If this is true then the particle will always affect the behaviour. /// </summary> [DataField] public bool TransmutationOverride = false; }
0
0.545074
1
0.545074
game-dev
MEDIA
0.967044
game-dev
0.723596
1
0.723596
PhaserEditor2D/PhaserEditor2D-v3
1,053
source/editor/plugins/phasereditor2d.scene/src/ui/sceneobjects/nineslice/ThreeSliceEditorSupport.ts
namespace phasereditor2d.scene.ui.sceneobjects { export class ThreeSliceEditorSupport extends BaseImageEditorSupport<ThreeSlice> { constructor(obj: ThreeSlice, scene: Scene) { super(ThreeSliceExtension.getInstance(), obj, scene, true, false, false, false); this.addComponent( new AlphaSingleComponent(obj), new TintSingleComponent(obj), new SizeComponent(obj), new ThreeSliceComponent(obj)); } setInteractive() { this.getObject().setInteractive(interactive_getAlpha_RenderTexture); } isCustom_SizeComponent_buildSetObjectPropertiesCodeDOM(): boolean { return true; } getSizeComponentGeneratesUpdateDisplayOrigin(): boolean { return false; } onUpdateAfterSetTexture(): void { const obj = this.getObject(); obj.updateVertices(); (obj as any).updateUVs(); } } }
0
0.73131
1
0.73131
game-dev
MEDIA
0.885221
game-dev
0.877839
1
0.877839
GiganticMinecraft/SeichiAssist
4,863
src/main/scala/com/github/unchama/seichiassist/menus/skill/PremiumPointTransactionHistoryMenu.scala
package com.github.unchama.seichiassist.menus.skill import cats.effect.IO import com.github.unchama.itemstackbuilder.{ IconItemStackBuilder, SkullItemStackBuilder, SkullOwnerReference } import com.github.unchama.menuinventory.router.CanOpen import com.github.unchama.menuinventory.slot.button.Button import com.github.unchama.menuinventory.{ChestSlotRef, Menu, MenuFrame, MenuSlotLayout} import com.github.unchama.seichiassist.SkullOwners import com.github.unchama.seichiassist.menus.CommonButtons import com.github.unchama.seichiassist.subsystems.donate.DonatePremiumPointAPI import com.github.unchama.seichiassist.subsystems.donate.domain.{Obtained, Used} import com.github.unchama.seichiassist.subsystems.playerheadskin.PlayerHeadSkinAPI import net.md_5.bungee.api.ChatColor._ import org.bukkit.ChatColor.{GOLD, GREEN, RESET} import org.bukkit.Material import org.bukkit.entity.Player object PremiumPointTransactionHistoryMenu { class Environment( implicit val ioCanOpenActiveSkillEffectMenu: IO CanOpen ActiveSkillEffectMenu.type, val ioCanOpenTransactionHistoryMenu: IO CanOpen PremiumPointTransactionHistoryMenu, val donateAPI: DonatePremiumPointAPI[IO], implicit val playerHeadSkinAPI: PlayerHeadSkinAPI[IO, Player] ) } case class PremiumPointTransactionHistoryMenu(pageNumber: Int) extends Menu { import com.github.unchama.menuinventory.syntax._ import eu.timepit.refined.auto._ override type Environment = PremiumPointTransactionHistoryMenu.Environment override val frame: MenuFrame = MenuFrame(4.chestRows, s"$BLUE${BOLD}プレミアムエフェクト購入履歴") def buttonToTransferTo(pageNumber: Int, skullOwnerReference: SkullOwnerReference)( implicit environment: Environment ): Button = { import environment._ CommonButtons.transferButton( new SkullItemStackBuilder(skullOwnerReference), s"${pageNumber}ページ目へ", PremiumPointTransactionHistoryMenu(pageNumber) ) } def computeDynamicParts(player: Player)( implicit environment: PremiumPointTransactionHistoryMenu.Environment ): IO[List[(Int, Button)]] = { import environment._ val uuid = player.getUniqueId for { purchaseHistory <- donateAPI.fetchGrantHistory(uuid) usageHistory <- donateAPI.fetchUseHistory(uuid) } yield { val entriesPerPage = 3 * 9 val history = (purchaseHistory ++ usageHistory).toList.sortBy(_.timestamp) val slicedHistory = history.slice((pageNumber - 1) * entriesPerPage, pageNumber * entriesPerPage) val historySection = slicedHistory.zipWithIndex.map { case (transaction, index) => val itemStack = transaction match { case Obtained(amount, date) => new IconItemStackBuilder(Material.DIAMOND) .title(s"$AQUA$UNDERLINE${BOLD}寄付") .lore( List( s"${RESET.toString}${GREEN}金額:${amount.value * 100}", s"$RESET${GREEN}プレミアムエフェクトポイント:+${amount.value}", s"$RESET${GREEN}日時:$date" ) ) .build() case Used(amount, date, forPurchaseOf) => { new IconItemStackBuilder(forPurchaseOf.materialOnUI).title( s"$RESET${YELLOW}購入エフェクト:${forPurchaseOf.nameOnUI}" ) }.lore( s"$RESET${GOLD}プレミアムエフェクトポイント: -${amount.value}", s"$RESET${GOLD}日時:$date" ).build() } (index, Button(itemStack, Nil)) } val previousPageButtonSection = if (pageNumber > 1) Seq(ChestSlotRef(3, 7) -> buttonToTransferTo(pageNumber - 1, SkullOwners.MHF_ArrowUp)) else Seq() val nextPageButtonSection = if (history.drop(pageNumber * entriesPerPage).nonEmpty) Seq( ChestSlotRef(3, 8) -> buttonToTransferTo(pageNumber + 1, SkullOwners.MHF_ArrowDown) ) else Seq() historySection ++ previousPageButtonSection ++ nextPageButtonSection } } def constantParts( implicit environment: PremiumPointTransactionHistoryMenu.Environment ): Map[Int, Button] = { import environment._ val moveBackButton = CommonButtons.transferButton( new SkullItemStackBuilder(SkullOwners.MHF_ArrowLeft), "整地スキルエフェクト選択メニューへ", ActiveSkillEffectMenu ) Map(ChestSlotRef(3, 0) -> moveBackButton) } override def computeMenuLayout(player: Player)( implicit environment: PremiumPointTransactionHistoryMenu.Environment ): IO[MenuSlotLayout] = { for { dynamicParts <- computeDynamicParts(player) } yield MenuSlotLayout(constantParts ++ dynamicParts) } }
0
0.896496
1
0.896496
game-dev
MEDIA
0.650393
game-dev
0.974969
1
0.974969
MATTYOneInc/AionEncomBase_Java8
3,629
AL-Game/data/scripts/system/handlers/quest/eltnen/_1385RescuingGriffo.java
/* * This file is part of aion-unique <aion-unique.org>. * * aion-unique is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * aion-unique is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with aion-unique. If not, see <http://www.gnu.org/licenses/>. */ package quest.eltnen; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.questEngine.model.QuestDialog; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; /** * @author MrPoke remod By Xitanium */ public class _1385RescuingGriffo extends QuestHandler { private final static int questId = 1385; public _1385RescuingGriffo() { super(questId); } @Override public void register() { qe.registerQuestNpc(204028).addOnQuestStart(questId); qe.registerQuestNpc(204028).addOnTalkEvent(questId); qe.registerQuestNpc(204029).addOnTalkEvent(questId); qe.registerAddOnReachTargetEvent(questId); qe.registerAddOnLostTargetEvent(questId); } @Override public boolean onDialogEvent(QuestEnv env) { final Player player = env.getPlayer(); int targetId = 0; if (env.getVisibleObject() instanceof Npc) targetId = ((Npc) env.getVisibleObject()).getNpcId(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (targetId == 204028) { if (qs == null || qs.getStatus() == QuestStatus.NONE) { if (env.getDialog() == QuestDialog.START_DIALOG) return sendQuestDialog(env, 1011); else return sendQuestStartDialog(env); } else if (qs != null && qs.getStatus() == QuestStatus.START) { if (env.getDialog() == QuestDialog.START_DIALOG) return sendQuestDialog(env, 1693); else if (env.getDialogId() == 1009) { qs.setQuestVar(2); qs.setStatus(QuestStatus.REWARD); updateQuestStatus(env); return sendQuestEndDialog(env); } } else if (qs != null && qs.getStatus() == QuestStatus.REWARD) { return sendQuestEndDialog(env); } } else if (targetId == 204029) { if (qs != null && qs.getStatus() == QuestStatus.START && qs.getQuestVarById(0) == 0) { if (env.getDialog() == QuestDialog.START_DIALOG) return sendQuestDialog(env, 1352); else if (env.getDialog() == QuestDialog.STEP_TO_1) { return defaultStartFollowEvent(env, (Npc) env.getVisibleObject(), 1923.47f, 2541.46f, 355.61f, 0, 1); } } } return false; } @Override public boolean onLogOutEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs != null && qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); if (var == 1) { changeQuestStep(env, 1, 0, false); } } return false; } @Override public boolean onNpcReachTargetEvent(QuestEnv env) { return defaultFollowEndEvent(env, 1, 2, false); // reward } @Override public boolean onNpcLostTargetEvent(QuestEnv env) { return defaultFollowEndEvent(env, 1, 0, false); // 1 } }
0
0.837265
1
0.837265
game-dev
MEDIA
0.971624
game-dev
0.954194
1
0.954194
The-Cataclysm-Preservation-Project/TrinityCore
7,511
src/server/scripts/EasternKingdoms/zone_hinterlands.cpp
/* * This file is part of the TrinityCore 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, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Hinterlands SD%Complete: 100 SDComment: Quest support: 836 SDCategory: The Hinterlands EndScriptData */ /* ContentData npc_oox09hl EndContentData */ #include "ScriptMgr.h" #include "MotionMaster.h" #include "Player.h" #include "ScriptedEscortAI.h" namespace Hinterlands { /*###### ## npc_oox09hl ######*/ enum eOOX { SAY_OOX_START = 0, SAY_OOX_AGGRO = 1, SAY_OOX_AMBUSH = 2, SAY_OOX_AMBUSH_REPLY = 3, SAY_OOX_END = 4, QUEST_RESQUE_OOX_09 = 836, NPC_MARAUDING_OWL = 7808, NPC_VILE_AMBUSHER = 7809 }; class npc_oox09hl : public CreatureScript { public: npc_oox09hl() : CreatureScript("npc_oox09hl") { } struct npc_oox09hlAI : public EscortAI { npc_oox09hlAI(Creature* creature) : EscortAI(creature) { } void Reset() override { } void JustEngagedWith(Unit* who) override { if (who->GetEntry() == NPC_MARAUDING_OWL || who->GetEntry() == NPC_VILE_AMBUSHER) return; Talk(SAY_OOX_AGGRO); } void JustSummoned(Creature* summoned) override { summoned->GetMotionMaster()->MovePoint(0, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ()); } void QuestAccept(Player* player, Quest const* quest) override { if (quest->GetQuestId() == QUEST_RESQUE_OOX_09) { me->SetStandState(UNIT_STAND_STATE_STAND); me->SetFaction(player->GetTeam() == ALLIANCE ? FACTION_ESCORTEE_A_PASSIVE : FACTION_ESCORTEE_H_PASSIVE); Talk(SAY_OOX_START, player); EscortAI::Start(false, false, player->GetGUID(), quest); } } void WaypointReached(uint32 waypointId, uint32 /*pathId*/) override { switch (waypointId) { case 26: Talk(SAY_OOX_AMBUSH); break; case 43: Talk(SAY_OOX_AMBUSH); break; case 64: Talk(SAY_OOX_END); if (Player* player = GetPlayerForEscort()) player->GroupEventHappens(QUEST_RESQUE_OOX_09, me); break; } } void WaypointStarted(uint32 pointId, uint32 /*pathId*/) override { switch (pointId) { case 27: for (uint8 i = 0; i < 3; ++i) { const Position src = {147.927444f, -3851.513428f, 130.893f, 0}; Position dst = me->GetRandomPoint(src, 7.0f); DoSummon(NPC_MARAUDING_OWL, dst, 25000, TEMPSUMMON_CORPSE_TIMED_DESPAWN); } break; case 44: for (uint8 i = 0; i < 3; ++i) { const Position src = {-141.151581f, -4291.213867f, 120.130f, 0}; Position dst = me->GetRandomPoint(src, 7.0f); me->SummonCreature(NPC_VILE_AMBUSHER, dst, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 25000); } break; } } }; CreatureAI* GetAI(Creature* creature) const override { return new npc_oox09hlAI(creature); } }; /*###### ## npc_sharpbeak used by Entrys 43161 & 51125 ######*/ enum Sharpbeak { NPC_SHARPBEAK_CAMP = 43161, NPC_SHARPBEAK_JINTHAALOR = 51125, SPELL_EJECT_ALL_PASSENGERS = 50630 }; Position const campPath[] = { { -75.40077f, -4037.111f, 114.6418f }, { -68.80193f, -4034.235f, 123.6844f }, { -62.2031f, -4031.36f, 132.727f }, { -48.5851f, -4008.04f, 156.977f }, { -26.2691f, -3987.88f, 176.755f }, { 11.5087f, -3960.86f, 203.561f }, { 45.0087f, -3922.58f, 236.672f }, { 75.4427f, -3856.91f, 255.672f }, { 74.8351f, -3768.84f, 279.839f }, { -53.0104f, -3582.62f, 287.755f }, { -169.123f, -3582.08f, 282.866f }, { -241.8403f, -3625.01f, 247.4203f } }; uint32 const campPathSize = std::extent<decltype(campPath)>::value; Position const jinthaalorPath[] = { { -249.4681f, -3632.487f, 232.6947f }, { -241.606f, -3627.713f, 236.61870f }, { -235.6163f, -3624.076f, 239.6081f }, { -226.8698f, -3623.929f, 244.8882f }, { -193.6406f, -3618.776f, 244.8882f }, { -149.7292f, -3613.349f, 244.8882f }, { -103.8976f, -3623.828f, 238.0368f }, { -41.33681f, -3710.568f, 232.4109f }, { 6.201389f, -3739.243f, 214.2869f }, { 37.44097f, -3773.431f, 189.4650f }, { 44.21875f, -3884.991f, 177.7446f }, { 39.81424f, -3934.679f, 168.1627f }, { 32.17535f, -3983.781f, 166.1228f }, { 21.34896f, -4005.293f, 162.9598f }, { -5.734375f, -4028.695f, 149.0161f }, { -23.23611f, -4040.689f, 140.1189f }, { -35.45139f, -4047.543f, 133.2071f }, { -59.21181f, -4051.257f, 128.0297f }, { -76.90625f, -4040.207f, 126.0433f }, { -77.51563f, -4022.026f, 123.2135f } }; uint32 const jinthaalorPathSize = std::extent<decltype(jinthaalorPath)>::value; class npc_sharpbeak : public CreatureScript { public: npc_sharpbeak() : CreatureScript("npc_sharpbeak") { } struct npc_sharpbeak_AI : public ScriptedAI { npc_sharpbeak_AI(Creature* creature) : ScriptedAI(creature) { Initialize(); } void Initialize() { endPoint = 0; } void PassengerBoarded(Unit* /*who*/, int8 /*seatId*/, bool apply) override { if (!apply) return; switch (me->GetEntry()) { case NPC_SHARPBEAK_CAMP: me->GetMotionMaster()->MoveSmoothPath(campPathSize, campPath, campPathSize, false); endPoint = campPathSize; break; case NPC_SHARPBEAK_JINTHAALOR: me->GetMotionMaster()->MoveSmoothPath(jinthaalorPathSize, jinthaalorPath, jinthaalorPathSize, false, true); endPoint = jinthaalorPathSize; break; } } void MovementInform(uint32 type, uint32 pointId) override { if (type == EFFECT_MOTION_TYPE && pointId == endPoint) { DoCast(SPELL_EJECT_ALL_PASSENGERS); } } private: uint8 endPoint; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_sharpbeak_AI(creature); } }; } void AddSC_hinterlands() { using namespace Hinterlands; new npc_oox09hl(); new npc_sharpbeak(); }
0
0.850985
1
0.850985
game-dev
MEDIA
0.99354
game-dev
0.916814
1
0.916814
ketoo/NoahGameFrame
11,917
Dependencies/navigation/RecastRasterization.cpp
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #define _USE_MATH_DEFINES #include <math.h> #include <stdio.h> #include "Recast.h" #include "RecastAlloc.h" #include "RecastAssert.h" inline bool overlapBounds(const float* amin, const float* amax, const float* bmin, const float* bmax) { bool overlap = true; overlap = (amin[0] > bmax[0] || amax[0] < bmin[0]) ? false : overlap; overlap = (amin[1] > bmax[1] || amax[1] < bmin[1]) ? false : overlap; overlap = (amin[2] > bmax[2] || amax[2] < bmin[2]) ? false : overlap; return overlap; } inline bool overlapInterval(unsigned short amin, unsigned short amax, unsigned short bmin, unsigned short bmax) { if (amax < bmin) return false; if (amin > bmax) return false; return true; } static rcSpan* allocSpan(rcHeightfield& hf) { // If running out of memory, allocate new page and update the freelist. if (!hf.freelist || !hf.freelist->next) { // Create new page. // Allocate memory for the new pool. rcSpanPool* pool = (rcSpanPool*)rcAlloc(sizeof(rcSpanPool), RC_ALLOC_PERM); if (!pool) return 0; // Add the pool into the list of pools. pool->next = hf.pools; hf.pools = pool; // Add new items to the free list. rcSpan* freelist = hf.freelist; rcSpan* head = &pool->items[0]; rcSpan* it = &pool->items[RC_SPANS_PER_POOL]; do { --it; it->next = freelist; freelist = it; } while (it != head); hf.freelist = it; } // Pop item from in front of the free list. rcSpan* it = hf.freelist; hf.freelist = hf.freelist->next; return it; } static void freeSpan(rcHeightfield& hf, rcSpan* ptr) { if (!ptr) return; // Add the node in front of the free list. ptr->next = hf.freelist; hf.freelist = ptr; } static bool addSpan(rcHeightfield& hf, const int x, const int y, const unsigned short smin, const unsigned short smax, const unsigned char area, const int flagMergeThr) { int idx = x + y*hf.width; rcSpan* s = allocSpan(hf); if (!s) return false; s->smin = smin; s->smax = smax; s->area = area; s->next = 0; // Empty cell, add the first span. if (!hf.spans[idx]) { hf.spans[idx] = s; return true; } rcSpan* prev = 0; rcSpan* cur = hf.spans[idx]; // Insert and merge spans. while (cur) { if (cur->smin > s->smax) { // Current span is further than the new span, break. break; } else if (cur->smax < s->smin) { // Current span is before the new span advance. prev = cur; cur = cur->next; } else { // Merge spans. if (cur->smin < s->smin) s->smin = cur->smin; if (cur->smax > s->smax) s->smax = cur->smax; // Merge flags. if (rcAbs((int)s->smax - (int)cur->smax) <= flagMergeThr) s->area = rcMax(s->area, cur->area); // Remove current span. rcSpan* next = cur->next; freeSpan(hf, cur); if (prev) prev->next = next; else hf.spans[idx] = next; cur = next; } } // Insert new span. if (prev) { s->next = prev->next; prev->next = s; } else { s->next = hf.spans[idx]; hf.spans[idx] = s; } return true; } /// @par /// /// The span addition can be set to favor flags. If the span is merged to /// another span and the new @p smax is within @p flagMergeThr units /// from the existing span, the span flags are merged. /// /// @see rcHeightfield, rcSpan. bool rcAddSpan(rcContext* ctx, rcHeightfield& hf, const int x, const int y, const unsigned short smin, const unsigned short smax, const unsigned char area, const int flagMergeThr) { rcAssert(ctx); if (!addSpan(hf, x, y, smin, smax, area, flagMergeThr)) { ctx->log(RC_LOG_ERROR, "rcAddSpan: Out of memory."); return false; } return true; } // divides a convex polygons into two convex polygons on both sides of a line static void dividePoly(const float* in, int nin, float* out1, int* nout1, float* out2, int* nout2, float x, int axis) { float d[12]; for (int i = 0; i < nin; ++i) d[i] = x - in[i*3+axis]; int m = 0, n = 0; for (int i = 0, j = nin-1; i < nin; j=i, ++i) { bool ina = d[j] >= 0; bool inb = d[i] >= 0; if (ina != inb) { float s = d[j] / (d[j] - d[i]); out1[m*3+0] = in[j*3+0] + (in[i*3+0] - in[j*3+0])*s; out1[m*3+1] = in[j*3+1] + (in[i*3+1] - in[j*3+1])*s; out1[m*3+2] = in[j*3+2] + (in[i*3+2] - in[j*3+2])*s; rcVcopy(out2 + n*3, out1 + m*3); m++; n++; // add the i'th point to the right polygon. Do NOT add points that are on the dividing line // since these were already added above if (d[i] > 0) { rcVcopy(out1 + m*3, in + i*3); m++; } else if (d[i] < 0) { rcVcopy(out2 + n*3, in + i*3); n++; } } else // same side { // add the i'th point to the right polygon. Addition is done even for points on the dividing line if (d[i] >= 0) { rcVcopy(out1 + m*3, in + i*3); m++; if (d[i] != 0) continue; } rcVcopy(out2 + n*3, in + i*3); n++; } } *nout1 = m; *nout2 = n; } static bool rasterizeTri(const float* v0, const float* v1, const float* v2, const unsigned char area, rcHeightfield& hf, const float* bmin, const float* bmax, const float cs, const float ics, const float ich, const int flagMergeThr) { const int w = hf.width; const int h = hf.height; float tmin[3], tmax[3]; const float by = bmax[1] - bmin[1]; // Calculate the bounding box of the triangle. rcVcopy(tmin, v0); rcVcopy(tmax, v0); rcVmin(tmin, v1); rcVmin(tmin, v2); rcVmax(tmax, v1); rcVmax(tmax, v2); // If the triangle does not touch the bbox of the heightfield, skip the triagle. if (!overlapBounds(bmin, bmax, tmin, tmax)) return true; // Calculate the footprint of the triangle on the grid's y-axis int y0 = (int)((tmin[2] - bmin[2])*ics); int y1 = (int)((tmax[2] - bmin[2])*ics); y0 = rcClamp(y0, 0, h-1); y1 = rcClamp(y1, 0, h-1); // Clip the triangle into all grid cells it touches. float buf[7*3*4]; float *in = buf, *inrow = buf+7*3, *p1 = inrow+7*3, *p2 = p1+7*3; rcVcopy(&in[0], v0); rcVcopy(&in[1*3], v1); rcVcopy(&in[2*3], v2); int nvrow, nvIn = 3; for (int y = y0; y <= y1; ++y) { // Clip polygon to row. Store the remaining polygon as well const float cz = bmin[2] + y*cs; dividePoly(in, nvIn, inrow, &nvrow, p1, &nvIn, cz+cs, 2); rcSwap(in, p1); if (nvrow < 3) continue; // find the horizontal bounds in the row float minX = inrow[0], maxX = inrow[0]; for (int i=1; i<nvrow; ++i) { if (minX > inrow[i*3]) minX = inrow[i*3]; if (maxX < inrow[i*3]) maxX = inrow[i*3]; } int x0 = (int)((minX - bmin[0])*ics); int x1 = (int)((maxX - bmin[0])*ics); x0 = rcClamp(x0, 0, w-1); x1 = rcClamp(x1, 0, w-1); int nv, nv2 = nvrow; for (int x = x0; x <= x1; ++x) { // Clip polygon to column. store the remaining polygon as well const float cx = bmin[0] + x*cs; dividePoly(inrow, nv2, p1, &nv, p2, &nv2, cx+cs, 0); rcSwap(inrow, p2); if (nv < 3) continue; // Calculate min and max of the span. float smin = p1[1], smax = p1[1]; for (int i = 1; i < nv; ++i) { smin = rcMin(smin, p1[i*3+1]); smax = rcMax(smax, p1[i*3+1]); } smin -= bmin[1]; smax -= bmin[1]; // Skip the span if it is outside the heightfield bbox if (smax < 0.0f) continue; if (smin > by) continue; // Clamp the span to the heightfield bbox. if (smin < 0.0f) smin = 0; if (smax > by) smax = by; // Snap the span to the heightfield height grid. unsigned short ismin = (unsigned short)rcClamp((int)floorf(smin * ich), 0, RC_SPAN_MAX_HEIGHT); unsigned short ismax = (unsigned short)rcClamp((int)ceilf(smax * ich), (int)ismin+1, RC_SPAN_MAX_HEIGHT); if (!addSpan(hf, x, y, ismin, ismax, area, flagMergeThr)) return false; } } return true; } /// @par /// /// No spans will be added if the triangle does not overlap the heightfield grid. /// /// @see rcHeightfield bool rcRasterizeTriangle(rcContext* ctx, const float* v0, const float* v1, const float* v2, const unsigned char area, rcHeightfield& solid, const int flagMergeThr) { rcAssert(ctx); rcScopedTimer timer(ctx, RC_TIMER_RASTERIZE_TRIANGLES); const float ics = 1.0f/solid.cs; const float ich = 1.0f/solid.ch; if (!rasterizeTri(v0, v1, v2, area, solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr)) { ctx->log(RC_LOG_ERROR, "rcRasterizeTriangle: Out of memory."); return false; } return true; } /// @par /// /// Spans will only be added for triangles that overlap the heightfield grid. /// /// @see rcHeightfield bool rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/, const int* tris, const unsigned char* areas, const int nt, rcHeightfield& solid, const int flagMergeThr) { rcAssert(ctx); rcScopedTimer timer(ctx, RC_TIMER_RASTERIZE_TRIANGLES); const float ics = 1.0f/solid.cs; const float ich = 1.0f/solid.ch; // Rasterize triangles. for (int i = 0; i < nt; ++i) { const float* v0 = &verts[tris[i*3+0]*3]; const float* v1 = &verts[tris[i*3+1]*3]; const float* v2 = &verts[tris[i*3+2]*3]; // Rasterize. if (!rasterizeTri(v0, v1, v2, areas[i], solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr)) { ctx->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory."); return false; } } return true; } /// @par /// /// Spans will only be added for triangles that overlap the heightfield grid. /// /// @see rcHeightfield bool rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/, const unsigned short* tris, const unsigned char* areas, const int nt, rcHeightfield& solid, const int flagMergeThr) { rcAssert(ctx); rcScopedTimer timer(ctx, RC_TIMER_RASTERIZE_TRIANGLES); const float ics = 1.0f/solid.cs; const float ich = 1.0f/solid.ch; // Rasterize triangles. for (int i = 0; i < nt; ++i) { const float* v0 = &verts[tris[i*3+0]*3]; const float* v1 = &verts[tris[i*3+1]*3]; const float* v2 = &verts[tris[i*3+2]*3]; // Rasterize. if (!rasterizeTri(v0, v1, v2, areas[i], solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr)) { ctx->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory."); return false; } } return true; } /// @par /// /// Spans will only be added for triangles that overlap the heightfield grid. /// /// @see rcHeightfield bool rcRasterizeTriangles(rcContext* ctx, const float* verts, const unsigned char* areas, const int nt, rcHeightfield& solid, const int flagMergeThr) { rcAssert(ctx); rcScopedTimer timer(ctx, RC_TIMER_RASTERIZE_TRIANGLES); const float ics = 1.0f/solid.cs; const float ich = 1.0f/solid.ch; // Rasterize triangles. for (int i = 0; i < nt; ++i) { const float* v0 = &verts[(i*3+0)*3]; const float* v1 = &verts[(i*3+1)*3]; const float* v2 = &verts[(i*3+2)*3]; // Rasterize. if (!rasterizeTri(v0, v1, v2, areas[i], solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr)) { ctx->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory."); return false; } } return true; }
0
0.985786
1
0.985786
game-dev
MEDIA
0.711492
game-dev
0.997555
1
0.997555
TheFlyingFoool/DuckGameRebuilt
3,000
DuckGame/src/DuckGame/Tiles/CustomPlatform.cs
namespace DuckGame { [EditorGroup("Blocks|custom", EditorItemType.Custom)] [BaggedProperty("isInDemo", false)] public class CustomPlatform : AutoPlatform { private static CustomType _customType = CustomType.Platform; public int customIndex; private string _currentTileset = ""; public static string customPlatform01 { get => Custom.data[_customType][0]; set { Custom.data[_customType][0] = value; Custom.Clear(CustomType.Platform, value); } } public CustomPlatform(float x, float y, string t = "CUSTOMPLAT01") : base(x, y, "") { _tileset = t; customIndex = 0; _editorName = "Custom Platform 01"; physicsMaterial = PhysicsMaterial.Metal; verticalWidth = 14f; verticalWidthThick = 15f; horizontalHeight = 8f; UpdateCurrentTileset(); } public void UpdateCurrentTileset() { CustomTileData data = Custom.GetData(customIndex, _customType); int num = 0; if (_sprite != null) num = _sprite.frame; if (data != null && data.texture != null) { _sprite = new SpriteMap((Tex2D)data.texture, 16, 16); horizontalHeight = data.horizontalHeight; verticalWidth = data.verticalWidth; verticalWidthThick = data.verticalWidthThick; _hasLeftNub = data.leftNubber; _hasRightNub = data.rightNubber; } else { _sprite = new SpriteMap("scaffolding", 16, 16); verticalWidth = 14f; verticalWidthThick = 15f; horizontalHeight = 8f; } if (horizontalHeight == 0) horizontalHeight = 8f; if (verticalWidth == 0) verticalWidth = 14f; if (verticalWidthThick == 0) verticalWidthThick = 15f; _sprite.frame = num; _tileset = "CUSTOMPLAT0" + (customIndex + 1).ToString(); _currentTileset = Custom.data[_customType][customIndex]; graphic = _sprite; UpdateNubbers(); } public override void Update() => base.Update(); public override void EditorUpdate() { if (!(Level.current is Editor) || !(_currentTileset != Custom.data[_customType][customIndex])) return; UpdateCurrentTileset(); } public override ContextMenu GetContextMenu() { EditorGroupMenu contextMenu = new EditorGroupMenu(null, true); contextMenu.AddItem(new ContextFile("style", null, new FieldBinding(this, "customPlatform0" + (customIndex + 1).ToString()), ContextFileType.Platform)); return contextMenu; } } }
0
0.811676
1
0.811676
game-dev
MEDIA
0.773557
game-dev
0.883987
1
0.883987
RektSuddenDeath/College-Champ-Data-pack
1,377
Lab-RP/data/gr/functions/rooms/5/yellow/complete.mcfunction
# Open Gates execute as @e[type=minecraft:area_effect_cloud,tag=gr_yellowanchor] at @s run summon area_effect_cloud ~ ~10 ~15 {Duration:9999999,Tags:["gr_opener"]} # Playsound execute as @a[team=yellow] at @s run playsound gr.roomcomplete record @s # Save times scoreboard players operation @e[type=area_effect_cloud,tag=gr_general,tag=gr_yellowany] gr_room5time = yellow gr_currenttime # Trim execute as @e[type=minecraft:area_effect_cloud,tag=gr_yellowanchor] at @s run fill ~1 111 ~-1 ~31 111 ~31 yellow_terracotta replace smooth_quartz # Calculate Position, and update scoreboard scoreboard players add yellow gr_completeroom 1 scoreboard players add 5 gr_indvroom 1 function gr:scoreboard/moveup/yellow scoreboard players operation yellow gr_currentpos = 5 gr_indvroom function gr:scoreboard/calc # Announce position tellraw @a[team=!yellow] ["",{"translate":"team.yellow"},"§7第",{"score":{"name": "5","objective": "gr_indvroom"},"color": "aqua"},"§7个完成了房间","§e[","§6The Crawl Maze","§e]"] tellraw @a[team=yellow] ["","§7你","§7第",{"score":{"name": "5","objective": "gr_indvroom"},"color": "aqua"},"§7个完成了房间","§e[","§6The Crawl Maze","§e]"] # Initiate next room scoreboard players add yellow gr_teamphase 1 execute as @e[type=minecraft:area_effect_cloud,tag=gr_yellowanchor] at @s run tp @s ~-47 ~ ~ function gr:rooms/6/yellow/divider function gr:rooms/6/yellow/master
0
0.725969
1
0.725969
game-dev
MEDIA
0.935835
game-dev
0.757421
1
0.757421
deater/dos33fsprogs
6,107
games/peasant/location_outer/quiz1.s
;========================= ; take quiz ;========================= take_quiz: quiz1_loop: ;======================= ; check keyboard special jsr check_keyboard_answer lda IN_QUIZ beq done_quiz1 ;======================== ; draw_scene jsr update_screen ;======================= ; draw quiz message lda WHICH_QUIZ cmp #2 beq draw_keeper1_quiz3 cmp #1 beq draw_keeper1_quiz2 draw_keeper1_quiz1: lda WRONG_KEY bne draw_keeper1_quiz1_again ldx #<cave_outer_quiz1_1 ldy #>cave_outer_quiz1_1 jmp draw_keeper1_quiz_common draw_keeper1_quiz1_again: ldx #<cave_outer_quiz1_1again ldy #>cave_outer_quiz1_1again jmp draw_keeper1_quiz_common draw_keeper1_quiz2: lda WRONG_KEY bne draw_keeper1_quiz2_again ldx #<cave_outer_quiz1_2 ldy #>cave_outer_quiz1_2 jmp draw_keeper1_quiz_common draw_keeper1_quiz2_again: ldx #<cave_outer_quiz1_2again ldy #>cave_outer_quiz1_2again jmp draw_keeper1_quiz_common draw_keeper1_quiz3: lda WRONG_KEY bne draw_keeper1_quiz3_again ldx #<cave_outer_quiz1_3 ldy #>cave_outer_quiz1_3 jmp draw_keeper1_quiz_common draw_keeper1_quiz3_again: ldx #<cave_outer_quiz1_3again ldy #>cave_outer_quiz1_3again draw_keeper1_quiz_common: stx OUTL sty OUTH jsr print_text_message ;===================== ; increment frame inc FRAME ;===================== ; increment flame jsr increment_flame ;======================= ; flip page ; jsr wait_vblank jsr hgr_page_flip jmp quiz1_loop done_quiz1: rts ;====================== ; quiz1 invalid answer ;====================== invalid_answer: bit KEYRESET ; clear the keyboard buffer inc WRONG_KEY rts .if 0 lda WHICH_QUIZ cmp #2 ; off by 1 beq resay_quiz3 cmp #1 beq resay_quiz2 resay_quiz1: ldx #<cave_outer_quiz1_1again ldy #>cave_outer_quiz1_1again jmp finish_parse_message_nowait resay_quiz2: ldx #<cave_outer_quiz1_2again ldy #>cave_outer_quiz1_2again jmp finish_parse_message_nowait resay_quiz3: ldx #<cave_outer_quiz1_3again ldy #>cave_outer_quiz1_3again jmp finish_parse_message_nowait .endif ;====================== ; quiz1 wrong answer ;====================== wrong_answer: bit KEYRESET ; clear the keyboard buffer ldx #<cave_outer_quiz1_wrong ldy #>cave_outer_quiz1_wrong jsr finish_parse_message ldx #<cave_outer_quiz1_wrong_part2 ldy #>cave_outer_quiz1_wrong_part2 jsr finish_parse_message ldx #<cave_outer_quiz1_wrong_part3 ldy #>cave_outer_quiz1_wrong_part3 jsr finish_parse_message ; transform to ron jsr ron_transform after_ron: ; force message to current page lda DRAW_PAGE eor #$20 sta DRAW_PAGE ldx #<cave_outer_quiz1_wrong_part4 ldy #>cave_outer_quiz1_wrong_part4 ; hack so Ron still displayed for message stx OUTL sty OUTH jsr print_text_message ; jsr hgr_page_flip bit KEYRESET jsr wait_until_keypress ; jsr finish_parse_message lda #0 sta IN_QUIZ ; game over lda #LOAD_GAME_OVER sta WHICH_LOAD lda #NEW_FROM_DISK sta LEVEL_OVER rts ;====================== ; quiz1 correct answer ;====================== right_answer: bit KEYRESET ; clear the keyboard buffer ldx #<cave_outer_quiz1_correct ldy #>cave_outer_quiz1_correct jsr finish_parse_message jsr cave_outer_get_shield rts quiz_answers: .byte 'B','A','C' ;=============================== ; ron transform ;=============================== ron_transform: lda #0 sta RON_COUNT ; look down for this lda #PEASANT_DIR_DOWN sta PEASANT_DIR ron1_loop: ;============================= ; copy page (note this is going to mess with sound) ; FIXME: instead just copy from BG like climb code? jsr hgr_copy_faster ; play sound if needed, 2.. 12 lda RON_COUNT cmp #2 bcc skip_ron_sound cmp #12 bcs skip_ron_sound and #1 beq ron_other_note lda #NOTE_F6 beq ron_common_note ; bra ron_other_note: lda #NOTE_E6 ron_common_note: sta speaker_frequency lda #8 sta speaker_duration jsr speaker_tone skip_ron_sound: inc RON_COUNT ldx RON_COUNT lda #10 sta SPRITE_X lda #60 sta SPRITE_Y ; get offset for graphics ldx RON_COUNT lda ron_which_keeper_sprite,X clc adc #5 ; skip ron tax jsr hgr_draw_sprite_mask ;======================= ; see if done animation blurgh: lda RON_COUNT cmp #21 ; beq ron_done cmp #12 bcc ron_peasant ; normal peasant first 12 frames ldx RON_COUNT lda PEASANT_X sta SPRITE_X lda PEASANT_Y sta SPRITE_Y ; get offset for graphics ; ldx RON_COUNT lda ron_which_ron_sprite,X tax jsr hgr_draw_sprite_mask jmp done_ron_peasant ron_peasant: ;======================== ; draw peasant jsr draw_peasant ;======================== ; increment flame jsr increment_flame done_ron_peasant: ;========================= ; delay ; lda #200 ; jsr wait ;========================= ; flip page jsr hgr_page_flip ; jsr wait_vblank jmp ron1_loop ron_done: ;=========================== ; weep sound lda #32 sta speaker_duration lda #NOTE_E5 sta speaker_frequency jsr speaker_tone lda #64 sta speaker_duration lda #NOTE_F5 sta speaker_frequency jsr speaker_tone jsr wait_until_keypress rts ;========================================== ; first keeper ron info ; flips peasant forward ; 3 (4) (u shaped) ; 5 (4) (up) ; 6 (6) (up, up) ; 7 (4) (up, down) ; 6 (4) ; 7 (4) ; 6 (4) ; 7 (4) ; 6 (4) ; 7 (4) ; 6 (4) ; 7 (4) 9? repeats, ending on down ; ron transition happens ; (8) switches to 5 part way through first frame? ; 3 / ron next , to 1 part way through second (cloud frame) ; 5 ron (gap) ; 10 ron (tiny smoke) ; 10 full ron ron_which_keeper_sprite: .byte 3, 5, 6, 7 .byte 6, 7, 6, 7 .byte 6, 7, 6, 7 .byte 7, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1 ron_which_ron_sprite: .byte 0, 0, 0, 0 .byte 0, 0, 0, 0 .byte 0, 0, 0, 0 .byte 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4
0
0.912658
1
0.912658
game-dev
MEDIA
0.846979
game-dev
0.631953
1
0.631953