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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Dimbreath/AzurLaneData | 12,773 | ko-KR/view/equipment/equipmenttransformtreescene.lua | slot0 = class("EquipmentTransformTreeScene", import("view.base.BaseUI"))
slot1 = require("Mgr/Pool/PoolPlural")
slot2 = "ui/EquipmentTransformTreeUI_atlas"
function slot0.getUIName(slot0)
return "EquipmentTransformTreeUI"
end
slot0.optionsPath = {
"blur_panel/adapt/top/option"
}
slot0.MODE_NORMAL = 1
slot0.MODE_HIDESIDE = 2
function slot0.init(slot0)
slot0.leftPanel = slot0._tf:Find("Adapt/Left")
slot0.rightPanel = slot0._tf:Find("Adapt/Right")
slot0.nationToggleGroup = slot0.leftPanel:Find("Nations"):Find("ViewPort/Content")
setActive(slot0.nationToggleGroup:GetChild(0), false)
slot0.nationToggleGroup:GetChild(0):Find("selectedCursor").gameObject:SetActive(false)
slot0.equipmentTypeToggleGroup = slot0.leftPanel:Find("EquipmentTypes"):Find("ViewPort/Content")
setActive(slot0.equipmentTypeToggleGroup:GetChild(0), false)
slot0.equipmentTypeToggleGroup:GetChild(0):Find("selectedframe").gameObject:SetActive(false)
slot0.TreeCanvas = slot0.rightPanel:Find("ViewPort/Content")
setActive(slot0.rightPanel:Find("EquipNode"), false)
setActive(slot0.rightPanel:Find("Link"), false)
slot0.nodes = {}
slot0.links = {}
slot0.plurals = {
EquipNode = uv0.New(slot0.rightPanel:Find("EquipNode").gameObject, 5),
Link = uv0.New(slot0.rightPanel:Find("Link").gameObject, 8)
}
slot0.pluralRoot = pg.PoolMgr.GetInstance().root
slot0.top = slot0._tf:Find("blur_panel")
slot0.loader = AutoLoader.New()
end
function slot0.GetEnv(slot0)
slot0.env = slot0.env or {}
return slot0.env
end
function slot0.SetEnv(slot0, slot1)
slot0.env = slot1
end
function slot0.didEnter(slot0)
pg.UIMgr.GetInstance():OverlayPanel(slot0.top)
onButton(slot0, slot0.top:Find("adapt/top/back"), function ()
uv0:closeView()
end, SFX_CANCEL)
if slot0.contextData.targetEquipId then
slot1, slot2 = nil
slot3 = false
for slot7, slot8 in pairs(slot0.env.nationsTree) do
for slot12, slot13 in pairs(slot8) do
for slot17, slot18 in ipairs(slot13.equipments) do
if slot18[3] == slot0.contextData.targetEquipId then
slot2 = slot12
slot1 = slot7
slot3 = true
break
end
end
end
if slot3 then
break
end
end
if slot3 then
slot0.contextData.nation = slot1
slot0.contextData.equipmentTypeIndex = slot2
end
end
slot0:InitPage()
if slot0.contextData.mode == uv0.MODE_HIDESIDE then
setActive(slot0.leftPanel, false)
slot1 = slot0.rightPanel.sizeDelta
slot1.x = 0
slot0.rightPanel.sizeDelta = slot1
setAnchoredPosition(slot0.rightPanel, {
x = 0
})
end
end
function slot0.GetSortKeys(slot0)
slot1 = {}
for slot5, slot6 in pairs(slot0) do
table.insert(slot1, slot5)
end
table.sort(slot1, function (slot0, slot1)
return slot0 < slot1
end)
return slot1
end
function slot0.InitPage(slot0)
slot0.firstInit = true
slot1.mode = slot0.contextData.mode or uv0.MODE_NORMAL
slot4 = uv0.GetSortKeys(slot0.env.nationsTree)
if not slot1.nation or not table.contains(slot4, slot3) then
slot3 = slot4[1]
end
if next(slot2.nationsTree[slot3]) == nil then
for slot8 = 2, #slot4 do
if next(slot2.nationsTree[slot4[slot8]]) ~= nil then
slot3 = slot4[slot8]
break
end
end
end
slot1.nation = nil
slot0:UpdateNations()
triggerButton(slot0.nationToggles[table.indexof(slot4, slot3) or 1])
slot0.firstInit = nil
end
function slot0.UpdateNations(slot0)
slot0.nationToggles = slot0.Clone2Full(slot0.nationToggleGroup, #uv0.GetSortKeys(slot0.env.nationsTree))
for slot5 = 1, #slot0.nationToggles do
slot6 = slot0.nationToggles[slot5]
slot0.loader:GetSprite(uv1, "nation" .. slot1[slot5] .. "_disable", slot6:Find("selectedIcon"))
setActive(slot6:Find("selectedCursor"), false)
onButton(slot0, slot6, function ()
if uv0.contextData.nation ~= uv1 then
if next(uv0.env.nationsTree[uv1]) == nil then
pg.TipsMgr.GetInstance():ShowTips(i18n("word_comingSoon"))
return
end
uv0.loader:GetSprite(uv2, "nation" .. uv1, uv3:Find("selectedIcon"))
if uv0.contextData.nation then
slot0 = table.indexof(uv4, uv0.contextData.nation)
setActive(uv0.nationToggles[slot0]:Find("selectedCursor"), false)
uv0.loader:GetSprite(uv2, "nation" .. uv0.contextData.nation .. "_disable", uv0.nationToggles[slot0]:Find("selectedIcon"))
end
uv0.contextData.nation = uv1
uv0:UpdateEquipmentTypes()
slot1 = uv5.GetSortKeys(uv0.env.nationsTree[uv1])[1]
if uv0.firstInit and uv0.contextData.equipmentTypeIndex and table.contains(slot0, slot2) then
slot1 = slot2
end
uv0.contextData.equipmentTypeIndex = nil
triggerToggle(uv0.equipmentTypeToggles[table.indexof(slot0, slot1) or 1], true)
end
end, SFX_UI_TAG)
end
end
function slot0.UpdateEquipmentTypes(slot0)
slot0.equipmentTypeToggles = slot0.Clone2Full(slot0.equipmentTypeToggleGroup, #uv0.GetSortKeys(slot0.env.nationsTree[slot0.contextData.nation]))
for slot5 = 1, #slot0.equipmentTypeToggles do
slot6 = slot0.equipmentTypeToggles[slot5]
slot6:GetComponent(typeof(Toggle)).isOn = false
slot0.loader:GetSprite(uv1, "equipmentType" .. slot1[slot5], slot6:Find("itemName"))
setActive(slot6:Find("selectedframe"), false)
onToggle(slot0, slot6, function (slot0)
if slot0 and uv0.contextData.equipmentTypeIndex ~= uv1 then
uv0.contextData.equipmentTypeIndex = uv1
uv0:ResetCanvas()
end
setActive(uv2:Find("selectedframe"), slot0)
end, SFX_UI_TAG)
end
slot0.equipmentTypeToggleGroup.anchoredPosition = Vector2.zero
slot0.leftPanel:Find("EquipmentTypes"):GetComponent(typeof(ScrollRect)).velocity = Vector2.zero
end
slot3 = {
15,
-4,
15,
6
}
function slot0.ResetCanvas(slot0)
slot1 = EquipmentProxy.EquipmentTransformTreeTemplate[slot0.contextData.nation][slot0.contextData.equipmentTypeIndex]
slot0.TreeCanvas.sizeDelta = Vector2(unpack(slot1.canvasSize))
slot0.TreeCanvas.anchoredPosition = Vector2.zero
slot0.rightPanel:GetComponent(typeof(ScrollRect)).velocity = Vector2.zero
slot0:ReturnCanvasItems()
for slot6, slot7 in ipairs(slot1.equipments) do
slot8 = slot0.plurals.EquipNode:Dequeue()
setActive(slot8, true)
setParent(slot8, slot0.TreeCanvas)
table.insert(slot0.nodes, {
id = slot7[3],
cfg = slot7,
go = slot8
})
slot8.name = slot7[3]
slot0:UpdateItemNode(tf(slot8), slot7)
end
for slot6, slot7 in ipairs(slot1.links) do
for slot11 = 1, #slot7 - 1 do
slot12 = slot7[slot11]
slot13 = slot7[slot11 + 1]
slot14 = {
slot13[1] - slot12[1],
slot12[2] - slot13[2]
}
slot15 = math.abs(slot14[2]) < math.abs(slot14[1])
slot16 = slot15 and math.abs(slot14[1]) or math.abs(slot14[2])
if slot15 then
slot14[2] = 0
else
slot14[1] = 0
end
slot18 = math.deg2Rad * 90 * (1 - math.sign(slot14[1]) ~= 1 and slot17 or 2 - math.sign(slot14[2]))
if #slot7 == 2 then
slot19 = slot0.plurals.Link:Dequeue()
table.insert(slot0.links, go(slot19))
setActive(slot19, true)
setParent(slot19, slot0.TreeCanvas)
slot0.loader:GetSprite(uv0, slot14[2] == 0 and "wirehead" or "wireline", slot19)
tf(slot19).sizeDelta = Vector2(28, 26)
tf(slot19).pivot = Vector2(0.5, 0.5)
tf(slot19).localRotation = Quaternion.Euler(0, 0, slot17 * 90)
slot20 = Vector2(math.cos(slot18), math.sin(slot18)) * uv1[(slot17 - 1) % 4 + 1]
tf(slot19).anchoredPosition = Vector2(slot12[1] + slot20.x, -slot12[2] + slot20.y)
slot19 = slot0.plurals.Link:Dequeue()
table.insert(slot0.links, go(slot19))
setActive(slot19, true)
setParent(slot19, slot0.TreeCanvas)
slot0.loader:GetSprite(uv0, "wiretail", slot19)
tf(slot19).sizeDelta = Vector2(28, 26)
tf(slot19).pivot = Vector2(0.5, 0.5)
tf(slot19).localRotation = Quaternion.Euler(0, 0, slot17 * 90)
slot21 = Vector2(math.cos(slot18), math.sin(slot18)) * -uv1[(slot17 + 1) % 4 + 1]
tf(slot19).anchoredPosition = Vector2(slot13[1] + slot21.x, -slot13[2] + slot21.y)
slot19 = slot0.plurals.Link:Dequeue()
table.insert(slot0.links, go(slot19))
setActive(slot19, true)
setParent(slot19, slot0.TreeCanvas)
slot0.loader:GetSprite(uv0, "wireline", slot19)
tf(slot19).sizeDelta = Vector2(math.max(0, slot16 - uv1[(slot17 - 1) % 4 + 1] - uv1[(slot17 + 1) % 4 + 1] - 28), 16)
tf(slot19).pivot = Vector2(0, 0.5)
tf(slot19).localRotation = Quaternion.Euler(0, 0, slot17 * 90)
tf(slot19).anchoredPosition = Vector2(slot12[1] + slot20.x, -slot12[2] + slot20.y) + Vector2(math.cos(slot18), math.sin(slot18)) * 14
break
end
slot19 = slot0.plurals.Link:Dequeue()
table.insert(slot0.links, go(slot19))
setActive(slot19, true)
setParent(slot19, slot0.TreeCanvas)
slot20 = 1
if slot11 == 1 then
slot0.loader:GetSprite(uv0, slot14[2] == 0 and "wirehead" or "wireline", slot19)
slot21 = slot16 + 14 + slot20 - uv1[(slot17 - 1) % 4 + 1]
tf(slot19).sizeDelta = Vector2(slot21, 26)
tf(slot19).pivot = Vector2((slot21 - slot20) / slot21, 0.5)
tf(slot19).localRotation = Quaternion.Euler(0, 0, slot17 * 90)
tf(slot19).anchoredPosition = Vector2(slot13[1], -slot13[2])
elseif slot11 + 1 == #slot7 then
slot0.loader:GetSprite(uv0, "wiretail", slot19)
tf(slot19).sizeDelta = Vector2(slot16 + 14 + slot20 - uv1[(slot17 + 1) % 4 + 1], 26)
tf(slot19).pivot = Vector2(slot20 / (slot16 + 14 + slot20 - uv1[(slot17 + 1) % 4 + 1]), 0.5)
tf(slot19).localRotation = Quaternion.Euler(0, 0, slot17 * 90)
tf(slot19).anchoredPosition = Vector2(slot12[1], -slot12[2])
else
slot0.loader:GetSprite(uv0, "wireline", slot19)
tf(slot19).sizeDelta = Vector2(slot16 + slot20 * 2, 16)
tf(slot19).pivot = Vector2(slot20 / (slot16 + slot20 * 2), 0.5)
tf(slot19).localRotation = Quaternion.Euler(0, 0, slot17 * 90)
tf(slot19).anchoredPosition = Vector2(slot12[1], -slot12[2])
end
end
end
end
function slot0.UpdateItemNode(slot0, slot1, slot2)
slot1 = tf(slot1)
slot1.anchoredPosition = Vector2(slot2[1], -slot2[2])
updateDrop(slot1:Find("Item"), {
id = slot2[3],
type = DROP_TYPE_EQUIP
})
onButton(slot0, slot1:Find("Item"), function ()
if not EquipmentProxy.GetTransformSources(uv0[3])[1] then
pg.TipsMgr.GetInstance():ShowTips(i18n("equipment_upgrade_initial_node"))
return
end
uv1:emit(EquipmentTransformTreeMediator.OPEN_LAYER, Context.New({
mediator = EquipmentTransformMediator,
viewComponent = EquipmentTransformLayer,
data = {
formulaId = slot0
}
}))
end, SFX_PANEL)
slot1:Find("Mask/NameText"):GetComponent("ScrollText"):SetText(pg.equip_data_statistics[slot2[3]].name)
setActive(slot1:Find("cratfable"), _.any(slot0.env.GetEquipTraceBack(slot2[3]), function (slot0)
return slot0.candicates and #slot1 > 0 and TransformEquipmentCommand.CheckEquipmentFormulasSucceed(slot0.formulas, slot1[#slot1].id)
end))
onButton(slot0, slot1:Find("cratfable"), function ()
uv0:emit(EquipmentTransformTreeMediator.OPEN_LAYER, Context.New({
mediator = EquipmentTraceBackMediator,
viewComponent = EquipmentTraceBackLayer,
data = {
TargetEquipmentId = uv1[3]
}
}))
end)
setActive(slot1:Find("Item/new"), slot2[4] and PlayerPrefs.GetInt("ShowTransformTip_" .. slot2[3], 0) == 0)
end
function slot0.UpdateItemNodes(slot0)
for slot4, slot5 in ipairs(slot0.nodes) do
slot0:UpdateItemNode(slot5.go, slot5.cfg)
end
end
function slot0.UpdateItemNodeByID(slot0, slot1)
for slot5, slot6 in ipairs(slot0.nodes) do
if slot1 == slot6.id then
slot0:UpdateItemNode(slot6.go, slot6.cfg)
break
end
end
end
function slot0.ReturnCanvasItems(slot0, slot1)
for slot5, slot6 in ipairs(slot0.nodes) do
if not slot0.plurals.EquipNode:Enqueue(slot6.go, slot1) then
setParent(slot6.go, slot0.pluralRoot)
end
end
table.clean(slot0.nodes)
for slot5, slot6 in ipairs(slot0.links) do
if not slot0.plurals.Link:Enqueue(slot6, slot1) then
setParent(slot6, slot0.pluralRoot)
end
end
table.clean(slot0.links)
end
function slot0.UpdateCanvas(slot0)
slot1 = EquipmentProxy.EquipmentTransformTreeTemplate[slot0.contextData.nation][slot0.contextData.equipmentTypeIndex]
end
function slot0.willExit(slot0)
slot4 = slot0._tf
pg.UIMgr.GetInstance():UnOverlayPanel(slot0.top, slot4)
slot0:ReturnCanvasItems(true)
for slot4, slot5 in pairs(slot0.plurals) do
slot5:Clear()
end
slot0.loader:Clear()
end
function slot0.Clone2Full(slot0, slot1)
slot3 = slot0:GetChild(0)
for slot8 = 0, slot0.childCount - 1 do
table.insert({}, slot0:GetChild(slot8))
end
for slot8 = slot4, slot1 - 1 do
table.insert(slot2, tf(cloneTplTo(slot3, slot0)))
end
for slot8 = 0, slot0.childCount - 1 do
setActive(slot0:GetChild(slot8), slot8 < slot1)
end
for slot8 = slot4, slot1 + 1, -1 do
table.remove(slot2)
end
return slot2
end
return slot0
| 411 | 0.582377 | 1 | 0.582377 | game-dev | MEDIA | 0.915278 | game-dev | 0.881796 | 1 | 0.881796 |
Joshua-F/osrs-dumps | 2,189 | script/[clientscript,forget_init_switches].cs2 | // 1243
[clientscript,forget_init_switches](int $int0)
if ($int0 = 1) {
if_sethide(true, forget_puzzle1:switch_model_a);
if_sethide(true, forget_puzzle1:switch_model_b);
if_sethide(true, forget_puzzle1:switch_model_c);
if_sethide(true, forget_puzzle1:switch_model_d);
if_sethide(true, forget_puzzle1:switch_model_e);
if_sethide(true, forget_puzzle1:switch_model_f);
if_sethide(true, forget_puzzle1:switch_model_g);
if_sethide(true, forget_puzzle1:switch_model_h);
} else if ($int0 = 2) {
if_sethide(true, forget_puzzle2:switch_model_a);
if_sethide(true, forget_puzzle2:switch_model_b);
if_sethide(true, forget_puzzle2:switch_model_c);
if_sethide(true, forget_puzzle2:switch_model_d);
if_sethide(true, forget_puzzle2:switch_model_e);
if_sethide(true, forget_puzzle2:switch_model_f);
if_sethide(true, forget_puzzle2:switch_model_g);
if_sethide(true, forget_puzzle2:switch_model_h);
if_sethide(true, forget_puzzle2:switch_model_i);
if_sethide(true, forget_puzzle2:switch_model_j);
if_sethide(true, forget_puzzle2:switch_model_k);
if_sethide(true, forget_puzzle2:switch_model_l);
} else if ($int0 = 3) {
if_sethide(true, forget_puzzle3:switch_model_a);
if_sethide(true, forget_puzzle3:switch_model_b);
if_sethide(true, forget_puzzle3:switch_model_c);
if_sethide(true, forget_puzzle3:switch_model_d);
if_sethide(true, forget_puzzle3:switch_model_e);
if_sethide(true, forget_puzzle3:switch_model_f);
if_sethide(true, forget_puzzle3:switch_model_g);
if_sethide(true, forget_puzzle3:switch_model_h);
if_sethide(true, forget_puzzle3:switch_model_i);
if_sethide(true, forget_puzzle3:switch_model_j);
if_sethide(true, forget_puzzle3:switch_model_k);
if_sethide(true, forget_puzzle3:switch_model_l);
if_sethide(true, forget_puzzle3:switch_model_m);
if_sethide(true, forget_puzzle3:switch_model_n);
if_sethide(true, forget_puzzle3:switch_model_o);
if_sethide(true, forget_puzzle3:switch_model_p);
if_sethide(true, forget_puzzle3:switch_model_q);
if_sethide(true, forget_puzzle3:switch_model_r);
if_sethide(true, forget_puzzle3:switch_model_s);
}
| 411 | 0.787882 | 1 | 0.787882 | game-dev | MEDIA | 0.727731 | game-dev | 0.895399 | 1 | 0.895399 |
mcMMO-Dev/mcMMO | 87,489 | src/main/resources/locale/locale_en_US.properties | Placeholder= This value is for any WIP locale entries that will not be displayed to users
JSON.Rank=Rank
JSON.DescriptionHeader=Description:
JSON.JWrapper.Header=Details
JSON.Type.Passive=Passive
JSON.Type.Active=Active
JSON.Type.SuperAbility=Super Ability
JSON.Locked=-=[LOCKED]=-
JSON.LevelRequirement=Level Requirement
JSON.JWrapper.Target.Type=Target Type:
JSON.JWrapper.Target.Block=Block
JSON.JWrapper.Target.Player=Player
JSON.JWrapper.Perks.Header=&6Lucky Perks
JSON.JWrapper.Perks.Lucky={0}% Better Odds
JSON.Hover.Tips=Tips
JSON.Acrobatics=Acrobatics
JSON.Alchemy=Alchemy
JSON.Archery=Archery
JSON.Axes=Axes
JSON.Crossbows=Crossbows
JSON.Excavation=Excavation
JSON.Fishing=Fishing
JSON.Herbalism=Herbalism
JSON.Mining=Mining
JSON.Repair=Repair
JSON.Salvage=Salvage
JSON.Swords=Swords
JSON.Taming=Taming
JSON.Tridents=Tridents
JSON.Maces=Maces
JSON.Unarmed=Unarmed
JSON.Woodcutting=Woodcutting
JSON.URL.Website=The official mcMMO Website!
JSON.URL.Discord=The official mcMMO Discord server!
JSON.URL.Patreon=Support nossr50 and his work for mcMMO on Patreon!
JSON.URL.Spigot=The official mcMMO Spigot Resource Page!
JSON.URL.Translation=Translate mcMMO into other languages!
JSON.URL.Wiki=The official mcMMO wiki!
JSON.SkillUnlockMessage=&6[ mcMMO&e @&3{0} &6Rank &3{1}&6 Unlocked! ]
JSON.Hover.Rank=&e&lRank:&r &f{0}
JSON.Hover.NextRank=&7&oNext upgrade at level {0}
# for JSON.Hover.Mystery you can add {0} to insert the level required into the name, I don't like how that looks so I'm not doing that atm
JSON.Hover.Mystery=&7???
JSON.Hover.Mystery2=&e[&8{0}&e]&8???&r
JSON.Hover.SkillName=&3{0}&r
JSON.Hover.SuperAbility=&5{0}&r
JSON.Hover.MaxRankSkillName=&6{0}&r
JSON.Hover.AtSymbolSkills=&e@
JSON.Hover.AtSymbolURL=&e@
#This is the message sent to players when an ability is activated
JSON.Notification.SuperAbility={0}
#These are the JSON Strings used for SubSkills
JSON.Acrobatics.Roll.Interaction.Activated=Test &cRolled Test
JSON.Acrobatics.SubSkill.Roll.Details.Tips=If you hold sneak while falling you can prevent up to twice the damage that you would normally take!
Anvil.SingleItemStack=&cYou cannot salvage or repair item stacks that have more than one item, split the stack first.
#DO NOT USE COLOR CODES IN THE JSON KEYS
#COLORS ARE DEFINED IN advanced.yml IF YOU WISH TO CHANGE THEM
mcMMO.Template.Prefix=&6(&amcMMO&6) &7{0}
# BEGIN STYLING
Ability.Generic.Refresh=&a**ABILITIES REFRESHED!**
Ability.Generic.Template.Lock=&7{0}
# Skill Command Styling
Ability.Generic.Template=&3{0}: &a{1}
Ability.Generic.Template.Custom=&3{0}
Skills.Overhaul.Header=&c[]=====[]&a {0} &c[]=====[]
Effects.Effects=EFFECTS
Effects.SubSkills.Overhaul=Sub-Skills
Effects.Child.Overhaul=&3Child Lv.&e {0}&3: {1}
Effects.Child.ParentList=&a{0}&6(&3Lv.&e{1}&6)
Effects.Level.Overhaul=&6LVL: &e{0} &3XP&e(&6{1}&e/&6{2}&e)
Effects.Parent=&6{0} -
Effects.Template=&3{0}: &a{1}
Commands.Stats.Self.Overhaul=Stats
Commands.XPGain.Overhaul=&6XP GAIN: &3{0}
MOTD.Version.Overhaul=&6[mcMMO] &3Overhaul Era&6 - &3{0}
Overhaul.mcMMO.Header=&c[]=====[]&a mcMMO - Overhaul Era &c[]=====[]
Overhaul.mcMMO.Url.Wrap.Prefix=&c[|
Overhaul.mcMMO.Url.Wrap.Suffix=&c|]
Overhaul.mcMMO.MmoInfo.Wiki=&e[&fView this skill on the wiki!&e]
# Overhaul.Levelup can take {0} - Skill Name defined in Overhaul.Name {1} - Amount of levels gained {2} - Level in skill
Overhaul.Levelup=&l{0} increased to &r&a&l{2}&r&f.
Overhaul.Name.Acrobatics=Acrobatics
Overhaul.Name.Alchemy=Alchemy
Overhaul.Name.Archery=Archery
Overhaul.Name.Axes=Axes
Overhaul.Name.Crossbows=Crossbows
Overhaul.Name.Excavation=Excavation
Overhaul.Name.Fishing=Fishing
Overhaul.Name.Herbalism=Herbalism
Overhaul.Name.Mining=Mining
Overhaul.Name.Repair=Repair
Overhaul.Name.Salvage=Salvage
Overhaul.Name.Smelting=Smelting
Overhaul.Name.Swords=Swords
Overhaul.Name.Taming=Taming
Overhaul.Name.Tridents=Tridents
Overhaul.Name.Maces=Maces
Overhaul.Name.Unarmed=Unarmed
Overhaul.Name.Woodcutting=Woodcutting
# /mcMMO Command Style Stuff
Commands.mcc.Header=&c[]=====[] &amcMMO Commands &c[]=====[]
Commands.Other=&c[]=====[] &aSPECIAL COMMANDS &c[]=====[]
Commands.Party.Header=&c[]=====[] &aPARTY &c[]=====[]
Commands.Party.Features.Header=&c[]=====[] &aFEATURES &c[]=====[]
# XP BAR Allows for the following variables -- {0} = Skill Level, {1} Current XP, {2} XP Needed for next level, {3} Power Level, {4} Percentage of Level
# Make sure you turn on Experience_Bars.ThisMayCauseLag.AlwaysUpdateTitlesWhenXPIsGained if you want the XP bar title to update every time a player gains XP!
XPBar.Template={0}
XPBar.Template.EarlyGameBoost=&6Learning a new skill...
XPBar.Acrobatics=Acrobatics Lv.&6{0}
XPBar.Alchemy=Alchemy Lv.&6{0}
XPBar.Archery=Archery Lv.&6{0}
XPBar.Axes=Axes Lv.&6{0}
XPBar.Crossbows=Crossbows Lv.&6{0}
XPBar.Excavation=Excavation Lv.&6{0}
XPBar.Fishing=Fishing Lv.&6{0}
XPBar.Herbalism=Herbalism Lv.&6{0}
XPBar.Mining=Mining Lv.&6{0}
XPBar.Repair=Repair Lv.&6{0}
XPBar.Salvage=Salvage Lv.&6{0}
XPBar.Smelting=Smelting Lv.&6{0}
XPBar.Swords=Swords Lv.&6{0}
XPBar.Taming=Taming Lv.&6{0}
XPBar.Tridents=Tridents Lv.&6{0}
XPBar.Maces=Maces Lv.&6{0}
XPBar.Unarmed=Unarmed Lv.&6{0}
XPBar.Woodcutting=Woodcutting Lv.&6{0}
#This is just a preset template that gets used if the 'ExtraDetails' setting is turned on in experience.yml (off by default), you can ignore this template and just edit the strings above
XPBar.Complex.Template={0} &3 {4}&f% &3(&f{1}&3/&f{2}&3)
# XP BAR Allows for the following variables -- {0} = Skill Level, {1} Current XP, {2} XP Needed for next level, {3} Power Level, {4} Percentage of Level
# Make sure you turn on Experience_Bars.ThisMayCauseLag.AlwaysUpdateTitlesWhenXPIsGained if you want the XP bar title to update every time a player gains XP!
# END STYLING
#ACROBATICS
Acrobatics.Ability.Proc=&a**Graceful Landing**
Acrobatics.Combat.Proc=&a**Dodged**
Acrobatics.SubSkill.Roll.Stats=&6Roll Chance &e{0}%&6 Graceful Roll Chance&e {1}%
Acrobatics.SubSkill.Roll.Stat=Roll Chance
Acrobatics.SubSkill.Roll.Stat.Extra=Graceful Roll Chance
Acrobatics.SubSkill.Roll.Name=Roll
Acrobatics.SubSkill.Roll.Description=Land strategically to avoid damage.
Acrobatics.SubSkill.Roll.Chance=Roll Chance: &e{0}
Acrobatics.SubSkill.Roll.GraceChance=Graceful Roll Chance: &e{0}
Acrobatics.SubSkill.Roll.Mechanics=&7Rolling is an active Sub-Skill with a passive component.\nWhenever you take fall damage you have a chance to completely negate the damage based on your skill level, at level &e{6}%&7 you have a &e{0}%&7 chance to prevent damage, and &e{1}%&7 if you activate Graceful Roll.\nThe chance for success is scaled against your skill level in a linear curve until level &e{2}&7 where it maxes out, every level in Acrobatics gives you a &e{3}%&7 chance to succeed.\nBy holding the sneak button you can double your odds to avoid fall damage and avoid up to twice the fall damage! Holding sneak will transform a normal roll into a Graceful Roll.\nRolling will only prevent up to &c{4}&7 damage. Graceful Rolls will prevent up to &a{5}&7 damage.
Acrobatics.SubSkill.GracefulRoll.Name=Graceful Roll
Acrobatics.SubSkill.GracefulRoll.Description=Twice as effective as a normal Roll
Acrobatics.SubSkill.Dodge.Name=Dodge
Acrobatics.SubSkill.Dodge.Description=Reduce attack damage by half
Acrobatics.SubSkill.Dodge.Stat=Dodge Chance
Acrobatics.Listener=Acrobatics:
Acrobatics.Roll.Text=&o**Rolled**
Acrobatics.SkillName=ACROBATICS
#ALCHEMY
Alchemy.SubSkill.Catalysis.Name=Catalysis
Alchemy.SubSkill.Catalysis.Description=Increases potion brewing speed
Alchemy.SubSkill.Catalysis.Stat=Brewing Speed
Alchemy.SubSkill.Concoctions.Name=Concoctions
Alchemy.SubSkill.Concoctions.Description=Brew potions with more ingredients
Alchemy.SubSkill.Concoctions.Stat=Concoctions Rank: &a{0}&3/&a{1}
Alchemy.SubSkill.Concoctions.Stat.Extra=Ingredients [&a{0}&3]: &a{1}
Alchemy.Listener=Alchemy:
Alchemy.Ability.Locked.0=LOCKED UNTIL {0}+ SKILL (CATALYSIS)
Alchemy.SkillName=ALCHEMY
#ARCHERY
Archery.SubSkill.SkillShot.Name=Skill Shot
Archery.SubSkill.SkillShot.Description=Increases damage done with bows
Archery.SubSkill.SkillShot.Stat=Skill Shot Bonus Damage
Archery.SubSkill.Daze.Name=Daze
Archery.SubSkill.Daze.Description=Disorients foes and deals extra DMG
Archery.SubSkill.Daze.Stat=Daze Chance
Archery.SubSkill.ArrowRetrieval.Name=Arrow Retrieval
Archery.SubSkill.ArrowRetrieval.Description=Chance to retrieve arrows from corpses
Archery.SubSkill.ArrowRetrieval.Stat=Arrow Recovery Chance
Archery.SubSkill.ArcheryLimitBreak.Name=Archery Limit Break
Archery.SubSkill.ArcheryLimitBreak.Description=Breaking your limits. Increased damage against tough opponents. Intended for PVP, up to server settings for whether it will boost damage in PVE.
Archery.SubSkill.ArcheryLimitBreak.Stat=Limit Break Max DMG
Archery.Listener=Archery:
Archery.SkillName=ARCHERY
Archery.SubSkill.ExplosiveShot.Name=Explosive Shot
Archery.SubSkill.ExplosiveShot.Description=Fire an explosive arrow
Archery.Skills.ExplosiveShot.Off=
Archery.Skills.ExplosiveShot.On=&a**EXPLOSIVE SHOT ACTIVATED**
Archery.Skills.ExplosiveShot.Other.Off=Explosive Shot&a has worn off for &e{0}
Archery.Skills.ExplosiveShot.Other.On=&a{0}&2 has used &cExplosive Shot!
Archery.Skills.ExplosiveShot.Refresh=&aYour &Explosive Shot &ability is refreshed!
#AXES
Axes.Ability.Bonus.0=Axe Mastery
Axes.Ability.Bonus.1=Bonus {0} damage
Axes.Ability.Bonus.2=Armor Impact
Axes.Ability.Bonus.3=Deal {0} Bonus DMG to armor
Axes.Ability.Bonus.4=Greater Impact
Axes.Ability.Bonus.5=Deal {0} Bonus DMG to unarmored foes
Axes.Ability.Lower=&7You lower your Axe.
Axes.Ability.Ready=&3You &6ready&3 your Axe.
Axes.Ability.Ready.Extra=&3You &6ready&3 your Axe. &7({0} is on cooldown for {1}s)
Axes.Combat.CritStruck=&4You were CRITICALLY hit!
Axes.Combat.CriticalHit=CRITICAL HIT!
Axes.Combat.GI.Proc=&a**STRUCK WITH GREAT FORCE**
Axes.Combat.GI.Struck=**HIT BY GREATER IMPACT**
Axes.Combat.SS.Struck=&4Struck by SKULL SPLITTER!
Axes.SubSkill.SkullSplitter.Name=Skull Splitter
Axes.SubSkill.SkullSplitter.Description=Deal AoE Damage
Axes.SubSkill.SkullSplitter.Stat=Skull Splitter Duration
Axes.SubSkill.CriticalStrikes.Name=Critical Strikes
Axes.SubSkill.CriticalStrikes.Description=Double Damage
Axes.SubSkill.CriticalStrikes.Stat=Critical Strike Chance
Axes.SubSkill.AxeMastery.Name=Axe Mastery
Axes.SubSkill.AxeMastery.Description=Adds bonus DMG
Axes.SubSkill.AxesLimitBreak.Name=Axes Limit Break
Axes.SubSkill.AxesLimitBreak.Description=Breaking your limits. Increased damage against tough opponents. Intended for PVP, up to server settings for whether it will boost damage in PVE.
Axes.SubSkill.AxesLimitBreak.Stat=Limit Break Max DMG
Axes.SubSkill.ArmorImpact.Name=Armor Impact
Axes.SubSkill.ArmorImpact.Description=Strike with enough force to shatter armor
Axes.SubSkill.GreaterImpact.Name=Greater Impact
Axes.SubSkill.GreaterImpact.Description=Deal bonus damage to unarmored foes
Axes.Listener=Axes:
Axes.SkillName=AXES
Axes.Skills.SS.Off=**Skull Splitter has worn off**
Axes.Skills.SS.On=&a**Skull Splitter ACTIVATED**
Axes.Skills.SS.Refresh=&aYour &eSkull Splitter &aability is refreshed!
Axes.Skills.SS.Other.Off=Skull Splitter&a has worn off for &e{0}
Axes.Skills.SS.Other.On=&a{0}&2 has used &cSkull Splitter!
#EXCAVATION
Excavation.Ability.Lower=&7You lower your shovel.
Excavation.Ability.Ready=&3You &6ready&3 your Shovel.
Excavation.SubSkill.GigaDrillBreaker.Name=Giga Drill Breaker
Excavation.SubSkill.GigaDrillBreaker.Description=3x Drop Rate, 3x EXP, +Speed
Excavation.SubSkill.GigaDrillBreaker.Stat=Giga Drill Breaker Duration
Excavation.SubSkill.Archaeology.Name=Archaeology
Excavation.SubSkill.Archaeology.Description=Unearth the secrets of the land! High skill levels increase your odds of finding experience orbs when you find treasure!
Excavation.SubSkill.Archaeology.Stat=Archaeology Experience Orb Chance
Excavation.SubSkill.Archaeology.Stat.Extra=Archaeology Experience Orb Amount
Excavation.Listener=Excavation:
Excavation.SkillName=EXCAVATION
Excavation.Skills.GigaDrillBreaker.Off=**Giga Drill Breaker has worn off**
Excavation.Skills.GigaDrillBreaker.On=&a**GIGA DRILL BREAKER ACTIVATED**
Excavation.Skills.GigaDrillBreaker.Refresh=&aYour &eGiga Drill Breaker &aability is refreshed!
Excavation.Skills.GigaDrillBreaker.Other.Off=Giga Drill Breaker&a has worn off for &e{0}
Excavation.Skills.GigaDrillBreaker.Other.On=&a{0}&2 has used &cGiga Drill Breaker!
#FISHING
Fishing.ScarcityTip=&e&oThis area is suffering from overfishing, cast your rod in a different spot for more fish. At least {0} blocks away.
Fishing.Scared=&7&oChaotic movements will scare fish!
Fishing.Exhausting=&c&oImproper use of the fishing rod will cause fatigue and wear out the rod!
Fishing.LowResourcesTip=&7You sense that there might not be many fish left in this area. Try fishing at least {0} blocks away.
Fishing.Ability.Info=Magic Hunter: &7 **Improves With Treasure Hunter Rank**
Fishing.Ability.Locked.0=LOCKED UNTIL {0}+ SKILL (SHAKE)
Fishing.Ability.Locked.1=LOCKED UNTIL {0}+ SKILL (ICE FISHING)
Fishing.Ability.Locked.2=LOCKED UNTIL {0}+ SKILL (MASTER ANGLER)
Fishing.SubSkill.TreasureHunter.Name=Treasure Hunter
Fishing.SubSkill.TreasureHunter.Description=Fish up misc. objects
Fishing.SubSkill.TreasureHunter.Stat=Treasure Hunter Rank: &a{0}&3/&a{1}
Fishing.SubSkill.TreasureHunter.Stat.Extra=Drop Rate: &7Common: &e{0} &aUncommon: &e{1}\n&9Rare: &e{2} &dEpic: &e{3} &6Legendary: &e{4} &bMythic: &e{5}
Fishing.SubSkill.MagicHunter.Name=Magic Hunter
Fishing.SubSkill.MagicHunter.Description=Find Enchanted Items
Fishing.SubSkill.MagicHunter.Stat=Magic Hunter Chance
Fishing.SubSkill.Shake.Name=Shake
Fishing.SubSkill.Shake.Description=Shake items off of mobs or players w/ fishing pole
Fishing.SubSkill.Shake.Stat=Shake Chance
Fishing.SubSkill.FishermansDiet.Name=Fisherman's Diet
Fishing.SubSkill.FishermansDiet.Description=Improves hunger restored from fished foods
Fishing.SubSkill.FishermansDiet.Stat=Fisherman's Diet:&a Rank {0}
Fishing.SubSkill.MasterAngler.Name=Master Angler
Fishing.SubSkill.MasterAngler.Description=Fish are caught more frequently, works better when fishing from a boat.
Fishing.SubSkill.MasterAngler.Stat=Fishing min wait time reduction: &a-{0} seconds
Fishing.SubSkill.MasterAngler.Stat.Extra=Fishing max wait time reduction: &a-{0} seconds
Fishing.SubSkill.IceFishing.Name=Ice Fishing
Fishing.SubSkill.IceFishing.Description=Allows you to fish in icy biomes
Fishing.SubSkill.IceFishing.Stat=Ice Fishing
Fishing.Chance.Raining=&9 Rain Bonus
Fishing.Listener=Fishing:
Fishing.Ability.TH.MagicFound=&7You feel a touch of magic with this catch...
Fishing.Ability.TH.Boom=&7BOOM TIME!!!
Fishing.Ability.TH.Poison=&7Something doesn't smell quite right...
Fishing.SkillName=FISHING
#HERBALISM
Herbalism.Ability.GTe.NeedMore=You need more seeds to spread Green Terra.
Herbalism.Ability.GTh.Fail=**GREEN THUMB FAIL**
Herbalism.Ability.GTh=&a**GREEN THUMB**
Herbalism.Ability.Lower=&7You lower your Hoe.
Herbalism.Ability.Ready=&3You &6ready&3 your Hoe.
Herbalism.Ability.ShroomThumb.Fail=**SHROOM THUMB FAIL**
Herbalism.SubSkill.GreenTerra.Name=Green Terra
Herbalism.SubSkill.GreenTerra.Description=Spread the Terra, 3x Drops, Boosts Green Thumb
Herbalism.SubSkill.GreenTerra.Stat=Green Terra Duration
Herbalism.SubSkill.GreenThumb.Name=Green Thumb
Herbalism.SubSkill.GreenThumb.Description=Auto-Plants crops when harvesting with hoe
Herbalism.SubSkill.GreenThumb.Stat=Green Thumb Chance
Herbalism.SubSkill.GreenThumb.Stat.Extra=Green Thumb Stage: &a Crops grow in stage {0}
Herbalism.Effect.4=Green Thumb (Blocks)
Herbalism.SubSkill.GreenThumb.Description.2=Make bricks mossy, or make grass grow
Herbalism.SubSkill.FarmersDiet.Name=Farmer's Diet
Herbalism.SubSkill.FarmersDiet.Description=Improves hunger restored from farmed foods
Herbalism.SubSkill.FarmersDiet.Stat=Farmer's Diet: &aRank {0}
Herbalism.SubSkill.DoubleDrops.Name=Double Drops
Herbalism.SubSkill.DoubleDrops.Description=Skillfully harvest double the loot
Herbalism.SubSkill.DoubleDrops.Stat=Double Drop Chance
Herbalism.SubSkill.VerdantBounty.Name=Verdant Bounty
Herbalism.SubSkill.VerdantBounty.Description=Masterfully harvest triple the loot
Herbalism.SubSkill.VerdantBounty.Stat=Triple Drop Chance
Herbalism.SubSkill.HylianLuck.Name=Hylian Luck
Herbalism.SubSkill.HylianLuck.Description=Gives a small chance of finding rare items
Herbalism.SubSkill.HylianLuck.Stat=Hylian Luck Chance
Herbalism.SubSkill.ShroomThumb.Name=Shroom Thumb
Herbalism.SubSkill.ShroomThumb.Description=Spread mycelium to dirt & grass
Herbalism.SubSkill.ShroomThumb.Stat=Shroom Thumb Chance
Herbalism.HylianLuck=&aThe luck of Hyrule is with you today!
Herbalism.Listener=Herbalism:
Herbalism.SkillName=HERBALISM
Herbalism.Skills.GTe.Off=**Green Terra has worn off**
Herbalism.Skills.GTe.On=&a**GREEN TERRA ACTIVATED**
Herbalism.Skills.GTe.Refresh=&aYour &eGreen Terra &aability is refreshed!
Herbalism.Skills.GTe.Other.Off=Green Terra&a has worn off for &e{0}
Herbalism.Skills.GTe.Other.On=&a{0}&2 has used &cGreen Terra!
#MINING
Mining.Ability.Locked.0=LOCKED UNTIL {0}+ SKILL (BLAST MINING)
Mining.Ability.Locked.1=LOCKED UNTIL {0}+ SKILL (BIGGER BOMBS)
Mining.Ability.Locked.2=LOCKED UNTIL {0}+ SKILL (DEMOLITIONS EXPERTISE)
Mining.Ability.Lower=&7You lower your Pickaxe.
Mining.Ability.Ready=&3You &6ready&3 your pickaxe.
Mining.SubSkill.SuperBreaker.Name=Super Breaker
Mining.SubSkill.SuperBreaker.Description=Speed+, Triple Drop Chance
Mining.SubSkill.SuperBreaker.Stat=Super Breaker Length
Mining.SubSkill.DoubleDrops.Name=Double Drops
Mining.SubSkill.DoubleDrops.Description=Skillfully mine double the loot
Mining.SubSkill.DoubleDrops.Stat=Double Drop Chance
Mining.SubSkill.MotherLode.Name=Mother Lode
Mining.SubSkill.MotherLode.Description=Masterfully mine triple the loot
Mining.SubSkill.MotherLode.Stat=Triple Drop Chance
Mining.SubSkill.BlastMining.Name=Blast Mining
Mining.SubSkill.BlastMining.Description=Bonuses to mining with TNT
Mining.SubSkill.BlastMining.Stat=Blast Mining:&a Rank {0}/{1} &7({2})
Mining.SubSkill.BlastMining.Stat.Extra=Blast Radius Increase: &a+{0}
Mining.SubSkill.BiggerBombs.Name=Bigger Bombs
Mining.SubSkill.BiggerBombs.Description=Increases TNT explosion radius
Mining.SubSkill.DemolitionsExpertise.Name=Demolitions Expertise
Mining.SubSkill.DemolitionsExpertise.Description=Decreases damage from TNT explosions
Mining.SubSkill.DemolitionsExpertise.Stat=Demolitions Expert Damage Decrease
Mining.Listener=Mining:
Mining.SkillName=MINING
Mining.Skills.SuperBreaker.Off=**Super Breaker has worn off**
Mining.Skills.SuperBreaker.On=&a**SUPER BREAKER ACTIVATED**
Mining.Skills.SuperBreaker.Other.Off=Super Breaker&a has worn off for &e{0}
Mining.Skills.SuperBreaker.Other.On=&a{0}&2 has used &cSuper Breaker!
Mining.Skills.SuperBreaker.Refresh=&aYour &eSuper Breaker &aability is refreshed!
#Blast Mining
Mining.Blast.Boom=&7**BOOM**
Mining.Blast.Cooldown=
Mining.Blast.Effect=+{0} ore yield, {1}x drops
Mining.Blast.Other.On=&a{0}&2 has used &cBlast Mining!
Mining.Blast.Refresh=&aYour &eBlast Mining &aability is refreshed!
#REPAIR
Repair.SubSkill.Repair.Name=Repair
Repair.SubSkill.Repair.Description=Repair Tools & Armor
Repair.SubSkill.GoldRepair.Name=Gold Repair ({0}+ SKILL)
Repair.SubSkill.GoldRepair.Description=Repair Gold Tools & Armor
Repair.SubSkill.IronRepair.Name=Iron Repair ({0}+ SKILL)
Repair.SubSkill.IronRepair.Description=Repair Iron Tools & Armor
Repair.SubSkill.StoneRepair.Name=Stone Repair ({0}+ SKILL)
Repair.SubSkill.StoneRepair.Description=Repair Stone Tools
Repair.SubSkill.RepairMastery.Name=Repair Mastery
Repair.SubSkill.RepairMastery.Description=Increased repair amount
Repair.SubSkill.RepairMastery.Stat=Repair Mastery: &aExtra {0} durability restored
Repair.SubSkill.SuperRepair.Name=Super Repair
Repair.SubSkill.SuperRepair.Description=Double effectiveness
Repair.SubSkill.SuperRepair.Stat=Super Repair Chance
Repair.SubSkill.DiamondRepair.Name=Diamond Repair ({0}+ SKILL)
Repair.SubSkill.DiamondRepair.Description=Repair Diamond Tools & Armor
Repair.SubSkill.ArcaneForging.Name=Arcane Forging
Repair.SubSkill.ArcaneForging.Description=Repair magic items
Repair.SubSkill.ArcaneForging.Stat=Arcane Forging: &eRank {0}/{1}
Repair.SubSkill.ArcaneForging.Stat.Extra=&3Arcane Forging Odds:&7 Success &a{0}&7%, Failure &c{1}&7%
Repair.Error=&4mcMMO encountered an error attempting to repair this item!
Repair.Listener.Anvil=&aYou have placed an anvil, anvils can repair tools and armor.
Repair.Listener=Repair:
Repair.SkillName=REPAIR
Repair.Skills.AdeptDiamond=&4You're not skilled enough to repair Diamond.
Repair.Skills.AdeptGold=&4You're not skilled enough to repair Gold.
Repair.Skills.AdeptIron=&4You're not skilled enough to repair Iron.
Repair.Skills.AdeptStone=&4You're not skilled enough to repair Stone.
Repair.Skills.Adept=&cYou must be level &e{0}&c to repair &e{1}
Repair.Skills.FeltEasy=&7That felt easy.
Repair.Skills.FullDurability=&7That is at full durability.
Repair.Skills.StackedItems=&4You can't repair stacked items.
Repair.Pretty.Name=Repair
#Arcane Forging
Repair.Arcane.Downgrade=Arcane power has decreased for this item.
Repair.Arcane.Fail=Arcane power has permanently left the item.
Repair.Arcane.Lost=You were not skilled enough to keep any enchantments.
Repair.Arcane.Perfect=&aYou have sustained the arcane energies in this item.
#SALVAGE
Salvage.Pretty.Name=Salvage
Salvage.SubSkill.UnderstandingTheArt.Name=Understanding The Art
Salvage.SubSkill.UnderstandingTheArt.Description=You're not just digging through your neighbors trash, you're taking care of the environment.\nPowers up various properties of Salvaging.
Salvage.SubSkill.ScrapCollector.Name=Scrap Collector
Salvage.SubSkill.ScrapCollector.Description=Salvage materials from an item, a perfect salvage depends on skill and luck.
Salvage.SubSkill.ScrapCollector.Stat=Scrap Collector: &aSalvage up to &e{0}&a items.
Salvage.SubSkill.ArcaneSalvage.Name=Arcane Salvaging
Salvage.SubSkill.ArcaneSalvage.Description=Extract enchantments from items
Salvage.SubSkill.ArcaneSalvage.Stat=Arcane Salvaging: &eRank {0}/{1}
Salvage.Ability.Bonus.0=Scrap Collector
Salvage.Ability.Bonus.1=Salvage up to &e{0}&a items. Some luck is involved.
Salvage.Arcane.ExtractFull=&7AS Full-Enchant Chance
Salvage.Arcane.ExtractPartial=&7AS Partial-Enchant Chance
Salvage.Skills.Success=&aItem salvaged!
Salvage.Skills.Adept.Damaged=&4You aren't skilled enough to salvage damaged items.
Salvage.Skills.Adept.Level=You must be level &e{0}&c to salvage &e{1}
Salvage.Skills.TooDamaged=&4This item is too damaged to be salvaged.
Salvage.Skills.ArcaneFailed=&cYou were unable to extract the knowledge contained within this item.
Salvage.Skills.ArcanePartial=&cYou were only able to extract some of the knowledge contained within this item.
Salvage.Skills.ArcaneSuccess=&aYou were able to extract all the knowledge contained within this item!
Salvage.Listener.Anvil=&aYou have placed a Salvage anvil, use this to Salvage tools and armor.
Salvage.Listener=Salvage:
Salvage.SkillName=SALVAGE
Salvage.Skills.Lottery.Normal=&6You were able to salvage &3{0}&6 materials from &e{1}&6.
Salvage.Skills.Lottery.Perfect=&a&lPerfect!&r&6 You salvaged &3{1}&6 effortlessly, retrieving &3{0}&6 materials.
Salvage.Skills.Lottery.Untrained=&7You aren't properly trained in salvaging. You were only able to recover &c{0}&7 materials from &a{1}&7.
#Anvil (Shared between SALVAGE and REPAIR)
Anvil.Unbreakable=This item is unbreakable!
Anvil.Repair.Reject.CustomModelData=A mysterious force prevents you from repairing this item...
Anvil.Salvage.Reject.CustomModelData=A mysterious force prevents you from salvaging this item...
#CROSSBOWS
Crossbows.SkillName=CROSSBOWS
Crossbows.Ability.Lower=&7You lower your crossbow.
Crossbows.Ability.Ready=&3You &6ready&3 your Crossbow.
Crossbows.Skills.SSG.Refresh=&aYour &eSuper Shotgun &aability is refreshed!
Crossbows.Skills.SSG.Other.On=&a{0}&2 used &Super Shotgun!
Crossbows.SubSkill.PoweredShot.Name=Powered Shot
Crossbows.SubSkill.PoweredShot.Description=Increases damage done with crossbows
Crossbows.SubSkill.PoweredShot.Stat=Powered Shot Bonus Damage
Crossbows.SubSkill.CrossbowsLimitBreak.Name=Crossbows Limit Break
Crossbows.SubSkill.CrossbowsLimitBreak.Description=Breaking your limits. Increased damage against tough opponents. Intended for PVP, up to server settings for whether it will boost damage in PVE.
Crossbows.SubSkill.CrossbowsLimitBreak.Stat=Limit Break Max DMG
Crossbows.SubSkill.TrickShot.Name=Trick Shot
Crossbows.SubSkill.TrickShot.Description=Richochet arrows with steep angles
Crossbows.SubSkill.TrickShot.Stat=Trick Shot Max Bounces
Crossbows.SubSkill.TrickShot.Stat.Extra=Trick Shot Max Bounces: &a{0}
Crossbows.SubSkill.TrickShot.Stat.Extra2=Trick Shot Reduced DMG per Bounce: &a{0}
Crossbows.SubSkill.SuperShotgun.Name=Super Shotgun
Crossbows.Listener=Crossbows:
#TRIDENTS
Tridents.SkillName=TRIDENTS
Tridents.Ability.Lower=&7You lower your trident.
Tridents.Ability.Ready=&3You &6ready&3 your Trident.
Tridents.SubSkill.Impale.Name=Impale
Tridents.SubSkill.Impale.Description=Increases damage done with tridents
Tridents.SubSkill.Impale.Stat=Impale Bonus Damage
Tridents.SubSkill.TridentsLimitBreak.Name=Tridents Limit Break
Tridents.SubSkill.TridentsLimitBreak.Description=Breaking your limits. Increased damage against tough opponents. Intended for PVP, up to server settings for whether it will boost damage in PVE.
Tridents.SubSkill.TridentsLimitBreak.Stat=Limit Break Max DMG
Tridents.SubSkill.TridentAbility.Name=WIP
Tridents.Listener=Tridents:
#MACES
Commands.McTop.MacesNotSupported=[[GREEN]]Maces are not supported in this version of Minecraft.
Maces.SkillName=MACES
Maces.Ability.Lower=&7You lower your mace.
Maces.Ability.Ready=&3You &6ready&3 your Mace.
Maces.SubSkill.MacesLimitBreak.Name=Maces Limit Break
Maces.SubSkill.MacesLimitBreak.Description=Breaking your limits. Increased damage against tough opponents. Intended for PVP, up to server settings for whether it will boost damage in PVE.
Maces.SubSkill.MacesLimitBreak.Stat=Limit Break Max DMG
Maces.SubSkill.Crush.Name=Crush
Maces.SubSkill.Crush.Description=Adds bonus damage to your attacks.
Maces.SubSkill.Crush.Stat=Crush Damage
Maces.SubSkill.Cripple.Proc=**CRIPPLED**
Maces.SubSkill.Cripple.Activated=CRIPPLED TARGET!
Maces.SubSkill.Cripple.Name=Cripple
Maces.SubSkill.Cripple.Description=Adds a chance to cripple your target.
Maces.SubSkill.Cripple.Stat=Cripple Chance
Maces.SubSkill.Cripple.Stat.Extra=[[DARK_AQUA]]Cripple Duration: &e{0}s&a vs Players, &e{1}s&a vs Mobs.
Maces.Listener=Maces:
#SWORDS
Swords.Ability.Lower=&7You lower your sword.
Swords.Ability.Ready=&3You &6ready&3 your Sword.
Swords.Combat.Rupture.Note.Update.One=&7(Rupture Note): Periodic damage is non-lethal occurring twice a second and bypasses armor
Swords.Combat.Bleeding.Started=&4 You're bleeding!
Swords.Combat.Bleeding.Stopped=&7The bleeding has &astopped&7!
Swords.Combat.Bleeding=&a**ENEMY BLEEDING**
Swords.Combat.Counter.Hit=&4Hit with a counter-attack!
Swords.Combat.Countered=&a**COUNTER-ATTACKED**
Swords.Combat.SS.Struck=&4Struck by SERRATED STRIKES!
Swords.SubSkill.CounterAttack.Name=Counter Attack
Swords.SubSkill.CounterAttack.Description=Reflect a portion of damage when attacked!
Swords.SubSkill.CounterAttack.Stat=Counter Attack Chance
Swords.SubSkill.SerratedStrikes.Name=Serrated Strikes
Swords.SubSkill.SerratedStrikes.Description=Deal partial damage in an AOE with a chance to apply Rupture!
Swords.SubSkill.SerratedStrikes.Stat=Serrated Strikes Length
Swords.SubSkill.Rupture.Name=Rupture
Swords.SubSkill.Rupture.Description=A damage over time effect that ends explosively
Swords.SubSkill.Stab.Name=Stab
Swords.SubSkill.Stab.Description=Adds bonus damage to your attacks.
Swords.SubSkill.Stab.Stat=Stab Damage
Swords.SubSkill.SwordsLimitBreak.Name=Swords Limit Break
Swords.SubSkill.SwordsLimitBreak.Description=Breaking your limits. Increased damage against tough opponents. Intended for PVP, up to server settings for whether it will boost damage in PVE.
Swords.SubSkill.SwordsLimitBreak.Stat=Limit Break Max DMG
Swords.SubSkill.Rupture.Stat=Rupture Chance
Swords.SubSkill.Rupture.Stat.Extra=[[DARK_AQUA]]Rupture Duration: &e{0}s&a vs Players, &e{1}s&a vs Mobs.
Swords.SubSkill.Rupture.Stat.TickDamage=[[DARK_AQUA]]Rupture Pure Tick Damage: &e{0}&a vs Players, &e{1}&a vs Mobs.
Swords.SubSkill.Rupture.Stat.ExplosionDamage=[[DARK_AQUA]]Rupture Explosion Damage: &e{0}&a vs Players, &e{1}&a vs Mobs
Swords.Effect.4=Serrated Strikes Rupture+
Swords.Effect.5={0} Tick Rupture
Swords.Listener=Swords:
Swords.SkillName=SWORDS
Swords.Skills.SS.Off=**Serrated Strikes has worn off**
Swords.Skills.SS.On=&a**SERRATED STRIKES ACTIVATED**
Swords.Skills.SS.Refresh=&aYour &eSerrated Strikes &aability is refreshed!
Swords.Skills.SS.Other.Off=Serrated Strikes&a has worn off for &e{0}
Swords.Skills.SS.Other.On=&a{0}&2 has used &cSerrated Strikes!
#TAMING
Taming.Ability.Bonus.0=Environmentally Aware
Taming.Ability.Bonus.1=Wolves avoid danger
Taming.Ability.Bonus.2=Thick Fur
Taming.Ability.Bonus.3=1/{0} Damage, Fire Resistance
Taming.Ability.Bonus.4=Shock Proof
Taming.Ability.Bonus.5=Explosives do 1/{0} normal damage
Taming.Ability.Bonus.6=Sharpened Claws
Taming.Ability.Bonus.7=+{0} Damage
Taming.Ability.Bonus.8=Fast Food Service
Taming.Ability.Bonus.9={0} Chance for heal on attack
Taming.Ability.Bonus.10=Holy Hound
Taming.Ability.Bonus.11=Regain health when damaged by magic or poison
Taming.Ability.Locked.0=LOCKED UNTIL {0}+ SKILL (ENVIRONMENTALLY AWARE)
Taming.Ability.Locked.1=LOCKED UNTIL {0}+ SKILL (THICK FUR)
Taming.Ability.Locked.2=LOCKED UNTIL {0}+ SKILL (SHOCK PROOF)
Taming.Ability.Locked.3=LOCKED UNTIL {0}+ SKILL (SHARPENED CLAWS)
Taming.Ability.Locked.4=LOCKED UNTIL {0}+ SKILL (FAST FOOD SERVICE)
Taming.Ability.Locked.5=LOCKED UNTIL {0}+ SKILL (HOLY HOUND)
Taming.Combat.Chance.Gore=Gore Chance
Taming.SubSkill.BeastLore.Name=Beast Lore
Taming.SubSkill.BeastLore.Description=Bone-whacking inspects wolves & ocelots
Taming.SubSkill.ShockProof.Name=Shock Proof
Taming.SubSkill.ShockProof.Description=Explosive Damage Reduction
Taming.SubSkill.CallOfTheWild.Name=Call of the Wild
Taming.SubSkill.CallOfTheWild.Description=Summon an animal to your side
Taming.SubSkill.CallOfTheWild.Description.2=&7COTW: Crouch and left-click with\n {0} {1} (Ocelot), {2} {3} (Wolf), {4} {5} (Horse)
Taming.SubSkill.FastFoodService.Name=Fast Food Service
Taming.SubSkill.FastFoodService.Description=Chance for wolves to heal on attack
Taming.SubSkill.HolyHound.Name=Holy Hound
Taming.SubSkill.HolyHound.Description=Healed by Magic & Poison
Taming.SubSkill.Gore.Name=Gore
Taming.SubSkill.Gore.Description=Critical Strike that applies Rupture
Taming.SubSkill.SharpenedClaws.Name=Sharpened Claws
Taming.SubSkill.SharpenedClaws.Description=Damage Bonus
Taming.SubSkill.EnvironmentallyAware.Name=Environmentally Aware
Taming.SubSkill.EnvironmentallyAware.Description=Cactus/Lava Phobia, Fall DMG Immune
Taming.SubSkill.ThickFur.Name=Thick Fur
Taming.SubSkill.ThickFur.Description=DMG Reduction, Fire Resistance
Taming.SubSkill.Pummel.Name=Pummel
Taming.SubSkill.Pummel.Description=Your Wolves have a chance of knocking back foes
Taming.SubSkill.Pummel.TargetMessage=You've been knocked back by a wolf!
Taming.Listener.Wolf=&8Your wolf scurries back to you...
Taming.Listener=Taming:
Taming.SkillName=TAMING
Taming.Summon.COTW.Success.WithoutLifespan=&a(Call Of The Wild) &7You have summoned a &6{0}&7
Taming.Summon.COTW.Success.WithLifespan=&a(Call Of The Wild) &7You have summoned a &6{0}&7 and it has a duration of &6{1}&7 seconds.
Taming.Summon.COTW.Limit=&a(Call Of The Wild) &7You can only have &c{0} &7summoned &7{1} pets at the same time.
Taming.Summon.COTW.TimeExpired=&a(Call Of The Wild) &7Time is up, your &6{0}&7 departs.
Taming.Summon.COTW.Removed=&a(Call Of The Wild) &7Your summoned &6{0}&7 has vanished from this world.
Taming.Summon.COTW.BreedingDisallowed=&a(Call Of The Wild) &cYou cannot breed a summoned animal.
Taming.Summon.COTW.NeedMoreItems=&a(Call Of The Wild) &7You need &e{0}&7 more &3{1}&7(s)
Taming.Summon.Name.Format=&6(COTW) &f{0}'s {1}
#UNARMED
Unarmed.Ability.Bonus.0=Steel Arm Style
Unarmed.Ability.Bonus.1=+{0} DMG Upgrade
Unarmed.Ability.IronGrip.Attacker=Your opponent has an iron grip!
Unarmed.Ability.IronGrip.Defender=&aYour iron grip kept you from being disarmed!
Unarmed.Ability.Lower=&7You lower your fists.
Unarmed.Ability.Ready=&3You &6ready&3 your fists.
Unarmed.SubSkill.Berserk.Name=Berserk
Unarmed.SubSkill.Berserk.Description=+50% DMG, Breaks weak materials
Unarmed.SubSkill.Berserk.Stat=Berserk Length
Unarmed.SubSkill.Disarm.Name=Disarm
Unarmed.SubSkill.Disarm.Description=Drops the foes item held in hand
Unarmed.SubSkill.Disarm.Stat=Disarm Chance
Unarmed.SubSkill.UnarmedLimitBreak.Name=Unarmed Limit Break
Unarmed.SubSkill.UnarmedLimitBreak.Description=Breaking your limits. Increased damage against tough opponents. Intended for PVP, up to server settings for whether it will boost damage in PVE.
Unarmed.SubSkill.UnarmedLimitBreak.Stat=Limit Break Max DMG
Unarmed.SubSkill.SteelArmStyle.Name=Steel Arm Style
Unarmed.SubSkill.SteelArmStyle.Description=Hardens your arm over time
Unarmed.SubSkill.ArrowDeflect.Name=Arrow Deflect
Unarmed.SubSkill.ArrowDeflect.Description=Deflect arrows
Unarmed.SubSkill.ArrowDeflect.Stat=Arrow Deflect Chance
Unarmed.SubSkill.IronGrip.Name=Iron Grip
Unarmed.SubSkill.IronGrip.Description=Prevents you from being disarmed
Unarmed.SubSkill.IronGrip.Stat=Iron Grip Chance
Unarmed.SubSkill.BlockCracker.Name=Block Cracker
Unarmed.SubSkill.BlockCracker.Description=Break rock with your fists
Unarmed.Listener=Unarmed:
Unarmed.SkillName=UNARMED
Unarmed.Skills.Berserk.Off=**Berserk has worn off**
Unarmed.Skills.Berserk.On=&a**BERSERK ACTIVATED**
Unarmed.Skills.Berserk.Other.Off=Berserk&a has worn off for &e{0}
Unarmed.Skills.Berserk.Other.On=&a{0}&2 has used &cBerserk!
Unarmed.Skills.Berserk.Refresh=&aYour &eBerserk &aability is refreshed!
#WOODCUTTING
Woodcutting.Ability.0=Leaf Blower
Woodcutting.Ability.1=Blow away leaves
Woodcutting.Ability.Locked.0=LOCKED UNTIL {0}+ SKILL (LEAF BLOWER)
Woodcutting.SubSkill.TreeFeller.Name=Tree Feller
Woodcutting.SubSkill.TreeFeller.Description=Make trees explode
Woodcutting.SubSkill.TreeFeller.Stat=Tree Feller Length
Woodcutting.SubSkill.LeafBlower.Name=Leaf Blower
Woodcutting.SubSkill.LeafBlower.Description=Blow Away Leaves
Woodcutting.SubSkill.KnockOnWood.Name=Knock On Wood
Woodcutting.SubSkill.KnockOnWood.Description=Find additional goodies when using Tree Feller
Woodcutting.SubSkill.KnockOnWood.Stat=Knock on Wood
Woodcutting.SubSkill.KnockOnWood.Loot.Normal=Standard loot from trees
Woodcutting.SubSkill.KnockOnWood.Loot.Rank2=Standard loot from trees and experience orbs
Woodcutting.SubSkill.HarvestLumber.Name=Harvest Lumber
Woodcutting.SubSkill.HarvestLumber.Description=Skillfully extract up to double the Lumber
Woodcutting.SubSkill.HarvestLumber.Stat=Double Drop Chance
Woodcutting.SubSkill.CleanCuts.Name=Clean Cuts
Woodcutting.SubSkill.CleanCuts.Description=Masterfully extract up to triple the Lumber
Woodcutting.SubSkill.CleanCuts.Stat=Triple Drop Chance
Woodcutting.SubSkill.Splinter.Name=Splinter
Woodcutting.SubSkill.Splinter.Description=Cut down trees more efficiently.
Woodcutting.SubSkill.BarkSurgeon.Name=Bark Surgeon
Woodcutting.SubSkill.BarkSurgeon.Description=Extract useful materials when stripping trees.
Woodcutting.SubSkill.NaturesBounty.Name=Nature's Bounty
Woodcutting.SubSkill.NaturesBounty.Description=Gather experience from nature.
Woodcutting.Listener=Woodcutting:
Woodcutting.SkillName=WOODCUTTING
Woodcutting.Skills.TreeFeller.Off=**Tree Feller has worn off**
Woodcutting.Skills.TreeFeller.On=&a**TREE FELLER ACTIVATED**
Woodcutting.Skills.TreeFeller.Refresh=&aYour &eTree Feller &aability is refreshed!
Woodcutting.Skills.TreeFeller.Other.Off=Tree Feller&a has worn off for &e{0}
Woodcutting.Skills.TreeFeller.Other.On=&a{0}&2 has used &cTree Feller!
Woodcutting.Skills.TreeFeller.Splinter=YOUR AXE SPLINTERS INTO DOZENS OF PIECES!
Woodcutting.Skills.TreeFeller.Threshold=That tree is too large!
#ABILITIY
#COMBAT
Combat.ArrowDeflect=&f**ARROW DEFLECT**
Combat.BeastLore=&a**BEAST LORE**
Combat.BeastLoreHealth=&3Health (&a{0}&3/{1})
Combat.BeastLoreOwner=&3Owner (&c{0}&3)
Combat.BeastLoreHorseSpeed=&3Horse Movement Speed (&a{0} blocks/s&3)
Combat.BeastLoreHorseJumpStrength=&3Horse Jump Strength (&aMax {0} blocks&3)
Combat.Gore=&a**GORED**
Combat.StruckByGore=**YOU HAVE BEEN GORED**
Combat.TargetDazed=Target was &4Dazed
Combat.TouchedFuzzy=&4Touched Fuzzy. Felt Dizzy.
#COMMANDS
##generic
mcMMO.Description=&3About the &emcMMO&3 Project:,&6mcMMO is an &copen source&6 RPG mod created in February 2011,&6by &9nossr50&6. The goal is to provide a quality RPG experience.,&3Tips:,&6 - &aUse &c/mcmmo help&a to see commands,&6 - &aType &c/SKILLNAME&a to see detailed skill info,&3Developers:,&6 - &anossr50 &9(Creator & Project Lead),&6 - &aelectronicboy &9(Dev),&6 - &akashike &9(Dev),&6 - &at00thpick1 &9(Classic Maintainer)
mcMMO.Description.FormerDevs=&3Former Devs: &aGJ, NuclearW, bm01, TfT_02, Glitchfinder
Commands.addlevels.AwardAll.1=&aYou were awarded {0} levels in all skills!
Commands.addlevels.AwardAll.2=All skills have been modified for {0}.
Commands.addlevels.AwardSkill.1=&aYou were awarded {0} levels in {1}!
Commands.addlevels.AwardSkill.2={0} has been modified for {1}.
Commands.addxp.AwardAll=&aYou were awarded {0} experience in all skills!
Commands.addxp.AwardSkill=&aYou were awarded {0} experience in {1}!
Commands.Ability.Off=Ability use toggled &coff
Commands.Ability.On=Ability use toggled &aon
Commands.Ability.Toggle=Ability use has been toggled for &e{0}
Commands.AdminChat.Off=Admin Chat only &cOff
Commands.AdminChat.On=Admin Chat only &aOn
Commands.AdminToggle=&3 /adminchat &a- Toggle admin chat
Commands.Chat.Console=*Console*
Commands.Cooldowns.Header=&6--= &amcMMO Ability Cooldowns&6 =--
Commands.Cooldowns.Row.N=\ &c{0}&f - &6{1} seconds left
Commands.Cooldowns.Row.Y=\ &b{0}&f - &2Ready!
Commands.Database.CooldownMS=You must wait {0} milliseconds before using this command again.
Commands.Database.Cooldown=You must wait {0} seconds before using this command again.
Commands.Database.Processing=Your previous command is still being processed. Please wait.
Commands.Disabled=This command is disabled.
Commands.DoesNotExist= &cPlayer does not exist in the database!
Commands.GodMode.Disabled=mcMMO Godmode Disabled
Commands.GodMode.Enabled=mcMMO Godmode Enabled
Commands.AdminChatSpy.Enabled=mcMMO Party Chat Spy Enabled
Commands.AdminChatSpy.Disabled=mcMMO Party Chat Spy Disabled
Commands.AdminChatSpy.Toggle=mcMMO Party Chat has been toggled for &e{0}
Commands.AdminChatSpy.Chat=&6[SPY: &a{0}&6] &f{1}
Commands.GodMode.Forbidden=[mcMMO] God Mode not permitted on this world (See Permissions)
Commands.GodMode.Toggle=God mode has been toggled for &e{0}
Commands.Healthbars.Changed.HEARTS=[mcMMO] Your healthbar display type was changed to &cHearts&f.
Commands.Healthbars.Changed.BAR=[mcMMO] Your healthbar display type was changed to &eBoxes&f.
Commands.Healthbars.Changed.DISABLED=[mcMMO] Your mob healthbars have been &7disabled&f.
Commands.Healthbars.Invalid=Invalid healthbar type!
Commands.Inspect=&3 /inspect <player> &a- View detailed player info
Commands.Invite.Success=&aInvite sent successfully.
Commands.Leaderboards=&3 /mctop <skill> <page> &a- Leaderboards
Commands.mcgod=&3 /mcgod &a- Toggle GodMode
Commands.mchud.Invalid=That is not a valid HUD type.
Commands.mcpurge.Success=&aThe database was successfully purged!
Commands.mcrank.Heading=&6-=PERSONAL RANKINGS=-
Commands.mcrank.Overall=Overall&a - &6Rank &f#&a{0}
Commands.mcrank.Player=&eRankings for &f{0}
Commands.mcrank.Skill=&e{0}&a - &6Rank &f#&a{1}
Commands.mcrank.Unranked=&fUnranked
Commands.mcrefresh.Success={0}''s cooldowns have been refreshed.
Commands.mcremove.Success=&a{0} was successfully removed from the database!
Commands.mctop.Tip=&6Tip: Use &c/mcrank&6 to view all of your personal rankings!
Commands.mmoedit=&3 /mmoedit [player] <skill> <newvalue> &a - Modify target
Commands.mmoedit.AllSkills.1=&aYour level in all skills was set to {0}!
Commands.mmoedit.Modified.1=&aYour level in {0} was set to {1}!
Commands.mmoedit.Modified.2={0} has been modified for {1}.
Commands.mcconvert.Database.Same=You are already using the {0} database!
Commands.mcconvert.Database.InvalidType={0} is not a valid database type.
Commands.mcconvert.Database.Start=&7Starting conversion from {0} to {1}...
Commands.mcconvert.Database.Finish=&7Database migration complete; the {1} database now has all data from the {0} database.
Commands.mmoshowdb=The currently used database is &a{0}
Commands.mcconvert.Experience.Invalid=Unknown formula type! Valid types are: &aLINEAR &cand &aEXPONENTIAL.
Commands.mcconvert.Experience.Same=Already using formula type {0}
Commands.mcconvert.Experience.Start=&7Starting conversion from {0} to {1} curve
Commands.mcconvert.Experience.Finish=&7Formula conversion complete; now using {0} XP curve.
Commands.ModDescription=&a- Read brief mod description
Commands.NoConsole=This command does not support console usage.
Commands.Notifications.Off=Ability notifications toggled &coff
Commands.Notifications.On=Ability notifications toggled &aon
Commands.Offline=This command does not work for offline players.
Commands.NotLoaded=Player profile is not loaded yet.
Commands.Party.Status=&8NAME: &f{0} {1} &8LEVEL: &3{2}
Commands.Party.Status.Alliance=&8ALLY: &f{0}
Commands.Party.UnlockedFeatures=&8Unlocked Features: &7&o{0}
Commands.Party.ShareMode=&8SHARE MODE:
Commands.Party.ItemShare=&7ITEM &3({0})
Commands.Party.ExpShare=&7EXP &3({0})
Commands.Party.ItemShareCategories=&8Sharing Items: &7&o{0}
Commands.Party.MembersNear=&8NEAR YOU &3{0}&8/&3{1}
Commands.Party.Accept=&3 /party accept &a- Accept party invite
Commands.Party.Chat.Off=Party Chat only &cOff
Commands.Party.Chat.On=Party Chat only &aOn
Commands.Party.Commands=&c---[]&aPARTY COMMANDS&c[]---
Commands.Party.Invite.0=&cALERT: &aYou have received a party invite for {0} from {1}
Commands.Party.Invite.1=&eType &a/party accept&e to accept the invite
Commands.Party.Invite=&3 /party invite <player> &a- Send party invite
Commands.Party.Invite.Accepted=&aInvite Accepted. You have joined party {0}
Commands.Party.Join=&7Joined Party: {0}
Commands.Party.PartyFull=&6{0}&c is full!
Commands.Party.PartyFull.Invite=You cannot invite &e{0}&c to &a{1}&c because it already has &3{2}&c players in it!
Commands.Party.PartyFull.InviteAccept=You cannot join &a{0}&c because it already has &3{1}&c players in it!
Commands.Party.Create=&7Created Party: {0}
Commands.Party.Rename=&7Party name changed to: &f{0}
Commands.Party.SetSharing=&7Party {0} sharing set to: &3{1}
Commands.Party.ToggleShareCategory=&7Party item sharing for &6{0} &7has been &3{1}
Commands.Party.AlreadyExists=&4Party {0} already exists!
Commands.Party.Kick=&cYou were kicked from party &a{0}&c!
Commands.Party.Leave=&eYou have left that party
Commands.Party.Members.Header=&c-----[]&aMEMBERS&c[]-----
Commands.Party.None=&cYou are not in a party.
Commands.Party.Quit=&3 /party quit &a- Leave your current party
Commands.Party.Teleport=&3 /party teleport <player> &a- Teleport to party member
Commands.Party.Toggle=&3 /party chat &a- Toggle Party Chat
Commands.Party1=&3 /party create <name> &a- Create a new party
Commands.Party2=&3 /party join <player> &a- Join a players party
Commands.Party.Alliance.Header=&c-----[]&aPARTY ALLIANCE&c[]-----
Commands.Party.Alliance.Ally=&f{0} &8IS ALLIED WITH: &f{1}
Commands.Party.Alliance.Members.Header=&c-----[]&aALLIANCE MEMBERS&c[]-----
Commands.Party.Alliance.Invite.0=ALERT: &aYou have received a party alliance invite for {0} from {1}
Commands.Party.Alliance.Invite.1=Type &a/party alliance accept&e to accept the invite
Commands.Party.Alliance.Invite.Accepted=&aAlliance invite Accepted.
Commands.Party.Alliance.None=&cYour party does not have an ally.
Commands.Party.Alliance.AlreadyAllies=&cYour party already has an ally. Disband with &3/party alliance disband
Commands.Party.Alliance.Help.0=&cThis party hasn't formed an alliance. Invite a party leader
Commands.Party.Alliance.Help.1=&c to an alliance with &3/party alliance invite <player>&c.
Commands.ptp.Enabled=Party teleporting &aenabled
Commands.ptp.Disabled=Party teleporting &cdisabled
Commands.ptp.NoRequests=&cYou have no teleport requests at this time
Commands.ptp.NoWorldPermissions=&c[mcMMO] You do not have permission to teleport to the world {0}.
Commands.ptp.Request1=&e{0} &ahas requested to teleport to you.
Commands.ptp.Request2=&aTo teleport, type &e/ptp accept&a. Request expires in &c{0} &aseconds.
Commands.ptp.AcceptAny.Enabled=Party teleport request confirmation &aenabled
Commands.ptp.AcceptAny.Disabled=Party teleport request confirmation &cdisabled
Commands.ptp.RequestExpired=&cParty teleport request has expired!
Commands.PowerLevel.Leaderboard=&e--mcMMO&9 Power Level &eLeaderboard--
Commands.PowerLevel.Capped=&4POWER LEVEL: &a{0} &4MAX LEVEL: &e{1}
Commands.PowerLevel=&4POWER LEVEL: &a{0}
Commands.Reset.All=&aAll of your skill levels have been reset successfully.
Commands.Reset.Single=&aYour {0} skill level has been reset successfully.
Commands.Reset=&3 /skillreset <skill|all> &a- Reset a skill's level to 0
Commands.Scoreboard.Clear=&3mcMMO scoreboard cleared.
Commands.Scoreboard.NoBoard=&cThe mcMMO scoreboard is not active.
Commands.Scoreboard.Keep=&3The mcMMO scoreboard will stay up until you use &a/mcscoreboard clear&3.
Commands.Scoreboard.Timer=&3The mcMMO scoreboard will clear &6{0}&3 seconds from now.
Commands.Scoreboard.Help.0=&6 == &aHelp for &c/mcscoreboard&6 ==
Commands.Scoreboard.Help.1=&3/mcscoreboard&b clear &f - clear the McMMO scoreboard
Commands.Scoreboard.Help.2=&3/mcscoreboard&b keep &f - keep the mcMMO scoreboard up
Commands.Scoreboard.Help.3=&3/mcscoreboard&b time [n] &f - clear the McMMO scoreboard after &dn&f seconds
Commands.Scoreboard.Tip.Keep=&6Tip: Use &c/mcscoreboard keep&6 while the scoreboard is shown to keep it from going away.
Commands.Scoreboard.Tip.Clear=&6Tip: Use &c/mcscoreboard clear&6 to get rid of the scoreboard.
Commands.XPBar.Reset=&6XP Bar settings for mcMMO have been reset.
Commands.XPBar.SettingChanged=&6XP Bar setting for &a{0}&6 is now set to &a{1}
Commands.Skill.Invalid=That is not a valid skillname!
Commands.Skill.ChildSkill=Child skills are not valid for this command!
Commands.Skill.Leaderboard=-&e-mcMMO &9{0}&e Leaderboard--
Commands.SkillInfo=&3 /<skill> &a- View detailed information about a skill
Commands.Stats=&3 /mcstats &a- View your mcMMO stats
Commands.ToggleAbility=&3 /mcability &a- Toggle ability activation with right click
Commands.Usage.0=&cProper usage is /{0}
Commands.Usage.1=&cProper usage is /{0} {1}
Commands.Usage.2=&cProper usage is /{0} {1} {2}
Commands.Usage.3=&cProper usage is /{0} {1} {2} {3}
Commands.Usage.3.XP=&cProper usage is /{0} {1} {2} {3}&7 (You can include -s at the end to execute the command without informing the player, effectively silencing it)
Commands.Usage.FullClassName=classname
Commands.Usage.Level=level
Commands.Usage.Message=message
Commands.Usage.Page=page
Commands.Usage.PartyName=name
Commands.Usage.Password=password
Commands.Usage.Player=player
Commands.Usage.Rate=rate
Commands.Usage.Skill=skill
Commands.Usage.SubSkill=subskill
Commands.Usage.XP=xp
Commands.Description.mmoinfo=Read details about a skill or mechanic.
Commands.MmoInfo.Mystery=&7You haven't unlocked this skill yet, but when you do you will be able to read details about it here!
Commands.MmoInfo.NoMatch=That subskill doesn't exist!
Commands.MmoInfo.Header=&3-=[]=====[]&6 MMO Info &3[]=====[]=-
Commands.MmoInfo.SubSkillHeader=&6Name:&e {0}
Commands.MmoInfo.DetailsHeader=&3-=[]=====[]&a Details &3[]=====[]=-
Commands.MmoInfo.OldSkill=&7mcMMO skills are being converted into an improved modular skill system, unfortunately this skill has not been converted yet and lacks detailed stats. The new system will allow for faster release times for new mcMMO skills and greater flexibility with existing skills.
Commands.MmoInfo.Mechanics=&3-=[]=====[]&6 Mechanics &3[]=====[]=-
Commands.MmoInfo.Stats=STATS: {0}
Commands.Mmodebug.Toggle=mcMMO Debug Mode is now &6{0}&7, use this command again to toggle. With debug mode true, you can punch blocks to print useful information used for support.
mcMMO.NoInvites=&cYou have no invites at this time
mcMMO.NoPermission=&4Insufficient permissions.
mcMMO.NoSkillNote=&8If you don't have access to a skill it will not be shown here.
##party
Party.Forbidden=[mcMMO] Parties not permitted on this world (See Permissions)
Party.Help.0=&cProper usage is &3{0} <player> [password].
Party.Help.1=&cTo create a party, use &3{0} <name> [password].
Party.Help.2=&cConsult &3{0} &cfor more information
Party.Help.3=&cUse &3{0} <player> [password] &cto join or &3{1} &cto quit
Party.Help.4=&cTo lock or unlock your party, use &3{0}
Party.Help.5=&cTo password protect your party, use &3{0} <password>
Party.Help.6=&cTo kick a player from your party, use &3{0} <player>
Party.Help.7=&cTo transfer ownership of your party, use &3{0} <player>
Party.Help.8=&cTo disband your party, use &3{0}
Party.Help.9=&cUse &3{0} &cto share items with party members
Party.Help.10=&cUse &3{0} &cto enable XP sharing with party members
Party.InformedOnJoin={0} &ahas joined your party
Party.InformedOnQuit={0} &ahas left your party
Party.InformedOnNameChange=&6{0} &ahas set the party name to &f{1}
Party.InvalidName=&4That is not a valid party name.
Party.Invite.Self=&cYou can't invite yourself!
Party.IsLocked=&cThis party is already locked!
Party.IsntLocked=&cThis party is not locked!
Party.Locked=&cParty is locked, only party leader may invite.
Party.NotInYourParty=&4{0} is not in your party
Party.NotOwner=&4You are not the party leader.
Party.Target.NotOwner=&4{0} is not the party leader.
Party.Owner.New=&a{0} is the new party leader.
Party.Owner.NotLeader=&4You are no longer the party leader.
Party.Owner.Player =&aYou are now the party leader.
Party.Password.None=&cThis party is password protected. Please provide a password to join.
Party.Password.Incorrect=&cParty password is incorrect.
Party.Password.Set=&aParty password set to {0}
Party.Password.Removed=&aParty password has been cleared.
Party.Player.Invalid=&cThat is not a valid player.
Party.NotOnline=&4{0} is not online!
Party.Player.InSameParty=&c{0} already is in your party!
Party.PlayerNotInParty=&4{0} is not in a party
Party.Specify=&cYou must specify a party.
Party.Teleport.Dead=&cYou can't teleport to a dead player.
Party.Teleport.Hurt=&cYou have been hurt in the last {0} seconds and cannot teleport.
Party.Teleport.Player=&aYou have teleported to {0}.
Party.Teleport.Self=&cYou can't teleport to yourself!
Party.Teleport.Target=&a{0} has teleported to you.
Party.Teleport.Disabled=&c{0} doesn't allow party teleportation.
Party.Rename.Same=&cThat is already the name of your party!
Party.Join.Self=&cYou can't join yourself!
Party.Unlocked=&7Party is unlocked
Party.Disband=&7The party has been disbanded
Party.Alliance.Formed=&7Your party is now allies with &a{0}
Party.Alliance.Disband=&7Your party is no longer allies with &c{0}
Party.Status.Locked=&4(INVITE-ONLY)
Party.Status.Unlocked=&2(OPEN)
Party.LevelUp=&eParty level increased by {0}. Total ({1})
Party.Feature.Chat=Party Chat
Party.Feature.Teleport=Party Teleport
Party.Feature.Alliance=Alliances
Party.Feature.ItemShare=Item Sharing
Party.Feature.XpShare=XP Sharing
Party.Feature.Locked.Chat=LOCKED UNTIL {0}+ (PARTY CHAT)
Party.Feature.Locked.Teleport=LOCKED UNTIL {0}+ (PARTY TELEPORT)
Party.Feature.Locked.Alliance=LOCKED UNTIL {0}+ (ALLIANCES)
Party.Feature.Locked.ItemShare=LOCKED UNTIL {0}+ (ITEM SHARING)
Party.Feature.Locked.XpShare=LOCKED UNTIL {0}+ (XP SHARING)
Party.Feature.Disabled.1=&cParty chat is not unlocked yet.
Party.Feature.Disabled.2=&cParty teleport is not unlocked yet.
Party.Feature.Disabled.3=&cParty alliances are not unlocked yet.
Party.Feature.Disabled.4=&cParty item sharing is not unlocked yet.
Party.Feature.Disabled.5=&cParty XP sharing is not unlocked yet.
Party.ShareType.Xp=XP
Party.ShareType.Item=ITEM
Party.ShareMode.None=NONE
Party.ShareMode.Equal=EQUAL
Party.ShareMode.Random=RANDOM
Party.ItemShare.Category.Loot=Loot
Party.ItemShare.Category.Mining=Mining
Party.ItemShare.Category.Herbalism=Herbalism
Party.ItemShare.Category.Woodcutting=Woodcutting
Party.ItemShare.Category.Misc=Misc
##xp
Commands.XPGain.Acrobatics=Falling
Commands.XPGain.Alchemy=Brewing Potions
Commands.XPGain.Archery=Attacking Monsters
Commands.XPGain.Axes=Attacking Monsters
Commands.XPGain.Child=Gains levels from Parent Skills
Commands.XPGain.Crossbows=Attacking Monsters
Commands.XPGain.Excavation=Digging and finding treasures
Commands.XPGain.Fishing=Fishing (Go figure!)
Commands.XPGain.Herbalism=Harvesting Herbs
Commands.XPGain.Maces=Attacking Monsters
Commands.XPGain.Mining=Mining Stone & Ore
Commands.XPGain.Repair=Repairing
Commands.XPGain.Swords=Attacking Monsters
Commands.XPGain.Taming=Animal Taming, or combat w/ your wolves
Commands.XPGain.Tridents=Attacking Monsters
Commands.XPGain.Unarmed=Attacking Monsters
Commands.XPGain.Woodcutting=Chopping down trees
Commands.XPGain=&8XP GAIN: &f{0}
Commands.xplock.locked=&6Your XP BAR is now locked to {0}!
Commands.xplock.unlocked=&6Your XP BAR is now &aUNLOCKED&6!
Commands.xprate.modified=&cThe XP RATE was modified to {0}
Commands.xprate.over=&cmcMMO XP Rate Event is OVER!!
Commands.xprate.proper.0=&cProper usage to change the XP rate is /xprate <integer> <true/false>
Commands.xprate.proper.1=&cProper usage to restore the XP rate to default is /xprate reset
Commands.xprate.proper.2=&cPlease specify true or false to indicate if this is an xp event or not
Commands.NegativeNumberWarn=Don't use negative numbers!
Commands.Event.Start=&amcMMO&6 Event!
Commands.Event.Stop=&amcMMO&3 Event Over!
Commands.Event.Stop.Subtitle=&aI hope you had fun!
Commands.Event.XP=&3XP Rate is now &6{0}&3x
Commands.xprate.started.0=&6XP EVENT FOR mcMMO HAS STARTED!
Commands.xprate.started.1=&6mcMMO XP RATE IS NOW {0}x!
# Admin Notifications
Server.ConsoleName=&e[Server]
Notifications.Admin.XPRate.Start.Self=&7You have set the global XP rate multiplier to &6{0}x
Notifications.Admin.XPRate.End.Self=&7You ended the XP rate event.
Notifications.Admin.XPRate.End.Others={0} &7has ended the XP rate event
Notifications.Admin.XPRate.Start.Others={0} &7has started or modified an XP rate event with global multiplier {1}x
Notifications.Admin.Format.Others=&6(&amcMMO &3Admin&6) &7{0}
Notifications.Admin.Format.Self=&6(&amcMMO&6) &7{0}
# Event
XPRate.Event=&6mcMMO is currently in an XP rate event! XP rate is {0}x!
#GUIDES
Guides.Available=&7Guide for {0} available - type /{1} ? [page]
Guides.Header=&6-=&a{0} Guide&6=-
Guides.Page.Invalid=Not a valid page number!
Guides.Page.OutOfRange=That page does not exist, there are only {0} total pages.
Guides.Usage= Usage is /{0} ? [page]
##Acrobatics
Guides.Acrobatics.Section.0=&3About Acrobatics:\n&eAcrobatics is the art of moving Gracefuly in mcMMO.\n&eIt provides combat bonuses and environment damage bonuses.\n\n&3XP GAIN:\n&eTo gain XP in this skill you need to perform a dodge\n&ein combat or survive falls from heights that damage you.
Guides.Acrobatics.Section.1=&3How does Rolling work?\n&eYou have a passive chance when you take fall damage\n&eto negate the damage done. You can hold the sneak button to\n&edouble your chances during the fall.\n&eThis triggers a Graceful Roll instead of a standard one.\n&eGraceful Rolls are like regular rolls but are twice as likely to\n&eoccur and provide more damage safety than regular rolls.\n&eRolling chance is tied to your skill level
Guides.Acrobatics.Section.2=&3How does Dodge work?\n&eDodge is a passive chance when you are\n&einjured in combat to halve the damage taken.\n&eIt is tied to your skill level.
##Alchemy
Guides.Alchemy.Section.0=[[DARK_AQUA]]About Alchemy:\n[[YELLOW]]Alchemy is about brewing potions.\n[[YELLOW]]It provides a speed increase in the potion brew time, as well\n[[YELLOW]]as the addition of new (previously) unobtainable potions.\n\n\n[[DARK_AQUA]]XP GAIN:\n[[YELLOW]]To gain XP in this skill you need to brew potions.
Guides.Alchemy.Section.1=[[DARK_AQUA]]How does Catalysis work?\n[[YELLOW]]Catalysis speeds of the brewing process, with a\n[[YELLOW]]max speed of 4x at level 1000.\n[[YELLOW]]This ability is unlocked at level 100 by default.
Guides.Alchemy.Section.2=[[DARK_AQUA]]How does Concoctions work?\n[[YELLOW]]Concoctions allows brewing of more potions with custom ingredients.\n[[YELLOW]]Which special ingredients are unlocked is determined\n[[YELLOW]]by your Rank. There are 8 ranks to unlock.
Guides.Alchemy.Section.3=[[DARK_AQUA]]Concoctions tier 1 ingredients:\n[[YELLOW]]Blaze Powder, Fermented Spider Eye, Ghast Tear, Redstone,\n[[YELLOW]]Glowstone Dust, Sugar, Glistering Melon, Golden Carrot,\n[[YELLOW]]Magma Cream, Nether Wart, Spider Eye, Gunpowder, Rabbit's Foot,\n[[YELLOW]]Pufferfish\n[[YELLOW]](Vanilla Potions)
Guides.Alchemy.Section.4=[[DARK_AQUA]]Concoctions tier 2 ingredients:\n[[YELLOW]]Carrot (Potion of Haste)\n[[YELLOW]]Slimeball (Potion of Dullness)\n\n[[DARK_AQUA]]Concoctions tier 3 ingredients:\n[[YELLOW]]Quartz (Potion of Absorption)\n[[YELLOW]]
Guides.Alchemy.Section.5=[[DARK_AQUA]]Concoctions tier 4 ingredients:\n[[YELLOW]]Apple (Potion of Health Boost)\n[[YELLOW]]Rotten Flesh (Potion of Hunger)\n\n[[DARK_AQUA]]Concoctions tier 5 ingredients:\n[[YELLOW]]Brown Mushroom (Potion of Nausea)\n[[YELLOW]]Ink Sack (Potion of Blindness)
Guides.Alchemy.Section.6=[[DARK_AQUA]]Concoctions tier 6 ingredients:\n[[YELLOW]]Fern (Potion of Saturation)\n\n[[DARK_AQUA]]Concoctions tier 7 ingredients:\n[[YELLOW]]Poisonous Potato (Potion of Decay)\n\n[[DARK_AQUA]]Concoctions tier 8 ingredients:\n[[YELLOW]]Regular Golden Apple (Potion of Resistance)
##Archery
Guides.Archery.Section.0=&3About Archery:\n&eArchery is about shooting with your bow and arrow.\n&eIt provides various combat bonuses, such as a damage boost\nðat scales with your level and the ability to daze your\n&eopponents in PvP. In addition to this, you can retrieve\n&esome of your spent arrows from the corpses of your foes.\n\n\n&3XP GAIN:\n&eTo gain XP in this skill you need to shoot mobs or\n&eother players.
Guides.Archery.Section.1=&3How does Skill Shot work?\n&eSkill Shot provides additional damage to your shots.\n&eThe bonus damage from Skill Shot increases as you\n&elevel in Archery.\n&eWith the default settings, your archery damage increases 10%\n&eevery 50 levels, to a maximum of 200% bonus damage.
Guides.Archery.Section.2=&3How does Daze work?\n&eYou have a passive chance to daze other players when\n&eyou shoot them. When Daze triggers it forces your opponents\n&eto look straight up for a short duration.\n&eA Daze shot also deals an additional 4 damage (2 hearts).
Guides.Archery.Section.3=&3How does Arrow Retrieval work?\n&eYou have a passive chance to retrieve some of your arrows\n&ewhen you kill a mob with your bow.\n&eThis chance increases as you level in Archery.\n&eBy default, this ability increases by 0.1% per level, up to 100%\n&eat level 1000.
##Axes
Guides.Axes.Section.0=&3About Axes:\n&eWith the Axes skill you can use your axe for much more then\n&ejust deforesting! You can hack and chop away at mobs\n&eand players to gain XP, hitting mobs with the effect of\n&eknockback and inflicting DEADLY criticals on mobs and players.\n&eYour axe also becomes a hand-held woodchipper,\n&ebreaking down the enemy's armor with ease as your level\n&eincreases.\n&3XP GAIN:\n&eTo gain XP in this skill you need hit other mobs or players\n&ewith an Axe.
Guides.Axes.Section.1=&3How does Skull Splitter work?\n&eThis ability allows you to deal an AoE (Area of Effect) hit.\n&eThis AoE hit will deal half as much damage as you did to the\n&emain target, so it's great for clearing out large piles of mobs.
Guides.Axes.Section.2=&3How does Critical Strikes work?\n&eCritical Strikes is a passive ability which gives players a\n&echance to deal additional damage.\n&eWith the default settings, every 2 skill levels in Axes awards a\n&e0.1% chance to deal a Critical Strike, causing 2.0 times damage\n&eto mobs or 1.5 times damage against other players.
Guides.Axes.Section.3=&3How does Axe Mastery work?\n&eAxe Mastery is a passive ability that will add additional damage\n&eto your hits when using Axes.\n&eBy default, the bonus damage increases by 1 every 50 levels,\n&eup to a cap of 4 extra damage at level 200.
Guides.Axes.Section.4=&3How does Armor Impact work?\n&eStrike with enough force to shatter armor!\n&eArmor Impact has a passive chance to damage your\n&eopponent's armor. This damage increases as you level in Axes.
Guides.Axes.Section.5=&3How does Greater Impact work?\n&eYou have a passive chance to achieve a greater impact when\n&ehitting mobs or players with your axe.\n&eBy default this chance is 25%. This passive ability has an\n&eextreme knockback effect, similar to the Knockback II\n&eenchantment. In addition, it deals bonus damage to the target.
##Excavation
Guides.Excavation.Section.0=&3About Excavation:\n&eExcavation is the act of digging up dirt to find treasures.\n&eBy excavating the land you will find treasures.\n&eThe more you do this the more treasures you can find.\n\n&3XP GAIN:\n&eTo gain XP in this skill you must dig with a shovel in hand.\n&eOnly certain materials can be dug up for treasures and XP.
Guides.Excavation.Section.1=&3Compatible Materials:\n&eGrass, Dirt, Sand, Clay, Gravel, Mycelium, Soul Sand, Snow
Guides.Excavation.Section.2=&3How to use Giga Drill Breaker:\n&eWith a shovel in hand right click to ready your tool.\n&eOnce in this state you have about 4 seconds to make\n&econtact with Excavation compatible materials this will\n&eactivate Giga Drill Breaker.
Guides.Excavation.Section.3=&3What is Giga Drill Breaker?\n&eGiga Drill Breaker is an ability with a cooldown\n&etied to Excavation skill. It triples your chance\n&eof finding treasures and enables instant break\n&eon Excavation materials.
Guides.Excavation.Section.4=&3How does Archaeology work?\n&eEvery possible treasure for Excavation has its own\n&eskill level requirement for it to drop, as a result it's\n&edifficult to say how much it is helping you.\n&eJust keep in mind that the higher your Excavation skill\n&eis, the more treasures that can be found.\n&eAnd also keep in mind that each type of Excavation\n&ecompatible material has its own unique list of treasures.\n&eIn other words you will find different treasures in Dirt\nðan you would in Gravel.
Guides.Excavation.Section.5=&3Notes about Excavation:\n&eExcavation drops are completely customizeable\n&eSo results vary server to server.
##Fishing
Guides.Fishing.Section.0=&3About Fishing:\n&eWith the Fishing skill, Fishing is exciting again!\n&eFind hidden treasures, and shake items off mobs.\n\n&3XP GAIN:\n&eCatch fish.
Guides.Fishing.Section.1=&3How does Treasure Hunter work?\n&eThis ability allows you to find treasure from fishing \n&ewith a small chance of the items being enchanted.\n&eEvery possible treasure for Fishing has a chance\n&eto drop on any level. It depends however\n&ewhat the rarity of the item is how often it will drop.\n&eThe higher your Fishing skill is, the better\n&eyour chances are to find better treasures.
Guides.Fishing.Section.2=&3How does Ice Fishing work?\n&eThis passive skill allows you to fish in ice lakes!\n&eCast your fishing rod in an ice lake and the ability will\n&ecreate a small hole in the ice to fish in.
Guides.Fishing.Section.3=&3How does Master Angler work?\n&eThis passive skill increases the bite chance while fishing.\n&eWhen you've unlocked this ability, fishing while in\n&ea boat improves odds of catching a fish.
Guides.Fishing.Section.4=&3How does Shake work?\n&eThis active ability allows you to shake items loose from mobs\n&eby hooking them with the fishing rod. \n&eMobs will drop items they would normally drop on death.\n&eIt is also possible to acquire mob skulls, which are normally \n&eunobtainable in survival mode.
Guides.Fishing.Section.5=&3How does Fisherman's Diet work?\n&eThis passive skill increases the amount of hunger restored \n&efrom eating fish.
Guides.Fishing.Section.6=&3Notes about Fishing:\n&eFishing drops are completely customizable,\n&eso results vary server to server.
##Herbalism
Guides.Herbalism.Section.0=&3About Herbalism:\n&eHerbalism is about collecting herbs and plants.\n\n\n&3XP GAIN:\n&eCollect plants and herbs.
Guides.Herbalism.Section.1=&3Compatible Blocks\n&eWheat, Potatoes, Carrots, Melons, \n&ePumpkins, Sugar Canes, Cocoa Beans, Flowers, Cacti, Mushrooms,\n&eNether Wart, Lily Pads, and Vines.
Guides.Herbalism.Section.2=&3How does Green Terra work?\n&eGreen Terra is an active ability, you can right-click\n&ewhile holding a hoe to activate Green Terra.\n&eGreen Terra grants players a chance to get 3x drops from\n&eharvesting plants. It also gives players the ability to\n&espread life into blocks and transform them using seeds\n&efrom your inventory.
Guides.Herbalism.Section.3=&3How does Green Thumb (Crops) work?\n&eThis passive ability will automatically replant crops when\n&eharvesting.\n&eYour chance of success depends on your Herbalism skill.
Guides.Herbalism.Section.4=&3How does Green Thumb (Cobble/Stone Brick/Dirt) work?\n&eThis active ability allows you to turn blocks into their\n&e"plant-related" counterparts. You can do this by right-clicking\n&ea block, while holding seeds. This will consume 1 seed.
Guides.Herbalism.Section.5=&3How does Farmer's Diet work?\n&eThis passive skill increases the amount of hunger restored \n&ewhen eating Bread, Cookies, Melons, Mushroom Soup, Carrots,\n&eand Potatoes.
Guides.Herbalism.Section.6=&3How does Hylian Luck work?\n&eThis passive ability gives you a chance to find rare items\n&ewhen certain blocks are broken with a sword.
Guides.Herbalism.Section.7=&3How do Double Drops work?\n&eThis passive ability gives players more yield from their\n&eharvests.
##Mining
Guides.Mining.Section.0=&3About Mining:\n&eMining consists of mining stone and ores. It provides bonuses\n&eto the amount of materials dropped while mining.\n\n&3XP GAIN:\n&eTo gain XP in this skill, you must mine with a pickaxe in hand.\n&eOnly certain blocks award XP.
Guides.Mining.Section.1=&3Compatible Materials:\n&eStone, Coal Ore, Iron Ore, Gold Ore, Diamond Ore, Redstone Ore,\n&eLapis Ore, Obsidian, Mossy Cobblestone, Ender Stone,\n&eGlowstone, and Netherrack.
Guides.Mining.Section.2=&3How to use Super Breaker:\n&eWith a pickaxe in your hand, right click to ready your tool.\n&eOnce in this state, you have about 4 seconds to make contact\n&ewith Mining compatible materials, which will activate Super\n&eBreaker.
Guides.Mining.Section.3=&3What is Super Breaker?\n&eSuper Breaker is an ability with a cooldown tied to the Mining\n&eskill. It triples your chance of extra items dropping and\n&eenables instant break on Mining materials.
Guides.Mining.Section.4=&3How to use Blast Mining:\n&eWith a pickaxe in hand,\n&ecrouch and right-click on TNT from a distance. This will cause the TNT\n&eto instantly explode.
Guides.Mining.Section.5=&3How does Blast Mining work?\n&eBlast Mining is an ability with a cooldown tied to the Mining\n&eskill. It gives bonuses when mining with TNT and allows you\n&eto remote detonate TNT. There are three parts to Blast Mining.\n&eThe first part is Bigger Bombs, which increases blast radius.\n&eThe second is Demolitions Expert, which decreases damage\n&efrom TNT explosions. The third part simply increases the\n&eamount of ores dropped from TNT and decreases the\n&edebris dropped.
##Repair
Guides.Repair.Section.0=&3About Repair:\n&eRepair allows you to use an iron block to repair armor and\n&etools.\n\n&3XP GAIN:\n&eRepair tools or armor using the mcMMO Anvil. This is an\n&eiron block by default and should not be confused with\nðe Vanilla Minecraft Anvil.
Guides.Repair.Section.1=&3How can I use Repair?\n&ePlace down a mcMMO Anvil and right-click to repair the item \n&eyou're currently holding. This consumes 1 item on every use.
Guides.Repair.Section.2=&3How does Repair Mastery work?\n&eRepair Mastery increases the repair amount. The extra amount\n&erepaired is influenced by your Repair skill level.
Guides.Repair.Section.3=&3How does Super Repair work?\n&eSuper Repair is a passive ability. When repairing an item,\n&eit grants players a chance to repair an item with\n&edouble effectiveness.
Guides.Repair.Section.4=&3How does Arcane Forging work?\n&eThis passive ability allows you to repair items with a certain\n&echance of maintaining its enchantments. The enchants may be\n&ekept at their existing levels, downgraded to a lower level,\n&eor lost entirely.
##Salvage
Guides.Salvage.Section.0=&3About Salvage:\n&eSalvage allows you to use a gold block to salvage armor and\n&etools.\n\n&3XP GAIN:\n&eSalvage is a child skill of Repair and Fishing, your Salvage\n&eskill level is based on your Fishing and Repair skill levels.
Guides.Salvage.Section.1=&3How can I use Salvage?\n&ePlace down a mcMMO Salvage Anvil and right-click to salvage\nðe item you're currently holding. This will break apart the item,\n&eand give back materials used to craft the item.\n\n&eFor example, salvaging an iron pickaxe will give you iron bars.
Guides.Salvage.Section.2=&3How does Advanced Salvage work?\n&eWhen unlocked, this ability allows you to salvage damaged items.\n&eThe yield percentage increases as you level up. A higher yield\n&emeans that you can get more materials back.\n&eWith advanced salvage you will always get 1 material back,\n&eunless the item is too damaged. So you don't have to worry\n&eabout destroying items without getting anything in return.
Guides.Salvage.Section.3=&3To illustrate how this works, here's an example:\n&eLet's say we salvage a gold pickaxe which is damaged for 20%,\nðis means that the maximum amount you could get is only 2\n&e(because the pick is crafted with 3 ingots - each worth\n&e33,33% durability) which is equal to 66%. If your yield\n&epercentage is below 66% you are not able to get 2 ingots.\n&eIf it is above this value you are able to gain the "full amount",\n&ewhich means that you will get 2 ingots.
Guides.Salvage.Section.4=&3How does Arcane Salvage work?\n&eThis ability allows you to get enchanted books when salvaging\n&eenchanted items. Depending on your level the chance of\n&esuccessfully extracting a full or partial enchantment varies.\n\n&eWhen an enchantment is partially extracted, the enchantment\n&ebook will have a lower level enchantment compared to what\n&eit was on the item.
##Smelting
Guides.Smelting.Section.0=Coming soon...
##Swords
Guides.Swords.Section.0=&3About Swords:\n&eThis skill awards combat bonuses to anyone fighting with a\n&esword.\n\n&3XP GAIN:\n&eXP is gained based on the amount of damage dealt to mobs or \n&eother players when wielding a sword.
Guides.Swords.Section.1=&3How does Serrated Strikes work?\n&eSerrated Strikes is an active ability, you can activate it by\n&eright-clicking with a sword. This ability allows you to deal \n&ean AoE (Area of Effect) hit. This AoE will do a bonus 25%\n&edamage and may apply Rupture
Guides.Swords.Section.2=&3How does Counter Attack work?\n&eCounter Attack is an active ability. When blocking and taking\n&ehits from mobs, you will have a chance to reflect 50% of \nðe damage that was taken.
Guides.Swords.Section.3=&3How does Rupture work?\n&eRupture causes enemies to take damage every two seconds. The \n&etarget will bleed until the effect wears off, or death, \n&ewhichever comes first.\n&eThe duration of the bleed is increased by your sword skill.
##Taming
Guides.Taming.Section.0=&3About Taming:\n&eTaming will give players various combat bonuses when using\n&etamed wolves.\n\n&3XP GAIN:\n&eTo gain XP in this skill, you need to tame wolves/ocelots or\n&eget into combat with your wolves.
Guides.Taming.Section.1=&3How does Call of the Wild work?\n&eCall of the Wild is an active ability that will allow you to summon\n&ea wolf or an ocelot by your side. You can do this by\n&esneaking + left-clicking while holding bones or fish.
Guides.Taming.Section.2=&3How does Beast Lore work?\n&eBeast Lore allows players to inspect pets and to check the\n&estats of wolves and ocelots. Left-click a wolf or ocelot to use\n&eBeast Lore.
Guides.Taming.Section.3=&3How does Gore work?\n&eGore is a passive ability that has a chance of inflicting a\n&ebleeding effect on your wolves' targets.
Guides.Taming.Section.4=&3How does Sharpened Claws work?\n&eSharpened Claws provides a damage bonus to damage dealt\n&eby wolves. The damage bonus depends on your Taming level.
Guides.Taming.Section.5=&3How does Environmentally Aware work?\n&eThis passive ability will allow wolves to teleport to you when\nðey get near hazards, such as Cacti/Lava. It will also give\n&ewolves fall damage immunity.
Guides.Taming.Section.6=&3How does Thick Fur work?\n&eThis passive ability will reduce damage and make wolves\n&efire resistant.
Guides.Taming.Section.7=&3How does Shock Proof work?\n&eThis passive ability reduces damage done to wolves\n&efrom explosions.
Guides.Taming.Section.8=&3How does Fast Food Service work?\n&eThis passive ability gives wolves a chance to heal whenever\nðey perform an attack.
##Unarmed
Guides.Unarmed.Section.0=&3About Unarmed:\n&eUnarmed will give players various combat bonuses when using\n&eyour fists as a weapon. \n\n&3XP GAIN:\n&eXP is gained based on the amount of damage dealt to mobs \n&eor other players when unarmed.
Guides.Unarmed.Section.1=&3How does Berserk work?\n&eBeserk is an active ability that is activated by\n&eright-clicking. While in Beserk mode, you deal 50% more\n&edamage and you can break weak materials instantly, such as\n&eDirt and Grass.
Guides.Unarmed.Section.2=&3How does Steel Arm Style work?\n&eSteel Arm Style increases the damage dealt when hitting mobs or\n&eplayers with your fists.
Guides.Unarmed.Section.3=&3How does Arrow Deflect work?\n&eArrow Deflect is a passive ability that gives you a chance\n&eto deflect arrows shot by Skeletons or other players.\n&eThe arrow will fall harmlessly to the ground.
Guides.Unarmed.Section.4=&3How does Iron Grip work?\n&eIron Grip is a passive ability that counters disarm. As your\n&eunarmed level increases, the chance of preventing a disarm increases.
Guides.Unarmed.Section.5=&3How does Disarm work?\n&eThis passive ability allows players to disarm other players,\n&ecausing the target's equipped item to fall to the ground.
##Woodcutting
Guides.Woodcutting.Section.0=&3About Woodcutting:\n&eWoodcutting is all about chopping down trees.\n\n&3XP GAIN:\n&eXP is gained whenever you break log blocks.
Guides.Woodcutting.Section.1=&3How does Tree Feller work?\n&eTree Feller is an active ability, you can right-click\n&ewhile holding an ax to activate Tree Feller. This will\n&ecause the entire tree to break instantly, dropping all\n&eof its logs at once.
Guides.Woodcutting.Section.2=&3How does Leaf Blower work?\n&eLeaf Blower is a passive ability that will cause leaf\n&eblocks to break instantly when hit with an axe. By default,\nðis ability unlocks at level 100.
Guides.Woodcutting.Section.3=&3How do Double Drops work?\n&eThis passive ability gives you a chance to obtain an extra\n&eblock for every log you chop.
# Crossbows
Guides.Crossbows.Section.0=&3About Crossbows:\n&eCrossbows is all about shooting with your crossbow.\n\n&3XP GAIN:\n&eXP is gained whenever you shoot mobs with a crossbow.\nThis is a WIP skill and more information will be added soon.
Guides.Crossbows.Section.1=&3How does Trickshot work?\n&eTrickshot is an passive ability, you shoot your bolts at a shallow angle with a crossbow to attempt a Trickshot. This will cause the arrow to ricochet off of blocks and potentially hit a target. The number of potential bounces from a ricochet depend on the rank of Trickshot.
# Tridents
Guides.Tridents.Section.0=&3About Tridents:\n&eTridents skill involves impaling foes with your trident.\n\n&3XP GAIN:\n&eXP is gained whenever you hit mobs with a trident.\nThis is a WIP skill and more information will be added soon.
Guides.Maces.Section.0=&3About Maces:\n&eMaces is all about smashing your foes with a mace.\n\n&3XP GAIN:\n&eXP is gained whenever you hit mobs with a mace.\nThis is a WIP skill and more information will be added soon.
#INSPECT
Inspect.Offline= &cYou do not have permission to inspect offline players!
Inspect.OfflineStats=mcMMO Stats for Offline Player &e{0}
Inspect.Stats=&amcMMO Stats for &e{0}
Inspect.TooFar=You are too far away to inspect that player!
#ITEMS
Item.ChimaeraWing.Fail=&c**CHIMAERA WING FAILED!**
Item.ChimaeraWing.Pass=**CHIMAERA WING**
Item.ChimaeraWing.Name=Chimaera Wing
Item.ChimaeraWing.Lore=&7Teleports you to your bed.
Item.ChimaeraWing.NotEnough=You need &e{0}&c more &6{1}&c!
Item.NotEnough=You need &e{0}&c more &6{1}&c!
Item.Generic.Wait=You need to wait before you can use this again! &e({0}s)
Item.Injured.Wait=You were injured recently and must wait to use this. &e({0}s)
Item.FluxPickaxe.Name=Flux Pickaxe
Item.FluxPickaxe.Lore.1=&7Has a chance of instantly smelting ores.
Item.FluxPickaxe.Lore.2=&7Requires Smelting level {0}+
#TELEPORTATION
Teleport.Commencing=&7Commencing teleport in &6({0}) &7seconds, please stand still...
Teleport.Cancelled=&4Teleportation canceled!
#SKILLS
Skills.Child=&6(CHILD SKILL)
Skills.Disarmed=&4You have been disarmed!
Skills.Header=-----[] &a{0}&c []-----
Skills.NeedMore=&4You need more &7{0}
Skills.NeedMore.Extra=&4You need more &7{0}{1}
Skills.Parents= PARENTS
Skills.Stats={0}&a{1}&3 XP(&7{2}&3/&7{3}&3)
Skills.ChildStats={0}&a{1}
Skills.MaxXP=Max
Skills.TooTired=You are too tired to use that ability again. &e({0}s)
Skills.TooTired.Named=&7(&6{0}&e {1}s&7)
Skills.TooTired.Extra=&6{0} &eSuper Ability CDs - {1}
Skills.Cancelled=&6{0} &ccancelled!
Skills.ConfirmOrCancel=&aRight-click again to confirm &6{0}&a. Left-click to cancel.
Skills.AbilityGateRequirementFail=&7You require &e{0}&7 more levels of &3{1}&7 to use this super ability.
#STATISTICS
Stats.Header.Combat=&6-=COMBAT SKILLS=-
Stats.Header.Gathering=&6-=GATHERING SKILLS=-
Stats.Header.Misc=&6-=MISC SKILLS=-
Stats.Own.Stats=&a[mcMMO] Stats
#PERKS
Perks.XP.Name=Experience
Perks.XP.Desc=Receive boosted XP in certain skills.
Perks.Lucky.Name=Luck
Perks.Lucky.Desc=Gives {0} skills and abilities a 33.3% better chance to activate.
Perks.Lucky.Desc.Login=Gives certain skills and abilities a 33.3% better chance to activate.
Perks.Lucky.Bonus=&6 ({0} with Lucky Perk)
Perks.Cooldowns.Name=Fast Recovery
Perks.Cooldowns.Desc=Cuts cooldown duration by {0}.
Perks.ActivationTime.Name=Endurance
Perks.ActivationTime.Desc=Increases ability activation time by {0} seconds.
Perks.ActivationTime.Bonus=&6 ({0}s with Endurance Perk)
#HARDCORE
Hardcore.Mode.Disabled=&6[mcMMO] Hardcore mode {0} disabled for {1}.
Hardcore.Mode.Enabled=&6[mcMMO] Hardcore mode {0} enabled for {1}.
Hardcore.DeathStatLoss.Name=Skill Death Penalty
Hardcore.DeathStatLoss.PlayerDeath=&6[mcMMO] &4You have lost &9{0}&4 levels from death.
Hardcore.DeathStatLoss.PercentageChanged=&6[mcMMO] The stat loss percentage was changed to {0}.
Hardcore.Vampirism.Name=Vampirism
Hardcore.Vampirism.Killer.Failure=&6[mcMMO] &e{0}&7 was too unskilled to grant you any knowledge.
Hardcore.Vampirism.Killer.Success=&6[mcMMO] &3You have stolen &9{0}&3 levels from &e{1}.
Hardcore.Vampirism.Victim.Failure=&6[mcMMO] &e{0}&7 was unable to steal knowledge from you!
Hardcore.Vampirism.Victim.Success=&6[mcMMO] &e{0}&4 has stolen &9{1}&4 levels from you!
Hardcore.Vampirism.PercentageChanged=&6[mcMMO] The stat leech percentage was changed to {0}.
#MOTD
MOTD.Donate=&3Donation Info:
MOTD.Hardcore.Enabled=&6[mcMMO] &3Hardcore Mode enabled: &4{0}
MOTD.Hardcore.DeathStatLoss.Stats=&6[mcMMO] &3Skill Death Penalty: &4{0}%
MOTD.Hardcore.Vampirism.Stats=&6[mcMMO] &3Vampirism Stat Leech: &4{0}%
MOTD.PerksPrefix=&6[mcMMO Perks]
MOTD.Version=&6[mcMMO] Running version &3{0}
MOTD.Website=&6[mcMMO] &a{0}&e - mcMMO Website
#SMELTING
Smelting.SubSkill.UnderstandingTheArt.Name=Understanding The Art
Smelting.SubSkill.UnderstandingTheArt.Description=Maybe you're spending a bit too much time smelting in the caves.\nPowers up various properties of Smelting.
Smelting.SubSkill.UnderstandingTheArt.Stat=Vanilla XP Multiplier: &e{0}x
Smelting.Ability.Locked.0=LOCKED UNTIL {0}+ SKILL (VANILLA XP BOOST)
Smelting.Ability.Locked.1=LOCKED UNTIL {0}+ SKILL (FLUX MINING)
Smelting.SubSkill.FuelEfficiency.Name=Fuel Efficiency
Smelting.SubSkill.FuelEfficiency.Description=Increase the burn time of fuel used in furnaces when smelting
Smelting.SubSkill.FuelEfficiency.Stat=Fuel Efficiency Multiplier: &e{0}x
Smelting.SubSkill.SecondSmelt.Name=Second Smelt
Smelting.SubSkill.SecondSmelt.Description=Double the resources gained from smelting
Smelting.SubSkill.SecondSmelt.Stat=Second Smelt Chance
Smelting.Effect.4=Vanilla XP Boost
Smelting.Effect.5=Increase vanilla XP gained while smelting
Smelting.SubSkill.FluxMining.Name=Flux Mining
Smelting.SubSkill.FluxMining.Description=Chance for ores to be instantly smelted while mining
Smelting.SubSkill.FluxMining.Stat=Flux Mining Chance
Smelting.Listener=Smelting:
Smelting.SkillName=SMELTING
#COMMAND DESCRIPTIONS
Commands.Description.addlevels=Add mcMMO levels to a user
Commands.Description.adminchat=Toggle mcMMO admin chat on/off or send admin chat messages
Commands.Description.addxp=Add mcMMO XP to a user
Commands.Description.hardcore=Modify the mcMMO hardcore percentage or toggle hardcore mode on/off
Commands.Description.inspect=View detailed mcMMO info on another player
Commands.Description.mcability=Toggle mcMMO abilities being readied on right-click on/off
Commands.Description.mccooldown=View all of the mcMMO ability cooldowns
Commands.Description.mcchatspy=Toggle mcMMO party chat spying on or off
Commands.Description.mcgod=Toggle mcMMO god-mode on/off
Commands.Description.mchud=Change your mcMMO HUD style
Commands.Description.mcmmo=Show a brief description of mcMMO
Commands.Description.mcnotify=Toggle mcMMO abilities chat display notifications on/off
Commands.Description.mcpurge=Purge users with no mcMMO levels and users who have not connected in over {0} months from the mcMMO database.
Commands.Description.mcrank=Show mcMMO ranking for a player
Commands.Description.mcrefresh=Refresh all cooldowns for mcMMO
Commands.Description.mcremove=Remove a user from the mcMMO database
Commands.Description.mcscoreboard=Manage your mcMMO Scoreboard
Commands.Description.mcstats=Show your mcMMO levels and XP
Commands.Description.mctop=Show mcMMO leader boards
Commands.Description.mmoedit=Edit mcMMO levels for a user
Commands.Description.mmodebug=Toggle a debug mode which prints useful information when you hit blocks
Commands.Description.mmoupdate=Migrate mcMMO database from an old database into the current one
Commands.Description.mcconvert=Converts database types or experience formula types
Commands.Description.mmoshowdb=Show the name of the current database type (for later use with /mmoupdate)
Commands.Description.party=Control various mcMMO party settings
Commands.Description.partychat=Toggle mcMMO party chat on/off or send party chat messages
Commands.Description.ptp=Teleport to an mcMMO party member
Commands.Description.Skill=Display detailed mcMMO skill info for {0}
Commands.Description.skillreset=Reset mcMMO levels for a user
Commands.Description.vampirism=Modify the mcMMO vampirism percentage or toggle vampirism mode on/off
Commands.Description.xplock=Lock your mcMMO XP bar to a specific mcMMO skill
Commands.Description.xprate=Modify the mcMMO XP rate or start an mcMMO XP event
#UPDATE CHECKER
UpdateChecker.Outdated=You are using an outdated version of mcMMO!
UpdateChecker.NewAvailable=There is a new version available on Spigot.
#SCOREBOARD HEADERS
Scoreboard.Header.PlayerStats=&emcMMO Stats
Scoreboard.Header.PlayerCooldowns=&emcMMO Cooldowns
Scoreboard.Header.PlayerRank=&emcMMO Rankings
Scoreboard.Header.PlayerInspect=&emcMMO Stats: {0}
Scoreboard.Header.PowerLevel=&cPower Level
Scoreboard.Misc.PowerLevel=&6Power Level
Scoreboard.Misc.Level=&3Level
Scoreboard.Misc.CurrentXP=&aCurrent XP
Scoreboard.Misc.RemainingXP=&eRemaining XP
Scoreboard.Misc.Cooldown=&dCooldown
Scoreboard.Misc.Overall=&6Overall
Scoreboard.Misc.Ability=Ability
#DATABASE RECOVERY
Profile.PendingLoad=&cYour mcMMO player data has not yet been loaded.
Profile.Loading.Success=&aYour mcMMO profile has been loaded.
Profile.Loading.FailurePlayer=&cmcMMO is having trouble loading your data, we have attempted to load it &a{0}&c times.&c You may want to contact the server admins about this issue. mcMMO will attempt to load your data until you disconnect, you will not gain XP or be able to use skills while the data is not loaded.
Profile.Loading.FailureNotice=&4[A]&c mcMMO was unable to load the player data for &e{0}&c. &dPlease inspect your database setup. Attempts made so far {1}.
#Holiday
Holiday.AprilFools.Levelup=&6{0} is now level &a{1}&6!
Holiday.Anniversary=&9Happy {0} Year Anniversary!\n&9In honor of all of nossr50's work and all the devs, here's a firework show!
#Reminder Messages
Reminder.Squelched=&7Reminder: You are currently not receiving notifications from mcMMO, to enable notifications please run the /mcnotify command again. This is an automated hourly reminder.
#Locale
Locale.Reloaded=&aLocale reloaded!
#Player Leveling Stuff
LevelCap.PowerLevel=&6(&amcMMO&6) &eYou have reached the power level cap of &c{0}&e. You will cease to level in skills from this point on.
LevelCap.Skill=&6(&amcMMO&6) &eYou have reached the level cap of &c{0}&e for &6{1}&e. You will cease to level in this skill from this point on.
Commands.XPBar.Usage=Proper usage is /mmoxpbar <skillname | reset> <show | hide>
Commands.Description.mmoxpbar=Player settings for mcMMO XP bars
Commands.Description.mmocompat=Information about mcMMO and whether its in compatibility mode or fully functional.
Compatibility.Layer.Unsupported=&6Compatibility for &a{0}&6 is not supported by this version of Minecraft.
Compatibility.Layer.PartialSupport=&6Compatibility for &a{0}&6 is not fully supported by this version of Minecraft, but mcMMO is running a secondary system to emulate some of the missing features.
Commands.XPBar.DisableAll=&6 All mcMMO XP bars are now disabled, use /mmoxpbar reset to restore default settings.
#Modern Chat Settings
Chat.Style.Admin=&b(A) &r{0} &b\u2192 &r{1}
Chat.Style.Party=&a(P) &r{0} &a\u2192 &r{1}
Chat.Style.Party.Leader=&a(P) &r{0} &6\u2192 &r{1}
Chat.Identity.Console=&6* Console *
Chat.Channel.On=&6(&amcMMO-Chat&6) &eYour chat messages will now be automatically delivered to the &a{0}&e chat channel.
Chat.Channel.Off=&6(&amcMMO-Chat&6) &7Your chat messages will no longer be automatically delivered to specific chat channels.
Chat.Spy.Party=&6[&eSPY&6-&a{2}&6] &r{0} &b\u2192 &r{1}
Broadcasts.LevelUpMilestone=&6(&amcMMO&6) {0}&7 has reached level &a{1}&7 in &3{2}&7!
Broadcasts.PowerLevelUpMilestone=&6(&amcMMO&6) {0}&7 has reached a Power level of &a{1}&7!
Scoreboard.Recovery=Attempting to recover mcMMO scoreboard...
Scoreboard.Disabled=The mcMMO scoreboards for this server are disabled, this setting is found in mcMMO/config.yml
Scoreboard.NotSetupYet=Your mcMMO scoreboard has not been setup yet, try again later.
| 411 | 0.839531 | 1 | 0.839531 | game-dev | MEDIA | 0.761606 | game-dev | 0.781635 | 1 | 0.781635 |
spatialos/UnrealGDK | 1,643 | SpatialGDK/Source/SpatialGDK/Public/SpatialView/AuthorityRecord.h | #pragma once
#include "SpatialView/EntityComponentId.h"
#include "Containers/Array.h"
namespace SpatialGDK
{
// A record of authority changes to entity-components.
// Authority for an entity-component can be in at most one of the following states:
// Recorded as gained.
// Recorded as lost.
// Recorded as lost-temporarily.
class AuthorityRecord
{
public:
// Record an authority change for an entity-component.
//
// The following values of `authority` will cause these respective state transitions:
// WORKER_AUTHORITY_NOT_AUTHORITATIVE
// not recorded -> lost
// gained -> not recorded
// lost -> UNDEFINED
// lost-temporarily -> lost
// WORKER_AUTHORITY_AUTHORITATIVE
// not recorded -> gained
// gained -> UNDEFINED
// lost -> lost-temporarily
// lost-temporarily -> UNDEFINED
// WORKER_AUTHORITY_AUTHORITY_LOSS_IMMINENT
// ignored
void SetAuthority(Worker_EntityId EntityId, Worker_ComponentId ComponentId, Worker_Authority Authority);
// Remove all records.
void Clear();
// Get all entity-components with an authority change recorded as gained.
const TArray<EntityComponentId>& GetAuthorityGained() const;
// Get all entity-components with an authority change recorded as lost.
const TArray<EntityComponentId>& GetAuthorityLost() const;
// Get all entity-components with an authority change recorded as lost-temporarily.
const TArray<EntityComponentId>& GetAuthorityLostTemporarily() const;
private:
TArray<EntityComponentId> AuthorityGained;
TArray<EntityComponentId> AuthorityLost;
TArray<EntityComponentId> AuthorityLossTemporary;
};
} // namespace SpatialGDK
| 411 | 0.97038 | 1 | 0.97038 | game-dev | MEDIA | 0.747157 | game-dev | 0.950198 | 1 | 0.950198 |
r-lyeh-archived/scriptorium | 23,094 | ruby/mruby/mrbgems/mruby-struct/src/struct.c | /*
** struct.c - Struct class
**
** See Copyright Notice in mruby.h
*/
#include <string.h>
#include "mruby.h"
#include "mruby/array.h"
#include "mruby/string.h"
#include "mruby/class.h"
#include "mruby/variable.h"
#include "mruby/hash.h"
#include "mruby/range.h"
#define RSTRUCT_LEN(st) mrb_ary_ptr(st)->len
#define RSTRUCT_PTR(st) mrb_ary_ptr(st)->ptr
static struct RClass *
struct_class(mrb_state *mrb)
{
return mrb_class_get(mrb, "Struct");
}
static inline mrb_value
struct_ivar_get(mrb_state *mrb, mrb_value c, mrb_sym id)
{
struct RClass* kclass;
struct RClass* sclass = struct_class(mrb);
mrb_value ans;
for (;;) {
ans = mrb_iv_get(mrb, c, id);
if (!mrb_nil_p(ans)) return ans;
kclass = RCLASS_SUPER(c);
if (kclass == 0 || kclass == sclass)
return mrb_nil_value();
c = mrb_obj_value(kclass);
}
}
static mrb_value
mrb_struct_s_members(mrb_state *mrb, mrb_value klass)
{
mrb_value members = struct_ivar_get(mrb, klass, mrb_intern_lit(mrb, "__members__"));
if (mrb_nil_p(members)) {
mrb_raise(mrb, E_TYPE_ERROR, "uninitialized struct");
}
if (!mrb_array_p(members)) {
mrb_raise(mrb, E_TYPE_ERROR, "corrupted struct");
}
return members;
}
static mrb_value
mrb_struct_members(mrb_state *mrb, mrb_value s)
{
mrb_value members = mrb_struct_s_members(mrb, mrb_obj_value(mrb_obj_class(mrb, s)));
if (!strcmp(mrb_class_name(mrb, mrb_obj_class(mrb, s)), "Struct")) {
if (RSTRUCT_LEN(s) != RARRAY_LEN(members)) {
mrb_raisef(mrb, E_TYPE_ERROR,
"struct size differs (%S required %S given)",
mrb_fixnum_value(RARRAY_LEN(members)), mrb_fixnum_value(RSTRUCT_LEN(s)));
}
}
return members;
}
static mrb_value
mrb_struct_s_members_m(mrb_state *mrb, mrb_value klass)
{
mrb_value members, ary;
members = mrb_struct_s_members(mrb, klass);
ary = mrb_ary_new_capa(mrb, RARRAY_LEN(members));
mrb_ary_replace(mrb, ary, members);
return ary;
}
/* 15.2.18.4.6 */
/*
* call-seq:
* struct.members -> array
*
* Returns an array of strings representing the names of the instance
* variables.
*
* Customer = Struct.new(:name, :address, :zip)
* joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
* joe.members #=> [:name, :address, :zip]
*/
static mrb_value
mrb_struct_members_m(mrb_state *mrb, mrb_value obj)
{
return mrb_struct_s_members_m(mrb, mrb_obj_value(mrb_obj_class(mrb, obj)));
}
static mrb_value
mrb_struct_getmember(mrb_state *mrb, mrb_value obj, mrb_sym id)
{
mrb_value members, slot, *ptr;
const mrb_value *ptr_members;
mrb_int i, len;
ptr = RSTRUCT_PTR(obj);
members = mrb_struct_members(mrb, obj);
ptr_members = RARRAY_PTR(members);
slot = mrb_symbol_value(id);
len = RARRAY_LEN(members);
for (i=0; i<len; i++) {
if (mrb_obj_equal(mrb, ptr_members[i], slot)) {
return ptr[i];
}
}
mrb_raisef(mrb, E_INDEX_ERROR, "'%S' is not a struct member", mrb_sym2str(mrb, id));
return mrb_nil_value(); /* not reached */
}
static mrb_value
mrb_struct_ref(mrb_state *mrb, mrb_value obj)
{
return mrb_struct_getmember(mrb, obj, mrb->c->ci->mid);
}
static mrb_value mrb_struct_ref0(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[0];}
static mrb_value mrb_struct_ref1(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[1];}
static mrb_value mrb_struct_ref2(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[2];}
static mrb_value mrb_struct_ref3(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[3];}
static mrb_value mrb_struct_ref4(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[4];}
static mrb_value mrb_struct_ref5(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[5];}
static mrb_value mrb_struct_ref6(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[6];}
static mrb_value mrb_struct_ref7(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[7];}
static mrb_value mrb_struct_ref8(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[8];}
static mrb_value mrb_struct_ref9(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[9];}
#define numberof(array) (int)(sizeof(array) / sizeof((array)[0]))
#define N_REF_FUNC numberof(ref_func)
static const mrb_func_t ref_func[] = {
mrb_struct_ref0,
mrb_struct_ref1,
mrb_struct_ref2,
mrb_struct_ref3,
mrb_struct_ref4,
mrb_struct_ref5,
mrb_struct_ref6,
mrb_struct_ref7,
mrb_struct_ref8,
mrb_struct_ref9,
};
static mrb_sym
mrb_id_attrset(mrb_state *mrb, mrb_sym id)
{
const char *name;
char *buf;
mrb_int len;
mrb_sym mid;
name = mrb_sym2name_len(mrb, id, &len);
buf = (char *)mrb_malloc(mrb, (size_t)len+2);
memcpy(buf, name, (size_t)len);
buf[len] = '=';
buf[len+1] = '\0';
mid = mrb_intern(mrb, buf, len+1);
mrb_free(mrb, buf);
return mid;
}
static mrb_value
mrb_struct_set(mrb_state *mrb, mrb_value obj, mrb_value val)
{
const char *name;
mrb_int i, len, slen;
mrb_sym mid;
mrb_value members, slot, *ptr;
const mrb_value *ptr_members;
/* get base id */
name = mrb_sym2name_len(mrb, mrb->c->ci->mid, &slen);
mid = mrb_intern(mrb, name, slen-1); /* omit last "=" */
members = mrb_struct_members(mrb, obj);
ptr_members = RARRAY_PTR(members);
len = RARRAY_LEN(members);
ptr = RSTRUCT_PTR(obj);
for (i=0; i<len; i++) {
slot = ptr_members[i];
if (mrb_symbol(slot) == mid) {
return ptr[i] = val;
}
}
mrb_raisef(mrb, E_INDEX_ERROR, "'%S' is not a struct member", mrb_sym2str(mrb, mid));
return mrb_nil_value(); /* not reached */
}
static mrb_value
mrb_struct_set_m(mrb_state *mrb, mrb_value obj)
{
mrb_value val;
mrb_get_args(mrb, "o", &val);
return mrb_struct_set(mrb, obj, val);
}
static mrb_bool
is_local_id(mrb_state *mrb, const char *name)
{
if (!name) return FALSE;
return !ISUPPER(name[0]);
}
static mrb_bool
is_const_id(mrb_state *mrb, const char *name)
{
if (!name) return FALSE;
return ISUPPER(name[0]);
}
static void
make_struct_define_accessors(mrb_state *mrb, mrb_value members, struct RClass *c)
{
const mrb_value *ptr_members = RARRAY_PTR(members);
mrb_int i;
mrb_int len = RARRAY_LEN(members);
int ai = mrb_gc_arena_save(mrb);
for (i=0; i<len; i++) {
mrb_sym id = mrb_symbol(ptr_members[i]);
const char *name = mrb_sym2name_len(mrb, id, NULL);
if (is_local_id(mrb, name) || is_const_id(mrb, name)) {
if (i < N_REF_FUNC) {
mrb_define_method_id(mrb, c, id, ref_func[i], MRB_ARGS_NONE());
}
else {
mrb_define_method_id(mrb, c, id, mrb_struct_ref, MRB_ARGS_NONE());
}
mrb_define_method_id(mrb, c, mrb_id_attrset(mrb, id), mrb_struct_set_m, MRB_ARGS_REQ(1));
mrb_gc_arena_restore(mrb, ai);
}
}
}
static mrb_value
make_struct(mrb_state *mrb, mrb_value name, mrb_value members, struct RClass * klass)
{
mrb_value nstr;
mrb_sym id;
struct RClass *c;
if (mrb_nil_p(name)) {
c = mrb_class_new(mrb, klass);
}
else {
/* old style: should we warn? */
name = mrb_str_to_str(mrb, name);
id = mrb_obj_to_sym(mrb, name);
if (!is_const_id(mrb, mrb_sym2name_len(mrb, id, NULL))) {
mrb_name_error(mrb, id, "identifier %S needs to be constant", name);
}
if (mrb_const_defined_at(mrb, mrb_obj_value(klass), id)) {
mrb_warn(mrb, "redefining constant Struct::%S", name);
/* ?rb_mod_remove_const(klass, mrb_sym2name(mrb, id)); */
}
c = mrb_define_class_under(mrb, klass, RSTRING_PTR(name), klass);
}
MRB_SET_INSTANCE_TT(c, MRB_TT_ARRAY);
nstr = mrb_obj_value(c);
mrb_iv_set(mrb, nstr, mrb_intern_lit(mrb, "__members__"), members);
mrb_define_class_method(mrb, c, "new", mrb_instance_new, MRB_ARGS_ANY());
mrb_define_class_method(mrb, c, "[]", mrb_instance_new, MRB_ARGS_ANY());
mrb_define_class_method(mrb, c, "members", mrb_struct_s_members_m, MRB_ARGS_NONE());
/* RSTRUCT(nstr)->basic.c->super = c->c; */
make_struct_define_accessors(mrb, members, c);
return nstr;
}
/* 15.2.18.3.1 */
/*
* call-seq:
* Struct.new( [aString] [, aSym]+> ) -> StructClass
* StructClass.new(arg, ...) -> obj
* StructClass[arg, ...] -> obj
*
* Creates a new class, named by <i>aString</i>, containing accessor
* methods for the given symbols. If the name <i>aString</i> is
* omitted, an anonymous structure class will be created. Otherwise,
* the name of this struct will appear as a constant in class
* <code>Struct</code>, so it must be unique for all
* <code>Struct</code>s in the system and should start with a capital
* letter. Assigning a structure class to a constant effectively gives
* the class the name of the constant.
*
* <code>Struct::new</code> returns a new <code>Class</code> object,
* which can then be used to create specific instances of the new
* structure. The number of actual parameters must be
* less than or equal to the number of attributes defined for this
* class; unset parameters default to <code>nil</code>. Passing too many
* parameters will raise an <code>ArgumentError</code>.
*
* The remaining methods listed in this section (class and instance)
* are defined for this generated class.
*
* # Create a structure with a name in Struct
* Struct.new("Customer", :name, :address) #=> Struct::Customer
* Struct::Customer.new("Dave", "123 Main") #=> #<struct Struct::Customer name="Dave", address="123 Main">
*
* # Create a structure named by its constant
* Customer = Struct.new(:name, :address) #=> Customer
* Customer.new("Dave", "123 Main") #=> #<struct Customer name="Dave", address="123 Main">
*/
static mrb_value
mrb_struct_s_def(mrb_state *mrb, mrb_value klass)
{
mrb_value name, rest;
mrb_value *pargv;
mrb_int argcnt;
mrb_int i;
mrb_value b, st;
mrb_sym id;
mrb_value *argv;
mrb_int argc;
name = mrb_nil_value();
rest = mrb_nil_value();
mrb_get_args(mrb, "*&", &argv, &argc, &b);
if (argc == 0) { /* special case to avoid crash */
rest = mrb_ary_new(mrb);
}
else {
if (argc > 0) name = argv[0];
if (argc > 1) rest = argv[1];
if (mrb_array_p(rest)) {
if (!mrb_nil_p(name) && mrb_symbol_p(name)) {
/* 1stArgument:symbol -> name=nil rest=argv[0]-[n] */
mrb_ary_unshift(mrb, rest, name);
name = mrb_nil_value();
}
}
else {
pargv = &argv[1];
argcnt = argc-1;
if (!mrb_nil_p(name) && mrb_symbol_p(name)) {
/* 1stArgument:symbol -> name=nil rest=argv[0]-[n] */
name = mrb_nil_value();
pargv = &argv[0];
argcnt++;
}
rest = mrb_ary_new_from_values(mrb, argcnt, pargv);
}
for (i=0; i<RARRAY_LEN(rest); i++) {
id = mrb_obj_to_sym(mrb, RARRAY_PTR(rest)[i]);
mrb_ary_set(mrb, rest, i, mrb_symbol_value(id));
}
}
st = make_struct(mrb, name, rest, struct_class(mrb));
if (!mrb_nil_p(b)) {
mrb_yield_with_class(mrb, b, 1, &st, st, mrb_class_ptr(klass));
}
return st;
}
static mrb_int
num_members(mrb_state *mrb, struct RClass *klass)
{
mrb_value members;
members = struct_ivar_get(mrb, mrb_obj_value(klass), mrb_intern_lit(mrb, "__members__"));
if (!mrb_array_p(members)) {
mrb_raise(mrb, E_TYPE_ERROR, "broken members");
}
return RARRAY_LEN(members);
}
/* 15.2.18.4.8 */
/*
*/
static mrb_value
mrb_struct_initialize_withArg(mrb_state *mrb, mrb_int argc, mrb_value *argv, mrb_value self)
{
struct RClass *klass = mrb_obj_class(mrb, self);
mrb_int i, n;
n = num_members(mrb, klass);
if (n < argc) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "struct size differs");
}
for (i = 0; i < argc; i++) {
mrb_ary_set(mrb, self, i, argv[i]);
}
for (i = argc; i < n; i++) {
mrb_ary_set(mrb, self, i, mrb_nil_value());
}
return self;
}
static mrb_value
mrb_struct_initialize_m(mrb_state *mrb, /*int argc, mrb_value *argv,*/ mrb_value self)
{
mrb_value *argv;
mrb_int argc;
mrb_get_args(mrb, "*", &argv, &argc);
return mrb_struct_initialize_withArg(mrb, argc, argv, self);
}
/* 15.2.18.4.9 */
/* :nodoc: */
static mrb_value
mrb_struct_init_copy(mrb_state *mrb, mrb_value copy)
{
mrb_value s;
mrb_int i, len;
mrb_get_args(mrb, "o", &s);
if (mrb_obj_equal(mrb, copy, s)) return copy;
if (!mrb_obj_is_instance_of(mrb, s, mrb_obj_class(mrb, copy))) {
mrb_raise(mrb, E_TYPE_ERROR, "wrong argument class");
}
if (!mrb_array_p(s)) {
mrb_raise(mrb, E_TYPE_ERROR, "corrupted struct");
}
if (RSTRUCT_LEN(copy) != RSTRUCT_LEN(s)) {
mrb_raise(mrb, E_TYPE_ERROR, "struct size mismatch");
}
len = RSTRUCT_LEN(copy);
for (i = 0; i < len; i++) {
mrb_ary_set(mrb, copy, i, RSTRUCT_PTR(s)[i]);
}
return copy;
}
static mrb_value
struct_aref_sym(mrb_state *mrb, mrb_value s, mrb_sym id)
{
mrb_value *ptr, members;
const mrb_value *ptr_members;
mrb_int i, len;
ptr = RSTRUCT_PTR(s);
members = mrb_struct_members(mrb, s);
ptr_members = RARRAY_PTR(members);
len = RARRAY_LEN(members);
for (i=0; i<len; i++) {
if (mrb_symbol(ptr_members[i]) == id) {
return ptr[i];
}
}
mrb_raisef(mrb, E_INDEX_ERROR, "no member '%S' in struct", mrb_sym2str(mrb, id));
return mrb_nil_value(); /* not reached */
}
static mrb_value
struct_aref_int(mrb_state *mrb, mrb_value s, mrb_int i)
{
if (i < 0) i = RSTRUCT_LEN(s) + i;
if (i < 0)
mrb_raisef(mrb, E_INDEX_ERROR,
"offset %S too small for struct(size:%S)",
mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
if (RSTRUCT_LEN(s) <= i)
mrb_raisef(mrb, E_INDEX_ERROR,
"offset %S too large for struct(size:%S)",
mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
return RSTRUCT_PTR(s)[i];
}
/* 15.2.18.4.2 */
/*
* call-seq:
* struct[symbol] -> anObject
* struct[fixnum] -> anObject
*
* Attribute Reference---Returns the value of the instance variable
* named by <i>symbol</i>, or indexed (0..length-1) by
* <i>fixnum</i>. Will raise <code>NameError</code> if the named
* variable does not exist, or <code>IndexError</code> if the index is
* out of range.
*
* Customer = Struct.new(:name, :address, :zip)
* joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
*
* joe["name"] #=> "Joe Smith"
* joe[:name] #=> "Joe Smith"
* joe[0] #=> "Joe Smith"
*/
static mrb_value
mrb_struct_aref(mrb_state *mrb, mrb_value s)
{
mrb_value idx;
mrb_get_args(mrb, "o", &idx);
if (mrb_string_p(idx)) {
mrb_value sym = mrb_check_intern_str(mrb, idx);
if (mrb_nil_p(sym)) {
mrb_raisef(mrb, E_INDEX_ERROR, "no member '%S' in struct", idx);
}
idx = sym;
}
if (mrb_symbol_p(idx)) {
return struct_aref_sym(mrb, s, mrb_symbol(idx));
}
return struct_aref_int(mrb, s, mrb_int(mrb, idx));
}
static mrb_value
mrb_struct_aset_sym(mrb_state *mrb, mrb_value s, mrb_sym id, mrb_value val)
{
mrb_value members, *ptr;
const mrb_value *ptr_members;
mrb_int i, len;
members = mrb_struct_members(mrb, s);
len = RARRAY_LEN(members);
if (RSTRUCT_LEN(s) != len) {
mrb_raisef(mrb, E_TYPE_ERROR,
"struct size differs (%S required %S given)",
mrb_fixnum_value(len), mrb_fixnum_value(RSTRUCT_LEN(s)));
}
ptr = RSTRUCT_PTR(s);
ptr_members = RARRAY_PTR(members);
for (i=0; i<len; i++) {
if (mrb_symbol(ptr_members[i]) == id) {
ptr[i] = val;
return val;
}
}
mrb_raisef(mrb, E_INDEX_ERROR, "no member '%S' in struct", mrb_sym2str(mrb, id));
return val; /* not reach */
}
/* 15.2.18.4.3 */
/*
* call-seq:
* struct[symbol] = obj -> obj
* struct[fixnum] = obj -> obj
*
* Attribute Assignment---Assigns to the instance variable named by
* <i>symbol</i> or <i>fixnum</i> the value <i>obj</i> and
* returns it. Will raise a <code>NameError</code> if the named
* variable does not exist, or an <code>IndexError</code> if the index
* is out of range.
*
* Customer = Struct.new(:name, :address, :zip)
* joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
*
* joe["name"] = "Luke"
* joe[:zip] = "90210"
*
* joe.name #=> "Luke"
* joe.zip #=> "90210"
*/
static mrb_value
mrb_struct_aset(mrb_state *mrb, mrb_value s)
{
mrb_int i;
mrb_value idx;
mrb_value val;
mrb_get_args(mrb, "oo", &idx, &val);
if (mrb_string_p(idx)) {
mrb_value sym = mrb_check_intern_str(mrb, idx);
if (mrb_nil_p(sym)) {
mrb_raisef(mrb, E_INDEX_ERROR, "no member '%S' in struct", idx);
}
idx = sym;
}
if (mrb_symbol_p(idx)) {
return mrb_struct_aset_sym(mrb, s, mrb_symbol(idx), val);
}
i = mrb_int(mrb, idx);
if (i < 0) i = RSTRUCT_LEN(s) + i;
if (i < 0) {
mrb_raisef(mrb, E_INDEX_ERROR,
"offset %S too small for struct(size:%S)",
mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
}
if (RSTRUCT_LEN(s) <= i) {
mrb_raisef(mrb, E_INDEX_ERROR,
"offset %S too large for struct(size:%S)",
mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
}
return RSTRUCT_PTR(s)[i] = val;
}
/* 15.2.18.4.1 */
/*
* call-seq:
* struct == other_struct -> true or false
*
* Equality---Returns <code>true</code> if <i>other_struct</i> is
* equal to this one: they must be of the same class as generated by
* <code>Struct::new</code>, and the values of all instance variables
* must be equal (according to <code>Object#==</code>).
*
* Customer = Struct.new(:name, :address, :zip)
* joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
* joejr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
* jane = Customer.new("Jane Doe", "456 Elm, Anytown NC", 12345)
* joe == joejr #=> true
* joe == jane #=> false
*/
static mrb_value
mrb_struct_equal(mrb_state *mrb, mrb_value s)
{
mrb_value s2;
mrb_value *ptr, *ptr2;
mrb_int i, len;
mrb_get_args(mrb, "o", &s2);
if (mrb_obj_equal(mrb, s, s2)) {
return mrb_true_value();
}
if (!strcmp(mrb_class_name(mrb, mrb_obj_class(mrb, s)), "Struct") ||
mrb_obj_class(mrb, s) != mrb_obj_class(mrb, s2)) {
return mrb_false_value();
}
if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
mrb_bug(mrb, "inconsistent struct"); /* should never happen */
}
ptr = RSTRUCT_PTR(s);
ptr2 = RSTRUCT_PTR(s2);
len = RSTRUCT_LEN(s);
for (i=0; i<len; i++) {
if (!mrb_equal(mrb, ptr[i], ptr2[i])) {
return mrb_false_value();
}
}
return mrb_true_value();
}
/* 15.2.18.4.12(x) */
/*
* code-seq:
* struct.eql?(other) -> true or false
*
* Two structures are equal if they are the same object, or if all their
* fields are equal (using <code>eql?</code>).
*/
static mrb_value
mrb_struct_eql(mrb_state *mrb, mrb_value s)
{
mrb_value s2;
mrb_value *ptr, *ptr2;
mrb_int i, len;
mrb_get_args(mrb, "o", &s2);
if (mrb_obj_equal(mrb, s, s2)) {
return mrb_true_value();
}
if (strcmp(mrb_class_name(mrb, mrb_obj_class(mrb, s2)), "Struct") ||
mrb_obj_class(mrb, s) != mrb_obj_class(mrb, s2)) {
return mrb_false_value();
}
if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
mrb_bug(mrb, "inconsistent struct"); /* should never happen */
}
ptr = RSTRUCT_PTR(s);
ptr2 = RSTRUCT_PTR(s2);
len = RSTRUCT_LEN(s);
for (i=0; i<len; i++) {
if (!mrb_eql(mrb, ptr[i], ptr2[i])) {
return mrb_false_value();
}
}
return mrb_true_value();
}
/*
* call-seq:
* struct.length -> Fixnum
* struct.size -> Fixnum
*
* Returns number of struct members.
*/
static mrb_value
mrb_struct_len(mrb_state *mrb, mrb_value self)
{
return mrb_fixnum_value(RSTRUCT_LEN(self));
}
/*
* call-seq:
* struct.to_a -> array
* struct.values -> array
*
* Create an array from struct values.
*/
static mrb_value
mrb_struct_to_a(mrb_state *mrb, mrb_value self)
{
return mrb_ary_new_from_values(mrb, RSTRUCT_LEN(self), RSTRUCT_PTR(self));
}
/*
* call-seq:
* struct.to_h -> hash
*
* Create a hash from member names and struct values.
*/
static mrb_value
mrb_struct_to_h(mrb_state *mrb, mrb_value self)
{
mrb_value members, ret;
mrb_int i;
members = mrb_struct_s_members(mrb, mrb_obj_value(mrb_class(mrb, self)));
ret = mrb_hash_new_capa(mrb, RARRAY_LEN(members));
for (i = 0; i < RARRAY_LEN(members); ++i) {
mrb_hash_set(mrb, ret, RARRAY_PTR(members)[i], RSTRUCT_PTR(self)[i]);
}
return ret;
}
static mrb_value
mrb_struct_values_at(mrb_state *mrb, mrb_value self)
{
mrb_int argc;
mrb_value *argv;
mrb_get_args(mrb, "*", &argv, &argc);
return mrb_get_values_at(mrb, self, RSTRUCT_LEN(self), argc, argv, struct_aref_int);
}
/*
* A <code>Struct</code> is a convenient way to bundle a number of
* attributes together, using accessor methods, without having to write
* an explicit class.
*
* The <code>Struct</code> class is a generator of specific classes,
* each one of which is defined to hold a set of variables and their
* accessors. In these examples, we'll call the generated class
* "<i>Customer</i>Class," and we'll show an example instance of that
* class as "<i>Customer</i>Inst."
*
* In the descriptions that follow, the parameter <i>symbol</i> refers
* to a symbol, which is either a quoted string or a
* <code>Symbol</code> (such as <code>:name</code>).
*/
void
mrb_mruby_struct_gem_init(mrb_state* mrb)
{
struct RClass *st;
st = mrb_define_class(mrb, "Struct", mrb->object_class);
mrb_define_class_method(mrb, st, "new", mrb_struct_s_def, MRB_ARGS_ANY()); /* 15.2.18.3.1 */
mrb_define_method(mrb, st, "==", mrb_struct_equal, MRB_ARGS_REQ(1)); /* 15.2.18.4.1 */
mrb_define_method(mrb, st, "[]", mrb_struct_aref, MRB_ARGS_REQ(1)); /* 15.2.18.4.2 */
mrb_define_method(mrb, st, "[]=", mrb_struct_aset, MRB_ARGS_REQ(2)); /* 15.2.18.4.3 */
mrb_define_method(mrb, st, "members", mrb_struct_members_m, MRB_ARGS_NONE()); /* 15.2.18.4.6 */
mrb_define_method(mrb, st, "initialize", mrb_struct_initialize_m,MRB_ARGS_ANY()); /* 15.2.18.4.8 */
mrb_define_method(mrb, st, "initialize_copy", mrb_struct_init_copy, MRB_ARGS_REQ(1)); /* 15.2.18.4.9 */
mrb_define_method(mrb, st, "eql?", mrb_struct_eql, MRB_ARGS_REQ(1)); /* 15.2.18.4.12(x) */
mrb_define_method(mrb, st, "size", mrb_struct_len, MRB_ARGS_NONE());
mrb_define_method(mrb, st, "length", mrb_struct_len, MRB_ARGS_NONE());
mrb_define_method(mrb, st, "to_a", mrb_struct_to_a, MRB_ARGS_NONE());
mrb_define_method(mrb, st, "values", mrb_struct_to_a, MRB_ARGS_NONE());
mrb_define_method(mrb, st, "to_h", mrb_struct_to_h, MRB_ARGS_NONE());
mrb_define_method(mrb, st, "values_at", mrb_struct_values_at, MRB_ARGS_NONE());
}
void
mrb_mruby_struct_gem_final(mrb_state* mrb)
{
}
| 411 | 0.6308 | 1 | 0.6308 | game-dev | MEDIA | 0.167124 | game-dev | 0.666628 | 1 | 0.666628 |
RobertSkalko/Age-of-Exile | 2,643 | src/main/java/com/robertx22/age_of_exile/saveclasses/spells/ChargeData.java | package com.robertx22.age_of_exile.saveclasses.spells;
import com.robertx22.age_of_exile.capability.player.EntitySpellCap;
import com.robertx22.age_of_exile.database.data.spells.components.Spell;
import com.robertx22.age_of_exile.uncommon.datasaving.Load;
import info.loenwind.autosave.annotations.Storable;
import info.loenwind.autosave.annotations.Store;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.MathHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Storable
public class ChargeData {
@Store
private HashMap<String, Integer> charges = new HashMap<>();
@Store
private HashMap<String, Integer> charge_regen = new HashMap<>();
public int getCurrentTicksChargingOf(String id) {
return charge_regen.getOrDefault(id, 0);
}
public boolean hasCharge(String id) {
return charges.getOrDefault(id, 0) > 0;
}
public void spendCharge(PlayerEntity player, String id) {
if (player.level.isClientSide) {
return;
}
charges.put(id, MathHelper.clamp(charges.getOrDefault(id, 0) - 1, 0, 100000));
Load.spells(player)
.syncToClient(player);
}
public int getCharges(String id) {
return charges.getOrDefault(id, 0);
}
public void addCharge(String id, Spell spell) {
int charge = MathHelper.clamp(charges.getOrDefault(id, 0) + 1, 0, spell.config.charges);
charges.put(id, charge);
}
public void onTicks(PlayerEntity player, int ticks) {
if (player.level.isClientSide) {
return;
}
boolean sync = false;
EntitySpellCap.ISpellsCap sdata = Load.spells(player);
List<String> chargesadded = new ArrayList<>(); // no duplicate charge regen
for (Spell s : sdata.getLearnedSpells()) {
String id = s.config.charge_name;
if (getCharges(id) >= s.config.charges) {
continue;
}
if (!chargesadded.contains(id)) {
if (s.config.charges > 0) {
chargesadded.add(id);
charge_regen.put(s.config.charge_name, ticks + charge_regen.getOrDefault(s.config.charge_name, 0));
if (charge_regen.get(id) >= s.config.charge_regen) {
charge_regen.put(id, 0);
addCharge(id, s);
sync = true;
}
}
}
}
if (sync) {
Load.spells(player)
.syncToClient(player);
}
}
}
| 411 | 0.961396 | 1 | 0.961396 | game-dev | MEDIA | 0.829762 | game-dev | 0.986994 | 1 | 0.986994 |
THEOplayer/react-native-theoplayer | 8,346 | ios/theoAds/THEOplayerRCTTHEOAdsEventHandler.swift | // THEOplayerRCTTHEOadsEventHandler.swift
import Foundation
import THEOplayerSDK
#if canImport(THEOplayerTHEOadsIntegration)
import THEOplayerTHEOadsIntegration
#endif
let EVENT_TYPE_ADD_INTERSTITIAL: String = "addinterstitial"
let EVENT_TYPE_INTERSTITIAL_BEGIN: String = "interstitialbegin"
let EVENT_TYPE_INTERSTITIAL_END: String = "interstitialend"
let EVENT_TYPE_INTERSTITIAL_UPDATE: String = "interstitialupdate"
let EVENT_TYPE_INTERSTITIAL_ERROR: String = "interstitialerror"
let THEOADS_EVENT_PROP_TYPE: String = "type"
let THEOADS_EVENT_PROP_INTERSTITIAL: String = "interstitial"
let THEOADS_EVENT_PROP_MESSAGE: String = "message"
class THEOplayerRCTTHEOadsEventHandler {
// MARK: Members
private weak var player: THEOplayer?
// MARK: Events
var onNativeTHEOadsEvent: RCTDirectEventBlock?
// MARK: THEOAds Listeners
private var addInterstitialListener: EventListener?
private var interstitialBeginListener: EventListener?
private var interstitialEndListener: EventListener?
private var interstitialUpdateListener: EventListener?
private var interstitialErrorListener: EventListener?
// MARK: - destruction
func destroy() {
// dettach listeners
self.dettachListeners()
}
// MARK: - player setup / breakdown
func setPlayer(_ player: THEOplayer) {
self.player = player;
// attach listeners
self.attachListeners()
}
// MARK: - attach/dettach Listeners
private func attachListeners() {
guard let player = self.player else {
return
}
#if canImport(THEOplayerTHEOadsIntegration)
// ADD_INTERSTITIAL
self.addInterstitialListener = player.ads.theoAds?.addEventListener(type: THEOadsEventTypes.ADD_INTERSTITIAL) { [weak self] event in
if DEBUG_THEOPLAYER_EVENTS { PrintUtils.printLog(logText: "[NATIVE] Received AddInterstitial event from THEOplayer.ads.theoAds") }
if let forwardedTHEOadsEvent = self?.onNativeTHEOadsEvent {
forwardedTHEOadsEvent([
THEOADS_EVENT_PROP_TYPE: EVENT_TYPE_ADD_INTERSTITIAL,
THEOADS_EVENT_PROP_INTERSTITIAL: THEOplayerRCTTHEOadsEventAdapter.fromInterstitial(event.interstitial)
])
}
}
if DEBUG_EVENTHANDLER { PrintUtils.printLog(logText: "[NATIVE] AddInterstitial listener attached to THEOplayer.ads.theoAds") }
// INTERSTITIAL_BEGIN
self.interstitialBeginListener = player.ads.theoAds?.addEventListener(type: THEOadsEventTypes.INTERSTITIAL_BEGIN) { [weak self] event in
if DEBUG_THEOPLAYER_EVENTS { PrintUtils.printLog(logText: "[NATIVE] Received InterstitialBegin event from THEOplayer.ads.theoAds") }
if let forwardedTHEOadsEvent = self?.onNativeTHEOadsEvent {
forwardedTHEOadsEvent([
THEOADS_EVENT_PROP_TYPE: EVENT_TYPE_INTERSTITIAL_BEGIN,
THEOADS_EVENT_PROP_INTERSTITIAL: THEOplayerRCTTHEOadsEventAdapter.fromInterstitial(event.interstitial)
])
}
}
if DEBUG_EVENTHANDLER { PrintUtils.printLog(logText: "[NATIVE] InterstitialBegin listener attached to THEOplayer.ads.theoAds") }
// INTERSTITIAL_END
self.interstitialEndListener = player.ads.theoAds?.addEventListener(type: THEOadsEventTypes.INTERSTITIAL_END) { [weak self] event in
if DEBUG_THEOPLAYER_EVENTS { PrintUtils.printLog(logText: "[NATIVE] Received InterstitialEnd event from THEOplayer.ads.theoAds") }
if let forwardedTHEOadsEvent = self?.onNativeTHEOadsEvent {
forwardedTHEOadsEvent([
THEOADS_EVENT_PROP_TYPE: EVENT_TYPE_INTERSTITIAL_END,
THEOADS_EVENT_PROP_INTERSTITIAL: THEOplayerRCTTHEOadsEventAdapter.fromInterstitial(event.interstitial)
])
}
}
if DEBUG_EVENTHANDLER { PrintUtils.printLog(logText: "[NATIVE] InterstitialEnd listener attached to THEOplayer.ads.theoAds") }
// INTERSTITIAL_UPDATE
self.interstitialUpdateListener = player.ads.theoAds?.addEventListener(type: THEOadsEventTypes.INTERSTITIAL_UPDATE) { [weak self] event in
if DEBUG_THEOPLAYER_EVENTS { PrintUtils.printLog(logText: "[NATIVE] Received InterstitialUpdate event from THEOplayer.ads.theoAds") }
if let forwardedTHEOadsEvent = self?.onNativeTHEOadsEvent {
forwardedTHEOadsEvent([
THEOADS_EVENT_PROP_TYPE: EVENT_TYPE_INTERSTITIAL_UPDATE,
THEOADS_EVENT_PROP_INTERSTITIAL: THEOplayerRCTTHEOadsEventAdapter.fromInterstitial(event.interstitial)
])
}
}
if DEBUG_EVENTHANDLER { PrintUtils.printLog(logText: "[NATIVE] InterstitialUpdate listener attached to THEOplayer.ads.theoAds") }
// INTERSTITIAL_ERROR
self.interstitialErrorListener = player.ads.theoAds?.addEventListener(type: THEOadsEventTypes.INTERSTITIAL_ERROR) { [weak self] event in
if DEBUG_THEOPLAYER_EVENTS { PrintUtils.printLog(logText: "[NATIVE] Received InterstitialError event from THEOplayer.ads.theoAds") }
if let forwardedTHEOadsEvent = self?.onNativeTHEOadsEvent {
var interstitialData: [String: Any] = [:]
interstitialData[THEOADS_EVENT_PROP_TYPE] = EVENT_TYPE_INTERSTITIAL_ERROR
interstitialData[THEOADS_EVENT_PROP_INTERSTITIAL] = THEOplayerRCTTHEOadsEventAdapter.fromInterstitial(event.interstitial)
if let errorMessage = event.message {
interstitialData[THEOADS_EVENT_PROP_MESSAGE] = errorMessage
}
forwardedTHEOadsEvent(interstitialData)
}
}
if DEBUG_EVENTHANDLER { PrintUtils.printLog(logText: "[NATIVE] InterstitialError listener attached to THEOplayer.ads.theoAds") }
#endif
}
private func dettachListeners() {
guard let player = self.player else {
return
}
#if canImport(THEOplayerTHEOadsIntegration)
// ADD_INTERSTITIAL
if let addInterstitialListener = self.addInterstitialListener {
player.ads.theoAds?.removeEventListener(
type: THEOadsEventTypes.ADD_INTERSTITIAL,
listener: addInterstitialListener
)
if DEBUG_EVENTHANDLER { PrintUtils.printLog(logText: "[NATIVE] AddInterstitial listener detached from THEOplayer.ads.theoAds") }
}
// INTERSTITIAL_BEGIN
if let interstitialBeginListener = self.interstitialBeginListener {
player.ads.theoAds?.removeEventListener(
type: THEOadsEventTypes.INTERSTITIAL_BEGIN,
listener: interstitialBeginListener
)
if DEBUG_EVENTHANDLER { PrintUtils.printLog(logText: "[NATIVE] InterstitialBegin listener detached from THEOplayer.ads.theoAds") }
}
// INTERSTITIAL_END
if let interstitialEndListener = self.interstitialEndListener {
player.ads.theoAds?.removeEventListener(
type: THEOadsEventTypes.INTERSTITIAL_END,
listener: interstitialEndListener
)
if DEBUG_EVENTHANDLER { PrintUtils.printLog(logText: "[NATIVE] InterstitialEnd listener detached from THEOplayer.ads.theoAds") }
}
// INTERSTITIAL_UPDATE
if let interstitialUpdateListener = self.interstitialUpdateListener {
player.ads.theoAds?.removeEventListener(
type: THEOadsEventTypes.INTERSTITIAL_UPDATE,
listener: interstitialUpdateListener
)
if DEBUG_EVENTHANDLER { PrintUtils.printLog(logText: "[NATIVE] InterstitialUpdate listener detached from THEOplayer.ads.theoAds") }
}
// INTERSTITIAL_ERROR
if let interstitialErrorListener = self.interstitialErrorListener {
player.ads.theoAds?.removeEventListener(
type: THEOadsEventTypes.INTERSTITIAL_ERROR,
listener: interstitialErrorListener
)
if DEBUG_EVENTHANDLER { PrintUtils.printLog(logText: "[NATIVE] InterstitialError listener detached from THEOplayer.ads.theoAds") }
}
#endif
}
}
| 411 | 0.909247 | 1 | 0.909247 | game-dev | MEDIA | 0.201814 | game-dev | 0.956986 | 1 | 0.956986 |
hughperkins/EasyCL | 1,987 | CLArrayFloat.h | // Copyright Hugh Perkins 2013 hughperkins at gmail
//
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#pragma once
#include <stdexcept>
//#include <CL/cl.h>
//#include "clcc/clew.h"
#include "EasyCL.h"
#include "CLArray.h"
namespace easycl {
class CLArrayFloat : public CLArray {
protected:
float *hostarray;
public:
CLArrayFloat(int N, EasyCL *easycl) :
CLArray(N, easycl) {
hostarray = 0;
}
CLArrayFloat(const CLArrayFloat &source) :
CLArray(0, 0) { // copy constructor
throw std::runtime_error("can't assign these...");
}
CLArrayFloat &operator=(const CLArrayFloat &two) { // assignment operator
if(this == &two) { // self-assignment
return *this;
}
throw std::runtime_error("can't assign these...");
}
virtual ~CLArrayFloat() {
if(onHost) {
deleteHostArray();
}
}
virtual void createOnHost() {
assert(!onHost && !onDevice);
allocateHostArray(N);
}
virtual void allocateHostArray(int N) {
hostarray = new float[N];
onHost = true;
}
virtual void deleteHostArray() {
delete[] hostarray;
onHost = false;
}
virtual int getElementSize() {
return sizeof(float);
}
virtual void *getHostArray() {
return hostarray;
}
// float const &operator[](int n) {
// if(!onHost) {
// if(!onDevice) {
// createOnHost();
// } else {
// copyToHost();
// }
// }
// return hostarray[n];
// }
float &operator[](int n) {
if(!onHost) {
if(!onDevice) {
createOnHost();
} else {
moveToHost();
}
}
return hostarray[n];
}
};
}
| 411 | 0.649609 | 1 | 0.649609 | game-dev | MEDIA | 0.255922 | game-dev | 0.696709 | 1 | 0.696709 |
Citadel-Station-13/Citadel-Station-13 | 1,608 | code/modules/antagonists/traitor/classes/subterfuge.dm | /datum/traitor_class/human/subterfuge
name = "MI13 Operative"
employer = "MI13"
weight = 25
chaos = -5
var/assassin_prob = 25
/datum/traitor_class/human/subterfuge/forge_single_objective(datum/antagonist/traitor/T)
var/datum/game_mode/dynamic/mode
if(istype(SSticker.mode,/datum/game_mode/dynamic))
mode = SSticker.mode
assassin_prob = max(0,mode.threat_level-20)
if(prob(assassin_prob))
var/datum/objective/assassinate/once/kill_objective = new
kill_objective.owner = T.owner
kill_objective.find_target()
T.add_objective(kill_objective)
return TRUE
else
var/list/weights = list()
var/datum/objective/sabotage/sabotage_objective = new
sabotage_objective.owner = T.owner
if(sabotage_objective.find_target())
weights["sabo"] = length(subtypesof(/datum/objective_item/steal))
var/datum/objective/steal/steal_objective = new
steal_objective.owner = T.owner
if(steal_objective.find_target())
weights["steal"] = length(subtypesof(/datum/objective_item/steal))
weights["download"] = !(locate(/datum/objective/download) in T.objectives || (T.owner.assigned_role in list("Research Director", "Scientist", "Roboticist")))
switch(pickweight(weights))
if("sabo")
T.add_objective(sabotage_objective)
qdel(steal_objective)
return TRUE
if("steal")
T.add_objective(steal_objective)
qdel(sabotage_objective)
return TRUE
if("download")
var/datum/objective/download/download_objective = new
download_objective.owner = T.owner
download_objective.gen_amount_goal()
T.add_objective(download_objective)
return TRUE
return FALSE
| 411 | 0.70531 | 1 | 0.70531 | game-dev | MEDIA | 0.958476 | game-dev | 0.67099 | 1 | 0.67099 |
SonicEraZoR/Portal-Base | 13,162 | sp/src/game/server/ai_task.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Defines the tasks for default AI.
//
// $NoKeywords: $
//=============================================================================//
#ifndef AI_TASK_H
#define AI_TASK_H
#ifdef _WIN32
#pragma once
#endif
class CStringRegistry;
// ----------------------------------------------------------------------
// Failure messages
//
// UNDONE: do this diffently so when not in developer mode we can
// not use any memory for these text strings
// ----------------------------------------------------------------------
// Codes are either one of the enumerated types below, or a string (similar to Windows resource IDs)
typedef int AI_TaskFailureCode_t;
enum AI_BaseTaskFailureCodes_t
{
NO_TASK_FAILURE,
FAIL_NO_TARGET,
FAIL_WEAPON_OWNED,
FAIL_ITEM_NO_FIND,
FAIL_NO_HINT_NODE,
FAIL_SCHEDULE_NOT_FOUND,
FAIL_NO_ENEMY,
FAIL_NO_BACKAWAY_NODE,
FAIL_NO_COVER,
FAIL_NO_FLANK,
FAIL_NO_SHOOT,
FAIL_NO_ROUTE,
FAIL_NO_ROUTE_GOAL,
FAIL_NO_ROUTE_BLOCKED,
FAIL_NO_ROUTE_ILLEGAL,
FAIL_NO_WALK,
FAIL_ALREADY_LOCKED,
FAIL_NO_SOUND,
FAIL_NO_SCENT,
FAIL_BAD_ACTIVITY,
FAIL_NO_GOAL,
FAIL_NO_PLAYER,
FAIL_NO_REACHABLE_NODE,
FAIL_NO_AI_NETWORK,
FAIL_BAD_POSITION,
FAIL_BAD_PATH_GOAL,
FAIL_STUCK_ONTOP,
FAIL_ITEM_TAKEN,
NUM_FAIL_CODES,
};
inline bool IsPathTaskFailure( AI_TaskFailureCode_t code )
{
return ( code >= FAIL_NO_ROUTE && code <= FAIL_NO_ROUTE_ILLEGAL );
}
const char *TaskFailureToString( AI_TaskFailureCode_t code );
inline int MakeFailCode( const char *pszGeneralError ) { return (int)pszGeneralError; }
enum TaskStatus_e
{
TASKSTATUS_NEW = 0, // Just started
TASKSTATUS_RUN_MOVE_AND_TASK = 1, // Running task & movement
TASKSTATUS_RUN_MOVE = 2, // Just running movement
TASKSTATUS_RUN_TASK = 3, // Just running task
TASKSTATUS_COMPLETE = 4, // Completed, get next task
};
// an array of tasks is a task list
// an array of schedules is a schedule list
struct Task_t
{
int iTask;
float flTaskData;
};
//=========================================================
// These are the shared tasks
//=========================================================
enum sharedtasks_e
{
TASK_INVALID = 0,
// Forces the activity to reset.
TASK_RESET_ACTIVITY,
// Waits for the specified number of seconds.
TASK_WAIT,
// Make announce attack sound
TASK_ANNOUNCE_ATTACK,
// Waits for the specified number of seconds. Will constantly turn to
// face the enemy while waiting.
TASK_WAIT_FACE_ENEMY,
// Waits up to the specified number of seconds. Will constantly turn to
// face the enemy while waiting.
TASK_WAIT_FACE_ENEMY_RANDOM,
// Wait until the player enters the same PVS as this character.
TASK_WAIT_PVS,
// DON'T use this, it needs to go away.
TASK_SUGGEST_STATE,
// Set m_hTargetEnt to nearest player
TASK_TARGET_PLAYER,
// Walk to m_hTargetEnt's location
TASK_SCRIPT_WALK_TO_TARGET,
// Run to m_hTargetEnt's location
TASK_SCRIPT_RUN_TO_TARGET,
// Move to m_hTargetEnt's location using the activity specified by m_hCine->m_iszCustomMove.
TASK_SCRIPT_CUSTOM_MOVE_TO_TARGET,
// Move to within specified range of m_hTargetEnt
TASK_MOVE_TO_TARGET_RANGE,
// Move to within specified range of our nav goal
TASK_MOVE_TO_GOAL_RANGE,
// Path that moves the character a few steps forward of where it is.
TASK_MOVE_AWAY_PATH,
TASK_GET_PATH_AWAY_FROM_BEST_SOUND,
// Set the implied goal for TASK_GET_PATH_TO_GOAL
TASK_SET_GOAL,
// Get the path to the goal specified by TASK_SET_GOAL
TASK_GET_PATH_TO_GOAL,
// Path to the enemy's location. Even if the enemy is unseen!
TASK_GET_PATH_TO_ENEMY,
// Path to the last place this character saw the enemy
TASK_GET_PATH_TO_ENEMY_LKP,
// Path to the enemy's location or path to a LOS with the enemy's last known position, depending on range
TASK_GET_CHASE_PATH_TO_ENEMY,
// Path to a LOS with the enemy's last known position
TASK_GET_PATH_TO_ENEMY_LKP_LOS,
// Path to the dead enemy's carcass.
TASK_GET_PATH_TO_ENEMY_CORPSE,
// Path to the player's origin
TASK_GET_PATH_TO_PLAYER,
// Path to node with line of sight to enemy
TASK_GET_PATH_TO_ENEMY_LOS,
// Path to node with line of sight to enemy, at least flTaskData units away from m_vSavePosition
TASK_GET_FLANK_RADIUS_PATH_TO_ENEMY_LOS,
// Path to node with line of sight to enemy, at least flTaskData degrees away from m_vSavePosition from the enemy's POV
TASK_GET_FLANK_ARC_PATH_TO_ENEMY_LOS,
// Path to the within shot range of last place this character saw the enemy
TASK_GET_PATH_TO_RANGE_ENEMY_LKP_LOS,
// Build a path to m_hTargetEnt
TASK_GET_PATH_TO_TARGET,
// Allow a little slop, and allow for some Z offset (like the target is a gun on a table).
TASK_GET_PATH_TO_TARGET_WEAPON,
TASK_CREATE_PENDING_WEAPON,
// Path to nodes[ m_pHintNode ]
TASK_GET_PATH_TO_HINTNODE,
// Store current position for later reference
TASK_STORE_LASTPOSITION,
// Clear stored position
TASK_CLEAR_LASTPOSITION,
// Store current position for later reference
TASK_STORE_POSITION_IN_SAVEPOSITION,
// Store best sound position for later reference
TASK_STORE_BESTSOUND_IN_SAVEPOSITION,
TASK_STORE_BESTSOUND_REACTORIGIN_IN_SAVEPOSITION,
TASK_REACT_TO_COMBAT_SOUND,
// Store current enemy position in saveposition
TASK_STORE_ENEMY_POSITION_IN_SAVEPOSITION,
// Move to the goal specified by the player in command mode.
TASK_GET_PATH_TO_COMMAND_GOAL,
TASK_MARK_COMMAND_GOAL_POS,
TASK_CLEAR_COMMAND_GOAL,
// Path to last position (Last position must be stored with TASK_STORE_LAST_POSITION)
TASK_GET_PATH_TO_LASTPOSITION,
// Path to saved position (Save position must by set in code or by a task)
TASK_GET_PATH_TO_SAVEPOSITION,
// Path to location that has line of sight to saved position (Save position must by set in code or by a task)
TASK_GET_PATH_TO_SAVEPOSITION_LOS,
// Path to random node
TASK_GET_PATH_TO_RANDOM_NODE,
// Path to source of loudest heard sound that I care about
TASK_GET_PATH_TO_BESTSOUND,
// Path to source of the strongest scend that I care about
TASK_GET_PATH_TO_BESTSCENT,
// Run the current path
TASK_RUN_PATH,
// Walk the current path
TASK_WALK_PATH,
// Walk the current path for a specified number of seconds
TASK_WALK_PATH_TIMED,
// Walk the current path until you are x units from the goal.
TASK_WALK_PATH_WITHIN_DIST,
// Walk the current path until for x units
TASK_WALK_PATH_FOR_UNITS,
// Rung the current path until you are x units from the goal.
TASK_RUN_PATH_FLEE,
// Run the current path for a specified number of seconds
TASK_RUN_PATH_TIMED,
// Run the current path until for x units
TASK_RUN_PATH_FOR_UNITS,
// Run the current path until you are x units from the goal.
TASK_RUN_PATH_WITHIN_DIST,
// Walk the current path sideways (must be supported by animation)
TASK_STRAFE_PATH,
// Clear m_flMoveWaitFinished (timer that inhibits movement)
TASK_CLEAR_MOVE_WAIT,
// Decide on the appropriate small flinch animation, and play it.
TASK_SMALL_FLINCH,
// Decide on the appropriate big flinch animation, and play it.
TASK_BIG_FLINCH,
// Prevent dodging for a certain amount of time.
TASK_DEFER_DODGE,
// Turn to face ideal yaw
TASK_FACE_IDEAL,
// Find an interesting direction to face. Don't face into walls, corners if you can help it.
TASK_FACE_REASONABLE,
// Turn to face the way I should walk or run
TASK_FACE_PATH,
// Turn to face a player
TASK_FACE_PLAYER,
// Turn to face the enemy
TASK_FACE_ENEMY,
// Turn to face nodes[ m_pHintNode ]
TASK_FACE_HINTNODE,
// Play activity associate with the current hint
TASK_PLAY_HINT_ACTIVITY,
// Turn to face m_hTargetEnt
TASK_FACE_TARGET,
// Turn to face stored last position (last position must be stored first!)
TASK_FACE_LASTPOSITION,
// Turn to face stored save position (save position must be stored first!)
TASK_FACE_SAVEPOSITION,
// Turn to face directly away from stored save position (save position must be stored first!)
TASK_FACE_AWAY_FROM_SAVEPOSITION,
// Set the current facing to be the ideal
TASK_SET_IDEAL_YAW_TO_CURRENT,
// Attack the enemy (should be facing the enemy)
TASK_RANGE_ATTACK1,
TASK_RANGE_ATTACK2,
TASK_MELEE_ATTACK1,
TASK_MELEE_ATTACK2,
// Reload weapon
TASK_RELOAD,
// Execute special attack (user-defined)
TASK_SPECIAL_ATTACK1,
TASK_SPECIAL_ATTACK2,
TASK_FIND_HINTNODE,
TASK_FIND_LOCK_HINTNODE,
TASK_CLEAR_HINTNODE,
// Claim m_pHintNode exclusively for this NPC.
TASK_LOCK_HINTNODE,
// Emit an angry sound
TASK_SOUND_ANGRY,
// Emit a dying sound
TASK_SOUND_DEATH,
// Emit an idle sound
TASK_SOUND_IDLE,
// Emit a sound because you are pissed off because you just saw someone you don't like
TASK_SOUND_WAKE,
// Emit a pain sound
TASK_SOUND_PAIN,
// Emit a death sound
TASK_SOUND_DIE,
// Speak a sentence
TASK_SPEAK_SENTENCE,
// Wait for the current sentence I'm speaking to finish
TASK_WAIT_FOR_SPEAK_FINISH,
// Set current animation activity to the specified activity
TASK_SET_ACTIVITY,
// Adjust the framerate to plus/minus N%
TASK_RANDOMIZE_FRAMERATE,
// Immediately change to a schedule of the specified type
TASK_SET_SCHEDULE,
// Set the specified schedule to execute if the current schedule fails.
TASK_SET_FAIL_SCHEDULE,
// How close to route goal do I need to get
TASK_SET_TOLERANCE_DISTANCE,
// How many seconds should I spend search for a route
TASK_SET_ROUTE_SEARCH_TIME,
// Return to use of default fail schedule
TASK_CLEAR_FAIL_SCHEDULE,
// Play the specified animation sequence before continuing
TASK_PLAY_SEQUENCE,
// Play the specified private animation sequence before continuing
TASK_PLAY_PRIVATE_SEQUENCE,
// Turn to face the enemy while playing specified animation sequence
TASK_PLAY_PRIVATE_SEQUENCE_FACE_ENEMY,
TASK_PLAY_SEQUENCE_FACE_ENEMY,
TASK_PLAY_SEQUENCE_FACE_TARGET,
// tries lateral cover first, then node cover
TASK_FIND_COVER_FROM_BEST_SOUND,
// tries lateral cover first, then node cover
TASK_FIND_COVER_FROM_ENEMY,
// Find a place to hide from the enemy, somewhere on either side of me
TASK_FIND_LATERAL_COVER_FROM_ENEMY,
// Find a place further from the saved position
TASK_FIND_BACKAWAY_FROM_SAVEPOSITION,
// Fine a place to hide from the enemy, anywhere. Use the node system.
TASK_FIND_NODE_COVER_FROM_ENEMY,
// Find a place to hide from the enemy that's within the specified distance
TASK_FIND_NEAR_NODE_COVER_FROM_ENEMY,
// data for this one is there MINIMUM aceptable distance to the cover.
TASK_FIND_FAR_NODE_COVER_FROM_ENEMY,
// Find a place to go that can't see to where I am now.
TASK_FIND_COVER_FROM_ORIGIN,
// Unhook from the AI system.
TASK_DIE,
// Wait until scripted sequence plays
TASK_WAIT_FOR_SCRIPT,
// Play scripted sequence animation
TASK_PUSH_SCRIPT_ARRIVAL_ACTIVITY,
TASK_PLAY_SCRIPT,
TASK_PLAY_SCRIPT_POST_IDLE,
TASK_ENABLE_SCRIPT,
TASK_PLANT_ON_SCRIPT,
TASK_FACE_SCRIPT,
// Wait for scene to complete
TASK_PLAY_SCENE,
// Wait for 0 to specified number of seconds
TASK_WAIT_RANDOM,
// Wait forever (until this schedule is interrupted)
TASK_WAIT_INDEFINITE,
TASK_STOP_MOVING,
// Turn left the specified number of degrees
TASK_TURN_LEFT,
// Turn right the specified number of degrees
TASK_TURN_RIGHT,
// Remember the specified piece of data
TASK_REMEMBER,
// Forget the specified piece of data
TASK_FORGET,
// Wait until current movement is complete.
TASK_WAIT_FOR_MOVEMENT,
// Wait until a single-step movement is complete.
TASK_WAIT_FOR_MOVEMENT_STEP,
// Wait until I can't hear any danger sound.
TASK_WAIT_UNTIL_NO_DANGER_SOUND,
// Pick up new weapons:
TASK_WEAPON_FIND,
TASK_WEAPON_PICKUP,
TASK_WEAPON_RUN_PATH, // run to weapon but break if someone else picks it up
TASK_WEAPON_CREATE,
TASK_ITEM_PICKUP,
TASK_ITEM_RUN_PATH,
// Use small hull for tight navigation
TASK_USE_SMALL_HULL,
// wait until you are on ground
TASK_FALL_TO_GROUND,
// Wander for a specfied amound of time
TASK_WANDER,
TASK_FREEZE,
// regather conditions at the start of a schedule (all conditions are cleared between schedules)
TASK_GATHER_CONDITIONS,
// Require an enemy be seen after the task is run to be considered a candidate enemy
TASK_IGNORE_OLD_ENEMIES,
TASK_DEBUG_BREAK,
// Add a specified amount of health to this NPC
TASK_ADD_HEALTH,
// Add a gesture layer and wait until it's finished
TASK_ADD_GESTURE_WAIT,
// Add a gesture layer
TASK_ADD_GESTURE,
// Get a path to my forced interaction partner
TASK_GET_PATH_TO_INTERACTION_PARTNER,
// First task of all schedules for playing back scripted sequences
TASK_PRE_SCRIPT,
// ======================================
// IMPORTANT: This must be the last enum
// ======================================
LAST_SHARED_TASK
};
#endif // AI_TASK_H
| 411 | 0.980059 | 1 | 0.980059 | game-dev | MEDIA | 0.978618 | game-dev | 0.982612 | 1 | 0.982612 |
Reava/UwUtils | 2,185 | Runtime/Scripts/MultiUISliderManager.cs | using UdonSharp;
using UnityEngine;
using UnityEngine.UI;
using VRC.SDKBase;
using VRC.Udon;
using UwUtils;
namespace UwUtils
{
[AddComponentMenu("UwUtils/Multi UI Slider Manager")]
[UdonBehaviourSyncMode(BehaviourSyncMode.None)]
public class MultiUISliderManager : UdonSharpBehaviour
{
[Space]
public float DefaultSliderValue = 0.6f;
[Space]
[SerializeField] private Slider[] TargetSliders;
[Header("Target behaviors to send an event on value change to")]
[Space]
[SerializeField] private UdonBehaviour[] TargetBehaviorUpdate;
[SerializeField] private string eventName = "_interact";
[Space]
[SerializeField] private bool enableLogging = true;
void Start()
{
if (TargetSliders == null) return;
foreach (Slider s in TargetSliders)
{
if (!s) continue;
s.SetValueWithoutNotify(DefaultSliderValue);
}
}
public override void Interact() => _SliderChange();
private void _SliderChange()
{
if (enableLogging) Debug.Log("[Reava_/UwUtils/SliderHub.cs]: Change detected, updating values from: " + gameObject.name + "", gameObject);
if (TargetSliders == null) return;
bool found = false;
Slider tempSlider = null;
foreach (Slider s in TargetSliders)
{
if (!s) continue;
if (found) s.SetValueWithoutNotify(DefaultSliderValue);
if (s.value != DefaultSliderValue)
{
DefaultSliderValue = s.value;
tempSlider = s;
found = true;
}
}
foreach (Slider s in TargetSliders)
{
if (!s) continue;
s.SetValueWithoutNotify(DefaultSliderValue);
if (s == tempSlider) break;
}
foreach(UdonBehaviour target in TargetBehaviorUpdate)
{
if (!target) continue;
target.SendCustomEvent(eventName);
}
}
}
} | 411 | 0.892661 | 1 | 0.892661 | game-dev | MEDIA | 0.883712 | game-dev | 0.941487 | 1 | 0.941487 |
shxzu/Simp | 1,684 | src/main/java/net/minecraft/client/renderer/entity/RenderSkeleton.java | package net.minecraft.client.renderer.entity;
import net.minecraft.client.model.ModelSkeleton;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.layers.LayerBipedArmor;
import net.minecraft.client.renderer.entity.layers.LayerHeldItem;
import net.minecraft.entity.monster.EntitySkeleton;
import net.minecraft.util.ResourceLocation;
public class RenderSkeleton extends RenderBiped<EntitySkeleton>
{
private static final ResourceLocation skeletonTextures = new ResourceLocation("textures/entity/skeleton/skeleton.png");
private static final ResourceLocation witherSkeletonTextures = new ResourceLocation("textures/entity/skeleton/wither_skeleton.png");
public RenderSkeleton(RenderManager renderManagerIn)
{
super(renderManagerIn, new ModelSkeleton(), 0.5F);
this.addLayer(new LayerHeldItem(this));
this.addLayer(new LayerBipedArmor(this)
{
protected void initArmor()
{
this.modelLeggings = new ModelSkeleton(0.5F, true);
this.modelArmor = new ModelSkeleton(1.0F, true);
}
});
}
protected void preRenderCallback(EntitySkeleton entitylivingbaseIn, float partialTickTime)
{
if (entitylivingbaseIn.getSkeletonType() == 1)
{
GlStateManager.scale(1.2F, 1.2F, 1.2F);
}
}
public void transformHeldFull3DItemLayer()
{
GlStateManager.translate(0.09375F, 0.1875F, 0.0F);
}
protected ResourceLocation getEntityTexture(EntitySkeleton entity)
{
return entity.getSkeletonType() == 1 ? witherSkeletonTextures : skeletonTextures;
}
}
| 411 | 0.66336 | 1 | 0.66336 | game-dev | MEDIA | 0.95378 | game-dev | 0.868193 | 1 | 0.868193 |
rwf93/Starbound | 10,590 | source/game/StarHumanoid.hpp | #ifndef STAR_HUMANOID_HPP
#define STAR_HUMANOID_HPP
#include "StarDataStream.hpp"
#include "StarGameTypes.hpp"
#include "StarDrawable.hpp"
#include "StarParticle.hpp"
namespace Star {
// Required for renderDummy
STAR_CLASS(HeadArmor);
STAR_CLASS(ChestArmor);
STAR_CLASS(LegsArmor);
STAR_CLASS(BackArmor);
STAR_CLASS(Humanoid);
STAR_STRUCT(Dance);
enum class HumanoidEmote {
Idle,
Blabbering,
Shouting,
Happy,
Sad,
NEUTRAL,
Laugh,
Annoyed,
Oh,
OOOH,
Blink,
Wink,
Eat,
Sleep
};
extern EnumMap<HumanoidEmote> const HumanoidEmoteNames;
size_t const EmoteSize = 14;
struct Personality {
String idle;
String armIdle;
Vec2F headOffset;
Vec2F armOffset;
};
Personality parsePersonality(Json const& config);
struct HumanoidIdentity {
explicit HumanoidIdentity(Json config = Json());
Json toJson() const;
String name;
// Must have :idle[1-5], :sit, :duck, :walk[1-8], :run[1-8], :jump[1-4], and
// :fall[1-4]
String species;
Gender gender;
String hairGroup;
// Must have :normal and :climb
String hairType;
String hairDirectives;
String bodyDirectives;
String emoteDirectives;
String facialHairGroup;
String facialHairType;
String facialHairDirectives;
String facialMaskGroup;
String facialMaskType;
String facialMaskDirectives;
Personality personality;
Vec4B color;
Maybe<String> imagePath;
};
DataStream& operator>>(DataStream& ds, HumanoidIdentity& identity);
DataStream& operator<<(DataStream& ds, HumanoidIdentity const& identity);
class Humanoid {
public:
enum State {
Idle, // 1 idle frame
Walk, // 8 walking frames
Run, // 8 run frames
Jump, // 4 jump frames
Fall, // 4 fall frames
Swim, // 7 swim frames
SwimIdle, // 2 swim idle frame
Duck, // 1 ducking frame
Sit, // 1 sitting frame
Lay, // 1 laying frame
STATESIZE
};
static EnumMap<State> const StateNames;
Humanoid(Json const& config);
Humanoid(HumanoidIdentity const& identity);
struct HumanoidTiming {
explicit HumanoidTiming(Json config = Json());
static bool cyclicState(State state);
static bool cyclicEmoteState(HumanoidEmote state);
int stateSeq(float timer, State state) const;
int emoteStateSeq(float timer, HumanoidEmote state) const;
int danceSeq(float timer, DancePtr dance) const;
int genericSeq(float timer, float cycle, unsigned frames, bool cyclic) const;
Array<float, STATESIZE> stateCycle;
Array<unsigned, STATESIZE> stateFrames;
Array<float, EmoteSize> emoteCycle;
Array<unsigned, EmoteSize> emoteFrames;
};
void setIdentity(HumanoidIdentity const& identity);
HumanoidIdentity const& identity() const;
// All of the image identifiers here are meant to be image *base* names, with
// a collection of frames specific to each piece. If an image is set to
// empty string, it is disabled.
// Asset directives for the head armor.
void setHeadArmorDirectives(String directives);
// Must have :normal, climb
void setHeadArmorFrameset(String headFrameset);
// Asset directives for the chest, back and front arms armor.
void setChestArmorDirectives(String directives);
// Will have :run, :normal, and :duck
void setChestArmorFrameset(String chest);
// Same as back arm image frames
void setBackSleeveFrameset(String backSleeveFrameset);
// Same as front arm image frames
void setFrontSleeveFrameset(String frontSleeveFrameset);
// Asset directives for the legs armor.
void setLegsArmorDirectives(String directives);
// Must have :idle, :duck, :walk[1-8], :run[1-8], :jump[1-4], :fall[1-4]
void setLegsArmorFrameset(String legsFrameset);
// Asset directives for the back armor.
void setBackArmorDirectives(String directives);
// Must have :idle, :duck, :walk[1-8], :run[1-8], :jump[1-4], :fall[1-4]
void setBackArmorFrameset(String backFrameset);
void setHelmetMaskDirectives(String helmetMaskDirectives);
void setBodyHidden(bool hidden);
void setState(State state);
void setEmoteState(HumanoidEmote state);
void setDance(Maybe<String> const& dance);
void setFacingDirection(Direction facingDirection);
void setMovingBackwards(bool movingBackwards);
void setRotation(float rotation);
void setVaporTrail(bool enabled);
State state() const;
HumanoidEmote emoteState() const;
Maybe<String> dance() const;
Direction facingDirection() const;
bool movingBackwards() const;
// If not rotating, then the arms follow normal movement animation. The
// angle parameter should be in the range [-pi/2, pi/2] (the facing direction
// should not be included in the angle).
void setPrimaryHandParameters(bool holdingItem, float angle, float itemAngle, bool twoHanded,
bool recoil, bool outsideOfHand);
void setPrimaryHandFrameOverrides(String backFrameOverride, String frontFrameOverride);
void setPrimaryHandDrawables(List<Drawable> drawables);
void setPrimaryHandNonRotatedDrawables(List<Drawable> drawables);
// Same as primary hand.
void setAltHandParameters(bool holdingItem, float angle, float itemAngle, bool recoil,
bool outsideOfHand);
void setAltHandFrameOverrides(String backFrameOverride, String frontFrameOverride);
void setAltHandDrawables(List<Drawable> drawables);
void setAltHandNonRotatedDrawables(List<Drawable> drawables);
// Updates the animation based on whatever the current animation state is,
// wrapping or clamping animation time as appropriate.
void animate(float dt);
// Reset animation time to 0.0f
void resetAnimation();
// Renders to centered drawables (centered on the normal image center for the
// player graphics), (in world space, not pixels)
List<Drawable> render();
// Renders to centered drawables (centered on the normal image center for the
// player graphics), (in pixels, not world space)
List<Drawable> renderPortrait(PortraitMode mode) const;
List<Drawable> renderSkull() const;
// Renders to centered drawables (centered on the normal image center for the
// player graphics), (in pixels, not world space)
static List<Drawable> renderDummy(Gender gender, HeadArmor const* head = nullptr, ChestArmor const* chest = nullptr,
LegsArmor const* legs = nullptr, BackArmor const* back = nullptr);
Vec2F primaryHandPosition(Vec2F const& offset) const;
Vec2F altHandPosition(Vec2F const& offset) const;
// Finds the arm position in world space if the humanoid was facing the given
// direction and applying the given arm angle. The offset given is from the
// rotation center of the arm.
Vec2F primaryArmPosition(Direction facingDirection, float armAngle, Vec2F const& offset) const;
Vec2F altArmPosition(Direction facingDirection, float armAngle, Vec2F const& offset) const;
// Gives the offset of the hand from the arm rotation center
Vec2F primaryHandOffset(Direction facingDirection) const;
Vec2F altHandOffset(Direction facingDirection) const;
Vec2F armAdjustment() const;
Vec2F mouthOffset(bool ignoreAdjustments = false) const;
float getBobYOffset() const;
Vec2F feetOffset() const;
Vec2F headArmorOffset() const;
Vec2F chestArmorOffset() const;
Vec2F legsArmorOffset() const;
Vec2F backArmorOffset() const;
String defaultDeathParticles() const;
List<Particle> particles(String const& name) const;
Json const& defaultMovementParameters() const;
private:
struct HandDrawingInfo {
List<Drawable> itemDrawables;
List<Drawable> nonRotatedDrawables;
bool holdingItem = false;
float angle = 0.0f;
float itemAngle = 0.0f;
String backFrame;
String frontFrame;
float frameAngleAdjust = 0.0f;
bool recoil = false;
bool outsideOfHand = false;
};
String frameBase(State state) const;
String emoteFrameBase(HumanoidEmote state) const;
String getHeadFromIdentity() const;
String getBodyFromIdentity() const;
String getFacialEmotesFromIdentity() const;
String getHairFromIdentity() const;
String getFacialHairFromIdentity() const;
String getFacialMaskFromIdentity() const;
String getBackArmFromIdentity() const;
String getFrontArmFromIdentity() const;
String getVaporTrailFrameset() const;
String getBodyDirectives() const;
String getHairDirectives() const;
String getEmoteDirectives() const;
String getFacialHairDirectives() const;
String getFacialMaskDirectives() const;
String getHelmetMaskDirectives() const;
String getHeadDirectives() const;
String getChestDirectives() const;
String getLegsDirectives() const;
String getBackDirectives() const;
int getEmoteStateSequence() const;
int getArmStateSequence() const;
int getBodyStateSequence() const;
Maybe<DancePtr> getDance() const;
Vec2F m_globalOffset;
Vec2F m_headRunOffset;
Vec2F m_headSwimOffset;
Vec2F m_headDuckOffset;
Vec2F m_headSitOffset;
Vec2F m_headLayOffset;
float m_runFallOffset;
float m_duckOffset;
float m_sitOffset;
float m_layOffset;
Vec2F m_recoilOffset;
Vec2F m_mouthOffset;
Vec2F m_feetOffset;
Vec2F m_headArmorOffset;
Vec2F m_chestArmorOffset;
Vec2F m_legsArmorOffset;
Vec2F m_backArmorOffset;
bool m_bodyHidden;
List<int> m_armWalkSeq;
List<int> m_armRunSeq;
List<float> m_walkBob;
List<float> m_runBob;
List<float> m_swimBob;
float m_jumpBob;
Vec2F m_frontArmRotationCenter;
Vec2F m_backArmRotationCenter;
Vec2F m_frontHandPosition;
Vec2F m_backArmOffset;
String m_headFrameset;
String m_bodyFrameset;
String m_backArmFrameset;
String m_frontArmFrameset;
String m_emoteFrameset;
String m_hairFrameset;
String m_facialHairFrameset;
String m_facialMaskFrameset;
bool m_bodyFullbright;
String m_vaporTrailFrameset;
unsigned m_vaporTrailFrames;
float m_vaporTrailCycle;
String m_backSleeveFrameset;
String m_frontSleeveFrameset;
String m_headArmorFrameset;
String m_headArmorDirectives;
String m_chestArmorFrameset;
String m_chestArmorDirectives;
String m_legsArmorFrameset;
String m_legsArmorDirectives;
String m_backArmorFrameset;
String m_backArmorDirectives;
String m_helmetMaskDirectives;
State m_state;
HumanoidEmote m_emoteState;
Maybe<String> m_dance;
Direction m_facingDirection;
bool m_movingBackwards;
float m_rotation;
bool m_drawVaporTrail;
HandDrawingInfo m_primaryHand;
HandDrawingInfo m_altHand;
bool m_twoHanded;
HumanoidIdentity m_identity;
HumanoidTiming m_timing;
float m_animationTimer;
float m_emoteAnimationTimer;
float m_danceTimer;
Json m_particleEmitters;
String m_defaultDeathParticles;
Json m_defaultMovementParameters;
};
}
#endif
| 411 | 0.89612 | 1 | 0.89612 | game-dev | MEDIA | 0.906235 | game-dev | 0.507604 | 1 | 0.507604 |
fireblade-engine/ecs | 8,187 | Tests/FirebladeECSTests/NexusEventDelegateTests.swift | //
// NexusEventDelegateTests.swift
//
//
// Created by Christian Treffs on 25.11.20.
//
import FirebladeECS
import XCTest
final class NexusEventDelegateTests: XCTestCase {
lazy var nexus = Nexus()
fileprivate var delegateTester: DelegateTester!
override func setUp() {
super.setUp()
nexus = Nexus()
delegateTester = nil
}
func testEventEntityCreated() {
var entityCreatedEvents: [EntityCreated] = []
delegateTester = DelegateTester(onEvent: { event in
switch event {
case let entityCreated as EntityCreated:
entityCreatedEvents.append(entityCreated)
default:
XCTFail("unexpected event \(event)")
return
}
})
nexus.delegate = delegateTester
XCTAssertEqual(entityCreatedEvents.count, 0)
nexus.createEntity()
XCTAssertEqual(entityCreatedEvents.count, 1)
nexus.createEntities(count: 100)
XCTAssertEqual(entityCreatedEvents.count, 101)
}
func testEventEntityDestroyed() {
var events: [EntityDestroyed] = []
delegateTester = DelegateTester(onEvent: { event in
switch event {
case let event as EntityDestroyed:
events.append(event)
case _ as EntityCreated:
break
default:
XCTFail("unexpected event \(event)")
return
}
})
nexus.delegate = delegateTester
XCTAssertEqual(events.count, 0)
nexus.createEntities(count: 100)
XCTAssertEqual(events.count, 0)
for entitiy in nexus.makeEntitiesIterator() {
entitiy.destroy()
}
XCTAssertEqual(events.count, 100)
}
func testEventComponentAdded() {
var componentsAddedEvents: [ComponentAdded] = []
var entityCreatedEvents: [EntityCreated] = []
delegateTester = DelegateTester(onEvent: { event in
switch event {
case let compAdded as ComponentAdded:
componentsAddedEvents.append(compAdded)
case let entityCreated as EntityCreated:
entityCreatedEvents.append(entityCreated)
default:
XCTFail("unexpected event \(event)")
return
}
})
nexus.delegate = delegateTester
XCTAssertEqual(componentsAddedEvents.count, 0)
XCTAssertEqual(entityCreatedEvents.count, 0)
let entity = nexus.createEntity()
entity.assign(MyComponent(name: "0", flag: true))
XCTAssertEqual(componentsAddedEvents.count, 1)
XCTAssertEqual(entityCreatedEvents.count, 1)
let entity2 = nexus.createEntity()
entity2.assign(MyComponent(name: "0", flag: true), YourComponent(number: 2))
XCTAssertEqual(componentsAddedEvents.count, 3)
XCTAssertEqual(entityCreatedEvents.count, 2)
}
func testEventComponentRemoved() {
var events: [ComponentRemoved] = []
delegateTester = DelegateTester(onEvent: { event in
switch event {
case let event as ComponentRemoved:
events.append(event)
default:
XCTFail("unexpected event \(event)")
return
}
})
let entity = nexus.createEntity()
entity.assign(
MyComponent(name: "Hello", flag: false),
YourComponent(number: 3.14),
EmptyComponent()
)
XCTAssertEqual(entity.numComponents, 3)
XCTAssertEqual(events.count, 0)
nexus.delegate = delegateTester
entity.remove(MyComponent.self)
XCTAssertEqual(events.count, 1)
XCTAssertEqual(entity.numComponents, 2)
entity.remove(EmptyComponent.self)
XCTAssertEqual(events.count, 2)
XCTAssertEqual(entity.numComponents, 1)
entity.remove(YourComponent.self)
XCTAssertEqual(events.count, 3)
XCTAssertEqual(entity.numComponents, 0)
}
func testFamilyMemeberAdded() {
var eventsFamilyMemberRemoved: [FamilyMemberRemoved] = []
var eventsComponentRemoved: [ComponentRemoved] = []
var eventsEntityDestroyed: [EntityDestroyed] = []
delegateTester = DelegateTester(onEvent: { event in
switch event {
case is FamilyMemberAdded,
is ComponentAdded,
is EntityCreated:
break
case let event as FamilyMemberRemoved:
eventsFamilyMemberRemoved.append(event)
case let event as ComponentRemoved:
eventsComponentRemoved.append(event)
case let event as EntityDestroyed:
eventsEntityDestroyed.append(event)
default:
XCTFail("unexpected event \(event)")
return
}
})
let family = nexus.family(requiresAll: MyComponent.self, YourComponent.self)
nexus.delegate = delegateTester
family.createMember(with: (MyComponent(name: "Bla", flag: true), YourComponent(number: 85)))
family.createMember(with: (MyComponent(name: "Hello", flag: false), YourComponent(number: 05050)))
family.createMember(with: (MyComponent(name: "asdasd", flag: true), YourComponent(number: 9494949)))
XCTAssertEqual(eventsFamilyMemberRemoved.count, 0)
XCTAssertEqual(eventsComponentRemoved.count, 0)
XCTAssertEqual(family.count, 3)
XCTAssertEqual(eventsEntityDestroyed.count, 0)
XCTAssertTrue(family.destroyMembers())
XCTAssertEqual(eventsFamilyMemberRemoved.count, 3)
XCTAssertEqual(eventsComponentRemoved.count, 6)
XCTAssertEqual(family.count, 0)
XCTAssertEqual(eventsEntityDestroyed.count, 3)
}
func testFamilyMemberRemoved() {
var eventsMemberAdded: [FamilyMemberAdded] = []
var eventsComponentAdded: [ComponentAdded] = []
var eventsEntityCreated: [EntityCreated] = []
delegateTester = DelegateTester(onEvent: { event in
switch event {
case let event as FamilyMemberAdded:
eventsMemberAdded.append(event)
case let event as ComponentAdded:
eventsComponentAdded.append(event)
case let event as EntityCreated:
eventsEntityCreated.append(event)
default:
XCTFail("unexpected event \(event)")
return
}
})
let family = nexus.family(requiresAll: MyComponent.self, YourComponent.self)
nexus.delegate = delegateTester
XCTAssertEqual(family.count, 0)
XCTAssertEqual(eventsMemberAdded.count, 0)
XCTAssertEqual(eventsComponentAdded.count, 0)
XCTAssertEqual(eventsEntityCreated.count, 0)
family.createMember(with: (MyComponent(name: "Bla", flag: true), YourComponent(number: 85)))
XCTAssertEqual(family.count, 1)
XCTAssertEqual(eventsMemberAdded.count, 1)
XCTAssertEqual(eventsComponentAdded.count, 2)
XCTAssertEqual(eventsEntityCreated.count, 1)
family.createMember(with: (MyComponent(name: "Hello", flag: false), YourComponent(number: 05050)))
XCTAssertEqual(family.count, 2)
XCTAssertEqual(eventsMemberAdded.count, 2)
XCTAssertEqual(eventsComponentAdded.count, 4)
XCTAssertEqual(eventsEntityCreated.count, 2)
}
}
fileprivate class DelegateTester: NexusEventDelegate {
var onEvent: (NexusEvent) -> ()
var onNonFatal: (String) -> ()
init(onEvent: @escaping (NexusEvent) -> Void = { _ in },
onNonFatal: @escaping (String) -> Void = { _ in }) {
self.onEvent = onEvent
self.onNonFatal = onNonFatal
}
func nexusEvent(_ event: NexusEvent) {
onEvent(event)
}
func nexusNonFatalError(_ message: String) {
onNonFatal(message)
}
}
| 411 | 0.916615 | 1 | 0.916615 | game-dev | MEDIA | 0.642683 | game-dev,testing-qa | 0.82606 | 1 | 0.82606 |
Fluorohydride/ygopro-scripts | 1,257 | c15582767.lua | --連成する振動
function c15582767.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(15582767,0))
e2:SetCategory(CATEGORY_DESTROY+CATEGORY_DRAW)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetRange(LOCATION_SZONE)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1,15582767)
e2:SetTarget(c15582767.target)
e2:SetOperation(c15582767.operation)
c:RegisterEffect(e2)
end
function c15582767.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_PZONE) and chkc:IsControler(tp) end
if chk==0 then return Duel.IsPlayerCanDraw(tp,1)
and Duel.IsExistingTarget(nil,tp,LOCATION_PZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,nil,tp,LOCATION_PZONE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c15582767.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.Destroy(tc,REASON_EFFECT)~=0 then
Duel.BreakEffect()
Duel.Draw(tp,1,REASON_EFFECT)
end
end
| 411 | 0.866334 | 1 | 0.866334 | game-dev | MEDIA | 0.982973 | game-dev | 0.70282 | 1 | 0.70282 |
andreakarasho/TinyEcs | 64,117 | src/TinyEcs.QueryIteratorEach.g.cs | #pragma warning disable 1591
#nullable enable
using System;
using System.Runtime.CompilerServices;
namespace TinyEcs
{
#if NET9_0_OR_GREATER
[SkipLocalsInit]
public unsafe ref struct Data<T0> : IData<Data<T0>>
where T0 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0> CreateIterator(QueryIterator iterator)
=> new Data<T0>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0)
{
ptr0 = _current0.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0> GetEnumerator() => this;
}
[SkipLocalsInit]
public unsafe ref struct Data<T0, T1> : IData<Data<T0, T1>>
where T0 : struct where T1 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
private DataRow<T1> _current1;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
builder.With<T1>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0, T1> CreateIterator(QueryIterator iterator)
=> new Data<T0, T1>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0, T1> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0, out Ptr<T1> ptr1)
{
ptr0 = _current0.Value;
ptr1 = _current1.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0, out Ptr<T1> ptr1)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
ptr1 = _current1.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_current1 = _iterator.GetColumn<T1>(1);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
_current1.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0, T1> GetEnumerator() => this;
}
[SkipLocalsInit]
public unsafe ref struct Data<T0, T1, T2> : IData<Data<T0, T1, T2>>
where T0 : struct where T1 : struct where T2 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
private DataRow<T1> _current1;
private DataRow<T2> _current2;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
builder.With<T1>();
builder.With<T2>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0, T1, T2> CreateIterator(QueryIterator iterator)
=> new Data<T0, T1, T2>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0, T1, T2> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2)
{
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_current1 = _iterator.GetColumn<T1>(1);
_current2 = _iterator.GetColumn<T2>(2);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
_current1.Next();
_current2.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0, T1, T2> GetEnumerator() => this;
}
[SkipLocalsInit]
public unsafe ref struct Data<T0, T1, T2, T3> : IData<Data<T0, T1, T2, T3>>
where T0 : struct where T1 : struct where T2 : struct where T3 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
private DataRow<T1> _current1;
private DataRow<T2> _current2;
private DataRow<T3> _current3;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
builder.With<T1>();
builder.With<T2>();
builder.With<T3>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0, T1, T2, T3> CreateIterator(QueryIterator iterator)
=> new Data<T0, T1, T2, T3>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0, T1, T2, T3> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3)
{
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_current1 = _iterator.GetColumn<T1>(1);
_current2 = _iterator.GetColumn<T2>(2);
_current3 = _iterator.GetColumn<T3>(3);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
_current1.Next();
_current2.Next();
_current3.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0, T1, T2, T3> GetEnumerator() => this;
}
[SkipLocalsInit]
public unsafe ref struct Data<T0, T1, T2, T3, T4> : IData<Data<T0, T1, T2, T3, T4>>
where T0 : struct where T1 : struct where T2 : struct where T3 : struct where T4 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
private DataRow<T1> _current1;
private DataRow<T2> _current2;
private DataRow<T3> _current3;
private DataRow<T4> _current4;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
builder.With<T1>();
builder.With<T2>();
builder.With<T3>();
builder.With<T4>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0, T1, T2, T3, T4> CreateIterator(QueryIterator iterator)
=> new Data<T0, T1, T2, T3, T4>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0, T1, T2, T3, T4> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4)
{
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_current1 = _iterator.GetColumn<T1>(1);
_current2 = _iterator.GetColumn<T2>(2);
_current3 = _iterator.GetColumn<T3>(3);
_current4 = _iterator.GetColumn<T4>(4);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
_current1.Next();
_current2.Next();
_current3.Next();
_current4.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0, T1, T2, T3, T4> GetEnumerator() => this;
}
[SkipLocalsInit]
public unsafe ref struct Data<T0, T1, T2, T3, T4, T5> : IData<Data<T0, T1, T2, T3, T4, T5>>
where T0 : struct where T1 : struct where T2 : struct where T3 : struct where T4 : struct where T5 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
private DataRow<T1> _current1;
private DataRow<T2> _current2;
private DataRow<T3> _current3;
private DataRow<T4> _current4;
private DataRow<T5> _current5;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
builder.With<T1>();
builder.With<T2>();
builder.With<T3>();
builder.With<T4>();
builder.With<T5>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0, T1, T2, T3, T4, T5> CreateIterator(QueryIterator iterator)
=> new Data<T0, T1, T2, T3, T4, T5>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0, T1, T2, T3, T4, T5> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5)
{
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_current1 = _iterator.GetColumn<T1>(1);
_current2 = _iterator.GetColumn<T2>(2);
_current3 = _iterator.GetColumn<T3>(3);
_current4 = _iterator.GetColumn<T4>(4);
_current5 = _iterator.GetColumn<T5>(5);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
_current1.Next();
_current2.Next();
_current3.Next();
_current4.Next();
_current5.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0, T1, T2, T3, T4, T5> GetEnumerator() => this;
}
[SkipLocalsInit]
public unsafe ref struct Data<T0, T1, T2, T3, T4, T5, T6> : IData<Data<T0, T1, T2, T3, T4, T5, T6>>
where T0 : struct where T1 : struct where T2 : struct where T3 : struct where T4 : struct where T5 : struct where T6 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
private DataRow<T1> _current1;
private DataRow<T2> _current2;
private DataRow<T3> _current3;
private DataRow<T4> _current4;
private DataRow<T5> _current5;
private DataRow<T6> _current6;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
builder.With<T1>();
builder.With<T2>();
builder.With<T3>();
builder.With<T4>();
builder.With<T5>();
builder.With<T6>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0, T1, T2, T3, T4, T5, T6> CreateIterator(QueryIterator iterator)
=> new Data<T0, T1, T2, T3, T4, T5, T6>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0, T1, T2, T3, T4, T5, T6> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6)
{
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_current1 = _iterator.GetColumn<T1>(1);
_current2 = _iterator.GetColumn<T2>(2);
_current3 = _iterator.GetColumn<T3>(3);
_current4 = _iterator.GetColumn<T4>(4);
_current5 = _iterator.GetColumn<T5>(5);
_current6 = _iterator.GetColumn<T6>(6);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
_current1.Next();
_current2.Next();
_current3.Next();
_current4.Next();
_current5.Next();
_current6.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0, T1, T2, T3, T4, T5, T6> GetEnumerator() => this;
}
[SkipLocalsInit]
public unsafe ref struct Data<T0, T1, T2, T3, T4, T5, T6, T7> : IData<Data<T0, T1, T2, T3, T4, T5, T6, T7>>
where T0 : struct where T1 : struct where T2 : struct where T3 : struct where T4 : struct where T5 : struct where T6 : struct where T7 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
private DataRow<T1> _current1;
private DataRow<T2> _current2;
private DataRow<T3> _current3;
private DataRow<T4> _current4;
private DataRow<T5> _current5;
private DataRow<T6> _current6;
private DataRow<T7> _current7;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
builder.With<T1>();
builder.With<T2>();
builder.With<T3>();
builder.With<T4>();
builder.With<T5>();
builder.With<T6>();
builder.With<T7>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0, T1, T2, T3, T4, T5, T6, T7> CreateIterator(QueryIterator iterator)
=> new Data<T0, T1, T2, T3, T4, T5, T6, T7>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0, T1, T2, T3, T4, T5, T6, T7> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7)
{
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_current1 = _iterator.GetColumn<T1>(1);
_current2 = _iterator.GetColumn<T2>(2);
_current3 = _iterator.GetColumn<T3>(3);
_current4 = _iterator.GetColumn<T4>(4);
_current5 = _iterator.GetColumn<T5>(5);
_current6 = _iterator.GetColumn<T6>(6);
_current7 = _iterator.GetColumn<T7>(7);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
_current1.Next();
_current2.Next();
_current3.Next();
_current4.Next();
_current5.Next();
_current6.Next();
_current7.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0, T1, T2, T3, T4, T5, T6, T7> GetEnumerator() => this;
}
[SkipLocalsInit]
public unsafe ref struct Data<T0, T1, T2, T3, T4, T5, T6, T7, T8> : IData<Data<T0, T1, T2, T3, T4, T5, T6, T7, T8>>
where T0 : struct where T1 : struct where T2 : struct where T3 : struct where T4 : struct where T5 : struct where T6 : struct where T7 : struct where T8 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
private DataRow<T1> _current1;
private DataRow<T2> _current2;
private DataRow<T3> _current3;
private DataRow<T4> _current4;
private DataRow<T5> _current5;
private DataRow<T6> _current6;
private DataRow<T7> _current7;
private DataRow<T8> _current8;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
builder.With<T1>();
builder.With<T2>();
builder.With<T3>();
builder.With<T4>();
builder.With<T5>();
builder.With<T6>();
builder.With<T7>();
builder.With<T8>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0, T1, T2, T3, T4, T5, T6, T7, T8> CreateIterator(QueryIterator iterator)
=> new Data<T0, T1, T2, T3, T4, T5, T6, T7, T8>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0, T1, T2, T3, T4, T5, T6, T7, T8> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8)
{
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_current1 = _iterator.GetColumn<T1>(1);
_current2 = _iterator.GetColumn<T2>(2);
_current3 = _iterator.GetColumn<T3>(3);
_current4 = _iterator.GetColumn<T4>(4);
_current5 = _iterator.GetColumn<T5>(5);
_current6 = _iterator.GetColumn<T6>(6);
_current7 = _iterator.GetColumn<T7>(7);
_current8 = _iterator.GetColumn<T8>(8);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
_current1.Next();
_current2.Next();
_current3.Next();
_current4.Next();
_current5.Next();
_current6.Next();
_current7.Next();
_current8.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0, T1, T2, T3, T4, T5, T6, T7, T8> GetEnumerator() => this;
}
[SkipLocalsInit]
public unsafe ref struct Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9> : IData<Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>>
where T0 : struct where T1 : struct where T2 : struct where T3 : struct where T4 : struct where T5 : struct where T6 : struct where T7 : struct where T8 : struct where T9 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
private DataRow<T1> _current1;
private DataRow<T2> _current2;
private DataRow<T3> _current3;
private DataRow<T4> _current4;
private DataRow<T5> _current5;
private DataRow<T6> _current6;
private DataRow<T7> _current7;
private DataRow<T8> _current8;
private DataRow<T9> _current9;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
builder.With<T1>();
builder.With<T2>();
builder.With<T3>();
builder.With<T4>();
builder.With<T5>();
builder.With<T6>();
builder.With<T7>();
builder.With<T8>();
builder.With<T9>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9> CreateIterator(QueryIterator iterator)
=> new Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8, out Ptr<T9> ptr9)
{
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
ptr9 = _current9.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8, out Ptr<T9> ptr9)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
ptr9 = _current9.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_current1 = _iterator.GetColumn<T1>(1);
_current2 = _iterator.GetColumn<T2>(2);
_current3 = _iterator.GetColumn<T3>(3);
_current4 = _iterator.GetColumn<T4>(4);
_current5 = _iterator.GetColumn<T5>(5);
_current6 = _iterator.GetColumn<T6>(6);
_current7 = _iterator.GetColumn<T7>(7);
_current8 = _iterator.GetColumn<T8>(8);
_current9 = _iterator.GetColumn<T9>(9);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
_current1.Next();
_current2.Next();
_current3.Next();
_current4.Next();
_current5.Next();
_current6.Next();
_current7.Next();
_current8.Next();
_current9.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9> GetEnumerator() => this;
}
[SkipLocalsInit]
public unsafe ref struct Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> : IData<Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>>
where T0 : struct where T1 : struct where T2 : struct where T3 : struct where T4 : struct where T5 : struct where T6 : struct where T7 : struct where T8 : struct where T9 : struct where T10 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
private DataRow<T1> _current1;
private DataRow<T2> _current2;
private DataRow<T3> _current3;
private DataRow<T4> _current4;
private DataRow<T5> _current5;
private DataRow<T6> _current6;
private DataRow<T7> _current7;
private DataRow<T8> _current8;
private DataRow<T9> _current9;
private DataRow<T10> _current10;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
builder.With<T1>();
builder.With<T2>();
builder.With<T3>();
builder.With<T4>();
builder.With<T5>();
builder.With<T6>();
builder.With<T7>();
builder.With<T8>();
builder.With<T9>();
builder.With<T10>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> CreateIterator(QueryIterator iterator)
=> new Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8, out Ptr<T9> ptr9, out Ptr<T10> ptr10)
{
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
ptr9 = _current9.Value;
ptr10 = _current10.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8, out Ptr<T9> ptr9, out Ptr<T10> ptr10)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
ptr9 = _current9.Value;
ptr10 = _current10.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_current1 = _iterator.GetColumn<T1>(1);
_current2 = _iterator.GetColumn<T2>(2);
_current3 = _iterator.GetColumn<T3>(3);
_current4 = _iterator.GetColumn<T4>(4);
_current5 = _iterator.GetColumn<T5>(5);
_current6 = _iterator.GetColumn<T6>(6);
_current7 = _iterator.GetColumn<T7>(7);
_current8 = _iterator.GetColumn<T8>(8);
_current9 = _iterator.GetColumn<T9>(9);
_current10 = _iterator.GetColumn<T10>(10);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
_current1.Next();
_current2.Next();
_current3.Next();
_current4.Next();
_current5.Next();
_current6.Next();
_current7.Next();
_current8.Next();
_current9.Next();
_current10.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> GetEnumerator() => this;
}
[SkipLocalsInit]
public unsafe ref struct Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> : IData<Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>>
where T0 : struct where T1 : struct where T2 : struct where T3 : struct where T4 : struct where T5 : struct where T6 : struct where T7 : struct where T8 : struct where T9 : struct where T10 : struct where T11 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
private DataRow<T1> _current1;
private DataRow<T2> _current2;
private DataRow<T3> _current3;
private DataRow<T4> _current4;
private DataRow<T5> _current5;
private DataRow<T6> _current6;
private DataRow<T7> _current7;
private DataRow<T8> _current8;
private DataRow<T9> _current9;
private DataRow<T10> _current10;
private DataRow<T11> _current11;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
builder.With<T1>();
builder.With<T2>();
builder.With<T3>();
builder.With<T4>();
builder.With<T5>();
builder.With<T6>();
builder.With<T7>();
builder.With<T8>();
builder.With<T9>();
builder.With<T10>();
builder.With<T11>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> CreateIterator(QueryIterator iterator)
=> new Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8, out Ptr<T9> ptr9, out Ptr<T10> ptr10, out Ptr<T11> ptr11)
{
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
ptr9 = _current9.Value;
ptr10 = _current10.Value;
ptr11 = _current11.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8, out Ptr<T9> ptr9, out Ptr<T10> ptr10, out Ptr<T11> ptr11)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
ptr9 = _current9.Value;
ptr10 = _current10.Value;
ptr11 = _current11.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_current1 = _iterator.GetColumn<T1>(1);
_current2 = _iterator.GetColumn<T2>(2);
_current3 = _iterator.GetColumn<T3>(3);
_current4 = _iterator.GetColumn<T4>(4);
_current5 = _iterator.GetColumn<T5>(5);
_current6 = _iterator.GetColumn<T6>(6);
_current7 = _iterator.GetColumn<T7>(7);
_current8 = _iterator.GetColumn<T8>(8);
_current9 = _iterator.GetColumn<T9>(9);
_current10 = _iterator.GetColumn<T10>(10);
_current11 = _iterator.GetColumn<T11>(11);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
_current1.Next();
_current2.Next();
_current3.Next();
_current4.Next();
_current5.Next();
_current6.Next();
_current7.Next();
_current8.Next();
_current9.Next();
_current10.Next();
_current11.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> GetEnumerator() => this;
}
[SkipLocalsInit]
public unsafe ref struct Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> : IData<Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>>
where T0 : struct where T1 : struct where T2 : struct where T3 : struct where T4 : struct where T5 : struct where T6 : struct where T7 : struct where T8 : struct where T9 : struct where T10 : struct where T11 : struct where T12 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
private DataRow<T1> _current1;
private DataRow<T2> _current2;
private DataRow<T3> _current3;
private DataRow<T4> _current4;
private DataRow<T5> _current5;
private DataRow<T6> _current6;
private DataRow<T7> _current7;
private DataRow<T8> _current8;
private DataRow<T9> _current9;
private DataRow<T10> _current10;
private DataRow<T11> _current11;
private DataRow<T12> _current12;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
builder.With<T1>();
builder.With<T2>();
builder.With<T3>();
builder.With<T4>();
builder.With<T5>();
builder.With<T6>();
builder.With<T7>();
builder.With<T8>();
builder.With<T9>();
builder.With<T10>();
builder.With<T11>();
builder.With<T12>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> CreateIterator(QueryIterator iterator)
=> new Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8, out Ptr<T9> ptr9, out Ptr<T10> ptr10, out Ptr<T11> ptr11, out Ptr<T12> ptr12)
{
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
ptr9 = _current9.Value;
ptr10 = _current10.Value;
ptr11 = _current11.Value;
ptr12 = _current12.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8, out Ptr<T9> ptr9, out Ptr<T10> ptr10, out Ptr<T11> ptr11, out Ptr<T12> ptr12)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
ptr9 = _current9.Value;
ptr10 = _current10.Value;
ptr11 = _current11.Value;
ptr12 = _current12.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_current1 = _iterator.GetColumn<T1>(1);
_current2 = _iterator.GetColumn<T2>(2);
_current3 = _iterator.GetColumn<T3>(3);
_current4 = _iterator.GetColumn<T4>(4);
_current5 = _iterator.GetColumn<T5>(5);
_current6 = _iterator.GetColumn<T6>(6);
_current7 = _iterator.GetColumn<T7>(7);
_current8 = _iterator.GetColumn<T8>(8);
_current9 = _iterator.GetColumn<T9>(9);
_current10 = _iterator.GetColumn<T10>(10);
_current11 = _iterator.GetColumn<T11>(11);
_current12 = _iterator.GetColumn<T12>(12);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
_current1.Next();
_current2.Next();
_current3.Next();
_current4.Next();
_current5.Next();
_current6.Next();
_current7.Next();
_current8.Next();
_current9.Next();
_current10.Next();
_current11.Next();
_current12.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> GetEnumerator() => this;
}
[SkipLocalsInit]
public unsafe ref struct Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> : IData<Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>>
where T0 : struct where T1 : struct where T2 : struct where T3 : struct where T4 : struct where T5 : struct where T6 : struct where T7 : struct where T8 : struct where T9 : struct where T10 : struct where T11 : struct where T12 : struct where T13 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
private DataRow<T1> _current1;
private DataRow<T2> _current2;
private DataRow<T3> _current3;
private DataRow<T4> _current4;
private DataRow<T5> _current5;
private DataRow<T6> _current6;
private DataRow<T7> _current7;
private DataRow<T8> _current8;
private DataRow<T9> _current9;
private DataRow<T10> _current10;
private DataRow<T11> _current11;
private DataRow<T12> _current12;
private DataRow<T13> _current13;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
builder.With<T1>();
builder.With<T2>();
builder.With<T3>();
builder.With<T4>();
builder.With<T5>();
builder.With<T6>();
builder.With<T7>();
builder.With<T8>();
builder.With<T9>();
builder.With<T10>();
builder.With<T11>();
builder.With<T12>();
builder.With<T13>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> CreateIterator(QueryIterator iterator)
=> new Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8, out Ptr<T9> ptr9, out Ptr<T10> ptr10, out Ptr<T11> ptr11, out Ptr<T12> ptr12, out Ptr<T13> ptr13)
{
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
ptr9 = _current9.Value;
ptr10 = _current10.Value;
ptr11 = _current11.Value;
ptr12 = _current12.Value;
ptr13 = _current13.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8, out Ptr<T9> ptr9, out Ptr<T10> ptr10, out Ptr<T11> ptr11, out Ptr<T12> ptr12, out Ptr<T13> ptr13)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
ptr9 = _current9.Value;
ptr10 = _current10.Value;
ptr11 = _current11.Value;
ptr12 = _current12.Value;
ptr13 = _current13.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_current1 = _iterator.GetColumn<T1>(1);
_current2 = _iterator.GetColumn<T2>(2);
_current3 = _iterator.GetColumn<T3>(3);
_current4 = _iterator.GetColumn<T4>(4);
_current5 = _iterator.GetColumn<T5>(5);
_current6 = _iterator.GetColumn<T6>(6);
_current7 = _iterator.GetColumn<T7>(7);
_current8 = _iterator.GetColumn<T8>(8);
_current9 = _iterator.GetColumn<T9>(9);
_current10 = _iterator.GetColumn<T10>(10);
_current11 = _iterator.GetColumn<T11>(11);
_current12 = _iterator.GetColumn<T12>(12);
_current13 = _iterator.GetColumn<T13>(13);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
_current1.Next();
_current2.Next();
_current3.Next();
_current4.Next();
_current5.Next();
_current6.Next();
_current7.Next();
_current8.Next();
_current9.Next();
_current10.Next();
_current11.Next();
_current12.Next();
_current13.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> GetEnumerator() => this;
}
[SkipLocalsInit]
public unsafe ref struct Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> : IData<Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>>
where T0 : struct where T1 : struct where T2 : struct where T3 : struct where T4 : struct where T5 : struct where T6 : struct where T7 : struct where T8 : struct where T9 : struct where T10 : struct where T11 : struct where T12 : struct where T13 : struct where T14 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
private DataRow<T1> _current1;
private DataRow<T2> _current2;
private DataRow<T3> _current3;
private DataRow<T4> _current4;
private DataRow<T5> _current5;
private DataRow<T6> _current6;
private DataRow<T7> _current7;
private DataRow<T8> _current8;
private DataRow<T9> _current9;
private DataRow<T10> _current10;
private DataRow<T11> _current11;
private DataRow<T12> _current12;
private DataRow<T13> _current13;
private DataRow<T14> _current14;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
builder.With<T1>();
builder.With<T2>();
builder.With<T3>();
builder.With<T4>();
builder.With<T5>();
builder.With<T6>();
builder.With<T7>();
builder.With<T8>();
builder.With<T9>();
builder.With<T10>();
builder.With<T11>();
builder.With<T12>();
builder.With<T13>();
builder.With<T14>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> CreateIterator(QueryIterator iterator)
=> new Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8, out Ptr<T9> ptr9, out Ptr<T10> ptr10, out Ptr<T11> ptr11, out Ptr<T12> ptr12, out Ptr<T13> ptr13, out Ptr<T14> ptr14)
{
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
ptr9 = _current9.Value;
ptr10 = _current10.Value;
ptr11 = _current11.Value;
ptr12 = _current12.Value;
ptr13 = _current13.Value;
ptr14 = _current14.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8, out Ptr<T9> ptr9, out Ptr<T10> ptr10, out Ptr<T11> ptr11, out Ptr<T12> ptr12, out Ptr<T13> ptr13, out Ptr<T14> ptr14)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
ptr9 = _current9.Value;
ptr10 = _current10.Value;
ptr11 = _current11.Value;
ptr12 = _current12.Value;
ptr13 = _current13.Value;
ptr14 = _current14.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_current1 = _iterator.GetColumn<T1>(1);
_current2 = _iterator.GetColumn<T2>(2);
_current3 = _iterator.GetColumn<T3>(3);
_current4 = _iterator.GetColumn<T4>(4);
_current5 = _iterator.GetColumn<T5>(5);
_current6 = _iterator.GetColumn<T6>(6);
_current7 = _iterator.GetColumn<T7>(7);
_current8 = _iterator.GetColumn<T8>(8);
_current9 = _iterator.GetColumn<T9>(9);
_current10 = _iterator.GetColumn<T10>(10);
_current11 = _iterator.GetColumn<T11>(11);
_current12 = _iterator.GetColumn<T12>(12);
_current13 = _iterator.GetColumn<T13>(13);
_current14 = _iterator.GetColumn<T14>(14);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
_current1.Next();
_current2.Next();
_current3.Next();
_current4.Next();
_current5.Next();
_current6.Next();
_current7.Next();
_current8.Next();
_current9.Next();
_current10.Next();
_current11.Next();
_current12.Next();
_current13.Next();
_current14.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> GetEnumerator() => this;
}
[SkipLocalsInit]
public unsafe ref struct Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> : IData<Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>>
where T0 : struct where T1 : struct where T2 : struct where T3 : struct where T4 : struct where T5 : struct where T6 : struct where T7 : struct where T8 : struct where T9 : struct where T10 : struct where T11 : struct where T12 : struct where T13 : struct where T14 : struct where T15 : struct
{
private QueryIterator _iterator;
private int _index, _count;
private ReadOnlySpan<EntityView> _entities;
private DataRow<T0> _current0;
private DataRow<T1> _current1;
private DataRow<T2> _current2;
private DataRow<T3> _current3;
private DataRow<T4> _current4;
private DataRow<T5> _current5;
private DataRow<T6> _current6;
private DataRow<T7> _current7;
private DataRow<T8> _current8;
private DataRow<T9> _current9;
private DataRow<T10> _current10;
private DataRow<T11> _current11;
private DataRow<T12> _current12;
private DataRow<T13> _current13;
private DataRow<T14> _current14;
private DataRow<T15> _current15;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Data(QueryIterator queryIterator)
{
_iterator = queryIterator;
_index = -1;
_count = -1;
}
public static void Build(QueryBuilder builder)
{
builder.With<T0>();
builder.With<T1>();
builder.With<T2>();
builder.With<T3>();
builder.With<T4>();
builder.With<T5>();
builder.With<T6>();
builder.With<T7>();
builder.With<T8>();
builder.With<T9>();
builder.With<T10>();
builder.With<T11>();
builder.With<T12>();
builder.With<T13>();
builder.With<T14>();
builder.With<T15>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> CreateIterator(QueryIterator iterator)
=> new Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(iterator);
[System.Diagnostics.CodeAnalysis.UnscopedRef]
public ref Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8, out Ptr<T9> ptr9, out Ptr<T10> ptr10, out Ptr<T11> ptr11, out Ptr<T12> ptr12, out Ptr<T13> ptr13, out Ptr<T14> ptr14, out Ptr<T15> ptr15)
{
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
ptr9 = _current9.Value;
ptr10 = _current10.Value;
ptr11 = _current11.Value;
ptr12 = _current12.Value;
ptr13 = _current13.Value;
ptr14 = _current14.Value;
ptr15 = _current15.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Deconstruct(out PtrRO<EntityView> entity, out Ptr<T0> ptr0, out Ptr<T1> ptr1, out Ptr<T2> ptr2, out Ptr<T3> ptr3, out Ptr<T4> ptr4, out Ptr<T5> ptr5, out Ptr<T6> ptr6, out Ptr<T7> ptr7, out Ptr<T8> ptr8, out Ptr<T9> ptr9, out Ptr<T10> ptr10, out Ptr<T11> ptr11, out Ptr<T12> ptr12, out Ptr<T13> ptr13, out Ptr<T14> ptr14, out Ptr<T15> ptr15)
{
entity = new (in _entities[_index]);
ptr0 = _current0.Value;
ptr1 = _current1.Value;
ptr2 = _current2.Value;
ptr3 = _current3.Value;
ptr4 = _current4.Value;
ptr5 = _current5.Value;
ptr6 = _current6.Value;
ptr7 = _current7.Value;
ptr8 = _current8.Value;
ptr9 = _current9.Value;
ptr10 = _current10.Value;
ptr11 = _current11.Value;
ptr12 = _current12.Value;
ptr13 = _current13.Value;
ptr14 = _current14.Value;
ptr15 = _current15.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (++_index >= _count)
{
if (!_iterator.Next())
return false;
_current0 = _iterator.GetColumn<T0>(0);
_current1 = _iterator.GetColumn<T1>(1);
_current2 = _iterator.GetColumn<T2>(2);
_current3 = _iterator.GetColumn<T3>(3);
_current4 = _iterator.GetColumn<T4>(4);
_current5 = _iterator.GetColumn<T5>(5);
_current6 = _iterator.GetColumn<T6>(6);
_current7 = _iterator.GetColumn<T7>(7);
_current8 = _iterator.GetColumn<T8>(8);
_current9 = _iterator.GetColumn<T9>(9);
_current10 = _iterator.GetColumn<T10>(10);
_current11 = _iterator.GetColumn<T11>(11);
_current12 = _iterator.GetColumn<T12>(12);
_current13 = _iterator.GetColumn<T13>(13);
_current14 = _iterator.GetColumn<T14>(14);
_current15 = _iterator.GetColumn<T15>(15);
_entities = _iterator.Entities();
_index = 0;
_count = _iterator.Count;
}
else
{
_current0.Next();
_current1.Next();
_current2.Next();
_current3.Next();
_current4.Next();
_current5.Next();
_current6.Next();
_current7.Next();
_current8.Next();
_current9.Next();
_current10.Next();
_current11.Next();
_current12.Next();
_current13.Next();
_current14.Next();
_current15.Next();
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Data<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> GetEnumerator() => this;
}
#endif
}
#pragma warning restore 1591
| 411 | 0.732982 | 1 | 0.732982 | game-dev | MEDIA | 0.170033 | game-dev | 0.958537 | 1 | 0.958537 |
ErikOverflow/SimpleIncremental | 1,317 | Simple Incremental/Assets/Scripts/Editors/EditorEnemyStatsSystem.cs | using UnityEditor;
using UnityEngine;
#if UNITY_EDITOR
[CustomEditor(typeof(EnemyStatsSystem))]
public class EnemyStatsSystemEditor : Editor
{
EnemyStatsSystem myStatSystem;
public override void OnInspectorGUI() //This is all just a fancy way to make a button to trigger "Recalculate"
{
DrawDefaultInspector();
myStatSystem = (EnemyStatsSystem)target;
GUILayout.BeginVertical();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Recalculate Stats", GUILayout.MaxWidth(200), GUILayout.Height(50)))
{
Recalculate();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.EndVertical();
}
//This is for initializing values in the editor only. ApplyAugments will be triggered during build by a GameEventListener listening for any type of stat changes
public void Recalculate()
{
myStatSystem.Awake();
EnemyHook enemyHook = myStatSystem.GetComponent<EnemyHook>();
enemyHook.Awake();
StatAugment[] statAugments = myStatSystem.GetComponentsInChildren<StatAugment>();
foreach (StatAugment augment in statAugments)
{
augment.Awake();
}
myStatSystem.ApplyAugments();
}
}
#endif | 411 | 0.679429 | 1 | 0.679429 | game-dev | MEDIA | 0.916689 | game-dev | 0.889652 | 1 | 0.889652 |
PixieCatSupreme/AnodyneSharp | 5,929 | AnodyneSharp/AnodyneSharp.Shared/States/MainMenu/MainMenuState.cs | using AnodyneSharp.Dialogue;
using AnodyneSharp.Input;
using AnodyneSharp.Registry;
using AnodyneSharp.Sounds;
using AnodyneSharp.States.MenuSubstates;
using AnodyneSharp.States.MenuSubstates.MainMenu;
using AnodyneSharp.UI;
using AnodyneSharp.UI.PauseMenu;
using Microsoft.Xna.Framework;
using RSG;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AnodyneSharp.States.MainMenu
{
public class MainMenuState : State
{
private static int _state = 0;
List<(UILabel label, Func<Substate> create)> substates;
private UILabel _inputLabel;
private MenuSelector _selector;
private int _lastState = _state;
private bool _inSubstate;
private Substate _substate;
private float xOffset;
public MainMenuState()
{
_selector = new MenuSelector();
_selector.Play("enabledRight");
UpdateEntities = false;
SetLabels();
StateChanged();
}
public override void Update()
{
base.Update();
if (GlobalState.RefreshLabels)
{
GlobalState.RefreshLabels = false;
SetLabels();
}
if (KeyInput.ControllerModeChanged)
{
_inputLabel.SetText($"{DialogueManager.GetDialogue("misc", "any", "secrets", 14)} {DialogueManager.GetDialogue("misc", "any", "secrets", 15)}");
}
_selector.Update();
_selector.PostUpdate();
_substate.Update();
if (!_inSubstate && KeyInput.JustPressedRebindableKey(KeyFunctions.Cancel))
{
SoundManager.PlayPitchedSoundEffect("pause_sound", -0.1f);
GlobalState.GameState.SetState<TitleState>();
}
else if (!_inSubstate)
{
BrowseInput();
}
else
{
_substate.HandleInput();
if (_substate.Exit)
{
_inSubstate = false;
_substate.Exit = false;
_selector.Play("enabledRight");
}
}
if (_lastState != _state)
{
StateChanged();
}
}
public override void DrawUI()
{
base.DrawUI();
_selector.Draw();
foreach (var (label, _) in substates)
{
label.Draw();
}
_inputLabel.Draw();
_substate.DrawUI();
}
private void BrowseInput()
{
if (KeyInput.JustPressedRebindableKey(KeyFunctions.Accept) || KeyInput.JustPressedRebindableKey(KeyFunctions.Right))
{
SoundManager.PlaySoundEffect("menu_select");
_inSubstate = true;
_selector.Play("disabledRight");
_substate.GetControl();
}
else if (KeyInput.JustPressedRebindableKey(KeyFunctions.Up))
{
if (_state == 0)
{
SoundManager.PlaySoundEffect("menu_move");
return;
}
SoundManager.PlaySoundEffect("menu_move");
_state--;
}
else if (KeyInput.JustPressedRebindableKey(KeyFunctions.Down))
{
if (_state == substates.Count-1)
{
SoundManager.PlaySoundEffect("menu_move");
return;
}
SoundManager.PlaySoundEffect("menu_move");
_state++;
}
}
private void StateChanged()
{
_lastState = _state;
_selector.Position = new Vector2(2 + xOffset, 34 + _state * 16);
_substate = substates[_state].create();
}
private void SetLabels()
{
xOffset = GlobalState.CurrentLanguage switch
{
Language.ES => -2,
Language.IT => -2,
Language.PT_BR => -2,
_ => 0,
};
float x = 10f + xOffset;
float startY = GameConstants.HEADER_HEIGHT - GameConstants.LineOffset + 11 + (GlobalState.CurrentLanguage == Language.ZH_CN ? 1 : 0);
float yStep = (GameConstants.FONT_LINE_HEIGHT - GameConstants.LineOffset) * 2;
Color color = new Color(116, 140, 144);
substates = GetLabels().Select((state, index) => (new UILabel(new(x, startY + yStep * index), false, state.name, color), state.create)).ToList();
Vector2 inputPos = Vector2.Zero;
if (GlobalState.CurrentLanguage == Language.ZH_CN)
{
inputPos = new Vector2(2, 168 - GameConstants.LineOffset + 1);
}
else
{
inputPos = new Vector2(2, 168);
if (GlobalState.CurrentLanguage == Language.KR)
{
inputPos.Y -= 1;
}
}
_inputLabel = new UILabel(inputPos, false, $"{DialogueManager.GetDialogue("misc", "any", "secrets", 14)} {DialogueManager.GetDialogue("misc", "any", "secrets", 15)}", color);
}
private List<(string name, Func<Substate> create)> GetLabels()
{
List<(string name, Func<Substate> create)> ret = new()
{
("1", () => new FileSubstate(0)),
("2", () => new FileSubstate(1)),
("3", () => new FileSubstate(2)),
(DialogueManager.GetDialogue("misc", "any", "config", 0), () => new ConfigSubstate(true)),
};
Modding.ModLoader.mods.ForEach(mod => mod.ChangeMainMenu(ref ret));
return ret;
}
}
}
| 411 | 0.829455 | 1 | 0.829455 | game-dev | MEDIA | 0.797179 | game-dev,desktop-app | 0.887724 | 1 | 0.887724 |
11011010/BFA-Frankenstein-Core | 7,626 | src/server/scripts/Northrend/Naxxramas/boss_razuvious.cpp | /*
* Copyright (C) 2020 BfaCore
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "InstanceScript.h"
#include "MotionMaster.h"
#include "naxxramas.h"
#include "ObjectAccessor.h"
#include "ScriptedCreature.h"
#include "SpellInfo.h"
enum Yells
{
SAY_AGGRO = 0,
SAY_SLAY = 1,
SAY_TAUNTED = 2,
SAY_DEATH = 3
};
enum Spells
{
SPELL_UNBALANCING_STRIKE = 26613,
SPELL_DISRUPTING_SHOUT = 29107,
SPELL_JAGGED_KNIFE = 55550,
SPELL_HOPELESS = 29125,
SPELL_UNDERSTUDY_TAUNT = 29060,
SPELL_UNDERSTUDY_BLOOD_STRIKE = 61696,
SPELL_FORCE_OBEDIENCE = 55479
};
enum Events
{
EVENT_ATTACK = 1,
EVENT_STRIKE,
EVENT_SHOUT,
EVENT_KNIFE
};
enum SummonGroups
{
SUMMON_GROUP_10MAN = 1,
SUMMON_GROUP_25MAN = 2
};
class boss_razuvious : public CreatureScript
{
public:
boss_razuvious() : CreatureScript("boss_razuvious") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetNaxxramasAI<boss_razuviousAI>(creature);
}
struct boss_razuviousAI : public BossAI
{
boss_razuviousAI(Creature* creature) : BossAI(creature, BOSS_RAZUVIOUS) { }
void SummonAdds()
{
me->SummonCreatureGroup(SUMMON_GROUP_10MAN);
if (Is25ManRaid())
me->SummonCreatureGroup(SUMMON_GROUP_25MAN);
}
void InitializeAI() override
{
if (!me->isDead())
{
Reset();
SummonAdds();
}
}
void JustReachedHome() override
{
_JustReachedHome();
SummonAdds();
me->GetMotionMaster()->Initialize();
}
void KilledUnit(Unit* victim) override
{
if (victim->GetTypeId() == TYPEID_PLAYER || (victim->GetTypeId() == TYPEID_UNIT && victim->GetEntry() == NPC_DK_UNDERSTUDY))
Talk(SAY_SLAY);
}
void SpellHit(Unit* caster, SpellInfo const* spell) override
{
if (spell->Id == SPELL_UNDERSTUDY_TAUNT)
Talk(SAY_TAUNTED, caster);
}
void JustDied(Unit* /*killer*/) override
{
for (ObjectGuid summonGuid : summons)
if (Creature* summon = ObjectAccessor::GetCreature(*me, summonGuid))
summon->RemoveCharmAuras();
Talk(SAY_DEATH);
DoCastAOE(SPELL_HOPELESS, true);
events.Reset();
instance->SetBossState(BOSS_RAZUVIOUS, DONE);
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
me->StopMoving();
summons.DoZoneInCombat();
Talk(SAY_AGGRO);
events.ScheduleEvent(EVENT_ATTACK, Seconds(7));
events.ScheduleEvent(EVENT_STRIKE, Seconds(21));
events.ScheduleEvent(EVENT_SHOUT, Seconds(16));
events.ScheduleEvent(EVENT_KNIFE, Seconds(10));
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_ATTACK:
SetCombatMovement(true);
if (Unit* victim = me->GetVictim())
me->GetMotionMaster()->MoveChase(victim);
break;
case EVENT_STRIKE:
DoCastVictim(SPELL_UNBALANCING_STRIKE);
events.Repeat(Seconds(6));
return;
case EVENT_SHOUT:
DoCastAOE(SPELL_DISRUPTING_SHOUT);
events.Repeat(Seconds(16));
return;
case EVENT_KNIFE:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 45.0f))
DoCast(target, SPELL_JAGGED_KNIFE);
events.Repeat(randtime(Seconds(10), Seconds(15)));
return;
}
}
DoMeleeAttackIfReady();
}
void Reset() override
{
SetCombatMovement(false);
_Reset();
}
};
};
class npc_dk_understudy : public CreatureScript
{
public:
npc_dk_understudy() : CreatureScript("npc_dk_understudy") { }
struct npc_dk_understudyAI : public ScriptedAI
{
npc_dk_understudyAI(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()), bloodStrikeTimer(0)
{
creature->LoadEquipment(1);
}
void EnterCombat(Unit* /*who*/) override
{
me->SetEmoteState(EMOTE_ONESHOT_NONE);
if (Creature* razuvious = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_RAZUVIOUS)))
razuvious->AI()->DoZoneInCombat(nullptr, 250.0f);
}
void JustReachedHome() override
{
if (_instance->GetBossState(BOSS_RAZUVIOUS) == DONE)
me->DespawnOrUnsummon();
else
ScriptedAI::JustReachedHome();
}
void UpdateAI(uint32 diff) override
{
if (!me->isPossessedByPlayer() && !UpdateVictim())
return;
if (!me->isPossessedByPlayer())
{
if (diff < bloodStrikeTimer)
bloodStrikeTimer -= diff;
else
DoCastVictim(SPELL_UNDERSTUDY_BLOOD_STRIKE);
}
DoMeleeAttackIfReady();
}
void OnCharmed(bool apply) override
{
ScriptedAI::OnCharmed(apply);
if (apply)
{
if (!me->IsInCombat())
EnterCombat(nullptr);
me->StopMoving();
me->SetReactState(REACT_PASSIVE);
_charmer = me->GetCharmerGUID();
}
else
{
me->SetReactState(REACT_AGGRESSIVE);
if (Unit* charmer = ObjectAccessor::GetUnit(*me, _charmer))
me->AddThreat(charmer, 100000.0f);
DoZoneInCombat(nullptr, 250.0f);
}
}
private:
InstanceScript* const _instance;
ObjectGuid _charmer;
uint32 bloodStrikeTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetNaxxramasAI<npc_dk_understudyAI>(creature);
}
};
void AddSC_boss_razuvious()
{
new boss_razuvious();
new npc_dk_understudy();
}
| 411 | 0.972066 | 1 | 0.972066 | game-dev | MEDIA | 0.987581 | game-dev | 0.988534 | 1 | 0.988534 |
ansys/pydyna | 13,940 | src/ansys/dyna/core/keywords/keyword_classes/auto/chemistry_control_pyrptechnic.py | # Copyright (C) 2021 - 2024 ANSYS, Inc. and/or its affiliates.
# SPDX-License-Identifier: MIT
#
#
# 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.
"""Module providing the ChemistryControlPyrptechnic class."""
import typing
from ansys.dyna.core.lib.card import Card, Field, Flag
from ansys.dyna.core.lib.keyword_base import KeywordBase
class ChemistryControlPyrptechnic(KeywordBase):
"""DYNA CHEMISTRY_CONTROL_PYRPTECHNIC keyword"""
keyword = "CHEMISTRY"
subkeyword = "CONTROL_PYRPTECHNIC"
def __init__(self, **kwargs):
"""Initialize the ChemistryControlPyrptechnic class."""
super().__init__(**kwargs)
self._cards = [
Card(
[
Field(
"comp1id",
int,
0,
10,
**kwargs,
),
Field(
"vol1",
float,
10,
10,
**kwargs,
),
Field(
"area1",
float,
20,
10,
**kwargs,
),
Field(
"cd1",
float,
30,
10,
**kwargs,
),
Field(
"p1",
float,
40,
10,
**kwargs,
),
Field(
"t1",
float,
50,
10,
**kwargs,
),
Field(
"delp1",
float,
60,
10,
**kwargs,
),
Field(
"tflame",
float,
70,
10,
**kwargs,
),
],
),
Card(
[
Field(
"comp2id",
int,
0,
10,
**kwargs,
),
Field(
"vol2",
float,
10,
10,
**kwargs,
),
Field(
"area2",
float,
20,
10,
**kwargs,
),
Field(
"cd2",
float,
30,
10,
**kwargs,
),
Field(
"p2",
float,
40,
10,
**kwargs,
),
Field(
"t2",
float,
50,
10,
**kwargs,
),
Field(
"delp2",
float,
60,
10,
**kwargs,
),
Field(
"truntime",
float,
70,
10,
**kwargs,
),
],
),
Card(
[
Field(
"comp3id",
int,
0,
10,
**kwargs,
),
Field(
"vol3",
float,
10,
10,
**kwargs,
),
Field(
"p3",
float,
20,
10,
**kwargs,
),
Field(
"t3",
float,
30,
10,
**kwargs,
),
Field(
"ptime",
float,
40,
10,
**kwargs,
),
],
),
Card(
[
Field(
"file",
str,
0,
80,
**kwargs,
),
],
),
]
@property
def comp1id(self) -> typing.Optional[int]:
"""Get or set the Chemical composition identifier of composition to use in the chamber
""" # nopep8
return self._cards[0].get_value("comp1id")
@comp1id.setter
def comp1id(self, value: int) -> None:
"""Set the comp1id property."""
self._cards[0].set_value("comp1id", value)
@property
def vol1(self) -> typing.Optional[float]:
"""Get or set the Volume of the chamber.
""" # nopep8
return self._cards[0].get_value("vol1")
@vol1.setter
def vol1(self, value: float) -> None:
"""Set the vol1 property."""
self._cards[0].set_value("vol1", value)
@property
def area1(self) -> typing.Optional[float]:
"""Get or set the Area of the chamber
""" # nopep8
return self._cards[0].get_value("area1")
@area1.setter
def area1(self, value: float) -> None:
"""Set the area1 property."""
self._cards[0].set_value("area1", value)
@property
def cd1(self) -> typing.Optional[float]:
"""Get or set the Discharge coefficient of the chamber
""" # nopep8
return self._cards[0].get_value("cd1")
@cd1.setter
def cd1(self, value: float) -> None:
"""Set the cd1 property."""
self._cards[0].set_value("cd1", value)
@property
def p1(self) -> typing.Optional[float]:
"""Get or set the Pressure in the chamber
""" # nopep8
return self._cards[0].get_value("p1")
@p1.setter
def p1(self, value: float) -> None:
"""Set the p1 property."""
self._cards[0].set_value("p1", value)
@property
def t1(self) -> typing.Optional[float]:
"""Get or set the Temperature in the chamber
""" # nopep8
return self._cards[0].get_value("t1")
@t1.setter
def t1(self, value: float) -> None:
"""Set the t1 property."""
self._cards[0].set_value("t1", value)
@property
def delp1(self) -> typing.Optional[float]:
"""Get or set the Rupture pressure in the chamber
""" # nopep8
return self._cards[0].get_value("delp1")
@delp1.setter
def delp1(self, value: float) -> None:
"""Set the delp1 property."""
self._cards[0].set_value("delp1", value)
@property
def tflame(self) -> typing.Optional[float]:
"""Get or set the Adiabatic flame temperature.
""" # nopep8
return self._cards[0].get_value("tflame")
@tflame.setter
def tflame(self, value: float) -> None:
"""Set the tflame property."""
self._cards[0].set_value("tflame", value)
@property
def comp2id(self) -> typing.Optional[int]:
"""Get or set the Chemical composition identifier of composition to use in the plenum
""" # nopep8
return self._cards[1].get_value("comp2id")
@comp2id.setter
def comp2id(self, value: int) -> None:
"""Set the comp2id property."""
self._cards[1].set_value("comp2id", value)
@property
def vol2(self) -> typing.Optional[float]:
"""Get or set the Volume of the plenum
""" # nopep8
return self._cards[1].get_value("vol2")
@vol2.setter
def vol2(self, value: float) -> None:
"""Set the vol2 property."""
self._cards[1].set_value("vol2", value)
@property
def area2(self) -> typing.Optional[float]:
"""Get or set the Area of the plenum
""" # nopep8
return self._cards[1].get_value("area2")
@area2.setter
def area2(self, value: float) -> None:
"""Set the area2 property."""
self._cards[1].set_value("area2", value)
@property
def cd2(self) -> typing.Optional[float]:
"""Get or set the Discharge coefficient of the plenum
""" # nopep8
return self._cards[1].get_value("cd2")
@cd2.setter
def cd2(self, value: float) -> None:
"""Set the cd2 property."""
self._cards[1].set_value("cd2", value)
@property
def p2(self) -> typing.Optional[float]:
"""Get or set the Pressure in the plenum
""" # nopep8
return self._cards[1].get_value("p2")
@p2.setter
def p2(self, value: float) -> None:
"""Set the p2 property."""
self._cards[1].set_value("p2", value)
@property
def t2(self) -> typing.Optional[float]:
"""Get or set the Temperature in the plenum
""" # nopep8
return self._cards[1].get_value("t2")
@t2.setter
def t2(self, value: float) -> None:
"""Set the t2 property."""
self._cards[1].set_value("t2", value)
@property
def delp2(self) -> typing.Optional[float]:
"""Get or set the Rupture pressure in the plenum
""" # nopep8
return self._cards[1].get_value("delp2")
@delp2.setter
def delp2(self, value: float) -> None:
"""Set the delp2 property."""
self._cards[1].set_value("delp2", value)
@property
def truntime(self) -> typing.Optional[float]:
"""Get or set the Total run time
""" # nopep8
return self._cards[1].get_value("truntime")
@truntime.setter
def truntime(self, value: float) -> None:
"""Set the truntime property."""
self._cards[1].set_value("truntime", value)
@property
def comp3id(self) -> typing.Optional[int]:
"""Get or set the Chemical composition identifier of composition to use in the airbag
""" # nopep8
return self._cards[2].get_value("comp3id")
@comp3id.setter
def comp3id(self, value: int) -> None:
"""Set the comp3id property."""
self._cards[2].set_value("comp3id", value)
@property
def vol3(self) -> typing.Optional[float]:
"""Get or set the Volume of the airbag
""" # nopep8
return self._cards[2].get_value("vol3")
@vol3.setter
def vol3(self, value: float) -> None:
"""Set the vol3 property."""
self._cards[2].set_value("vol3", value)
@property
def p3(self) -> typing.Optional[float]:
"""Get or set the Pressure in the airbag
""" # nopep8
return self._cards[2].get_value("p3")
@p3.setter
def p3(self, value: float) -> None:
"""Set the p3 property."""
self._cards[2].set_value("p3", value)
@property
def t3(self) -> typing.Optional[float]:
"""Get or set the Temperature in the airbag.
""" # nopep8
return self._cards[2].get_value("t3")
@t3.setter
def t3(self, value: float) -> None:
"""Set the t3 property."""
self._cards[2].set_value("t3", value)
@property
def ptime(self) -> typing.Optional[float]:
"""Get or set the Time interval for output of time history data to FILE.
""" # nopep8
return self._cards[2].get_value("ptime")
@ptime.setter
def ptime(self, value: float) -> None:
"""Set the ptime property."""
self._cards[2].set_value("ptime", value)
@property
def file(self) -> typing.Optional[str]:
"""Get or set the Name of the lsda file in which to write the results of the inflator simulation.Two load curves are written out to this file: mass flow rate and total temperature as a function of time.
""" # nopep8
return self._cards[3].get_value("file")
@file.setter
def file(self, value: str) -> None:
"""Set the file property."""
self._cards[3].set_value("file", value)
| 411 | 0.565443 | 1 | 0.565443 | game-dev | MEDIA | 0.2623 | game-dev | 0.934961 | 1 | 0.934961 |
Unity-Technologies/com.unity.formats.fbx | 2,576 | com.unity.formats.fbx/Tests/FbxTests/ExportPerformanceTest.cs | using UnityEngine;
using NUnit.Framework;
using System.Diagnostics;
using UnityEditor.Formats.Fbx.Exporter;
namespace FbxExporter.UnitTests
{
public class ExportPerformanceTest : ExporterTestBase
{
private const int NumMeshesToCombine = 15;
// Export should not take longer than this, otherwise test fails
private const long PerformanceThresholdMilliseconds = 30000;
private Stopwatch m_stopwatch;
private GameObject m_toExport;
[SetUp]
public override void Init()
{
base.Init();
m_stopwatch = new Stopwatch();
m_toExport = CreateGameObjectToExport();
}
[TearDown]
public override void Term()
{
base.Term();
GameObject.DestroyImmediate(m_toExport);
}
/// <summary>
/// Creates a GameObject containing a very large mesh to export.
/// </summary>
/// <returns>The game object to export.</returns>
private GameObject CreateGameObjectToExport()
{
CombineInstance[] combine = new CombineInstance[NumMeshesToCombine];
GameObject spheres = GameObject.CreatePrimitive(PrimitiveType.Sphere);
Transform sphereTransform = spheres.transform;
MeshFilter sphereMeshFilter = spheres.GetComponent<MeshFilter>();
Assert.IsNotNull(sphereMeshFilter);
for (int i = 0; i < NumMeshesToCombine; i++)
{
combine[i].mesh = sphereMeshFilter.sharedMesh;
sphereTransform.position = new Vector3(i, i, i);
combine[i].transform = sphereTransform.localToWorldMatrix;
}
sphereMeshFilter.sharedMesh = new Mesh();
sphereMeshFilter.sharedMesh.name = "Spheres Mesh";
sphereMeshFilter.sharedMesh.CombineMeshes(combine);
return spheres;
}
[Test]
public void TestPerformance()
{
Assert.IsNotNull(m_toExport);
var filename = GetRandomFbxFilePath();
UnityEngine.Debug.unityLogger.logEnabled = false;
m_stopwatch.Reset();
m_stopwatch.Start();
var fbxFileName = ModelExporter.ExportObjects(filename, new Object[] {m_toExport}) as string;
m_stopwatch.Stop();
UnityEngine.Debug.unityLogger.logEnabled = true;
Assert.IsNotNull(fbxFileName);
Assert.LessOrEqual(m_stopwatch.ElapsedMilliseconds, PerformanceThresholdMilliseconds);
}
}
}
| 411 | 0.750119 | 1 | 0.750119 | game-dev | MEDIA | 0.775109 | game-dev,graphics-rendering | 0.875272 | 1 | 0.875272 |
Pathoschild/SMAPI | 6,737 | src/SMAPI/Framework/Events/ManagedEvent.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using StardewModdingAPI.Events;
using StardewModdingAPI.Internal;
namespace StardewModdingAPI.Framework.Events;
/// <summary>An event wrapper which intercepts and logs errors in handler code.</summary>
/// <typeparam name="TEventArgs">The event arguments type.</typeparam>
internal class ManagedEvent<TEventArgs> : IManagedEvent
{
/*********
** Fields
*********/
/// <summary>The mod registry with which to identify mods.</summary>
protected readonly ModRegistry ModRegistry;
/// <summary>The underlying event handlers.</summary>
private readonly List<ManagedEventHandler<TEventArgs>> Handlers = [];
/// <summary>A cached snapshot of the <see cref="Handlers"/> sorted by event priority, or <c>null</c> to rebuild it next raise.</summary>
private ManagedEventHandler<TEventArgs>[]? CachedHandlers = [];
/// <summary>The total number of event handlers registered for this events, regardless of whether they're still registered.</summary>
private int RegistrationIndex;
/// <summary>Whether handlers were removed since the last raise.</summary>
private bool HasRemovedHandlers;
/// <summary>Whether any of the handlers have a custom priority.</summary>
private bool HasPriorities;
/*********
** Accessors
*********/
/// <inheritdoc />
public string EventName { get; }
/// <inheritdoc />
public bool HasListeners { get; private set; }
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="eventName">A human-readable name for the event.</param>
/// <param name="modRegistry">The mod registry with which to identify mods.</param>
public ManagedEvent(string eventName, ModRegistry modRegistry)
{
this.EventName = eventName;
this.ModRegistry = modRegistry;
}
/// <summary>Add an event handler.</summary>
/// <param name="handler">The event handler.</param>
/// <param name="mod">The mod which added the event handler.</param>
public void Add(EventHandler<TEventArgs> handler, IModMetadata mod)
{
lock (this.Handlers)
{
EventPriority priority = handler.Method.GetCustomAttribute<EventPriorityAttribute>()?.Priority ?? EventPriority.Normal;
var managedHandler = new ManagedEventHandler<TEventArgs>(handler, this.RegistrationIndex++, priority, mod);
this.Handlers.Add(managedHandler);
this.CachedHandlers = null;
this.HasListeners = true;
this.HasPriorities |= priority != EventPriority.Normal;
}
}
/// <summary>Remove an event handler.</summary>
/// <param name="handler">The event handler.</param>
public void Remove(EventHandler<TEventArgs> handler)
{
lock (this.Handlers)
{
// match C# events: if a handler is listed multiple times, remove the last one added
for (int i = this.Handlers.Count - 1; i >= 0; i--)
{
if (this.Handlers[i].Handler != handler)
continue;
this.Handlers.RemoveAt(i);
this.CachedHandlers = null;
this.HasListeners = this.Handlers.Count != 0;
this.HasRemovedHandlers = true;
break;
}
}
}
/// <summary>Raise the event and notify all handlers.</summary>
/// <param name="args">The event arguments to pass.</param>
public void Raise(TEventArgs args)
{
// skip if no handlers
if (this.Handlers.Count == 0)
return;
// raise event
foreach (ManagedEventHandler<TEventArgs> handler in this.GetHandlers())
{
Context.HeuristicModsRunningCode.Push(handler.SourceMod);
try
{
handler.Handler(null, args);
}
catch (Exception ex)
{
this.LogError(handler, ex);
}
finally
{
Context.HeuristicModsRunningCode.TryPop(out _);
}
}
}
/// <summary>Raise the event and notify all handlers.</summary>
/// <param name="invoke">Invoke an event handler. This receives the mod which registered the handler, and should invoke the callback with the event arguments to pass it.</param>
public void Raise(Action<IModMetadata, Action<TEventArgs>> invoke)
{
// skip if no handlers
if (this.Handlers.Count == 0)
return;
// raise event
foreach (ManagedEventHandler<TEventArgs> handler in this.GetHandlers())
{
Context.HeuristicModsRunningCode.Push(handler.SourceMod);
try
{
invoke(handler.SourceMod, args => handler.Handler(null, args));
}
catch (Exception ex)
{
this.LogError(handler, ex);
}
finally
{
Context.HeuristicModsRunningCode.TryPop(out _);
}
}
}
/*********
** Private methods
*********/
/// <summary>Log an exception from an event handler.</summary>
/// <param name="handler">The event handler instance.</param>
/// <param name="ex">The exception that was raised.</param>
private void LogError(ManagedEventHandler<TEventArgs> handler, Exception ex)
{
handler.SourceMod.LogAsMod($"This mod failed in the {this.EventName} event. Technical details: \n{ex.GetLogSummary()}", LogLevel.Error);
}
/// <summary>Get cached copy of the sorted handlers to invoke.</summary>
/// <remarks>This returns the handlers sorted by priority, and allows iterating the list even if a mod adds/removes handlers while handling it. This is debounced when requested to avoid repeatedly sorting when handlers are added/removed.</remarks>
private ManagedEventHandler<TEventArgs>[] GetHandlers()
{
ManagedEventHandler<TEventArgs>[]? handlers = this.CachedHandlers;
if (handlers == null)
{
lock (this.Handlers)
{
// recheck priorities
if (this.HasRemovedHandlers)
this.HasPriorities = this.Handlers.Any(p => p.Priority != EventPriority.Normal);
// sort by priority if needed
if (this.HasPriorities)
this.Handlers.Sort();
// update cache
this.CachedHandlers = handlers = this.Handlers.ToArray();
this.HasRemovedHandlers = false;
}
}
return handlers;
}
}
| 411 | 0.898118 | 1 | 0.898118 | game-dev | MEDIA | 0.167762 | game-dev | 0.86731 | 1 | 0.86731 |
Deadrik/TFC2 | 2,924 | src/Common/com/bioxx/tfc2/blocks/BlockThatch.java | package com.bioxx.tfc2.blocks;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import com.bioxx.tfc2.TFCItems;
import com.bioxx.tfc2.blocks.terrain.BlockCollapsible;
import com.bioxx.tfc2.core.TFCTabs;
public class BlockThatch extends BlockCollapsible
{
public BlockThatch()
{
super(Material.GRASS, null);
this.setCreativeTab(TFCTabs.TFCBuilding);
this.setSoundType(SoundType.PLANT);
this.lightOpacity = 255;
}
/*******************************************************************************
* 1. Content
*******************************************************************************/
@Override
public int getNaturalSupportRange(IBlockAccess world, BlockPos pos,IBlockState myState)
{
return 6;
}
@Override
public void createFallingEntity(World world, BlockPos pos, IBlockState state)
{
world.setBlockToAir(pos);
EntityItem ei = new EntityItem(world, pos.getX()+0.5, pos.getY(), pos.getZ()+0.5, new ItemStack(TFCItems.Straw, 1+world.rand.nextInt(3)));
world.spawnEntity(ei);
}
@Override
public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos)
{
if(!world.isRemote && pos.up().equals(fromPos) && world.isAirBlock(pos.down()))
{
if(world.getBlockState(fromPos).getBlock() instanceof BlockGravity)
world.destroyBlock(pos, true);
}
}
@Override
public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn)
{
entityIn.motionX *= 0.1D;
entityIn.motionZ *= 0.1D;
}
@Override
public boolean isSideSolid(IBlockState base_state, IBlockAccess world, BlockPos pos, EnumFacing side)
{
if(side == EnumFacing.UP || side == EnumFacing.DOWN)
return false;
return true;
}
@Override
public boolean isPassable(IBlockAccess worldIn, BlockPos pos)
{
return true;
}
/*******************************************************************************
* 2. Rendering
*******************************************************************************/
/*******************************************************************************
* 3. Blockstate
*******************************************************************************/
@Override
public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos)
{
return null;
}
@Override
public boolean isOpaqueCube(IBlockState state)
{
return false;
}
@Override
public boolean isFullCube(IBlockState state)
{
return false;
}
}
| 411 | 0.685493 | 1 | 0.685493 | game-dev | MEDIA | 0.998946 | game-dev | 0.538207 | 1 | 0.538207 |
CalamityTeam/CalamityModPublic | 2,209 | Items/Weapons/Ranged/SandstormGun.cs | using CalamityMod.Items.Materials;
using CalamityMod.Projectiles.Ranged;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Items.Weapons.Ranged
{
public class SandstormGun : ModItem, ILocalizedModType
{
public new string LocalizationCategory => "Items.Weapons.Ranged";
public override void SetDefaults()
{
Item.width = 62;
Item.height = 26;
Item.damage = 80;
Item.DamageType = DamageClass.Ranged;
Item.useTime = 15;
Item.useAnimation = 15;
Item.useStyle = ItemUseStyleID.Shoot;
Item.noMelee = true;
Item.knockBack = 5f;
Item.value = CalamityGlobalItem.RarityLimeBuyPrice;
Item.rare = ItemRarityID.Lime;
Item.UseSound = SoundID.Item11;
Item.autoReuse = true;
Item.shootSpeed = 12f;
Item.shoot = ModContent.ProjectileType<SandstormBullet>();
Item.useAmmo = AmmoID.Sand;
Item.Calamity().canFirePointBlankShots = true;
}
public override Vector2? HoldoutOffset()
{
return new Vector2(-10, 0);
}
public override bool CanConsumeAmmo(Item ammo, Player player)
{
if (Main.rand.Next(0, 100) < 50)
return false;
return true;
}
public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback)
{
Projectile.NewProjectile(source, position.X, position.Y, velocity.X, velocity.Y, ModContent.ProjectileType<SandstormBullet>(), damage, knockback, player.whoAmI);
return false;
}
public override void AddRecipes()
{
CreateRecipe().
AddIngredient(ItemID.Sandgun).
AddIngredient<GrandScale>().
AddIngredient(ItemID.Amber, 5).
AddIngredient(ItemID.SandBlock, 50).
AddTile(TileID.MythrilAnvil).
Register();
}
}
}
| 411 | 0.945656 | 1 | 0.945656 | game-dev | MEDIA | 0.992363 | game-dev | 0.887735 | 1 | 0.887735 |
mauge123/mechanical-blender | 12,420 | extern/bullet2/src/BulletCollision/CollisionShapes/btOptimizedBvh.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 "btOptimizedBvh.h"
#include "btStridingMeshInterface.h"
#include "LinearMath/btAabbUtil2.h"
#include "LinearMath/btIDebugDraw.h"
btOptimizedBvh::btOptimizedBvh()
{
}
btOptimizedBvh::~btOptimizedBvh()
{
}
void btOptimizedBvh::build(btStridingMeshInterface* triangles, bool useQuantizedAabbCompression, const btVector3& bvhAabbMin, const btVector3& bvhAabbMax)
{
m_useQuantization = useQuantizedAabbCompression;
// NodeArray triangleNodes;
struct NodeTriangleCallback : public btInternalTriangleIndexCallback
{
NodeArray& m_triangleNodes;
NodeTriangleCallback& operator=(NodeTriangleCallback& other)
{
m_triangleNodes.copyFromArray(other.m_triangleNodes);
return *this;
}
NodeTriangleCallback(NodeArray& triangleNodes)
:m_triangleNodes(triangleNodes)
{
}
virtual void internalProcessTriangleIndex(btVector3* triangle,int partId,int triangleIndex)
{
btOptimizedBvhNode node;
btVector3 aabbMin,aabbMax;
aabbMin.setValue(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
aabbMax.setValue(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));
aabbMin.setMin(triangle[0]);
aabbMax.setMax(triangle[0]);
aabbMin.setMin(triangle[1]);
aabbMax.setMax(triangle[1]);
aabbMin.setMin(triangle[2]);
aabbMax.setMax(triangle[2]);
//with quantization?
node.m_aabbMinOrg = aabbMin;
node.m_aabbMaxOrg = aabbMax;
node.m_escapeIndex = -1;
//for child nodes
node.m_subPart = partId;
node.m_triangleIndex = triangleIndex;
m_triangleNodes.push_back(node);
}
};
struct QuantizedNodeTriangleCallback : public btInternalTriangleIndexCallback
{
QuantizedNodeArray& m_triangleNodes;
const btQuantizedBvh* m_optimizedTree; // for quantization
QuantizedNodeTriangleCallback& operator=(QuantizedNodeTriangleCallback& other)
{
m_triangleNodes.copyFromArray(other.m_triangleNodes);
m_optimizedTree = other.m_optimizedTree;
return *this;
}
QuantizedNodeTriangleCallback(QuantizedNodeArray& triangleNodes,const btQuantizedBvh* tree)
:m_triangleNodes(triangleNodes),m_optimizedTree(tree)
{
}
virtual void internalProcessTriangleIndex(btVector3* triangle,int partId,int triangleIndex)
{
// The partId and triangle index must fit in the same (positive) integer
btAssert(partId < (1<<MAX_NUM_PARTS_IN_BITS));
btAssert(triangleIndex < (1<<(31-MAX_NUM_PARTS_IN_BITS)));
//negative indices are reserved for escapeIndex
btAssert(triangleIndex>=0);
btQuantizedBvhNode node;
btVector3 aabbMin,aabbMax;
aabbMin.setValue(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
aabbMax.setValue(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));
aabbMin.setMin(triangle[0]);
aabbMax.setMax(triangle[0]);
aabbMin.setMin(triangle[1]);
aabbMax.setMax(triangle[1]);
aabbMin.setMin(triangle[2]);
aabbMax.setMax(triangle[2]);
//PCK: add these checks for zero dimensions of aabb
const btScalar MIN_AABB_DIMENSION = btScalar(0.002);
const btScalar MIN_AABB_HALF_DIMENSION = btScalar(0.001);
if (aabbMax.x() - aabbMin.x() < MIN_AABB_DIMENSION)
{
aabbMax.setX(aabbMax.x() + MIN_AABB_HALF_DIMENSION);
aabbMin.setX(aabbMin.x() - MIN_AABB_HALF_DIMENSION);
}
if (aabbMax.y() - aabbMin.y() < MIN_AABB_DIMENSION)
{
aabbMax.setY(aabbMax.y() + MIN_AABB_HALF_DIMENSION);
aabbMin.setY(aabbMin.y() - MIN_AABB_HALF_DIMENSION);
}
if (aabbMax.z() - aabbMin.z() < MIN_AABB_DIMENSION)
{
aabbMax.setZ(aabbMax.z() + MIN_AABB_HALF_DIMENSION);
aabbMin.setZ(aabbMin.z() - MIN_AABB_HALF_DIMENSION);
}
m_optimizedTree->quantize(&node.m_quantizedAabbMin[0],aabbMin,0);
m_optimizedTree->quantize(&node.m_quantizedAabbMax[0],aabbMax,1);
node.m_escapeIndexOrTriangleIndex = (partId<<(31-MAX_NUM_PARTS_IN_BITS)) | triangleIndex;
m_triangleNodes.push_back(node);
}
};
int numLeafNodes = 0;
if (m_useQuantization)
{
//initialize quantization values
setQuantizationValues(bvhAabbMin,bvhAabbMax);
QuantizedNodeTriangleCallback callback(m_quantizedLeafNodes,this);
triangles->InternalProcessAllTriangles(&callback,m_bvhAabbMin,m_bvhAabbMax);
//now we have an array of leafnodes in m_leafNodes
numLeafNodes = m_quantizedLeafNodes.size();
m_quantizedContiguousNodes.resize(2*numLeafNodes);
} else
{
NodeTriangleCallback callback(m_leafNodes);
btVector3 aabbMin(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));
btVector3 aabbMax(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
triangles->InternalProcessAllTriangles(&callback,aabbMin,aabbMax);
//now we have an array of leafnodes in m_leafNodes
numLeafNodes = m_leafNodes.size();
m_contiguousNodes.resize(2*numLeafNodes);
}
m_curNodeIndex = 0;
buildTree(0,numLeafNodes);
///if the entire tree is small then subtree size, we need to create a header info for the tree
if(m_useQuantization && !m_SubtreeHeaders.size())
{
btBvhSubtreeInfo& subtree = m_SubtreeHeaders.expand();
subtree.setAabbFromQuantizeNode(m_quantizedContiguousNodes[0]);
subtree.m_rootNodeIndex = 0;
subtree.m_subtreeSize = m_quantizedContiguousNodes[0].isLeafNode() ? 1 : m_quantizedContiguousNodes[0].getEscapeIndex();
}
//PCK: update the copy of the size
m_subtreeHeaderCount = m_SubtreeHeaders.size();
//PCK: clear m_quantizedLeafNodes and m_leafNodes, they are temporary
m_quantizedLeafNodes.clear();
m_leafNodes.clear();
}
void btOptimizedBvh::refit(btStridingMeshInterface* meshInterface,const btVector3& aabbMin,const btVector3& aabbMax)
{
if (m_useQuantization)
{
setQuantizationValues(aabbMin,aabbMax);
updateBvhNodes(meshInterface,0,m_curNodeIndex,0);
///now update all subtree headers
int i;
for (i=0;i<m_SubtreeHeaders.size();i++)
{
btBvhSubtreeInfo& subtree = m_SubtreeHeaders[i];
subtree.setAabbFromQuantizeNode(m_quantizedContiguousNodes[subtree.m_rootNodeIndex]);
}
} else
{
}
}
void btOptimizedBvh::refitPartial(btStridingMeshInterface* meshInterface,const btVector3& aabbMin,const btVector3& aabbMax)
{
//incrementally initialize quantization values
btAssert(m_useQuantization);
btAssert(aabbMin.getX() > m_bvhAabbMin.getX());
btAssert(aabbMin.getY() > m_bvhAabbMin.getY());
btAssert(aabbMin.getZ() > m_bvhAabbMin.getZ());
btAssert(aabbMax.getX() < m_bvhAabbMax.getX());
btAssert(aabbMax.getY() < m_bvhAabbMax.getY());
btAssert(aabbMax.getZ() < m_bvhAabbMax.getZ());
///we should update all quantization values, using updateBvhNodes(meshInterface);
///but we only update chunks that overlap the given aabb
unsigned short quantizedQueryAabbMin[3];
unsigned short quantizedQueryAabbMax[3];
quantize(&quantizedQueryAabbMin[0],aabbMin,0);
quantize(&quantizedQueryAabbMax[0],aabbMax,1);
int i;
for (i=0;i<this->m_SubtreeHeaders.size();i++)
{
btBvhSubtreeInfo& subtree = m_SubtreeHeaders[i];
//PCK: unsigned instead of bool
unsigned overlap = testQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,subtree.m_quantizedAabbMin,subtree.m_quantizedAabbMax);
if (overlap != 0)
{
updateBvhNodes(meshInterface,subtree.m_rootNodeIndex,subtree.m_rootNodeIndex+subtree.m_subtreeSize,i);
subtree.setAabbFromQuantizeNode(m_quantizedContiguousNodes[subtree.m_rootNodeIndex]);
}
}
}
void btOptimizedBvh::updateBvhNodes(btStridingMeshInterface* meshInterface,int firstNode,int endNode,int index)
{
(void)index;
btAssert(m_useQuantization);
int curNodeSubPart=-1;
//get access info to trianglemesh data
const unsigned char *vertexbase = 0;
int numverts = 0;
PHY_ScalarType type = PHY_INTEGER;
int stride = 0;
const unsigned char *indexbase = 0;
int indexstride = 0;
int numfaces = 0;
PHY_ScalarType indicestype = PHY_INTEGER;
btVector3 triangleVerts[3];
btVector3 aabbMin,aabbMax;
const btVector3& meshScaling = meshInterface->getScaling();
int i;
for (i=endNode-1;i>=firstNode;i--)
{
btQuantizedBvhNode& curNode = m_quantizedContiguousNodes[i];
if (curNode.isLeafNode())
{
//recalc aabb from triangle data
int nodeSubPart = curNode.getPartId();
int nodeTriangleIndex = curNode.getTriangleIndex();
if (nodeSubPart != curNodeSubPart)
{
if (curNodeSubPart >= 0)
meshInterface->unLockReadOnlyVertexBase(curNodeSubPart);
meshInterface->getLockedReadOnlyVertexIndexBase(&vertexbase,numverts, type,stride,&indexbase,indexstride,numfaces,indicestype,nodeSubPart);
curNodeSubPart = nodeSubPart;
btAssert(indicestype==PHY_INTEGER||indicestype==PHY_SHORT);
}
//triangles->getLockedReadOnlyVertexIndexBase(vertexBase,numVerts,
unsigned int* gfxbase = (unsigned int*)(indexbase+nodeTriangleIndex*indexstride);
for (int j=2;j>=0;j--)
{
int graphicsindex = indicestype==PHY_SHORT?((unsigned short*)gfxbase)[j]:gfxbase[j];
if (type == PHY_FLOAT)
{
float* graphicsbase = (float*)(vertexbase+graphicsindex*stride);
triangleVerts[j] = btVector3(
graphicsbase[0]*meshScaling.getX(),
graphicsbase[1]*meshScaling.getY(),
graphicsbase[2]*meshScaling.getZ());
}
else
{
double* graphicsbase = (double*)(vertexbase+graphicsindex*stride);
triangleVerts[j] = btVector3( btScalar(graphicsbase[0]*meshScaling.getX()), btScalar(graphicsbase[1]*meshScaling.getY()), btScalar(graphicsbase[2]*meshScaling.getZ()));
}
}
aabbMin.setValue(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
aabbMax.setValue(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));
aabbMin.setMin(triangleVerts[0]);
aabbMax.setMax(triangleVerts[0]);
aabbMin.setMin(triangleVerts[1]);
aabbMax.setMax(triangleVerts[1]);
aabbMin.setMin(triangleVerts[2]);
aabbMax.setMax(triangleVerts[2]);
quantize(&curNode.m_quantizedAabbMin[0],aabbMin,0);
quantize(&curNode.m_quantizedAabbMax[0],aabbMax,1);
} else
{
//combine aabb from both children
btQuantizedBvhNode* leftChildNode = &m_quantizedContiguousNodes[i+1];
btQuantizedBvhNode* rightChildNode = leftChildNode->isLeafNode() ? &m_quantizedContiguousNodes[i+2] :
&m_quantizedContiguousNodes[i+1+leftChildNode->getEscapeIndex()];
{
for (int i=0;i<3;i++)
{
curNode.m_quantizedAabbMin[i] = leftChildNode->m_quantizedAabbMin[i];
if (curNode.m_quantizedAabbMin[i]>rightChildNode->m_quantizedAabbMin[i])
curNode.m_quantizedAabbMin[i]=rightChildNode->m_quantizedAabbMin[i];
curNode.m_quantizedAabbMax[i] = leftChildNode->m_quantizedAabbMax[i];
if (curNode.m_quantizedAabbMax[i] < rightChildNode->m_quantizedAabbMax[i])
curNode.m_quantizedAabbMax[i] = rightChildNode->m_quantizedAabbMax[i];
}
}
}
}
if (curNodeSubPart >= 0)
meshInterface->unLockReadOnlyVertexBase(curNodeSubPart);
}
///deSerializeInPlace loads and initializes a BVH from a buffer in memory 'in place'
btOptimizedBvh* btOptimizedBvh::deSerializeInPlace(void *i_alignedDataBuffer, unsigned int i_dataBufferSize, bool i_swapEndian)
{
btQuantizedBvh* bvh = btQuantizedBvh::deSerializeInPlace(i_alignedDataBuffer,i_dataBufferSize,i_swapEndian);
//we don't add additional data so just do a static upcast
return static_cast<btOptimizedBvh*>(bvh);
}
| 411 | 0.958778 | 1 | 0.958778 | game-dev | MEDIA | 0.882283 | game-dev | 0.992742 | 1 | 0.992742 |
FalconClient/FalconClient | 2,441 | src/main/java/net/minecraft/world/chunk/storage/RegionFileCache.java | package net.minecraft.world.chunk.storage;
import com.google.common.collect.Maps;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public class RegionFileCache
{
private static final Map<File, RegionFile> regionsByFilename = Maps.<File, RegionFile>newHashMap();
public static synchronized RegionFile createOrLoadRegionFile(File worldDir, int chunkX, int chunkZ)
{
File file1 = new File(worldDir, "region");
File file2 = new File(file1, "r." + (chunkX >> 5) + "." + (chunkZ >> 5) + ".mca");
RegionFile regionfile = (RegionFile)regionsByFilename.get(file2);
if (regionfile != null)
{
return regionfile;
}
else
{
if (!file1.exists())
{
file1.mkdirs();
}
if (regionsByFilename.size() >= 256)
{
clearRegionFileReferences();
}
RegionFile regionfile1 = new RegionFile(file2);
regionsByFilename.put(file2, regionfile1);
return regionfile1;
}
}
/**
* clears region file references
*/
public static synchronized void clearRegionFileReferences()
{
for (RegionFile regionfile : regionsByFilename.values())
{
try
{
if (regionfile != null)
{
regionfile.close();
}
}
catch (IOException ioexception)
{
ioexception.printStackTrace();
}
}
regionsByFilename.clear();
}
/**
* Returns an input stream for the specified chunk. Args: worldDir, chunkX, chunkZ
*/
public static DataInputStream getChunkInputStream(File worldDir, int chunkX, int chunkZ)
{
RegionFile regionfile = createOrLoadRegionFile(worldDir, chunkX, chunkZ);
return regionfile.getChunkDataInputStream(chunkX & 31, chunkZ & 31);
}
/**
* Returns an output stream for the specified chunk. Args: worldDir, chunkX, chunkZ
*/
public static DataOutputStream getChunkOutputStream(File worldDir, int chunkX, int chunkZ)
{
RegionFile regionfile = createOrLoadRegionFile(worldDir, chunkX, chunkZ);
return regionfile.getChunkDataOutputStream(chunkX & 31, chunkZ & 31);
}
}
| 411 | 0.681856 | 1 | 0.681856 | game-dev | MEDIA | 0.781847 | game-dev | 0.71443 | 1 | 0.71443 |
wolfetplayer/RealRTCW | 2,891 | sdk/rtcw-bspc-custom/src/unix/Conscript-game | # game
Import qw( BASE_CFLAGS CONFIG_DIR BUILD_DIR BASEGAME CC CXX LINK );
$env = new cons(
CC => $CC,
CXX => $CXX,
LINK => $LINK,
CPPPATH => '#../game:#../botai',
# NOTE TTimo what about the GAMEDLL define? where is it needed?
CFLAGS => $BASE_CFLAGS . '-fPIC -DGAMEDLL',
LDFLAGS => '-shared -ldl -lm'
);
@FILES = qw(
../game/ai_cast.c
../game/ai_cast_characters.c
../game/ai_cast_debug.c
../game/ai_cast_events.c
../game/ai_cast_fight.c
../game/ai_cast_func_attack.c
../game/ai_cast_func_boss1.c
../game/ai_cast_funcs.c
../game/ai_cast_script.c
../game/ai_cast_script_actions.c
../game/ai_cast_script_ents.c
../game/ai_cast_sight.c
../game/ai_cast_think.c
../botai/ai_chat.c
../botai/ai_cmd.c
../botai/ai_dmnet.c
../botai/ai_dmq3.c
../botai/ai_main.c
../botai/ai_team.c
../game/bg_animation.c
../game/bg_misc.c
../game/bg_pmove.c
../game/bg_slidemove.c
../game/g_active.c
../game/g_alarm.c
../game/g_bot.c
../game/g_client.c
../game/g_cmds.c
../game/g_combat.c
../game/g_items.c
../game/g_main.c
../game/g_mem.c
../game/g_misc.c
../game/g_missile.c
../game/g_mover.c
../game/g_props.c
../game/g_save.c
../game/g_script.c
../game/g_script_actions.c
../game/g_session.c
../game/g_spawn.c
../game/g_svcmds.c
../game/g_syscalls.c
../game/g_target.c
../game/g_team.c
../game/g_tramcar.c
../game/g_trigger.c
../game/g_utils.c
../game/g_weapon.c
../game/q_math.c
../game/q_shared.c
);
$FILESREF = \@FILES;
# build a list of the *.c files in game/ for generation and dependencies
# we exclude g_save of course
$game_files_string = `ls -1 ../game/*.c | grep -v g_save`;
@GAMES = split "\n", $game_files_string;
$GAMESREF = \@GAMES;
# process into a friendly string for extractfunc
$GAMES_STRING = "";
$LDIR = `pwd`;
chop $LDIR;
$LDIR .= '/../game';
for($i=0; $i<scalar(@GAMES); $i++)
{
my $tmp = $GAMES[$i];
$tmp =~ s/\.\.\/game\/(.*)/\1/;
$GAMES_STRING .= "$tmp ";
}
# explicit perl code to generate the func headers
# run extractfuncs with straight .c filenames, output to the right place
sub build_funcs {
print "Building functions table\n";
system("LDIR=`pwd`; cd ../game; echo \"in `pwd`\"; \$LDIR/extractfuncs -o \$LDIR/$BUILD_DIR/game/g_funcs.h \$LDIR/$BUILD_DIR/game/g_func_decs.h $GAMES_STRING");
return 1;
}
# explicit dependency of those headers
Depends $env ['../game/g_funcs.h', '../game/g_func_decs.h'], @$GAMESREF;
Depends $env ['../game/g_funcs.h', '../game/g_func_decs.h'], '#extractfuncs';
# generation command
Command $env ['../game/g_funcs.h', '../game/g_func_decs.h'], "[perl] &build_funcs()";
# FIXME CPU string
# FIXME wolfgamei386.so ?
# TODO use an ldd -r after .so build to catch unresolved symbols? (PostBuild command)
Program $env 'qagamei386.so', @$FILESREF;
Install $env '#' . $CONFIG_DIR . '/out/' . $BASEGAME, 'qagamei386.so';
| 411 | 0.772347 | 1 | 0.772347 | game-dev | MEDIA | 0.905429 | game-dev | 0.521035 | 1 | 0.521035 |
PentestSS13/Pentest | 11,179 | modular_pentest/modules/cult/code/cult_structures.dm | /obj/structure/destructible/cult
density = TRUE
anchored = TRUE
icon = 'icons/obj/cult.dmi'
light_power = 2
var/cooldowntime = 0
break_sound = 'sound/hallucinations/veryfar_noise.ogg'
debris = list(/obj/item/stack/sheet/mineral/hidden/hellstone = 1)
/obj/structure/destructible/cult/proc/conceal() //for spells that hide cult presence
density = FALSE
visible_message(span_danger("[src] fades away."))
invisibility = INVISIBILITY_OBSERVER
alpha = 100 //To help ghosts distinguish hidden runes
light_range = 0
light_power = 0
update_light()
STOP_PROCESSING(SSfastprocess, src)
/obj/structure/destructible/cult/proc/reveal() //for spells that reveal cult presence
density = initial(density)
invisibility = 0
visible_message(span_danger("[src] suddenly appears!"))
alpha = initial(alpha)
light_range = initial(light_range)
light_power = initial(light_power)
update_light()
START_PROCESSING(SSfastprocess, src)
/obj/structure/destructible/cult/examine(mob/user)
. = ..()
. += span_notice("\The [src] is [anchored ? "":"not "]secured to the floor.")
if((iscultist(user) || isobserver(user)) && cooldowntime > world.time)
. += span_cultitalic("The magic in [src] is too weak, [p_they()] will be ready to use again in [DisplayTimeText(cooldowntime - world.time)].")
/obj/structure/destructible/cult/examine_status(mob/user)
if(iscultist(user) || isobserver(user))
var/t_It = p_they(TRUE)
var/t_is = p_are()
return span_cult("[t_It] [t_is] at <b>[round(obj_integrity * 100 / max_integrity)]%</b> stability.")
return ..()
/obj/structure/destructible/cult/attack_animal(mob/living/simple_animal/M)
if(istype(M, /mob/living/simple_animal/hostile/construct/artificer))
if(obj_integrity < max_integrity)
M.changeNext_move(CLICK_CD_MELEE)
obj_integrity = min(max_integrity, obj_integrity + 5)
Beam(M, icon_state="sendbeam", time=4)
M.visible_message(span_danger("[M] repairs \the <b>[src]</b>."), \
span_cult("You repair <b>[src]</b>, leaving [p_they()] at <b>[round(obj_integrity * 100 / max_integrity)]%</b> stability."))
else
to_chat(M, span_cult("You cannot repair [src], as [p_theyre()] undamaged!"))
else
..()
/obj/structure/destructible/cult/set_anchored(anchorvalue)
. = ..()
if(isnull(.))
return
update_appearance()
/obj/structure/destructible/cult/update_icon_state()
icon_state = "[initial(icon_state)][anchored ? null : "_off"]"
return ..()
/obj/structure/destructible/cult/attackby(obj/I, mob/user, params)
if(istype(I, /obj/item/melee/cultblade/dagger) && iscultist(user))
set_anchored(!anchored)
to_chat(user, span_notice("You [anchored ? "":"un"]secure \the [src] [anchored ? "to":"from"] the floor."))
else
return ..()
/obj/structure/destructible/cult/proc/check_menu(mob/user)
if(!istype(user))
return FALSE
if(user.incapacitated() || !user.Adjacent(src))
return FALSE
return TRUE
/obj/structure/destructible/cult/talisman
name = "altar"
desc = "A bloodstained altar dedicated to Nar'Sie."
icon_state = "talismanaltar"
break_message = span_warning("The altar shatters, leaving only the wailing of the damned!")
/obj/structure/destructible/cult/talisman/attack_hand(mob/living/user)
. = ..()
if(.)
return
if(!iscultist(user))
to_chat(user, span_warning("You're pretty sure you know exactly what this is used for and you can't seem to touch it."))
return
if(!anchored)
to_chat(user, span_cultitalic("You need to anchor [src] to the floor with your dagger first."))
return
if(cooldowntime > world.time)
to_chat(user, span_cultitalic("The magic in [src] is weak, it will be ready to use again in [DisplayTimeText(cooldowntime - world.time)]."))
return
var/list/items = list(
"Eldritch Whetstone" = image(icon = 'icons/obj/kitchen.dmi', icon_state = "cult_sharpener"),
"Construct Shell" = image(icon = 'icons/obj/wizard.dmi', icon_state = "construct_cult"),
"Flask of Unholy Water" = image(icon = 'icons/obj/drinks/drinks.dmi', icon_state = "holyflask")
)
var/choice = show_radial_menu(user, src, items, custom_check = CALLBACK(src, PROC_REF(check_menu), user), require_near = TRUE, tooltips = TRUE)
var/list/pickedtype = list()
switch(choice)
if("Eldritch Whetstone")
pickedtype += /obj/item/sharpener/cult
if("Construct Shell")
pickedtype += /obj/structure/constructshell
if("Flask of Unholy Water")
pickedtype += /obj/item/reagent_containers/glass/beaker/unholywater
else
return
if(src && !QDELETED(src) && anchored && pickedtype && Adjacent(user) && !user.incapacitated() && iscultist(user) && cooldowntime <= world.time)
cooldowntime = world.time + 2400
for(var/N in pickedtype)
new N(get_turf(src))
to_chat(user, span_cultitalic("You kneel before the altar and your faith is rewarded with the [choice]!"))
/obj/structure/destructible/cult/forge
name = "daemon forge"
desc = "A forge used in crafting the unholy weapons used by the armies of Nar'Sie."
icon_state = "forge"
light_range = 2
light_color = LIGHT_COLOR_LAVA
break_message = span_warning("The force breaks apart into shards with a howling scream!")
/obj/structure/destructible/cult/forge/attack_hand(mob/living/user)
. = ..()
if(.)
return
if(!iscultist(user))
to_chat(user, span_warning("The heat radiating from [src] pushes you back."))
return
if(!anchored)
to_chat(user, span_cultitalic("You need to anchor [src] to the floor with your dagger first."))
return
if(cooldowntime > world.time)
to_chat(user, span_cultitalic("The magic in [src] is weak, it will be ready to use again in [DisplayTimeText(cooldowntime - world.time)]."))
return
var/list/items = list(
"Shielded Robe" = image(icon = 'icons/obj/clothing/suits.dmi', icon_state = "cult_armor"),
"Flagellant's Robe" = image(icon = 'icons/obj/clothing/suits.dmi', icon_state = "cultrobes"),
"Mirror Shield" = image(icon = 'icons/obj/shields.dmi', icon_state = "mirror_shield")
)
var/choice = show_radial_menu(user, src, items, custom_check = CALLBACK(src, PROC_REF(check_menu), user), require_near = TRUE, tooltips = TRUE)
var/list/pickedtype = list()
switch(choice)
if("Shielded Robe")
pickedtype += /obj/item/clothing/suit/hooded/cultrobes/cult_shield
if("Flagellant's Robe")
pickedtype += /obj/item/clothing/suit/hooded/cultrobes/berserker
if("Mirror Shield")
pickedtype += /obj/item/shield/mirror
else
return
if(src && !QDELETED(src) && anchored && pickedtype && Adjacent(user) && !user.incapacitated() && iscultist(user) && cooldowntime <= world.time)
cooldowntime = world.time + 2400
for(var/N in pickedtype)
new N(get_turf(src))
to_chat(user, span_cultitalic("You work the forge as dark knowledge guides your hands, creating the [choice]!"))
/obj/structure/destructible/cult/pylon
name = "pylon"
desc = "A floating crystal that slowly heals those faithful to Nar'Sie."
icon_state = "pylon"
light_range = 1.5
light_color = COLOR_SOFT_RED
break_sound = 'sound/effects/glassbr2.ogg'
break_message = span_warning("The blood-red crystal falls to the floor and shatters!")
var/heal_delay = 25
var/last_heal = 0
var/corrupt_delay = 50
var/last_corrupt = 0
/obj/structure/destructible/cult/pylon/New()
START_PROCESSING(SSfastprocess, src)
..()
/obj/structure/destructible/cult/pylon/Destroy()
STOP_PROCESSING(SSfastprocess, src)
return ..()
/obj/structure/destructible/cult/pylon/process()
if(!anchored)
return
if(last_heal <= world.time)
last_heal = world.time + heal_delay
for(var/mob/living/L in range(5, src))
if(iscultist(L) || isshade(L) || isconstruct(L))
if(L.health != L.maxHealth)
new /obj/effect/temp_visual/heal(get_turf(src), "#960000")
if(ishuman(L))
L.adjustBruteLoss(-1, 0)
L.adjustFireLoss(-1, 0)
L.updatehealth()
if(isshade(L) || isconstruct(L))
var/mob/living/simple_animal/M = L
if(M.health < M.maxHealth)
M.adjustHealth(-3)
if(ishuman(L) && L.blood_volume < BLOOD_VOLUME_NORMAL)
L.blood_volume += 1.0
CHECK_TICK
if(last_corrupt <= world.time)
var/list/validturfs = list()
var/list/cultturfs = list()
for(var/T in circleviewturfs(src, 5))
if(istype(T, /turf/open/floor/engine/cult))
cultturfs |= T
continue
var/static/list/blacklisted_pylon_turfs = typecacheof(list(
/turf/closed,
/turf/open/floor/engine/cult,
/turf/open/space,
/turf/open/lava,
/turf/open/chasm))
if(is_type_in_typecache(T, blacklisted_pylon_turfs))
continue
else
validturfs |= T
last_corrupt = world.time + corrupt_delay
if(length(validturfs))
var/turf/T = pick(validturfs)
if(istype(T, /turf/open/floor/plating))
T.PlaceOnTop(/turf/open/floor/engine/cult, flags = CHANGETURF_INHERIT_AIR)
else
T.ChangeTurf(/turf/open/floor/engine/cult, flags = CHANGETURF_INHERIT_AIR)
else if (length(cultturfs))
var/turf/open/floor/engine/cult/F = pick(cultturfs)
new /obj/effect/temp_visual/cult/turf/floor(F)
else
// Are we in space or something? No cult turfs or
// convertable turfs?
last_corrupt = world.time + corrupt_delay*2
/obj/structure/destructible/cult/tome
name = "archives"
desc = "A desk covered in arcane manuscripts and tomes in unknown languages. Looking at the text makes your skin crawl."
icon_state = "tomealtar"
light_range = 1.5
light_color = LIGHT_COLOR_FIRE
break_message = span_warning("The books and tomes of the archives burn into ash as the desk shatters!")
/obj/structure/destructible/cult/tome/attack_hand(mob/living/user)
. = ..()
if(.)
return
if(!iscultist(user))
to_chat(user, span_warning("These books won't open and it hurts to even try and read the covers."))
return
if(!anchored)
to_chat(user, span_cultitalic("You need to anchor [src] to the floor with your dagger first."))
return
if(cooldowntime > world.time)
to_chat(user, span_cultitalic("The magic in [src] is weak, it will be ready to use again in [DisplayTimeText(cooldowntime - world.time)]."))
return
var/list/items = list(
"Zealot's Blindfold" = image(icon = icon = 'icons/obj/clothing/eyes/eyes.dmi', icon_state = "blindfold"),
"Veil Walker Set" = image(icon = 'icons/obj/cult.dmi', icon_state = "shifter")
)
var/choice = show_radial_menu(user, src, items, custom_check = CALLBACK(src, PROC_REF(check_menu), user), require_near = TRUE, tooltips = TRUE)
var/list/pickedtype = list()
switch(choice)
if("Zealot's Blindfold")
pickedtype += /obj/item/clothing/glasses/hud/health/night/cultblind
if("Veil Walker Set")
pickedtype += /obj/item/cult_shift
pickedtype += /obj/item/flashlight/flare/culttorch
else
return
if(src && !QDELETED(src) && anchored && pickedtype.len && Adjacent(user) && !user.incapacitated() && iscultist(user) && cooldowntime <= world.time)
cooldowntime = world.time + 2400
for(var/N in pickedtype)
new N(get_turf(src))
to_chat(user, span_cultitalic("You summon the [choice] from the archives!"))
/obj/effect/gateway
name = "gateway"
desc = "You're pretty sure that abyss is staring back."
icon = 'icons/obj/cult.dmi'
icon_state = "hole"
density = TRUE
anchored = TRUE
/obj/effect/gateway/singularity_act()
return
/obj/effect/gateway/singularity_pull()
return
| 411 | 0.962656 | 1 | 0.962656 | game-dev | MEDIA | 0.972995 | game-dev | 0.929602 | 1 | 0.929602 |
trapexit/3do-star-control-2 | 5,701 | starcon2/restart.c | #include "starcon.h"
enum
{
START_NEW_GAME = 0,
LOAD_SAVED_GAME,
PLAY_SUPER_MELEE
};
PROC(STATIC
void near DrawRestartMenu, (OldState, NewState, f),
ARG (BYTE OldState)
ARG (BYTE NewState)
ARG_END (FRAME f)
)
{
RECT r;
SetSemaphore (&GraphicsSem);
SetContext (ScreenContext);
r.corner.x = r.corner.y = r.extent.width = r.extent.height = 0;
SetContextClipRect (&r);
r.corner.x = 0;
r.corner.y = 0;
r.extent.width = SCREEN_WIDTH;
r.extent.height = SCREEN_HEIGHT;
SetFlashRect (&r, SetAbsFrameIndex (f, NewState + 1));
ClearSemaphore (&GraphicsSem);
}
DWORD InTime;
PROC(
STATIC BOOLEAN DoRestart, (InputState, pMS),
ARG (INPUT_STATE InputState)
ARG_END (PMENU_STATE pMS)
)
{
if (!pMS->Initialized)
{
DrawRestartMenu ((BYTE)~0, pMS->CurState, pMS->CurFrame);
pMS->Initialized = TRUE;
{
BYTE clut_buf[] = {FadeAllToColor};
SleepTask (XFormColorMap ((COLORMAPPTR)clut_buf, ONE_SECOND / 2));
}
}
#ifdef TESTING
else if (InputState & DEVICE_EXIT) return (FALSE);
#endif /* TESTING */
else if (InputState == 0)
{
if (GetTimeCounter () - InTime < ONE_SECOND * 15)
return (TRUE);
GLOBAL (CurrentActivity) = (ACTIVITY)~0;
return (FALSE);
}
else if (InputState & DEVICE_BUTTON1)
{
switch (pMS->CurState)
{
case LOAD_SAVED_GAME:
LastActivity = CHECK_LOAD;
GLOBAL (CurrentActivity) = IN_INTERPLANETARY;
break;
case START_NEW_GAME:
LastActivity = CHECK_LOAD | CHECK_RESTART;
GLOBAL (CurrentActivity) = IN_INTERPLANETARY;
break;
case PLAY_SUPER_MELEE:
GLOBAL (CurrentActivity) = SUPER_MELEE;
break;
}
SetSemaphore (&GraphicsSem);
SetFlashRect (NULL_PTR, (FRAME)0);
ClearSemaphore (&GraphicsSem);
return (FALSE);
}
else
{
BYTE NewState;
NewState = pMS->CurState;
if (GetInputXComponent (InputState) < 0
|| GetInputYComponent (InputState) < 0)
{
if (NewState-- == START_NEW_GAME)
NewState = PLAY_SUPER_MELEE;
}
else if (GetInputXComponent (InputState) > 0
|| GetInputYComponent (InputState) > 0)
{
if (NewState++ == PLAY_SUPER_MELEE)
NewState = START_NEW_GAME;
}
if (NewState != pMS->CurState)
{
DrawRestartMenu (pMS->CurState, NewState, pMS->CurFrame);
pMS->CurState = NewState;
}
}
InTime = GetTimeCounter ();
return (TRUE);
}
PROC(
BOOLEAN StartGame, (),
ARG_VOID
)
{
MENU_STATE MenuState;
TimedOut:
LastActivity = GLOBAL (CurrentActivity);
GLOBAL (CurrentActivity) = 0;
if (LastActivity == (ACTIVITY)~0)
Introduction ();
MEMSET ((PMENU_STATE)&MenuState, 0, sizeof (MenuState));
MenuState.InputFunc = DoRestart;
{
DWORD TimeOut;
BYTE black_buf[1];
extern ACTIVITY NextActivity;
TryAgain:
ReinitQueue (&race_q[0]);
ReinitQueue (&race_q[1]);
black_buf[0] = FadeAllToBlack;
SetContext (ScreenContext);
SetContextBGFrame ((FRAME)0);
SetContextDrawState (DEST_PIXMAP | DRAW_REPLACE);
GLOBAL (CurrentActivity) |= CHECK_ABORT;
if (GLOBAL_SIS (CrewEnlisted) == (COUNT)~0
&& GET_GAME_STATE (UTWIG_BOMB_ON_SHIP)
&& !GET_GAME_STATE (UTWIG_BOMB))
{
BYTE white_buf[] = {FadeAllToWhite};
SET_GAME_STATE (UTWIG_BOMB_ON_SHIP, 0);
SleepTask (XFormColorMap ((COLORMAPPTR)white_buf, ONE_SECOND / 8) + 2);
SetContextBackGroundColor (BUILD_COLOR (MAKE_RGB15 (0x1F, 0x1F, 0x1F), 0x0F));
ClearDrawable ();
FlushColorXForms ();
TimeOut = ONE_SECOND / 8;
}
else
{
TimeOut = ONE_SECOND / 2;
#ifdef NOTYET
LastActivity = WON_LAST_BATTLE;
#endif /* NOTYET */
if (LOBYTE (LastActivity) == WON_LAST_BATTLE)
{
Victory ();
Credits ();
TimeOut = ONE_SECOND / 2;
}
}
LastActivity = NextActivity = 0;
{
RECT r;
STAMP s;
s.frame = CaptureDrawable (
LoadGraphic (RESTART_PMAP_ANIM)
);
MenuState.CurFrame = s.frame;
GetFrameRect (s.frame, &r);
s.origin.x = (SCREEN_WIDTH - r.extent.width) >> 1;
s.origin.y = (SCREEN_HEIGHT - r.extent.height) >> 1;
SleepTask (XFormColorMap ((COLORMAPPTR)black_buf, TimeOut));
if (TimeOut == ONE_SECOND / 8)
SleepTask (GetTimeCounter () + ONE_SECOND * 3);
SetContextBackGroundColor (BLACK_COLOR);
ClearDrawable ();
FlushColorXForms ();
DrawStamp (&s);
FlushInput ();
DoInput ((PVOID)&MenuState);
SetSemaphore (&GraphicsSem);
SetFlashRect ((PRECT)0, (FRAME)0);
ClearSemaphore (&GraphicsSem);
DestroyDrawable (ReleaseDrawable (s.frame));
if (GLOBAL (CurrentActivity) == (ACTIVITY)~0)
goto TimedOut;
#ifdef TESTING
if (GLOBAL (CurrentActivity) & CHECK_ABORT)
{
while (SoundPlaying ());
StopSound ();
FreeSC2Data ();
FreeLanderData ();
FreeIPData ();
FreeHyperData ();
FlushColorXForms ();
return (FALSE);
}
#endif /* TESTING */
TimeOut = XFormColorMap ((COLORMAPPTR)black_buf, ONE_SECOND / 2);
}
SleepTask (TimeOut);
FlushColorXForms ();
SeedRandomNumbers ();
if (LOBYTE (GLOBAL (CurrentActivity)) == SUPER_MELEE)
{
FreeSC2Data ();
FreeLanderData ();
FreeIPData ();
FreeHyperData ();
Melee ();
MenuState.Initialized = FALSE;
goto TryAgain;
}
{
extern STAR_DESC starmap_array[];
extern PSTR cluster_array[];
extern CONST BYTE element_array[];
extern CONST PlanetFrame planet_array[];
extern PSTR *ClusterNames;
star_array = starmap_array;
ClusterNames = cluster_array;
Elements = element_array;
PlanData = planet_array;
}
PlayerControl[0] = HUMAN_CONTROL | STANDARD_RATING | JOYSTICK_CONTROL;
PlayerControl[1] = COMPUTER_CONTROL | JOYSTICK_CONTROL | AWESOME_RATING;
SetPlayerInput ();
return (TRUE);
}
return (FALSE);
}
| 411 | 0.904892 | 1 | 0.904892 | game-dev | MEDIA | 0.722718 | game-dev | 0.983861 | 1 | 0.983861 |
refinedmods/refinedstorage2 | 2,112 | refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/slotreference/CompositeSlotReferenceProvider.java | package com.refinedmods.refinedstorage.common.support.slotreference;
import com.refinedmods.refinedstorage.common.api.support.slotreference.SlotReference;
import com.refinedmods.refinedstorage.common.api.support.slotreference.SlotReferenceProvider;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import net.minecraft.ChatFormatting;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import static com.refinedmods.refinedstorage.common.util.IdentifierUtil.createTranslation;
public class CompositeSlotReferenceProvider implements SlotReferenceProvider {
private final List<SlotReferenceProvider> providers = new ArrayList<>(List.of(
new InventorySlotReferenceProvider()
));
public void addProvider(final SlotReferenceProvider provider) {
providers.add(provider);
}
@Override
public List<SlotReference> find(final Player player, final Set<Item> validItems) {
return providers.stream().flatMap(p -> p.find(player, validItems).stream()).toList();
}
public Optional<SlotReference> findForUse(final Player player,
final Item referenceItem,
final Set<Item> validItems) {
final List<SlotReference> foundReferences = find(player, validItems);
if (foundReferences.size() > 1) {
player.sendSystemMessage(createTranslation(
"item",
"network_item.cannot_open_with_shortcut_due_to_duplicate",
referenceItem.getDescription()
).withStyle(ChatFormatting.RED));
return Optional.empty();
}
if (foundReferences.isEmpty()) {
player.sendSystemMessage(createTranslation(
"item",
"network_item.cannot_open_because_not_found",
referenceItem.getDescription()
).withStyle(ChatFormatting.RED));
return Optional.empty();
}
return Optional.of(foundReferences.getFirst());
}
}
| 411 | 0.898173 | 1 | 0.898173 | game-dev | MEDIA | 0.819127 | game-dev | 0.975524 | 1 | 0.975524 |
DeanRoddey/CQC | 5,695 | Source/AllProjects/CQCAppShell/NS/CQCNSShell_ThisFacility.cpp | //
// FILE NAME: CQCNSShell_ThisFacility.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 07/30/2001
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "CQCNSShell.hpp"
// ---------------------------------------------------------------------------
// Magic macros
// ---------------------------------------------------------------------------
RTTIDecls(TFacCQCNSShell,TFacility)
// ---------------------------------------------------------------------------
// CLASS: TFacCQCNSShell
// PREFIX: fac
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TFacCQCNSShell: Constructors and Destructor
// ---------------------------------------------------------------------------
//
// Note that we use the same version constants as the toolkit facility. Since
// they must be used together, this makes sense.
//
TFacCQCNSShell::TFacCQCNSShell() :
TFacility
(
L"CQCNSShell"
, tCIDLib::EModTypes::Exe
, kCQCKit::c4MajVersion
, kCQCKit::c4MinVersion
, kCQCKit::c4Revision
, tCIDLib::EModFlags::None
)
, m_evShutdown(tCIDLib::EEventStates::Reset)
{
}
TFacCQCNSShell::~TFacCQCNSShell()
{
}
// ---------------------------------------------------------------------------
// TFacCQCNSShell: Public, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean TFacCQCNSShell::bHandleSignal(const tCIDLib::ESignals)
{
// Trigger our shutdown event to cause the main thread to exit
m_evShutdown.Trigger();
return kCIDLib::True;
}
tCIDLib::TBoolean
TFacCQCNSShell::bQueryNewMsgs( tCIDLib::TCard4& c4MsgIndex
, TVector<TString>& colMsgs
, const tCIDLib::TBoolean bAddNewLine)
{
// Just delegate to the engine
return facCQCAppShellLib().bQueryNewMsgs(c4MsgIndex, colMsgs, bAddNewLine);
}
tCIDLib::TCard4 TFacCQCNSShell::c4QueryApps(tCIDLib::TKVPList& colApps)
{
// Just delegate to the app engine
return facCQCAppShellLib().c4QueryApps(colApps);
}
tCIDLib::TVoid TFacCQCNSShell::CycleApps()
{
// Just delegate to the app shell engine
facCQCAppShellLib().CycleApps();
}
tCIDLib::EExitCodes
TFacCQCNSShell::eMainThread(TThread& thrThis, tCIDLib::TVoid*)
{
// Let our caller go
thrThis.Sync();
// Get the first parm. If not 'Booble', then just exit
const tCIDLib::TCard4 c4ParmCnt = TSysInfo::c4CmdLineParmCount();
if ((c4ParmCnt < 1) || (c4ParmCnt > 2))
return tCIDLib::EExitCodes::Normal;
TString strParm = TSysInfo::strCmdLineParmAt(0);
if (strParm != L"Booble")
return tCIDLib::EExitCodes::Normal;
// Register ourself as a signal handler
TSignals::c4AddHandler(this);
// Show our blurb to the console
ShowBlurb();
//
// Set the environment variable that the stack dump program
// uses to create dump files, so that we insure that they get
// into the right spot. So get our target path, remove the Bin
// part, then add on the logs directory.
//
TPathStr pathDumpDir = strPath();
pathDumpDir.bRemoveLevel();
pathDumpDir.AddLevel(L"\\CQCData\\Logs");
TProcEnvironment::bAddOrUpdate(kCIDLib::pszErrDumpDir, pathDumpDir);
//
// Initialize the engine. Generally we'd point it at the same directory
// as what we are running in, but for debug purposes, we allow it to be
// set on the command line as a second parameter. If not there, then we
// use our directory.
//
TString strFilePath;
if (c4ParmCnt == 2)
strFilePath = TSysInfo::strCmdLineParmAt(1);
else
strFilePath = strPath();
m_conOut << L"Initilizing app shell\n Path="
<< strFilePath
<< kCIDLib::EndLn;
facCQCAppShellLib().Initialize(strFilePath);
// And now block forever until asked to stop
m_evShutdown.WaitFor();
// Ask the engine to stop
m_conOut << L"Stopping app shell" << kCIDLib::EndLn;
facCQCAppShellLib().StopEngine();
return tCIDLib::EExitCodes::Normal;
}
tCIDLib::TVoid TFacCQCNSShell::StartAllApps()
{
// Tell the engine to activate all the apps
m_conOut << L"Starting up all apps" << kCIDLib::EndLn;
facCQCAppShellLib().StartAllApps();
}
tCIDLib::TVoid TFacCQCNSShell::StopAllApps()
{
// Tell the engine to stop all the apps
m_conOut << L"Stopping all apps" << kCIDLib::EndLn;
facCQCAppShellLib().StopAllApps();
}
// ---------------------------------------------------------------------------
// TFacCQCNSShell: Private, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid TFacCQCNSShell::ShowBlurb()
{
// Show the general blurb line, and a version
m_conOut << facCQCAppShellLib().strMsg(kCQCShMsgs::midGen_Blurb)
<< facCQCAppShellLib().strMsg(kCQCShMsgs::midGen_Version)
<< strVersion()
<< kCIDLib::NewLn
<< facCQCAppShellLib().strMsg(kCQCShMsgs::midGen_StopInfo)
<< kCIDLib::EndLn;
}
| 411 | 0.921359 | 1 | 0.921359 | game-dev | MEDIA | 0.270765 | game-dev | 0.748478 | 1 | 0.748478 |
wasm-bindgen/wasm-bindgen | 10,326 | crates/web-sys/webidls/enabled/IDB.webidl | // https://www.w3.org/TR/IndexedDB-2/
[Exposed=(Window,Worker)]
interface IDBRequest : EventTarget {
[Throws]
readonly attribute any result;
[Throws]
readonly attribute DOMException? error;
readonly attribute (IDBObjectStore or IDBIndex or IDBCursor)? source;
readonly attribute IDBTransaction? transaction;
readonly attribute IDBRequestReadyState readyState;
// Event handlers:
attribute EventHandler onsuccess;
attribute EventHandler onerror;
};
enum IDBRequestReadyState {
"pending",
"done"
};
[Exposed=(Window,Worker)]
interface IDBOpenDBRequest : IDBRequest {
// Event handlers:
attribute EventHandler onblocked;
attribute EventHandler onupgradeneeded;
};
[Exposed=(Window,Worker),
Constructor(DOMString type, optional IDBVersionChangeEventInit eventInitDict)]
interface IDBVersionChangeEvent : Event {
readonly attribute unsigned long long oldVersion;
readonly attribute unsigned long long? newVersion;
};
dictionary IDBVersionChangeEventInit : EventInit {
unsigned long long oldVersion = 0;
unsigned long long? newVersion = null;
};
partial interface mixin WindowOrWorkerGlobalScope {
// Breaking change: Should this throw or be optional?
[Throws, SameObject] readonly attribute IDBFactory? indexedDB;
};
[Exposed=(Window,Worker)]
interface IDBFactory {
[Throws, NewObject] IDBOpenDBRequest open(DOMString name,
optional [EnforceRange] unsigned long long version);
[Throws, NewObject] IDBOpenDBRequest deleteDatabase(DOMString name);
[Throws]
short cmp(any first, any second);
};
[Exposed=(Window,Worker)]
interface IDBDatabase : EventTarget {
readonly attribute DOMString name;
readonly attribute unsigned long long version;
readonly attribute DOMStringList objectStoreNames;
[Throws, NewObject] IDBTransaction transaction((DOMString or sequence<DOMString>) storeNames,
optional IDBTransactionMode mode = "readonly");
undefined close();
[Throws, NewObject] IDBObjectStore createObjectStore(DOMString name,
optional IDBObjectStoreParameters options);
[Throws] undefined deleteObjectStore(DOMString name);
// Event handlers:
attribute EventHandler onabort;
attribute EventHandler onclose;
attribute EventHandler onerror;
attribute EventHandler onversionchange;
};
dictionary IDBObjectStoreParameters {
(DOMString or sequence<DOMString>)? keyPath = null;
boolean autoIncrement = false;
};
[Exposed=(Window,Worker)]
interface IDBObjectStore {
[SetterThrows] attribute DOMString name;
[Throws] readonly attribute any keyPath;
readonly attribute DOMStringList indexNames;
[SameObject] readonly attribute IDBTransaction transaction;
readonly attribute boolean autoIncrement;
[Throws, NewObject] IDBRequest put(any value, optional any key);
[Throws, NewObject] IDBRequest add(any value, optional any key);
[Throws, NewObject] IDBRequest delete(any query);
[Throws, NewObject] IDBRequest clear();
[Throws, NewObject] IDBRequest get(any query);
[Throws, NewObject] IDBRequest getKey(any query);
[Throws, NewObject] IDBRequest getAll(optional any query,
optional [EnforceRange] unsigned long count);
[Throws, NewObject] IDBRequest getAllKeys(optional any query,
optional [EnforceRange] unsigned long count);
[Throws, NewObject] IDBRequest count(optional any query);
[Throws, NewObject] IDBRequest openCursor(optional any query,
optional IDBCursorDirection direction = "next");
[Throws, NewObject] IDBRequest openKeyCursor(optional any query,
optional IDBCursorDirection direction = "next");
[Throws] IDBIndex index(DOMString name);
[Throws, NewObject] IDBIndex createIndex(DOMString name,
(DOMString or sequence<DOMString>) keyPath,
optional IDBIndexParameters options);
[Throws] undefined deleteIndex(DOMString name);
};
dictionary IDBIndexParameters {
boolean unique = false;
boolean multiEntry = false;
};
[Exposed=(Window,Worker)]
interface IDBIndex {
[SetterThrows] attribute DOMString name;
[SameObject] readonly attribute IDBObjectStore objectStore;
[Throws] readonly attribute any keyPath;
readonly attribute boolean multiEntry;
readonly attribute boolean unique;
[Throws, NewObject] IDBRequest get(any query);
[Throws, NewObject] IDBRequest getKey(any query);
[Throws, NewObject] IDBRequest getAll(optional any query,
optional [EnforceRange] unsigned long count);
[Throws, NewObject] IDBRequest getAllKeys(optional any query,
optional [EnforceRange] unsigned long count);
[Throws, NewObject] IDBRequest count(optional any query);
[Throws, NewObject] IDBRequest openCursor(optional any query,
optional IDBCursorDirection direction = "next");
[Throws, NewObject] IDBRequest openKeyCursor(optional any query,
optional IDBCursorDirection direction = "next");
};
[Exposed=(Window,Worker)]
interface IDBKeyRange {
[Throws] readonly attribute any lower;
[Throws] readonly attribute any upper;
readonly attribute boolean lowerOpen;
readonly attribute boolean upperOpen;
// Static construction methods:
[Throws, NewObject] static IDBKeyRange only(any value);
[Throws, NewObject] static IDBKeyRange lowerBound(any lower, optional boolean open = false);
[Throws, NewObject] static IDBKeyRange upperBound(any upper, optional boolean open = false);
[Throws, NewObject] static IDBKeyRange bound(any lower,
any upper,
optional boolean lowerOpen = false,
optional boolean upperOpen = false);
[Throws] boolean _includes(any key);
};
[Exposed=(Window,Worker)]
interface IDBCursor {
readonly attribute (IDBObjectStore or IDBIndex) source;
readonly attribute IDBCursorDirection direction;
[Throws] readonly attribute any key;
[Throws] readonly attribute any primaryKey;
[Throws] undefined advance([EnforceRange] unsigned long count);
[Throws] undefined continue(optional any key);
[Throws] undefined continuePrimaryKey(any key, any primaryKey);
[Throws, NewObject] IDBRequest update(any value);
[Throws, NewObject] IDBRequest delete();
};
enum IDBCursorDirection {
"next",
"nextunique",
"prev",
"prevunique"
};
[Exposed=(Window,Worker)]
interface IDBCursorWithValue : IDBCursor {
[Throws] readonly attribute any value;
};
[Exposed=(Window,Worker)]
interface IDBTransaction : EventTarget {
readonly attribute DOMStringList objectStoreNames;
[Throws] readonly attribute IDBTransactionMode mode;
[SameObject] readonly attribute IDBDatabase db;
// TODO: remove optional?
readonly attribute DOMException? error;
[Throws] IDBObjectStore objectStore(DOMString name);
[Throws] undefined abort();
// Event handlers:
attribute EventHandler onabort;
attribute EventHandler oncomplete;
attribute EventHandler onerror;
};
enum IDBTransactionMode {
"readonly",
"readwrite",
"versionchange",
// TODO: deprecated
"readwriteflush",
// TODO: deprecated
"cleanup"
};
/*
** DEPRECATED
*/
partial interface IDBFactory {
[RustDeprecated, Throws, NewObject]
IDBOpenDBRequest open(DOMString name, optional IDBOpenDBOptions options = {});
[RustDeprecated, Throws, NewObject]
IDBOpenDBRequest deleteDatabase(DOMString name, optional IDBOpenDBOptions options = {});
};
partial dictionary IDBIndexParameters {
[RustDeprecated] DOMString? locale = null;
};
partial interface IDBIndex {
[RustDeprecated] readonly attribute DOMString? locale;
[RustDeprecated] readonly attribute boolean isAutoLocale;
};
partial interface IDBCursor {
[RustDeprecated] readonly attribute IDBRequest request;
};
partial interface IDBTransaction {
[RustDeprecated, Throws] undefined commit();
};
partial interface IDBDatabase {
[RustDeprecated] readonly attribute StorageType storage;
[RustDeprecated, Throws] IDBRequest createMutableFile (DOMString name, optional DOMString type);
};
[RustDeprecated] dictionary IDBOpenDBOptions {
[EnforceRange] unsigned long long version;
StorageType storage;
};
[RustDeprecated] dictionary IDBFileMetadataParameters {
boolean size = true;
boolean lastModified = true;
};
[RustDeprecated] interface IDBFileHandle : EventTarget {
readonly attribute IDBMutableFile? mutableFile;
readonly attribute IDBMutableFile? fileHandle;
readonly attribute FileMode mode;
readonly attribute boolean active;
attribute unsigned long long? location;
[Throws]
IDBFileRequest? getMetadata(optional IDBFileMetadataParameters parameters = {});
[Throws]
IDBFileRequest? readAsArrayBuffer(unsigned long long size);
[Throws]
IDBFileRequest? readAsText(unsigned long long size,
optional DOMString? encoding = null);
[Throws]
IDBFileRequest? write((DOMString or ArrayBuffer or ArrayBufferView or Blob) value);
[Throws]
IDBFileRequest? append((DOMString or ArrayBuffer or ArrayBufferView or Blob) value);
[Throws]
IDBFileRequest? truncate(optional unsigned long long size);
[Throws]
IDBFileRequest? flush();
[Throws]
undefined abort();
attribute EventHandler oncomplete;
attribute EventHandler onabort;
attribute EventHandler onerror;
};
[RustDeprecated] interface IDBFileRequest : DOMRequest {
readonly attribute IDBFileHandle? fileHandle;
readonly attribute IDBFileHandle? lockedFile;
attribute EventHandler onprogress;
};
[RustDeprecated] interface IDBLocaleAwareKeyRange : IDBKeyRange {
[Throws]
static IDBLocaleAwareKeyRange bound (any lower, any upper, optional boolean lowerOpen = false, optional boolean upperOpen = false);
};
[RustDeprecated] interface IDBMutableFile : EventTarget {
readonly attribute DOMString name;
readonly attribute DOMString type;
readonly attribute IDBDatabase database;
[Throws] IDBFileHandle open(optional FileMode mode = "readonly");
[Throws] DOMRequest getFile();
attribute EventHandler onabort;
attribute EventHandler onerror;
};
| 411 | 0.899027 | 1 | 0.899027 | game-dev | MEDIA | 0.13727 | game-dev | 0.726375 | 1 | 0.726375 |
neostarfall/neostarfall | 3,468 | lua/entities/starfall_prop/cl_init.lua | include("shared.lua")
ENT.DefaultMaterial = Material("models/wireframe")
ENT.Material = ENT.DefaultMaterial
local Ent_IsValid = FindMetaTable("Entity").IsValid
local Phys_IsValid = FindMetaTable("PhysObj").IsValid
local Ent_GetTable = FindMetaTable("Entity").GetTable
function ENT:Initialize()
self.rendermesh = Mesh(self.Material)
self.rendermeshloaded = false
self:DrawShadow(false)
self:EnableCustomCollisions(true)
local mesh
SF.CallOnRemove(self, "sf_prop", function()
mesh = self.rendermesh
end, function()
if mesh then
mesh:Destroy()
end
end)
end
function ENT:BuildPhysics(mesh)
self:PhysicsInitMultiConvex(mesh)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:EnableCustomCollisions(true)
end
function ENT:Think()
local physobj = self:GetPhysicsObject()
if Phys_IsValid(physobj) then
physobj:SetPos(self:GetPos())
physobj:SetAngles(self:GetAngles())
physobj:EnableMotion(false)
physobj:Sleep()
end
end
function ENT:Draw(flags)
self:DrawModel(flags)
end
function ENT:GetRenderMesh()
local ent_tbl = Ent_GetTable(self)
if ent_tbl.custom_mesh then
if ent_tbl.custom_mesh_data[ent_tbl.custom_mesh] then
return {
Mesh = ent_tbl.custom_mesh,
Material = ent_tbl.Material --[[, Matrix = ent_tbl.render_matrix]],
}
else
ent_tbl.custom_mesh = nil
end
else
return {
Mesh = ent_tbl.rendermesh,
Material = ent_tbl.Material --[[, Matrix = ent_tbl.render_matrix]],
}
end
end
net.Receive("starfall_custom_prop", function()
local self, data
local function applyData()
local ent_tbl = Ent_GetTable(self)
if not (ent_tbl and ent_tbl.rendermesh:IsValid() and data and not ent_tbl.rendermeshloaded) then
return
end
local stream = SF.StringStream(data)
local physmesh = {}
local mins, maxs = Vector(math.huge, math.huge, math.huge), Vector(-math.huge, -math.huge, -math.huge)
for i = 1, stream:readUInt32() do
local convex = {}
for o = 1, stream:readUInt32() do
local x, y, z = stream:readFloat(), stream:readFloat(), stream:readFloat()
if x > maxs.x then
maxs.x = x
end
if y > maxs.y then
maxs.y = y
end
if z > maxs.z then
maxs.z = z
end
if x < mins.x then
mins.x = x
end
if y < mins.y then
mins.y = y
end
if z < mins.z then
mins.z = z
end
convex[o] = Vector(x, y, z)
end
physmesh[i] = convex
end
ent_tbl.sf_physmesh = physmesh
ent_tbl.BuildPhysics(self, physmesh)
local phys = self:GetPhysicsObject()
if Phys_IsValid(phys) then
local convexes = phys:GetMeshConvexes()
local rendermesh = convexes[1]
for i = 2, #convexes do
for k, v in ipairs(convexes[i]) do
rendermesh[#rendermesh + 1] = v
end
end
-- less than 3 can crash
if #rendermesh >= 3 then
ent_tbl.rendermesh:BuildFromTriangles(rendermesh)
end
self:SetRenderBounds(mins, maxs)
self:SetCollisionBounds(mins, maxs)
end
ent_tbl.rendermeshloaded = true
end
net.ReadReliableEntity(function(e)
if e and e:GetClass() == "starfall_prop" then
self = e
applyData()
end
end)
net.ReadStream(nil, function(data_)
if data_ then
data = util.Decompress(data_)
applyData()
end
end)
end)
hook.Add("NetworkEntityCreated", "starfall_prop_physics", function(ent)
local ent_tbl = Ent_GetTable(ent)
local mesh = ent_tbl.sf_physmesh
if mesh and not Phys_IsValid(ent:GetPhysicsObject()) then
ent_tbl.BuildPhysics(ent, mesh)
end
end)
| 411 | 0.76332 | 1 | 0.76332 | game-dev | MEDIA | 0.611881 | game-dev,graphics-rendering | 0.91512 | 1 | 0.91512 |
Fluorohydride/ygopro-scripts | 3,682 | c41443249.lua | --R-ACEプリベンター
local s,id,o=GetID()
function s.initial_effect(c)
--Special Summon (from hand : itself)
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,id)
e1:SetCost(s.sscost)
e1:SetTarget(s.sstg)
e1:SetOperation(s.ssop)
c:RegisterEffect(e1)
--Change position
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_POSITION)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetRange(LOCATION_MZONE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetHintTiming(TIMINGS_CHECK_MONSTER)
e2:SetCountLimit(1,id+o)
e2:SetCondition(s.poscon)
e2:SetTarget(s.postg)
e2:SetOperation(s.posop)
c:RegisterEffect(e2)
--Special Summon (banished)
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(id,2))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetCountLimit(1,id+o+o)
e3:SetTarget(s.sptg)
e3:SetOperation(s.spop)
c:RegisterEffect(e3)
end
function s.costfilter(c)
return c:IsSetCard(0x18b) and c:IsAbleToRemoveAsCost()
end
function s.sscost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.costfilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,s.costfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function s.sstg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function s.ssop(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e) then
Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP)
end
end
function s.confilter(c)
return c:IsFaceup() and c:IsSetCard(0x18b)
end
function s.poscon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(s.confilter,tp,LOCATION_MZONE,0,1,e:GetHandler())
end
function s.posfilter(c)
return c:IsFaceup() and c:IsCanTurnSet() and c:IsType(TYPE_EFFECT)
end
function s.postg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and s.posfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(s.posfilter,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_POSCHANGE)
local g=Duel.SelectTarget(tp,s.posfilter,tp,0,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_POSITION,g,1,0,0)
end
function s.posop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.ChangePosition(tc,POS_FACEDOWN_DEFENSE)
end
end
function s.spfilter(c,e,tp)
return c:IsSetCard(0x18b) and not c:IsLevel(8) and c:IsFaceup()
and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_REMOVED) and chkc:IsControler(tp) and s.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(s.spfilter,tp,LOCATION_REMOVED,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,s.spfilter,tp,LOCATION_REMOVED,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
| 411 | 0.931809 | 1 | 0.931809 | game-dev | MEDIA | 0.975434 | game-dev | 0.934862 | 1 | 0.934862 |
GodotHub/gdscript-tutorial | 1,606 | tutorial/10.object-oriented-intro/10.7.design-patterns/10.7.3.behavioral-patterns/10.7.3.8.strategy-pattern.md | # 策略模式
把一个对象的“行为算法”提取出来,做成可替换的策略,让对象在运行时可以“挑一个”策略来用
# 适用的场景
* 当你发现一堆 if/else/switch 在判断“用哪种算法”时!
* 当你希望行为可切换、可扩展,又不想每次都改主类逻辑!
* 当行为算法/规则经常变动,但主体对象逻辑不想动!
比如:
* 不同排序策略(快排、冒泡、归并)
* 不同攻击策略(近战、远程、魔法)
* 不同定价策略(打折、满减、会员)
# 基本结构
* Context(上下文):使用策略的对象,持有策略对象的引用
* Strategy(策略):抽象策略接口,定义统一的行为函数
* ConcreteStrategy(具体策略):每种具体策略,实现不同的行为
你可以随时通过 Context 设置新的策略来改变行为,就像切换武器一样
# 示例
```csharp
interface IAttackStrategy
{
void Attack();
}
class MeleeAttack : IAttackStrategy
{
public void Attack() => Console.WriteLine("近身砍一刀!");
}
class RangedAttack : IAttackStrategy
{
public void Attack() => Console.WriteLine("远程射箭!");
}
class MagicAttack : IAttackStrategy
{
public void Attack() => Console.WriteLine("释放火球术!");
}
class Hero
{
public IAttackStrategy Strategy { get; set; }
public void PerformAttack()
{
Strategy.Attack();
}
}
// 使用:
var hero = new Hero();
hero.Strategy = new MeleeAttack();
hero.PerformAttack(); // 砍一刀
hero.Strategy = new MagicAttack();
hero.PerformAttack(); // 扔火球
```
### GDScript
```gdscript
class AttackStrategy:
func attack():
pass
class MeleeAttack extends AttackStrategy:
func attack():
print("近战攻击!")
class RangedAttack extends AttackStrategy:
func attack():
print("射箭射爆!")
class Hero:
var strategy: AttackStrategy
func perform_attack():
strategy.attack()
func _ready():
var hero = Hero.new()
hero.strategy = MeleeAttack.new()
hero.perform_attack() # 近战攻击!
hero.strategy = RangedAttack.new()
hero.perform_attack() # 射箭射爆!
```
| 411 | 0.659362 | 1 | 0.659362 | game-dev | MEDIA | 0.943927 | game-dev | 0.58735 | 1 | 0.58735 |
Raven-APlus/RavenAPlus | 3,855 | src/main/java/keystrokesmod/module/impl/combat/velocity/IntaveVelocity.java | package keystrokesmod.module.impl.combat.velocity;
import keystrokesmod.event.PostVelocityEvent;
import keystrokesmod.module.impl.combat.Velocity;
import keystrokesmod.module.setting.impl.ButtonSetting;
import keystrokesmod.module.setting.impl.SliderSetting;
import keystrokesmod.module.setting.impl.SubMode;
import keystrokesmod.utility.Utils;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.potion.Potion;
import net.minecraftforge.event.entity.player.AttackEntityEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import org.jetbrains.annotations.NotNull;
public class IntaveVelocity extends SubMode<Velocity> {
private final SliderSetting xzOnHit;
private final SliderSetting xzOnSprintHit;
private final ButtonSetting reduceUnnecessarySlowdown;
private final SliderSetting chance;
private final ButtonSetting jump;
private final ButtonSetting jumpInInv;
private final SliderSetting jumpChance;
private final ButtonSetting notWhileSpeed;
private final ButtonSetting notWhileJumpBoost;
private final ButtonSetting debug;
private boolean reduced = false;
public IntaveVelocity(String name, @NotNull Velocity parent) {
super(name, parent);
this.registerSetting(xzOnHit = new SliderSetting("XZ on hit", 0.6, 0, 1, 0.01));
this.registerSetting(xzOnSprintHit = new SliderSetting("XZ on sprint hit", 0.6, 0, 1, 0.01));
this.registerSetting(reduceUnnecessarySlowdown = new ButtonSetting("Reduce unnecessary slowdown", false));
this.registerSetting(chance = new SliderSetting("Chance", 100, 0, 100, 1, "%"));
this.registerSetting(jump = new ButtonSetting("Jump", false));
this.registerSetting(jumpInInv = new ButtonSetting("Jump in inv", false, jump::isToggled));
this.registerSetting(jumpChance = new SliderSetting("Jump chance", 80, 0, 100, 1, "%", jump::isToggled));
this.registerSetting(notWhileSpeed = new ButtonSetting("Not while speed", false));
this.registerSetting(notWhileJumpBoost = new ButtonSetting("Not while jump boost", false));
this.registerSetting(debug = new ButtonSetting("Debug", false));
}
@Override
public void onEnable() {
reduced = false;
}
@SubscribeEvent
public void onPostVelocity(PostVelocityEvent event) {
if (noAction()) return;
if (jump.isToggled()) {
if (Math.random() > jumpChance.getInput() / 100) return;
if (mc.thePlayer.onGround && (jumpInInv.isToggled() || mc.currentScreen == null))
mc.thePlayer.jump();
}
reduced = false;
}
@SubscribeEvent
public void onAttack(@NotNull AttackEntityEvent event) {
if (event.target instanceof EntityLivingBase && mc.thePlayer.hurtTime > 0) {
if (noAction()) return;
if (Math.random() > chance.getInput() / 100) return;
if (reduceUnnecessarySlowdown.isToggled() && reduced) return;
if (mc.thePlayer.isSprinting()) {
mc.thePlayer.motionX *= xzOnSprintHit.getInput();
mc.thePlayer.motionZ *= xzOnSprintHit.getInput();
} else {
mc.thePlayer.motionX *= xzOnHit.getInput();
mc.thePlayer.motionZ *= xzOnHit.getInput();
}
reduced = true;
if (debug.isToggled())
Utils.sendMessage(String.format("Reduced %.3f %.3f", mc.thePlayer.motionX, mc.thePlayer.motionZ));
}
}
private boolean noAction() {
return mc.thePlayer.getActivePotionEffects().parallelStream()
.anyMatch(effect -> notWhileSpeed.isToggled() && effect.getPotionID() == Potion.moveSpeed.getId()
|| notWhileJumpBoost.isToggled() && effect.getPotionID() == Potion.jump.getId());
}
}
| 411 | 0.804172 | 1 | 0.804172 | game-dev | MEDIA | 0.929083 | game-dev | 0.932625 | 1 | 0.932625 |
cre8ivepark/COVID19DataVisualizationHoloLens2 | 19,683 | Assets/MRTK/SDK/Features/UX/Scripts/AppBar/AppBar.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.UI
{
/// <summary>
/// Logic for the App Bar. Generates buttons, manages states.
/// </summary>
[AddComponentMenu("Scripts/MRTK/SDK/AppBar")]
public class AppBar : MonoBehaviour
{
private const float backgroundBarMoveSpeed = 5;
#region Enum Definitions
[Flags]
public enum ButtonTypeEnum
{
Custom = 0,
Remove = 1,
Adjust = 2,
Hide = 4,
Show = 8,
Done = 16
}
public enum AppBarDisplayTypeEnum
{
Manipulation,
Standalone
}
public enum AppBarStateEnum
{
Default,
Manipulation,
Hidden
}
#endregion
#region Private Serialized Fields with Public Properties
[Header("Target Bounding Box")]
[Tooltip("Object the app bar is controlling - This object must implement the IBoundsTargetProvider.")]
[SerializeField]
private MonoBehaviour boundingBox = null;
/// <summary>
/// Object the app bar is controlling - This object must implement the IBoundsTargetProvider.
/// </summary>
public MonoBehaviour Target
{
get { return boundingBox; }
set { boundingBox = value; }
}
[Tooltip("The parent game object for the renderable objects in the app bar")]
[SerializeField]
private GameObject baseRenderer = null;
/// <summary>
/// The parent game object for the renderable objects in the AppBar
/// </summary>
public GameObject BaseRenderer
{
get => baseRenderer;
set => baseRenderer = value;
}
[Tooltip("The parent transform for the button collection")]
[SerializeField]
private Transform buttonParent = null;
/// <summary>
/// The parent transform for the button collection
/// </summary>
public Transform ButtonParent
{
get => buttonParent;
set => buttonParent = value;
}
[Tooltip("The background gameobject, scales to fill area behind buttons")]
[SerializeField]
private GameObject backgroundBar = null;
/// <summary>
/// The background gameobject, scales to fill area behind buttons
/// </summary>
public GameObject BackgroundBar
{
get => backgroundBar;
set => backgroundBar = value;
}
[Header("States")]
[Tooltip("The AppBar's display type; default is Manipulation")]
[SerializeField]
private AppBarDisplayTypeEnum displayType = AppBarDisplayTypeEnum.Manipulation;
/// <summary>
/// The AppBar's display type; default is Manipulation
/// </summary>
public AppBarDisplayTypeEnum DisplayType
{
get { return displayType; }
set { displayType = value; }
}
[Tooltip("The AppBar's current state")]
[SerializeField]
private AppBarStateEnum state = AppBarStateEnum.Default;
/// <summary>
/// The AppBar's current state
/// </summary>
public AppBarStateEnum State
{
get { return state; }
set { state = value; }
}
[Header("Default Button Options")]
[Tooltip("Should the AppBar have a remove button")]
[SerializeField]
private bool useRemove = true;
/// <summary>
/// Should the AppBar have a remove button
/// </summary>
public bool UseRemove
{
get { return useRemove; }
set { useRemove = value; }
}
[Tooltip("Should the AppBar have an adjust button")]
[SerializeField]
private bool useAdjust = true;
/// <summary>
/// Should the AppBar have an adjust button
/// </summary>
public bool UseAdjust
{
get { return useAdjust; }
set { useAdjust = value; }
}
[Tooltip("Should the AppBar have a hide button")]
[SerializeField]
private bool useHide = true;
/// <summary>
/// Should the AppBar have a hide button
/// </summary>
public bool UseHide
{
get { return useHide; }
set { useHide = value; }
}
[Header("Default Button Icons")]
[Tooltip("The adjust button texture")]
[SerializeField]
private Texture adjustIcon = null;
/// <summary>
/// The adjust button texture
/// </summary>
public Texture AdjustIcon
{
get => adjustIcon;
set => adjustIcon = value;
}
[Tooltip("The done button texture")]
[SerializeField]
private Texture doneIcon = null;
/// <summary>
/// The done button texture
/// </summary>
public Texture DoneIcon
{
get => doneIcon;
set => doneIcon = value;
}
[Tooltip("The hide button texture")]
[SerializeField]
private Texture hideIcon = null;
/// <summary>
/// The hide button texture
/// </summary>
public Texture HideIcon
{
get => hideIcon;
set => hideIcon = value;
}
[Tooltip("The Remove button texture")]
[SerializeField]
private Texture removeIcon = null;
/// <summary>
/// The remove button texture
/// </summary>
public Texture RemoveIcon
{
get => removeIcon;
set => removeIcon = value;
}
[Tooltip("The show button texture")]
[SerializeField]
private Texture showIcon = null;
/// <summary>
/// The show button texture
/// </summary>
public Texture ShowIcon
{
get => showIcon;
set => showIcon = value;
}
[Header("Scale & Position Options")]
[SerializeField]
[Tooltip("Uses an alternate follow style that works better for very oblong objects.")]
private bool useTightFollow = false;
/// <summary>
/// Uses an alternate follow style that works better for very oblong objects
/// </summary>
public bool UseTightFollow
{
get { return useTightFollow; }
set { useTightFollow = value; }
}
[SerializeField]
[Tooltip("Where to display the app bar on the y axis. This can be set to negative values to force the app bar to appear below the object.")]
private float hoverOffsetYScale = 0.25f;
/// <summary>
/// Where to display the app bar on the y axis
/// This can be set to negative values
/// to force the app bar to appear below the object
/// </summary>
public float HoverOffsetYScale
{
get { return hoverOffsetYScale; }
set { hoverOffsetYScale = value; }
}
[SerializeField]
[Tooltip("Pushes the app bar away from the object.")]
private float hoverOffsetZ = 0f;
/// <summary>
/// Pushes the app bar away from the object
/// </summary>
public float HoverOffsetZ
{
get { return hoverOffsetZ; }
set { hoverOffsetZ = value; }
}
[Tooltip("The button width for each button")]
[SerializeField]
private float buttonWidth = 0.032f;
/// <summary>
/// The button width for each button
/// </summary>
public float ButtonWidth
{
get => buttonWidth;
set => buttonWidth = value;
}
[Tooltip("The button depth for each button")]
[SerializeField]
private float buttonDepth = 0.016f;
/// <summary>
/// The button depth for each button
/// </summary>
public float ButtonDepth
{
get => buttonDepth;
set => buttonDepth = value;
}
#endregion
private List<AppBarButton> buttons = new List<AppBarButton>();
private Vector3 targetBarSize = Vector3.one;
private float lastTimeTapped = 0f;
private float coolDownTime = 0.5f;
private BoundingBoxHelper helper = new BoundingBoxHelper();
private List<Vector3> boundsPoints = new List<Vector3>();
#region MonoBehaviour Functions
private void OnEnable()
{
InitializeButtons();
}
private void LateUpdate()
{
UpdateAppBar();
}
#endregion
public void Reset()
{
State = AppBarStateEnum.Default;
FollowTargetObject(false);
lastTimeTapped = Time.time + coolDownTime;
}
public void OnButtonPressed(AppBarButton button)
{
if (Time.time < lastTimeTapped + coolDownTime)
return;
lastTimeTapped = Time.time;
switch (button.ButtonType)
{
case ButtonTypeEnum.Remove:
OnClickRemove();
break;
case ButtonTypeEnum.Adjust:
State = AppBarStateEnum.Manipulation;
break;
case ButtonTypeEnum.Hide:
State = AppBarStateEnum.Hidden;
break;
case ButtonTypeEnum.Show:
State = AppBarStateEnum.Default;
break;
case ButtonTypeEnum.Done:
State = AppBarStateEnum.Default;
break;
default:
break;
}
}
protected virtual void OnClickRemove()
{
// Set the app bar and bounding box to inactive
var boundsProvider = Target as IBoundsTargetProvider;
if (boundsProvider != null)
{
boundsProvider.Target.SetActive(false);
}
Target.gameObject.SetActive(false);
gameObject.SetActive(false);
}
private void InitializeButtons()
{
buttons.Clear();
foreach (Transform child in ButtonParent)
{
AppBarButton appBarButton = child.GetComponent<AppBarButton>();
if (appBarButton == null)
throw new Exception("Found a transform without an AppBarButton component under buttonTransforms!");
appBarButton.InitializeButtonContent(this);
// Set to invisible initially if not custom
switch (appBarButton.ButtonType)
{
case ButtonTypeEnum.Custom:
break;
default:
appBarButton.SetVisible(false);
break;
}
buttons.Add(appBarButton);
}
}
private void UpdateAppBar()
{
UpdateButtons();
UpdateTargetObject();
FollowTargetObject(true);
}
private void UpdateButtons()
{
// First just count how many buttons are visible
int activeButtonNum = 0;
for (int i = 0; i < buttons.Count; i++)
{
AppBarButton button = buttons[i];
switch (button.ButtonType)
{
case ButtonTypeEnum.Custom:
break;
default:
button.SetVisible(GetButtonVisible(button.ButtonType));
break;
}
if (!buttons[i].Visible)
{
continue;
}
activeButtonNum++;
}
// Sort the buttons by display order
buttons.Sort(delegate (AppBarButton b1, AppBarButton b2) { return b2.DisplayOrder.CompareTo(b1.DisplayOrder); });
// Use active button number to determine background size and offset
float backgroundBarSize = ButtonWidth * activeButtonNum;
Vector3 positionOffset = Vector3.right * ((backgroundBarSize / 2) - (ButtonWidth / 2));
// Go through them again, setting active as
activeButtonNum = 0;
for (int i = 0; i < buttons.Count; i++)
{
// Set the sibling index and target position so the button will behave predictably when set visible
buttons[i].transform.SetSiblingIndex(i);
buttons[i].SetTargetPosition((Vector3.left * ButtonWidth * activeButtonNum) + positionOffset);
if (!buttons[i].Visible)
continue;
activeButtonNum++;
}
targetBarSize.x = backgroundBarSize;
BackgroundBar.transform.localScale = Vector3.Lerp(BackgroundBar.transform.localScale, targetBarSize, Time.deltaTime * backgroundBarMoveSpeed);
BackgroundBar.transform.localPosition = Vector3.forward * ButtonDepth / 2;
}
private void UpdateTargetObject()
{
var boundsProvider = Target as IBoundsTargetProvider;
if (boundsProvider == null || boundsProvider.Target == null)
{
if (DisplayType == AppBarDisplayTypeEnum.Manipulation)
{
// Hide our buttons
BaseRenderer.SetActive(false);
}
else
{
BaseRenderer.SetActive(true);
}
return;
}
// Target can't be updated in editor mode
if (!Application.isPlaying)
return;
if (boundsProvider == null)
return;
switch (State)
{
case AppBarStateEnum.Manipulation:
boundsProvider.Active = true;
break;
default:
boundsProvider.Active = false;
break;
}
}
private void FollowTargetObject(bool smooth)
{
var boundsProvider = Target as IBoundsTargetProvider;
if (boundsProvider == null)
return;
//calculate best follow position for AppBar
Vector3 finalPosition = Vector3.zero;
Vector3 headPosition = CameraCache.Main.transform.position;
boundsPoints.Clear();
helper.UpdateNonAABoundsCornerPositions(boundsProvider.TargetBounds, boundsPoints);
int followingFaceIndex = helper.GetIndexOfForwardFace(headPosition);
Vector3 faceNormal = helper.GetFaceNormal(followingFaceIndex);
//finally we have new position
finalPosition = helper.GetFaceBottomCentroid(followingFaceIndex) + (faceNormal * HoverOffsetZ);
// Follow our bounding box
transform.position = smooth ? Vector3.Lerp(transform.position, finalPosition, Time.deltaTime * backgroundBarMoveSpeed) : finalPosition;
// Rotate on the y axis
Vector3 direction = (boundsProvider.TargetBounds.bounds.center - finalPosition).normalized;
if (direction != Vector3.zero)
{
Vector3 eulerAngles = Quaternion.LookRotation(direction, Vector3.up).eulerAngles;
eulerAngles.x = 0f;
eulerAngles.z = 0f;
transform.eulerAngles = eulerAngles;
}
else
{
transform.eulerAngles = Vector3.zero;
}
}
private bool GetButtonVisible(ButtonTypeEnum buttonType)
{
// Set visibility based on button type / options
switch (buttonType)
{
default:
break;
case ButtonTypeEnum.Remove:
if (!UseRemove)
return false;
break;
case ButtonTypeEnum.Hide:
if (!UseHide)
return false;
break;
case ButtonTypeEnum.Adjust:
if (!UseAdjust)
return false;
break;
}
switch (State)
{
case AppBarStateEnum.Default:
default:
switch (buttonType)
{
// Show hide, adjust, remove buttons
// The rest are hidden
case AppBar.ButtonTypeEnum.Hide:
case AppBar.ButtonTypeEnum.Remove:
case AppBar.ButtonTypeEnum.Adjust:
case AppBar.ButtonTypeEnum.Custom:
return true;
default:
return false;
}
case AppBarStateEnum.Hidden:
switch (buttonType)
{
// Show show button
// The rest are hidden
case ButtonTypeEnum.Show:
return true;
default:
return false;
}
case AppBarStateEnum.Manipulation:
switch (buttonType)
{
// Show done button
// The rest are hidden
case AppBar.ButtonTypeEnum.Done:
return true;
default:
return false;
}
}
}
public void GetButtonTextAndIconFromType(ButtonTypeEnum type, out string buttonText, out Texture buttonIcon, out int displayOrder)
{
switch (type)
{
case ButtonTypeEnum.Show:
buttonText = "Show";
buttonIcon = ShowIcon;
displayOrder = 0;
break;
case ButtonTypeEnum.Hide:
buttonText = "Hide";
buttonIcon = HideIcon;
displayOrder = 1;
break;
case ButtonTypeEnum.Adjust:
buttonText = "Adjust";
buttonIcon = AdjustIcon;
displayOrder = 2;
break;
case ButtonTypeEnum.Remove:
buttonText = "Remove";
buttonIcon = RemoveIcon;
displayOrder = 3;
break;
case ButtonTypeEnum.Done:
buttonText = "Done";
buttonIcon = DoneIcon;
displayOrder = 4;
break;
default:
throw new ArgumentOutOfRangeException("type", type, null);
}
}
}
}
| 411 | 0.952417 | 1 | 0.952417 | game-dev | MEDIA | 0.532241 | game-dev,desktop-app | 0.80287 | 1 | 0.80287 |
XFactHD/FramedBlocks | 6,661 | src/main/java/io/github/xfacthd/framedblocks/common/block/pane/FramedBoardBlock.java | package io.github.xfacthd.framedblocks.common.block.pane;
import io.github.xfacthd.framedblocks.api.block.FramedProperties;
import io.github.xfacthd.framedblocks.api.block.PlacementStateBuilder;
import io.github.xfacthd.framedblocks.api.camo.CamoList;
import io.github.xfacthd.framedblocks.api.util.Utils;
import io.github.xfacthd.framedblocks.common.FBContent;
import io.github.xfacthd.framedblocks.common.block.FramedBlock;
import io.github.xfacthd.framedblocks.common.data.BlockType;
import io.github.xfacthd.framedblocks.common.data.PropertyHolder;
import io.github.xfacthd.framedblocks.common.item.block.FramedSpecialBlockItem;
import net.minecraft.Util;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Mirror;
import net.minecraft.world.level.block.Rotation;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import org.jetbrains.annotations.Nullable;
public class FramedBoardBlock extends FramedBlock
{
private static final Direction[] HOR_DIRECTIONS = Direction.Plane.HORIZONTAL.stream().toArray(Direction[]::new);
private static final int[] EDGE_MASKS = Util.make(new int[3], arr ->
{
for (Direction.Axis axis : Direction.Axis.values())
{
int mask = (1 << axis.getPositive().ordinal()) | (1 << axis.getNegative().ordinal());
arr[axis.ordinal()] = ~mask & 0b00111111;
}
});
private static final int DEFAULT_FACE = 1 << Direction.DOWN.ordinal();
public FramedBoardBlock(Properties props)
{
super(BlockType.FRAMED_BOARD, props);
registerDefaultState(defaultBlockState().setValue(PropertyHolder.FACES, DEFAULT_FACE));
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder)
{
super.createBlockStateDefinition(builder);
builder.add(PropertyHolder.FACES, BlockStateProperties.WATERLOGGED, FramedProperties.SOLID);
}
@Override
@Nullable
public BlockState getStateForPlacement(BlockPlaceContext ctx)
{
return PlacementStateBuilder.of(this, ctx)
.withCustom((state, modCtx) ->
{
Level level = modCtx.getLevel();
BlockPos pos = modCtx.getClickedPos();
Direction face = modCtx.getClickedFace().getOpposite();
BlockState prevState = level.getBlockState(pos);
if (prevState.is(this))
{
if (modCtx.replacingClickedOnBlock())
{
face = Utils.getDirByCross(face, modCtx.getClickLocation());
}
return isFacePresent(prevState, face) ? null : setFacePresent(prevState, face, true);
}
return state.setValue(PropertyHolder.FACES, 1 << face.ordinal());
})
.withWater()
.build();
}
@Override
protected boolean canBeReplaced(BlockState state, BlockPlaceContext ctx)
{
if (ctx.getPlayer() != null && !ctx.getPlayer().isShiftKeyDown() && ctx.getItemInHand().is(asItem()))
{
if (!ctx.getItemInHand().getOrDefault(FBContent.DC_TYPE_CAMO_LIST, CamoList.EMPTY).isEmpty())
{
return false;
}
if (ctx.replacingClickedOnBlock())
{
Direction face = ctx.getClickedFace();
double fraction = Utils.fractionInDir(ctx.getClickLocation(), face);
return !isFacePresent(state, face) || (fraction > 0F && fraction < (3F / 32F));
}
return true;
}
return false;
}
@Override
public BlockItem createBlockItem(Item.Properties props)
{
return new FramedSpecialBlockItem.Single(this, props)
{
@Override
@Nullable
protected BlockState getReplacementState(BlockPlaceContext ctx, BlockState originalState)
{
return FramedBoardBlock.this.getStateForPlacement(ctx);
}
};
}
@Override
protected BlockState rotate(BlockState state, Rotation rot)
{
int mask = 0;
for (Direction side : HOR_DIRECTIONS)
{
if (isFacePresent(state, side))
{
mask |= 1 << side.get2DDataValue();
}
}
mask |= mask << 4;
mask = Integer.rotateRight(mask, 4 - rot.ordinal());
for (Direction side : HOR_DIRECTIONS)
{
boolean set = (mask & (1 << side.get2DDataValue())) != 0;
state = setFacePresent(state, side, set);
}
return state;
}
@Override
protected BlockState mirror(BlockState state, Mirror mirror)
{
if (mirror == Mirror.NONE) return state;
boolean invZ = mirror == Mirror.LEFT_RIGHT;
Direction dirOne = invZ ? Direction.NORTH : Direction.WEST;
Direction dirTwo = invZ ? Direction.SOUTH : Direction.EAST;
boolean temp = isFacePresent(state, dirOne);
state = setFacePresent(state, dirOne, isFacePresent(state, dirTwo));
return setFacePresent(state, dirTwo, temp);
}
@Override
public BlockState getItemModelSource()
{
return defaultBlockState();
}
@Override
public BlockState getJadeRenderState(BlockState state)
{
return defaultBlockState();
}
public static boolean isFacePresent(BlockState state, Direction side)
{
return (state.getValue(PropertyHolder.FACES) & (1 << side.ordinal())) != 0;
}
public static BlockState setFacePresent(BlockState state, Direction side, boolean present)
{
int faces = state.getValue(PropertyHolder.FACES);
int mask = 1 << side.ordinal();
if (present)
{
faces |= mask;
}
else
{
faces &= ~mask;
}
return faces == 0 ? state : state.setValue(PropertyHolder.FACES, faces);
}
public static int computeEdgeMask(BlockState state, Direction side)
{
return state.getValue(PropertyHolder.FACES) & EDGE_MASKS[side.getAxis().ordinal()];
}
}
| 411 | 0.958079 | 1 | 0.958079 | game-dev | MEDIA | 0.930048 | game-dev | 0.970716 | 1 | 0.970716 |
Bartis1313/csgo | 5,364 | hack/SDK/ConVar.hpp | #pragma once
#include "CUtlVector.hpp"
#include "helpers/pad.hpp"
#include "helpers/vfunc.hpp"
//-----------------------------------------------------------------------------
// ConVar flags
//-----------------------------------------------------------------------------
// The default, no flags at all
#define FCVAR_NONE 0
// Command to ConVars and ConCommands
// ConVar Systems
#define FCVAR_UNREGISTERED (1<<0) // If this is set, don't add to linked list, etc.
#define FCVAR_DEVELOPMENTONLY (1<<1) // Hidden in released products. Flag is removed automatically if ALLOW_DEVELOPMENT_CVARS is defined.
#define FCVAR_GAMEDLL (1<<2) // defined by the game DLL
#define FCVAR_CLIENTDLL (1<<3) // defined by the client DLL
#define FCVAR_HIDDEN (1<<4) // Hidden. Doesn't appear in find or auto complete. Like DEVELOPMENTONLY, but can't be compiled out.
// ConVar only
#define FCVAR_PROTECTED (1<<5) // It's a server cvar, but we don't send the data since it's a password, etc. Sends 1 if it's not bland/zero, 0 otherwise as value
#define FCVAR_SPONLY (1<<6) // This cvar cannot be changed by clients connected to a multiplayer server.
#define FCVAR_ARCHIVE (1<<7) // set to cause it to be saved to vars.rc
#define FCVAR_NOTIFY (1<<8) // notifies players when changed
#define FCVAR_USERINFO (1<<9) // changes the client's info string
#define FCVAR_PRINTABLEONLY (1<<10) // This cvar's string cannot contain unprintable characters ( e.g., used for player name etc ).
#define FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS (1<<10) // When on concommands this allows remote clients to execute this cmd on the server.
// We are changing the default behavior of concommands to disallow execution by remote clients without
// this flag due to the number existing concommands that can lag or crash the server when clients abuse them.
#define FCVAR_UNLOGGED (1<<11) // If this is a FCVAR_SERVER, don't log changes to the log file / console if we are creating a log
#define FCVAR_NEVER_AS_STRING (1<<12) // never try to print that cvar
// It's a ConVar that's shared between the client and the server.
// At signon, the values of all such ConVars are sent from the server to the client (skipped for local
// client, of course )
// If a change is requested it must come from the console (i.e., no remote client changes)
// If a value is changed while a server is active, it's replicated to all connected clients
#define FCVAR_REPLICATED (1<<13) // server setting enforced on clients, TODO rename to FCAR_SERVER at some time
#define FCVAR_CHEAT (1<<14) // Only useable in singleplayer / debug / multiplayer & sv_cheats
#define FCVAR_SS (1<<15) // causes varnameN where N == 2 through max splitscreen slots for mod to be autogenerated
#define FCVAR_DEMO (1<<16) // record this cvar when starting a demo file
#define FCVAR_DONTRECORD (1<<17) // don't record these command in demofiles
#define FCVAR_SS_ADDED (1<<18) // This is one of the "added" FCVAR_SS variables for the splitscreen players
#define FCVAR_RELEASE (1<<19) // Cvars tagged with this are the only cvars avaliable to customers
#define FCVAR_RELOAD_MATERIALS (1<<20) // If this cvar changes, it forces a material reload
#define FCVAR_RELOAD_TEXTURES (1<<21) // If this cvar changes, if forces a texture reload
#define FCVAR_NOT_CONNECTED (1<<22) // cvar cannot be changed by a client that is connected to a server
#define FCVAR_MATERIAL_SYSTEM_THREAD (1<<23) // Indicates this cvar is read from the material system thread
#define FCVAR_ARCHIVE_GAMECONSOLE (1<<24) // cvar written to config.cfg on the Xbox
#define FCVAR_SERVER_CAN_EXECUTE (1<<28)// the server is allowed to execute this command on clients via ClientCommand/NET_StringCmd/CBaseClientState::ProcessStringCmd.
#define FCVAR_SERVER_CANNOT_QUERY (1<<29)// If this is set, then the server is not allowed to query this cvar's value (via IServerPluginHelpers::StartQueryCvarValue).
#define FCVAR_CLIENTCMD_CAN_EXECUTE (1<<30) // IVEngineClient::ClientCmd is allowed to execute this command.
// Note: IVEngineClient::ClientCmd_Unrestricted can run any client command.
#define FCVAR_ACCESSIBLE_FROM_THREADS (1<<25) // used as a debugging tool necessary to check material system thread convars
// #define FCVAR_AVAILABLE (1<<26)
// #define FCVAR_AVAILABLE (1<<27)
// #define FCVAR_AVAILABLE (1<<31)
#define FCVAR_MATERIAL_THREAD_MASK ( FCVAR_RELOAD_MATERIALS | FCVAR_RELOAD_TEXTURES | FCVAR_MATERIAL_SYSTEM_THREAD )
class IConVar
{
public:
VFUNC(float, getFloat, 12, (), (this));
VFUNC(int, getInt, 13, (), (this));
VFUNC(void, setValue, 14, (const char* val), (this, val));
VFUNC(void, setValue, 15, (float val), (this, val));
VFUNC(void, setValue, 16, (int val), (this, val));
VFUNC(void, setValue, 17, (bool val), (this, val));
private:
void* sometable;
public:
IConVar* m_next;
alignas(4) bool registered;
char* m_name;
char* m_helper;
int m_flags;
private:
void* unkCallback;
public:
IConVar* m_parent;
const char* m_defaultValue;
char* m_valueNow;
int m_valueLength;
private:
IConVar* parentCopy1;
IConVar* parentCopy2;
public:
char* valuenowCopied; // bit delayed
int m_valueLengthCopied;
private:
IConVar* parentCopy3;
IConVar* parentCopy4; // wtf?
PAD(16); // all zeros
CUtlVector<std::add_pointer_t<void __cdecl()>> m_callbacks;
}; | 411 | 0.879618 | 1 | 0.879618 | game-dev | MEDIA | 0.775501 | game-dev,networking | 0.707803 | 1 | 0.707803 |
Kirby64Ret/kirby64 | 5,360 | asm/non_matchings/ovl2_6/func_8010D8A4.s | glabel func_8010D8A4
/* 096314 8010D8A4 27BDFFA0 */ addiu $sp, $sp, -0x60
/* 096318 8010D8A8 AFBF002C */ sw $ra, 0x2c($sp)
/* 09631C 8010D8AC AFB00028 */ sw $s0, 0x28($sp)
/* 096320 8010D8B0 0C0413EE */ jal func_80104FB8
/* 096324 8010D8B4 00808025 */ move $s0, $a0
/* 096328 8010D8B8 44800000 */ mtc1 $zero, $f0
/* 09632C 8010D8BC 3C01BF80 */ li $at, 0xBF800000 # -1.000000
/* 096330 8010D8C0 44812000 */ mtc1 $at, $f4
/* 096334 8010D8C4 3C038013 */ lui $v1, %hi(D_8012BD00) # $v1, 0x8013
/* 096338 8010D8C8 2463BD00 */ addiu $v1, %lo(D_8012BD00) # addiu $v1, $v1, -0x4300
/* 09633C 8010D8CC E7A00038 */ swc1 $f0, 0x38($sp)
/* 096340 8010D8D0 E7A00040 */ swc1 $f0, 0x40($sp)
/* 096344 8010D8D4 E7A4003C */ swc1 $f4, 0x3c($sp)
/* 096348 8010D8D8 C6060004 */ lwc1 $f6, 4($s0)
/* 09634C 8010D8DC C4680004 */ lwc1 $f8, 4($v1)
/* 096350 8010D8E0 26020010 */ addiu $v0, $s0, 0x10
/* 096354 8010D8E4 3C018013 */ lui $at, %hi(D_80128AE0) # $at, 0x8013
/* 096358 8010D8E8 46083280 */ add.s $f10, $f6, $f8
/* 09635C 8010D8EC C4680008 */ lwc1 $f8, 8($v1)
/* 096360 8010D8F0 27AE0034 */ addiu $t6, $sp, 0x34
/* 096364 8010D8F4 27A40050 */ addiu $a0, $sp, 0x50
/* 096368 8010D8F8 E7AA0050 */ swc1 $f10, 0x50($sp)
/* 09636C 8010D8FC C6100008 */ lwc1 $f16, 8($s0)
/* 096370 8010D900 C4520004 */ lwc1 $f18, 4($v0)
/* 096374 8010D904 27A50044 */ addiu $a1, $sp, 0x44
/* 096378 8010D908 27A60038 */ addiu $a2, $sp, 0x38
/* 09637C 8010D90C 46128100 */ add.s $f4, $f16, $f18
/* 096380 8010D910 C7B00050 */ lwc1 $f16, 0x50($sp)
/* 096384 8010D914 00003825 */ move $a3, $zero
/* 096388 8010D918 E7A40054 */ swc1 $f4, 0x54($sp)
/* 09638C 8010D91C C606000C */ lwc1 $f6, 0xc($s0)
/* 096390 8010D920 E7B00044 */ swc1 $f16, 0x44($sp)
/* 096394 8010D924 46083280 */ add.s $f10, $f6, $f8
/* 096398 8010D928 C4288AE0 */ lwc1 $f8, %lo(D_80128AE0)($at)
/* 09639C 8010D92C E7AA0058 */ swc1 $f10, 0x58($sp)
/* 0963A0 8010D930 C4440008 */ lwc1 $f4, 8($v0)
/* 0963A4 8010D934 C6120008 */ lwc1 $f18, 8($s0)
/* 0963A8 8010D938 C7B00058 */ lwc1 $f16, 0x58($sp)
/* 0963AC 8010D93C AFA0001C */ sw $zero, 0x1c($sp)
/* 0963B0 8010D940 46049180 */ add.s $f6, $f18, $f4
/* 0963B4 8010D944 AFAE0018 */ sw $t6, 0x18($sp)
/* 0963B8 8010D948 AFA00014 */ sw $zero, 0x14($sp)
/* 0963BC 8010D94C AFA00010 */ sw $zero, 0x10($sp)
/* 0963C0 8010D950 46083281 */ sub.s $f10, $f6, $f8
/* 0963C4 8010D954 E7B0004C */ swc1 $f16, 0x4c($sp)
/* 0963C8 8010D958 0C040FA8 */ jal func_80103EA0
/* 0963CC 8010D95C E7AA0048 */ swc1 $f10, 0x48($sp)
/* 0963D0 8010D960 10400009 */ beqz $v0, .L8010D988_ovl2
/* 0963D4 8010D964 8FA40034 */ lw $a0, 0x34($sp)
/* 0963D8 8010D968 00002825 */ move $a1, $zero
/* 0963DC 8010D96C 00003025 */ move $a2, $zero
/* 0963E0 8010D970 0C0408C9 */ jal D_80102324_ovl2
/* 0963E4 8010D974 00003825 */ move $a3, $zero
/* 0963E8 8010D978 14400003 */ bnez $v0, .L8010D988_ovl2
/* 0963EC 8010D97C 00000000 */ nop
/* 0963F0 8010D980 10000024 */ b .L8010DA14_ovl2
/* 0963F4 8010D984 00001025 */ move $v0, $zero
.L8010D988_ovl2:
/* 0963F8 8010D988 3C028013 */ lui $v0, %hi(D_8012BD00) # $v0, 0x8013
/* 0963FC 8010D98C 2442BD00 */ addiu $v0, %lo(D_8012BD00) # addiu $v0, $v0, -0x4300
/* 096400 8010D990 C444000C */ lwc1 $f4, 0xc($v0)
/* 096404 8010D994 C6120004 */ lwc1 $f18, 4($s0)
/* 096408 8010D998 C44A0010 */ lwc1 $f10, 0x10($v0)
/* 09640C 8010D99C 27AF0034 */ addiu $t7, $sp, 0x34
/* 096410 8010D9A0 46049180 */ add.s $f6, $f18, $f4
/* 096414 8010D9A4 27A40050 */ addiu $a0, $sp, 0x50
/* 096418 8010D9A8 27A50044 */ addiu $a1, $sp, 0x44
/* 09641C 8010D9AC 27A60038 */ addiu $a2, $sp, 0x38
/* 096420 8010D9B0 E7A60050 */ swc1 $f6, 0x50($sp)
/* 096424 8010D9B4 C608000C */ lwc1 $f8, 0xc($s0)
/* 096428 8010D9B8 C7B20050 */ lwc1 $f18, 0x50($sp)
/* 09642C 8010D9BC AFA0001C */ sw $zero, 0x1c($sp)
/* 096430 8010D9C0 460A4400 */ add.s $f16, $f8, $f10
/* 096434 8010D9C4 AFAF0018 */ sw $t7, 0x18($sp)
/* 096438 8010D9C8 AFA00014 */ sw $zero, 0x14($sp)
/* 09643C 8010D9CC AFA00010 */ sw $zero, 0x10($sp)
/* 096440 8010D9D0 E7B00058 */ swc1 $f16, 0x58($sp)
/* 096444 8010D9D4 C7A40058 */ lwc1 $f4, 0x58($sp)
/* 096448 8010D9D8 00003825 */ move $a3, $zero
/* 09644C 8010D9DC E7B20044 */ swc1 $f18, 0x44($sp)
/* 096450 8010D9E0 0C040FA8 */ jal func_80103EA0
/* 096454 8010D9E4 E7A4004C */ swc1 $f4, 0x4c($sp)
/* 096458 8010D9E8 10400009 */ beqz $v0, .L8010DA10_ovl2
/* 09645C 8010D9EC 8FA40034 */ lw $a0, 0x34($sp)
/* 096460 8010D9F0 00002825 */ move $a1, $zero
/* 096464 8010D9F4 00003025 */ move $a2, $zero
/* 096468 8010D9F8 0C0408C9 */ jal D_80102324_ovl2
/* 09646C 8010D9FC 00003825 */ move $a3, $zero
/* 096470 8010DA00 54400004 */ bnezl $v0, .L8010DA14_ovl2
/* 096474 8010DA04 24020001 */ li $v0, 1
/* 096478 8010DA08 10000002 */ b .L8010DA14_ovl2
/* 09647C 8010DA0C 00001025 */ move $v0, $zero
.L8010DA10_ovl2:
/* 096480 8010DA10 24020001 */ li $v0, 1
.L8010DA14_ovl2:
/* 096484 8010DA14 8FBF002C */ lw $ra, 0x2c($sp)
/* 096488 8010DA18 8FB00028 */ lw $s0, 0x28($sp)
/* 09648C 8010DA1C 27BD0060 */ addiu $sp, $sp, 0x60
/* 096490 8010DA20 03E00008 */ jr $ra
/* 096494 8010DA24 00000000 */ nop
.type func_8010D8A4, @function
.size func_8010D8A4, . - func_8010D8A4
| 411 | 0.719755 | 1 | 0.719755 | game-dev | MEDIA | 0.808907 | game-dev | 0.583493 | 1 | 0.583493 |
mayao11/PracticalGameAI | 1,987 | AI_Enemy3_Behavior_basic/Assets/Behavior Designer/Runtime/Actions/RestartBehaviorTree.cs | using UnityEngine;
namespace BehaviorDesigner.Runtime.Tasks
{
[TaskDescription("Restarts a behavior tree, returns success after it has been restarted.")]
[HelpURL("http://www.opsive.com/assets/BehaviorDesigner/documentation.php?id=66")]
[TaskIcon("{SkinColor}RestartBehaviorTreeIcon.png")]
public class RestartBehaviorTree : Action
{
[Tooltip("The GameObject of the behavior tree that should be restarted. If null use the current behavior")]
public SharedGameObject behaviorGameObject;
[Tooltip("The group of the behavior tree that should be restarted")]
public SharedInt group;
private Behavior behavior;
public override void OnAwake()
{
var behaviorTrees = GetDefaultGameObject(behaviorGameObject.Value).GetComponents<Behavior>();
if (behaviorTrees.Length == 1) {
behavior = behaviorTrees[0];
} else if (behaviorTrees.Length > 1) {
for (int i = 0; i < behaviorTrees.Length; ++i) {
if (behaviorTrees[i].Group == group.Value) {
behavior = behaviorTrees[i];
break;
}
}
// If the group can't be found then use the first behavior tree
if (behavior == null) {
behavior = behaviorTrees[0];
}
}
}
public override TaskStatus OnUpdate()
{
if (behavior == null) {
return TaskStatus.Failure;
}
// Stop the behavior tree
behavior.DisableBehavior();
// Start the behavior tree back up
behavior.EnableBehavior();
// Return success
return TaskStatus.Success;
}
public override void OnReset()
{
// Reset the properties back to their original values.
behavior = null;
}
}
} | 411 | 0.876427 | 1 | 0.876427 | game-dev | MEDIA | 0.836373 | game-dev | 0.75254 | 1 | 0.75254 |
EmptyBottleInc/DFU-Tanguy-Multiplayer | 3,073 | Assets/Scripts/Game/Guilds/IGuild.cs | // Project: Daggerfall Unity
// Copyright: Copyright (C) 2009-2022 Daggerfall Workshop
// Web Site: http://www.dfworkshop.net
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/Interkarma/daggerfall-unity
// Original Author: Hazelnut
// Contributors:
using System.Collections.Generic;
using DaggerfallConnect;
using DaggerfallConnect.Arena2;
using DaggerfallWorkshop.Game.Entity;
using DaggerfallWorkshop.Utility;
using DaggerfallWorkshop.Game.Serialization;
namespace DaggerfallWorkshop.Game.Guilds
{
/// <summary>
/// Guild objects define player rank progression and benefits with the guild.
/// For vanilla style guilds, extend abstract class Guild.cs which defines most
/// of the vanilla base behaviour.
/// </summary>
public interface IGuild : IMacroContextProvider
{
#region Properties
string[] RankTitles { get; }
List<DFCareer.Skills> GuildSkills { get; }
List<DFCareer.Skills> TrainingSkills { get; }
#endregion
#region Guild Ranks
int Rank { get; set; }
void ImportLastRankChange(uint timeOfLastRankChange);
TextFile.Token[] UpdateRank(PlayerEntity playerEntity);
TextFile.Token[] TokensPromotion(int newRank);
TextFile.Token[] TokensDemotion();
TextFile.Token[] TokensExpulsion();
#endregion
#region Guild Membership and Faction Data
bool IsMember();
int GetFactionId();
int GetReputation(PlayerEntity playerEntity);
string GetGuildName();
string GetAffiliation();
string GetTitle();
#endregion
#region Common Benefits
bool CanRest();
bool HallAccessAnytime();
bool FreeHealing();
bool FreeMagickaRecharge();
int AlterReward(int reward);
int ReducedRepairCost(int price);
int ReducedIdentifyCost(int price);
int ReducedCureCost(int price);
#endregion
#region Special benefits:
bool FreeTavernRooms();
bool FreeShipTravel();
int FastTravel(int duration);
int DeepBreath(int duration);
bool AvoidDeath();
#endregion
#region Service Access:
bool CanAccessLibrary();
bool CanAccessService(GuildServices service);
#endregion
#region Service: Training
int GetTrainingMax(DFCareer.Skills skill);
int GetTrainingPrice();
#endregion
#region Joining
void Join();
void Leave();
bool IsEligibleToJoin(PlayerEntity playerEntity);
TextFile.Token[] TokensIneligible(PlayerEntity playerEntity);
TextFile.Token[] TokensEligible(PlayerEntity playerEntity);
TextFile.Token[] TokensWelcome();
#endregion
#region Serialization
GuildMembership_v1 GetGuildData();
void RestoreGuildData(GuildMembership_v1 data);
#endregion
}
}
| 411 | 0.787791 | 1 | 0.787791 | game-dev | MEDIA | 0.97056 | game-dev | 0.72895 | 1 | 0.72895 |
CalamityTeam/CalamityModPublic | 4,639 | Projectiles/Summon/GhostlyMine.cs | using System;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.Audio;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Projectiles.Summon
{
public class GhostlyMine : ModProjectile, ILocalizedModType
{
public new string LocalizationCategory => "Projectiles.Summon";
public override string Texture => "CalamityMod/Projectiles/Boss/PhantomMine";
public bool start = true;
public bool spawnDust = true;
public override void SetDefaults()
{
Projectile.width = Projectile.height = 30;
Projectile.friendly = true;
Projectile.ignoreWater = true;
Projectile.minionSlots = 0f;
Projectile.timeLeft = 900;
Projectile.penetrate = 1;
Projectile.tileCollide = false;
Projectile.minion = true;
Projectile.DamageType = DamageClass.Summon;
}
public override void AI()
{
Player player = Main.player[Projectile.owner];
if (start)
{
SoundEngine.PlaySound(SoundID.Item20, Projectile.position);
Projectile.ai[1] = Projectile.ai[0];
start = false;
}
double deg = (double)Projectile.ai[1];
double rad = deg * (Math.PI / 180);
double dist = 550;
Projectile.position.X = player.Center.X - (int)(Math.Cos(rad) * dist) - Projectile.width / 2;
Projectile.position.Y = player.Center.Y - (int)(Math.Sin(rad) * dist) - Projectile.height / 2;
Projectile.ai[1] += 1f;
if (spawnDust)
{
for (int i = 0; i < 10; i++)
{
int dust = Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, DustID.DungeonSpirit, 0f, 0f, 100, default, 2f);
Main.dust[dust].velocity *= 3f;
if (Main.rand.NextBool())
{
Main.dust[dust].scale = 0.5f;
Main.dust[dust].fadeIn = 1f + (float)Main.rand.Next(10) * 0.1f;
}
}
for (int j = 0; j < 15; j++)
{
int dust2 = Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, DustID.DungeonSpirit, 0f, 0f, 100, default, 3f);
Main.dust[dust2].noGravity = true;
Main.dust[dust2].velocity *= 5f;
dust2 = Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, DustID.DungeonSpirit, 0f, 0f, 100, default, 2f);
Main.dust[dust2].velocity *= 2f;
}
spawnDust = false;
}
}
public override Color? GetAlpha(Color lightColor)
{
if (Projectile.timeLeft < 85)
{
byte b2 = (byte)(Projectile.timeLeft * 3);
byte a2 = (byte)(100f * ((float)b2 / 255f));
return new Color((int)b2, (int)b2, (int)b2, (int)a2);
}
return new Color(255, 255, 255, 100);
}
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone)
{
Projectile.position = Projectile.Center;
Projectile.width = Projectile.height = 160;
Projectile.position.X = Projectile.position.X - (float)(Projectile.width / 2);
Projectile.position.Y = Projectile.position.Y - (float)(Projectile.height / 2);
SoundEngine.PlaySound(SoundID.Item14, Projectile.position);
for (int i = 0; i < 30; i++)
{
int dust = Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, DustID.DungeonSpirit, 0f, 0f, 100, default, 1.2f);
Main.dust[dust].velocity *= 3f;
if (Main.rand.NextBool())
{
Main.dust[dust].scale = 0.5f;
Main.dust[dust].fadeIn = 1f + (float)Main.rand.Next(10) * 0.1f;
}
}
for (int j = 0; j < 60; j++)
{
int dust2 = Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, DustID.DungeonSpirit, 0f, 0f, 100, default, 1.7f);
Main.dust[dust2].noGravity = true;
Main.dust[dust2].velocity *= 5f;
dust2 = Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, DustID.DungeonSpirit, 0f, 0f, 100, default, 1f);
Main.dust[dust2].velocity *= 2f;
}
}
}
}
| 411 | 0.734786 | 1 | 0.734786 | game-dev | MEDIA | 0.983905 | game-dev | 0.96193 | 1 | 0.96193 |
newagebegins/BattleCity | 1,579 | src/Player.js | function Player() {
this._lives = 2;
this._score = 0;
this.resetTanks();
}
Player.Event = {};
Player.Event.OUT_OF_LIVES = 'Player.Event.OUT_OF_LIVES';
Player.prototype.resetTanks = function () {
this._tanks = {};
this._tanks[Tank.Type.BASIC] = 0;
this._tanks[Tank.Type.FAST] = 0;
this._tanks[Tank.Type.POWER] = 0;
this._tanks[Tank.Type.ARMOR] = 0;
this._tanksCount = 0;
};
Player.prototype.setEventManager = function (eventManager) {
this._eventManager = eventManager;
this._eventManager.addSubscriber(this, [
PointsFactory.Event.POINTS_CREATED,
Tank.Event.PLAYER_DESTROYED,
PowerUpHandler.Event.TANK,
Tank.Event.ENEMY_DESTROYED
]);
};
Player.prototype.notify = function (event) {
if (event.name == PointsFactory.Event.POINTS_CREATED) {
this._score += event.points.getValue();
}
else if (event.name == Tank.Event.PLAYER_DESTROYED) {
if (this._lives == 0) {
this._eventManager.fireEvent({'name': Player.Event.OUT_OF_LIVES});
}
else {
this._lives--;
}
}
else if (event.name == PowerUpHandler.Event.TANK) {
this._lives++;
}
else if (event.name == Tank.Event.ENEMY_DESTROYED) {
if (event.tank.getValue() > 0) {
this._tanks[event.tank.getType()]++;
this._tanksCount++;
}
}
};
Player.prototype.getScore = function () {
return this._score;
};
Player.prototype.getLives = function () {
return this._lives;
};
Player.prototype.getTanks = function (type) {
return this._tanks[type];
};
Player.prototype.getTanksCount = function () {
return this._tanksCount;
};
| 411 | 0.544786 | 1 | 0.544786 | game-dev | MEDIA | 0.98798 | game-dev | 0.767461 | 1 | 0.767461 |
plooshi/CelestiaGS | 2,539 | SDK/Athena_Prop_BP_TRV_tall_shelf_01_classes.hpp | #pragma once
/*
* SDK generated by Dumper-7
*
* https://github.com/Encryqed/Dumper-7
*/
// Package: Athena_Prop_BP_TRV_tall_shelf_01
#include "Basic.hpp"
#include "Engine_structs.hpp"
#include "FortniteGame_classes.hpp"
namespace SDK
{
// BlueprintGeneratedClass Athena_Prop_BP_TRV_tall_shelf_01.Athena_Prop_BP_TRV_tall_shelf_01_C
// 0x0018 (0x0BD8 - 0x0BC0)
class AAthena_Prop_BP_TRV_tall_shelf_01_C final : public ABuildingProp
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0BC0(0x0008)(ZeroConstructor, Transient, DuplicateTransient)
class UAudioComponent* Sound_Flies; // 0x0BC8(0x0008)(BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData, NonTransactional, NoDestructor, HasGetValueTypeHash)
class UParticleSystemComponent* Flies; // 0x0BD0(0x0008)(Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
public:
void ExecuteUbergraph_Athena_Prop_BP_TRV_tall_shelf_01(int32 EntryPoint);
void ReceiveDestroyed();
void ReceiveBeginPlay();
void OnDamagePlayEffects(float Damage, const struct FGameplayTagContainer& DamageTags, const struct FVector& Momentum, const struct FHitResult& HitInfo, class AFortPawn* InstigatedBy, class AActor* DamageCauser, const struct FGameplayEffectContextHandle& EffectContext);
public:
static class UClass* StaticClass()
{
return StaticBPGeneratedClassImpl<"Athena_Prop_BP_TRV_tall_shelf_01_C">();
}
static class AAthena_Prop_BP_TRV_tall_shelf_01_C* GetDefaultObj()
{
return GetDefaultObjImpl<AAthena_Prop_BP_TRV_tall_shelf_01_C>();
}
};
static_assert(alignof(AAthena_Prop_BP_TRV_tall_shelf_01_C) == 0x000008, "Wrong alignment on AAthena_Prop_BP_TRV_tall_shelf_01_C");
static_assert(sizeof(AAthena_Prop_BP_TRV_tall_shelf_01_C) == 0x000BD8, "Wrong size on AAthena_Prop_BP_TRV_tall_shelf_01_C");
static_assert(offsetof(AAthena_Prop_BP_TRV_tall_shelf_01_C, UberGraphFrame) == 0x000BC0, "Member 'AAthena_Prop_BP_TRV_tall_shelf_01_C::UberGraphFrame' has a wrong offset!");
static_assert(offsetof(AAthena_Prop_BP_TRV_tall_shelf_01_C, Sound_Flies) == 0x000BC8, "Member 'AAthena_Prop_BP_TRV_tall_shelf_01_C::Sound_Flies' has a wrong offset!");
static_assert(offsetof(AAthena_Prop_BP_TRV_tall_shelf_01_C, Flies) == 0x000BD0, "Member 'AAthena_Prop_BP_TRV_tall_shelf_01_C::Flies' has a wrong offset!");
}
| 411 | 0.606073 | 1 | 0.606073 | game-dev | MEDIA | 0.960303 | game-dev | 0.590593 | 1 | 0.590593 |
oguzeroglu/ROYGBIV | 1,659 | js/engine_objects/ParticleSystemPool.js | var ParticleSystemPool = function(name){
this.isParticleSystemPool = true;
this.name = name;
this.particleSystems = new Object();
this.availableParticleSystems = new Map();
}
ParticleSystemPool.prototype.add = function(particleSystem){
this.particleSystems[particleSystem.name] = particleSystem;
if (!particleSystem.mesh.visible){
this.availableParticleSystems.set(particleSystem.name, particleSystem);
}
particleSystem.psPool = this.name;
}
ParticleSystemPool.prototype.get = function(){
if (this.availableParticleSystems.size == 0 || this.registeredSceneName != sceneHandler.getActiveSceneName()){
return false;
}
var ps = this.availableParticleSystems.values().next().value;
this.availableParticleSystems.delete(ps.name);
if (this.consumedCallback && this.availableParticleSystems.size == 0){
this.consumedCallback();
}
return ps;
}
ParticleSystemPool.prototype.remove = function(particleSystem){
delete this.particleSystems[particleSystem.name];
this.availableParticleSystems.delete(particleSystem.name);
delete particleSystem.psPool;
}
ParticleSystemPool.prototype.destroy = function(){
for (var psName in this.particleSystems){
delete this.particleSystems[psName].psPool;
delete this.particleSystems[psName];
this.availableParticleSystems.delete(psName);
}
delete particleSystemPools[this.name];
this.destroyed = true;
}
ParticleSystemPool.prototype.notifyPSAvailable = function(particleSystem){
this.availableParticleSystems.set(particleSystem.name, particleSystem);
if (this.availableCallback && this.availableParticleSystems.size == 1){
this.availableCallback();
}
}
| 411 | 0.647996 | 1 | 0.647996 | game-dev | MEDIA | 0.907364 | game-dev | 0.52269 | 1 | 0.52269 |
wormtql/genshin_artifact | 1,402 | mona_core/src/buffs/buffs/common/critical_damage.rs | use crate::attribute::{Attribute, AttributeName};
use crate::buffs::{Buff, BuffConfig};
use crate::buffs::buff::BuffMeta;
use crate::buffs::buff_meta::{BuffFrom, BuffGenre, BuffImage, BuffMetaData};
use crate::buffs::buff_name::BuffName;
use crate::common::item_config_type::ItemConfig;
use crate::enemies::Enemy;
pub struct BuffCriticalDamage {
pub value: f64,
}
impl<A: Attribute> Buff<A> for BuffCriticalDamage {
fn change_attribute(&self, attribute: &mut A) {
attribute.set_value_by(AttributeName::CriticalDamageBase, "BUFF: 暴击伤害", self.value);
}
}
impl BuffMeta for BuffCriticalDamage {
#[cfg(not(target_family = "wasm"))]
const META_DATA: BuffMetaData = BuffMetaData {
name: BuffName::CriticalDamage,
name_locale: crate::common::i18n::locale!(
zh_cn: "暴击伤害",
en: "Crit DMG",
),
image: BuffImage::Misc("sword"),
genre: BuffGenre::Common,
description: None,
from: BuffFrom::Common
};
#[cfg(not(target_family = "wasm"))]
const CONFIG: Option<&'static [ItemConfig]> = Some(&[
ItemConfig::BUFFV1P
]);
fn create<A: Attribute>(b: &BuffConfig) -> Box<dyn Buff<A>> {
let value = match *b {
BuffConfig::CriticalDamage { p } => p / 100.0,
_ => 0.0
};
Box::new(BuffCriticalDamage {
value
})
}
}
| 411 | 0.777235 | 1 | 0.777235 | game-dev | MEDIA | 0.158659 | game-dev | 0.687927 | 1 | 0.687927 |
Cloudhunter/OpenCCSensors | 3,233 | src/main/java/openccsensors/common/util/AppliedEnergisticsUtils.java | package openccsensors.common.util;
import java.util.HashMap;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
import appeng.api.AEApi;
import appeng.api.networking.IGridBlock;
import appeng.api.networking.IGridNode;
import appeng.api.networking.energy.IEnergyGrid;
import appeng.api.storage.ICellInventory;
import appeng.api.storage.IMEInventory;
import appeng.api.storage.IMEInventoryHandler;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IAEStack;
import appeng.api.storage.data.IItemList;
public class AppliedEnergisticsUtils {
private static final String ME_WIRELESS_CLASS = "appeng.me.tile.TileWireless";
public static boolean isValidTarget(Object target) {
return target != null && target.getClass().getName() == ME_WIRELESS_CLASS;
}
public static HashMap getTileDetails(Object obj, boolean additional) {
HashMap response = new HashMap();
if (!(obj instanceof TileEntity)) {
return response;
}
TileEntity aeWirelessAPtileEntity = (TileEntity) obj;
response.put("Powered", false);
IGridBlock aeMachine = (IGridBlock) aeWirelessAPtileEntity;
IGridNode gi = aeMachine.getMachine().getGridNode(ForgeDirection.UNKNOWN);
if (aeMachine instanceof IEnergyGrid && ((IEnergyGrid)aeMachine).isNetworkPowered() && aeMachine instanceof IMEInventoryHandler) {
IMEInventoryHandler imivh = (IMEInventoryHandler) aeMachine;
IMEInventory imiv = (IMEInventory) imivh;
IEnergyGrid eGrid = (IEnergyGrid) aeMachine;
response.put("Powered",true);
if (imiv instanceof ICellInventory) {
//uses ICellInventory for remaining item types and count.
ICellInventory cells = (ICellInventory) imiv;
response.put("FreeTypes", (int) cells.getRemainingItemTypes());
response.put("FreeCount", (int) cells.getRemainingItemCount());
response.put("FreeBytes", (int) cells.getFreeBytes());
long usedBytes = cells.getUsedBytes();
long totalBytes = cells.getTotalBytes();
response.put("UsedBytes", (int) usedBytes);
response.put("TotalBytes", (int) totalBytes);
double percent = (double)100 / totalBytes * usedBytes;
percent = Math.max(Math.min(percent, 100), 0);
response.put("InventoryPercentFull", percent);
response.put("CanHoldNewItems", cells.canHoldNewItem());
}
if (additional) {
IItemList list = AEApi.instance().storage().createItemList();
imiv.getAvailableItems(list);
int totalCount = 0;
int i = 0;
HashMap stacks = new HashMap();
Iterable<IAEStack> iterator = (Iterable<IAEStack>)list.iterator();
for (IAEStack stack : iterator) {
if (stack.isItem()) {
IAEItemStack itemStack = (IAEItemStack) stack;
ItemStack items = itemStack.getItemStack();
stacks.put(i++, InventoryUtils.itemstackToMap(items));
totalCount += items.stackSize;
}
};
response.put("UsedTypes", list.size());
response.put("UsedCount", totalCount);
response.put("Slots", stacks);
response.put("Priority", imivh.getPriority());
response.put("SystemPower", eGrid.getAvgPowerUsage());
}
}
return response;
}
}
| 411 | 0.851077 | 1 | 0.851077 | game-dev | MEDIA | 0.86538 | game-dev | 0.962771 | 1 | 0.962771 |
chrisboyle/sgtpuzzles | 5,914 | app/src/main/jni/nullgame.c | /*
* nullgame.c [FIXME]: Template defining the null game (in which no
* moves are permitted and nothing is ever drawn). This file exists
* solely as a basis for constructing new game definitions - it
* helps to have something which will compile from the word go and
* merely doesn't _do_ very much yet.
*
* Parts labelled FIXME actually want _removing_ (e.g. the dummy
* field in each of the required data structures, and this entire
* comment itself) when converting this source file into one
* describing a real game.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#ifdef NO_TGMATH_H
# include <math.h>
#else
# include <tgmath.h>
#endif
#include "puzzles.h"
enum {
COL_BACKGROUND,
NCOLOURS
};
struct game_params {
int FIXME;
};
struct game_state {
int FIXME;
};
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
ret->FIXME = 0;
return ret;
}
static bool game_fetch_preset(int i, char **name, game_params **params)
{
return false;
}
static void free_params(game_params *params)
{
sfree(params);
}
static game_params *dup_params(const game_params *params)
{
game_params *ret = snew(game_params);
*ret = *params; /* structure copy */
return ret;
}
static void decode_params(game_params *params, char const *string)
{
}
static char *encode_params(const game_params *params, bool full)
{
return dupstr("FIXME");
}
static const char *validate_params(const game_params *params, bool full)
{
return NULL;
}
static char *new_game_desc(const game_params *params, random_state *rs,
char **aux, bool interactive)
{
return dupstr("FIXME");
}
static const char *validate_desc(const game_params *params, const char *desc)
{
return NULL;
}
static game_state *new_game(midend *me, const game_params *params,
const char *desc)
{
game_state *state = snew(game_state);
state->FIXME = 0;
return state;
}
static game_state *dup_game(const game_state *state)
{
game_state *ret = snew(game_state);
ret->FIXME = state->FIXME;
return ret;
}
static void free_game(game_state *state)
{
sfree(state);
}
static game_ui *new_ui(const game_state *state)
{
return NULL;
}
static void free_ui(game_ui *ui)
{
}
static void game_changed_state(game_ui *ui, const game_state *oldstate,
const game_state *newstate)
{
}
struct game_drawstate {
int tilesize;
int FIXME;
};
static char *interpret_move(const game_state *state, game_ui *ui,
const game_drawstate *ds,
int x, int y, int button)
{
return NULL;
}
static game_state *execute_move(const game_state *state, const char *move)
{
return NULL;
}
/* ----------------------------------------------------------------------
* Drawing routines.
*/
static void game_compute_size(const game_params *params, int tilesize,
const game_ui *ui, int *x, int *y)
{
*x = *y = 10 * tilesize; /* FIXME */
}
static void game_set_size(drawing *dr, game_drawstate *ds,
const game_params *params, int tilesize)
{
ds->tilesize = tilesize;
}
static float *game_colours(frontend *fe, int *ncolours)
{
float *ret = snewn(3 * NCOLOURS, float);
frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
*ncolours = NCOLOURS;
return ret;
}
static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
{
struct game_drawstate *ds = snew(struct game_drawstate);
ds->tilesize = 0;
ds->FIXME = 0;
return ds;
}
static void game_free_drawstate(drawing *dr, game_drawstate *ds)
{
sfree(ds);
}
static void game_redraw(drawing *dr, game_drawstate *ds,
const game_state *oldstate, const game_state *state,
int dir, const game_ui *ui,
float animtime, float flashtime)
{
}
static float game_anim_length(const game_state *oldstate,
const game_state *newstate, int dir, game_ui *ui)
{
return 0.0F;
}
static float game_flash_length(const game_state *oldstate,
const game_state *newstate, int dir, game_ui *ui)
{
return 0.0F;
}
static void game_get_cursor_location(const game_ui *ui,
const game_drawstate *ds,
const game_state *state,
const game_params *params,
int *x, int *y, int *w, int *h)
{
}
static int game_status(const game_state *state)
{
return 0;
}
#ifdef COMBINED
#define thegame nullgame
#endif
const struct game thegame = {
"Null Game", NULL, NULL,
default_params,
game_fetch_preset, NULL,
decode_params,
encode_params,
free_params,
dup_params,
false, NULL, NULL, /* configure, custom_params */
validate_params,
new_game_desc,
validate_desc,
new_game,
dup_game,
free_game,
false, NULL, /* solve */
false, NULL, NULL, /* can_format_as_text_now, text_format */
NULL, NULL, /* get_prefs, set_prefs */
new_ui,
free_ui,
NULL, /* encode_ui */
NULL, /* decode_ui */
NULL, /* game_request_keys */
game_changed_state,
NULL, /* current_key_label */
interpret_move,
execute_move,
20 /* FIXME */, game_compute_size, game_set_size,
game_colours,
game_new_drawstate,
game_free_drawstate,
game_redraw,
game_anim_length,
game_flash_length,
game_get_cursor_location,
game_status,
#ifndef NO_PRINTING
false, false, NULL, NULL, /* print_size, print */
#endif
false, /* wants_statusbar */
false, NULL, /* timing_state */
0, /* flags */
};
| 411 | 0.816277 | 1 | 0.816277 | game-dev | MEDIA | 0.751062 | game-dev | 0.564593 | 1 | 0.564593 |
magemonkeystudio/fabled | 2,777 | src/main/java/studio/magemonkey/fabled/dynamic/mechanic/RememberTargetsMechanic.java | /**
* Fabled
* studio.magemonkey.fabled.dynamic.mechanic.RememberTargetsMechanic
* <p>
* The MIT License (MIT)
* <p>
* Copyright (c) 2024 MageMonkeyStudio
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p>
* 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 studio.magemonkey.fabled.dynamic.mechanic;
import org.bukkit.entity.LivingEntity;
import studio.magemonkey.fabled.api.CastData;
import studio.magemonkey.fabled.dynamic.DynamicSkill;
import java.util.List;
/**
* Applies a flag to each target
*/
public class RememberTargetsMechanic extends MechanicComponent {
private static final String KEY = "key";
private static final String OVERWRITE = "overwrite";
@Override
public String getKey() {
return "remember targets";
}
/**
* Executes the component
*
* @param caster caster of the skill
* @param level level of the skill
* @param targets targets to apply to
* @param force
* @return true if applied to something, false otherwise
*/
@Override
public boolean execute(LivingEntity caster, int level, List<LivingEntity> targets, boolean force) {
if (targets.isEmpty() || !settings.has(KEY)) {
return false;
}
String key = settings.getString(KEY);
boolean overwrite = settings.getBool(OVERWRITE, true);
CastData castData = DynamicSkill.getCastData(caster);
Object rawTargets = castData.getRaw(key);
if (!overwrite && rawTargets instanceof List<?>) {
@SuppressWarnings("unchecked")
List<LivingEntity> originalTargets = (List<LivingEntity>) rawTargets;
originalTargets.addAll(targets);
} else {
castData.put(key, targets);
}
return true;
}
}
| 411 | 0.848654 | 1 | 0.848654 | game-dev | MEDIA | 0.638342 | game-dev | 0.866013 | 1 | 0.866013 |
mechakotik/tails-adventure | 4,042 | src/objects/walker.cpp | #include "walker.h"
#include "dead_kukku.h"
#include "tilemap.h"
#include "tools.h"
void TA_Walker::load(TA_Point newPosition, int range, bool flip) {
loadFromToml("objects/pf_enemies.toml");
hitbox.setRectangle(TA_Point(5, 0), TA_Point(18, 26));
collisionType = TA_COLLISION_DAMAGE | TA_COLLISION_TARGET;
position = newPosition;
direction = flip;
if(range <= 0) {
alwaysIdle = true;
} else {
if(!flip) {
rangeLeft = position.x;
rangeRight = position.x + range;
} else {
rangeLeft = position.x - range;
rangeRight = position.x;
}
}
updatePosition();
}
bool TA_Walker::update() {
switch(state) {
case TA_WALKER_STATE_IDLE:
updateIdle();
break;
case TA_WALKER_STATE_MOVE:
updateMove();
break;
case TA_WALKER_STATE_FIRE:
updateFire();
break;
case TA_WALKER_STATE_MOVE_AWAY:
updateMoveAway();
break;
}
setPosition(position);
setFlip(!direction);
hitbox.setPosition(position);
int flags;
objectSet->checkCollision(hitbox, flags);
if(flags & TA_COLLISION_ATTACK) {
objectSet->spawnObject<TA_DeadKukku>(position);
objectSet->resetInstaShield();
return false;
}
return true;
}
void TA_Walker::updateIdle() {
setAnimation("walker_idle");
TA_Point distance = getDistanceToCharacter();
if(abs(distance.x) <= 140 && abs(distance.y) <= 90) {
state = TA_WALKER_STATE_MOVE;
}
}
void TA_Walker::updateMove() {
if(alwaysIdle) {
setAnimation("walker_idle");
} else {
setAnimation("walker");
if(!direction) {
position.x += speed * TA::elapsedTime;
if(position.x > rangeRight) {
direction = true;
}
} else {
position.x -= speed * TA::elapsedTime;
if(position.x < rangeLeft) {
direction = false;
}
}
}
TA_Point distance = getDistanceToCharacter();
if(direction == (distance.x < 0) && abs(distance.x) <= 64 && abs(distance.y) <= 16) {
state = TA_WALKER_STATE_FIRE;
timer = 0;
}
}
void TA_Walker::updateFire() {
if(!alwaysIdle && timer < standTime) {
setAnimation("walker_idle");
} else {
setAnimation("walker_fire");
}
timer += TA::elapsedTime;
if(timer > fireTime) {
objectSet->spawnObject<TA_WalkerBullet>(position + TA_Point((direction ? -1 : 16), 16), direction);
state = TA_WALKER_STATE_MOVE_AWAY;
}
}
void TA_Walker::updateMoveAway() {
if(alwaysIdle) {
state = TA_WALKER_STATE_MOVE;
return;
}
setAnimation("walker");
if(!direction) {
position.x -= speed * TA::elapsedTime;
if(position.x < rangeLeft) {
state = TA_WALKER_STATE_MOVE;
}
} else {
position.x += speed * TA::elapsedTime;
if(position.x > rangeRight) {
state = TA_WALKER_STATE_MOVE;
}
}
}
TA_Point TA_Walker::getDistanceToCharacter() {
TA_Point centeredPosition = position + TA_Point(12, 16);
TA_Point characterPosition = objectSet->getCharacterPosition();
return characterPosition - centeredPosition;
}
void TA_WalkerBullet::load(TA_Point newPosition, bool newDirection) {
TA_Sprite::load("objects/walker_bullet.png");
position = newPosition;
direction = newDirection;
hitbox.setRectangle(TA_Point(0, 0), TA_Point(7, 7));
collisionType = TA_COLLISION_DAMAGE;
}
bool TA_WalkerBullet::update() {
if(direction) {
position.x -= speed * TA::elapsedTime;
} else {
position.x += speed * TA::elapsedTime;
}
setPosition(position);
hitbox.setPosition(position);
int flags;
objectSet->checkCollision(hitbox, flags);
if((flags & TA_COLLISION_SOLID) || (flags & TA_COLLISION_SOLID_UP)) {
return false;
}
return true;
}
| 411 | 0.986587 | 1 | 0.986587 | game-dev | MEDIA | 0.965147 | game-dev | 0.996905 | 1 | 0.996905 |
anoyetta/ACT.Hojoring | 5,879 | source/ACT.TTSYukkuri/ACT.TTSYukkuri.Core/FFXIVWatcher.cs | using ACT.TTSYukkuri.Config;
using FFXIV.Framework.Bridge;
using FFXIV.Framework.Common;
using FFXIV.Framework.XIVHelper;
using NLog;
using System;
using System.Threading;
namespace ACT.TTSYukkuri
{
/// <summary>
/// スピークdelegate
/// </summary>
/// <param name="textToSpeak"></param>
public delegate void Speak(string textToSpeak, PlayDevices playDevice = PlayDevices.Both, VoicePalettes play = VoicePalettes.Default, bool isSync = false, float? volume = null);
/// <summary>
/// FF14を監視する
/// </summary>
public partial class FFXIVWatcher
{
#region Logger
private Logger Logger => AppLog.DefaultLogger;
#endregion Logger
private const int WatcherInterval = 400;
private const int WatcherLongInterval = 5000;
/// <summary>
/// シングルトンインスタンス
/// </summary>
private static FFXIVWatcher instance;
/// <summary>
/// ロックオブジェクト
/// </summary>
private static object lockObject = new object();
private volatile bool isRunning = false;
private ThreadWorker watchWorker;
/// <summary>
/// シングルトンインスタンス
/// </summary>
public static FFXIVWatcher Default
{
get
{
FFXIVWatcher.Initialize();
return instance;
}
}
/// <summary>
/// スピークdelegate
/// </summary>
public Speak SpeakDelegate { get; set; }
/// <summary>
/// 後片付けをする
/// </summary>
public static void Deinitialize()
{
lock (lockObject)
{
if (instance != null)
{
instance.watchWorker?.Abort(10);
instance.isRunning = false;
instance = null;
}
}
}
/// <summary>
/// 初期化する
/// </summary>
public static void Initialize()
{
lock (lockObject)
{
if (instance != null)
{
instance.Start(); // instance作成直後はStartに成功しないことがあるのでInitializeを呼び出すたびにStartを試みる
return;
}
instance = new FFXIVWatcher();
instance.Start();
}
}
/// <summary>
/// スピーク
/// </summary>
/// <param name="textToSpeak">喋る文字列</param>
public void Speak(
string textToSpeak,
PlayDevices device = PlayDevices.Both,
bool isSync = false) =>
Speak(textToSpeak, device, VoicePalettes.Default, isSync);
/// <summary>
/// スピーク
/// </summary>
/// <param name="textToSpeak">喋る文字列</param>
public void Speak(
string textToSpeak,
PlayDevices device = PlayDevices.Both,
VoicePalettes voicePalette = VoicePalettes.Default,
bool isSync = false) =>
this.SpeakDelegate?.Invoke(textToSpeak, device, voicePalette, isSync);
public void Start()
{
lock (lockObject)
{
if (this.watchWorker == null)
{
this.watchWorker = new ThreadWorker(
this.WatchCore,
WatcherInterval,
"TTSYukkuri Status Subscriber",
ThreadPriority.Lowest);
}
if (Settings.Default.StatusAlertSettings.EnabledHPAlert ||
Settings.Default.StatusAlertSettings.EnabledMPAlert ||
Settings.Default.StatusAlertSettings.EnabledTPAlert ||
Settings.Default.StatusAlertSettings.EnabledGPAlert)
{
if (!this.isRunning)
{
this.isRunning = true;
this.watchWorker.Run();
}
}
}
}
public void Stop()
{
lock (lockObject)
{
if (!Settings.Default.StatusAlertSettings.EnabledHPAlert &&
!Settings.Default.StatusAlertSettings.EnabledMPAlert &&
!Settings.Default.StatusAlertSettings.EnabledTPAlert &&
!Settings.Default.StatusAlertSettings.EnabledGPAlert)
{
if (this.watchWorker != null)
{
this.isRunning = false;
this.watchWorker.Abort();
this.watchWorker = null;
}
}
}
}
/// <summary>
/// 監視の中核
/// </summary>
private void WatchCore()
{
try
{
// FF14Processがなければ何もしない
if (XIVPluginHelper.Instance.CurrentFFXIVProcess == null ||
XIVPluginHelper.Instance.CurrentFFXIVProcess.HasExited)
{
Thread.Sleep(WatcherLongInterval);
return;
}
// オプションが全部OFFならば何もしない
if (!Settings.Default.StatusAlertSettings.EnabledHPAlert &&
!Settings.Default.StatusAlertSettings.EnabledMPAlert &&
!Settings.Default.StatusAlertSettings.EnabledTPAlert &&
!Settings.Default.StatusAlertSettings.EnabledGPAlert)
{
Thread.Sleep(WatcherLongInterval);
return;
}
// パーティメンバの監視を行う
this.WatchParty();
}
catch (Exception)
{
Thread.Sleep(WatcherLongInterval);
throw;
}
}
}
}
| 411 | 0.802968 | 1 | 0.802968 | game-dev | MEDIA | 0.773451 | game-dev | 0.95837 | 1 | 0.95837 |
HaliteChallenge/Halite-III | 3,267 | starter_kits/OCaml/game.ml | (* OCaml Starter for Halite III on Halite.io
This code is public domain. There is no warranty.
*)
open Type;;
let time_seconds_elapsed_this_turn state =
Unix.gettimeofday () -. state.last_update
;;
let wrap_position state (row, col) =
let wr =
if row < 0 then
row + state.height
else if row >= state.height then
row - state.height
else row
in
let wc =
if col < 0 then
col + state.width
else if col >= state.width then
col - state.width
else col
in
wr, wc
;;
let add_position (r1, c1) (r2, c2) =
(r1 + r2), (c1 + c2)
;;
let subtract_position (r1, c1) (r2, c2) =
(r1 - r2), (c1 - c2)
;;
let dir_offset = function
| North -> (-1, 0)
| East -> (0, 1)
| South -> (1, 0)
| West -> (0, -1)
| Still -> (0, 0)
;;
let directional_offset_position state position direction =
wrap_position state (add_position position (dir_offset direction))
;;
let abs_position (r, c) = (abs r, abs c);;
(* this logic was copied over from the Python starter, it has not been tested *)
let calculate_distance state source target =
let source' = wrap_position state source in
let target' = wrap_position state target in
let row, col = abs_position (subtract_position source' target') in
(min row (state.height - row)) + (min col (state.width - col))
;;
let ships_of_player state player =
List.filter (fun entity ->
entity.owner = player
) state.ships
;;
let my_ships state =
ships_of_player state state.my_id
;;
let int_to_dir = function
| 0 -> North
| 1 -> East
| 2 -> South
| 3 -> West
| _ -> Still
;;
let random_nonstill_dir () =
int_to_dir (Random.int 4)
;;
let my_halite state =
state.energy.(state.my_id)
;;
let get_shipyard state player =
List.find (fun entity ->
entity.owner = player
) state.shipyards
;;
let shipyard_occupied state player =
try (
let shipyard = get_shipyard state player in
let result = (List.exists (fun ship ->
ship.position = shipyard.position
) state.ships)
in
result
)
with e ->
Debug.debug (Printexc.to_string e);
true
;;
let new_constant_set () = {
capture_enabled = false;
capture_radius = 0;
default_map_height = 0;
default_map_width = 0;
dropoff_cost = 0;
dropoff_penalty_ratio = 0;
extract_ratio = 0;
factor_exp_1 = 0.0;
factor_exp_2 = 0.0;
initial_energy = 0;
inspiration_enabled = false;
inspiration_radius = 0;
inspiration_ship_count = 0;
inspired_bonus_multiplier = 0.0;
inspired_extract_ratio = 0;
inspired_move_cost_ratio = 0;
max_cell_production = 0;
max_energy = 0;
max_players = 0;
max_turns = 0;
max_turn_threshold = 0;
min_cell_production = 0;
min_turns = 0;
min_turn_threshold = 0;
move_cost_ratio = 0;
new_entity_energy_cost = 0;
persistence = 0.0;
ships_above_for_capture = 0;
strict_errors = false;
game_seed = 0
};;
let new_state () = {
tokens = [];
num_players = 0;
my_id = -1;
width = 1;
height = 1;
map = [||];
shipyards = [];
ships = [];
dropoffs = [];
energy = [||];
turn = -1;
last_update = Unix.gettimeofday();
persist = {
magicNumber = 42;
magicList = [];
previous_state = None;
previous_commands = None;
};
const = new_constant_set();
};;
| 411 | 0.708927 | 1 | 0.708927 | game-dev | MEDIA | 0.229474 | game-dev | 0.921747 | 1 | 0.921747 |
QuestionableM/SM-ProximityVoiceChat | 2,739 | Dependencies/bullet3/BulletCollision/Gimpact/btQuantization.h | #ifndef BT_GIMPACT_QUANTIZATION_H_INCLUDED
#define BT_GIMPACT_QUANTIZATION_H_INCLUDED
/*! \file btQuantization.h
*\author Francisco Leon Najera
*/
/*
This source file is part of GIMPACT Library.
For the latest info, see http://gimpact.sourceforge.net/
Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371.
email: projectileman@yahoo.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "LinearMath/btTransform.h"
SIMD_FORCE_INLINE void bt_calc_quantization_parameters(
btVector3& outMinBound,
btVector3& outMaxBound,
btVector3& bvhQuantization,
const btVector3& srcMinBound, const btVector3& srcMaxBound,
btScalar quantizationMargin)
{
//enlarge the AABB to avoid division by zero when initializing the quantization values
btVector3 clampValue(quantizationMargin, quantizationMargin, quantizationMargin);
outMinBound = srcMinBound - clampValue;
outMaxBound = srcMaxBound + clampValue;
btVector3 aabbSize = outMaxBound - outMinBound;
bvhQuantization = btVector3(btScalar(65535.0),
btScalar(65535.0),
btScalar(65535.0)) /
aabbSize;
}
SIMD_FORCE_INLINE void bt_quantize_clamp(
unsigned short* out,
const btVector3& point,
const btVector3& min_bound,
const btVector3& max_bound,
const btVector3& bvhQuantization)
{
btVector3 clampedPoint(point);
clampedPoint.setMax(min_bound);
clampedPoint.setMin(max_bound);
btVector3 v = (clampedPoint - min_bound) * bvhQuantization;
out[0] = (unsigned short)(v.getX() + 0.5f);
out[1] = (unsigned short)(v.getY() + 0.5f);
out[2] = (unsigned short)(v.getZ() + 0.5f);
}
SIMD_FORCE_INLINE btVector3 bt_unquantize(
const unsigned short* vecIn,
const btVector3& offset,
const btVector3& bvhQuantization)
{
btVector3 vecOut;
vecOut.setValue(
(btScalar)(vecIn[0]) / (bvhQuantization.getX()),
(btScalar)(vecIn[1]) / (bvhQuantization.getY()),
(btScalar)(vecIn[2]) / (bvhQuantization.getZ()));
vecOut += offset;
return vecOut;
}
#endif // BT_GIMPACT_QUANTIZATION_H_INCLUDED
| 411 | 0.948555 | 1 | 0.948555 | game-dev | MEDIA | 0.874738 | game-dev | 0.989771 | 1 | 0.989771 |
lgf196/ant-simple-pro | 1,434 | vue/src/utils/tsx-helper.ts | import { Slots, Component, createApp } from 'vue'
import { isFunc } from '@/utils/type'
/**
* @description 获取 slot
*/
export function getSlot(slots: Slots, slot = 'default', data?: unknown) {
if (!slots || !Reflect.has(slots, slot)) {
return null
}
if (!isFunc(slots[slot])) {
console.error(`${slot} is not a function!`)
return null
}
const slotFn = slots[slot]
if (!slotFn) {
return null
}
return slotFn(data)
}
/**
* extends slots
* @param slots
* @param excludeKeys
*/
export function extendSlots(slots: Slots, excludeKeys: string[] = []) {
const slotKeys = Object.keys(slots)
const ret: Record<string, unknown> = {}
slotKeys.map(key => {
if (excludeKeys.includes(key)) {
return null
}
ret[key] = () => getSlot(slots, key)
})
return ret
}
// Get events on attrs
export function getListeners(attrs: Record<string, unknown>) {
const listeners: Record<string, unknown> = {}
Object.keys(attrs).forEach(key => {
if (/^on/.test(key)) {
listeners[key] = attrs[key]
}
})
return listeners
}
export function mountComponent(RootComponent: Component, className = '') {
const app = createApp(RootComponent)
const root = document.createElement('div')
root.className = className
document.body.appendChild(root)
return {
instance: app.mount(root),
unmount() {
app.unmount(root)
document.body.removeChild(root)
}
}
}
| 411 | 0.927103 | 1 | 0.927103 | game-dev | MEDIA | 0.368149 | game-dev | 0.937302 | 1 | 0.937302 |
BeamMP/BeamMP | 10,913 | lua/vehicle/extensions/BeamMP/velocityVE.lua | -- Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
-- Licensed under AGPL-3.0 (or later), see <https://www.gnu.org/licenses/>.
-- SPDX-License-Identifier: AGPL-3.0-or-later
local M = {}
local abs = math.abs
local min = math.min
local max = math.max
local maxBeamLengthRatio = 2 -- If a beam becomes longer than its original length by this factor, it will be treated as broken
local damageThreshold = 100 -- Recalculate center of gravity if beamstate.damage changes by more than this amount
local damageDelay = 0.2 -- How long to wait before recalculating connected nodes or COG after the car was damaged
local connectedNodes = {}
local nodes = {}
local disconnectedNodes = {}
local parentNode = nil
local beamsChanged = false
local lastDamage = 0
local damageTimer = 0
local physicsFPS = 0
M.cogRel = vec3(0,0,0)
local refNode = v.data.refNodes[0].ref
-- Calculate center of gravity from connected nodes
local function calcCOG()
--print("Calculating COG "..obj:getId())
local totalMass = 0
local cog = vec3(0,0,0)
for i = 1, #nodes do
local node = nodes[i]
local nid = node[1]
local nodeMass = node[2]
local nodePos = obj:getNodePosition(nid)
cog:setAdd(nodePos*nodeMass)
totalMass = totalMass + nodeMass
end
cog:setScaled(1/totalMass)
local rot = quatFromDir(-obj:getDirectionVector(), obj:getDirectionVectorUp())
M.cogRel = cog:rotated(rot:inversed())
end
-- Find all nodes that are connected to the parent node
local function findConnectedNodes()
if not parentNode then return end
--print("Find connected nodes "..obj:getId())
nodes = {}
disconnectedNodes = {}
local nodeStack = {}
local visited = {}
local connected = {}
local stackIdx = 1
nodeStack[1] = parentNode
visited[parentNode] = true
local cog = vec3(0,0,0)
local totalMass = 0
while stackIdx > 0 do
local node = nodeStack[stackIdx]
local nodeMass = obj:getNodeMass(node)
local nodePos = obj:getNodePosition(node)
nodes[#nodes+1] = {node, nodeMass*physicsFPS}
connected[node] = 1
cog:setAdd(nodePos*nodeMass)
totalMass = totalMass + nodeMass
nodeStack[stackIdx] = nil
stackIdx = stackIdx - 1
local conNodes = connectedNodes[node] or {}
for i = 1, #conNodes do
local nid = conNodes[i][1]
if not visited[nid] then
local bid = conNodes[i][2]
if not obj:beamIsBroken(bid) and (obj:getBeamCurLengthRefRatio(bid) < maxBeamLengthRatio) then
stackIdx = stackIdx + 1
nodeStack[stackIdx] = nid
visited[nid] = true
end
end
end
end
local refClusterID = obj:getNodeCluster(refNode)
for cid,_ in pairs(v.data.nodes) do
if not connected[cid] then
if obj:getNodeCluster(cid) == refClusterID then
local nodeMass = obj:getNodeMass(cid)
disconnectedNodes[#disconnectedNodes+1] = {cid, nodeMass*physicsFPS}
end
end
end
cog:setScaled(1/totalMass)
local rot = quatFromDir(-obj:getDirectionVector(), obj:getDirectionVectorUp())
M.cogRel = cog:rotated(rot:inversed())
end
local function onInit()
physicsFPS = obj:getPhysicsFPS() or 2000
-- For each node, store all other nodes that are directly connected to it
connectedNodes = {}
for _, b in pairs(v.data.beams) do
-- exclude types BEAM_PRESSURED, BEAM_LBEAM, and BEAM_SUPPORT
if b.beamType ~= 3 and b.beamType ~= 4 and b.beamType ~= 7 then
if connectedNodes[b.id1] == nil then
connectedNodes[b.id1] = {}
end
if connectedNodes[b.id2] == nil then
connectedNodes[b.id2] = {}
end
table.insert(connectedNodes[b.id1], {b.id2, b.cid})
table.insert(connectedNodes[b.id2], {b.id1, b.cid})
end
end
-- Choose ref node with connected beams as parent node
local refNodes = v.data.refNodes[0]
local refPos = vec3(v.data.nodes[refNodes.ref].pos)
local backPos = vec3(v.data.nodes[refNodes.back].pos) - refPos
local upPos = vec3(v.data.nodes[refNodes.up].pos) - refPos
local leftPos = vec3(v.data.nodes[refNodes.left].pos) - refPos
local cosAng = leftPos:cosAngle(backPos:cross(upPos))
if cosAng < 0 then
log('M', 'onInit', "Misaligned refNodes detected in vehicle "..obj:getId().."! This might cause wrong rotations or instability.")
end
if connectedNodes[refNodes.ref] then
parentNode = refNodes.ref
elseif connectedNodes[refNodes.back] then
parentNode = refNodes.back
elseif connectedNodes[refNodes.left] then
parentNode = refNodes.left
elseif connectedNodes[refNodes.up] then
parentNode = refNodes.up
end
if parentNode then
-- TODO: find less hacky way to get beamBroke events
local beamBroke = powertrain.beamBroke
powertrain.beamBroke = function(id, ...)
local beamType = v.data.beams[id].beamType
if beamType ~= 3 and beamType ~= 4 and beamType ~= 7 then
beamsChanged = true
end
return beamBroke(id, ...)
end
findConnectedNodes()
else
log('M', 'onInit', "Vehicle has no connections to ref nodes! Using all nodes.")
for _, n in pairs(v.data.nodes) do
nodes[#nodes+1] = {n.cid, obj:getNodeMass(n.cid)*physicsFPS}
end
calcCOG()
end
log('M', 'onInit', "velocityVE init, physicsFPS: "..physicsFPS..", parentNode: "..parentNode)
end
local function onReset()
findConnectedNodes()
end
-- Add velocity to vehicle in m/s
-- How it works: Apply enough force to each node, so it accelerates to the target speed in 1 physics tick.
-- Because all nodes accelerate at the same rate, the vehicle will not get ripped apart
-- NOTE: - very high values can cause instability
local function addForce(nodes, x, y, z, isCounterVel)
local mainClusterID = obj:getNodeCluster(refNode)
for i=1, #nodes do
local node = nodes[i]
if node then
if not isCounterVel or obj:getNodeCluster(node[1]) == mainClusterID then
obj:applyForceVector(node[1], float3(x*node[2], y*node[2], z*node[2]))
elseif isCounterVel then
table.remove(disconnectedNodes,i)
end
end
end
end
local function addVelocity(x, y, z)
local connectedNodeCount = #nodes
local disconnectedNodeCount = #disconnectedNodes
if connectedNodeCount < disconnectedNodeCount then
addForce(nodes, x, y, z)
else
obj:applyClusterLinearAngularAccel(refNode,vec3(x, y, z)*physicsFPS, vec3())
addForce(disconnectedNodes, -x, -y, -z, true)
end
end
-- Instantly set vehicle velocity in m/s
local function setVelocity(x, y, z)
local vvel = obj:getVelocity()
addVelocity(x - vvel.x, y - vvel.y, z - vvel.z)
end
-- Add angular velocity to vehicle in rad/s
-- How it works: Calculate node tangential velocity relative to car center of gravity at the desired angular velocity
-- and apply enough force to reach the calculated speed in 1 physics tick.
-- NOTE: - very high values can destroy vehicles (above about 20-30 rad/s for most cars) or cause instability
local function addAngularForce(nodes, x, y, z, pitchAV, rollAV, yawAV, isCounterVel)
local rot = quatFromDir(-vec3(obj:getDirectionVector()), vec3(obj:getDirectionVectorUp()))
local cog = M.cogRel:rotated(rot)
local mainClusterID = obj:getNodeCluster(refNode)
--print("addAngularVelocity: pitchAV: "..pitchAV..", rollAV: "..rollAV..", yawAV: "..yawAV)
for i=1, #nodes do
local node = nodes[i]
if node then
local cid = node[1]
if not isCounterVel or obj:getNodeCluster(cid) == mainClusterID then
local mul = node[2]
local nodePos = obj:getNodePosition(cid)
local posX = nodePos.x - cog.x
local posY = nodePos.y - cog.y
local posZ = nodePos.z - cog.z
-- Calculate linear force from torque axis and node position using vector cross product
-- doing this manually is ~3 times faster than vec3:cross(vec3)
local forceX = (x + posY * yawAV - posZ * rollAV)*mul
local forceY = (y + posZ * pitchAV - posX * yawAV)*mul
local forceZ = (z + posX * rollAV - posY * pitchAV)*mul
obj:applyForceVector(cid, float3(forceX, forceY, forceZ))
elseif isCounterVel then
table.remove(disconnectedNodes,i)
end
end
end
end
local function addAngularVelocity(x, y, z, pitchAV, rollAV, yawAV, onlyAngularVelocity, noCounterVelocity)
local rot = quatFromDir(-vec3(obj:getDirectionVector()), vec3(obj:getDirectionVectorUp()))
local cog = M.cogRel:rotated(rot)
local vel = vec3(x, y, z) - cog:cross(vec3(pitchAV, rollAV, yawAV))
local velMulti = 1
if onlyAngularVelocity then
velMulti = 0
end
local connectedNodeCount = #nodes
local disconnectedNodeCount = #disconnectedNodes
if connectedNodeCount < disconnectedNodeCount then
addAngularForce(nodes, x, y, z, pitchAV, rollAV, yawAV)
local mainClusterID = obj:getNodeCluster(refNode)
for i=1, disconnectedNodeCount do
local node = disconnectedNodes[i]
if node then
if obj:getNodeCluster(node[1]) ~= mainClusterID then
table.remove(disconnectedNodes,i)
end
end
end
else
obj:applyClusterLinearAngularAccel(refNode,vel*physicsFPS*velMulti, -vec3(pitchAV, rollAV, yawAV)*physicsFPS)
if noCounterVelocity then return end -- used on spawn and reset to wait with the counter velocity for a bit so things like logs on the T-series don't slide off
addAngularForce(disconnectedNodes, -x, -y, -z, -pitchAV, -rollAV, -yawAV, true)
end
end
-- Instantly set vehicle angular velocity in rad/s
local function setAngularVelocity(x, y, z, pitchAV, rollAV, yawAV, onlyAngularVelocity, noCounterVelocity)
local rot = quatFromDir(-vec3(obj:getDirectionVector()), vec3(obj:getDirectionVectorUp()))
local cog = M.cogRel:rotated(rot)
local rvel = vec3(pitchAV, rollAV, yawAV)
local vrvel = vec3(obj:getPitchAngularVelocity(), obj:getRollAngularVelocity(), obj:getYawAngularVelocity()):rotated(rot)
local rvelDiff = rvel - vrvel
local vel = vec3(x, y, z)
local vvel = vec3(obj:getVelocity()) + cog:cross(vrvel)
local velDiff = vel - vvel
addAngularVelocity(velDiff.x, velDiff.y, velDiff.z, rvelDiff.x, rvelDiff.y, rvelDiff.z, onlyAngularVelocity, noCounterVelocity)
end
local function updateGFX(dt)
if beamsChanged or abs(beamstate.damage - lastDamage) >= damageThreshold then
damageTimer = damageTimer + dt
if damageTimer >= damageDelay then
if beamsChanged then
findConnectedNodes()
beamsChanged = false
else
calcCOG()
end
lastDamage = beamstate.damage
damageTimer = 0
end
else
damageTimer = 0
end
-- Connected nodes and COG debug
--[[
local vehRot = quatFromDir(-obj:getDirectionVector(), obj:getDirectionVectorUp())
for i = 1, #nodes do
obj.debugDrawProxy:drawNodeSphere(nodes[i][1], 0.03, color(255, 0, 0, 200))
end
obj.debugDrawProxy:drawSphere(0.3, obj:getPosition()+M.cogRel:rotated(vehRot), color(0, 0, 255, 200))
--]]
end
-- public interface
M.onInit = onInit
M.onExtensionLoaded = onInit
M.onReset = onReset
M.updateGFX = updateGFX
M.addVelocity = addVelocity
M.setVelocity = setVelocity
M.addAngularVelocity = addAngularVelocity
M.setAngularVelocity = setAngularVelocity
return M
| 411 | 0.904581 | 1 | 0.904581 | game-dev | MEDIA | 0.563691 | game-dev | 0.97616 | 1 | 0.97616 |
wise-old-man/wise-old-man | 12,240 | server/src/api/modules/efficiency/EfficiencyAlgorithm.ts | import {
Boss,
BOSSES,
BossMetaConfig,
EfficiencyAlgorithmType,
Skill,
SkillMetaBonus,
SkillMetaConfig,
SkillMetaMethod,
SKILLS
} from '../../../types';
import { MAX_SKILL_EXP, REAL_SKILLS, SKILL_EXP_AT_99 } from '../../../utils/shared';
import { roundNumber } from '../../../utils/shared/round-number.util';
enum BonusType {
START,
END
}
class EfficiencyAlgorithm {
public type: EfficiencyAlgorithmType;
public skillMetas: SkillMetaConfig[];
public bossMetas: BossMetaConfig[];
private startBonuses: SkillMetaBonus[];
private endBonuses: SkillMetaBonus[];
private bonusDirectionMap: Map<Skill, Skill[]>;
private maximumEHPMap: Map<Skill, number>;
constructor(type: EfficiencyAlgorithmType, skillMetas: SkillMetaConfig[], bossMetas?: BossMetaConfig[]) {
this.type = type;
this.skillMetas = skillMetas;
this.bossMetas = bossMetas || [];
// Cache the start and end bonus ratios for this algorithm type
this.startBonuses = this.getBonuses(skillMetas, BonusType.START);
this.endBonuses = this.getBonuses(skillMetas, BonusType.END);
// Cache the direction in which bonuses flow from one skill to the other, this allows us to only
// calculate skill time for bonus skills that will actually affect the origin skill. (30x less iterations)
this.bonusDirectionMap = this.getBonusDirectionMap([...this.startBonuses, ...this.endBonuses]);
// Cache the maximum EHP for each skill, this is used to cap some skills that get overtrained
this.maximumEHPMap = this.calculateMaximumEHPMap();
}
calculateEHB(killcountMap: Map<Boss, number>) {
return Array.from(this.calculateEHBMap(killcountMap).values()).reduce((a, c) => a + c, 0);
}
calculateEHP(stats: Map<Skill, number>) {
return this.calculateEHPMap(stats).get(Skill.OVERALL)!;
}
calculateTT200mAll(stats: Map<Skill, number>) {
return this.maximumEHPMap.get(Skill.OVERALL)! - this.calculateEHPMap(stats).get(Skill.OVERALL)!;
}
calculateTTM(stats: Map<Skill, number>) {
const maxedStats = new Map(REAL_SKILLS.map(s => [s, SKILL_EXP_AT_99]));
const cappedStats = new Map(REAL_SKILLS.map(s => [s, Math.min(stats.get(s)!, SKILL_EXP_AT_99)]));
return this.calculateEHP(maxedStats) - this.calculateEHP(cappedStats);
}
calculateEHPMap(stats: Map<Skill, number>) {
// Ensure no skills can be -1 exp
const fixedStats = new Map(stats);
REAL_SKILLS.forEach(skill => fixedStats.set(skill, Math.max(0, stats.get(skill) ?? 0)));
const map = new Map(SKILLS.map(s => [s, 0]));
const startBonusExp = this.calculateBonusExp(fixedStats, BonusType.START);
const endBonusExp = this.calculateBonusExp(fixedStats, BonusType.END);
REAL_SKILLS.forEach(originSkill => {
let timeSum = 0;
const bonusSkills = new Set(this.bonusDirectionMap.get(originSkill) ?? []);
// Some skills' bonus skills also have bonus skills (e.g. wc -> fm -> cooking), so
// to properly calculate WC EHP, we need to account for its effect on FM and Cooking.
// In other words, add Cooking as a "bonus skill" to WC, because it's indirectly affected.
bonusSkills.forEach(bonusSkill => {
const dependants = this.bonusDirectionMap.get(bonusSkill) ?? [];
dependants.forEach(d => bonusSkills.add(d));
});
[...bonusSkills, originSkill].forEach(bonusSkill => {
const startExp = fixedStats.get(bonusSkill)! + startBonusExp.get(bonusSkill)!;
const endExp = MAX_SKILL_EXP - endBonusExp.get(bonusSkill)!;
if (endExp - startExp <= 0 && bonusSkill !== originSkill) {
return;
}
const resetStats = new Map(fixedStats);
resetStats.set(originSkill, 0);
const startBonusesReset = this.calculateBonusExp(resetStats, BonusType.START);
const endBonusesReset = this.calculateBonusExp(resetStats, BonusType.END);
const startExpReset = resetStats.get(bonusSkill)! + startBonusesReset.get(bonusSkill)!;
const endExpReset = MAX_SKILL_EXP - endBonusesReset.get(bonusSkill)!;
const diff =
this.calculateSkillTime(bonusSkill, startExpReset, endExpReset) -
this.calculateSkillTime(bonusSkill, startExp, endExp);
if (endExp - startExp <= 0) {
timeSum += Math.min(this.maximumEHPMap.get(bonusSkill)!, diff);
} else {
timeSum += diff;
}
});
map.set(originSkill, roundNumber(timeSum, 5));
});
const totalEHP = Array.from(map.values()).reduce((a, b) => a + b, 0);
map.set(Skill.OVERALL, totalEHP);
return map;
}
calculateEHBMap(killcountMap: Map<Boss, number>) {
// Ensure no bosses can be -1 exp
const fixedKillcount = new Map(killcountMap);
BOSSES.forEach(boss => fixedKillcount.set(boss, Math.max(0, killcountMap.get(boss) ?? 0)));
const map = new Map(BOSSES.map(s => [s, 0]));
this.bossMetas.forEach(meta => {
if (!meta || meta.rate <= 0) return;
map.set(meta.boss, roundNumber((fixedKillcount.get(meta.boss) ?? 0) / meta.rate, 5));
});
return map;
}
private calculateBonusExp(stats: Map<Skill, number>, type: BonusType) {
const isStart = type === BonusType.START;
const bonuses = isStart ? this.startBonuses : this.endBonuses;
const map = new Map(REAL_SKILLS.map(skill => [skill, 0]));
bonuses
.sort((a, b) => {
// Sort the bonuses by the number of dependencies they have.
// This ensures skills with no received bonus exp are applied first (ex: Slayer).
return (
(this.bonusDirectionMap.get(b.bonusSkill)?.length ?? 0) -
(this.bonusDirectionMap.get(a.bonusSkill)?.length ?? 0)
);
})
.forEach(b => {
if (!isStart && b.originSkill === Skill.HUNTER && b.bonusSkill === Skill.FISHING) {
// Apply special BXP scaling function for drift net fishing/hunter
const driftNetBonus = this.getDriftNetScaledBonus(stats);
if (driftNetBonus) {
map.set(Skill.FISHING, map.get(Skill.FISHING)! + driftNetBonus);
return;
}
}
if (!isStart && b.originSkill === Skill.THIEVING && b.bonusSkill === Skill.AGILITY) {
// Apply special BXP scaling function for swimming thieving/agility
const swimmingBonus = this.getSwimmingScaledBonus(stats);
if (swimmingBonus) {
map.set(Skill.AGILITY, map.get(Skill.AGILITY)! + swimmingBonus);
return;
}
}
if (!isStart && b.originSkill === Skill.FIREMAKING && b.bonusSkill === Skill.THIEVING) {
// Apply special BXP scaling function for firefact firemaking/thieving
const firefactBonus = this.getFirefactScaledBonus(stats);
if (firefactBonus) {
map.set(Skill.THIEVING, map.get(Skill.THIEVING)! + firefactBonus);
return;
}
}
const expCap = Math.min(b.endExp, MAX_SKILL_EXP);
const originStart =
Math.max(stats.get(b.originSkill)!, b.startExp) + (isStart ? map.get(b.originSkill)! : 0);
const originEnd = !isStart ? expCap - map.get(b.originSkill)! : expCap;
const bonusToApply = Math.max(0, originEnd - originStart) * b.ratio;
map.set(b.bonusSkill, Math.min(MAX_SKILL_EXP, map.get(b.bonusSkill)! + bonusToApply));
});
return map;
}
private getDriftNetScaledBonus(stats: Map<Skill, number>) {
return this.getScaledMaxBonus(
stats,
Skill.HUNTER,
Skill.FISHING,
this.skillMetas.find(sm => sm.skill === Skill.HUNTER)?.methods.find(m => !!m.realRate),
this.skillMetas.find(sm => sm.skill === Skill.FISHING)?.methods.at(-1),
this.skillMetas.find(sm => sm.skill === Skill.HUNTER)?.bonuses[0]?.ratio
);
}
private getSwimmingScaledBonus(stats: Map<Skill, number>) {
return this.getScaledMaxBonus(
stats,
Skill.THIEVING,
Skill.AGILITY,
this.skillMetas.find(sm => sm.skill === Skill.THIEVING)?.methods.find(m => !!m.realRate),
this.skillMetas.find(sm => sm.skill === Skill.AGILITY)?.methods.at(-1),
this.skillMetas.find(sm => sm.skill === Skill.THIEVING)?.bonuses[0]?.ratio
);
}
private getFirefactScaledBonus(stats: Map<Skill, number>) {
return this.getScaledMaxBonus(
stats,
Skill.FIREMAKING,
Skill.THIEVING,
this.skillMetas.find(sm => sm.skill === Skill.FIREMAKING)?.methods.find(m => !!m.realRate),
this.skillMetas.find(sm => sm.skill === Skill.THIEVING)?.methods.at(-1),
this.skillMetas.find(sm => sm.skill === Skill.FIREMAKING)?.bonuses[0]?.ratio
);
}
private getScaledMaxBonus(
stats: Map<Skill, number>,
originSkill: Skill,
bonusSkill: Skill,
originSkillMethod: SkillMetaMethod | undefined,
bonusSkillMethod: SkillMetaMethod | undefined,
bonusRatio: number | undefined
) {
if (!originSkillMethod || !bonusSkillMethod || !bonusRatio) return 0;
const originSkillStart = Math.max(originSkillMethod.startExp, stats.get(originSkill)!);
const originExpLeft = MAX_SKILL_EXP - originSkillStart;
const realTime =
this.calculateSkillTime(originSkill, originSkillStart, MAX_SKILL_EXP, true) +
this.calculateSkillTime(bonusSkill, stats.get(bonusSkill)!, MAX_SKILL_EXP, true);
const fakeTime =
this.calculateSkillTime(originSkill, originSkillStart, MAX_SKILL_EXP, false) +
this.calculateSkillTime(bonusSkill, stats.get(bonusSkill)!, MAX_SKILL_EXP, false);
const excessBonuses = (realTime - fakeTime) * bonusSkillMethod.rate;
const fakeBonusLeft = originExpLeft * bonusRatio;
return fakeBonusLeft - excessBonuses;
}
private calculateSkillTime(skill: Skill, startExp: number, endExp: number, useRealRates = false) {
const methods = this.skillMetas.find(sm => sm.skill === skill)?.methods;
// Handle 0 time skills (Hitpoints, Magic, Fletching)
if (!methods || (methods.length === 1 && methods[0].rate === 0)) {
return (endExp - startExp) / MAX_SKILL_EXP;
}
let skillTime = 0;
for (let i = 0; i < methods.length; i++) {
const current = methods[i];
const next = methods[i + 1];
if (current.rate === 0) continue;
const rate = useRealRates && current.realRate ? current.realRate : current.rate;
// Start exp is within this method's boundaries
if (next && next.startExp > startExp && current.startExp < endExp) {
const gained = Math.min(next.startExp, endExp) - Math.max(startExp, current.startExp);
skillTime += gained / rate;
}
// End exp is beyond this method's boundaries
if (!next && endExp > current.startExp) {
const gained = endExp - Math.max(current.startExp, startExp);
skillTime += gained / rate;
}
}
return skillTime;
}
private calculateMaximumEHPMap() {
const map = new Map(SKILLS.map(s => [s, 0]));
const zeroStats = new Map(REAL_SKILLS.map(skill => [skill, 0]));
const startBonusExp = this.calculateBonusExp(zeroStats, BonusType.START);
const endBonusExp = this.calculateBonusExp(zeroStats, BonusType.END);
REAL_SKILLS.forEach(skill => {
const startExp = zeroStats.get(skill)! + startBonusExp.get(skill)!;
const endExp = MAX_SKILL_EXP - endBonusExp.get(skill)!;
map.set(skill, this.calculateSkillTime(skill, startExp, endExp));
});
const totalEHP = Array.from(map.values()).reduce((a, b) => a + b, 0);
map.set(Skill.OVERALL, totalEHP);
return map;
}
private getBonusDirectionMap(bonuses: SkillMetaBonus[]) {
const map = new Map();
bonuses.forEach(b => {
const currentList = map.get(b.originSkill);
if (currentList) {
if (currentList.includes(b.bonusSkill)) return;
map.set(b.originSkill, [...currentList, b.bonusSkill]);
} else {
map.set(b.originSkill, [b.bonusSkill]);
}
});
return map;
}
private getBonuses(metas: SkillMetaConfig[], type: BonusType): SkillMetaBonus[] {
return metas
.filter(r => r.bonuses.length > 0)
.map(r => r.bonuses)
.flat()
.filter(b => b?.end === (type === BonusType.END));
}
}
export default EfficiencyAlgorithm;
| 411 | 0.626501 | 1 | 0.626501 | game-dev | MEDIA | 0.943131 | game-dev | 0.908437 | 1 | 0.908437 |
SonicEraZoR/Portal-Base | 2,481 | sp/src/game/client/baseclientrendertargets.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Has init functions for all the standard render targets used by most games.
// Mods who wish to make their own render targets can inherit from this class
// and in the 'InitClientRenderTargets' interface called by the engine, set up
// their own render targets as well as calling the init functions for various
// common render targets provided by this class.
//
// Note: Unless the client defines a singleton interface by inheriting from
// this class and exposing the singleton instance, these init and shutdown
// functions WILL NOT be called by the engine.
//
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//=============================================================================//
#ifndef CLIENTRENDERTARTETS_H_
#define CLIENTRENDERTARTETS_H_
#ifdef _WIN32
#pragma once
#endif
#include "game/client/iclientrendertargets.h" // base class with interfaces called by the engine
#include "materialsystem/imaterialsystem.h" // for material system classes and interfaces
// Externs
class IMaterialSystem;
class IMaterialSystemHardwareConfig;
class CBaseClientRenderTargets : public IClientRenderTargets
{
// no networked vars
DECLARE_CLASS_GAMEROOT( CBaseClientRenderTargets, IClientRenderTargets );
public:
// Interface called by engine during material system startup.
virtual void InitClientRenderTargets ( IMaterialSystem* pMaterialSystem, IMaterialSystemHardwareConfig* pHardwareConfig, int iWaterTextureSize = 1024, int iCameraTextureSize = 256 );
// Shutdown all custom render targets here.
virtual void ShutdownClientRenderTargets ( void );
protected:
// Standard render textures used by most mods-- Classes inheriting from
// this can choose to init these or not depending on their needs.
// For reflective and refracting water
CTextureReference m_WaterReflectionTexture;
CTextureReference m_WaterRefractionTexture;
// Used for monitors
CTextureReference m_CameraTexture;
// Used for the HUD in stereo and head tracking mode
CTextureReference m_UITexture;
// Init functions for the common render targets
ITexture* CreateWaterReflectionTexture( IMaterialSystem* pMaterialSystem, int iSize = 1024 );
ITexture* CreateWaterRefractionTexture( IMaterialSystem* pMaterialSystem, int iSize = 1024 );
ITexture* CreateCameraTexture( IMaterialSystem* pMaterialSystem, int iSize = 256 );
};
#endif // CLIENTRENDERTARTETS_H_ | 411 | 0.89112 | 1 | 0.89112 | game-dev | MEDIA | 0.710769 | game-dev | 0.597173 | 1 | 0.597173 |
RoboJackets/rrt | 6,732 | src/rrt/BiRRT.hpp | #pragma once
#include <limits.h>
#include <rrt/Tree.hpp>
namespace RRT {
/**
* @brief Bi-directional RRT
* @details It is often preferable to use two RRTs when searching the state
* space with one rooted at the source and one rooted at the goal. When the
* two trees intersect, a solution has been found.
*/
template <typename T>
class BiRRT {
public:
BiRRT(std::shared_ptr<StateSpace<T>> stateSpace,
std::function<size_t(T)> hash, int dimensions,
std::function<T(double*)> arrayToT = NULL,
std::function<void(T, double*)> TToArray = NULL)
: _startTree(stateSpace, hash, dimensions, true, arrayToT, TToArray),
_goalTree(stateSpace, hash, dimensions, false, arrayToT, TToArray) {
_minIterations = 0;
reset();
}
void reset() {
_startTree.reset();
_goalTree.reset();
_iterationCount = 0;
_startSolutionNode = nullptr;
_goalSolutionNode = nullptr;
_solutionLength = INT_MAX;
}
const Tree<T>& startTree() const { return _startTree; }
const Tree<T>& goalTree() const { return _goalTree; }
bool isASCEnabled() const { return _startTree.isASCEnabled(); }
void setASCEnabled(bool checked) {
_startTree.setASCEnabled(checked);
_goalTree.setASCEnabled(checked);
}
double goalBias() const { return _startTree.goalBias(); }
void setGoalBias(double goalBias) {
_startTree.setGoalBias(goalBias);
_goalTree.setGoalBias(goalBias);
}
int maxIterations() const { return _startTree.maxIterations(); }
void setMaxIterations(int itr) {
_startTree.setMaxIterations(itr);
_goalTree.setMaxIterations(itr);
}
/**
* The minimum number of iterations to run.
*
* At the default value of zero, the rrt will return the first path it
* finds. Setting this to a higher value can allow the tree to search for
* longer in order to find a better path.
*/
int minIterations() const { return _minIterations; }
void setMinIterations(int itr) { _minIterations = itr; }
double waypointBias() const { return _startTree.waypointBias(); }
void setWaypointBias(double waypointBias) {
_startTree.setWaypointBias(waypointBias);
_goalTree.setWaypointBias(waypointBias);
}
const std::vector<T>& waypoints() { return _startTree.waypoints(); }
void setWaypoints(const std::vector<T>& waypoints) {
_startTree.setWaypoints(waypoints);
_goalTree.setWaypoints(waypoints);
}
double stepSize() const { return _startTree.stepSize(); }
void setStepSize(double stepSize) {
_startTree.setStepSize(stepSize);
_goalTree.setStepSize(stepSize);
}
double maxStepSize() const { return _startTree.maxStepSize(); }
void setMaxStepSize(double stepSize) {
_startTree.setMaxStepSize(stepSize);
_goalTree.setMaxStepSize(stepSize);
}
double goalMaxDist() const { return _startTree.goalMaxDist(); }
void setGoalMaxDist(double maxDist) {
_startTree.setGoalMaxDist(maxDist);
_goalTree.setGoalMaxDist(maxDist);
}
/**
* @brief Get the shortest path from the start to the goal
*/
std::vector<T> getPath() {
std::vector<T> path;
_startTree.getPath(&path, _startSolutionNode);
_startTree.getPath(&path, _goalSolutionNode, true);
return path;
}
/**
* @brief
* @details Attempts to add a new node to each of the two trees. If
* a new solution is found that is shorter than any previous solution, we
* store
* it instead.
*/
void grow() {
int depth;
const Node<T>* otherNode;
Node<T>* newStartNode = _startTree.grow();
if (newStartNode) {
otherNode = _findBestPath(newStartNode->state(), _goalTree, &depth);
if (otherNode && depth + newStartNode->depth() < _solutionLength &&
_goalTree.stateSpace().transitionValid(newStartNode->state(),
otherNode->state())) {
_startSolutionNode = newStartNode;
_goalSolutionNode = otherNode;
_solutionLength = newStartNode->depth() + depth;
}
}
Node<T>* newGoalNode = _goalTree.grow();
if (newGoalNode) {
otherNode = _findBestPath(newGoalNode->state(), _startTree, &depth);
if (otherNode && depth + newGoalNode->depth() < _solutionLength &&
_goalTree.stateSpace().transitionValid(otherNode->state(),
newGoalNode->state())) {
_startSolutionNode = otherNode;
_goalSolutionNode = newGoalNode;
_solutionLength = newGoalNode->depth() + depth;
}
}
++_iterationCount;
}
/**
* @brief Grows the trees until we find a solution or run out of iterations.
* @return true if a solution is found
*/
bool run() {
for (int i = 0; i < _startTree.maxIterations(); i++) {
grow();
if (_startSolutionNode != nullptr && i >= minIterations())
return true;
}
return false;
}
void setStartState(const T& start) {
_startTree.setStartState(start);
_goalTree.setGoalState(start);
}
const T& startState() const { return _startTree.startState(); }
void setGoalState(const T& goal) {
_startTree.setGoalState(goal);
_goalTree.setStartState(goal);
}
const T& goalState() const { return _startTree.goalState(); }
const Node<T>* startSolutionNode() { return _startSolutionNode; }
const Node<T>* goalSolutionNode() { return _goalSolutionNode; }
int iterationCount() const { return _iterationCount; }
protected:
const Node<T>* _findBestPath(const T& targetState, Tree<T>& treeToSearch,
int* depthOut) const {
const Node<T>* bestNode = nullptr;
int depth = INT_MAX;
for (const Node<T>& other : treeToSearch.allNodes()) {
double dist =
_startTree.stateSpace().distance(other.state(), targetState);
if (dist < goalMaxDist() && other.depth() < depth) {
bestNode = &other;
depth = other.depth();
}
}
if (depthOut) *depthOut = depth;
return bestNode;
}
private:
Tree<T> _startTree;
Tree<T> _goalTree;
int _iterationCount;
int _minIterations;
int _solutionLength;
const Node<T> *_startSolutionNode, *_goalSolutionNode;
};
} // namespace RRT
| 411 | 0.937118 | 1 | 0.937118 | game-dev | MEDIA | 0.304323 | game-dev | 0.941306 | 1 | 0.941306 |
leonardoporro/Detached-Mapper | 2,397 | src/Detached.Mappers/Context/MapContext.cs | using Detached.Mappers.TypeMappers.Entity;
using System;
using System.Collections.Generic;
namespace Detached.Mappers.Context
{
public class MapContext : IMapContext
{
readonly LinkedList<(object, object)> _objectStack =
new LinkedList<(object, object)>();
public MapContext(MapParameters parameters = null)
{
Parameters = parameters ?? new MapParameters();
}
public MapParameters Parameters { get; }
public virtual TEntity TrackChange<TEntity, TSource, TKey>(TEntity entity, TSource source, TKey key, MapperActionType actionType)
where TEntity : class
where TSource : class
where TKey : IEntityKey
{
return entity;
}
public virtual void Push<TKeyOrSource, TTarget>(TKeyOrSource keyOrSource, TTarget target)
{
_objectStack.AddLast((keyOrSource, target));
}
public virtual void Pop()
{
_objectStack.RemoveLast();
}
public virtual bool TryGetResult<TKeyOrSource, TTarget>(TKeyOrSource keyOrDto, out TTarget target)
where TTarget : class
{
var entry = _objectStack.Last;
while (entry != null && !Equals(entry.Value.Item1, keyOrDto))
{
entry = entry.Previous;
}
if (entry != null)
{
target = (TTarget)entry.Value.Item2;
return true;
}
else
{
target = default;
return false;
}
}
public virtual bool TryGetParent<TTarget>(out TTarget target)
where TTarget : class
{
Type targetType = typeof(TTarget);
var entry = _objectStack.Last;
while (entry != null
&& !(entry.Value.Item1 is EntityRef entityRef
&& !entityRef.Key.IsEmpty
&& targetType.IsAssignableFrom(entityRef.ClrType)))
{
entry = entry.Previous;
}
if (entry != null)
{
target = (TTarget)entry.Value.Item2;
return true;
}
else
{
target = null;
return false;
}
}
}
} | 411 | 0.916695 | 1 | 0.916695 | game-dev | MEDIA | 0.626788 | game-dev | 0.96262 | 1 | 0.96262 |
OwlGamingCommunity/MTA | 3,111 | mods/deathmatch/resources/[vehicle]/vehicle/activity_g.lua | --[[
* ***********************************************************************************************************************
* Copyright (c) 2015 OwlGaming Community - All Rights Reserved
* All rights reserved. This program and the accompanying materials are private property belongs to OwlGaming Community
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* ***********************************************************************************************************************
]]
function isActive(veh)
local warning_last_login, warning_last_used = nil
local job = getElementData(veh, "job") or 0
local owner = getElementData(veh, "owner") or -1
local faction = getElementData(veh, "faction") or -1
local Impounded = getElementData(veh, "Impounded") or 0
if job ~= 0 or owner <= 0 or faction ~= -1 or Impounded ~= 0 then
return true
elseif getVehicleType(veh) == "Trailer" then
return true
else
local oneDay = 60*60*24
local owner_last_login = getElementData(veh, "owner_last_login")
if owner_last_login and tonumber(owner_last_login) then
local owner_last_login_text, owner_last_login_sec = exports.datetime:formatTimeInterval(owner_last_login)
if owner_last_login_sec > oneDay*30 then
return false, "Inactive Vehicle | Owner is inactive ("..owner_last_login_text..")", owner_last_login_sec
elseif owner_last_login_sec > (oneDay*30 - oneDay/2) then --12 hours before it becomes inactive
warning_last_login = (oneDay*30)-owner_last_login_sec
end
end
local dim = getElementDimension(veh)
-- Allow players to have their vehicles currently outside, as long as their respawn position is in a interior(due to some issues with vehicles falling out of interiors and into dimension 0) //Chaos
local parkDim = getElementData(veh, "dimension")
if dim == 0 and tonumber(parkDim) == 0 then
local lastused = getElementData(veh, "lastused")
if lastused and tonumber(lastused) then
local lastusedText, lastusedSeconds = exports.datetime:formatTimeInterval(lastused)
if lastusedSeconds > oneDay*14 then
return false, "Inactive Vehicle | Last used "..lastusedText.." while parking outdoors", lastusedSeconds
elseif lastusedSeconds > (oneDay*14 - oneDay/2) then --12 hours before it becomes inactive
warning_last_used = (oneDay*14)-lastusedSeconds
end
end
end
end
return true, getMoreCriticalWarning(warning_last_used,warning_last_login)
end
function isProtected(veh)
local job = getElementData(veh, "job") or 0
local owner = getElementData(veh, "owner") or -1
local faction = getElementData(veh, "faction") or -1
if job ~= 0 or owner <= 0 or faction ~= -1 then
return false
end
local protected_until = getElementData(veh, "protected_until") or -1
local protectText, protectSeconds = exports.datetime:formatFutureTimeInterval(protected_until)
return protectSeconds > 0, protectText, protectSeconds
end
function getMoreCriticalWarning(a, b)
if not a then
return b
end
if not b then
return a
end
if a and b then
return (a < b) and a or b
end
return nil
end
| 411 | 0.807316 | 1 | 0.807316 | game-dev | MEDIA | 0.234658 | game-dev | 0.516123 | 1 | 0.516123 |
ggnkua/Atari_ST_Sources | 4,556 | C/Jim Patchell/dxedsrc/VSEL2.C | /*
this file is a voice selector dialog box
input parrameters:
file name path
voice name
returns
result of dialog
*/
#include <osbind.h>
#include <obdefs.h>
#include <gemdefs.h>
#include <string.h>
#include "dx.h"
#include "dxed.h"
#include <stdio.h>
#define PAGE_UP 0
#define PAGE_DN 1
#define ROW_UP 2
#define ROW_DN 3
#define PAG_LF 4
#define PAG_RT 5
#define COL_LF 6
#define COL_RT 7
#define NLINES 32
#define NCHARS 10
extern char temp[128];
extern int res;
extern int gl_hchar,gl_wchar;
extern int slidpos[10];
int xlines;
static int cur_line, cur_col;
char voice_name[11]; /* voice currently being edited */
char names[32][11];
int name_indexes[] = {
VSELNM1,VSELNM2,VSELNM3,VSELNM4,VSELNM5,VSELNM6,VSELNM7,VSELNM8,VSELNM9,VSELNM10 };
voice_sel(file,voice,vw)
char voice[],file[];
int vw; /* workstation handle */
{
OBJECT *box;
int x,y,w,h; /* coordinates of dialog box */
int result,size,selection;
int tag = -1;
register int i;
char *ptr,*p;
selection = 0;
rsrc_gaddr(R_TREE,V_SEL,&box);
form_center(box,&x,&y,&w,&h);
vreset(0,box,VSELTRK,VSELSLID,22,22);
form_dial(FMD_START,x,y,0,0,x,y,w,h);
form_dial(FMD_GROW,x,y,0,0,x,y,w,h);
if((ptr = rindex(file,'\\')) == NULL)
ptr = file;
else
++ptr;
if((p = rindex(ptr,'.')) != NULL)
*p = '\0';
strcpy(((TEDINFO *)(box[VSELNAME].ob_spec))->te_ptext,ptr);
get_names(voice,names); /* get voice names */
write_names(box,names,x,y,w,h,0,-1,FALSE);
objc_draw(box,0,10,x,y,w,h);
do
{
result = form_do(box,0);
switch(result)
{
case VSELUP:
case VSELDN:
case VSELTRK:
case VSELSLID:
do_vslider(0,box,VSELTRK,VSELSLID,VSELUP,VSELDN,result,4);
selection = 22 - slidpos[0];
write_names(box,names,x,y,w,h,selection,tag,TRUE);
break;
case VSELNM1:
case VSELNM2:
case VSELNM3:
case VSELNM4:
case VSELNM5:
case VSELNM6:
case VSELNM7:
case VSELNM8:
case VSELNM9:
case VSELNM10:
for(i=0;(i<10) && (result != name_indexes[i]);++i);
tag = selection + i;
write_names(box,names,x,y,w,h,selection,tag,TRUE);
break;
case VS_OK:
if(tag == -1)
{
form_alert(1,"[3][You Must select|a voice!][Gee-Whiz]");
result = -1;
}
break;
} /* end switch result */
}while((result != VS_OK) && (result != VS_CAN));
box[result].ob_state = NORMAL;
form_dial(FMD_SHRINK,x,y,0,0,x,y,w,h);
form_dial(FMD_FINISH,x,y,0,0,x,y,w,h);
return(tag);
}
get_names(v,n)
char v[],n[32][11];
{
register int iv,ii,i;
iv = 118;
for(i=0;i<32;++i)
{
for(ii=0;ii<10;++ii)
{
n[i][ii] = v[iv + ii];
}
n[i][ii] = '\0'; /* null terminator */
iv += 128;
}
}
write_names(box,names,x,y,w,h,n,tag,update)
OBJECT *box;
char names[32][11];
int x,y,w,h,n,tag;
int update;
{
register int i;
for(i=0;i<10;++i)
{
if((i + n) == tag)
{
strcpy(box[name_indexes[i]].ob_spec,names[i + n]);
box[name_indexes[i]].ob_state = SELECTED;
strcpy(voice_name,names[i + n]);
}
else
{
strcpy(box[name_indexes[i]].ob_spec,names[i + n]);
box[name_indexes[i]].ob_state = NORMAL;
}
}
if(update)
objc_draw(box,VSELBOX,2,x,y,w,h);
}
do_arrows(operation,whand,vw,nlines,col,line)
int operation,whand,vw;
int nlines;
int *col,*line;
{
int x,y,w,h,wlines,wcols;
extern gl_wchar,gl_hchar,xlines;
int vertical,horizontal;
wind_get(whand,WF_WORKXYWH,&x,&y,&w,&h);
wlines = h / gl_hchar; /* calculate number of line in window */
wcols = w / gl_wchar; /* calculate number of columns in window */
switch (operation)
{
case PAGE_UP:
*line -= wlines;
if (*line < 0)
*line = 0;
break;
case PAGE_DN:
*line += wlines;
if (*line > nlines - wlines)
*line = nlines - wlines;
break;
case ROW_UP:
--*line;
if(*line < 0 )
*line = 0;
break;
case ROW_DN:
++*line;
if(*line > nlines - wlines)
*line = nlines - wlines;
break;
}
slide_pos(wlines,nlines,*line,&vertical);
wind_set(whand,WF_VSLIDE,vertical,0,0,0);
}
slide_pos(visible,total,line,pos)
int visible,total,line,*pos;
{
*pos = 1000l * line / (total - visible);
}
v_touched(whand,vw,vertical,nlines,line)
int whand,vw,vertical,nlines;
int *line;
{
int x,y,w,h,wlines;
extern int gl_hchar;
wind_get(whand,WF_WORKXYWH,&x,&y,&w,&h);
wlines = h / gl_hchar;
pos_slide(wlines,nlines,line,vertical);
}
pos_slide(visible,total,line,pos)
int visible,total,*line,pos;
{
*line = (pos * (total - visible)) / 1000l;
}
slide_size(visible,total,size)
int visible,total,*size;
{
*size = 1000l * visible / total;
if(*size <= 0 )
*size = -1;
if (*size > 1000)
*size = 1000;
}
| 411 | 0.898309 | 1 | 0.898309 | game-dev | MEDIA | 0.216983 | game-dev | 0.852683 | 1 | 0.852683 |
ehsankamrani/vandaengine | 30,804 | Vanda Engine Editor/VandaEngineEditor/GraphicsEngine/Geometry.h | //Original Work: Copyright 2006 Sony Computer Entertainment Inc.
//Modified Work: Copyright (C) 2024 Ehsan Kamrani
//This file is licensed and distributed under MIT license
#pragma once
#include <iostream>
#include "base.h"
#include "skin.h"
#include "image.h"
#include "texture.h"
//#include "cfxLoader.h"
//#include "cfxEffect.h"
//#include "cfxSurface.h"
//#include "cfxPlatform.h"
#include "OpenGLUtility.h"
#include "../common/utility.h"
#include "../common/vector.h"
#include "../common/list.h"
#include <string>
#include <set>
#include <map>
#include <vector>
#include "Prefab.h"
class CMaterial;
class CGeometry;
class COctree;
class CInstanceMaterial;
class CInstanceLight;
class CLOD;
class CInstanceMaterial
{
public:
CInstanceMaterial()
{
m_targetMaterial=0;
//m_targetcfxMaterial=0;
m_symbol= "";
m_target= "";
};
CNode *m_parent; // Node where this instance was instantiated
std::string m_symbol;
std::string m_target;
CMaterial * m_targetMaterial;
//cfxMaterial * m_targetcfxMaterial;
};
class CInstance
{
public:
CInstance() : m_parent(0) {};
//I assume that all the CMatrial objects are deleted insied CScene destructor
~CInstance(){ m_materialInstances.clear(); };
CNode *m_parent; // Node where this instance was instantiated */
std::vector <CInstanceMaterial *> m_materialInstances; // list of material instances in the <technique_common>
};
class CInstanceGeometry : public CInstance
{
public:
CInstanceGeometry() : m_abstractGeometry(0) { m_renderCount = 0; m_nameIndex = -1; m_hasPhysX = CFalse; Cpy(m_physXName, "\n"); m_lodAlgorithm = eLOD_NONE; m_prevLodAlgorithm = eLOD_NONE; m_physXDensity = 0.0f; m_physXPercentage = 50; m_physXCount = 0; m_firstUpdate = CTrue; m_isTrigger = CFalse; m_isInvisible = CFalse;
m_distanceFromCamera = 0.0f; m_radius = 0.0f; m_renderWithPhysX = CFalse; m_hasPhysicsMaterial = CFalse; m_isController = CFalse;
CMatrixLoadIdentity(m_localToWorldMatrix); CMatrixLoadIdentity(m_localToWorldMatrixControlledByPhysX); CMatrixLoadIdentity(m_firstLocalToWorldMatrix); }
~CInstanceGeometry() { m_parentTree.clear(); m_lights.clear();}
CVoid SetIndex() { m_nameIndex = g_nameIndex++; }
//We delete CGeometry object insied CScene destructor
CGeometry *m_abstractGeometry; // The abstract geometry where the original data is stored
std::vector<COctree*>m_parentTree;
CInt m_renderCount;
std::vector<CInstanceLight*>m_lights; //Lights that affect this geometry
CMatrix m_localToWorldMatrix; // Full local to world matrix for this geometry
CMatrix m_firstLocalToWorldMatrix;
CBool m_firstUpdate;
CMatrix m_localToWorldMatrixControlledByPhysX;
CVec3f m_minLocalToWorldAABB; //To hold the world space max values of the AABB box
CVec3f m_maxLocalToWorldAABB; //To hold the world space min values of the AABB box
CVec3f m_minLocalToWorldAABBControlledByPhysX;
CVec3f m_maxLocalToWorldAABBControlledByPhysX;
CVec3f m_center;
CFloat m_radius;
CFloat m_distanceFromCamera;
CVec3f m_localToWorldVertex[8];
CInt m_nameIndex;
CChar m_physXName[MAX_NAME_SIZE];
CBool m_hasPhysX;
CBool m_isTrigger;
CBool m_isInvisible;
////////////////physics material
CBool m_hasPhysicsMaterial;
CFloat m_physicsRestitution;
CFloat m_physicsStaticFriction;
CFloat m_physicsDynamicFriction;
CFloat m_physicsSkinWidth;
////////////////
CFloat m_physXDensity;
CInt m_physXPercentage;
CPhysXAlgorithm m_lodAlgorithm;
CPhysXAlgorithm m_prevLodAlgorithm;
CInt m_physXCount;
CBool m_renderWithPhysX;
CNode* m_node; //instance geometry is attached to this node
CBool m_isController;
CChar* GetPhysXActorName() { return m_physXName; }
CFloat GetPhysXActorDensity() { return m_physXDensity; }
CBool GetHasPhysXActor() { return m_hasPhysX; }
//physics material
CBool HasPhysicsMaterial() { return m_hasPhysicsMaterial; }
CFloat GetPhysicsRestitution() { return m_physicsRestitution; }
CFloat GetPhysicsSkinWidth() { return m_physicsSkinWidth; }
CFloat GetPhysicsStaticFriction() { return m_physicsStaticFriction; }
CFloat GetPhysicsDynamicFriction() { return m_physicsDynamicFriction; }
CVoid EnablePhysicsMaterial(CBool state) { m_hasPhysicsMaterial = state; }
CVoid SetPhysicsRestitution(CFloat restitution) { m_physicsRestitution = restitution; }
CVoid SetPhysicsSkinWidth(CFloat skinWidth) { m_physicsSkinWidth = skinWidth; }
CVoid SetPhysicsStaticFriction(CFloat staticFriction) { m_physicsStaticFriction = staticFriction; }
CVoid SetPhysicsDynamicFriction(CFloat dynamicFriction) { m_physicsDynamicFriction = dynamicFriction; }
CVoid SetDistanceFromCamera(CFloat distance) { m_distanceFromCamera = distance; }
CFloat GetDistanceFromCamera() { return m_distanceFromCamera; }
CVoid CalculateDistance();
};
class CInstanceController : public CInstance
{
public:
CInstanceController() : m_abstractController(0) { m_instanceGeometry = CNew(CInstanceGeometry);};
~CInstanceController() { CDelete( m_instanceGeometry) };
CController * m_abstractController;
CInstanceGeometry * m_instanceGeometry;
};
class CVertexAllPtr
{
public:
CVec3f* m_point;
CVec3f* m_normal;
CVec2f* m_texcoord[MAX_TEX_COORDS];
CVec3f* m_tangent;
CVec3f* m_bNormal;
CWeight* m_weights;
CVec3f* m_bindPoint;
CVec3f* m_bindNormal;
CVertexAllPtr():
m_point(NULL),
m_normal(NULL),
m_tangent(NULL),
m_bNormal(NULL),
m_weights(NULL),
m_bindPoint(NULL),
m_bindNormal(NULL)
{
memset( m_texcoord, 0, sizeof( m_texcoord ));
}
};
class CPolyGroup;
class CVertexAll
{
public:
CVec3f m_point;
CVec3f m_normal;
CVec2f m_texcoord[MAX_TEX_COORDS];
CVec3f m_tangent;
CVec3f m_bNormal;
CWeight m_weights;
CVec3f m_bindPoint;
CVec3f m_bindNormal;
CVertexAll()
{
// All the members have default constructors that initialize them
}
~CVertexAll()
{
}
inline CVoid Set( CVertexAllPtr * v )
{
if( v->m_point )
m_point = *v->m_point;
if( v->m_normal )
m_normal = *v->m_normal;
for ( CInt32 i = 0;i < MAX_TEX_COORDS; i++)
{
if( v->m_texcoord[i] )
m_texcoord[i] = *v->m_texcoord[i];
}
if( v->m_tangent )
m_tangent = *v->m_tangent;
if( v->m_bNormal )
m_bNormal = *v->m_bNormal;
if( v->m_weights )
m_weights.Copy( v->m_weights );
if ( v->m_bindPoint )
m_bindPoint = *v->m_bindPoint;
if ( v->m_bindNormal )
m_bindNormal = *v->m_bindNormal;
}
inline CVoid Set( CVertexAll * v )
{
m_point = v->m_point;
m_normal = v->m_normal;
for ( CInt i =0 ; i<MAX_TEX_COORDS ; i++ )
m_texcoord[i] = v->m_texcoord[i];
m_tangent = v->m_tangent;
m_bNormal = v->m_bNormal;
m_weights.Copy( &v->m_weights );
m_bindPoint = v->m_bindPoint;
m_bindNormal = v->m_bindNormal;
}
CBool Compare( CPolyGroup * polyGroup, CInt idx );
CVoid Copy( CPolyGroup * polyGroup, CInt idx );
};
class CPoly
{
public:
CInt32* m_points;
CVertexAllPtr* m_pointData;
CInt32 m_numIndices;
CInt32 m_numPoints;
CPoly():
m_points(NULL),
m_pointData(NULL),
m_numIndices(0),
m_numPoints(0)
{
}
~CPoly()
{
CDelete( m_points );
CDelete( m_pointData );
}
};
class CTri
{
public:
CInt32 m_points[3];
CTri()
{
memset( m_points, 0, sizeof ( m_points ));
}
};
class CSource
{
public:
CFloat* m_data;
CInt32 m_nbr;
CChar m_id[MAX_NAME_SIZE];
CChar m_semantic[MAX_NAME_SIZE];
CChar m_vertexSourceId[MAX_NAME_SIZE];
CBool m_hasVertexBinding;
CSource():
m_data(NULL),
m_nbr(0),
m_hasVertexBinding(CFalse)
{
memset( m_id, 0, sizeof ( m_id ));
memset( m_semantic, 0, sizeof ( m_semantic ));
memset( m_vertexSourceId, 0, sizeof ( m_vertexSourceId ));
}
~CSource()
{
DeleteData();
}
CVoid DeleteData()
{
CDeleteData( m_data );
}
};
class CInput
{
public:
CChar m_semantic[MAX_NAME_SIZE];
CChar m_sourceName[MAX_NAME_SIZE];
CSource *m_source;
CInputType m_type;
CInput():
m_source(NULL),
m_type(eUNKNOWN)
{
memset( m_semantic, 0, sizeof ( m_semantic ));
memset( m_sourceName, 0, sizeof ( m_sourceName ));
}
};
struct CVertexArray
{
CInt m_primitiveType;
CInt m_count;
CInt m_vertexFormat;
CVoid* m_i;
CVoid* m_p;
};
struct CMultiArray
{
CVertexArray* m_pVertexArray;
CInt32 m_nbVertexArray;
};
CVoid Cpy( CChar * s1, const CChar * s2 );
class CController;
class CJoint;
class CPolyGroup;
class CPolyGroup : public CBase
{
public:
//cfxMaterial *m_fXMaterial; // COLLADA FX material for this polygon group */
CMaterial * m_material; // OBSOLETE, will be removed by refactor later
CChar m_materialName[MAX_NAME_SIZE]; // could be obsolete or kept for debugging
CBool m_hasSkin;
CGeometry* m_geometry;
CPoly* m_polys;
CTri* m_tris;
CMultiArray m_multiArray;
CVertexArray m_boundingBoxArray;
CVec3f m_minBound;
CVec3f m_maxBound;
CUInt32 m_count;
CInt32 m_numTextures;
CInt32 m_numSharedVerts;
CBool m_vertsShared;
CBool m_dataReadyForCg;
CVec4f* m_skinIndicesCg;
CVec4f* m_skinWeightsCg;
CUInt* m_indexes;
CUInt m_nameIndex;
CChar m_strDirtMap[MAX_NAME_SIZE];
CChar m_strOriginalDirtMapPath[MAX_NAME_SIZE]; //save functions
CImage *m_dirtMapImg;
CBool SetDirtMap( CString path, CBool test = CFalse );
CBool m_hasDirtMap;
CBool m_loadedDirtMap;
CBool m_updateDirtMap;
CChar m_strNormalMap[MAX_NAME_SIZE];
CChar m_strOriginalNormalMapPath[MAX_NAME_SIZE]; //save functions
CFloat m_parallaxMapBias, m_parallaxMapScale;
//Material Colors
CFloat m_fAmbientColor[4];
CFloat m_fDiffuseColor[4];
CFloat m_fSpecularColor[4];
CFloat m_fEmissionColor[4];
CFloat m_fShininess, m_fTransparency;
CFloat* GetAmbient() { return m_fAmbientColor; }
CFloat* GetDiffuse() { return m_fDiffuseColor; }
CFloat* GetSpecular() { return m_fSpecularColor; }
CFloat* GetEmission() { return m_fEmissionColor; }
CFloat GetShininess() { return m_fShininess; }
CFloat GetTransparency() { return m_fTransparency; }
CVoid SetAmbient(CFloat* ambient)
{
for (CUInt i = 0; i < 4; i++)
m_fAmbientColor[i] = ambient[i];
}
CVoid SetDiffuse(CFloat* diffuse)
{
for (CUInt i = 0; i < 4; i++)
m_fDiffuseColor[i] = diffuse[i];
}
CVoid SetSpecular(CFloat* specular)
{
for (CUInt i = 0; i < 4; i++)
m_fSpecularColor[i] = specular[i];
}
CVoid SetEmission(CFloat* emission)
{
for (CUInt i = 0; i < 4; i++)
m_fEmissionColor[i] = emission[i];
}
CVoid SetShininess(CFloat shininess) { m_fShininess = shininess; }
CVoid SetTransparency(CFloat transparency) { m_fTransparency = transparency; }
//////////////////
CImage *m_normalMapImg;
CBool SetNormalMap( CString path, CFloat bias, CFloat scale, CBool test = CFalse );
CBool m_hasNormalMap;
CBool m_loadedNormalMap;
CBool m_updateNormalMap;
CChar m_strDiffuse[MAX_NAME_SIZE];
CChar m_strOriginalDiffusePath[MAX_NAME_SIZE]; //save functions
CImage *m_diffuseImg;
CBool m_updateDiffuse;
CVoid TrimOriginalPath(CChar* path ); //save functions
CBool SetDiffuse( CString path, CBool test = CFalse );
CBool m_hasDiffuse;
CBool m_loadedDiffuse;
CChar m_strGlossMap[MAX_NAME_SIZE];
CChar m_strOriginalGlossMapPath[MAX_NAME_SIZE]; //save functions
CImage *m_glossMapImg;
CBool SetGlossMap( CString path, CBool test = CFalse );
CBool m_hasGlossMap;
CBool m_loadedGlossMap;
CBool m_updateGlossMap;
CBool m_hasAnimation;
CImage* GetImage( const CChar * name );
std::vector<CImage*>m_images; //this points to all the *map pointers( see bellow )
inline CVoid RemoveDiffuse()
{
Cpy( m_strDiffuse, "\n" );
//CTexture::DeleteTexture( m_diffuseImg );
m_hasDiffuse = CFalse;
m_updateDiffuse = CFalse;
}
inline CVoid RemoveNormalMap()
{
Cpy( m_strNormalMap, "\n" );
//CTexture::DeleteTexture( m_normalMapImg );
m_hasNormalMap = CFalse;
m_updateNormalMap = CFalse;
}
inline CVoid RemoveDirtMap()
{
Cpy( m_strDirtMap, "\n" );
//CTexture::DeleteTexture( m_dirtMapImg );
m_hasDirtMap = CFalse;
m_updateDirtMap = CFalse;
}
inline CVoid RemoveGlossMap()
{
Cpy( m_strGlossMap, "\n" );
//CTexture::DeleteTexture( m_glossMapImg );
m_hasGlossMap = CFalse;
m_updateGlossMap = CFalse;
}
CBool m_setMatFromCollada;
public:
CPolyGroup()
{
m_material = NULL;
//m_fXMaterial = NULL;
m_numTextures = 0;
m_polys = NULL;
m_tris = NULL;
m_multiArray.m_pVertexArray = 0;
m_numSharedVerts = 0;
m_hasSkin = CFalse;
m_vertsShared = CFalse;
m_dataReadyForCg = CFalse;
m_skinIndicesCg = NULL;
m_skinWeightsCg = NULL;
m_hasAnimation = CFalse;
m_indexes = 0;
m_nameIndex = 0; //selection
Cpy (m_strDiffuse, "\n");
m_hasDiffuse = CFalse;
m_diffuseImg = NULL;
m_updateDiffuse = CTrue;
Cpy (m_strNormalMap, "\n");
m_hasNormalMap = CFalse;
m_normalMapImg = NULL;
m_updateNormalMap = CTrue;
Cpy (m_strDirtMap, "\n");
m_hasDirtMap = CFalse;
m_dirtMapImg = NULL;
m_updateDirtMap = CTrue;
Cpy (m_strGlossMap, "\n");
m_hasGlossMap = CFalse;
m_glossMapImg = NULL;
m_updateGlossMap = CTrue;
m_parallaxMapBias = -0.03;
m_parallaxMapScale = 0.06;
m_setMatFromCollada = CTrue;
}
~CPolyGroup()
{
Destroy();
DeleteVertexData();
DeletePolygonData();
m_images.clear();
}
CVoid EnableShader();
protected:
friend class CScene;
friend class CGeometry;
CVoid DeleteVertexData()
{
if (m_indexes)
{
CDeleteData( m_indexes );
m_indexes = NULL;
}
}
CVoid DeleteData()
{
}
CVoid DeletePolygonData()
{
CDeleteData( m_polys );
CDeleteData( m_tris );
}
CVoid DeleteAll()
{
DeleteVertexData();
DeleteData();
DeletePolygonData();
}
CVoid SetMaterialFromCOLLADA( CMaterial * mat, CChar * matName )
{
m_material = mat;
Cpy( m_materialName, matName );
}
CInput * GetPointInput();
CVoid CopyPointInput( CPolyGroup * group );
CVoid ParseSource( const CChar * data, const CChar * name, const CChar * count );
CInputType SetType( CChar * s );
CVoid Draw(CNode *parentNode, CInstance * instance, CGeometryColor color, CBool hasDiffuse ); //if the object is selected we have to use another color for the diffuse component
CVoid SetHasSkin(){ m_hasSkin = CTrue; }
CVoid DrawSkinned( CNode *parentNode, CVec3f * bindPos, CVec3f * bindNorms,
CJoint * joints, CInt nbrBindPoints, CInt nbrJoints, CInstance * instance);
CVoid RenderSkinnedCg( CVec3f * bindPos, CVec3f * bindNorms,
CJoint * joints, CInt nbrBindPoints, CInt nbrJoints );
/*cfxMaterial* */ CVoid SetupMaterialForDrawFromCOLLADA(CNode *parentNode, CInstance * instance, CGeometryColor color, CBool hasDiffuse );
CVoid SetupMaterialForDrawFromGameEngine(CGeometryColor color);
CVoid SaveMaterialValues(CMaterial * mat);
CBool SetupDiffuseTexture(CNode *parentNode, CInstance * instance);
CBool SetupNormalTexture(CNode *parentNode, CInstance * instance);
CBool SetupDirtTexture(CNode *parentNode, CInstance * instance);
CBool SetupGlossTexture(CNode *parentNode, CInstance * instance);
CVoid RenderCg();
CVoid SetDataPointers();
CVoid RenderDebug();
public:
//---------------------- External interfaces ---------------------------------//
// Each Geometry represents a COLLADA Geometry Library. Each lib can have
// may groups. I these groups you will get the Material and from the Material
// you can get the texture(s) if there are any.
// You will also get the Point,Normal,Tanget, TexCoords[8], UVs and Weights.
// Currently the Weight data is loaded, but I have added it to the triangulation
// so this will return null for now. But you can build your interface from the
// stucts that I have provide already.
inline CMaterial *GetMaterial() { return m_material; }
inline CTri *GetTris() { return m_tris; }
CVoid SetRender();
virtual CVoid Render() = 0;
virtual CVoid SetVBOs() = 0;
CVoid SetReadMaterialColorFromCOLLADA() { m_setMatFromCollada = CTrue; }
CVoid SetReadMaterialColorFromGameEngine(){ m_setMatFromCollada = CFalse; }
//---------------------- End External interfaces -----------------------------//
};
class CPolygons : public CPolyGroup
{
public:
CPolygons ();
~CPolygons ();
CVoid SetVBOs();
CVoid Render();
std::vector<CUInt> m_countvector;
std::vector<CUInt *> m_indexvector;
private:
CUInt * m_VBOID;
};
class CTriangles : public CPolyGroup
{
public:
CTriangles ();
~CTriangles ();
CVoid SetVBOs();
CVoid Render();
private:
CUInt m_VBOID;
};
class CLines : public CPolyGroup
{
public:
CLines ();
~CLines ();
CVoid SetVBOs();
CVoid Render();
private:
CUInt m_VBOID;
};
class CLinestrips : public CPolyGroup
{
public:
CLinestrips ();
~CLinestrips ();
std::vector<CUInt> m_countvector;
std::vector<CUInt *> m_indexvector;
CVoid SetVBOs();
CVoid Render();
private:
CUInt * m_VBOID;
};
class CTriStrips : public CPolyGroup
{
public:
CTriStrips ();
~CTriStrips ();
std::vector<CUInt> m_countvector;
std::vector<CUInt *> m_indexvector;
CVoid SetVBOs();
CVoid Render();
private:
CUInt * m_VBOID;
};
class CGeometry : public CBase
{
CController *m_skinData;
CBool m_verticesSet;
CBool m_vertexSourceCopied;
public:
CVec3f* m_points;
CVec3f* m_normals;
CVec3f* m_tangents;
CVec3f* m_bNormals;
//CColor4f* m_colors;
CVec2f* m_texCoords[MAX_TEX_COORDS];
CWeight* m_weights;
CUInt m_vertexcount;
CUInt m_vertexcountmax;
CUInt* m_skinIndex;
CVec3f* m_bindPoints;
CVec3f* m_bindNormals;
CMatrix* m_skinMatrixStack;
CMatrix3x4* m_skinMatrixStack3x4;
CUInt m_VBOIDs[eGeoDataTypeMax];
CUInt m_nameIndex; //This is used for OpenGL selection. This is a unique name which we pass to glPushName() in selection mode
CUInt GetNameIndex() { return m_nameIndex; }
CVector m_minAABB; //To hold the max values of the AABB box
CVector m_maxAABB; //To hold the min values of the AABB box
CVector m_center; //object center
List<int> m_collapseMap; // to which neighbor each vertex collapses
std::vector<CInstanceGeometry*> m_instanceGeometries;
CInstanceGeometry* m_currentInstanceGeometry; //used for selection color
std::vector<CInstanceController*> m_instanceControllers;
std::vector<CVec3f*>m_physx_points;
std::vector<CTriangles*> m_physx_triangles;
CLOD* m_lod;
//To get required shader data. I get this data inside the editor.
CChar m_strNormalMap[MAX_NAME_SIZE];
CChar m_strDirtMap[MAX_NAME_SIZE];
CChar m_strGlossMap[MAX_NAME_SIZE];
CChar m_strHeightMap[MAX_NAME_SIZE];
CChar m_strDuDvMap[MAX_NAME_SIZE];
CChar m_strDiffuse[MAX_NAME_SIZE];
CFloat m_parallaxMapBias, m_parallaxMapScale;
//Material Colors
CFloat m_fAmbientColor[4];
CFloat m_fDiffuseColor[4];
CFloat m_fSpecularColor[4];
CFloat m_fEmissionColor[4];
CFloat m_fShininess, m_fTransparency;
CFloat* GetAmbient() { return m_fAmbientColor; }
CFloat* GetDiffuse() { return m_fDiffuseColor; }
CFloat* GetSpecular() { return m_fSpecularColor; }
CFloat* GetEmission() { return m_fEmissionColor; }
CFloat GetShininess() { return m_fShininess; }
CFloat GetTransparency() { return m_fTransparency; }
CVoid SetAmbient(CFloat* ambient)
{
for (CUInt i = 0; i < 4; i++)
m_fAmbientColor[i] = ambient[i];
}
CVoid SetDiffuse(CFloat* diffuse)
{
for (CUInt i = 0; i < 4; i++)
m_fDiffuseColor[i] = diffuse[i];
}
CVoid SetSpecular(CFloat* specular)
{
for (CUInt i = 0; i < 4; i++)
m_fSpecularColor[i] = specular[i];
}
CVoid SetEmission(CFloat* emission)
{
for (CUInt i = 0; i < 4; i++)
m_fEmissionColor[i] = emission[i];
}
CVoid SetShininess(CFloat shininess) { m_fShininess = shininess; }
CVoid SetTransparency(CFloat transparency) { m_fTransparency = transparency; }
//////////////////
std::vector<CImage*>m_images; //this points to all the *map pointers( see bellow )
CImage *m_normalMapImg;
CImage *m_dirtMapImg;
CImage *m_glossMapImg;
CImage *m_heightMapImg;
CImage *m_dudvMapImg;
CImage *m_diffuseImg;
CBool m_hasNormalMap, m_hasGlossMap, m_hasHeightMap, m_hasDuDvMap, m_hasDirtMap, m_hasDiffuse;
CBool m_cullFaces; // Cull faces of the current geometry?
CBool m_hasAnimation;
CUpAxis m_upAxis;
CVoid SetSkins(CInt nbrJoints );
std::vector<CPolyGroup *> m_groups;
CBool m_updateSkin;
CGeometry()
{
m_verticesSet = CFalse;
m_vertexSourceCopied = CFalse;
m_skinData = NULL;
m_bindPoints = NULL;
m_bindNormals = NULL;
m_skinMatrixStack = NULL;
m_skinMatrixStack3x4 = NULL;
m_vertexcount = 0;
m_vertexcountmax = 1/* * 1024*/;
m_points = CNewData(CVec3f, m_vertexcountmax);
m_normals = CNewData( CVec3f, m_vertexcountmax);
m_tangents = NULL;
m_bNormals = NULL;
m_skinIndex = NULL;
m_currentInstanceGeometry = NULL; //used for selection color
for( CInt i = 0; i < MAX_TEX_COORDS; i++ )
m_texCoords[i] = NULL;
m_weights = 0;
m_nameIndex = 0;
m_minAABB.m_i = m_minAABB.m_j = m_minAABB.m_k = 100000000.0f;
m_maxAABB.m_i = m_maxAABB.m_j = m_maxAABB.m_k = -100000000.0f;
memset( m_VBOIDs, 0, sizeof( m_VBOIDs ));
Cpy (m_strNormalMap, "\n");
Cpy (m_strDirtMap, "\n");
Cpy (m_strGlossMap, "\n");
Cpy (m_strHeightMap, "\n"); // I currently use the alpha channel of the normal map as a height map
Cpy (m_strDuDvMap, "\n");
Cpy (m_strDiffuse, "\n");
m_lod = NULL;
//I just use per pixel lighting at the beginning
m_hasGlossMap = m_hasNormalMap = m_hasHeightMap = m_hasDuDvMap = m_hasDirtMap = m_hasDiffuse = CFalse;
m_cullFaces = CTrue;
m_hasAnimation = CFalse;
m_normalMapImg = NULL;
m_dirtMapImg = NULL;
m_glossMapImg = NULL;
m_heightMapImg = NULL; // I currently use the alpha channel of the normal map as a height map, so this item is not required right now
m_dudvMapImg = NULL;
m_diffuseImg = NULL;
m_parallaxMapBias = -0.03;
m_parallaxMapScale = 0.06;
m_minAABB.m_i = m_minAABB.m_j = m_minAABB.m_k = 100000000.0f;
m_maxAABB.m_i = m_maxAABB.m_j = m_maxAABB.m_k = -100000000.0f;
m_updateSkin = CTrue;
//m_normalMapImg = new CImage();
//m_dirtMapImg = new CImage();
//m_glossMapImg = new CImage();
}
~CGeometry();
CVoid SetUpdateSkin(CBool set) { m_updateSkin = set; }
CBool GetUpdateSkin() { return m_updateSkin; }
CImage* GetImage( const CChar * name );
CVoid SetDiffuse( CString path );
CVoid SetNormalMap( CString path );
CVoid SetDirtMap( CString path );
CVoid SetGlossMap( CString path );
CVoid SetHeightMap( CString path );
CVoid CalculateLODInfo(CPhysXAlgorithm algorithm);
inline CVoid RegenerateIndex(CUInt MaxLODVertex, std::vector<CInt>&tri_vector)
{
for(CUInt i=0;i<m_groups.size();i++)
{
CTriangles* triangle = m_physx_triangles[i];
for (CUInt a = 0; a < triangle->m_count; a++)
{
CUInt i0, i1, i2;
i0 = Map(triangle->m_indexes[a*3], MaxLODVertex);
i1 = Map(triangle->m_indexes[1+a*3], MaxLODVertex);
i2 = Map(triangle->m_indexes[2+a*3], MaxLODVertex);
if(i0==i1 || i1==i2 || i2==i0) continue;
tri_vector.push_back( i0);
tri_vector.push_back(i1);
tri_vector.push_back(i2);
glBegin( GL_LINE_LOOP );
glVertex3f( m_physx_points[i0]->x, m_physx_points[i0]->y, m_physx_points[i0]->z );
glVertex3f( m_physx_points[i1]->x, m_physx_points[i1]->y, m_physx_points[i1]->z );
glVertex3f( m_physx_points[i2]->x, m_physx_points[i2]->y, m_physx_points[i2]->z );
glEnd();
}
}
}
inline CInt Map(CUInt a,CUInt max) {
if(max<=0) return 0;
while(a>=max) {
a= m_collapseMap[a];
}
return a;
}
inline CVoid RemoveNormalMap()
{
Cpy( m_strNormalMap, "\n" );
//CTexture::DeleteTexture( m_normalMapImg );
m_hasNormalMap = CFalse;
//m_hasHeightMap = CFalse; //Currently the alpha channel of normal map consists of height map
}
inline CVoid RemoveGlossMap()
{
Cpy( m_strGlossMap, "\n" );
//CTexture::DeleteTexture( m_glossMapImg );
m_hasGlossMap = CFalse;
}
inline CVoid RemoveHeightMap()
{
Cpy( m_strHeightMap, "\n" );
//CTexture::DeleteTexture( m_heightMapImg );
m_hasHeightMap = CFalse;
}
inline CVoid RemoveDirtMap()
{
Cpy( m_strDirtMap, "\n" );
//CTexture::DeleteTexture( m_dirtMapImg );
m_hasDirtMap = CFalse;
}
inline CVoid RemoveDiffuse()
{
Cpy( m_strDiffuse, "\n" );
//CTexture::DeleteTexture( m_diffuseImg );
m_hasDiffuse = CFalse;
}
inline CVoid SetCullFace( CBool cullFaces )
{
m_cullFaces = cullFaces;
}
CVoid DrawAABBWithLines();
CVoid DrawAABBWithQuads();
protected:
friend class CScene;
friend class CNode;
CVoid ComputeAABB_Center()
{
for ( CUInt i = 0; i < m_vertexcount; i++ )
{
if( m_points[i].x > m_maxAABB.m_i )
m_maxAABB.m_i = m_points[i].x;
if( m_points[i].y > m_maxAABB.m_j )
m_maxAABB.m_j = m_points[i].y;
if( m_points[i].z > m_maxAABB.m_k )
m_maxAABB.m_k = m_points[i].z;
if( m_points[i].x < m_minAABB.m_i )
m_minAABB.m_i = m_points[i].x;
if( m_points[i].y < m_minAABB.m_j )
m_minAABB.m_j = m_points[i].y;
if( m_points[i].z < m_minAABB.m_k )
m_minAABB.m_k = m_points[i].z;
}
if( m_minAABB.m_i == 100000000.0f && m_minAABB.m_j == 100000000.0f && m_minAABB.m_k == 100000000.0f &&
m_maxAABB.m_i == -100000000.0f && m_maxAABB.m_j == -100000000.0f && m_maxAABB.m_k == -100000000.0f ) //there's no vertex!
{
m_minAABB.m_i = m_minAABB.m_j = m_minAABB.m_k = 0;
m_maxAABB.m_i = m_maxAABB.m_j = m_maxAABB.m_k = 0;
}
CVector m_centerTemp = m_minAABB + m_maxAABB;
m_center = m_centerTemp * 0.5f;
}
CVoid SetHeightMap();
CVoid SetDuDvMap();
CVoid SetGlossMap();
CVoid ParseSource( const CChar * data, const CChar * name, const CChar * count );
CVoid DeleteSources();
CVoid AddVertexBinding( const CChar * curName, const CChar * newName, const CChar * sematic );
inline CVoid SetVerticesReady() { m_verticesSet = CTrue; }
// Draw function iterates all the polygroups in the geometry and draws them
CVoid SetupGlossTexture(CNode *parentNode, CInstance * instance)
{
CBool m_setGeoName = CFalse;
for (CUInt i = 0; i < m_groups.size(); i++ )
{
if( m_groups[i]->SetupGlossTexture( parentNode, instance ) )
m_setGeoName = CTrue;
}
if( !m_setGeoName )
{
Cpy( m_strGlossMap, "\n" );
m_hasGlossMap = CFalse;
}
else
{
//whether all the groups use the same texture or not?
CBool m_foundTarget = CFalse;
for( CUInt i = 0; i < m_groups.size(); i++ )
{
for( CUInt j = 0; j < m_groups.size(); j++ )
{
if( !Cmp( m_groups[i]->m_strGlossMap, m_groups[j]->m_strGlossMap ) ) //if these materials are not equal
{
m_foundTarget = CTrue;
}
if( m_foundTarget )
break;
}
if( m_foundTarget )
break;
}
if( m_foundTarget )
{
Cpy( m_strGlossMap, "*Different Textures*" );
m_hasGlossMap = CTrue;
}
else //same materials
{
Cpy( m_strGlossMap, m_groups[0]->m_strGlossMap );
m_hasGlossMap = CTrue;
}
}
}
CVoid SetupDirtTexture(CNode *parentNode, CInstance * instance)
{
CBool m_setGeoName = CFalse;
for (CUInt i = 0; i < m_groups.size(); i++ )
{
if( m_groups[i]->SetupDirtTexture( parentNode, instance ) )
m_setGeoName = CTrue;
}
if( !m_setGeoName )
{
Cpy( m_strDirtMap, "\n" );
m_hasDirtMap = CFalse;
}
else
{
//whether all the groups use the same texture or not?
CBool m_foundTarget = CFalse;
for( CUInt i = 0; i < m_groups.size(); i++ )
{
for( CUInt j = 0; j < m_groups.size(); j++ )
{
if( !Cmp( m_groups[i]->m_strDirtMap, m_groups[j]->m_strDirtMap ) ) //if these materials are not equal
{
m_foundTarget = CTrue;
}
if( m_foundTarget )
break;
}
if( m_foundTarget )
break;
}
if( m_foundTarget )
{
Cpy( m_strDirtMap, "*Different Textures*" );
m_hasDirtMap = CTrue;
}
else //same materials
{
Cpy( m_strDirtMap, m_groups[0]->m_strDirtMap );
m_hasDirtMap = CTrue;
}
}
}
CVoid SetupNormalTexture(CNode *parentNode, CInstance * instance)
{
CBool m_setGeoName = CFalse;
for (CUInt i = 0; i < m_groups.size(); i++ )
{
if( m_groups[i]->SetupNormalTexture( parentNode, instance ) )
m_setGeoName = CTrue;
}
if( !m_setGeoName )
{
Cpy( m_strNormalMap, "\n" );
m_hasNormalMap = CFalse;
}
else
{
//whether all the groups use the same texture or not?
CBool m_foundTarget = CFalse;
for( CUInt i = 0; i < m_groups.size(); i++ )
{
for( CUInt j = 0; j < m_groups.size(); j++ )
{
if( !Cmp( m_groups[i]->m_strNormalMap, m_groups[j]->m_strNormalMap ) ) //if these materials are not equal
{
m_foundTarget = CTrue;
}
if( m_foundTarget )
break;
}
if( m_foundTarget )
break;
}
if( m_foundTarget )
{
Cpy( m_strNormalMap, "*Different Textures*" );
m_hasNormalMap = CTrue;
}
else //same materials
{
Cpy( m_strNormalMap, m_groups[0]->m_strNormalMap );
m_hasNormalMap = CTrue;
}
}
}
CVoid SetupDiffuseTexture(CNode *parentNode, CInstance * instance)
{
CBool m_setGeoName = CFalse;
for (CUInt i = 0; i < m_groups.size(); i++ )
{
if( m_groups[i]->SetupDiffuseTexture( parentNode, instance ) )
m_setGeoName = CTrue;
}
if( !m_setGeoName )
{
Cpy( m_strDiffuse, "\n" );
m_hasDiffuse = CFalse;
}
else
{
//whether all the groups use the same texture or not?
CBool m_foundTarget = CFalse;
for( CUInt i = 0; i < m_groups.size(); i++ )
{
for( CUInt j = 0; j < m_groups.size(); j++ )
{
if( !Cmp( m_groups[i]->m_strDiffuse, m_groups[j]->m_strDiffuse ) ) //if these materials are not equal
{
m_foundTarget = CTrue;
}
if( m_foundTarget )
break;
}
if( m_foundTarget )
break;
}
if( m_foundTarget )
{
Cpy( m_strDiffuse, "*Different Textures*" );
m_hasDiffuse = CTrue;
}
else //same materials
{
Cpy( m_strDiffuse, m_groups[0]->m_strDiffuse );
m_hasDiffuse = CTrue;
}
}
}
CVoid DrawSelectionMode(CNode *parentNode, CInstance * instance);
CVoid SetRender();
CVoid ResetStates();
CVoid SetGroupRender( CPolyGroup* group );
CVoid ResetGroupStates( CPolyGroup* group );
CVoid DrawSkinned(CNode *parentNode, CInstance * instance );
CVoid DrawSkinnedSelectionMode(CNode *parentNode, CInstance * instance );
inline CVoid SetController( CController * ctrl )
{
m_skinData = ctrl;
for (CUInt i = 0; i < m_groups.size(); i++)
m_groups[i]->SetHasSkin();
}
CChar * GetSkinName();
//inline CInt GetTotalNumTris(){ return TotalNumTris; }
public:
inline CBool HasSkinController()
{
if ( m_skinData )
return CTrue;
else
return CFalse;
}
CVoid GetJointsForWeights( CJoint *& Joints, CInt & NumJoints );
CVoid Draw(CNode *parentNode, CInstance * instance);
};
struct CTransparentGeometry
{
CInstancePrefab* m_instancePrefab;
CScene* m_scene;
CInstanceGeometry* m_instanceGeometry;
};
struct SortTransparentGeometry
{
inline bool operator() (const CTransparentGeometry& struct1, const CTransparentGeometry& struct2)
{
return (struct1.m_instanceGeometry->GetDistanceFromCamera() > struct2.m_instanceGeometry->GetDistanceFromCamera());
}
};
| 411 | 0.982782 | 1 | 0.982782 | game-dev | MEDIA | 0.488001 | game-dev | 0.589487 | 1 | 0.589487 |
EsProgram/WaveformProvider | 4,169 | Assets/UniDanceSample/UnityChan/Scripts/CameraController.cs | //CameraController.cs for UnityChan
//Original Script is here:
//TAK-EMI / CameraController.cs
//https://gist.github.com/TAK-EMI/d67a13b6f73bed32075d
//https://twitter.com/TAK_EMI
//
//Revised by N.Kobayashi 2014/5/15
//Change : To prevent rotation flips on XY plane, use Quaternion in cameraRotate()
//Change : Add the instrustion window
//Change : Add the operation for Mac
//
using UnityEngine;
using System.Collections;
namespace UnityChan
{
enum MouseButtonDown
{
MBD_LEFT = 0,
MBD_RIGHT,
MBD_MIDDLE,
};
public class CameraController : MonoBehaviour
{
[SerializeField]
private Vector3 focus = Vector3.zero;
[SerializeField]
private GameObject focusObj = null;
public bool showInstWindow = true;
private Vector3 oldPos;
void setupFocusObject(string name)
{
GameObject obj = this.focusObj = new GameObject(name);
obj.transform.position = this.focus;
obj.transform.LookAt(this.transform.position);
return;
}
void Start ()
{
if (this.focusObj == null)
this.setupFocusObject("CameraFocusObject");
Transform trans = this.transform;
transform.parent = this.focusObj.transform;
trans.LookAt(this.focus);
return;
}
void Update ()
{
this.mouseEvent();
return;
}
//Show Instrustion Window
void OnGUI()
{
if(showInstWindow){
GUI.Box(new Rect(Screen.width -210, Screen.height - 100, 200, 90), "Camera Operations");
GUI.Label(new Rect(Screen.width -200, Screen.height - 80, 200, 30),"RMB / Alt+LMB: Tumble");
GUI.Label(new Rect(Screen.width -200, Screen.height - 60, 200, 30),"MMB / Alt+Cmd+LMB: Track");
GUI.Label(new Rect(Screen.width -200, Screen.height - 40, 200, 30),"Wheel / 2 Fingers Swipe: Dolly");
}
}
void mouseEvent()
{
float delta = Input.GetAxis("Mouse ScrollWheel");
if (delta != 0.0f)
this.mouseWheelEvent(delta);
if (Input.GetMouseButtonDown((int)MouseButtonDown.MBD_LEFT) ||
Input.GetMouseButtonDown((int)MouseButtonDown.MBD_MIDDLE) ||
Input.GetMouseButtonDown((int)MouseButtonDown.MBD_RIGHT))
this.oldPos = Input.mousePosition;
this.mouseDragEvent(Input.mousePosition);
return;
}
void mouseDragEvent(Vector3 mousePos)
{
Vector3 diff = mousePos - oldPos;
if(Input.GetMouseButton((int)MouseButtonDown.MBD_LEFT))
{
//Operation for Mac : "Left Alt + Left Command + LMB Drag" is Track
if(Input.GetKey(KeyCode.LeftAlt) && Input.GetKey(KeyCode.LeftCommand))
{
if (diff.magnitude > Vector3.kEpsilon)
this.cameraTranslate(-diff / 100.0f);
}
//Operation for Mac : "Left Alt + LMB Drag" is Tumble
else if (Input.GetKey(KeyCode.LeftAlt))
{
if (diff.magnitude > Vector3.kEpsilon)
this.cameraRotate(new Vector3(diff.y, diff.x, 0.0f));
}
//Only "LMB Drag" is no action.
}
//Track
else if (Input.GetMouseButton((int)MouseButtonDown.MBD_MIDDLE))
{
if (diff.magnitude > Vector3.kEpsilon)
this.cameraTranslate(-diff / 100.0f);
}
//Tumble
else if (Input.GetMouseButton((int)MouseButtonDown.MBD_RIGHT))
{
if (diff.magnitude > Vector3.kEpsilon)
this.cameraRotate(new Vector3(diff.y, diff.x, 0.0f));
}
this.oldPos = mousePos;
return;
}
//Dolly
public void mouseWheelEvent(float delta)
{
Vector3 focusToPosition = this.transform.position - this.focus;
Vector3 post = focusToPosition * (1.0f + delta);
if (post.magnitude > 0.01)
this.transform.position = this.focus + post;
return;
}
void cameraTranslate(Vector3 vec)
{
Transform focusTrans = this.focusObj.transform;
vec.x *= -1;
focusTrans.Translate(Vector3.right * vec.x);
focusTrans.Translate(Vector3.up * vec.y);
this.focus = focusTrans.position;
return;
}
public void cameraRotate(Vector3 eulerAngle)
{
//Use Quaternion to prevent rotation flips on XY plane
Quaternion q = Quaternion.identity;
Transform focusTrans = this.focusObj.transform;
focusTrans.localEulerAngles = focusTrans.localEulerAngles + eulerAngle;
//Change this.transform.LookAt(this.focus) to q.SetLookRotation(this.focus)
q.SetLookRotation (this.focus) ;
return;
}
}
} | 411 | 0.940026 | 1 | 0.940026 | game-dev | MEDIA | 0.574155 | game-dev,desktop-app | 0.993653 | 1 | 0.993653 |
progrium/darwinkit | 2,165 | macos/mediaplayer/now_playing_info_language_option_group.gen.go | // Code generated by DarwinKit. DO NOT EDIT.
package mediaplayer
import (
"unsafe"
"github.com/progrium/darwinkit/objc"
)
// The class instance for the [NowPlayingInfoLanguageOptionGroup] class.
var NowPlayingInfoLanguageOptionGroupClass = _NowPlayingInfoLanguageOptionGroupClass{objc.GetClass("MPNowPlayingInfoLanguageOptionGroup")}
type _NowPlayingInfoLanguageOptionGroupClass struct {
objc.Class
}
// An interface definition for the [NowPlayingInfoLanguageOptionGroup] class.
type INowPlayingInfoLanguageOptionGroup interface {
objc.IObject
AllowEmptySelection() bool
}
// A grouped set of language options where only a single language option can be active at a time. [Full Topic]
//
// [Full Topic]: https://developer.apple.com/documentation/mediaplayer/mpnowplayinginfolanguageoptiongroup?language=objc
type NowPlayingInfoLanguageOptionGroup struct {
objc.Object
}
func NowPlayingInfoLanguageOptionGroupFrom(ptr unsafe.Pointer) NowPlayingInfoLanguageOptionGroup {
return NowPlayingInfoLanguageOptionGroup{
Object: objc.ObjectFrom(ptr),
}
}
func (nc _NowPlayingInfoLanguageOptionGroupClass) Alloc() NowPlayingInfoLanguageOptionGroup {
rv := objc.Call[NowPlayingInfoLanguageOptionGroup](nc, objc.Sel("alloc"))
return rv
}
func (nc _NowPlayingInfoLanguageOptionGroupClass) New() NowPlayingInfoLanguageOptionGroup {
rv := objc.Call[NowPlayingInfoLanguageOptionGroup](nc, objc.Sel("new"))
rv.Autorelease()
return rv
}
func NewNowPlayingInfoLanguageOptionGroup() NowPlayingInfoLanguageOptionGroup {
return NowPlayingInfoLanguageOptionGroupClass.New()
}
func (n_ NowPlayingInfoLanguageOptionGroup) Init() NowPlayingInfoLanguageOptionGroup {
rv := objc.Call[NowPlayingInfoLanguageOptionGroup](n_, objc.Sel("init"))
return rv
}
// A Boolean that indicates whether the system requires a selection for the language option group. [Full Topic]
//
// [Full Topic]: https://developer.apple.com/documentation/mediaplayer/mpnowplayinginfolanguageoptiongroup/1623161-allowemptyselection?language=objc
func (n_ NowPlayingInfoLanguageOptionGroup) AllowEmptySelection() bool {
rv := objc.Call[bool](n_, objc.Sel("allowEmptySelection"))
return rv
}
| 411 | 0.633215 | 1 | 0.633215 | game-dev | MEDIA | 0.562721 | game-dev | 0.639551 | 1 | 0.639551 |
bilibili/LastOrder | 30,105 | src/LastOrder_DLL/LastOrder/AttackManager.cpp | #include "AttackManager.h"
AttackManager::AttackManager()
{
// do init first
myArmy[BWAPI::UnitTypes::Zerg_Zergling] = new ZerglingArmy();
myArmy[BWAPI::UnitTypes::Zerg_Mutalisk] = new MutaliskArmy();
myArmy[BWAPI::UnitTypes::Zerg_Hydralisk] = new HydraliskArmy();
myArmy[BWAPI::UnitTypes::Zerg_Overlord] = new OverLordArmy();
myArmy[BWAPI::UnitTypes::Zerg_Lurker] = new LurkerArmy();
myArmy[BWAPI::UnitTypes::Zerg_Scourge] = new ScourgeArmy();
myArmy[BWAPI::UnitTypes::Zerg_Ultralisk] = new UltraliskArmy();
myArmy[BWAPI::UnitTypes::Zerg_Devourer] = new DevourerArmy();
myArmy[BWAPI::UnitTypes::Zerg_Guardian] = new GuardianArmy();
isNeedDefend = false;
unRallyArmy.reserve(1000);
hasWorkerScouter = false;
assignWorkerToScouter = false;
nextScoutTime = 24 * 60 * 5;
nextOverlordPatrolTime = 0;
assignOverlord = false;
enemyDisappearedTime = 0;
}
bool AttackManager::hasGroundUnit()
{
for (auto& army : myArmy)
{
if (!army.first.isFlyer() && !army.second->getUnits().empty())
{
return true;
}
}
return false;
}
bool AttackManager::hasAttackArmy()
{
for (auto army : myArmy)
{
if (army.first != BWAPI::UnitTypes::Zerg_Overlord && army.second->getUnits().size() > 0)
{
return true;
}
}
return false;
}
std::map<BWAPI::UnitType, int> AttackManager::reaminArmy()
{
std::map<BWAPI::UnitType, int> result;
for (auto army : myArmy)
{
if (army.first != BWAPI::UnitTypes::Zerg_Overlord)
{
result[army.first] = army.second->getUnits().size();
}
}
return result;
}
void AttackManager::groupArmy()
{
std::map<const Area*, TilePosition> & myRegions = InformationManager::Instance().getBaseOccupiedRegions(BWAPI::Broodwar->self());
if (myRegions.find(BWEMMap.GetArea(InformationManager::Instance().getOurNatrualLocation())) != myRegions.end())
rallyPosition = BWAPI::Position(InformationManager::Instance().getOurNatrualLocation());
else
rallyPosition = BWAPI::Position(BWAPI::Broodwar->self()->getStartLocation());
//battle unit rally to the natural choke center
for (auto it = unRallyArmy.begin(); it != unRallyArmy.end();)
{
if ((*it)->canIssueCommand(BWAPI::UnitCommand(*it, BWAPI::UnitCommandTypes::Move, nullptr, rallyPosition.x, rallyPosition.y, 0)))
{
(*it)->move(rallyPosition);
//may add lurker egg
if (myArmy.find((*it)->getType()) != myArmy.end())
{
myArmy[(*it)->getType()]->addUnit(*it);
}
it = unRallyArmy.erase(it);
}
else
{
it++;
}
}
int count = 0;
bool isArmyUnderAttack = false;
BWAPI::Position underAttackPosition;
int natrualRallyGroundMax = 18;
unitAttackPath.clear();
unitRetreatPath.clear();
enemyAssign.clear();
unitRetreatInfo.clear();
//group outside unit
for (auto armyUnits : myArmy)
{
if (armyUnits.first == BWAPI::UnitTypes::Zerg_Overlord)
continue;
if (armyUnits.first == BWAPI::UnitTypes::Zerg_Zergling && hasWorkerScouter)
continue;
for (auto u : armyUnits.second->getUnits())
{
Position trueRallyPosition;
if (myRegions.find(BWEMMap.GetArea(InformationManager::Instance().getOurNatrualLocation())) != myRegions.end())
{
if ((armyUnits.first.isFlyer() == false && count < natrualRallyGroundMax) || armyUnits.first.isFlyer())
{
trueRallyPosition = rallyPosition;
count++;
}
else
{
trueRallyPosition = Position(BWAPI::Broodwar->self()->getStartLocation());
}
}
else
{
trueRallyPosition = Position(BWAPI::Broodwar->self()->getStartLocation());
}
//armyUnits.second->microUpdate(u, unitAttackPath, unitRetreatPath, unitRetreatInfo,
// enemyAssign, false, trueRallyPosition, GroupArmy);
if (BWEMMap.GetArea(u.unit->getTilePosition()) == BWEMMap.GetArea(TilePosition(trueRallyPosition)))
{
BattleArmy::smartAttackMove(u.unit, trueRallyPosition);
}
else
{
Position nextP = Astar::Instance().getNextMovePosition(u.unit, trueRallyPosition);
BattleArmy::smartAttackMove(u.unit, nextP);
}
}
}
}
void AttackManager::overlordProtect()
{
OverLordArmy* overlords = dynamic_cast<OverLordArmy*>(myArmy[BWAPI::UnitTypes::Zerg_Overlord]);
map<Unit, int> sporeAssign;
for (size_t i = 0; i < overlords->getUnits().size(); i++)
{
overlords->overlordUpdate(overlords->getUnits()[i], sporeAssign, i);
}
}
// attack manger trigger for two situation:defend and attack
void AttackManager::update()
{
groupArmy();
DefendUpdate();
ScoutUpdate();
PatrolUpdate();
overlordProtect();
}
void AttackManager::addArmyToTactic(tacticType type)
{
if (TacticManager::Instance().isOneTacticRun(type))
{
Position attackPosition = TacticManager::Instance().getTacticPosition(type);
switch (type)
{
case MutaliskHarassTac:
{
TacticManager::Instance().addTacticArmy(MutaliskHarassTac, attackPosition, myArmy, BWAPI::UnitTypes::Zerg_Mutalisk, myArmy[BWAPI::UnitTypes::Zerg_Mutalisk]->getUnits().size());
TacticManager::Instance().addTacticArmy(MutaliskHarassTac, attackPosition, myArmy, BWAPI::UnitTypes::Zerg_Scourge, myArmy[BWAPI::UnitTypes::Zerg_Scourge]->getUnits().size());
}
break;
case HydraliskPushTactic:
{
for (auto army : myArmy)
{
if (army.first != BWAPI::UnitTypes::Zerg_Overlord)
{
if (army.first == BWAPI::UnitTypes::Zerg_Zergling && hasWorkerScouter && army.second->getUnits().size() > 2)
TacticManager::Instance().addTacticArmy(HydraliskPushTactic, attackPosition, myArmy, army.first, army.second->getUnits().size() - 2);
else
TacticManager::Instance().addTacticArmy(HydraliskPushTactic, attackPosition, myArmy, army.first, army.second->getUnits().size());
}
}
//TacticManager::Instance().addTacticArmy(HydraliskPushTactic, attackPosition, myArmy, BWAPI::UnitTypes::Zerg_Overlord, 1);
map<BWAPI::UnitType, int> tacArmy = TacticManager::Instance().getTacArmyForceDetail(type, attackPosition);
if (InformationManager::Instance().isEnemyHasInvisibleUnit() && BWAPI::Broodwar->getFrameCount() > 5 * 24 * 60
&& tacArmy[UnitTypes::Zerg_Overlord] < 2)
{
TacticManager::Instance().addTacticArmy(HydraliskPushTactic, attackPosition, myArmy, BWAPI::UnitTypes::Zerg_Overlord, 1);
}
}
break;
default:
break;
}
}
//else
//{
// logInfo("AttackManager", "tactic is not running " + to_string(type), "BIG_ERROR_AttackManager");
//}
}
void AttackManager::issueAttackCommand(tacticType type, BWAPI::Position attackPosition)
{
if (attackPosition == BWAPI::Positions::None)
{
logInfo("AttackManager", "attackPosition is invalid " + to_string(type), "BIG_ERROR_AttackManager");
return;
}
triggerTactic(type, attackPosition);
}
/*
void AttackManager::ScoutUpdate()
{
int curOverlordCount = BWAPI::Broodwar->self()->allUnitCount(BWAPI::UnitTypes::Zerg_Overlord);
std::vector<UnitState>& army = myArmy[BWAPI::UnitTypes::Zerg_Overlord]->getUnits();
bool isTacticRunning = TacticManager::Instance().isOneTacticRun(ScoutTac);
if (!isTacticRunning)
{
TacticManager::Instance().addTactic(ScoutTac, BWAPI::Positions::None);
std::vector<UnitState>& army = myArmy[BWAPI::UnitTypes::Zerg_Overlord]->getUnits();
for (auto it = army.begin(); it != army.end();)
{
TacticManager::Instance().addTacticUnit(ScoutTac, BWAPI::Positions::None, it->unit);
it = army.erase(it);
}
}
else
{
if (Broodwar->self()->allUnitCount(UnitTypes::Zerg_Drone) == 9 && InformationManager::Instance().GetEnemyBasePosition() == BWAPI::Positions::None &&
!assignWorkerToScouter)
{
Unit scounter = WorkerManager::Instance().addScountWorker();
TacticManager::Instance().addTacticUnit(ScoutTac, BWAPI::Positions::None, scounter);
assignWorkerToScouter = true;
}
if (curOverlordCount - army.size() < 4)
{
for (auto it = army.begin(); it != army.end();)
{
//can generate safe attack path
TacticManager::Instance().addTacticUnit(ScoutTac, BWAPI::Positions::None, it->unit);
it = army.erase(it);
}
}
if (TacticManager::Instance().isAssignScoutZergling())
return;
int checkInterval = 0;
if (BWAPI::Broodwar->getFrameCount() >= 4 * 24 * 60 && BWAPI::Broodwar->getFrameCount() < 7 * 24 * 60)
checkInterval = 24 * 30;
else if (BWAPI::Broodwar->getFrameCount() >= 7 * 24 * 60 && BWAPI::Broodwar->getFrameCount() < 11 * 24 * 60)
checkInterval = 24 * 30;
else
checkInterval = 24 * 30;
if (InformationManager::Instance().GetEnemyBasePosition() != Positions::None
&& BWAPI::Broodwar->getFrameCount() > nextScoutTime)
{
nextScoutTime = BWAPI::Broodwar->getFrameCount() + checkInterval;
int armyZerglingCount = myArmy[BWAPI::UnitTypes::Zerg_Zergling]->getUnits().size();
if (armyZerglingCount == 0)
{
if (Broodwar->self()->allUnitCount(UnitTypes::Zerg_Drone) <= 15)
{
return;
}
//assign worker to scout
Unit scounter = WorkerManager::Instance().addScountWorker();
if (scounter != NULL)
{
TacticManager::Instance().addTacticUnit(ScoutTac, BWAPI::Positions::None, scounter);
}
}
else
{
std::vector<UnitState>& army = myArmy[BWAPI::UnitTypes::Zerg_Zergling]->getUnits();
for (auto it = army.begin(); it != army.end();)
{
TacticManager::Instance().addTacticUnit(ScoutTac, BWAPI::Positions::None, it->unit);
it = army.erase(it);
break;
}
}
}
}
}
*/
void AttackManager::ScoutUpdate()
{
int curOverlordCount = BWAPI::Broodwar->self()->allUnitCount(BWAPI::UnitTypes::Zerg_Overlord);
std::vector<UnitState>& army = myArmy[BWAPI::UnitTypes::Zerg_Overlord]->getUnits();
bool isTacticRunning = TacticManager::Instance().isOneTacticRun(ScoutTac);
if (!isTacticRunning)
{
//assign scout task to the 9th drone
if (Broodwar->self()->allUnitCount(UnitTypes::Zerg_Drone) >= 5) {
TacticManager::Instance().addTactic(ScoutTac, BWAPI::Positions::None);
Unit scounter = WorkerManager::Instance().addScountWorker();
if (scounter != NULL) {
TacticManager::Instance().addTacticUnit(ScoutTac, BWAPI::Positions::None, scounter);
assignWorkerToScouter = true;
}
}
}
else
{
/*
if (Broodwar->self()->allUnitCount(UnitTypes::Zerg_Drone) == 9 && InformationManager::Instance().GetEnemyBasePosition() == BWAPI::Positions::None &&
!assignWorkerToScouter)
{
Unit scounter = WorkerManager::Instance().addScountWorker();
TacticManager::Instance().addTacticUnit(ScoutTac, BWAPI::Positions::None, scounter);
assignWorkerToScouter = true;
}
if (curOverlordCount - army.size() < 4)
{
for (auto it = army.begin(); it != army.end();)
{
//can generate safe attack path
TacticManager::Instance().addTacticUnit(ScoutTac, BWAPI::Positions::None, it->unit);
it = army.erase(it);
}
}
*/
if (assignOverlord == false &&
InformationManager::Instance().GetEnemyBasePosition() != Positions::None &&
Broodwar->enemy()->getRace() != Races::Terran &&
army.size() > 0)
{
Position enemyBase = InformationManager::Instance().GetEnemyBasePosition();
double totalDistance = Position(Broodwar->self()->getStartLocation()).getDistance(enemyBase);
double flyFrame = totalDistance / UnitTypes::Zerg_Overlord.topSpeed();
int desiredReachTime = 24 * 60 * 8;
int startScoutTime = desiredReachTime - int(flyFrame);
if (Broodwar->getFrameCount() > startScoutTime)
{
logInfo("AttackManager", "send overlord to enemy base ");
TacticManager::Instance().addTacticUnit(ScoutTac, BWAPI::Positions::None, army.back().unit);
army.pop_back();
assignOverlord = true;
}
}
int checkInterval = 0;
if (BWAPI::Broodwar->getFrameCount() >= 4 * 24 * 60 && BWAPI::Broodwar->getFrameCount() < 7 * 24 * 60)
checkInterval = 24 * 30;
else if (BWAPI::Broodwar->getFrameCount() >= 7 * 24 * 60 && BWAPI::Broodwar->getFrameCount() < 11 * 24 * 60)
checkInterval = 24 * 30;
else
checkInterval = 24 * 30;
if (TacticManager::Instance().isAssignScoutZergling())
{
nextScoutTime = BWAPI::Broodwar->getFrameCount() + checkInterval;
return;
}
if (InformationManager::Instance().GetEnemyBasePosition() != Positions::None
&& BWAPI::Broodwar->getFrameCount() > nextScoutTime)
{
nextScoutTime = BWAPI::Broodwar->getFrameCount() + checkInterval;
int armyZerglingCount = myArmy[BWAPI::UnitTypes::Zerg_Zergling]->getUnits().size();
if (armyZerglingCount == 0)
{
if (Broodwar->self()->allUnitCount(UnitTypes::Zerg_Drone) <= 15)
{
return;
}
//assign worker to scout
Unit scounter = WorkerManager::Instance().addScountWorker();
if (scounter != NULL)
{
TacticManager::Instance().addTacticUnit(ScoutTac, BWAPI::Positions::None, scounter);
}
}
else
{
std::vector<UnitState>& army = myArmy[BWAPI::UnitTypes::Zerg_Zergling]->getUnits();
for (auto it = army.begin(); it != army.end();)
{
TacticManager::Instance().addTacticUnit(ScoutTac, BWAPI::Positions::None, it->unit);
it = army.erase(it);
break;
}
}
}
}
}
void AttackManager::PatrolUpdate() {
std::vector<UnitState>& army = myArmy[BWAPI::UnitTypes::Zerg_Overlord]->getUnits();
bool isTacticRunning = TacticManager::Instance().isOneTacticRun(PatrolTac);
if (!isTacticRunning) {
TacticManager::Instance().addTactic(PatrolTac, BWAPI::Positions::None);
std::vector<UnitState>& army = myArmy[BWAPI::UnitTypes::Zerg_Overlord]->getUnits();
for (auto it = army.begin(); it != army.end();)
{
TacticManager::Instance().addTacticUnit(PatrolTac, BWAPI::Positions::None, it->unit);
it = army.erase(it);
break;
}
}
else {
if (TacticManager::Instance().isAssignPatrolOverlord()) {
int checkInterval = 24 * 60 * 1;
nextOverlordPatrolTime = Broodwar->getFrameCount() + checkInterval;
return;
}
if (Broodwar->getFrameCount() > nextOverlordPatrolTime) {
// not enough overlord(less than the total number of overlord required plus 3)
if (int(army.size()) <= (Broodwar->self()->supplyUsed() + 15) / 16 + 2)
return;
int assignOverlord = 1;
//// if we have too many overlord, assign two overlord to patrol
//if (army.size() >= (Broodwar->self()->supplyUsed() + 15) / 16 + 7)
// assignOverlord = 2;
//// if we have too too many overlord, assign two overlord to patrol
//if (army.size() >= (Broodwar->self()->supplyUsed() + 15) / 16 + 10)
// assignOverlord = 3;
std::vector<UnitState>& army = myArmy[BWAPI::UnitTypes::Zerg_Overlord]->getUnits();
for (auto it = army.begin(); it != army.end();)
{
TacticManager::Instance().addTacticUnit(PatrolTac, BWAPI::Positions::None, it->unit);
it = army.erase(it);
assignOverlord--;
if (assignOverlord == 0)
break;
}
}
}
}
void AttackManager::triggerTactic(tacticType tacType, BWAPI::Position attackPosition)
{
bool isTacticRunning;
switch (tacType)
{
case MutaliskHarassTac:
{
isTacticRunning = TacticManager::Instance().isOneTacticRun(MutaliskHarassTac);
if (!isTacticRunning)
{
if (tacticTrigCondition(MutaliskHarassTac, attackPosition))
{
TacticManager::Instance().addTactic(MutaliskHarassTac, attackPosition);
TacticManager::Instance().addTacticArmy(MutaliskHarassTac, attackPosition, myArmy, BWAPI::UnitTypes::Zerg_Mutalisk, myArmy[BWAPI::UnitTypes::Zerg_Mutalisk]->getUnits().size());
TacticManager::Instance().addTacticArmy(MutaliskHarassTac, attackPosition, myArmy, BWAPI::UnitTypes::Zerg_Scourge, myArmy[BWAPI::UnitTypes::Zerg_Scourge]->getUnits().size());
}
}
}
break;
case HydraliskPushTactic:
{
// trigger hydrisk attack
isTacticRunning = TacticManager::Instance().isOneTacticRun(HydraliskPushTactic);
if (!isTacticRunning)
{
if (tacticTrigCondition(HydraliskPushTactic, attackPosition))
{
TacticManager::Instance().addTactic(HydraliskPushTactic, attackPosition);
for (auto army : myArmy)
{
if (army.first != BWAPI::UnitTypes::Zerg_Overlord)
{
if (army.first == BWAPI::UnitTypes::Zerg_Zergling && hasWorkerScouter && army.second->getUnits().size() > 2)
TacticManager::Instance().addTacticArmy(HydraliskPushTactic, attackPosition, myArmy, army.first, army.second->getUnits().size() - 2);
else
TacticManager::Instance().addTacticArmy(HydraliskPushTactic, attackPosition, myArmy, army.first, army.second->getUnits().size());
}
}
if (InformationManager::Instance().isEnemyHasInvisibleUnit() && BWAPI::Broodwar->getFrameCount() > 5 * 24 * 60)
{
TacticManager::Instance().addTacticArmy(HydraliskPushTactic, attackPosition, myArmy, BWAPI::UnitTypes::Zerg_Overlord, 2);
}
}
}
}
break;
case AirdropTac: {
if (tacticTrigCondition(AirdropTac, attackPosition))
{
TacticManager::Instance().addTactic(AirdropTac, attackPosition);
std::pair<UnitType, int> armyInfo = availableAirDropArmy();
//TacticManager::Instance().addTacticArmy(AirdropTac, attackPosition, myArmy, UnitTypes::Zerg_Overlord, 1);
std::vector<UnitState>& army = myArmy[BWAPI::UnitTypes::Zerg_Overlord]->getUnits();
bool foundFullHPOverlord = false;
int maxHP = -1;
auto targetIT = army.begin();
for (auto it = army.begin(); it != army.end();)
{
if ((*it).unit->getHitPoints() > maxHP) {
maxHP = (*it).unit->getHitPoints();
targetIT = it;
}
if ((*it).unit->getHitPoints() == (*it).unit->getType().maxHitPoints()) {
foundFullHPOverlord = true;
TacticManager::Instance().addTacticUnit(AirdropTac, attackPosition, it->unit);
it = army.erase(it);
break;
}
else {
it++;
}
}
if (!foundFullHPOverlord) {
TacticManager::Instance().addTacticUnit(AirdropTac, attackPosition, targetIT->unit);
army.erase(targetIT);
}
TacticManager::Instance().addTacticArmy(AirdropTac, attackPosition, myArmy, armyInfo.first, armyInfo.second);
//std::vector<UnitState>& army_overlord = TacticManager::Instance().getTacArmy(AirdropTac, attackPosition)[UnitTypes::Zerg_Overlord]->getUnits();
//for (auto it = army_overlord.begin(); it != army_overlord.end(); it++)
// TacticManager::Instance().addTacticUnit(AirdropTac, attackPosition, it->unit);
std::vector<UnitState>& army_airdrop = TacticManager::Instance().getTacArmy(AirdropTac, attackPosition)[armyInfo.first]->getUnits();
for (auto it = army_airdrop.begin(); it != army_airdrop.end(); it++)
TacticManager::Instance().addTacticUnit(AirdropTac, attackPosition, it->unit);
}
}
break;
default:
{
logInfo("AttackManager", "tactype is invalid " + to_string(tacType), "BIG_ERROR_AttackManager");
}
break;
}
}
bool AttackManager::tacticTrigCondition(int tac, BWAPI::Position attackPosition)
{
if (tac != int(AirdropTac) && TacticManager::Instance().isTacticRun(tacticType(tac), attackPosition))
return false;
if (tac == int(MutaliskHarassTac))
{
return myArmy[BWAPI::UnitTypes::Zerg_Mutalisk]->getUnits().size() > 0;
}
else if (tac == int(HydraliskPushTactic))
{
return hasGroundUnit();
}
else if (tac == int(AirdropTac)) {
return availableAirDropArmy().first != UnitTypes::None;
}
return false;
}
void AttackManager::addTacArmy(int needArmySupply, tacticType tacType, BWAPI::Position attackPosition, bool allAirEnemy, bool allGroundEnemy)
{
vector<std::pair<UnitState, double>> unitDistance;
unitDistance.reserve(1000);
for (auto& army : myArmy)
{
if (army.first != BWAPI::UnitTypes::Zerg_Overlord)
{
if (allAirEnemy == true && army.first.airWeapon() == WeaponTypes::None)
{
continue;
}
if (allGroundEnemy == true && army.first.groundWeapon() == WeaponTypes::None)
{
continue;
}
for (auto u : army.second->getUnits())
{
unitDistance.push_back(std::pair<UnitState, double>(u, u.unit->getDistance(attackPosition)));
}
army.second->getUnits().clear();
}
}
std::sort(unitDistance.begin(), unitDistance.end(),
[](const std::pair<UnitState, double>& a, const std::pair<UnitState, double>& b)
{
return a.second < b.second;
});
for (auto army : unitDistance)
{
if (needArmySupply > 0)
{
TacticManager::Instance().addTacticUnit(DefendTactic, attackPosition, army.first.unit);
needArmySupply -= army.first.unit->getType().supplyRequired();
}
else
{
if (myArmy.find(army.first.unit->getType()) != myArmy.end())
myArmy[army.first.unit->getType()]->addUnit(army.first.unit);
else
logInfo("AttackManager", "addTacArmy " + to_string(army.first.unit->getType()) + " not exist!", "ERROR");
}
}
}
void AttackManager::DefendUpdate()
{
//each base corresponding to defend enemy
std::map<const Area*, std::set<BWAPI::Unit>>& enemyUnitsTargetRegion = \
InformationManager::Instance().getDefendEnemyInfo();
std::map<const Area*, TilePosition>& myRegion = InformationManager::Instance().getBaseOccupiedRegions(BWAPI::Broodwar->self());
std::map<const Area*, int> enemyUnitsInRegionSupply;
std::map<const Area*, int> enemyUnitsInRegionFlySupply;
//get grouped enemy supply info
for (auto baseEnemy : enemyUnitsTargetRegion)
{
for (auto enemyUnit : baseEnemy.second)
{
if (!enemyUnit->getType().isBuilding())
{
if (enemyUnit->getType().isFlyer())
enemyUnitsInRegionFlySupply[baseEnemy.first] += enemyUnit->getType().supplyRequired();
enemyUnitsInRegionSupply[baseEnemy.first] += enemyUnit->getType().supplyRequired();
}
else
{
if (enemyUnit->getType().canAttack())
{
enemyUnitsInRegionSupply[baseEnemy.first] += 8;
}
else if (enemyUnit->getType() == BWAPI::UnitTypes::Terran_Bunker)
{
enemyUnitsInRegionSupply[baseEnemy.first] += 12;
}
else
enemyUnitsInRegionSupply[baseEnemy.first] += 1;
}
}
}
std::map<BWAPI::UnitType, std::set<BWAPI::Unit>>& myBuildings = InformationManager::Instance().getOurAllBuildingUnit();
bool hasSunken = false;
for(auto const& sunker : myBuildings[BWAPI::UnitTypes::Zerg_Sunken_Colony])
{
if (sunker->isCompleted())
{
hasSunken = true;
break;
}
}
if (enemyUnitsTargetRegion.empty())
{
enemyDisappearedTime += 1;
if (enemyDisappearedTime > 10 * 24)
{
isNeedDefend = false;
hasWorkerScouter = false;
WorkerManager::Instance().finishedWithCombatWorkers();
enemyDisappearedTime = 0;
}
return;
}
enemyDisappearedTime = 0;
//special case for scouter
if (enemyUnitsTargetRegion.size() == 1 && enemyUnitsTargetRegion.begin()->second.size() == 1 &&
(*enemyUnitsTargetRegion.begin()->second.begin())->getType().isWorker() && myArmy[BWAPI::UnitTypes::Zerg_Zergling]->getUnits().empty())
{
hasWorkerScouter = true;
BWAPI::Unit enemyWorker = *enemyUnitsTargetRegion.begin()->second.begin();
BWAPI::Unit workerDefender = WorkerManager::Instance().getClosestMineralWorkerTo(enemyWorker);
WorkerManager::Instance().setCombatWorker(workerDefender);
}
//use zergling to kill scout worker
else if (enemyUnitsTargetRegion.size() == 1 && enemyUnitsTargetRegion.begin()->second.size() == 1 &&
(*enemyUnitsTargetRegion.begin()->second.begin())->getType().isWorker() && myArmy[BWAPI::UnitTypes::Zerg_Zergling]->getUnits().size() > 0)
{
hasWorkerScouter = true;
WorkerManager::Instance().finishedWithCombatWorkers();
ZerglingArmy* zerglings = dynamic_cast<ZerglingArmy*>(myArmy[BWAPI::UnitTypes::Zerg_Zergling]);
zerglings->attackScoutWorker(*enemyUnitsTargetRegion.begin()->second.begin());
}
else
{
//trig defend tactic
vector<std::pair<const Area*, double>> enemyAttackRegionsPriority;
BWAPI::Position myBase = BWAPI::Position(BWAPI::Broodwar->self()->getStartLocation());
for (auto const& r : enemyUnitsTargetRegion)
{
Position enemyTarget = Position(myRegion[r.first]);
enemyAttackRegionsPriority.push_back(std::pair<const Area*, double>(r.first, myBase.getDistance(enemyTarget)));
}
std::sort(enemyAttackRegionsPriority.begin(), enemyAttackRegionsPriority.end(),
[](const std::pair<const Area*, double>& a, const std::pair<const Area*, double>& b)
{
return a.second < b.second;
});
// defend priority is defined by attack region's distance to start base, we traverse to assign defend army from high priority to low
for (auto const& targetBase : enemyAttackRegionsPriority)
{
int myRemainSupply = 0;
map<UnitType, set<Unit>> ourUnits, enemyUnits;
for(auto const& p : myArmy)
{
myRemainSupply += ((p.first).supplyRequired() * p.second->getUnits().size());
for (auto& u : p.second->getUnits())
{
ourUnits[p.first].insert(u.unit);
}
}
if (myRemainSupply == 0)
{
return;
}
bool enemyHasDetector = false;
for (auto const& unit : enemyUnitsTargetRegion[targetBase.first])
{
enemyUnits[unit->getType()].insert(unit);
if (checkDetectorFunc(unit->getType()))
{
enemyHasDetector = true;
}
}
int enemySupply = enemyUnitsInRegionSupply[targetBase.first];
std::map<BWAPI::UnitType, std::set<BWAPI::Unit>>& myBuildings = InformationManager::Instance().getOurAllBuildingUnit();
bool allAirEnemy = false;
bool allGroundEnemy = false;
if (enemyUnitsInRegionFlySupply[targetBase.first] > 0)
{
int needAirDefend = enemyUnitsInRegionFlySupply[targetBase.first];
if (enemySupply > 0 && (needAirDefend * 10 / enemySupply >= 9))
{
allAirEnemy = true;
}
}
else
{
allGroundEnemy = true;
}
map<string, std::pair<int, int>> ourArmyScoreDict, enemyArmyScoreDict;
BattleArmy::parsedArmyScore(ourUnits, ourArmyScoreDict, enemyHasDetector, true);
BattleArmy::parsedArmyScore(enemyUnits, enemyArmyScoreDict, true, false);
set<string> overWhelmEnemyArmy;
int retreatFlag = BattleArmy::needRetreat(ourArmyScoreDict, enemyArmyScoreDict, overWhelmEnemyArmy, true, enemyHasDetector);
bool isDefendStartBase = false;
if (targetBase.first == BWEMMap.GetArea(Broodwar->self()->getStartLocation())
|| targetBase.first == BWEMMap.GetArea(InformationManager::Instance().getOurNatrualLocation()))
{
isDefendStartBase = true;
}
int needDefendSupply = int(enemySupply * 2);
Position defendBasePosition = Position(myRegion[targetBase.first]);
if (TacticManager::Instance().isTacticRun(DefendTactic, defendBasePosition))
{
int defendTacArmySupply = TacticManager::Instance().getTacArmyForce(DefendTactic, defendBasePosition);
if (defendTacArmySupply < needDefendSupply)
{
int needSupply = needDefendSupply - defendTacArmySupply;
addTacArmy(needSupply, DefendTactic, defendBasePosition, allAirEnemy, allGroundEnemy);
}
}
else
{
if (retreatFlag == 1 && overWhelmEnemyArmy.empty() && !isDefendStartBase)
{
return;
}
else
{
TacticManager::Instance().addTactic(DefendTactic, defendBasePosition);
addTacArmy(enemySupply, DefendTactic, defendBasePosition, allAirEnemy, allGroundEnemy);
//Broodwar->printf("trigger tactic");
}
}
}
}
}
void AttackManager::onUnitMorph(BWAPI::Unit unit)
{
if (unit == nullptr)
{
return;
}
if (myArmy.find(unit->getType()) == myArmy.end())
{
BWAPI::UnitType u = unit->getType();
return;
}
unRallyArmy.push_back(unit);
}
void AttackManager::onUnitDestroy(BWAPI::Unit unit)
{
if (unit == nullptr || myArmy.find(unit->getType()) == myArmy.end())
return;
std::vector<UnitState>& army = myArmy[unit->getType()]->getUnits();
for (auto it = army.begin(); it != army.end(); it++)
{
if (it->unit == unit)
{
army.erase(it);
break;
}
}
for (std::vector<BWAPI::Unit>::iterator it = unRallyArmy.begin(); it != unRallyArmy.end(); it++)
{
if (*it == unit)
{
unRallyArmy.erase(it);
break;
}
}
}
void AttackManager::onLurkerMorph()
{
std::vector<UnitState>& army = myArmy[BWAPI::UnitTypes::Zerg_Hydralisk]->getUnits();
for (std::vector<UnitState>::iterator it = army.begin(); it != army.end(); it++)
{
if (it->unit->isMorphing())
{
army.erase(it);
break;
}
}
}
AttackManager& AttackManager::Instance()
{
static AttackManager a;
return a;
}
void AttackManager::addTacticRemainArmy(std::map<BWAPI::UnitType, BattleArmy*>& tacticArmy)
{
for(auto const& p : tacticArmy)
{
if (myArmy.find(p.first) != myArmy.end())
{
std::vector<UnitState>& t = myArmy[p.first]->getUnits();
t.insert(t.end(), p.second->getUnits().begin(), p.second->getUnits().end());
}
}
}
std::pair<UnitType,int> AttackManager::availableAirDropArmy() {
// if two upgrade level are not satisfied
if (Broodwar->self()->getUpgradeLevel(UpgradeTypes::Pneumatized_Carapace) == 0 || Broodwar->self()->getUpgradeLevel(UpgradeTypes::Ventral_Sacs) == 0)
return std::make_pair(UnitTypes::None, -1);
// if do not have enough overlord
if (myArmy[UnitTypes::Zerg_Overlord]->getUnits().size() < 5)
return std::make_pair(UnitTypes::None, -1);
// if upgraded Adrenal_Glands, use zergling first
if (Broodwar->self()->getUpgradeLevel(UpgradeTypes::Adrenal_Glands) == 0) {
// if we have more than 2 free Lurkers
if (myArmy.find(UnitTypes::Zerg_Lurker) != myArmy.end() && myArmy[UnitTypes::Zerg_Lurker]->getUnits().size() >= 2)
return std::make_pair(UnitTypes::Zerg_Lurker, 2);
// if we have enough zerglings
if (myArmy.find(UnitTypes::Zerg_Zergling) != myArmy.end() && myArmy[UnitTypes::Zerg_Zergling]->getUnits().size() > 0) {
int minZerglingNum = (hasWorkerScouter ? 10 : 8);
if (int(myArmy[UnitTypes::Zerg_Zergling]->getUnits().size()) >= minZerglingNum)
return std::make_pair(UnitTypes::Zerg_Zergling, 8);
}
}
else {
// if we have enough zerglings
if (myArmy.find(UnitTypes::Zerg_Zergling) != myArmy.end() && myArmy[UnitTypes::Zerg_Zergling]->getUnits().size() > 0) {
int minZerglingNum = (hasWorkerScouter ? 10 : 8);
if (int(myArmy[UnitTypes::Zerg_Zergling]->getUnits().size()) >= minZerglingNum)
return std::make_pair(UnitTypes::Zerg_Zergling, 8);
}
// if we have more than 2 free Lurkers
if (myArmy.find(UnitTypes::Zerg_Lurker) != myArmy.end() && myArmy[UnitTypes::Zerg_Lurker]->getUnits().size() >= 2)
return std::make_pair(UnitTypes::Zerg_Lurker, 2);
}
// if we have enough hydralisks
if (myArmy.find(UnitTypes::Zerg_Hydralisk) != myArmy.end() && myArmy[UnitTypes::Zerg_Hydralisk]->getUnits().size() >= 4)
return std::make_pair(UnitTypes::Zerg_Hydralisk, 4);
return std::make_pair(UnitTypes::None, -1);
}
| 411 | 0.857541 | 1 | 0.857541 | game-dev | MEDIA | 0.989995 | game-dev | 0.980874 | 1 | 0.980874 |
hlissner/evil-snipe | 2,360 | test/evil-snipe-highlight-test.el | ;;; evil-snipe-highlight-test.el
(defun face-at-pt! (&optional pos)
(let ((pt (or pos (point))))
(or (get-char-property pt 'read-face-name)
(get-char-property pt 'face))))
(defun overlays-p! (count keys &optional pos-list)
(evil-snipe--cleanup)
(let (list)
(if (progn
(mapc (lambda (ov)
(when (eq (overlay-get ov 'category) 'evil-snipe)
(push (list (overlay-start ov) (overlay-end ov))
list)))
(evil-snipe--highlight-all
count (> count 0) (mapcar #'evil-snipe--process-key keys)))
(unless list (error "List is empty"))
list)
(sort list (lambda (a b) (< (car a) (car b))))
(when pos-list
(error "%s != %s" pos-list it)))))
(ert-deftest evil-snipe-highlight-test ()
(let ((evil-snipe-scope 'whole-buffer)
(evil-snipe-smart-case t))
(with! "money money money is so funny in a rich man's world"
(should (from! (point-min)
(evil-snipe--highlight 7 8 t)
(eql (face-at-pt! 7) 'evil-snipe-first-match-face)))
(should (from! (point-min)
(evil-snipe--highlight 11 12)
(eql (face-at-pt! 11) 'evil-snipe-matches-face))))))
(ert-deftest evil-snipe-1char-highlight-test ()
(let ((evil-snipe-scope 'whole-buffer)
(evil-snipe-smart-case t))
(with! "money money money is so funny in a rich man's world"
(should-error (from! (point-max) (overlays-p! 1 [?x])))
(dotimes (_ 2) ; do twice to test idempotence
(should (from! (point-min)
(overlays-p! 1 [?m] '((1 2) (7 8) (13 14) (41 42))))))
(should (from! (point-max)
(overlays-p! -1 [?m] '((1 2) (7 8) (13 14) (41 42))))))))
(ert-deftest evil-snipe-2char-highlight-test ()
(let ((evil-snipe-scope 'whole-buffer)
(evil-snipe-smart-case t))
(with! "money money money is so funny in a rich man's world"
(should-error (from! (point-max) (overlays-p! 1 [?n ?a])))
(dotimes (_ 2) ; do twice to test idempotence
(should (from! (point-min)
(overlays-p! 1 [?m ?o] '((1 3) (7 9) (13 15))))))
;; Backwards
(should (from! (point-max)
(overlays-p! -1 [?m ?o]
'((1 3) (7 9) (13 15))))))))
| 411 | 0.909443 | 1 | 0.909443 | game-dev | MEDIA | 0.565866 | game-dev | 0.85343 | 1 | 0.85343 |
Monkestation/Monkestation2.0 | 1,699 | code/modules/events/ghost_role/nightmare.dm | /datum/round_event_control/nightmare
name = "Spawn Nightmare"
typepath = /datum/round_event/ghost_role/nightmare
max_occurrences = 1
min_players = 20
//dynamic_should_hijack = TRUE
category = EVENT_CATEGORY_ENTITIES
description = "Spawns a nightmare, aiming to darken the station."
min_wizard_trigger_potency = 6
max_wizard_trigger_potency = 7
track = EVENT_TRACK_MAJOR
tags = list(TAG_COMBAT, TAG_SPOOKY, TAG_EXTERNAL, TAG_ALIEN, TAG_OUTSIDER_ANTAG)
checks_antag_cap = TRUE
dont_spawn_near_roundend = TRUE
repeated_mode_adjust = TRUE
/datum/round_event/ghost_role/nightmare
minimum_required = 1
role_name = "nightmare"
fakeable = FALSE
/datum/round_event/ghost_role/nightmare/spawn_role()
var/list/mob/dead/observer/candidates = SSpolling.poll_ghost_candidates(
"Do you want to play as a Nightmare?",
role = ROLE_NIGHTMARE,
check_jobban = ROLE_NIGHTMARE,
poll_time = 20 SECONDS,
alert_pic = /datum/antagonist/nightmare,
role_name_text = "nightmare"
)
if(!length(candidates))
return NOT_ENOUGH_PLAYERS
var/mob/dead/selected = pick(candidates)
var/datum/mind/player_mind = new /datum/mind(selected.key)
player_mind.active = TRUE
var/turf/spawn_loc = find_maintenance_spawn(atmos_sensitive = TRUE, require_darkness = TRUE)
if(isnull(spawn_loc))
return MAP_ERROR
var/mob/living/carbon/human/S = new (spawn_loc)
player_mind.transfer_to(S)
player_mind.add_antag_datum(/datum/antagonist/nightmare)
playsound(S, 'sound/magic/ethereal_exit.ogg', 50, TRUE, -1)
message_admins("[ADMIN_LOOKUPFLW(S)] has been made into a Nightmare by an event.")
S.log_message("was spawned as a Nightmare by an event.", LOG_GAME)
spawned_mobs += S
return SUCCESSFUL_SPAWN
| 411 | 0.962818 | 1 | 0.962818 | game-dev | MEDIA | 0.999585 | game-dev | 0.949952 | 1 | 0.949952 |
dbjorkholm/FORGOTTENSERVER-ORTS | 2,431 | data/npc/scripts/A Prisoner.lua | local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local function creatureSayCallback(cid, type, msg)
if not npcHandler:isFocused(cid) then
return false
end
local player = Player(cid)
if msgcontains(msg, "riddle") then
if player:getStorageValue(Storage.madMageQuest) ~= 1 then
npcHandler:say("Great riddle, isn´t it? If you can tell me the correct answer, I will give you something. Hehehe!", cid)
npcHandler.topic[cid] = 1
end
elseif msgcontains(msg, "PD-D-KS-P-PD") then
if npcHandler.topic[cid] == 1 then
npcHandler:say("Hurray! For that I will give you my key for - hmm - let´s say ... some apples. Interested?", cid)
npcHandler.topic[cid] = 2
end
elseif msgcontains(msg, "yes") then
if npcHandler.topic[cid] == 2 then
if player:removeItem(2674, 7) then
npcHandler:say("Mnjam - excellent apples. Now - about that key. You are sure want it?", cid)
npcHandler.topic[cid] = 3
else
npcHandler:say("Get some more apples first!", cid)
npcHandler.topic[cid] = 0
end
elseif npcHandler.topic[cid] == 3 then
npcHandler:say("Really, really?", cid)
npcHandler.topic[cid] = 4
elseif npcHandler.topic[cid] == 4 then
npcHandler:say("Really, really, really, really?", cid)
npcHandler.topic[cid] = 5
elseif npcHandler.topic[cid] == 5 then
player:setStorageValue(Storage.madMageQuest, 1)
npcHandler:say("Then take it and get happy - or die, hehe.", cid)
local key = player:addItem(2088, 1)
if key then
key:setActionId(3666)
end
npcHandler.topic[cid] = 0
end
elseif msgcontains(msg, "no") then
npcHandler:say("Then go away!", cid)
end
return true
end
npcHandler:setMessage(MESSAGE_WALKAWAY, "Wait! Don't leave! I want to tell you about my surreal numbers.")
npcHandler:setMessage(MESSAGE_FAREWELL, "Next time we should talk about my surreal numbers.")
npcHandler:setMessage(MESSAGE_GREET, "Huh? What? I can see! Wow! A non-mino. Did they {capture} you as well?")
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
| 411 | 0.878026 | 1 | 0.878026 | game-dev | MEDIA | 0.371483 | game-dev | 0.931715 | 1 | 0.931715 |
Florian-Thake/TeaScript-Cpp-Library | 2,444 | include/teascript/Func.hpp | /* === Part of TeaScript C++ Library ===
* SPDX-FileCopyrightText: Copyright (C) 2024 Florian Thake <contact |at| tea-age.solutions>.
* SPDX-License-Identifier: MPL-2.0
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/
*/
#pragma once
#include "FunctionBase.hpp"
#include "ValueObject.hpp"
#include "ASTNode.hpp"
#include "Context.hpp"
namespace teascript {
/// class Func is for all ordinary functions defined within TeaScript code.
class Func : public FunctionBase
{
std::shared_ptr< ASTNode_ParamSpec > mParamSpec;
std::shared_ptr< ASTNode_Block > mBlock;
public:
Func( ASTNodePtr const ¶mspec, ASTNodePtr const &block, SourceLocation const &rLoc = {} )
: FunctionBase()
, mParamSpec( std::dynamic_pointer_cast<ASTNode_ParamSpec>(paramspec) )
, mBlock( std::dynamic_pointer_cast<ASTNode_Block>(block) )
{
if( !mParamSpec || !mBlock ) {
throw exception::runtime_error( rLoc, "Teascript Function has no fitting ASTNode instances!" );
}
}
virtual ~Func() {}
ValueObject Call( Context &rContext, std::vector<ValueObject> &rParams, SourceLocation const &rLoc ) override
{
ScopedNewScope new_scope( rContext, rParams, rLoc );
(void)mParamSpec->Eval(rContext);
if( rContext.CurrentParamCount() > 0 ) { // TODO: relax this check ?
throw exception::eval_error( rLoc, "Calling Func: Too many arguments!" );
}
try {
return mBlock->Eval( rContext );
} catch( control::Return_From_Function &rReturn ) {
return rReturn.MoveResult();
}
}
int ParamCount() const override
{
return static_cast<int>(mParamSpec->ChildCount());
}
std::string ParameterInfoStr() const override
{
std::string res = "(";
bool first = true;
for( auto const &node : *mParamSpec ) {
if( node->ChildCount() == 0 ) { // sth. strange!
return FunctionBase::ParameterInfoStr();
}
if( first ) {
first = false;
} else {
res += ", ";
}
res += (*node->begin())->GetDetail();
}
res += ")";
return res;
}
};
} // namespace teascript
| 411 | 0.851848 | 1 | 0.851848 | game-dev | MEDIA | 0.118942 | game-dev | 0.783047 | 1 | 0.783047 |
oestrich/kalevala | 2,712 | example/assets/js/redux/eventsReducer.js | import { createReducer, Types as KalevalaTypes } from "../kalevala";
import { Types } from "./actions";
const INITIAL_STATE = {
character: null,
contexts: {},
inventory: [],
miniMap: [],
room: null,
vitals: null,
};
const characterEntered = (state, action) => {
const { character } = action.data;
const characters = [...state.room.characters, character];
return { ...state, room: { ...state.room, characters } };
};
const characterLeft = (state, action) => {
const { character } = action.data;
const characters = state.room.characters.filter((existingCharacter) => {
return existingCharacter.id != character.id;
});
return { ...state, room: { ...state.room, characters } };
};
const characterLoggedIn = (state, action) => {
const { character } = action.data;
return { ...state, character: character };
};
const eventReceived = (state, action) => {
const { event } = action.data;
switch (event.topic) {
case "Character.Vitals": {
return { ...state, vitals: event.data };
}
case "Context.Verbs": {
const { contexts } = state;
const { verbs, context, type, id } = event.data;
contexts[`${context}:${type}:${id}`] = verbs;
return { ...state, contexts: contexts };
}
case "Inventory.All": {
const { item_instances } = event.data;
return { ...state, inventory: item_instances };
}
case "Inventory.DropItem": {
return dropItem(state, event);
}
case "Inventory.PickupItem": {
return pickupItem(state, event);
}
case "Room.Info": {
return { ...state, room: event.data };
}
case "Zone.MiniMap": {
return { ...state, miniMap: event.data.mini_map };
}
default: {
return state;
}
}
};
const dropItem = (state, event) => {
const { item_instance } = event.data;
let { inventory } = state;
inventory = inventory.filter((instance) => instance.id != item_instance.id);
return { ...state, inventory: inventory };
};
const pickupItem = (state, event) => {
const { item_instance } = event.data;
return { ...state, inventory: [item_instance, ...state.inventory] };
};
const eventClearVerbs = (state, event) => {
const { contexts } = state;
const { context, type, id } = event.data;
delete contexts[`${context}:${type}:${id}`];
return { ...state, contexts: contexts };
};
const HANDLERS = {
[KalevalaTypes.SOCKET_RECEIVED_EVENT]: eventReceived,
[KalevalaTypes.SOCKET_CLEAR_VERBS]: eventClearVerbs,
[Types.LOGGED_IN]: characterLoggedIn,
[Types.ROOM_CHARACTER_ENTERED]: characterEntered,
[Types.ROOM_CHARACTER_LEFT]: characterLeft,
};
export const eventsReducer = createReducer(INITIAL_STATE, HANDLERS);
| 411 | 0.692571 | 1 | 0.692571 | game-dev | MEDIA | 0.816461 | game-dev | 0.908047 | 1 | 0.908047 |
biud436/MV | 10,122 | RS_GhostEffect.js | //================================================================
// RS_GhostEffect.js
// ---------------------------------------------------------------
// The MIT License
// Copyright (c) 2019 biud436
// ---------------------------------------------------------------
// Free for commercial and non commercial use.
//================================================================
/*:
* @plugindesc This plugin allows you to apply a ghost-like visual effect to characters. <RS_GhostEffect>
* @author biud436
*
* @param Uniform
*
* @param lifeTime
* @parent Uniform
* @type number
* @desc Specifies the duration (in milliseconds) for each cycle of the ghost effect. After this time, the effect pattern will change.
* @default 100
* @min 1
*
* @param threshold
* @parent Uniform
* @type number
* @desc Controls the visibility intensity of the effect. Higher values reduce the effect's intensity.
* @default 0.7
* @decimals 2
* @min 0.10
* @max 1.00
*
* @param xoffset
* @parent Uniform
* @type number
* @desc Adjusts the horizontal distortion of the ghost effect. Lower values make it look like burning paper.
* @default 0.07
* @decimals 2
*
* @help
*
* This plugin requires WebGL mode to work properly.
*
* =======================================================
* How to Enable or Disable Ghost Mode
* =======================================================
* Use the following script calls within the "Set Move Route" event command:
*
* To enable ghost mode:
* this.ghostModeOn();
*
* To disable ghost mode:
* this.ghostModeOff();
*
* These commands can be applied to any character, including followers.
*
* =======================================================
* Plugin Commands
* =======================================================
* You can use these commands in event scripts to adjust the ghost effect dynamically:
*
* 1. Set the lifeTime of the ghost effect:
* GhostEffect lifetime 100
* - Changes the duration of the ghost effect cycle to 0.1 seconds.
*
* 2. Set the threshold of the ghost effect:
* GhostEffect threshold 0.7
* - Adjusts the intensity of the ghost effect. A value closer to 1.0 makes it less noticeable.
*
* 3. Set the xoffset of the ghost effect:
* GhostEffect xoffset 0.07
* - Controls the horizontal distortion, making the effect resemble burning paper at lower values.
*
* =======================================================
* Examples
* =======================================================
* Make a character look like a ghost with a quick effect change:
* GhostEffect lifetime 50
*
* Reduce the intensity of the ghost effect:
* GhostEffect threshold 0.9
*
* Create a more distorted ghost effect:
* GhostEffect xoffset 0.1
*
* =======================================================
* Technical Details
* =======================================================
* - WebGL Requirement: This plugin uses WebGL shaders. Ensure the game is running in WebGL mode.
* - Performance Consideration: Using too many ghost effects may impact performance on lower-end devices.
*
* =======================================================
* Version History
* =======================================================
* v1.0.0 (2019.01.19) - First release.
* v1.0.1 (2023.08.12) - ES6 refactoring and tested on RPG Maker MV v1.6.2 with NW.js v0.55.0.
*
* =======================================================
* Tips
* =======================================================
* - Combine the ghost effect with lighting or particle effects for a supernatural atmosphere.
* - Useful for boss fights or special characters to visually distinguish them.
*
*/
(() => {
'use strict';
const RS = window.RS || {};
RS.GhostEffect = RS.GhostEffect || {};
let parameters = $plugins.filter(i => {
return i.description.contains('<RS_GhostEffect>');
});
parameters = parameters.length > 0 && parameters[0].parameters;
RS.GhostEffect.Params = RS.GhostEffect.Params || {};
RS.GhostEffect.Params.lifeTime = parseInt(parameters.lifeTime || 100, 10);
RS.GhostEffect.Params.threshold = parseFloat(parameters.threshold || 0.7);
RS.GhostEffect.Params.xoffset = parseFloat(parameters.xoffset || 0.07);
//============================================================================
// PIXI.GhostEffect
//============================================================================
PIXI.GhostEffect = function () {
const vertexSrc = [
'attribute vec2 aVertexPosition;',
'attribute vec2 aTextureCoord;',
'uniform mat3 projectionMatrix;',
'varying vec2 vTextureCoord;',
'void main(void){',
' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);',
' vTextureCoord = aTextureCoord;',
'}',
].join('\n');
const fragmentSrc = `
precision mediump float;
uniform vec2 u_scale;
varying vec2 vTextureCoord;
uniform sampler2D uSampler;
uniform vec2 dimensions;
uniform float u_xoffset;
uniform vec4 filterArea;
uniform vec4 filterClamp;
void main(void){
vec4 baseColor = texture2D(uSampler, vTextureCoord);
vec2 vRec = (vTextureCoord * filterArea.xy) / dimensions;
vRec -= 0.5;
vRec *= u_scale;
vRec += 0.5;
vRec.x += u_xoffset;
vec4 recColor = texture2D(uSampler, vRec);
gl_FragColor = baseColor * recColor;
}
`;
PIXI.Filter.call(this, vertexSrc, fragmentSrc);
this.uniforms.dimensions = new Float32Array(2);
this.uniforms.u_scale = [0.5, 0.5];
this.uniforms.u_xoffset = 0.07;
this._effectVal = 0;
this._time = performance.now();
this.enabled = true;
this.resolution = 1;
};
PIXI.GhostEffect.prototype = Object.create(PIXI.Filter.prototype);
PIXI.GhostEffect.prototype.constructor = PIXI.GhostEffect;
PIXI.GhostEffect.prototype.apply = function (
filterManager,
input,
output,
clear
) {
this.uniforms.dimensions[0] = input.sourceFrame.width;
this.uniforms.dimensions[1] = input.sourceFrame.height;
filterManager.applyFilter(this, input, output, clear);
};
PIXI.GhostEffect.prototype.updateEffect = function () {
const isInvalidUpdateEffect =
performance.now() - this._time < RS.GhostEffect.Params.lifeTime;
if (isInvalidUpdateEffect) return;
this._effectVal = Math.random();
if (this._effectVal > RS.GhostEffect.Params.threshold) {
this._effectVal = RS.GhostEffect.Params.threshold;
}
this.uniforms.u_scale[0] = this._effectVal;
this.uniforms.u_scale[1] = this._effectVal;
this.uniforms.u_xoffset = RS.GhostEffect.Params.xoffset;
this._time = performance.now();
};
//============================================================================
// Game_CharacterBase
//============================================================================
const alias_Game_CharacterBase_initMembers =
Game_CharacterBase.prototype.initMembers;
Game_CharacterBase.prototype.initMembers = function () {
alias_Game_CharacterBase_initMembers.call(this);
this._isGhost = false;
};
Game_CharacterBase.prototype.isGhost = function () {
return this._isGhost;
};
Game_CharacterBase.prototype.ghostModeOn = function () {
this._isGhost = true;
};
Game_CharacterBase.prototype.ghostModeOff = function () {
this._isGhost = false;
};
Game_Player.prototype.ghostModeOn = function () {
this._isGhost = true;
this._followers.forEach(follower => {
follower.ghostModeOn();
});
};
Game_Player.prototype.ghostModeOff = function () {
this._isGhost = false;
this._followers.forEach(follower => {
follower.ghostModeOff();
});
};
//============================================================================
// Sprite_Character
//============================================================================
const alias_Sprite_Character_initialize =
Sprite_Character.prototype.initialize;
Sprite_Character.prototype.initialize = function (character) {
alias_Sprite_Character_initialize.call(this, character);
this.createGhostEffect();
};
const alias_Sprite_Character_update = Sprite_Character.prototype.update;
Sprite_Character.prototype.update = function () {
alias_Sprite_Character_update.call(this);
this.updateGhostEffect();
};
Sprite_Character.prototype.createGhostEffect = function () {
const isValid = this._GhostEffect;
if (!isValid) {
this._GhostEffect = new PIXI.GhostEffect();
if (!this.filters) {
this.filters = [];
}
this.filters = [this._GhostEffect].concat(this.filters);
} else {
if (!this.filters) {
this.filters = [];
}
this.filters = this.filters.filter(function (filter) {
return filter !== isValid;
}, this);
}
};
Sprite_Character.prototype.updateGhostEffect = function () {
if (!$gameSystem) return;
if (!this._GhostEffect) return;
if (!this._character) return;
const isValid = this._character.isGhost();
this._GhostEffect.enabled = isValid;
if (isValid) {
this._GhostEffect.updateEffect();
}
};
const alias_Game_Interpreter_pluginCommand =
Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function (command, args) {
alias_Game_Interpreter_pluginCommand.call(this, command, args);
if (command === 'GhostEffect') {
switch (args[0]) {
case 'lifetime':
RS.GhostEffect.Params.lifeTime = Number(args[1] || 100);
break;
case 'threshold':
RS.GhostEffect.Params.threshold = parseFloat(args[1] || 0.7);
break;
case 'xoffset':
RS.GhostEffect.Params.xoffset = parseFloat(args[1] || 0.07);
break;
default:
break;
}
}
};
})();
| 411 | 0.865486 | 1 | 0.865486 | game-dev | MEDIA | 0.966664 | game-dev | 0.906636 | 1 | 0.906636 |
bernie-g/geckolib | 5,067 | common/src/main/java/software/bernie/geckolib/constant/dataticket/SerializableDataTicket.java | package software.bernie.geckolib.constant.dataticket;
import it.unimi.dsi.fastutil.Pair;
import net.minecraft.core.BlockPos;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.phys.Vec3;
import software.bernie.geckolib.constant.DataTickets;
/**
* Network-compatible {@link DataTicket} implementation
* <p>
* Used for sending data from server -> client in an easy manner
*/
public final class SerializableDataTicket<D> extends DataTicket<D> {
public static final StreamCodec<RegistryFriendlyByteBuf, SerializableDataTicket<?>> STREAM_CODEC = StreamCodec.composite(
ByteBufCodecs.STRING_UTF8,
SerializableDataTicket::id,
DataTickets::byName);
private final StreamCodec<? super RegistryFriendlyByteBuf, D> streamCodec;
private SerializableDataTicket(String id, Class<? extends D> objectType, StreamCodec<? super RegistryFriendlyByteBuf, D> streamCodec) {
super(id, objectType);
this.streamCodec = streamCodec;
}
/**
* Create a new network-syncable DataTicket for a given name and object type
* <p>
* <b><u>MUST</u></b> be created during mod construct
* <p>
* This DataTicket should then be stored statically somewhere and re-used.
*/
public static <D> SerializableDataTicket<D> create(String id, Class<? extends D> objectType, StreamCodec<? super RegistryFriendlyByteBuf, D> streamCodec) {
return (SerializableDataTicket<D>)IDENTITY_CACHE.computeIfAbsent(Pair.of(objectType, id), pair -> DataTickets.registerSerializable(new SerializableDataTicket<>(id, objectType, streamCodec)));
}
/**
* @return The {@link StreamCodec} for the given SerializableDataTicket
*/
public StreamCodec<? super RegistryFriendlyByteBuf, D> streamCodec() {
return this.streamCodec;
}
// Pre-defined typings for use
/**
* Generate a new {@code SerializableDataTicket<Double>} for the given id
*
* @param id The unique id of your ticket. Include your modid
*/
public static SerializableDataTicket<Double> ofDouble(ResourceLocation id) {
return SerializableDataTicket.create(id.toString(), Double.class, ByteBufCodecs.DOUBLE);
}
/**
* Generate a new {@code SerializableDataTicket<Float>} for the given id
*
* @param id The unique id of your ticket. Include your modid
*/
public static SerializableDataTicket<Float> ofFloat(ResourceLocation id) {
return SerializableDataTicket.create(id.toString(), Float.class, ByteBufCodecs.FLOAT);
}
/**
* Generate a new {@code SerializableDataTicket<Boolean>} for the given id
*
* @param id The unique id of your ticket. Include your modid
*/
public static SerializableDataTicket<Boolean> ofBoolean(ResourceLocation id) {
return SerializableDataTicket.create(id.toString(), Boolean.class, ByteBufCodecs.BOOL);
}
/**
* Generate a new {@code SerializableDataTicket<Integer>} for the given id
*
* @param id The unique id of your ticket. Include your modid
*/
public static SerializableDataTicket<Integer> ofInt(ResourceLocation id) {
return SerializableDataTicket.create(id.toString(), Integer.class, ByteBufCodecs.INT);
}
/**
* Generate a new {@code SerializableDataTicket<String>} for the given id
*
* @param id The unique id of your ticket. Include your modid
*/
public static SerializableDataTicket<String> ofString(ResourceLocation id) {
return SerializableDataTicket.create(id.toString(), String.class, ByteBufCodecs.STRING_UTF8);
}
/**
* Generate a new {@code SerializableDataTicket<Enum>} for the given id
*
* @param id The unique id of your ticket. Include your modid
*/
public static <E extends Enum<E>> SerializableDataTicket<E> ofEnum(ResourceLocation id, Class<E> enumClass) {
return SerializableDataTicket.create(id.toString(), enumClass, new StreamCodec<>() {
@Override
public E decode(RegistryFriendlyByteBuf buf) {
return Enum.valueOf(enumClass, buf.readUtf());
}
@Override
public void encode(RegistryFriendlyByteBuf buf, E data) {
buf.writeUtf(data.toString());
}
});
}
/**
* Generate a new {@code SerializableDataTicket<Vec3>} for the given id
*
* @param id The unique id of your ticket. Include your modid
*/
public static SerializableDataTicket<Vec3> ofVec3(ResourceLocation id) {
return SerializableDataTicket.create(id.toString(), Vec3.class, ByteBufCodecs.VECTOR3F.map(Vec3::new, Vec3::toVector3f));
}
/**
* Generate a new {@code SerializableDataTicket<BlockPos>} for the given id
*
* @param id The unique id of your ticket. Include your modid
*/
public static SerializableDataTicket<BlockPos> ofBlockPos(ResourceLocation id) {
return SerializableDataTicket.create(id.toString(), BlockPos.class, new StreamCodec<>() {
@Override
public BlockPos decode(RegistryFriendlyByteBuf buf) {
return buf.readBlockPos();
}
@Override
public void encode(RegistryFriendlyByteBuf buf, BlockPos blockPos) {
buf.writeBlockPos(blockPos);
}
});
}
}
| 411 | 0.782305 | 1 | 0.782305 | game-dev | MEDIA | 0.595597 | game-dev,networking | 0.650614 | 1 | 0.650614 |
sh-akira/VirtualMotionCapture | 3,265 | Assets/VMCMOD/ModManager.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEngine;
namespace VMCMod
{
public class ModManager : MonoBehaviour
{
private string ModsPath;
private Dictionary<VMCPluginAttribute, Component> LoadedMods = new Dictionary<VMCPluginAttribute, Component>();
public Action OnBeforeModLoad;
public bool IsModLoaded => LoadedMods.Any();
private void Awake()
{
ModsPath = Application.dataPath + "/../Mods/";
}
public void ImportMods()
{
if (Directory.Exists(ModsPath) == false)
{
Directory.CreateDirectory(ModsPath);
}
Debug.Log("Start Loading Mods");
var attributeTypesList = new Dictionary<List<Type>, string>();
foreach (var dllFile in Directory.GetFiles(ModsPath, "*.dll", SearchOption.AllDirectories))
{
try
{
Assembly assembly = Assembly.LoadFrom(dllFile);
var attributeTypes = assembly.GetTypes().Where(x => x.IsPublic && x.IsDefined(typeof(VMCPluginAttribute)));
if (attributeTypes.Any())
{
attributeTypesList.Add(attributeTypes.ToList(), dllFile);
}
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
if (attributeTypesList.Any())
{
OnBeforeModLoad?.Invoke();
}
foreach (var attributeTypes in attributeTypesList)
{
foreach (Type t in attributeTypes.Key)
{
try
{
var attribute = (VMCPluginAttribute)Attribute.GetCustomAttribute(t, typeof(VMCPluginAttribute));
attribute.InstanceId = Guid.NewGuid().ToString();
attribute.AssemblyPath = attributeTypes.Value;
var component = gameObject.AddComponent(t);
attribute.OnSetting = new List<Action>();
foreach (MethodInfo method in t.GetMethods().Where(x => x.IsDefined(typeof(OnSettingAttribute))))
{
attribute.OnSetting.Add(() => method.Invoke(component, null));
}
LoadedMods[attribute] = component;
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
}
}
public List<VMCPluginAttribute> GetModsList()
{
return LoadedMods.Keys.ToList();
}
public void InvokeSetting(string instanceId)
{
var attribute = LoadedMods.Keys.FirstOrDefault(x => x.InstanceId == instanceId);
if (attribute != null)
{
foreach (var settingAction in attribute.OnSetting)
{
settingAction?.Invoke();
}
}
}
}
} | 411 | 0.905966 | 1 | 0.905966 | game-dev | MEDIA | 0.710494 | game-dev | 0.940218 | 1 | 0.940218 |
AmProsius/gothic-1-community-patch | 2,701 | scriptbase/_work/Data/Scripts/Content/Magic/ZS/ZS_MagicSleep.d | func int B_StopMagicSleep()
{
Npc_PercDisable (self, PERC_ASSESSDAMAGE);
Npc_ClearAIQueue(self); // alle AI Befehle entfernen
AI_PlayAni (self, "T_VICTIM_SLE_2_STAND" );
AI_StandUp (self);
B_SayOverlay (self, other, "$WHATSTHAT"); // eigentlich $whatwasthat, aber was ist das ?
//-------- fallgelassene Waffe aufheben... --------
//B_RegainDroppedWeapon(self);
//-------- und wieder dem Zauberer zuwenden... --------
if Hlp_IsValidNpc(other)
{
PrintDebugNpc (PD_ZS_CHECK, "...'other' gltig!");
if (Npc_GetAttitude(self,other) == ATT_HOSTILE)
{
PrintDebugNpc (PD_ZS_CHECK, "...'other' hostile!");
AI_StartState (self, ZS_AssessEnemy, 0, "");
};
};
AI_ContinueRoutine(self);
};
func void ZS_MagicSleep()
{
PrintDebugNpc (PD_ZS_FRAME, "ZS_MagicSleep");
// der ZS_MagicSleep beendet sich selbst im loop, daher ist keine perception PERC_ASSESSSTOPMAGIC ntig, und darf
// auch nicht gesetzt werden, ansonsten wird der diesen zustand aktivierende effekt wenn er beendet ist (z.B. weil
// der partikeleffekt stirbt) ein assessstopmagic senden, und dadurch illegalerweise vorzeitig den zustand beenden
// mit anderen worten: der pfx triggert diesen zustand, und der zustand beendet sich selbst
Npc_PercEnable (self, PERC_ASSESSDAMAGE, B_StopMagicSleep);
Npc_PercEnable (self, PERC_ASSESSMAGIC, B_AssessMagic);
// wenn Opfer Schwimmt oder Taucht wird es nicht einschlafen
if ( C_BodystateContains(self,BS_SWIM) || C_BodystateContains(self,BS_DIVE) )
{
AI_ContinueRoutine ( self );
return;
};
if (Npc_WasInState(self, ZS_Unconscious))
{
AI_ContinueRoutine (self);
return;
};
Npc_ClearAIQueue (self);
if ( !Npc_HasBodyFlag (self, BS_FLAG_INTERRUPTABLE) )
{
PrintDebugNpc (PD_MAGIC, "bodystate not interuptable, standing up...");
AI_StandUp (self);
};
//B_DropWeapon (self); //SN: macht Probleme!
AI_PlayAniBS (self, "T_STAND_2_VICTIM_SLE", BS_LIE );
//Npc_SetTempAttitude (self, ATT_HOSTILE); //SN: macht Probleme!
};
func void ZS_MagicSleep_Loop ()
{
PrintDebugNpc (PD_ZS_LOOP, "MagicSleep Loop" );
var int time;
time = Npc_GetStateTime (self);
if ( time>SPL_TIME_SLEEP ) // nach 30 sekunden wird der zustand beendet.
{
B_StopMagicSleep();
};
AI_Wait (self, 1);
};
func void ZS_MagicSleep_End()
{
PrintDebugNpc ( PD_ZS_FRAME, "ZS_MagicSleep_End" );
};
| 411 | 0.938123 | 1 | 0.938123 | game-dev | MEDIA | 0.959093 | game-dev | 0.963832 | 1 | 0.963832 |
bigsinger/awesomeFrida | 4,332 | pthread_create-replace-jni.js | /**
* Frida Hook - 监视 `pthread_create`,检测目标库创建的线程
*
* 目标:
* - 监视 `dlopen` 和 `android_dlopen_ext`,检测目标库何时加载。
* - 通过 `call_constructors` 确保 `pthread_create` Hook 在目标库加载后执行。
* - 拦截 `pthread_create`,检查线程函数是否在目标库 `so` 的范围内。
* - 若发现目标库创建的线程,则替换线程函数,阻止其执行。
* - 并在 JNI_OnLoad 里替换未注册成功的jni函数。
*
* 说明:
* - `pthread_create` 是创建线程的标准函数,Hook 它可以拦截所有新建线程。
* - `call_constructors` 由 `linker` 调用,用于执行动态库的全局构造函数。
* - `hook_call_constructors()` 确保 `TargetLibModule` 记录目标库的基地址,并在适当时机 Hook `pthread_create`。
*/
const TARGET_LIB_NAME = "libmsaoaidsec.so";
var TargetLibModule = null; // 存储目标库模块信息
/////////////////////////////////////////
/**
* Hook pthread_create,拦截目标库创建的线程
*/
function hook_pthread_create() {
let pthread_create_addr = Module.findExportByName("libc.so", "pthread_create");
if (!pthread_create_addr) {
console.error("Failed to find pthread_create!");
return;
}
Interceptor.attach(pthread_create_addr, {
onEnter(args) {
let thread_func_ptr = args[2]; // 线程函数地址
console.log("[+] pthread_create called, thread function address: " + thread_func_ptr);
// 确保目标库已加载
if (!TargetLibModule) {
//console.warn("Target library not loaded yet!");
return;
}
// 判断线程函数是否在目标库 `so` 的范围内
if (thread_func_ptr.compare(TargetLibModule.base) > 0 &&
thread_func_ptr.compare(TargetLibModule.base.add(TargetLibModule.size)) < 0) {
console.warn("[!] Intercepted thread function at: " + thread_func_ptr +
" (Offset: " + thread_func_ptr.sub(TargetLibModule.base) + ")");
// 替换线程函数,防止执行
Interceptor.replace(thread_func_ptr, new NativeCallback(() => {
console.log("[*] Fake thread function executed, doing nothing...");
}, "void", []));
}
}
});
}
function hook_JNI_OnLoad() {
// 先尝试通过 `findExportByName`
let jniOnLoad = Module.findExportByName(TARGET_LIB_NAME, "JNI_OnLoad");
// 如果找不到,就遍历所有导出符号
if (!jniOnLoad) {
console.log("[Info] `JNI_OnLoad` 未导出,尝试遍历导出符号...");
for (let symbol of module.enumerateSymbols()) {
if (symbol.name.indexOf("JNI_OnLoad") >= 0) {
jniOnLoad = symbol.address;
console.log("[Success] 找到 JNI_OnLoad: ", jniOnLoad);
break;
}
}
}
if (!jniOnLoad) {
console.error("[Error] 未找到 `JNI_OnLoad` 函数");
return;
}
// Hook `JNI_OnLoad`
Interceptor.attach(jniOnLoad, {
onEnter(args) {
console.log("[Hooked] JNI_OnLoad 被调用");
bypass();
}
});
}
function bypass() {
try {
var targetClassName = "com.bun.miitmdid.e";
var targetClass = Java.use(targetClassName);
console.log("[*] Successfully loaded class: " + targetClass);
targetClass.a.overloads.forEach(function (overload) {
overload.implementation = function () {
console.log("[*] Hooked " + targetClass + ".a() with args: " + JSON.stringify(arguments));
return 0; // 理论上要返回对应的值,这里粗暴一点随便返回个数值,不影响App正常运行即可。
};
});
} catch (e) {
console.log("[!] Error: " + e);
}
}
function find_call_constructors() {
is64Bit = Process.pointerSize === 8;
var linkerModule = Process.getModuleByName(is64Bit ? "linker64" : "linker");
var symbols = linkerModule.enumerateSymbols();
for (var i = 0; i < symbols.length; i++) {
if (symbols[i].name.indexOf('call_constructors') > 0) {
console.warn(`call_constructors symbol name: ${symbols[i].name} address: ${symbols[i].address}`);
return symbols[i].address;
}
}
}
function hook_call_constructors() {
var ptr_call_constructors = find_call_constructors();
var listener = Interceptor.attach(ptr_call_constructors, {
onEnter: function (args) {
console.warn(`call_constructors onEnter`);
if (!TargetLibModule) {
TargetLibModule = Process.findModuleByName(TARGET_LIB_NAME);
}
hook_pthread_create();
listener.detach();
},
})
}
function hook_dlopen() {
["android_dlopen_ext", "dlopen"].forEach(funcName => {
let addr = Module.findExportByName(null, funcName);
if (addr) {
Interceptor.attach(addr, {
onEnter(args) {
let libName = ptr(args[0]).readCString();
if (libName && libName.indexOf(TARGET_LIB_NAME) >= 0) {
this.is_can_hook = true;
hook_call_constructors();
}
},
onLeave: function (retval) {
if (this.is_can_hook) {
console.log(`[+] ${funcName} onLeave, start hook JNI_OnLoad `);
hook_JNI_OnLoad();
}
}
});
}
});
}
var is64Bit = Process.pointerSize === 8;
hook_dlopen()
| 411 | 0.849565 | 1 | 0.849565 | game-dev | MEDIA | 0.236012 | game-dev | 0.89938 | 1 | 0.89938 |
DynamXInc/DynamX | 3,877 | src/main/java/fr/dynamx/common/entities/modules/MovableModule.java | package fr.dynamx.common.entities.modules;
import com.jme3.bullet.joints.Constraint;
import fr.dynamx.api.entities.modules.AttachModule;
import fr.dynamx.api.entities.modules.IPhysicsModule;
import fr.dynamx.api.entities.modules.ModuleListBuilder;
import fr.dynamx.common.entities.PhysicsEntity;
import fr.dynamx.common.entities.modules.movables.AttachObjects;
import fr.dynamx.common.entities.modules.movables.MoveObjects;
import fr.dynamx.common.entities.modules.movables.PickObjects;
import fr.dynamx.common.physics.entities.AbstractEntityPhysicsHandler;
import fr.dynamx.common.physics.joints.EntityJoint;
import fr.dynamx.common.physics.joints.JointHandler;
import fr.dynamx.common.physics.joints.JointHandlerRegistry;
import fr.dynamx.utils.DynamXConstants;
import lombok.Getter;
import net.minecraft.util.ResourceLocation;
import java.util.Arrays;
public class MovableModule implements IPhysicsModule<AbstractEntityPhysicsHandler<?, ?>>, AttachModule.AttachToSelfModule, IPhysicsModule.IEntityUpdateListener, IPhysicsModule.IPhysicsUpdateListener {
public static final ResourceLocation JOINT_NAME = new ResourceLocation(DynamXConstants.ID, "movable_module");
static {
JointHandlerRegistry.register(new JointHandler(JOINT_NAME, PhysicsEntity.class, PhysicsEntity.class, MovableModule.class));
}
public final PhysicsEntity<?> entity;
public PickObjects pickObjects;
public AttachObjects attachObjects;
public MoveObjects moveObjects;
public EnumAction usingAction;
public MovableModule(PhysicsEntity<?> entity) {
this.entity = entity;
}
/* Should not be called in the constructor */
public void initSubModules(ModuleListBuilder modules, PhysicsEntity<?> entity) {
//System.out.println("init modules ! " + this);
modules.add(moveObjects = new MoveObjects(entity));
modules.add(pickObjects = new PickObjects(entity));
modules.add(attachObjects = new AttachObjects(entity));
}
@Override
public Constraint createJoint(byte jointId) {
if (jointId == 0) {
return pickObjects.createWeldJoint();
} else if (jointId == 1 || jointId == 2) {
return attachObjects.createJointBetween2Objects(jointId);
}
return null;
}
@Override
public boolean canCreateJoint(PhysicsEntity<?> withEntity, byte jointId) {
if (jointId == 0) {
return pickObjects.canCreateJoint(withEntity, jointId);
} else if (jointId == 1 || jointId == 2) {
return attachObjects.canCreateJoint(withEntity, jointId);
}
return false;
}
@Override
public void onJointDestroyed(EntityJoint<?> joint) {
if (joint.getJointId() == 0) {
pickObjects.onJointDestroyed(joint);
} else if (joint.getJointId() == 1 || joint.getJointId() == 2) {
attachObjects.onJointDestroyed(joint);
}
}
public enum EnumAction {
TAKE, UNTAKE, PICK, UNPICK, LENGTH_CHANGE, FREEZE_OBJECT, ATTACH_OBJECTS, THROW
}
public static class Action {
@Getter
private Object[] info;
private EnumAction enumAction;
public Action() {
}
public Action(EnumAction action, Object... info) {
this.enumAction = action;
this.info = info;
}
public void setEnumAction(EnumAction enumAction) {
this.enumAction = enumAction;
}
public void setInfo(Object[] info) {
this.info = info;
}
public EnumAction getMovableAction() {
return enumAction;
}
@Override
public String toString() {
return "Action{" +
"info=" + Arrays.toString(info) +
", enumAction=" + enumAction +
'}';
}
}
}
| 411 | 0.791207 | 1 | 0.791207 | game-dev | MEDIA | 0.363029 | game-dev | 0.912089 | 1 | 0.912089 |
bates64/papermario-dx | 7,876 | src/world/area_kkj/kkj_14/main.c | #include "kkj_14.h"
#include "world/common/atomic/TexturePan.inc.c"
#include "../common/RestoreFromPeachState.inc.c"
API_CALLABLE(N(EnableParasol)) {
gGameStatusPtr->peachFlags |= PEACH_FLAG_HAS_PARASOL;
return ApiStatus_DONE2;
}
Gfx N(setup_gfx_candle_lights)[] = {
gsDPPipeSync(),
gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_ON),
gsDPSetCycleType(G_CYC_2CYCLE),
gsDPSetTexturePersp(G_TP_PERSP),
gsDPSetTextureDetail(G_TD_CLAMP),
gsDPSetTextureLOD(G_TL_TILE),
gsDPSetTextureLUT(G_TT_NONE),
gsDPSetTextureFilter(G_TF_BILERP),
gsDPSetTextureConvert(G_TC_FILT),
gsDPSetPrimColor(0, 0, 75, 31, 19, 255),
gsDPSetEnvColor(255, 118, 77, 0),
gsDPSetCombineMode(PM_CC_CANDLE_1, PM_CC_CANDLE_2),
gsDPSetRenderMode(G_RM_PASS, G_RM_ZB_CLD_SURF2),
gsSPClearGeometryMode(G_LIGHTING),
gsSPSetGeometryMode(G_SHADE | G_CULL_BACK | G_SHADING_SMOOTH),
gsSPEndDisplayList(),
};
EvtScript N(EVS_EndPeachChapter7) = {
Set(LVar0, GB_KKJ_LastPartner)
Call(N(RestoreFromPeachState))
Call(PlaySound, SOUND_SLIDE_WHISTLE_OUT)
Call(GotoMapSpecial, Ref("pra_01"), pra_01_ENTRY_4, TRANSITION_END_PEACH_INTERLUDE)
Wait(100)
};
EvtScript N(EVS_ExitDoor_GrandHall) = {
SetGroup(EVT_GROUP_EXIT_MAP)
Call(DisablePlayerInput, TRUE)
Set(AF_KKJ_13, TRUE)
Call(UseDoorSounds, DOOR_SOUNDS_BASIC)
Set(LVar0, kkj_14_ENTRY_0)
Set(LVar1, COLLIDER_ttw)
Set(LVar2, MODEL_o4)
Set(LVar3, DOOR_SWING_IN)
Exec(ExitSingleDoor)
Wait(17)
IfEq(GB_StoryProgress, STORY_INTRO)
Call(GotoMap, Ref("kkj_01"), kkj_01_ENTRY_4)
Else
Call(GotoMap, Ref("kkj_11"), kkj_11_ENTRY_4)
EndIf
Wait(100)
Return
End
};
EvtScript N(EVS_ExitDoors_Balcony) = {
SetGroup(EVT_GROUP_EXIT_MAP)
Call(DisablePlayerInput, TRUE)
Set(AF_KKJ_13, FALSE)
Call(UseDoorSounds, DOOR_SOUNDS_DOOR)
Set(LVar0, kkj_14_ENTRY_1)
Set(LVar1, COLLIDER_tte)
Set(LVar2, MODEL_o83)
Set(LVar3, MODEL_o85)
Set(LVar4, MODEL_o84)
Set(LVar5, MODEL_o86)
Exec(ExitSplitDoubleDoor)
Wait(17)
Call(GotoMap, Ref("kkj_26"), kkj_26_ENTRY_0)
Wait(100)
Return
End
};
EvtScript N(EVS_ExitWalk_SecretPassage) = {
SetGroup(EVT_GROUP_EXIT_MAP)
Set(AF_KKJ_13, FALSE)
Call(UseExitHeading, 60, kkj_14_ENTRY_2)
Exec(ExitWalk)
IfEq(GF_KKJ14_SkipSecretPassage, FALSE)
Call(GotoMap, Ref("kkj_27"), kkj_27_ENTRY_0)
Else
Call(GotoMap, Ref("kkj_15"), kkj_15_ENTRY_1)
EndIf
Wait(100)
Return
End
};
EvtScript N(EVS_ShowMessage_CantOpen) = {
Call(DisablePlayerInput, TRUE)
Call(ShowMessageAtScreenPos, MSG_Menus_Inspect_DoesntOpen, 160, 40)
Call(DisablePlayerInput, FALSE)
Return
End
};
EvtScript N(EVS_BindExitTriggers) = {
IfEq(GB_StoryProgress, STORY_INTRO)
BindTrigger(Ref(N(EVS_ShowMessage_CantOpen)), TRIGGER_WALL_PRESS_A, COLLIDER_tte, 1, 0)
Else
BindTrigger(Ref(N(EVS_ExitDoors_Balcony)), TRIGGER_WALL_PRESS_A, COLLIDER_tte, 1, 0)
BindTrigger(Ref(N(EVS_ExitWalk_SecretPassage)), TRIGGER_FLOOR_ABOVE, COLLIDER_o119, 1, 0)
EndIf
BindTrigger(Ref(N(EVS_ExitDoor_GrandHall)), TRIGGER_WALL_PRESS_A, COLLIDER_ttw, 1, 0)
Return
End
};
EvtScript N(EVS_EnterMap) = {
Call(GetEntryID, LVar0)
Switch(LVar0)
CaseEq(kkj_14_ENTRY_0)
Call(UseDoorSounds, DOOR_SOUNDS_BASIC)
Set(LVar2, MODEL_o4)
Set(LVar3, DOOR_SWING_IN)
ExecWait(EnterSingleDoor)
Exec(N(EVS_BindExitTriggers))
CaseEq(kkj_14_ENTRY_1)
Call(UseDoorSounds, DOOR_SOUNDS_DOOR)
Set(LVar2, MODEL_o83)
Set(LVar3, MODEL_o85)
Set(LVar4, MODEL_o84)
Set(LVar5, MODEL_o86)
ExecWait(EnterSplitDoubleDoor)
Exec(N(EVS_BindExitTriggers))
CaseEq(kkj_14_ENTRY_2)
Set(LVar0, Ref(N(EVS_BindExitTriggers)))
Exec(EnterWalk)
CaseEq(kkj_14_ENTRY_3)
Exec(N(EVS_Scene_Chapter0))
CaseEq(kkj_14_ENTRY_4)
Exec(N(EVS_Scene_Chapter1))
Exec(N(EVS_BindExitTriggers))
CaseEq(kkj_14_ENTRY_5)
Exec(N(EVS_Scene_Chapter2))
Exec(N(EVS_BindExitTriggers))
CaseEq(kkj_14_ENTRY_6)
Exec(N(EVS_Scene_Chapter3))
Exec(N(EVS_BindExitTriggers))
CaseEq(kkj_14_ENTRY_7)
Exec(N(EVS_Scene_Chapter4))
Exec(N(EVS_BindExitTriggers))
CaseEq(kkj_14_ENTRY_8)
Exec(N(EVS_Scene_Chapter5))
Exec(N(EVS_BindExitTriggers))
CaseEq(kkj_14_ENTRY_9)
Exec(N(EVS_Scene_Chapter6))
Exec(N(EVS_BindExitTriggers))
CaseEq(kkj_14_ENTRY_A)
Exec(N(EVS_Scene_Chapter7))
CaseEq(kkj_14_ENTRY_B)
Exec(N(EVS_Scene_TossedBackInRoom))
Exec(N(EVS_BindExitTriggers))
EndSwitch
Return
End
};
EvtScript N(EVS_Main) = {
Set(GB_WorldLocation, LOCATION_PEACHS_CASTLE)
Call(SetSpriteShading, SHADING_NONE)
EVT_SETUP_CAMERA_DEFAULT(0, 0, 0)
Call(GetEntryID, LVar0)
IfGe(LVar0, kkj_14_ENTRY_3)
IfNe(LVar0, kkj_14_ENTRY_B)
Set(GF_KKJ14_RevealedButton, FALSE)
Set(GF_KKJ14_OpenedPassage, FALSE)
EndIf
Switch(LVar0)
CaseEq(kkj_14_ENTRY_3)
Set(GB_StoryProgress, STORY_CH0_BEGAN_PEACH_MISSION)
Set(GB_KKJ_CaughtCount, 0)
Set(GF_KKJ14_SkipSecretPassage, FALSE)
Call(MakeNpcs, FALSE, Ref(N(Chapter0NPCs)))
CaseEq(kkj_14_ENTRY_4)
Set(GB_StoryProgress, STORY_CH1_BEGAN_PEACH_MISSION)
Set(GB_KKJ_CaughtCount, 0)
Set(GF_KKJ14_SkipSecretPassage, FALSE)
CaseEq(kkj_14_ENTRY_5)
Set(GB_StoryProgress, STORY_CH2_BEGAN_PEACH_MISSION)
Set(GB_KKJ_CaughtCount, 0)
Set(GF_KKJ14_SkipSecretPassage, FALSE)
Set(AF_KKJ_06, FALSE)
Call(MakeNpcs, FALSE, Ref(N(Chapter2NPCs)))
CaseEq(kkj_14_ENTRY_6)
Set(GB_StoryProgress, STORY_CH3_BEGAN_PEACH_MISSION)
Set(GB_KKJ_CaughtCount, 0)
Set(GF_KKJ14_SkipSecretPassage, FALSE)
CaseEq(kkj_14_ENTRY_7)
Set(GB_StoryProgress, STORY_CH4_BEGAN_PEACH_MISSION)
Set(GB_KKJ_CaughtCount, 0)
Set(GF_KKJ14_SkipSecretPassage, TRUE)
CaseEq(kkj_14_ENTRY_8)
Set(GB_StoryProgress, STORY_CH5_BEGAN_PEACH_MISSION)
Set(GB_KKJ_CaughtCount, 0)
Set(GF_KKJ14_SkipSecretPassage, TRUE)
CaseEq(kkj_14_ENTRY_9)
Call(N(EnableParasol))
Set(GB_StoryProgress, STORY_CH6_BEGAN_PEACH_MISSION)
Set(GB_KKJ_CaughtCount, 0)
Set(GF_KKJ14_SkipSecretPassage, TRUE)
CaseEq(kkj_14_ENTRY_A)
Call(MakeNpcs, FALSE, Ref(N(Chapter7NPCs)))
CaseEq(kkj_14_ENTRY_B)
Add(GB_KKJ_CaughtCount, 1)
Call(MakeNpcs, FALSE, Ref(N(TossBackNPCs)))
EndSwitch
EndIf
Exec(N(EVS_SetupInteractables))
Call(GetEntryID, LVar0)
IfNe(LVar0, kkj_14_ENTRY_5)
Exec(N(EVS_SetupMusic))
EndIf
Exec(N(EVS_EnterMap))
Call(SetTexPanner, MODEL_o154, TEX_PANNER_0)
Thread
TEX_PAN_PARAMS_ID(TEX_PANNER_0)
TEX_PAN_PARAMS_STEP( 0, 0, 40, 900)
TEX_PAN_PARAMS_FREQ( 1, 1, 1, 1)
TEX_PAN_PARAMS_INIT( 0, 0, 0, 0)
Exec(N(EVS_UpdateTexturePan))
EndThread
Call(SetModelCustomGfx, MODEL_o154, CUSTOM_GFX_0, ENV_TINT_UNCHANGED)
Call(SetCustomGfx, CUSTOM_GFX_0, Ref(N(setup_gfx_candle_lights)), NULL)
Return
End
};
| 411 | 0.932568 | 1 | 0.932568 | game-dev | MEDIA | 0.651413 | game-dev | 0.972927 | 1 | 0.972927 |
ForOne-Club/ImproveGame | 2,117 | UI/AmmoChainPanel/ChainEditPage/TipClickToAdd.cs | using ImproveGame.Content.Functions.ChainedAmmo;
using ImproveGame.Core;
using ImproveGame.UIFramework.BaseViews;
using ImproveGame.UIFramework.SUIElements;
namespace ImproveGame.UI.AmmoChainPanel.ChainEditPage;
public class TipClickToAdd : TimerView
{
public ChainEditPage Parent;
public TipClickToAdd(ChainEditPage parent)
{
Parent = parent;
SetSizePercent(1f);
SetSizePixels(0, -6);
Border = 0f;
Rounded = new Vector4(4f);
Spacing = new Vector2(2);
var text = new SUIText
{
TextOrKey = "Mods.ImproveGame.UI.AmmoChain.ClickToAddL1",
UseKey = true,
TextAlign = new Vector2(0.5f)
};
text.SetPosPixels(0f, -15f);
text.SetSizePercent(1f);
text.JoinParent(this);
text = new SUIText
{
TextOrKey = "Mods.ImproveGame.UI.AmmoChain.ClickToAddL2",
UseKey = true,
TextAlign = new Vector2(0.5f)
};
text.SetPosPixels(0f, 11f);
text.SetSizePercent(1f);
text.JoinParent(this);
}
public override void LeftMouseDown(UIMouseEvent evt)
{
if (Parent.EditingChain.Chain.Count != 0)
return;
base.LeftMouseDown(evt);
if (Parent.SelectedAmmoType is ItemID.None)
return;
var item = new Item(Parent.SelectedAmmoType);
Parent.EditingChain.Chain.Add(new AmmoChain.Ammo(new ItemTypeData(item), 10));
Parent.ShouldResetCurrentChain = true;
SoundEngine.PlaySound(SoundID.MenuTick);
}
public override void Update(GameTime gameTime)
{
if (Parent.EditingChain.Chain.Count != 0)
{
SetSizePercent(0f);
Recalculate();
return;
}
base.Update(gameTime);
SetSizePercent(1f);
Recalculate();
BgColor = Color.Black * HoverTimer.Lerp(0.3f, 0.6f);
}
public override void Draw(SpriteBatch spriteBatch)
{
if (Parent.EditingChain.Chain.Count != 0)
return;
base.Draw(spriteBatch);
}
} | 411 | 0.880307 | 1 | 0.880307 | game-dev | MEDIA | 0.942499 | game-dev | 0.953562 | 1 | 0.953562 |
ryichando/shiokaze | 18,492 | local/include/bullet3/BulletCollision/CollisionDispatch/btCollisionObject.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_COLLISION_OBJECT_H
#define BT_COLLISION_OBJECT_H
#include "LinearMath/btTransform.h"
//island management, m_activationState1
#define ACTIVE_TAG 1
#define ISLAND_SLEEPING 2
#define WANTS_DEACTIVATION 3
#define DISABLE_DEACTIVATION 4
#define DISABLE_SIMULATION 5
struct btBroadphaseProxy;
class btCollisionShape;
struct btCollisionShapeData;
#include "LinearMath/btMotionState.h"
#include "LinearMath/btAlignedAllocator.h"
#include "LinearMath/btAlignedObjectArray.h"
typedef btAlignedObjectArray<class btCollisionObject*> btCollisionObjectArray;
#ifdef BT_USE_DOUBLE_PRECISION
#define btCollisionObjectData btCollisionObjectDoubleData
#define btCollisionObjectDataName "btCollisionObjectDoubleData"
#else
#define btCollisionObjectData btCollisionObjectFloatData
#define btCollisionObjectDataName "btCollisionObjectFloatData"
#endif
/// btCollisionObject can be used to manage collision detection objects.
/// btCollisionObject maintains all information that is needed for a collision detection: Shape, Transform and AABB proxy.
/// They can be added to the btCollisionWorld.
ATTRIBUTE_ALIGNED16(class)
btCollisionObject
{
protected:
btTransform m_worldTransform;
///m_interpolationWorldTransform is used for CCD and interpolation
///it can be either previous or future (predicted) transform
btTransform m_interpolationWorldTransform;
//those two are experimental: just added for bullet time effect, so you can still apply impulses (directly modifying velocities)
//without destroying the continuous interpolated motion (which uses this interpolation velocities)
btVector3 m_interpolationLinearVelocity;
btVector3 m_interpolationAngularVelocity;
btVector3 m_anisotropicFriction;
int m_hasAnisotropicFriction;
btScalar m_contactProcessingThreshold;
btBroadphaseProxy* m_broadphaseHandle;
btCollisionShape* m_collisionShape;
///m_extensionPointer is used by some internal low-level Bullet extensions.
void* m_extensionPointer;
///m_rootCollisionShape is temporarily used to store the original collision shape
///The m_collisionShape might be temporarily replaced by a child collision shape during collision detection purposes
///If it is NULL, the m_collisionShape is not temporarily replaced.
btCollisionShape* m_rootCollisionShape;
int m_collisionFlags;
int m_islandTag1;
int m_companionId;
int m_worldArrayIndex; // index of object in world's collisionObjects array
mutable int m_activationState1;
mutable btScalar m_deactivationTime;
btScalar m_friction;
btScalar m_restitution;
btScalar m_rollingFriction; //torsional friction orthogonal to contact normal (useful to stop spheres rolling forever)
btScalar m_spinningFriction; // torsional friction around the contact normal (useful for grasping)
btScalar m_contactDamping;
btScalar m_contactStiffness;
///m_internalType is reserved to distinguish Bullet's btCollisionObject, btRigidBody, btSoftBody, btGhostObject etc.
///do not assign your own m_internalType unless you write a new dynamics object class.
int m_internalType;
///users can point to their objects, m_userPointer is not used by Bullet, see setUserPointer/getUserPointer
void* m_userObjectPointer;
int m_userIndex2;
int m_userIndex;
int m_userIndex3;
///time of impact calculation
btScalar m_hitFraction;
///Swept sphere radius (0.0 by default), see btConvexConvexAlgorithm::
btScalar m_ccdSweptSphereRadius;
/// Don't do continuous collision detection if the motion (in one step) is less then m_ccdMotionThreshold
btScalar m_ccdMotionThreshold;
/// If some object should have elaborate collision filtering by sub-classes
int m_checkCollideWith;
btAlignedObjectArray<const btCollisionObject*> m_objectsWithoutCollisionCheck;
///internal update revision number. It will be increased when the object changes. This allows some subsystems to perform lazy evaluation.
int m_updateRevision;
btVector3 m_customDebugColorRGB;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
enum CollisionFlags
{
CF_STATIC_OBJECT = 1,
CF_KINEMATIC_OBJECT = 2,
CF_NO_CONTACT_RESPONSE = 4,
CF_CUSTOM_MATERIAL_CALLBACK = 8, //this allows per-triangle material (friction/restitution)
CF_CHARACTER_OBJECT = 16,
CF_DISABLE_VISUALIZE_OBJECT = 32, //disable debug drawing
CF_DISABLE_SPU_COLLISION_PROCESSING = 64, //disable parallel/SPU processing
CF_HAS_CONTACT_STIFFNESS_DAMPING = 128,
CF_HAS_CUSTOM_DEBUG_RENDERING_COLOR = 256,
CF_HAS_FRICTION_ANCHOR = 512,
CF_HAS_COLLISION_SOUND_TRIGGER = 1024
};
enum CollisionObjectTypes
{
CO_COLLISION_OBJECT = 1,
CO_RIGID_BODY = 2,
///CO_GHOST_OBJECT keeps track of all objects overlapping its AABB and that pass its collision filter
///It is useful for collision sensors, explosion objects, character controller etc.
CO_GHOST_OBJECT = 4,
CO_SOFT_BODY = 8,
CO_HF_FLUID = 16,
CO_USER_TYPE = 32,
CO_FEATHERSTONE_LINK = 64
};
enum AnisotropicFrictionFlags
{
CF_ANISOTROPIC_FRICTION_DISABLED = 0,
CF_ANISOTROPIC_FRICTION = 1,
CF_ANISOTROPIC_ROLLING_FRICTION = 2
};
SIMD_FORCE_INLINE bool mergesSimulationIslands() const
{
///static objects, kinematic and object without contact response don't merge islands
return ((m_collisionFlags & (CF_STATIC_OBJECT | CF_KINEMATIC_OBJECT | CF_NO_CONTACT_RESPONSE)) == 0);
}
const btVector3& getAnisotropicFriction() const
{
return m_anisotropicFriction;
}
void setAnisotropicFriction(const btVector3& anisotropicFriction, int frictionMode = CF_ANISOTROPIC_FRICTION)
{
m_anisotropicFriction = anisotropicFriction;
bool isUnity = (anisotropicFriction[0] != 1.f) || (anisotropicFriction[1] != 1.f) || (anisotropicFriction[2] != 1.f);
m_hasAnisotropicFriction = isUnity ? frictionMode : 0;
}
bool hasAnisotropicFriction(int frictionMode = CF_ANISOTROPIC_FRICTION) const
{
return (m_hasAnisotropicFriction & frictionMode) != 0;
}
///the constraint solver can discard solving contacts, if the distance is above this threshold. 0 by default.
///Note that using contacts with positive distance can improve stability. It increases, however, the chance of colliding with degerate contacts, such as 'interior' triangle edges
void setContactProcessingThreshold(btScalar contactProcessingThreshold)
{
m_contactProcessingThreshold = contactProcessingThreshold;
}
btScalar getContactProcessingThreshold() const
{
return m_contactProcessingThreshold;
}
SIMD_FORCE_INLINE bool isStaticObject() const
{
return (m_collisionFlags & CF_STATIC_OBJECT) != 0;
}
SIMD_FORCE_INLINE bool isKinematicObject() const
{
return (m_collisionFlags & CF_KINEMATIC_OBJECT) != 0;
}
SIMD_FORCE_INLINE bool isStaticOrKinematicObject() const
{
return (m_collisionFlags & (CF_KINEMATIC_OBJECT | CF_STATIC_OBJECT)) != 0;
}
SIMD_FORCE_INLINE bool hasContactResponse() const
{
return (m_collisionFlags & CF_NO_CONTACT_RESPONSE) == 0;
}
btCollisionObject();
virtual ~btCollisionObject();
virtual void setCollisionShape(btCollisionShape * collisionShape)
{
m_updateRevision++;
m_collisionShape = collisionShape;
m_rootCollisionShape = collisionShape;
}
SIMD_FORCE_INLINE const btCollisionShape* getCollisionShape() const
{
return m_collisionShape;
}
SIMD_FORCE_INLINE btCollisionShape* getCollisionShape()
{
return m_collisionShape;
}
void setIgnoreCollisionCheck(const btCollisionObject* co, bool ignoreCollisionCheck)
{
if (ignoreCollisionCheck)
{
//We don't check for duplicates. Is it ok to leave that up to the user of this API?
//int index = m_objectsWithoutCollisionCheck.findLinearSearch(co);
//if (index == m_objectsWithoutCollisionCheck.size())
//{
m_objectsWithoutCollisionCheck.push_back(co);
//}
}
else
{
m_objectsWithoutCollisionCheck.remove(co);
}
m_checkCollideWith = m_objectsWithoutCollisionCheck.size() > 0;
}
virtual bool checkCollideWithOverride(const btCollisionObject* co) const
{
int index = m_objectsWithoutCollisionCheck.findLinearSearch(co);
if (index < m_objectsWithoutCollisionCheck.size())
{
return false;
}
return true;
}
///Avoid using this internal API call, the extension pointer is used by some Bullet extensions.
///If you need to store your own user pointer, use 'setUserPointer/getUserPointer' instead.
void* internalGetExtensionPointer() const
{
return m_extensionPointer;
}
///Avoid using this internal API call, the extension pointer is used by some Bullet extensions
///If you need to store your own user pointer, use 'setUserPointer/getUserPointer' instead.
void internalSetExtensionPointer(void* pointer)
{
m_extensionPointer = pointer;
}
SIMD_FORCE_INLINE int getActivationState() const { return m_activationState1; }
void setActivationState(int newState) const;
void setDeactivationTime(btScalar time)
{
m_deactivationTime = time;
}
btScalar getDeactivationTime() const
{
return m_deactivationTime;
}
void forceActivationState(int newState) const;
void activate(bool forceActivation = false) const;
SIMD_FORCE_INLINE bool isActive() const
{
return ((getActivationState() != ISLAND_SLEEPING) && (getActivationState() != DISABLE_SIMULATION));
}
void setRestitution(btScalar rest)
{
m_updateRevision++;
m_restitution = rest;
}
btScalar getRestitution() const
{
return m_restitution;
}
void setFriction(btScalar frict)
{
m_updateRevision++;
m_friction = frict;
}
btScalar getFriction() const
{
return m_friction;
}
void setRollingFriction(btScalar frict)
{
m_updateRevision++;
m_rollingFriction = frict;
}
btScalar getRollingFriction() const
{
return m_rollingFriction;
}
void setSpinningFriction(btScalar frict)
{
m_updateRevision++;
m_spinningFriction = frict;
}
btScalar getSpinningFriction() const
{
return m_spinningFriction;
}
void setContactStiffnessAndDamping(btScalar stiffness, btScalar damping)
{
m_updateRevision++;
m_contactStiffness = stiffness;
m_contactDamping = damping;
m_collisionFlags |= CF_HAS_CONTACT_STIFFNESS_DAMPING;
//avoid divisions by zero...
if (m_contactStiffness < SIMD_EPSILON)
{
m_contactStiffness = SIMD_EPSILON;
}
}
btScalar getContactStiffness() const
{
return m_contactStiffness;
}
btScalar getContactDamping() const
{
return m_contactDamping;
}
///reserved for Bullet internal usage
int getInternalType() const
{
return m_internalType;
}
btTransform& getWorldTransform()
{
return m_worldTransform;
}
const btTransform& getWorldTransform() const
{
return m_worldTransform;
}
void setWorldTransform(const btTransform& worldTrans)
{
m_updateRevision++;
m_worldTransform = worldTrans;
}
SIMD_FORCE_INLINE btBroadphaseProxy* getBroadphaseHandle()
{
return m_broadphaseHandle;
}
SIMD_FORCE_INLINE const btBroadphaseProxy* getBroadphaseHandle() const
{
return m_broadphaseHandle;
}
void setBroadphaseHandle(btBroadphaseProxy * handle)
{
m_broadphaseHandle = handle;
}
const btTransform& getInterpolationWorldTransform() const
{
return m_interpolationWorldTransform;
}
btTransform& getInterpolationWorldTransform()
{
return m_interpolationWorldTransform;
}
void setInterpolationWorldTransform(const btTransform& trans)
{
m_updateRevision++;
m_interpolationWorldTransform = trans;
}
void setInterpolationLinearVelocity(const btVector3& linvel)
{
m_updateRevision++;
m_interpolationLinearVelocity = linvel;
}
void setInterpolationAngularVelocity(const btVector3& angvel)
{
m_updateRevision++;
m_interpolationAngularVelocity = angvel;
}
const btVector3& getInterpolationLinearVelocity() const
{
return m_interpolationLinearVelocity;
}
const btVector3& getInterpolationAngularVelocity() const
{
return m_interpolationAngularVelocity;
}
SIMD_FORCE_INLINE int getIslandTag() const
{
return m_islandTag1;
}
void setIslandTag(int tag)
{
m_islandTag1 = tag;
}
SIMD_FORCE_INLINE int getCompanionId() const
{
return m_companionId;
}
void setCompanionId(int id)
{
m_companionId = id;
}
SIMD_FORCE_INLINE int getWorldArrayIndex() const
{
return m_worldArrayIndex;
}
// only should be called by CollisionWorld
void setWorldArrayIndex(int ix)
{
m_worldArrayIndex = ix;
}
SIMD_FORCE_INLINE btScalar getHitFraction() const
{
return m_hitFraction;
}
void setHitFraction(btScalar hitFraction)
{
m_hitFraction = hitFraction;
}
SIMD_FORCE_INLINE int getCollisionFlags() const
{
return m_collisionFlags;
}
void setCollisionFlags(int flags)
{
m_collisionFlags = flags;
}
///Swept sphere radius (0.0 by default), see btConvexConvexAlgorithm::
btScalar getCcdSweptSphereRadius() const
{
return m_ccdSweptSphereRadius;
}
///Swept sphere radius (0.0 by default), see btConvexConvexAlgorithm::
void setCcdSweptSphereRadius(btScalar radius)
{
m_ccdSweptSphereRadius = radius;
}
btScalar getCcdMotionThreshold() const
{
return m_ccdMotionThreshold;
}
btScalar getCcdSquareMotionThreshold() const
{
return m_ccdMotionThreshold * m_ccdMotionThreshold;
}
/// Don't do continuous collision detection if the motion (in one step) is less then m_ccdMotionThreshold
void setCcdMotionThreshold(btScalar ccdMotionThreshold)
{
m_ccdMotionThreshold = ccdMotionThreshold;
}
///users can point to their objects, userPointer is not used by Bullet
void* getUserPointer() const
{
return m_userObjectPointer;
}
int getUserIndex() const
{
return m_userIndex;
}
int getUserIndex2() const
{
return m_userIndex2;
}
int getUserIndex3() const
{
return m_userIndex3;
}
///users can point to their objects, userPointer is not used by Bullet
void setUserPointer(void* userPointer)
{
m_userObjectPointer = userPointer;
}
///users can point to their objects, userPointer is not used by Bullet
void setUserIndex(int index)
{
m_userIndex = index;
}
void setUserIndex2(int index)
{
m_userIndex2 = index;
}
void setUserIndex3(int index)
{
m_userIndex3 = index;
}
int getUpdateRevisionInternal() const
{
return m_updateRevision;
}
void setCustomDebugColor(const btVector3& colorRGB)
{
m_customDebugColorRGB = colorRGB;
m_collisionFlags |= CF_HAS_CUSTOM_DEBUG_RENDERING_COLOR;
}
void removeCustomDebugColor()
{
m_collisionFlags &= ~CF_HAS_CUSTOM_DEBUG_RENDERING_COLOR;
}
bool getCustomDebugColor(btVector3 & colorRGB) const
{
bool hasCustomColor = (0 != (m_collisionFlags & CF_HAS_CUSTOM_DEBUG_RENDERING_COLOR));
if (hasCustomColor)
{
colorRGB = m_customDebugColorRGB;
}
return hasCustomColor;
}
inline bool checkCollideWith(const btCollisionObject* co) const
{
if (m_checkCollideWith)
return checkCollideWithOverride(co);
return true;
}
virtual int calculateSerializeBufferSize() const;
///fills the dataBuffer and returns the struct name (and 0 on failure)
virtual const char* serialize(void* dataBuffer, class btSerializer* serializer) const;
virtual void serializeSingleObject(class btSerializer * serializer) const;
};
// clang-format off
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btCollisionObjectDoubleData
{
void *m_broadphaseHandle;
void *m_collisionShape;
btCollisionShapeData *m_rootCollisionShape;
char *m_name;
btTransformDoubleData m_worldTransform;
btTransformDoubleData m_interpolationWorldTransform;
btVector3DoubleData m_interpolationLinearVelocity;
btVector3DoubleData m_interpolationAngularVelocity;
btVector3DoubleData m_anisotropicFriction;
double m_contactProcessingThreshold;
double m_deactivationTime;
double m_friction;
double m_rollingFriction;
double m_contactDamping;
double m_contactStiffness;
double m_restitution;
double m_hitFraction;
double m_ccdSweptSphereRadius;
double m_ccdMotionThreshold;
int m_hasAnisotropicFriction;
int m_collisionFlags;
int m_islandTag1;
int m_companionId;
int m_activationState1;
int m_internalType;
int m_checkCollideWith;
int m_collisionFilterGroup;
int m_collisionFilterMask;
int m_uniqueId;//m_uniqueId is introduced for paircache. could get rid of this, by calculating the address offset etc.
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btCollisionObjectFloatData
{
void *m_broadphaseHandle;
void *m_collisionShape;
btCollisionShapeData *m_rootCollisionShape;
char *m_name;
btTransformFloatData m_worldTransform;
btTransformFloatData m_interpolationWorldTransform;
btVector3FloatData m_interpolationLinearVelocity;
btVector3FloatData m_interpolationAngularVelocity;
btVector3FloatData m_anisotropicFriction;
float m_contactProcessingThreshold;
float m_deactivationTime;
float m_friction;
float m_rollingFriction;
float m_contactDamping;
float m_contactStiffness;
float m_restitution;
float m_hitFraction;
float m_ccdSweptSphereRadius;
float m_ccdMotionThreshold;
int m_hasAnisotropicFriction;
int m_collisionFlags;
int m_islandTag1;
int m_companionId;
int m_activationState1;
int m_internalType;
int m_checkCollideWith;
int m_collisionFilterGroup;
int m_collisionFilterMask;
int m_uniqueId;
};
// clang-format on
SIMD_FORCE_INLINE int btCollisionObject::calculateSerializeBufferSize() const
{
return sizeof(btCollisionObjectData);
}
#endif //BT_COLLISION_OBJECT_H
| 411 | 0.963575 | 1 | 0.963575 | game-dev | MEDIA | 0.994223 | game-dev | 0.859582 | 1 | 0.859582 |
johnttaylor/pim | 1,706 | src/Bsp/RP2040/Pico/gcc/Api.cpp | /*-----------------------------------------------------------------------------
* This file is part of the Colony.Core Project. The Colony.Core Project is an
* open source project with a BSD type of licensing agreement. See the license
* agreement (license.txt) in the top/ directory or on the Internet at
* http://integerfox.com/colony.core/license.txt
*
* Copyright (c) 2022 John T. Taylor
*
* Redistributions of the source code must retain the above copyright notice.
*----------------------------------------------------------------------------*/
#include "Bsp/Api.h"
#include "pico/stdlib.h"
#include <ios>
#define SECT_ "bsp"
critical_section_t g_bspGlobalCritSec_;
#ifdef USE_BSP_NO_STDIO
#define INIT_STDIO()
#else
#define INIT_STDIO stdio_init_all
#endif
///////////////////////////////////////////
void Bsp_Api_initialize( void )
{
// Initialize STDIO
INIT_STDIO();
// Initialize the global critical section
critical_section_init( &g_bspGlobalCritSec_ );
// Configure the LEDs as output pins
gpio_init( OPTION_BSP_DEBUG_LED1_INDEX );
gpio_set_dir( OPTION_BSP_DEBUG_LED1_INDEX, GPIO_OUT );
}
////////////////////////////////////////////////////
/*
** Method stubs to satisfy the linker -->NOTE: C++ Streams are NOT supported by this BSP
*/
//void std::ios_base::Init::_S_ios_destroy()
//{
//}
//
//void std::ios_base::Init::_S_ios_create( bool )
//{
//}
std::ios_base::Init::Init()
{
}
std::ios_base::Init::~Init()
{
}
//void *operator new(size_t size, std::nothrow_t const&){
// return malloc( size );
//}
//
//void *operator new[]( size_t size, std::nothrow_t const& ) {
// return malloc( size );
//}
//
//const std::nothrow_t std::nothrow; | 411 | 0.772403 | 1 | 0.772403 | game-dev | MEDIA | 0.12419 | game-dev | 0.542965 | 1 | 0.542965 |
wuhaoyu1990/KingdomRush | 5,852 | Classes/Scene/GameView.cpp | #include "GameView.h"
#include "TransitionGame.h"
#include "WelcomeScene.h"
#include "MapFlag.h"
#include "Road.h"
#include "GameViewMenu.h"
#include "GameManager.h"
#include "RespirationSprite.h"
#include "SoundManager.h"
USING_NS_CC;
Scene* GameView::createScene()
{
auto scene = Scene::create();
auto layer = GameView::create();
auto menuLayer = GameViewMenu::create();
scene->addChild(layer);
scene->addChild(menuLayer);
return scene;
}
bool GameView::init()
{
if ( !Layer::init() )
{
return false;
}
instance = GameManager::getInstance();
//в
//UserDefault::getInstance()->setIntegerForKey(instance->LEVELX_DOWNCOUNT,0);
winSize = Director::getInstance()->getWinSize();
bgSprite = Sprite::createWithSpriteFrameName("MapBackground.png");
bgSprite->setAnchorPoint(Vec2::ZERO);
bgSprite->setPosition(Vec2::ZERO);
mapFlagPointVector.push_back(Point(375,775));
mapFlagPointVector.push_back(Point(495,735));
mapFlagPointVector.push_back(Point(510,620));
mapFlagPointVector.push_back(Point(370,575));
mapFlagPointVector.push_back(Point(205,505));
mapFlagPointVector.push_back(Point(455,305));
mapFlagPointVector.push_back(Point(690,420));
mapFlagPointVector.push_back(Point(855,254));
mapFlagPointVector.push_back(Point(1020,340));
mapFlagPointVector.push_back(Point(934,490));
mapFlagPointVector.push_back(Point(830,560));
mapFlagPointVector.push_back(Point(795,710));
mapFlagPointVector.push_back(Point(910,770));
mapFlagPointVector.push_back(Point(1015,770));
addChild(bgSprite);
//ӵ·
addRoad();
//
addMapFlag();
//this->setPosition(Point(0,winSize.height-bgSprite->getContentSize().height));
int newReady = UserDefault::getInstance()->getIntegerForKey(instance->LEVELX_NEWDOWN,0);
Point location = Point();
location.x = winSize.width/2 - mapFlagPointVector.at(newReady).x;
location.y = winSize.height/2 - mapFlagPointVector.at(newReady).y;
auto bgSpriteCurrSize = bgSprite->getBoundingBox().size;
location.x = MIN(location.x,0);
location.x = MAX(location.x, -bgSpriteCurrSize.width + winSize.width);
location.y = MIN(location.y,0);
location.y = MAX(location.y, -bgSpriteCurrSize.height + winSize.height);
this->setPosition(location);
auto listener = EventListenerTouchAllAtOnce::create();
// 2 ¼
listener->onTouchesBegan = CC_CALLBACK_2(GameView::onTouchesBegan, this);// ʼʱ
listener->onTouchesMoved = CC_CALLBACK_2(GameView::onTouchesMoved, this);// ƶʱ
// 3 Ӽ
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, bgSprite);
auto listenerkeyPad = EventListenerKeyboard::create();
listenerkeyPad->onKeyReleased = CC_CALLBACK_2(GameView::onKeyReleased, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listenerkeyPad, this);
SoundManager::playGameTheme1();
return true;
}
void GameView::onEnterTransitionDidFinish()
{
int newReady = UserDefault::getInstance()->getIntegerForKey(instance->LEVELX_NEWDOWN,0);
if(newReady<=12){//13
if(UserDefault::getInstance()->getIntegerForKey(instance->SLOTX_DOWNCOUNT,0)!=newReady){
UserDefault::getInstance()->setIntegerForKey(instance->SLOTX_DOWNCOUNT,newReady);
mapFlagVector.at(newReady-1)->changeType(0);
auto sequence = Sequence::create(
CallFuncN::create(CC_CALLBACK_0(MapFlag::startSuccessAnimation, mapFlagVector.at(newReady-1)))
,CallFuncN::create(CC_CALLBACK_0(Road::buildRoadAnimation, road,newReady-1))
,DelayTime::create(1.5f)
,CallFuncN::create(CC_CALLBACK_0(GameView::addNewMapFlag,this ,newReady))
,NULL);
runAction(sequence);
}
}
}
void GameView::addNewMapFlag(int num)
{
auto mapFlag = MapFlag::createWithLevel(num);
mapFlag->setPosition(mapFlagPointVector.at(num));
addChild(mapFlag);
mapFlagVector.pushBack(mapFlag);
mapFlag->startDropdownAnimation();
}
void GameView::addRoad()
{
road = Road::create();
road->setPosition(Point(635,500));
addChild(road);
}
void GameView::onTouchesMoved(const std::vector<Touch*>& touches, Event *event)
{
if(touches.size() == 1) // ƶ
{
// ʱtouchesֻһTouchͨtouches[0]ͿԵõ
auto touch = touches[0];
// 㻬еĻ
auto diff = touch->getDelta();
// õǰbgSpriteλ
auto currentPos = this->getPosition();
// õbgSpriteӦڵλ
auto pos = currentPos + diff;
// õ˿bgSpriteijߴ
auto bgSpriteCurrSize = bgSprite->getBoundingBox().size;
//߽ƣԼposλ
pos.x = MIN(pos.x, bgSpriteCurrSize.width * bgSprite->getAnchorPoint().x);
pos.x = MAX(pos.x, -bgSpriteCurrSize.width + winSize.width + bgSpriteCurrSize.width * bgSprite->getAnchorPoint().x);
pos.y = MIN(pos.y, bgSpriteCurrSize.height * bgSprite->getAnchorPoint().y);
pos.y = MAX(pos.y, -bgSpriteCurrSize.height + winSize.height + bgSpriteCurrSize.height * bgSprite->getAnchorPoint().y);
this->setPosition(pos);
}
}
void GameView::onTouchesBegan(const std::vector<Touch*>& touches, Event *event)
{
}
void GameView::onKeyReleased(EventKeyboard::KeyCode keycode, Event* event)
{
if(keycode==EventKeyboard::KeyCode::KEY_BACK)
{
auto scene = WelcomeScene::createScene();
Director::getInstance()->replaceScene(TransitionGame::create(2.0f,scene));
}
}
void GameView::addMapFlag()
{
int count = UserDefault::getInstance()->getIntegerForKey(instance->SLOTX_DOWNCOUNT,0);
for(int i=0;i<= count;i++)
{
auto mapFlag = MapFlag::createWithLevel(i);
mapFlag->setPosition(mapFlagPointVector.at(i));
mapFlagVector.pushBack(mapFlag);
if(i == count)
{
mapFlag->setStarClose();
}
addChild(mapFlag);
}
if(UserDefault::getInstance()->getIntegerForKey(instance->LEVELX_NEWDOWN,0)==0){
auto respirationSprite = RespirationSprite::createRespirationSprite("mapBalloon_starthere.png");
respirationSprite->setPosition(Point(375,855));
addChild(respirationSprite);
}
} | 411 | 0.790602 | 1 | 0.790602 | game-dev | MEDIA | 0.780092 | game-dev | 0.779552 | 1 | 0.779552 |
vmbatlle/super-mario-kart | 6,853 | src/audio/audio.h | #pragma once
#include <SFML/Audio.hpp>
#include <mutex>
#include "entities/enums.h"
// all music annotations are based on this video:
// https://www.youtube.com/watch?v=AlAmXXNz5ac
enum class Music : int {
MENU_TITLE_SCREEN, // mario kart main menu
MENU_PLAYER_CIRCUIT, // player & circuit/gp selection
CIRCUIT_ANIMATION_START, // race start jingle (before semaphore)
CIRCUIT_NORMAL, // circuit's theme for laps 1-4
CIRCUIT_LAST_LAP, // circuit's theme for lap 5
CONGRATULATIONS_SCREEN, // you won the grand prix
CIRCUIT_PLAYER_WIN, // you won the race
CIRCUIT_PLAYER_LOSE, // you lose the grand prix
__COUNT,
};
enum class SFX : int {
MENU_INTRO_SCREEN_DING, // nintendo "ding"
MENU_SELECTION_ACCEPT, // title screen (all presses) and player/circuit
// (only 'select'/'confirm' actions)
MENU_SELECTION_CANCEL, // title screen (back) and player/circuit
MENU_SELECTION_MOVE, // player/circuit (cursor move)
CIRCUIT_LAKITU_SEMAPHORE, // 3-2-1 semaphore
CIRCUIT_LAKITU_WARNING, // player going backwards
CIRCUIT_COLLISION, // player hits an object
CIRCUIT_COLLISION_PIPE, // player hits a pipe
CIRCUIT_PASS_MOTOR, // played when a player passes you (doppler?)
CIRCUIT_OVERTAKE_UP, // played when you overtake a player (ui update)
CIRCUIT_OVERTAKE_DOWN, // played when a player overtakes you (ui update)
CIRCUIT_LAST_LAP_NOTICE,
CIRCUIT_GOAL_END, // finished all 5 laps
CIRCUIT_END_VICTORY, // finished lap 5, small driver animation & standings
CIRCUIT_END_DEFEAT, // finished lap 5 ( but in bad position :-( )
// ----------------
CIRCUIT_PLAYER_MOTOR, // your background motor noise (depends on speed)
CIRCUIT_PLAYER_MOTOR_SPOOK, // special motor noise for ghost valley
CIRCUIT_PLAYER_BRAKE, // player hit brake
CIRCUIT_PLAYER_DRIFT, // drift noise
CIRCUIT_PLAYER_DRIFT_SPOOK, // special drift noise for ghost valley
CIRCUIT_MATERIAL_GRASS, // moving over grass terrain
CIRCUIT_MATERIAL_WOOD, // moving over wood terrain (normal)
CIRCUIT_MATERIAL_SPOOK, // moving over wood terrain (ghost valley)
// ----------------
CIRCUIT_PLAYER_JUMP, // noise before drifting/using jump pad
CIRCUIT_PLAYER_LANDING, // noise after drifting/using jump pad
CIRCUIT_PLAYER_FALL, // falling to empty
CIRCUIT_PLAYER_FALL_WATER, // falling to water
CIRCUIT_PLAYER_FALL_LAVA, // falling to lava
CIRCUIT_PLAYER_HIT, // banana hit
CIRCUIT_PLAYER_SMASH, // thwomp smash
CIRCUIT_PLAYER_GROW, // change size to normal
CIRCUIT_PLAYER_SHRINK, // change size to small
CIRCUIT_COIN, // floor coin get
// OR player hits you and you lose a coin
// ----------------
CIRCUIT_ITEM_RANDOMIZING, // jingle while your object is randomized
CIRCUIT_ITEM_GET, // ding ding ding after pressing a question panel
CIRCUIT_ITEM_USE_LAUNCH, // use item and launch it forward (ex. banana)
CIRCUIT_ITEM_USE_UP, // use item forward (don't launch, ex. shell)
CIRCUIT_ITEM_USE_DOWN, // use item and launch it behind you
CIRCUIT_ITEM_COIN, // use coin item
CIRCUIT_ITEM_STAR, // use star item
CIRCUIT_ITEM_MUSHROOM, // use mushroom item
CIRCUIT_ITEM_THUNDER, // use thunder item
CIRCUIT_ITEM_RED_SHELL,
// ------------
RESULTS_POINTS_UPDATE, // leaderboard point update animation
__COUNT,
};
class Audio {
private:
static constexpr const float VOLUME_MULTIPLIER = 0.8f;
static constexpr const float VOLUME_LOG_EXP = 1.0f; // max true volume val.
std::array<sf::Music, (int)Music::__COUNT> musicList;
std::array<sf::SoundBuffer, (int)SFX::__COUNT> sfxList;
std::array<int, (int)SFX::__COUNT> sfxLastIndex = {-1};
std::array<sf::Music, (int)MenuPlayer::__COUNT> sfxEngines;
unsigned int playerIndex = 0;
bool raceMode = false;
bool enginesPlaying = false;
std::mutex musicMutex, sfxMutex;
static const int MAX_SOUNDS = 32;
std::array<sf::Sound, MAX_SOUNDS> playingSounds;
int currentSoundIndex = 0;
int lastDurableSFXIndex = 0;
static Audio instance;
float musicVolumePct, sfxVolumePct;
float getMusicValue, getSFXValue;
Audio() {
musicVolumePct = logFunc(0.5f) * 100.0;
sfxVolumePct = logFunc(0.5f) * 100.0;
getMusicValue = 0.5f;
getSFXValue = 0.5f;
}
static SFX loadDing(); // small sound before everything starts loading :-)
static void loadAll(); // load rest of the assets meanwhile
static float logFunc(const float value);
void load(const Music music, const std::string &filename);
void load(const SFX sfx, const std::string &filename);
friend class StateInitLoad;
public:
static void loadCircuit(const std::string &folder);
static void play(const Music music, bool loop = true);
static void play(const SFX sfx, bool loop = false);
static bool isPlaying(const SFX sfx);
// fades out in 2s (aprox) by default
static void fadeOut(const Music music, const sf::Time &deltaTime,
const sf::Time &time = sf::seconds(2.0f));
static void pauseMusic();
static void pauseSFX();
static void resumeMusic();
static void resumeSFX();
static void stopSFX();
static void stop(const SFX sfx);
static void stopMusic();
// set volume as percent 0-1
static void setVolume(const float musicVolumePct, const float sfxVolumePct);
static float getMusicVolume() {
// return instance.musicVolumePct / (100.0f * VOLUME_MULTIPLIER);
return instance.getMusicValue;
}
static float getSfxVolume() {
// instance.sfxVolumePct / (100.0f * VOLUME_MULTIPLIER);
return instance.getSFXValue;
}
static void setPitch(const SFX sfx, const float sfxPitch);
static void playEngines(unsigned int playerIndex, bool raceMode = true);
static void playEngines(bool playerOnly = false);
static void setEngineVolume(unsigned int i, float volume = 100.0f);
static void setEnginesVolume(float volume = 100.0f);
static void updateEngine(unsigned int i, sf::Vector2f position,
float height, float speedForward, float speedTurn);
static void updateEngine(sf::Vector2f position, float height,
float speedForward, float speedTurn);
static void updateListener(sf::Vector2f position, float angle,
float height);
static void pauseEngines();
static void resumeEngines();
static void stopEngines();
}; | 411 | 0.736463 | 1 | 0.736463 | game-dev | MEDIA | 0.891575 | game-dev | 0.970682 | 1 | 0.970682 |
LekKit/ScalarEvolution | 5,250 | src/main/java/lekkit/scev/inventory/InventoryItem.java | package lekkit.scev.inventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.util.Constants;
public class InventoryItem implements IInventory {
private final ItemStack item_stack;
private final int inv_size;
private ItemStack[] inventory;
public InventoryItem(ItemStack stack, int size) {
item_stack = stack;
inv_size = size;
inventory = new ItemStack[inv_size];
if (!item_stack.hasTagCompound()) {
item_stack.setTagCompound(new NBTTagCompound());
}
readFromNBT(item_stack.getTagCompound());
}
public ItemStack getInventoryItemStack() {
return item_stack;
}
@Override
public int getSizeInventory() {
return inventory.length;
}
@Override
public ItemStack getStackInSlot(int slot) {
if (slot < inv_size) {
return inventory[slot];
}
return null;
}
@Override
public ItemStack decrStackSize(int slot, int amount) {
ItemStack stack = getStackInSlot(slot);
if (stack != null) {
if (stack.stackSize > amount) {
stack = stack.splitStack(amount);
// Don't forget this line or your inventory will not be saved!
markDirty();
} else {
// this method also calls onInventoryChanged, so we don't need to call it again
setInventorySlotContents(slot, null);
}
}
return stack;
}
@Override
public ItemStack getStackInSlotOnClosing(int slot) {
ItemStack stack = getStackInSlot(slot);
setInventorySlotContents(slot, null);
return stack;
}
@Override
public void setInventorySlotContents(int slot, ItemStack stack) {
inventory[slot] = stack;
if (stack != null && stack.stackSize > getInventoryStackLimit()) {
stack.stackSize = getInventoryStackLimit();
}
// Don't forget this line or your inventory will not be saved!
markDirty();
}
@Override
public String getInventoryName() {
return "";
}
@Override
public boolean hasCustomInventoryName() {
return false;
}
@Override
public int getInventoryStackLimit() {
return 1;
}
/**
* This is the method that will handle saving the inventory contents, as it is called (or should be called!)
* anytime the inventory changes. Perfect. Much better than using onUpdate in an Item, as this will also
* let you change things in your inventory without ever opening a Gui, if you want.
*/
@Override
public void markDirty() {
for (int i = 0; i < getSizeInventory(); ++i) {
if (getStackInSlot(i) != null && getStackInSlot(i).stackSize == 0) {
inventory[i] = null;
}
}
// This line here does the work:
writeToNBT(item_stack.getTagCompound());
}
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer) {
return entityplayer.getHeldItem() == item_stack;
}
@Override
public void openInventory() {}
@Override
public void closeInventory() {}
@Override
public boolean isItemValidForSlot(int slot, ItemStack itemstack) {
// Don't want to be able to store the inventory item within itself
// Bad things will happen, like losing your inventory
// Actually, this needs a custom Slot to work
return itemstack.getItem() != item_stack.getItem();
}
public void readFromNBT(NBTTagCompound compound) {
NBTTagList items = compound.getTagList("Items", Constants.NBT.TAG_COMPOUND);
inventory = new ItemStack[inv_size];
for (int i = 0; i < items.tagCount(); ++i) {
NBTTagCompound item = (NBTTagCompound) items.getCompoundTagAt(i);
int slot = item.getInteger("Slot");
// Just double-checking that the saved slot index is within our inventory array bounds
if (slot >= 0 && slot < inv_size) {
inventory[slot] = ItemStack.loadItemStackFromNBT(item);
}
}
}
public void writeToNBT(NBTTagCompound tagcompound) {
// Create a new NBT Tag List to store itemstacks as NBT Tags
NBTTagList items = new NBTTagList();
for (int i = 0; i < inv_size; ++i) {
// Only write stacks that contain items
if (getStackInSlot(i) != null) {
// Make a new NBT Tag Compound to write the itemstack and slot index to
NBTTagCompound item = new NBTTagCompound();
item.setInteger("Slot", i);
// Writes the itemstack in slot(i) to the Tag Compound we just made
getStackInSlot(i).writeToNBT(item);
// add the tag compound to our tag list
items.appendTag(item);
}
}
// Add the TagList to the ItemStack's Tag Compound with the name "Items"
tagcompound.setTag("Items", items);
}
}
| 411 | 0.921946 | 1 | 0.921946 | game-dev | MEDIA | 0.996416 | game-dev | 0.918927 | 1 | 0.918927 |
prolog/shadow-of-the-wyrm | 2,125 | engine/calculators/source/IntimidationCalculator.cpp | #include "IntimidationCalculator.hpp"
#include "CurrentCreatureAbilities.hpp"
#include "RaceManager.hpp"
const int IntimidationCalculator::MAX_PCT_CHANCE_INTIMIDATION = 85;
const int IntimidationCalculator::INTIMIDATION_DIVISOR = 3;
const int IntimidationCalculator::CHARISMA_DIVISOR = 4;
const int IntimidationCalculator::LEVEL_DIVISOR = 2;
int IntimidationCalculator::calculate_pct_chance_intimidated(CreaturePtr attacking_creature, CreaturePtr attacked_creature)
{
int pct_chance = 0;
CurrentCreatureAbilities cca;
if (attacking_creature != nullptr && attacked_creature != nullptr && cca.can_act(attacked_creature))
{
RaceManager rm;
Race* race = rm.get_race(attacked_creature->get_race_id());
if (race != nullptr && race->get_mindless())
{
return 0;
}
bool attacking_raging = attacking_creature->has_status(StatusIdentifiers::STATUS_ID_RAGE);
if (attacking_raging)
{
return 0;
}
int attack_intim = attacking_creature->get_skills().get_value(SkillType::SKILL_GENERAL_INTIMIDATION);
int attack_cha = attacking_creature->get_charisma().get_current();
int attack_level = attacking_creature->get_level().get_current();
int attacked_intim = attacked_creature->get_skills().get_value(SkillType::SKILL_GENERAL_INTIMIDATION);
int attacked_cha = attacked_creature->get_charisma().get_current();
int attacked_level = attacked_creature->get_level().get_current();
// Check to see if the attacked creature has intimidation - this can cause
// the attacker to pull back in fear.
if (attacked_intim > 0)
{
int attack = (attack_intim / INTIMIDATION_DIVISOR) + (attack_cha / CHARISMA_DIVISOR) + (attack_level / LEVEL_DIVISOR);
int attacked = (attacked_intim / INTIMIDATION_DIVISOR) + (attacked_cha / CHARISMA_DIVISOR) + (attacked_level / LEVEL_DIVISOR);
pct_chance = attacked - attack;
pct_chance = std::max(0, pct_chance);
pct_chance = std::min(MAX_PCT_CHANCE_INTIMIDATION, pct_chance);
}
}
return pct_chance;
}
#ifdef UNIT_TESTS
#include "unit_tests/IntimidationCalculator_test.cpp"
#endif
| 411 | 0.870529 | 1 | 0.870529 | game-dev | MEDIA | 0.978184 | game-dev | 0.674074 | 1 | 0.674074 |
WispSnow/SDLShooter | 1,923 | src/Game.h | #ifndef GAME_H
#define GAME_H
#include "Scene.h"
#include "Object.h"
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <string>
#include <map>
class Game
{
public:
static Game& getInstance(){
static Game instance;
return instance;
}
~Game();
void run();
void init();
void clean();
void changeScene(Scene* scene);
void handleEvent(SDL_Event *event);
void update(float deltaTime);
void render();
// 渲染文字函数
SDL_Point renderTextCentered(std::string text, float posY, bool isTitle);
void renderTextPos(std::string text, int posX, int posY, bool isLeft = true);
// setters
void setFinalScore(int score) { finalScore = score; }
void insertLeaderBoard(int score, std::string name); // 插入排行榜
// getters
SDL_Window* getWindow() { return window; }
SDL_Renderer* getRenderer() { return renderer; }
int getWindowWidth() { return windowWidth; }
int getWindowHeight() { return windowHeight; }
int getFinalScore() { return finalScore; }
std::multimap<int, std::string, std::greater<int>>& getLeaderBoard() { return leaderBoard;} // 返回leaderBoard的引用
private:
Game();
// 删除拷贝与赋值构造函数
Game(const Game&) = delete;
Game& operator=(const Game&) = delete;
TTF_Font* titleFont;
TTF_Font* textFont;
bool isRunning = true;
bool isFullscreen = false;
Scene* currentScene = nullptr;
SDL_Window* window = nullptr;
SDL_Renderer* renderer = nullptr;
int windowWidth = 600;
int windowHeight = 800;
int FPS = 60;
Uint32 frameTime;
float deltaTime;
int finalScore = 0;
Background nearStars;
Background farStars;
std::multimap<int, std::string, std::greater<int>> leaderBoard; // 使用multimap来存储分数和名字,分数作为键,名字作为值
void backgroundUpdate(float deltaTime);
void renderBackground();
void saveData();
void loadData();
};
#endif
| 411 | 0.672588 | 1 | 0.672588 | game-dev | MEDIA | 0.50678 | game-dev,graphics-rendering | 0.514839 | 1 | 0.514839 |
ejoy/vaststars | 6,130 | startup/pkg/vaststars.gameplay/interface/assembling.lua | local prototype = require "prototype"
local query = require "prototype".queryById
local iFluidbox = require "interface.fluidbox"
local iBuilding = require "interface.building"
local iChest = require "interface.chest"
local cChest = require "vaststars.chest.core"
local STATUS_IDLE <const> = 0
local STATUS_DONE <const> = 1
local function isFluidId(id)
local pt = query(id)
for _, t in ipairs(pt.type) do
if t == "fluid" then
return true
end
end
return false
end
local function findFluidbox(init, id)
local name = query(id).name
for i, v in ipairs(init) do
if name == v then
return i
end
end
return 0
end
local function createFluidBox(init, recipe, fluidboxes, items)
local input_fluids = {}
local output_fluids = {}
local ingredients_n <const> = #recipe.ingredients//4 - 1
local results_n <const> = #recipe.results//4 - 1
assert(ingredients_n <= 16 and results_n <= 16)
for idx = 1, ingredients_n + results_n do
local s = items[idx]
if s.type == "none" then
local fluid_idx = findFluidbox(init.input, s.item)
if fluid_idx ~= 0 then
if fluid_idx > 4 then
error "The assembling does not support this recipe."
end
input_fluids[fluid_idx] = idx
fluidboxes["in"..fluid_idx.."_limit"] = s.limit
end
end
end
for idx = 1, results_n do
local s = items[ingredients_n + idx]
if s.type == "none" then
local fluid_idx = findFluidbox(init.output, s.item)
if fluid_idx ~= 0 then
if fluid_idx > 3 then
error "The assembling does not support this recipe."
end
output_fluids[fluid_idx] = ingredients_n + idx
fluidboxes["out"..fluid_idx.."_limit"] = s.limit
end
end
end
local fluidbox_in = 0
local fluidbox_out = 0
for i = 4, 1, -1 do
fluidbox_in = (fluidbox_in << 4) | (input_fluids[i] or 0)
end
for i = 3, 1, -1 do
fluidbox_out = (fluidbox_out << 4) | (output_fluids[i] or 0)
end
return fluidbox_in, fluidbox_out
end
local InvalidChest <const> = 0
local function chest_destroy(world, chest, recycle)
return cChest.destroy(world._cworld, chest.chest, recycle)
end
local function assembling_reset(world, e)
local chest = e.chest
local olditems = {}
if chest.chest ~= InvalidChest then
for i = 1, 256 do
local slot = cChest.get(world._cworld, chest.chest, i)
if not slot then
break
end
if slot.type ~= "none" then
assert(not olditems[slot.item])
olditems[i] = slot
end
end
chest_destroy(world, chest, true)
chest.chest = InvalidChest
iBuilding.dirty(world, "chest")
end
end
local function assembling_reset_items(world, recipe, chest, option, maxslot)
local ingredients_n <const> = #recipe.ingredients//4 - 1
local results_n <const> = #recipe.results//4 - 1
local olditems = {}
local newitems = {}
if chest.chest ~= InvalidChest then
for i = 1, 256 do
local slot = cChest.get(world._cworld, chest.chest, i)
if not slot then
break
end
olditems[slot.item] = (olditems[slot.item] or 0) + slot.amount
end
end
local function create_slot(type, id, limit)
local amount = 0
if olditems[id] then
amount = olditems[id]
olditems[id] = nil
end
newitems[#newitems+1] = {
type = type,
item = id,
limit = limit,
amount = amount,
}
end
for idx = 1, ingredients_n do
local id, n = string.unpack("<I2I2", recipe.ingredients, 4*idx+1)
create_slot(isFluidId(id) and "none" or "demand", id, n * option.ingredientsLimit)
end
for idx = 1, results_n do
local id, n = string.unpack("<I2I2", recipe.results, 4*idx+1)
create_slot(isFluidId(id) and "none" or "supply", id, n * option.resultsLimit)
end
for item, amount in pairs(olditems) do
if amount > 0 then
create_slot("supply", item, amount)
end
if #newitems >= maxslot then
break
end
end
return newitems
end
local function assembling_set(world, e, recipe, option, maxslot)
local chest = e.chest
option = option or {
ingredientsLimit = 2,
resultsLimit = 2,
}
local items = assembling_reset_items(world, recipe, chest, option, maxslot)
if chest.chest ~= InvalidChest then
chest_destroy(world, chest, false)
end
chest.chest = iChest.create(world, items)
iBuilding.dirty(world, "chest")
return items
end
local function del_recipe(world, e)
local assembling = e.assembling
assembling.progress = 0
assembling.status = STATUS_IDLE
assembling.recipe = 0
assembling.fluidbox_in = 0
assembling.fluidbox_out = 0
assembling_reset(world, e)
end
local function set_recipe(world, e, pt, recipe_name, fluids, option)
iFluidbox.update_fluidboxes(world, e, pt, fluids)
if recipe_name == nil then
del_recipe(world, e)
return
end
local assembling = e.assembling
local recipe = assert(prototype.queryByName(recipe_name), "unknown recipe: "..recipe_name)
if assembling.recipe == recipe.id then
return
end
assembling.recipe = recipe.id
assembling.progress = 0
assembling.status = STATUS_IDLE
local items = assembling_set(world, e, recipe, option, pt.maxslot)
if fluids and pt.fluidboxes then
local fluidbox_in, fluidbox_out = createFluidBox(fluids, recipe, e.fluidboxes, items)
assembling.fluidbox_in = fluidbox_in
assembling.fluidbox_out = fluidbox_out
else
assembling.fluidbox_in = 0
assembling.fluidbox_out = 0
end
end
return {
set_recipe = set_recipe,
}
| 411 | 0.665221 | 1 | 0.665221 | game-dev | MEDIA | 0.911138 | game-dev | 0.86087 | 1 | 0.86087 |
alexkulya/pandaria_5.4.8 | 120,390 | src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp | /*
* This file is part of the Pandaria 5.4.8 Project. See THANKS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "SpellScript.h"
#include "ulduar.h"
#include "Unit.h"
#include "Vehicle.h"
#include "PassiveAI.h"
#include <limits>
#include <map>
#include "ace/Mutex.h"
enum Yells
{
// Mimiron
SAY_AGGRO = 0,
SAY_HARDMODE_ON = 1,
SAY_MKII_ACTIVATE = 2,
SAY_MKII_SLAY = 3,
SAY_MKII_DEATH = 4,
SAY_VX001_ACTIVATE = 5,
SAY_VX001_SLAY = 6,
SAY_VX001_DEATH = 7,
SAY_AERIAL_ACTIVATE = 8,
SAY_AERIAL_SLAY = 9,
SAY_AERIAL_DEATH = 10,
SAY_V07TRON_ACTIVATE = 11,
SAY_V07TRON_SLAY = 12,
SAY_V07TRON_DEATH = 13,
SAY_BERSERK = 14,
// Leviathan MK II
EMOTE_PLASMA_BLAST = 0,
// Computer
SAY_SELF_DESTRUCT_START = 0,
SAY_SELF_DESTRUCT_6 = 1,
SAY_SELF_DESTRUCT_5 = 2,
SAY_SELF_DESTRUCT_4 = 3,
SAY_SELF_DESTRUCT_3 = 4,
SAY_SELF_DESTRUCT_2 = 5,
SAY_SELF_DESTRUCT_1 = 6,
SAY_SELF_DESTRUCT_0 = 7,
SAY_SELF_DESTRUCT_7 = 8,
SAY_SELF_DESTRUCT_8 = 9,
SAY_SELF_DESTRUCT_9 = 10,
SAY_SELF_DESTRUCT_10 = 11,
SAY_SELF_DESTRUCT_END = 12,
};
enum Spells
{
SPELL_JETPACK = 63341, // Unused
SPELL_EMERGENCY_MODE = 64582,
SPELL_SELF_REPAIR = 64383,
// Leviathan MK II
SPELL_MINES_SPAWN = 65347,
SPELL_FLAME_SUPPRESSANT_MK = 64570,
SPELL_NAPALM_SHELL = 63666,
SPELL_PLASMA_BLAST = 62997,
SPELL_PROXIMITY_MINES = 63027,
SPELL_SHOCK_BLAST = 63631,
SPELL_EXPLOSION = 66351,
SPELL_EXPLOSION_25 = 63009,
SPELL_DEATH_GRIP = 49560, // used at MK turret's immunity
// VX 001
SPELL_FROSTBOMB = 64623, // 64627 ?
SPELL_FROST_BOMB_VISUAL = 64624,
SPELL_FROST_BOMB_EXPLOSION_10 = 64626,
SPELL_FROST_BOMB_EXPLOSION_25 = 65333,
SPELL_P3WX2_LASER_BARRAGE = 63293, // Cast through SPELL_SPINNING_UP
SPELL_P3WX2_LASER_BARRAGE_LEVIATHAN = 66490, // Root aura on Leviathan Mk II
SPELL_RAPID_BURST = 63382,
SPELL_RAPID_BURST_LEFT_10 = 63387,
SPELL_RAPID_BURST_RIGHT_10 = 64019,
SPELL_RAPID_BURST_LEFT_25 = 64531,
SPELL_RAPID_BURST_RIGHT_25 = 64532,
SPELL_ROCKET_STRIKE = 63036,
SPELL_ROCKET_STRIKE_AURA = 64064,
SPELL_ROCKET_STRIKE_DMG = 63041,
SPELL_SPINNING_UP = 63414,
SPELL_HEAT_WAVE = 63677,
SPELL_HAND_PULSE = 64348,
SPELL_SELF_STUN = 14821,
SPELL_BOMB_BOT = 63811,
SPELL_SUMMON_SCRAP_BOT_JUNK_BOT = 63819,
SPELL_SUMMON_SCRAP_BOT_TRIGGER_JUNK_BOT = 63820,
SPELL_SUMMON_SCRAP_BOT_AURA_JUNK_BOT = 64398,
SPELL_SUMMON_SCRAP_BOT_TRIGGER_ASSAULT_BOT = 64425,
SPELL_SUMMON_SCRAP_BOT_AURA_ASSAULT_BOT = 64426,
SPELL_SUMMON_SCRAP_BOT_ASSAULT_BOT = 64427,
SPELL_SUMMON_FIRE_BOT_TRIGGER = 64620,
SPELL_SUMMON_FIRE_BOT_AURA = 64621,
SPELL_SUMMON_FIRE_BOT = 64622,
// Aerial Command Unit
SPELL_PLASMA_BALL = 63689,
SPELL_MAGNETIC_CORE = 64436,
SPELL_MAGNETIC_CORE_VISUAL = 64438,
SPELL_BOOM_BOT = 63767,
SPELL_BOOM_BOT_PERIODIC = 63801,
SPELL_MAGNETIC_FIELD = 64668,
SPELL_HOVER = 57764, // Set Hover position
SPELL_BERSERK = 47008,
// Additonal spells
SPELL_DEAFENING_SIREN = 64616,
SPELL_SELF_DESTRUCTION = 64610,
SPELL_SELF_DESTRUCTION_VISUAL = 64613,
SPELL_FLAME_SUPPRESSANT_VX001 = 65192,
SPELL_SUMMON_FLAMES_INITIAL = 64563,
SPELL_FLAME = 64561,
SPELL_NOT_SO_FRIENDLY_FIRE = 65040,
SPELL_WATER_SPRAY = 64619,
SPELL_RIDE_VEHICLE = 46598,
};
enum Events
{
// Mimiron
EVENT_CHECK_TARGET = 1,
EVENT_ENRAGE = 2,
EVENT_FLAME = 3,
EVENT_STEP_1 = 4,
EVENT_STEP_2 = 5,
EVENT_STEP_3 = 6,
EVENT_STEP_4 = 7,
EVENT_STEP_5 = 8,
EVENT_STEP_6 = 9,
EVENT_STEP_7 = 10,
EVENT_STEP_8 = 11,
EVENT_STEP_9 = 12,
EVENT_CHECK_BOTALIVE = 13,
// Leviathan MK II
EVENT_PROXIMITY_MINE = 14,
EVENT_NAPALM_SHELL = 15,
EVENT_PLASMA_BLAST = 16,
EVENT_SHOCK_BLAST = 17,
EVENT_FLAME_SUPPRESSANT = 18,
// VX-001
EVENT_RAPID_BURST = 19,
EVENT_LASER_BARRAGE = 20,
EVENT_LASER_BARRAGE_END = 21,
EVENT_ROCKET_STRIKE = 22,
EVENT_HEAT_WAVE = 23,
EVENT_HAND_PULSE = 24,
EVENT_FROST_BOMB = 25,
EVENT_FLAME_SUPPRESSANT_VX001 = 26,
// Aerial unit
EVENT_PLASMA_BALL = 27,
EVENT_REACTIVATE_AERIAL = 28,
EVENT_SUMMON_JUNK_BOT = 29,
EVENT_SUMMON_ASSAULT_BOT = 30,
EVENT_SUMMON_BOOM_BOT = 31,
EVENT_SUMMON_FIRE_BOT = 32,
// Computer
EVENT_SELF_DESTRUCT_MIMIRON_YELL,
EVENT_SELF_DESTRUCT_10,
EVENT_SELF_DESTRUCT_9,
EVENT_SELF_DESTRUCT_8,
EVENT_SELF_DESTRUCT_7,
EVENT_SELF_DESTRUCT_6,
EVENT_SELF_DESTRUCT_5,
EVENT_SELF_DESTRUCT_4,
EVENT_SELF_DESTRUCT_3,
EVENT_SELF_DESTRUCT_2,
EVENT_SELF_DESTRUCT_1,
};
enum Phases
{
// Mimiron
PHASE_IDLE = 0,
PHASE_INTRO = 1,
PHASE_COMBAT = 2,
PHASE_VX001_ACTIVATION = 3,
PHASE_AERIAL_ACTIVATION = 4,
PHASE_V0L7R0N_ACTIVATION = 5,
// Leviathan MK II
PHASE_LEVIATHAN_SOLO__GLOBAL_1 = 6,
PHASE_LEVIATHAN_ASSEMBLED__GLOBAL_4 = 7,
// VX-001
PHASE_VX001_SOLO__GLOBAL_2 = 8,
PHASE_VX001_ASSEMBLED__GLOBAL_4 = 9,
// Aerial unit
PHASE_AERIAL_SOLO__GLOBAL_3 = 10,
PHASE_AERIAL_ASSEMBLED__GLOBAL_4 = 11,
};
enum Actions
{
DO_START_ENCOUNTER = 1,
DO_ACTIVATE_VX001 = 2,
DO_START_VX001 = 3,
DO_ACTIVATE_AERIAL = 4,
DO_START_AERIAL = 5,
DO_DISABLE_AERIAL = 6,
DO_ACTIVATE_V0L7R0N = 7,
DO_LEVIATHAN_ASSEMBLED = 8,
DO_LEVIATHAN_SELF_REPAIR_START = 9,
DO_LEVIATHAN_SELF_REPAIR_END = 10,
DO_VX001_ASSEMBLED = 11,
DO_VX001_SELF_REPAIR_START = 12,
DO_VX001_SELF_REPAIR_END = 13,
DO_AERIAL_ASSEMBLED = 14,
DO_AERIAL_SELF_REPAIR_START = 15,
DO_AERIAL_SELF_REPAIR_END = 16,
DO_ENTER_ENRAGE = 17,
DO_ACTIVATE_HARD_MODE = 18,
DO_INCREASE_FLAME_COUNT = 19,
DO_DECREASE_FLAME_COUNT = 20,
DATA_GET_HARD_MODE = 21,
DATA_FLAME_COUNT = 22
};
enum Npcs
{
NPC_COMPUTER = 34143,
NPC_ROCKET = 34050,
NPC_BURST_TARGET = 34211,
NPC_JUNK_BOT = 33855,
NPC_ASSAULT_BOT = 34057,
NPC_BOMB_BOT = 33836,
NPC_FIRE_BOT = 34147,
NPC_FLAMES_INITIAL = 34363,
NPC_FLAME_SPREAD = 34121,
NPC_FROST_BOMB = 34149,
NPC_MKII_TURRET = 34071,
NPC_PROXIMITY_MINE = 34362,
NPC_MIMIRON_FOCUS = 33835
};
// Achievements
#define ACHIEVEMENT_SET_UP_US_THE_BOMB RAID_MODE(2989, 3237)
// TODO:
// Achiev 2989: Criterias 10543, 10544, 10545
// Achiev 3237: Criterias 10546, 10547, 10548
// Which criteria is reponsible for which step ?
// 26491 - 38080 - 45033 <- what do these numbers mean ?
enum BombIndices // Scripts are present, but criteria-id <-> script is missing
{
DATA_AVOIDED_PROXIMITY_MINES = 30,
DATA_AVOIDED_ROCKET_STRIKES,
DATA_AVOIDED_BOOM_BOT_EXPLOSION
};
Position const turretPos = {2744.64f, 2569.459f, 364.397f, 0.0f};
#define FLAME_CAP 200 // find a good (blizzlike!) value
struct EqualHelper // Helper for Mimirons map that stores the members repair states
{
EqualHelper(bool& base) : __base(base) { }
void operator()(std::pair<uint32, bool> value)
{
__base = __base && value.second;
}
private:
bool& __base;
};
class boss_mimiron : public CreatureScript
{
public:
boss_mimiron() : CreatureScript("boss_mimiron") { }
struct boss_mimironAI : public BossAI
{
boss_mimironAI(Creature* creature) : BossAI(creature, BOSS_MIMIRON)
{
me->SetReactState(REACT_PASSIVE);
_gotEncounterFinished = false;
}
void DespawnCreatures(uint32 entry, float distance)
{
std::list<Creature*> creatures;
GetCreatureListWithEntryInGrid(creatures, me, entry, distance);
if (creatures.empty())
return;
for (auto&& creature : creatures)
if (creature)
creature->DespawnOrUnsummon();
}
void Reset() override
{
_gotEncounterFinished = _gotEncounterFinished || (instance && instance->GetBossState(BOSS_MIMIRON) == DONE);
if (_gotEncounterFinished)
return;
_Reset();
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1);
me->SetUInt32Value(UNIT_FIELD_NPC_EMOTESTATE, EMOTE_STATE_USE_STANDING);
me->SetVisible(true);
me->ExitVehicle();
me->GetMotionMaster()->MoveTargetedHome();
instance->SetData(DATA_MIMIRON_ELEVATOR, GO_STATE_ACTIVE);
instance->DoUpdateWorldState(WORLD_STATE_MIMIRON, 0);
_phase = PHASE_IDLE;
events.SetPhase(_phase);
_flameCount = 0;
_gotHardMode = false;
me->GetMap()->SetWorldState(WORLDSTATE_FIRE_FIGHTER, 0);
_enraged = false;
me->GetMap()->SetWorldState(WORLDSTATE_SET_UP_US_BOMB_MINE, 1);
me->GetMap()->SetWorldState(WORLDSTATE_SET_UP_US_BOMB_ROCKET, 1);
me->GetMap()->SetWorldState(WORLDSTATE_SET_UP_US_BOMB_BOT, 1);
events.ScheduleEvent(EVENT_CHECK_TARGET, 7*IN_MILLISECONDS);
DespawnCreatures(NPC_FLAMES_INITIAL, 100.0f);
DespawnCreatures(NPC_PROXIMITY_MINE, 100.0f);
DespawnCreatures(NPC_ROCKET, 100.0f);
DespawnCreatures(NPC_JUNK_BOT, 100.0f);
DespawnCreatures(NPC_ASSAULT_BOT, 100.0f);
DespawnCreatures(NPC_BOMB_BOT, 100.0f);
DespawnCreatures(NPC_FIRE_BOT, 100.0f);
for (uint8 data = DATA_LEVIATHAN_MK_II; data <= DATA_AERIAL_UNIT; ++data)
if (Creature* creature = ObjectAccessor::GetCreature(*me, instance->GetData64(data)))
if (creature->IsAlive())
{
creature->ExitVehicle();
creature->AI()->EnterEvadeMode();
}
if (GameObject* go = me->FindNearestGameObject(GO_BIG_RED_BUTTON, 200))
{
go->SetGoState(GO_STATE_READY);
go->SetLootState(GO_JUST_DEACTIVATED);
go->RemoveFlag(GAMEOBJECT_FIELD_FLAGS, GO_FLAG_NOT_SELECTABLE);
}
_isSelfRepairing[DATA_LEVIATHAN_MK_II] = false;
_isSelfRepairing[DATA_VX_001] = false;
_isSelfRepairing[DATA_AERIAL_UNIT] = false;
_avoidedProximityMines = true;
_avoidedRocketStrikes = true;
_avoidedBoomBotExplosion = true;
}
void BotAliveCheck()
{
if (_phase != PHASE_COMBAT)
return;
_mapMutex.acquire();
bool res = true;
// Check if there is still a false value.
std::for_each(_isSelfRepairing.begin(), _isSelfRepairing.end(), EqualHelper(res));
_mapMutex.release();
if (res)
{
// We're down, baby.
Creature* Leviathan = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_LEVIATHAN_MK_II));
Creature* VX_001 = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_VX_001));
Creature* AerialUnit = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_AERIAL_UNIT));
if (Leviathan && VX_001 && AerialUnit)
{
Leviathan->DisappearAndDie();
VX_001->DisappearAndDie();
AerialUnit->DisappearAndDie();
DespawnCreatures(NPC_FLAMES_INITIAL, 100.0f);
DespawnCreatures(NPC_PROXIMITY_MINE, 100.0f);
DespawnCreatures(NPC_ROCKET, 100);
me->ExitVehicle();
EncounterPostProgress();
}
}
}
void EncounterPostProgress()
{
if (_gotEncounterFinished)
return;
instance->UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, NPC_LEVIATHAN_MKII, nullptr);
me->SetReactState(REACT_PASSIVE);
me->RemoveAllAuras();
me->AttackStop();
me->SetFaction(35);
me->DeleteThreatList();
me->CombatStop(true);
if (_gotHardMode)
{
instance->SetData(DATA_MIMIRON_HARDMODE, true);
ComputerTalk(SAY_SELF_DESTRUCT_END);
me->m_Events.Schedule(11000, [this]() { Talk(SAY_V07TRON_DEATH); });
}
else
Talk(SAY_V07TRON_DEATH);
instance->DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, NPC_LEVIATHAN_MKII, 1);
_JustDied();
me->DespawnOrUnsummon(30*IN_MILLISECONDS);
}
void EnterCombat(Unit* /*who*/) override
{
_gotEncounterFinished = _gotEncounterFinished || (instance && instance->GetBossState(BOSS_MIMIRON) == DONE);
if (_gotEncounterFinished)
return;
_EnterCombat();
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1);
_phase = PHASE_INTRO;
events.SetPhase(_phase);
if (_gotHardMode)
{
events.ScheduleEvent(EVENT_FLAME, 5*IN_MILLISECONDS);
uint32 delay = 5000;
events.ScheduleEvent(EVENT_SELF_DESTRUCT_10, delay);
events.ScheduleEvent(EVENT_SELF_DESTRUCT_MIMIRON_YELL, delay + 1000);
events.ScheduleEvent(EVENT_SELF_DESTRUCT_9, delay + 1*MINUTE*IN_MILLISECONDS);
events.ScheduleEvent(EVENT_SELF_DESTRUCT_8, delay + 2*MINUTE*IN_MILLISECONDS);
events.ScheduleEvent(EVENT_SELF_DESTRUCT_7, delay + 3*MINUTE*IN_MILLISECONDS);
events.ScheduleEvent(EVENT_SELF_DESTRUCT_6, delay + 4*MINUTE*IN_MILLISECONDS);
events.ScheduleEvent(EVENT_SELF_DESTRUCT_5, delay + 5*MINUTE*IN_MILLISECONDS);
events.ScheduleEvent(EVENT_SELF_DESTRUCT_4, delay + 6*MINUTE*IN_MILLISECONDS);
events.ScheduleEvent(EVENT_SELF_DESTRUCT_3, delay + 7*MINUTE*IN_MILLISECONDS);
events.ScheduleEvent(EVENT_SELF_DESTRUCT_2, delay + 8*MINUTE*IN_MILLISECONDS);
events.ScheduleEvent(EVENT_SELF_DESTRUCT_1, delay + 9*MINUTE*IN_MILLISECONDS);
events.ScheduleEvent(EVENT_ENRAGE, delay + 10*MINUTE*IN_MILLISECONDS); // Enrage in 10 (hard mode) min
}
else
events.ScheduleEvent(EVENT_ENRAGE, 15*MINUTE*IN_MILLISECONDS); // Enrage in 15 min
events.ScheduleEvent(EVENT_STEP_1, 0.1*IN_MILLISECONDS, 0, _phase);
if (GameObject* go = me->FindNearestGameObject(GO_BIG_RED_BUTTON, 200.0f))
go->SetFlag(GAMEOBJECT_FIELD_FLAGS, GO_FLAG_NOT_SELECTABLE);
}
void JustDied(Unit* /*killer*/) override
{
EncounterPostProgress();
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_CHECK_TARGET:
// prevent mimiron staying infight with leviathan introduced in rev #b40bf69
// TODO: find out why this happens
if (!SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true))
{
EnterEvadeMode();
return;
}
events.ScheduleEvent(EVENT_CHECK_TARGET, 7*IN_MILLISECONDS);
return;
case EVENT_ENRAGE:
Talk(SAY_BERSERK);
for (uint8 data = DATA_LEVIATHAN_MK_II; data <= DATA_AERIAL_UNIT; ++data)
if (Creature* creature = ObjectAccessor::GetCreature(*me, instance->GetData64(data)))
creature->AI()->DoAction(DO_ENTER_ENRAGE);
_enraged = true;
if (_gotHardMode)
{
ComputerTalk(SAY_SELF_DESTRUCT_0);
DoCast(me, SPELL_SELF_DESTRUCTION, true);
DoCast(me, SPELL_SELF_DESTRUCTION_VISUAL, true);
}
return;
case EVENT_SELF_DESTRUCT_MIMIRON_YELL: Talk(SAY_HARDMODE_ON); break;
case EVENT_SELF_DESTRUCT_10: ComputerTalk(SAY_SELF_DESTRUCT_10); break;
case EVENT_SELF_DESTRUCT_9: ComputerTalk(SAY_SELF_DESTRUCT_9); break;
case EVENT_SELF_DESTRUCT_8: ComputerTalk(SAY_SELF_DESTRUCT_8); break;
case EVENT_SELF_DESTRUCT_7: ComputerTalk(SAY_SELF_DESTRUCT_7); break;
case EVENT_SELF_DESTRUCT_6: ComputerTalk(SAY_SELF_DESTRUCT_6); break;
case EVENT_SELF_DESTRUCT_5: ComputerTalk(SAY_SELF_DESTRUCT_5); break;
case EVENT_SELF_DESTRUCT_4: ComputerTalk(SAY_SELF_DESTRUCT_4); break;
case EVENT_SELF_DESTRUCT_3: ComputerTalk(SAY_SELF_DESTRUCT_3); break;
case EVENT_SELF_DESTRUCT_2: ComputerTalk(SAY_SELF_DESTRUCT_2); break;
case EVENT_SELF_DESTRUCT_1: ComputerTalk(SAY_SELF_DESTRUCT_1); break;
case EVENT_FLAME:
for (uint8 i = 0; i < 3; ++i)
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true))
DoCast(target, SPELL_SUMMON_FLAMES_INITIAL, true);
events.ScheduleEvent(EVENT_FLAME, 30*IN_MILLISECONDS);
return;
case EVENT_STEP_1:
switch (_phase)
{
case PHASE_INTRO:
if (_gotHardMode)
{
ComputerTalk(SAY_SELF_DESTRUCT_START);
events.ScheduleEvent(EVENT_STEP_2, 16*IN_MILLISECONDS, 0, PHASE_INTRO);
}
else
{
Talk(SAY_AGGRO);
events.ScheduleEvent(EVENT_STEP_2, 10*IN_MILLISECONDS, 0, PHASE_INTRO);
}
break;
case PHASE_VX001_ACTIVATION:
Talk(SAY_MKII_DEATH);
events.ScheduleEvent(EVENT_STEP_2, 10*IN_MILLISECONDS, 0, PHASE_VX001_ACTIVATION);
break;
case PHASE_AERIAL_ACTIVATION:
me->ChangeSeat(4);
me->SetUInt32Value(UNIT_FIELD_NPC_EMOTESTATE, EMOTE_STATE_STAND);
events.ScheduleEvent(EVENT_STEP_2, 2.5*IN_MILLISECONDS, 0, PHASE_AERIAL_ACTIVATION);
break;
case PHASE_V0L7R0N_ACTIVATION:
if (instance)
{
//me->SetVisible(true);
if (Creature* Leviathan = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_LEVIATHAN_MK_II)))
Leviathan->GetMotionMaster()->MovePoint(0, 2744.65f, 2569.46f, 364.397f);
if (Creature* VX_001 = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_VX_001)))
{
me->EnterVehicle(VX_001, 1);
me->SetUInt32Value(UNIT_FIELD_NPC_EMOTESTATE, EMOTE_STATE_STAND);
Talk(SAY_AERIAL_DEATH);
}
}
events.ScheduleEvent(EVENT_STEP_2, 5*IN_MILLISECONDS, 0, PHASE_V0L7R0N_ACTIVATION);
break;
default:
break;
}
return;
case EVENT_STEP_2:
switch (_phase)
{
case PHASE_INTRO:
if (instance)
if (Creature* Leviathan = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_LEVIATHAN_MK_II)))
me->EnterVehicle(Leviathan, 4);
events.ScheduleEvent(EVENT_STEP_3, 2*IN_MILLISECONDS, 0, PHASE_INTRO);
break;
case PHASE_VX001_ACTIVATION:
me->ChangeSeat(1);
events.ScheduleEvent(EVENT_STEP_3, 2*IN_MILLISECONDS, 0, PHASE_VX001_ACTIVATION);
break;
case PHASE_AERIAL_ACTIVATION:
Talk(SAY_VX001_DEATH);
me->SetUInt32Value(UNIT_FIELD_NPC_EMOTESTATE, EMOTE_STATE_TALK);
events.ScheduleEvent(EVENT_STEP_3, 5*IN_MILLISECONDS, 0, PHASE_AERIAL_ACTIVATION);
break;
case PHASE_V0L7R0N_ACTIVATION:
if (instance)
if (Creature* VX_001 = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_VX_001)))
if (Creature* Leviathan = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_LEVIATHAN_MK_II)))
{
VX_001->SetStandState(UNIT_STAND_STATE_STAND);
VX_001->SetUInt32Value(UNIT_FIELD_NPC_EMOTESTATE, EMOTE_STATE_CUSTOM_SPELL_01);
VX_001->EnterVehicle(Leviathan, 7);
}
events.ScheduleEvent(EVENT_STEP_3, 2*IN_MILLISECONDS, 0, PHASE_V0L7R0N_ACTIVATION);
break;
default:
break;
}
return;
case EVENT_STEP_3:
switch (_phase)
{
case PHASE_INTRO:
me->ChangeSeat(2);
events.ScheduleEvent(EVENT_STEP_4, 2*IN_MILLISECONDS, 0, PHASE_INTRO);
break;
case PHASE_VX001_ACTIVATION:
if (instance)
instance->SetData(DATA_MIMIRON_ELEVATOR, GO_STATE_READY);
events.ScheduleEvent(EVENT_STEP_4, 15*IN_MILLISECONDS, 0, PHASE_VX001_ACTIVATION);
break;
case PHASE_AERIAL_ACTIVATION:
me->SetUInt32Value(UNIT_FIELD_NPC_EMOTESTATE, EMOTE_STATE_STAND);
if (instance)
{
if (Creature* AerialUnit = me->SummonCreature(NPC_AERIAL_COMMAND_UNIT, 2744.65f, 2569.46f, 380.0f, 3.14159f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 10*IN_MILLISECONDS))
{
AerialUnit->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
AerialUnit->SetVisible(true);
}
}
events.ScheduleEvent(EVENT_STEP_4, 5*IN_MILLISECONDS, 0, PHASE_AERIAL_ACTIVATION);
break;
case PHASE_V0L7R0N_ACTIVATION:
if (instance)
if (Creature* VX_001 = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_VX_001)))
if (Creature* AerialUnit = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_AERIAL_UNIT)))
{
AerialUnit->SetFlying(false);
AerialUnit->EnterVehicle(VX_001, 3);
instance->DoUpdateWorldState(WORLD_STATE_MIMIRON, 1);
Talk(SAY_V07TRON_ACTIVATE);
}
events.ScheduleEvent(EVENT_STEP_4, 10*IN_MILLISECONDS, 0, PHASE_V0L7R0N_ACTIVATION);
break;
default:
break;
}
return;
case EVENT_STEP_4:
switch (_phase)
{
case PHASE_INTRO:
me->ChangeSeat(5);
me->SetUInt32Value(UNIT_FIELD_NPC_EMOTESTATE, EMOTE_STATE_STAND);
events.ScheduleEvent(EVENT_STEP_5, 2.5*IN_MILLISECONDS, 0, PHASE_INTRO);
break;
case PHASE_VX001_ACTIVATION:
if (instance)
{
if (Creature* VX_001 = me->SummonCreature(NPC_VX_001, 2744.65f, 2569.46f, 364.397f, 3.14159f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 10*IN_MILLISECONDS))
{
instance->SetData(DATA_MIMIRON_ELEVATOR, GO_STATE_ACTIVE_ALTERNATIVE);
VX_001->SetVisible(true);
VX_001->SetFaction(35);
VX_001->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
for (uint8 n = 5; n < 7; ++n)
{
if (Creature* Rocket = VX_001->SummonCreature(NPC_ROCKET, VX_001->GetPositionX(), VX_001->GetPositionY(), VX_001->GetPositionZ(), 0, TEMPSUMMON_MANUAL_DESPAWN))
{
Rocket->SetFaction(14);
Rocket->SetReactState(REACT_PASSIVE);
Rocket->EnterVehicle(VX_001, n);
}
}
}
}
events.ScheduleEvent(EVENT_STEP_5, 8*IN_MILLISECONDS, 0, PHASE_VX001_ACTIVATION);
break;
case PHASE_AERIAL_ACTIVATION:
me->ExitVehicle();
me->GetMotionMaster()->MoveJump(2745.06f, 2569.36f, 379.90f, 10, 15);
// entering the vehicle makes Mimiron leave combat and restart the encounter
if (Creature* AerialUnit = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_AERIAL_UNIT)))
me->EnterVehicle(AerialUnit, 0);
events.ScheduleEvent(EVENT_STEP_5, 2*IN_MILLISECONDS, 0, PHASE_AERIAL_ACTIVATION);
break;
case PHASE_V0L7R0N_ACTIVATION:
if (instance)
{
if (Creature* Leviathan = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_LEVIATHAN_MK_II)))
Leviathan->AI()->DoAction(DO_LEVIATHAN_ASSEMBLED);
if (Creature* VX_001 = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_VX_001)))
VX_001->AI()->DoAction(DO_VX001_ASSEMBLED);
if (Creature* AerialUnit = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_AERIAL_UNIT)))
AerialUnit->AI()->DoAction(DO_AERIAL_ASSEMBLED);
_phase = PHASE_COMBAT;
events.SetPhase(_phase);
}
break;
default:
break;
}
return;
case EVENT_STEP_5:
switch (_phase)
{
case PHASE_INTRO:
Talk(SAY_MKII_ACTIVATE);
me->SetUInt32Value(UNIT_FIELD_NPC_EMOTESTATE, EMOTE_STATE_TALK);
events.ScheduleEvent(EVENT_STEP_6, 6*IN_MILLISECONDS, 0, PHASE_INTRO);
break;
case PHASE_VX001_ACTIVATION:
if (instance)
if (Creature* VX_001 = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_VX_001)))
me->EnterVehicle(VX_001, 0);
events.ScheduleEvent(EVENT_STEP_6, 3.5*IN_MILLISECONDS, 0, PHASE_VX001_ACTIVATION);
break;
case PHASE_AERIAL_ACTIVATION:
me->SetUInt32Value(UNIT_FIELD_NPC_EMOTESTATE, EMOTE_STATE_TALK);
Talk(SAY_AERIAL_ACTIVATE);
events.ScheduleEvent(EVENT_STEP_6, 8*IN_MILLISECONDS, 0, PHASE_AERIAL_ACTIVATION);
break;
default:
break;
}
return;
case EVENT_STEP_6:
switch (_phase)
{
case PHASE_INTRO:
me->ChangeSeat(6);
events.ScheduleEvent(EVENT_STEP_7, 2*IN_MILLISECONDS, 0, PHASE_INTRO);
break;
case PHASE_VX001_ACTIVATION:
me->SetUInt32Value(UNIT_FIELD_NPC_EMOTESTATE, EMOTE_STATE_TALK);
Talk(SAY_VX001_ACTIVATE);
events.ScheduleEvent(EVENT_STEP_7, 10*IN_MILLISECONDS, 0, PHASE_VX001_ACTIVATION);
break;
case PHASE_AERIAL_ACTIVATION:
me->SetUInt32Value(UNIT_FIELD_NPC_EMOTESTATE, EMOTE_STATE_STAND);
//me->SetVisible(false);
if (instance)
{
if (Creature* AerialUnit = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_AERIAL_UNIT)))
{
AerialUnit->AI()->DoAction(DO_START_AERIAL);
AerialUnit->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
_phase = PHASE_COMBAT;
events.SetPhase(_phase);
}
}
break;
default:
break;
}
return;
case EVENT_STEP_7:
switch (_phase)
{
case PHASE_INTRO:
if (instance)
{
if (Creature* Leviathan = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_LEVIATHAN_MK_II)))
{
me->SetUInt32Value(UNIT_FIELD_NPC_EMOTESTATE, EMOTE_STATE_STAND);
Leviathan->AI()->DoAction(DO_START_ENCOUNTER);
_phase = PHASE_COMBAT;
events.SetPhase(_phase);
}
}
break;
case PHASE_VX001_ACTIVATION:
me->ChangeSeat(1);
me->SetUInt32Value(UNIT_FIELD_NPC_EMOTESTATE, EMOTE_STATE_SIT);
events.ScheduleEvent(EVENT_STEP_8, 2*IN_MILLISECONDS, 0, PHASE_VX001_ACTIVATION);
break;
default:
break;
}
return;
case EVENT_STEP_8:
switch (_phase)
{
case PHASE_VX001_ACTIVATION:
if (instance)
if (Creature* VX_001 = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_VX_001)))
VX_001->HandleEmoteCommand(EMOTE_ONESHOT_EMERGE);
events.ScheduleEvent(EVENT_STEP_9, 3.5*IN_MILLISECONDS, 0, PHASE_VX001_ACTIVATION);
break;
default:
break;
}
return;
case EVENT_STEP_9:
switch (_phase)
{
case PHASE_VX001_ACTIVATION:
if (instance)
if (Creature* VX_001 = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_VX_001)))
{
VX_001->AddAura(SPELL_HOVER, VX_001); // Hover
VX_001->AI()->DoAction(DO_START_VX001);
_phase = PHASE_COMBAT;
events.SetPhase(_phase);
}
break;
default:
break;
}
return;
default:
return;
}
}
}
uint32 GetData(uint32 type) const override
{
switch (type)
{
case DATA_GET_HARD_MODE:
return _gotHardMode ? true : false;
case DATA_FLAME_COUNT:
return _flameCount;
case DATA_AVOIDED_ROCKET_STRIKES:
return _avoidedRocketStrikes ? true : false;
case DATA_AVOIDED_PROXIMITY_MINES:
return _avoidedProximityMines ? true : false;
case DATA_AVOIDED_BOOM_BOT_EXPLOSION:
return _avoidedBoomBotExplosion ? true : false;
default:
break;
}
return 0;
}
void DoAction(int32 action) override
{
switch (action)
{
case DO_ACTIVATE_VX001:
_phase = PHASE_VX001_ACTIVATION;
events.SetPhase(PHASE_VX001_ACTIVATION);
events.ScheduleEvent(EVENT_STEP_1, 0.1*IN_MILLISECONDS, 0, PHASE_VX001_ACTIVATION);
break;
case DO_ACTIVATE_AERIAL:
_phase = PHASE_AERIAL_ACTIVATION;
events.SetPhase(PHASE_AERIAL_ACTIVATION);
events.ScheduleEvent(EVENT_STEP_1, 5*IN_MILLISECONDS, 0, PHASE_AERIAL_ACTIVATION);
break;
case DO_ACTIVATE_V0L7R0N:
me->SetVisible(true);
_phase = PHASE_V0L7R0N_ACTIVATION;
events.SetPhase(PHASE_V0L7R0N_ACTIVATION);
events.ScheduleEvent(EVENT_STEP_1, 1*IN_MILLISECONDS, 0, PHASE_V0L7R0N_ACTIVATION);
break;
case DO_ACTIVATE_HARD_MODE: // Cannot be done infight, since the button gets locked on EnterCombat() with Mimiron.
me->GetMap()->SetWorldState(WORLDSTATE_FIRE_FIGHTER, 1);
_gotHardMode = true;
DoZoneInCombat();
break;
case DO_INCREASE_FLAME_COUNT:
++_flameCount;
break;
case DO_DECREASE_FLAME_COUNT:
if (_flameCount)
--_flameCount;
break;
// Repair stuff
case DO_LEVIATHAN_SELF_REPAIR_START:
_mapMutex.acquire();
_isSelfRepairing[DATA_LEVIATHAN_MK_II] = true;
_mapMutex.release();
BotAliveCheck();
break;
case DO_LEVIATHAN_SELF_REPAIR_END:
_mapMutex.acquire();
_isSelfRepairing[DATA_LEVIATHAN_MK_II] = false;
_mapMutex.release();
break;
case DO_VX001_SELF_REPAIR_START:
_mapMutex.acquire();
_isSelfRepairing[DATA_VX_001] = true;
_mapMutex.release();
BotAliveCheck();
break;
case DO_VX001_SELF_REPAIR_END:
_mapMutex.acquire();
_isSelfRepairing[DATA_VX_001] = false;
_mapMutex.release();
break;
case DO_AERIAL_SELF_REPAIR_START:
_mapMutex.acquire();
_isSelfRepairing[DATA_AERIAL_UNIT] = true;
_mapMutex.release();
BotAliveCheck();
break;
case DO_AERIAL_SELF_REPAIR_END:
_mapMutex.acquire();
_isSelfRepairing[DATA_AERIAL_UNIT] = false;
_mapMutex.release();
break;
// Achiev
case DATA_AVOIDED_ROCKET_STRIKES:
_avoidedRocketStrikes = false;
me->GetMap()->SetWorldState(WORLDSTATE_SET_UP_US_BOMB_ROCKET, 0);
break;
case DATA_AVOIDED_PROXIMITY_MINES:
_avoidedProximityMines = false;
me->GetMap()->SetWorldState(WORLDSTATE_SET_UP_US_BOMB_MINE, 0);
break;
case DATA_AVOIDED_BOOM_BOT_EXPLOSION:
_avoidedBoomBotExplosion = false;
me->GetMap()->SetWorldState(WORLDSTATE_SET_UP_US_BOMB_BOT, 0);
break;
default:
break;
}
}
private:
ACE_Mutex _mapMutex;
std::map<uint32, bool> _isSelfRepairing;
std::map<BombIndices, bool> _setUpUsTheBomb;
Phases _phase;
uint32 _flameCount;
bool _gotHardMode;
bool _enraged;
bool _gotEncounterFinished;
bool _avoidedRocketStrikes;
bool _avoidedProximityMines;
bool _avoidedBoomBotExplosion;
void ComputerTalk(uint32 textId)
{
if (Creature* computer = me->FindNearestCreature(NPC_COMPUTER, 100.0f))
computer->AI()->Talk(textId);
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<boss_mimironAI>(creature);
}
};
class boss_leviathan_mk : public CreatureScript
{
public:
boss_leviathan_mk() : CreatureScript("boss_leviathan_mk") { }
struct boss_leviathan_mkAI : public ScriptedAI
{
boss_leviathan_mkAI(Creature* creature) : ScriptedAI(creature) { }
void InitializeAI() override
{
instance = me->GetInstanceScript();
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
Reset();
}
void Reset() override
{
_events.Reset();
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1);
me->SetStandState(UNIT_STAND_STATE_STAND);
me->SetReactState(REACT_PASSIVE);
me->ClearUnitState(UNIT_STATE_ROTATING);
me->RemoveAllAurasExceptType(SPELL_AURA_CONTROL_VEHICLE);
_phase = PHASE_IDLE;
_events.SetPhase(_phase);
_gotMimironHardMode = false;
}
void JustReachedHome() override
{
Creature* findturret = me->FindNearestCreature(NPC_MKII_TURRET, 50.0f);
if (!findturret)
if (Creature* turret = me->SummonCreature(NPC_MKII_TURRET, turretPos))
{
turret->EnterVehicle(me, 3);
turret->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1);
turret->SetReactState(REACT_PASSIVE);
}
}
void KilledUnit(Unit* /*who*/) override
{
if (Creature* mimiron = ObjectAccessor::GetCreature(*me, instance ? instance->GetData64(BOSS_MIMIRON) : 0))
{
if (_phase == PHASE_LEVIATHAN_SOLO__GLOBAL_1)
{
if (!urand(0,5))
Talk(SAY_MKII_SLAY, mimiron);
}
else
if (!urand(0,5))
Talk(SAY_V07TRON_SLAY, mimiron);
}
}
void SpellHit(Unit* caster, SpellInfo const* spell) override
{
if (!caster || !spell)
return;
if (spell->Id == SPELL_SELF_REPAIR)
{
DoAction(DO_LEVIATHAN_SELF_REPAIR_END);
if (Creature* Mimiron = ObjectAccessor::GetCreature(*me, instance->GetData64(BOSS_MIMIRON)))
Mimiron->AI()->DoAction(DO_LEVIATHAN_SELF_REPAIR_END);
}
}
void DamageTaken(Unit* /*who*/, uint32& damage) override
{
if (damage >= me->GetHealth())
{
// Common stuff
damage = 0;
if (_phase == PHASE_IDLE)
return;
me->InterruptNonMeleeSpells(true);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1);
me->AttackStop();
me->SetReactState(REACT_PASSIVE);
me->RemoveAllAurasExceptType(SPELL_AURA_CONTROL_VEHICLE);
switch (_phase)
{
case PHASE_LEVIATHAN_SOLO__GLOBAL_1:
me->SetHealth(me->GetMaxHealth());
if (Creature* Mimiron = ObjectAccessor::GetCreature(*me, instance->GetData64(BOSS_MIMIRON)))
Mimiron->AI()->DoAction(DO_ACTIVATE_VX001);
if (Creature* turret = me->GetVehicleKit()->GetPassenger(3)->ToCreature())
{
turret->Kill(turret, false);
turret->DespawnOrUnsummon(5000);
}
me->SetSpeed(MOVE_RUN, 1.5f, true);
me->GetMotionMaster()->MovePoint(0, 2790.11f, 2595.83f, 364.32f);
break;
case PHASE_LEVIATHAN_ASSEMBLED__GLOBAL_4:
me->SetStandState(UNIT_STAND_STATE_DEAD);
if (Creature* Mimiron = ObjectAccessor::GetCreature(*me, instance->GetData64(BOSS_MIMIRON)))
Mimiron->AI()->DoAction(DO_LEVIATHAN_SELF_REPAIR_START);
DoCast(me, SPELL_SELF_REPAIR);
break;
default:
break;
}
_events.Reset(); // Wipe events, just for the case
_phase = PHASE_IDLE;
_events.SetPhase(_phase);
}
}
void EnterCombat(Unit* /*who*/) override
{
if (Creature* Mimiron = ObjectAccessor::GetCreature(*me, instance ? instance->GetData64(BOSS_MIMIRON) : 0))
_gotMimironHardMode = Mimiron->AI()->GetData(DATA_GET_HARD_MODE);
if (Creature* turret = me->GetVehicleKit()->GetPassenger(3)->ToCreature())
{
turret->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_IMMUNE_TO_PC);
turret->SetReactState(REACT_AGGRESSIVE);
turret->AI()->DoZoneInCombat();
}
_events.ScheduleEvent(EVENT_SHOCK_BLAST, 30*IN_MILLISECONDS, 0, PHASE_LEVIATHAN_SOLO__GLOBAL_1);
_events.ScheduleEvent(EVENT_PROXIMITY_MINE, 0, 0, PHASE_LEVIATHAN_SOLO__GLOBAL_1);
_events.ScheduleEvent(EVENT_PLASMA_BLAST, 10*IN_MILLISECONDS, 0, PHASE_LEVIATHAN_SOLO__GLOBAL_1);
if (_gotMimironHardMode)
{
DoCast(me, SPELL_EMERGENCY_MODE, true);
_events.ScheduleEvent(EVENT_FLAME_SUPPRESSANT, 1*MINUTE*IN_MILLISECONDS, 0, PHASE_LEVIATHAN_SOLO__GLOBAL_1);
}
}
void DoAction(int32 action) override
{
switch (action)
{
case DO_START_ENCOUNTER:
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_IMMUNE_TO_PC);
me->SetReactState(REACT_AGGRESSIVE);
_phase = PHASE_LEVIATHAN_SOLO__GLOBAL_1;
_events.SetPhase(_phase);
DoZoneInCombat();
break;
case DO_LEVIATHAN_ASSEMBLED: // Assemble and self-repair share some stuff, so the fallthrough is intended!
me->SetHealth((me->GetMaxHealth() >> 1));
// no break here
case DO_LEVIATHAN_SELF_REPAIR_END:
if (_gotMimironHardMode)
if (!me->HasAura(SPELL_EMERGENCY_MODE))
DoCast(me, SPELL_EMERGENCY_MODE, true);
_phase = PHASE_LEVIATHAN_ASSEMBLED__GLOBAL_4;
_events.SetPhase(_phase);
me->InterruptNonMeleeSpells(false);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1);
if (!me->HasUnitState(UNIT_STATE_ROTATING))
me->SetReactState(REACT_AGGRESSIVE);
me->SetSpeed(MOVE_RUN, 1.0f, true);
me->SetStandState(UNIT_STAND_STATE_STAND);
_events.RescheduleEvent(EVENT_PROXIMITY_MINE, 1*IN_MILLISECONDS, 0, PHASE_LEVIATHAN_ASSEMBLED__GLOBAL_4);
_events.RescheduleEvent(EVENT_SHOCK_BLAST, 3*IN_MILLISECONDS, 0, PHASE_LEVIATHAN_ASSEMBLED__GLOBAL_4);
break;
case DO_ENTER_ENRAGE:
DoCast(me, SPELL_BERSERK, true);
break;
default:
break;
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim() || _phase == PHASE_IDLE)
return;
_events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING) || me->HasUnitState(UNIT_STATE_STUNNED))
return;
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_PROXIMITY_MINE:
{
DoCast(SPELL_PROXIMITY_MINES);
_events.RescheduleEvent(EVENT_PROXIMITY_MINE, 35*IN_MILLISECONDS, _phase);
}
return;
case EVENT_PLASMA_BLAST:
Talk(EMOTE_PLASMA_BLAST);
DoCast(SPELL_PLASMA_BLAST);
_events.RescheduleEvent(EVENT_PLASMA_BLAST, urand(30*IN_MILLISECONDS, 35*IN_MILLISECONDS), 0, _phase);
_events.RescheduleEvent(EVENT_SHOCK_BLAST, urand(6*IN_MILLISECONDS, 10*IN_MILLISECONDS), 0, _phase);
return;
case EVENT_SHOCK_BLAST:
DoCastAOE(SPELL_SHOCK_BLAST);
_events.RescheduleEvent(EVENT_SHOCK_BLAST, 35*IN_MILLISECONDS, 0, _phase);
return;
case EVENT_FLAME_SUPPRESSANT:
DoCastAOE(SPELL_FLAME_SUPPRESSANT_MK);
_events.RescheduleEvent(EVENT_FLAME_SUPPRESSANT, 1*MINUTE*IN_MILLISECONDS, 0, PHASE_LEVIATHAN_SOLO__GLOBAL_1);
return;
default:
return;
}
}
DoMeleeAttackIfReady();
}
private:
Phases _phase;
EventMap _events;
bool _gotMimironHardMode;
InstanceScript* instance;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<boss_leviathan_mkAI>(creature);
}
};
// Levi's turret
class boss_leviathan_mk_turret : public CreatureScript
{
public:
boss_leviathan_mk_turret() : CreatureScript("boss_leviathan_mk_turret") { }
struct boss_leviathan_mk_turretAI : public ScriptedAI
{
boss_leviathan_mk_turretAI(Creature* c) : ScriptedAI(c) { }
void InitializeAI() override
{
me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true);
me->ApplySpellImmune(0, IMMUNITY_ID, SPELL_DEATH_GRIP, true);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
Reset();
}
void Reset() override
{
me->SetReactState(REACT_PASSIVE);
_napalmShellTimer = urand(8*IN_MILLISECONDS, 12*IN_MILLISECONDS);
}
void DamageTaken(Unit* who, uint32& damage) override
{
damage = 0;
}
// prefer ranged targets
Unit* GetNapalmShellTarget()
{
if (Map* map = me->GetMap())
{
std::list<Player*> playerList;
for (auto&& itr : map->GetPlayers())
{
if (Player* player = itr.GetSource())
{
if (player->isDead() || player->IsGameMaster())
continue;
float Distance = player->GetDistance(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ());
if (Distance < 15.0f || Distance > 100.0f)
continue;
playerList.push_back(player);
}
}
if (playerList.empty())
return SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true);
else
return Trinity::Containers::SelectRandomContainerElement(playerList);
}
else
return 0;
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (_napalmShellTimer <= diff)
{
if (Unit* shellTarget = GetNapalmShellTarget())
DoCast(shellTarget, SPELL_NAPALM_SHELL);
_napalmShellTimer = urand(8*IN_MILLISECONDS, 12*IN_MILLISECONDS);
}
else
_napalmShellTimer -= diff;
}
private:
uint32 _napalmShellTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<boss_leviathan_mk_turretAI>(creature);
}
};
// Npc that triggers the mine explosion
// Bomb will explode after 35 seconds or if a potential target is within half a meter
class npc_proximity_mine : public CreatureScript
{
public:
npc_proximity_mine() : CreatureScript("npc_proximity_mine") { }
struct npc_proximity_mineAI : public ScriptedAI
{
npc_proximity_mineAI(Creature* creature) : ScriptedAI(creature)
{
SetCombatMovement(false);
}
void InitializeAI() override
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
_boomTimer = 35*IN_MILLISECONDS;
_boomLocked = false;
}
void SpellHitTarget(Unit* target, SpellInfo const* spell) override
{
if (!target || !spell)
return;
if (target->ToPlayer())
if (spell->Id == SPELL_EXPLOSION || spell->Id == SPELL_EXPLOSION_25)
if (InstanceScript* instance = me->GetInstanceScript())
if (Creature* mimiron = ObjectAccessor::GetCreature(*me, instance->GetData64(BOSS_MIMIRON)))
mimiron->AI()->DoAction(DATA_AVOIDED_PROXIMITY_MINES);
}
void MoveInLineOfSight(Unit* who) override
{
if (!who)
return;
if (Player* player = who->ToPlayer())
if (!player->IsGameMaster())
if (!_boomLocked && me->GetDistance2d(player) < 2.0f)
{
DoCastAOE(SPELL_EXPLOSION);
_boomLocked = true;
me->DespawnOrUnsummon(1*IN_MILLISECONDS);
}
}
void UpdateAI(uint32 diff) override
{
if (_boomTimer <= diff)
{
if (!_boomLocked)
{
DoCastAOE(SPELL_EXPLOSION);
me->DespawnOrUnsummon(0.2*IN_MILLISECONDS);
_boomLocked = true;
}
}
else
_boomTimer -= diff;
}
private:
uint32 _boomTimer;
bool _boomLocked;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_proximity_mineAI>(creature);
}
};
class spell_proximity_mines : public SpellScriptLoader // Spell 63027
{
public:
spell_proximity_mines() : SpellScriptLoader("spell_proximity_mines") { }
class spell_proximity_mines_SpellScript : public SpellScript
{
PrepareSpellScript(spell_proximity_mines_SpellScript);
void HandleDummyTick(SpellEffIndex /*effIndex*/)
{
if (Unit* caster = GetCaster())
{
for (uint8 i = 0; i < 10; i++)
caster->CastSpell(caster, SPELL_MINES_SPAWN, true);
}
}
void Register() override
{
OnEffectHit += SpellEffectFn(spell_proximity_mines_SpellScript::HandleDummyTick, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_proximity_mines_SpellScript();
}
};
class boss_vx_001 : public CreatureScript
{
public:
boss_vx_001() : CreatureScript("boss_vx_001") { }
struct boss_vx_001AI : public ScriptedAI
{
boss_vx_001AI(Creature* creature) : ScriptedAI(creature)
{
SetCombatMovement(false);
}
void InitializeAI() override
{
instance = me->GetInstanceScript();
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
Reset();
}
void Reset() override
{
_spinning = false;
_direction = false;
_spinTimer = 0.25*IN_MILLISECONDS;
_events.Reset();
me->SetReactState(REACT_PASSIVE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_DISABLE_MOVE);
//me->SetStandState(UNIT_STAND_STATE_STAND);
me->ClearUnitState(UNIT_STATE_STUNNED);
me->RemoveAllAurasExceptType(SPELL_AURA_CONTROL_VEHICLE);
_phase = PHASE_IDLE;
_events.SetPhase(_phase);
_mimironHardMode = false;
}
void KilledUnit(Unit* /*who*/) override
{
if (instance)
if (Creature* mimiron = ObjectAccessor::GetCreature(*me, instance ? instance->GetData64(BOSS_MIMIRON) : 0))
{
if (_phase == PHASE_VX001_SOLO__GLOBAL_2)
{
if (!urand(0,5))
Talk(SAY_VX001_SLAY, mimiron);
}
else
if (!urand(0,5))
Talk(SAY_V07TRON_SLAY, mimiron);
}
}
void EnterCombat(Unit* /*who*/) override
{
if (Creature* Mimiron = ObjectAccessor::GetCreature(*me, instance ? instance->GetData64(BOSS_MIMIRON) : 0))
_mimironHardMode = Mimiron->AI()->GetData(DATA_GET_HARD_MODE);
if (_mimironHardMode)
{
DoCast(me, SPELL_EMERGENCY_MODE, true);
_events.ScheduleEvent(EVENT_FROST_BOMB, 15*IN_MILLISECONDS, 0, PHASE_VX001_SOLO__GLOBAL_2);
_events.ScheduleEvent(EVENT_FLAME_SUPPRESSANT_VX001, 1*IN_MILLISECONDS, 0, PHASE_VX001_SOLO__GLOBAL_2);
}
_events.ScheduleEvent(EVENT_RAPID_BURST, 2.5*IN_MILLISECONDS, 0, PHASE_VX001_SOLO__GLOBAL_2);
_events.ScheduleEvent(EVENT_LASER_BARRAGE, urand(35*IN_MILLISECONDS, 40*IN_MILLISECONDS), 0, PHASE_VX001_SOLO__GLOBAL_2);
_events.ScheduleEvent(EVENT_ROCKET_STRIKE, 20*IN_MILLISECONDS, 0, PHASE_VX001_SOLO__GLOBAL_2);
_events.ScheduleEvent(EVENT_HEAT_WAVE, urand(8*IN_MILLISECONDS, 10*IN_MILLISECONDS), 0, PHASE_VX001_SOLO__GLOBAL_2);
}
void AttackStart(Unit* victim) override
{
// Do nothing, don't change target
}
void DoAction(int32 action) override
{
switch (action)
{
case DO_START_VX001:
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NOT_SELECTABLE);
_phase = PHASE_VX001_SOLO__GLOBAL_2;
_events.SetPhase(_phase);
me->SetFaction(14);
me->SetInCombatWithZone();
break;
case DO_VX001_ASSEMBLED: // Reassemble and heal share some stuff, fallthrough is intended
me->SetHealth( (me->GetMaxHealth() >> 1) );
case DO_VX001_SELF_REPAIR_END:
if (_mimironHardMode)
if (!me->HasAura(SPELL_EMERGENCY_MODE))
DoCast(me, SPELL_EMERGENCY_MODE, true);
_phase = PHASE_VX001_ASSEMBLED__GLOBAL_4;
_events.SetPhase(_phase);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1);
me->SetStandState(UNIT_STAND_STATE_STAND);
_events.RescheduleEvent(EVENT_LASER_BARRAGE, urand(35*IN_MILLISECONDS, 40*IN_MILLISECONDS), 0, PHASE_VX001_ASSEMBLED__GLOBAL_4);
_events.RescheduleEvent(EVENT_ROCKET_STRIKE, 20*IN_MILLISECONDS, 0, PHASE_VX001_ASSEMBLED__GLOBAL_4);
_events.RescheduleEvent(EVENT_HAND_PULSE, 5*IN_MILLISECONDS, 0, PHASE_VX001_ASSEMBLED__GLOBAL_4);
if (_mimironHardMode)
_events.RescheduleEvent(EVENT_FROST_BOMB, 15*IN_MILLISECONDS, 0, PHASE_VX001_ASSEMBLED__GLOBAL_4);
break;
case DO_ENTER_ENRAGE:
DoCast(me, SPELL_BERSERK, true);
break;
default:
break;
}
}
void DamageTaken(Unit* /*who*/, uint32& damage) override
{
if (damage >= me->GetHealth())
{
damage = 0;
if (_phase == PHASE_IDLE)
return;
_spinning = false;
me->InterruptNonMeleeSpells(true);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1);
me->AttackStop();
me->RemoveAllAurasExceptType(SPELL_AURA_CONTROL_VEHICLE);
me->SetStandState(UNIT_STAND_STATE_DEAD);
switch (_phase)
{
case PHASE_VX001_SOLO__GLOBAL_2:
me->SetHealth(me->GetMaxHealth());
if (Creature* Mimiron = ObjectAccessor::GetCreature(*me, instance->GetData64(BOSS_MIMIRON)))
Mimiron->AI()->DoAction(DO_ACTIVATE_AERIAL);
break;
case PHASE_VX001_ASSEMBLED__GLOBAL_4:
if (Creature* Mimiron = ObjectAccessor::GetCreature(*me, instance->GetData64(BOSS_MIMIRON)))
Mimiron->AI()->DoAction(DO_VX001_SELF_REPAIR_START);
DoCast(me, SPELL_SELF_REPAIR);
break;
default:
break;
}
_events.Reset();
_phase = PHASE_IDLE;
_events.SetPhase(_phase);
}
}
void SpellHit(Unit* caster, SpellInfo const* spell) override
{
if (!caster || !spell)
return;
if (spell->Id == SPELL_SELF_REPAIR)
{
DoAction(DO_VX001_SELF_REPAIR_END);
if (Creature* Mimiron = ObjectAccessor::GetCreature(*me, instance->GetData64(BOSS_MIMIRON)))
Mimiron->AI()->DoAction(DO_VX001_SELF_REPAIR_END);
}
}
void SpellHitTarget(Unit* target, SpellInfo const* spell) override
{
switch (spell->Id)
{
case SPELL_FROSTBOMB:
me->SummonCreature(NPC_FROST_BOMB, *target, TEMPSUMMON_TIMED_DESPAWN, 11*IN_MILLISECONDS);
break;
default:
break;
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim() || _phase == PHASE_IDLE)
return;
_events.Update(diff);
if (_spinning)
{
if (Creature* leviathan = me->GetVehicleCreatureBase())
{
me->m_movementInfo.transport.pos.SetOrientation(me->GetOrientation() - leviathan->GetOrientation());
me->SendMovementFlagUpdate();
}
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_RAPID_BURST:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true))
if (Creature* BurstTarget = me->SummonCreature(NPC_BURST_TARGET, *target, TEMPSUMMON_TIMED_DESPAWN, 3.1*IN_MILLISECONDS))
{
DoCast(BurstTarget, SPELL_RAPID_BURST);
me->SetFacingToObject(target);
}
_events.RescheduleEvent(EVENT_RAPID_BURST, 2500, 0, PHASE_VX001_SOLO__GLOBAL_2);
return;
case EVENT_LASER_BARRAGE:
{
if (Creature* leviathan = me->GetVehicleCreatureBase())
{
leviathan->AddUnitState(UNIT_STATE_ROTATING);
leviathan->SetReactState(REACT_PASSIVE);
leviathan->SetFacingTo(leviathan->GetOrientation());
leviathan->SetTarget(0);
}
_direction = RAND(true, false);
_spinning = true;
DoCast(SPELL_SPINNING_UP); // The triggered spells should be casted on another target, seem to be self-casted 63274,66490
_events.DelayEvents(15*IN_MILLISECONDS);
_events.RescheduleEvent(EVENT_LASER_BARRAGE, 1*MINUTE*IN_MILLISECONDS, 0, _phase);
_events.RescheduleEvent(EVENT_LASER_BARRAGE_END, 14*IN_MILLISECONDS, 0, _phase);
return;
}
case EVENT_LASER_BARRAGE_END:
me->m_movementInfo.transport.pos.SetOrientation(0);
me->SendMovementFlagUpdate();
if (Creature* leviathan = me->GetVehicleCreatureBase())
{
leviathan->ClearUnitState(UNIT_STATE_ROTATING);
if (!leviathan->FindCurrentSpellBySpellId(SPELL_SELF_REPAIR))
leviathan->SetReactState(REACT_AGGRESSIVE);
if (leviathan->GetVictim())
leviathan->SetTarget(leviathan->GetVictim()->GetGUID());
}
if (me->GetVictim())
AttackStart(me->GetVictim());
else if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 50.0f, true))
AttackStart(target);
_spinning = false;
return;
case EVENT_ROCKET_STRIKE:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true))
{
if (Creature* pTemp = me->SummonCreature(NPC_MIMIRON_FOCUS, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 10*IN_MILLISECONDS))
{
pTemp->SetReactState(REACT_PASSIVE);
pTemp->SetDisplayId(pTemp->GetCreatureTemplate()->Modelid2);
pTemp->GetMotionMaster()->MoveIdle();
pTemp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE);
pTemp->CombatStop();
pTemp->CastSpell(pTemp, SPELL_ROCKET_STRIKE_AURA, true);
pTemp->DespawnOrUnsummon(6000);
}
if (Unit* missile = me->GetVehicleKit()->GetPassenger(5))
missile->CastSpell(target, SPELL_ROCKET_STRIKE);
}
if (_phase == PHASE_VX001_ASSEMBLED__GLOBAL_4)
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true))
{
if (Creature* pTemp = me->SummonCreature(NPC_MIMIRON_FOCUS, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 10*IN_MILLISECONDS))
{
pTemp->SetReactState(REACT_PASSIVE);
pTemp->SetDisplayId(pTemp->GetCreatureTemplate()->Modelid2);
pTemp->GetMotionMaster()->MoveIdle();
pTemp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE);
pTemp->CombatStop();
pTemp->CastSpell(pTemp, SPELL_ROCKET_STRIKE_AURA, true);
pTemp->DespawnOrUnsummon(6000);
}
if (Unit* missile = me->GetVehicleKit()->GetPassenger(6))
missile->CastSpell(target, SPELL_ROCKET_STRIKE);
}
_events.RescheduleEvent(EVENT_ROCKET_STRIKE, urand(20*IN_MILLISECONDS, 25*IN_MILLISECONDS), 0, _phase);
return;
case EVENT_HEAT_WAVE:
DoCastAOE(SPELL_HEAT_WAVE);
_events.RescheduleEvent(EVENT_HEAT_WAVE, 10*IN_MILLISECONDS, 0, PHASE_VX001_SOLO__GLOBAL_2);
return;
case EVENT_HAND_PULSE:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true))
DoCast(target, SPELL_HAND_PULSE);
_events.RescheduleEvent(EVENT_HAND_PULSE, urand(3*IN_MILLISECONDS, 4*IN_MILLISECONDS), 0 , PHASE_VX001_ASSEMBLED__GLOBAL_4);
return;
case EVENT_FROST_BOMB:
if (me->FindNearestCreature(NPC_FLAME_SPREAD, 100.0f))
{
DoCast(SPELL_FROSTBOMB);
_events.RescheduleEvent(EVENT_FROST_BOMB, 45*IN_MILLISECONDS, 0, _phase);
}
else
_events.RescheduleEvent(EVENT_FROST_BOMB, 5*IN_MILLISECONDS, 0, _phase);
return;
case EVENT_FLAME_SUPPRESSANT_VX001:
DoCastAOE(SPELL_FLAME_SUPPRESSANT_VX001);
_events.RescheduleEvent(EVENT_FLAME_SUPPRESSANT_VX001, 10*IN_MILLISECONDS, 0, PHASE_VX001_SOLO__GLOBAL_2);
return;
default:
return;
}
}
}
private:
Phases _phase;
EventMap _events;
InstanceScript* instance;
bool _mimironHardMode;
bool _spinning;
bool _direction;
uint32 _spinTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<boss_vx_001AI>(creature);
}
};
class npc_rocket_strike : public CreatureScript
{
public:
npc_rocket_strike() : CreatureScript("npc_rocket_strike") { }
struct npc_rocket_strikeAI : public ScriptedAI
{
npc_rocket_strikeAI(Creature* creature) : ScriptedAI(creature)
{
SetCombatMovement(false);
}
void InitializeAI() override
{
me->SetReactState(REACT_PASSIVE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED);
me->DespawnOrUnsummon(1);
Reset();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_rocket_strikeAI>(creature);
}
};
class spell_rapid_burst : public SpellScriptLoader
{
public:
spell_rapid_burst() : SpellScriptLoader("spell_rapid_burst") { }
class spell_rapid_burst_AuraScript : public AuraScript
{
PrepareAuraScript(spell_rapid_burst_AuraScript);
void HandleDummyTick(AuraEffect const* aurEff)
{
if (!GetTarget())
return;
if (Unit* caster = GetCaster())
{
caster->RemoveAurasDueToSpell(SPELL_HOVER);
switch (caster->GetMap()->GetDifficulty())
{
case RAID_DIFFICULTY_10MAN_NORMAL:
caster->CastSpell(GetTarget(), (left = !left) ? SPELL_RAPID_BURST_LEFT_10 : SPELL_RAPID_BURST_RIGHT_10, true, nullptr, aurEff);
break;
case RAID_DIFFICULTY_25MAN_NORMAL:
caster->CastSpell(GetTarget(), (left = !left) ? SPELL_RAPID_BURST_LEFT_25 : SPELL_RAPID_BURST_RIGHT_25, true, nullptr, aurEff);
break;
default:
break;
}
if (!aurEff->GetBase()->GetDuration())
caster->CastSpell(caster, SPELL_HOVER, true);
}
}
void Register() override
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_rapid_burst_AuraScript::HandleDummyTick, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY);
}
private:
bool left = false;
};
AuraScript* GetAuraScript() const override
{
return new spell_rapid_burst_AuraScript();
}
};
class boss_aerial_unit : public CreatureScript
{
public:
boss_aerial_unit() : CreatureScript("boss_aerial_unit") { }
struct boss_aerial_unitAI : public ScriptedAI
{
boss_aerial_unitAI(Creature* creature) : ScriptedAI(creature), _summons(me), _phase(PHASE_IDLE) { }
void InitializeAI() override
{
instance = me->GetInstanceScript();
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->SetFlying(true);
Reset();
}
void Reset() override
{
_events.Reset();
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_DISABLE_MOVE);
me->SetReactState(REACT_PASSIVE);
me->SetStandState(UNIT_STAND_STATE_STAND);
me->SetVisible(false);
me->RemoveAllAurasExceptType(SPELL_AURA_CONTROL_VEHICLE);
me->SetFlying(true);
_phase = PHASE_IDLE;
_events.SetPhase(PHASE_IDLE);
_summons.DespawnAll();
_gotMimironHardMode = false;
}
void KilledUnit(Unit* /*who*/) override
{
if (instance)
if (Creature* mimiron = ObjectAccessor::GetCreature(*me, instance ? instance->GetData64(BOSS_MIMIRON) : 0))
{
if (_phase == PHASE_AERIAL_SOLO__GLOBAL_3)
{
if (!urand(0,5))
Talk(SAY_AERIAL_SLAY, mimiron);
}
else
if (!urand(0,5))
Talk(SAY_V07TRON_SLAY, mimiron);
}
}
void SpellHit(Unit* caster, SpellInfo const* spell) override
{
if (!caster || !spell)
return;
if (spell->Id == SPELL_SELF_REPAIR)
{
DoAction(DO_AERIAL_SELF_REPAIR_END);
if (Creature* Mimiron = ObjectAccessor::GetCreature(*me, instance->GetData64(BOSS_MIMIRON)))
Mimiron->AI()->DoAction(DO_AERIAL_SELF_REPAIR_END);
}
}
void SpellHitTarget(Unit* target, SpellInfo const* spell) override
{
uint32 aura = 0;
switch (spell->Id)
{
case SPELL_SUMMON_SCRAP_BOT_TRIGGER_JUNK_BOT: aura = SPELL_SUMMON_SCRAP_BOT_AURA_JUNK_BOT; break;
case SPELL_SUMMON_SCRAP_BOT_TRIGGER_ASSAULT_BOT: aura = SPELL_SUMMON_SCRAP_BOT_AURA_ASSAULT_BOT; break;
case SPELL_SUMMON_FIRE_BOT_TRIGGER: aura = SPELL_SUMMON_FIRE_BOT_AURA; break;
default:
return;
}
target->CastSpell(target, aura, true);
for (uint32 id = 194740; id <= 194748; ++id)
{
if (GameObject* go = target->FindNearestGameObject(id, 5.0f))
{
go->UseDoorOrButton();
break;
}
}
}
void EnterCombat(Unit* /*who*/) override
{
if (Creature* Mimiron = ObjectAccessor::GetCreature(*me, instance ? instance->GetData64(BOSS_MIMIRON) : 0))
_gotMimironHardMode = Mimiron->AI()->GetData(DATA_GET_HARD_MODE);
if (_gotMimironHardMode)
DoCast(me, SPELL_EMERGENCY_MODE, true);
_events.ScheduleEvent(EVENT_PLASMA_BALL, 1*IN_MILLISECONDS);
_events.ScheduleEvent(EVENT_SUMMON_JUNK_BOT, 10 * IN_MILLISECONDS, 0, PHASE_AERIAL_SOLO__GLOBAL_3);
_events.ScheduleEvent(EVENT_SUMMON_FIRE_BOT, 2 * IN_MILLISECONDS, 0, PHASE_AERIAL_SOLO__GLOBAL_3);
_events.ScheduleEvent(EVENT_SUMMON_ASSAULT_BOT, 7 * IN_MILLISECONDS, 0, PHASE_AERIAL_SOLO__GLOBAL_3);
_events.ScheduleEvent(EVENT_SUMMON_BOOM_BOT, 11 * IN_MILLISECONDS, 0, PHASE_AERIAL_SOLO__GLOBAL_3);
}
void AttackStart(Unit* target)
{
AttackStartCaster(target, 100.0f);
}
void DoAction(int32 action) override
{
switch (action)
{
case DO_START_AERIAL:
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_IMMUNE_TO_PC);
me->SetReactState(REACT_AGGRESSIVE);
_phase = PHASE_AERIAL_SOLO__GLOBAL_3;
_events.SetPhase(PHASE_AERIAL_SOLO__GLOBAL_3);
DoZoneInCombat();
break;
case DO_DISABLE_AERIAL:
if (_phase == PHASE_AERIAL_SOLO__GLOBAL_3)
{
me->CastStop();
me->SetReactState(REACT_PASSIVE);
me->GetMotionMaster()->Clear();
// check if the aura works correctly (+50% damage from all sources)
DoCast(me, SPELL_MAGNETIC_CORE);
DoCast(me, SPELL_MAGNETIC_CORE_VISUAL);
// Move to floor.
Position destination;
me->GetPosition(&destination);
destination.m_positionZ = 368.965f;
me->GetMotionMaster()->MoveLand(1, destination, 5.0f); // Check if MoveLand is ok here, a flying unit should have a landing animation, but... just 4 the case
_events.DelayEvents(20*IN_MILLISECONDS);
_events.ScheduleEvent(EVENT_REACTIVATE_AERIAL, 20*IN_MILLISECONDS, 0, PHASE_AERIAL_SOLO__GLOBAL_3);
}
break;
case DO_AERIAL_ASSEMBLED:
me->SetHealth( (me->GetMaxHealth() >> 1) ); // Once again, re-assemble and repairing share some stuff, so the fallthrough is intended!
case DO_AERIAL_SELF_REPAIR_END:
if (_gotMimironHardMode)
if (!me->HasAura(SPELL_EMERGENCY_MODE))
DoCast(me, SPELL_EMERGENCY_MODE, true);
_phase = PHASE_AERIAL_ASSEMBLED__GLOBAL_4;
_events.SetPhase(_phase);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1);
me->SetReactState(REACT_AGGRESSIVE);
me->SetStandState(UNIT_STAND_STATE_STAND);
_events.RescheduleEvent(EVENT_PLASMA_BALL, 2*IN_MILLISECONDS);
break;
case DO_ENTER_ENRAGE:
DoCast(me, SPELL_BERSERK, true);
break;
default:
break;
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim() || _phase == PHASE_IDLE)
return;
_events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_PLASMA_BALL:
if (_phase == PHASE_AERIAL_SOLO__GLOBAL_3 && me->GetVictim())
{
float x = me->GetVictim()->GetPositionX();
float y = me->GetVictim()->GetPositionY();
float z = me->GetVictim()->GetPositionZ();
if (me->IsWithinDist3d(x, y, z, 30.0f))
{
me->GetMotionMaster()->Initialize();
DoCastVictim(SPELL_PLASMA_BALL);
}
else
me->GetMotionMaster()->MovePoint(0, x, y, 380.04f);
}
else if (_phase == PHASE_AERIAL_ASSEMBLED__GLOBAL_4 && me->GetVictim())
{
if (me->GetVictim()->IsWithinDist3d(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), 30.0f))
DoCastVictim(SPELL_PLASMA_BALL);
else if (Unit* target = SelectTarget(SELECT_TARGET_NEAREST, 0, 0.0f, true))
DoCast(target, SPELL_PLASMA_BALL);
}
_events.RescheduleEvent(EVENT_PLASMA_BALL, urand(3000, 5000));
return;
case EVENT_REACTIVATE_AERIAL:
me->RemoveAurasDueToSpell(SPELL_MAGNETIC_CORE_VISUAL);
Position destination;
me->GetPosition(&destination);
destination.m_positionZ = 380.04f;
// FIXME find correct speed
me->GetMotionMaster()->MoveTakeoff(1, destination, 5.0f); // Check if MoveTakeoff is ok here, a flying unit should have a landing animation, but... just 4 the case
me->SetReactState(REACT_AGGRESSIVE);
return;
case EVENT_SUMMON_JUNK_BOT:
me->CastCustomSpell(SPELL_SUMMON_SCRAP_BOT_TRIGGER_JUNK_BOT, SPELLVALUE_MAX_TARGETS, 1, me, true);
_events.RescheduleEvent(EVENT_SUMMON_JUNK_BOT, urand(10 * IN_MILLISECONDS, 12 * IN_MILLISECONDS), 0, PHASE_AERIAL_SOLO__GLOBAL_3);
return;
case EVENT_SUMMON_ASSAULT_BOT:
me->CastCustomSpell(SPELL_SUMMON_SCRAP_BOT_TRIGGER_ASSAULT_BOT, SPELLVALUE_MAX_TARGETS, 1, me, true);
_events.RescheduleEvent(EVENT_SUMMON_ASSAULT_BOT, 30 * IN_MILLISECONDS, 0, PHASE_AERIAL_SOLO__GLOBAL_3);
return;
case EVENT_SUMMON_BOOM_BOT:
DoCast(me, SPELL_BOMB_BOT, true);
_events.RescheduleEvent(EVENT_SUMMON_BOOM_BOT, 15 * IN_MILLISECONDS, 0, PHASE_AERIAL_SOLO__GLOBAL_3);
return;
case EVENT_SUMMON_FIRE_BOT:
if (_gotMimironHardMode)
me->CastCustomSpell(SPELL_SUMMON_FIRE_BOT_TRIGGER, SPELLVALUE_MAX_TARGETS, 3, me, true);
_events.RescheduleEvent(EVENT_SUMMON_FIRE_BOT, 45 * IN_MILLISECONDS, 0, PHASE_AERIAL_SOLO__GLOBAL_3);
return;
default:
return;
}
}
}
void JustSummoned(Creature* summon) override
{
_summons.Summon(summon);
if (summon->GetEntry() == NPC_BOMB_BOT || summon->GetEntry() == NPC_FIRE_BOT)
return;
DoZoneInCombat(summon, 100.0f);
if (_gotMimironHardMode)
summon->CastSpell(summon, SPELL_EMERGENCY_MODE, true);
}
void DamageTaken(Unit* /*who*/, uint32& damage) override
{
if (damage >= me->GetHealth())
{
damage = 0;
if (_phase == PHASE_IDLE)
return;
me->InterruptNonMeleeSpells(true);
me->GetMotionMaster()->Clear(true);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1);
me->SetReactState(REACT_PASSIVE);
me->AttackStop();
me->RemoveAllAurasExceptType(SPELL_AURA_CONTROL_VEHICLE);
switch (_phase)
{
case PHASE_AERIAL_SOLO__GLOBAL_3:
me->SetHealth(me->GetMaxHealth());
if (Creature* Mimiron = ObjectAccessor::GetCreature(*me, instance->GetData64(BOSS_MIMIRON)))
Mimiron->AI()->DoAction(DO_ACTIVATE_V0L7R0N);
break;
case PHASE_AERIAL_ASSEMBLED__GLOBAL_4:
if (Creature* Mimiron = ObjectAccessor::GetCreature(*me, instance->GetData64(BOSS_MIMIRON)))
Mimiron->AI()->DoAction(DO_AERIAL_SELF_REPAIR_START);
DoCast(me, SPELL_SELF_REPAIR);
break;
default:
break;
}
_events.Reset();
_phase = PHASE_IDLE;
_events.SetPhase(PHASE_IDLE);
}
}
private:
Phases _phase;
EventMap _events;
SummonList _summons;
InstanceScript* instance;
bool _gotMimironHardMode;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<boss_aerial_unitAI>(creature);
}
};
class npc_magnetic_core : public CreatureScript
{
public:
npc_magnetic_core() : CreatureScript("npc_magnetic_core") { }
struct npc_magnetic_coreAI : public ScriptedAI
{
npc_magnetic_coreAI(Creature* creature) : ScriptedAI(creature)
{
SetCombatMovement(false);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED);
me->DespawnOrUnsummon(21*IN_MILLISECONDS);
if (Creature* AerialUnit = me->FindNearestCreature(NPC_AERIAL_COMMAND_UNIT, 100.0f, true))
{
AerialUnit->AI()->DoAction(DO_DISABLE_AERIAL); // Causes the NPC to land
// me->GetMotionMaster()->MoveFall();
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_magnetic_coreAI>(creature);
}
};
class npc_junk_bot : public CreatureScript
{
public:
npc_junk_bot() : CreatureScript("npc_junk_bot") { }
struct npc_junk_botAI : public ScriptedAI
{
npc_junk_botAI(Creature* creature) : ScriptedAI(creature) { }
void IsSummonedBy(Unit* summoner) override
{
if (me->GetInstanceScript()->GetBossState(BOSS_MIMIRON) != IN_PROGRESS)
{
me->DespawnOrUnsummon();
return;
}
DoCast(me, 65256, true); // Self Stun (1 sec)
if (Creature* aerialCommandUnit = me->FindNearestCreature(NPC_AERIAL_COMMAND_UNIT, 100.0f, true))
aerialCommandUnit->AI()->JustSummoned(me);
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_junk_botAI>(creature);
}
};
class npc_assault_bot : public CreatureScript
{
public:
npc_assault_bot() : CreatureScript("npc_assault_bot") { }
struct npc_assault_botAI : public ScriptedAI
{
npc_assault_botAI(Creature* creature) : ScriptedAI(creature) { }
void Reset() override
{
_fieldTimer = urand(4*IN_MILLISECONDS, 6*IN_MILLISECONDS);
}
void IsSummonedBy(Unit* summoner) override
{
if (me->GetInstanceScript()->GetBossState(BOSS_MIMIRON) != IN_PROGRESS)
{
me->DespawnOrUnsummon();
return;
}
DoCast(me, 65256, true); // Self Stun (1 sec)
if (Creature* aerialCommandUnit = me->FindNearestCreature(NPC_AERIAL_COMMAND_UNIT, 100.0f, true))
aerialCommandUnit->AI()->JustSummoned(me);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (_fieldTimer <= diff)
{
DoCastVictim(SPELL_MAGNETIC_FIELD);
_fieldTimer = urand(15*IN_MILLISECONDS, 20*IN_MILLISECONDS);
}
else
_fieldTimer -= diff;
DoMeleeAttackIfReady();
}
void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override
{
// Achievement Not-So-Friendly Fire
if (spell->Id == SPELL_ROCKET_STRIKE_DMG)
if (Player* player = me->SelectNearestPlayer(100.0f))
player->CastSpell(player, SPELL_NOT_SO_FRIENDLY_FIRE, true);
}
private:
uint32 _fieldTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_assault_botAI>(creature);
}
};
class npc_emergency_bot : public CreatureScript
{
public:
npc_emergency_bot() : CreatureScript("npc_emergency_bot") { }
struct npc_emergency_botAI : public ScriptedAI
{
npc_emergency_botAI(Creature* creature) : ScriptedAI(creature) { }
void InitializeAI() override
{
me->SetFaction(14);
me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true);
me->ApplySpellImmune(0, IMMUNITY_ID, SPELL_DEATH_GRIP, true);
me->SetReactState(REACT_PASSIVE);
Reset();
}
void Reset() override
{
me->GetMotionMaster()->MoveRandom(15);
_sprayTimer = 5*IN_MILLISECONDS;
if (Is25ManRaid())
DoCast(me, SPELL_DEAFENING_SIREN, true);
}
void IsSummonedBy(Unit* summoner) override
{
if (me->GetInstanceScript()->GetBossState(BOSS_MIMIRON) != IN_PROGRESS)
{
me->DespawnOrUnsummon();
return;
}
DoCast(me, 65256, true); // Self Stun (1 sec)
if (Creature* aerialCommandUnit = me->FindNearestCreature(NPC_AERIAL_COMMAND_UNIT, 100.0f, true))
aerialCommandUnit->AI()->JustSummoned(me);
}
void UpdateAI(uint32 diff) override
{
if (_sprayTimer <= diff)
{
DoCast(SPELL_WATER_SPRAY);
_sprayTimer = 10*IN_MILLISECONDS;
}
else
_sprayTimer -= diff;
}
private:
uint32 _sprayTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_emergency_botAI>(creature);
}
};
class npc_mimiron_bomb_bot : public CreatureScript
{
public:
npc_mimiron_bomb_bot() : CreatureScript("npc_mimiron_bomb_bot") { }
struct npc_mimiron_bomb_botAI : public ScriptedAI
{
npc_mimiron_bomb_botAI(Creature* creature) : ScriptedAI(creature) { }
void InitializeAI() override
{
me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, true);
me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, true);
me->SetReactState(REACT_PASSIVE);
_despawn = false;
}
void IsSummonedBy(Unit* summoner) override
{
if (me->GetInstanceScript()->GetBossState(BOSS_MIMIRON) != IN_PROGRESS)
{
me->DespawnOrUnsummon();
return;
}
if (Creature* aerialCommandUnit = me->FindNearestCreature(NPC_AERIAL_COMMAND_UNIT, 100.0f, true))
aerialCommandUnit->AI()->JustSummoned(me);
me->m_Events.Schedule(3000, [this]()
{
Position pos;
pos.Relocate(me);
me->UpdateAllowedPositionZ(pos.GetPositionX(), pos.GetPositionY(), pos.m_positionZ, 0, 100.0f);
me->UpdatePosition(pos);
DoCast(me, SPELL_BOOM_BOT, true);
DoZoneInCombat(me, 100.0f);
if (Unit* target = me->FindNearestPlayer(100.0f))
{
AttackStart(target);
me->AddThreat(target, 100000000.0f);
me->GetMotionMaster()->MoveFollow(target, 0.01f, 0.0f);
}
});
}
void SpellHitTarget(Unit* target, SpellInfo const* spell) override
{
if (!target || !spell)
return;
if (target->ToPlayer())
if (spell->Id == SPELL_BOOM_BOT || spell->Id == SPELL_BOOM_BOT_PERIODIC)
if (InstanceScript* instance = me->GetInstanceScript())
if (Creature* mimiron = ObjectAccessor::GetCreature(*me, instance->GetData64(BOSS_MIMIRON)))
mimiron->AI()->DoAction(DATA_AVOIDED_BOOM_BOT_EXPLOSION);
}
void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override
{
if (spell->Id == SPELL_BOOM_BOT_PERIODIC)
me->DespawnOrUnsummon(1*IN_MILLISECONDS);
}
void JustDied(Unit* /*killer*/)
{
DoCast(me, SPELL_BOOM_BOT, true);
}
void UpdateAI(uint32 /*diff*/) override
{
if (!UpdateVictim())
return;
// suicide has procflag PROC_FLAG_DONE_MELEE_AUTO_ATTACK, they have to melee, even tho the spell is delayed if the npc misses
DoMeleeAttackIfReady();
}
private:
bool _despawn;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_mimiron_bomb_botAI>(creature);
}
};
class go_not_push_button : public GameObjectScript
{
public:
go_not_push_button() : GameObjectScript("go_mimiron_hard_mode_activator") { }
bool OnGossipHello(Player* player, GameObject* go) override
{
if (InstanceScript* instance = go->GetInstanceScript())
{
if (go->HasFlag(GAMEOBJECT_FIELD_FLAGS, GO_FLAG_IN_USE))
return false;
if ((instance->GetBossState(BOSS_MIMIRON) != IN_PROGRESS && instance->GetBossState(BOSS_MIMIRON) != DONE) && player)
if (Creature* mimiron = ObjectAccessor::GetCreature((*player), instance->GetData64(BOSS_MIMIRON)))
{
mimiron->AI()->DoAction(DO_ACTIVATE_HARD_MODE);
go->UseDoorOrButton();
return true;
}
}
return false;
}
};
class npc_mimiron_flame_trigger : public CreatureScript
{
public:
npc_mimiron_flame_trigger() : CreatureScript("npc_mimiron_flame_trigger") { }
struct npc_mimiron_flame_triggerAI : public ScriptedAI
{
npc_mimiron_flame_triggerAI(Creature* creature) : ScriptedAI(creature) { }
void InitializeAI() override
{
instance = me->GetInstanceScript();
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_NPC);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED);
me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, true);
me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, true);
Reset();
}
void Reset() override
{
_flameTimer = 2*IN_MILLISECONDS;
me->SetInCombatWithZone();
}
void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override
{
switch (spell->Id)
{
case SPELL_FLAME_SUPPRESSANT_MK:
case SPELL_FLAME_SUPPRESSANT_VX001:
case SPELL_FROST_BOMB_EXPLOSION_10:
case SPELL_FROST_BOMB_EXPLOSION_25:
case SPELL_WATER_SPRAY:
_flameTimer = 1*IN_MILLISECONDS;
me->DespawnOrUnsummon(0.5*IN_MILLISECONDS);
break;
default:
break;
}
}
void JustSummoned(Creature* /*summon*/) override
{
if (Creature* mimiron = ObjectAccessor::GetCreature(*me, instance ? instance->GetData64(BOSS_MIMIRON) : 0))
mimiron->AI()->DoAction(DO_INCREASE_FLAME_COUNT);
}
void UpdateAI(uint32 diff) override
{
if (_flameTimer <= diff)
{
// check if flame cap is reached
if (Creature* mimiron = ObjectAccessor::GetCreature(*me, instance ? instance->GetData64(BOSS_MIMIRON) : 0))
if (mimiron->AI()->GetData(DATA_FLAME_COUNT) >= FLAME_CAP)
{
me->DespawnOrUnsummon();
return;
}
DoZoneInCombat(me, 100.0f);
if (Player* nearest = me->SelectNearestPlayer(100.0f))
{
me->GetMotionMaster()->Clear();
me->GetMotionMaster()->MoveFollow(nearest, 0.0f, 0.0f);
}
if (GetClosestCreatureWithEntry(me, NPC_FLAME_SPREAD, 1.0f))
_flameTimer = 1*IN_MILLISECONDS;
else
{
me->SummonCreature(NPC_FLAME_SPREAD, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ());
_flameTimer = 4*IN_MILLISECONDS;
}
}
else
_flameTimer -= diff;
}
private:
InstanceScript* instance;
uint32 _flameTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_mimiron_flame_triggerAI>(creature);
}
};
class npc_mimiron_flame_spread : public CreatureScript
{
public:
npc_mimiron_flame_spread() : CreatureScript("npc_mimiron_flame_spread") { }
struct npc_mimiron_flame_spreadAI : public ScriptedAI
{
npc_mimiron_flame_spreadAI(Creature* creature) : ScriptedAI(creature) { }
void InitializeAI() override
{
instance = me->GetInstanceScript();
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED | UNIT_FLAG_DISABLE_MOVE);
me->SetReactState(REACT_PASSIVE);
Reset();
}
void Reset() override
{
DoCast(me, SPELL_FLAME, true);
}
void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override
{
switch (spell->Id)
{
case SPELL_FLAME_SUPPRESSANT_MK:
case SPELL_FLAME_SUPPRESSANT_VX001:
case SPELL_FROST_BOMB_EXPLOSION_10:
case SPELL_FROST_BOMB_EXPLOSION_25:
case SPELL_WATER_SPRAY:
if (Creature* mimiron = ObjectAccessor::GetCreature(*me, instance ? instance->GetData64(BOSS_MIMIRON) : 0))
mimiron->AI()->DoAction(DO_DECREASE_FLAME_COUNT);
me->DespawnOrUnsummon(0.5*IN_MILLISECONDS);
break;
default:
break;
}
}
void UpdateAI(uint32 /*diff*/) override
{
if (instance && instance->GetBossState(BOSS_MIMIRON) != IN_PROGRESS)
me->DespawnOrUnsummon();
}
private:
InstanceScript* instance;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_mimiron_flame_spreadAI>(creature);
}
};
class npc_frost_bomb : public CreatureScript
{
public:
npc_frost_bomb() : CreatureScript("npc_frost_bomb") { }
struct npc_frost_bombAI : public ScriptedAI
{
npc_frost_bombAI(Creature* creature) : ScriptedAI(creature)
{
SetCombatMovement(false);
}
void InitializeAI() override
{
me->SetReactState(REACT_PASSIVE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED);
Reset();
}
void Reset() override
{
DoCast(me, SPELL_FROST_BOMB_VISUAL, true);
_frostTimer = 10*IN_MILLISECONDS;
}
void UpdateAI(uint32 diff) override
{
if (_frostTimer <= diff)
{
DoCast(me, RAID_MODE(SPELL_FROST_BOMB_EXPLOSION_10, SPELL_FROST_BOMB_EXPLOSION_25), true);
_frostTimer = 10*IN_MILLISECONDS;
}
else
_frostTimer -= diff;
}
private:
uint32 _frostTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_frost_bombAI>(creature);
}
};
class npc_mimiron_db_target : public CreatureScript
{
public:
npc_mimiron_db_target() : CreatureScript("npc_mimiron_db_target") { }
struct npc_mimiron_db_targetAI : public PassiveAI
{
npc_mimiron_db_targetAI(Creature* creature) : PassiveAI(creature) { }
void DamageTaken(Unit* /*who*/, uint32& damage) override
{
damage = 0;
}
void EnterCombat(Unit* /*who*/) override { }
void EnterEvadeMode() override { }
void UpdateAI(uint32 /*diff*/) override { }
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_mimiron_db_targetAI>(creature);
}
};
class spell_frost_bomb : public SpellScriptLoader
{
public:
spell_frost_bomb() : SpellScriptLoader("spell_frost_bomb") { }
class spell_frost_bomb_SpellScript : public SpellScript
{
PrepareSpellScript(spell_frost_bomb_SpellScript);
void FilterTargets(std::list<WorldObject*>& targets)
{
if (WorldObject* _target = Trinity::Containers::SelectRandomContainerElement(targets))
{
targets.clear();
targets.push_back(_target);
}
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_frost_bomb_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENTRY);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_frost_bomb_SpellScript();
}
};
class spell_rocket_strike : public SpellScriptLoader
{
public:
spell_rocket_strike() : SpellScriptLoader("spell_rocket_strike") { }
class spell_rocket_strike_SpellScript : public SpellScript
{
PrepareSpellScript(spell_rocket_strike_SpellScript);
void HandleHitTarget(SpellEffIndex /*effIndex*/)
{
if (GetHitPlayer())
if (Unit* caster = GetCaster())
if (InstanceScript* instance = caster->GetInstanceScript())
if (Creature* mimiron = ObjectAccessor::GetCreature(*caster, instance->GetData64(BOSS_MIMIRON)))
mimiron->AI()->DoAction(DATA_AVOIDED_ROCKET_STRIKES);
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_rocket_strike_SpellScript::HandleHitTarget, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_rocket_strike_SpellScript();
}
};
class spell_p3wx2_laser_barrage : public SpellScriptLoader
{
public:
spell_p3wx2_laser_barrage() : SpellScriptLoader("spell_p3wx2_laser_barrage") { }
class spell_p3wx2_laser_barrage_SpellScript : public SpellScript
{
PrepareSpellScript(spell_p3wx2_laser_barrage_SpellScript);
void SelectDest(SpellDestination& dest)
{
if (Unit* caster = GetCaster())
dest._position.m_positionZ = caster->GetPositionZ();
}
void Register() override
{
OnDestinationTargetSelect += SpellDestinationTargetSelectFn(spell_p3wx2_laser_barrage_SpellScript::SelectDest, EFFECT_0, TARGET_DEST_CASTER_FRONT);
OnDestinationTargetSelect += SpellDestinationTargetSelectFn(spell_p3wx2_laser_barrage_SpellScript::SelectDest, EFFECT_1, m_scriptSpellId == 63297 ? TARGET_DEST_DEST_LEFT : TARGET_DEST_DEST_RIGHT);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_p3wx2_laser_barrage_SpellScript();
}
};
class achievement_set_up_us_the_bomb__proximity_mines : public AchievementCriteriaScript
{
public:
achievement_set_up_us_the_bomb__proximity_mines(const char* name) : AchievementCriteriaScript(name) { }
bool OnCheck(Player* player, Unit* /*target*/)
{
if (player)
if (InstanceScript* instance = player->GetInstanceScript())
if (Creature* mimiron = ObjectAccessor::GetCreature(*player, instance->GetData64(BOSS_MIMIRON)))
return (mimiron->AI()->GetData(DATA_AVOIDED_PROXIMITY_MINES));
return false;
}
};
class achievement_set_up_us_the_bomb__rocket_strikes : public AchievementCriteriaScript
{
public:
achievement_set_up_us_the_bomb__rocket_strikes(const char* name) : AchievementCriteriaScript(name) { }
bool OnCheck(Player* player, Unit* /*target*/)
{
if (player)
if (InstanceScript* instance = player->GetInstanceScript())
if (Creature* mimiron = ObjectAccessor::GetCreature(*player, instance->GetData64(BOSS_MIMIRON)))
return (mimiron->AI()->GetData(DATA_AVOIDED_ROCKET_STRIKES));
return false;
}
};
class achievement_set_up_us_the_bomb__boombot_explosion : public AchievementCriteriaScript
{
public:
achievement_set_up_us_the_bomb__boombot_explosion(const char* name) : AchievementCriteriaScript(name) { }
bool OnCheck(Player* player, Unit* /*target*/)
{
if (player)
if (InstanceScript* instance = player->GetInstanceScript())
if (Creature* mimiron = ObjectAccessor::GetCreature(*player, instance->GetData64(BOSS_MIMIRON)))
return (mimiron->AI()->GetData(DATA_AVOIDED_BOOM_BOT_EXPLOSION));
return false;
}
};
void AddSC_boss_mimiron()
{
new boss_mimiron();
new boss_leviathan_mk();
new boss_leviathan_mk_turret();
new boss_vx_001();
new boss_aerial_unit();
new npc_proximity_mine();
new npc_rocket_strike();
new npc_magnetic_core();
new npc_junk_bot();
new npc_assault_bot();
new npc_emergency_bot();
new npc_mimiron_bomb_bot();
new npc_mimiron_flame_trigger();
new npc_mimiron_flame_spread();
new npc_frost_bomb();
new npc_mimiron_db_target();
new spell_rapid_burst();
new spell_proximity_mines();
new spell_frost_bomb();
new spell_rocket_strike();
new spell_p3wx2_laser_barrage();
new go_not_push_button();
}
| 411 | 0.986919 | 1 | 0.986919 | game-dev | MEDIA | 0.996502 | game-dev | 0.527886 | 1 | 0.527886 |
liushijiegame/Fairygui-hybridCLR-YooAsset | 1,504 | Assets/Scripts/ThirdParty/UniFramework/UniTask/Runtime/Linq/Throw.cs | using Cysharp.Threading.Tasks.Internal;
using System;
using System.Threading;
namespace Cysharp.Threading.Tasks.Linq
{
public static partial class UniTaskAsyncEnumerable
{
public static IUniTaskAsyncEnumerable<TValue> Throw<TValue>(Exception exception)
{
return new Throw<TValue>(exception);
}
}
internal class Throw<TValue> : IUniTaskAsyncEnumerable<TValue>
{
readonly Exception exception;
public Throw(Exception exception)
{
this.exception = exception;
}
public IUniTaskAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
return new _Throw(exception, cancellationToken);
}
class _Throw : IUniTaskAsyncEnumerator<TValue>
{
readonly Exception exception;
CancellationToken cancellationToken;
public _Throw(Exception exception, CancellationToken cancellationToken)
{
this.exception = exception;
this.cancellationToken = cancellationToken;
}
public TValue Current => default;
public UniTask<bool> MoveNextAsync()
{
cancellationToken.ThrowIfCancellationRequested();
return UniTask.FromException<bool>(exception);
}
public UniTask DisposeAsync()
{
return default;
}
}
}
} | 411 | 0.801645 | 1 | 0.801645 | game-dev | MEDIA | 0.390442 | game-dev | 0.570119 | 1 | 0.570119 |
SinlessDevil/TestToolKit | 3,151 | Assets/Plugins/Zenject/Source/Providers/IProviderExtensions.cs | using System;
using System.Collections.Generic;
using ModestTree;
using Zenject.Internal;
namespace Zenject
{
public static class IProviderExtensions
{
static readonly List<TypeValuePair> EmptyArgList = new List<TypeValuePair>();
public static void GetAllInstancesWithInjectSplit(
this IProvider creator, InjectContext context, out Action injectAction, List<object> buffer)
{
creator.GetAllInstancesWithInjectSplit(
context, EmptyArgList, out injectAction, buffer);
}
public static void GetAllInstances(
this IProvider creator, InjectContext context, List<object> buffer)
{
creator.GetAllInstances(context, EmptyArgList, buffer);
}
public static void GetAllInstances(
this IProvider creator, InjectContext context, List<TypeValuePair> args, List<object> buffer)
{
Assert.IsNotNull(context);
Action injectAction;
creator.GetAllInstancesWithInjectSplit(context, args, out injectAction, buffer);
if (injectAction != null)
{
injectAction.Invoke();
}
}
public static object TryGetInstance(
this IProvider creator, InjectContext context)
{
return creator.TryGetInstance(context, EmptyArgList);
}
public static object TryGetInstance(
this IProvider creator, InjectContext context, List<TypeValuePair> args)
{
var allInstances = ZenPools.SpawnList<object>();
try
{
creator.GetAllInstances(context, args, allInstances);
if (allInstances.Count == 0)
{
return null;
}
Assert.That(allInstances.Count == 1,
"Provider returned multiple instances when one or zero was expected");
return allInstances[0];
}
finally
{
ZenPools.DespawnList(allInstances);
}
}
public static object GetInstance(
this IProvider creator, InjectContext context)
{
return creator.GetInstance(context, EmptyArgList);
}
public static object GetInstance(
this IProvider creator, InjectContext context, List<TypeValuePair> args)
{
var allInstances = ZenPools.SpawnList<object>();
try
{
creator.GetAllInstances(context, args, allInstances);
Assert.That(allInstances.Count > 0,
"Provider returned zero instances when one was expected when looking up type '{0}'", context.MemberType);
Assert.That(allInstances.Count == 1,
"Provider returned multiple instances when only one was expected when looking up type '{0}'", context.MemberType);
return allInstances[0];
}
finally
{
ZenPools.DespawnList(allInstances);
}
}
}
}
| 411 | 0.771999 | 1 | 0.771999 | game-dev | MEDIA | 0.519737 | game-dev,web-backend | 0.665065 | 1 | 0.665065 |
Hannah-Sten/TeXiFy-IDEA | 2,336 | src/nl/hannahsten/texifyidea/lang/commands/LatexColorDefinitionCommand.kt | package nl.hannahsten.texifyidea.lang.commands
import nl.hannahsten.texifyidea.lang.LatexPackage
import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.COLOR
import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.XCOLOR
/**
* @author Hannah Schellekens
*/
enum class LatexColorDefinitionCommand(
override val command: String,
override vararg val arguments: Argument = emptyArray(),
override val dependency: LatexPackage = LatexPackage.DEFAULT,
override val display: String? = null,
override val isMathMode: Boolean = false,
val collapse: Boolean = false
) : LatexCommand {
DEFINECOLOR("definecolor", "type".asOptional(), "name".asRequired(), "model-list".asRequired(), "spec-list".asRequired(), dependency = COLOR),
PROVIDECOLOR("providecolor", "type".asOptional(), "name".asRequired(), "model-list".asRequired(), "spec-list".asRequired(), dependency = XCOLOR),
COLORLET("colorlet", "type".asOptional(), "name".asRequired(), "num model".asOptional(), "color".asRequired(), dependency = XCOLOR),
DEFINECOLORSET("definecolorset", "type".asOptional(), "model-list".asRequired(), "head".asRequired(), "tail".asRequired(), "set spec".asRequired(), dependency = XCOLOR),
PROVIDECOLORSET("providecolorset", "type".asOptional(), "model-list".asRequired(), "head".asRequired(), "tail".asRequired(), "set spec".asRequired(), dependency = XCOLOR),
PREPARECOLOR("preparecolor", "type".asOptional(), "name".asRequired(), "model-list".asRequired(), "spec-list".asRequired(), dependency = XCOLOR),
PREPARECOLORSET("preparecolorset", "type".asOptional(), "model-list".asRequired(), "head".asRequired(), "tail".asRequired(), "set spec".asRequired(), dependency = XCOLOR),
DEFINE_NAMED_COLOR("DefineNamedColor", "type".asRequired(), "name".asRequired(), "model-list".asRequired(), "spec-list".asRequired(), dependency = COLOR),
DEFINECOLORS("definecolors", "id-list".asRequired(), dependency = XCOLOR),
PROVIDECOLORS("providecolors", "id-list".asRequired(), dependency = XCOLOR),
DEFINECOLORSERIES("definecolorseries", "name".asRequired(), "core model".asRequired(), "method".asRequired(), "b-model".asOptional(), "b-spec".asRequired(), "s-model".asRequired(), "s-spec".asRequired(), dependency = XCOLOR),
;
override val identifier: String
get() = name
} | 411 | 0.725565 | 1 | 0.725565 | game-dev | MEDIA | 0.27932 | game-dev | 0.580652 | 1 | 0.580652 |
omnetpp/omnetpp | 4,184 | src/sim/parsim/clinkdelaylookahead.cc | //=========================================================================
// CLINKDELAYLOOKAHEAD.CC - part of
//
// OMNeT++/OMNEST
// Discrete System Simulation in C++
//
//=========================================================================
/*--------------------------------------------------------------*
Copyright (C) 1992-2017 Andras Varga
Copyright (C) 2006-2017 OpenSim Ltd.
This file is distributed WITHOUT ANY WARRANTY. See the file
`license' for details on this and other legal matters.
*--------------------------------------------------------------*/
#include "omnetpp/csimulation.h"
#include "omnetpp/cmessage.h"
#include "omnetpp/cenvir.h"
#include "omnetpp/cparsimcomm.h"
#include "omnetpp/cdataratechannel.h"
#include "omnetpp/globals.h"
#include "omnetpp/regmacros.h"
#include "clinkdelaylookahead.h"
#include "cnullmessageprot.h"
#include "cparsimpartition.h"
#include "cplaceholdermod.h"
#include "cproxygate.h"
namespace omnetpp {
Register_Class(cLinkDelayLookahead);
cLinkDelayLookahead::~cLinkDelayLookahead()
{
delete[] segInfo;
}
void cLinkDelayLookahead::configure(cSimulation *simulation, cConfiguration *cfg, cParsimPartition *partition)
{
this->simulation = simulation;
this->partition = partition;
}
void cLinkDelayLookahead::startRun()
{
EV << "starting Link Delay Lookahead...\n";
delete[] segInfo;
cParsimCommunications *comm = partition->getCommunications();
numSeg = comm->getNumPartitions();
segInfo = new PartitionInfo[numSeg];
int myProcId = comm->getProcId();
// temporarily initialize everything to zero.
for (int i = 0; i < numSeg; i++)
segInfo[i].minDelay = -1;
// fill in minDelays
EV << " calculating minimum link delays...\n";
for (int modId = 0; modId <= simulation->getLastComponentId(); modId++) {
cPlaceholderModule *mod = dynamic_cast<cPlaceholderModule *>(simulation->getModule(modId));
if (mod) {
for (cModule::GateIterator it(mod); !it.end(); ++it) {
// if this is a properly connected proxygate, process it
cGate *g = *it;
cProxyGate *pg = dynamic_cast<cProxyGate *>(g);
if (pg && !pg->getPathStartGate()->getOwnerModule()->isPlaceholder()) {
ASSERT(pg->getRemoteProcId() >= 0);
// check we have a delay on this link (it gives us lookahead)
simtime_t linkDelay = collectPathDelay(pg);
if (linkDelay <= 0.0)
throw cRuntimeError("cLinkDelayLookahead: Zero delay on path that ends at proxy gate '%s', no lookahead for parallel simulation",
pg->getFullPath().c_str());
// store
int procId = pg->getRemoteProcId();
if (segInfo[procId].minDelay == -1 || segInfo[procId].minDelay > linkDelay)
segInfo[procId].minDelay = linkDelay;
}
}
}
}
// if two partitions are not connected, the lookeahead is "infinity"
for (int i = 0; i < numSeg; i++)
if (i != myProcId && segInfo[i].minDelay == -1)
segInfo[i].minDelay = SIMTIME_MAX;
for (int i = 0; i < numSeg; i++)
if (i != myProcId)
EV << " lookahead to procId=" << i << " is " << segInfo[i].minDelay << "\n";
EV << " setup done.\n";
}
simtime_t cLinkDelayLookahead::collectPathDelay(cGate *g)
{
simtime_t sum = 0;
while (g->getPreviousGate()) {
cGate *prevg = g->getPreviousGate();
cChannel *chan = prevg->getChannel();
simtime_t delay = (chan && chan->hasPar("delay")) ? chan->par("delay").doubleValue() : 0.0;
sum += delay;
g = prevg;
}
return sum;
}
void cLinkDelayLookahead::endRun()
{
delete[] segInfo;
segInfo = nullptr;
}
simtime_t cLinkDelayLookahead::getCurrentLookahead(cMessage *, int procId, void *)
{
return segInfo[procId].minDelay;
}
simtime_t cLinkDelayLookahead::getCurrentLookahead(int procId)
{
return segInfo[procId].minDelay;
}
} // namespace omnetpp
| 411 | 0.87959 | 1 | 0.87959 | game-dev | MEDIA | 0.388792 | game-dev | 0.953871 | 1 | 0.953871 |
MathOnco/Lenia-in-HAL | 8,235 | HAL/Tools/PhylogenyTracker/Genome.java | package HAL.Tools.PhylogenyTracker;
import HAL.Interfaces.GetGenomeAttrs;
import java.util.ArrayList;
import java.util.Iterator;
//TODO: add sibling and children for-loop iteration, consider adding iter-living as well
/**
* the genome class is useful for keeping track of shared genetic information and phylogenies. extend this class to add any genetic/inherited information that needs to be tracked. an instance of the Genome class should be created once for every new mutation, and all agents with the same genome should share the same class instance as a member variable
*/
public class Genome<T extends Genome> implements Iterable<T>{
long pop;
T parent;
T firstChild;
T nextSibling;
T prevSibling;
T next;
T prev;
int id;
final PhylogenyTrackerInternal<T> myTracker;
/**
* call this with the parent set to null to create a new phylogeny. the removeLeaves option specifies whether the phylogeny should continue to store dead leaves (lineages with no active individuals). should also be called whenever a new clone is created, along with IncPop to add one individual to the new clone.
*/
public Genome(T parent, boolean removeLeaves){
if(parent!=null) {
myTracker=parent.myTracker;
parent.NewMutantGenome(this);
this.parent=parent;
}
else{
myTracker=new PhylogenyTrackerInternal(this,removeLeaves);
}
this.id = myTracker.nGenomesEver;
myTracker.nGenomesEver++;
myTracker.nLivingGenomes++;
myTracker.nTreeGenomes++;
this.pop = 0;
}
public Genome(T parent){
if(parent!=null) {
myTracker=parent.myTracker;
parent.NewMutantGenome(this);
this.parent=parent;
}
else{
myTracker=new PhylogenyTrackerInternal(this,true);
}
this.id = myTracker.nGenomesEver;
myTracker.nGenomesEver++;
myTracker.nLivingGenomes++;
myTracker.nTreeGenomes++;
this.pop = 0;
}
/**
* gets the ID of the genome, which indicates the order in which it arose
*/
public int GetId() {
return id;
}
/**
* returns the current active population that shares this genome
*/
public long GetPop() {
return pop;
}
/**
* returns the parent genome that was mutated to give rise to this genome
*/
public T GetParent() {
return parent;
}
/**
* sets the active population size for this genome to a specific value.
*/
public void SetPop(long pop) {
if (myTracker == null) {
throw new IllegalStateException("Genome must be part of tracker before pop can be changed!");
}
if (pop < 0) {
throw new IllegalStateException("Can't decrease pop below 0!");
}
//if (this.pop <= 0) {
// throw new IllegalStateException("Can't alter dead Genome!");
//}
myTracker.totalPop += pop - this.pop;
this.pop = pop;
if (pop == 0) {
KillGenome();
}
}
/**
* adds an individual to the genome population, should be called as part of the initialization of all agents that share this genome.
*/
public void IncPop() {
SetPop(this.pop + 1);
}
/**
* removes an individual from the genome population, should be called as part of the disposal of all agents that share this genome.
*/
public void DecPop() {
SetPop(this.pop - 1);
}
/**
* runs the GenomeFunction argument on every descendant of this genome
*/
public void Traverse(GenomeFn GenomeFunction) {
GenomeFunction.GenomeFn(this);
T child = firstChild;
while (child != null) {
child.Traverse(GenomeFunction);
child = (T)child.nextSibling;
}
}
/**
* runs the GenomeFunction argument on every descendant of this genome, will pass as argument the lineage from this genome to the descendant
*/
public void TraverseWithLineage(ArrayList<T> lineageStorage, GenomeLineageFn GenomeFunction) {
lineageStorage.add((T) this);
GenomeFunction.GenomeLineageFn(lineageStorage);
T child = firstChild;
while (child != null) {
child.TraverseWithLineage(lineageStorage, GenomeFunction);
lineageStorage.remove(lineageStorage.size() - 1);
child = (T)child.nextSibling;
}
}
/**
* adds all direct descendants of the genome to the arraylist
*/
public void GetChildren(ArrayList<T> childrenStorage) {
T child = firstChild;
while (child != null) {
childrenStorage.add((T)child);
child = (T)child.nextSibling;
}
}
/**
* adds all ancestors of the genome ot the arraylist
*/
public void GetLineage(ArrayList<T> lineageStorage) {
T parent = (T)this;
while (parent != null) {
lineageStorage.add((T)parent);
parent = (T)parent.parent;
}
}
/**
* returns the total number of genomes that have ever existed in the phylogeny
*/
public int GetNumGenomes() {
return myTracker.nGenomesEver;
}
/**
* returns the number of currently active unique genomes
*/
public int GetNumLivingGenomes() {
return myTracker.nLivingGenomes;
}
/**
* returns the number of genomes that exist in the phylogeny (not counting removed leaves)
*/
public int GetNumTreeGenomes() {
return myTracker.nTreeGenomes;
}
/**
* returns the current population size that shares this genome
*/
public long Pop() {
return pop;
}
/**
* returns the total population of all living members of the phylogeny
*/
public long PhylogenyPop(){
return myTracker.totalPop;
}
/**
* gets the first genome that started the phylogeny
*/
public T GetRoot(){
return (T)myTracker.progenitor;
}
void NewMutantGenome(T child) {
T new_clone = child;
T current_right_child = this.firstChild;
this.firstChild = new_clone;
if (current_right_child != null) {
current_right_child.prevSibling = new_clone;
new_clone.nextSibling = current_right_child;
}
child.next = myTracker.listFirst;
if (myTracker.listFirst != null) {
myTracker.listFirst.prev = child;
}
myTracker.listFirst = child;
}
void RemoveGenomeFromTree() {
myTracker.nTreeGenomes--;
T my_left_sib = this.nextSibling;
T my_right_sib = this.prevSibling;
T parent = this.parent;
if (parent!=null&&this == parent.firstChild) {
// clone is parent's most recent child
parent.firstChild = my_left_sib;
if (my_left_sib == null && parent.pop == 0) {
//recursively remove dead branches
parent.RemoveGenomeFromTree();
}
}
if (my_right_sib != null) {
my_right_sib.nextSibling = my_left_sib;
}
if (my_left_sib != null) {
my_left_sib.prevSibling = my_right_sib;
}
if (prev != null) {
prev.next = next;
}
if (next != null) {
next.prev = prev;
}
}
public void ResetCloneRecord(){
myTracker.ResetCloneRecord();
}
public void RecordClones(double timepoint){
myTracker.RecordClones(timepoint);
}
public void RecordClones(String timepointLabel){
myTracker.RecordClones(timepointLabel);
}
public void OutputClonesToCSV(String path, String[]AttrHeaders, GetGenomeAttrs<T> GetAttrs, int excludePopCutoff){
myTracker.OutputClonesToCSV(path, AttrHeaders, GetAttrs,excludePopCutoff);
}
void KillGenome() {
myTracker.nLivingGenomes--;
if (myTracker.removeEmptyLeaves && firstChild == null) {
this.RemoveGenomeFromTree();
}
}
@Override
public Iterator<T> iterator() {
return myTracker.iterator();
}
}
| 411 | 0.870909 | 1 | 0.870909 | game-dev | MEDIA | 0.237167 | game-dev | 0.876234 | 1 | 0.876234 |
tezos/tezos-mirror | 4,442 | src/rust_deps/wasmer-3.3.0/lib/sys-utils/tests/fd_mmap_memory.rs | // // TODO: make this a sensible test before merge NOTE: commented out since it's mostly here for demonstration purposes.
// use std::sync::Arc;
// use wasmer::{BaseTunables, Engine, Module, Store, Tunables};
// use wasmer_vm::VMMemory;
// use wasmer_wasix::{
// bin_factory::spawn_exec_module, virtual_fs::host_fs::File, BusSpawnedProcessJoin,
// PluggableRuntimeImplementation, WasiControlPlane, WasiEnv, WasiRuntime,
// WasiState,
// };
// use wasmer_sys_utils::memory::fd_memory::{VMOwnedMemory, VMSharedMemory};
// struct FdTunables {
// base: BaseTunables,
// }
// impl Tunables for FdTunables {
// fn memory_style(&self, memory: &wasmer::MemoryType) -> wasmer::vm::MemoryStyle {
// self.base.memory_style(memory)
// }
// fn table_style(&self, table: &wasmer::TableType) -> wasmer::vm::TableStyle {
// self.base.table_style(table)
// }
// fn create_host_memory(
// &self,
// ty: &wasmer::MemoryType,
// style: &wasmer::vm::MemoryStyle,
// ) -> Result<wasmer::vm::VMMemory, wasmer::MemoryError> {
// Ok(VMMemory(Box::new(VMOwnedMemory::new(ty, style)?)))
// }
// unsafe fn create_vm_memory(
// &self,
// ty: &wasmer::MemoryType,
// style: &wasmer::vm::MemoryStyle,
// vm_definition_location: std::ptr::NonNull<wasmer::vm::VMMemoryDefinition>,
// ) -> Result<wasmer::vm::VMMemory, wasmer::MemoryError> {
// if ty.shared {
// let mem = VMSharedMemory::from_definition(ty, style, vm_definition_location)?;
// Ok(VMMemory(Box::new(mem)))
// } else {
// let mem = VMOwnedMemory::from_definition(ty, style, vm_definition_location)?;
// Ok(VMMemory(Box::new(mem)))
// }
// }
// fn create_host_table(
// &self,
// ty: &wasmer::TableType,
// style: &wasmer::vm::TableStyle,
// ) -> Result<wasmer::vm::VMTable, String> {
// self.base.create_host_table(ty, style)
// }
// unsafe fn create_vm_table(
// &self,
// ty: &wasmer::TableType,
// style: &wasmer::vm::TableStyle,
// vm_definition_location: std::ptr::NonNull<wasmer::vm::VMTableDefinition>,
// ) -> Result<wasmer::vm::VMTable, String> {
// self.base.create_vm_table(ty, style, vm_definition_location)
// }
// }
// #[test]
// fn test_fd_mmap_memory() {
// tracing_subscriber::fmt()
// .with_level(true)
// .with_test_writer()
// .with_max_level(tracing::Level::TRACE)
// .try_init()
// .unwrap();
// let mut store = Store::default();
// // let engine = wasmer_compiler_cranelift::Cranelift::default();
// // let engine = Engine::default();
// let code = std::fs::read("/home/theduke/dev/github.com/wasmerio/wasix-integration-tests/rust/simple/target/wasm32-wasmer-wasi/debug/examples/spawn_threads_and_sleep.wasm").unwrap();
// let module = Module::new(&store, code).unwrap();
// let control_plane = WasiControlPlane::default();
// let rt = Arc::new(PluggableRuntimeImplementation::default());
// let wasi_env = WasiState::builder("fdmem")
// .args(["500", "100", "10"])
// .runtime(&rt)
// .finalize_with(&mut store, &control_plane)
// .unwrap();
// // let rt = wasi_env
// // .data(&store)
// // .runtime()
// // .as_any()
// // .unwrap()
// // .downcast_ref::<PluggableRuntimeImplementation>()
// // .unwrap()
// // .clone();
// // Generate an `ImportObject`.
// // let instance = wasmer_wasix::build_wasi_instance(&module, &mut wasi_env, &mut store).unwrap();
// let config = wasmer_wasix::wasmer_vbus::SpawnOptionsConfig {
// reuse: false,
// env: wasi_env.data(&store).clone(),
// remote_instance: None,
// access_token: None,
// };
// let rt2: Arc<dyn WasiRuntime + Send + Sync> = rt.clone();
// let bus = spawn_exec_module(module, store, config, &rt2).unwrap();
// dbg!("spawned, sleeping!");
// let _joiner = BusSpawnedProcessJoin::new(bus);
// std::thread::sleep(std::time::Duration::from_secs(100000000000000));
// // Let's call the `_start` function, which is our `main` function in Rust.
// // let start = instance.exports.get_function("_start").unwrap();
// // start.call(&mut store, &[]).unwrap();
// }
| 411 | 0.82327 | 1 | 0.82327 | game-dev | MEDIA | 0.214855 | game-dev | 0.573534 | 1 | 0.573534 |
nature-of-code/noc-examples-processing | 2,015 | chp06_agents/StayWithinCircle/Vehicle.pde | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
class Vehicle {
PVector position;
PVector velocity;
PVector acceleration;
float r;
float maxspeed;
float maxforce;
Vehicle(float x, float y) {
acceleration = new PVector(0, 0);
velocity = new PVector(1,0);
velocity.mult(5);
position = new PVector(x, y);
r = 3;
maxspeed = 3;
maxforce = 0.15;
}
void run() {
update();
display();
}
// Method to update position
void update() {
// Update velocity
velocity.add(acceleration);
// Limit speed
velocity.limit(maxspeed);
position.add(velocity);
// Reset accelertion to 0 each cycle
acceleration.mult(0);
}
void boundaries() {
PVector desired = null;
// Predict position 25 (arbitrary choice) frames ahead
PVector predict = velocity.get();
predict.mult(25);
PVector futureposition = PVector.add(position, predict);
float distance = PVector.dist(futureposition,circleposition);
if (distance > circleRadius) {
PVector toCenter = PVector.sub(circleposition,position);
toCenter.normalize();
toCenter.mult(velocity.mag());
desired = PVector.add(velocity,toCenter);
desired.normalize();
desired.mult(maxspeed);
}
if (desired != null) {
PVector steer = PVector.sub(desired, velocity);
steer.limit(maxforce);
applyForce(steer);
}
fill(255,0,0);
ellipse(futureposition.x,futureposition.y,4,4);
}
void applyForce(PVector force) {
// We could add mass here if we want A = F / M
acceleration.add(force);
}
void display() {
// Draw a triangle rotated in the direction of velocity
float theta = velocity.heading2D() + radians(90);
fill(175);
stroke(0);
pushMatrix();
translate(position.x, position.y);
rotate(theta);
beginShape(TRIANGLES);
vertex(0, -r*2);
vertex(-r, r*2);
vertex(r, r*2);
endShape();
popMatrix();
}
}
| 411 | 0.789784 | 1 | 0.789784 | game-dev | MEDIA | 0.528147 | game-dev,graphics-rendering | 0.991342 | 1 | 0.991342 |
ProjectIgnis/CardScripts | 2,751 | official/c25861589.lua | --アロマブレンド
--Aroma Blend
--scripted by Naim
local s,id=GetID()
function s.initial_effect(c)
--Place 1 "Humid Winds/Dried Winds/Blessed Winds" face-up in the Spell/Trap Zone
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,id)
e1:SetCost(s.plcost)
e1:SetTarget(s.pltg)
e1:SetOperation(s.plop)
c:RegisterEffect(e1)
--Fusion Summon 1 Plant Fusion Monster
local params={handler=c,fusfilter=aux.FilterBoolFunction(Card.IsRace,RACE_PLANT),
matfilter=Card.IsAbleToRemove,extrafil=s.extrafil,
extraop=Fusion.BanishMaterial,extratg=s.extratg}
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_FUSION_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetCountLimit(1,{id,1})
e2:SetCost(Cost.SelfBanish)
e2:SetTarget(Fusion.SummonEffTG(params))
e2:SetOperation(Fusion.SummonEffOP(params))
c:RegisterEffect(e2)
end
s.listed_names={28265983,92266279,15177750} --Humid Winds, Dried Winds, Blessed Winds
function s.cfilter(c,tp)
return c:IsDiscardable() and Duel.IsExistingMatchingCard(s.plfilter,tp,LOCATION_DECK|LOCATION_HAND,0,1,c,tp)
end
function s.plfilter(c,tp)
return c:IsCode(28265983,92266279,15177750) and not c:IsForbidden() and c:CheckUniqueOnField(tp)
end
function s.plcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.cfilter,tp,LOCATION_HAND,0,1,e:GetHandler(),tp) end
Duel.DiscardHand(tp,s.cfilter,1,1,REASON_COST|REASON_DISCARD,nil,tp)
end
function s.pltg(e,tp,eg,ep,ev,re,r,rp,chk)
local ft=Duel.GetLocationCount(tp,LOCATION_SZONE)
if e:GetHandler():IsLocation(LOCATION_HAND) then ft=ft-1 end
if chk==0 then return ft>0 and Duel.IsExistingMatchingCard(s.plfilter,tp,LOCATION_DECK|LOCATION_HAND,0,1,nil,tp) end
end
function s.plop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOFIELD)
local tc=Duel.SelectMatchingCard(tp,s.plfilter,tp,LOCATION_DECK|LOCATION_HAND,0,1,1,nil,tp):GetFirst()
if tc then
Duel.MoveToField(tc,tp,tp,LOCATION_SZONE,POS_FACEUP,true)
end
end
function s.exfilter(c)
return c:IsRace(RACE_PLANT) and c:IsAbleToRemove()
end
function s.extrafil(e,tp,mg)
if Duel.GetLP(tp)>Duel.GetLP(1-tp) and not Duel.IsPlayerAffectedByEffect(tp,CARD_SPIRIT_ELIMINATION) then
return Duel.GetMatchingGroup(s.exfilter,tp,LOCATION_GRAVE,0,nil)
end
return nil
end
function s.extratg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,1,tp,LOCATION_HAND|LOCATION_MZONE)
Duel.SetPossibleOperationInfo(0,CATEGORY_REMOVE,nil,1,tp,LOCATION_GRAVE)
end | 411 | 0.976665 | 1 | 0.976665 | game-dev | MEDIA | 0.946904 | game-dev | 0.980026 | 1 | 0.980026 |
Dimbreath/AzurLaneData | 64,597 | ja-JP/view/main/settingsscene.lua | slot0 = class("SettingsScene", import("..base.BaseUI"))
slot0.CLD_RED = Color.New(0.6, 0.05, 0.05, 0.5)
slot0.DEFAULT_GREY = Color.New(0.5, 0.5, 0.5, 0.5)
slot0.EnterToggle = {
options = "options",
res = "res",
interface = "interface",
sound = "sound"
}
function slot0.getUIName(slot0)
return "SettingsUI"
end
function slot0.init(slot0)
slot0.eventTriggers = {}
slot0.top = slot0:findTF("blur_panel/adapt/top")
slot0.backButton = slot0:findTF("blur_panel/adapt/top/back_btn")
slot0.leftPanel = slot0:findTF("blur_panel/adapt/left_length")
slot0.logoutButton = slot0:findTF("logout", slot0.leftPanel)
slot0.bbsButton = slot0:findTF("bbs", slot0.leftPanel)
slot0.soundToggle = slot0:findTF("resources", slot0.leftPanel)
slot0.optionsToggle = slot0:findTF("options", slot0.leftPanel)
slot0.otherToggle = slot0:findTF("other", slot0.leftPanel)
slot0.interfaceToggle = slot0:findTF("battle_ui", slot0.leftPanel)
slot0.resToggle = slot0:findTF("resources", slot0.leftPanel)
slot0.helpUS = slot0:findTF("help_us", slot0.leftPanel)
setActive(slot0.helpUS, PLATFORM_CODE == PLATFORM_US)
slot0.repairMask = slot0:findTF("mask_repair")
slot0.msgBox = SettingsMsgBosPage.New(slot0._tf, slot0.event)
slot0:initSoundPanel(slot0:findTF("main/resources"))
slot0:initOptionsPanel(slot0:findTF("main/options"))
slot0:initInterfacePreference(slot0:findTF("main/battle_ui"))
slot0:initOtherPanel(slot0:findTF("main/other"))
slot0:initResDownloadPanel(slot0:findTF("main/resources"))
end
function slot0.initResDownloadPanel(slot0, slot1)
setActive(slot1, false)
slot0.resRepairGroup = {}
slot3 = slot0:findTF("main/resources/mask/main_panel"):Find("repair")
slot0.resRepairGroup.Button = slot3
slot0.resRepairGroup.Progress = slot3:Find("progress")
slot0.resRepairGroup.ProgressHandle = slot3:Find("progress/handle")
slot0.resRepairGroup.Info1 = slot3:Find("status")
slot0.resRepairGroup.Info2 = slot3:Find("version")
slot0.resRepairGroup.LabelNew = slot3:Find("version/new")
slot0.resRepairGroup.Dot = slot3:Find("new")
slot0.resRepairGroup.Loading = slot3:Find("loading")
setText(slot3:Find("title"), i18n("repair_setting_label"))
function ()
setSlider(uv0.resRepairGroup.Progress, 0, 1, 0)
setActive(uv0.resRepairGroup.Dot, false)
setActive(uv0.resRepairGroup.Loading, false)
setText(uv0.resRepairGroup.Info1, i18n("word_files_repair"))
setText(uv0.resRepairGroup.Info2, "")
slot2 = 1
setSlider(uv0.resRepairGroup.Progress, 0, 1, slot2)
setActive(uv0.resRepairGroup.ProgressHandle, slot2 ~= 0 and slot2 ~= 1)
setActive(uv0.resRepairGroup.Dot, false)
setActive(uv0.resRepairGroup.Loading, false)
setActive(uv0.resRepairGroup.LabelNew, false)
end()
onButton(slot0, slot0.resRepairGroup.Button, function ()
showRepairMsgbox()
end, SFX_PANEL)
slot0.live2DDownloadBtn = slot0:findTF("main/resources/mask/main_panel/live2d")
slot0.live2DDownloadProgress = slot0:findTF("main/resources/mask/main_panel/live2d/progress")
slot0.live2DDownloadProgressHandle = slot0:findTF("main/resources/mask/main_panel/live2d/progress/handle")
slot0.live2DDownloadInfo1 = slot0:findTF("main/resources/mask/main_panel/live2d/status")
slot0.live2DDownloadInfo2 = slot0:findTF("main/resources/mask/main_panel/live2d/version")
slot0.live2DDownloadLabelNew = slot0:findTF("main/resources/mask/main_panel/live2d/version/new")
slot0.live2DDownloadDot = slot0:findTF("main/resources/mask/main_panel/live2d/new")
slot0.live2DDownloadLoading = slot0:findTF("main/resources/mask/main_panel/live2d/loading")
setSlider(slot0.live2DDownloadProgress, 0, 1, 0)
setActive(slot0.live2DDownloadDot, false)
setActive(slot0.live2DDownloadLoading, false)
slot0.live2DDownloadTimer = Timer.New(function ()
uv0:updateLive2DDownloadState()
end, 0.5, -1)
slot0.live2DDownloadTimer:Start()
slot0:updateLive2DDownloadState()
if BundleWizard.Inst:GetGroupMgr("L2D").state == DownloadState.None then
slot5:CheckD()
end
onButton(slot0, slot0.live2DDownloadBtn, function ()
if uv0.state == DownloadState.CheckFailure then
uv0:CheckD()
elseif slot0 == DownloadState.CheckToUpdate or slot0 == DownloadState.UpdateFailure then
VersionMgr.Inst:RequestUIForUpdateD("L2D", true)
end
end, SFX_PANEL)
slot0.soundDownloadBtn = slot0:findTF("main/resources/mask/main_panel/cv")
slot0.soundDownloadProgress = slot0:findTF("main/resources/mask/main_panel/cv/progress")
slot0.soundDownloadProgressHandle = slot0:findTF("main/resources/mask/main_panel/cv/progress/handle")
slot0.soundDownloadInfo1 = slot0:findTF("main/resources/mask/main_panel/cv/status")
slot0.soundDownloadInfo2 = slot0:findTF("main/resources/mask/main_panel/cv/version")
slot0.soundDownloadLabelNew = slot0:findTF("main/resources/mask/main_panel/cv/version/new")
slot0.soundDownloadDot = slot0:findTF("main/resources/mask/main_panel/cv/new")
slot0.soundDownloadLoading = slot0:findTF("main/resources/mask/main_panel/cv/loading")
setSlider(slot0.soundDownloadProgress, 0, 1, 0)
setActive(slot0.soundDownloadDot, false)
setActive(slot0.soundDownloadLoading, false)
BundleWizard.Inst:GetGroupMgr("CV"):CheckD()
slot0.soundDownloadTimer = Timer.New(function ()
uv0:updateSoundDownloadState()
end, 0.5, -1)
slot0.soundDownloadTimer:Start()
slot0:updateSoundDownloadState()
onButton(slot0, slot0.soundDownloadBtn, function ()
if uv0.state == DownloadState.CheckFailure then
uv0:CheckD()
elseif uv0.state == DownloadState.CheckToUpdate or uv0.state == DownloadState.UpdateFailure then
VersionMgr.Inst:RequestUIForUpdateD("CV", true)
end
end, SFX_PANEL)
slot0.galleryDownloadBtn = slot0:findTF("main/resources/mask/main_panel/gallery")
slot0.galleryDownloadProgress = slot0:findTF("main/resources/mask/main_panel/gallery/progress")
slot0.galleryDownloadProgressHandle = slot0:findTF("main/resources/mask/main_panel/gallery/progress/handle")
slot0.galleryDownloadInfo1 = slot0:findTF("main/resources/mask/main_panel/gallery/status")
slot0.galleryDownloadInfo2 = slot0:findTF("main/resources/mask/main_panel/gallery/version")
slot0.galleryDownloadLabelNew = slot0:findTF("main/resources/mask/main_panel/gallery/version/new")
slot0.galleryDownloadDot = slot0:findTF("main/resources/mask/main_panel/gallery/new")
slot0.galleryDownloadLoading = slot0:findTF("main/resources/mask/main_panel/gallery/loading")
setSlider(slot0.galleryDownloadProgress, 0, 1, 0)
setActive(slot0.galleryDownloadDot, false)
setActive(slot0.galleryDownloadLoading, false)
BundleWizard.Inst:GetGroupMgr("GALLERY_PIC"):CheckD()
slot0.galleryDownloadTimer = Timer.New(function ()
uv0:updateGalleryDownloadState()
end, 0.5, -1)
slot0.galleryDownloadTimer:Start()
slot0:updateGalleryDownloadState()
onButton(slot0, slot0.galleryDownloadBtn, function ()
if uv0.state == DownloadState.CheckFailure then
uv0:CheckD()
elseif uv0.state == DownloadState.CheckToUpdate or uv0.state == DownloadState.UpdateFailure then
VersionMgr.Inst:RequestUIForUpdateD("GALLERY_PIC", true)
end
end, SFX_PANEL)
slot0.musicDownloadBtn = slot0:findTF("main/resources/mask/main_panel/music")
slot0.musicDownloadProgress = slot0:findTF("main/resources/mask/main_panel/music/progress")
slot0.musicDownloadProgressHandle = slot0:findTF("main/resources/mask/main_panel/music/progress/handle")
slot0.musicDownloadInfo1 = slot0:findTF("main/resources/mask/main_panel/music/status")
slot0.musicDownloadInfo2 = slot0:findTF("main/resources/mask/main_panel/music/version")
slot0.musicDownloadLabelNew = slot0:findTF("main/resources/mask/main_panel/music/version/new")
slot0.musicDownloadDot = slot0:findTF("main/resources/mask/main_panel/music/new")
slot0.musicDownloadLoading = slot0:findTF("main/resources/mask/main_panel/music/loading")
setSlider(slot0.musicDownloadProgress, 0, 1, 0)
setActive(slot0.musicDownloadDot, false)
setActive(slot0.musicDownloadLoading, false)
BundleWizard.Inst:GetGroupMgr("GALLERY_BGM"):CheckD()
slot0.musicDownloadTimer = Timer.New(function ()
uv0:updateMusicDownloadState()
end, 0.5, -1)
slot0.musicDownloadTimer:Start()
slot0:updateMusicDownloadState()
onButton(slot0, slot0.musicDownloadBtn, function ()
if uv0.state == DownloadState.CheckFailure then
uv0:CheckD()
elseif uv0.state == DownloadState.CheckToUpdate or uv0.state == DownloadState.UpdateFailure then
VersionMgr.Inst:RequestUIForUpdateD("GALLERY_BGM", true)
end
end, SFX_PANEL)
end
function slot0.initSoundPanel(slot0, slot1)
setActive(slot1, false)
slot2 = slot0:findTF("main/resources/mask/main_panel")
slot3 = PlayerPrefs.GetInt("mute_audio", 0) == 1
slot0.bgmSlider = slot2:Find("settings/bgm/slider")
function ()
slot0 = pg.CriMgr.GetInstance():getBGMVolume()
if uv0 then
slot0 = PlayerPrefs.GetFloat("bgm_vol_mute_setting", DEFAULT_BGMVOLUME)
end
setSlider(uv1.bgmSlider, 0, 1, slot0)
end()
slot0:initSoundSlider(slot0.bgmSlider, function (slot0)
if uv0 then
return
end
pg.CriMgr.GetInstance():setBGMVolume(slot0)
end)
slot0.effectSlider = slot2:Find("settings/sfx/slider")
function ()
slot0 = pg.CriMgr.GetInstance():getSEVolume()
if uv0 then
slot0 = PlayerPrefs.GetFloat("se_vol_mute_setting", DEFAULT_SEVOLUME)
end
setSlider(uv1.effectSlider, 0, 1, slot0)
end()
slot0:initSoundSlider(slot0.effectSlider, function (slot0)
if uv0 then
return
end
pg.CriMgr.GetInstance():setSEVolume(slot0)
end)
slot0.mainSlider = slot2:Find("settings/cv/slider")
function ()
slot0 = pg.CriMgr.GetInstance():getCVVolume()
if uv0 then
slot0 = PlayerPrefs.GetFloat("cv_vol_mute_setting", DEFAULT_CVVOLUME)
end
setSlider(uv1.mainSlider, 0, 1, slot0)
end()
slot0:initSoundSlider(slot0.mainSlider, function (slot0)
if uv0 then
return
end
pg.CriMgr.GetInstance():setCVVolume(slot0)
end)
setText(slot2:Find("settings/buttons/soundswitch/Text"), i18n("voice_control"))
slot7 = slot2:Find("settings/buttons/soundswitch/on")
triggerToggle(slot7, not slot3)
triggerToggle(slot2:Find("settings/buttons/soundswitch/off"), slot3)
onToggle(slot0, slot7, function (slot0)
if not slot0 then
PlayerPrefs.SetFloat("bgm_vol_mute_setting", pg.CriMgr.GetInstance():getBGMVolume())
PlayerPrefs.SetFloat("se_vol_mute_setting", pg.CriMgr.GetInstance():getSEVolume())
PlayerPrefs.SetFloat("cv_vol_mute_setting", pg.CriMgr.GetInstance():getCVVolume())
pg.CriMgr.GetInstance():setBGMVolume(0)
pg.CriMgr.GetInstance():setSEVolume(0)
pg.CriMgr.GetInstance():setCVVolume(0)
PlayerPrefs.SetInt("mute_audio", 1)
else
pg.CriMgr.GetInstance():setBGMVolume(PlayerPrefs.GetFloat("bgm_vol_mute_setting", DEFAULT_BGMVOLUME))
pg.CriMgr.GetInstance():setSEVolume(PlayerPrefs.GetFloat("se_vol_mute_setting", DEFAULT_SEVOLUME))
pg.CriMgr.GetInstance():setCVVolume(PlayerPrefs.GetFloat("cv_vol_mute_setting", DEFAULT_CVVOLUME))
PlayerPrefs.SetInt("mute_audio", 0)
end
uv0:setSliderEnable(uv0.bgmSlider, slot0)
uv0:setSliderEnable(uv0.effectSlider, slot0)
uv0:setSliderEnable(uv0.mainSlider, slot0)
uv1 = not slot0
end, SFX_UI_TAG, SFX_UI_TAG)
slot0:setSliderEnable(slot0.bgmSlider, not slot3)
slot0:setSliderEnable(slot0.effectSlider, not slot3)
slot0:setSliderEnable(slot0.mainSlider, not slot3)
slot0.soundRevertBtn = slot2:Find("settings/buttons/reset")
onButton(slot0, slot0.soundRevertBtn, function ()
pg.MsgboxMgr.GetInstance():ShowMsgBox({
content = i18n("sure_resume_volume"),
onYes = function ()
triggerToggle(uv0, true)
setSlider(uv1.bgmSlider, 0, 1, DEFAULT_BGMVOLUME)
setSlider(uv1.effectSlider, 0, 1, DEFAULT_SEVOLUME)
setSlider(uv1.mainSlider, 0, 1, DEFAULT_CVVOLUME)
end
})
end, SFX_UI_CLICK)
end
function slot0.initSoundSlider(slot0, slot1, slot2)
slot3 = slot1:GetComponent("Slider")
slot3.onValueChanged:RemoveAllListeners()
pg.DelegateInfo.Add(slot0, slot3.onValueChanged)
slot3.onValueChanged:AddListener(slot2)
slot4 = (slot3.maxValue - slot3.minValue) * 0.1
onButton(slot0, slot1:Find("up"), function ()
uv0.value = math.clamp(uv0.value + uv1, uv0.minValue, uv0.maxValue)
end, SFX_PANEL)
onButton(slot0, slot1:Find("down"), function ()
uv0.value = math.clamp(uv0.value - uv1, uv0.minValue, uv0.maxValue)
end, SFX_PANEL)
end
function slot0.setSliderEnable(slot0, slot1, slot2)
slot2 = tobool(slot2)
slot1:GetComponent("Slider").interactable = slot2
setButtonEnabled(slot1:Find("up"), slot2)
setButtonEnabled(slot1:Find("down"), slot2)
end
slot1 = {}
slot2 = {
{
title = i18n("words_show_ship_name_label"),
desc = i18n("option_desc1")
},
{
title = i18n("words_auto_battle_label"),
name = AUTO_BATTLE_LABEL,
desc = i18n("option_desc2")
},
{
default = 1,
title = i18n("words_rare_ship_vibrate"),
name = RARE_SHIP_VIBRATE,
desc = i18n("option_desc3")
},
{
default = 1,
title = i18n("words_display_ship_get_effect"),
name = DISPLAY_SHIP_GET_EFFECT,
desc = i18n("option_desc4")
},
{
default = 1,
title = i18n("words_show_touch_effect"),
name = SHOW_TOUCH_EFFECT,
desc = i18n("option_desc5")
},
{
default = 0,
title = i18n("words_bg_fit_mode"),
name = BG_FIT_MODE,
desc = i18n("option_desc6")
},
{
default = 1,
title = i18n("words_battle_hide_bg"),
name = BATTLE_HIDE_BG,
desc = i18n("option_desc10")
},
{
default = 0,
alignment = 1,
title = i18n("words_battle_expose_line"),
name = BATTLE_EXPOSE_LINE,
desc = i18n("option_desc11")
}
}
if not LOCK_BATTERY_SAVEMODE then
table.insert(slot2, {
default = 0,
title = i18n("words_autoFight_battery_savemode"),
name = AUTOFIGHT_BATTERY_SAVEMODE,
desc = i18n("words_autoFight_battery_savemode_des")
})
table.insert(slot2, {
default = 0,
title = i18n("words_autoFIght_down_frame"),
name = AUTOFIGHT_DOWN_FRAME,
desc = i18n("words_autoFIght_down_frame_des")
})
end
slot3 = {
{
default = 1,
title = i18n("words_visit_backyard_toggle"),
name = ALLOW_FIREND_VISIT_BACKYARD,
desc = i18n("option_desc7"),
playerFlag = ALLOW_FIREND_VISIT_BACKYARD_FLAG
},
{
default = 0,
title = i18n("words_show_friend_backyardship_toggle"),
name = SHOW_FIREND_BACKYARD_SHIP,
desc = i18n("option_desc8"),
playerFlag = SHOW_FIREND_BACKYARD_SHIP_FLAG
},
{
default = 0,
title = i18n("words_show_my_backyardship_toggle"),
name = SHOW_MY_BACKYARD_SHIP,
desc = i18n("option_desc9"),
playerFlag = SHOW_MY_BACKYARD_SHIP_FLAG
}
}
function slot0.initOptionsPanel(slot0, slot1)
slot2 = slot1:Find("scroll_view/Viewport/content/fps_setting")
slot3 = slot2:Find("options/30fps")
onToggle(slot0, slot3, function (slot0)
if slot0 then
PlayerPrefs.SetInt("fps_limit", 30)
Application.targetFrameRate = 30
end
end, SFX_UI_TAG, SFX_UI_TAG)
onToggle(slot0, slot2:Find("options/60fps"), function (slot0)
if slot0 then
PlayerPrefs.SetInt("fps_limit", 60)
Application.targetFrameRate = 60
end
end, SFX_UI_TAG, SFX_UI_TAG)
triggerToggle(slot3, PlayerPrefs.GetInt("fps_limit", 30) == 30)
triggerToggle(slot4, slot5 == 60)
slot7 = slot0:findTF("scroll_view/Viewport/content/other_settings/options", slot1)
for slot13, slot14 in ipairs(pg.push_data_template) do
slot15 = cloneTplTo(slot0:findTF("scroll_view/Viewport/content/notifications/options", slot1):Find("notify_tpl"), slot6)
setText(slot0:findTF("Text", slot15), slot14.title)
onButton(slot0, slot0:findTF("Text", slot15), function ()
uv0.msgBox:ExecuteAction("Show", uv1.desc, uv1.alignment)
end)
onToggle(slot0, slot15:Find("on"), function (slot0)
pg.PushNotificationMgr.GetInstance():setSwitch(uv0.id, slot0)
end, SFX_UI_TAG, SFX_UI_CANCEL)
slot16 = pg.PushNotificationMgr.GetInstance():isEnabled(slot14.id)
triggerToggle(slot15:Find("on"), slot16)
triggerToggle(slot15:Find("off"), not slot16)
end
for slot13, slot14 in pairs(uv0) do
slot15 = cloneTplTo(slot7:Find("notify_tpl"), slot7)
setText(slot0:findTF("Text", slot15), slot14.title)
onButton(slot0, slot0:findTF("Text", slot15), function ()
uv0.msgBox:ExecuteAction("Show", uv1.desc, uv1.alignment)
end)
if slot13 == 1 then
onToggle(slot0, slot15:Find("on"), function (slot0)
pg.PushNotificationMgr.GetInstance():setSwitchShipName(slot0)
end, SFX_UI_TAG, SFX_UI_CANCEL)
triggerToggle(slot15:Find("on"), pg.PushNotificationMgr.GetInstance():isEnableShipName())
triggerToggle(slot15:Find("off"), not pg.PushNotificationMgr.GetInstance():isEnableShipName())
else
slot0[slot14.name] = PlayerPrefs.GetInt(slot14.name, slot14.default or 0) > 0
if slot14.name == AUTOFIGHT_BATTERY_SAVEMODE then
onToggle(slot0, slot15:Find("on"), function (slot0)
if uv0[uv1.name] ~= slot0 then
PlayerPrefs.SetInt(uv1.name, slot0 and 1 or 0)
PlayerPrefs.Save()
uv0[uv1.name] = slot0
if uv1.name == AUTOFIGHT_BATTERY_SAVEMODE and table.indexof(uv2, _.detect(uv2, function (slot0)
return slot0.name == AUTOFIGHT_DOWN_FRAME
end)) then
slot3 = uv3:GetChild(slot2)
triggerToggle(slot3:Find(slot0 and "on" or "off"), true)
uv4.SetGrayAndUninteractable(slot3, slot0)
end
end
end, SFX_UI_TAG, SFX_UI_CANCEL)
elseif slot14.name == AUTOFIGHT_DOWN_FRAME then
onToggle(slot0, slot15:Find("on"), function (slot0)
if not uv0[AUTOFIGHT_BATTERY_SAVEMODE] and slot0 then
pg.TipsMgr.GetInstance():ShowTips(i18n("words_autoFight_tips"))
triggerToggle(uv1:Find("off"), true)
return
end
if uv0[uv2.name] ~= slot0 then
PlayerPrefs.SetInt(uv2.name, slot0 and 1 or 0)
PlayerPrefs.Save()
uv0[uv2.name] = slot0
end
end, SFX_UI_TAG, SFX_UI_CANCEL)
uv1.SetGrayAndUninteractable(slot15, slot0[AUTOFIGHT_BATTERY_SAVEMODE])
else
onToggle(slot0, slot15:Find("on"), function (slot0)
if uv0[uv1.name] ~= slot0 then
PlayerPrefs.SetInt(uv1.name, slot0 and 1 or 0)
PlayerPrefs.Save()
uv0[uv1.name] = slot0
end
if uv1.name == SHOW_TOUCH_EFFECT and pg.UIMgr.GetInstance().OverlayEffect then
setActive(slot1, slot0)
end
end, SFX_UI_TAG, SFX_UI_CANCEL)
end
triggerToggle(slot15:Find("on"), slot0[slot14.name])
triggerToggle(slot15:Find("off"), not slot0[slot14.name])
end
end
slot0:UpdateBackYardConfig()
setActive(slot0:findTF("scroll_view/Viewport/content/world_boss_notifications", slot1), false)
slot10, slot11 = pg.SystemOpenMgr.GetInstance():isOpenSystem(getProxy(PlayerProxy):getData().level, "WorldMediator")
setActive(slot1:Find("scroll_view/Viewport/content/world_settings"), slot10)
if slot10 then
slot0:InitWorldPanel(slot1)
end
slot0:InitStorySpeedPanel(slot1)
slot0:InitStoryAutoPlayPanel(slot1)
end
function slot0.SetGrayAndUninteractable(slot0, slot1)
setGray(slot0:Find("on"), not slot1)
setGray(slot0:Find("off"), not slot1)
end
function slot0.InitStorySpeedPanel(slot0, slot1)
setText(slot1:Find("scroll_view/Viewport/content/story_speed_setting/title"), i18n("story_setting_label"))
setText(slot1:Find("scroll_view/Viewport/content/story_speed_setting/title/title_text"), i18n1("/AUTO SPEED"))
slot3 = slot1:Find("scroll_view/Viewport/content/story_speed_setting/speeds")
for slot9 = 1, slot3.childCount do
slot10 = slot3:GetChild(slot9 - 1)
onToggle(slot0, slot10, function (slot0)
if slot0 then
getProxy(SettingsProxy):SetStorySpeed(uv0[uv1])
end
end, SFX_PANEL)
setText(slot10:Find("Text"), i18n("setting_story_speed_" .. slot9))
if slot9 == (table.indexof(Story.STORY_AUTO_SPEED, getProxy(SettingsProxy):GetStorySpeed()) or 2) then
triggerToggle(slot10, true)
end
end
end
function slot0.InitStoryAutoPlayPanel(slot0, slot1)
setText(slot1:Find("scroll_view/Viewport/content/story_autoplay_setting/title"), i18n("story_autoplay_setting_label"))
setText(slot1:Find("scroll_view/Viewport/content/story_autoplay_setting/title/title_text"), i18n1("/AUTO"))
for slot7, slot8 in ipairs({
slot1:Find("scroll_view/Viewport/content/story_autoplay_setting/speeds/1"),
slot1:Find("scroll_view/Viewport/content/story_autoplay_setting/speeds/2")
}) do
onToggle(slot0, slot8, function (slot0)
if slot0 then
getProxy(SettingsProxy):SetStoryAutoPlayFlag(uv0 - 1)
end
end, SFX_PANEL)
setText(slot8:Find("Text"), i18n("story_autoplay_setting_" .. slot7))
if slot7 == (getProxy(SettingsProxy):GetStoryAutoPlayFlag() and 2 or 1) then
triggerToggle(slot8, true)
end
end
end
function slot0.UpdateBackYardConfig(slot0)
if not slot0.backyardConfigToggles then
slot0.backyardConfigToggles = {}
slot5 = slot0
slot6 = "main/options"
notiTpl = slot0:findTF("scroll_view/Viewport/content/other_settings/options", slot0.findTF(slot5, slot6)):Find("notify_tpl")
for slot5, slot6 in ipairs(uv0) do
slot7 = cloneTplTo(notiTpl, slot1)
setText(slot0:findTF("Text", slot7), slot6.title)
onButton(slot0, slot0:findTF("Text", slot7), function ()
uv0.msgBox:ExecuteAction("Show", uv1.desc, uv1.alignment)
end)
table.insert(slot0.backyardConfigToggles, {
value = slot6,
btn = slot7
})
end
end
for slot4, slot5 in ipairs(slot0.backyardConfigToggles) do
slot0:InitOptionByPlayerFlag(slot5.value, slot5.btn)
end
end
function slot0.InitOptionByPlayerFlag(slot0, slot1, slot2)
slot4 = getProxy(PlayerProxy):getData():GetCommonFlag(slot1.playerFlag)
slot5 = nil
slot5 = slot1.default == 1 and slot4 or not slot4
onToggle(slot0, slot2:Find("on"), function (slot0)
uv0:emit(SettingsMediator.SET_PLAYER_FLAG, uv1.playerFlag)
end, SFX_UI_TAG, SFX_UI_CANCEL)
triggerToggle(slot2:Find("on"), not slot5)
triggerToggle(slot2:Find("off"), slot5)
end
function slot0.InitWorldBossPanel(slot0, slot1)
for slot8, slot9 in ipairs({
i18n("world_word_world"),
i18n("world_word_friend"),
i18n("world_word_guild")
}) do
slot10 = cloneTplTo(slot0:findTF("scroll_view/Viewport/content/world_boss_notifications/options", slot1):Find("notify_tpl"), slot2)
slot11 = getProxy(SettingsProxy):GetWorldBossFlag(slot8)
setText(slot10:Find("Text"), slot9)
onToggle(slot0, slot10:Find("on"), function (slot0)
if uv0 ~= slot0 then
getProxy(SettingsProxy):SetWorldBossFlag(uv1, slot0)
uv0 = slot0
end
end, SFX_UI_TAG, SFX_UI_CANCEL)
triggerToggle(slot10:Find("on"), slot11)
triggerToggle(slot10:Find("off"), not slot11)
end
end
function slot0.InitWorldPanel(slot0, slot1)
for slot8, slot9 in pairs({
{
key = "story_tips",
title = i18n("world_setting_quickmode"),
desc = i18n("world_setting_quickmodetip")
},
{
key = "consume_item",
title = i18n("world_setting_submititem"),
desc = i18n("world_setting_submititemtip")
}
}) do
slot10 = cloneTplTo(slot1:Find("scroll_view/Viewport/content/world_settings/options"):Find("notify_tpl"), slot2)
slot11 = getProxy(SettingsProxy):GetWorldFlag(slot9.key)
setText(slot10:Find("Text"), slot9.title)
onButton(slot0, slot10:Find("Text"), function ()
uv0.msgBox:ExecuteAction("Show", uv1.desc)
end)
onToggle(slot0, slot10:Find("on"), function (slot0)
if uv0 ~= slot0 then
getProxy(SettingsProxy):SetWorldFlag(uv1.key, slot0)
uv0 = slot0
end
end, SFX_UI_TAG, SFX_UI_CANCEL)
triggerToggle(slot10:Find("on"), slot11)
triggerToggle(slot10:Find("off"), not slot11)
end
setText(slot1:Find("scroll_view/Viewport/content/world_settings/title"), i18n("world_setting_title"))
end
function slot0.initInterfacePreference(slot0, slot1)
setActive(slot1, false)
slot0.editPanel = slot1:Find("editor")
slot2 = slot0:findTF("main/battle_ui/editor/buttons")
slot0.normalBtns = findTF(slot2, "normal")
slot0.editBtns = findTF(slot2, "editing")
slot0.saveBtn = findTF(slot0.editBtns, "save")
slot0.cancelBtn = findTF(slot0.editBtns, "cancel")
slot0.editBtn = findTF(slot0.normalBtns, "edit")
slot0.revertBtn = findTF(slot0.normalBtns, "reset")
onButton(slot0, slot0.editBtn, function ()
uv0:editModeEnabled(true)
end, SFX_PANEL)
onButton(slot0, slot0.revertBtn, function ()
pg.MsgboxMgr.GetInstance():ShowMsgBox({
hideNo = false,
content = i18n("setting_interface_revert_check"),
onYes = function ()
uv0:revertInterfaceSetting(true)
end
})
end, SFX_PANEL)
onButton(slot0, slot0.cancelBtn, function ()
if uv0._currentDrag then
LuaHelper.triggerEndDrag(uv0._currentDrag)
end
pg.MsgboxMgr.GetInstance():ShowMsgBox({
hideNo = false,
content = i18n("setting_interface_cancel_check"),
onYes = function ()
uv0:editModeEnabled(false)
uv0:revertInterfaceSetting(false)
end
})
end, SFX_PANEL)
onButton(slot0, slot0.saveBtn, function ()
if uv0._currentDrag then
LuaHelper.triggerEndDrag(uv0._currentDrag)
end
uv0:editModeEnabled(false)
uv0:saveInterfaceSetting()
pg.TipsMgr.GetInstance():ShowTips(i18n("setting_interface_save_success"))
end, SFX_PANEL)
slot0.interface = slot0:findTF("main/battle_ui/editor/editing_region")
if rtf(slot0.interface).rect.width / rtf(slot0.interface).rect.height > rtf(slot0._tf).rect.width / rtf(slot0._tf).rect.height then
slot8 = rtf(slot0.interface).sizeDelta.y
slot0.scale = slot4 / slot6
slot7 = rtf(slot0.interface).sizeDelta.x - (slot3 - slot4 * slot5 / slot6)
else
slot7 = rtf(slot1).sizeDelta.x
slot0.scale = slot3 / slot5
slot8 = rtf(slot1).sizeDelta.y - (slot4 - slot3 * slot6 / slot5)
end
slot0.stick = findTF(slot0.interface, "Stick")
slot0.skillBtn1 = findTF(slot0.interface, "Skill_1")
slot0.skillBtn2 = findTF(slot0.interface, "Skill_2")
slot0.skillBtn3 = findTF(slot0.interface, "Skill_3")
slot0.skillBtn4 = findTF(slot0.interface, "Skill_4")
slot0.mask = findTF(slot0.interface, "mask")
slot0:initInterfaceComponent(slot0.stick, "joystick_anchorX", "joystick_anchorY", ys.Battle.BattleConfig.JOY_STICK_DEFAULT_PREFERENCE)
slot9 = ys.Battle.BattleConfig.SKILL_BUTTON_DEFAULT_PREFERENCE
slot0:initInterfaceComponent(slot0.skillBtn1, "skill_1_anchorX", "skill_1_anchorY", slot9[1])
slot0:initInterfaceComponent(slot0.skillBtn2, "skill_2_anchorX", "skill_2_anchorY", slot9[2])
slot0:initInterfaceComponent(slot0.skillBtn3, "skill_3_anchorX", "skill_3_anchorY", slot9[3])
slot14 = "skill_4_anchorY"
slot0:initInterfaceComponent(slot0.skillBtn4, "skill_4_anchorX", slot14, slot9[4])
slot0.components = {
findTF(slot0.interface, "top"),
slot0.stick,
slot0.skillBtn1,
slot0.skillBtn2,
slot0.skillBtn3,
slot0.skillBtn4
}
for slot14 = 2, #slot0.components do
setLocalScale(slot0.components[slot14], Vector3.New(slot0.scale, slot0.scale, 1))
end
slot0:editModeEnabled(false)
end
function slot0.initInterfaceComponent(slot0, slot1, slot2, slot3, slot4)
slot7 = rtf(slot0._tf).rect.width * 0.5 + slot0.interface.localPosition.x + slot0.interface.parent.localPosition.x + slot0.interface.parent.parent.localPosition.x
slot8 = rtf(slot0._tf).rect.height * 0.5 + slot0.interface.localPosition.y + slot0.interface.parent.localPosition.y + slot0.interface.parent.parent.localPosition.y
slot9 = GetOrAddComponent(slot1, "EventTriggerListener")
slot0.eventTriggers[slot9] = true
slot10, slot11, slot12, slot13 = nil
slot9:AddBeginDragFunc(function (slot0, slot1)
uv0._currentDrag = uv1
uv2 = uv3 / UnityEngine.Screen.width
uv4 = uv5 / UnityEngine.Screen.height
for slot5 = 2, #uv0.components do
if uv0.components[slot5] ~= uv6 then
GetOrAddComponent(slot6, "EventTriggerListener").enabled = false
end
end
uv7 = uv6.localPosition.x
uv8 = uv6.localPosition.y
end)
slot9:AddDragFunc(function (slot0, slot1)
uv0.localPosition = Vector3(slot1.position.x * uv1 - uv2, slot1.position.y * uv3 - uv4, 0)
uv5:checkInterfaceIntersect()
end)
slot9:AddDragEndFunc(function (slot0, slot1)
uv0._currentDrag = nil
if uv0:checkInterfaceIntersect() then
uv1.localPosition = Vector3(uv2, uv3, 0)
end
for slot6 = 2, #uv0.components do
GetOrAddComponent(uv0.components[slot6], "EventTriggerListener").enabled = true
end
uv0:checkInterfaceIntersect()
end)
slot0:setInterfaceAnchor(slot1, slot2, slot3, slot4)
end
function slot0.editModeEnabled(slot0, slot1)
setActive(slot0.normalBtns, not slot1)
setActive(slot0.mask, not slot1)
setActive(slot0.editBtns, slot1)
for slot5, slot6 in ipairs(slot0.components) do
setActive(findTF(slot6, "rect"), slot1)
if slot5 > 1 then
GetOrAddComponent(slot6, "EventTriggerListener").enabled = slot1
end
end
slot0.backButton:GetComponent(typeof(Button)).interactable = not slot1
slot0.otherToggle:GetComponent(typeof(Toggle)).interactable = not slot1
slot0.optionsToggle:GetComponent(typeof(Toggle)).interactable = not slot1
slot0.interfaceToggle:GetComponent(typeof(Toggle)).interactable = not slot1
slot0.resToggle:GetComponent(typeof(Toggle)).interactable = not slot1
slot0.logoutButton:GetComponent("ButtonExtend").interactable = not slot1
end
function slot0.setInterfaceAnchor(slot0, slot1, slot2, slot3, slot4, slot5)
slot6, slot7 = nil
if slot5 then
slot6 = slot4.x
slot7 = slot4.y
else
slot6 = PlayerPrefs.GetFloat(slot2, slot4.x)
slot7 = PlayerPrefs.GetFloat(slot3, slot4.y)
end
slot1.localPosition = Vector3((slot6 - 0.5) * rtf(slot0.interface).rect.width, (slot7 - 0.5) * rtf(slot0.interface).rect.height, 0)
end
function slot4(slot0)
slot1 = rtf(slot0)
slot2 = slot1.rect
slot3 = slot2.width * slot1.lossyScale.x
slot4 = slot2.height * slot1.lossyScale.y
slot5 = slot1.position
return UnityEngine.Rect.New(slot5.x - slot3 / 2, slot5.y - slot4 / 2, slot3, slot4)
end
function slot0.checkInterfaceIntersect(slot0)
slot1 = {}
slot2 = false
slot3 = {
[slot9] = uv0(slot9:Find("rect"))
}
slot4 = uv0(slot0.interface)
for slot8, slot9 in ipairs(slot0.components) do
-- Nothing
end
for slot8, slot9 in ipairs(slot0.components) do
for slot13, slot14 in ipairs(slot0.components) do
if slot9 ~= slot14 and slot3[slot9]:Overlaps(slot3[slot14]) then
slot1[slot14] = true
end
end
if slot8 > 1 then
if not slot4:Contains(Vector2.New(slot3[slot9].xMin, slot3[slot9].yMin)) or not slot4:Contains(Vector2.New(slot3[slot9].xMax, slot3[slot9].yMax)) then
slot1[slot9] = true
end
end
end
for slot8, slot9 in ipairs(slot0.components) do
if slot1[slot9] then
findTF(slot9, "rect"):GetComponent(typeof(Image)).color = uv1.CLD_RED
slot2 = true
else
slot10.color = uv1.DEFAULT_GREY
end
end
return slot2
end
function slot0.revertInterfaceSetting(slot0, slot1)
slot3 = ys.Battle.BattleConfig.SKILL_BUTTON_DEFAULT_PREFERENCE
slot0:setInterfaceAnchor(slot0.stick, "joystick_anchorX", "joystick_anchorY", ys.Battle.BattleConfig.JOY_STICK_DEFAULT_PREFERENCE, slot1)
slot0:setInterfaceAnchor(slot0.skillBtn1, "skill_1_anchorX", "skill_1_anchorY", slot3[1], slot1)
slot0:setInterfaceAnchor(slot0.skillBtn2, "skill_2_anchorX", "skill_2_anchorY", slot3[2], slot1)
slot0:setInterfaceAnchor(slot0.skillBtn3, "skill_3_anchorX", "skill_3_anchorY", slot3[3], slot1)
slot0:setInterfaceAnchor(slot0.skillBtn4, "skill_4_anchorX", "skill_4_anchorY", slot3[4], slot1)
slot0:saveInterfaceSetting()
end
function slot0.saveInterfaceSetting(slot0)
slot0:overrideInterfaceSetting(slot0.stick, "joystick_anchorX", "joystick_anchorY")
slot0:overrideInterfaceSetting(slot0.skillBtn1, "skill_1_anchorX", "skill_1_anchorY")
slot0:overrideInterfaceSetting(slot0.skillBtn2, "skill_2_anchorX", "skill_2_anchorY")
slot0:overrideInterfaceSetting(slot0.skillBtn3, "skill_3_anchorX", "skill_3_anchorY")
slot0:overrideInterfaceSetting(slot0.skillBtn4, "skill_4_anchorX", "skill_4_anchorY")
end
function slot0.overrideInterfaceSetting(slot0, slot1, slot2, slot3)
slot4 = rtf(slot0.interface).rect.width
slot5 = rtf(slot0.interface).rect.height
PlayerPrefs.SetFloat(slot2, (slot1.localPosition.x + slot4 * 0.5) / slot4)
PlayerPrefs.SetFloat(slot3, (slot1.localPosition.y + slot5 * 0.5) / slot5)
end
function slot0.updateSoundDownloadState(slot0)
slot3, slot4, slot5, slot6, slot7 = nil
slot8 = false
if BundleWizard.Inst:GetGroupMgr("CV").state == DownloadState.None then
slot3 = i18n("word_soundfiles_download_title")
slot4 = i18n("word_soundfiles_download")
slot5 = "DOWNLOAD"
slot6 = 0
slot7 = false
elseif slot2 == DownloadState.Checking then
slot3 = i18n("word_soundfiles_checking_title")
slot4 = i18n("word_soundfiles_checking")
slot5 = "CHECKING"
slot6 = 0
slot7 = false
elseif slot2 == DownloadState.CheckToUpdate then
slot3 = i18n("word_soundfiles_checkend_title")
slot4 = i18n("word_soundfiles_checkend")
slot5 = string.format("V.%d > V.%d", slot1.localVersion.Build, slot1.serverVersion.Build)
slot6 = 0
slot7 = true
elseif slot2 == DownloadState.CheckOver then
slot3 = i18n("word_soundfiles_checkend_title")
slot4 = i18n("word_soundfiles_noneedupdate")
slot5 = "V." .. slot1.CurrentVersion.Build
slot6 = 1
slot7 = false
elseif slot2 == DownloadState.CheckFailure then
slot3 = i18n("word_soundfiles_checkfailed")
slot4 = i18n("word_soundfiles_retry")
slot5 = string.format("ERROR(CODE:%d)", slot1.errorCode)
slot6 = 0
slot7 = false
elseif slot2 == DownloadState.Updating then
slot3 = i18n("word_soundfiles_update")
slot4 = string.format("(%d/%d)", slot1.downloadCount, slot1.downloadTotal)
slot5 = slot1.downPath
slot6 = slot1.downloadCount / math.max(slot1.downloadTotal, 1)
slot7 = false
slot8 = true
elseif slot2 == DownloadState.UpdateSuccess then
slot3 = i18n("word_soundfiles_update_end_title")
slot4 = i18n("word_soundfiles_update_end")
slot5 = "V." .. slot1.CurrentVersion.Build
slot6 = 1
slot7 = false
elseif slot2 == DownloadState.UpdateFailure then
slot3 = i18n("word_soundfiles_update_failed")
slot4 = i18n("word_soundfiles_update_retry")
slot5 = string.format("ERROR(CODE:%d)", slot1.errorCode)
slot6 = slot1.downloadCount / math.max(slot1.downloadTotal, 1)
slot7 = true
end
if slot5:len() > 15 then
slot5 = slot5:sub(1, 12) .. "..."
end
setText(slot0.soundDownloadInfo1, slot4)
setText(slot0.soundDownloadInfo2, slot5)
setAnchoredPosition(slot0.soundDownloadInfo2, {
x = slot2 == DownloadState.CheckToUpdate and 82.5 or 91.5
})
setSlider(slot0.soundDownloadProgress, 0, 1, slot6)
setActive(slot0.soundDownloadProgressHandle, slot6 ~= 0 and slot6 ~= 1)
setActive(slot0.soundDownloadDot, slot7)
setActive(slot0.soundDownloadLoading, slot8)
setActive(slot0.soundDownloadLabelNew, slot2 == DownloadState.CheckToUpdate)
end
function slot0.updateLive2DDownloadState(slot0)
slot3, slot4, slot5, slot6, slot7 = nil
slot8 = false
if BundleWizard.Inst:GetGroupMgr("L2D").state == DownloadState.None then
slot3 = i18n("word_live2dfiles_download_title")
slot4 = i18n("word_live2dfiles_download")
slot5 = "DOWNLOAD"
slot6 = 0
slot7 = false
elseif slot2 == DownloadState.Checking then
slot3 = i18n("word_live2dfiles_checking_title")
slot4 = i18n("word_live2dfiles_checking")
slot5 = "CHECKING"
slot6 = 0
slot7 = false
elseif slot2 == DownloadState.CheckToUpdate then
if slot1.serverVersion.Build <= slot1.localVersion.Build then
slot1.state = DownloadState.CheckOver
slot0:updateLive2DDownloadState()
return
end
slot3 = i18n("word_live2dfiles_checkend_title")
slot4 = i18n("word_live2dfiles_checkend")
slot5 = string.format("V.%d > V.%d", slot1.localVersion.Build, slot1.serverVersion.Build)
slot6 = 0
slot7 = true
elseif slot2 == DownloadState.CheckOver then
slot3 = i18n("word_live2dfiles_checkend_title")
slot4 = i18n("word_live2dfiles_noneedupdate")
slot5 = "V." .. slot1.CurrentVersion.Build
slot6 = 1
slot7 = false
elseif slot2 == DownloadState.CheckFailure then
slot3 = i18n("word_live2dfiles_checkfailed")
slot4 = i18n("word_live2dfiles_retry")
slot5 = string.format("ERROR(CODE:%d)", slot1.errorCode)
slot6 = 0
slot7 = false
elseif slot2 == DownloadState.Updating then
slot3 = i18n("word_live2dfiles_update")
slot4 = string.format("(%d/%d)", slot1.downloadCount, slot1.downloadTotal)
slot5 = slot1.downPath
slot6 = slot1.downloadCount / math.max(slot1.downloadTotal, 1)
slot7 = false
slot8 = true
elseif slot2 == DownloadState.UpdateSuccess then
slot3 = i18n("word_live2dfiles_update_end_title")
slot4 = i18n("word_live2dfiles_update_end")
slot5 = "V." .. slot1.CurrentVersion.Build
slot6 = 1
slot7 = false
elseif slot2 == DownloadState.UpdateFailure then
slot3 = i18n("word_live2dfiles_update_failed")
slot4 = i18n("word_live2dfiles_update_retry")
slot5 = string.format("ERROR(CODE:%d)", slot1.errorCode)
slot6 = slot1.downloadCount / math.max(slot1.downloadTotal, 1)
slot7 = true
end
if slot5:len() > 15 then
slot5 = slot5:sub(1, 12) .. "..."
end
setText(slot0.live2DDownloadInfo1, slot4)
setText(slot0.live2DDownloadInfo2, slot5)
setAnchoredPosition(slot0.live2DDownloadInfo2, {
x = slot2 == DownloadState.CheckToUpdate and 82.5 or 91.5
})
setSlider(slot0.live2DDownloadProgress, 0, 1, slot6)
setActive(slot0.live2DDownloadProgressHandle, slot6 ~= 0 and slot6 ~= 1)
setActive(slot0.live2DDownloadDot, slot7)
setActive(slot0.live2DDownloadLoading, slot8)
setActive(slot0.live2DDownloadLabelNew, slot2 == DownloadState.CheckToUpdate)
end
function slot0.updateGalleryDownloadState(slot0)
slot3, slot4, slot5, slot6, slot7 = nil
slot8 = false
if BundleWizard.Inst:GetGroupMgr("GALLERY_PIC").state == DownloadState.None then
slot3 = i18n("word_soundfiles_download_title")
slot4 = i18n("word_soundfiles_download")
slot5 = "DOWNLOAD"
slot6 = 0
slot7 = false
elseif slot2 == DownloadState.Checking then
slot3 = i18n("word_soundfiles_checking_title")
slot4 = i18n("word_soundfiles_checking")
slot5 = "CHECKING"
slot6 = 0
slot7 = false
elseif slot2 == DownloadState.CheckToUpdate then
slot3 = i18n("word_soundfiles_checkend_title")
slot4 = i18n("word_soundfiles_checkend")
slot5 = string.format("V.%d > V.%d", slot1.localVersion.Build, slot1.serverVersion.Build)
slot6 = 0
slot7 = true
elseif slot2 == DownloadState.CheckOver then
slot3 = i18n("word_soundfiles_checkend_title")
slot4 = i18n("word_soundfiles_noneedupdate")
slot5 = "V." .. slot1.CurrentVersion.Build
slot6 = 1
slot7 = false
elseif slot2 == DownloadState.CheckFailure then
slot3 = i18n("word_soundfiles_checkfailed")
slot4 = i18n("word_soundfiles_retry")
slot5 = string.format("ERROR(CODE:%d)", slot1.errorCode)
slot6 = 0
slot7 = false
elseif slot2 == DownloadState.Updating then
slot3 = i18n("word_soundfiles_update")
slot4 = string.format("(%d/%d)", slot1.downloadCount, slot1.downloadTotal)
slot5 = slot1.downPath
slot6 = slot1.downloadCount / math.max(slot1.downloadTotal, 1)
slot7 = false
slot8 = true
elseif slot2 == DownloadState.UpdateSuccess then
slot3 = i18n("word_soundfiles_update_end_title")
slot4 = i18n("word_soundfiles_update_end")
slot5 = "V." .. slot1.CurrentVersion.Build
slot6 = 1
slot7 = false
elseif slot2 == DownloadState.UpdateFailure then
slot3 = i18n("word_soundfiles_update_failed")
slot4 = i18n("word_soundfiles_update_retry")
slot5 = string.format("ERROR(CODE:%d)", slot1.errorCode)
slot6 = slot1.downloadCount / math.max(slot1.downloadTotal, 1)
slot7 = true
end
if slot5:len() > 15 then
slot5 = slot5:sub(1, 12) .. "..."
end
setText(slot0.galleryDownloadInfo1, slot4)
setText(slot0.galleryDownloadInfo2, slot5)
setAnchoredPosition(slot0.galleryDownloadInfo2, {
x = slot2 == DownloadState.CheckToUpdate and 82.5 or 91.5
})
setSlider(slot0.galleryDownloadProgress, 0, 1, slot6)
setActive(slot0.galleryDownloadProgressHandle, slot6 ~= 0 and slot6 ~= 1)
setActive(slot0.galleryDownloadDot, slot7)
setActive(slot0.galleryDownloadLoading, slot8)
setActive(slot0.galleryDownloadLabelNew, slot2 == DownloadState.CheckToUpdate)
end
function slot0.updateMusicDownloadState(slot0)
slot3, slot4, slot5, slot6, slot7 = nil
slot8 = false
if BundleWizard.Inst:GetGroupMgr("GALLERY_BGM").state == DownloadState.None then
slot3 = i18n("word_soundfiles_download_title")
slot4 = i18n("word_soundfiles_download")
slot5 = "DOWNLOAD"
slot6 = 0
slot7 = false
elseif slot2 == DownloadState.Checking then
slot3 = i18n("word_soundfiles_checking_title")
slot4 = i18n("word_soundfiles_checking")
slot5 = "CHECKING"
slot6 = 0
slot7 = false
elseif slot2 == DownloadState.CheckToUpdate then
slot3 = i18n("word_soundfiles_checkend_title")
slot4 = i18n("word_soundfiles_checkend")
slot5 = string.format("V.%d > V.%d", slot1.localVersion.Build, slot1.serverVersion.Build)
slot6 = 0
slot7 = true
elseif slot2 == DownloadState.CheckOver then
slot3 = i18n("word_soundfiles_checkend_title")
slot4 = i18n("word_soundfiles_noneedupdate")
slot5 = "V." .. slot1.CurrentVersion.Build
slot6 = 1
slot7 = false
elseif slot2 == DownloadState.CheckFailure then
slot3 = i18n("word_soundfiles_checkfailed")
slot4 = i18n("word_soundfiles_retry")
slot5 = string.format("ERROR(CODE:%d)", slot1.errorCode)
slot6 = 0
slot7 = false
elseif slot2 == DownloadState.Updating then
slot3 = i18n("word_soundfiles_update")
slot4 = string.format("(%d/%d)", slot1.downloadCount, slot1.downloadTotal)
slot5 = slot1.downPath
slot6 = slot1.downloadCount / math.max(slot1.downloadTotal, 1)
slot7 = false
slot8 = true
elseif slot2 == DownloadState.UpdateSuccess then
slot3 = i18n("word_soundfiles_update_end_title")
slot4 = i18n("word_soundfiles_update_end")
slot5 = "V." .. slot1.CurrentVersion.Build
slot6 = 1
slot7 = false
elseif slot2 == DownloadState.UpdateFailure then
slot3 = i18n("word_soundfiles_update_failed")
slot4 = i18n("word_soundfiles_update_retry")
slot5 = string.format("ERROR(CODE:%d)", slot1.errorCode)
slot6 = slot1.downloadCount / math.max(slot1.downloadTotal, 1)
slot7 = true
end
if slot5:len() > 15 then
slot5 = slot5:sub(1, 12) .. "..."
end
setText(slot0.musicDownloadInfo1, slot4)
setText(slot0.musicDownloadInfo2, slot5)
setAnchoredPosition(slot0.musicDownloadInfo2, {
x = slot2 == DownloadState.CheckToUpdate and 82.5 or 91.5
})
setSlider(slot0.musicDownloadProgress, 0, 1, slot6)
setActive(slot0.musicDownloadProgressHandle, slot6 ~= 0 and slot6 ~= 1)
setActive(slot0.musicDownloadDot, slot7)
setActive(slot0.musicDownloadLoading, slot8)
setActive(slot0.musicDownloadLabelNew, slot2 == DownloadState.CheckToUpdate)
end
slot5 = nil
function slot6()
slot0 = pg.SecondaryPWDMgr.GetInstance()
uv0 = uv0 or {
[slot0.UNLOCK_SHIP] = {
title = i18n("words_settings_unlock_ship")
},
[slot0.RESOLVE_EQUIPMENT] = {
title = i18n("words_settings_resolve_equip")
},
[slot0.UNLOCK_COMMANDER] = {
title = i18n("words_settings_unlock_commander")
},
[slot0.CREATE_INHERIT] = {
title = i18n("words_settings_create_inherit")
}
}
return uv0
end
function slot0.initOtherPanel(slot0)
if PlayerPrefs.GetFloat("firstIntoOtherPanel") == 0 then
setActive(slot0.otherToggle:Find("tip"), true)
end
slot0.otherContent = slot0:findTF("main/other/scroll_view/Viewport/content")
slot0.redeem = slot0:findTF("redeem", slot0.otherContent)
slot1 = true
setActive(slot0:findTF("account", slot0.otherContent), false)
if PLATFORM_CODE == PLATFORM_CH or PLATFORM_CODE == PLATFORM_KR then
if PLATFORM_CODE == PLATFORM_KR then
slot0:initKrHelp()
end
if PLATFORM == PLATFORM_IPHONEPLAYER then
slot1 = false
end
elseif PLATFORM_CODE == PLATFORM_JP then
slot0.accountJP = slot0:findTF("account", slot0.otherContent)
setActive(slot0.accountJP, true)
slot0:initJPAccountPanel(slot0.accountJP)
if PLATFORM == PLATFORM_IPHONEPLAYER then
slot1 = false
end
elseif PLATFORM_CODE == PLATFORM_US then
slot0.accountUS = slot0:findTF("account_us", slot0.otherContent)
setActive(slot0.accountUS, true)
slot0:initUSAccountPanel(slot0.accountUS)
slot1 = false
elseif PLATFORM_CODE == PLATFORM_CHT then
slot0.accountTw = slot0:findTF("account_tw", slot0.otherContent)
setActive(slot0.accountTw, true)
slot0:UpdateTwAccountPanel(slot0.accountTw)
if PLATFORM == PLATFORM_IPHONEPLAYER then
slot1 = false
end
end
if slot1 then
setActive(slot0.redeem, true)
slot0.codeInput = slot0:findTF("voucher", slot0.redeem)
slot0.placeholder = slot0:findTF("Placeholder", slot0.codeInput)
slot0.placeholder:GetComponent(typeof(Text)).text = i18n("exchangecode_use_placeholder")
slot0.achieveBtn = slot0:findTF("submit", slot0.codeInput)
onButton(slot0, slot0.achieveBtn, function ()
pg.m02:sendNotification(GAME.EXCHANGECODE_USE, {
key = uv0.codeInput:GetComponent(typeof(InputField)).text
})
end, SFX_CONFIRM)
setGray(slot0.achieveBtn, getInputText(slot0.codeInput) == "")
onInputChanged(slot0, slot0.codeInput, function ()
setGray(uv0.achieveBtn, getInputText(uv0.codeInput) == "")
end)
else
setActive(slot0.redeem, false)
end
slot0.notchPanel = slot0:findTF("main/options/scroll_view/Viewport/content/notch_setting")
if ADAPT_NOTICE < Screen.width / Screen.height - 0.001 then
setActive(slot0.notchPanel, true)
slot0.notchSlider = slot0:findTF("slider", slot0.notchPanel)
setSlider(slot0.notchSlider, ADAPT_MIN, slot2, getProxy(SettingsProxy):GetScreenRatio())
slot0:initSoundSlider(slot0.notchSlider, function (slot0)
uv0:SetScreenRatio(slot0)
NotchAdapt.CheckNotchRatio = slot0
NotchAdapt.AdjustUI()
end)
else
setActive(slot0.notchPanel, false)
end
onButton(slot0, slot0:findTF("secondpwd/btnhelp", slot0.otherContent), function ()
pg.MsgboxMgr.GetInstance():ShowMsgBox({
type = MSGBOX_TYPE_HELP,
helps = i18n("secondary_password_help")
})
end)
slot4 = slot0:findTF("secondpwd", slot0.otherContent)
slot9 = getProxy(SecondaryPWDProxy):getRawData()
onButton(slot0, slot4:Find("options/close"), function ()
if uv0.state > 0 then
uv1:ChangeSetting({}, function ()
uv0:updateOtherPanel()
end)
end
end, SFX_UI_TAG)
onButton(slot0, slot4:Find("options/open"), function ()
if uv0.state <= 0 then
function slot0()
uv0:SetPassword(function ()
uv0:updateOtherPanel()
end)
end
if PlayerPrefs.GetFloat("firstOpenSecondaryPassword") == 0 then
pg.MsgboxMgr.GetInstance():ShowMsgBox({
type = MSGBOX_TYPE_HELP,
helps = i18n("secondary_password_help"),
onYes = slot0,
onClose = slot0
})
PlayerPrefs.SetFloat("firstOpenSecondaryPassword", 1)
PlayerPrefs.Save()
else
slot0()
end
end
end, SFX_UI_TAG)
slot0.secPwdOpts = {}
for slot15, slot16 in ipairs(uv0()) do
if table.contains(pg.SecondaryPWDMgr.GetInstance().LIMITED_OPERATION, slot15) then
slot17 = cloneTplTo(slot0:findTF("notify_tpl"), slot0:findTF("limited_operations/options", slot0.otherContent))
slot0.secPwdOpts[slot15] = slot17
setText(slot0:findTF("Text", slot17), slot16.title)
onButton(slot0, slot17, function ()
slot1 = nil
if not table.contains(uv0.system_list, uv1) then
slot1 = Clone(uv0.system_list)
slot1[#slot1 + 1] = uv1
table.sort(slot1, function (slot0, slot1)
return slot0 < slot1
end)
elseif slot0 then
for slot5 = #Clone(uv0.system_list), 1, -1 do
if slot1[slot5] == uv1 then
table.remove(slot1, slot5)
end
end
end
uv2:ChangeSetting(slot1, function ()
uv0:updateOtherPanel()
end)
end, SFX_UI_TAG)
end
end
slot0:UpdateAgreementPanel()
slot0:updateOtherPanel()
end
function slot0.UpdateAgreementPanel(slot0)
slot2 = PLATFORM_CODE == PLATFORM_CH
setActive(slot0:findTF("agreement", slot0.otherContent), slot2)
if slot2 then
onButton(slot0, slot1:Find("private"), function ()
pg.SdkMgr.GetInstance():ShowPrivate()
end, SFX_PANEL)
onButton(slot0, slot1:Find("licence"), function ()
pg.SdkMgr.GetInstance():ShowLicence()
end, SFX_PANEL)
end
end
function slot0.updateOtherPanel(slot0)
slot1 = slot0:findTF("secondpwd", slot0.otherContent)
slot2 = slot1:Find("options/close")
slot3 = slot1:Find("options/open")
slot4 = pg.SecondaryPWDMgr.GetInstance()
slot7 = getProxy(SecondaryPWDProxy):getRawData().state > 0
setActive(slot2:Find("on"), not slot7)
setActive(slot2:Find("off"), slot7)
setActive(slot3:Find("on"), slot7)
setActive(slot3:Find("off"), not slot7)
for slot11, slot12 in pairs(slot0.secPwdOpts) do
slot13 = table.contains(slot6.system_list, slot11)
slot12:GetComponent(typeof(Button)).interactable = slot7
setActive(slot12:Find("on/on_on"), slot13)
setActive(slot12:Find("off/off_off"), slot13)
setActive(slot12:Find("on/on_off"), not slot13)
setActive(slot12:Find("off/off_on"), not slot13)
end
end
function slot0.clearExchangeCode(slot0)
slot0.codeInput:GetComponent(typeof(InputField)).text = ""
end
slot7 = true
function slot0.onAddToggleEvent(slot0, slot1, slot2, slot3, slot4, slot5)
slot7 = GetComponent(slot2, typeof(Toggle)).onValueChanged
pg.DelegateInfo.Add(slot1, slot7)
slot7:AddListener(function (slot0)
if uv0 then
if slot0 and uv1 and uv2.isOn == slot0 then
uv1 = SFX_UI_TAG
pg.CriMgr.GetInstance():PlaySoundEffect_V3(uv1)
elseif not slot0 and uv3 then
pg.CriMgr.GetInstance():PlaySoundEffect_V3(uv3)
end
end
uv4(slot0)
end)
if not IsNil(GetComponent(slot2, typeof(UIToggleEvent))) then
slot8:Rebind()
end
end
function slot0.didEnter(slot0)
onButton(slot0, slot0.backButton, function ()
uv0:emit(uv1.ON_BACK)
end, SFX_CANCEL)
onButton(slot0, slot0.logoutButton, function ()
pg.MsgboxMgr.GetInstance():ShowMsgBox({
content = i18n("main_settingsScene_quest_exist"),
onYes = function ()
uv0:emit(SettingsMediator.ON_LOGOUT)
end
})
end, SFX_PANEL)
onButton(slot0, slot0.helpUS, function ()
pg.SdkMgr.GetInstance():OpenYostarHelp()
end)
slot0:onAddToggleEvent(slot0, slot0.otherToggle, function (slot0)
if slot0 and PlayerPrefs.GetFloat("firstIntoOtherPanel") == 0 then
setActive(uv0.otherToggle:Find("tip"), false)
slot2 = uv0:findTF("main/other/scroll_view/Viewport/content")
setAnchoredPosition(slot2, {
x = slot2.anchoredPosition.x,
y = -uv0:findTF("secondpwd", slot2).anchoredPosition.y
})
PlayerPrefs.SetFloat("firstIntoOtherPanel", 1)
PlayerPrefs.Save()
end
end)
slot1 = slot0.soundToggle
if slot0.contextData.toggle and uv0.EnterToggle[slot0.contextData.toggle] then
slot1 = slot0[slot0.contextData.toggle .. "Toggle"]
end
triggerToggle(slot1, true)
if slot1 == slot0.optionsToggle and slot0.contextData.scroll then
if slot0._tf:Find("main/options/scroll_view"):Find("Viewport"):Find("content"):Find(slot0.contextData.scroll) then
onDelayTick(function ()
scrollTo(uv3, nil, 1 - math.clamp(math.abs(uv0.anchoredPosition.y) / (uv1.rect.height - uv2.rect.height), 0, 1))
end, 0.05)
end
end
end
function slot0.onBackPressed(slot0)
if isActive(slot0.repairMask) then
return
end
pg.CriMgr.GetInstance():PlaySoundEffect_V3(SFX_CANCEL)
if isActive(GameObject.Find("OverlayCamera/Overlay/UIMain/DialogPanel")) then
triggerButton(slot1.transform:Find("dialog/title/back"))
return
end
slot0:emit(uv0.ON_BACK)
if BUTTON_SOUND_EFFECT then
pg.CriMgr.GetInstance():PlaySoundEffect_V3(SFX_CANCEL)
end
end
function slot0.clearCV(slot0)
if slot0._currentVoice then
slot0._currentVoice:Stop(true)
end
slot0._currentVoice = nil
if slot0._cvList then
for slot4, slot5 in pairs(slot0._cvList) do
pg.CriMgr.UnloadCVBank(pg.CriMgr.GetCVBankName(slot4))
pg.CriMgr.UnloadCVBank(pg.CriMgr.GetBattleCVBankName(slot4))
end
end
slot0._cvList = nil
end
function slot0.willExit(slot0)
if slot0.eventTriggers then
for slot4, slot5 in pairs(slot0.eventTriggers) do
ClearEventTrigger(slot4)
end
slot0.eventTriggers = nil
end
slot0:clearCV()
slot0.soundDownloadTimer:Stop()
slot0.soundDownloadTimer = nil
slot0.live2DDownloadTimer:Stop()
slot0.live2DDownloadTimer = nil
slot0.galleryDownloadTimer:Stop()
slot0.galleryDownloadTimer = nil
slot0.musicDownloadTimer:Stop()
slot0.musicDownloadTimer = nil
slot0.userProxy = nil
slot0.msgBox:Destroy()
slot0.msgBox = nil
end
function slot0.initJPAccountPanel(slot0, slot1)
slot0.userProxy = getProxy(UserProxy)
slot0.accountTwitterUI = slot0:findTF("page1", slot1)
slot0.goTranscodeUIBtn = slot0:findTF("bind_account", slot0:findTF("btn_layout/account_con", slot0.accountTwitterUI))
slot3 = slot0:findTF("btn_layout/twitter_con", slot0.accountTwitterUI)
slot0.twitterBtn = slot0:findTF("bind_twitter", slot3)
slot0.twitterUnlinkBtn = slot0:findTF("unlink_twitter", slot3)
slot0.twitterLinkSign = slot0:findTF("twitter_status", slot3)
slot4 = slot0:findTF("btn_layout/apple_con", slot0.accountTwitterUI)
slot0.appleBtn = slot0:findTF("bind_apple", slot4)
slot0.appleUnlinkBtn = slot0:findTF("unlink_apple", slot4)
slot0.appleLinkSign = slot0:findTF("apple_status", slot4)
setActive(slot4, PLATFORM_CODE == PLATFORM_JP and pg.SdkMgr.GetInstance():GetChannelUID() == "1")
slot5 = slot0:findTF("btn_layout/amazon_con", slot0.accountTwitterUI)
slot0.amazonBtn = slot0:findTF("bind_amazon", slot5)
slot0.amazonUnlinkBtn = slot0:findTF("unlink_amazon", slot5)
slot0.amazonLinkSign = slot0:findTF("amazon_status", slot5)
setActive(slot5, PLATFORM_CODE == PLATFORM_JP and pg.SdkMgr.GetInstance():GetChannelUID() == "3")
slot0.transcodeUI = slot0:findTF("page2", slot1)
slot0.uidTxt = slot0:findTF("account_name/Text", slot0.transcodeUI)
slot0.transcodeTxt = slot0:findTF("password/Text", slot0.transcodeUI)
slot0.getCodeBtn = slot0:findTF("publish_transcode", slot0.transcodeUI)
slot0.codeDesc = slot0:findTF("title_desc", slot0.transcodeUI)
onButton(slot0, slot0.getCodeBtn, function ()
if uv0.transcode == "" then
slot1 = pg.SecondaryPWDMgr
slot1:LimitedOperation(slot1.CREATE_INHERIT, nil, function ()
pg.SdkMgr.GetInstance():TranscodeRequest()
end)
end
end)
onButton(slot0, slot0.twitterBtn, function ()
pg.SdkMgr.GetInstance():LinkSocial(AIRI_PLATFORM_TWITTER)
end)
onButton(slot0, slot0.twitterUnlinkBtn, function ()
pg.SdkMgr.GetInstance():UnlinkSocial(AIRI_PLATFORM_TWITTER)
end)
onButton(slot0, slot0.appleBtn, function ()
pg.SdkMgr.GetInstance():LinkSocial(AIRI_PLATFORM_APPLE)
end)
onButton(slot0, slot0.appleUnlinkBtn, function ()
pg.SdkMgr.GetInstance():UnlinkSocial(AIRI_PLATFORM_APPLE)
end)
onButton(slot0, slot0.amazonBtn, function ()
pg.SdkMgr.GetInstance():LinkSocial(AIRI_PLATFORM_AMAZON)
end)
onButton(slot0, slot0.amazonUnlinkBtn, function ()
pg.SdkMgr.GetInstance():UnlinkSocial(AIRI_PLATFORM_AMAZON)
end)
onButton(slot0, slot0.goTranscodeUIBtn, function ()
setActive(uv0.accountTwitterUI, false)
setActive(uv0.transcodeUI, true)
end)
slot0:checkAllAccountState()
end
function slot0.checkAllAccountState(slot0)
slot0:checkTranscodeView()
slot0:checkAccountTwitterView()
slot0:checkAccountAppleView()
slot0:checkAccountAmazonView()
end
function slot0.showTranscode(slot0, slot1)
slot0.userProxy:saveTranscode(slot1)
slot0:checkTranscodeView()
end
function slot0.checkTranscodeView(slot0)
slot0.transcode = pg.SdkMgr.GetInstance():GetYostarTransCode() or ""
if not slot0.transcode or slot0.transcode == "" or slot0.transcode == "NULL" then
slot0.transcode = slot0.userProxy:getTranscode()
end
setActive(slot0.codeDesc, slot0.transcode ~= "")
setActive(slot0.getCodeBtn, slot0.transcode == "")
if slot0.transcode ~= "" then
setText(slot0.uidTxt, pg.SdkMgr.GetInstance():GetYostarUid())
setText(slot0.transcodeTxt, slot0.transcode)
end
end
function slot0.checkAccountTwitterView(slot0)
slot1 = pg.SdkMgr.GetInstance():IsSocialLink(AIRI_PLATFORM_TWITTER)
setActive(slot0.twitterUnlinkBtn, slot1)
setActive(slot0.twitterLinkSign, slot1)
setActive(slot0.twitterBtn, not slot1)
if slot1 then
setText(slot0.twitterLinkSign, i18n("twitter_link_title", pg.SdkMgr.GetInstance():GetSocialName(AIRI_PLATFORM_TWITTER)))
end
end
function slot0.checkAccountAppleView(slot0)
slot1 = pg.SdkMgr.GetInstance():IsSocialLink(AIRI_PLATFORM_APPLE)
setActive(slot0.appleUnlinkBtn, slot1)
setActive(slot0.appleLinkSign, slot1)
setActive(slot0.appleBtn, not slot1)
if isTwitterLinked then
setText(slot0.appleLinkSign, i18n("apple_link_title", pg.SdkMgr.GetInstance():GetSocialName(AIRI_PLATFORM_APPLE)))
end
end
function slot0.checkAccountAmazonView(slot0)
if pg.SdkMgr.GetInstance():GetChannelUID() == "3" then
slot1 = pg.SdkMgr.GetInstance():IsSocialLink(AIRI_PLATFORM_AMAZON)
setActive(slot0.amazonUnlinkBtn, slot1)
setActive(slot0.amazonLinkSign, slot1)
setActive(slot0.amazonBtn, not slot1)
if isTwitterLinked then
setText(slot0.amazonLinkSign, i18n("amazon_link_title", pg.SdkMgr.GetInstance():GetSocialName(AIRI_PLATFORM_AMAZON)))
end
end
end
function slot0.initUSAccountPanel(slot0, slot1)
slot2 = slot0:findTF("page1", slot1)
slot3 = slot0:findTF("btn_layout/twitter_con", slot2)
slot0.btnBindTwitter = slot0:findTF("bind_twitter", slot3)
slot0.btnUnlinkTwitter = slot0:findTF("unlink_twitter", slot3)
slot0.twitterStatus = slot0:findTF("twitter_status", slot3)
slot4 = slot0:findTF("btn_layout/facebook_con", slot2)
slot0.btnBindFacebook = slot0:findTF("bind_facebook", slot4)
slot0.btnUnlinkFacebook = slot0:findTF("unlink_facebook", slot4)
slot0.facebookStatus = slot0:findTF("facebook_status", slot4)
setActive(slot4, PLATFORM_CODE == PLATFORM_US and pg.SdkMgr.GetInstance():GetChannelUID() ~= "3")
slot5 = slot0:findTF("btn_layout/yostar_con", slot2)
slot0.btnBindYostar = slot0:findTF("bind_yostar", slot5)
slot0.btnUnlinkYostar = slot0:findTF("unlink_yostar", slot5)
slot0.yostarStatus = slot0:findTF("yostar_status", slot5)
slot6 = slot0:findTF("btn_layout/apple_con", slot2)
slot0.btnBindApple = slot0:findTF("bind_apple", slot6)
slot0.btnUnlinkApple = slot0:findTF("unlink_apple", slot6)
slot0.appleStatus = slot0:findTF("apple_status", slot6)
setActive(slot6, PLATFORM_CODE == PLATFORM_US and pg.SdkMgr.GetInstance():GetChannelUID() == "1")
slot7 = slot0:findTF("btn_layout/amazon_con", slot2)
slot0.btnBindAmazon = slot0:findTF("bind_amazon", slot7)
slot0.btnUnlinkAmazon = slot0:findTF("unlink_amazon", slot7)
slot0.amazonStatus = slot0:findTF("amazon_status", slot7)
setActive(slot7, PLATFORM_CODE == PLATFORM_US and pg.SdkMgr.GetInstance():GetChannelUID() == "3")
slot0.yostarAlert = slot0:findTF("page2", slot1)
slot0.yostarEmailTxt = slot0:findTF("email_input_txt", slot0.yostarAlert)
slot0.yostarCodeTxt = slot0:findTF("code_input_txt", slot0.yostarAlert)
slot0.yostarGenCodeBtn = slot0:findTF("gen_code_btn", slot0.yostarAlert)
slot0.yostarGenTxt = slot0:findTF("Text", slot0.yostarGenCodeBtn)
slot0.yostarSureBtn = slot0:findTF("login_btn", slot0.yostarAlert)
onButton(slot0, slot0.btnBindTwitter, function ()
pg.SdkMgr.GetInstance():LinkSocial(AIRI_PLATFORM_TWITTER)
end)
onButton(slot0, slot0.btnUnlinkTwitter, function ()
pg.SdkMgr.GetInstance():UnlinkSocial(AIRI_PLATFORM_TWITTER)
end)
onButton(slot0, slot0.btnBindFacebook, function ()
pg.SdkMgr.GetInstance():LinkSocial(AIRI_PLATFORM_FACEBOOK)
end)
onButton(slot0, slot0.btnUnlinkFacebook, function ()
pg.SdkMgr.GetInstance():UnlinkSocial(AIRI_PLATFORM_FACEBOOK)
end)
onButton(slot0, slot0.btnBindApple, function ()
pg.SdkMgr.GetInstance():LinkSocial(AIRI_PLATFORM_APPLE)
end)
onButton(slot0, slot0.btnUnlinkApple, function ()
pg.SdkMgr.GetInstance():UnlinkSocial(AIRI_PLATFORM_APPLE)
end)
onButton(slot0, slot0.btnBindAmazon, function ()
pg.SdkMgr.GetInstance():LinkSocial(AIRI_PLATFORM_AMAZON)
end)
onButton(slot0, slot0.btnUnlinkAmazon, function ()
pg.SdkMgr.GetInstance():UnlinkSocial(AIRI_PLATFORM_AMAZON)
end)
onButton(slot0, slot0.btnBindYostar, function ()
pg.UIMgr.GetInstance():BlurPanel(uv0.yostarAlert, false)
setActive(uv0.yostarAlert, true)
end)
onButton(slot0, slot0.yostarAlert, function ()
pg.UIMgr.GetInstance():UnblurPanel(uv0.yostarAlert, uv0.accountUS)
setActive(uv0.yostarAlert, false)
end)
onButton(slot0, slot0.yostarGenCodeBtn, function ()
if getInputText(uv0.yostarEmailTxt) ~= "" then
pg.SdkMgr.GetInstance():VerificationCodeReq(slot0)
uv0:checkAiriGenCodeCounter_US()
else
pg.TipsMgr.GetInstance():ShowTips(i18n("verification_code_req_tip1"))
end
end)
onButton(slot0, slot0.yostarSureBtn, function ()
slot1 = getInputText(uv0.yostarCodeTxt)
if getInputText(uv0.yostarEmailTxt) ~= "" and slot1 ~= "" then
pg.UIMgr.GetInstance():LoadingOn()
pg.SdkMgr.GetInstance():LinkSocial(AIRI_PLATFORM_YOSTAR, slot0, slot1)
else
pg.TipsMgr.GetInstance():ShowTips(i18n("verification_code_req_tip3"))
end
triggerButton(uv0.yostarAlert)
end)
slot0:checkAllAccountState_US()
slot0:checkAiriGenCodeCounter_US()
end
function slot0.checkAllAccountState_US(slot0)
slot0:checkAccountTwitterView_US()
slot0:checkAccountFacebookView_US()
slot0:checkAccountAppleView_US()
slot0:checkAccountYostarView_US()
slot0:checkAccountAmazonView_US()
end
function slot0.checkAccountTwitterView_US(slot0)
slot1 = pg.SdkMgr.GetInstance():IsSocialLink(AIRI_PLATFORM_TWITTER)
setActive(slot0.btnUnlinkTwitter, slot1)
setActive(slot0.twitterStatus, slot1)
setActive(slot0.btnBindTwitter, not slot1)
if slot1 then
setText(slot0.twitterStatus, i18n("twitter_link_title", pg.SdkMgr.GetInstance():GetSocialName(AIRI_PLATFORM_TWITTER)))
end
end
function slot0.checkAccountFacebookView_US(slot0)
if PLATFORM_CODE == PLATFORM_US and pg.SdkMgr.GetInstance():GetChannelUID() ~= "3" then
slot1 = pg.SdkMgr.GetInstance():IsSocialLink(AIRI_PLATFORM_FACEBOOK)
setActive(slot0.btnUnlinkFacebook, slot1)
setActive(slot0.facebookStatus, slot1)
setActive(slot0.btnBindFacebook, not slot1)
if slot1 then
setText(slot0.facebookStatus, i18n("facebook_link_title", pg.SdkMgr.GetInstance():GetSocialName(AIRI_PLATFORM_FACEBOOK)))
end
end
end
function slot0.checkAccountAppleView_US(slot0)
slot1 = pg.SdkMgr.GetInstance():IsSocialLink(AIRI_PLATFORM_APPLE)
setActive(slot0.btnUnlinkApple, slot1)
setActive(slot0.appleStatus, slot1)
setActive(slot0.btnBindApple, not slot1)
if slot1 then
setText(slot0.appleStatus, i18n("apple_link_title", pg.SdkMgr.GetInstance():GetSocialName(AIRI_PLATFORM_APPLE)))
end
end
function slot0.checkAccountAmazonView_US(slot0)
if pg.SdkMgr.GetInstance():GetChannelUID() == "3" then
slot1 = pg.SdkMgr.GetInstance():IsSocialLink(AIRI_PLATFORM_AMAZON)
setActive(slot0.btnUnlinkAmazon, slot1)
setActive(slot0.amazonStatus, slot1)
setActive(slot0.btnBindAmazon, not slot1)
if slot1 then
setText(slot0.amazonStatus, i18n("amazon_link_title", pg.SdkMgr.GetInstance():GetSocialName(AIRI_PLATFORM_AMAZON)))
end
end
end
function slot0.checkAccountYostarView_US(slot0)
slot1 = pg.SdkMgr.GetInstance():IsSocialLink(AIRI_PLATFORM_YOSTAR)
setActive(slot0.btnUnlinkYostar, slot1)
setActive(slot0.yostarStatus, slot1)
setActive(slot0.btnBindYostar, not slot1)
if slot1 then
setText(slot0.yostarStatus, i18n("yostar_link_title", pg.SdkMgr.GetInstance():GetSocialName(AIRI_PLATFORM_YOSTAR)))
end
end
function slot0.checkAiriGenCodeCounter_US(slot0)
if GetAiriGenCodeTimeRemain() > 0 then
setButtonEnabled(slot0.yostarGenCodeBtn, false)
slot0.genCodeTimer = Timer.New(function ()
if GetAiriGenCodeTimeRemain() > 0 then
setText(uv0.yostarGenTxt, "(" .. slot0 .. ")")
else
setText(uv0.yostarGenTxt, "Generate")
uv0:clearAiriGenCodeTimer_US()
end
end, 1, -1):Start()
end
end
function slot0.clearAiriGenCodeTimer_US(slot0)
setButtonEnabled(slot0.yostarGenCodeBtn, true)
if slot0.genCodeTimer then
slot0.genCodeTimer:Stop()
slot0.genCodeTimer = nil
end
end
function slot0.initKrHelp(slot0)
onButton(slot0, slot0:findTF("blur_panel/adapt/left_length/helpBtn"), function ()
print("help:")
pg.SdkMgr.GetInstance():BugReport()
end, SFX_CANCEL)
end
function slot0.UpdateTwAccountPanel(slot0)
if PLATFORM == PLATFORM_ANDROID then
setActive(slot0.accountTw:Find("page1/bind_google"), true)
setActive(slot0.accountTw:Find("page1/bind_gamecenter"), false)
else
setActive(slot0.accountTw:Find("page1/bind_google"), true)
setActive(slot0.accountTw:Find("page1/bind_gamecenter"), false)
end
slot2 = pg.SdkMgr.GetInstance()
for slot11, slot12 in ipairs({
slot0.accountTw:Find("page1/bind_facebook"),
slot0.accountTw:Find("page1/bind_google"),
slot0.accountTw:Find("page1/bind_phone"),
slot0.accountTw:Find("page1/bind_gamecenter")
}) do
slot13 = ({
slot2:IsBindFaceBook(),
slot2:IsBindGoogle(),
slot2:IsBindPhone(),
slot2:IsBindGameCenter()
})[slot11]
setActive(slot12:Find("unbind"), not slot13)
setActive(slot12:Find("bind"), slot13)
onButton(slot0, slot12, function ()
if not uv0 then
uv1:BindSocial(uv2)
end
end, SFX_PANEL)
end
end
return slot0
| 411 | 0.831673 | 1 | 0.831673 | game-dev | MEDIA | 0.76379 | game-dev | 0.947058 | 1 | 0.947058 |
akhuting/gms083 | 2,696 | src/main/resources/scripts/event/AreaBossDoor4.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
-- Odin JavaScript --------------------------------------------------------------------------------
Door boss Spawner (based on xQuasar's King Clang spawner)
**/
function init() {
scheduleNew();
}
function scheduleNew() {
setupTask = em.schedule("start", 0); //spawns upon server start. Each 3 hours an server event checks if boss exists, if not spawns it instantly.
}
function cancelSchedule() {
if (setupTask != null)
setupTask.cancel(true);
}
function start() {
var bossMobid = 9400633;
var bossMapid = 677000012;
var bossMsg = "Astaroth has appeared!";
var bossPos = new Packages.java.awt.Point(842, 0);
var map = em.getChannelServer().getMapFactory().getMap(bossMapid);
if (map.getMonsterById(bossMobid) != null) {
em.schedule("start", 3 * 60 * 60 * 1000);
return;
}
var boss = Packages.server.life.MapleLifeFactory.getMonster(bossMobid);
map.spawnMonsterOnGroundBelow(boss, bossPos);
map.broadcastMessage(Packages.tools.MaplePacketCreator.serverNotice(6, bossMsg));
em.schedule("start", 3 * 60 * 60 * 1000);
}
// ---------- FILLER FUNCTIONS ----------
function dispose() {}
function setup(eim, leaderid) {}
function monsterValue(eim, mobid) {return 0;}
function disbandParty(eim, player) {}
function playerDisconnected(eim, player) {}
function playerEntry(eim, player) {}
function monsterKilled(mob, eim) {}
function scheduledTimeout(eim) {}
function afterSetup(eim) {}
function changedLeader(eim, leader) {}
function playerExit(eim, player) {}
function leftParty(eim, player) {}
function clearPQ(eim) {}
function allMonstersDead(eim) {}
function playerUnregistered(eim, player) {}
| 411 | 0.720781 | 1 | 0.720781 | game-dev | MEDIA | 0.930102 | game-dev | 0.675074 | 1 | 0.675074 |
EngineHub/Intake | 2,679 | intake/src/main/java/com/sk89q/intake/argument/StringListArgs.java | /*
* Intake, a command processing library
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) Intake team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.intake.argument;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
class StringListArgs extends AbstractCommandArgs {
private final List<String> arguments;
private final Map<Character, String> flags;
private final Namespace namespace;
private int position = 0;
StringListArgs(List<String> arguments, Map<Character, String> flags, Namespace namespace) {
checkNotNull(arguments, "arguments");
checkNotNull(flags, "flags");
checkNotNull(namespace, "namespace");
this.arguments = Lists.newArrayList(arguments);
this.flags = flags;
this.namespace = namespace;
}
protected void insert(String argument) {
arguments.add(position, argument);
}
@Override
public boolean hasNext() {
return position < arguments.size();
}
@Override
public String next() throws MissingArgumentException {
try {
return arguments.get(position++);
} catch (IndexOutOfBoundsException ignored) {
throw new MissingArgumentException();
}
}
@Override
public String peek() throws MissingArgumentException {
try {
return arguments.get(position);
} catch (IndexOutOfBoundsException ignored) {
throw new MissingArgumentException();
}
}
@Override
public int position() {
return position;
}
@Override
public int size() {
return arguments.size();
}
@Override
public void markConsumed() {
position = arguments.size();
}
@Override
public Map<Character, String> getFlags() {
return flags;
}
@Override
public Namespace getNamespace() {
return namespace;
}
}
| 411 | 0.870421 | 1 | 0.870421 | game-dev | MEDIA | 0.217173 | game-dev | 0.788855 | 1 | 0.788855 |
Gibberlings3/SwordCoastStratagems | 3,991 | stratagems/kobold/kobold.tpa | INCLUDE ~%MOD_FOLDER%/lib/ai_wrap.tph~
DEFINE_ACTION_FUNCTION kobold BEGIN
LAF kobold_core END
LAF kobold_ambush END
END
DEFINE_ACTION_FUNCTION kobold_core BEGIN
LAF check_label STR_VAR label=dw#help RET value END
ACTION_IF value BEGIN
OUTER_SPRINT help dw#gpsht
END ELSE BEGIN
OUTER_SPRINT help ~%tutu_var%koboldf~
END
// items
ACTION_IF enhanced_edition BEGIN
OUTER_SET dagger_desc1=RESOLVE_STR_REF (@21316)
OUTER_SET dagger_desc2=RESOLVE_STR_REF (@21317)
OUTER_SET arrow_desc=RESOLVE_STR_REF (@21319)
END ELSE BEGIN
OUTER_SET dagger_desc1=RESOLVE_STR_REF (@21306)
OUTER_SET dagger_desc2=RESOLVE_STR_REF (@21307)
OUTER_SET arrow_desc=RESOLVE_STR_REF (@21309)
END
// daggers
itm.copy[dagg01=>dw#kob01]
[
m_identified_name:=@21304
m_unidentified_description:="%dagger_desc1%"
m_identified_description:="%dagger_desc2%"
m_desc_image:=cdagg03
m_icon:=idagg03
m.fx.alter{PATCH_MATCH s_parameter1 WITH 72 BEGIN s_parameter2=21 END 62 BEGIN s_parameter2=20 END 91 BEGIN s_parameter2=16 END DEFAULT END}
m.ab_fx.add{s_opcode=25 s_target=2 s_duration=6 s_parameter1=1 s_parameter2=2 s_save_vs_poison=1}
m.ab_fx.add{s_opcode=25 s_target=1 s_probability1=4 s_duration=6 s_parameter1=1 s_parameter2=2 s_save_vs_poison=1}
]
// arrows
itm.copy[arow01=>dw#kob02]
[
m_identified_name:=@21308
m_identified_description:="%arrow_desc%"
m.ab_fx.add{s_opcode=25 s_target=2 s_duration=6 s_parameter1=2 s_parameter2=2 s_save_vs_poison=1}
m.ab_fx.add{s_opcode=25 s_target=1 s_probability1=4 s_duration=6 s_parameter1=2 s_parameter2=2 s_save_vs_poison=1}
]
// install needed files
LAF install STR_VAR files=~dw#kobsp.baf dw#kobch.cre dw#kobgd.cre dw#kobsh.cre galtok.d~ location=resource END
// add kobold-summoning script
ACTION_FOR_EACH koboldtype IN obola_a obola_c obola_e obold_a obold_c obold_e oboldal BEGIN
LAF edit_creature STR_VAR creature= ~%tutu_scriptk%%koboldtype%~ editstring=~insert_script_high=>dw#kobsp~ END
END
LAF edit_creature INT_VAR tv=1 STR_VAR creature=kobolda editstring=~insert_script_high=>dw#kobsp~ END
// Commander
MAKE_PATCH
steal_sounds_from=>~%tutu_var%kobold~
say_both_names=>21301
script_race=>~%help%~
remove_items=>~_arow01 _bow05~
add_items=>~%tutu_var%bow05 %tutu_var%arow01(20,quiver2)~
enforce_charclass=>is_bg1
END
LAF edit_creature STR_VAR creature=dw#kobch edits=patch_data END
// guards
MAKE_PATCH
steal_sounds_from=>~%tutu_var%kobold~
say_both_names=>21302
script_race=>~%help%~
enforce_charclass=>is_bg1
END
LAF edit_creature STR_VAR creature=dw#kobgd edits=patch_data END
// shaman
MAKE_PATCH
steal_sounds_from=>~%tutu_var%kobold~
say_both_names=>21303
strip_script=>all
script_race=>~%help%~
enforce_charclass=>is_bg1
enforce_mage=>null
END
LAF edit_creature STR_VAR creature=dw#kobsh edits=patch_data END
END
DEFINE_ACTION_FUNCTION kobold_ambush BEGIN
LAF extend_area_script STR_VAR area=~%NashkelMines_L3%~ top=ambush location=resource END
// the "specifics" change means that they won't hear other kobolds' help cries
LAF clone_creature STR_VAR creature=~dw#kobch=>dw#kbach %tutu_var%kobcomm=>dw#kbacm dw#kobsh=>dw#kbash dw#kobsh=>dw#kbas2 dw#kobgd=>dw#kbagd~
editstring=~specifics=>77~
END
LAF check_label STR_VAR label=dw#mage RET value END
ACTION_IF value BEGIN
LAF edit_creature STR_VAR creature=dw#kbash editstring=~kit=>INVOKER enforce_mage=>null~ END
LAF edit_creature STR_VAR creature=dw#kbas2 editstring=~kit=>ENCHANTER enforce_mage=>null~ END
END
END
| 411 | 0.894189 | 1 | 0.894189 | game-dev | MEDIA | 0.246548 | game-dev | 0.907098 | 1 | 0.907098 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.