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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
shiversoftdev/t8-src | 1,439 | scripts/mp_common/gametypes/os.gsc | // Decompiled by Serious. Credits to Scoba for his original tool, Cerberus, which I heavily upgraded to support remaining features, other games, and other platforms.
#using scripts\mp_common\player\player_loadout.gsc;
#using scripts\core_common\gameobjects_shared.gsc;
#namespace os;
/*
Name: turn_back_time
Namespace: os
Checksum: 0xC5ED5BBD
Offset: 0xA0
Size: 0xC6
Parameters: 1
Flags: None
*/
function turn_back_time(basegametype)
{
gameobjects::register_allowed_gameobject("os");
gameobjects::register_allowed_gameobject(basegametype);
level.oldschoolweapon = getweapon("pistol_standard");
level.primaryoffhandnull = getweapon(#"null_offhand_primary");
level.secondaryoffhandnull = getweapon(#"null_offhand_secondary");
level.givecustomloadout = &give_oldschool_loadout;
}
/*
Name: give_oldschool_loadout
Namespace: os
Checksum: 0xC504632D
Offset: 0x170
Size: 0x136
Parameters: 0
Flags: None
*/
function give_oldschool_loadout()
{
self loadout::init_player(1);
self loadout::function_f436358b("CLASS_ASSAULT");
self giveweapon(level.oldschoolweapon);
self switchtoweapon(level.oldschoolweapon);
self giveweapon(level.primaryoffhandnull);
self giveweapon(level.secondaryoffhandnull);
self setweaponammoclip(level.primaryoffhandnull, 0);
self setweaponammoclip(level.secondaryoffhandnull, 0);
if(self.firstspawn !== 0)
{
self setspawnweapon(level.oldschoolweapon);
}
return level.oldschoolweapon;
}
| 0 | 0.796646 | 1 | 0.796646 | game-dev | MEDIA | 0.980371 | game-dev | 0.585511 | 1 | 0.585511 |
The-Final-Nights/The-Final-Nights | 7,032 | code/modules/research/xenobiology/crossbreeding/stabilized.dm | /*
Stabilized extracts:
Provides a passive buff to the holder.
*/
//To add: Create an effect in crossbreeding/_status_effects.dm with the name "/datum/status_effect/stabilized/[color]"
//Status effect will automatically be applied while held, and lost on drop.
/obj/item/slimecross/stabilized
name = "stabilized extract"
desc = "It seems inert, but anything it touches glows softly..."
effect = "stabilized"
icon_state = "stabilized"
var/datum/status_effect/linked_effect
var/mob/living/owner
/obj/item/slimecross/stabilized/Initialize()
. = ..()
START_PROCESSING(SSobj,src)
/obj/item/slimecross/stabilized/Destroy()
STOP_PROCESSING(SSobj,src)
qdel(linked_effect)
return ..()
/obj/item/slimecross/stabilized/process()
var/humanfound = null
if(ishuman(loc))
humanfound = loc
if(ishuman(loc.loc)) //Check if in backpack.
humanfound = (loc.loc)
if(!humanfound)
return
var/mob/living/carbon/human/H = humanfound
var/effectpath = /datum/status_effect/stabilized
var/static/list/effects = subtypesof(/datum/status_effect/stabilized)
for(var/X in effects)
var/datum/status_effect/stabilized/S = X
if(initial(S.colour) == colour)
effectpath = S
break
if(!H.has_status_effect(effectpath))
var/datum/status_effect/stabilized/S = H.apply_status_effect(effectpath)
owner = H
S.linked_extract = src
STOP_PROCESSING(SSobj,src)
//Colors and subtypes:
/obj/item/slimecross/stabilized/grey
colour = "grey"
effect_desc = "Makes slimes friendly to the owner"
/obj/item/slimecross/stabilized/orange
colour = "orange"
effect_desc = "Passively tries to increase or decrease the owner's body temperature to normal"
/obj/item/slimecross/stabilized/purple
colour = "purple"
effect_desc = "Provides a regeneration effect"
/obj/item/slimecross/stabilized/blue
colour = "blue"
effect_desc = "Makes the owner immune to slipping on water, soap or foam. Space lube and ice are still too slippery."
/obj/item/slimecross/stabilized/metal
colour = "metal"
effect_desc = "Every 30 seconds, adds a sheet of material to a random stack in the owner's backpack."
/obj/item/slimecross/stabilized/yellow
colour = "yellow"
effect_desc = "Every ten seconds it recharges a device on the owner by 10%."
/obj/item/slimecross/stabilized/darkpurple
colour = "dark purple"
effect_desc = "Gives you burning fingertips, automatically cooking any microwavable food you hold."
/obj/item/slimecross/stabilized/darkblue
colour = "dark blue"
effect_desc = "Slowly extinguishes the owner if they are on fire, also wets items like monkey cubes, creating a monkey."
/obj/item/slimecross/stabilized/silver
colour = "silver"
effect_desc = "Slows the rate at which the owner loses nutrition"
/obj/item/slimecross/stabilized/bluespace
colour = "bluespace"
effect_desc = "On a two minute cooldown, when the owner has taken enough damage, they are teleported to a safe place."
/obj/item/slimecross/stabilized/sepia
colour = "sepia"
effect_desc = "Randomly adjusts the owner's speed."
/obj/item/slimecross/stabilized/cerulean
colour = "cerulean"
effect_desc = "Creates a duplicate of the owner. If the owner dies they will take control of the duplicate, unless the death was from beheading or gibbing."
/obj/item/slimecross/stabilized/pyrite
colour = "pyrite"
effect_desc = "Randomly colors the owner every few seconds."
/obj/item/slimecross/stabilized/red
colour = "red"
effect_desc = "Nullifies all equipment based slowdowns."
/obj/item/slimecross/stabilized/green
colour = "green"
effect_desc = "Changes the owner's name and appearance while holding this extract."
/obj/item/slimecross/stabilized/pink
colour = "pink"
effect_desc = "As long as no creatures are harmed in the owner's presense, they will not attack you. If the peace is broken it takes two minutes to restore."
/obj/item/slimecross/stabilized/gold
colour = "gold"
effect_desc = "Creates a pet when held."
var/mob_type
var/datum/mind/saved_mind
var/mob_name = "Familiar"
/obj/item/slimecross/stabilized/gold/proc/generate_mobtype()
var/static/list/mob_spawn_pets = list()
if(mob_spawn_pets.len <= 0)
for(var/T in typesof(/mob/living/simple_animal))
var/mob/living/simple_animal/SA = T
switch(initial(SA.gold_core_spawnable))
if(FRIENDLY_SPAWN)
mob_spawn_pets += T
mob_type = pick(mob_spawn_pets)
/obj/item/slimecross/stabilized/gold/Initialize()
. = ..()
generate_mobtype()
/obj/item/slimecross/stabilized/gold/attack_self(mob/user)
var/choice = input(user, "Which do you want to reset?", "Familiar Adjustment") as null|anything in sort_list(list("Familiar Location", "Familiar Species", "Familiar Sentience", "Familiar Name"))
if(!user.canUseTopic(src, BE_CLOSE))
return
if(isliving(user))
var/mob/living/L = user
if(L.has_status_effect(/datum/status_effect/stabilized/gold))
L.remove_status_effect(/datum/status_effect/stabilized/gold)
if(choice == "Familiar Location")
to_chat(user, "<span class='notice'>You prod [src], and it shudders slightly.</span>")
START_PROCESSING(SSobj, src)
if(choice == "Familiar Species")
to_chat(user, "<span class='notice'>You squeeze [src], and a shape seems to shift around inside.</span>")
generate_mobtype()
START_PROCESSING(SSobj, src)
if(choice == "Familiar Sentience")
to_chat(user, "<span class='notice'>You poke [src], and it lets out a glowing pulse.</span>")
saved_mind = null
START_PROCESSING(SSobj, src)
if(choice == "Familiar Name")
var/newname = sanitize_name(stripped_input(user, "Would you like to change the name of [mob_name]", "Name change", mob_name, MAX_NAME_LEN))
if(newname)
mob_name = newname
to_chat(user, "<span class='notice'>You speak softly into [src], and it shakes slightly in response.</span>")
START_PROCESSING(SSobj, src)
/obj/item/slimecross/stabilized/oil
colour = "oil"
effect_desc = "The owner will violently explode when they die while holding this extract."
/obj/item/slimecross/stabilized/black
colour = "black"
effect_desc = "While strangling someone, the owner's hands melt around their neck, draining their life in exchange for food and healing."
/obj/item/slimecross/stabilized/lightpink
colour = "light pink"
effect_desc = "The owner moves at high speeds while holding this extract, also stabilizes anyone in critical condition around you using Epinephrine."
/obj/item/slimecross/stabilized/adamantine
colour = "adamantine"
effect_desc = "Owner gains a slight boost in damage resistance to all types."
/obj/item/slimecross/stabilized/rainbow
colour = "rainbow"
effect_desc = "Accepts a regenerative extract and automatically uses it if the owner enters a critical condition."
var/obj/item/slimecross/regenerative/regencore
/obj/item/slimecross/stabilized/rainbow/attackby(obj/item/O, mob/user)
var/obj/item/slimecross/regenerative/regen = O
if(istype(regen) && !regencore)
to_chat(user, "<span class='notice'>You place [O] in [src], prepping the extract for automatic application!</span>")
regencore = regen
regen.forceMove(src)
return
return ..()
| 0 | 0.963284 | 1 | 0.963284 | game-dev | MEDIA | 0.980761 | game-dev | 0.975941 | 1 | 0.975941 |
bergerhealer/BKCommonLib | 7,245 | src/test/java/com/bergerkiller/bukkit/common/JsonSerializerTest.java | package com.bergerkiller.bukkit.common;
import com.bergerkiller.bukkit.common.config.JsonSerializer;
import com.bergerkiller.bukkit.common.inventory.CommonItemMaterials;
import com.bergerkiller.bukkit.common.inventory.CommonItemStack;
import com.bergerkiller.bukkit.common.utils.MaterialUtil;
import com.bergerkiller.bukkit.common.wrappers.CustomModelData;
import com.bergerkiller.generated.com.mojang.authlib.GameProfileHandle;
import com.bergerkiller.generated.com.mojang.authlib.properties.PropertyHandle;
import com.bergerkiller.generated.org.bukkit.craftbukkit.util.CraftMagicNumbersHandle;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import static org.junit.Assert.*;
public class JsonSerializerTest {
final int dataVersion = CraftMagicNumbersHandle.getDataVersion();
@Test
public void testItemStackFromToJsonCMD() throws JsonSerializer.JsonSyntaxException {
CommonItemStack item = CommonItemStack.create(MaterialUtil.getFirst("DIAMOND_SWORD", "LEGACY_DIAMOND_SWORD"), 1)
.setCustomModelDataComponents(CustomModelData.EMPTY
.withColors(Arrays.asList(1, 2, 3))
.withFlags(Arrays.asList(true, false, true))
.withFloats(Arrays.asList(1.0f, 2.0f, 3.0f))
.withStrings(Arrays.asList("1", "a", "b")));
JsonSerializer serializer = new JsonSerializer();
String json = serializer.itemStackToJson(item.toBukkit());
CommonItemStack decoded = CommonItemStack.of(serializer.fromJsonToItemStack(json));
assertEquals(item, decoded);
}
@Test
public void testEmptyMapToJson() {
JsonSerializer serializer = new JsonSerializer();
Map<String, Object> jsonMap = new LinkedHashMap<>();
jsonMap.put("key", Collections.emptyMap());
String json = serializer.toJson(jsonMap);
assertEquals("{\"key\":{}}", json);
}
@Test
public void testItemStackToJsonStick() throws JsonSerializer.JsonSyntaxException {
JsonSerializer serializer = new JsonSerializer();
String json = serializer.itemStackToJson(CommonItemStack.create(CommonItemMaterials.STICK, 1).toBukkit());
Map<String, Object> jsonMap = serializer.jsonToMap(json);
assertEquals(dataVersion, ((Number) jsonMap.get("v")).intValue());
assertEquals("STICK", jsonMap.get("type"));
}
@Test
@SuppressWarnings("unchecked")
public void testItemStackToJsonPlayerHead() throws JsonSerializer.JsonSyntaxException {
JsonSerializer serializer = new JsonSerializer();
GameProfileHandle profile = GameProfileHandle.createNew(
UUID.fromString("04049c90-d3e9-4621-9caf-0000aaa58540"),
"HeadDatabase");
profile = profile.withPropertyPut("textures", PropertyHandle.createNew("textures",
"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjllNzVlMDQxNTFlN2NkZThlN2YxNDlkYWU5MmYwYzE0ZWY1ZjNmZjQ1Y2QzMjM5NTc4NzZiMGFkZDJjNDk0OSJ9fX0="));
String json = serializer.itemStackToJson(
CommonItemStack.createPlayerSkull(profile)
.toBukkit());
//System.out.println(json);
Map<String, Object> jsonMap = serializer.jsonToMap(json);
// Just a rough check all the info is in there
assertEquals(dataVersion, ((Number) jsonMap.get("v")).intValue());
assertEquals("PLAYER_HEAD", jsonMap.get("type"));
Map<String, Object> meta = (Map<String, Object>) jsonMap.get("meta");
assertEquals("SKULL", meta.get("meta-type"));
Map<String, Object> skullOwner = (Map<String, Object>) meta.get("skull-owner");
assertEquals("04049c90-d3e9-4621-9caf-0000aaa58540", skullOwner.get("uniqueId"));
}
@Test
public void testItemStackFromJsonStick() throws JsonSerializer.JsonSyntaxException {
JsonSerializer serializer = new JsonSerializer();
String json = "{\"v\":3953,\"type\":\"STICK\"}";
CommonItemStack itemStack = CommonItemStack.of(serializer.fromJsonToItemStack(json));
assertEquals(CommonItemMaterials.STICK, itemStack.getType());
assertEquals(1, itemStack.getAmount());
}
@Test
public void testItemStackFromJsonPlayerHead() throws JsonSerializer.JsonSyntaxException {
JsonSerializer serializer = new JsonSerializer();
String json = "{\"v\":3953,\"type\":\"PLAYER_HEAD\",\"meta\":{\"meta-type\":\"SKULL\",\"skull-owner\":{\"uniqueId\":\"04049c90-d3e9-4621-9caf-0000aaa58540\",\"name\":\"HeadDatabase\",\"properties\":[{\"name\":\"textures\",\"value\":\"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjllNzVlMDQxNTFlN2NkZThlN2YxNDlkYWU5MmYwYzE0ZWY1ZjNmZjQ1Y2QzMjM5NTc4NzZiMGFkZDJjNDk0OSJ9fX0=\"}],\"==\":\"PlayerProfile\"},\"==\":\"ItemMeta\"}}";
CommonItemStack itemStack = CommonItemStack.of(serializer.fromJsonToItemStack(json));
assertEquals(CommonItemMaterials.SKULL, itemStack.getType());
assertEquals(1, itemStack.getAmount());
GameProfileHandle profile = itemStack.getSkullProfile();
assertNotNull(profile);
assertEquals(UUID.fromString("04049c90-d3e9-4621-9caf-0000aaa58540"), profile.getId());
for (PropertyHandle prop : profile.getProperties("textures")) {
assertEquals("textures", prop.getName());
assertTrue(prop.getValue().length() > 10);
}
}
@Test
public void testItemStackFromJsonDamagedItem() throws JsonSerializer.JsonSyntaxException {
JsonSerializer serializer = new JsonSerializer();
String json = "{\"v\":3700,\"amount\":2,\"type\":\"DIAMOND_SWORD\",\"meta\":{\"meta-type\":\"UNSPECIFIC\",\"ItemFlags\":[\"HIDE_ENCHANTS\",\"HIDE_ATTRIBUTES\",\"HIDE_UNBREAKABLE\",\"HIDE_DESTROYS\",\"HIDE_PLACED_ON\",\"HIDE_POTION_EFFECTS\",\"HIDE_DYE\",\"HIDE_ARMOR_TRIM\"],\"Unbreakable\":true,\"Damage\":126,\"\u003d\u003d\":\"ItemMeta\"}}";
CommonItemStack itemStack = CommonItemStack.of(serializer.fromJsonToItemStack(json));
assertEquals(MaterialUtil.getFirst("DIAMOND_SWORD", "LEGACY_DIAMOND_SWORD"), itemStack.getType());
assertEquals(2, itemStack.getAmount());
assertEquals(126, itemStack.getDamage());
}
@Test
public void testItemStackFromJsonDamagedItemWithoutTypeHeader() throws JsonSerializer.JsonSyntaxException {
JsonSerializer serializer = new JsonSerializer();
String json = "{\"v\":3700,\"amount\":2,\"type\":\"DIAMOND_SWORD\",\"meta\":{\"meta-type\":\"UNSPECIFIC\",\"ItemFlags\":[\"HIDE_ENCHANTS\",\"HIDE_ATTRIBUTES\",\"HIDE_UNBREAKABLE\",\"HIDE_DESTROYS\",\"HIDE_PLACED_ON\",\"HIDE_POTION_EFFECTS\",\"HIDE_DYE\",\"HIDE_ARMOR_TRIM\"],\"Unbreakable\":true,\"Damage\":126}}";
CommonItemStack itemStack = CommonItemStack.of(serializer.fromJsonToItemStack(json));
assertEquals(MaterialUtil.getFirst("DIAMOND_SWORD", "LEGACY_DIAMOND_SWORD"), itemStack.getType());
assertEquals(2, itemStack.getAmount());
assertEquals(126, itemStack.getDamage());
}
}
| 0 | 0.788661 | 1 | 0.788661 | game-dev | MEDIA | 0.896745 | game-dev,testing-qa | 0.669813 | 1 | 0.669813 |
Cannoneers-of-Create/CreateBigCannons | 15,606 | src/main/java/rbasamoyai/createbigcannons/compat/common_jei/MunitionAssemblyRecipes.java | package rbasamoyai.createbigcannons.compat.common_jei;
import java.util.ArrayList;
import java.util.List;
import com.simibubi.create.content.kinetics.deployer.DeployerApplicationRecipe;
import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
import net.minecraft.client.resources.language.I18n;
import net.minecraft.core.NonNullList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.StringTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.CraftingBookCategory;
import net.minecraft.world.item.crafting.CraftingRecipe;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.ShapedRecipe;
import net.minecraft.world.item.crafting.ShapelessRecipe;
import rbasamoyai.createbigcannons.CBCTags;
import rbasamoyai.createbigcannons.CreateBigCannons;
import rbasamoyai.createbigcannons.index.CBCBlocks;
import rbasamoyai.createbigcannons.index.CBCItems;
import rbasamoyai.createbigcannons.munitions.FuzedItemMunition;
import rbasamoyai.createbigcannons.munitions.autocannon.AutocannonCartridgeItem;
import rbasamoyai.createbigcannons.munitions.autocannon.AutocannonRoundItem;
import rbasamoyai.createbigcannons.munitions.big_cannon.propellant.BigCartridgeBlockItem;
import rbasamoyai.createbigcannons.munitions.fuzes.FuzeItem;
import rbasamoyai.createbigcannons.utils.CBCRegistryUtils;
public class MunitionAssemblyRecipes {
public static List<CraftingRecipe> getFuzingRecipes() {
List<Item> fuzes = new ArrayList<>();
List<Item> munitions = new ArrayList<>();
CBCRegistryUtils.streamAllItems()
.forEach(i -> {
if (i instanceof FuzeItem) fuzes.add(i);
else if (i instanceof FuzedItemMunition) munitions.add(i);
});
Ingredient fuzeIngredient = Ingredient.of(fuzes.toArray(new Item[]{}));
String group = CreateBigCannons.MOD_ID + ".fuzing";
ListTag loreTag = new ListTag();
String loc = I18n.get("tooltip." + CreateBigCannons.MOD_ID + ".jei_info.added_fuze");
loreTag.add(StringTag.valueOf("\"" + loc + "\""));
CompoundTag displayTag = new CompoundTag();
displayTag.put("Lore", loreTag);
List<CraftingRecipe> recipes = new ArrayList<>();
for (Item munition : munitions) {
NonNullList<Ingredient> inputs = NonNullList.of(Ingredient.EMPTY, Ingredient.of(munition), fuzeIngredient);
ResourceLocation id = CreateBigCannons.resource(group + "." + munition.getDescriptionId());
ItemStack fuzedMunition = new ItemStack(munition);
fuzedMunition.getOrCreateTag().put("display", displayTag.copy());
recipes.add(new ShapelessRecipe(id, group, CraftingBookCategory.MISC, fuzedMunition, inputs));
if (munition instanceof AutocannonRoundItem round) {
NonNullList<Ingredient> inputs1 = NonNullList.of(Ingredient.EMPTY, Ingredient.of(round.getCreativeTabCartridgeItem()), fuzeIngredient);
ResourceLocation id1 = CreateBigCannons.resource(group + ".autocannon_round." + munition.getDescriptionId());
ItemStack fuzedCartridge = round.getCreativeTabCartridgeItem();
fuzedCartridge.getOrCreateTag().put("display", displayTag.copy());
recipes.add(new ShapelessRecipe(id1, group + ".autocannon_round", CraftingBookCategory.MISC, fuzedCartridge, inputs1));
}
}
return recipes;
}
public static List<CraftingRecipe> getAutocannonRoundRecipes() {
String group = CreateBigCannons.MOD_ID + ".autocannon_round";
Ingredient cartridge = Ingredient.of(CBCItems.FILLED_AUTOCANNON_CARTRIDGE.get());
List<Item> fuzes = new ArrayList<>();
List<AutocannonRoundItem> munitions = new ArrayList<>();
CBCRegistryUtils.streamAllItems()
.forEach(i -> {
if (i instanceof FuzeItem) fuzes.add(i);
else if (i instanceof AutocannonRoundItem acr) munitions.add(acr);
});
Ingredient fuzeIngredient = Ingredient.of(fuzes.toArray(new Item[]{}));
ListTag loreTag = new ListTag();
String loc = I18n.get("tooltip." + CreateBigCannons.MOD_ID + ".jei_info.added_fuze");
loreTag.add(StringTag.valueOf("\"" + loc + "\""));
CompoundTag displayTag = new CompoundTag();
displayTag.put("Lore", loreTag);
List<CraftingRecipe> recipes = new ArrayList<>();
for (AutocannonRoundItem round : munitions) {
NonNullList<Ingredient> inputs = NonNullList.of(Ingredient.EMPTY, Ingredient.of(round), cartridge);
ResourceLocation id = CreateBigCannons.resource(group + "." + round.getDescriptionId());
recipes.add(new ShapedRecipe(id, group, CraftingBookCategory.MISC, 1, 2, inputs, round.getCreativeTabCartridgeItem()));
if (round instanceof FuzedItemMunition) {
NonNullList<Ingredient> inputs1 = NonNullList.of(Ingredient.EMPTY, fuzeIngredient, Ingredient.of(round), cartridge);
ResourceLocation id1 = CreateBigCannons.resource(group + ".fuzed." + round.getDescriptionId());
ItemStack fuzedRound = round.getCreativeTabCartridgeItem();
fuzedRound.getOrCreateTag().put("display", displayTag.copy());
recipes.add(new ShapedRecipe(id1, group, CraftingBookCategory.MISC, 1, 3, inputs1, fuzedRound));
}
}
return recipes;
}
public static List<CraftingRecipe> getBigCartridgeFillingRecipe() {
String group = CreateBigCannons.MOD_ID + ".big_cartridge_filling";
ResourceLocation id = CreateBigCannons.resource(group + "." + CBCBlocks.BIG_CARTRIDGE.get().getDescriptionId());
NonNullList<Ingredient> inputs = NonNullList.of(Ingredient.EMPTY, Ingredient.of(BigCartridgeBlockItem.getWithPower(0)),
Ingredient.of(CBCTags.CBCItemTags.NITROPOWDER));
ItemStack result = BigCartridgeBlockItem.getWithPower(1);
ListTag loreTag = new ListTag();
String loc = I18n.get("tooltip." + CreateBigCannons.MOD_ID + ".jei_info.added_power");
loreTag.add(StringTag.valueOf("\"" + loc + "\""));
CompoundTag displayTag = new CompoundTag();
displayTag.put("Lore", loreTag);
result.getOrCreateTag().put("display", displayTag);
return List.of(new ShapelessRecipe(id, group, CraftingBookCategory.MISC, result, inputs));
}
public static List<CraftingRecipe> getTracerRecipes() {
List<Item> munitions = new ArrayList<>();
CBCRegistryUtils.streamAllItems()
.forEach(i -> {
if (i instanceof AutocannonRoundItem || CBCItems.MACHINE_GUN_ROUND.is(i)) munitions.add(i);
});
Ingredient tracerIngredient = Ingredient.of(CBCItems.TRACER_TIP.get());
String group = CreateBigCannons.MOD_ID + ".tracer";
List<CraftingRecipe> recipes = new ArrayList<>();
for (Item munition : munitions) {
NonNullList<Ingredient> inputs = NonNullList.of(Ingredient.EMPTY, Ingredient.of(munition), tracerIngredient);
ResourceLocation id = CreateBigCannons.resource(group + "." + munition.getDescriptionId());
ItemStack tracerMunition = new ItemStack(munition);
tracerMunition.getOrCreateTag().putBoolean("Tracer", true);
recipes.add(new ShapelessRecipe(id, group, CraftingBookCategory.MISC, tracerMunition, inputs));
if (munition instanceof AutocannonRoundItem round) {
NonNullList<Ingredient> inputs1 = NonNullList.of(Ingredient.EMPTY, Ingredient.of(round.getCreativeTabCartridgeItem()), tracerIngredient);
ResourceLocation id1 = CreateBigCannons.resource(group + ".autocannon_round." + munition.getDescriptionId());
ItemStack tracerCartridge = round.getCreativeTabCartridgeItem();
CBCItems.AUTOCANNON_CARTRIDGE.get().setTracer(tracerCartridge, true);
recipes.add(new ShapelessRecipe(id1, group + ".autocannon_round", CraftingBookCategory.MISC, tracerCartridge, inputs1));
}
}
return recipes;
}
public static List<DeployerApplicationRecipe> getFuzingDeployerRecipes() {
List<Item> fuzes = new ArrayList<>();
List<Item> munitions = new ArrayList<>();
CBCRegistryUtils.streamAllItems()
.forEach(i -> {
if (i instanceof FuzeItem) fuzes.add(i);
else if (i instanceof FuzedItemMunition) munitions.add(i);
});
Ingredient fuzeIngredient = Ingredient.of(fuzes.toArray(new Item[]{}));
String group = CreateBigCannons.MOD_ID + ".fuzing_deployer";
ListTag loreTag = new ListTag();
String loc = I18n.get("tooltip." + CreateBigCannons.MOD_ID + ".jei_info.added_fuze");
loreTag.add(StringTag.valueOf("\"" + loc + "\""));
CompoundTag displayTag = new CompoundTag();
displayTag.put("Lore", loreTag);
List<DeployerApplicationRecipe> recipes = new ArrayList<>();
for (Item munition : munitions) {
ResourceLocation id = CreateBigCannons.resource(group + "." + munition.getDescriptionId());
ItemStack fuzedMunition = new ItemStack(munition);
fuzedMunition.getOrCreateTag().put("display", displayTag.copy());
recipes.add(new ProcessingRecipeBuilder<>(DeployerApplicationRecipe::new, id)
.require(Ingredient.of(munition))
.require(fuzeIngredient)
.output(fuzedMunition)
.build());
if (munition instanceof AutocannonRoundItem round) {
ResourceLocation id1 = CreateBigCannons.resource(group + ".autocannon_round." + munition.getDescriptionId());
ItemStack fuzedCartridge = round.getCreativeTabCartridgeItem();
fuzedCartridge.getOrCreateTag().put("display", displayTag.copy());
recipes.add(new ProcessingRecipeBuilder<>(DeployerApplicationRecipe::new, id1)
.require(Ingredient.of(round.getCreativeTabCartridgeItem()))
.require(fuzeIngredient)
.output(fuzedCartridge)
.build());
}
}
return recipes;
}
public static List<DeployerApplicationRecipe> getAutocannonRoundDeployerRecipes() {
String group = CreateBigCannons.MOD_ID + ".autocannon_round_deployer";
List<AutocannonRoundItem> munitions = new ArrayList<>();
CBCRegistryUtils.streamAllItems()
.forEach(i -> {
if (i instanceof AutocannonRoundItem acr) munitions.add(acr);
});
List<DeployerApplicationRecipe> recipes = new ArrayList<>();
for (AutocannonRoundItem round : munitions) {
ResourceLocation id = CreateBigCannons.resource(group + "." + round.getDescriptionId());
recipes.add(new ProcessingRecipeBuilder<>(DeployerApplicationRecipe::new, id)
.require(CBCItems.FILLED_AUTOCANNON_CARTRIDGE.get())
.require(round)
.output(round.getCreativeTabCartridgeItem())
.build());
}
return recipes;
}
public static List<DeployerApplicationRecipe> getBigCartridgeDeployerRecipe() {
String group = CreateBigCannons.MOD_ID + ".big_cartridge_filling_deployer";
ResourceLocation id = CreateBigCannons.resource(group + "." + CBCBlocks.BIG_CARTRIDGE.get().getDescriptionId());
ItemStack result = BigCartridgeBlockItem.getWithPower(1);
ListTag loreTag = new ListTag();
String loc = I18n.get("tooltip." + CreateBigCannons.MOD_ID + ".jei_info.added_power");
loreTag.add(StringTag.valueOf("\"" + loc + "\""));
CompoundTag displayTag = new CompoundTag();
displayTag.put("Lore", loreTag);
result.getOrCreateTag().put("display", displayTag);
return List.of(new ProcessingRecipeBuilder<>(DeployerApplicationRecipe::new, id)
.require(Ingredient.of(BigCartridgeBlockItem.getWithPower(0)))
.require(CBCTags.CBCItemTags.NITROPOWDER)
.output(result)
.build());
}
public static List<DeployerApplicationRecipe> getTracerDeployerRecipes() {
List<Item> munitions = new ArrayList<>();
CBCRegistryUtils.streamAllItems()
.forEach(i -> {
if (i instanceof AutocannonRoundItem || CBCItems.MACHINE_GUN_ROUND.is(i)) munitions.add(i);
});
Ingredient tracerIngredient = Ingredient.of(CBCItems.TRACER_TIP.get());
String group = CreateBigCannons.MOD_ID + ".tracer_deployer";
List<DeployerApplicationRecipe> recipes = new ArrayList<>();
for (Item munition : munitions) {
ResourceLocation id = CreateBigCannons.resource(group + "." + munition.getDescriptionId());
ItemStack tracerMunition = new ItemStack(munition);
tracerMunition.getOrCreateTag().putBoolean("Tracer", true);
recipes.add(new ProcessingRecipeBuilder<>(DeployerApplicationRecipe::new, id)
.require(Ingredient.of(munition))
.require(tracerIngredient)
.output(tracerMunition)
.build());
if (munition instanceof AutocannonRoundItem round) {
ResourceLocation id1 = CreateBigCannons.resource(group + ".autocannon_round." + munition.getDescriptionId());
ItemStack tracerCartridge = round.getCreativeTabCartridgeItem();
CBCItems.AUTOCANNON_CARTRIDGE.get().setTracer(tracerCartridge, true);
recipes.add(new ProcessingRecipeBuilder<>(DeployerApplicationRecipe::new, id1)
.require(Ingredient.of(round.getCreativeTabCartridgeItem()))
.require(tracerIngredient)
.output(tracerCartridge)
.build());
}
}
return recipes;
}
public static List<CraftingRecipe> getFuzeRemovalRecipes() {
List<Item> fuzes = new ArrayList<>();
List<Item> munitions = new ArrayList<>();
CBCRegistryUtils.streamAllItems()
.forEach(i -> {
if (i instanceof FuzeItem) fuzes.add(i);
else if (i instanceof FuzedItemMunition) munitions.add(i);
});
String group = CreateBigCannons.MOD_ID + ".fuze_removal";
List<CraftingRecipe> recipes = new ArrayList<>();
for (Item munition : munitions) {
for (Item fuze : fuzes) {
ItemStack fuzeStack = new ItemStack(fuze);
ItemStack fuzedMunitionStack = new ItemStack(munition);
fuzedMunitionStack.getOrCreateTag().put("Fuze", fuzeStack.save(new CompoundTag()));
String subid = munition.getDescriptionId() + "." + fuze.getDescriptionId();
NonNullList<Ingredient> inputs = NonNullList.of(Ingredient.EMPTY, Ingredient.of(fuzedMunitionStack));
ResourceLocation id = CreateBigCannons.resource(group + "." + subid);
recipes.add(new ShapelessRecipe(id, group, CraftingBookCategory.MISC, fuzeStack, inputs));
if (munition instanceof AutocannonRoundItem) {
ItemStack fuzedCartridge = CBCItems.AUTOCANNON_CARTRIDGE.asStack();
AutocannonCartridgeItem.writeProjectile(fuzedMunitionStack, fuzedCartridge);
NonNullList<Ingredient> inputs1 = NonNullList.of(Ingredient.EMPTY, Ingredient.of(fuzedCartridge));
ResourceLocation id1 = CreateBigCannons.resource(group + ".autocannon_round." + subid);
recipes.add(new ShapelessRecipe(id1, group + ".autocannon_round", CraftingBookCategory.MISC, fuzeStack, inputs1));
}
}
}
return recipes;
}
public static List<CraftingRecipe> getTracerRemovalRecipes() {
List<Item> munitions = new ArrayList<>();
CBCRegistryUtils.streamAllItems()
.forEach(i -> {
if (i instanceof AutocannonRoundItem || CBCItems.MACHINE_GUN_ROUND.is(i)) munitions.add(i);
});
String group = CreateBigCannons.MOD_ID + ".tracer_removal";
List<CraftingRecipe> recipes = new ArrayList<>();
for (Item munition : munitions) {
ItemStack tracerMunition = new ItemStack(munition);
tracerMunition.getOrCreateTag().putBoolean("Tracer", true);
ResourceLocation id = CreateBigCannons.resource(group + "." + munition.getDescriptionId());
NonNullList<Ingredient> inputs = NonNullList.of(Ingredient.EMPTY, Ingredient.of(tracerMunition));
recipes.add(new ShapelessRecipe(id, group, CraftingBookCategory.MISC, CBCItems.TRACER_TIP.asStack(), inputs));
if (munition instanceof AutocannonRoundItem round) {
ItemStack tracerCartridge = round.getCreativeTabCartridgeItem();
CBCItems.AUTOCANNON_CARTRIDGE.get().setTracer(tracerCartridge, true);
NonNullList<Ingredient> inputs1 = NonNullList.of(Ingredient.EMPTY, Ingredient.of(tracerCartridge));
ResourceLocation id1 = CreateBigCannons.resource(group + ".autocannon_round." + munition.getDescriptionId());
recipes.add(new ShapelessRecipe(id1, group + ".autocannon_round", CraftingBookCategory.MISC, CBCItems.TRACER_TIP.asStack(), inputs1));
}
}
return recipes;
}
private MunitionAssemblyRecipes() {}
}
| 0 | 0.727085 | 1 | 0.727085 | game-dev | MEDIA | 0.990772 | game-dev | 0.880561 | 1 | 0.880561 |
chunky-dev/chunky | 1,471 | chunky/src/java/se/llbit/chunky/block/legacy/blocks/LegacyLargeFlower.java | package se.llbit.chunky.block.legacy.blocks;
import se.llbit.chunky.block.FinalizationState;
import se.llbit.chunky.block.legacy.LegacyBlockUtils;
import se.llbit.chunky.block.legacy.LegacyBlocks;
import se.llbit.chunky.block.legacy.UnfinalizedLegacyBlock;
import se.llbit.chunky.world.Material;
import se.llbit.nbt.CompoundTag;
public class LegacyLargeFlower extends UnfinalizedLegacyBlock {
public LegacyLargeFlower(String name, CompoundTag tag) {
super(name, tag);
}
@Override
public void finalizeBlock(FinalizationState state) {
CompoundTag newTag;
if ((this.data&8) != 0) {
Material bottom = state.getMaterial(0, -1, 0);
if (bottom instanceof LegacyLargeFlower) {
newTag = LegacyBlocks.createTag(LegacyBlockUtils.getName(bottom));
} else {
String name = LegacyBlockUtils.getName(bottom);
switch (name) {
case "sunflower":
case "lilac":
case "tall_grass":
case "large_fern":
case "rose_bush":
case "peony":
newTag = LegacyBlocks.createTag(name);
break;
default:
newTag = LegacyBlocks.createTag("unknown"); // Invalid state
}
}
LegacyBlocks.stringTag(newTag, "half", "upper");
} else {
newTag = LegacyBlocks.createTag(LegacyBlockUtils.getName(this.block));
LegacyBlocks.stringTag(newTag, "half", "lower");
}
state.replaceCurrentBlock(newTag);
}
}
| 0 | 0.847513 | 1 | 0.847513 | game-dev | MEDIA | 0.915883 | game-dev | 0.854823 | 1 | 0.854823 |
Dark-Basic-Software-Limited/AGKRepo | 15,655 | AGK/common/Source/JSONElement.cpp | #include "agk.h"
using namespace AGK;
const char* JSONElement::TypeToString( int type )
{
switch( type )
{
case 0: return "Undefined";
case AGK_JSON_OBJECT: return "Object";
case AGK_JSON_ARRAY: return "Array";
case AGK_JSON_STRING: return "String";
case AGK_JSON_NUMBER: return "Number";
case AGK_JSON_BOOL: return "Bool";
default: return "Unknown";
}
}
JSONElement* JSONElement::LoadJSONFromFile( const char* filename )
{
cFile oFile;
if ( !oFile.OpenToRead( filename ) ) return 0;
uint32_t size = oFile.GetSize();
char* data = new char[ size+1 ];
oFile.ReadData( data, size );
oFile.Close();
data[ size ] = 0;
JSONElement* element = LoadJSONFromData( data );
delete [] data;
return element;
}
JSONElement* JSONElement::LoadJSONFromData( const char* data )
{
uint32_t index = 0;
while( 1 )
{
switch( data[ index ] )
{
case ' ':
case '\t':
case '\r':
case '\n': break;
case '{':
{
JSONObject *pObject = new JSONObject();
index++;
if ( pObject->ParseObject( data+index ) < 0 )
{
delete pObject;
return 0;
}
return pObject;
}
case '[':
{
JSONArray *pArray = new JSONArray();
index++;
if ( pArray->ParseArray( data+index ) < 0 )
{
delete pArray;
return 0;
}
return pArray;
}
default:
{
agk::Error( "Failed to parse JSON file, must begin with an object or array" );
return 0;
}
}
index++;
}
return 0;
}
int JSONObject::ParseObject( const char* data )
{
int index = 0;
JSONKeyPair *pPairList = 0;
JSONKeyPair *pLastPair = 0;
int count = 0;
while ( 1 )
{
switch( data[ index ] )
{
case 0:
{
while ( pPairList ) { pLastPair = pPairList; pPairList = pPairList->m_pTempNext; delete pLastPair; }
agk::Error("Invalid JSON, unexpected end of object");
return -1;
}
case ' ':
case '\t':
case '\r':
case '\n': index++; break;
case '}': return index+1;
case '"':
{
JSONKeyPair *pNewPair = new JSONKeyPair();
pNewPair->m_sName.SetStr("");
index++;
int length = pNewPair->ParsePair( data+index );
if ( length < 0 )
{
while ( pPairList ) { pLastPair = pPairList; pPairList = pPairList->m_pTempNext; delete pLastPair; }
delete pNewPair;
return -1;
}
if ( pLastPair ) pLastPair->m_pTempNext = pNewPair;
else pPairList = pNewPair;
pLastPair = pNewPair;
count++;
index += length;
if ( data[index] == '}' )
{
m_iNumPairs = count;
m_pPairs = new JSONKeyPair*[ count ];
for( int i = 0; i < count; i++ )
{
if ( pPairList )
{
m_pPairs[ i ] = pPairList;
pPairList = pPairList->m_pTempNext;
m_pPairs[ i ]->m_pTempNext = 0;
}
else m_pPairs[ i ] = 0;
}
return index+1;
}
break;
}
default:
{
agk::Error("Invalid JSON, unexpected character in object");
return -1;
}
}
}
}
int JSONArray::ParseArray( const char* data )
{
int index = 0;
JSONElement *pElementList = 0;
JSONElement *pLastElement = 0;
int count = 0;
while ( 1 )
{
switch( data[ index ] )
{
case 0:
{
while ( pElementList ) { pLastElement = pElementList; pElementList = pElementList->m_pTempNext; delete pLastElement; }
agk::Error("Invalid JSON, unexpected end of array");
return -1;
}
case ' ':
case '\t':
case '\r':
case '\n': index++; break;
case ']':
{
m_iNumElements = count;
m_pElements = new JSONElement*[ count ];
for( int i = 0; i < count; i++ )
{
if ( pElementList )
{
m_pElements[ i ] = pElementList;
pElementList = pElementList->m_pTempNext;
m_pElements[ i ]->m_pTempNext = 0;
}
else m_pElements[ i ] = 0;
}
return index+1;
}
case '[':
{
JSONArray *pArray = new JSONArray();
index++;
int length = pArray->ParseArray( data+index );
if ( length < 0 )
{
delete pArray;
while ( pElementList ) { pLastElement = pElementList; pElementList = pElementList->m_pTempNext; delete pLastElement; }
return -1;
}
index += length;
if ( pLastElement ) pLastElement->m_pTempNext = pArray;
else pElementList = pArray;
pLastElement = pArray;
count++;
length = FindArrayEnd( data + index );
if ( length < 0 )
{
while ( pElementList ) { pLastElement = pElementList; pElementList = pElementList->m_pTempNext; delete pLastElement; }
return -1;
}
index += length;
break;
}
case '{':
{
JSONObject *pObject = new JSONObject();
index++;
int length = pObject->ParseObject( data+index );
if ( length < 0 )
{
delete pObject;
while ( pElementList ) { pLastElement = pElementList; pElementList = pElementList->m_pTempNext; delete pLastElement; }
return -1;
}
index += length;
if ( pLastElement ) pLastElement->m_pTempNext = pObject;
else pElementList = pObject;
pLastElement = pObject;
count++;
length = FindArrayEnd( data + index );
if ( length < 0 )
{
while ( pElementList ) { pLastElement = pElementList; pElementList = pElementList->m_pTempNext; delete pLastElement; }
return -1;
}
index += length;
break;
}
case '"':
{
index++;
int length = JSONElement::ParseString( data+index );
if ( length < 0 )
{
while ( pElementList ) { pLastElement = pElementList; pElementList = pElementList->m_pTempNext; delete pLastElement; }
return -1;
}
JSONString *pString = new JSONString();
if ( length > 0 ) pString->m_sValue.AppendN( data+index, length );
pString->m_sValue.Unescape();
index += (length+1);
if ( pLastElement ) pLastElement->m_pTempNext = pString;
else pElementList = pString;
pLastElement = pString;
count++;
length = FindArrayEnd( data + index );
if ( length < 0 )
{
while ( pElementList ) { pLastElement = pElementList; pElementList = pElementList->m_pTempNext; delete pLastElement; }
return -1;
}
index += length;
break;
}
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
{
int length = JSONElement::ParseNumber( data+index );
if ( length < 0 )
{
while ( pElementList ) { pLastElement = pElementList; pElementList = pElementList->m_pTempNext; delete pLastElement; }
return -1;
}
uString sNum;
if ( length > 0 ) sNum.AppendN( data+index, length );
JSONNumber *pNumber = new JSONNumber();
if ( sNum.Find('.') < 0 && sNum.Find('e') < 0 && sNum.Find('E') < 0 )
{
pNumber->m_iIsInt = 1;
pNumber->m_iValue = atoi( sNum.GetStr() );
}
pNumber->m_fValue = (float) atof( sNum.GetStr() );
index += length;
if ( pLastElement ) pLastElement->m_pTempNext = pNumber;
else pElementList = pNumber;
pLastElement = pNumber;
count++;
length = FindArrayEnd( data + index );
if ( length < 0 )
{
while ( pElementList ) { pLastElement = pElementList; pElementList = pElementList->m_pTempNext; delete pLastElement; }
return -1;
}
index += length;
break;
}
case 'n':
{
if ( data[ index+1 ] == 'u'
&& data[ index+2 ] == 'l'
&& data[ index+3 ] == 'l' )
{
JSONNull *pNull = new JSONNull();
if ( pLastElement ) pLastElement->m_pTempNext = pNull;
else pElementList = pNull;
pLastElement = pNull;
count++;
int length = FindArrayEnd( data + index );
if ( length < 0 )
{
while ( pElementList ) { pLastElement = pElementList; pElementList = pElementList->m_pTempNext; delete pLastElement; }
return -1;
}
index += length;
break;
}
else
{
agk::Error("Invalid JSON, unexpected character in array element");
return -1;
}
}
case 't':
{
if ( data[ index+1 ] == 'r'
&& data[ index+2 ] == 'u'
&& data[ index+3 ] == 'e' )
{
JSONBool *pBool = new JSONBool();
pBool->m_bValue = true;
if ( pLastElement ) pLastElement->m_pTempNext = pBool;
else pElementList = pBool;
pLastElement = pBool;
count++;
int length = FindArrayEnd( data + index );
if ( length < 0 )
{
while ( pElementList ) { pLastElement = pElementList; pElementList = pElementList->m_pTempNext; delete pLastElement; }
return -1;
}
index += length;
break;
}
else
{
agk::Error("Invalid JSON, unexpected character in array element");
return -1;
}
}
case 'f':
{
if ( data[ index+1 ] == 'a'
&& data[ index+2 ] == 'l'
&& data[ index+3 ] == 's'
&& data[ index+4 ] == 'e' )
{
JSONBool *pBool = new JSONBool();
pBool->m_bValue = false;
if ( pLastElement ) pLastElement->m_pTempNext = pBool;
else pElementList = pBool;
pLastElement = pBool;
count++;
int length = FindArrayEnd( data + index );
if ( length < 0 )
{
while ( pElementList ) { pLastElement = pElementList; pElementList = pElementList->m_pTempNext; delete pLastElement; }
return -1;
}
index += length;
break;
}
else
{
agk::Error("Invalid JSON, unexpected character in array element");
return -1;
}
}
default:
{
agk::Error("Invalid JSON, unexpected character in array element");
return -1;
}
}
}
}
int JSONArray::FindArrayEnd( const char* data )
{
int index = 0;
while ( data[index] && data[index] != ',' && data[index] != ']' ) index++;
if ( !data[index] )
{
agk::Error("Invalid JSON, unexpected end of array element");
return -1;
}
if ( data[index] == ',' ) index++;
return index;
}
int JSONKeyPair::FindPairEnd( const char* data )
{
int index = 0;
while ( data[index] && data[index] != ',' && data[index] != '}' ) index++;
if ( !data[index] )
{
agk::Error("Invalid JSON, unexpected end of object key pair");
return -1;
}
if ( data[index] == ',' ) index++;
return index;
}
int JSONKeyPair::ParsePair( const char *data )
{
int length = JSONElement::ParseString( data );
if ( length < 0 ) return -1;
if ( length > 0 ) m_sName.AppendN( data, length );
m_sName.Unescape();
int index = length+1;
while ( data[index] && data[index] != ':' ) index++;
if ( !data[index] )
{
agk::Error("Invalid JSON, unexpected end of object key pair");
return -1;
}
index++;
while( 1 )
{
switch( data[ index ] )
{
case 0: agk::Error("Invalid JSON, unexpected end of object key pair"); return -1;
case ' ':
case '\t':
case '\r':
case '\n': index++; break;
case '[':
{
JSONArray *pArray = new JSONArray();
index++;
int length = pArray->ParseArray( data+index );
if ( length < 0 )
{
delete pArray;
return -1;
}
index += length;
m_pElement = pArray;
length = FindPairEnd( data + index );
if ( length < 0 ) return -1;
return index+length;
}
case '{':
{
JSONObject *pObject = new JSONObject();
index++;
int length = pObject->ParseObject( data+index );
if ( length < 0 )
{
delete pObject;
return -1;
}
index += length;
m_pElement = pObject;
length = FindPairEnd( data + index );
if ( length < 0 ) return -1;
return index+length;
}
case '"':
{
index++;
int length = JSONElement::ParseString( data+index );
if ( length < 0 ) return -1;
JSONString *pString = new JSONString();
if ( length > 0 ) pString->m_sValue.AppendN( data+index, length );
pString->m_sValue.Unescape();
index += (length+1);
m_pElement = pString;
length = FindPairEnd( data + index );
if ( length < 0 ) return -1;
return index+length;
}
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
{
int length = JSONElement::ParseNumber( data+index );
if ( length < 0 ) return -1;
uString sNum;
if ( length > 0 ) sNum.AppendN( data+index, length );
JSONNumber *pNumber = new JSONNumber();
if ( sNum.Find('.') < 0 && sNum.Find('e') < 0 && sNum.Find('E') < 0 )
{
pNumber->m_iIsInt = 1;
pNumber->m_iValue = atoi( sNum.GetStr() );
}
pNumber->m_fValue = (float) atof( sNum.GetStr() );
index += length;
m_pElement = pNumber;
length = FindPairEnd( data + index );
if ( length < 0 ) return -1;
return index+length;
}
case 'n':
{
if ( data[ index+1 ] == 'u'
&& data[ index+2 ] == 'l'
&& data[ index+3 ] == 'l' )
{
JSONNull *pNull = new JSONNull();
m_pElement = pNull;
length = FindPairEnd( data + index );
if ( length < 0 ) return -1;
return index+length;
}
else
{
agk::Error("Invalid JSON, unexpected character in object key pair");
return -1;
}
}
case 't':
{
if ( data[ index+1 ] == 'r'
&& data[ index+2 ] == 'u'
&& data[ index+3 ] == 'e' )
{
JSONBool *pBool = new JSONBool();
pBool->m_bValue = true;
m_pElement = pBool;
length = FindPairEnd( data + index );
if ( length < 0 ) return -1;
return index+length;
}
else
{
agk::Error("Invalid JSON, unexpected character in object key pair");
return -1;
}
}
case 'f':
{
if ( data[ index+1 ] == 'a'
&& data[ index+2 ] == 'l'
&& data[ index+3 ] == 's'
&& data[ index+4 ] == 'e' )
{
JSONBool *pBool = new JSONBool();
pBool->m_bValue = false;
m_pElement = pBool;
length = FindPairEnd( data + index );
if ( length < 0 ) return -1;
return index+length;
}
else
{
agk::Error("Invalid JSON, unexpected character in object key pair");
return -1;
}
}
default:
{
agk::Error("Invalid JSON, unexpected character in object key pair");
return -1;
}
}
}
}
int JSONElement::ParseString( const char* data )
{
int index = 0;
while ( 1 )
{
switch( data[ index ] )
{
case 0: agk::Error("Invalid JSON, unexpected end of string"); return -1;
case '"': return index;
case '\\':
{
// skip escaped character
index++;
if ( data[ index ] == 0 )
{
agk::Error("Invalid JSON, unexpected end of string");
return -1;
}
break;
}
}
index++;
}
}
int JSONElement::ParseNumber( const char* data )
{
int index = 0;
while ( 1 )
{
switch( data[ index ] )
{
case 0: agk::Error("Invalid JSON, unexpected end of string"); return -1;
case ',': return index;
case '}': return index;
case ']': return index;
case '\n': return index;
case '\r': return index;
case ' ':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
case '+':
case '.':
case 'e':
case 'E': break;
default: agk::Error("Invalid JSON, unexpected character in number"); return -1;
}
index++;
}
}
JSONElement* JSONObject::GetElement( const char *szKey )
{
if ( !m_pPairs ) return 0;
for( uint32_t i = 0; i < m_iNumPairs; i++ )
{
if ( m_pPairs[ i ]->m_sName.CompareCaseTo( szKey ) == 0 ) return m_pPairs[ i ]->m_pElement;
}
return 0;
}
JSONElement* JSONArray::GetElement( int index )
{
if ( !m_pElements ) return 0;
if ( index < 0 || index >= (int) m_iNumElements ) return 0;
return m_pElements[ index ];
} | 0 | 0.823704 | 1 | 0.823704 | game-dev | MEDIA | 0.23478 | game-dev | 0.923434 | 1 | 0.923434 |
project-topaz/topaz | 1,451 | scripts/commands/bring.lua | ---------------------------------------------------------------------------------------------------
-- func: bring <player>
-- desc: Brings the target to the player.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "si"
}
function error(player, msg)
player:PrintToPlayer(msg)
player:PrintToPlayer("!bring <player> {forceZone}")
end
function onTrigger(player, target, forceZone)
-- validate target
if (target == nil) then
error(player, "You must enter a target player name.")
return
end
local targ = GetPlayerByName( target )
if (targ == nil) then
if not player:bringPlayer( target ) then
error(player, string.format( "Player named '%s' not found!", target ) )
end
return
end
-- validate forceZone
if (forceZone ~= nil) then
if (forceZone ~= 0 and forceZone ~= 1) then
error(player, "If provided, forceZone must be 1 (true) or 0 (false).")
return
end
else
forceZone = 1
end
-- bring target
if (targ:getZoneID() ~= player:getZoneID() or forceZone == 1) then
targ:setPos( player:getXPos(), player:getYPos(), player:getZPos(), player:getRotPos(), player:getZoneID() )
else
targ:setPos( player:getXPos(), player:getYPos(), player:getZPos(), player:getRotPos() )
end
end
| 0 | 0.666653 | 1 | 0.666653 | game-dev | MEDIA | 0.948687 | game-dev | 0.776571 | 1 | 0.776571 |
wzk1015/sanguosha | 1,504 | sanguosha/cards/strategy/JueDou.java | package sanguosha.cards.strategy;
import sanguosha.cards.Color;
import sanguosha.cards.Strategy;
public class JueDou extends Strategy {
public JueDou(Color color, int number) {
super(color, number);
}
@Override
public Object use() {
if (!gotWuXie(getTarget())) {
getSource().jueDouBegin();
getTarget().jueDouBegin();
while (true) {
if ((!getSource().hasWuShuang() && getTarget().requestSha() == null) ||
getSource().hasWuShuang() && (getTarget().requestSha() == null ||
getTarget().requestSha() == null)) {
getTarget().hurt(getThisCard(), getSource(),1);
break;
}
if ((!getTarget().hasWuShuang() && getSource().requestSha() == null) ||
getTarget().hasWuShuang() && (getSource().requestSha() == null ||
getSource().requestSha() == null)) {
getSource().hurt(getThisCard(), getTarget(),1);
break;
}
}
return true;
}
return false;
}
@Override
public String toString() {
return "决斗";
}
@Override
public boolean needChooseTarget() {
return true;
}
@Override
public String details() {
return "出牌阶段,对一名其他角色使用。由其开始,其与你轮流打出一张【杀】,直到其中一方未打出【杀】为止。" +
"未打出【杀】的一方受到另一方对其造成的1点伤害。";
}
}
| 0 | 0.936304 | 1 | 0.936304 | game-dev | MEDIA | 0.771181 | game-dev | 0.962947 | 1 | 0.962947 |
fallahn/crogine | 2,847 | android/BulletDroid/src/BulletDynamics/Featherstone/btMultiBodyFixedConstraint.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2013 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///This file was written by Erwin Coumans
#ifndef BT_MULTIBODY_FIXED_CONSTRAINT_H
#define BT_MULTIBODY_FIXED_CONSTRAINT_H
#include "btMultiBodyConstraint.h"
class btMultiBodyFixedConstraint : public btMultiBodyConstraint
{
protected:
btRigidBody* m_rigidBodyA;
btRigidBody* m_rigidBodyB;
btVector3 m_pivotInA;
btVector3 m_pivotInB;
btMatrix3x3 m_frameInA;
btMatrix3x3 m_frameInB;
public:
btMultiBodyFixedConstraint(btMultiBody* body, int link, btRigidBody* bodyB, const btVector3& pivotInA, const btVector3& pivotInB, const btMatrix3x3& frameInA, const btMatrix3x3& frameInB);
btMultiBodyFixedConstraint(btMultiBody* bodyA, int linkA, btMultiBody* bodyB, int linkB, const btVector3& pivotInA, const btVector3& pivotInB, const btMatrix3x3& frameInA, const btMatrix3x3& frameInB);
virtual ~btMultiBodyFixedConstraint();
virtual void finalizeMultiDof();
virtual int getIslandIdA() const;
virtual int getIslandIdB() const;
virtual void createConstraintRows(btMultiBodyConstraintArray& constraintRows,
btMultiBodyJacobianData& data,
const btContactSolverInfo& infoGlobal);
const btVector3& getPivotInA() const
{
return m_pivotInA;
}
void setPivotInA(const btVector3& pivotInA)
{
m_pivotInA = pivotInA;
}
const btVector3& getPivotInB() const
{
return m_pivotInB;
}
virtual void setPivotInB(const btVector3& pivotInB)
{
m_pivotInB = pivotInB;
}
const btMatrix3x3& getFrameInA() const
{
return m_frameInA;
}
void setFrameInA(const btMatrix3x3& frameInA)
{
m_frameInA = frameInA;
}
const btMatrix3x3& getFrameInB() const
{
return m_frameInB;
}
virtual void setFrameInB(const btMatrix3x3& frameInB)
{
m_frameInB = frameInB;
}
virtual void debugDraw(class btIDebugDraw* drawer);
};
#endif //BT_MULTIBODY_FIXED_CONSTRAINT_H
| 0 | 0.728331 | 1 | 0.728331 | game-dev | MEDIA | 0.965928 | game-dev | 0.767188 | 1 | 0.767188 |
iniside/ActionRPGGame | 4,244 | Plugins/AbilityFramework/Source/AbilityFrameworkEditor/Public/AFAbilityInfinitePeriodSpecDetails.cpp | // Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
#include "AbilityFrameworkEditor.h"
#include "Editor/PropertyEditor/Public/PropertyEditing.h"
#include "STextCombobox.h"
#include "STreeView.h"
#include "Abilities/AFAbilityPeriodicInfiniteSpec.h"
#include "AFAbilityInfinitePeriodSpecDetails.h"
#include "Effects/AFEffectCustomApplication.h"
#include "AFEffectCustomizationCommon.h"
TSharedRef<IDetailCustomization> FAFAbilityInfinitePeriodSpecDetails::MakeInstance()
{
return MakeShareable(new FAFAbilityInfinitePeriodSpecDetails);
}
void FAFAbilityInfinitePeriodSpecDetails::CustomizeDetails(IDetailLayoutBuilder& DetailLayout)
{
MyDetailLayout = &DetailLayout;
TArray<TWeakObjectPtr<UObject>> Objects;
DetailLayout.GetObjectsBeingCustomized(Objects);
ApplicationTypeHandle = DetailLayout.GetProperty(GET_MEMBER_NAME_CHECKED(UGAGameEffectSpec, Application), UGAGameEffectSpec::StaticClass());
FSimpleDelegate UpdateEffectTypeyDelegate = FSimpleDelegate::CreateSP(this, &FAFAbilityInfinitePeriodSpecDetails::OnDurationPolicyChange);
ApplicationTypeHandle->SetOnPropertyValueChanged(UpdateEffectTypeyDelegate);
for (TWeakObjectPtr<UObject> obj : Objects)
{
if (UAFAbilityPeriodicInfiniteSpec* Spec = Cast<UAFAbilityPeriodicInfiniteSpec>(obj.Get()))
{
bIsDuration = Spec->Application.GetDefaultObject()->ShowDuration();
bIsPeriodic = Spec->Application.GetDefaultObject()->ShowPeriod();
FAFEffectCustomizationCommon::HideProperty(DetailLayout, "ApplicationRequirement");
//FAFEffectCustomizationCommon::HideProperty(DetailLayout, "Application");
FAFEffectCustomizationCommon::HideProperty(DetailLayout, "EffectAggregation");
FAFEffectCustomizationCommon::HideProperty(DetailLayout, "MaxStackedDuration");
FAFEffectCustomizationCommon::HideProperty(DetailLayout, "MaxStacks");
FAFEffectCustomizationCommon::HideProperty(DetailLayout, "bTickOnApplication");
FAFEffectCustomizationCommon::HideProperty(DetailLayout, "bExecuteOnApplication");
//FAFEffectCustomizationCommon::HideProperty(DetailLayout, "Extension");
//FAFEffectCustomizationCommon::HideProperty(DetailLayout, "OnAppliedEffects");
//FAFEffectCustomizationCommon::HideProperty(DetailLayout, "OnExpiredEffects");
//FAFEffectCustomizationCommon::HideProperty(DetailLayout, "OnRemovedEffects");
FAFEffectCustomizationCommon::HideProperty(DetailLayout, "ConditonalEffects");
FAFEffectCustomizationCommon::HideProperty(DetailLayout, "RemoveEffectWithTags");
FAFEffectCustomizationCommon::HideProperty(DetailLayout, "AtributeModifier");
FAFEffectCustomizationCommon::HideProperty(DetailLayout, "Modifiers");
//FAFEffectCustomizationCommon::HideProperty(DetailLayout, "AppliedEventTags");
//FAFEffectCustomizationCommon::HideProperty(DetailLayout, "ExecuteEventTags");
FAFEffectCustomizationCommon::HideProperty(DetailLayout, "AttributeTags");
FAFEffectCustomizationCommon::HideProperty(DetailLayout, "DenyTags");
FAFEffectCustomizationCommon::HideProperty(DetailLayout, "AppliedImmunityTags");
FAFEffectCustomizationCommon::HideProperty(DetailLayout, "RequiredTags");
FAFEffectCustomizationCommon::HideProperty(DetailLayout, "ExecutionRequiredTags");
DetailLayout.HideCategory("Duration");
DurationProperty = DetailLayout.GetProperty(GET_MEMBER_NAME_CHECKED(UGAGameEffectSpec, Duration), UGAGameEffectSpec::StaticClass());
PeriodProperty = DetailLayout.GetProperty(GET_MEMBER_NAME_CHECKED(UGAGameEffectSpec, Period), UGAGameEffectSpec::StaticClass());
DetailLayout.HideProperty(DurationProperty);
DetailLayout.HideProperty(PeriodProperty);
DurationCalcTypeProp = DurationProperty->GetChildHandle("CalculationType");
PeriodCalcTypeProp = PeriodProperty->GetChildHandle("CalculationType");
FAFEffectCustomizationCommon::CreateMagnitudeLayout(DetailLayout, DurationProperty, "Duration");
FAFEffectCustomizationCommon::CreateMagnitudeLayout(DetailLayout, PeriodProperty, "Period");
DurationCalcTypeProp->SetOnPropertyValueChanged(UpdateEffectTypeyDelegate);
PeriodCalcTypeProp->SetOnPropertyValueChanged(UpdateEffectTypeyDelegate);
}
}
}
void FAFAbilityInfinitePeriodSpecDetails::OnDurationPolicyChange()
{
MyDetailLayout->ForceRefreshDetails();
} | 0 | 0.832573 | 1 | 0.832573 | game-dev | MEDIA | 0.765384 | game-dev | 0.880288 | 1 | 0.880288 |
ThePhysicsGuys/Physics3D | 1,661 | Physics3D/softlinks/softLink.cpp | #include "softLink.h"
namespace P3D {
SoftLink::SoftLink(const AttachedPart& attachedPartA, const AttachedPart& attachedPartB)
: attachedPartA(attachedPartA)
, attachedPartB(attachedPartB) {}
SoftLink::~SoftLink() = default;
GlobalCFrame SoftLink::getGlobalCFrameOfAttachmentA() const {
return this->attachedPartA.part->getCFrame();
}
GlobalCFrame SoftLink::getGlobalCFrameOfAttachmentB() const {
return this->attachedPartB.part->getCFrame();
}
CFrame SoftLink::getLocalCFrameOfAttachmentA() const {
return this->attachedPartA.attachment;
}
CFrame SoftLink::getLocalCFrameOfAttachmentB() const {
return this->attachedPartB.attachment;
}
CFrame SoftLink::getRelativeOfAttachmentA() const {
return this->getGlobalCFrameOfAttachmentA().localToRelative(this->attachedPartA.attachment);
}
CFrame SoftLink::getRelativeOfAttachmentB() const {
return this->getGlobalCFrameOfAttachmentB().localToRelative(this->attachedPartB.attachment);
}
Position SoftLink::getGlobalPositionOfAttachmentB() const {
return this->getGlobalCFrameOfAttachmentB().getPosition();
}
Position SoftLink::getGlobalPositionOfAttachmentA() const {
return this->getGlobalCFrameOfAttachmentA().getPosition();
}
Vec3 SoftLink::getLocalPositionOfAttachmentA() const {
return this->getLocalCFrameOfAttachmentA().getPosition();
}
Vec3 SoftLink::getLocalPositionOfAttachmentB() const {
return this->getLocalCFrameOfAttachmentB().getPosition();
}
Vec3 SoftLink::getRelativePositionOfAttachmentA() const {
return this->getRelativeOfAttachmentA().getPosition();
}
Vec3 SoftLink::getRelativePositionOfAttachmentB() const {
return this->getRelativeOfAttachmentB().getPosition();
}
};
| 0 | 0.825127 | 1 | 0.825127 | game-dev | MEDIA | 0.176836 | game-dev | 0.516549 | 1 | 0.516549 |
tractal/loris | 17,960 | src/phasefix.C | /*
* This is the Loris C++ Class Library, implementing analysis,
* manipulation, and synthesis of digitized sounds using the Reassigned
* Bandwidth-Enhanced Additive Sound Model.
*
* Loris is Copyright (c) 1999-2010 by Kelly Fitz and Lippold Haken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY, without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* phasefix.C
*
* Implements a phase correction algorithm that perturbs slightly the
* frequencies or Breakpoints in a Partial so that the rendered Partial
* will achieve (or be closer to) the analyzed Breakpoint phases.
*
* Kelly Fitz, 23 Sept 04
* loris@cerlsoundgroup.org
*
* http://www.cerlsoundgroup.org/Loris/
*
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include "phasefix.h"
#include "Breakpoint.h"
#include "BreakpointUtils.h"
#include "LorisExceptions.h"
#include "Notifier.h"
#include "Partial.h"
#include <algorithm>
#include <cmath>
#include <iostream>
#include <utility>
#if defined(HAVE_M_PI) && (HAVE_M_PI)
const double Pi = M_PI;
#else
const double Pi = 3.14159265358979324;
#endif
// begin namespace
namespace Loris {
// -- local helpers --
// ---------------------------------------------------------------------------
// wrapPi
// Wrap an unwrapped phase value to the range [-pi,pi] using
// O'Donnell's phase wrapping function.
//
double wrapPi( double x )
{
using namespace std; // floor should be in std
#define ROUND(x) (floor(.5 + (x)))
const double TwoPi = 2.0*Pi;
return x + ( TwoPi * ROUND(-x/TwoPi) );
}
// ---------------------------------------------------------------------------
// phaseTravel
//
// Compute the sinusoidal phase travel between two Breakpoints.
// Return the total unwrapped phase travel.
//
double phaseTravel( const Breakpoint & bp0, const Breakpoint & bp1,
double dt )
{
double f0 = bp0.frequency();
double f1 = bp1.frequency();
double favg = .5 * ( f0 + f1 );
return 2 * Pi * favg * dt;
}
// ---------------------------------------------------------------------------
// phaseTravel
//
// Compute the sinusoidal phase travel between two Breakpoints.
// Return the total unwrapped phase travel.
//
static double phaseTravel( Partial::const_iterator bp0, Partial::const_iterator bp1 )
{
return phaseTravel( bp0.breakpoint(), bp1.breakpoint(),
bp1.time() - bp0.time() );
}
// -- phase correction --
// ---------------------------------------------------------------------------
// fixPhaseBackward
//
//! Recompute phases of all Breakpoints on the half-open range [stopHere, pos)
//! so that the synthesized phases of those Breakpoints matches
//! the stored phase, as long as the synthesized phase at stopHere
//! matches the stored (not recomputed) phase.
//!
//! The phase is corrected beginning at the end of the range, maintaining
//! the stored phase in the Breakpoint at pos.
//!
//! Backward phase-fixing stops if a null (zero-amplitude) Breakpoint
//! is encountered, because nulls are interpreted as phase reset points
//! in Loris. If a null is encountered, the remainder of the range
//! (the front part) is fixed in the forward direction, beginning at
//! the start of the stopHere.
//!
//! \pre pos and stopHere are iterators on the same Partial, and
//! pos must be not later than stopHere.
//! \pre pos cannot be end of the Partial, it must be the postion
//! of a valid Breakpoint.
//! \param stopHere the position of the earliest Breakpoint whose phase might be
//! recomputed.
//! \param pos the position of a (later) Breakpoint whose phase is to be matched.
//! The phase at pos is not modified.
//
void fixPhaseBackward( Partial::iterator stopHere, Partial::iterator pos )
{
while ( pos != stopHere &&
BreakpointUtils::isNonNull( pos.breakpoint() ) )
{
// pos is not the first Breakpoint in the Partial,
// and pos is not a Null Breakpoint.
// Compute the correct phase for the
// predecessor of pos.
Partial::iterator posFwd = pos--;
double travel = phaseTravel( pos, posFwd );
pos.breakpoint().setPhase( wrapPi( posFwd.breakpoint().phase() - travel ) );
}
// if a null was encountered, then stop fixing backwards,
// and fix the front of the Partial in the forward direction:
if ( pos != stopHere )
{
// pos is not the first Breakpoint in the Partial,
// and it is a Null Breakpoint (zero amplitude),
// so it will be used to reset the phase during
// synthesis.
// The phase of all Breakpoints starting with pos
// and ending with the Breakpoint nearest to time t
// has been corrected.
// Fix phases before pos starting at the beginning
// of the Partial.
//
// Dont fix pos, it has already been fixed.
fixPhaseForward( stopHere, --pos );
}
}
// ----------------------------------------------------------------------- ----
// fixPhaseForward
//
//! Recompute phases of all Breakpoints on the closed range [pos, stopHere]
//! so that the synthesized phases of those Breakpoints matches
//! the stored phase, as long as the synthesized phase at pos
//! matches the stored (not recomputed) phase. The phase at pos
//! is modified only if pos is the position of a null Breakpoint
//! and the Breakpoint that follows is non-null.
//!
//! Phase fixing is only applied to non-null (nonzero-amplitude) Breakpoints,
//! because null Breakpoints are interpreted as phase reset points in
//! Loris. If a null is encountered, its phase is corrected from its non-Null
//! successor, if it has one, otherwise it is unmodified.
//!
//! \pre pos and stopHere are iterators on the same Partial, and
//! pos must be not later than stopHere.
//! \pre stopHere cannot be end of the Partial, it must be the postion
//! of a valid Breakpoint.
//! \param pos the position of the first Breakpoint whose phase might be
//! recomputed.
//! \param stopHere the position of the last Breakpoint whose phase might
//! be modified.
//
void fixPhaseForward( Partial::iterator pos, Partial::iterator stopHere )
{
while ( pos != stopHere )
{
Partial::iterator posPrev = pos++;
// update phase based on the phase travel between
// posPrev and pos UNLESS pos is Null:
if ( BreakpointUtils::isNonNull( pos.breakpoint() ) )
{
// pos is the position of a non-Null Breakpoint,
// posPrev is its predecessor:
double travel = phaseTravel( posPrev, pos );
if ( BreakpointUtils::isNonNull( posPrev.breakpoint() ) )
{
// if its predecessor of pos is non-Null, then fix
// the phase of the Breakpoint at pos.
pos.breakpoint().setPhase( wrapPi( posPrev.breakpoint().phase() + travel ) );
}
else
{
// if the predecessor of pos is Null, then
// correct the predecessor's phase so that
// it correctly resets the synthesis phase
// so that the phase of the Breakpoint at
// pos is achieved in synthesis.
posPrev.breakpoint().setPhase( wrapPi( pos.breakpoint().phase() - travel ) );
}
}
}
}
// ---------------------------------------------------------------------------
// fixPhaseBetween
//
//! Fix the phase travel between two Breakpoints by adjusting the
//! frequency and phase of Breakpoints between those two.
//!
//! This algorithm assumes that there is nothing interesting about the
//! phases of the intervening Breakpoints, and modifies their frequencies
//! as little as possible to achieve the correct amount of phase travel
//! such that the frequencies and phases at the specified times
//! match the stored values. The phases of all the Breakpoints between
//! the specified times are recomputed.
//!
//! Null Breakpoints are treated the same as non-null Breakpoints.
//!
//! \pre b and e are iterators on the same Partials, and
//! e must not preceed b in that Partial.
//! \pre There must be at least one Breakpoint in the
//! Partial between b and e.
//! \post The phases and frequencies of the Breakpoints in the
//! range have been recomputed such that an oscillator
//! initialized to the parameters of the first Breakpoint
//! will arrive at the parameters of the last Breakpoint,
//! and all the intervening Breakpoints will be matched.
//! \param b The phases and frequencies of Breakpoints later than
//! this one may be modified.
//! \param e The phases and frequencies of Breakpoints earlier than
//! this one may be modified.
//
void fixPhaseBetween( Partial::iterator b, Partial::iterator e )
{
if ( 1 < std::distance( b, e ) )
{
// Accumulate the actual phase travel over the Breakpoint
// span, and count the envelope segments.
double travel = 0;
Partial::iterator next = b;
do
{
Partial::iterator prev = next++;
travel += phaseTravel( prev, next );
} while( next != e );
// Compute the desired amount of phase travel:
double deviation = wrapPi( e.breakpoint().phase() - ( b.breakpoint().phase() + travel ) );
double desired = travel + deviation;
// Compute the amount by which to perturb the frequencies of
// all the null Breakpoints between b and e.
//
// The accumulated phase travel is the sum of the average frequency
// (in radians) of each segment times the duration of each segment
// (the actual phase travel is computed this way). If this sum is
// computed with each Breakpoint frequency perturbed (additively)
// by delta, and set equal to the desired phase travel, then it
// can be simplified to:
// delta = 2 * ( phase error ) / ( tN + tN-1 - t1 - t0 )
// where tN is the time of e, tN-1 is the time of its predecessor,
// t0 is the time of b, and t1 is the time of b's successor.
//
Partial::iterator iter = b;
double t0 = iter.time();
++iter;
double t1 = iter.time();
iter = e;
double tN = iter.time();
--iter;
double tNm1 = iter.time();
Assert( t1 < tN ); // else there were no Breakpoints in between
double delta = ( 2 * ( desired - travel ) / ( tN + tNm1 - t1 - t0 ) ) / ( 2 * Pi );
// Perturb the Breakpoint frequencies.
next = b;
Partial::iterator prev = next++;
while ( next != e )
{
next.breakpoint().setFrequency( next.breakpoint().frequency() + delta );
double newtravel = phaseTravel( prev, next );
next.breakpoint().setPhase( wrapPi( prev.breakpoint().phase() + newtravel ) );
prev = next++;
}
}
else
{
// Preconditions not met, cannot fix the phase travel.
// Should raise exception?
debugger << "cannot fix phase between " << b.time() << " and " << e.time()
<< ", there are no Breakpoints between those times" << endl;
}
}
// ---------------------------------------------------------------------------
// matchPhaseFwd
//
//! Compute the target frequency that will affect the
//! predicted (by the Breakpoint phases) amount of
//! sinusoidal phase travel between two breakpoints,
//! and assign that frequency to the target Breakpoint.
//! After computing the new frequency, update the phase of
//! the later Breakpoint.
//!
//! If the earlier Breakpoint is null and the later one
//! is non-null, then update the phase of the earlier
//! Breakpoint, and do not modify its frequency or the
//! later Breakpoint.
//!
//! The most common kinds of errors are local (or burst) errors in
//! frequency and phase. These errors are best corrected by correcting
//! less than half the detected error at any time. Correcting more
//! than that will produce frequency oscillations for the remainder of
//! the Partial, in the case of a single bad frequency (as is common
//! at the onset of a tone). Any damping factor less then one will
//! converge eventually, .5 or less will converge without oscillating.
//! Use the damping argument to control the damping of the correction.
//! Specify 1 for no damping.
//!
//! \pre The two Breakpoints are assumed to be consecutive in
//! a Partial.
//! \param bp0 The earlier Breakpoint.
//! \param bp1 The later Breakpoint.
//! \param dt The time (in seconds) between bp0 and bp1.
//! \param damping The fraction of the amount of phase error that will
//! be corrected (.5 or less will prevent frequency oscilation
//! due to burst errors in phase).
//! \param maxFixPct The maximum amount of frequency adjustment
//! that can be made to the frequency of bp1, expressed
//! as a precentage of the unmodified frequency of bp1.
//! If the necessary amount of frequency adjustment exceeds
//! this amount, then the phase will not be matched,
//! but will be updated as well to be consistent with
//! the frequencies. (default is 0.2%)
//
void matchPhaseFwd( Breakpoint & bp0, Breakpoint & bp1,
double dt, double damping, double maxFixPct )
{
double travel = phaseTravel( bp0, bp1, dt );
if ( ! BreakpointUtils::isNonNull( bp1 ) )
{
// if bp1 is null, DON'T compute a new phase,
// because Nulls are phase reset points.
// bp1.setPhase( wrapPi( bp0.phase() + travel ) );
}
else if ( ! BreakpointUtils::isNonNull( bp0 ) )
{
// if bp0 is null, and bp1 is not, then bp0
// should be a phase reset Breakpoint during
// rendering, so compute a new phase for
// bp0 that achieves bp1's phase.
bp0.setPhase( wrapPi( bp1.phase() - travel ) ) ;
}
else
{
// invariant:
// neither bp0 nor bp1 is null
//
// modify frequecies to match phases as nearly as possible
double err = wrapPi( bp1.phase() - ( bp0.phase() + travel ) );
// The most common kinds of errors are local (or burst) errors in
// frequency and phase. These errors are best corrected by correcting
// less than half the detected error at any time. Correcting more
// than that will produce frequency oscillations for the remainder of
// the Partial, in the case of a single bad frequency (as is common
// at the onset of a tone). Any damping factor less then one will
// converge eventually, .5 or less will converge without oscillating.
// #define DAMPING .5
travel += damping * err;
double f0 = bp0.frequency();
double ftgt = ( travel / ( Pi * dt ) ) - f0;
#ifdef Loris_Debug
debugger << "matchPhaseFwd: correcting " << bp1.frequency() << " to " << ftgt
<< " (phase " << wrapPi( bp1.phase() ) << "), ";
#endif
// If the target is not a null breakpoint, may need to
// clamp the amount of frequency modification.
if ( ftgt > bp1.frequency() * ( 1 + (maxFixPct*.01) ) )
{
ftgt = bp1.frequency() * ( 1 + (maxFixPct*.01) );
}
else if ( ftgt < bp1.frequency() * ( 1 - (maxFixPct*.01) ) )
{
ftgt = bp1.frequency() * ( 1 - (maxFixPct*.01) );
}
bp1.setFrequency( ftgt );
// Recompute the phase according to the new frequency.
double phi = wrapPi( bp0.phase() + phaseTravel( bp0, bp1, dt ) );
bp1.setPhase( phi );
#ifdef Loris_Debug
debugger << "achieved " << ftgt << " (phase " << phi << ")" << endl;
#endif
}
}
// ---------------------------------------------------------------------------
// fixFrequency
//
//! Adjust frequencies of the Breakpoints in the
//! specified Partial such that the rendered Partial
//! achieves (or matches as nearly as possible, within
//! the constraint of the maximum allowable frequency
//! alteration) the analyzed phases.
//!
//! This just iterates over the Partial calling
//! matchPhaseFwd, should probably name those similarly.
//!
//! \param partial The Partial whose frequencies,
//! and possibly phases (if the frequencies
//! cannot be sufficiently altered to match
//! the phases), will be recomputed.
//! \param maxFixPct The maximum allowable frequency
//! alteration, default is 0.2%.
//
void fixFrequency( Partial & partial, double maxFixPct )
{
if ( partial.numBreakpoints() > 1 )
{
Partial::iterator next = partial.begin();
Partial::iterator prev = next++;
while ( next != partial.end() )
{
if ( BreakpointUtils::isNonNull( next.breakpoint() ) )
{
matchPhaseFwd( prev.breakpoint(), next.breakpoint(),
next.time() - prev.time(), 0.5, maxFixPct );
}
prev = next++;
}
}
}
} // end of namespace Loris
| 0 | 0.943961 | 1 | 0.943961 | game-dev | MEDIA | 0.168689 | game-dev | 0.876589 | 1 | 0.876589 |
spacebuild/spacebuild | 2,894 | lua/entities/generator_energy_hydro/init.lua | AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
util.PrecacheSound("Airboat_engine_idle")
util.PrecacheSound("Airboat_engine_stop")
include('shared.lua')
local Energy_Increment = 100 --60
function ENT:Initialize()
self.BaseClass.Initialize(self)
self.Active = 0
self.damaged = 0
self.thinkcount = 0
if not (WireAddon == nil) then
self.WireDebugName = self.PrintName
self.Outputs = Wire_CreateOutputs(self, { "Out" })
end
end
function ENT:Damage()
if (self.damaged == 0) then self.damaged = 1 end
end
function ENT:Repair()
self.BaseClass.Repair(self)
self:SetColor(Color(255, 255, 255, 255))
self.damaged = 0
end
function ENT:Destruct()
if CAF and CAF.GetAddon("Life Support") then
CAF.GetAddon("Life Support").Destruct(self, true)
end
end
function ENT:Extract_Energy()
local waterlevel = 0
if CAF then
waterlevel = self:WaterLevel2()
else
waterlevel = self:WaterLevel()
end
if (waterlevel > 0) then
waterlevel = waterlevel / 3
else
waterlevel = 1 / 3
end
local energy = math.Round(Energy_Increment * self:GetMultiplier() * waterlevel)
self:SupplyResource("energy", energy)
if not (WireAddon == nil) then Wire_TriggerOutput(self, "Out", energy) end
end
function ENT:GenEnergy()
local waterlevel = 0
if CAF then
waterlevel = self:WaterLevel2()
else
waterlevel = self:WaterLevel()
end
if (waterlevel > 0) then
if (self.Active == 0) then
self.Active = 1
self:SetOOO(1)
self.sequence = self:LookupSequence("HydroFans")
if self.sequence and self.sequence ~= -1 then
self:SetSequence(self.sequence)
self:ResetSequence(self.sequence)
self:SetPlaybackRate(1)
end
end
if (self.damaged == 1) then
if (math.random(1, 10) < 6) then self:Extract_Energy() end
else
self:Extract_Energy()
end
else
if (self.Active == 1) then
self.Active = 0
self:SetOOO(0)
self.sequence = self:LookupSequence("idle")
if self.sequence and self.sequence ~= -1 then
self:SetSequence(self.sequence)
self:ResetSequence(self.sequence)
self:SetPlaybackRate(1)
end
if not (WireAddon == nil) then Wire_TriggerOutput(self, "Out", 0) end
end
end
end
function ENT:Think()
self.BaseClass.Think(self)
if self.sequence and self.sequence ~= -1 then
self:ResetSequence(self.sequence)
self:SetPlaybackRate(1)
end
self.thinkcount = self.thinkcount + 1
if self.thinkcount == 10 then
self:GenEnergy()
self.thinkcount = 0
end
self:NextThink(CurTime() + 0.1)
return true
end
| 0 | 0.876307 | 1 | 0.876307 | game-dev | MEDIA | 0.916129 | game-dev | 0.903699 | 1 | 0.903699 |
fr1tz/terminal-overload | 7,705 | Engine/lib/sdl/src/video/haiku/SDL_bkeyboard.cc | /*
Simple DirectMedia Layer
Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
#if SDL_VIDEO_DRIVER_HAIKU
#include <SupportDefs.h>
#include <support/UTF8.h>
#ifdef __cplusplus
extern "C" {
#endif
#include "SDL_events.h"
#include "SDL_keycode.h"
#include "SDL_bkeyboard.h"
#define KEYMAP_SIZE 128
static SDL_Scancode keymap[KEYMAP_SIZE];
static int8 keystate[KEYMAP_SIZE];
void BE_InitOSKeymap() {
for( uint i = 0; i < SDL_TABLESIZE(keymap); ++i ) {
keymap[i] = SDL_SCANCODE_UNKNOWN;
}
for( uint i = 0; i < KEYMAP_SIZE; ++i ) {
keystate[i] = SDL_RELEASED;
}
keymap[0x01] = SDL_GetScancodeFromKey(SDLK_ESCAPE);
keymap[B_F1_KEY] = SDL_GetScancodeFromKey(SDLK_F1);
keymap[B_F2_KEY] = SDL_GetScancodeFromKey(SDLK_F2);
keymap[B_F3_KEY] = SDL_GetScancodeFromKey(SDLK_F3);
keymap[B_F4_KEY] = SDL_GetScancodeFromKey(SDLK_F4);
keymap[B_F5_KEY] = SDL_GetScancodeFromKey(SDLK_F5);
keymap[B_F6_KEY] = SDL_GetScancodeFromKey(SDLK_F6);
keymap[B_F7_KEY] = SDL_GetScancodeFromKey(SDLK_F7);
keymap[B_F8_KEY] = SDL_GetScancodeFromKey(SDLK_F8);
keymap[B_F9_KEY] = SDL_GetScancodeFromKey(SDLK_F9);
keymap[B_F10_KEY] = SDL_GetScancodeFromKey(SDLK_F10);
keymap[B_F11_KEY] = SDL_GetScancodeFromKey(SDLK_F11);
keymap[B_F12_KEY] = SDL_GetScancodeFromKey(SDLK_F12);
keymap[B_PRINT_KEY] = SDL_GetScancodeFromKey(SDLK_PRINTSCREEN);
keymap[B_SCROLL_KEY] = SDL_GetScancodeFromKey(SDLK_SCROLLLOCK);
keymap[B_PAUSE_KEY] = SDL_GetScancodeFromKey(SDLK_PAUSE);
keymap[0x11] = SDL_GetScancodeFromKey(SDLK_BACKQUOTE);
keymap[0x12] = SDL_GetScancodeFromKey(SDLK_1);
keymap[0x13] = SDL_GetScancodeFromKey(SDLK_2);
keymap[0x14] = SDL_GetScancodeFromKey(SDLK_3);
keymap[0x15] = SDL_GetScancodeFromKey(SDLK_4);
keymap[0x16] = SDL_GetScancodeFromKey(SDLK_5);
keymap[0x17] = SDL_GetScancodeFromKey(SDLK_6);
keymap[0x18] = SDL_GetScancodeFromKey(SDLK_7);
keymap[0x19] = SDL_GetScancodeFromKey(SDLK_8);
keymap[0x1a] = SDL_GetScancodeFromKey(SDLK_9);
keymap[0x1b] = SDL_GetScancodeFromKey(SDLK_0);
keymap[0x1c] = SDL_GetScancodeFromKey(SDLK_MINUS);
keymap[0x1d] = SDL_GetScancodeFromKey(SDLK_EQUALS);
keymap[0x1e] = SDL_GetScancodeFromKey(SDLK_BACKSPACE);
keymap[0x1f] = SDL_GetScancodeFromKey(SDLK_INSERT);
keymap[0x20] = SDL_GetScancodeFromKey(SDLK_HOME);
keymap[0x21] = SDL_GetScancodeFromKey(SDLK_PAGEUP);
keymap[0x22] = SDL_GetScancodeFromKey(SDLK_NUMLOCKCLEAR);
keymap[0x23] = SDL_GetScancodeFromKey(SDLK_KP_DIVIDE);
keymap[0x24] = SDL_GetScancodeFromKey(SDLK_KP_MULTIPLY);
keymap[0x25] = SDL_GetScancodeFromKey(SDLK_KP_MINUS);
keymap[0x26] = SDL_GetScancodeFromKey(SDLK_TAB);
keymap[0x27] = SDL_GetScancodeFromKey(SDLK_q);
keymap[0x28] = SDL_GetScancodeFromKey(SDLK_w);
keymap[0x29] = SDL_GetScancodeFromKey(SDLK_e);
keymap[0x2a] = SDL_GetScancodeFromKey(SDLK_r);
keymap[0x2b] = SDL_GetScancodeFromKey(SDLK_t);
keymap[0x2c] = SDL_GetScancodeFromKey(SDLK_y);
keymap[0x2d] = SDL_GetScancodeFromKey(SDLK_u);
keymap[0x2e] = SDL_GetScancodeFromKey(SDLK_i);
keymap[0x2f] = SDL_GetScancodeFromKey(SDLK_o);
keymap[0x30] = SDL_GetScancodeFromKey(SDLK_p);
keymap[0x31] = SDL_GetScancodeFromKey(SDLK_LEFTBRACKET);
keymap[0x32] = SDL_GetScancodeFromKey(SDLK_RIGHTBRACKET);
keymap[0x33] = SDL_GetScancodeFromKey(SDLK_BACKSLASH);
keymap[0x34] = SDL_GetScancodeFromKey(SDLK_DELETE);
keymap[0x35] = SDL_GetScancodeFromKey(SDLK_END);
keymap[0x36] = SDL_GetScancodeFromKey(SDLK_PAGEDOWN);
keymap[0x37] = SDL_GetScancodeFromKey(SDLK_KP_7);
keymap[0x38] = SDL_GetScancodeFromKey(SDLK_KP_8);
keymap[0x39] = SDL_GetScancodeFromKey(SDLK_KP_9);
keymap[0x3a] = SDL_GetScancodeFromKey(SDLK_KP_PLUS);
keymap[0x3b] = SDL_GetScancodeFromKey(SDLK_CAPSLOCK);
keymap[0x3c] = SDL_GetScancodeFromKey(SDLK_a);
keymap[0x3d] = SDL_GetScancodeFromKey(SDLK_s);
keymap[0x3e] = SDL_GetScancodeFromKey(SDLK_d);
keymap[0x3f] = SDL_GetScancodeFromKey(SDLK_f);
keymap[0x40] = SDL_GetScancodeFromKey(SDLK_g);
keymap[0x41] = SDL_GetScancodeFromKey(SDLK_h);
keymap[0x42] = SDL_GetScancodeFromKey(SDLK_j);
keymap[0x43] = SDL_GetScancodeFromKey(SDLK_k);
keymap[0x44] = SDL_GetScancodeFromKey(SDLK_l);
keymap[0x45] = SDL_GetScancodeFromKey(SDLK_SEMICOLON);
keymap[0x46] = SDL_GetScancodeFromKey(SDLK_QUOTE);
keymap[0x47] = SDL_GetScancodeFromKey(SDLK_RETURN);
keymap[0x48] = SDL_GetScancodeFromKey(SDLK_KP_4);
keymap[0x49] = SDL_GetScancodeFromKey(SDLK_KP_5);
keymap[0x4a] = SDL_GetScancodeFromKey(SDLK_KP_6);
keymap[0x4b] = SDL_GetScancodeFromKey(SDLK_LSHIFT);
keymap[0x4c] = SDL_GetScancodeFromKey(SDLK_z);
keymap[0x4d] = SDL_GetScancodeFromKey(SDLK_x);
keymap[0x4e] = SDL_GetScancodeFromKey(SDLK_c);
keymap[0x4f] = SDL_GetScancodeFromKey(SDLK_v);
keymap[0x50] = SDL_GetScancodeFromKey(SDLK_b);
keymap[0x51] = SDL_GetScancodeFromKey(SDLK_n);
keymap[0x52] = SDL_GetScancodeFromKey(SDLK_m);
keymap[0x53] = SDL_GetScancodeFromKey(SDLK_COMMA);
keymap[0x54] = SDL_GetScancodeFromKey(SDLK_PERIOD);
keymap[0x55] = SDL_GetScancodeFromKey(SDLK_SLASH);
keymap[0x56] = SDL_GetScancodeFromKey(SDLK_RSHIFT);
keymap[0x57] = SDL_GetScancodeFromKey(SDLK_UP);
keymap[0x58] = SDL_GetScancodeFromKey(SDLK_KP_1);
keymap[0x59] = SDL_GetScancodeFromKey(SDLK_KP_2);
keymap[0x5a] = SDL_GetScancodeFromKey(SDLK_KP_3);
keymap[0x5b] = SDL_GetScancodeFromKey(SDLK_KP_ENTER);
keymap[0x5c] = SDL_GetScancodeFromKey(SDLK_LCTRL);
keymap[0x5d] = SDL_GetScancodeFromKey(SDLK_LALT);
keymap[0x5e] = SDL_GetScancodeFromKey(SDLK_SPACE);
keymap[0x5f] = SDL_GetScancodeFromKey(SDLK_RALT);
keymap[0x60] = SDL_GetScancodeFromKey(SDLK_RCTRL);
keymap[0x61] = SDL_GetScancodeFromKey(SDLK_LEFT);
keymap[0x62] = SDL_GetScancodeFromKey(SDLK_DOWN);
keymap[0x63] = SDL_GetScancodeFromKey(SDLK_RIGHT);
keymap[0x64] = SDL_GetScancodeFromKey(SDLK_KP_0);
keymap[0x65] = SDL_GetScancodeFromKey(SDLK_KP_PERIOD);
keymap[0x66] = SDL_GetScancodeFromKey(SDLK_LGUI);
keymap[0x67] = SDL_GetScancodeFromKey(SDLK_RGUI);
keymap[0x68] = SDL_GetScancodeFromKey(SDLK_MENU);
keymap[0x69] = SDL_GetScancodeFromKey(SDLK_2); /* SDLK_EURO */
keymap[0x6a] = SDL_GetScancodeFromKey(SDLK_KP_EQUALS);
keymap[0x6b] = SDL_GetScancodeFromKey(SDLK_POWER);
}
SDL_Scancode BE_GetScancodeFromBeKey(int32 bkey) {
if(bkey > 0 && bkey < (int32)SDL_TABLESIZE(keymap)) {
return keymap[bkey];
} else {
return SDL_SCANCODE_UNKNOWN;
}
}
int8 BE_GetKeyState(int32 bkey) {
if(bkey > 0 && bkey < KEYMAP_SIZE) {
return keystate[bkey];
} else {
return SDL_RELEASED;
}
}
void BE_SetKeyState(int32 bkey, int8 state) {
if(bkey > 0 && bkey < KEYMAP_SIZE) {
keystate[bkey] = state;
}
}
#ifdef __cplusplus
}
#endif
#endif /* SDL_VIDEO_DRIVER_HAIKU */
| 0 | 0.914947 | 1 | 0.914947 | game-dev | MEDIA | 0.812821 | game-dev | 0.807652 | 1 | 0.807652 |
buildbuddy-io/buildbuddy | 33,504 | cli/explain/compactgraph/compactgraph.go | package compactgraph
import (
"bufio"
"cmp"
"errors"
"fmt"
"io"
"maps"
"path"
"slices"
"sort"
"strings"
"sync"
"github.com/buildbuddy-io/buildbuddy/cli/log"
"github.com/buildbuddy-io/buildbuddy/proto/spawn_diff"
"github.com/klauspost/compress/zstd"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/encoding/protodelim"
spawnproto "github.com/buildbuddy-io/buildbuddy/proto/spawn"
)
// CompactGraph represents the compact execution log as a directed acyclic graph of spawns.
type CompactGraph struct {
// The keys are the output paths of all spawns in the graph and each spawn contains references to other execution
// log entries, such as input files, directories, and input sets. The edges between spawns are tracked implicitly by
// matching the output paths of the spawns to the input paths of the referenced entries.
spawns map[string]*Spawn
// symlinkResolutions maps the paths of artifacts that are known to be symlinks to their target paths (through arbitrary
// levels of indirection).
symlinkResolutions map[string]string
settings globalSettings
}
type globalSettings struct {
hashFunction string
workspaceRunfilesDirectory string
legacyExternalRunfiles *bool
invocationId string
}
// ReadCompactLog reads a compact execution log from the given reader and returns the graph of spawns, the hash function
// used to compute the file digests, and an error if any.
func ReadCompactLog(in io.Reader) (*CompactGraph, error) {
diffEG := errgroup.Group{}
// A size > 1 shows noticeable performance improvements in benchmarks. Larger sizes don't show relevant further
// improvements.
entries := make(chan *spawnproto.ExecLogEntry, 100)
diffEG.Go(func() error {
defer close(entries)
d, err := zstd.NewReader(in)
if err != nil {
return err
}
defer d.Close()
r := bufio.NewReader(d)
unmarshalOpts := protodelim.UnmarshalOptions{MaxSize: -1}
for {
var entry spawnproto.ExecLogEntry
err = unmarshalOpts.UnmarshalFrom(r, &entry)
if err == io.EOF {
break
}
if err != nil {
return err
}
entries <- &entry
}
return nil
})
cg := &CompactGraph{}
diffEG.Go(func() error {
cg.spawns = make(map[string]*Spawn)
interner := newInterner()
previousInputs := make(map[uint32]Input)
previousInputs[0] = emptyInputSet
for entry := range entries {
switch entry.Type.(type) {
case *spawnproto.ExecLogEntry_Invocation_:
if entry.GetInvocation().GetSiblingRepositoryLayout() {
return errors.New("--experimental_sibling_repository_layout is not supported")
}
cg.settings.hashFunction = entry.GetInvocation().HashFunctionName
cg.settings.workspaceRunfilesDirectory = entry.GetInvocation().WorkspaceRunfilesDirectory
cg.settings.invocationId = entry.GetInvocation().GetId()
case *spawnproto.ExecLogEntry_File_:
file := protoToFile(entry.GetFile(), cg.settings.hashFunction)
previousInputs[entry.Id] = file
case *spawnproto.ExecLogEntry_UnresolvedSymlink_:
symlink := protoToSymlink(entry.GetUnresolvedSymlink())
previousInputs[entry.Id] = symlink
case *spawnproto.ExecLogEntry_Directory_:
dir := protoToDirectory(entry.GetDirectory(), cg.settings.hashFunction)
previousInputs[entry.Id] = dir
case *spawnproto.ExecLogEntry_InputSet_:
inputSet := protoToInputSet(entry.GetInputSet(), previousInputs)
previousInputs[entry.Id] = inputSet
case *spawnproto.ExecLogEntry_Spawn_:
spawn, outputPaths := protoToSpawn(entry.GetSpawn(), previousInputs, interner)
if spawn != nil {
for _, p := range outputPaths {
cg.spawns[p] = spawn
}
}
case *spawnproto.ExecLogEntry_SymlinkAction_:
symlinkAction := entry.GetSymlinkAction()
target := symlinkAction.InputPath
if resolvedTarget, ok := cg.symlinkResolutions[target]; ok {
target = resolvedTarget
}
if cg.symlinkResolutions == nil {
cg.symlinkResolutions = make(map[string]string)
}
cg.symlinkResolutions[symlinkAction.OutputPath] = target
case *spawnproto.ExecLogEntry_SymlinkEntrySet_:
symlinkEntrySet := protoToSymlinkEntrySet(entry.GetSymlinkEntrySet(), previousInputs)
previousInputs[entry.Id] = symlinkEntrySet
case *spawnproto.ExecLogEntry_RunfilesTree_:
runfilesTreeProto := entry.GetRunfilesTree()
if cg.settings.legacyExternalRunfiles == nil {
// The value of the legacy_external_runfiles flag is the same for all runfiles trees in a single
// build.
cg.settings.legacyExternalRunfiles = &runfilesTreeProto.LegacyExternalRunfiles
}
runfilesTree := protoToRunfilesTree(runfilesTreeProto, previousInputs, cg.settings.hashFunction, interner)
previousInputs[entry.Id] = addRunfilesTreeSpawn(cg, runfilesTree)
default:
log.Fatalf("unexpected entry type: %T", entry.Type)
}
}
return nil
})
err := diffEG.Wait()
if err != nil {
return nil, err
}
return cg, nil
}
func newInterner() func(string) string {
interned := make(map[string]string)
return func(s string) string {
if i, ok := interned[s]; ok {
return i
}
interned[s] = s
return s
}
}
// This synthetic mnemonic contains a space to ensure it doesn't conflict with any real mnemonic.
const runfilesTreeSpawnMnemonic = "Runfiles directory"
// addRunfilesTreeSpawn adds a synthetic spawn creating the given runfiles tree and returns its output, which is an
// opaque directory that represents the runfiles tree. This is used to structurally "intern" the runfiles tree and diff
// it only once, even if it is used as a tool in multiple spawns or is an input to a test with multiple attempts.
func addRunfilesTreeSpawn(cg *CompactGraph, tree *RunfilesTree) Input {
output := &OpaqueRunfilesDirectory{tree}
s := &Spawn{
Mnemonic: runfilesTreeSpawnMnemonic,
Inputs: &InputSet{
DirectEntries: []Input{tree},
shallowPathHash: tree.ShallowPathHash(),
shallowContentHash: tree.ShallowContentHash(),
},
Tools: emptyInputSet,
ParamFiles: emptyInputSet,
Outputs: []Input{output},
}
// The spawn producing the executable corresponding to this runfiles tree may not have been run in the current
// build, but if it has, we can attach a label to the runfiles tree.
runfilesOwner := cg.resolveSymlinksFunc()(strings.TrimSuffix(tree.Path(), ".runfiles"))
if owner, ok := cg.spawns[runfilesOwner]; ok {
s.TargetLabel = owner.TargetLabel
}
cg.spawns[tree.Path()] = s
return output
}
func Diff(old, new *CompactGraph) (*spawn_diff.DiffResult, error) {
settingDiffs := diffSettings(&old.settings, &new.settings)
if settingDiffs != nil {
return nil, fmt.Errorf("global settings changed:\n%s", strings.Join(settingDiffs, "\n"))
}
var spawnDiffs []*spawn_diff.SpawnDiff
oldPrimaryOutputs := old.primaryOutputs()
newPrimaryOutputs := new.primaryOutputs()
oldOnlyPrimaryOutputs := setDifference(oldPrimaryOutputs, newPrimaryOutputs)
oldOnlyTopLevelOutputs := old.findRootSet(oldOnlyPrimaryOutputs)
for _, p := range oldOnlyPrimaryOutputs {
sd := newDiff(old.spawns[p])
_, topLevel := oldOnlyTopLevelOutputs[p]
sd.Diff = &spawn_diff.SpawnDiff_OldOnly{OldOnly: &spawn_diff.OldOnly{
TopLevel: topLevel,
}}
spawnDiffs = append(spawnDiffs, sd)
}
newOnlyPrimaryOutputs := setDifference(newPrimaryOutputs, oldPrimaryOutputs)
newOnlyTopLevelOutputs := new.findRootSet(newOnlyPrimaryOutputs)
for _, p := range newOnlyPrimaryOutputs {
sd := newDiff(new.spawns[p])
_, topLevel := newOnlyTopLevelOutputs[p]
sd.Diff = &spawn_diff.SpawnDiff_NewOnly{NewOnly: &spawn_diff.NewOnly{
TopLevel: topLevel,
}}
spawnDiffs = append(spawnDiffs, sd)
}
commonOutputs := setIntersection(oldPrimaryOutputs, newPrimaryOutputs)
var commonSpawnOutputs, commonRunfilesTrees []string
for _, output := range commonOutputs {
oldIsRunfilesTree := old.spawns[output].Mnemonic == runfilesTreeSpawnMnemonic
newIsRunfilesTree := new.spawns[output].Mnemonic == runfilesTreeSpawnMnemonic
if oldIsRunfilesTree || newIsRunfilesTree {
if !oldIsRunfilesTree || !newIsRunfilesTree {
// This can only happen in pathological cases where an executable in one build no longer exists in
// another build, but an output at <executable>.runfiles does.
log.Fatalf("inconsistent runfiles trees %s: %v vs. %v", output, old.spawns[output], new.spawns[output])
}
commonRunfilesTrees = append(commonRunfilesTrees, output)
} else {
commonSpawnOutputs = append(commonSpawnOutputs, output)
}
}
oldResolveSymlinks := old.resolveSymlinksFunc()
newResolveSymlinks := new.resolveSymlinksFunc()
type diffResult struct {
spawnDiff *spawn_diff.SpawnDiff
localChange bool
invalidatedBy []string
invalidates []any
}
diffResults := sync.Map{}
diffWG := sync.WaitGroup{}
// Diff runfiles tree spawns first to compute exact content hashes that are used when diffing other spawns.
for _, output := range commonRunfilesTrees {
diffWG.Add(1)
go func() {
defer diffWG.Done()
spawnDiff, localChange, invalidatedBy := diffRunfilesTrees(old.spawns[output], new.spawns[output], oldResolveSymlinks, newResolveSymlinks, old.settings.workspaceRunfilesDirectory, old.settings.hashFunction)
diffResults.Store(output, &diffResult{
spawnDiff: spawnDiff,
localChange: localChange,
invalidatedBy: invalidatedBy,
})
}()
}
diffWG.Wait()
for _, output := range commonSpawnOutputs {
diffWG.Add(1)
go func() {
defer diffWG.Done()
spawnDiff, localChange, invalidatedBy := diffSpawns(old.spawns[output], new.spawns[output], oldResolveSymlinks, newResolveSymlinks)
diffResults.Store(output, &diffResult{
spawnDiff: spawnDiff,
localChange: localChange,
invalidatedBy: invalidatedBy,
})
}()
}
diffWG.Wait()
// Visit spawns in topological order and attribute their diffs to transitive dependencies if possible.
commonOutputsSet := make(map[string]struct{})
for _, output := range commonOutputs {
commonOutputsSet[output] = struct{}{}
}
for _, output := range new.sortedPrimaryOutputs() {
if _, ok := commonOutputsSet[output]; !ok {
continue
}
resultEntry, _ := diffResults.Load(output)
result := resultEntry.(*diffResult)
if len(result.spawnDiff.GetModified().Diffs) == 0 {
continue
}
spawn := new.spawns[output]
foundTransitiveCause := false
// Don't propagate invalidations through local changes:
// 1) The local change would cause the spawn to be re-run anyway, which in turn may be responsible for the
// invalidation of dependents.
// 2) Avoids pathological memory usage during flattening below for a large number of local changes that each
// invalidate a large number of other local changes - if all of them are flattened, the memory usage can grow
// quadratically in the number of local changes.
if !result.localChange {
// Get the deduplicated primary outputs for those spawns referenced via invalidatedBy.
invalidatedByPrimaryOutput := make(map[string]struct{})
for _, invalidatedBy := range result.invalidatedBy {
if s, ok := new.spawns[invalidatedBy]; ok {
invalidatedByPrimaryOutput[s.PrimaryOutputPath()] = struct{}{}
}
}
for invalidatedBy, _ := range invalidatedByPrimaryOutput {
if invalidatingResultEntry, ok := diffResults.Load(invalidatedBy); ok {
invalidatingResult := invalidatingResultEntry.(*diffResult)
foundTransitiveCause = true
// Intentionally not flattening the slice here to avoid quadratic complexity when there are many
// transitively invalidated target, but few transitive causes. Quadratic complexity can't be avoided
// in the general case.
invalidatingResult.invalidates = append(invalidatingResult.invalidates, result.invalidates, spawn)
}
}
}
if result.localChange || !foundTransitiveCause {
if len(result.invalidates) > 0 {
// result.invalidates isn't modified after this point as the spawns are visited in topological order.
diffWG.Add(1)
go func() {
defer diffWG.Done()
result.spawnDiff.GetModified().TransitivelyInvalidated = flattenInvalidates(result.invalidates, isExecOutputPath(output))
}()
}
spawnDiffs = append(spawnDiffs, result.spawnDiff)
}
}
diffWG.Wait()
return &spawn_diff.DiffResult{
SpawnDiffs: spawnDiffs,
OldInvocationId: old.settings.invocationId,
NewInvocationId: new.settings.invocationId,
}, nil
}
// flattenInvalidates flattens a tree of Spawn nodes into a deduplicated map of mnemonic to count of transitively
// invalidated spawns.
// Mnemonics of spawns are suffixed with " (as tool)" if the invalidating spawn is a tool and the invalidated spawn is
// not, that is, if the dependency path crosses an edge with an "exec" transition (ignoring "exec" transitions on
// targets that are already in the "exec" configuration).
func flattenInvalidates(invalidates []any, isTool bool) map[string]uint32 {
transitivelyInvalidated := make(map[string]uint32)
spawnsSeen := make(map[*Spawn]struct{})
toVisit := invalidates
for len(toVisit) > 0 {
var n any
n, toVisit = toVisit[0], toVisit[1:]
switch n := n.(type) {
case *Spawn:
if _, seen := spawnsSeen[n]; !seen {
spawnsSeen[n] = struct{}{}
suffix := ""
if isTool && !isExecOutputPath(n.PrimaryOutputPath()) {
suffix = " (as tool)"
}
transitivelyInvalidated[n.Mnemonic+suffix]++
}
default:
// If n is not a Spawn, it must be a slice of Spawns or slices.
toVisit = append(toVisit, n.([]any)...)
}
}
return transitivelyInvalidated
}
func diffSettings(old, new *globalSettings) []string {
var settingDiffs []string
if old.hashFunction != new.hashFunction {
settingDiffs = append(settingDiffs, fmt.Sprintf(" --digest_function: %s -> %s\n", old.hashFunction, new.hashFunction))
}
if old.workspaceRunfilesDirectory != new.workspaceRunfilesDirectory {
oldUsesLegacyExeclog := old.workspaceRunfilesDirectory == ""
newUsesLegacyExeclog := new.workspaceRunfilesDirectory == ""
oldUsesBzlmod := old.workspaceRunfilesDirectory == "_main"
newUsesBzlmod := new.workspaceRunfilesDirectory == "_main"
if oldUsesLegacyExeclog != newUsesLegacyExeclog {
settingDiffs = append(settingDiffs, fmt.Sprintf(" Bazel 7.4.0 or higher: %t -> %t", !oldUsesLegacyExeclog, !newUsesLegacyExeclog))
} else if oldUsesBzlmod != newUsesBzlmod {
settingDiffs = append(settingDiffs, fmt.Sprintf(" --enable_bzlmod: %t -> %t", oldUsesBzlmod, newUsesBzlmod))
} else {
settingDiffs = append(settingDiffs, fmt.Sprintf(" WORKSPACE name: %s -> %s", old.workspaceRunfilesDirectory, new.workspaceRunfilesDirectory))
}
}
// One build may contain spawns with runfiles trees, while the other doesn't. In this case, the flag is set to nil
// in the latter build and shouldn't be considered a change.
if old.legacyExternalRunfiles != nil && new.legacyExternalRunfiles != nil && *old.legacyExternalRunfiles != *new.legacyExternalRunfiles {
settingDiffs = append(settingDiffs, fmt.Sprintf(" --legacy_external_runfiles: %t -> %t", *old.legacyExternalRunfiles, *new.legacyExternalRunfiles))
}
return settingDiffs
}
// findRootSet returns the subset of outputs that are not inputs to any other spawn in the subgraph corresponding to
// the given outputs.
func (cg *CompactGraph) findRootSet(outputs []string) map[string]struct{} {
rootsSet := make(map[string]struct{}, len(outputs))
for _, output := range outputs {
rootsSet[output] = struct{}{}
}
// Visit all nodes in the graph and remove those with incoming edges from the set of roots.
var toVisit []any
visited := make(map[any]struct{})
markForVisit := func(n any) {
if _, seen := visited[n]; !seen {
toVisit = append(toVisit, n)
visited[n] = struct{}{}
}
}
for _, output := range outputs {
markForVisit(cg.spawns[output])
}
for len(toVisit) > 0 {
var node any
node, toVisit = toVisit[0], toVisit[1:]
switch n := node.(type) {
case *File:
delete(rootsSet, n.Path())
case *Directory:
delete(rootsSet, n.Path())
}
cg.visitSuccessors(node, markForVisit)
}
return rootsSet
}
// sortedPrimaryOutputs returns the primary output paths of the spawns in topological order.
func (cg *CompactGraph) sortedPrimaryOutputs() []string {
toVisit := make([]any, 0, len(cg.spawns))
for output, spawn := range cg.spawns {
if spawn.PrimaryOutputPath() == output {
toVisit = append(toVisit, spawn)
}
}
sort.Slice(toVisit, func(i, j int) bool {
return toVisit[i].(*Spawn).PrimaryOutputPath() < toVisit[j].(*Spawn).PrimaryOutputPath()
})
ordered := make([]string, 0, len(cg.spawns))
// An entry is present in the map if it has been visited and its state is true if it either isn't a spawn or its
// been visited again (necessarily after all its successors have been visited).
state := make(map[any]bool)
for len(toVisit) > 0 {
n := toVisit[len(toVisit)-1]
toVisit = toVisit[:len(toVisit)-1]
if done, seen := state[n]; seen {
if !done {
state[n] = true
ordered = append(ordered, n.(*Spawn).PrimaryOutputPath())
}
continue
}
// Only spawns need to be revisited.
if _, isSpawn := n.(*Spawn); isSpawn {
state[n] = false
toVisit = append(toVisit, n)
} else {
state[n] = true
}
cg.visitSuccessors(n, func(input any) {
toVisit = append(toVisit, input)
})
}
slices.Reverse(ordered)
return ordered
}
func (cg *CompactGraph) visitSuccessors(node any, visitor func(input any)) {
switch n := node.(type) {
case *File:
if spawn, ok := cg.spawns[n.Path()]; ok {
visitor(spawn)
}
case *Directory:
if spawn, ok := cg.spawns[n.Path()]; ok {
visitor(spawn)
}
case *InputSet:
for _, input := range n.DirectEntries {
visitor(input)
}
for _, transitiveSet := range n.TransitiveSets {
visitor(transitiveSet)
}
case *SymlinkEntrySet:
targets := slices.SortedFunc(maps.Values(n.directEntries), func(a, b Input) int {
return cmp.Compare(a.Path(), b.Path())
})
for _, target := range targets {
visitor(target)
}
for _, transitiveSet := range n.transitiveSets {
visitor(transitiveSet)
}
case *RunfilesTree:
visitor(n.Artifacts)
visitor(n.Symlinks)
visitor(n.RootSymlinks)
// The repo mapping manifest is a synthetic File not produced by any Spawn, so we don't need to visit it.
case *OpaqueRunfilesDirectory:
visitor(cg.spawns[n.Path()])
case *Spawn:
visitor(n.Inputs)
// Tools are a subset of all inputs, so we don't need to visit them separately.
}
}
func (cg *CompactGraph) primaryOutputs() []string {
var primaryOutputs []string
for p, spawn := range cg.spawns {
if spawn.PrimaryOutputPath() == p {
primaryOutputs = append(primaryOutputs, p)
}
}
slices.Sort(primaryOutputs)
return primaryOutputs
}
func (cg *CompactGraph) resolveSymlinksFunc() func(string) string {
return func(p string) string {
// Symlinks are resolved deeply before being stored in the map, so a single lookup is sufficient.
if resolved, ok := cg.symlinkResolutions[p]; ok {
return resolved
}
return p
}
}
func diffSpawns(old, new *Spawn, oldResolveSymlinks, newResolveSymlinks func(string) string) (diff *spawn_diff.SpawnDiff, localChange bool, invalidatedBy []string) {
diff = newDiff(new)
m := &spawn_diff.Modified{}
diff.Diff = &spawn_diff.SpawnDiff_Modified{Modified: m}
envDiff := diffDicts(old.Env, new.Env)
if envDiff != nil {
localChange = true
m.Diffs = append(m.Diffs, &spawn_diff.Diff{Diff: &spawn_diff.Diff_Env{Env: envDiff}})
}
execPropertiesDiff := diffDicts(old.ExecProperties, new.ExecProperties)
if execPropertiesDiff != nil {
localChange = true
m.Diffs = append(m.Diffs, &spawn_diff.Diff{Diff: &spawn_diff.Diff_ExecProperties{ExecProperties: execPropertiesDiff}})
}
inputPathsDiff, inputContentsDiff := diffInputSets(old.Inputs, new.Inputs, oldResolveSymlinks, newResolveSymlinks)
if inputPathsDiff != nil {
m.Diffs = append(m.Diffs, &spawn_diff.Diff{Diff: &spawn_diff.Diff_InputPaths{InputPaths: inputPathsDiff}})
}
if inputContentsDiff != nil {
m.Diffs = append(m.Diffs, &spawn_diff.Diff{Diff: &spawn_diff.Diff_InputContents{InputContents: inputContentsDiff}})
}
// Tools are a subset of all inputs, so we only need to compare the paths, not the contents.
toolPathsDiff := diffInputSetsIgnoringContents(old.Tools, new.Tools, oldResolveSymlinks, newResolveSymlinks)
if toolPathsDiff != nil {
m.Diffs = append(m.Diffs, &spawn_diff.Diff{Diff: &spawn_diff.Diff_ToolPaths{ToolPaths: toolPathsDiff}})
}
argsChanged := !slices.Equal(old.Args, new.Args)
if argsChanged {
m.Diffs = append(m.Diffs, &spawn_diff.Diff{Diff: &spawn_diff.Diff_Args{
Args: &spawn_diff.ListDiff{
Old: old.Args,
New: new.Args,
},
}})
}
paramFilePathsDiff, paramFileContentsDiff := diffInputSets(old.ParamFiles, new.ParamFiles, oldResolveSymlinks, newResolveSymlinks)
if paramFilePathsDiff != nil {
localChange = true
m.Diffs = append(m.Diffs, &spawn_diff.Diff{Diff: &spawn_diff.Diff_ParamFilePaths{ParamFilePaths: paramFilePathsDiff}})
}
if paramFileContentsDiff != nil {
m.Diffs = append(m.Diffs, &spawn_diff.Diff{Diff: &spawn_diff.Diff_ParamFileContents{ParamFileContents: paramFileContentsDiff}})
}
// We assume that changes in the spawn's arguments are caused by changes to the spawn's input or tool paths if any
// and thus don't show the spawn's diff if the path and argument changes are the only differences and the spawn that
// caused the path changes is contained in the log (and thus shown as the transitive cause).
// This heuristic can be wrong if the spawn's arguments also changed in other ways (e.g. adding a copt and a new dep
// at the same time), but we would still show at least one (transitive) cause for invalidating the spawn.
if (argsChanged || paramFilePathsDiff != nil || paramFileContentsDiff != nil) && inputPathsDiff == nil && toolPathsDiff == nil && !mayExplainArgsChange(inputContentsDiff) {
// Split XML generation receives the test duration as an argument, which is clearly non-hermetic and should not
// be considered at all if the test action reran.
if new.Mnemonic == testRunnerXmlGeneration {
m.Expected = true
} else {
localChange = true
}
}
for _, fileDiff := range inputContentsDiff.GetFileDiffs() {
var p string
switch fd := fileDiff.New.(type) {
case *spawn_diff.FileDiff_NewFile:
p = fd.NewFile.Path
case *spawn_diff.FileDiff_NewSymlink:
p = fd.NewSymlink.Path
case *spawn_diff.FileDiff_NewDirectory:
p = fd.NewDirectory.Path
}
if isSourcePath(p) {
localChange = true
} else {
invalidatedBy = append(invalidatedBy, p)
}
}
if new.Mnemonic == testRunnerXmlGeneration && argsChanged && len(invalidatedBy) == 0 {
// The arguments for the split XML generation contain the duration of the test, which is non-hermetic. We
// attribute it to the main test action, which has the test log as primary output.
testLog := path.Dir(new.PrimaryOutputPath()) + "/test.log"
invalidatedBy = append(invalidatedBy, testLog)
}
// TODO: Report changes in the set of inputs if neither the contents nor the arguments changed.
var oldOutputPaths []string
for _, output := range old.Outputs {
oldOutputPaths = append(oldOutputPaths, output.Path())
}
slices.Sort(oldOutputPaths)
var newOutputPaths []string
for _, output := range new.Outputs {
newOutputPaths = append(newOutputPaths, output.Path())
}
slices.Sort(newOutputPaths)
if !slices.Equal(oldOutputPaths, newOutputPaths) {
localChange = true
m.Diffs = append(m.Diffs, &spawn_diff.Diff{Diff: &spawn_diff.Diff_OutputPaths{
OutputPaths: &spawn_diff.StringSetDiff{
OldOnly: setDifference(oldOutputPaths, newOutputPaths),
NewOnly: setDifference(newOutputPaths, oldOutputPaths),
},
}})
}
// Do not report changes in the outputs of a spawn whose inputs changed.
if len(m.Diffs) > 0 {
return
}
if new.ExitCode != old.ExitCode {
// This action is flaky, always report it.
localChange = true
m.Diffs = append(m.Diffs, &spawn_diff.Diff{Diff: &spawn_diff.Diff_ExitCode{
ExitCode: &spawn_diff.IntDiff{
Old: old.ExitCode,
New: new.ExitCode,
},
}})
// Don't report changes in the outputs of a flaky action.
return
}
var outputContentsDiffs []*spawn_diff.FileDiff
for i, oldOutput := range old.Outputs {
// oldOutput.Path() == new.Outputs[i].Path() by construction, so we can pass either as the unresolved path.
fileDiff := diffContents(oldOutput, new.Outputs[i], oldOutput.Path(), oldResolveSymlinks, newResolveSymlinks)
if fileDiff != nil {
outputContentsDiffs = append(outputContentsDiffs, fileDiff)
}
}
if len(outputContentsDiffs) > 0 {
// This action is non-hermetic, always report it.
localChange = true
if new.Mnemonic == "TestRunner" {
// Test action outputs are usually non-reproducible due to timestamps in the test.log and test.xml files.
m.Expected = true
}
m.Diffs = append(m.Diffs, &spawn_diff.Diff{Diff: &spawn_diff.Diff_OutputContents{
OutputContents: &spawn_diff.FileSetDiff{FileDiffs: outputContentsDiffs},
}})
}
return
}
// mayExplainArgsChange returns true if the given diff of input contents may explain a change in the spawn's arguments.
func mayExplainArgsChange(diff *spawn_diff.FileSetDiff) bool {
for _, fileDiff := range diff.GetFileDiffs() {
// Contents of non-directories and source directories are not evaluated before spawn execution and thus don't
// influence the spawn's arguments. Runfiles directories can be flattened in rules logic, but this is only
// commonly done when the runfiles are staged as inputs (e.g. in packaging actions), not as runfiles. In the
// former case, they wouldn't show up as directories at this point.
if fileDiff.GetOldDirectory() == nil || fileDiff.GetNewDirectory() == nil || !IsTreeArtifactPath(fileDiff.LogicalPath) {
continue
}
if len(fileDiff.GetOldDirectory().Files) != len(fileDiff.GetNewDirectory().Files) {
return true
}
oldPaths := make(map[string]struct{})
for _, oldFile := range fileDiff.GetOldDirectory().Files {
oldPaths[oldFile.Path] = struct{}{}
}
for _, newFile := range fileDiff.GetNewDirectory().Files {
if _, ok := oldPaths[newFile.Path]; !ok {
return true
}
}
}
return false
}
func diffInputSets(old, new *InputSet, oldResolveSymlinks, newResolveSymlinks func(string) string) (pathsDiff *spawn_diff.StringSetDiff, contentsDiff *spawn_diff.FileSetDiff) {
return diffInputSetsInternal(old, new, oldResolveSymlinks, newResolveSymlinks, false)
}
func diffInputSetsIgnoringContents(old, new *InputSet, oldResolveSymlinks, newResolveSymlinks func(string) string) *spawn_diff.StringSetDiff {
pathsDiff, _ := diffInputSetsInternal(old, new, oldResolveSymlinks, newResolveSymlinks, true)
return pathsDiff
}
func diffInputSetsInternal(old, new *InputSet, oldResolveSymlinks, newResolveSymlinks func(string) string, ignoreContents bool) (pathsDiff *spawn_diff.StringSetDiff, contentsDiff *spawn_diff.FileSetDiff) {
pathsCertainlyUnchanged := slices.Equal(old.ShallowPathHash(), new.ShallowPathHash())
contentsCertainlyUnchanged := ignoreContents || slices.Equal(old.ShallowContentHash(), new.ShallowContentHash())
if pathsCertainlyUnchanged && contentsCertainlyUnchanged {
return nil, nil
}
oldInputs := old.Flatten()
newInputs := new.Flatten()
if !pathsCertainlyUnchanged && !slices.EqualFunc(oldInputs, newInputs, func(a, b Input) bool { return a.Path() == b.Path() }) {
oldPaths := make([]string, len(oldInputs))
for i, input := range oldInputs {
oldPaths[i] = input.Path()
}
newPaths := make([]string, len(newInputs))
for i, input := range newInputs {
newPaths[i] = input.Path()
}
return &spawn_diff.StringSetDiff{
OldOnly: setDifference(oldPaths, newPaths),
NewOnly: setDifference(newPaths, oldPaths),
}, nil
}
if !contentsCertainlyUnchanged {
var fileDiffs []*spawn_diff.FileDiff
for i, oldInput := range oldInputs {
// oldInput.Path() == newInputs[i].Path() by construction, so we can pass either as the unresolved path.
fileDiff := diffContents(oldInput, newInputs[i], oldInput.Path(), oldResolveSymlinks, newResolveSymlinks)
if fileDiff != nil {
fileDiffs = append(fileDiffs, fileDiff)
}
}
if len(fileDiffs) > 0 {
return nil, &spawn_diff.FileSetDiff{FileDiffs: fileDiffs}
}
}
return nil, nil
}
// diffRunfilesTrees returns a diff of the runfiles trees if the paths or contents of the inputs differ, or nil if they
// are equal.
func diffRunfilesTrees(old, new *Spawn, oldResolveSymlinks, newResolveSymlinks func(string) string, workspaceRunfilesDirectory, hashFunction string) (diff *spawn_diff.SpawnDiff, localChange bool, invalidatedBy []string) {
oldTree := old.Inputs.DirectEntries[0].(*RunfilesTree)
newTree := new.Inputs.DirectEntries[0].(*RunfilesTree)
diff = newDiff(new)
m := &spawn_diff.Modified{}
diff.Diff = &spawn_diff.SpawnDiff_Modified{Modified: m}
contentsCertainlyUnchanged := slices.Equal(oldTree.ShallowContentHash(), newTree.ShallowContentHash())
if contentsCertainlyUnchanged {
return
}
oldMapping := oldTree.ComputeMapping(workspaceRunfilesDirectory, hashFunction)
newMapping := newTree.ComputeMapping(workspaceRunfilesDirectory, hashFunction)
var oldOnly, newOnly []string
for p, _ := range oldMapping {
if _, ok := newMapping[p]; !ok {
oldOnly = append(oldOnly, p)
}
}
for p, _ := range newMapping {
if _, ok := oldMapping[p]; !ok {
newOnly = append(newOnly, p)
}
}
if len(oldOnly) > 0 || len(newOnly) > 0 {
slices.Sort(oldOnly)
slices.Sort(newOnly)
localChange = true
m.Diffs = append(m.Diffs, &spawn_diff.Diff{Diff: &spawn_diff.Diff_InputPaths{
InputPaths: &spawn_diff.StringSetDiff{
OldOnly: oldOnly,
NewOnly: newOnly,
}}})
return
}
var fileDiffs []*spawn_diff.FileDiff
for p, oldInput := range oldMapping {
newInput := newMapping[p]
fileDiff := diffContents(oldInput, newInput, p, oldResolveSymlinks, newResolveSymlinks)
if fileDiff != nil {
fileDiffs = append(fileDiffs, fileDiff)
invalidatedBy = append(invalidatedBy, newInput.Path())
}
}
if len(fileDiffs) > 0 {
slices.SortFunc(fileDiffs, func(a, b *spawn_diff.FileDiff) int {
return cmp.Compare(a.LogicalPath, b.LogicalPath)
})
m.Diffs = append(m.Diffs, &spawn_diff.Diff{Diff: &spawn_diff.Diff_InputContents{
InputContents: &spawn_diff.FileSetDiff{
FileDiffs: fileDiffs,
}}})
}
return
}
// diffContents returns a file diff if the contents of the old and new inputs differ, or nil if they are equal.
func diffContents(old, new Input, logicalPath string, oldResolveSymlinks, newResolveSymlinks func(string) string) *spawn_diff.FileDiff {
if slices.Equal(old.ShallowContentHash(), new.ShallowContentHash()) {
return nil
}
fileDiff := &spawn_diff.FileDiff{
LogicalPath: logicalPath,
}
switch oldProto := old.Proto().(type) {
case *spawnproto.ExecLogEntry_File:
oldProto.Path = oldResolveSymlinks(oldProto.Path)
fileDiff.Old = &spawn_diff.FileDiff_OldFile{OldFile: oldProto}
case *spawnproto.ExecLogEntry_UnresolvedSymlink:
oldProto.Path = oldResolveSymlinks(oldProto.Path)
fileDiff.Old = &spawn_diff.FileDiff_OldSymlink{OldSymlink: oldProto}
case *spawnproto.ExecLogEntry_Directory:
oldProto.Path = oldResolveSymlinks(oldProto.Path)
fileDiff.Old = &spawn_diff.FileDiff_OldDirectory{OldDirectory: oldProto}
case string:
fileDiff.Old = &spawn_diff.FileDiff_OldInvalidOutput{OldInvalidOutput: oldProto}
}
switch newProto := new.Proto().(type) {
case *spawnproto.ExecLogEntry_File:
newProto.Path = newResolveSymlinks(newProto.Path)
fileDiff.New = &spawn_diff.FileDiff_NewFile{NewFile: newProto}
case *spawnproto.ExecLogEntry_UnresolvedSymlink:
newProto.Path = newResolveSymlinks(newProto.Path)
fileDiff.New = &spawn_diff.FileDiff_NewSymlink{NewSymlink: newProto}
case *spawnproto.ExecLogEntry_Directory:
newProto.Path = newResolveSymlinks(newProto.Path)
fileDiff.New = &spawn_diff.FileDiff_NewDirectory{NewDirectory: newProto}
case string:
fileDiff.New = &spawn_diff.FileDiff_NewInvalidOutput{NewInvalidOutput: newProto}
}
return fileDiff
}
func diffDicts(old, new map[string]string) *spawn_diff.DictDiff {
if maps.Equal(old, new) {
return nil
}
diff := &spawn_diff.DictDiff{
OldChanged: make(map[string]string),
NewChanged: make(map[string]string),
}
for key, value := range old {
if newValue, ok := new[key]; !ok || value != newValue {
diff.OldChanged[key] = value
}
}
for key, value := range new {
if oldValue, ok := old[key]; !ok || value != oldValue {
diff.NewChanged[key] = value
}
}
return diff
}
func newDiff(s *Spawn) *spawn_diff.SpawnDiff {
return &spawn_diff.SpawnDiff{
PrimaryOutput: s.PrimaryOutputPath(),
TargetLabel: s.TargetLabel,
Mnemonic: s.Mnemonic,
}
}
// setDifference computes the sorted slice a \ b for sorted slices a and b.
func setDifference(a, b []string) []string {
var difference []string
i, j := 0, 0
for i < len(a) && j < len(b) {
switch {
case a[i] < b[j]:
difference = append(difference, a[i])
i++
case a[i] > b[j]:
j++
default:
i++
j++
}
}
difference = append(difference, a[i:]...)
return difference
}
// setIntersection computes the sorted slice a ∩ b for sorted slices a and b.
func setIntersection(a, b []string) []string {
var intersection []string
i, j := 0, 0
for i < len(a) && j < len(b) {
switch {
case a[i] < b[j]:
i++
case a[i] > b[j]:
j++
default:
intersection = append(intersection, a[i])
i++
j++
}
}
return intersection
}
| 0 | 0.902016 | 1 | 0.902016 | game-dev | MEDIA | 0.408498 | game-dev | 0.870872 | 1 | 0.870872 |
dpjudas/SurrealEngine | 17,196 | Thirdparty/openmpt/include/nlohmann-json/include/nlohmann/detail/conversions/to_json.hpp | // __ _____ _____ _____
// __| | __| | | | JSON for Modern C++
// | | |__ | | | | | | version 3.12.0
// |_____|_____|_____|_|___| https://github.com/nlohmann/json
//
// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT
#pragma once
#include <nlohmann/detail/macro_scope.hpp> // JSON_HAS_CPP_17
#ifdef JSON_HAS_CPP_17
#include <optional> // optional
#endif
#include <algorithm> // copy
#include <iterator> // begin, end
#include <string> // string
#include <tuple> // tuple, get
#include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
#include <utility> // move, forward, declval, pair
#include <valarray> // valarray
#include <vector> // vector
#include <nlohmann/detail/iterators/iteration_proxy.hpp>
#include <nlohmann/detail/meta/cpp_future.hpp>
#include <nlohmann/detail/meta/std_fs.hpp>
#include <nlohmann/detail/meta/type_traits.hpp>
#include <nlohmann/detail/value_t.hpp>
NLOHMANN_JSON_NAMESPACE_BEGIN
namespace detail
{
//////////////////
// constructors //
//////////////////
/*
* Note all external_constructor<>::construct functions need to call
* j.m_data.m_value.destroy(j.m_data.m_type) to avoid a memory leak in case j contains an
* allocated value (e.g., a string). See bug issue
* https://github.com/nlohmann/json/issues/2865 for more information.
*/
template<value_t> struct external_constructor;
template<>
struct external_constructor<value_t::boolean>
{
template<typename BasicJsonType>
static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
{
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::boolean;
j.m_data.m_value = b;
j.assert_invariant();
}
};
template<>
struct external_constructor<value_t::string>
{
template<typename BasicJsonType>
static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
{
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::string;
j.m_data.m_value = s;
j.assert_invariant();
}
template<typename BasicJsonType>
static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
{
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::string;
j.m_data.m_value = std::move(s);
j.assert_invariant();
}
template < typename BasicJsonType, typename CompatibleStringType,
enable_if_t < !std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
int > = 0 >
static void construct(BasicJsonType& j, const CompatibleStringType& str)
{
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::string;
j.m_data.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
j.assert_invariant();
}
};
template<>
struct external_constructor<value_t::binary>
{
template<typename BasicJsonType>
static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b)
{
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::binary;
j.m_data.m_value = typename BasicJsonType::binary_t(b);
j.assert_invariant();
}
template<typename BasicJsonType>
static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b)
{
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::binary;
j.m_data.m_value = typename BasicJsonType::binary_t(std::move(b));
j.assert_invariant();
}
};
template<>
struct external_constructor<value_t::number_float>
{
template<typename BasicJsonType>
static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
{
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::number_float;
j.m_data.m_value = val;
j.assert_invariant();
}
};
template<>
struct external_constructor<value_t::number_unsigned>
{
template<typename BasicJsonType>
static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
{
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::number_unsigned;
j.m_data.m_value = val;
j.assert_invariant();
}
};
template<>
struct external_constructor<value_t::number_integer>
{
template<typename BasicJsonType>
static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
{
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::number_integer;
j.m_data.m_value = val;
j.assert_invariant();
}
};
template<>
struct external_constructor<value_t::array>
{
template<typename BasicJsonType>
static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
{
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::array;
j.m_data.m_value = arr;
j.set_parents();
j.assert_invariant();
}
template<typename BasicJsonType>
static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
{
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::array;
j.m_data.m_value = std::move(arr);
j.set_parents();
j.assert_invariant();
}
template < typename BasicJsonType, typename CompatibleArrayType,
enable_if_t < !std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
int > = 0 >
static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
{
using std::begin;
using std::end;
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::array;
j.m_data.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
j.set_parents();
j.assert_invariant();
}
template<typename BasicJsonType>
static void construct(BasicJsonType& j, const std::vector<bool>& arr)
{
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::array;
j.m_data.m_value = value_t::array;
j.m_data.m_value.array->reserve(arr.size());
for (const bool x : arr)
{
j.m_data.m_value.array->push_back(x);
j.set_parent(j.m_data.m_value.array->back());
}
j.assert_invariant();
}
template<typename BasicJsonType, typename T,
enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
static void construct(BasicJsonType& j, const std::valarray<T>& arr)
{
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::array;
j.m_data.m_value = value_t::array;
j.m_data.m_value.array->resize(arr.size());
if (arr.size() > 0)
{
std::copy(std::begin(arr), std::end(arr), j.m_data.m_value.array->begin());
}
j.set_parents();
j.assert_invariant();
}
};
template<>
struct external_constructor<value_t::object>
{
template<typename BasicJsonType>
static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
{
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::object;
j.m_data.m_value = obj;
j.set_parents();
j.assert_invariant();
}
template<typename BasicJsonType>
static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
{
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::object;
j.m_data.m_value = std::move(obj);
j.set_parents();
j.assert_invariant();
}
template < typename BasicJsonType, typename CompatibleObjectType,
enable_if_t < !std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int > = 0 >
static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
{
using std::begin;
using std::end;
j.m_data.m_value.destroy(j.m_data.m_type);
j.m_data.m_type = value_t::object;
j.m_data.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
j.set_parents();
j.assert_invariant();
}
};
/////////////
// to_json //
/////////////
#ifdef JSON_HAS_CPP_17
template<typename BasicJsonType, typename T,
enable_if_t<std::is_constructible<BasicJsonType, T>::value, int> = 0>
void to_json(BasicJsonType& j, const std::optional<T>& opt)
{
if (opt.has_value())
{
j = *opt;
}
else
{
j = nullptr;
}
}
#endif
template<typename BasicJsonType, typename T,
enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
inline void to_json(BasicJsonType& j, T b) noexcept
{
external_constructor<value_t::boolean>::construct(j, b);
}
template < typename BasicJsonType, typename BoolRef,
enable_if_t <
((std::is_same<std::vector<bool>::reference, BoolRef>::value
&& !std::is_same <std::vector<bool>::reference, typename BasicJsonType::boolean_t&>::value)
|| (std::is_same<std::vector<bool>::const_reference, BoolRef>::value
&& !std::is_same <detail::uncvref_t<std::vector<bool>::const_reference>,
typename BasicJsonType::boolean_t >::value))
&& std::is_convertible<const BoolRef&, typename BasicJsonType::boolean_t>::value, int > = 0 >
inline void to_json(BasicJsonType& j, const BoolRef& b) noexcept
{
external_constructor<value_t::boolean>::construct(j, static_cast<typename BasicJsonType::boolean_t>(b));
}
template<typename BasicJsonType, typename CompatibleString,
enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
inline void to_json(BasicJsonType& j, const CompatibleString& s)
{
external_constructor<value_t::string>::construct(j, s);
}
template<typename BasicJsonType>
inline void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
{
external_constructor<value_t::string>::construct(j, std::move(s));
}
template<typename BasicJsonType, typename FloatType,
enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
inline void to_json(BasicJsonType& j, FloatType val) noexcept
{
external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
}
template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
inline void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
{
external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
}
template<typename BasicJsonType, typename CompatibleNumberIntegerType,
enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
inline void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
{
external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
}
#if !JSON_DISABLE_ENUM_SERIALIZATION
template<typename BasicJsonType, typename EnumType,
enable_if_t<std::is_enum<EnumType>::value, int> = 0>
inline void to_json(BasicJsonType& j, EnumType e) noexcept
{
using underlying_type = typename std::underlying_type<EnumType>::type;
static constexpr value_t integral_value_t = std::is_unsigned<underlying_type>::value ? value_t::number_unsigned : value_t::number_integer;
external_constructor<integral_value_t>::construct(j, static_cast<underlying_type>(e));
}
#endif // JSON_DISABLE_ENUM_SERIALIZATION
template<typename BasicJsonType>
inline void to_json(BasicJsonType& j, const std::vector<bool>& e)
{
external_constructor<value_t::array>::construct(j, e);
}
template < typename BasicJsonType, typename CompatibleArrayType,
enable_if_t < is_compatible_array_type<BasicJsonType,
CompatibleArrayType>::value&&
!is_compatible_object_type<BasicJsonType, CompatibleArrayType>::value&&
!is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value&&
!std::is_same<typename BasicJsonType::binary_t, CompatibleArrayType>::value&&
!is_basic_json<CompatibleArrayType>::value,
int > = 0 >
inline void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
{
external_constructor<value_t::array>::construct(j, arr);
}
template<typename BasicJsonType>
inline void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin)
{
external_constructor<value_t::binary>::construct(j, bin);
}
template<typename BasicJsonType, typename T,
enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
inline void to_json(BasicJsonType& j, const std::valarray<T>& arr)
{
external_constructor<value_t::array>::construct(j, std::move(arr));
}
template<typename BasicJsonType>
inline void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
{
external_constructor<value_t::array>::construct(j, std::move(arr));
}
template < typename BasicJsonType, typename CompatibleObjectType,
enable_if_t < is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value&& !is_basic_json<CompatibleObjectType>::value, int > = 0 >
inline void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
{
external_constructor<value_t::object>::construct(j, obj);
}
template<typename BasicJsonType>
inline void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
{
external_constructor<value_t::object>::construct(j, std::move(obj));
}
template <
typename BasicJsonType, typename T, std::size_t N,
enable_if_t < !std::is_constructible<typename BasicJsonType::string_t,
const T(&)[N]>::value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
int > = 0 >
inline void to_json(BasicJsonType& j, const T(&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
{
external_constructor<value_t::array>::construct(j, arr);
}
template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible<BasicJsonType, T1>::value&& std::is_constructible<BasicJsonType, T2>::value, int > = 0 >
inline void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
{
j = { p.first, p.second };
}
// for https://github.com/nlohmann/json/pull/1134
template<typename BasicJsonType, typename T,
enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
inline void to_json(BasicJsonType& j, const T& b)
{
j = { {b.key(), b.value()} };
}
template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
inline void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
{
j = { std::get<Idx>(t)... };
}
template<typename BasicJsonType, typename Tuple>
inline void to_json_tuple_impl(BasicJsonType& j, const Tuple& /*unused*/, index_sequence<> /*unused*/)
{
using array_t = typename BasicJsonType::array_t;
j = array_t();
}
template<typename BasicJsonType, typename T, enable_if_t<is_constructible_tuple<BasicJsonType, T>::value, int > = 0>
inline void to_json(BasicJsonType& j, const T& t)
{
to_json_tuple_impl(j, t, make_index_sequence<std::tuple_size<T>::value> {});
}
#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM
template<typename BasicJsonType>
inline void to_json(BasicJsonType& j, const std_fs::path& p)
{
#ifdef JSON_HAS_CPP_20
const std::u8string s = p.u8string();
j = std::string(s.begin(), s.end());
#else
j = p.u8string(); // returns std::string in C++17
#endif
}
#endif
struct to_json_fn
{
template<typename BasicJsonType, typename T>
auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
-> decltype(to_json(j, std::forward<T>(val)), void())
{
return to_json(j, std::forward<T>(val));
}
};
} // namespace detail
#ifndef JSON_HAS_CPP_17
/// namespace to hold default `to_json` function
/// to see why this is required:
/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces)
{
#endif
JSON_INLINE_VARIABLE constexpr const auto& to_json = // NOLINT(misc-definitions-in-headers)
detail::static_const<detail::to_json_fn>::value;
#ifndef JSON_HAS_CPP_17
} // namespace
#endif
NLOHMANN_JSON_NAMESPACE_END
| 0 | 0.907107 | 1 | 0.907107 | game-dev | MEDIA | 0.147885 | game-dev | 0.940161 | 1 | 0.940161 |
manisha-v/Unity3D | 7,351 | Part2 - 3D Object Intraction/Codes/Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Editor/TMP_ColorGradientEditor.cs | using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TMP_ColorGradient))]
public class TMP_ColorGradientEditor : Editor
{
SerializedProperty m_ColorMode;
SerializedProperty m_TopLeftColor;
SerializedProperty m_TopRightColor;
SerializedProperty m_BottomLeftColor;
SerializedProperty m_BottomRightColor;
void OnEnable()
{
m_ColorMode = serializedObject.FindProperty("colorMode");
m_TopLeftColor = serializedObject.FindProperty("topLeft");
m_TopRightColor = serializedObject.FindProperty("topRight");
m_BottomLeftColor = serializedObject.FindProperty("bottomLeft");
m_BottomRightColor = serializedObject.FindProperty("bottomRight");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_ColorMode, new GUIContent("Color Mode"));
if (EditorGUI.EndChangeCheck())
{
switch ((ColorMode)m_ColorMode.enumValueIndex)
{
case ColorMode.Single:
m_TopRightColor.colorValue = m_TopLeftColor.colorValue;
m_BottomLeftColor.colorValue = m_TopLeftColor.colorValue;
m_BottomRightColor.colorValue = m_TopLeftColor.colorValue;
break;
case ColorMode.HorizontalGradient:
m_BottomLeftColor.colorValue = m_TopLeftColor.colorValue;
m_BottomRightColor.colorValue = m_TopRightColor.colorValue;
break;
case ColorMode.VerticalGradient:
m_TopRightColor.colorValue = m_TopLeftColor.colorValue;
m_BottomRightColor.colorValue = m_BottomLeftColor.colorValue;
break;
}
}
Rect rect;
switch ((ColorMode)m_ColorMode.enumValueIndex)
{
case ColorMode.Single:
EditorGUI.BeginChangeCheck();
rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2));
EditorGUI.PrefixLabel(rect, new GUIContent("Colors"));
rect.x += EditorGUIUtility.labelWidth;
rect.width = (rect.width - EditorGUIUtility.labelWidth) / (EditorGUIUtility.wideMode ? 1f : 2f);
TMP_EditorUtility.DrawColorProperty(rect, m_TopLeftColor);
if (EditorGUI.EndChangeCheck())
{
m_TopRightColor.colorValue = m_TopLeftColor.colorValue;
m_BottomLeftColor.colorValue = m_TopLeftColor.colorValue;
m_BottomRightColor.colorValue = m_TopLeftColor.colorValue;
}
break;
case ColorMode.HorizontalGradient:
rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2));
EditorGUI.PrefixLabel(rect, new GUIContent("Colors"));
rect.x += EditorGUIUtility.labelWidth;
rect.width = (rect.width - EditorGUIUtility.labelWidth) / 2f;
EditorGUI.BeginChangeCheck();
TMP_EditorUtility.DrawColorProperty(rect, m_TopLeftColor);
if (EditorGUI.EndChangeCheck())
{
m_BottomLeftColor.colorValue = m_TopLeftColor.colorValue;
}
rect.x += rect.width;
EditorGUI.BeginChangeCheck();
TMP_EditorUtility.DrawColorProperty(rect, m_TopRightColor);
if (EditorGUI.EndChangeCheck())
{
m_BottomRightColor.colorValue = m_TopRightColor.colorValue;
}
break;
case ColorMode.VerticalGradient:
rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2));
EditorGUI.PrefixLabel(rect, new GUIContent("Colors"));
rect.x += EditorGUIUtility.labelWidth;
rect.width = (rect.width - EditorGUIUtility.labelWidth) / (EditorGUIUtility.wideMode ? 1f : 2f);
rect.height = EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2);
EditorGUI.BeginChangeCheck();
TMP_EditorUtility.DrawColorProperty(rect, m_TopLeftColor);
if (EditorGUI.EndChangeCheck())
{
m_TopRightColor.colorValue = m_TopLeftColor.colorValue;
}
rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2));
rect.x += EditorGUIUtility.labelWidth;
rect.width = (rect.width - EditorGUIUtility.labelWidth) / (EditorGUIUtility.wideMode ? 1f : 2f);
rect.height = EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2);
EditorGUI.BeginChangeCheck();
TMP_EditorUtility.DrawColorProperty(rect, m_BottomLeftColor);
if (EditorGUI.EndChangeCheck())
{
m_BottomRightColor.colorValue = m_BottomLeftColor.colorValue;
}
break;
case ColorMode.FourCornersGradient:
rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2));
EditorGUI.PrefixLabel(rect, new GUIContent("Colors"));
rect.x += EditorGUIUtility.labelWidth;
rect.width = (rect.width - EditorGUIUtility.labelWidth) / 2f;
rect.height = EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2);
TMP_EditorUtility.DrawColorProperty(rect, m_TopLeftColor);
rect.x += rect.width;
TMP_EditorUtility.DrawColorProperty(rect, m_TopRightColor);
rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2));
rect.x += EditorGUIUtility.labelWidth;
rect.width = (rect.width - EditorGUIUtility.labelWidth) / 2f;
rect.height = EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2);
TMP_EditorUtility.DrawColorProperty(rect, m_BottomLeftColor);
rect.x += rect.width;
TMP_EditorUtility.DrawColorProperty(rect, m_BottomRightColor);
break;
}
if (serializedObject.ApplyModifiedProperties())
TMPro_EventManager.ON_COLOR_GRADIENT_PROPERTY_CHANGED(target as TMP_ColorGradient);
}
}
}
| 0 | 0.83075 | 1 | 0.83075 | game-dev | MEDIA | 0.552347 | game-dev,desktop-app | 0.972602 | 1 | 0.972602 |
auroramod/iw7-mod | 4,873 | src/client/game/ui_scripting/script_value.hpp | #pragma once
#include "game/game.hpp"
#include <utils/string.hpp>
namespace ui_scripting
{
class lightuserdata;
class userdata_value;
class userdata;
class table_value;
class table;
class function;
class script_value;
namespace
{
template <typename T>
std::string get_typename()
{
auto& info = typeid(T);
if (info == typeid(std::string) ||
info == typeid(const char*))
{
return "string";
}
if (info == typeid(lightuserdata))
{
return "lightuserdata";
}
if (info == typeid(userdata))
{
return "userdata";
}
if (info == typeid(table))
{
return "table";
}
if (info == typeid(function))
{
return "function";
}
if (info == typeid(int) ||
info == typeid(float) ||
info == typeid(unsigned int))
{
return "number";
}
if (info == typeid(bool))
{
return "boolean";
}
return info.name();
}
}
class hks_object
{
public:
hks_object() = default;
hks_object(const game::hks::HksObject& value);
hks_object(const hks_object& other) noexcept;
hks_object(hks_object&& other) noexcept;
hks_object& operator=(const hks_object& other) noexcept;
hks_object& operator=(hks_object&& other) noexcept;
~hks_object();
const game::hks::HksObject& get() const;
private:
void assign(const game::hks::HksObject& value);
void release();
game::hks::HksObject value_{game::hks::TNONE, {}};
int ref_{};
};
using arguments = std::vector<script_value>;
using event_arguments = std::unordered_map<std::string, script_value>;
class script_value
{
public:
script_value() = default;
script_value(const game::hks::HksObject& value);
script_value(int value);
script_value(unsigned int value);
script_value(long long value);
script_value(unsigned long long value);
script_value(bool value);
script_value(float value);
script_value(double value);
script_value(const char* value);
script_value(const char* value, const size_t len);
script_value(const std::string& value);
script_value(const lightuserdata& value);
script_value(const userdata& value);
script_value(const table& value);
script_value(const function& value);
template <template<class, class> class C, class T, typename TableType = table>
script_value(const C<T, std::allocator<T>>& container)
{
TableType table_{};
int index = 1;
for (const auto& value : container)
{
table_.set(index++, value);
}
game::hks::HksObject obj{};
obj.t = game::hks::TTABLE;
obj.v.ptr = table_.ptr;
this->value_ = obj;
}
template <typename F>
script_value(F f)
: script_value(function(f))
{
}
bool operator==(const script_value& other) const;
arguments operator()() const;
arguments operator()(const arguments& arguments) const;
template<class ...T>
arguments operator()(T... arguments) const
{
return this->as<function>().call({arguments...});
}
template <size_t Size>
table_value operator[](const char(&key)[Size]) const
{
return {this->as<table>(), key};
}
template <typename T = script_value>
table_value operator[](const T& key) const
{
return {this->as<table>(), key};
}
template <typename T>
bool is() const;
template <typename T>
T as() const
{
if (!this->is<T>())
{
const auto hks_typename = game::hks::s_compilerTypeName[this->get_raw().t + 2];
const auto typename_ = get_typename<T>();
throw std::runtime_error(utils::string::va("%s expected, got %s",
typename_.data(), hks_typename));
}
return get<T>();
}
template <typename T>
operator T() const
{
return this->as<T>();
}
const game::hks::HksObject& get_raw() const;
hks_object value_{};
private:
template <typename T>
T get() const;
};
class variadic_args : public arguments
{
};
class function_argument
{
public:
function_argument(const arguments& args, const script_value& value, const int index);
template <typename T>
T as() const
{
try
{
return this->value_.as<T>();
}
catch (const std::exception& e)
{
throw std::runtime_error(utils::string::va("bad argument #%d (%s)",
this->index_ + 1, e.what()));
}
}
template <>
variadic_args as() const
{
variadic_args args{};
for (auto i = this->index_; i < this->values_.size(); i++)
{
args.push_back(this->values_[i]);
}
return args;
}
template <typename T>
operator T() const
{
return this->as<T>();
}
private:
arguments values_{};
script_value value_{};
int index_{};
};
class function_arguments
{
public:
function_arguments(const arguments& values);
function_argument operator[](const int index) const
{
if (index >= values_.size())
{
return {values_, {}, index};
}
return {values_, values_[index], index};
}
private:
arguments values_{};
};
}
| 0 | 0.928402 | 1 | 0.928402 | game-dev | MEDIA | 0.530229 | game-dev | 0.901711 | 1 | 0.901711 |
ModificationStation/StationAPI | 1,108 | station-items-v0/src/main/java/net/modificationstation/stationapi/mixin/item/client/GameRendererMixin.java | package net.modificationstation.stationapi.mixin.item.client;
import net.minecraft.class_555;
import net.minecraft.client.Minecraft;
import net.minecraft.util.hit.HitResultType;
import net.modificationstation.stationapi.api.StationAPI;
import net.modificationstation.stationapi.api.event.entity.player.PlayerEvent;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.Constant;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
@Mixin(class_555.class)
class GameRendererMixin {
@Shadow
private Minecraft field_2349;
@ModifyConstant(
method = "method_1838(F)V",
constant = @Constant(doubleValue = 3)
)
private double stationapi_getEntityReach(double originalReach) {
return StationAPI.EVENT_BUS.post(
PlayerEvent.Reach.builder()
.player(field_2349.player)
.type(HitResultType.ENTITY)
.currentReach(originalReach)
.build()
).currentReach;
}
}
| 0 | 0.585129 | 1 | 0.585129 | game-dev | MEDIA | 0.981278 | game-dev | 0.784912 | 1 | 0.784912 |
HackerN64/HackerOoT | 4,745 | src/overlays/actors/ovl_Bg_Zg/z_bg_zg.c | /*
* File: z_bg_zg.c
* Overlay: ovl_Bg_Zg
* Description: Metal bars (Ganon's Castle)
*/
#include "z_bg_zg.h"
#include "gfx.h"
#include "gfx_setupdl.h"
#include "ichain.h"
#include "printf.h"
#include "regs.h"
#include "sfx.h"
#include "sys_matrix.h"
#include "terminal.h"
#include "translation.h"
#include "play_state.h"
#include "assets/objects/object_zg/object_zg.h"
#define FLAGS ACTOR_FLAG_UPDATE_CULLING_DISABLED
void BgZg_Init(Actor* thisx, PlayState* play);
void BgZg_Destroy(Actor* thisx, PlayState* play);
void BgZg_Update(Actor* thisx, PlayState* play);
void BgZg_Draw(Actor* thisx, PlayState* play);
void func_808C0C50(BgZg* this);
s32 func_808C0C98(BgZg* this, PlayState* play);
s32 func_808C0CC8(BgZg* this);
void func_808C0CD4(BgZg* this, PlayState* play);
void func_808C0D08(BgZg* this, PlayState* play);
void func_808C0EEC(BgZg* this, PlayState* play);
static BgZgActionFunc sActionFuncs[] = {
func_808C0CD4,
func_808C0D08,
};
static InitChainEntry sInitChain[] = {
ICHAIN_VEC3F_DIV1000(scale, 1000, ICHAIN_STOP),
};
static BgZgDrawFunc sDrawFuncs[] = {
func_808C0EEC,
};
ActorProfile Bg_Zg_Profile = {
/**/ ACTOR_BG_ZG,
/**/ ACTORCAT_NPC,
/**/ FLAGS,
/**/ OBJECT_ZG,
/**/ sizeof(BgZg),
/**/ BgZg_Init,
/**/ BgZg_Destroy,
/**/ BgZg_Update,
/**/ BgZg_Draw,
};
void BgZg_Destroy(Actor* thisx, PlayState* play) {
BgZg* this = (BgZg*)thisx;
DynaPoly_DeleteBgActor(play, &play->colCtx.dyna, this->dyna.bgId);
}
void func_808C0C50(BgZg* this) {
SFX_PLAY_AT_POS(&this->dyna.actor.projectedPos, NA_SE_EV_METALDOOR_OPEN);
}
s32 func_808C0C98(BgZg* this, PlayState* play) {
s32 flag = PARAMS_GET_U(this->dyna.actor.params, 8, 8);
return Flags_GetSwitch(play, flag);
}
s32 func_808C0CC8(BgZg* this) {
s32 flag = PARAMS_GET_U(this->dyna.actor.params, 0, 8);
return flag;
}
void func_808C0CD4(BgZg* this, PlayState* play) {
#if PLATFORM_N64
// Anti-piracy check, bars will not open if the check fails.
// The address 0x000002E8 is near the start of RDRAM, and is written when IPL3 copies itself to
// RDRAM after RDRAM has been initialized. Specifically, this is an instruction from some
// embedded RSP code at offset 0x7F8 into IPL3 (0xC86E2000 disassembles to `lqv $v14[0], ($3)`).
if (IO_READ(0x000002E8) != 0xC86E2000) {
return;
}
#endif
if (func_808C0C98(this, play) != 0) {
this->action = 1;
func_808C0C50(this);
}
}
void func_808C0D08(BgZg* this, PlayState* play) {
this->dyna.actor.world.pos.y += (kREG(16) + 20.0f) * 1.2f;
if ((((kREG(17) + 200.0f) * 1.2f) + this->dyna.actor.home.pos.y) <= this->dyna.actor.world.pos.y) {
Actor_Kill(&this->dyna.actor);
}
}
void BgZg_Update(Actor* thisx, PlayState* play) {
BgZg* this = (BgZg*)thisx;
s32 action = this->action;
if (((action < 0) || (1 < action)) || (sActionFuncs[action] == NULL)) {
PRINTF(VT_FGCOL(RED) T("メインモードがおかしい!!!!!!!!!!!!!!!!!!!!!!!!!\n",
"The main mode is wrong!!!!!!!!!!!!!!!!!!!!!!!!!\n") VT_RST);
} else {
sActionFuncs[action](this, play);
}
}
void BgZg_Init(Actor* thisx, PlayState* play) {
s32 pad[2];
BgZg* this = (BgZg*)thisx;
CollisionHeader* colHeader;
Actor_ProcessInitChain(&this->dyna.actor, sInitChain);
DynaPolyActor_Init(&this->dyna, 0);
colHeader = NULL;
CollisionHeader_GetVirtual(&gTowerCollapseBarsCol, &colHeader);
this->dyna.bgId = DynaPoly_SetBgActor(play, &play->colCtx.dyna, &this->dyna.actor, colHeader);
if ((func_808C0CC8(this) == 8) || (func_808C0CC8(this) == 9)) {
this->dyna.actor.scale.x *= 1.3f;
this->dyna.actor.scale.z *= 1.3f;
this->dyna.actor.scale.y *= 1.2f;
}
this->action = 0;
this->drawConfig = 0;
if (func_808C0C98(this, play)) {
Actor_Kill(&this->dyna.actor);
}
}
void func_808C0EEC(BgZg* this, PlayState* play) {
GraphicsContext* localGfxCtx = play->state.gfxCtx;
OPEN_DISPS(localGfxCtx, "../z_bg_zg.c", 311);
Gfx_SetupDL_25Opa(localGfxCtx);
MATRIX_FINALIZE_AND_LOAD(POLY_OPA_DISP++, localGfxCtx, "../z_bg_zg.c", 315);
gSPDisplayList(POLY_OPA_DISP++, gTowerCollapseBarsDL);
CLOSE_DISPS(localGfxCtx, "../z_bg_zg.c", 320);
}
void BgZg_Draw(Actor* thisx, PlayState* play) {
BgZg* this = (BgZg*)thisx;
s32 drawConfig = this->drawConfig;
if (((drawConfig < 0) || (drawConfig > 0)) || sDrawFuncs[drawConfig] == NULL) {
PRINTF(VT_FGCOL(RED) T("描画モードがおかしい!!!!!!!!!!!!!!!!!!!!!!!!!\n",
"The drawing mode is wrong!!!!!!!!!!!!!!!!!!!!!!!!!\n") VT_RST);
} else {
sDrawFuncs[drawConfig](this, play);
}
}
| 0 | 0.690758 | 1 | 0.690758 | game-dev | MEDIA | 0.922747 | game-dev | 0.734319 | 1 | 0.734319 |
jswigart/omni-bot | 13,733 | GameInterfaces/RTCW-MP-GPL/src/bspc/aas_areamerging.c | /*
===========================================================================
Return to Castle Wolfenstein multiplayer GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein multiplayer GPL Source Code (RTCW MP Source Code).
RTCW MP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW MP Source Code 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 RTCW MP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW MP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW MP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
//===========================================================================
//
// Name: aas_areamerging.c
// Function: Merging of Areas
// Programmer: Mr Elusive (MrElusive@demigod.demon.nl)
// Last update: 1997-12-04
// Tab Size: 3
//===========================================================================
#include "qbsp.h"
#include "../botlib/aasfile.h"
#include "aas_create.h"
#include "aas_store.h"
#define CONVEX_EPSILON 0.3
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
tmp_node_t *AAS_RefreshMergedTree_r( tmp_node_t *tmpnode ) {
tmp_area_t *tmparea;
//if this is a solid leaf
if ( !tmpnode ) {
return NULL;
}
//if this is an area leaf
if ( tmpnode->tmparea ) {
tmparea = tmpnode->tmparea;
while ( tmparea->mergedarea ) tmparea = tmparea->mergedarea;
tmpnode->tmparea = tmparea;
return tmpnode;
} //end if
//do the children recursively
tmpnode->children[0] = AAS_RefreshMergedTree_r( tmpnode->children[0] );
tmpnode->children[1] = AAS_RefreshMergedTree_r( tmpnode->children[1] );
return tmpnode;
} //end of the function AAS_RefreshMergedTree_r
//===========================================================================
// returns true if the two given faces would create a non-convex area at
// the given sides, otherwise false is returned
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int NonConvex( tmp_face_t *face1, tmp_face_t *face2, int side1, int side2 ) {
int i;
winding_t *w1, *w2;
plane_t *plane1, *plane2;
w1 = face1->winding;
w2 = face2->winding;
plane1 = &mapplanes[face1->planenum ^ side1];
plane2 = &mapplanes[face2->planenum ^ side2];
//check if one of the points of face1 is at the back of the plane of face2
for ( i = 0; i < w1->numpoints; i++ )
{
if ( DotProduct( plane2->normal, w1->p[i] ) - plane2->dist < -CONVEX_EPSILON ) {
return true;
}
} //end for
//check if one of the points of face2 is at the back of the plane of face1
for ( i = 0; i < w2->numpoints; i++ )
{
if ( DotProduct( plane1->normal, w2->p[i] ) - plane1->dist < -CONVEX_EPSILON ) {
return true;
}
} //end for
return false;
} //end of the function NonConvex
//===========================================================================
// try to merge the areas at both sides of the given face
//
// Parameter: seperatingface : face that seperates two areas
// Returns: -
// Changes Globals: -
//===========================================================================
int AAS_TryMergeFaceAreas( tmp_face_t *seperatingface ) {
int side1, side2, area1faceflags, area2faceflags;
tmp_area_t *tmparea1, *tmparea2, *newarea;
tmp_face_t *face1, *face2, *nextface1, *nextface2;
tmparea1 = seperatingface->frontarea;
tmparea2 = seperatingface->backarea;
//areas must have the same presence type
if ( tmparea1->presencetype != tmparea2->presencetype ) {
return false;
}
//areas must have the same area contents
if ( tmparea1->contents != tmparea2->contents ) {
return false;
}
//areas must have the same bsp model inside (or both none)
if ( tmparea1->modelnum != tmparea2->modelnum ) {
return false;
}
area1faceflags = 0;
area2faceflags = 0;
for ( face1 = tmparea1->tmpfaces; face1; face1 = face1->next[side1] )
{
side1 = ( face1->frontarea != tmparea1 );
//debug: check if the area belongs to the area
if ( face1->frontarea != tmparea1 &&
face1->backarea != tmparea1 ) {
Error( "face does not belong to area1" );
}
//just continue if the face is seperating the two areas
//NOTE: a result of this is that ground and gap areas can
// be merged if the seperating face is the gap
if ( ( face1->frontarea == tmparea1 &&
face1->backarea == tmparea2 ) ||
( face1->frontarea == tmparea2 &&
face1->backarea == tmparea1 ) ) {
continue;
}
//get area1 face flags
area1faceflags |= face1->faceflags;
if ( AAS_GapFace( face1, side1 ) ) {
area1faceflags |= FACE_GAP;
}
//
for ( face2 = tmparea2->tmpfaces; face2; face2 = face2->next[side2] )
{
side2 = ( face2->frontarea != tmparea2 );
//debug: check if the area belongs to the area
if ( face2->frontarea != tmparea2 &&
face2->backarea != tmparea2 ) {
Error( "face does not belong to area2" );
}
//just continue if the face is seperating the two areas
//NOTE: a result of this is that ground and gap areas can
// be merged if the seperating face is the gap
if ( ( face2->frontarea == tmparea1 &&
face2->backarea == tmparea2 ) ||
( face2->frontarea == tmparea2 &&
face2->backarea == tmparea1 ) ) {
continue;
}
//get area2 face flags
area2faceflags |= face2->faceflags;
if ( AAS_GapFace( face2, side2 ) ) {
area2faceflags |= FACE_GAP;
}
//if the two faces would create a non-convex area
if ( NonConvex( face1, face2, side1, side2 ) ) {
return false;
}
} //end for
} //end for
//if one area has gap faces (that aren't seperating the two areas)
//and the other has ground faces (that aren't seperating the two areas),
//the areas can't be merged
if ( ( ( area1faceflags & FACE_GROUND ) && ( area2faceflags & FACE_GAP ) ) ||
( ( area2faceflags & FACE_GROUND ) && ( area1faceflags & FACE_GAP ) ) ) {
// Log_Print(" can't merge: ground/gap\n");
return false;
} //end if
// Log_Print("merged area %d & %d to %d with %d faces\n", tmparea1->areanum, tmparea2->areanum, newarea->areanum, numfaces);
// return false;
//
//AAS_CheckArea(tmparea1);
//AAS_CheckArea(tmparea2);
//create the new area
newarea = AAS_AllocTmpArea();
newarea->presencetype = tmparea1->presencetype;
newarea->contents = tmparea1->contents;
newarea->modelnum = tmparea1->modelnum;
newarea->tmpfaces = NULL;
//add all the faces (except the seperating ones) from the first area
//to the new area
for ( face1 = tmparea1->tmpfaces; face1; face1 = nextface1 )
{
side1 = ( face1->frontarea != tmparea1 );
nextface1 = face1->next[side1];
//don't add seperating faces
if ( ( face1->frontarea == tmparea1 &&
face1->backarea == tmparea2 ) ||
( face1->frontarea == tmparea2 &&
face1->backarea == tmparea1 ) ) {
continue;
} //end if
//
AAS_RemoveFaceFromArea( face1, tmparea1 );
AAS_AddFaceSideToArea( face1, side1, newarea );
} //end for
//add all the faces (except the seperating ones) from the second area
//to the new area
for ( face2 = tmparea2->tmpfaces; face2; face2 = nextface2 )
{
side2 = ( face2->frontarea != tmparea2 );
nextface2 = face2->next[side2];
//don't add seperating faces
if ( ( face2->frontarea == tmparea1 &&
face2->backarea == tmparea2 ) ||
( face2->frontarea == tmparea2 &&
face2->backarea == tmparea1 ) ) {
continue;
} //end if
//
AAS_RemoveFaceFromArea( face2, tmparea2 );
AAS_AddFaceSideToArea( face2, side2, newarea );
} //end for
//free all shared faces
for ( face1 = tmparea1->tmpfaces; face1; face1 = nextface1 )
{
side1 = ( face1->frontarea != tmparea1 );
nextface1 = face1->next[side1];
//
AAS_RemoveFaceFromArea( face1, face1->frontarea );
AAS_RemoveFaceFromArea( face1, face1->backarea );
AAS_FreeTmpFace( face1 );
} //end for
//
tmparea1->mergedarea = newarea;
tmparea1->invalid = true;
tmparea2->mergedarea = newarea;
tmparea2->invalid = true;
//
AAS_CheckArea( newarea );
AAS_FlipAreaFaces( newarea );
// Log_Print("merged area %d & %d to %d with %d faces\n", tmparea1->areanum, tmparea2->areanum, newarea->areanum);
return true;
} //end of the function AAS_TryMergeFaceAreas
//===========================================================================
// try to merge areas
// merged areas are added to the end of the convex area list so merging
// will be tried for those areas as well
//
// Parameter: -
// Returns: -
// Changes Globals: tmpaasworld
//===========================================================================
/*
void AAS_MergeAreas(void)
{
int side, nummerges;
tmp_area_t *tmparea, *othertmparea;
tmp_face_t *face;
nummerges = 0;
Log_Write("AAS_MergeAreas\r\n");
qprintf("%6d areas merged", 1);
//first merge grounded areas only
//NOTE: this is useless because the area settings aren't available yet
for (tmparea = tmpaasworld.areas; tmparea; tmparea = tmparea->l_next)
{
// Log_Print("checking area %d\n", i);
//if the area is invalid
if (tmparea->invalid)
{
// Log_Print(" area invalid\n");
continue;
} //end if
//
// if (!(tmparea->settings->areaflags & AREA_GROUNDED)) continue;
//
for (face = tmparea->tmpfaces; face; face = face->next[side])
{
side = (face->frontarea != tmparea);
//if the face has both a front and back area
if (face->frontarea && face->backarea)
{
//
if (face->frontarea == tmparea) othertmparea = face->backarea;
else othertmparea = face->frontarea;
// if (!(othertmparea->settings->areaflags & AREA_GROUNDED)) continue;
// Log_Print(" checking area %d with %d\n", face->frontarea, face->backarea);
if (AAS_TryMergeFaceAreas(face))
{
qprintf("\r%6d", ++nummerges);
break;
} //end if
} //end if
} //end for
} //end for
//merge all areas
for (tmparea = tmpaasworld.areas; tmparea; tmparea = tmparea->l_next)
{
// Log_Print("checking area %d\n", i);
//if the area is invalid
if (tmparea->invalid)
{
// Log_Print(" area invalid\n");
continue;
} //end if
//
for (face = tmparea->tmpfaces; face; face = face->next[side])
{
side = (face->frontarea != tmparea);
//if the face has both a front and back area
if (face->frontarea && face->backarea)
{
// Log_Print(" checking area %d with %d\n", face->frontarea, face->backarea);
if (AAS_TryMergeFaceAreas(face))
{
qprintf("\r%6d", ++nummerges);
break;
} //end if
} //end if
} //end for
} //end for
Log_Print("\r%6d areas merged\n", nummerges);
//refresh the merged tree
AAS_RefreshMergedTree_r(tmpaasworld.nodes);
} //end of the function AAS_MergeAreas*/
int AAS_GroundArea( tmp_area_t *tmparea ) {
tmp_face_t *face;
int side;
for ( face = tmparea->tmpfaces; face; face = face->next[side] )
{
side = ( face->frontarea != tmparea );
if ( face->faceflags & FACE_GROUND ) {
return true;
}
} //end for
return false;
} //end of the function AAS_GroundArea
void AAS_MergeAreas( void ) {
int side, nummerges, merges, groundfirst;
tmp_area_t *tmparea, *othertmparea;
tmp_face_t *face;
nummerges = 0;
Log_Write( "AAS_MergeAreas\r\n" );
qprintf( "%6d areas merged", 1 );
//
groundfirst = true;
//for (i = 0; i < 4 || merges; i++)
while ( 1 )
{
//if (i < 2) groundfirst = true;
//else groundfirst = false;
//
merges = 0;
//first merge grounded areas only
for ( tmparea = tmpaasworld.areas; tmparea; tmparea = tmparea->l_next )
{
//if the area is invalid
if ( tmparea->invalid ) {
continue;
} //end if
//
if ( groundfirst ) {
if ( !AAS_GroundArea( tmparea ) ) {
continue;
}
} //end if
//
for ( face = tmparea->tmpfaces; face; face = face->next[side] )
{
side = ( face->frontarea != tmparea );
//if the face has both a front and back area
if ( face->frontarea && face->backarea ) {
//
if ( face->frontarea == tmparea ) {
othertmparea = face->backarea;
} else { othertmparea = face->frontarea;}
//
if ( groundfirst ) {
if ( !AAS_GroundArea( othertmparea ) ) {
continue;
}
} //end if
if ( AAS_TryMergeFaceAreas( face ) ) {
qprintf( "\r%6d", ++nummerges );
merges++;
break;
} //end if
} //end if
} //end for
} //end for
if ( !merges ) {
if ( groundfirst ) {
groundfirst = false;
} else { break;}
} //end if
} //end for
qprintf( "\n" );
Log_Write( "%6d areas merged\r\n", nummerges );
//refresh the merged tree
AAS_RefreshMergedTree_r( tmpaasworld.nodes );
} //end of the function AAS_MergeAreas
| 0 | 0.961378 | 1 | 0.961378 | game-dev | MEDIA | 0.648387 | game-dev | 0.96945 | 1 | 0.96945 |
sdthompson1/knights | 19,985 | src/coercri/sdl/gfx/sdl_gfx_driver.cpp | /*
* FILE:
* sdl_gfx_driver.cpp
*
* AUTHOR:
* Stephen Thompson <stephen@solarflare.org.uk>
*
* COPYRIGHT:
* Copyright (C) Stephen Thompson, 2008 - 2024.
*
* This file is part of the "Coercri" software library. Usage of "Coercri"
* is permitted under the terms of the Boost Software License, Version 1.0,
* the text of which is displayed below.
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
#include "sdl_gfx_context.hpp"
#include "sdl_gfx_driver.hpp"
#include "sdl_graphic.hpp"
#include "sdl_window.hpp"
#include "../../core/coercri_error.hpp"
#include "../../gfx/mouse_button.hpp"
#include "../../gfx/rectangle.hpp"
#include "../../gfx/region.hpp"
#include "../../gfx/window_listener_funcs.hpp"
#include "boost/weak_ptr.hpp"
#include <map>
#include <SDL2/SDL.h>
namespace Coercri {
namespace {
// Global key tables
std::map<SDL_Keycode, KeyCode> g_keytable;
void InitKeyTable()
{
if (!g_keytable.empty()) return; // already initialized
g_keytable[SDLK_BACKSPACE] = KC_BACKSPACE;
g_keytable[SDLK_TAB] = KC_TAB;
g_keytable[SDLK_CLEAR] = KC_CLEAR;
g_keytable[SDLK_RETURN] = KC_RETURN;
g_keytable[SDLK_PAUSE] = KC_PAUSE;
g_keytable[SDLK_ESCAPE] = KC_ESCAPE;
g_keytable[SDLK_SPACE] = KC_SPACE;
g_keytable[SDLK_EXCLAIM] = KC_EXCLAIM;
g_keytable[SDLK_QUOTEDBL] = KC_DOUBLE_QUOTE;
g_keytable[SDLK_HASH] = KC_HASH;
g_keytable[SDLK_DOLLAR] = KC_DOLLAR;
g_keytable[SDLK_AMPERSAND] = KC_AMPERSAND;
g_keytable[SDLK_QUOTE] = KC_SINGLE_QUOTE;
g_keytable[SDLK_LEFTPAREN] = KC_LEFT_PAREN;
g_keytable[SDLK_RIGHTPAREN] = KC_RIGHT_PAREN;
g_keytable[SDLK_ASTERISK] = KC_ASTERISK;
g_keytable[SDLK_PLUS] = KC_PLUS;
g_keytable[SDLK_COMMA] = KC_COMMA;
g_keytable[SDLK_MINUS] = KC_MINUS;
g_keytable[SDLK_PERIOD] = KC_PERIOD;
g_keytable[SDLK_SLASH] = KC_SLASH;
g_keytable[SDLK_0] = KC_0;
g_keytable[SDLK_1] = KC_1;
g_keytable[SDLK_2] = KC_2;
g_keytable[SDLK_3] = KC_3;
g_keytable[SDLK_4] = KC_4;
g_keytable[SDLK_5] = KC_5;
g_keytable[SDLK_6] = KC_6;
g_keytable[SDLK_7] = KC_7;
g_keytable[SDLK_8] = KC_8;
g_keytable[SDLK_9] = KC_9;
g_keytable[SDLK_COLON] = KC_COLON;
g_keytable[SDLK_SEMICOLON] = KC_SEMICOLON;
g_keytable[SDLK_LESS] = KC_LESS;
g_keytable[SDLK_EQUALS] = KC_EQUALS;
g_keytable[SDLK_GREATER] = KC_GREATER;
g_keytable[SDLK_QUESTION] = KC_QUESTION;
g_keytable[SDLK_AT] = KC_AT;
g_keytable[SDLK_LEFTBRACKET] = KC_LEFT_BRACKET;
g_keytable[SDLK_BACKSLASH] = KC_BACKSLASH;
g_keytable[SDLK_RIGHTBRACKET] = KC_RIGHT_BRACKET;
g_keytable[SDLK_CARET] = KC_CARET;
g_keytable[SDLK_UNDERSCORE] = KC_UNDERSCORE;
g_keytable[SDLK_BACKQUOTE] = KC_BACKQUOTE;
g_keytable[SDLK_a] = KC_A;
g_keytable[SDLK_b] = KC_B;
g_keytable[SDLK_c] = KC_C;
g_keytable[SDLK_d] = KC_D;
g_keytable[SDLK_e] = KC_E;
g_keytable[SDLK_f] = KC_F;
g_keytable[SDLK_g] = KC_G;
g_keytable[SDLK_h] = KC_H;
g_keytable[SDLK_i] = KC_I;
g_keytable[SDLK_j] = KC_J;
g_keytable[SDLK_k] = KC_K;
g_keytable[SDLK_l] = KC_L;
g_keytable[SDLK_m] = KC_M;
g_keytable[SDLK_n] = KC_N;
g_keytable[SDLK_o] = KC_O;
g_keytable[SDLK_p] = KC_P;
g_keytable[SDLK_q] = KC_Q;
g_keytable[SDLK_r] = KC_R;
g_keytable[SDLK_s] = KC_S;
g_keytable[SDLK_t] = KC_T;
g_keytable[SDLK_u] = KC_U;
g_keytable[SDLK_v] = KC_V;
g_keytable[SDLK_w] = KC_W;
g_keytable[SDLK_x] = KC_X;
g_keytable[SDLK_y] = KC_Y;
g_keytable[SDLK_z] = KC_Z;
g_keytable[SDLK_DELETE] = KC_DELETE;
g_keytable[SDLK_KP_0] = KC_KP_0;
g_keytable[SDLK_KP_1] = KC_KP_1;
g_keytable[SDLK_KP_2] = KC_KP_2;
g_keytable[SDLK_KP_3] = KC_KP_3;
g_keytable[SDLK_KP_4] = KC_KP_4;
g_keytable[SDLK_KP_5] = KC_KP_5;
g_keytable[SDLK_KP_6] = KC_KP_6;
g_keytable[SDLK_KP_7] = KC_KP_7;
g_keytable[SDLK_KP_8] = KC_KP_8;
g_keytable[SDLK_KP_9] = KC_KP_9;
g_keytable[SDLK_KP_PERIOD] = KC_KP_PERIOD;
g_keytable[SDLK_KP_DIVIDE] = KC_KP_DIVIDE;
g_keytable[SDLK_KP_MULTIPLY] = KC_KP_MULTIPLY;
g_keytable[SDLK_KP_MINUS] = KC_KP_MINUS;
g_keytable[SDLK_KP_PLUS] = KC_KP_PLUS;
g_keytable[SDLK_KP_ENTER] = KC_KP_ENTER;
g_keytable[SDLK_KP_EQUALS] = KC_KP_EQUALS;
g_keytable[SDLK_UP] = KC_UP;
g_keytable[SDLK_DOWN] = KC_DOWN;
g_keytable[SDLK_RIGHT] = KC_RIGHT;
g_keytable[SDLK_LEFT] = KC_LEFT;
g_keytable[SDLK_INSERT] = KC_INSERT;
g_keytable[SDLK_HOME] = KC_HOME;
g_keytable[SDLK_END] = KC_END;
g_keytable[SDLK_PAGEUP] = KC_PAGE_UP;
g_keytable[SDLK_PAGEDOWN] = KC_PAGE_DOWN;
g_keytable[SDLK_F1] = KC_F1;
g_keytable[SDLK_F2] = KC_F2;
g_keytable[SDLK_F3] = KC_F3;
g_keytable[SDLK_F4] = KC_F4;
g_keytable[SDLK_F5] = KC_F5;
g_keytable[SDLK_F6] = KC_F6;
g_keytable[SDLK_F7] = KC_F7;
g_keytable[SDLK_F8] = KC_F8;
g_keytable[SDLK_F9] = KC_F9;
g_keytable[SDLK_F10] = KC_F10;
g_keytable[SDLK_F11] = KC_F11;
g_keytable[SDLK_F12] = KC_F12;
g_keytable[SDLK_F13] = KC_F13;
g_keytable[SDLK_F14] = KC_F14;
g_keytable[SDLK_F15] = KC_F15;
g_keytable[SDLK_NUMLOCKCLEAR] = KC_NUM_LOCK;
g_keytable[SDLK_CAPSLOCK] = KC_CAPS_LOCK;
g_keytable[SDLK_SCROLLLOCK] = KC_SCROLL_LOCK;
g_keytable[SDLK_RSHIFT] = KC_RIGHT_SHIFT;
g_keytable[SDLK_LSHIFT] = KC_LEFT_SHIFT;
g_keytable[SDLK_RCTRL] = KC_RIGHT_CONTROL;
g_keytable[SDLK_LCTRL] = KC_LEFT_CONTROL;
g_keytable[SDLK_RALT] = KC_RIGHT_ALT;
g_keytable[SDLK_LALT] = KC_LEFT_ALT;
g_keytable[SDLK_LGUI] = KC_LEFT_WINDOWS;
g_keytable[SDLK_RGUI] = KC_RIGHT_WINDOWS;
g_keytable[SDLK_MODE] = KC_MODE;
g_keytable[SDLK_HELP] = KC_HELP;
g_keytable[SDLK_PRINTSCREEN] = KC_PRINT_SCREEN;
g_keytable[SDLK_SYSREQ] = KC_SYSREQ;
g_keytable[SDLK_MENU] = KC_MENU;
g_keytable[SDLK_APPLICATION] = KC_MENU;
g_keytable[SDLK_POWER] = KC_POWER;
g_keytable[SDLK_CURRENCYUNIT] = KC_EURO;
g_keytable[SDLK_UNDO] = KC_UNDO;
}
int GetModifiers(unsigned int sdl_mod)
{
int result = 0;
if (sdl_mod & KMOD_ALT) result += KM_ALT;
if (sdl_mod & KMOD_CTRL) result += KM_CONTROL;
if (sdl_mod & KMOD_SHIFT) result += KM_SHIFT;
return result;
}
MouseButton MouseButtonFromSDL(int m, bool &error)
{
switch (m) {
case SDL_BUTTON_LEFT: return MB_LEFT;
case SDL_BUTTON_RIGHT: return MB_RIGHT;
case SDL_BUTTON_MIDDLE: return MB_MIDDLE;
default: error = true; return MB_LEFT;
}
}
//
// Handle SDL events.
//
void DoEvent(SDLWindow *focus_window, const SDL_Event &event)
{
switch (event.type) {
case SDL_QUIT:
if (focus_window) {
focus_window->forEachListener(OnClose());
}
break;
case SDL_WINDOWEVENT:
{
SDL_Window *sdl_window = SDL_GetWindowFromID(event.window.windowID);
if (sdl_window) {
SDLWindow *window = static_cast<SDLWindow*>(SDL_GetWindowData(sdl_window, "coercri"));
switch (event.window.event) {
case SDL_WINDOWEVENT_EXPOSED:
{
// Invalidate the entire screen (I don't think SDL
// gives more detailed info about the invalid
// rectangle?)
int w, h;
SDL_GetWindowSize(sdl_window, &w, &h);
Rectangle rectangle(0, 0, w, h);
window->invalidateRectangle(rectangle);
}
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
window->forEachListener(OnGainFocus());
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
window->forEachListener(OnLoseFocus());
break;
case SDL_WINDOWEVENT_SHOWN:
case SDL_WINDOWEVENT_HIDDEN:
case SDL_WINDOWEVENT_MINIMIZED:
case SDL_WINDOWEVENT_MAXIMIZED:
case SDL_WINDOWEVENT_RESTORED:
{
bool old_hidden = window->hidden_flag;
bool old_minimized = window->minimized_flag;
switch (event.window.event) {
case SDL_WINDOWEVENT_HIDDEN: window->hidden_flag = true; break;
case SDL_WINDOWEVENT_SHOWN: window->hidden_flag = false; break;
case SDL_WINDOWEVENT_MINIMIZED: window->minimized_flag = true; break;
default: window->minimized_flag = false; break;
}
bool old_min = old_hidden || old_minimized;
bool new_min = window->hidden_flag || window->minimized_flag;
if (new_min && !old_min) window->forEachListener(OnMinimize());
if (!new_min && old_min) window->forEachListener(OnUnminimize());
break;
}
case SDL_WINDOWEVENT_SIZE_CHANGED:
window->forEachListener(OnResize(event.window.data1, event.window.data2));
break;
}
}
}
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
{
// Find out what kind of key event this is.
const SDL_Keycode keysym = event.key.keysym.sym;
KeyEventType type;
if (event.type == SDL_KEYDOWN) {
if (event.key.repeat) {
type = KEY_AUTO_REPEAT;
} else {
type = KEY_PRESSED;
}
} else {
type = KEY_RELEASED;
}
// Find the corresponding KeyCode.
KeyCode kc = KC_UNKNOWN;
std::map<SDL_Keycode, KeyCode>::const_iterator key_it = g_keytable.find(keysym);
if (key_it != g_keytable.end()) kc = key_it->second;
// Find the modifiers.
const int modifiers = GetModifiers(event.key.keysym.mod);
// Send the key event, if required.
if (kc != KC_UNKNOWN && focus_window) {
focus_window->forEachListener(OnKey(type, kc, KeyModifier(modifiers)));
}
}
break;
case SDL_TEXTINPUT:
{
OnTextInput oti;
oti.str = UTF8String::fromUTF8Safe(event.text.text);
if (focus_window) focus_window->forEachListener(oti);
}
break;
case SDL_MOUSEBUTTONDOWN:
{
bool err = false;
const MouseButton mb = MouseButtonFromSDL(event.button.button, err);
if (!err && focus_window) {
focus_window->forEachListener(OnMouseDown(event.button.x, event.button.y, mb));
}
}
break;
case SDL_MOUSEBUTTONUP:
{
bool err = false;
const MouseButton mb = MouseButtonFromSDL(event.button.button, err);
if (!err && focus_window) {
focus_window->forEachListener(OnMouseUp(event.button.x, event.button.y, mb));
}
}
break;
case SDL_MOUSEMOTION:
if (focus_window) {
focus_window->forEachListener(OnMouseMove(event.motion.x, event.motion.y));
}
break;
case SDL_MOUSEWHEEL:
if (focus_window) {
int dy = event.wheel.y;
if (event.wheel.direction == SDL_MOUSEWHEEL_FLIPPED) {
dy = -dy;
}
const MouseButton mb = dy > 0 ? MB_WHEEL_UP : MB_WHEEL_DOWN;
// note: can't use event.wheel.mouseX/Y here,
// because not all linux distributions will have
// SDL 2.26 or later yet.
int x, y;
SDL_GetMouseState(&x, &y);
focus_window->forEachListener(OnMouseDown(x, y, mb));
focus_window->forEachListener(OnMouseUp(x, y, mb));
}
break;
}
}
SDLWindow * FindCurrentWindow(const std::vector<boost::weak_ptr<SDLWindow> > & windows)
{
// Look for a window with current keyboard or mouse focus; we will send the
// event to this window.
// TODO: We should probably distinguish between keyboard and mouse events and
// look for the appropriate focus type?
SDL_Window * sdl_win = SDL_GetKeyboardFocus();
if (!sdl_win) {
sdl_win = SDL_GetMouseFocus();
}
if (sdl_win) {
return static_cast<SDLWindow*>(SDL_GetWindowData(sdl_win, "coercri"));
}
// If no window currently has focus then just return the first valid window in
// our list of windows, if possible.
for (auto it = windows.begin(); it != windows.end(); ++it) {
boost::shared_ptr<SDLWindow> win = it->lock();
if (win) {
return win.get();
}
}
// As a last resort, return null. (This will drop the event.)
return nullptr;
}
} // namespace
//
// SDLGfxDriver implementation
//
SDLGfxDriver::SDLGfxDriver()
: video_subsystem(SDL_INIT_VIDEO)
{
InitKeyTable();
}
boost::shared_ptr<Window> SDLGfxDriver::createWindow(const WindowParams ¶ms)
{
int width = params.width;
int height = params.height;
if (params.fullscreen) {
SDL_DisplayMode mode;
int err = SDL_GetDesktopDisplayMode(0, &mode);
if (err) {
width = height = 600;
} else {
width = mode.w;
height = mode.h;
}
}
Uint32 flags = 0;
if (params.fullscreen) flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
if (params.resizable) flags |= SDL_WINDOW_RESIZABLE;
if (params.maximized) flags |= SDL_WINDOW_MAXIMIZED;
SDL_Window *sdl_window = SDL_CreateWindow(params.title.c_str(),
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
width,
height,
flags);
if (sdl_window == NULL) {
throw CoercriError("SDL_CreateWindow failed");
}
boost::shared_ptr<SDLWindow> result(new SDLWindow(sdl_window, params.vsync));
windows.push_back(boost::weak_ptr<SDLWindow>(result));
return result;
}
boost::shared_ptr<Graphic> SDLGfxDriver::createGraphic(boost::shared_ptr<const PixelArray> pixels, int hx, int hy)
{
return boost::shared_ptr<Graphic>(new SDLGraphic(pixels, hx, hy));
}
bool SDLGfxDriver::pollEvents()
{
return waitEventMsec(0);
}
bool SDLGfxDriver::waitEventMsec(int ms)
{
// Remove expired weak ptrs from this->windows
for (auto iter = windows.begin(); iter != windows.end(); ) {
if (iter->expired()) {
windows.erase(iter);
} else {
++iter;
}
}
// Check for windows that need resizing
for (auto iter = windows.begin(); iter != windows.end(); ++iter) {
boost::shared_ptr<SDLWindow> window = iter->lock();
if (window && window->need_window_resize) {
// process this first.
int w,h;
window->getSize(w,h);
window->forEachListener(OnResize(w, h));
window->need_window_resize = false;
return true;
}
}
// Check for an SDL event
SDL_Event event;
bool got_event;
if (ms > 0) {
got_event = SDL_WaitEventTimeout(&event, ms);
} else {
got_event = SDL_PollEvent(&event);
}
if (got_event) {
SDLWindow *win = FindCurrentWindow(windows);
DoEvent(win, event);
return true;
} else {
return false;
}
}
}
| 0 | 0.983885 | 1 | 0.983885 | game-dev | MEDIA | 0.826557 | game-dev | 0.960076 | 1 | 0.960076 |
microsoft/automatic-graph-layout | 16,349 | GraphLayout/Samples/LocationLabeling/IncrementalLabeler.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Msagl;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Routing;
namespace LocationLabeling {
internal class IncrementalLabeler {
Dictionary<object, Node> labelById = new Dictionary<object, Node>();
private int giveUpNumber = 10;
public int GiveUpNumber {
get { return giveUpNumber; }
set { giveUpNumber = value; }
}
Random random = new Random(1);
Set<Node> liveLabels = new Set<Node>();
Set<Node> fixedLabels = new Set<Node>();
double locationRadius;
Set<Node> locations = new Set<Node>();
bool routeEdges;
public bool RouteEdges {
get { return routeEdges; }
set { routeEdges = value; }
}
Dictionary<Node, TreeNode> liveNodeToTreeNode = new Dictionary<Node, TreeNode>();
Dictionary<Node, ICurve> nodeToNodeBoundary = new Dictionary<Node, ICurve>();
Dictionary<Node, Point> nodeToCenter = new Dictionary<Node, Point>();
double labelSeparation;
TreeNode liveTree = new TreeNode(null);
TreeNode fixedTree = new TreeNode(null);
private void OptimizePositionsByShiftingRandomly() {
PrepareTreesForOverlapDetection();
int numberOfUnseccsesfulAttemptsInARow = 0;
SaveCurrentConfig();
double e = GetEnergy();
do {
Shift();
var newE = GetEnergy();
System.Diagnostics.Debug.WriteLine("e {0} newE {1} diff {2}", e, newE, e - newE);
if (newE < e) {
e = newE;
numberOfUnseccsesfulAttemptsInARow = 0;
//RemoveIntersectionsOfStems();
//RestoreTree(root);
SaveCurrentConfig();
} else {
numberOfUnseccsesfulAttemptsInARow++;
RestoreConfig();
}
} while (numberOfUnseccsesfulAttemptsInARow < giveUpNumber);
}
private void RestoreConfig() {
foreach (var p in nodeToCenter)
p.Key.Center = p.Value;
RestoreTree(liveTree);
}
private Rectangle RestoreTree(TreeNode t) {
if (t.node != null)
return t.box = Pad(t.node.BoundingBox, labelSeparation / 2);
t.box = RestoreTree(t.l);
t.box.Add(RestoreTree(t.r));
return t.box;
}
private void SaveCurrentConfig() {
foreach (var node in liveLabels) {
nodeToNodeBoundary[node] = node.BoundaryCurve.Clone();
nodeToCenter[node] = node.Center;
}
}
private void Shift() {
foreach (var label in liveLabels)
ShiftLabel(label);
}
private void ShiftLabel(Node label) {
int nOfTries = 200;
var curve = nodeToNodeBoundary[label];
var center = nodeToCenter[label];
var dir = FindLocationByLabel(label).Center - label.Center;
while (nOfTries-- > 0) {
double angle = Math.PI * random.NextDouble() - Math.PI / 2;
double r = random.NextDouble();
//only one time from 4 jump over the location
int rn = random.Next(7);
var del = r * dir.Rotate(angle);
label.Center += del;
if (LabelIsSeparatedFromOtherLabels(label, liveTree) && LabelIsSeparatedFromLocations(label, fixedTree)) {
UpdateTreeOfLabels(liveNodeToTreeNode[label]);
return;
}
}
label.Center = center;
}
private void UpdateTreeOfLabels(TreeNode t) {
t.box = t.node.BoundingBox;
t = t.parent;
while (t != null) {
t.box = t.l.box;
t.box.Add(t.r.box);
t = t.parent;
}
}
private bool LabelIsSeparatedFromLocations(Node label, TreeNode t) {
if (t == null)
return true;
if (label.BoundingBox.Intersects(t.box) == false)
return true;
if (t.node == null)
return LabelIsSeparatedFromLocations(label, t.l) && LabelIsSeparatedFromLocations(label, t.r);
var r = label.Width / 2 + t.node.Width / 2;
var del = label.Center - t.node.Center;
return del * del > r * r;
}
private bool LabelIsSeparatedFromOtherLabels(Node label, TreeNode t) {
if (t == null)
return true;
if (label.BoundingBox.Intersects(t.box) == false)
return true;
if (t.node == null)
return LabelIsSeparatedFromOtherLabels(label, t.l) && LabelIsSeparatedFromOtherLabels(label, t.r);
if (t.node == label)
return true;
var r = label.Width / 2 + t.node.Width / 2 + labelSeparation;
var del = label.Center - t.node.Center;
return del * del > r * r;
}
//private void CheckLabelOverlap() {
// var ls = labels.ToArray();
// for (int i = 0; i < ls.Length ; i++)
// for (int j = i + 1; j < ls.Length; j++)
// if (CirclesAreTooClose(ls[i], ls[j]))
// System.Diagnostics.Debug.WriteLine("mistake");
//}
//private void CheckTree() {
// bool r=CheckTreeOnNode(root);
// System.Diagnostics.Debug.Assert(r);
//}
private bool CheckTreeOnNode(TreeNode t) {
if (t == null)
return true;
if (t.node != null)
if (t.box.Contains(t.node.BoundingBox))
return true;
else
return false;
else
return t.box.Contains(t.l.box) && t.box.Contains(t.r.box) && CheckTreeOnNode(t.l) &&
CheckTreeOnNode(t.r);
}
private void FillList(List<ICurve> listOfTreeCurves, TreeNode treeNode) {
listOfTreeCurves.Add(BoundingBoxCurve(ref treeNode.box));
if (treeNode.node != null)
listOfTreeCurves.Add(treeNode.node.BoundaryCurve);
else {
FillList(listOfTreeCurves, treeNode.l);
FillList(listOfTreeCurves, treeNode.r);
}
}
private ICurve BoundingBoxCurve(ref Rectangle rectangle) {
Curve c = new Curve();
c.AddSegment(new LineSegment(rectangle.LeftTop, rectangle.LeftBottom));
Curve.ContinueWithLineSegment(c, rectangle.RightBottom);
Curve.ContinueWithLineSegment(c, rectangle.RightTop);
Curve.CloseCurve(c);
return c;
}
private double GetEnergy() {
return (from n in liveLabels let p = FindLocationByLabel(n).Center let t = p - n.Center select t * t).Sum();
}
Rectangle Pad(Rectangle box, double padding) {
box.Width += 2 * padding;
if (box.Width < 0)
box.Width = 0;
box.Height += 2 * padding;
if (box.Height < 0)
box.Height = 0;
return box;
}
private void PrepareTreesForOverlapDetection() {
liveTree = new TreeNode(null);
foreach (var lab in this.liveLabels)
AddNodeToTree(liveTree, lab, Pad(lab.BoundingBox, this.labelSeparation / 2));
liveNodeToTreeNode.Clear();
FillNodeToTreeNodeMap(liveTree);
}
private void FillNodeToTreeNodeMap(TreeNode tn) {
if (tn == null)
return;
if (tn.node != null)
liveNodeToTreeNode[tn.node] = tn;
FillNodeToTreeNodeMap(tn.l);
FillNodeToTreeNodeMap(tn.r);
}
private void AddNodeToTree(TreeNode tn, Node node, Rectangle box) {
AddNodeToTreeWithoutOverlaps(tn, ref box, node);
}
private void AddNodeToTreeWithoutOverlaps(TreeNode tn, ref Rectangle box, Node node) {
if (tn.count == 0) {
tn.node = node;
tn.box = box;
} else if (tn.count == 1) {
if (tn.node == null) {
System.Diagnostics.Debug.Assert(tn.l != null);
TreeNode t = tn.r = new TreeNode(tn);
t.node = node;
t.count = 1;
t.box = box;
} else {
tn.l = new TreeNode(tn);
tn.l.box = tn.box;
tn.l.node = tn.node;
tn.l.count = 1;
tn.node = null;
tn.r = new TreeNode(tn);
tn.r.node = node;
tn.r.box = box;
tn.r.count = 1;
}
} else if (tn.l.count * 2 < tn.r.count)
AddNodeToTreeWithoutOverlaps(tn.l, ref box, node);
else if (tn.r.count * 2 < tn.l.count)
AddNodeToTreeWithoutOverlaps(tn.r, ref box, node);
else {
double leftGrouth = CommonArea(ref tn.l.box, ref box) - tn.l.box.Area;
double rigthGrouth = CommonArea(ref tn.r.box, ref box) - tn.r.box.Area;
if (leftGrouth < rigthGrouth)
AddNodeToTreeWithoutOverlaps(tn.l, ref box, node);
else
AddNodeToTreeWithoutOverlaps(tn.r, ref box, node);
}
tn.count++;
tn.box.Add(box);
// ShowRoot();
}
static double CommonArea(ref Rectangle a, ref Rectangle b) {
double l = Math.Min(a.Left, b.Left);
double r = Math.Max(a.Right, b.Right);
double t = Math.Max(a.Top, b.Top);
double bt = Math.Min(a.Bottom, b.Bottom);
return (r - l) * (t - bt);
}
private void RemoveIntersectionsOfStems() {
while (RemoveIntersections(liveLabels.ToArray())) ; //can take a while
}
private bool RemoveIntersections(Node[] labels) {
double energy = GetEnergy();
bool ret = false;
for (int i = 0; i < labels.Length; i++)
for (int j = i + 1; j < labels.Length; j++)
ret = (RemoveIntersection(labels[i], labels[j]) || ret);
return ret && energy > GetEnergy();
}
private bool RemoveIntersection(Node a, Node b) {
Point t;
if (LineSegment.Intersect(a.Center, LocationNodeOfLabel(a).Center, b.Center, LocationNodeOfLabel(b).Center, out t)) {
var tmpa = a.Center;
a.Center = b.Center;
b.Center = tmpa;
return true;
}
return false;
}
Node LocationNodeOfLabel(Node label) {
return label.OutEdges.First().Target;
}
double NodeSeparation = 9;
private void RemoveOverlaps() {
var g = new GeometryGraph();
NodeSeparation = 2 * Math.Max(NodeSeparation, (from label in liveLabels select 2 * Math.Max(label.Width, label.Height)).Max());
foreach (var node in this.liveLabels.Concat(fixedLabels))
g.Nodes.Add(node);
Microsoft.Msagl.Core.Layout.ProximityOverlapRemoval.MinimumSpanningTree.GTreeOverlapRemoval.RemoveOverlaps(g.Nodes.ToArray(), NodeSeparation);
}
IEnumerable<Node> AllLabels() {
return liveLabels.Concat(fixedLabels).Concat(locations);
}
IEnumerable<Edge> Edges() {
return from n in AllLabels() from e in n.OutEdges select e;
}
private void Route() {
//foreach (var edge in graph.Edges) {
// edge.EdgeGeometry.Curve = new LineSegment(edge.Source.Center, edge.Target.Center);
//}
//return;
var edgeRouter = new InteractiveEdgeRouter(from v in AllLabels() select v.BoundaryCurve, this.locationRadius / 3, this.locationRadius/9, Math.PI/6);
edgeRouter.Run();//it will calculate the visibility graph
edgeRouter.GetVisibilityGraph();
foreach (var edge in Edges()) {
SmoothedPolyline sp;
edge.EdgeGeometry.Curve =
edgeRouter.RouteSplineFromPortToPortWhenTheWholeGraphIsReady(new FloatingPort(edge.Source.BoundaryCurve, edge.Source.Center), new FloatingPort(null, edge.Target.Center), true, out sp);
TrimAtSource(edge);
}
}
private void TrimAtSource(Edge edge) {
//pick the intersection furthest from the source
IntersectionInfo x = Curve.GetAllIntersections(edge.Source.BoundaryCurve, edge.Curve, true).Aggregate((a, b) => a.Par1 > b.Par1 ? a : b);
edge.Curve = edge.Curve.Trim(x.Par1, edge.Curve.ParEnd);
}
private Node FindLocationByLabel(Node node) {
foreach (var edge in node.OutEdges)
return edge.Target;
throw new Exception();
}
private bool OverlapsFound() {
foreach (var label in liveLabels) {
if (!LabelIsSeparatedFromOtherLabels(label, liveTree))
return true;
if (!LabelIsSeparatedFromLocations(label, fixedTree))
return true;
}
return false;
}
internal IncrementalLabeler(double radius, bool route, double labelSep) {
this.labelSeparation = labelSep;
this.routeEdges = route;
this.locationRadius = radius;
}
internal void AddNode(Node label) {
liveLabels.Insert(label);
var loc = new Node(
CurveFactory.CreateEllipse(this.locationRadius, this.locationRadius, label.Center), label.UserData + "_");
loc.Center = label.Center;
label.AddOutEdge(new Edge(label, loc));
this.locations.Insert(loc);
AddNodeToTree(fixedTree, loc, Pad(loc.BoundingBox, this.labelSeparation / 2 + this.locationRadius));
}
internal void Layout() {
if (OverlapsFound()) {
RemoveOverlaps();
RemoveIntersectionsOfStems();
OptimizePositionsByShiftingRandomly();
if (routeEdges)
Route();
}
foreach (var label in this.liveLabels) {
AddNodeToTree(this.fixedTree, label, Pad(label.BoundingBox, labelSeparation/2));
fixedLabels.Insert(label);
}
labelById.Clear();
foreach (var node in this.fixedLabels)
labelById[node.UserData] = node;
liveLabels.Clear();
}
/// <summary>
/// move the location and its label uniformly to the new place
/// </summary>
/// <param name="id"></param>
/// <param name="newPosition"></param>
public void ChangeLocation(string id, Point newPosition) {
Node label = labelById[id];
Node location = FindLocationByLabel(label);
Point del = newPosition - location.Center;
location.Center = newPosition;
label.Center += del;
}
/// <summary>
/// update the internal data depending on the positions
/// </summary>
public void UpdateLocations() {
fixedTree = new TreeNode(null);
foreach (var label in fixedLabels) {
var loc=FindLocationByLabel(label);
AddNodeToTree(fixedTree, label, Pad(label.BoundingBox, labelSeparation/2));
AddNodeToTree(fixedTree, loc, Pad(loc.BoundingBox, locationRadius+labelSeparation/2));
}
}
}
}
| 0 | 0.884933 | 1 | 0.884933 | game-dev | MEDIA | 0.41568 | game-dev | 0.811491 | 1 | 0.811491 |
goblinhack/zorbash | 4,713 | src/my_dungeon_grid.hpp | //
// Copyright goblinhack@gmail.com
//
#pragma once
//
// Implements layered cycles that can be used to then create a dungeon
//
#include "my_biomes.hpp"
#include "my_fwd.hpp"
#include "my_random.hpp"
class DungeonNode
{
public:
biome_t biome {BIOME_UNKNOWN};
//
// Nodes have a depth number, optional key, start and exit and corridors
// to adjoining depths. Depth increases as we get closer to the exit.
//
int depth {0};
//
// Used only in the game start when creating a grid of levels
//
int walk_order_level_no {};
bool generating {};
bool generated {};
//
// pass 1 is the main dungeon
// pass 2 are secret levels
//
int pass {0};
int x, y;
//
// Not necessarily an actual key or lock, but something allowing access
// to the other node. Only one key per node depth.
//
bool is_walked {false};
bool is_secret {false};
bool is_key {false};
bool is_lock {false};
bool is_ascend_dungeon {false};
bool is_descend_dungeon {false};
bool on_critical_path {false};
bool has_door {false};
bool has_door_up {false};
bool has_door_down {false};
bool has_door_left {false};
bool has_door_right {false};
bool has_secret_exit_up {false};
bool has_secret_exit_down {false};
bool has_secret_exit_left {false};
bool has_secret_exit_right {false};
bool dir_up {false};
bool dir_down {false};
bool dir_left {false};
bool dir_right {false};
//
// Update init_nodes on changes
//
bool has_path(void) { return (dir_down || dir_up || dir_left || dir_right); }
void set_has_door_up(bool v)
{
has_door = v;
has_door_up = v;
has_secret_exit_up = false;
}
void set_has_door_down(bool v)
{
has_door = v;
has_door_down = v;
has_secret_exit_down = false;
}
void set_has_door_right(bool v)
{
has_door = v;
has_door_right = v;
has_secret_exit_right = false;
}
void set_has_door_left(bool v)
{
has_door = v;
has_door_left = v;
has_secret_exit_left = false;
}
void set_has_secret_exit_up(bool v)
{
has_secret_exit_up = v;
has_door = false;
has_door_up = false;
}
void set_has_secret_exit_down(bool v)
{
has_secret_exit_down = v;
has_door = false;
has_door_down = false;
}
void set_has_secret_exit_right(bool v)
{
has_secret_exit_right = v;
has_door = false;
has_door_right = false;
}
void set_has_secret_exit_left(bool v)
{
has_secret_exit_left = v;
has_door = false;
has_door_left = false;
}
};
class Nodes
{
public:
std::vector< DungeonNode > nodes;
biome_t biome {BIOME_UNKNOWN};
//
// We build either a single or all dungeons
//
int grid_width {5};
int grid_height {5};
bool is_dungeon {};
int max_depth {0};
int max_vdepth {0};
//
// Water, rocks etc...
//
int depth_obstacle {-1};
Nodes(biome_t biome, int grid_width, int grid_height, bool is_dungeon)
: grid_width(grid_width), grid_height(grid_height), is_dungeon(is_dungeon)
{
pcg_random_allowed++;
finish_constructor(biome);
pcg_random_allowed--;
}
Nodes(biome_t biome) { finish_constructor(biome); }
void finish_constructor(biome_t);
void debug(std::string msg);
void dump(void);
void log(void);
int offset(const int x, const int y);
bool is_oob(const int x, const int y);
DungeonNode *node_addr(const int x, const int y);
void putn(const int x, const int y, const DungeonNode n);
DungeonNode *getn(const int x, const int y);
point random_dir(void);
void random_dir(int *dx, int *dy);
void init_nodes(void);
int snake_walk(int depth, int max_placed, int pass);
void join_nodes_of_same_depth(int depth, int pass);
void join_depth_to_next_depth(int depth, int pass);
void join_depth_secret(int depth, int pass);
bool place_lock(int depth, int pass);
void hide_other_locks(int depth, int pass);
bool place_key(int depth, int pass);
bool place_entrance(void);
bool place_exit(void);
void set_max_depth(void);
bool node_is_free(DungeonNode *n);
bool node_is_a_room(DungeonNode *n);
void remove_stubs();
bool create_path_to_exit(int pass);
void create_path_lock_to_key(int depth);
void make_paths_off_critical_path_reachable(void);
void dmap_print_walls(Dmapp d);
void remove_redundant_directions(void);
};
extern class Nodes *grid_test(void);
| 0 | 0.854047 | 1 | 0.854047 | game-dev | MEDIA | 0.81013 | game-dev | 0.752654 | 1 | 0.752654 |
ImLegiitXD/Dream-Advanced | 1,160 | dll/back/1.20/net/minecraft/util/datafix/schemas/V1928.java | package net.minecraft.util.datafix.schemas;
import com.mojang.datafixers.DSL;
import com.mojang.datafixers.schemas.Schema;
import com.mojang.datafixers.types.templates.TypeTemplate;
import java.util.Map;
import java.util.function.Supplier;
import net.minecraft.util.datafix.fixes.References;
public class V1928 extends NamespacedSchema {
public V1928(int p_17798_, Schema p_17799_) {
super(p_17798_, p_17799_);
}
protected static TypeTemplate equipment(Schema p_17801_) {
return DSL.optionalFields("ArmorItems", DSL.list(References.ITEM_STACK.in(p_17801_)), "HandItems", DSL.list(References.ITEM_STACK.in(p_17801_)));
}
protected static void registerMob(Schema p_17803_, Map<String, Supplier<TypeTemplate>> p_17804_, String p_17805_) {
p_17803_.register(p_17804_, p_17805_, () -> {
return equipment(p_17803_);
});
}
public Map<String, Supplier<TypeTemplate>> registerEntities(Schema p_17809_) {
Map<String, Supplier<TypeTemplate>> map = super.registerEntities(p_17809_);
map.remove("minecraft:illager_beast");
registerMob(p_17809_, map, "minecraft:ravager");
return map;
}
} | 0 | 0.666643 | 1 | 0.666643 | game-dev | MEDIA | 0.899442 | game-dev | 0.530531 | 1 | 0.530531 |
ImLegiitXD/Dream-Advanced | 2,936 | dll/back/1.20/net/minecraft/world/level/block/EndGatewayBlock.java | package net.minecraft.world.level.block;
import javax.annotation.Nullable;
import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.util.RandomSource;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityTicker;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.entity.TheEndGatewayBlockEntity;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Fluid;
public class EndGatewayBlock extends BaseEntityBlock {
protected EndGatewayBlock(BlockBehaviour.Properties p_52999_) {
super(p_52999_);
}
public BlockEntity newBlockEntity(BlockPos p_153193_, BlockState p_153194_) {
return new TheEndGatewayBlockEntity(p_153193_, p_153194_);
}
@Nullable
public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level p_153189_, BlockState p_153190_, BlockEntityType<T> p_153191_) {
return createTickerHelper(p_153191_, BlockEntityType.END_GATEWAY, p_153189_.isClientSide ? TheEndGatewayBlockEntity::beamAnimationTick : TheEndGatewayBlockEntity::teleportTick);
}
public void animateTick(BlockState p_221097_, Level p_221098_, BlockPos p_221099_, RandomSource p_221100_) {
BlockEntity blockentity = p_221098_.getBlockEntity(p_221099_);
if (blockentity instanceof TheEndGatewayBlockEntity) {
int i = ((TheEndGatewayBlockEntity)blockentity).getParticleAmount();
for(int j = 0; j < i; ++j) {
double d0 = (double)p_221099_.getX() + p_221100_.nextDouble();
double d1 = (double)p_221099_.getY() + p_221100_.nextDouble();
double d2 = (double)p_221099_.getZ() + p_221100_.nextDouble();
double d3 = (p_221100_.nextDouble() - 0.5D) * 0.5D;
double d4 = (p_221100_.nextDouble() - 0.5D) * 0.5D;
double d5 = (p_221100_.nextDouble() - 0.5D) * 0.5D;
int k = p_221100_.nextInt(2) * 2 - 1;
if (p_221100_.nextBoolean()) {
d2 = (double)p_221099_.getZ() + 0.5D + 0.25D * (double)k;
d5 = (double)(p_221100_.nextFloat() * 2.0F * (float)k);
} else {
d0 = (double)p_221099_.getX() + 0.5D + 0.25D * (double)k;
d3 = (double)(p_221100_.nextFloat() * 2.0F * (float)k);
}
p_221098_.addParticle(ParticleTypes.PORTAL, d0, d1, d2, d3, d4, d5);
}
}
}
public ItemStack getCloneItemStack(BlockGetter p_53003_, BlockPos p_53004_, BlockState p_53005_) {
return ItemStack.EMPTY;
}
public boolean canBeReplaced(BlockState p_53012_, Fluid p_53013_) {
return false;
}
} | 0 | 0.783518 | 1 | 0.783518 | game-dev | MEDIA | 0.986863 | game-dev | 0.931843 | 1 | 0.931843 |
Goob-Station/Goob-Station | 9,567 | Content.Server/Anomaly/Effects/InnerBodyAnomalySystem.cs | // SPDX-FileCopyrightText: 2024 Ed <96445749+TheShuEd@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Patrik Caes-Sayrs <heartofgoldfish@gmail.com>
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 SX_7 <sn1.test.preria.2002@gmail.com>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
using Content.Server.Administration.Logs;
using Content.Server.Body.Systems;
using Content.Server.Chat.Managers;
using Content.Server.Jittering;
using Content.Server.Mind;
using Content.Server.Stunnable;
using Content.Shared.Anomaly;
using Content.Shared.Anomaly.Components;
using Content.Shared.Anomaly.Effects;
using Content.Shared.Body.Components;
using Content.Shared.Chat;
using Content.Shared.Database;
using Content.Shared.Mobs;
using Content.Shared.Popups;
using Content.Shared.Whitelist;
using Robust.Shared.Audio.Systems;
using Robust.Shared.Physics.Events;
using Robust.Shared.Player;
using Robust.Shared.Prototypes;
namespace Content.Server.Anomaly.Effects;
public sealed class InnerBodyAnomalySystem : SharedInnerBodyAnomalySystem
{
[Dependency] private readonly IAdminLogManager _adminLog = default!;
[Dependency] private readonly AnomalySystem _anomaly = default!;
[Dependency] private readonly SharedAudioSystem _audio = default!;
[Dependency] private readonly BodySystem _body = default!;
[Dependency] private readonly IChatManager _chat = default!;
[Dependency] private readonly ISharedPlayerManager _player = default!;
[Dependency] private readonly EntityWhitelistSystem _whitelist = default!;
[Dependency] private readonly JitteringSystem _jitter = default!;
[Dependency] private readonly MindSystem _mind = default!;
[Dependency] private readonly SharedPopupSystem _popup = default!;
[Dependency] private readonly IPrototypeManager _proto = default!;
[Dependency] private readonly StunSystem _stun = default!;
private readonly Color _messageColor = Color.FromSrgb(new Color(201, 22, 94));
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<InnerBodyAnomalyInjectorComponent, StartCollideEvent>(OnStartCollideInjector);
SubscribeLocalEvent<InnerBodyAnomalyComponent, MapInitEvent>(OnMapInit);
SubscribeLocalEvent<InnerBodyAnomalyComponent, ComponentShutdown>(OnCompShutdown);
SubscribeLocalEvent<InnerBodyAnomalyComponent, AnomalyPulseEvent>(OnAnomalyPulse);
SubscribeLocalEvent<InnerBodyAnomalyComponent, AnomalyShutdownEvent>(OnAnomalyShutdown);
SubscribeLocalEvent<InnerBodyAnomalyComponent, AnomalySupercriticalEvent>(OnAnomalySupercritical);
SubscribeLocalEvent<InnerBodyAnomalyComponent, AnomalySeverityChangedEvent>(OnSeverityChanged);
SubscribeLocalEvent<InnerBodyAnomalyComponent, MobStateChangedEvent>(OnMobStateChanged);
SubscribeLocalEvent<AnomalyComponent, ActionAnomalyPulseEvent>(OnActionPulse);
}
private void OnActionPulse(Entity<AnomalyComponent> ent, ref ActionAnomalyPulseEvent args)
{
if (args.Handled)
return;
_anomaly.DoAnomalyPulse(ent, ent.Comp);
args.Handled = true;
}
private void OnStartCollideInjector(Entity<InnerBodyAnomalyInjectorComponent> ent, ref StartCollideEvent args)
{
if (ent.Comp.Whitelist is not null && !_whitelist.IsValid(ent.Comp.Whitelist, args.OtherEntity))
return;
if (TryComp<InnerBodyAnomalyComponent>(args.OtherEntity, out var innerAnom) && innerAnom.Injected)
return;
if (!_mind.TryGetMind(args.OtherEntity, out _, out var mindComponent))
return;
EntityManager.AddComponents(args.OtherEntity, ent.Comp.InjectionComponents);
QueueDel(ent);
}
private void OnMapInit(Entity<InnerBodyAnomalyComponent> ent, ref MapInitEvent args)
{
AddAnomalyToBody(ent);
}
private void AddAnomalyToBody(Entity<InnerBodyAnomalyComponent> ent)
{
if (!_proto.TryIndex(ent.Comp.InjectionProto, out var injectedAnom))
return;
if (ent.Comp.Injected)
return;
ent.Comp.Injected = true;
EntityManager.AddComponents(ent, injectedAnom.Components);
_stun.TryParalyze(ent, TimeSpan.FromSeconds(ent.Comp.StunDuration), true);
_jitter.DoJitter(ent, TimeSpan.FromSeconds(ent.Comp.StunDuration), true);
if (ent.Comp.StartSound is not null)
_audio.PlayPvs(ent.Comp.StartSound, ent);
if (ent.Comp.StartMessage is not null &&
_mind.TryGetMind(ent, out _, out var mindComponent) &&
_player.TryGetSessionById(mindComponent.UserId, out var session))
{
var message = Loc.GetString(ent.Comp.StartMessage);
var wrappedMessage = Loc.GetString("chat-manager-server-wrap-message", ("message", message));
_chat.ChatMessageToOne(ChatChannel.Server,
message,
wrappedMessage,
default,
false,
session.Channel,
_messageColor);
_popup.PopupEntity(message, ent, ent, PopupType.MediumCaution);
_adminLog.Add(LogType.Anomaly,LogImpact.Medium,$"{ToPrettyString(ent)} became anomaly host.");
}
Dirty(ent);
}
private void OnAnomalyPulse(Entity<InnerBodyAnomalyComponent> ent, ref AnomalyPulseEvent args)
{
_stun.TryParalyze(ent, TimeSpan.FromSeconds(ent.Comp.StunDuration / 2 * args.Severity), true);
_jitter.DoJitter(ent, TimeSpan.FromSeconds(ent.Comp.StunDuration / 2 * args.Severity), true);
}
private void OnAnomalySupercritical(Entity<InnerBodyAnomalyComponent> ent, ref AnomalySupercriticalEvent args)
{
if (!TryComp<BodyComponent>(ent, out var body))
return;
_body.GibBody(ent, true, body, splatModifier: 5f);
}
private void OnSeverityChanged(Entity<InnerBodyAnomalyComponent> ent, ref AnomalySeverityChangedEvent args)
{
if (!_mind.TryGetMind(ent, out _, out var mindComponent) ||
!_player.TryGetSessionById(mindComponent.UserId, out var session))
return;
var message = string.Empty;
if (args.Severity >= 0.5 && ent.Comp.LastSeverityInformed < 0.5)
{
ent.Comp.LastSeverityInformed = 0.5f;
message = Loc.GetString("inner-anomaly-severity-info-50");
}
if (args.Severity >= 0.75 && ent.Comp.LastSeverityInformed < 0.75)
{
ent.Comp.LastSeverityInformed = 0.75f;
message = Loc.GetString("inner-anomaly-severity-info-75");
}
if (args.Severity >= 0.9 && ent.Comp.LastSeverityInformed < 0.9)
{
ent.Comp.LastSeverityInformed = 0.9f;
message = Loc.GetString("inner-anomaly-severity-info-90");
}
if (args.Severity >= 1 && ent.Comp.LastSeverityInformed < 1)
{
ent.Comp.LastSeverityInformed = 1f;
message = Loc.GetString("inner-anomaly-severity-info-100");
}
if (message == string.Empty)
return;
var wrappedMessage = Loc.GetString("chat-manager-server-wrap-message", ("message", message));
_chat.ChatMessageToOne(ChatChannel.Server,
message,
wrappedMessage,
default,
false,
session.Channel,
_messageColor);
_popup.PopupEntity(message, ent, ent, PopupType.MediumCaution);
}
private void OnMobStateChanged(Entity<InnerBodyAnomalyComponent> ent, ref MobStateChangedEvent args)
{
if (args.NewMobState != MobState.Dead)
return;
var ev = new BeforeRemoveAnomalyOnDeathEvent();
RaiseLocalEvent(args.Target, ref ev);
if (ev.Cancelled)
return;
_anomaly.ChangeAnomalyHealth(ent, -2); //Shutdown it
}
private void OnAnomalyShutdown(Entity<InnerBodyAnomalyComponent> ent, ref AnomalyShutdownEvent args)
{
RemoveAnomalyFromBody(ent);
RemCompDeferred<InnerBodyAnomalyComponent>(ent);
}
private void OnCompShutdown(Entity<InnerBodyAnomalyComponent> ent, ref ComponentShutdown args)
{
RemoveAnomalyFromBody(ent);
}
private void RemoveAnomalyFromBody(Entity<InnerBodyAnomalyComponent> ent)
{
if (!ent.Comp.Injected)
return;
if (_proto.TryIndex(ent.Comp.InjectionProto, out var injectedAnom))
EntityManager.RemoveComponents(ent, injectedAnom.Components);
_stun.TryParalyze(ent, TimeSpan.FromSeconds(ent.Comp.StunDuration), true);
if (ent.Comp.EndMessage is not null &&
_mind.TryGetMind(ent, out _, out var mindComponent) &&
_player.TryGetSessionById(mindComponent.UserId, out var session))
{
var message = Loc.GetString(ent.Comp.EndMessage);
var wrappedMessage = Loc.GetString("chat-manager-server-wrap-message", ("message", message));
_chat.ChatMessageToOne(ChatChannel.Server,
message,
wrappedMessage,
default,
false,
session.Channel,
_messageColor);
_popup.PopupEntity(message, ent, ent, PopupType.MediumCaution);
_adminLog.Add(LogType.Anomaly, LogImpact.Medium,$"{ToPrettyString(ent)} is no longer a host for the anomaly.");
}
ent.Comp.Injected = false;
RemCompDeferred<AnomalyComponent>(ent);
}
} | 0 | 0.820687 | 1 | 0.820687 | game-dev | MEDIA | 0.722786 | game-dev | 0.953284 | 1 | 0.953284 |
forest0xia/dota2bot-OpenHyperAI | 20,959 | bots/BotLib/hero_jakiro.lua | ----------------------------------------------------------------------------------------------------
--- The Creation Come From: BOT EXPERIMENT Credit:FURIOUSPUPPY
--- BOT EXPERIMENT Author: Arizona Fauzie 2018.11.21
--- Link:http://steamcommunity.com/sharedfiles/filedetails/?id=837040016
--- Refactor: 决明子 Email: dota2jmz@163.com 微博@Dota2_决明子
--- Link:http://steamcommunity.com/sharedfiles/filedetails/?id=1573671599
--- Link:http://steamcommunity.com/sharedfiles/filedetails/?id=1627071163
----------------------------------------------------------------------------------------------------
local X = {}
local bDebugMode = ( 1 == 10 )
local bot = GetBot()
local J = require( GetScriptDirectory()..'/FunLib/jmz_func' )
local Minion = dofile( GetScriptDirectory()..'/FunLib/aba_minion' )
local sTalentList = J.Skill.GetTalentList( bot )
local sAbilityList = J.Skill.GetAbilityList( bot )
local sRole = J.Item.GetRoleItemsBuyList( bot )
local tTalentTreeList = {
['t25'] = {10, 0},
['t20'] = {10, 0},
['t15'] = {10, 0},
['t10'] = {0, 10},
}
local tAllAbilityBuildList = {
{1,3,1,2,1,6,1,2,2,2,6,3,3,3,6},--pos4,5
}
local nAbilityBuildList = J.Skill.GetRandomBuild( tAllAbilityBuildList )
local nTalentBuildList = J.Skill.GetTalentBuild( tTalentTreeList )
local sRoleItemsBuyList = {}
sRoleItemsBuyList['pos_3'] = {
"item_mage_outfit",
"item_ancient_janggo",
"item_glimmer_cape",
"item_boots_of_bearing",
"item_rod_of_atos",
"item_mjollnir",--
"item_aghanims_shard",
"item_veil_of_discord",
"item_cyclone",
"item_shivas_guard",
"item_sheepstick",
"item_wind_waker",
"item_moon_shard",
"item_ultimate_scepter_2",
}
sRoleItemsBuyList['pos_4'] = {
"item_blood_grenade",
"item_priest_outfit",
"item_mekansm",
"item_glimmer_cape",
"item_aghanims_shard",
"item_guardian_greaves",
"item_spirit_vessel",
-- "item_wraith_pact",
"item_ultimate_scepter",
"item_shivas_guard",
"item_moon_shard",
"item_ultimate_scepter_2",
"item_sheepstick",
}
sRoleItemsBuyList['pos_5'] = {
"item_blood_grenade",
'item_mage_outfit',
'item_ancient_janggo',
'item_glimmer_cape',
'item_boots_of_bearing',
'item_pipe',
"item_shivas_guard",
'item_cyclone',
'item_sheepstick',
"item_wind_waker",
"item_moon_shard",
"item_ultimate_scepter_2",
}
sRoleItemsBuyList['pos_2'] = {
"item_crystal_maiden_outfit",
-- "item_falcon_blade",
"item_witch_blade",
"item_orchid",
"item_force_staff",
"item_ultimate_scepter",
"item_hurricane_pike",--
"item_yasha_and_kaya",--
-- "item_black_king_bar",--
"item_bloodthorn",--
-- "item_mjollnir",--
"item_sphere",--
"item_aghanims_shard",
"item_skadi",--
"item_moon_shard",
"item_ultimate_scepter_2",
"item_travel_boots_2",--
}
sRoleItemsBuyList['pos_1'] = sRoleItemsBuyList['pos_2']
X['sBuyList'] = sRoleItemsBuyList[sRole]
X['sSellList'] = {
"item_black_king_bar",
"item_quelling_blade",
"item_ultimate_scepter",
"item_magic_wand",
"item_cyclone",
"item_magic_wand",
"item_shivas_guard",
'item_magic_wand',
"item_skadi",--
"item_witch_blade",
}
if J.Role.IsPvNMode() or J.Role.IsAllShadow() then X['sBuyList'], X['sSellList'] = { 'PvN_mage' }, {} end
nAbilityBuildList, nTalentBuildList, X['sBuyList'], X['sSellList'] = J.SetUserHeroInit( nAbilityBuildList, nTalentBuildList, X['sBuyList'], X['sSellList'] )
X['sSkillList'] = J.Skill.GetSkillList( sAbilityList, nAbilityBuildList, sTalentList, nTalentBuildList )
X['bDeafaultAbility'] = false
X['bDeafaultItem'] = true
function X.MinionThink(hMinionUnit)
if Minion.IsValidUnit( hMinionUnit )
then
Minion.IllusionThink( hMinionUnit )
end
end
--[[
npc_dota_hero_jakiro
"Ability1" "jakiro_dual_breath"
"Ability2" "jakiro_ice_path"
"Ability3" "jakiro_liquid_fire"
"Ability4" "generic_hidden"
"Ability5" "generic_hidden"
"Ability6" "jakiro_macropyre"
"Ability10" "special_bonus_attack_range_300"
"Ability11" "special_bonus_spell_amplify_8"
"Ability12" "special_bonus_exp_boost_40"
"Ability13" "special_bonus_unique_jakiro_2"
"Ability14" "special_bonus_unique_jakiro_4"
"Ability15" "special_bonus_gold_income_25"
"Ability16" "special_bonus_unique_jakiro_3"
"Ability17" "special_bonus_unique_jakiro"
modifier_jakiro_dual_breath
modifier_jakiro_dual_breath_slow
modifier_jakiro_dual_breath_burn
modifier_jakiro_ice_path_stun
modifier_jakiro_ice_path
modifier_jakiro_liquidfire
modifier_jakiro_liquid_fire_burn
modifier_jakiro_macropyre
modifier_jakiro_macropyre_burn
--]]
local abilityQ = bot:GetAbilityByName('jakiro_dual_breath')
local abilityW = bot:GetAbilityByName('jakiro_ice_path')
local abilityE = bot:GetAbilityByName('jakiro_liquid_fire')
local abilityAS = bot:GetAbilityByName('jakiro_liquid_frost')
local abilityR = bot:GetAbilityByName('jakiro_macropyre')
local castQDesire, castQTarget
local castWDesire, castWLocation
local castEDesire, castETarget
local castASDesire, castASTarget
local castRDesire, castRLocation
function X.SkillsComplement()
if J.CanNotUseAbility( bot ) then return end
castWDesire, castWLocation = X.ConsiderW()
if ( castWDesire > 0 )
then
J.SetQueuePtToINT( bot, true )
bot:ActionQueue_UseAbilityOnLocation( abilityW, castWLocation )
return
end
castRDesire, castRLocation = X.ConsiderR()
if ( castRDesire > 0 )
then
J.SetQueuePtToINT( bot, true )
bot:ActionQueue_UseAbilityOnLocation( abilityR, castRLocation )
return
end
castQDesire, castQTarget = X.ConsiderQ()
if ( castQDesire > 0 )
then
J.SetQueuePtToINT( bot, true )
bot:ActionQueue_UseAbilityOnLocation( abilityQ, castQTarget )
return
end
castEDesire, castETarget = X.ConsiderE()
if ( castEDesire > 0 )
then
J.SetQueuePtToINT( bot, true )
bot:ActionQueue_UseAbilityOnEntity( abilityE, castETarget )
return
end
castASDesire, castASTarget = X.ConsiderAS()
if ( castASDesire > 0 )
then
J.SetQueuePtToINT( bot, true )
bot:ActionQueue_UseAbilityOnEntity( abilityAS, castASTarget )
return
end
end
function X.ConsiderQ()
if not J.CanCastAbility(abilityQ) then return 0 end
local nCastRange = J.GetProperCastRange(false, bot, abilityQ:GetCastRange())
local nCastPoint = abilityQ:GetCastPoint()
local manaCost = abilityQ:GetManaCost()
local nRadius = abilityQ:GetSpecialValueInt( "start_radius" )
local nDuration = abilityQ:GetDuration()
local nSpeed = abilityQ:GetSpecialValueInt( 'speed' )
local nDamage = abilityQ:GetSpecialValueInt( 'burn_damage' )
local botTarget = J.GetProperTarget( bot )
local nEnemyHeroes = bot:GetNearbyHeroes( 1600, true, BOT_MODE_NONE )
for _, enemy in pairs(nEnemyHeroes)
do
if J.IsValidHero(enemy)
and J.IsInRange(bot, enemy, nCastRange)
and J.CanCastOnNonMagicImmune(enemy)
and J.WillKillTarget(enemy, nDamage, DAMAGE_TYPE_MAGICAL, nDuration)
and not enemy:HasModifier('modifier_abaddon_borrowed_time')
and not enemy:HasModifier('modifier_dazzle_shallow_grave')
and not enemy:HasModifier('modifier_necrolyte_reapers_scythe')
and not enemy:HasModifier('modifier_oracle_false_promise_timer')
and not enemy:HasModifier('modifier_templar_assassin_refraction_absorb')
then
return BOT_ACTION_DESIRE_HIGH, J.GetCorrectLoc(enemy, nCastPoint)
end
end
if J.IsInTeamFight( bot, 1300 )
then
local nLocationAoE = bot:FindAoELocation( true, true, bot:GetLocation(), nCastRange, nRadius, 0, 0 )
local nInRangeEnemy = J.GetEnemiesNearLoc(nLocationAoE.targetloc, nRadius)
if #nInRangeEnemy >= 2
then
return BOT_ACTION_DESIRE_LOW, nLocationAoE.targetloc
end
end
if J.IsGoingOnSomeone( bot ) and #nEnemyHeroes == 1
then
if J.IsValidHero( botTarget )
and J.CanCastOnNonMagicImmune( botTarget )
and J.IsInRange( botTarget, bot, nCastRange )
and not botTarget:HasModifier('modifier_abaddon_borrowed_time')
and not botTarget:HasModifier('modifier_dazzle_shallow_grave')
and not botTarget:HasModifier('modifier_necrolyte_reapers_scythe')
and not botTarget:HasModifier('modifier_oracle_false_promise_timer')
then
return BOT_ACTION_DESIRE_HIGH, J.GetCorrectLoc(botTarget, nCastPoint)
end
end
if J.IsRetreating( bot )
and not J.IsRealInvisible(bot)
and bot:WasRecentlyDamagedByAnyHero(3.0)
then
if J.IsValidHero(nEnemyHeroes[1])
and J.CanCastOnNonMagicImmune(nEnemyHeroes[1])
and J.IsInRange(bot, nEnemyHeroes[1], nCastRange)
and J.IsChasingTarget(nEnemyHeroes[1], bot)
and not nEnemyHeroes[1]:HasModifier('modifier_necrolyte_reapers_scythe')
then
return BOT_ACTION_DESIRE_HIGH, nEnemyHeroes[1]:GetLocation()
end
local nLocationAoE = bot:FindAoELocation( true, true, bot:GetLocation(), nCastRange - 100, nRadius * 1.6, nCastPoint, 0 )
if nLocationAoE.count >= 2 and #nEnemyHeroes >= 2
then
return BOT_ACTION_DESIRE_HIGH, nLocationAoE.targetloc
end
end
local tEnemyLaneCreeps = bot:GetNearbyLaneCreeps(nCastRange, true)
if J.IsPushing(bot)
and J.GetManaAfter(manaCost) >= 0.5
and not J.IsThereCoreNearby(1400)
then
if #tEnemyLaneCreeps > 3
and J.CanBeAttacked(tEnemyLaneCreeps[1])
then
return BOT_ACTION_DESIRE_HIGH, J.GetCenterOfUnits(tEnemyLaneCreeps)
end
end
if J.IsDefending(bot)
and J.GetManaAfter(manaCost) >= 0.35
then
if #tEnemyLaneCreeps > 3
and J.CanBeAttacked(tEnemyLaneCreeps[1])
then
return BOT_ACTION_DESIRE_HIGH, J.GetCenterOfUnits(tEnemyLaneCreeps)
end
end
if J.IsFarming(bot)
and J.GetManaAfter(manaCost) >= 0.4
then
local tCreeps = bot:GetNearbyCreeps(nCastRange, true)
if #tCreeps > 2
and J.CanBeAttacked(tCreeps[1])
then
return BOT_ACTION_DESIRE_HIGH, J.GetCenterOfUnits(tCreeps)
end
end
if J.IsDoingRoshan(bot)
then
if J.IsRoshan(botTarget)
and J.CanCastOnNonMagicImmune(botTarget)
and J.IsInRange(bot, botTarget, nCastRange)
and J.IsAttacking(bot)
then
return BOT_ACTION_DESIRE_HIGH, botTarget:GetLocation()
end
end
if J.IsDoingTormentor(bot)
then
if J.IsTormentor(botTarget)
and J.IsInRange(bot, botTarget, nCastRange)
and J.IsAttacking(bot)
then
return BOT_ACTION_DESIRE_HIGH, botTarget:GetLocation()
end
end
return BOT_ACTION_DESIRE_NONE, 0
end
function X.ConsiderW()
if not J.CanCastAbility(abilityW) then return 0 end
local nCastRange = J.GetProperCastRange(false, bot, abilityW:GetCastRange())
local nCastPoint = abilityW:GetCastPoint()
local manaCost = abilityW:GetManaCost()
local nRadius = abilityW:GetSpecialValueInt( "path_radius" )
local nDelay = abilityW:GetSpecialValueFloat( 'path_delay' )
local nDamage = abilityW:GetSpecialValueInt( 'damage' )
local botTarget = J.GetProperTarget( bot )
local nEnemyHeroes = bot:GetNearbyHeroes( nCastRange + 200, true, BOT_MODE_NONE )
local hNearEnemyHeroList = bot:GetNearbyHeroes( nCastRange, true, BOT_MODE_NONE )
for _, enemy in pairs( nEnemyHeroes )
do
if J.IsValidHero(enemy)
and J.IsInRange(bot, enemy, nCastRange + 200)
and J.CanCastOnNonMagicImmune(enemy)
then
if enemy:IsChanneling() then
return BOT_ACTION_DESIRE_HIGH, enemy:GetLocation()
end
end
end
if J.IsRetreating( bot )
and not J.IsRealInvisible(bot)
then
if #nEnemyHeroes > 0 and bot:WasRecentlyDamagedByAnyHero( 2.0 ) then
local locationAoE = bot:FindAoELocation( true, true, bot:GetLocation(), nCastRange - 100, nRadius * 1.6, nCastPoint, 0 )
if locationAoE.count >= 1 and #hNearEnemyHeroList >= 1
then
return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc
end
end
end
if ( J.IsPushing( bot ) or J.IsDefending( bot ) ) and J.IsAllowedToSpam( bot, manaCost )
then
local lanecreeps = bot:GetNearbyLaneCreeps( nCastRange, true )
local locationAoE = bot:FindAoELocation( true, false, bot:GetLocation(), nCastRange, nRadius, nCastPoint, 0 )
if ( locationAoE.count >= 6 and #lanecreeps >= 6 )
then
return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc
end
end
if J.IsInTeamFight( bot, 1300 )
then
local locationAoE = bot:FindAoELocation( true, true, bot:GetLocation(), nCastRange, nRadius, nDelay + nCastPoint, 0 )
local nInRangeEnemy = J.GetEnemiesNearLoc(locationAoE.targetloc, nRadius)
if #nInRangeEnemy >= 2
then
return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc
end
end
if J.IsGoingOnSomeone( bot )
then
if J.IsValidHero( botTarget )
and J.CanCastOnNonMagicImmune( botTarget )
and J.IsInRange( botTarget, bot, nCastRange - 150 )
and not J.IsDisabled( botTarget )
and not botTarget:HasModifier('modifier_faceless_void_chronosphere_freeze')
and not botTarget:HasModifier('modifier_necrolyte_reapers_scythe')
then
return BOT_ACTION_DESIRE_HIGH, J.GetCorrectLoc(botTarget, nDelay + nCastPoint)
end
end
return BOT_ACTION_DESIRE_NONE
end
function X.ConsiderE()
if not J.CanCastAbility(abilityE) then return 0 end
local nCastRange = bot:GetAttackRange() + 200
if nCastRange > 1300 then nCastRange = 1300 end
local botTarget = J.GetProperTarget( bot )
local aTarget = bot:GetAttackTarget()
local nEnemyHeroes = bot:GetNearbyHeroes( nCastRange, true, BOT_MODE_NONE )
local nRadius = 300
--团战中对作用数量最多或物理输出最强的敌人使用
if J.IsInTeamFight( bot, 1200 )
then
local npcMostAoeEnemy = nil
local nMostAoeECount = 1
local nEnemysHerosInBonus = bot:GetNearbyHeroes( nCastRange + 299, true, BOT_MODE_NONE )
local nEnemysHerosInRange = bot:GetNearbyHeroes( nCastRange + 43, true, BOT_MODE_NONE )
local nEmemysCreepsInRange = bot:GetNearbyCreeps( nCastRange + 43, true )
local nAllEnemyUnits = J.CombineTwoTable( nEnemysHerosInRange, nEmemysCreepsInRange )
local npcMostDangerousEnemy = nil
local nMostDangerousDamage = 0
for _, npcEnemy in pairs( nAllEnemyUnits )
do
if J.IsValid( npcEnemy )
and J.CanCastOnNonMagicImmune( npcEnemy )
then
local nEnemyHeroCount = J.GetAroundTargetEnemyHeroCount( npcEnemy, nRadius )
if ( nEnemyHeroCount > nMostAoeECount )
then
nMostAoeECount = nEnemyHeroCount
npcMostAoeEnemy = npcEnemy
end
if npcEnemy:IsHero()
then
local npcEnemyDamage = npcEnemy:GetEstimatedDamageToTarget( false, bot, 3.0, DAMAGE_TYPE_PHYSICAL )
if ( npcEnemyDamage > nMostDangerousDamage )
then
nMostDangerousDamage = npcEnemyDamage
npcMostDangerousEnemy = npcEnemy
end
end
end
end
if ( npcMostAoeEnemy ~= nil )
then
return BOT_ACTION_DESIRE_HIGH, npcMostAoeEnemy
end
if ( npcMostDangerousEnemy ~= nil )
then
return BOT_ACTION_DESIRE_HIGH, npcMostDangerousEnemy
end
end
if J.IsValidBuilding(aTarget)
and J.IsInRange( aTarget, bot, nCastRange )
then
return BOT_ACTION_DESIRE_HIGH, aTarget
end
if aTarget == nil and #nEnemyHeroes == 0
then
local hEnemyTowerList = bot:GetNearbyTowers( nCastRange + 36, true )
local hEnemyBarrackList = bot:GetNearbyBarracks( nCastRange + 36, true )
local hTarget = hEnemyTowerList[1]
if hTarget == nil then hTarget = hEnemyBarrackList[1] end
if hTarget ~= nil
and not hTarget:IsAttackImmune()
and not hTarget:IsInvulnerable()
and not hTarget:HasModifier( "modifier_fountain_glyph" )
and not hTarget:HasModifier( "modifier_backdoor_protection_active" )
then
return BOT_ACTION_DESIRE_HIGH, hTarget
end
end
if ( J.IsPushing( bot ) or J.IsDefending( bot ) )
then
local towers = bot:GetNearbyTowers( nCastRange, true )
if J.IsValidBuilding(towers[1]) and J.CanBeAttacked(towers[1])
then
return BOT_ACTION_DESIRE_HIGH, towers[1]
end
local barracks = bot:GetNearbyBarracks( nCastRange, true )
if J.IsValidBuilding(barracks[1]) and J.CanBeAttacked(barracks[1])
then
return BOT_ACTION_DESIRE_HIGH, barracks[1]
end
local creeps = bot:GetNearbyLaneCreeps( nCastRange, true )
if #creeps >= 2 and J.IsValid(creeps[1]) and J.CanBeAttacked(creeps[1])
then
return BOT_ACTION_DESIRE_HIGH, creeps[1]
end
end
if J.IsGoingOnSomeone( bot )
then
if J.IsValidHero( botTarget )
and J.CanCastOnNonMagicImmune( botTarget )
and J.IsInRange( botTarget, bot, nCastRange )
then
return BOT_ACTION_DESIRE_HIGH, botTarget
end
end
if J.IsDoingRoshan(bot)
then
if J.IsRoshan(botTarget)
and J.CanCastOnNonMagicImmune(botTarget)
and J.IsInRange(bot, botTarget, nRadius)
and J.IsAttacking(bot)
then
return BOT_ACTION_DESIRE_HIGH, botTarget
end
end
if J.IsDoingTormentor(bot)
then
if J.IsTormentor(botTarget)
and J.IsInRange(bot, botTarget, nRadius)
and J.IsAttacking(bot)
then
return BOT_ACTION_DESIRE_HIGH, botTarget
end
end
return BOT_ACTION_DESIRE_NONE
end
function X.ConsiderAS()
if not J.CanCastAbility(abilityAS) then return 0 end
local nCastRange = bot:GetAttackRange() + 200
if nCastRange > 1300 then nCastRange = 1300 end
local botTarget = J.GetProperTarget( bot )
local aTarget = bot:GetAttackTarget()
local nEnemyHeroes = bot:GetNearbyHeroes( nCastRange, true, BOT_MODE_NONE )
if J.IsValidBuilding(aTarget)
and J.IsInRange( aTarget, bot, nCastRange )
then
return BOT_ACTION_DESIRE_HIGH, aTarget
end
if aTarget == nil and #nEnemyHeroes == 0
then
local hEnemyTowerList = bot:GetNearbyTowers( nCastRange + 36, true )
local hEnemyBarrackList = bot:GetNearbyBarracks( nCastRange + 36, true )
local hTarget = hEnemyTowerList[1]
if hTarget == nil then hTarget = hEnemyBarrackList[1] end
if hTarget ~= nil
and not hTarget:IsAttackImmune()
and not hTarget:IsInvulnerable()
and not hTarget:HasModifier( "modifier_fountain_glyph" )
and not hTarget:HasModifier( "modifier_backdoor_protection_active" )
then
return BOT_ACTION_DESIRE_HIGH, hTarget
end
end
if ( J.IsPushing( bot ) or J.IsDefending( bot ) )
then
local towers = bot:GetNearbyTowers( nCastRange, true )
if J.IsValidBuilding(towers[1]) and J.CanBeAttacked(towers[1])
then
return BOT_ACTION_DESIRE_HIGH, towers[1]
end
local barracks = bot:GetNearbyBarracks( nCastRange, true )
if J.IsValidBuilding(barracks[1]) and J.CanBeAttacked(barracks[1])
then
return BOT_ACTION_DESIRE_HIGH, barracks[1]
end
end
if J.IsGoingOnSomeone( bot )
then
if J.IsValidHero( botTarget )
and J.CanCastOnNonMagicImmune( botTarget )
and J.IsInRange( botTarget, bot, nCastRange )
then
return BOT_ACTION_DESIRE_HIGH, botTarget
end
end
return BOT_ACTION_DESIRE_NONE
end
function X.ConsiderR()
if not J.CanCastAbility(abilityR) then return 0 end
local nCastRange = J.GetProperCastRange(false, bot, abilityR:GetCastRange())
if nCastRange > 1500 then nCastRange = 1500 end
local nCastPoint = abilityR:GetCastPoint()
local manaCost = abilityR:GetManaCost()
local nRadius = abilityR:GetSpecialValueInt( "path_radius" )
local nDamage = abilityR:GetSpecialValueInt( 'damage' )
local botTarget = J.GetProperTarget( bot )
local nEnemyHeroes = bot:GetNearbyHeroes( nCastRange, true, BOT_MODE_NONE )
for _, enemy in pairs(nEnemyHeroes)
do
if J.IsValidHero(enemy)
and J.GetHP(bot) > 0.5
and not J.IsSuspiciousIllusion(enemy)
then
if enemy:HasModifier('modifier_faceless_void_chronosphere_freeze')
or enemy:HasModifier('modifier_enigma_black_hole_pull')
then
return BOT_ACTION_DESIRE_HIGH, enemy:GetLocation()
end
end
end
if J.IsRetreating( bot )
and not J.IsRealInvisible(bot)
then
if #nEnemyHeroes > 0 and bot:WasRecentlyDamagedByAnyHero( 2.0 )
then
local locationAoE = bot:FindAoELocation( true, true, bot:GetLocation(), nCastRange - 100, nRadius * 1.6, nCastPoint, 0 )
local nInRangeEnemy = J.GetEnemiesNearLoc(locationAoE.targetloc, nRadius)
if #nInRangeEnemy >= 2
then
return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc
end
end
end
if ( J.IsPushing( bot ) or J.IsDefending( bot ) )
then
local locationAoE = bot:FindAoELocation( true, true, bot:GetLocation(), nCastRange, nRadius, nCastPoint, 0 )
if locationAoE.count >= 2
then
local hTrueHeroList = J.GetEnemyList( bot, 1200 )
if #hTrueHeroList >= 2
then
return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc
end
end
end
if J.IsInTeamFight( bot, 1300 )
then
local locationAoE = bot:FindAoELocation( true, true, bot:GetLocation(), nCastRange, nRadius, nCastPoint, 0 )
if locationAoE.count >= 2
then
local hTrueHeroList = J.GetEnemyList( bot, 1300 )
if #hTrueHeroList >= 2
then
return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc
end
end
end
if J.IsGoingOnSomeone( bot )
then
if J.IsValidHero( botTarget )
and botTarget:GetHealth() > 600
and J.CanCastOnNonMagicImmune( botTarget )
and J.IsInRange( botTarget, bot, nCastRange -200 )
and not botTarget:HasModifier('modifier_necrolyte_reapers_scythe')
then
local targetAllies = botTarget:GetNearbyHeroes( 2 * nRadius, false, BOT_MODE_NONE )
if #targetAllies >= 2 or J.IsInRange( botTarget, bot, 600 )
then
return BOT_ACTION_DESIRE_HIGH, J.GetCorrectLoc(botTarget, nCastPoint)
end
end
end
return BOT_ACTION_DESIRE_NONE
end
return X
| 0 | 0.880526 | 1 | 0.880526 | game-dev | MEDIA | 0.964096 | game-dev | 0.964617 | 1 | 0.964617 |
Rogueadyn/SaintCoinach | 2,871 | SaintCoinach/Xiv/Items/Shield.cs | using System.Collections.Generic;
using SaintCoinach.Ex.Relational;
namespace SaintCoinach.Xiv.Items {
/// <summary>
/// Class representing a shield.
/// </summary>
public class Shield : Equipment {
#region Fields
/// <summary>
/// <see cref="ParameterCollection" /> containing primary parameters of the current item.
/// </summary>
private ParameterCollection _PrimaryParameters;
#endregion
#region Properties
/// <summary>
/// Gets the primary <see cref="Parameter"/>s of the current item.
/// </summary>
/// <value>The primary <see cref="Parameter"/>s of the current item.</value>
public override IEnumerable<Parameter> PrimaryParameters {
get { return _PrimaryParameters ?? (_PrimaryParameters = BuildPrimaryParameters()); }
}
/// <summary>
/// Gets the block strength of the current item.
/// </summary>
/// <value>The block strength of the current item.</value>
public int BlockStrength { get { return AsInt32("Block"); } }
/// <summary>
/// Gets the block rate of the current item.
/// </summary>
/// <value>The block rate of the current item.</value>
public int BlockRate { get { return AsInt32("BlockRate"); } }
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Shield" /> class.
/// </summary>
/// <param name="sheet"><see cref="IXivSheet" /> containing this object.</param>
/// <param name="sourceRow"><see cref="IRelationalRow" /> to read data from.</param>
public Shield(IXivSheet sheet, IRelationalRow sourceRow) : base(sheet, sourceRow) { }
#endregion
#region Build
/// <summary>
/// Build the <see cref="ParameterCollection" /> containg the primary parameters of the current item.
/// </summary>
/// <returns>The <see cref="ParameterCollection" /> containg the primary parameters of the current item.</returns>
private ParameterCollection BuildPrimaryParameters() {
var param = new ParameterCollection();
// XXX: Here be magic numbers
const int BlockStrengthKey = 17;
const int BlockRateKey = 18;
var paramSheet = Sheet.Collection.GetSheet<BaseParam>();
if (BlockStrength != 0)
param.AddParameterValue(paramSheet[BlockStrengthKey],
new ParameterValueFixed(ParameterType.Primary, BlockStrength));
if (BlockRate != 0)
param.AddParameterValue(paramSheet[BlockRateKey],
new ParameterValueFixed(ParameterType.Primary, BlockRate));
return param;
}
#endregion
}
}
| 0 | 0.841304 | 1 | 0.841304 | game-dev | MEDIA | 0.393946 | game-dev | 0.710622 | 1 | 0.710622 |
servo/mozjs | 11,652 | mozjs-sys/mozjs/nsprpub/lib/ds/plhash.c | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
/*
* PL hash table package.
*/
#include "plhash.h"
#include "prbit.h"
#include "prlog.h"
#include "prmem.h"
#include "prtypes.h"
#include <stdlib.h>
#include <string.h>
/* Compute the number of buckets in ht */
#define NBUCKETS(ht) (1 << (PL_HASH_BITS - (ht)->shift))
/* The smallest table has 16 buckets */
#define MINBUCKETSLOG2 4
#define MINBUCKETS (1 << MINBUCKETSLOG2)
/* Compute the maximum entries given n buckets that we will tolerate, ~90% */
#define OVERLOADED(n) ((n) - ((n) >> 3))
/* Compute the number of entries below which we shrink the table by half */
#define UNDERLOADED(n) (((n) > MINBUCKETS) ? ((n) >> 2) : 0)
/*
** Stubs for default hash allocator ops.
*/
static void* PR_CALLBACK DefaultAllocTable(void* pool, PRSize size) {
return PR_MALLOC(size);
}
static void PR_CALLBACK DefaultFreeTable(void* pool, void* item) {
PR_Free(item);
}
static PLHashEntry* PR_CALLBACK DefaultAllocEntry(void* pool, const void* key) {
return PR_NEW(PLHashEntry);
}
static void PR_CALLBACK DefaultFreeEntry(void* pool, PLHashEntry* he,
PRUintn flag) {
if (flag == HT_FREE_ENTRY) {
PR_Free(he);
}
}
static PLHashAllocOps defaultHashAllocOps = {
DefaultAllocTable, DefaultFreeTable, DefaultAllocEntry, DefaultFreeEntry};
PR_IMPLEMENT(PLHashTable*)
PL_NewHashTable(PRUint32 n, PLHashFunction keyHash, PLHashComparator keyCompare,
PLHashComparator valueCompare, const PLHashAllocOps* allocOps,
void* allocPriv) {
PLHashTable* ht;
PRSize nb;
if (n <= MINBUCKETS) {
n = MINBUCKETSLOG2;
} else {
n = PR_CeilingLog2(n);
if ((PRInt32)n < 0) {
return 0;
}
}
if (!allocOps) {
allocOps = &defaultHashAllocOps;
}
ht = (PLHashTable*)((*allocOps->allocTable)(allocPriv, sizeof *ht));
if (!ht) {
return 0;
}
memset(ht, 0, sizeof *ht);
ht->shift = PL_HASH_BITS - n;
n = 1 << n;
nb = n * sizeof(PLHashEntry*);
ht->buckets = (PLHashEntry**)((*allocOps->allocTable)(allocPriv, nb));
if (!ht->buckets) {
(*allocOps->freeTable)(allocPriv, ht);
return 0;
}
memset(ht->buckets, 0, nb);
ht->keyHash = keyHash;
ht->keyCompare = keyCompare;
ht->valueCompare = valueCompare;
ht->allocOps = allocOps;
ht->allocPriv = allocPriv;
return ht;
}
PR_IMPLEMENT(void)
PL_HashTableDestroy(PLHashTable* ht) {
PRUint32 i, n;
PLHashEntry *he, *next;
const PLHashAllocOps* allocOps = ht->allocOps;
void* allocPriv = ht->allocPriv;
n = NBUCKETS(ht);
for (i = 0; i < n; i++) {
for (he = ht->buckets[i]; he; he = next) {
next = he->next;
(*allocOps->freeEntry)(allocPriv, he, HT_FREE_ENTRY);
}
}
#ifdef DEBUG
memset(ht->buckets, 0xDB, n * sizeof ht->buckets[0]);
#endif
(*allocOps->freeTable)(allocPriv, ht->buckets);
#ifdef DEBUG
memset(ht, 0xDB, sizeof *ht);
#endif
(*allocOps->freeTable)(allocPriv, ht);
}
/*
** Multiplicative hash, from Knuth 6.4.
*/
#define GOLDEN_RATIO 0x9E3779B9U /* 2/(1+sqrt(5))*(2^32) */
PR_IMPLEMENT(PLHashEntry**)
PL_HashTableRawLookup(PLHashTable* ht, PLHashNumber keyHash, const void* key) {
PLHashEntry *he, **hep, **hep0;
PLHashNumber h;
#ifdef HASHMETER
ht->nlookups++;
#endif
h = keyHash * GOLDEN_RATIO;
h >>= ht->shift;
hep = hep0 = &ht->buckets[h];
while ((he = *hep) != 0) {
if (he->keyHash == keyHash && (*ht->keyCompare)(key, he->key)) {
/* Move to front of chain if not already there */
if (hep != hep0) {
*hep = he->next;
he->next = *hep0;
*hep0 = he;
}
return hep0;
}
hep = &he->next;
#ifdef HASHMETER
ht->nsteps++;
#endif
}
return hep;
}
/*
** Same as PL_HashTableRawLookup but doesn't reorder the hash entries.
*/
PR_IMPLEMENT(PLHashEntry**)
PL_HashTableRawLookupConst(PLHashTable* ht, PLHashNumber keyHash,
const void* key) {
PLHashEntry *he, **hep;
PLHashNumber h;
#ifdef HASHMETER
ht->nlookups++;
#endif
h = keyHash * GOLDEN_RATIO;
h >>= ht->shift;
hep = &ht->buckets[h];
while ((he = *hep) != 0) {
if (he->keyHash == keyHash && (*ht->keyCompare)(key, he->key)) {
break;
}
hep = &he->next;
#ifdef HASHMETER
ht->nsteps++;
#endif
}
return hep;
}
PR_IMPLEMENT(PLHashEntry*)
PL_HashTableRawAdd(PLHashTable* ht, PLHashEntry** hep, PLHashNumber keyHash,
const void* key, void* value) {
PRUint32 i, n;
PLHashEntry *he, *next, **oldbuckets;
PRSize nb;
/* Grow the table if it is overloaded */
n = NBUCKETS(ht);
if (ht->nentries >= OVERLOADED(n)) {
oldbuckets = ht->buckets;
nb = 2 * n * sizeof(PLHashEntry*);
ht->buckets =
(PLHashEntry**)((*ht->allocOps->allocTable)(ht->allocPriv, nb));
if (!ht->buckets) {
ht->buckets = oldbuckets;
return 0;
}
memset(ht->buckets, 0, nb);
#ifdef HASHMETER
ht->ngrows++;
#endif
ht->shift--;
for (i = 0; i < n; i++) {
for (he = oldbuckets[i]; he; he = next) {
next = he->next;
hep = PL_HashTableRawLookup(ht, he->keyHash, he->key);
PR_ASSERT(*hep == 0);
he->next = 0;
*hep = he;
}
}
#ifdef DEBUG
memset(oldbuckets, 0xDB, n * sizeof oldbuckets[0]);
#endif
(*ht->allocOps->freeTable)(ht->allocPriv, oldbuckets);
hep = PL_HashTableRawLookup(ht, keyHash, key);
}
/* Make a new key value entry */
he = (*ht->allocOps->allocEntry)(ht->allocPriv, key);
if (!he) {
return 0;
}
he->keyHash = keyHash;
he->key = key;
he->value = value;
he->next = *hep;
*hep = he;
ht->nentries++;
return he;
}
PR_IMPLEMENT(PLHashEntry*)
PL_HashTableAdd(PLHashTable* ht, const void* key, void* value) {
PLHashNumber keyHash;
PLHashEntry *he, **hep;
keyHash = (*ht->keyHash)(key);
hep = PL_HashTableRawLookup(ht, keyHash, key);
if ((he = *hep) != 0) {
/* Hit; see if values match */
if ((*ht->valueCompare)(he->value, value)) {
/* key,value pair is already present in table */
return he;
}
if (he->value) {
(*ht->allocOps->freeEntry)(ht->allocPriv, he, HT_FREE_VALUE);
}
he->value = value;
return he;
}
return PL_HashTableRawAdd(ht, hep, keyHash, key, value);
}
PR_IMPLEMENT(void)
PL_HashTableRawRemove(PLHashTable* ht, PLHashEntry** hep, PLHashEntry* he) {
PRUint32 i, n;
PLHashEntry *next, **oldbuckets;
PRSize nb;
*hep = he->next;
(*ht->allocOps->freeEntry)(ht->allocPriv, he, HT_FREE_ENTRY);
/* Shrink table if it's underloaded */
n = NBUCKETS(ht);
if (--ht->nentries < UNDERLOADED(n)) {
oldbuckets = ht->buckets;
nb = n * sizeof(PLHashEntry*) / 2;
ht->buckets =
(PLHashEntry**)((*ht->allocOps->allocTable)(ht->allocPriv, nb));
if (!ht->buckets) {
ht->buckets = oldbuckets;
return;
}
memset(ht->buckets, 0, nb);
#ifdef HASHMETER
ht->nshrinks++;
#endif
ht->shift++;
for (i = 0; i < n; i++) {
for (he = oldbuckets[i]; he; he = next) {
next = he->next;
hep = PL_HashTableRawLookup(ht, he->keyHash, he->key);
PR_ASSERT(*hep == 0);
he->next = 0;
*hep = he;
}
}
#ifdef DEBUG
memset(oldbuckets, 0xDB, n * sizeof oldbuckets[0]);
#endif
(*ht->allocOps->freeTable)(ht->allocPriv, oldbuckets);
}
}
PR_IMPLEMENT(PRBool)
PL_HashTableRemove(PLHashTable* ht, const void* key) {
PLHashNumber keyHash;
PLHashEntry *he, **hep;
keyHash = (*ht->keyHash)(key);
hep = PL_HashTableRawLookup(ht, keyHash, key);
if ((he = *hep) == 0) {
return PR_FALSE;
}
/* Hit; remove element */
PL_HashTableRawRemove(ht, hep, he);
return PR_TRUE;
}
PR_IMPLEMENT(void*)
PL_HashTableLookup(PLHashTable* ht, const void* key) {
PLHashNumber keyHash;
PLHashEntry *he, **hep;
keyHash = (*ht->keyHash)(key);
hep = PL_HashTableRawLookup(ht, keyHash, key);
if ((he = *hep) != 0) {
return he->value;
}
return 0;
}
/*
** Same as PL_HashTableLookup but doesn't reorder the hash entries.
*/
PR_IMPLEMENT(void*)
PL_HashTableLookupConst(PLHashTable* ht, const void* key) {
PLHashNumber keyHash;
PLHashEntry *he, **hep;
keyHash = (*ht->keyHash)(key);
hep = PL_HashTableRawLookupConst(ht, keyHash, key);
if ((he = *hep) != 0) {
return he->value;
}
return 0;
}
/*
** Iterate over the entries in the hash table calling func for each
** entry found. Stop if "f" says to (return value & PR_ENUMERATE_STOP).
** Return a count of the number of elements scanned.
*/
PR_IMPLEMENT(int)
PL_HashTableEnumerateEntries(PLHashTable* ht, PLHashEnumerator f, void* arg) {
PLHashEntry *he, **hep;
PRUint32 i, nbuckets;
int rv, n = 0;
PLHashEntry* todo = 0;
nbuckets = NBUCKETS(ht);
for (i = 0; i < nbuckets; i++) {
hep = &ht->buckets[i];
while ((he = *hep) != 0) {
rv = (*f)(he, n, arg);
n++;
if (rv & (HT_ENUMERATE_REMOVE | HT_ENUMERATE_UNHASH)) {
*hep = he->next;
if (rv & HT_ENUMERATE_REMOVE) {
he->next = todo;
todo = he;
}
} else {
hep = &he->next;
}
if (rv & HT_ENUMERATE_STOP) {
goto out;
}
}
}
out:
hep = &todo;
while ((he = *hep) != 0) {
PL_HashTableRawRemove(ht, hep, he);
}
return n;
}
#ifdef HASHMETER
# include <math.h>
# include <stdio.h>
PR_IMPLEMENT(void)
PL_HashTableDumpMeter(PLHashTable* ht, PLHashEnumerator dump, FILE* fp) {
double mean, variance;
PRUint32 nchains, nbuckets;
PRUint32 i, n, maxChain, maxChainLen;
PLHashEntry* he;
variance = 0;
nchains = 0;
maxChainLen = 0;
nbuckets = NBUCKETS(ht);
for (i = 0; i < nbuckets; i++) {
he = ht->buckets[i];
if (!he) {
continue;
}
nchains++;
for (n = 0; he; he = he->next) {
n++;
}
variance += n * n;
if (n > maxChainLen) {
maxChainLen = n;
maxChain = i;
}
}
mean = (double)ht->nentries / nchains;
variance = fabs(variance / nchains - mean * mean);
fprintf(fp, "\nHash table statistics:\n");
fprintf(fp, " number of lookups: %u\n", ht->nlookups);
fprintf(fp, " number of entries: %u\n", ht->nentries);
fprintf(fp, " number of grows: %u\n", ht->ngrows);
fprintf(fp, " number of shrinks: %u\n", ht->nshrinks);
fprintf(fp, " mean steps per hash: %g\n",
(double)ht->nsteps / ht->nlookups);
fprintf(fp, "mean hash chain length: %g\n", mean);
fprintf(fp, " standard deviation: %g\n", sqrt(variance));
fprintf(fp, " max hash chain length: %u\n", maxChainLen);
fprintf(fp, " max hash chain: [%u]\n", maxChain);
for (he = ht->buckets[maxChain], i = 0; he; he = he->next, i++)
if ((*dump)(he, i, fp) != HT_ENUMERATE_NEXT) {
break;
}
}
#endif /* HASHMETER */
PR_IMPLEMENT(int)
PL_HashTableDump(PLHashTable* ht, PLHashEnumerator dump, FILE* fp) {
int count;
count = PL_HashTableEnumerateEntries(ht, dump, fp);
#ifdef HASHMETER
PL_HashTableDumpMeter(ht, dump, fp);
#endif
return count;
}
PR_IMPLEMENT(PLHashNumber)
PL_HashString(const void* key) {
PLHashNumber h;
const PRUint8* s;
h = 0;
for (s = (const PRUint8*)key; *s; s++) {
h = PR_ROTATE_LEFT32(h, 4) ^ *s;
}
return h;
}
PR_IMPLEMENT(int)
PL_CompareStrings(const void* v1, const void* v2) {
return strcmp((const char*)v1, (const char*)v2) == 0;
}
PR_IMPLEMENT(int)
PL_CompareValues(const void* v1, const void* v2) { return v1 == v2; }
| 0 | 0.950114 | 1 | 0.950114 | game-dev | MEDIA | 0.11479 | game-dev | 0.980659 | 1 | 0.980659 |
HyperMC-Team/OpenRoxy | 6,845 | src/main/java/net/optifine/DynamicLight.java | package net.optifine;
import java.util.HashSet;
import java.util.Set;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.renderer.chunk.CompiledChunk;
import net.minecraft.client.renderer.chunk.RenderChunk;
import net.minecraft.entity.Entity;
import net.minecraft.init.Blocks;
import net.minecraft.src.Config;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.MathHelper;
import net.optifine.DynamicLights;
public class DynamicLight {
private Entity entity = null;
private double offsetY = 0.0;
private double lastPosX = -2.147483648E9;
private double lastPosY = -2.147483648E9;
private double lastPosZ = -2.147483648E9;
private int lastLightLevel = 0;
private boolean underwater = false;
private long timeCheckMs = 0L;
private Set<BlockPos> setLitChunkPos = new HashSet<BlockPos>();
private final BlockPos.MutableBlockPos blockPosMutable = new BlockPos.MutableBlockPos();
public DynamicLight(Entity entity) {
this.entity = entity;
this.offsetY = entity.getEyeHeight();
}
public void update(RenderGlobal renderGlobal) {
if (Config.isDynamicLightsFast()) {
long i = System.currentTimeMillis();
if (i < this.timeCheckMs + 500L) {
return;
}
this.timeCheckMs = i;
}
double d6 = this.entity.posX - 0.5;
double d0 = this.entity.posY - 0.5 + this.offsetY;
double d1 = this.entity.posZ - 0.5;
int j = DynamicLights.getLightLevel(this.entity);
double d2 = d6 - this.lastPosX;
double d3 = d0 - this.lastPosY;
double d4 = d1 - this.lastPosZ;
double d5 = 0.1;
if (Math.abs(d2) > d5 || Math.abs(d3) > d5 || Math.abs(d4) > d5 || this.lastLightLevel != j) {
this.lastPosX = d6;
this.lastPosY = d0;
this.lastPosZ = d1;
this.lastLightLevel = j;
this.underwater = false;
WorldClient world = renderGlobal.getWorld();
if (world != null) {
this.blockPosMutable.set(MathHelper.floor_double(d6), MathHelper.floor_double(d0), MathHelper.floor_double(d1));
IBlockState iblockstate = world.getBlockState(this.blockPosMutable);
Block block = iblockstate.getBlock();
this.underwater = block == Blocks.water;
}
HashSet<BlockPos> set = new HashSet<BlockPos>();
if (j > 0) {
EnumFacing enumfacing2 = (MathHelper.floor_double(d6) & 0xF) >= 8 ? EnumFacing.EAST : EnumFacing.WEST;
EnumFacing enumfacing = (MathHelper.floor_double(d0) & 0xF) >= 8 ? EnumFacing.UP : EnumFacing.DOWN;
EnumFacing enumfacing1 = (MathHelper.floor_double(d1) & 0xF) >= 8 ? EnumFacing.SOUTH : EnumFacing.NORTH;
BlockPos blockpos = new BlockPos(d6, d0, d1);
RenderChunk renderchunk = renderGlobal.getRenderChunk(blockpos);
BlockPos blockpos1 = this.getChunkPos(renderchunk, blockpos, enumfacing2);
RenderChunk renderchunk1 = renderGlobal.getRenderChunk(blockpos1);
BlockPos blockpos2 = this.getChunkPos(renderchunk, blockpos, enumfacing1);
RenderChunk renderchunk2 = renderGlobal.getRenderChunk(blockpos2);
BlockPos blockpos3 = this.getChunkPos(renderchunk1, blockpos1, enumfacing1);
RenderChunk renderchunk3 = renderGlobal.getRenderChunk(blockpos3);
BlockPos blockpos4 = this.getChunkPos(renderchunk, blockpos, enumfacing);
RenderChunk renderchunk4 = renderGlobal.getRenderChunk(blockpos4);
BlockPos blockpos5 = this.getChunkPos(renderchunk4, blockpos4, enumfacing2);
RenderChunk renderchunk5 = renderGlobal.getRenderChunk(blockpos5);
BlockPos blockpos6 = this.getChunkPos(renderchunk4, blockpos4, enumfacing1);
RenderChunk renderchunk6 = renderGlobal.getRenderChunk(blockpos6);
BlockPos blockpos7 = this.getChunkPos(renderchunk5, blockpos5, enumfacing1);
RenderChunk renderchunk7 = renderGlobal.getRenderChunk(blockpos7);
this.updateChunkLight(renderchunk, this.setLitChunkPos, set);
this.updateChunkLight(renderchunk1, this.setLitChunkPos, set);
this.updateChunkLight(renderchunk2, this.setLitChunkPos, set);
this.updateChunkLight(renderchunk3, this.setLitChunkPos, set);
this.updateChunkLight(renderchunk4, this.setLitChunkPos, set);
this.updateChunkLight(renderchunk5, this.setLitChunkPos, set);
this.updateChunkLight(renderchunk6, this.setLitChunkPos, set);
this.updateChunkLight(renderchunk7, this.setLitChunkPos, set);
}
this.updateLitChunks(renderGlobal);
this.setLitChunkPos = set;
}
}
private BlockPos getChunkPos(RenderChunk renderChunk, BlockPos pos, EnumFacing facing) {
return renderChunk != null ? renderChunk.getBlockPosOffset16(facing) : pos.offset(facing, 16);
}
private void updateChunkLight(RenderChunk renderChunk, Set<BlockPos> setPrevPos, Set<BlockPos> setNewPos) {
if (renderChunk != null) {
CompiledChunk compiledchunk = renderChunk.getCompiledChunk();
if (compiledchunk != null && !compiledchunk.isEmpty()) {
renderChunk.setNeedsUpdate(true);
}
BlockPos blockpos = renderChunk.getPosition();
if (setPrevPos != null) {
setPrevPos.remove(blockpos);
}
if (setNewPos != null) {
setNewPos.add(blockpos);
}
}
}
public void updateLitChunks(RenderGlobal renderGlobal) {
for (BlockPos blockpos : this.setLitChunkPos) {
RenderChunk renderchunk = renderGlobal.getRenderChunk(blockpos);
this.updateChunkLight(renderchunk, null, null);
}
}
public Entity getEntity() {
return this.entity;
}
public double getLastPosX() {
return this.lastPosX;
}
public double getLastPosY() {
return this.lastPosY;
}
public double getLastPosZ() {
return this.lastPosZ;
}
public int getLastLightLevel() {
return this.lastLightLevel;
}
public boolean isUnderwater() {
return this.underwater;
}
public double getOffsetY() {
return this.offsetY;
}
public String toString() {
return "Entity: " + this.entity + ", offsetY: " + this.offsetY;
}
}
| 0 | 0.775414 | 1 | 0.775414 | game-dev | MEDIA | 0.826812 | game-dev,graphics-rendering | 0.942285 | 1 | 0.942285 |
OpenXRay/xray-16 | 1,632 | src/xrGame/smart_cover_loophole_inline.h | ////////////////////////////////////////////////////////////////////////////
// Module : smart_cover_loophole_inline.h
// Created : 29.08.2007
// Author : Alexander Dudin
// Description : Loophole class inline functions
////////////////////////////////////////////////////////////////////////////
#ifndef SMART_COVER_LOOPHOLE_INLINE_H_INCLUDED
#define SMART_COVER_LOOPHOLE_INLINE_H_INCLUDED
namespace smart_cover
{
IC shared_str const& loophole::id() const { return (m_id); }
IC float const& loophole::fov() const { return (m_fov); }
IC float const& loophole::danger_fov() const { return (m_danger_fov); }
IC float const& loophole::range() const { return (m_range); }
IC Fvector const& loophole::fov_position() const { return (m_fov_position); }
IC Fvector const& loophole::fov_direction() const { return (m_fov_direction); }
IC Fvector const& loophole::danger_fov_direction() const { return (m_danger_fov_direction); }
IC Fvector const& loophole::enter_direction() const { return (m_enter_direction); }
IC loophole::ActionList const& loophole::actions() const { return (m_actions); }
IC bool const& loophole::enterable() const { return (m_enterable); }
IC void loophole::enterable(bool value) { m_enterable = value; }
IC bool const& loophole::usable() const { return (m_usable); }
IC bool loophole::is_action_available(shared_str const& action_id) const
{
return (m_actions.find(action_id) != m_actions.end());
}
IC bool const& loophole::exitable() const { return (m_exitable); }
IC void loophole::exitable(bool value) { m_exitable = value; }
} // namespace smart_cover
#endif // SMART_COVER_LOOPHOLE_INLINE_H_INCLUDED
| 0 | 0.729912 | 1 | 0.729912 | game-dev | MEDIA | 0.46523 | game-dev | 0.508303 | 1 | 0.508303 |
LeavesMC/Leaves | 42,283 | leaves-server/minecraft-patches/features/0102-Old-Block-remove-behaviour.patch | From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: violetc <58360096+s-yh-china@users.noreply.github.com>
Date: Wed, 14 Aug 2024 01:48:14 +0800
Subject: [PATCH] Old Block remove behaviour
diff --git a/net/minecraft/world/Containers.java b/net/minecraft/world/Containers.java
index da10ca5ef12be1a834adda9243c082dadde24ec0..f682930f765d04f0a278b0648c2773ab5d4d740e 100644
--- a/net/minecraft/world/Containers.java
+++ b/net/minecraft/world/Containers.java
@@ -51,4 +51,15 @@ public class Containers {
public static void updateNeighboursAfterDestroy(BlockState state, Level level, BlockPos pos) {
level.updateNeighbourForOutputSignal(pos, state.getBlock());
}
+
+ // Leaves start - behaviour 1.21.1-
+ public static void dropContentsOnDestroy(BlockState state, BlockState newState, Level level, BlockPos pos) {
+ if (!state.is(newState.getBlock())) {
+ if (level.getBlockEntity(pos) instanceof Container container) {
+ dropContents(level, pos, container);
+ level.updateNeighbourForOutputSignal(pos, state.getBlock());
+ }
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
}
diff --git a/net/minecraft/world/level/block/AbstractFurnaceBlock.java b/net/minecraft/world/level/block/AbstractFurnaceBlock.java
index d52eeff0d564a24bddb873750c81e3fe999f16f0..aa2597d825f93b0b0623ab7fae29e45de3f3ebcc 100644
--- a/net/minecraft/world/level/block/AbstractFurnaceBlock.java
+++ b/net/minecraft/world/level/block/AbstractFurnaceBlock.java
@@ -51,6 +51,26 @@ public abstract class AbstractFurnaceBlock extends BaseEntityBlock {
return this.defaultBlockState().setValue(FACING, context.getHorizontalDirection().getOpposite());
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!state.is(newState.getBlock())) {
+ BlockEntity blockEntity = level.getBlockEntity(pos);
+ if (blockEntity instanceof AbstractFurnaceBlockEntity) {
+ if (level instanceof ServerLevel) {
+ Containers.dropContents(level, pos, (AbstractFurnaceBlockEntity)blockEntity);
+ ((AbstractFurnaceBlockEntity)blockEntity).getRecipesToAwardAndPopExperience((ServerLevel)level, net.minecraft.world.phys.Vec3.atCenterOf(pos));
+ }
+
+ super.onRemove(state, level, pos, newState, isMoving);
+ level.updateNeighbourForOutputSignal(pos, this);
+ } else {
+ super.onRemove(state, level, pos, newState, isMoving);
+ }
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
Containers.updateNeighboursAfterDestroy(state, level, pos);
diff --git a/net/minecraft/world/level/block/BarrelBlock.java b/net/minecraft/world/level/block/BarrelBlock.java
index f7820265f10b78674acd13e6204b9212fd27b038..700bd0f6a4f4fd6cd85b3e666fff1b3fd0a96b8e 100644
--- a/net/minecraft/world/level/block/BarrelBlock.java
+++ b/net/minecraft/world/level/block/BarrelBlock.java
@@ -49,6 +49,14 @@ public class BarrelBlock extends BaseEntityBlock {
return InteractionResult.SUCCESS;
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ Containers.dropContentsOnDestroy(state, newState, level, pos);
+ super.onRemove(state, level, pos, newState, isMoving);
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
Containers.updateNeighboursAfterDestroy(state, level, pos);
diff --git a/net/minecraft/world/level/block/BasePressurePlateBlock.java b/net/minecraft/world/level/block/BasePressurePlateBlock.java
index 42ee3f32fe44c1f0680c994a69201f7bd7792673..19214c236bca4e454e3bbe7dc50e00b66398c119 100644
--- a/net/minecraft/world/level/block/BasePressurePlateBlock.java
+++ b/net/minecraft/world/level/block/BasePressurePlateBlock.java
@@ -125,6 +125,19 @@ public abstract class BasePressurePlateBlock extends Block {
}
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!isMoving && !state.is(newState.getBlock())) {
+ if (this.getSignalForState(state) > 0) {
+ this.updateNeighbours(level, pos);
+ }
+
+ super.onRemove(state, level, pos, newState, isMoving);
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
if (!movedByPiston && this.getSignalForState(state) > 0) {
diff --git a/net/minecraft/world/level/block/BaseRailBlock.java b/net/minecraft/world/level/block/BaseRailBlock.java
index 5f99e18244501ed2d85be77b71f48cc93058cdb7..6bf50d9c3921b15f40b4fba273abeb4c2e0f30b3 100644
--- a/net/minecraft/world/level/block/BaseRailBlock.java
+++ b/net/minecraft/world/level/block/BaseRailBlock.java
@@ -121,6 +121,23 @@ public abstract class BaseRailBlock extends Block implements SimpleWaterloggedBl
}
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!isMoving) {
+ super.onRemove(state, level, pos, newState, isMoving);
+ if (state.getValue(this.getShapeProperty()).isSlope()) {
+ level.updateNeighborsAt(pos.above(), this);
+ }
+
+ if (this.isStraight) {
+ level.updateNeighborsAt(pos, this);
+ level.updateNeighborsAt(pos.below(), this);
+ }
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
if (!movedByPiston) {
diff --git a/net/minecraft/world/level/block/BrewingStandBlock.java b/net/minecraft/world/level/block/BrewingStandBlock.java
index f563f8ea63e67f808802baa4c6a700e803c045a0..0cc4479d9d3f6aea280c9f88997d141dc24917a9 100644
--- a/net/minecraft/world/level/block/BrewingStandBlock.java
+++ b/net/minecraft/world/level/block/BrewingStandBlock.java
@@ -78,6 +78,14 @@ public class BrewingStandBlock extends BaseEntityBlock {
level.addParticle(ParticleTypes.SMOKE, d, d1, d2, 0.0, 0.0, 0.0);
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ Containers.dropContentsOnDestroy(state, newState, level, pos);
+ super.onRemove(state, level, pos, newState, isMoving);
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
Containers.updateNeighboursAfterDestroy(state, level, pos);
diff --git a/net/minecraft/world/level/block/ButtonBlock.java b/net/minecraft/world/level/block/ButtonBlock.java
index 66c589bc633d32ebf36b1ab55ba6250ca2ddd6f6..f96d3c7b7ec15973aca3aabe056608fd5efb856b 100644
--- a/net/minecraft/world/level/block/ButtonBlock.java
+++ b/net/minecraft/world/level/block/ButtonBlock.java
@@ -132,6 +132,19 @@ public class ButtonBlock extends FaceAttachedHorizontalDirectionalBlock {
return isOn ? this.type.buttonClickOn() : this.type.buttonClickOff();
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!isMoving && !state.is(newState.getBlock())) {
+ if (state.getValue(POWERED)) {
+ this.updateNeighbours(state, level, pos);
+ }
+
+ super.onRemove(state, level, pos, newState, isMoving);
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
if (!movedByPiston && state.getValue(POWERED)) {
diff --git a/net/minecraft/world/level/block/CampfireBlock.java b/net/minecraft/world/level/block/CampfireBlock.java
index 028e2ad8bcb23b3f9f80a5ec551204bb2d7db1ae..c9e2becc0644de707e0bd251318813c50fc82be2 100644
--- a/net/minecraft/world/level/block/CampfireBlock.java
+++ b/net/minecraft/world/level/block/CampfireBlock.java
@@ -105,6 +105,20 @@ public class CampfireBlock extends BaseEntityBlock implements SimpleWaterloggedB
return InteractionResult.TRY_WITH_EMPTY_HAND;
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!state.is(newState.getBlock())) {
+ BlockEntity blockEntity = level.getBlockEntity(pos);
+ if (blockEntity instanceof CampfireBlockEntity) {
+ net.minecraft.world.Containers.dropContents(level, pos, ((CampfireBlockEntity)blockEntity).getItems());
+ }
+
+ super.onRemove(state, level, pos, newState, isMoving);
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void entityInside(BlockState state, Level level, BlockPos pos, Entity entity, InsideBlockEffectApplier effectApplier) {
if (!new io.papermc.paper.event.entity.EntityInsideBlockEvent(entity.getBukkitEntity(), org.bukkit.craftbukkit.block.CraftBlock.at(level, pos)).callEvent()) { return; } // Paper - Add EntityInsideBlockEvent
diff --git a/net/minecraft/world/level/block/ChestBlock.java b/net/minecraft/world/level/block/ChestBlock.java
index c4937d1b482e2ec60961bda62ad6cc155f0ce8f7..818b1a5df0e9a0566210e4b3512ad856515e385f 100644
--- a/net/minecraft/world/level/block/ChestBlock.java
+++ b/net/minecraft/world/level/block/ChestBlock.java
@@ -244,6 +244,14 @@ public class ChestBlock extends AbstractChestBlock<ChestBlockEntity> implements
return blockState.is(this) && blockState.getValue(TYPE) == ChestType.SINGLE ? blockState.getValue(FACING) : null;
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ Containers.dropContentsOnDestroy(state, newState, level, pos);
+ super.onRemove(state, level, pos, newState, isMoving);
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
Containers.updateNeighboursAfterDestroy(state, level, pos);
diff --git a/net/minecraft/world/level/block/ChiseledBookShelfBlock.java b/net/minecraft/world/level/block/ChiseledBookShelfBlock.java
index eb315a50a83dc7230d7ad66f4daeb0d632679941..7bccf15310f6851875bfd77d4c66f4ce863b65e1 100644
--- a/net/minecraft/world/level/block/ChiseledBookShelfBlock.java
+++ b/net/minecraft/world/level/block/ChiseledBookShelfBlock.java
@@ -180,6 +180,27 @@ public class ChiseledBookShelfBlock extends BaseEntityBlock {
SLOT_OCCUPIED_PROPERTIES.forEach(property -> builder.add(property));
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean movedByPiston) {
+ if (!state.is(newState.getBlock())) {
+ if (level.getBlockEntity(pos) instanceof ChiseledBookShelfBlockEntity chiseledBookShelfBlockEntity && !chiseledBookShelfBlockEntity.isEmpty()) {
+ for (int i = 0; i < 6; i++) {
+ ItemStack item = chiseledBookShelfBlockEntity.getItem(i);
+ if (!item.isEmpty()) {
+ Containers.dropItemStack(level, pos.getX(), pos.getY(), pos.getZ(), item);
+ }
+ }
+
+ chiseledBookShelfBlockEntity.clearContent();
+ level.updateNeighbourForOutputSignal(pos, this);
+ }
+
+ super.onRemove(state, level, pos, newState, movedByPiston);
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
Containers.updateNeighboursAfterDestroy(state, level, pos);
diff --git a/net/minecraft/world/level/block/CrafterBlock.java b/net/minecraft/world/level/block/CrafterBlock.java
index a073188275456ee2eee776b149a14f68e4557f4a..89e69eb87d43d35002a352bdb187f503033f6630 100644
--- a/net/minecraft/world/level/block/CrafterBlock.java
+++ b/net/minecraft/world/level/block/CrafterBlock.java
@@ -129,6 +129,14 @@ public class CrafterBlock extends BaseEntityBlock {
}
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean movedByPiston) {
+ Containers.dropContentsOnDestroy(state, newState, level, pos);
+ super.onRemove(state, level, pos, newState, movedByPiston);
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
Containers.updateNeighboursAfterDestroy(state, level, pos);
diff --git a/net/minecraft/world/level/block/CreakingHeartBlock.java b/net/minecraft/world/level/block/CreakingHeartBlock.java
index 73885449a3316face50292756de2a3f298d3d111..333e18e4ead0bb6ef9681ce27ec156f79821af7c 100644
--- a/net/minecraft/world/level/block/CreakingHeartBlock.java
+++ b/net/minecraft/world/level/block/CreakingHeartBlock.java
@@ -152,6 +152,16 @@ public class CreakingHeartBlock extends BaseEntityBlock {
builder.add(AXIS, STATE, NATURAL);
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean movedByPiston) {
+ if (level.getBlockEntity(pos) instanceof CreakingHeartBlockEntity creakingHeartBlockEntity) {
+ creakingHeartBlockEntity.removeProtector(null);
+ }
+ super.onRemove(state, level, pos, newState, movedByPiston);
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
Containers.updateNeighboursAfterDestroy(state, level, pos);
diff --git a/net/minecraft/world/level/block/DecoratedPotBlock.java b/net/minecraft/world/level/block/DecoratedPotBlock.java
index f1570f1f4f7e43aacbcffef8bcf8ef27d46899da..6afd1c618112234ce4940105582a4399e20ab34c 100644
--- a/net/minecraft/world/level/block/DecoratedPotBlock.java
+++ b/net/minecraft/world/level/block/DecoratedPotBlock.java
@@ -165,6 +165,14 @@ public class DecoratedPotBlock extends BaseEntityBlock implements SimpleWaterlog
return new DecoratedPotBlockEntity(pos, state);
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean movedByPiston) {
+ Containers.dropContentsOnDestroy(state, newState, level, pos);
+ super.onRemove(state, level, pos, newState, movedByPiston);
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
Containers.updateNeighboursAfterDestroy(state, level, pos);
diff --git a/net/minecraft/world/level/block/DiodeBlock.java b/net/minecraft/world/level/block/DiodeBlock.java
index 558751ade918a92a1173096ccfeacf238f4260d0..94d35e4812705771756a0ee1a9b0255be75e3770 100644
--- a/net/minecraft/world/level/block/DiodeBlock.java
+++ b/net/minecraft/world/level/block/DiodeBlock.java
@@ -175,6 +175,16 @@ public abstract class DiodeBlock extends HorizontalDirectionalBlock {
this.updateNeighborsInFront(level, pos, state);
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!isMoving && !state.is(newState.getBlock())) {
+ super.onRemove(state, level, pos, newState, isMoving);
+ this.updateNeighborsInFront(level, pos, state);
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
if (!movedByPiston) {
diff --git a/net/minecraft/world/level/block/DispenserBlock.java b/net/minecraft/world/level/block/DispenserBlock.java
index 7ff6255fcd50344cd6ac7f8a67d61fd59c85e413..7a23d27ce76ae6b90d01c4dc7af416bb6b6516ea 100644
--- a/net/minecraft/world/level/block/DispenserBlock.java
+++ b/net/minecraft/world/level/block/DispenserBlock.java
@@ -147,6 +147,14 @@ public class DispenserBlock extends BaseEntityBlock {
return this.defaultBlockState().setValue(FACING, context.getNearestLookingDirection().getOpposite());
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ Containers.dropContentsOnDestroy(state, newState, level, pos);
+ super.onRemove(state, level, pos, newState, isMoving);
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
Containers.updateNeighboursAfterDestroy(state, level, pos);
diff --git a/net/minecraft/world/level/block/HopperBlock.java b/net/minecraft/world/level/block/HopperBlock.java
index 46a27f60ba407dacdac190b5e292ab3f1db5a078..d3535a9dc462d92a306aea981d7799d8d975f59d 100644
--- a/net/minecraft/world/level/block/HopperBlock.java
+++ b/net/minecraft/world/level/block/HopperBlock.java
@@ -125,6 +125,14 @@ public class HopperBlock extends BaseEntityBlock {
}
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ Containers.dropContentsOnDestroy(state, newState, level, pos);
+ super.onRemove(state, level, pos, newState, isMoving);
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
Containers.updateNeighboursAfterDestroy(state, level, pos);
diff --git a/net/minecraft/world/level/block/JukeboxBlock.java b/net/minecraft/world/level/block/JukeboxBlock.java
index 56cf6528f0cd9b8528490d7cee9a1f0e54108ef9..955854e5b3a18b8f1441145554a97c5454a65d12 100644
--- a/net/minecraft/world/level/block/JukeboxBlock.java
+++ b/net/minecraft/world/level/block/JukeboxBlock.java
@@ -73,6 +73,19 @@ public class JukeboxBlock extends BaseEntityBlock {
}
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!state.is(newState.getBlock())) {
+ if (level.getBlockEntity(pos) instanceof JukeboxBlockEntity jukeboxBlockEntity) {
+ jukeboxBlockEntity.popOutTheItem();
+ }
+
+ super.onRemove(state, level, pos, newState, isMoving);
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
Containers.updateNeighboursAfterDestroy(state, level, pos);
diff --git a/net/minecraft/world/level/block/LecternBlock.java b/net/minecraft/world/level/block/LecternBlock.java
index 5a9b601b7bf7e80b04ebd8f5c8b7d121031132c7..b714d3c7649384a8fdbe0a713e2193e241c80618 100644
--- a/net/minecraft/world/level/block/LecternBlock.java
+++ b/net/minecraft/world/level/block/LecternBlock.java
@@ -197,6 +197,36 @@ public class LecternBlock extends BaseEntityBlock {
changePowered(level, pos, state, false);
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!state.is(newState.getBlock())) {
+ if (state.getValue(HAS_BOOK)) {
+ this.popBook(state, level, pos);
+ }
+
+ if (state.getValue(POWERED)) {
+ updateBelow(level, pos, state);
+ }
+ super.onRemove(state, level, pos, newState, isMoving);
+ }
+ }
+
+ private void popBook(BlockState state, Level level, BlockPos pos) {
+ if (level.getBlockEntity(pos) instanceof LecternBlockEntity lecternBlockEntity) { // CraftBukkit - don't validate, type may be changed already // Leaves - the method with validate arg already removed by paper...
+ Direction direction = state.getValue(FACING);
+ ItemStack itemStack = lecternBlockEntity.getBook().copy();
+ if (itemStack.isEmpty()) return; // CraftBukkit - SPIGOT-5500
+ float f = 0.25F * direction.getStepX();
+ float f1 = 0.25F * direction.getStepZ();
+ net.minecraft.world.entity.item.ItemEntity itemEntity = new net.minecraft.world.entity.item.ItemEntity(level, pos.getX() + 0.5 + f, pos.getY() + 1, pos.getZ() + 0.5 + f1, itemStack);
+ itemEntity.setDefaultPickUpDelay();
+ level.addFreshEntity(itemEntity);
+ lecternBlockEntity.clearContent();
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
if (state.getValue(POWERED)) {
diff --git a/net/minecraft/world/level/block/LeverBlock.java b/net/minecraft/world/level/block/LeverBlock.java
index 76f2a29f37187344324d68941307d58e6343b6ae..3645ca9589aa1a74134180c9918a6f67bc64ce7a 100644
--- a/net/minecraft/world/level/block/LeverBlock.java
+++ b/net/minecraft/world/level/block/LeverBlock.java
@@ -125,6 +125,19 @@ public class LeverBlock extends FaceAttachedHorizontalDirectionalBlock {
}
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!isMoving && !state.is(newState.getBlock())) {
+ if (state.getValue(POWERED)) {
+ this.updateNeighbours(state, level, pos);
+ }
+
+ super.onRemove(state, level, pos, newState, isMoving);
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
if (!movedByPiston && state.getValue(POWERED)) {
diff --git a/net/minecraft/world/level/block/LightningRodBlock.java b/net/minecraft/world/level/block/LightningRodBlock.java
index 13b92472d50a41446b86c62ec31919fe0a953374..d567a7c303bf1baa92fc24ff47870d56c70907af 100644
--- a/net/minecraft/world/level/block/LightningRodBlock.java
+++ b/net/minecraft/world/level/block/LightningRodBlock.java
@@ -120,6 +120,18 @@ public class LightningRodBlock extends RodBlock implements SimpleWaterloggedBloc
}
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean movedByPiston) {
+ if (!state.is(newState.getBlock())) {
+ if (state.getValue(POWERED)) {
+ this.updateNeighbours(state, level, pos);
+ }
+ super.onRemove(state, level, pos, newState, movedByPiston);
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
if (state.getValue(POWERED)) {
diff --git a/net/minecraft/world/level/block/ObserverBlock.java b/net/minecraft/world/level/block/ObserverBlock.java
index bd2aa00ce8b78c16f6107064dd00bfbb072df0df..6db3a21bcc37ae79f82b19ee0a851f539d4a654d 100644
--- a/net/minecraft/world/level/block/ObserverBlock.java
+++ b/net/minecraft/world/level/block/ObserverBlock.java
@@ -127,6 +127,17 @@ public class ObserverBlock extends DirectionalBlock {
}
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!state.is(newState.getBlock())) {
+ if (state.getValue(POWERED) && level.getBlockTicks().hasScheduledTick(pos, this)) {
+ this.updateNeighborsInFront(level, pos, state.setValue(POWERED, Boolean.FALSE));
+ }
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
if (state.getValue(POWERED) && level.getBlockTicks().hasScheduledTick(pos, this)) {
diff --git a/net/minecraft/world/level/block/RedStoneWireBlock.java b/net/minecraft/world/level/block/RedStoneWireBlock.java
index 35dc47d5ba1a2659304ccc08010611438ccf04d8..04cc3c5a6ae0bea5f3a47ff7f9a7fe1f486294eb 100644
--- a/net/minecraft/world/level/block/RedStoneWireBlock.java
+++ b/net/minecraft/world/level/block/RedStoneWireBlock.java
@@ -363,6 +363,27 @@ public class RedStoneWireBlock extends Block {
}
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!isMoving && !state.is(newState.getBlock())) {
+ super.onRemove(state, level, pos, newState, isMoving);
+ for (Direction direction : Direction.values()) {
+ level.updateNeighborsAt(pos.relative(direction), this);
+ }
+
+ // Paper start - optimize redstone - replace call to updatePowerStrength
+ if (level.paperConfig().misc.redstoneImplementation == io.papermc.paper.configuration.WorldConfiguration.Misc.RedstoneImplementation.ALTERNATE_CURRENT) {
+ level.getWireHandler().onWireRemoved(pos, state); // Alternate Current
+ } else {
+ this.updateSurroundingRedstone(level, pos, state, null, false); // Vanilla/Eigencraft
+ }
+ // Paper end - optimize redstone
+ this.updateNeighborsOfNeighboringWires(level, pos);
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
if (!movedByPiston) {
diff --git a/net/minecraft/world/level/block/RedstoneTorchBlock.java b/net/minecraft/world/level/block/RedstoneTorchBlock.java
index 33e2f2de19208b7af6551132887e310744b4b702..d36c3bdb59bf9b9467d1a9807ab789b4c180010d 100644
--- a/net/minecraft/world/level/block/RedstoneTorchBlock.java
+++ b/net/minecraft/world/level/block/RedstoneTorchBlock.java
@@ -53,6 +53,15 @@ public class RedstoneTorchBlock extends BaseTorchBlock {
}
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!isMoving) {
+ this.notifyNeighbors(level, pos, state);
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
if (!movedByPiston) {
diff --git a/net/minecraft/world/level/block/SculkSensorBlock.java b/net/minecraft/world/level/block/SculkSensorBlock.java
index f0101e88140f480c1a94f899744991f78c9e3756..fa9cb4c40a41eea7fd63a4513d0b0f39067de9ba 100644
--- a/net/minecraft/world/level/block/SculkSensorBlock.java
+++ b/net/minecraft/world/level/block/SculkSensorBlock.java
@@ -129,6 +129,18 @@ public class SculkSensorBlock extends BaseEntityBlock implements SimpleWaterlogg
}
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean movedByPiston) {
+ if (!state.is(newState.getBlock())) {
+ if (getPhase(state) == SculkSensorPhase.ACTIVE) {
+ updateNeighbours(level, pos, state);
+ }
+ super.onRemove(state, level, pos, newState, movedByPiston);
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
if (getPhase(state) == SculkSensorPhase.ACTIVE) {
diff --git a/net/minecraft/world/level/block/SculkShriekerBlock.java b/net/minecraft/world/level/block/SculkShriekerBlock.java
index 757f8453e147875ab9f14d9726bb734ef27447c9..d0558d0e33f3d6e25af2dd71650d723e8997dae6 100644
--- a/net/minecraft/world/level/block/SculkShriekerBlock.java
+++ b/net/minecraft/world/level/block/SculkShriekerBlock.java
@@ -68,6 +68,16 @@ public class SculkShriekerBlock extends BaseEntityBlock implements SimpleWaterlo
super.stepOn(level, pos, state, entity);
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean movedByPiston) {
+ if (level instanceof ServerLevel serverLevel && state.getValue(SHRIEKING) && !state.is(newState.getBlock())) {
+ serverLevel.getBlockEntity(pos, BlockEntityType.SCULK_SHRIEKER).ifPresent(sculkShrieker -> sculkShrieker.tryRespond(serverLevel));
+ }
+ super.onRemove(state, level, pos, newState, movedByPiston);
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) {
if (state.getValue(SHRIEKING)) {
diff --git a/net/minecraft/world/level/block/ShulkerBoxBlock.java b/net/minecraft/world/level/block/ShulkerBoxBlock.java
index 45e48e6d225a2741cd615345711072610d728474..80520260ccb52935f3c1564c2f161bb148ba7baa 100644
--- a/net/minecraft/world/level/block/ShulkerBoxBlock.java
+++ b/net/minecraft/world/level/block/ShulkerBoxBlock.java
@@ -152,6 +152,19 @@ public class ShulkerBoxBlock extends BaseEntityBlock {
// Paper end - re-set loot table if it was cleared
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!state.is(newState.getBlock())) {
+ BlockEntity blockEntity = level.getBlockEntity(pos);
+ if (blockEntity instanceof ShulkerBoxBlockEntity) {
+ level.updateNeighbourForOutputSignal(pos, state.getBlock());
+ }
+ super.onRemove(state, level, pos, newState, isMoving);
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
Containers.updateNeighboursAfterDestroy(state, level, pos);
diff --git a/net/minecraft/world/level/block/TripWireBlock.java b/net/minecraft/world/level/block/TripWireBlock.java
index c8f793d1cdeef7e3e0d5fceb45a4507d542e4b33..27f382f6c663b2954a6fb966ece05ba021fcd6b1 100644
--- a/net/minecraft/world/level/block/TripWireBlock.java
+++ b/net/minecraft/world/level/block/TripWireBlock.java
@@ -108,6 +108,16 @@ public class TripWireBlock extends Block {
}
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (io.papermc.paper.configuration.GlobalConfiguration.get().blockUpdates.disableTripwireUpdates) return; // Paper - prevent adjacent tripwires from updating
+ if (!isMoving && !state.is(newState.getBlock())) {
+ this.updateSource(level, pos, state.setValue(POWERED, Boolean.TRUE));
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
if (io.papermc.paper.configuration.GlobalConfiguration.get().blockUpdates.disableTripwireUpdates) return; // Paper - prevent adjacent tripwires from updating
diff --git a/net/minecraft/world/level/block/TripWireHookBlock.java b/net/minecraft/world/level/block/TripWireHookBlock.java
index a92462c76a648e6c175b8c2ef3e925aba81ba774..b32760f1096581059418f479b060019f7dccbd67 100644
--- a/net/minecraft/world/level/block/TripWireHookBlock.java
+++ b/net/minecraft/world/level/block/TripWireHookBlock.java
@@ -245,6 +245,25 @@ public class TripWireHookBlock extends Block {
level.updateNeighborsAt(pos.relative(opposite), block, orientation);
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!isMoving && !state.is(newState.getBlock())) {
+ boolean attachedValue = state.getValue(ATTACHED);
+ boolean poweredValue = state.getValue(POWERED);
+ if (attachedValue || poweredValue) {
+ calculateState(level, pos, state, true, false, -1, null);
+ }
+
+ if (poweredValue) {
+ notifyNeighbors(this, level, pos, state.getValue(FACING));
+ }
+
+ super.onRemove(state, level, pos, newState, isMoving);
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
if (!movedByPiston) {
diff --git a/net/minecraft/world/level/block/entity/BlockEntityType.java b/net/minecraft/world/level/block/entity/BlockEntityType.java
index 386e6a48701b4c9256e33174123381a93d61e292..abade114c5b5051ce96b6489f08feb7e1cc774ee 100644
--- a/net/minecraft/world/level/block/entity/BlockEntityType.java
+++ b/net/minecraft/world/level/block/entity/BlockEntityType.java
@@ -263,7 +263,7 @@ public class BlockEntityType<T extends BlockEntity> {
}
public boolean isValid(BlockState state) {
- return this.validBlocks.contains(state.getBlock());
+ return org.leavesmc.leaves.LeavesConfig.modify.oldMC.updater.oldBlockRemoveBehaviour || this.validBlocks.contains(state.getBlock()); // Leaves - behaviour 1.21.1-
}
@Deprecated
diff --git a/net/minecraft/world/level/block/piston/MovingPistonBlock.java b/net/minecraft/world/level/block/piston/MovingPistonBlock.java
index 05bbc2e59384702439548a988e128a85f1adbe82..af516d5b6bd31de2c6a388ec8001126e2a351cf3 100644
--- a/net/minecraft/world/level/block/piston/MovingPistonBlock.java
+++ b/net/minecraft/world/level/block/piston/MovingPistonBlock.java
@@ -67,6 +67,18 @@ public class MovingPistonBlock extends BaseEntityBlock {
return createTickerHelper(blockEntityType, BlockEntityType.PISTON, PistonMovingBlockEntity::tick);
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!state.is(newState.getBlock())) {
+ BlockEntity blockEntity = level.getBlockEntity(pos);
+ if (blockEntity instanceof PistonMovingBlockEntity) {
+ ((PistonMovingBlockEntity)blockEntity).finalTick();
+ }
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
public void destroy(LevelAccessor level, BlockPos pos, BlockState state) {
BlockPos blockPos = pos.relative(state.getValue(FACING).getOpposite());
diff --git a/net/minecraft/world/level/block/piston/PistonHeadBlock.java b/net/minecraft/world/level/block/piston/PistonHeadBlock.java
index 6c789e56f21f01252c21786cfeb48d88485b5636..e24a61a4e2dac0159d52f07c93ddf860f4bfb8f7 100644
--- a/net/minecraft/world/level/block/piston/PistonHeadBlock.java
+++ b/net/minecraft/world/level/block/piston/PistonHeadBlock.java
@@ -78,6 +78,19 @@ public class PistonHeadBlock extends DirectionalBlock {
return super.playerWillDestroy(level, pos, state, player);
}
+ // Leaves start - behaviour 1.21.1-
+ @Override
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
+ if (!state.is(newState.getBlock())) {
+ super.onRemove(state, level, pos, newState, isMoving);
+ BlockPos blockPos = pos.relative(state.getValue(FACING).getOpposite());
+ if (this.isFittingBase(state, level.getBlockState(blockPos))) {
+ level.destroyBlock(blockPos, true);
+ }
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
@Override
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
BlockPos blockPos = pos.relative(state.getValue(FACING).getOpposite());
diff --git a/net/minecraft/world/level/block/state/BlockBehaviour.java b/net/minecraft/world/level/block/state/BlockBehaviour.java
index be66f0f1cb1b0bcec8f9489a1fdd8777df1adb6b..67719dce9017a4c86a70b62fb660bddc636d5582 100644
--- a/net/minecraft/world/level/block/state/BlockBehaviour.java
+++ b/net/minecraft/world/level/block/state/BlockBehaviour.java
@@ -171,6 +171,15 @@ public abstract class BlockBehaviour implements FeatureElement {
org.spigotmc.AsyncCatcher.catchOp("block onPlace"); // Spigot
}
+ // Leaves start - behaviour 1.21.1-
+ protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean movedByPiston) {
+ org.spigotmc.AsyncCatcher.catchOp("block remove"); // Spigot
+ if (state.hasBlockEntity() && !state.is(newState.getBlock())) {
+ level.removeBlockEntity(pos);
+ }
+ }
+ // Leaves end - behaviour 1.21.1-
+
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) {
}
@@ -867,6 +876,12 @@ public abstract class BlockBehaviour implements FeatureElement {
// CraftBukkit end
}
+ // Leaves start - behaviour 1.21.1-
+ public void onRemove(Level level, BlockPos pos, BlockState newState, boolean movedByPiston) {
+ this.getBlock().onRemove(this.asState(), level, pos, newState, movedByPiston);
+ }
+ // Leaves end - behaviour 1.21.1-
+
public void affectNeighborsAfterRemoval(ServerLevel level, BlockPos pos, boolean movedByPiston) {
this.getBlock().affectNeighborsAfterRemoval(this.asState(), level, pos, movedByPiston);
}
diff --git a/net/minecraft/world/level/chunk/LevelChunk.java b/net/minecraft/world/level/chunk/LevelChunk.java
index 0e22116fefcbdbf2049b7ec285b35fd03c723dc5..45386818312fbd99bbcb72d14ad9e54cd864a2a8 100644
--- a/net/minecraft/world/level/chunk/LevelChunk.java
+++ b/net/minecraft/world/level/chunk/LevelChunk.java
@@ -396,20 +396,26 @@ public class LevelChunk extends ChunkAccess implements ca.spottedleaf.moonrise.p
boolean flag = !blockState.is(block);
boolean flag1 = (flags & 64) != 0;
boolean flag2 = (flags & 256) == 0;
- if (flag && blockState.hasBlockEntity()) {
- if (!this.level.isClientSide && flag2) {
- BlockEntity blockEntity = this.level.getBlockEntity(pos);
- if (blockEntity != null) {
- blockEntity.preRemoveSideEffects(pos, blockState);
+ // Leaves start - behaviour 1.21.1-
+ if (!org.leavesmc.leaves.LeavesConfig.modify.oldMC.updater.oldBlockRemoveBehaviour) {
+ if (flag && blockState.hasBlockEntity()) {
+ if (!this.level.isClientSide && flag2) {
+ BlockEntity blockEntity = this.level.getBlockEntity(pos);
+ if (blockEntity != null) {
+ blockEntity.preRemoveSideEffects(pos, blockState);
+ }
}
- }
- this.removeBlockEntity(pos);
- }
+ this.removeBlockEntity(pos);
+ }
- if ((flag || block instanceof BaseRailBlock) && this.level instanceof ServerLevel serverLevel && ((flags & 1) != 0 || flag1)) {
- blockState.affectNeighborsAfterRemoval(serverLevel, pos, flag1);
+ if ((flag || block instanceof BaseRailBlock) && this.level instanceof ServerLevel serverLevel && ((flags & 1) != 0 || flag1)) {
+ blockState.affectNeighborsAfterRemoval(serverLevel, pos, flag1);
+ }
+ } else {
+ blockState.onRemove(this.level, pos, state, flag1);
}
+ // Leaves end - behaviour 1.21.1-
if (!section.getBlockState(i, i1, i2).is(block)) {
return null;
| 0 | 0.876375 | 1 | 0.876375 | game-dev | MEDIA | 0.991773 | game-dev | 0.857231 | 1 | 0.857231 |
ServUO/ServUO | 3,079 | Scripts/Mobiles/Normal/TheButcher.cs | using System;
using Server.Items;
namespace Server.Mobiles
{
[CorpseName("an butcher corpse")]
public class TheButcher : BaseCreature
{
[Constructable]
public TheButcher()
: base(AIType.AI_Necro, FightMode.Closest, 10, 1, 0.2, 0.4)
{
Name = NameList.RandomName("daemon");
Title = "the Butcher";
Hue = 2075;
Body = 306;
BaseSoundID = 0x2A7;
SetStr(250, 300);
SetDex(90, 130);
SetInt(800, 1000);
SetHits(700, 1000);
SetDamage(15, 27);
SetDamageType(ResistanceType.Physical, 20);
SetDamageType(ResistanceType.Cold, 40);
SetDamageType(ResistanceType.Energy, 40);
SetResistance(ResistanceType.Physical, 70, 80);
SetResistance(ResistanceType.Fire, 25, 40);
SetResistance(ResistanceType.Cold, 60, 70);
SetResistance(ResistanceType.Poison, 60, 70);
SetResistance(ResistanceType.Energy, 35, 40);
SetSkill(SkillName.DetectHidden, 80.0);
SetSkill(SkillName.Meditation, 120.0);
SetSkill(SkillName.Poisoning, 160.0);
SetSkill(SkillName.MagicResist, 180.0, 200.0);
SetSkill(SkillName.Tactics, 100.0);
SetSkill(SkillName.Wrestling, 75.0, 80.0);
SetSkill(SkillName.Necromancy, 100.0, 110.0);
SetSkill(SkillName.SpiritSpeak, 95.0, 105.0);
Fame = 24000;
Karma = -24000;
VirtualArmor = 49;
if (Utility.RandomDouble() < 0.2)
PackItem(new PumpkinCarvingKit());
}
public TheButcher(Serial serial)
: base(serial)
{
}
public override bool IgnoreYoungProtection { get { return Core.ML; } }
public override bool AutoDispel { get { return true; } }
public override bool BardImmune { get { return !Core.SE; } }
public override bool Unprovokable { get { return Core.SE; } }
public override bool AreaPeaceImmune { get { return Core.SE; } }
public override Poison PoisonImmune { get { return Poison.Lethal; } }
public override Poison HitPoison { get { return 0.8 >= Utility.RandomDouble() ? Poison.Greater : Poison.Deadly; } }
public override int TreasureMapLevel { get { return 1; } }
public override bool AlwaysMurderer { get { return true; } }
public override WeaponAbility GetWeaponAbility()
{
return Utility.RandomBool() ? WeaponAbility.MortalStrike : WeaponAbility.BleedAttack;
}
public override void GenerateLoot()
{
AddLoot(LootPack.UltraRich, 2);
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
| 0 | 0.915343 | 1 | 0.915343 | game-dev | MEDIA | 0.976579 | game-dev | 0.877451 | 1 | 0.877451 |
osudroid/osu-droid | 3,523 | src/com/osudroid/ui/v2/modmenu/ModMenuToggle.kt | package com.osudroid.ui.v2.modmenu
import com.osudroid.multiplayer.*
import com.osudroid.utils.searchContiguously
import com.reco1l.andengine.*
import com.reco1l.andengine.buffered.*
import com.reco1l.andengine.component.*
import com.reco1l.andengine.container.*
import com.reco1l.andengine.modifier.*
import com.reco1l.andengine.shape.*
import com.reco1l.andengine.text.*
import com.reco1l.andengine.ui.*
import com.rian.osu.mods.*
import ru.nsu.ccfit.zuev.osu.*
class ModMenuToggle(var mod: Mod): UIButton() {
/**
* Whether the [Mod] represented by this [ModMenuToggle] is incompatible with one or more enabled [Mod]s.
*/
var hasIncompatibility = false
set(value) {
if (field != value) {
field = value
applyCompatibilityState()
}
}
init {
orientation = Orientation.Horizontal
width = FillParent
spacing = 8f
cullingMode = CullingMode.CameraBounds
background = UIBox().apply {
cornerRadius = 12f
// Sharing the same VBO across all toggles to reduce memory usage.
buffer = sharedButtonVBO
}
+ModIcon(mod).apply {
width = 38f
height = 38f
anchor = Anchor.CenterLeft
origin = Anchor.CenterLeft
}
linearContainer {
orientation = Orientation.Vertical
width = FillParent
anchor = Anchor.CenterLeft
origin = Anchor.CenterLeft
text {
text = mod.name
font = ResourceManager.getInstance().getFont("smallFont")
buffer = sharedTextCB
}
text {
width = FillParent
font = ResourceManager.getInstance().getFont("xs")
text = mod.description
clipToBounds = true
alpha = 0.75f
buffer = sharedTextCB
}
}
onActionUp = {
if (isSelected) {
ModMenu.removeMod(mod)
ResourceManager.getInstance().getSound("check-off")?.play()
} else {
ModMenu.addMod(mod)
ResourceManager.getInstance().getSound("check-on")?.play()
}
}
updateVisibility()
}
@JvmOverloads
fun updateVisibility(searchTerm: String = "") {
var shouldBeVisible = if (Multiplayer.isMultiplayer && Multiplayer.room != null) {
mod.isValidForMultiplayer && (Multiplayer.isRoomHost ||
(Multiplayer.room!!.gameplaySettings.isFreeMod && mod.isValidForMultiplayerAsFreeMod))
} else {
true
}
if (searchTerm.isNotBlank()) {
shouldBeVisible = shouldBeVisible &&
(mod.acronym.equals(searchTerm, true) ||
mod.name.searchContiguously(searchTerm, true))
}
isVisible = shouldBeVisible
}
fun applyCompatibilityState() {
// Intentionally not using isEnabled here, otherwise the button will not be clickable.
clearModifiers(ModifierType.Alpha)
fadeTo(if (hasIncompatibility) 0.5f else 1f, 0.2f)
}
companion object {
private val sharedButtonVBO = UIBox.BoxVBO(12f, UICircle.approximateSegments(12f, 12f, 90f), PaintStyle.Fill)
private val sharedTextCB = CompoundBuffer(UIText.TextTextureBuffer(256), UIText.TextVertexBuffer(256)).asSharedDynamically()
}
} | 0 | 0.861317 | 1 | 0.861317 | game-dev | MEDIA | 0.795659 | game-dev,desktop-app | 0.904883 | 1 | 0.904883 |
ggnkua/Atari_ST_Sources | 3,922 | C/Markus Storcz/Sysgem.250/PRINTER.C | /* ------------------------------------------------------------------- *
* Module Version : 2.00 *
* Author : Andrea Pietsch *
* Programming Language : Pure-C *
* Copyright : (c) 1994, Andrea Pietsch, 56727 Mayen *
* ------------------------------------------------------------------- */
#include "kernel.h"
#include "sgem.h"
#include <string.h>
#include <stdlib.h>
/* ------------------------------------------------------------------- */
EXTERN SYSGEM sysgem;
/* ------------------------------------------------------------------- */
LOCAL BYTE dev_tab [20][48];
LOCAL LONG result_id = 0L;
LOCAL INT result_bt = 0;
LOCAL INT result_dv = 0;
LOCAL INT anz_dev = 0;
/* ------------------------------------------------------------------- */
#define rsc_main sysgem.cycle_win
/* ------------------------------------------------------------------- */
LOCAL INT sgem_hdl_device ( INT msg, INT button, DIALOG_INFO *inf )
{
switch ( msg )
{
case SG_START : LinkSlider ( rsc_main, CY_UP, CY_DN, CY_SHOW, CY_HIDE, anz_dev, CY_BOX, &dev_tab [0][0], 48, FALSE );
SelectSldItem ( rsc_main, CY_BOX, result_dv, FALSE );
break;
case SG_SLIDER : if (( button >= 0 ) && ( button != result_dv ))
{
result_dv = button;
SelectSldItem ( rsc_main, CY_BOX, result_dv, TRUE );
}
break;
case SG_QUIT : UnLinkSlider ( rsc_main, CY_BOX );
break;
case SG_END : result_id = inf->id;
result_bt = button;
break;
}
return ( SG_CONT );
}
/* ------------------------------------------------------------------- */
LOCAL BOOL BeginDevice ( LONG win_id, OBJECT *tree, INT edit, BYTE *title )
{
return ( WindowDialog ( win_id, -1, -1, title, "", FALSE, TRUE, tree, NULL, edit, NULL, sgem_hdl_device ));
}
/* ------------------------------------------------------------------- */
LOCAL INT HandleDevice ( LONG win_id )
{
if ( find_window ( -1, win_id ) == NULL ) return ( -1 );
forever
{
result_id = 0L;
result_bt = 0;
HandleEvents ();
if ( result_id == win_id )
{
return ( result_bt );
}
}
}
/* ------------------------------------------------------------------- */
LOCAL VOID FinishDevice ( LONG win_id )
{
WINDOW *win;
win = find_window ( -1, win_id );
if ( win != NULL )
{
DestroyWindow ( win, TRUE );
}
}
/* ------------------------------------------------------------------- */
INT SelectPrinter ( VOID )
{
INT i;
INT open;
BYTE s [100];
anz_dev = 0;
result_dv = 0;
result_id = 0L;
result_bt = 0;
memset ( &dev_tab, 0, sizeof ( dev_tab ));
if ( ! vq_gdos ()) return ( -1 );
for ( i = 21; i < 100; i++ )
{
VqtDevice ( i, &open, s );
if ( length ( s ) > 0 )
{
sprintf ( dev_tab [anz_dev], " %2d %-36.36s ", i, s );
anz_dev++;
}
memset ( s, 0, sizeof ( s ));
}
if ( anz_dev == 0 ) return ( -1 );
if ( sysgem.english )
{
ChangeButton ( rsc_main, CY_ABORT, "[Abort" );
}
else
{
ChangeButton ( rsc_main, CY_ABORT, "[Abbruch" );
}
if ( BeginDevice ( 'xdeV', rsc_main, 0, (( sysgem.english != FALSE ) ? "Select Device" : "|Gerteauswahl:" )))
{
i = HandleDevice ( 'xdeV' );
FinishDevice ( 'xdeV' );
if ( i == CY_OK )
{
dev_tab [result_dv][3] = 0;
return ( atoi ( &dev_tab [result_dv][1] ));
}
}
return ( -1 );
}
/* ------------------------------------------------------------------- */
| 0 | 0.789441 | 1 | 0.789441 | game-dev | MEDIA | 0.304102 | game-dev | 0.922015 | 1 | 0.922015 |
pmmp/PocketMine-MP | 2,167 | src/crafting/PotionContainerChangeRecipe.php | <?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\crafting;
use pocketmine\data\bedrock\item\SavedItemData;
use pocketmine\item\Item;
use pocketmine\world\format\io\GlobalItemDataHandlers;
class PotionContainerChangeRecipe implements BrewingRecipe{
public function __construct(
private string $inputItemId,
private RecipeIngredient $ingredient,
private string $outputItemId
){}
public function getInputItemId() : string{
return $this->inputItemId;
}
public function getIngredient() : RecipeIngredient{
return $this->ingredient;
}
public function getOutputItemId() : string{
return $this->outputItemId;
}
public function getResultFor(Item $input) : ?Item{
//TODO: this is a really awful hack, but there isn't another way for now
//this relies on transforming the serialized item's ID, relying on the target item type's data being the same as the input.
//This is the same assumption previously made using ItemFactory::get(), except it was less obvious how bad it was.
//The other way is to bake the actual Potion class types into here, which isn't great for data-driving stuff.
//We need a better solution for this.
$data = GlobalItemDataHandlers::getSerializer()->serializeType($input);
return $data->getName() === $this->getInputItemId() ?
GlobalItemDataHandlers::getDeserializer()->deserializeType(new SavedItemData($this->getOutputItemId(), $data->getMeta(), $data->getBlock(), $data->getTag())) :
null;
}
}
| 0 | 0.894876 | 1 | 0.894876 | game-dev | MEDIA | 0.717425 | game-dev | 0.9272 | 1 | 0.9272 |
jarjin/FinalFramework | 3,001 | FirClient/Assets/ToLua/Source/Generate/FirClient_Manager_SoundManagerWrap.cs | //this source code was auto-generated by tolua#, do not modify it
using System;
using LuaInterface;
public class FirClient_Manager_SoundManagerWrap
{
public static void Register(LuaState L)
{
L.BeginClass(typeof(FirClient.Manager.SoundManager), typeof(FirClient.Manager.BaseManager));
L.RegFunction("CanPlayBackSound", new LuaCSFunction(CanPlayBackSound));
L.RegFunction("PlayBacksound", new LuaCSFunction(PlayBacksound));
L.RegFunction("CanPlaySoundEffect", new LuaCSFunction(CanPlaySoundEffect));
L.RegFunction("Play", new LuaCSFunction(Play));
L.RegFunction("New", new LuaCSFunction(_CreateFirClient_Manager_SoundManager));
L.RegFunction("__tostring", new LuaCSFunction(ToLua.op_ToString));
L.EndClass();
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _CreateFirClient_Manager_SoundManager(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 0)
{
FirClient.Manager.SoundManager obj = new FirClient.Manager.SoundManager();
ToLua.PushObject(L, obj);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to ctor method: FirClient.Manager.SoundManager.New");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int CanPlayBackSound(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
FirClient.Manager.SoundManager obj = (FirClient.Manager.SoundManager)ToLua.CheckObject<FirClient.Manager.SoundManager>(L, 1);
bool o = obj.CanPlayBackSound();
LuaDLL.lua_pushboolean(L, o);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int PlayBacksound(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 3);
FirClient.Manager.SoundManager obj = (FirClient.Manager.SoundManager)ToLua.CheckObject<FirClient.Manager.SoundManager>(L, 1);
string arg0 = ToLua.CheckString(L, 2);
bool arg1 = LuaDLL.luaL_checkboolean(L, 3);
obj.PlayBacksound(arg0, arg1);
return 0;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int CanPlaySoundEffect(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
FirClient.Manager.SoundManager obj = (FirClient.Manager.SoundManager)ToLua.CheckObject<FirClient.Manager.SoundManager>(L, 1);
bool o = obj.CanPlaySoundEffect();
LuaDLL.lua_pushboolean(L, o);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int Play(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 2);
FirClient.Manager.SoundManager obj = (FirClient.Manager.SoundManager)ToLua.CheckObject<FirClient.Manager.SoundManager>(L, 1);
string arg0 = ToLua.CheckString(L, 2);
obj.Play(arg0);
return 0;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
}
| 0 | 0.665821 | 1 | 0.665821 | game-dev | MEDIA | 0.740339 | game-dev | 0.892125 | 1 | 0.892125 |
TerraFirmaCraft/TerraFirmaCraft | 5,239 | src/main/java/net/dries007/tfc/common/blocks/plant/coral/TFCSeaPickleBlock.java | /*
* Licensed under the EUPL, Version 1.2.
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12
*/
package net.dries007.tfc.common.blocks.plant.coral;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockBehaviour;
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 net.minecraft.world.level.block.state.properties.IntegerProperty;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.Nullable;
import net.dries007.tfc.common.blocks.TFCBlockStateProperties;
import net.dries007.tfc.common.fluids.FluidHelpers;
import net.dries007.tfc.common.fluids.FluidProperty;
import net.dries007.tfc.common.fluids.IFluidLoggable;
import net.dries007.tfc.common.fluids.TFCFluids;
import net.dries007.tfc.util.Helpers;
/**
* {@link net.minecraft.world.level.block.SeaPickleBlock}
*/
public class TFCSeaPickleBlock extends Block implements IFluidLoggable
{
public static final IntegerProperty PICKLES = BlockStateProperties.PICKLES;
public static final FluidProperty FLUID = TFCBlockStateProperties.SALT_WATER;
protected static final VoxelShape ONE_AABB = Block.box(6.0D, 0.0D, 6.0D, 10.0D, 6.0D, 10.0D);
protected static final VoxelShape TWO_AABB = Block.box(3.0D, 0.0D, 3.0D, 13.0D, 6.0D, 13.0D);
protected static final VoxelShape THREE_AABB = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 6.0D, 14.0D);
protected static final VoxelShape FOUR_AABB = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 7.0D, 14.0D);
public static boolean isDead(BlockState state)
{
FluidProperty property = ((TFCSeaPickleBlock) state.getBlock()).getFluidProperty();
return state.getValue(property) == property.keyFor(Fluids.EMPTY);
}
public TFCSeaPickleBlock(BlockBehaviour.Properties properties)
{
super(properties);
registerDefaultState(getStateDefinition().any().setValue(PICKLES, 1));
}
@Nullable
@Override
public BlockState getStateForPlacement(BlockPlaceContext context)
{
BlockState blockstate = context.getLevel().getBlockState(context.getClickedPos());
if (Helpers.isBlock(blockstate, this))
{
return blockstate.setValue(PICKLES, Math.min(4, blockstate.getValue(PICKLES) + 1));
}
else
{
FluidState fluidstate = context.getLevel().getFluidState(context.getClickedPos());
boolean flag = fluidstate.getType() == TFCFluids.SALT_WATER.getSource();
return defaultBlockState().setValue(getFluidProperty(), flag ? getFluidProperty().keyFor(TFCFluids.SALT_WATER.getSource()) : getFluidProperty().keyFor(Fluids.EMPTY));
}
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder)
{
builder.add(PICKLES, getFluidProperty());
}
@Override
protected BlockState updateShape(BlockState state, Direction facing, BlockState facingState, LevelAccessor level, BlockPos currentPos, BlockPos facingPos)
{
FluidHelpers.tickFluid(level, currentPos, state);
return !state.canSurvive(level, currentPos) ? Blocks.AIR.defaultBlockState() : super.updateShape(state, facing, facingState, level, currentPos, facingPos);
}
@Override
public FluidState getFluidState(BlockState state)
{
return IFluidLoggable.super.getFluidState(state);
}
@Override
protected boolean canBeReplaced(BlockState state, BlockPlaceContext useContext)
{
return useContext.getItemInHand().getItem() == this.asItem() && state.getValue(PICKLES) < 4 || super.canBeReplaced(state, useContext);
}
@Override
protected boolean canSurvive(BlockState state, LevelReader level, BlockPos pos)
{
BlockPos blockpos = pos.below();
return mayPlaceOn(level.getBlockState(blockpos), level, blockpos);
}
@Override
protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context)
{
return switch (state.getValue(PICKLES))
{
case 2 -> TWO_AABB;
case 3 -> THREE_AABB;
case 4 -> FOUR_AABB;
default -> ONE_AABB;
};
}
@Override
public FluidProperty getFluidProperty()
{
return FLUID;
}
protected boolean mayPlaceOn(BlockState state, BlockGetter level, BlockPos pos)
{
return !state.getCollisionShape(level, pos).getFaceShape(Direction.UP).isEmpty() || state.isFaceSturdy(level, pos, Direction.UP);
}
}
| 0 | 0.908328 | 1 | 0.908328 | game-dev | MEDIA | 0.99458 | game-dev | 0.93551 | 1 | 0.93551 |
TeamGalacticraft/Galacticraft | 3,874 | src/main/java/dev/galacticraft/api/component/GCDataComponents.java | /*
* Copyright (c) 2019-2025 Team Galacticraft
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.galacticraft.api.component;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import dev.galacticraft.api.rocket.RocketData;
import dev.galacticraft.mod.Constant;
import dev.galacticraft.mod.util.StreamCodecs;
import net.minecraft.core.Registry;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.ExtraCodecs;
import java.util.function.UnaryOperator;
public class GCDataComponents {
public static final DataComponentType<RocketData> ROCKET_DATA = register("rocket_data", b -> b
.persistent(RocketData.CODEC).networkSynchronized(RocketData.STREAM_CODEC));
public static final DataComponentType<Long> AMOUNT = register("amount", b -> b
.persistent(Codec.LONG).networkSynchronized(StreamCodecs.LONG));
public static final DataComponentType<Integer> COLOR = register("color", b -> b
.persistent(ExtraCodecs.NON_NEGATIVE_INT).networkSynchronized(ByteBufCodecs.INT));
public static final DataComponentType<Integer> TICKS_UNTIL_COOL = register("ticks_until_cool", b -> b
.persistent(ExtraCodecs.NON_NEGATIVE_INT).networkSynchronized(ByteBufCodecs.INT));
public static final DataComponentType<Boolean> CREATIVE = register("creative", b -> b
.persistent(Codec.BOOL).networkSynchronized(ByteBufCodecs.BOOL));
public static final DataComponentType<ResourceKey<?>> KEY = register("key", b -> b
.persistent(RecordCodecBuilder.create(i ->
i.group(
ResourceLocation.CODEC.fieldOf("registry").forGetter(ResourceKey::registry),
ResourceLocation.CODEC.fieldOf("location").forGetter(ResourceKey::location)
).apply(i, (r, l) -> ResourceKey.create(ResourceKey.createRegistryKey(r), l))
)).networkSynchronized(StreamCodec.composite(
ResourceLocation.STREAM_CODEC,
ResourceKey::registry,
ResourceLocation.STREAM_CODEC,
ResourceKey::location,
(r, l) -> ResourceKey.create(ResourceKey.createRegistryKey(r), l)
)));
private static <T> DataComponentType<T> register(String id, UnaryOperator<DataComponentType.Builder<T>> op) {
return Registry.register(BuiltInRegistries.DATA_COMPONENT_TYPE, Constant.id(id), op.apply(DataComponentType.builder()).build());
}
public static void init() {
}
}
| 0 | 0.610531 | 1 | 0.610531 | game-dev | MEDIA | 0.982685 | game-dev | 0.76759 | 1 | 0.76759 |
foxgame/W3Rebuild | 2,071 | Client/Assets/Scripts/Data/W3ForceManager.cs | using UnityEngine;
using System;
using System.Collections.Generic;
public class W3Force
{
public int id;
public List<int> players;
}
public class W3ForceManager : SingletonMono< W3ForceManager >
{
public int forceID = 0;
public List< W3Force > forces = new List< W3Force >();
public int createForce()
{
forceID++;
W3Force t = new W3Force();
t.id = forceID;
return t.id;
}
public void destroyForce( int id )
{
for ( int i = 0 ; i < forces.Count ; i++ )
{
if ( forces[ i ].id == id )
{
forces.RemoveAt( i );
return;
}
}
}
public void forceAddPlayer( int id , int pid )
{
for ( int i = 0 ; i < forces.Count ; i++ )
{
if ( forces[ i ].id == id )
{
forces[ i ].players.Add( pid );
return;
}
}
}
public void forceRemovePlayer( int id , int pid )
{
for ( int i = 0 ; i < forces.Count ; i++ )
{
if ( forces[ i ].id == id )
{
for ( int j = 0 ; j < forces[ i ].players.Count ; j++ )
{
if ( forces[ i ].players[ j ] == pid )
{
forces[ i ].players.RemoveAt( j );
return;
}
}
return;
}
}
}
public void forceClear( int id )
{
for ( int i = 0 ; i < forces.Count ; i++ )
{
if ( forces[ i ].id == id )
{
forces[ i ].players.Clear();
return;
}
}
}
public void forceEnumPlayers( int id , int countLimit )
{
}
public void forceEnumAllies( int id , int pid , int countLimit )
{
}
public void forceEnumEnemies( int id , int pid , int countLimit )
{
}
public void forForce( int id ,BJCode code )
{
}
}
| 0 | 0.688364 | 1 | 0.688364 | game-dev | MEDIA | 0.886056 | game-dev | 0.803853 | 1 | 0.803853 |
Jeija/spheretest | 9,017 | src/mapgen_flat.cpp | /*
Minetest
Copyright (C) 2010-2015 kwolekr, Ryan Kwolek <kwolekr@minetest.net>
Copyright (C) 2010-2015 paramat, Matt Gregory
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 2.1 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "mapgen.h"
#include "voxel.h"
#include "noise.h"
#include "mapblock.h"
#include "mapnode.h"
#include "map.h"
#include "content_sao.h"
#include "nodedef.h"
#include "voxelalgorithms.h"
//#include "profiler.h" // For TimeTaker
#include "settings.h" // For g_settings
#include "emerge.h"
#include "dungeongen.h"
#include "cavegen.h"
#include "treegen.h"
#include "mg_biome.h"
#include "mg_ore.h"
#include "mg_decoration.h"
#include "mapgen_flat.h"
FlagDesc flagdesc_mapgen_flat[] = {
{"lakes", MGFLAT_LAKES},
{"hills", MGFLAT_HILLS},
{NULL, 0}
};
///////////////////////////////////////////////////////////////////////////////////////
MapgenFlat::MapgenFlat(int mapgenid, MapgenFlatParams *params, EmergeManager *emerge)
: MapgenBasic(mapgenid, params, emerge)
{
this->spflags = params->spflags;
this->ground_level = params->ground_level;
this->large_cave_depth = params->large_cave_depth;
this->cave_width = params->cave_width;
this->lake_threshold = params->lake_threshold;
this->lake_steepness = params->lake_steepness;
this->hill_threshold = params->hill_threshold;
this->hill_steepness = params->hill_steepness;
//// 2D noise
noise_terrain = new Noise(¶ms->np_terrain, seed, csize.X, csize.Z);
noise_filler_depth = new Noise(¶ms->np_filler_depth, seed, csize.X, csize.Z);
MapgenBasic::np_cave1 = params->np_cave1;
MapgenBasic::np_cave2 = params->np_cave2;
}
MapgenFlat::~MapgenFlat()
{
delete noise_terrain;
delete noise_filler_depth;
}
MapgenFlatParams::MapgenFlatParams()
{
spflags = 0;
ground_level = 8;
large_cave_depth = -33;
cave_width = 0.2;
lake_threshold = -0.45;
lake_steepness = 48.0;
hill_threshold = 0.45;
hill_steepness = 64.0;
np_terrain = NoiseParams(0, 1, v3f(600, 600, 600), 7244, 5, 0.6, 2.0);
np_filler_depth = NoiseParams(0, 1.2, v3f(150, 150, 150), 261, 3, 0.7, 2.0);
np_cave1 = NoiseParams(0, 12, v3f(61, 61, 61), 52534, 3, 0.5, 2.0);
np_cave2 = NoiseParams(0, 12, v3f(67, 67, 67), 10325, 3, 0.5, 2.0);
}
void MapgenFlatParams::readParams(const Settings *settings)
{
settings->getFlagStrNoEx("mgflat_spflags", spflags, flagdesc_mapgen_flat);
settings->getS16NoEx("mgflat_ground_level", ground_level);
settings->getS16NoEx("mgflat_large_cave_depth", large_cave_depth);
settings->getFloatNoEx("mgflat_cave_width", cave_width);
settings->getFloatNoEx("mgflat_lake_threshold", lake_threshold);
settings->getFloatNoEx("mgflat_lake_steepness", lake_steepness);
settings->getFloatNoEx("mgflat_hill_threshold", hill_threshold);
settings->getFloatNoEx("mgflat_hill_steepness", hill_steepness);
settings->getNoiseParams("mgflat_np_terrain", np_terrain);
settings->getNoiseParams("mgflat_np_filler_depth", np_filler_depth);
settings->getNoiseParams("mgflat_np_cave1", np_cave1);
settings->getNoiseParams("mgflat_np_cave2", np_cave2);
}
void MapgenFlatParams::writeParams(Settings *settings) const
{
settings->setFlagStr("mgflat_spflags", spflags, flagdesc_mapgen_flat, U32_MAX);
settings->setS16("mgflat_ground_level", ground_level);
settings->setS16("mgflat_large_cave_depth", large_cave_depth);
settings->setFloat("mgflat_cave_width", cave_width);
settings->setFloat("mgflat_lake_threshold", lake_threshold);
settings->setFloat("mgflat_lake_steepness", lake_steepness);
settings->setFloat("mgflat_hill_threshold", hill_threshold);
settings->setFloat("mgflat_hill_steepness", hill_steepness);
settings->setNoiseParams("mgflat_np_terrain", np_terrain);
settings->setNoiseParams("mgflat_np_filler_depth", np_filler_depth);
settings->setNoiseParams("mgflat_np_cave1", np_cave1);
settings->setNoiseParams("mgflat_np_cave2", np_cave2);
}
/////////////////////////////////////////////////////////////////
int MapgenFlat::getSpawnLevelAtPoint(v2s16 p)
{
s16 level_at_point = ground_level;
float n_terrain = NoisePerlin2D(&noise_terrain->np, p.X, p.Y, seed);
if ((spflags & MGFLAT_LAKES) && n_terrain < lake_threshold) {
level_at_point = ground_level -
(lake_threshold - n_terrain) * lake_steepness;
} else if ((spflags & MGFLAT_HILLS) && n_terrain > hill_threshold) {
level_at_point = ground_level +
(n_terrain - hill_threshold) * hill_steepness;
}
if (ground_level < water_level) // Ocean world, allow spawn in water
return MYMAX(level_at_point, water_level);
else if (level_at_point > water_level)
return level_at_point; // Spawn on land
else
return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point
}
void MapgenFlat::makeChunk(BlockMakeData *data)
{
// Pre-conditions
assert(data->vmanip);
assert(data->nodedef);
assert(data->blockpos_requested.X >= data->blockpos_min.X &&
data->blockpos_requested.Y >= data->blockpos_min.Y &&
data->blockpos_requested.Z >= data->blockpos_min.Z);
assert(data->blockpos_requested.X <= data->blockpos_max.X &&
data->blockpos_requested.Y <= data->blockpos_max.Y &&
data->blockpos_requested.Z <= data->blockpos_max.Z);
this->generating = true;
this->vm = data->vmanip;
this->ndef = data->nodedef;
//TimeTaker t("makeChunk");
v3s16 blockpos_min = data->blockpos_min;
v3s16 blockpos_max = data->blockpos_max;
node_min = blockpos_min * MAP_BLOCKSIZE;
node_max = (blockpos_max + v3s16(1, 1, 1)) * MAP_BLOCKSIZE - v3s16(1, 1, 1);
full_node_min = (blockpos_min - 1) * MAP_BLOCKSIZE;
full_node_max = (blockpos_max + 2) * MAP_BLOCKSIZE - v3s16(1, 1, 1);
blockseed = getBlockSeed2(full_node_min, seed);
// Generate base terrain, mountains, and ridges with initial heightmaps
s16 stone_surface_max_y = generateTerrain();
// Create heightmap
updateHeightmap(node_min, node_max);
// Init biome generator, place biome-specific nodes, and build biomemap
biomegen->calcBiomeNoise(node_min);
MgStoneType stone_type = generateBiomes();
if (flags & MG_CAVES)
generateCaves(stone_surface_max_y, large_cave_depth);
if (flags & MG_DUNGEONS)
generateDungeons(stone_surface_max_y, stone_type);
// Generate the registered decorations
if (flags & MG_DECORATIONS)
m_emerge->decomgr->placeAllDecos(this, blockseed, node_min, node_max);
// Generate the registered ores
m_emerge->oremgr->placeAllOres(this, blockseed, node_min, node_max);
// Sprinkle some dust on top after everything else was generated
dustTopNodes();
//printf("makeChunk: %dms\n", t.stop());
updateLiquid(&data->transforming_liquid, full_node_min, full_node_max);
if (flags & MG_LIGHT)
calcLighting(node_min - v3s16(0, 1, 0), node_max + v3s16(0, 1, 0),
full_node_min, full_node_max);
//setLighting(node_min - v3s16(1, 0, 1) * MAP_BLOCKSIZE,
// node_max + v3s16(1, 0, 1) * MAP_BLOCKSIZE, 0xFF);
this->generating = false;
}
s16 MapgenFlat::generateTerrain()
{
MapNode n_air(CONTENT_AIR);
MapNode n_stone(c_stone);
MapNode n_water(c_water_source);
v3s16 em = vm->m_area.getExtent();
s16 stone_surface_max_y = -MAX_MAP_GENERATION_LIMIT;
u32 ni2d = 0;
bool use_noise = (spflags & MGFLAT_LAKES) || (spflags & MGFLAT_HILLS);
if (use_noise)
noise_terrain->perlinMap2D(node_min.X, node_min.Z);
for (s16 z = node_min.Z; z <= node_max.Z; z++)
for (s16 x = node_min.X; x <= node_max.X; x++, ni2d++) {
s16 stone_level = ground_level;
float n_terrain = use_noise ? noise_terrain->result[ni2d] : 0.0f;
if ((spflags & MGFLAT_LAKES) && n_terrain < lake_threshold) {
s16 depress = (lake_threshold - n_terrain) * lake_steepness;
stone_level = ground_level - depress;
} else if ((spflags & MGFLAT_HILLS) && n_terrain > hill_threshold) {
s16 rise = (n_terrain - hill_threshold) * hill_steepness;
stone_level = ground_level + rise;
}
u32 vi = vm->m_area.index(x, node_min.Y - 1, z);
for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++) {
if (vm->m_data[vi].getContent() == CONTENT_IGNORE) {
if (y <= stone_level) {
vm->m_data[vi] = n_stone;
if (y > stone_surface_max_y)
stone_surface_max_y = y;
} else if (y <= water_level) {
vm->m_data[vi] = n_water;
} else {
vm->m_data[vi] = n_air;
}
}
vm->m_area.add_y(em, vi, 1);
}
}
return stone_surface_max_y;
}
| 0 | 0.976467 | 1 | 0.976467 | game-dev | MEDIA | 0.688058 | game-dev | 0.796855 | 1 | 0.796855 |
gwathlobal/CotD | 59,474 | src/generate-level.lisp | (in-package :cotd)
;; the level generation function takes the following parameters:
;; sector-level-gen-func - main funcation to generate a level from template (for example, city level)
;; takes: (template-level set-max-buildings-func set-reserved-buildings-func)
;; returns: (real-terrain mob-template-list item-template-list feature-template-list)
;; item-process-func-list - list of functions that generate items on the level
;; takes: (item-template-list)
;; returns: (list of items)
;; feature-process-func-list - list of functions that generate features on the level
;; takes: (feature-template-list)
;; returns: (list of features)
;; mob-process-func-list - list of functions that generate mobs on the level
;; takes: (mob-template-list)
;; returns: (list of mobs)
;; level-template-pre-process-func-list - list of functions that modify the template level before the sector-level-gen-func
;; takes: (template-level)
;; returns: (template-level (list of buildings))
;; terrain-level-post-process-func-list - list of functions that modify the real terrain on the level after the sector-level-gen-func
;; takes: (real-terrain)
;; returns: (real-terrain)
;;
(defun generate-level-from-sector (sector-level-gen-func &key (max-x *max-x-level*) (max-y *max-y-level*) (max-z *max-z-level*)
(overall-post-process-func-list ())
(level-template-pre-process-func-list ())
(terrain-level-post-process-func-list ())
(world-sector nil)
(mission nil)
(world nil)
)
(unless world-sector (error ":WORLD-SECTOR is an obligatory parameter!"))
(unless mission (error ":MISSION is an obligatory parameter!"))
(unless world (error ":WORLD is an obligatory parameter!"))
;; create a template level
(let* ((level nil)
(terrain-level nil)
(feature-template-result nil)
(mob-template-result nil)
(item-template-result nil))
(let* ((template-max-x (truncate max-x *level-grid-size*)) (template-max-y (truncate max-y *level-grid-size*)) (template-max-z max-z)
(template-level (make-array (list template-max-x template-max-y template-max-z) :initial-element t))
;; the values in template-level are as follows:
;; t - reserved
;; nil - free
;; list of (+building-type-<id>+ x y z)
)
(setf *max-progress-bar* 11)
(setf *cur-progress-bar* 0)
(funcall *update-screen-closure* "Generating map")
;; all grid cells along the borders are reserved, while everything inside is free for claiming
(loop for y from 1 below (1- template-max-y) do
(loop for x from 1 below (1- template-max-x) do
(loop for z from 0 below template-max-z do
(setf (aref template-level x y z) nil))))
;; use level template pre-process functions to place reserved buildings from sector features, factions, etc
(loop for level-template-pre-process-func in level-template-pre-process-func-list do
(funcall level-template-pre-process-func template-level world-sector mission world))
;; adjusting the progress bar : 1
(incf *cur-progress-bar*)
(funcall *update-screen-closure* nil)
;; produce terrain level from template using the supplied function
(multiple-value-setq (terrain-level mob-template-result item-template-result feature-template-result) (funcall sector-level-gen-func
template-level
max-x max-y max-z))
;; create level with dimenision based on terrain-level dimensions
(setf level (create-level :max-x (array-dimension terrain-level 0) :max-y (array-dimension terrain-level 1) :max-z (array-dimension terrain-level 2)))
(setf (terrain level) terrain-level)
(setf (level world) level)
;; adjusting the progress bar : 2
(incf *cur-progress-bar*)
(funcall *update-screen-closure* nil)
(setf (mob-quadrant-map level) (make-array (list (ceiling (array-dimension (terrain level) 0) 10)
(ceiling (array-dimension (terrain level) 1) 10))
:initial-element ()))
(setf (item-quadrant-map level) (make-array (list (ceiling (array-dimension (terrain level) 0) 10)
(ceiling (array-dimension (terrain level) 1) 10))
:initial-element ()))
(setf (light-quadrant-map level) (make-array (list (ceiling (array-dimension (terrain level) 0) 10)
(ceiling (array-dimension (terrain level) 1) 10))
:initial-element ()))
(setf (mission level) mission)
(setf (world-sector level) world-sector)
;; populate world with items
(log:info "Placing standard items")
(loop for (item-type-id x y z qty) in item-template-result
do
(add-item-to-level-list level (make-instance 'item :item-type item-type-id :x x :y y :z z :qty qty)))
;; populate world with features
(log:info "Placing standard features")
(loop for (feature-type-id x y z) in feature-template-result
do
(add-feature-to-level-list level (make-instance 'feature :feature-type feature-type-id :x x :y y :z z)))
;; adjusting the progress bar : 3
(incf *cur-progress-bar*)
(funcall *update-screen-closure* nil)
;; post process actual level (demonic portals, blood spatter, irradiated spots, etc)
(loop for terrain-post-process-func in terrain-level-post-process-func-list do
(setf terrain-level (funcall terrain-post-process-func level world-sector mission world)))
)
;; check map for connectivity : 4
(incf *cur-progress-bar*)
(funcall *update-screen-closure* "Creating connectivity maps")
(setf *time-at-end-of-player-turn* (get-internal-real-time))
;; generate connectivity maps
(let* ((size-1-thread (bt:make-thread #'(lambda ()
(let ((start-time (get-internal-real-time)))
(create-connect-map-walk level 1)
(incf *cur-progress-bar*)
(funcall *update-screen-closure* nil)
(log:info "TIME-ELAPSED AFTER WALK 1: ~A" (- (get-internal-real-time) start-time))
)
(let ((start-time (get-internal-real-time)))
(create-connect-map-climb level 1)
(incf *cur-progress-bar*)
(funcall *update-screen-closure* nil)
(log:info "TIME-ELAPSED AFTER CLIMB 1: ~A" (- (get-internal-real-time) start-time))
)
(let ((start-time (get-internal-real-time)))
(create-connect-map-fly level 1)
(incf *cur-progress-bar*)
(funcall *update-screen-closure* nil)
(log:info "TIME-ELAPSED AFTER FLY 1: ~A" (- (get-internal-real-time) start-time))
)
(let ((start-time (get-internal-real-time)))
(create-connect-map-aux level)
(incf *cur-progress-bar*)
(funcall *update-screen-closure* nil)
(log:info "TIME-ELAPSED AFTER CLIMB 1: ~A" (- (get-internal-real-time) start-time))
)
)
:name "Connectivity map (size 1) thread"))
(size-3-thread (bt:make-thread #'(lambda ()
(let ((start-time (get-internal-real-time)))
(create-connect-map-walk level 3)
(incf *cur-progress-bar*)
(funcall *update-screen-closure* nil)
(log:info "TIME-ELAPSED AFTER WALK 3: ~A" (- (get-internal-real-time) start-time))
)
(let ((start-time (get-internal-real-time)))
(create-connect-map-climb level 3)
(incf *cur-progress-bar*)
(funcall *update-screen-closure* nil)
(log:info "TIME-ELAPSED AFTER CLIMB 3: ~A" (- (get-internal-real-time) start-time))
)
;;(let ((start-time (get-internal-real-time)))
;; (create-connect-map-fly (level world) 3)
;; (incf *cur-progress-bar*)
;; (funcall *update-screen-closure* nil)
;; (format out "TIME-ELAPSED AFTER FLY 3: ~A~%" (- (get-internal-real-time) start-time))
;; )
)
:name "Connectivity map (size 3) thread"))
)
(bt:join-thread size-1-thread)
(log:info "SIZE 1 CREATION FINISHED")
(bt:join-thread size-3-thread)
(log:info "SIZE 3 CREATION FINISHED")
)
;; adjusting the progress bar : 10
(incf *cur-progress-bar*)
(funcall *update-screen-closure* "Finalizing")
(push +game-event-adjust-outdoor-light+ (game-events level))
;; populate world with standard mobs (from actual level template)
(log:info "Placing standard mobs")
(loop for (mob-type-id x y z) in mob-template-result
when (null (get-mob-* level x y z))
do
(add-mob-to-level-list level (make-instance 'mob :mob-type mob-type-id :x x :y y :z z)))
;; populate the world with special mobs (military in outposts, demons around portals, etc) depending on present factions
(loop for overall-post-process-func in overall-post-process-func-list
do
(funcall overall-post-process-func level world-sector mission world))
;; setting up demonic portals so that mobs could access them directly without iterating through the whole list of features
(loop for feature-id in (feature-id-list (level world))
for feature = (get-feature-by-id feature-id)
when (= (feature-type feature) +feature-demonic-portal+)
do
(push feature-id (demonic-portals level)))
)
)
(defun create-level (&key (max-x *max-x-level*) (max-y *max-y-level*) (max-z *max-z-level*))
(let ((level))
(setf level (make-instance 'level))
(setf (terrain level) (make-array (list max-x max-y max-z) :initial-element +terrain-floor-stone+))
(setf (mobs level) (make-array (list max-x max-y max-z) :initial-element nil))
(setf (items level) (make-array (list max-x max-y max-z) :initial-element nil))
(setf (features level) (make-array (list max-x max-y max-z) :initial-element nil))
(setf (memo level) (make-array (list max-x max-y max-z)))
(setf (light-map level) (make-array (list max-x max-y max-z) :initial-element 0))
(loop for x from 0 below max-x do
(loop for y from 0 below max-y do
(loop for z from 0 below max-z do
(set-memo-* level x y z (create-single-memo 0 sdl:*white* sdl:*black* nil nil 0 nil)))))
level))
(defun reserve-build-on-grid (template-building-id gx gy gz template-level)
(destructuring-bind (dx . dy) (building-grid-dim (get-building-type template-building-id))
(let ((building (list template-building-id gx gy gz)))
(loop for y1 from 0 below dy do
(loop for x1 from 0 below dx do
(setf (aref template-level (+ gx x1) (+ gy y1) gz) building)))
building)))
(defun can-place-build-on-grid (template-building-id gx gy gz template-level)
(destructuring-bind (dx . dy) (building-grid-dim (get-building-type template-building-id))
;; if the staring point of the building + its dimensions) is more than level dimensions - fail
(when (or (> (+ gx dx) (array-dimension template-level 0))
(> (+ gy dy) (array-dimension template-level 1)))
(return-from can-place-build-on-grid nil))
;; if any of the grid tiles that the building is going to occupy are already reserved - fail
(loop for y1 from 0 below dy do
(loop for x1 from 0 below dx do
(unless (eq (aref template-level (+ gx x1) (+ gy y1) gz) nil)
(return-from can-place-build-on-grid nil))
))
;; all checks done - success
t
))
(defun prepare-gen-build-id-list (max-building-types &optional increased-build-type-id)
;; a hack to make houses appear 3 times more frequently
(append (loop repeat 3
collect (prepare-spec-build-id-list increased-build-type-id))
(loop for gen-build-type-id being the hash-key in max-building-types
collect (prepare-spec-build-id-list gen-build-type-id))))
(defun prepare-spec-build-id-list (gen-build-type-id)
(loop for spec-build-type being the hash-value in *building-types*
when (= (building-type spec-build-type) gen-build-type-id)
collect (building-id spec-build-type)))
(defun flood-fill (first-cell &key (max-x *max-x-level*) (max-y *max-y-level*) (max-z *max-z-level*) check-func make-func)
(declare (optimize (speed 3) (safety 0))
(type function check-func make-func)
(type fixnum max-x max-y max-z))
(let ((open-list nil))
(push first-cell open-list)
(loop while open-list
for c-cell of-type list = (pop open-list)
for cx of-type fixnum = (first c-cell)
for cy of-type fixnum = (second c-cell)
for cz of-type fixnum = (third c-cell)
do
(funcall make-func cx cy cz)
(loop for y-offset of-type fixnum from -1 to 1
for y of-type fixnum = (+ cy y-offset) do
(loop for x-offset of-type fixnum from -1 to 1
for x of-type fixnum = (+ cx x-offset) do
(loop for z-offset of-type fixnum from -1 to 1
for z of-type fixnum = (+ cz z-offset)
when (and (>= x 0) (>= y 0) (>= z 0) (< x max-x) (< y max-y) (< z max-z)
(not (and (zerop x-offset) (zerop y-offset) (zerop z-offset)))
(funcall check-func x y z cx cy cz))
do
(push (list x y z) open-list))))
)
))
(defun create-connect-map-walk (level mob-size)
(declare (optimize (speed 3))
(type fixnum mob-size))
(let* ((max-x (array-dimension (terrain level) 0))
(max-y (array-dimension (terrain level) 1))
(max-z (array-dimension (terrain level) 2))
(connect-map (if (aref (connect-map level) mob-size)
(aref (connect-map level) mob-size)
(make-array (list max-x max-y max-z) :initial-element nil)))
(room-id 0)
(check-func #'(lambda (x y z cx cy cz)
(let* ((connect-id (get-connect-map-value connect-map x y z +connect-map-move-walk+))
(half-size (truncate (1- mob-size) 2)))
(declare (type fixnum connect-id half-size cx cy cz x y z))
(if (and (= connect-id +connect-room-none+)
(funcall #'(lambda (sx sy)
(let ((result t))
(block from-result
(loop for off-x of-type fixnum from (- half-size) to (+ half-size)
for nx of-type fixnum = (+ sx off-x) do
(loop for off-y of-type fixnum from (- half-size) to (+ half-size)
for ny of-type fixnum = (+ sy off-y) do
(when (or (< nx 0) (< ny 0) (>= nx max-x) (>= ny max-y)
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-blocks-move+)
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-openable-door+))
(setf result nil)
(return-from from-result))
;; magic starts here
(setf result nil)
(when (and (or (= (- cz z) 0)
(and (/= (- cz z) 0)
(= nx cx)
(= ny cy))
)
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-water+)
(get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-water+))
(setf result t))
;; the following case is connected
;; on floor z = 1 -> | |p| |
;; floor z = 1 -> | |.| |
;; on floor z = 0 -> | |x| |
;; floor z = 0 -> | |w| |
;; where
;; w - water
;; . - air (no floor, no wall, no water)
;; p - starting cell
;; x - current cell
(when (and (not result)
(< (- z cz) 0)
(not (get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-blocks-move-floor+))
(not (get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-blocks-move+))
(not (get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-water+))
(and (= cx nx)
(= cy ny))
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-water+))
(setf result t))
;; the following case is connected
;; on floor z = 1 -> | | |x|
;; floor z = 1 -> | | |#|
;; on floor z = 0 -> | |p| |
;; floor z = 0 -> | |w| |
;; where
;; # - floor
;; . - air
;; w - water
;; p - starting cell
;; x - current cell
(when (and (> (- z cz) 0)
(get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-water+)
(not (and (= cx nx)
(= cy ny)))
(not (get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-blocks-move+))
(or (get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-blocks-move-floor+)
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-water+)))
;(format t "FLOOD FILL HERE~%")
(setf result t))
;; the following case is connected
;; on floor z = 1 -> | | |x|
;; floor z = 1 -> | | |#|
;; on floor z = 0 -> | |p| |
;; floor z = 0 -> | |u| |
;; where
;; # - floor
;; . - air
;; u - slope up (with floor)
;; p - starting cell
;; x - current cell
(when (and (> (- z cz) 0)
(get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-blocks-move-floor+)
(get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-slope-up+)
(not (and (= cx nx)
(= cy ny)))
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-blocks-move-floor+))
;(format t "FLOOD FILL HERE~%")
(setf result t))
;; the following case is connected
;; on floor z = 1 -> | |p| |
;; floor z = 1 -> | |d| |
;; on floor z = 0 -> | |x| |
;; floor z = 0 -> | |u| |
;; where
;; u - slope up (with floor)
;; d - slope down (with air)
;; p - starting cell
;; x - current cell
(when (and (not result)
(< (- z cz) 0)
(get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-slope-down+)
(and (= cx nx)
(= cy ny))
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-slope-up+)
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-blocks-move-floor+))
(setf result t))
;; the following case is connected
;; on floor z = 0 -> | |x|p|
;; floor z = 0 -> | |?|#|
;; where
;; # - floor
;; ? - not important
;; p - starting cell
;; x - current cell
(when (and (not result)
(= (- z cz) 0)
(get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-blocks-move-floor+)
;(not (get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-blocks-move-floor+))
)
(setf result t))
;; if you are large, you can move only if all you tiles have opaque floor
(when (and (> mob-size 1)
(= (- z cz) 0)
(not (get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-blocks-move-floor+)))
(setf result nil))
;; all other cases are disconnected
(unless result
(return-from from-result))
)))
result))
x y))
t
nil))))
(make-func #'(lambda (x y z)
(set-connect-map-value connect-map x y z +connect-map-move-walk+ room-id)
)))
(declare (type fixnum max-x max-y max-z room-id))
(loop for x of-type fixnum from 0 below max-x do
(loop for y of-type fixnum from 0 below max-y do
(loop for z of-type fixnum from 0 below max-z do
(when (funcall check-func x y z x y z)
(flood-fill (list x y z) :max-x max-x :max-y max-y :max-z max-z :check-func check-func :make-func make-func)
(incf room-id))
)))
(setf (aref (connect-map level) mob-size) connect-map)
))
(defun create-connect-map-climb (level mob-size)
(declare (optimize (speed 3))
(type fixnum mob-size))
(let* ((max-x (array-dimension (terrain level) 0))
(max-y (array-dimension (terrain level) 1))
(max-z (array-dimension (terrain level) 2))
(connect-map (if (aref (connect-map level) mob-size)
(aref (connect-map level) mob-size)
(make-array (list max-x max-y max-z) :initial-element nil)))
(room-id 0)
(check-func #'(lambda (x y z cx cy cz)
(let* ((connect-id (get-connect-map-value connect-map x y z +connect-map-move-climb+))
(half-size (truncate (1- mob-size) 2)))
(declare (type fixnum connect-id half-size cx cy cz x y z))
(if (and (= connect-id +connect-room-none+)
(funcall #'(lambda (sx sy)
(let ((result t))
(block from-result
(loop for off-x of-type fixnum from (- half-size) to (+ half-size)
for nx of-type fixnum = (+ sx off-x) do
(loop for off-y of-type fixnum from (- half-size) to (+ half-size)
for ny of-type fixnum = (+ sy off-y) do
(when (or (< nx 0) (< ny 0) (>= nx max-x) (>= ny max-y)
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-blocks-move+)
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-openable-door+))
(setf result nil)
(return-from from-result))
;; magic starts here
(setf result nil)
(when (and (or (= (- cz z) 0)
(and (/= (- cz z) 0)
(= nx cx)
(= ny cy))
)
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-water+)
(get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-water+))
(setf result t))
;; the following case is connected
;; on floor z = 1 -> | |p| |
;; floor z = 1 -> | |.| |
;; on floor z = 0 -> | |x| |
;; floor z = 0 -> | |w| |
;; where
;; w - water
;; . - air (no floor, no wall, no water)
;; p - starting cell
;; x - current cell
(when (and (not result)
(< (- z cz) 0)
(not (get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-blocks-move-floor+))
(not (get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-blocks-move+))
(not (get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-water+))
(and (= cx nx)
(= cy ny))
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-water+))
(setf result t))
;; the following case is connected
;; on floor z = 1 -> | | |x|
;; floor z = 1 -> | | |#|
;; on floor z = 0 -> | |p| |
;; floor z = 0 -> | |w| |
;; where
;; # - floor
;; . - air
;; w - water
;; p - starting cell
;; x - current cell
(when (and (> (- z cz) 0)
(get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-water+)
(not (and (= cx nx)
(= cy ny)))
(not (get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-blocks-move+))
(or (get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-blocks-move-floor+)
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-water+)))
;(format t "FLOOD FILL HERE~%")
(setf result t))
;; the following case is connected
;; on floor z = 0 -> | |x|p|
;; floor z = 0 -> | |?|#|
;; where
;; # - floor
;; ? - not important
;; p - starting cell
;; x - current cell
(when (and (= (- z cz) 0)
(get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-blocks-move-floor+)
)
(setf result t))
(when (and (not result)
(or (= (- cz z) 0)
(and (/= (- cz z) 0)
(= nx cx)
(= ny cy)))
(check-move-along-z cx cy cz nx ny z)
(funcall #'(lambda ()
(let ((result nil))
(block surround
(check-surroundings nx ny nil
#'(lambda (mx my)
(when (and (get-terrain-* (level *world*) mx my z)
(not (get-terrain-type-trait (get-terrain-* (level *world*) mx my z) +terrain-trait-not-climable+))
(or (get-terrain-type-trait (get-terrain-* (level *world*) mx my z) +terrain-trait-blocks-move-floor+)
(get-terrain-type-trait (get-terrain-* (level *world*) mx my z) +terrain-trait-blocks-move+)))
(setf result t)
(return-from surround)))))
result))))
(setf result t))
;; if you are large, you can move only if all you tiles have opaque floor
(when (and (> mob-size 1)
(= (- z cz) 0)
(not (get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-blocks-move-floor+)))
(setf result nil))
;; all other cases are disconnected
(unless result
(return-from from-result))
)))
result))
x y))
t
nil))))
(make-func #'(lambda (x y z)
(set-connect-map-value connect-map x y z +connect-map-move-climb+ room-id)
)))
(declare (type fixnum max-x max-y max-z room-id))
(loop for x of-type fixnum from 0 below max-x do
(loop for y of-type fixnum from 0 below max-y do
(loop for z of-type fixnum from 0 below max-z do
(when (funcall check-func x y z x y z)
(flood-fill (list x y z) :max-x max-x :max-y max-y :max-z max-z :check-func check-func :make-func make-func)
(incf room-id))
)))
(setf (aref (connect-map level) mob-size) connect-map)))
(defun create-connect-map-fly (level mob-size)
(declare (optimize (speed 3))
(type fixnum mob-size))
(let* ((max-x (array-dimension (terrain level) 0))
(max-y (array-dimension (terrain level) 1))
(max-z (array-dimension (terrain level) 2))
(connect-map (if (aref (connect-map level) mob-size)
(aref (connect-map level) mob-size)
(make-array (list max-x max-y max-z) :initial-element nil)))
(room-id 0)
(check-func #'(lambda (x y z cx cy cz)
(let* ((connect-id (get-connect-map-value connect-map x y z +connect-map-move-fly+))
(half-size (truncate (1- mob-size) 2)))
(declare (type fixnum connect-id half-size cx cy cz x y z))
(if (and (= connect-id +connect-room-none+)
(funcall #'(lambda (sx sy)
(let ((result t))
(block from-result
(loop for off-x of-type fixnum from (- half-size) to (+ half-size)
for nx of-type fixnum = (+ sx off-x) do
(loop for off-y of-type fixnum from (- half-size) to (+ half-size)
for ny of-type fixnum = (+ sy off-y) do
(when (or (< nx 0) (< ny 0) (>= nx max-x) (>= ny max-y)
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-blocks-move+)
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-openable-door+))
(setf result nil)
(return-from from-result))
;; magic starts here
(setf result nil)
(when (and (or (= (- cz z) 0)
(and (/= (- cz z) 0)
(= nx cx)
(= ny cy))
)
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-water+)
(get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-water+))
(setf result t))
;; the following case is connected
;; on floor z = 1 -> | |p| |
;; floor z = 1 -> | |.| |
;; on floor z = 0 -> | |x| |
;; floor z = 0 -> | |w| |
;; where
;; w - water
;; . - air (no floor, no wall, no water)
;; p - starting cell
;; x - current cell
(when (and (not result)
(< (- z cz) 0)
(not (get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-blocks-move-floor+))
(not (get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-blocks-move+))
(not (get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-water+))
(and (= cx nx)
(= cy ny))
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-water+))
(setf result t))
;; the following case is connected
;; on floor z = 1 -> | | |x|
;; floor z = 1 -> | | |#|
;; on floor z = 0 -> | |p| |
;; floor z = 0 -> | |w| |
;; where
;; # - floor
;; . - air
;; w - water
;; p - starting cell
;; x - current cell
(when (and (> (- z cz) 0)
(get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-water+)
(not (and (= cx nx)
(= cy ny)))
(not (get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-blocks-move+))
(or (get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-blocks-move-floor+)
(get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-water+)))
;(format t "FLOOD FILL HERE~%")
(setf result t))
;; the following case is connected
;; on floor z = 0 -> | |x|p|
;; floor z = 0 -> | |?|#|
;; where
;; # - floor
;; ? - not important
;; p - starting cell
;; x - current cell
(when (and (= (- z cz) 0)
(get-terrain-type-trait (get-terrain-* level cx cy cz) +terrain-trait-blocks-move-floor+)
)
(setf result t))
;; check small mobs connectivity via flight
(when (and (not result)
(or (= (- cz z) 0)
(and (/= (- cz z) 0)
(= nx cx)
(= ny cy))
)
(check-move-along-z cx cy cz nx ny z)
)
(setf result t))
;; check large mobs connectivity via flight
(when (and (not result)
(> mob-size 1)
(/= (- cz z) 0)
(check-move-along-z nx ny cz nx ny z))
(setf result t))
;; if you are large, you can move only if all you tiles have opaque floor
;(when (and (> mob-size 1)
; (= (- z cz) 0)
; (not (get-terrain-type-trait (get-terrain-* level nx ny z) +terrain-trait-blocks-move-floor+)))
; (setf result nil))
;; all other cases are disconnected
(unless result
(return-from from-result))
)))
result))
x y))
t
nil))))
(make-func #'(lambda (x y z)
(set-connect-map-value connect-map x y z +connect-map-move-fly+ room-id)
)))
(declare (type fixnum max-x max-y max-z room-id))
(loop for x of-type fixnum from 0 below max-x do
(loop for y of-type fixnum from 0 below max-y do
(loop for z of-type fixnum from 0 below max-z do
(when (funcall check-func x y z x y z)
(flood-fill (list x y z) :max-x max-x :max-y max-y :max-z max-z :check-func check-func :make-func make-func)
(incf room-id))
)))
(setf (aref (connect-map level) mob-size) connect-map)))
(defun create-connect-map-aux (level)
;; make auxiliary links
(let ((max-x (array-dimension (terrain level) 0))
(max-y (array-dimension (terrain level) 1))
(max-z (array-dimension (terrain level) 2)))
(loop for x of-type fixnum from 1 below (1- max-x) do
(loop for y of-type fixnum from 1 below (1- max-y) do
(loop for z of-type fixnum from 0 below max-z do
(when (get-terrain-type-trait (get-terrain-* level x y z) +terrain-trait-openable-door+)
(let ((func #'(lambda (&key map-size move-mode)
(let ((room-id-list nil)
;; increase actual connection depending on door being open/close
(delta-actual (if (get-terrain-type-trait (get-terrain-* level x y z) +terrain-trait-blocks-move+)
0
1)))
(check-surroundings x y nil #'(lambda (dx dy)
(when (/= (get-level-connect-map-value level dx dy z map-size move-mode) +connect-room-none+)
(pushnew (get-level-connect-map-value level dx dy z map-size move-mode)
room-id-list))))
(loop for room-id-start in room-id-list do
(loop for room-id-end in room-id-list do
(when (/= room-id-start room-id-end)
(set-aux-map-connection level room-id-start room-id-end map-size move-mode :delta-potential 1 :delta-actual delta-actual))))))))
(funcall func :map-size 1 :move-mode +connect-map-move-walk+)
(funcall func :map-size 1 :move-mode +connect-map-move-climb+)
(funcall func :map-size 1 :move-mode +connect-map-move-fly+)
)))))))
| 0 | 0.955789 | 1 | 0.955789 | game-dev | MEDIA | 0.612908 | game-dev | 0.787883 | 1 | 0.787883 |
Slimefun/Slimefun4 | 2,837 | src/main/java/io/github/thebusybiscuit/slimefun4/core/guide/options/LearningAnimationOption.java | package io.github.thebusybiscuit.slimefun4.core.guide.options;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nonnull;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import io.github.bakedlibs.dough.data.persistent.PersistentDataAPI;
import io.github.bakedlibs.dough.items.CustomItemStack;
import io.github.thebusybiscuit.slimefun4.api.SlimefunAddon;
import io.github.thebusybiscuit.slimefun4.core.SlimefunRegistry;
import io.github.thebusybiscuit.slimefun4.implementation.Slimefun;
/**
* {@link LearningAnimationOption} represents a setting in the Slimefun guide book.
* It allows users to disable/enable the "learning animation",
* the information in chat when doing a Slimefun research.
*
* @author martinbrom
*/
class LearningAnimationOption implements SlimefunGuideOption<Boolean> {
@Nonnull
@Override
public SlimefunAddon getAddon() {
return Slimefun.instance();
}
@Nonnull
@Override
public NamespacedKey getKey() {
return new NamespacedKey(Slimefun.instance(), "research_learning_animation");
}
@Nonnull
@Override
public Optional<ItemStack> getDisplayItem(@Nonnull Player p, @Nonnull ItemStack guide) {
SlimefunRegistry registry = Slimefun.getRegistry();
if (!registry.isResearchingEnabled() || registry.isLearningAnimationDisabled()) {
return Optional.empty();
} else {
boolean enabled = getSelectedOption(p, guide).orElse(true);
String optionState = enabled ? "enabled" : "disabled";
List<String> lore = Slimefun.getLocalization().getMessages(p, "guide.options.learning-animation." + optionState + ".text");
lore.add("");
lore.add("&7\u21E8 " + Slimefun.getLocalization().getMessage(p, "guide.options.learning-animation." + optionState + ".click"));
ItemStack item = CustomItemStack.create(enabled ? Material.MAP : Material.PAPER, lore);
return Optional.of(item);
}
}
@Override
public void onClick(@Nonnull Player p, @Nonnull ItemStack guide) {
setSelectedOption(p, guide, !getSelectedOption(p, guide).orElse(true));
SlimefunGuideSettings.openSettings(p, guide);
}
@Override
public Optional<Boolean> getSelectedOption(@Nonnull Player p, @Nonnull ItemStack guide) {
NamespacedKey key = getKey();
boolean value = !PersistentDataAPI.hasByte(p, key) || PersistentDataAPI.getByte(p, key) == (byte) 1;
return Optional.of(value);
}
@Override
public void setSelectedOption(@Nonnull Player p, @Nonnull ItemStack guide, @Nonnull Boolean value) {
PersistentDataAPI.setByte(p, getKey(), (byte) (value.booleanValue() ? 1 : 0));
}
}
| 0 | 0.823116 | 1 | 0.823116 | game-dev | MEDIA | 0.925384 | game-dev | 0.825927 | 1 | 0.825927 |
daydayasobi/TowerDefense-TEngine-Demo | 4,569 | Packages/YooAsset/Editor/AssetArtScanner/AssetArtScannerSettingData.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using UnityEngine;
using UnityEditor;
namespace YooAsset.Editor
{
public class AssetArtScannerSettingData
{
/// <summary>
/// 配置数据是否被修改
/// </summary>
public static bool IsDirty { private set; get; } = false;
static AssetArtScannerSettingData()
{
}
private static AssetArtScannerSetting _setting = null;
public static AssetArtScannerSetting Setting
{
get
{
if (_setting == null)
_setting = SettingLoader.LoadSettingData<AssetArtScannerSetting>();
return _setting;
}
}
/// <summary>
/// 存储配置文件
/// </summary>
public static void SaveFile()
{
if (Setting != null)
{
IsDirty = false;
EditorUtility.SetDirty(Setting);
AssetDatabase.SaveAssets();
Debug.Log($"{nameof(AssetArtScannerSetting)}.asset is saved!");
}
}
/// <summary>
/// 清空所有数据
/// </summary>
public static void ClearAll()
{
Setting.Scanners.Clear();
SaveFile();
}
/// <summary>
/// 扫描所有项
/// </summary>
public static void ScanAll()
{
foreach (var scanner in Setting.Scanners)
{
var scanResult = Setting.BeginScan(scanner.ScannerGUID);
if (scanResult.Succeed == false)
{
Debug.LogError($"{scanner.ScannerName} failed : {scanResult.ErrorInfo}");
}
}
}
/// <summary>
/// 扫描所有项
/// </summary>
public static void ScanAll(string keyword)
{
foreach (var scanner in Setting.Scanners)
{
if (string.IsNullOrEmpty(keyword) == false)
{
if (scanner.CheckKeyword(keyword) == false)
continue;
}
var scanResult = Setting.BeginScan(scanner.ScannerGUID);
if (scanResult.Succeed == false)
{
Debug.LogError($"{scanner.ScannerName} failed : {scanResult.ErrorInfo}");
}
}
}
/// <summary>
/// 扫描单项
/// </summary>
public static ScannerResult Scan(string scannerGUID)
{
var scanResult = Setting.BeginScan(scannerGUID);
if (scanResult.Succeed == false)
{
Debug.LogError(scanResult.ErrorInfo);
}
return scanResult;
}
// 扫描器编辑相关
public static AssetArtScanner CreateScanner(string name, string desc)
{
AssetArtScanner scanner = new AssetArtScanner();
scanner.ScannerGUID = System.Guid.NewGuid().ToString();
scanner.ScannerName = name;
scanner.ScannerDesc = desc;
Setting.Scanners.Add(scanner);
IsDirty = true;
return scanner;
}
public static void RemoveScanner(AssetArtScanner scanner)
{
if (Setting.Scanners.Remove(scanner))
{
IsDirty = true;
}
else
{
Debug.LogWarning($"Failed remove scanner : {scanner.ScannerName}");
}
}
public static void ModifyScanner(AssetArtScanner scanner)
{
if (scanner != null)
{
IsDirty = true;
}
}
// 资源收集编辑相关
public static void CreateCollector(AssetArtScanner scanner, AssetArtCollector collector)
{
scanner.Collectors.Add(collector);
IsDirty = true;
}
public static void RemoveCollector(AssetArtScanner scanner, AssetArtCollector collector)
{
if (scanner.Collectors.Remove(collector))
{
IsDirty = true;
}
else
{
Debug.LogWarning($"Failed remove collector : {collector.CollectPath}");
}
}
public static void ModifyCollector(AssetArtScanner scanner, AssetArtCollector collector)
{
if (scanner != null && collector != null)
{
IsDirty = true;
}
}
}
} | 0 | 0.882388 | 1 | 0.882388 | game-dev | MEDIA | 0.650767 | game-dev | 0.840295 | 1 | 0.840295 |
RS485/LogisticsPipes | 3,188 | common/logisticspipes/items/ItemHUDArmor.java | package logisticspipes.items;
import javax.annotation.Nonnull;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.world.World;
import net.minecraftforge.common.ISpecialArmor;
import logisticspipes.LogisticsPipes;
import logisticspipes.api.IHUDArmor;
import logisticspipes.interfaces.ILogisticsItem;
import logisticspipes.network.GuiIDs;
import logisticspipes.proxy.MainProxy;
public class ItemHUDArmor extends ItemArmor implements ISpecialArmor, IHUDArmor, ILogisticsItem {
public ItemHUDArmor() {
super(ArmorMaterial.LEATHER, 0, EntityEquipmentSlot.HEAD);
}
@Override
public ArmorProperties getProperties(EntityLivingBase player, @Nonnull ItemStack armor, DamageSource source, double damage, int slot) {
return new ArmorProperties(0, 0, 0);
}
@Override
public int getArmorDisplay(EntityPlayer player, @Nonnull ItemStack armor, int slot) {
return 0;
}
@Override
public void damageArmor(EntityLivingBase entity, @Nonnull ItemStack stack, DamageSource source, int damage, int slot) {
// Does not get damaged
}
@Override
public boolean getShareTag() {
return true;
}
@Nonnull
@Override
public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, @Nonnull EnumHand handIn) {
ItemStack stack = player.getHeldItem(handIn);
if (MainProxy.isClient(world)) {
return new ActionResult<>(EnumActionResult.PASS, stack);
}
useItem(player, world);
return new ActionResult<>(EnumActionResult.SUCCESS, stack);
}
@Nonnull
@Override
public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {
useItem(player, world);
if (MainProxy.isClient(world)) {
return EnumActionResult.PASS;
}
return EnumActionResult.SUCCESS;
}
private void useItem(EntityPlayer player, World world) {
player.openGui(LogisticsPipes.instance, GuiIDs.GUI_HUD_Settings, world, player.inventory.currentItem, -1, 0);
}
@Nonnull
@Override
public CreativeTabs[] getCreativeTabs() {
// is visible in the LP creative tab and the ItemArmor creative tab
return new CreativeTabs[] { getCreativeTab(), LogisticsPipes.CREATIVE_TAB_LP };
}
@Override
public boolean isEnabled(@Nonnull ItemStack item) {
return true;
}
@Override
public String getArmorTexture(@Nonnull ItemStack stack, Entity entity, EntityEquipmentSlot slot, String type) {
return "logisticspipes:textures/armor/LogisticsHUD_1.png";
}
@Nonnull
@Override
public String getItemStackDisplayName(@Nonnull ItemStack itemstack) {
return I18n.translateToLocal(getTranslationKey(itemstack) + ".name").trim();
}
}
| 0 | 0.766038 | 1 | 0.766038 | game-dev | MEDIA | 0.995893 | game-dev | 0.958044 | 1 | 0.958044 |
modernuo/ModernUO | 1,077 | Projects/UOContent/Items/Weapons/Artifacts/TheDryadBow.cs | using ModernUO.Serialization;
namespace Server.Items
{
[SerializationGenerator(0, false)]
public partial class TheDryadBow : Bow
{
private static readonly SkillName[] m_PossibleBonusSkills =
{
SkillName.Archery,
SkillName.Healing,
SkillName.MagicResist,
SkillName.Peacemaking,
SkillName.Chivalry,
SkillName.Ninjitsu
};
[Constructible]
public TheDryadBow()
{
ItemID = 0x13B1;
Hue = 0x48F;
SkillBonuses.SetValues(0, m_PossibleBonusSkills.RandomElement(), Utility.Random(4) == 0 ? 10.0 : 5.0);
WeaponAttributes.SelfRepair = 5;
Attributes.WeaponSpeed = 50;
Attributes.WeaponDamage = 35;
WeaponAttributes.ResistPoisonBonus = 15;
}
public override int LabelNumber => 1061090; // The Dryad Bow
public override int ArtifactRarity => 11;
public override int InitMinHits => 255;
public override int InitMaxHits => 255;
}
}
| 0 | 0.817025 | 1 | 0.817025 | game-dev | MEDIA | 0.95808 | game-dev | 0.854769 | 1 | 0.854769 |
Fluorohydride/ygopro-scripts | 3,407 | c21438286.lua | --デーモンの杖
function c21438286.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_CONTINUOUS_TARGET)
e1:SetTarget(c21438286.target)
e1:SetOperation(c21438286.operation)
c:RegisterEffect(e1)
--Equip limit
local e2=Effect.CreateEffect(c)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_EQUIP_LIMIT)
e2:SetValue(c21438286.eqlimit)
c:RegisterEffect(e2)
--confirm
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(21438286,0))
e3:SetCategory(CATEGORY_ATKCHANGE)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_SZONE)
e3:SetCountLimit(1,21438286)
e3:SetTarget(c21438286.cftg)
e3:SetOperation(c21438286.cfop)
c:RegisterEffect(e3)
--tograve
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(21438286,1))
e4:SetCategory(CATEGORY_TOHAND)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e4:SetProperty(EFFECT_FLAG_DELAY)
e4:SetCode(EVENT_TO_GRAVE)
e4:SetCountLimit(1,21438287)
e4:SetCondition(c21438286.thcon)
e4:SetCost(c21438286.thcost)
e4:SetTarget(c21438286.thtg)
e4:SetOperation(c21438286.thop)
c:RegisterEffect(e4)
end
function c21438286.eqlimit(e,c)
return c:IsControler(e:GetHandlerPlayer())
end
function c21438286.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and chkc:IsFaceup() end
if chk==0 then return Duel.IsExistingTarget(Card.IsFaceup,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,Card.IsFaceup,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c21438286.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if e:GetHandler():IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.Equip(tp,e:GetHandler(),tc)
end
end
function c21438286.cftg(e,tp,eg,ep,ev,re,r,rp,chk)
local ec=e:GetHandler():GetEquipTarget()
if chk==0 then return ec and ec:IsAttackAbove(1) and Duel.GetMatchingGroupCount(Card.IsFaceup,tp,0,LOCATION_MZONE,nil)>0 end
end
function c21438286.cfop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local g=Duel.GetMatchingGroup(Card.IsFaceup,tp,0,LOCATION_MZONE,nil)
if g:GetCount()>0 then
local d=c:GetEquipTarget():GetAttack()
d=math.ceil(d/2)
local sc=g:GetFirst()
while sc do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
e1:SetValue(-d)
sc:RegisterEffect(e1)
sc=g:GetNext()
end
end
end
function c21438286.thcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsPreviousLocation(LOCATION_SZONE) and c:GetPreviousEquipTarget() and not c:IsReason(REASON_LOST_TARGET)
end
function c21438286.thcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,1000) end
Duel.PayLPCost(tp,1000)
end
function c21438286.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToHand() end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,e:GetHandler(),1,0,0)
end
function c21438286.thop(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e) then
Duel.SendtoHand(e:GetHandler(),nil,REASON_EFFECT)
end
end
| 0 | 0.892708 | 1 | 0.892708 | game-dev | MEDIA | 0.980922 | game-dev | 0.924946 | 1 | 0.924946 |
FTL13/FTL13 | 4,686 | code/game/objects/effects/step_triggers.dm | /* Simple object type, calls a proc when "stepped" on by something */
/obj/effect/step_trigger
var/affect_ghosts = 0
var/stopper = 1 // stops throwers
var/mobs_only = FALSE
invisibility = INVISIBILITY_ABSTRACT // nope cant see this shit
anchored = TRUE
/obj/effect/step_trigger/proc/Trigger(atom/movable/A)
return 0
/obj/effect/step_trigger/Crossed(H as mob|obj)
..()
if(!H)
return
if(isobserver(H) && !affect_ghosts)
return
if(!ismob(H) && mobs_only)
return
Trigger(H)
/* Sends a message to mob when triggered*/
/obj/effect/step_trigger/message
var/message //the message to give to the mob
var/once = 1
mobs_only = TRUE
/obj/effect/step_trigger/message/Trigger(mob/M)
if(M.client)
to_chat(M, "<span class='info'>[message]</span>")
if(once)
qdel(src)
/* Tosses things in a certain direction */
/obj/effect/step_trigger/thrower
var/direction = SOUTH // the direction of throw
var/tiles = 3 // if 0: forever until atom hits a stopper
var/immobilize = 1 // if nonzero: prevents mobs from moving while they're being flung
var/speed = 1 // delay of movement
var/facedir = 0 // if 1: atom faces the direction of movement
var/nostop = 0 // if 1: will only be stopped by teleporters
var/list/affecting = list()
/obj/effect/step_trigger/thrower/Trigger(atom/A)
if(!A || !ismovableatom(A))
return
var/atom/movable/AM = A
var/curtiles = 0
var/stopthrow = 0
for(var/obj/effect/step_trigger/thrower/T in orange(2, src))
if(AM in T.affecting)
return
if(ismob(AM))
var/mob/M = AM
if(immobilize)
M.canmove = 0
affecting.Add(AM)
while(AM && !stopthrow)
if(tiles)
if(curtiles >= tiles)
break
if(AM.z != src.z)
break
curtiles++
sleep(speed)
// Calculate if we should stop the process
if(!nostop)
for(var/obj/effect/step_trigger/T in get_step(AM, direction))
if(T.stopper && T != src)
stopthrow = 1
else
for(var/obj/effect/step_trigger/teleporter/T in get_step(AM, direction))
if(T.stopper)
stopthrow = 1
if(AM)
var/predir = AM.dir
step(AM, direction)
if(!facedir)
AM.setDir(predir)
affecting.Remove(AM)
if(ismob(AM))
var/mob/M = AM
if(immobilize)
M.canmove = 1
/* Stops things thrown by a thrower, doesn't do anything */
/obj/effect/step_trigger/stopper
/* Instant teleporter */
/obj/effect/step_trigger/teleporter
var/teleport_x = 0 // teleportation coordinates (if one is null, then no teleport!)
var/teleport_y = 0
var/teleport_z = 0
/obj/effect/step_trigger/teleporter/Trigger(atom/movable/A)
if(teleport_x && teleport_y && teleport_z)
A.x = teleport_x
A.y = teleport_y
A.z = teleport_z
/* Random teleporter, teleports atoms to locations ranging from teleport_x - teleport_x_offset, etc */
/obj/effect/step_trigger/teleporter/random
var/teleport_x_offset = 0
var/teleport_y_offset = 0
var/teleport_z_offset = 0
/obj/effect/step_trigger/teleporter/random/Trigger(atom/movable/A)
if(teleport_x && teleport_y && teleport_z)
if(teleport_x_offset && teleport_y_offset && teleport_z_offset)
A.x = rand(teleport_x, teleport_x_offset)
A.y = rand(teleport_y, teleport_y_offset)
A.z = rand(teleport_z, teleport_z_offset)
/* Fancy teleporter, creates sparks and smokes when used */
/obj/effect/step_trigger/teleport_fancy
var/locationx
var/locationy
var/uses = 1 //0 for infinite uses
var/entersparks = 0
var/exitsparks = 0
var/entersmoke = 0
var/exitsmoke = 0
/obj/effect/step_trigger/teleport_fancy/Trigger(mob/M)
var/dest = locate(locationx, locationy, z)
M.Move(dest)
if(entersparks)
var/datum/effect_system/spark_spread/s = new
s.set_up(4, 1, src)
s.start()
if(exitsparks)
var/datum/effect_system/spark_spread/s = new
s.set_up(4, 1, dest)
s.start()
if(entersmoke)
var/datum/effect_system/smoke_spread/s = new
s.set_up(4, 1, src, 0)
s.start()
if(exitsmoke)
var/datum/effect_system/smoke_spread/s = new
s.set_up(4, 1, dest, 0)
s.start()
uses--
if(uses == 0)
qdel(src)
/* Simple sound player, Mapper friendly! */
/obj/effect/step_trigger/sound_effect
var/sound //eg. path to the sound, inside '' eg: 'growl.ogg'
var/volume = 100
var/freq_vary = 1 //Should the frequency of the sound vary?
var/extra_range = 0 // eg World.view = 7, extra_range = 1, 7+1 = 8, 8 turfs radius
var/happens_once = 0
var/triggerer_only = 0 //Whether the triggerer is the only person who hears this
/obj/effect/step_trigger/sound_effect/Trigger(atom/movable/A)
var/turf/T = get_turf(A)
if(!T)
return
if(triggerer_only && ismob(A))
var/mob/B = A
B.playsound_local(T, sound, volume, freq_vary)
else
playsound(T, sound, volume, freq_vary, extra_range)
if(happens_once)
qdel(src)
| 0 | 0.956298 | 1 | 0.956298 | game-dev | MEDIA | 0.975984 | game-dev | 0.997055 | 1 | 0.997055 |
Overload-Technologies/Overload | 5,309 | Dependencies/bullet3/bullet/BulletCollision/CollisionShapes/btTriangleMeshShape.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 "btTriangleMeshShape.h"
#include "LinearMath/btVector3.h"
#include "LinearMath/btQuaternion.h"
#include "btStridingMeshInterface.h"
#include "LinearMath/btAabbUtil2.h"
#include "BulletCollision/CollisionShapes/btCollisionMargin.h"
btTriangleMeshShape::btTriangleMeshShape(btStridingMeshInterface* meshInterface)
: btConcaveShape(), m_meshInterface(meshInterface)
{
m_shapeType = TRIANGLE_MESH_SHAPE_PROXYTYPE;
if (meshInterface->hasPremadeAabb())
{
meshInterface->getPremadeAabb(&m_localAabbMin, &m_localAabbMax);
}
else
{
recalcLocalAabb();
}
}
btTriangleMeshShape::~btTriangleMeshShape()
{
}
void btTriangleMeshShape::getAabb(const btTransform& trans, btVector3& aabbMin, btVector3& aabbMax) const
{
btVector3 localHalfExtents = btScalar(0.5) * (m_localAabbMax - m_localAabbMin);
localHalfExtents += btVector3(getMargin(), getMargin(), getMargin());
btVector3 localCenter = btScalar(0.5) * (m_localAabbMax + m_localAabbMin);
btMatrix3x3 abs_b = trans.getBasis().absolute();
btVector3 center = trans(localCenter);
btVector3 extent = localHalfExtents.dot3(abs_b[0], abs_b[1], abs_b[2]);
aabbMin = center - extent;
aabbMax = center + extent;
}
void btTriangleMeshShape::recalcLocalAabb()
{
for (int i = 0; i < 3; i++)
{
btVector3 vec(btScalar(0.), btScalar(0.), btScalar(0.));
vec[i] = btScalar(1.);
btVector3 tmp = localGetSupportingVertex(vec);
m_localAabbMax[i] = tmp[i] + m_collisionMargin;
vec[i] = btScalar(-1.);
tmp = localGetSupportingVertex(vec);
m_localAabbMin[i] = tmp[i] - m_collisionMargin;
}
}
class SupportVertexCallback : public btTriangleCallback
{
btVector3 m_supportVertexLocal;
public:
btTransform m_worldTrans;
btScalar m_maxDot;
btVector3 m_supportVecLocal;
SupportVertexCallback(const btVector3& supportVecWorld, const btTransform& trans)
: m_supportVertexLocal(btScalar(0.), btScalar(0.), btScalar(0.)), m_worldTrans(trans), m_maxDot(btScalar(-BT_LARGE_FLOAT))
{
m_supportVecLocal = supportVecWorld * m_worldTrans.getBasis();
}
virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex)
{
(void)partId;
(void)triangleIndex;
for (int i = 0; i < 3; i++)
{
btScalar dot = m_supportVecLocal.dot(triangle[i]);
if (dot > m_maxDot)
{
m_maxDot = dot;
m_supportVertexLocal = triangle[i];
}
}
}
btVector3 GetSupportVertexWorldSpace()
{
return m_worldTrans(m_supportVertexLocal);
}
btVector3 GetSupportVertexLocal()
{
return m_supportVertexLocal;
}
};
void btTriangleMeshShape::setLocalScaling(const btVector3& scaling)
{
m_meshInterface->setScaling(scaling);
recalcLocalAabb();
}
const btVector3& btTriangleMeshShape::getLocalScaling() const
{
return m_meshInterface->getScaling();
}
//#define DEBUG_TRIANGLE_MESH
void btTriangleMeshShape::processAllTriangles(btTriangleCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax) const
{
struct FilteredCallback : public btInternalTriangleIndexCallback
{
btTriangleCallback* m_callback;
btVector3 m_aabbMin;
btVector3 m_aabbMax;
FilteredCallback(btTriangleCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax)
: m_callback(callback),
m_aabbMin(aabbMin),
m_aabbMax(aabbMax)
{
}
virtual void internalProcessTriangleIndex(btVector3* triangle, int partId, int triangleIndex)
{
if (TestTriangleAgainstAabb2(&triangle[0], m_aabbMin, m_aabbMax))
{
//check aabb in triangle-space, before doing this
m_callback->processTriangle(triangle, partId, triangleIndex);
}
}
};
FilteredCallback filterCallback(callback, aabbMin, aabbMax);
m_meshInterface->InternalProcessAllTriangles(&filterCallback, aabbMin, aabbMax);
}
void btTriangleMeshShape::calculateLocalInertia(btScalar mass, btVector3& inertia) const
{
(void)mass;
//moving concave objects not supported
btAssert(0);
inertia.setValue(btScalar(0.), btScalar(0.), btScalar(0.));
}
btVector3 btTriangleMeshShape::localGetSupportingVertex(const btVector3& vec) const
{
btVector3 supportVertex;
btTransform ident;
ident.setIdentity();
SupportVertexCallback supportCallback(vec, ident);
btVector3 aabbMax(btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT));
processAllTriangles(&supportCallback, -aabbMax, aabbMax);
supportVertex = supportCallback.GetSupportVertexLocal();
return supportVertex;
}
| 0 | 0.887083 | 1 | 0.887083 | game-dev | MEDIA | 0.974684 | game-dev | 0.976025 | 1 | 0.976025 |
holycake/mhsj | 985 | d/jz/yamen.c | //Cracked by Roath
inherit ROOM;
void create ()
{
set ("short", "江州知府");
set ("long", @LONG
离老远你就看到一块匾:
[31m ■■■■■■■■■■■■■■■■■■■■■
■ ■
■ [1;37m 江 州 知 府 [0;31m ■
■ ■
■■■■■■■■■■■■■■■■■■■■■[m
LONG);
set("exits",
([ //sizeof() == 4
"east" : __DIR__"xw-2",
"west" : __DIR__"datang",
]));
set("objects",
([ //sizeof() == 1
__DIR__"npc/yayi" : 4,
]));
set("no_clean_up", 0);
setup();
}
int valid_leave(object me, string dir)
{ if (dir == "west") {
if (objectp(present("yayi", environment(me)))) {
if(!present("zhuang zhi", me) && me->query("office_number") < 300 )
return notify_fail("衙役喝道:没有状纸(zhuang zhi),为何乱闯?速速离去!\n");
}
return ::valid_leave(me, dir);
}
return 1;
}
| 0 | 0.663709 | 1 | 0.663709 | game-dev | MEDIA | 0.242277 | game-dev | 0.816394 | 1 | 0.816394 |
ProjectSkyfire/SkyFire.406a | 40,073 | src/server/scripts/EasternKingdoms/MagistersTerrace/boss_priestess_delrissa.cpp | /*
* Copyright (C) 2011-2019 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2019 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2019 ScriptDev2 <https://github.com/scriptdev2/scriptdev2/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Boss_Priestess_Delrissa
SD%Complete: 65
SDComment: No Heroic support yet. Needs further testing. Several scripts for pets disabled, not seem to require any special script.
SDCategory: Magister's Terrace
EndScriptData */
#include "ScriptPCH.h"
#include "magisters_terrace.h"
struct Speech
{
int32 id;
};
static Speech LackeyDeath[]=
{
{-1585013},
{-1585014},
{-1585015},
{-1585016},
};
static Speech PlayerDeath[]=
{
{-1585017},
{-1585018},
{-1585019},
{-1585020},
{-1585021},
};
enum eEnums
{
SAY_AGGRO = -1585012,
SAY_DEATH = -1585022,
SPELL_DISPEL_MAGIC = 27609,
SPELL_FLASH_HEAL = 17843,
SPELL_SW_PAIN_NORMAL = 14032,
SPELL_SW_PAIN_HEROIC = 15654,
SPELL_SHIELD = 44291,
SPELL_RENEW_NORMAL = 44174,
SPELL_RENEW_HEROIC = 46192,
MAX_ACTIVE_LACKEY = 4
};
const float fOrientation = 4.98f;
const float fZLocation = -19.921f;
float LackeyLocations[4][2]=
{
{123.77f, 17.6007f},
{131.731f, 15.0827f},
{121.563f, 15.6213f},
{129.988f, 17.2355f},
};
const uint32 AddEntries[] =
{
24557, //Kagani Nightstrike
24558, //Elris Duskhallow
24554, //Eramas Brightblaze
24561, //Yazzaj
24559, //Warlord Salaris
24555, //Garaxxas
24553, //Apoko
24556, //Zelfan
};
class boss_priestess_delrissa : public CreatureScript
{
public:
boss_priestess_delrissa() : CreatureScript("boss_priestess_delrissa") {}
CreatureAI* GetAI(Creature* creature) const
{
return new boss_priestess_delrissaAI(creature);
}
struct boss_priestess_delrissaAI : public ScriptedAI
{
boss_priestess_delrissaAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
memset(&LackeyGUID, 0, sizeof(LackeyGUID));
LackeyEntryList.clear();
}
InstanceScript* instance;
std::vector<uint32> LackeyEntryList;
uint64 LackeyGUID[MAX_ACTIVE_LACKEY];
uint8 PlayersKilled;
uint32 HealTimer;
uint32 RenewTimer;
uint32 ShieldTimer;
uint32 SWPainTimer;
uint32 DispelTimer;
uint32 ResetTimer;
void Reset()
{
PlayersKilled = 0;
HealTimer = 15000;
RenewTimer = 10000;
ShieldTimer = 2000;
SWPainTimer = 5000;
DispelTimer = 7500;
ResetTimer = 5000;
InitializeLackeys();
}
//this mean she at some point evaded
void JustReachedHome()
{
if (instance)
instance->SetData(DATA_DELRISSA_EVENT, FAIL);
}
void EnterCombat(Unit* who)
{
DoScriptText(SAY_AGGRO, me);
for (uint8 i = 0; i < MAX_ACTIVE_LACKEY; ++i)
{
if (Unit* add = Unit::GetUnit(*me, LackeyGUID[i]))
{
if (!add->getVictim())
{
who->SetInCombatWith(add);
add->AddThreat(who, 0.0f);
}
}
}
if (instance)
instance->SetData(DATA_DELRISSA_EVENT, IN_PROGRESS);
}
void InitializeLackeys()
{
//can be called if Creature are dead, so avoid
if (!me->isAlive())
return;
uint8 j = 0;
//it's empty, so first time
if (LackeyEntryList.empty())
{
//pre-allocate size for speed
LackeyEntryList.resize((sizeof(AddEntries) / sizeof(uint32)));
//fill vector array with entries from Creature array
for (uint8 i = 0; i < LackeyEntryList.size(); ++i)
LackeyEntryList[i] = AddEntries[i];
//remove random entries
while (LackeyEntryList.size() > MAX_ACTIVE_LACKEY)
LackeyEntryList.erase(LackeyEntryList.begin() + rand()%LackeyEntryList.size());
//summon all the remaining in vector
for (std::vector<uint32>::const_iterator itr = LackeyEntryList.begin(); itr != LackeyEntryList.end(); ++itr)
{
if (Creature* add = me->SummonCreature((*itr), LackeyLocations[j][0], LackeyLocations[j][1], fZLocation, fOrientation, TEMPSUMMON_CORPSE_DESPAWN, 0))
LackeyGUID[j] = add->GetGUID();
++j;
}
}
else
{
for (std::vector<uint32>::const_iterator itr = LackeyEntryList.begin(); itr != LackeyEntryList.end(); ++itr)
{
Unit* add = Unit::GetUnit(*me, LackeyGUID[j]);
//object already removed, not exist
if (!add)
{
add = me->SummonCreature((*itr), LackeyLocations[j][0], LackeyLocations[j][1], fZLocation, fOrientation, TEMPSUMMON_CORPSE_DESPAWN, 0);
if (add)
LackeyGUID[j] = add->GetGUID();
}
++j;
}
}
}
void KilledUnit(Unit* victim)
{
if (victim->GetTypeId() != TYPEID_PLAYER)
return;
DoScriptText(PlayerDeath[PlayersKilled].id, me);
if (PlayersKilled < 4)
++PlayersKilled;
}
void JustDied(Unit* /*killer*/)
{
DoScriptText(SAY_DEATH, me);
if (!instance)
return;
if (instance->GetData(DATA_DELRISSA_DEATH_COUNT) == MAX_ACTIVE_LACKEY)
instance->SetData(DATA_DELRISSA_EVENT, DONE);
else
{
if (me->HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE))
me->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
}
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
if (ResetTimer <= diff)
{
float x, y, z, o;
me->GetHomePosition(x, y, z, o);
if (me->GetPositionZ() >= z+10)
{
EnterEvadeMode();
return;
}
ResetTimer = 5000;
}
else ResetTimer -= diff;
if (HealTimer <= diff)
{
uint32 health = me->GetHealth();
Unit* target = me;
for (uint8 i = 0; i < MAX_ACTIVE_LACKEY; ++i)
{
if (Unit* add = Unit::GetUnit(*me, LackeyGUID[i]))
{
if (add->isAlive() && add->GetHealth() < health)
target = add;
}
}
DoCast(target, SPELL_FLASH_HEAL);
HealTimer = 15000;
}
else HealTimer -= diff;
if (RenewTimer <= diff)
{
Unit* target = me;
if (urand(0, 1))
if (Unit* add = Unit::GetUnit(*me, LackeyGUID[rand()%MAX_ACTIVE_LACKEY]))
if (add->isAlive())
target = add;
DoCast(target, SPELL_RENEW_NORMAL);
RenewTimer = 5000;
}
else RenewTimer -= diff;
if (ShieldTimer <= diff)
{
Unit* target = me;
if (urand(0, 1))
if (Unit* add = Unit::GetUnit(*me, LackeyGUID[rand()%MAX_ACTIVE_LACKEY]))
if (add->isAlive() && !add->HasAura(SPELL_SHIELD))
target = add;
DoCast(target, SPELL_SHIELD);
ShieldTimer = 7500;
}
else ShieldTimer -= diff;
if (DispelTimer <= diff)
{
Unit* target = NULL;
if (urand(0, 1))
target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true);
else
{
if (urand(0, 1))
target = me;
else
if (Unit* add = Unit::GetUnit(*me, LackeyGUID[rand()%MAX_ACTIVE_LACKEY]))
if (add->isAlive())
target = add;
}
if (target)
DoCast(target, SPELL_DISPEL_MAGIC);
DispelTimer = 12000;
}
else DispelTimer -= diff;
if (SWPainTimer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
DoCast(target, SPELL_SW_PAIN_NORMAL);
SWPainTimer = 10000;
}
else SWPainTimer -= diff;
DoMeleeAttackIfReady();
}
};
};
enum eHealingPotion
{
SPELL_HEALING_POTION = 15503
};
//all 8 possible lackey use this common
struct boss_priestess_lackey_commonAI : public ScriptedAI
{
boss_priestess_lackey_commonAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
memset(&LackeyGUIDs, 0, sizeof(LackeyGUIDs));
AcquireGUIDs();
}
InstanceScript* instance;
uint64 LackeyGUIDs[MAX_ACTIVE_LACKEY];
uint32 ResetThreatTimer;
bool UsedPotion;
void Reset()
{
UsedPotion = false;
// These guys does not follow normal threat system rules
// For later development, some alternative threat system should be made
// We do not know what this system is based upon, but one theory is class (healers=high threat, dps=medium, etc)
// We reset their threat frequently as an alternative until such a system exist
ResetThreatTimer = urand(5000, 20000);
// in case she is not alive and Reset was for some reason called, respawn her (most likely party wipe after killing her)
if (Creature* delrissa = Unit::GetCreature(*me, instance ? instance->GetData64(DATA_DELRISSA) : 0))
{
if (!delrissa->isAlive())
delrissa->Respawn();
}
}
void EnterCombat(Unit* who)
{
if (!who)
return;
if (instance)
{
for (uint8 i = 0; i < MAX_ACTIVE_LACKEY; ++i)
{
if (Unit* add = Unit::GetUnit(*me, LackeyGUIDs[i]))
{
if (!add->getVictim() && add != me)
{
who->SetInCombatWith(add);
add->AddThreat(who, 0.0f);
}
}
}
if (Creature* delrissa = Unit::GetCreature(*me, instance->GetData64(DATA_DELRISSA)))
{
if (delrissa->isAlive() && !delrissa->getVictim())
{
who->SetInCombatWith(delrissa);
delrissa->AddThreat(who, 0.0f);
}
}
}
}
void JustDied(Unit* /*killer*/)
{
if (!instance)
return;
Creature* delrissa = Unit::GetCreature(*me, instance->GetData64(DATA_DELRISSA));
uint32 LackeyDeathCount = instance->GetData(DATA_DELRISSA_DEATH_COUNT);
if (!delrissa)
return;
//should delrissa really yell if dead?
DoScriptText(LackeyDeath[LackeyDeathCount].id, delrissa);
instance->SetData(DATA_DELRISSA_DEATH_COUNT, SPECIAL);
//increase local var, since we now may have four dead
++LackeyDeathCount;
if (LackeyDeathCount == MAX_ACTIVE_LACKEY)
{
//time to make her lootable and complete event if she died before lackeys
if (!delrissa->isAlive())
{
if (!delrissa->HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE))
delrissa->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
instance->SetData(DATA_DELRISSA_EVENT, DONE);
}
}
}
void KilledUnit(Unit* victim)
{
if (!instance)
return;
if (Creature* Delrissa = Unit::GetCreature(*me, instance->GetData64(DATA_DELRISSA)))
Delrissa->AI()->KilledUnit(victim);
}
void AcquireGUIDs()
{
if (!instance)
return;
if (Creature* Delrissa = (Unit::GetCreature(*me, instance->GetData64(DATA_DELRISSA))))
{
for (uint8 i = 0; i < MAX_ACTIVE_LACKEY; ++i)
LackeyGUIDs[i] = CAST_AI(boss_priestess_delrissa::boss_priestess_delrissaAI, Delrissa->AI())->LackeyGUID[i];
}
}
void UpdateAI(const uint32 diff)
{
if (!UsedPotion && HealthBelowPct(25))
{
DoCast(me, SPELL_HEALING_POTION);
UsedPotion = true;
}
if (ResetThreatTimer <= diff)
{
DoResetThreat();
ResetThreatTimer = urand(5000, 20000);
}
else ResetThreatTimer -= diff;
}
};
enum eRogueSpells
{
SPELL_KIDNEY_SHOT = 27615,
SPELL_GOUGE = 12540,
SPELL_KICK = 27613,
SPELL_VANISH = 44290,
SPELL_BACKSTAB = 15657,
SPELL_EVISCERATE = 27611
};
class boss_kagani_nightstrike : public CreatureScript
{
public:
boss_kagani_nightstrike() : CreatureScript("boss_kagani_nightstrike") {}
CreatureAI* GetAI(Creature* creature) const
{
return new boss_kagani_nightstrikeAI(creature);
}
struct boss_kagani_nightstrikeAI : public boss_priestess_lackey_commonAI
{
//Rogue
boss_kagani_nightstrikeAI(Creature* creature) : boss_priestess_lackey_commonAI(creature) {}
uint32 Gouge_Timer;
uint32 Kick_Timer;
uint32 Vanish_Timer;
uint32 Eviscerate_Timer;
uint32 Wait_Timer;
bool InVanish;
void Reset()
{
Gouge_Timer = 5500;
Kick_Timer = 7000;
Vanish_Timer = 2000;
Eviscerate_Timer = 6000;
Wait_Timer = 5000;
InVanish = false;
me->SetVisible(true);
boss_priestess_lackey_commonAI::Reset();
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
boss_priestess_lackey_commonAI::UpdateAI(diff);
if (Vanish_Timer <= diff)
{
DoCast(me, SPELL_VANISH);
Unit* unit = SelectTarget(SELECT_TARGET_RANDOM, 0);
DoResetThreat();
if (unit)
me->AddThreat(unit, 1000.0f);
InVanish = true;
Vanish_Timer = 30000;
Wait_Timer = 10000;
}
else Vanish_Timer -= diff;
if (InVanish)
{
if (Wait_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_BACKSTAB, true);
DoCast(me->getVictim(), SPELL_KIDNEY_SHOT, true);
me->SetVisible(true); // ...? Hacklike
InVanish = false;
}
else Wait_Timer -= diff;
}
if (Gouge_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_GOUGE);
Gouge_Timer = 5500;
}
else Gouge_Timer -= diff;
if (Kick_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_KICK);
Kick_Timer = 7000;
}
else Kick_Timer -= diff;
if (Eviscerate_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_EVISCERATE);
Eviscerate_Timer = 4000;
}
else Eviscerate_Timer -= diff;
if (!InVanish)
DoMeleeAttackIfReady();
}
};
};
enum eWarlockSpells
{
SPELL_IMMOLATE = 44267,
SPELL_SHADOW_BOLT = 12471,
SPELL_SEED_OF_CORRUPTION = 44141,
SPELL_CURSE_OF_AGONY = 14875,
SPELL_FEAR = 38595,
SPELL_IMP_FIREBALL = 44164,
SPELL_SUMMON_IMP = 44163
};
class boss_ellris_duskhallow : public CreatureScript
{
public:
boss_ellris_duskhallow() : CreatureScript("boss_ellris_duskhallow") {}
CreatureAI* GetAI(Creature* creature) const
{
return new boss_ellris_duskhallowAI(creature);
}
struct boss_ellris_duskhallowAI : public boss_priestess_lackey_commonAI
{
//Warlock
boss_ellris_duskhallowAI(Creature* creature) : boss_priestess_lackey_commonAI(creature) {}
uint32 Immolate_Timer;
uint32 Shadow_Bolt_Timer;
uint32 Seed_of_Corruption_Timer;
uint32 Curse_of_Agony_Timer;
uint32 Fear_Timer;
void Reset()
{
Immolate_Timer = 6000;
Shadow_Bolt_Timer = 3000;
Seed_of_Corruption_Timer = 2000;
Curse_of_Agony_Timer = 1000;
Fear_Timer = 10000;
boss_priestess_lackey_commonAI::Reset();
}
void EnterCombat(Unit* /*who*/)
{
DoCast(me, SPELL_SUMMON_IMP);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
boss_priestess_lackey_commonAI::UpdateAI(diff);
if (Immolate_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_IMMOLATE);
Immolate_Timer = 6000;
}
else Immolate_Timer -= diff;
if (Shadow_Bolt_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_SHADOW_BOLT);
Shadow_Bolt_Timer = 5000;
}
else Shadow_Bolt_Timer -= diff;
if (Seed_of_Corruption_Timer <= diff)
{
if (Unit* unit = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(unit, SPELL_SEED_OF_CORRUPTION);
Seed_of_Corruption_Timer = 10000;
}
else Seed_of_Corruption_Timer -= diff;
if (Curse_of_Agony_Timer <= diff)
{
if (Unit* unit = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(unit, SPELL_CURSE_OF_AGONY);
Curse_of_Agony_Timer = 13000;
}
else Curse_of_Agony_Timer -= diff;
if (Fear_Timer <= diff)
{
if (Unit* unit = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(unit, SPELL_FEAR);
Fear_Timer = 10000;
}
else Fear_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
enum eKickDown
{
SPELL_KNOCKDOWN = 11428,
SPELL_SNAP_KICK = 46182
};
class boss_eramas_brightblaze : public CreatureScript
{
public:
boss_eramas_brightblaze() : CreatureScript("boss_eramas_brightblaze") {}
CreatureAI* GetAI(Creature* creature) const
{
return new boss_eramas_brightblazeAI(creature);
}
struct boss_eramas_brightblazeAI : public boss_priestess_lackey_commonAI
{
//Monk
boss_eramas_brightblazeAI(Creature* creature) : boss_priestess_lackey_commonAI(creature) {}
uint32 Knockdown_Timer;
uint32 Snap_Kick_Timer;
void Reset()
{
Knockdown_Timer = 6000;
Snap_Kick_Timer = 4500;
boss_priestess_lackey_commonAI::Reset();
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
boss_priestess_lackey_commonAI::UpdateAI(diff);
if (Knockdown_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_KNOCKDOWN);
Knockdown_Timer = 6000;
}
else Knockdown_Timer -= diff;
if (Snap_Kick_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_SNAP_KICK);
Snap_Kick_Timer = 4500;
}
else Snap_Kick_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
enum eMageSpells
{
SPELL_POLYMORPH = 13323,
SPELL_ICE_BLOCK = 27619,
SPELL_BLIZZARD = 44178,
SPELL_ICE_LANCE = 46194,
SPELL_CONE_OF_COLD = 38384,
SPELL_FROSTBOLT = 15043,
SPELL_BLINK = 14514
};
class boss_yazzai : public CreatureScript
{
public:
boss_yazzai() : CreatureScript("boss_yazzai") {}
CreatureAI* GetAI(Creature* creature) const
{
return new boss_yazzaiAI(creature);
}
struct boss_yazzaiAI : public boss_priestess_lackey_commonAI
{
//Mage
boss_yazzaiAI(Creature* creature) : boss_priestess_lackey_commonAI(creature) {}
bool HasIceBlocked;
uint32 Polymorph_Timer;
uint32 Ice_Block_Timer;
uint32 Wait_Timer;
uint32 Blizzard_Timer;
uint32 Ice_Lance_Timer;
uint32 Cone_of_Cold_Timer;
uint32 Frostbolt_Timer;
uint32 Blink_Timer;
void Reset()
{
HasIceBlocked = false;
Polymorph_Timer = 1000;
Ice_Block_Timer = 20000;
Wait_Timer = 10000;
Blizzard_Timer = 8000;
Ice_Lance_Timer = 12000;
Cone_of_Cold_Timer = 10000;
Frostbolt_Timer = 3000;
Blink_Timer = 8000;
boss_priestess_lackey_commonAI::Reset();
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
boss_priestess_lackey_commonAI::UpdateAI(diff);
if (Polymorph_Timer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
{
DoCast(target, SPELL_POLYMORPH);
Polymorph_Timer = 20000;
}
}
else Polymorph_Timer -= diff;
if (HealthBelowPct(35) && !HasIceBlocked)
{
DoCast(me, SPELL_ICE_BLOCK);
HasIceBlocked = true;
}
if (Blizzard_Timer <= diff)
{
if (Unit* unit = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(unit, SPELL_BLIZZARD);
Blizzard_Timer = 8000;
}
else Blizzard_Timer -= diff;
if (Ice_Lance_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_ICE_LANCE);
Ice_Lance_Timer = 12000;
}
else Ice_Lance_Timer -= diff;
if (Cone_of_Cold_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_CONE_OF_COLD);
Cone_of_Cold_Timer = 10000;
}
else Cone_of_Cold_Timer -= diff;
if (Frostbolt_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_FROSTBOLT);
Frostbolt_Timer = 8000;
}
else Frostbolt_Timer -= diff;
if (Blink_Timer <= diff)
{
bool InMeleeRange = false;
std::list<HostileReference*>& t_list = me->getThreatManager().getThreatList();
for (std::list<HostileReference*>::const_iterator itr = t_list.begin(); itr!= t_list.end(); ++itr)
{
if (Unit* target = Unit::GetUnit(*me, (*itr)->getUnitGuid()))
{
//if in melee range
if (target->IsWithinDistInMap(me, 5))
{
InMeleeRange = true;
break;
}
}
}
//if anybody is in melee range than escape by blink
if (InMeleeRange)
DoCast(me, SPELL_BLINK);
Blink_Timer = 8000;
}
else Blink_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
enum eWarriorSpells
{
SPELL_INTERCEPT_STUN = 27577,
SPELL_DISARM = 27581,
SPELL_PIERCING_HOWL = 23600,
SPELL_FRIGHTENING_SHOUT = 19134,
SPELL_HAMSTRING = 27584,
SPELL_BATTLE_SHOUT = 27578,
SPELL_MORTAL_STRIKE = 44268
};
class boss_warlord_salaris : public CreatureScript
{
public:
boss_warlord_salaris() : CreatureScript("boss_warlord_salaris") {}
CreatureAI* GetAI(Creature* creature) const
{
return new boss_warlord_salarisAI(creature);
}
struct boss_warlord_salarisAI : public boss_priestess_lackey_commonAI
{
//Warrior
boss_warlord_salarisAI(Creature* creature) : boss_priestess_lackey_commonAI(creature) {}
uint32 Intercept_Stun_Timer;
uint32 Disarm_Timer;
uint32 Piercing_Howl_Timer;
uint32 Frightening_Shout_Timer;
uint32 Hamstring_Timer;
uint32 Mortal_Strike_Timer;
void Reset()
{
Intercept_Stun_Timer = 500;
Disarm_Timer = 6000;
Piercing_Howl_Timer = 10000;
Frightening_Shout_Timer = 18000;
Hamstring_Timer = 4500;
Mortal_Strike_Timer = 8000;
boss_priestess_lackey_commonAI::Reset();
}
void EnterCombat(Unit* /*who*/)
{
DoCast(me, SPELL_BATTLE_SHOUT);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
boss_priestess_lackey_commonAI::UpdateAI(diff);
if (Intercept_Stun_Timer <= diff)
{
bool InMeleeRange = false;
std::list<HostileReference*>& t_list = me->getThreatManager().getThreatList();
for (std::list<HostileReference*>::const_iterator itr = t_list.begin(); itr!= t_list.end(); ++itr)
{
if (Unit* target = Unit::GetUnit(*me, (*itr)->getUnitGuid()))
{
//if in melee range
if (target->IsWithinDistInMap(me, ATTACK_DISTANCE))
{
InMeleeRange = true;
break;
}
}
}
//if nobody is in melee range than try to use Intercept
if (!InMeleeRange)
{
if (Unit* unit = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(unit, SPELL_INTERCEPT_STUN);
}
Intercept_Stun_Timer = 10000;
}
else Intercept_Stun_Timer -= diff;
if (Disarm_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_DISARM);
Disarm_Timer = 6000;
}
else Disarm_Timer -= diff;
if (Hamstring_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_HAMSTRING);
Hamstring_Timer = 4500;
}
else Hamstring_Timer -= diff;
if (Mortal_Strike_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_MORTAL_STRIKE);
Mortal_Strike_Timer = 4500;
}
else Mortal_Strike_Timer -= diff;
if (Piercing_Howl_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_PIERCING_HOWL);
Piercing_Howl_Timer = 10000;
}
else Piercing_Howl_Timer -= diff;
if (Frightening_Shout_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_FRIGHTENING_SHOUT);
Frightening_Shout_Timer = 18000;
}
else Frightening_Shout_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
enum eHunterSpells
{
SPELL_AIMED_SHOT = 44271,
SPELL_SHOOT = 15620,
SPELL_CONCUSSIVE_SHOT = 27634,
SPELL_MULTI_SHOT = 31942,
SPELL_WING_CLIP = 44286,
SPELL_FREEZING_TRAP = 44136,
NPC_SLIVER = 24552
};
class boss_garaxxas : public CreatureScript
{
public:
boss_garaxxas() : CreatureScript("boss_garaxxas") {}
CreatureAI* GetAI(Creature* creature) const
{
return new boss_garaxxasAI(creature);
}
struct boss_garaxxasAI : public boss_priestess_lackey_commonAI
{
//Hunter
boss_garaxxasAI(Creature* creature) : boss_priestess_lackey_commonAI(creature) { PetGUID = 0; }
uint64 PetGUID;
uint32 Aimed_Shot_Timer;
uint32 Shoot_Timer;
uint32 Concussive_Shot_Timer;
uint32 Multi_Shot_Timer;
uint32 Wing_Clip_Timer;
uint32 Freezing_Trap_Timer;
void Reset()
{
Aimed_Shot_Timer = 6000;
Shoot_Timer = 2500;
Concussive_Shot_Timer = 8000;
Multi_Shot_Timer = 10000;
Wing_Clip_Timer = 4000;
Freezing_Trap_Timer = 15000;
Unit* pet = Unit::GetUnit(*me, PetGUID);
if (!pet)
me->SummonCreature(NPC_SLIVER, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_CORPSE_DESPAWN, 0);
boss_priestess_lackey_commonAI::Reset();
}
void JustSummoned(Creature* summoned)
{
PetGUID = summoned->GetGUID();
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
boss_priestess_lackey_commonAI::UpdateAI(diff);
if (me->IsWithinDistInMap(me->getVictim(), ATTACK_DISTANCE))
{
if (Wing_Clip_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_WING_CLIP);
Wing_Clip_Timer = 4000;
}
else Wing_Clip_Timer -= diff;
if (Freezing_Trap_Timer <= diff)
{
//attempt find go summoned from spell (casted by me)
GameObject* go = me->GetGameObject(SPELL_FREEZING_TRAP);
//if we have a go, we need to wait (only one trap at a time)
if (go)
Freezing_Trap_Timer = 2500;
else
{
//if go does not exist, then we can cast
DoCast(me->getVictim(), SPELL_FREEZING_TRAP);
Freezing_Trap_Timer = 15000;
}
}
else Freezing_Trap_Timer -= diff;
DoMeleeAttackIfReady();
}
else
{
if (Concussive_Shot_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_CONCUSSIVE_SHOT);
Concussive_Shot_Timer = 8000;
}
else Concussive_Shot_Timer -= diff;
if (Multi_Shot_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_MULTI_SHOT);
Multi_Shot_Timer = 10000;
}
else Multi_Shot_Timer -= diff;
if (Aimed_Shot_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_AIMED_SHOT);
Aimed_Shot_Timer = 6000;
}
else Aimed_Shot_Timer -= diff;
if (Shoot_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_SHOOT);
Shoot_Timer = 2500;
}
else Shoot_Timer -= diff;
}
}
};
};
enum Spells
{
SPELL_WINDFURY_TOTEM = 27621,
SPELL_WAR_STOMP = 46026,
SPELL_PURGE = 27626,
SPELL_LESSER_HEALING_WAVE = 44256,
SPELL_FROST_SHOCK = 21401,
SPELL_FIRE_NOVA_TOTEM = 44257,
SPELL_EARTHBIND_TOTEM = 15786
};
class boss_apoko : public CreatureScript
{
public:
boss_apoko() : CreatureScript("boss_apoko") {}
CreatureAI* GetAI(Creature* creature) const
{
return new boss_apokoAI(creature);
}
struct boss_apokoAI : public boss_priestess_lackey_commonAI
{
//Shaman
boss_apokoAI(Creature* creature) : boss_priestess_lackey_commonAI(creature) {}
uint32 Totem_Timer;
uint8 Tote_Amount;
uint32 War_Stomp_Timer;
uint32 Purge_Timer;
uint32 Healing_Wave_Timer;
uint32 Frost_Shock_Timer;
void Reset()
{
Totem_Timer = 2000;
Tote_Amount = 1;
War_Stomp_Timer = 10000;
Purge_Timer = 8000;
Healing_Wave_Timer = 5000;
Frost_Shock_Timer = 7000;
boss_priestess_lackey_commonAI::Reset();
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
boss_priestess_lackey_commonAI::UpdateAI(diff);
if (Totem_Timer <= diff)
{
DoCast(me, RAND(SPELL_WINDFURY_TOTEM, SPELL_FIRE_NOVA_TOTEM, SPELL_EARTHBIND_TOTEM));
++Tote_Amount;
Totem_Timer = Tote_Amount*2000;
}
else Totem_Timer -= diff;
if (War_Stomp_Timer <= diff)
{
DoCast(me, SPELL_WAR_STOMP);
War_Stomp_Timer = 10000;
}
else War_Stomp_Timer -= diff;
if (Purge_Timer <= diff)
{
if (Unit* unit = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(unit, SPELL_PURGE);
Purge_Timer = 15000;
}
else Purge_Timer -= diff;
if (Frost_Shock_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_FROST_SHOCK);
Frost_Shock_Timer = 7000;
}
else Frost_Shock_Timer -= diff;
if (Healing_Wave_Timer <= diff)
{
// std::vector<Add*>::const_iterator itr = Group.begin() + rand()%Group.size();
// uint64 guid = (*itr)->guid;
// if (guid)
// {
// Unit* add = Unit::GetUnit(*me, (*itr)->guid);
// if (add && add->isAlive())
// {
DoCast(me, SPELL_LESSER_HEALING_WAVE);
Healing_Wave_Timer = 5000;
// }
// }
}
else Healing_Wave_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
enum eEngineerSpells
{
SPELL_GOBLIN_DRAGON_GUN = 44272,
SPELL_ROCKET_LAUNCH = 44137,
SPELL_RECOMBOBULATE = 44274,
SPELL_HIGH_EXPLOSIVE_SHEEP = 44276,
SPELL_FEL_IRON_BOMB = 46024,
SPELL_SHEEP_EXPLOSION = 44279
};
class boss_zelfan : public CreatureScript
{
public:
boss_zelfan() : CreatureScript("boss_zelfan") {}
CreatureAI* GetAI(Creature* creature) const
{
return new boss_zelfanAI(creature);
}
struct boss_zelfanAI : public boss_priestess_lackey_commonAI
{
//Engineer
boss_zelfanAI(Creature* creature) : boss_priestess_lackey_commonAI(creature) {}
uint32 Goblin_Dragon_Gun_Timer;
uint32 Rocket_Launch_Timer;
uint32 Recombobulate_Timer;
uint32 High_Explosive_Sheep_Timer;
uint32 Fel_Iron_Bomb_Timer;
void Reset()
{
Goblin_Dragon_Gun_Timer = 20000;
Rocket_Launch_Timer = 7000;
Recombobulate_Timer = 4000;
High_Explosive_Sheep_Timer = 10000;
Fel_Iron_Bomb_Timer = 15000;
boss_priestess_lackey_commonAI::Reset();
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
boss_priestess_lackey_commonAI::UpdateAI(diff);
if (Goblin_Dragon_Gun_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_GOBLIN_DRAGON_GUN);
Goblin_Dragon_Gun_Timer = 10000;
} else Goblin_Dragon_Gun_Timer -= diff;
if (Rocket_Launch_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_ROCKET_LAUNCH);
Rocket_Launch_Timer = 9000;
} else Rocket_Launch_Timer -= diff;
if (Fel_Iron_Bomb_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_FEL_IRON_BOMB);
Fel_Iron_Bomb_Timer = 15000;
} else Fel_Iron_Bomb_Timer -= diff;
if (Recombobulate_Timer <= diff)
{
for (uint8 i = 0; i < MAX_ACTIVE_LACKEY; ++i)
{
if (Unit* add = Unit::GetUnit(*me, LackeyGUIDs[i]))
{
if (add->IsPolymorphed())
{
DoCast(add, SPELL_RECOMBOBULATE);
break;
}
}
}
Recombobulate_Timer = 2000;
}
else Recombobulate_Timer -= diff;
if (High_Explosive_Sheep_Timer <= diff)
{
DoCast(me, SPELL_HIGH_EXPLOSIVE_SHEEP);
High_Explosive_Sheep_Timer = 65000;
}
else High_Explosive_Sheep_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
/*
class mob_high_explosive_sheep : public CreatureScript
{
public:
mob_high_explosive_sheep() : CreatureScript("mob_high_explosive_sheep") {}
//CreatureAI* GetAI(Creature* creature) const
//{
// return new mob_high_explosive_sheepAI (creature);
//};
};
*/
void AddSC_boss_priestess_delrissa()
{
new boss_priestess_delrissa();
new boss_kagani_nightstrike();
new boss_ellris_duskhallow();
new boss_eramas_brightblaze();
new boss_yazzai();
new boss_warlord_salaris();
new boss_garaxxas();
new boss_apoko();
new boss_zelfan();
// new mob_high_explosive_sheep();
}
| 0 | 0.983059 | 1 | 0.983059 | game-dev | MEDIA | 0.967569 | game-dev | 0.989484 | 1 | 0.989484 |
SkytAsul/BeautyQuests | 3,238 | integrations/src/main/java/fr/skytasul/quests/integrations/npcs/BQFancyNPCs.java | package fr.skytasul.quests.integrations.npcs;
import de.oliver.fancynpcs.api.FancyNpcsPlugin;
import de.oliver.fancynpcs.api.Npc;
import de.oliver.fancynpcs.api.NpcData;
import de.oliver.fancynpcs.api.actions.ActionTrigger;
import de.oliver.fancynpcs.api.events.NpcInteractEvent;
import fr.skytasul.quests.api.npcs.BqInternalNpc;
import fr.skytasul.quests.api.npcs.BqInternalNpcFactory.BqInternalNpcFactoryCreatable;
import fr.skytasul.quests.api.npcs.NpcClickType;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.stream.Collectors;
public class BQFancyNPCs implements BqInternalNpcFactoryCreatable, Listener {
@Override
public int getTimeToWaitForNPCs() {
return 105;
}
@Override
public Collection<String> getIDs() {
return FancyNpcsPlugin.get().getNpcManager().getAllNpcs().stream().map(npc -> npc.getData().getName()).collect(Collectors.toList());
}
@Override
public boolean isNPC(Entity entity) {
return false;
}
@Override
public BqInternalNpc fetchNPC(String internalId) {
Npc npc = FancyNpcsPlugin.get().getNpcManager().getNpc(internalId);
return npc == null ? null : new BQFancyNpc(npc);
}
@Override
public boolean isValidEntityType(EntityType type) {
return true;
}
@Override
public @NotNull BqInternalNpc create(@NotNull Location location, @NotNull EntityType type, @NotNull String name,
@Nullable String skin) {
String id;
int i = 1;
while (FancyNpcsPlugin.get().getNpcManager().getNpc(id = name + "-" + i) != null) {
i++;
}
NpcData npcData = new NpcData(id, null, location);
npcData.setType(type);
Npc npc = FancyNpcsPlugin.get().getNpcAdapter().apply(npcData);
FancyNpcsPlugin.get().getNpcManager().registerNpc(npc);
return new BQFancyNpc(npc);
}
@EventHandler
public void onInteract(NpcInteractEvent e) {
npcClicked(null, e.getNpc().getData().getName(), e.getPlayer(),
NpcClickType.of(e.getInteractionType() == ActionTrigger.LEFT_CLICK, e.getPlayer().isSneaking()));
}
public static class BQFancyNpc implements BqInternalNpc {
private final Npc npc;
private BQFancyNpc(Npc npc) {
this.npc = npc;
}
@Override
public String getInternalId() {
return npc.getData().getName();
}
@Override
public String getName() {
return npc.getData().getDisplayName();
}
@Override
public boolean isSpawned() {
return true;
}
@Override
public Entity getEntity() {
return null;
}
@Override
public Location getLocation() {
return npc.getData().getLocation();
}
@Override
public boolean setNavigationPaused(boolean paused) {
return true;
}
}
} | 0 | 0.715955 | 1 | 0.715955 | game-dev | MEDIA | 0.843315 | game-dev | 0.905298 | 1 | 0.905298 |
esmini/esmini | 1,610 | EnvironmentSimulator/Modules/ScenarioEngine/OSCTypeDefs/OSCParameterDeclarations.hpp | /*
* esmini - Environment Simulator Minimalistic
* https://github.com/esmini/esmini
*
* 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/.
*
* Copyright (c) partners of Simulation Scenarios
* https://sites.google.com/view/simulationscenarios
*/
#pragma once
#include <iostream>
#include <string>
#include <iostream>
#include <string>
#include <vector>
#include "CommonMini.hpp"
namespace scenarioengine
{
class OSCParameterDeclarations
{
public:
enum class ParameterType
{
PARAM_TYPE_NONE,
PARAM_TYPE_INTEGER,
PARAM_TYPE_DOUBLE,
PARAM_TYPE_STRING,
PARAM_TYPE_BOOL
};
struct ParameterStruct
{
std::string name;
ParameterType type = ParameterType::PARAM_TYPE_NONE;
struct value
{
int _int = 0;
double _double = 0;
std::string _string;
bool _bool = false;
} value;
bool variable = false;
bool dirty = false;
};
std::vector<ParameterStruct> Parameter;
void* getValueFromStruct(ParameterStruct* p)
{
return static_cast<void*>(&p->value._int);
}
void* setValueInStruct(ParameterStruct* p)
{
return static_cast<void*>(&p->value._int);
}
};
} // namespace scenarioengine | 0 | 0.907039 | 1 | 0.907039 | game-dev | MEDIA | 0.363891 | game-dev | 0.795727 | 1 | 0.795727 |
Apress/build-your-own-2d-game-engine | 1,683 | BookSourceCode/Chapter10/10.2.ParallaxObjects/public_html/src/Engine/Physics/RigidCircle_Collision.js | /*
* File: RigidCircle_Collision.js
* Detects RigidCircle collisions
*/
/*jslint node: true, vars:true , white: true*/
/*global RigidShape, RigidCircle, vec2, LineRenderable */
/* find out more about jslint: http://www.jslint.com/help.html */
"use strict";
RigidCircle.prototype.containsPos = function(pos) {
var dist = vec2.distance(this.getPosition(), pos);
return (dist < this.getRadius());
};
RigidCircle.prototype.collidedCircCirc = function(c1, c2, collisionInfo) {
var vFrom1to2 = [0, 0];
vec2.sub(vFrom1to2, c2.getPosition(), c1.getPosition());
var rSum = c1.getRadius() + c2.getRadius();
var sqLen = vec2.squaredLength(vFrom1to2);
if (sqLen > (rSum * rSum)) {
return false;
}
var dist = Math.sqrt(sqLen);
if (dist !== 0) { // overlapping
vec2.scale(vFrom1to2, vFrom1to2, 1/dist);
collisionInfo.setNormal(vFrom1to2);
collisionInfo.setDepth(rSum - dist);
}
else //same position
{
collisionInfo.setDepth(rSum / 10);
collisionInfo.setNormal([0, 1]);
}
return true;
};
RigidCircle.prototype.collided = function(otherShape, collisionInfo) {
var status = false;
var n;
collisionInfo.setDepth(0);
switch (otherShape.rigidType()) {
case RigidShape.eRigidType.eRigidCircle:
status = this.collidedCircCirc(this, otherShape, collisionInfo);
break;
case RigidShape.eRigidType.eRigidRectangle:
status = this.collidedRectCirc(otherShape, this, collisionInfo);
n = collisionInfo.getNormal();
n[0] = -n[0];
n[1] = -n[1];
break;
}
return status;
}; | 0 | 0.873318 | 1 | 0.873318 | game-dev | MEDIA | 0.923267 | game-dev | 0.941241 | 1 | 0.941241 |
lua9520/source-engine-2018-hl2_src | 25,580 | game/client/econ/item_pickup_panel.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "vgui/IInput.h"
#include <vgui/IVGui.h>
#include <vgui/IScheme.h>
#include <vgui/ILocalize.h>
#include "vgui_controls/TextImage.h"
#include "ienginevgui.h"
#include "iclientmode.h"
#include "baseviewport.h"
#include "item_pickup_panel.h"
#include "econ_ui.h"
#include "econ_item_inventory.h"
#include "econ_item_constants.h"
#include "item_confirm_delete_dialog.h"
#include "backpack_panel.h"
#ifdef TF_CLIENT_DLL
#include "c_tf_freeaccount.h"
#include "clientmode_tf.h"
#include "quest_log_panel.h"
#endif
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CItemPickupPanel::CItemPickupPanel( Panel *parent ) : Frame( parent, "item_pickup" )
{
vgui::VPANEL gameuiPanel = enginevgui->GetPanel( PANEL_GAMEUIDLL );
SetParent( gameuiPanel );
// We don't want the gameui to delete us, or things get messy
SetAutoDelete( false );
SetMoveable( false );
SetSizeable( false );
vgui::HScheme scheme = vgui::scheme()->LoadSchemeFromFileEx( enginevgui->GetPanel( PANEL_CLIENTDLL ), "resource/ClientScheme.res", "ClientScheme");
SetScheme(scheme);
SetProportional( true );
m_pNextButton = new vgui::Button( this, "NextButton", "#Next" );
m_pPrevButton = new vgui::Button( this, "PrevButton", "#Prev" );
m_pDiscardButton = NULL;
m_pDiscardedLabel = NULL;
m_pOpenLoadoutButton = NULL;
m_pConfirmDeleteDialog = NULL;
m_pModelPanelsKV = NULL;
m_bRandomizePickupMethods = false;
m_pItemFoundMethod = NULL;
m_pCloseButton = NULL;
for ( int i = 0; i < ITEMPICKUP_NUM_MODELPANELS; i++ )
{
m_aModelPanels[i] = new CItemModelPanel( this, VarArgs("modelpanel%d", i) );
}
ListenForGameEvent( "gameui_hidden" );
vgui::EditablePanel *pToolTipPanel = new vgui::EditablePanel( this, "DiscardButtonTooltip" );
m_pToolTip = new CSimplePanelToolTip( this );
m_pToolTip->SetControlledPanel( pToolTipPanel );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CItemPickupPanel::~CItemPickupPanel()
{
if ( m_pModelPanelsKV )
{
m_pModelPanelsKV->deleteThis();
m_pModelPanelsKV = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemPickupPanel::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
LoadControlSettings( "Resource/UI/econ/ItemPickupPanel.res" );
m_pItemsFoundLabel = dynamic_cast<vgui::Label*>(FindChildByName( "ItemsFoundLabel" ));
m_pDiscardedLabel = dynamic_cast<vgui::Label*>( FindChildByName("DiscardedLabel") );
m_pItemFoundMethod = dynamic_cast<vgui::Label*>(FindChildByName( "SelectedItemFoundMethodLabel" ));
for ( int i = 0; i < ITEMPICKUP_NUM_MODELPANELS; i++ )
{
m_aModelPanels[i]->SetPaintBackgroundType( 2 );
}
m_pDiscardButton = dynamic_cast<CExImageButton*>( FindChildByName("DiscardButton") );
if ( m_pDiscardButton )
{
m_pDiscardButton->SetTooltip( m_pToolTip, "" );
}
m_pOpenLoadoutButton = dynamic_cast<vgui::Button*>( FindChildByName("OpenLoadoutButton") );
m_pCloseButton = dynamic_cast<CExButton*>( FindChildByName("CloseButton") );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemPickupPanel::ApplySettings( KeyValues *inResourceData )
{
BaseClass::ApplySettings( inResourceData );
KeyValues *pModelKV = inResourceData->FindKey( "modelpanelskv" );
if ( pModelKV )
{
if ( m_pModelPanelsKV )
{
m_pModelPanelsKV->deleteThis();
}
m_pModelPanelsKV = new KeyValues("modelpanelkv");
pModelKV->CopySubkeys( m_pModelPanelsKV );
for ( int i = 0; i < ITEMPICKUP_NUM_MODELPANELS; i++ )
{
m_aModelPanels[i]->ApplySettings( m_pModelPanelsKV );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemPickupPanel::PerformLayout( void )
{
if ( GetVParent() )
{
int w,h;
vgui::ipanel()->GetSize( GetVParent(), w, h );
SetBounds(0,0,w,h);
}
BaseClass::PerformLayout();
// Now lay out our model panels
for ( int i = 0; i < ITEMPICKUP_NUM_MODELPANELS; i++ )
{
int iPos = (i - ITEMPICKUP_MODELPANEL_CENTER);
int iXPos = (GetWide() * 0.5) + (iPos * m_iModelPanelSpacing) + (iPos * m_iModelPanelW) - (m_iModelPanelW * 0.5);
m_aModelPanels[i]->SetBounds( iXPos, m_iModelPanelY, m_iModelPanelW, m_iModelPanelH );
m_aModelPanels[i]->SetVisible( m_aModelPanels[i]->HasItem() );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemPickupPanel::ShowPanel(bool bShow)
{
if ( bShow )
{
// Start with the first item centered, and the rest off to the right.
m_iSelectedItem = 0;
UpdateModelPanels();
MoveToFront(); // Any open dialogs from the main menu (options, servers, etc.) showing up sometimes - this should fix.
}
else
{
for ( int i = 0; i < m_aItems.Count(); i++ )
{
if ( !m_aItems[i].bDiscarded )
{
// if not a real item, ignore
if ( m_aItems[i].pItem.GetSOCData() == NULL )
{
continue;
}
// ignore items that are purchased or are store promotional items
CEconItem *pEconItem = m_aItems[i].pItem.GetSOCData();
switch ( pEconItem->GetOrigin() )
{
case kEconItemOrigin_PreviewItem:
case kEconItemOrigin_Purchased:
case kEconItemOrigin_StorePromotion:
continue;
}
}
}
if ( m_pConfirmDeleteDialog )
{
m_pConfirmDeleteDialog->MarkForDeletion();
m_pConfirmDeleteDialog = NULL;
}
m_aItems.Purge();
}
SetMouseInputEnabled( bShow );
SetVisible( bShow );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemPickupPanel::FireGameEvent( IGameEvent *event )
{
if ( !IsVisible() )
return;
const char * type = event->GetName();
if ( Q_strcmp(type, "gameui_hidden") == 0 )
{
ShowPanel( false );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemPickupPanel::OnCommand( const char *command )
{
if ( !Q_stricmp( command, "vguicancel" ) )
{
AcknowledgeItems();
ShowPanel( false );
}
else if ( !Q_stricmp( command, "changeloadout" ) )
{
AcknowledgeItems();
ShowPanel( false );
EconUI()->OpenEconUI( ECONUI_LOADOUT, true );
}
else if ( !Q_stricmp( command, "nextitem" ) )
{
m_iSelectedItem = clamp( m_iSelectedItem+1, 0, m_aItems.Count()-1 );
UpdateModelPanels();
}
else if ( !Q_stricmp( command, "previtem" ) )
{
m_iSelectedItem = clamp( m_iSelectedItem-1, 0, m_aItems.Count()-1 );
UpdateModelPanels();
}
else if ( !Q_stricmp( command, "discarditem" ) )
{
// Bring up confirm dialog
CConfirmDeleteItemDialog *pConfirm = vgui::SETUP_PANEL( new CConfirmDeleteItemDialog( this ) );
if ( pConfirm )
{
pConfirm->Show();
m_pConfirmDeleteDialog = pConfirm;
}
}
else
{
engine->ClientCmd( const_cast<char *>( command ) );
}
BaseClass::OnCommand( command );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemPickupPanel::UpdateModelPanels( void )
{
for ( int i = 0; i < ITEMPICKUP_NUM_MODELPANELS; i++ )
{
int iPos = (i - ITEMPICKUP_MODELPANEL_CENTER);
int iItem = m_iSelectedItem + iPos;
if ( iItem < 0 || iItem >= m_aItems.Count() )
{
m_aModelPanels[i]->SetItem( NULL );
m_aModelPanels[i]->SetVisible( false );
continue;
}
m_aModelPanels[i]->SetItem( &m_aItems[iItem].pItem );
m_aModelPanels[i]->SetVisible( true );
}
// Enable next & prev buttons if there are other items to the sides
bool bCanScrollRight = (m_iSelectedItem + 1) < m_aItems.Count();
m_pNextButton->SetVisible( bCanScrollRight );
m_pNextButton->SetEnabled( bCanScrollRight );
bool bCanScrollLeft = ((m_iSelectedItem - 1) >= 0) && m_aItems.Count();
m_pPrevButton->SetVisible( bCanScrollLeft );
m_pPrevButton->SetEnabled( bCanScrollLeft );
bool bDiscarded = false;
if ( m_iSelectedItem >= 0 && m_iSelectedItem < m_aItems.Count() )
{
bDiscarded = m_aItems[m_iSelectedItem].bDiscarded;
}
bool bAllowDiscard = true;
int iFoundMethod = 0;
if ( m_bRandomizePickupMethods )
{
iFoundMethod = RandomInt( 0, ARRAYSIZE(g_pszItemPickupMethodStrings)-1 );
}
else if ( m_iSelectedItem >= 0 && m_iSelectedItem < m_aItems.Count() )
{
iFoundMethod = GetUnacknowledgedReason( m_aItems[m_iSelectedItem].pItem.GetInventoryPosition() );
bAllowDiscard = ( iFoundMethod <= UNACK_ITEM_DROPPED );
iFoundMethod--;
if ( iFoundMethod < 0 || iFoundMethod >= ARRAYSIZE(g_pszItemPickupMethodStrings) )
{
iFoundMethod = 0;
}
}
// Hide the discard button if it's not a random find
m_pDiscardButton->SetVisible( !bDiscarded && bAllowDiscard );
m_pOpenLoadoutButton->SetVisible( !bDiscarded );
m_pDiscardedLabel->SetVisible( bDiscarded );
if ( m_pItemFoundMethod )
{
enum
{
COLOR_NORMAL = 1,
COLOR_HIGHLIGHTED = 2,
};
m_pItemFoundMethod->GetTextImage()->ClearColorChangeStream();
wchar_t wszTmp[1024];
wchar_t *pLocText = g_pVGuiLocalize->Find( g_pszItemPickupMethodStrings[iFoundMethod] );
if ( pLocText )
{
// Loop through and replace the color changes
Color baseColor = m_pItemFoundMethod->GetFgColor();
wchar_t *wpszChar = pLocText;
int iOutPos = 0;
while ( *wpszChar )
{
if ( *wpszChar == COLOR_NORMAL )
{
m_pItemFoundMethod->GetTextImage()->AddColorChange( baseColor, iOutPos );
}
else if ( *wpszChar == COLOR_HIGHLIGHTED )
{
m_pItemFoundMethod->GetTextImage()->AddColorChange( Color(200,80,60,255), iOutPos );
}
else
{
wszTmp[iOutPos] = *wpszChar;
iOutPos++;
}
wpszChar++;
if ( iOutPos >= (ARRAYSIZE(wszTmp) - 1) )
{
wszTmp[iOutPos] = L'\0';
break;
}
}
if ( iOutPos < (ARRAYSIZE(wszTmp) - 1) )
{
wszTmp[iOutPos] = L'\0';
}
m_pItemFoundMethod->SetText( wszTmp );
}
}
if ( m_pItemsFoundLabel )
{
if ( m_aItems.Count() > 1 )
{
m_pItemsFoundLabel->SetText( "#NewItemsAcquired" );
SetDialogVariable( "numitems", m_aItems.Count() );
}
else
{
m_pItemsFoundLabel->SetText( "#NewItemAcquired" );
}
}
SetDialogVariable( "selecteditem", m_iSelectedItem+1 );
// Update the loadout button as appropriate
if ( m_iSelectedItem >= 0 && m_iSelectedItem < m_aItems.Count() )
{
if ( m_aItems[m_iSelectedItem].pItem.IsValid() && !bDiscarded )
{
SetDialogVariable("loadouttext", g_pVGuiLocalize->Find( "#OpenGeneralLoadout" ) );
}
}
if ( m_pCloseButton )
{
const char *pszCloseString = (m_bReturnToGame && engine->IsInGame()) ? "#CloseItemPanel" : "#GameUI_OK";
m_pCloseButton->SetText( g_pVGuiLocalize->Find( pszCloseString ) );
}
m_pCloseButton->RequestFocus();
}
//-----------------------------------------------------------------------------
void CItemPickupPanel::AcknowledgeItems( void )
{
// On command, AckKnowledge all these items
for ( int i = 0; i < m_aItems.Count(); i++ )
{
InventoryManager()->AcknowledgeItem( &m_aItems[i].pItem, false );
}
InventoryManager()->SaveAckFile();
// If we were crafting, and the craft panel is up, we return to that instead.
if ( EconUI()->IsUIPanelVisible( ECONUI_CRAFTING ) )
return;
// Check to make sure the player has room for all his items. If not, bring up the discard panel. Otherwise, go away.
if ( !InventoryManager()->CheckForRoomAndForceDiscard( ) )
{
#ifdef TF_CLIENT_DLL
// If the quest log is up, we just go back to that
if ( GetQuestLog() && GetQuestLog()->IsVisible() )
return;
#endif
// If we're connected to a game server, we also close the game UI.
if ( m_bReturnToGame && engine->IsInGame() )
{
engine->ClientCmd_Unrestricted( "gameui_hide" );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Handles the escape key
//-----------------------------------------------------------------------------
void CItemPickupPanel::OnKeyCodeTyped( vgui::KeyCode code )
{
if( code == KEY_ESCAPE )
{
OnCommand( "vguicancel" );
}
else
{
BaseClass::OnKeyCodeTyped( code );
}
}
//-----------------------------------------------------------------------------
// Purpose: Handles button press code for controllers and enter
//-----------------------------------------------------------------------------
void CItemPickupPanel::OnKeyCodePressed( vgui::KeyCode code )
{
ButtonCode_t nButtonCode = GetBaseButtonCode( code );
if( code == KEY_ENTER || nButtonCode == KEY_XBUTTON_A || nButtonCode == KEY_XBUTTON_B || nButtonCode == STEAMCONTROLLER_A || nButtonCode == STEAMCONTROLLER_B )
{
OnCommand( "vguicancel" );
}
else if( code == KEY_HOME || nButtonCode == KEY_XBUTTON_Y || nButtonCode == STEAMCONTROLLER_Y )
{
OnCommand( "changeloadout" );
}
else if ( nButtonCode == KEY_XBUTTON_RIGHT ||
nButtonCode == KEY_XSTICK1_RIGHT ||
nButtonCode == KEY_XSTICK2_RIGHT ||
nButtonCode == KEY_RIGHT )
{
OnCommand( "nextitem" );
}
else if ( nButtonCode == KEY_XBUTTON_LEFT ||
nButtonCode == KEY_XSTICK1_LEFT ||
nButtonCode == KEY_XSTICK2_LEFT ||
nButtonCode == KEY_LEFT )
{
OnCommand( "previtem" );
}
else
{
BaseClass::OnKeyCodePressed( code );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemPickupPanel::AddItem( CEconItemView *pItem )
{
// Guard against duplicates
FOR_EACH_VEC( m_aItems, i )
{
if ( m_aItems[i].pItem.GetItemID() == pItem->GetItemID() )
return;
}
int iIdx = m_aItems.AddToTail();
m_aItems[iIdx].pItem = *pItem;
m_aItems[iIdx].bDiscarded = false;
if ( IsVisible() )
{
UpdateModelPanels();
InvalidateLayout();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemPickupPanel::OnConfirmDelete( KeyValues *data )
{
m_pConfirmDeleteDialog = NULL;
m_pCloseButton->RequestFocus();
int iConfirmed = data->GetInt( "confirmed", 0 );
if ( !iConfirmed )
return;
if ( m_iSelectedItem >= 0 && m_iSelectedItem < m_aItems.Count() )
{
if ( m_aItems[m_iSelectedItem].pItem.IsValid() )
{
CPlayerInventory *pInventory = InventoryManager()->GetLocalInventory();
if ( pInventory )
{
EconUI()->Gamestats_ItemTransaction( IE_ITEM_DISCARDED, &m_aItems[m_iSelectedItem].pItem );
InventoryManager()->DropItem( m_aItems[m_iSelectedItem].pItem.GetItemID() );
InvalidateLayout();
m_aItems[m_iSelectedItem].bDiscarded = true;
m_pDiscardButton->SetVisible( false );
m_pOpenLoadoutButton->SetVisible( false );
m_pDiscardedLabel->SetVisible( true );
// If we've discarded all our items, we exit immediately
bool bFoundUndiscarded = false;
for ( int i = 0; i < m_aItems.Count(); i++ )
{
if ( !m_aItems[i].bDiscarded )
{
bFoundUndiscarded = true;
break;
}
}
if ( !bFoundUndiscarded )
{
OnCommand( "vguicancel" );
}
}
}
}
}
static vgui::DHANDLE<CItemPickupPanel> g_ItemPickupPanel;
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CItemPickupPanel *OpenItemPickupPanel( void )
{
if (!g_ItemPickupPanel.Get())
{
g_ItemPickupPanel = vgui::SETUP_PANEL( new CItemPickupPanel( NULL ) );
g_ItemPickupPanel->InvalidateLayout( false, true );
}
engine->ClientCmd_Unrestricted( "gameui_activate" );
g_ItemPickupPanel->ShowPanel( true );
return g_ItemPickupPanel;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CItemPickupPanel *GetItemPickupPanel( void )
{
return g_ItemPickupPanel.Get();
}
//=======================================================================================================================================================
// ITEM DISCARD PANEL
//=======================================================================================================================================================
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CItemDiscardPanel::CItemDiscardPanel( Panel *parent ) : Frame( parent, "item_discard" )
{
vgui::VPANEL gameuiPanel = enginevgui->GetPanel( PANEL_GAMEUIDLL );
SetParent( gameuiPanel );
// We don't want the gameui to delete us, or things get messy
SetAutoDelete( false );
SetMoveable( false );
SetSizeable( false );
vgui::HScheme scheme = vgui::scheme()->LoadSchemeFromFileEx( enginevgui->GetPanel( PANEL_CLIENTDLL ), "resource/ClientScheme.res", "ClientScheme");
SetScheme(scheme);
SetProportional( true );
m_pModelPanel = new CItemModelPanel( this, "modelpanel" );
m_pBackpackPanel = new CBackpackPanel( this, "backpack_panel" );
m_pConfirmDeleteDialog = NULL;
m_bDiscardedNewItem = false;
m_bMadeRoom = false;
m_pDiscardedLabelCarat = NULL;
m_pDiscardedLabel = NULL;
m_pDiscardButton = NULL;
m_pCloseButton = NULL;
m_pItemMouseOverPanel = new CItemModelPanel( this, "ItemMouseOverItemPanel" );
m_pItemToolTip = new CSimplePanelToolTip( this );
m_pItemToolTip->SetControlledPanel( m_pItemMouseOverPanel );
m_pModelPanel->SetTooltip( m_pItemToolTip, "" );
m_pModelPanel->SetActAsButton( false, true );
ListenForGameEvent( "gameui_hidden" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemDiscardPanel::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
m_pItemMouseOverPanel->InvalidateLayout( true, true );
m_pModelPanel->InvalidateLayout( true, true );
LoadControlSettings( "Resource/UI/econ/ItemDiscardPanel.res" );
// Highlight the X on the discard button
m_pDiscardButton = dynamic_cast<CExButton*>( FindChildByName("DiscardButton") );
if ( m_pDiscardButton )
{
SetXToRed( m_pDiscardButton );
}
m_pCloseButton = dynamic_cast<CExButton*>( FindChildByName("CloseButton") );
m_pDiscardedLabel = dynamic_cast<vgui::Label*>( FindChildByName("DiscardedLabel") );
m_pDiscardedLabelCarat = dynamic_cast<vgui::Label*>( FindChildByName("DiscardedCaratLabel") );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemDiscardPanel::PerformLayout( void )
{
if ( GetVParent() )
{
int w,h;
vgui::ipanel()->GetSize( GetVParent(), w, h );
SetBounds(0,0,w,h);
}
BaseClass::PerformLayout();
m_pDiscardedLabelCarat->SetVisible( m_bDiscardedNewItem );
m_pDiscardedLabel->SetVisible( m_bDiscardedNewItem );
m_pDiscardButton->SetVisible( !m_bDiscardedNewItem && !m_bMadeRoom );
m_pCloseButton->SetVisible( m_bDiscardedNewItem || m_bMadeRoom );
if ( m_pItemMouseOverPanel->IsVisible() )
{
m_pItemMouseOverPanel->SetVisible( false );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemDiscardPanel::ShowPanel(bool bShow)
{
if ( bShow )
{
m_bDiscardedNewItem = false;
m_bMadeRoom = false;
m_pBackpackPanel->ShowPanel( 0, true );
InvalidateLayout();
}
else
{
if ( m_pConfirmDeleteDialog )
{
m_pConfirmDeleteDialog->MarkForDeletion();
m_pConfirmDeleteDialog = NULL;
}
}
SetMouseInputEnabled( bShow );
SetVisible( bShow );
#ifdef TF_CLIENT_DLL
// If the player made room and is a trial account, suggest that they upgrade to get more space.
if ( bShow && IsFreeTrialAccount() )
{
ShowUpgradeMessageBox( "#TF_TrialNeedSpace_Title", "#TF_TrialNeedSpace_Text" );
}
#endif
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemDiscardPanel::FireGameEvent( IGameEvent *event )
{
if ( !IsVisible() )
return;
const char * type = event->GetName();
if ( Q_strcmp(type, "gameui_hidden") == 0 )
{
// If they haven't discarded down to <MAX items, bring us right back up again
if ( InventoryManager()->CheckForRoomAndForceDiscard() )
{
engine->ClientCmd_Unrestricted( "gameui_activate" );
}
else
{
ShowPanel( false );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemDiscardPanel::OnCommand( const char *command )
{
if ( !Q_stricmp( command, "vguicancel" ) )
{
ShowPanel( false );
// Check to make sure the player has room for all his items. If not, bring up the discard panel. Otherwise, go away.
if ( !InventoryManager()->CheckForRoomAndForceDiscard() )
{
// If we're connected to a game server, we also close the game UI.
if ( engine->IsInGame() )
{
engine->ClientCmd_Unrestricted( "gameui_hide" );
}
}
}
else if ( !Q_stricmp( command, "discarditem" ) )
{
// Bring up confirm dialog
CConfirmDeleteItemDialog *pConfirm = vgui::SETUP_PANEL( new CConfirmDeleteItemDialog( this ) );
if ( pConfirm )
{
pConfirm->Show();
m_pConfirmDeleteDialog = pConfirm;
}
}
else
{
engine->ClientCmd( const_cast<char *>( command ) );
}
BaseClass::OnCommand( command );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemDiscardPanel::SetItem( CEconItemView *pItem )
{
if ( m_pModelPanel )
{
m_pModelPanel->SetItem( pItem );
}
if ( m_pItemMouseOverPanel )
{
m_pItemMouseOverPanel->SetItem( pItem );
IScheme *pScheme = scheme()->GetIScheme( GetScheme() );
m_pItemMouseOverPanel->InvalidateLayout(true);
m_pItemMouseOverPanel->SetBorder( pScheme->GetBorder("MainMenuBGBorder") );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemDiscardPanel::OnConfirmDelete( KeyValues *data )
{
if ( !m_bDiscardedNewItem && !m_bMadeRoom && data && m_pModelPanel->HasItem() )
{
int iConfirmed = data->GetInt( "confirmed", 0 );
if ( iConfirmed == 2 )
{
// Player discarded an item from the backpack to make room
m_bMadeRoom = true;
InvalidateLayout();
}
else if ( iConfirmed )
{
CPlayerInventory *pInventory = InventoryManager()->GetLocalInventory();
if ( !pInventory )
return;
InventoryManager()->DropItem( m_pModelPanel->GetItem()->GetItemID() );
m_bDiscardedNewItem = true;
InvalidateLayout();
}
m_pBackpackPanel->RequestFocus();
}
m_pConfirmDeleteDialog = NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Handles the escape key
//-----------------------------------------------------------------------------
void CItemDiscardPanel::OnKeyCodeTyped( vgui::KeyCode code )
{
if( code == KEY_ESCAPE )
{
OnCommand( "vguicancel" );
}
else
{
BaseClass::OnKeyCodeTyped( code );
}
}
//-----------------------------------------------------------------------------
// Purpose: Handles button press code for controllers and enter
//-----------------------------------------------------------------------------
void CItemDiscardPanel::OnKeyCodePressed( vgui::KeyCode code )
{
ButtonCode_t nButtonCode = GetBaseButtonCode( code );
if( nButtonCode == KEY_XBUTTON_B )
{
OnCommand( "vguicancel" );
}
else
{
BaseClass::OnKeyCodePressed( code );
}
}
static vgui::DHANDLE<CItemDiscardPanel> g_ItemDiscardPanel;
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CItemDiscardPanel *OpenItemDiscardPanel( void )
{
if (!g_ItemDiscardPanel.Get())
{
g_ItemDiscardPanel = vgui::SETUP_PANEL( new CItemDiscardPanel( NULL ) );
g_ItemDiscardPanel->InvalidateLayout( false, true );
}
engine->ClientCmd_Unrestricted( "gameui_activate" );
g_ItemDiscardPanel->ShowPanel( true );
return g_ItemDiscardPanel;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CItemDiscardPanel *GetItemDiscardPanel( void )
{
return g_ItemDiscardPanel.Get();
}
| 0 | 0.987794 | 1 | 0.987794 | game-dev | MEDIA | 0.738679 | game-dev,desktop-app | 0.982635 | 1 | 0.982635 |
BIDData/BIDMach | 4,499 | src/main/java/edu/berkeley/bvlc/NET.java | package edu.berkeley.bvlc;
public final class NET {
static {
LibUtils.loadLibrary("caffe");
}
public NET() {_shptr = 0;}
public NET(String pfile) {_shptr = netFromParamFile(pfile);}
public NET(String pfile, String prefilled) {_shptr = netFromPretrained(pfile, prefilled);}
protected NET(long shptr) {_shptr = shptr;}
public void init(String pfile) {
if (_shptr != 0) clearNet(_shptr);
_shptr = netFromParamFile(pfile);
}
public void init(String pfile, String prefilled) {
if (_shptr != 0) clearNet(_shptr);
_shptr = netFromPretrained(pfile, prefilled);
}
public int num_inputs() {if (_shptr != 0) return num_inputs(_shptr); else throw new RuntimeException("Net uninitialized");}
public int num_outputs() {if (_shptr != 0) return num_outputs(_shptr); else throw new RuntimeException("Net uninitialized");}
public int num_layers() {if (_shptr != 0) return num_layers(_shptr); else throw new RuntimeException("Net uninitialized");}
public int num_blobs() {if (_shptr != 0) return num_blobs(_shptr); else throw new RuntimeException("Net uninitialized");}
public BLOB blob(int i) {
if (_shptr == 0) {
throw new RuntimeException("Net uninitialized");
} else {
int n = num_blobs();
if (i < 0 || i >= n) {
throw new RuntimeException("Net blob index "+i+" out of range (0, "+(n-1)+")");
}
return new BLOB(blob(_shptr, i));
}
}
public BLOB input_blob(int i) {
if (_shptr == 0) {
throw new RuntimeException("Net uninitialized");
} else {
int n = num_inputs();
if (i < 0 || i >= n) {
throw new RuntimeException("Net input blob index "+i+" out of range (0, "+(n-1)+")");
}
return new BLOB(input_blob(_shptr, i));
}
}
public BLOB output_blob(int i) {
if (_shptr == 0) {
throw new RuntimeException("Net uninitialized");
} else {
int n = num_outputs();
if (i < 0 || i >= n) {
throw new RuntimeException("Net output blob index "+i+" out of range (0, "+(n-1)+")");
}
return new BLOB(output_blob(_shptr, i));
}
}
public LAYER layer(int i) {
if (_shptr == 0) {
throw new RuntimeException("Net uninitialized");
} else {
int n = num_layers();
if (i < 0 || i >= n) {
throw new RuntimeException("Net layer index "+i+" out of range (0, "+(n-1)+")");
}
return new LAYER(layer(_shptr, i));
}
}
public String [] blob_names() {if (_shptr != 0) return blob_names(_shptr); else throw new RuntimeException("Net uninitialized");}
public String [] layer_names() {if (_shptr != 0) return layer_names(_shptr); else throw new RuntimeException("Net uninitialized");}
public BLOB blob_by_name(String s) {if (_shptr != 0) return new BLOB(blob_by_name(_shptr, s)); else throw new RuntimeException("Net uninitialized");}
public LAYER layer_by_name(String s) {if (_shptr != 0) return new LAYER(layer_by_name(_shptr, s)); else throw new RuntimeException("Net uninitialized");}
public void forward() {if (_shptr != 0) forward(_shptr); else throw new RuntimeException("Net uninitialized");}
public void backward() {if (_shptr != 0) backward(_shptr); else throw new RuntimeException("Net uninitialized");}
@Override
protected void finalize() {
if (_shptr != 0) clearNet(_shptr);
}
private long _shptr;
private static native long netFromParamFile(String name);
private static native long netFromPretrained(String name, String prefilled);
private static native int num_inputs(long ref);
private static native int num_outputs(long ref);
private static native int num_layers(long ref);
private static native int num_blobs(long ref);
private static native void forward(long ref);
private static native void backward(long ref);
private static native int clearNet(long ref);
private static native long layer(long ref, int i);
private static native long blob(long ref, int i);
private static native long input_blob(long ref, int i);
private static native long output_blob(long ref, int i);
private static native String [] blob_names(long ref);
private static native String [] layer_names(long ref);
private static native long blob_by_name(long ref, String s);
private static native long layer_by_name(long ref, String s);
}
| 0 | 0.952312 | 1 | 0.952312 | game-dev | MEDIA | 0.154131 | game-dev | 0.978376 | 1 | 0.978376 |
MergHQ/CRYENGINE | 8,408 | Code/GameSDK/GameDll/ScriptBind_ProtectedBinds.cpp | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
/*************************************************************************
-------------------------------------------------------------------------
$Id$
$DateTime$
Description: Script Binding for anything we only want to be accessed at controlled/protected points in the application
-------------------------------------------------------------------------
History:
- 17:01:2012 11:11 : Created by AndrewB
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// Pre-compiled header
#include "StdAfx.h"
// This include
#include "ScriptBind_ProtectedBinds.h"
#include <CryFlowGraph/IFlowSystem.h>
#include "IPlayerProfiles.h"
#include "PersistantStats.h"
#include "DLCManager.h"
//------------------------------------------------------------------------
// Constructor
CScriptBind_ProtectedBinds::CScriptBind_ProtectedBinds( ISystem *pSystem )
: m_pSystem( pSystem )
, m_active( false )
{
}
//------------------------------------------------------------------------
// Destructor
CScriptBind_ProtectedBinds::~CScriptBind_ProtectedBinds()
{
Disable();
}
//------------------------------------------------------------------------
void CScriptBind_ProtectedBinds::Enable()
{
if( ! m_active )
{
//setup
Init(m_pSystem->GetIScriptSystem(), m_pSystem);
RegisterMethods();
RegisterGlobals();
//allow global access
SetGlobalName( "ProtectedBinds" );
//activate
m_active = true;
}
}
//------------------------------------------------------------------------
void CScriptBind_ProtectedBinds::Disable()
{
if( m_active )
{
//replace the global reference to the table with a NULL reference and release table
Done();
//deactivate
m_active = false;
}
}
//------------------------------------------------------------------------
void CScriptBind_ProtectedBinds::RegisterMethods()
{
#undef SCRIPT_REG_CLASSNAME
#define SCRIPT_REG_CLASSNAME &CScriptBind_ProtectedBinds::
SCRIPT_REG_TEMPLFUNC( GetPersistantStat, "name" );
SCRIPT_REG_TEMPLFUNC( SetPersistantStat, "name, valueTab ");
SCRIPT_REG_TEMPLFUNC( SavePersistantStatsToBlaze, "");
SCRIPT_REG_TEMPLFUNC( GetProfileAttribute, "name" );
SCRIPT_REG_TEMPLFUNC( SetProfileAttribute, "name, valueTab" );
SCRIPT_REG_TEMPLFUNC( ActivateDemoEventEntitlement, "");
#undef SCRIPT_REG_CLASSNAME
}
//------------------------------------------------------------------------
void CScriptBind_ProtectedBinds::RegisterGlobals()
{
}
//------------------------------------------------------------------------
int CScriptBind_ProtectedBinds::GetPersistantStat(IFunctionHandler *pH, const char *name)
{
if( ! m_active )
{
//abort
return pH->EndFunction();
}
if (CPersistantStats *pPersistantStats = CPersistantStats::GetInstance())
{
ScriptAnyValue scriptVal;
bool found=false;
EIntPersistantStats intStat = CPersistantStats::GetIntStatFromName(name);
if (intStat != EIPS_Invalid)
{
int intStatValue = pPersistantStats->GetStat(intStat);
CryLog("CScriptBind_ProtectedBinds::GetPersistantStat() found stat=%s is an intStat=%d with value=%d", name, intStat, intStatValue);
scriptVal = intStatValue;
found=true;
}
else
{
EFloatPersistantStats floatStat = CPersistantStats::GetFloatStatFromName(name);
if (floatStat != EFPS_Invalid)
{
float floatStatValue = pPersistantStats->GetStat(floatStat);
CryLog("CScriptBind_ProtectedBinds::GetPersistantStat() found stat=%s is a floatStat=%d with value=%f", name, floatStat, floatStatValue);
scriptVal = floatStatValue;
found=true;
}
}
if (found)
{
return pH->EndFunction( scriptVal );
}
}
return pH->EndFunction();
}
//------------------------------------------------------------------------
int CScriptBind_ProtectedBinds::SetPersistantStat(IFunctionHandler *pH, const char *name, SmartScriptTable valueTab)
{
//@Todo: Steam
return pH->EndFunction();
}
//------------------------------------------------------------------------
int CScriptBind_ProtectedBinds::SavePersistantStatsToBlaze(IFunctionHandler *pH)
{
if( ! m_active )
{
//abort
return pH->EndFunction();
}
//@Todo: Steam
return pH->EndFunction();
}
//------------------------------------------------------------------------
int CScriptBind_ProtectedBinds::GetProfileAttribute( IFunctionHandler *pH, const char* name )
{
if( ! m_active )
{
//abort
return pH->EndFunction();
}
if( IPlayerProfile* pProfile = GetCurrentUserProfile() )
{
TFlowInputData dataVal;
if( pProfile->GetAttribute( name, dataVal ) )
{
ScriptAnyValue scriptVal;
//find the type of the value to access it
switch( dataVal.GetType() )
{
case eFDT_Int: {
int* intVal = dataVal.GetPtr<int>();
scriptVal = *intVal;
break;
}
case eFDT_Float: {
float* floatVal = dataVal.GetPtr<float>();
scriptVal = *floatVal;
break;
}
case eFDT_Vec3: {
Vec3* vecVal = dataVal.GetPtr<Vec3>();
scriptVal = *vecVal;
break;
}
case eFDT_String: {
string* stringVal = dataVal.GetPtr<string>();
scriptVal = stringVal->c_str();
break;
}
case eFDT_Bool: {
bool* boolVal = dataVal.GetPtr<bool>();
scriptVal = *boolVal;
break;
}
}
return pH->EndFunction( scriptVal );
}
}
return pH->EndFunction();
}
//------------------------------------------------------------------------
int CScriptBind_ProtectedBinds::SetProfileAttribute( IFunctionHandler *pH, const char* name, SmartScriptTable valueTab )
{
if( ! m_active )
{
//abort
return pH->EndFunction(0);
}
if( IPlayerProfile* pProfile = GetCurrentUserProfile() )
{
TFlowInputData dataVal;
ScriptAnyValue scriptVal;
valueTab->GetValueAny( "value", scriptVal );
switch( scriptVal.type )
{
case ANY_TBOOLEAN: {
bool boolVal;
scriptVal.CopyTo( boolVal );
dataVal.Set( boolVal );
break;
}
case ANY_TNUMBER: {
//numbers could be float or int in the profile
//get the attribute and try to match the current type if it exists
bool isInt = false;
TFlowInputData originalData;
if( pProfile->GetAttribute( name, originalData ) )
{
if( originalData.GetType() == eFDT_Int )
{
isInt = true;
}
}
//if it doesn't exist or is currently a non-number type then we assume float
if( isInt )
{
int intVal;
scriptVal.CopyTo( intVal );
dataVal.Set( intVal );
}
else
{
float floatVal;
scriptVal.CopyTo( floatVal );
dataVal.Set( floatVal );
}
break;
}
case ANY_TSTRING: {
const char* charVal;
scriptVal.CopyTo( charVal );
string stringVal( charVal );
dataVal.Set( stringVal );
break;
}
case ANY_TVECTOR: {
Vec3 vecVal;
scriptVal.CopyTo( vecVal );
dataVal.Set( vecVal );
break;
}
}
pProfile->SetAttribute( name, dataVal );
}
return pH->EndFunction(0);
}
//------------------------------------------------------------------------
int CScriptBind_ProtectedBinds::ActivateDemoEventEntitlement( IFunctionHandler *pH )
{
if( ! m_active )
{
//abort
return pH->EndFunction(0);
}
return pH->EndFunction(0);
}
//------------------------------------------------------------------------
IPlayerProfile* CScriptBind_ProtectedBinds::GetCurrentUserProfile()
{
IPlayerProfile* pProfile = NULL;
if( IPlayerProfileManager *pProfileMan = gEnv->pGame->GetIGameFramework()->GetIPlayerProfileManager() )
{
const char *user = pProfileMan->GetCurrentUser();
pProfile = pProfileMan->GetCurrentProfile( user );
}
return pProfile;
}
| 0 | 0.872 | 1 | 0.872 | game-dev | MEDIA | 0.845591 | game-dev,networking | 0.958341 | 1 | 0.958341 |
gamebooster/dota2-lua-engine | 2,780 | hl2sdk-dota/public/tier1/stringpool.h | //========= Copyright (c) 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef STRINGPOOL_H
#define STRINGPOOL_H
#if defined( _WIN32 )
#pragma once
#endif
#include "utlrbtree.h"
#include "utlvector.h"
#include "utlbuffer.h"
//-----------------------------------------------------------------------------
// Purpose: Allocates memory for strings, checking for duplicates first,
// reusing exising strings if duplicate found.
//-----------------------------------------------------------------------------
enum StringPoolCase_t
{
StringPoolCaseInsensitive,
StringPoolCaseSensitive
};
class CStringPool
{
public:
CStringPool( StringPoolCase_t caseSensitivity = StringPoolCaseInsensitive );
~CStringPool();
unsigned int Count() const;
const char * Allocate( const char *pszValue );
void FreeAll();
// searches for a string already in the pool
const char * Find( const char *pszValue );
protected:
typedef CUtlRBTree<const char *, unsigned short> CStrSet;
CStrSet m_Strings;
};
//-----------------------------------------------------------------------------
// Purpose: A reference counted string pool.
//
// Elements are stored more efficiently than in the conventional string pool,
// quicker to look up, and storage is tracked via reference counts.
//
// At some point this should replace CStringPool
//-----------------------------------------------------------------------------
class CCountedStringPool
{
public: // HACK, hash_item_t structure should not be public.
struct hash_item_t
{
char* pString;
unsigned short nNextElement;
unsigned char nReferenceCount;
unsigned char pad;
};
enum
{
INVALID_ELEMENT = 0,
MAX_REFERENCE = 0xFF,
HASH_TABLE_SIZE = 1024
};
CUtlVector<unsigned short> m_HashTable; // Points to each element
CUtlVector<hash_item_t> m_Elements;
unsigned short m_FreeListStart;
StringPoolCase_t m_caseSensitivity;
public:
CCountedStringPool( StringPoolCase_t caseSensitivity = StringPoolCaseInsensitive );
virtual ~CCountedStringPool();
void FreeAll();
char *FindString( const char* pIntrinsic );
char *ReferenceString( const char* pIntrinsic );
void DereferenceString( const char* pIntrinsic );
// These are only reliable if there are less than 64k strings in your string pool
unsigned short FindStringHandle( const char* pIntrinsic );
unsigned short ReferenceStringHandle( const char* pIntrinsic );
char *HandleToString( unsigned short handle );
void SpewStrings();
unsigned Hash( const char *pszKey );
bool SaveToBuffer( CUtlBuffer &buffer );
bool RestoreFromBuffer( CUtlBuffer &buffer );};
#endif // STRINGPOOL_H
| 0 | 0.742078 | 1 | 0.742078 | game-dev | MEDIA | 0.551094 | game-dev | 0.717998 | 1 | 0.717998 |
flowtsohg/mdx-m3-viewer | 3,927 | src/parsers/w3x/w3f/file.ts | import BinaryStream from '../../../common/binarystream';
import MapTitle from './maptitle';
import MapOrder from './maporder';
import { byteLengthUtf8 } from '../../../common/utf8';
/**
* war3campaign.w3f - the campaign information file.
*/
export default class War3CampaignW3f {
version = 0;
campaignVersion = 0;
editorVersion = 0;
name = '';
difficulty = '';
author = '';
description = '';
mode = -1; // 0: fixed difficulty, only w3m maps, 1: variable difficulty, only w3m maps, 1: fixed..., contains w3x maps, 2: variable..., contains w3xm maps.
backgroundScreen = -1; // -1 = none or custom path
backgroundScreenPath = '';
minimapImagePath = '';
ambientSound = 0; // -1 = imported, 0 = none, >0 = preset index
ambientSoundPath = '';
terrainFog = 0; // 0 = not used, >0 = index of terrain fog style
fogStartZ = 0;
fogEndZ = 0;
fogDensity = 0;
fogColor = new Uint8Array(4);
userInterface = -1; // 0 = human
mapTitles: MapTitle[] = [];
mapOrders: MapOrder[] = [];
load(buffer: ArrayBuffer | Uint8Array): void {
const stream = new BinaryStream(buffer);
this.version = stream.readInt32();
this.campaignVersion = stream.readInt32();
this.editorVersion = stream.readInt32();
this.name = stream.readNull();
this.difficulty = stream.readNull();
this.author = stream.readNull();
this.description = stream.readNull();
this.mode = stream.readInt32();
this.backgroundScreen = stream.readInt32();
this.backgroundScreenPath = stream.readNull();
this.minimapImagePath = stream.readNull();
this.ambientSound = stream.readInt32();
this.ambientSoundPath = stream.readNull();
this.terrainFog = stream.readInt32();
this.fogStartZ = stream.readFloat32();
this.fogEndZ = stream.readFloat32();
this.fogDensity = stream.readFloat32();
stream.readUint8Array(this.fogColor);
this.userInterface = stream.readInt32();
for (let i = 0, l = stream.readUint32(); i < l; i++) {
const mapTitle = new MapTitle();
mapTitle.load(stream);
this.mapTitles[i] = mapTitle;
}
for (let i = 0, l = stream.readUint32(); i < l; i++) {
const mapOrder = new MapOrder();
mapOrder.load(stream);
this.mapOrders[i] = mapOrder;
}
}
save(): Uint8Array {
const stream = new BinaryStream(new ArrayBuffer(this.getByteLength()));
stream.writeInt32(this.version);
stream.writeInt32(this.campaignVersion);
stream.writeInt32(this.editorVersion);
stream.writeNull(this.name);
stream.writeNull(this.difficulty);
stream.writeNull(this.author);
stream.writeNull(this.description);
stream.writeInt32(this.mode);
stream.writeInt32(this.backgroundScreen);
stream.writeNull(this.backgroundScreenPath);
stream.writeNull(this.minimapImagePath);
stream.writeInt32(this.ambientSound);
stream.writeNull(this.ambientSoundPath);
stream.writeInt32(this.terrainFog);
stream.writeFloat32(this.fogStartZ);
stream.writeFloat32(this.fogEndZ);
stream.writeFloat32(this.fogDensity);
stream.writeUint8Array(this.fogColor);
stream.writeInt32(this.userInterface);
stream.writeUint32(this.mapTitles.length);
for (const title of this.mapTitles) {
title.save(stream);
}
stream.writeUint32(this.mapOrders.length);
for (const order of this.mapOrders) {
order.save(stream);
}
return stream.uint8array;
}
getByteLength(): number {
let size = 63 + byteLengthUtf8(this.name) + byteLengthUtf8(this.difficulty) + byteLengthUtf8(this.author) + byteLengthUtf8(this.description) + byteLengthUtf8(this.backgroundScreenPath) + byteLengthUtf8(this.minimapImagePath) + byteLengthUtf8(this.ambientSoundPath);
for (const title of this.mapTitles) {
size += title.getByteLength();
}
for (const order of this.mapOrders) {
size += order.getByteLength();
}
return size;
}
}
| 0 | 0.726993 | 1 | 0.726993 | game-dev | MEDIA | 0.426711 | game-dev | 0.885305 | 1 | 0.885305 |
energye/lcl | 2,455 | lcl/mainmenu.go | //----------------------------------------
//
// Copyright © yanghy. All Rights Reserved.
//
// Licensed under Apache License 2.0
//
//----------------------------------------
package lcl
import (
. "github.com/energye/lcl/api"
"github.com/energye/lcl/api/imports"
. "github.com/energye/lcl/types"
)
// IMainMenu Parent: IMenu
type IMainMenu interface {
IMenu
Height() int32 // property
WindowHandle() HWND // property
SetWindowHandle(AValue HWND) // property
Merge(Menu IMainMenu) // procedure
Unmerge(Menu IMainMenu) // procedure
SetOnChange(fn TMenuChangeEvent) // property event
}
// TMainMenu Parent: TMenu
type TMainMenu struct {
TMenu
changePtr uintptr
}
func NewMainMenu(AOwner IComponent) IMainMenu {
r1 := mainMenuImportAPI().SysCallN(1, GetObjectUintptr(AOwner))
return AsMainMenu(r1)
}
func (m *TMainMenu) Height() int32 {
r1 := mainMenuImportAPI().SysCallN(2, m.Instance())
return int32(r1)
}
func (m *TMainMenu) WindowHandle() HWND {
r1 := mainMenuImportAPI().SysCallN(6, 0, m.Instance(), 0)
return HWND(r1)
}
func (m *TMainMenu) SetWindowHandle(AValue HWND) {
mainMenuImportAPI().SysCallN(6, 1, m.Instance(), uintptr(AValue))
}
func MainMenuClass() TClass {
ret := mainMenuImportAPI().SysCallN(0)
return TClass(ret)
}
func (m *TMainMenu) Merge(Menu IMainMenu) {
mainMenuImportAPI().SysCallN(3, m.Instance(), GetObjectUintptr(Menu))
}
func (m *TMainMenu) Unmerge(Menu IMainMenu) {
mainMenuImportAPI().SysCallN(5, m.Instance(), GetObjectUintptr(Menu))
}
func (m *TMainMenu) SetOnChange(fn TMenuChangeEvent) {
if m.changePtr != 0 {
RemoveEventElement(m.changePtr)
}
m.changePtr = MakeEventDataPtr(fn)
mainMenuImportAPI().SysCallN(4, m.Instance(), m.changePtr)
}
var (
mainMenuImport *imports.Imports = nil
mainMenuImportTables = []*imports.Table{
/*0*/ imports.NewTable("MainMenu_Class", 0),
/*1*/ imports.NewTable("MainMenu_Create", 0),
/*2*/ imports.NewTable("MainMenu_Height", 0),
/*3*/ imports.NewTable("MainMenu_Merge", 0),
/*4*/ imports.NewTable("MainMenu_SetOnChange", 0),
/*5*/ imports.NewTable("MainMenu_Unmerge", 0),
/*6*/ imports.NewTable("MainMenu_WindowHandle", 0),
}
)
func mainMenuImportAPI() *imports.Imports {
if mainMenuImport == nil {
mainMenuImport = NewDefaultImports()
mainMenuImport.SetImportTable(mainMenuImportTables)
mainMenuImportTables = nil
}
return mainMenuImport
}
| 0 | 0.786347 | 1 | 0.786347 | game-dev | MEDIA | 0.506821 | game-dev | 0.79543 | 1 | 0.79543 |
Haleth/Aurora | 3,283 | Skin/Retail/FrameXML/StaticPopup.lua | local _, private = ...
if not private.isRetail then return end
--[[ Lua Globals ]]
-- luacheck: globals tinsert max
--[[ Core ]]
local Aurora = private.Aurora
local Base = Aurora.Base
local Skin = Aurora.Skin
local Color = Aurora.Color
--do --[[ FrameXML\StaticPopup.lua ]]
--end
do --[[ FrameXML\StaticPopup.xml ]]
function Skin.StaticPopupButtonTemplate(Button)
Skin.FrameTypeButton(Button)
end
local function CloseButton_SetNormalTexture(Button, texture)
if Button._setNormal then return end
Button._setNormal = true
Button:SetNormalTexture("")
if texture:find("Hide") then
Button._auroraTextures[1]:Hide()
Button._auroraTextures[2]:Hide()
Button._auroraTextures[3]:Show()
else
Button._auroraTextures[1]:Show()
Button._auroraTextures[2]:Show()
Button._auroraTextures[3]:Hide()
end
Button._setNormal = nil
end
local function CloseButton_SetPushedTexture(Button, texture)
if Button._setPushed then return end
Button._setPushed = true
Button:SetPushedTexture("")
Button._setPushed = nil
end
function Skin.StaticPopupTemplate(Frame)
local name = Frame:GetName()
Skin.DialogBorderTemplate(Frame.Border)
do -- CloseButton
local close = _G[name .. "CloseButton"]
Skin.UIPanelCloseButton(close)
local bg = close:GetBackdropTexture("bg")
local hline = close:CreateTexture()
hline:SetColorTexture(1, 1, 1)
hline:SetSize(11, 1)
hline:SetPoint("BOTTOMLEFT", bg, 3, 3)
_G.tinsert(close._auroraTextures, hline)
_G.hooksecurefunc(close, "SetNormalTexture", CloseButton_SetNormalTexture)
_G.hooksecurefunc(close, "SetPushedTexture", CloseButton_SetPushedTexture)
end
Skin.StaticPopupButtonTemplate(Frame.button1)
Skin.StaticPopupButtonTemplate(Frame.button2)
Skin.StaticPopupButtonTemplate(Frame.button3)
Skin.StaticPopupButtonTemplate(Frame.button4)
Skin.StaticPopupButtonTemplate(Frame.extraButton)
local EditBox = _G[name .. "EditBox"]
EditBox.Left = _G[name .. "EditBoxLeft"]
EditBox.Right = _G[name .. "EditBoxRight"]
EditBox.Middle = _G[name .. "EditBoxMid"]
Skin.InputBoxTemplate(EditBox) -- BlizzWTF: this should use InputBoxTemplate
Skin.SmallMoneyFrameTemplate(Frame.moneyFrame)
Skin.MoneyInputFrameTemplate(Frame.moneyInputFrame)
Skin.FrameTypeItemButton(Frame.ItemFrame)
local nameFrame = _G[Frame.ItemFrame:GetName().."NameFrame"]
nameFrame:Hide()
local nameBG = _G.CreateFrame("Frame", nil, Frame.ItemFrame)
nameBG:SetPoint("TOPLEFT", Frame.ItemFrame.icon, "TOPRIGHT", 2, 1)
nameBG:SetPoint("BOTTOMLEFT", Frame.ItemFrame.icon, "BOTTOMRIGHT", 2, -1)
nameBG:SetPoint("RIGHT", 120, 0)
Base.SetBackdrop(nameBG, Color.frame)
end
end
function private.FrameXML.StaticPopup()
Skin.StaticPopupTemplate(_G.StaticPopup1)
Skin.StaticPopupTemplate(_G.StaticPopup2)
Skin.StaticPopupTemplate(_G.StaticPopup3)
Skin.StaticPopupTemplate(_G.StaticPopup4)
end
| 0 | 0.810864 | 1 | 0.810864 | game-dev | MEDIA | 0.79093 | game-dev | 0.879599 | 1 | 0.879599 |
BeanCheeseBurrito/Flecs.NET | 2,831 | src/Flecs.NET/Generated/PipelineBuilder/PipelineBuilder/T2.g.cs | // /_/src/Flecs.NET/Generated/PipelineBuilder/PipelineBuilder/T2.g.cs
// File was auto-generated by /_/src/Flecs.NET.Codegen/Generators/PipelineBuilder.cs
#nullable enable
using System;
using static Flecs.NET.Bindings.flecs;
namespace Flecs.NET.Core;
/// <summary>
/// A type-safe wrapper around <see cref="PipelineBuilder"/> that takes 2 type arguments.
/// </summary>
/// <typeparam name="T0">The T0 component type.</typeparam> <typeparam name="T1">The T1 component type.</typeparam>
public unsafe partial struct PipelineBuilder<T0, T1> : IEquatable<PipelineBuilder<T0, T1>>, IQueryBuilder<PipelineBuilder<T0, T1>, Pipeline<T0, T1>>
{
private PipelineBuilder _pipelineBuilder;
/// <inheritdoc cref="PipelineBuilder.World"/>
public ref ecs_world_t* World => ref _pipelineBuilder.World;
/// <inheritdoc cref="PipelineBuilder.Desc"/>
public ref ecs_pipeline_desc_t Desc => ref _pipelineBuilder.Desc;
/// <inheritdoc cref="PipelineBuilder.QueryBuilder"/>
public ref QueryBuilder QueryBuilder => ref _pipelineBuilder.QueryBuilder;
/// <inheritdoc cref="PipelineBuilder(ecs_world_t*)"/>
public PipelineBuilder(ecs_world_t* world)
{
_pipelineBuilder = new PipelineBuilder(world).With<T0>().With<T1>();
}
/// <inheritdoc cref="PipelineBuilder(ecs_world_t*, ulong)"/>
public PipelineBuilder(ecs_world_t* world, ulong entity)
{
_pipelineBuilder = new PipelineBuilder(world, entity).With<T0>().With<T1>();
}
/// <inheritdoc cref="PipelineBuilder(ecs_world_t*, string)"/>
public PipelineBuilder(ecs_world_t* world, string name)
{
_pipelineBuilder = new PipelineBuilder(world, name).With<T0>().With<T1>();
}
/// <inheritdoc cref="PipelineBuilder.Build()"/>
public Pipeline<T0, T1> Build()
{
return new Pipeline<T0, T1>(_pipelineBuilder.Build());
}
/// <inheritdoc cref="PipelineBuilder.Equals(PipelineBuilder)"/>
public bool Equals(PipelineBuilder<T0, T1> other)
{
return _pipelineBuilder == other._pipelineBuilder;
}
/// <inheritdoc cref="PipelineBuilder.Equals(object)"/>
public override bool Equals(object? obj)
{
return obj is PipelineBuilder<T0, T1> other && Equals(other);
}
/// <inheritdoc cref="PipelineBuilder.GetHashCode()"/>
public override int GetHashCode()
{
return _pipelineBuilder.GetHashCode();
}
/// <inheritdoc cref="PipelineBuilder.op_Equality"/>
public static bool operator ==(PipelineBuilder<T0, T1> left, PipelineBuilder<T0, T1> right)
{
return left.Equals(right);
}
/// <inheritdoc cref="PipelineBuilder.op_Inequality"/>
public static bool operator !=(PipelineBuilder<T0, T1> left, PipelineBuilder<T0, T1> right)
{
return !(left == right);
}
} | 0 | 0.633584 | 1 | 0.633584 | game-dev | MEDIA | 0.471413 | game-dev | 0.645918 | 1 | 0.645918 |
davechurchill/PrismataAI | 1,953 | source/ai/BuildOrderSearch.h | #pragma once
#include "Common.h"
#include "GameState.h"
#include "BuyLimits.h"
#include "Heuristics.h"
#include "BuildOrderSearchParameters.h"
#include "PartialPlayer_ActionAbility_EconomyDefault.h"
namespace Prismata
{
class BuildOrderSearch
{
protected:
BuildOrderSearchParameters _params;
PartialPlayer_ActionAbility_EconomyDefault _buyPlayer;
Move _econMove;
std::vector<CardID> _allowedBuyableIndex;
std::vector< std::vector<Action> > _actionStack;
std::vector<CardID> _boughtCardIDStack;
std::vector<CardID> _cardTypeCount;
CardType _droneType;
size_t _numBuys;
size_t _nodesSearched;
bool _solutionFound;
size_t _bestSolutionTurn;
size_t _currentMaxTurn;
size_t _bestSolutionMaxDrones;
std::string _bestSolutionString;
void passTurn(const GameState & state, const size_t turn);
void updateSolution(const GameState & state, const size_t & turn);
std::string getStackString(const size_t & turn) const;
bool isTerminalNode(const GameState & state, const CardID currentCardBuyableIndex, const size_t & turn);
public:
BuildOrderSearch(const BuildOrderSearchParameters & params);
void recurse(GameState & state, const CardID currentCardBuyableIndex, const size_t numBought, const size_t turn);
size_t getNumBuys();
size_t getNodesSearched();
void solve();
static void DoBuildOrderSearch(const rapidjson::Value & val);
static void ParseBuildOrderSearch(const std::string & json);
};
} | 0 | 0.936418 | 1 | 0.936418 | game-dev | MEDIA | 0.750907 | game-dev | 0.844785 | 1 | 0.844785 |
hajimehoshi/ebiten | 4,750 | internal/gamepad/extern_android.go | // Copyright 2022 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gamepad
import (
"github.com/hajimehoshi/ebiten/v2/internal/gamepaddb"
)
func AddAndroidGamepad(androidDeviceID int, name, sdlID string, axisCount, hatCount int) {
theGamepads.addAndroidGamepad(androidDeviceID, name, sdlID, axisCount, hatCount)
}
func RemoveAndroidGamepad(androidDeviceID int) {
theGamepads.removeAndroidGamepad(androidDeviceID)
}
func UpdateAndroidGamepadAxis(androidDeviceID int, axis int, value float64) {
theGamepads.updateAndroidGamepadAxis(androidDeviceID, axis, value)
}
func UpdateAndroidGamepadButton(androidDeviceID int, button Button, pressed bool) {
theGamepads.updateAndroidGamepadButton(androidDeviceID, button, pressed)
}
func UpdateAndroidGamepadHat(androidDeviceID int, hat int, xValue, yValue int) {
theGamepads.updateAndroidGamepadHat(androidDeviceID, hat, xValue, yValue)
}
func (g *gamepads) addAndroidGamepad(androidDeviceID int, name, sdlID string, axisCount, hatCount int) {
g.m.Lock()
defer g.m.Unlock()
gp := g.add(name, sdlID)
gp.native = &nativeGamepadImpl{
androidDeviceID: androidDeviceID,
axesReady: make([]bool, axisCount),
axes: make([]float64, axisCount),
buttons: make([]bool, gamepaddb.SDLControllerButtonMax+1),
hats: make([]int, hatCount),
}
}
func (g *gamepads) removeAndroidGamepad(androidDeviceID int) {
g.m.Lock()
defer g.m.Unlock()
g.remove(func(gamepad *Gamepad) bool {
return gamepad.native.(*nativeGamepadImpl).androidDeviceID == androidDeviceID
})
}
func (g *gamepads) updateAndroidGamepadAxis(androidDeviceID int, axis int, value float64) {
g.m.Lock()
defer g.m.Unlock()
gp := g.find(func(gamepad *Gamepad) bool {
return gamepad.native.(*nativeGamepadImpl).androidDeviceID == androidDeviceID
})
if gp == nil {
return
}
gp.updateAndroidGamepadAxis(axis, value)
}
func (g *gamepads) updateAndroidGamepadButton(androidDeviceID int, button Button, pressed bool) {
g.m.Lock()
defer g.m.Unlock()
gp := g.find(func(gamepad *Gamepad) bool {
return gamepad.native.(*nativeGamepadImpl).androidDeviceID == androidDeviceID
})
if gp == nil {
return
}
gp.updateAndroidGamepadButton(button, pressed)
}
func (g *gamepads) updateAndroidGamepadHat(androidDeviceID int, hat int, xValue, yValue int) {
g.m.Lock()
defer g.m.Unlock()
gp := g.find(func(gamepad *Gamepad) bool {
return gamepad.native.(*nativeGamepadImpl).androidDeviceID == androidDeviceID
})
if gp == nil {
return
}
gp.updateAndroidGamepadHat(hat, xValue, yValue)
}
func (g *Gamepad) updateAndroidGamepadAxis(axis int, value float64) {
g.m.Lock()
defer g.m.Unlock()
n := g.native.(*nativeGamepadImpl)
if axis < 0 || axis >= len(n.axes) {
return
}
n.axes[axis] = value
// MotionEvent with 0 value can be sent when a gamepad is connected even though an axis is not touched (#2598).
// This is problematic when an axis is a trigger button where -1 should be the default value.
// When MotionEvent with non-0 value is sent, it seems fine to assume that the axis is actually touched and ready.
if value != 0 {
n.axesReady[axis] = true
}
}
func (g *Gamepad) updateAndroidGamepadButton(button Button, pressed bool) {
g.m.Lock()
defer g.m.Unlock()
n := g.native.(*nativeGamepadImpl)
if button < 0 || int(button) >= len(n.buttons) {
return
}
n.buttons[button] = pressed
}
func (g *Gamepad) updateAndroidGamepadHat(hat int, xValue, yValue int) {
g.m.Lock()
defer g.m.Unlock()
n := g.native.(*nativeGamepadImpl)
if hat < 0 || hat >= len(n.hats) {
return
}
var v int
switch {
case xValue < 0:
v |= hatLeft
case xValue > 0:
v |= hatRight
}
switch {
case yValue < 0:
v |= hatUp
case yValue > 0:
v |= hatDown
}
n.hats[hat] = v
// Update the gamepad buttons in addition to hats.
// See https://github.com/libsdl-org/SDL/blob/47f2373dc13b66c48bf4024fcdab53cd0bdd59bb/src/joystick/android/SDL_sysjoystick.c#L290-L301
n.buttons[gamepaddb.SDLControllerButtonDpadLeft] = v&hatLeft != 0
n.buttons[gamepaddb.SDLControllerButtonDpadRight] = v&hatRight != 0
n.buttons[gamepaddb.SDLControllerButtonDpadUp] = v&hatUp != 0
n.buttons[gamepaddb.SDLControllerButtonDpadDown] = v&hatDown != 0
}
| 0 | 0.881385 | 1 | 0.881385 | game-dev | MEDIA | 0.578495 | game-dev | 0.797022 | 1 | 0.797022 |
fallahn/crogine | 2,145 | samples/golf/src/sportsball/SBallParticleDirector.cpp | /*-----------------------------------------------------------------------
Matt Marchant 2025
http://trederia.blogspot.com
Super Video Golf - zlib licence.
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 "SBallParticleDirector.hpp"
#include "SBallConsts.hpp"
#include <crogine/ecs/components/Transform.hpp>
SBallParticleDirector::SBallParticleDirector(cro::TextureResource& tr)
{
m_emitterSettings[sc::ParticleID::BallMatch].loadFromFile("assets/arcade/sportsball/particles/puff.cps", tr);
}
//public
void SBallParticleDirector::handleMessage(const cro::Message& msg)
{
const auto getEnt = [&](std::int32_t id, glm::vec3 position)
{
auto entity = getNextEntity();
entity.getComponent<cro::Transform>().setPosition(position);
entity.getComponent<cro::ParticleEmitter>().settings = m_emitterSettings[id];
entity.getComponent<cro::ParticleEmitter>().start();
return entity;
};
if (msg.id == sb::MessageID::CollisionMessage)
{
const auto& data = msg.getData<sb::CollisionEvent>();
if (data.type == sb::CollisionEvent::Match)
{
getEnt(sc::ParticleID::BallMatch, data.position).getComponent<cro::ParticleEmitter>().settings.spawnRadius = data.ballRadius;
}
}
} | 0 | 0.727123 | 1 | 0.727123 | game-dev | MEDIA | 0.755138 | game-dev | 0.743721 | 1 | 0.743721 |
ProjectSkyfire/SkyFire_548 | 17,416 | src/server/game/Texts/CreatureTextMgr.cpp | /*
* This file is part of Project SkyFire https://www.projectskyfire.org.
* See LICENSE.md file for Copyright information
*/
#include "Cell.h"
#include "CellImpl.h"
#include "Chat.h"
#include "Common.h"
#include "CreatureTextMgr.h"
#include "DatabaseEnv.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "ObjectMgr.h"
class CreatureTextBuilder
{
public:
CreatureTextBuilder(WorldObject* obj, ChatMsg msgtype, uint8 textGroup, uint32 id, Language language, WorldObject const* target)
: _source(obj), _msgType(msgtype), _textGroup(textGroup), _textId(id), _language(language), _target(target)
{
}
size_t operator()(WorldPacket* data, LocaleConstant locale) const
{
std::string const& text = sCreatureTextMgr->GetLocalizedChatString(_source->GetEntry(), _textGroup, _textId, locale);
return ChatHandler::BuildChatPacket(*data, _msgType, _language, _source, _target, text, 0, "", locale);;
}
WorldObject* _source;
ChatMsg _msgType;
uint8 _textGroup;
uint32 _textId;
Language _language;
WorldObject const* _target;
};
class PlayerTextBuilder
{
public:
PlayerTextBuilder(WorldObject* obj, WorldObject* speaker, ChatMsg msgtype, uint8 textGroup, uint32 id, Language language, WorldObject const* target)
: _source(obj), _talker(speaker), _msgType(msgtype), _textGroup(textGroup), _textId(id), _language(language), _target(target) { }
size_t operator()(WorldPacket* data, LocaleConstant locale) const
{
std::string const& text = sCreatureTextMgr->GetLocalizedChatString(_source->GetEntry(), _textGroup, _textId, locale);
return ChatHandler::BuildChatPacket(*data, _msgType, _language, _talker, _target, text, 0, "", locale);
}
WorldObject* _source;
WorldObject* _talker;
ChatMsg _msgType;
uint8 _textGroup;
uint32 _textId;
Language _language;
WorldObject const* _target;
};
void CreatureTextMgr::LoadCreatureTexts()
{
uint32 oldMSTime = getMSTime();
mTextMap.clear(); // for reload case
mTextRepeatMap.clear(); //reset all currently used temp texts
PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_CREATURE_TEXT);
PreparedQueryResult result = WorldDatabase.Query(stmt);
if (!result)
{
SF_LOG_INFO("server.loading", ">> Loaded 0 ceature texts. DB table `creature_texts` is empty.");
return;
}
uint32 textCount = 0;
uint32 creatureCount = 0;
do
{
Field* fields = result->Fetch();
CreatureTextEntry temp;
temp.entry = fields[0].GetUInt32();
temp.group = fields[1].GetUInt8();
temp.id = fields[2].GetUInt8();
temp.text = fields[3].GetString();
temp.type = ChatMsg(fields[4].GetUInt8());
temp.lang = Language(fields[5].GetUInt8());
temp.probability = fields[6].GetFloat();
temp.emote = Emote(fields[7].GetUInt32());
temp.duration = fields[8].GetUInt32();
temp.sound = fields[9].GetUInt32();
if (temp.sound)
{
if (!sSoundEntriesStore.LookupEntry(temp.sound)) {
SF_LOG_ERROR("sql.sql", "CreatureTextMgr: Entry %u, Group %u in table `creature_texts` has Sound %u but sound does not exist.", temp.entry, temp.group, temp.sound);
temp.sound = 0;
}
}
if (!GetLanguageDescByID(temp.lang))
{
SF_LOG_ERROR("sql.sql", "CreatureTextMgr: Entry %u, Group %u in table `creature_texts` using Language %u but Language does not exist.", temp.entry, temp.group, uint32(temp.lang));
temp.lang = Language::LANG_UNIVERSAL;
}
if (temp.type >= ChatMsg::MSG_NULL_ACTION)
{
SF_LOG_ERROR("sql.sql", "CreatureTextMgr: Entry %u, Group %u in table `creature_texts` has Type %u but this Chat Type does not exist.", temp.entry, temp.group, uint32(temp.type));
temp.type = ChatMsg::CHAT_MSG_SAY;
}
if (temp.emote)
{
if (!sEmotesStore.LookupEntry(temp.emote))
{
SF_LOG_ERROR("sql.sql", "CreatureTextMgr: Entry %u, Group %u in table `creature_texts` has Emote %u but emote does not exist.", temp.entry, temp.group, uint32(temp.emote));
temp.emote = EMOTE_ONESHOT_NONE;
}
}
//entry not yet added, add empty TextHolder (list of groups)
if (mTextMap.find(temp.entry) == mTextMap.end())
++creatureCount;
//add the text into our entry's group
mTextMap[temp.entry][temp.group].push_back(temp);
++textCount;
} while (result->NextRow());
SF_LOG_INFO("server.loading", ">> Loaded %u creature texts for %u creatures in %u ms", textCount, creatureCount, GetMSTimeDiffToNow(oldMSTime));
}
void CreatureTextMgr::LoadCreatureTextLocales()
{
uint32 oldMSTime = getMSTime();
mLocaleTextMap.clear(); // for reload case
QueryResult result = WorldDatabase.Query("SELECT entry, groupid, id, text_loc1, text_loc2, text_loc3, text_loc4, text_loc5, text_loc6, text_loc7, text_loc8, text_loc9, text_loc10, text_loc11 FROM locales_creature_text");
if (!result)
return;
uint32 textCount = 0;
do
{
Field* fields = result->Fetch();
CreatureTextLocale& loc = mLocaleTextMap[CreatureTextId(fields[0].GetUInt32(), uint32(fields[1].GetUInt8()), uint32(fields[2].GetUInt8()))];
for (uint8 i = 1; i < TOTAL_LOCALES; ++i)
{
LocaleConstant locale = LocaleConstant(i);
ObjectMgr::AddLocaleString(fields[3 + i - 1].GetString(), locale, loc.Text);
}
++textCount;
} while (result->NextRow());
SF_LOG_INFO("server.loading", ">> Loaded %u creature localized texts in %u ms", textCount, GetMSTimeDiffToNow(oldMSTime));
}
uint32 CreatureTextMgr::SendChat(Creature* source, uint8 textGroup, WorldObject const* whisperTarget /*= NULL*/, ChatMsg msgType /*= CHAT_MSG_ADDON*/, Language language /*= LANG_ADDON*/, CreatureTextRange range /*= TEXT_RANGE_NORMAL*/, uint32 sound /*= 0*/, Team team /*= TEAM_OTHER*/, bool gmOnly /*= false*/, Player* srcPlr /*= NULL*/)
{
if (!source)
return 0;
CreatureTextMap::const_iterator sList = mTextMap.find(source->GetEntry());
if (sList == mTextMap.end())
{
SF_LOG_ERROR("sql.sql", "CreatureTextMgr: Could not find Text for Creature(%s) Entry %u in 'creature_text' table. Ignoring.", source->GetName().c_str(), source->GetEntry());
return 0;
}
CreatureTextHolder const& textHolder = sList->second;
CreatureTextHolder::const_iterator itr = textHolder.find(textGroup);
if (itr == textHolder.end())
{
SF_LOG_ERROR("sql.sql", "CreatureTextMgr: Could not find TextGroup %u for Creature(%s) GuidLow %u Entry %u. Ignoring.", uint32(textGroup), source->GetName().c_str(), source->GetGUIDLow(), source->GetEntry());
return 0;
}
CreatureTextGroup const& textGroupContainer = itr->second; //has all texts in the group
CreatureTextRepeatIds repeatGroup = GetRepeatGroup(source, textGroup);//has all textIDs from the group that were already said
CreatureTextGroup tempGroup;//will use this to talk after sorting repeatGroup
for (CreatureTextGroup::const_iterator giter = textGroupContainer.begin(); giter != textGroupContainer.end(); ++giter)
if (std::find(repeatGroup.begin(), repeatGroup.end(), giter->id) == repeatGroup.end())
tempGroup.push_back(*giter);
if (tempGroup.empty())
{
CreatureTextRepeatMap::iterator mapItr = mTextRepeatMap.find(source->GetGUID());
if (mapItr != mTextRepeatMap.end())
{
CreatureTextRepeatGroup::iterator groupItr = mapItr->second.find(textGroup);
groupItr->second.clear();
}
tempGroup = textGroupContainer;
}
uint8 count = 0;
float lastChance = -1;
bool isEqualChanced = true;
float totalChance = 0;
for (CreatureTextGroup::const_iterator iter = tempGroup.begin(); iter != tempGroup.end(); ++iter)
{
if (lastChance >= 0 && lastChance != iter->probability)
isEqualChanced = false;
lastChance = iter->probability;
totalChance += iter->probability;
++count;
}
int32 offset = -1;
if (!isEqualChanced)
{
for (CreatureTextGroup::const_iterator iter = tempGroup.begin(); iter != tempGroup.end(); ++iter)
{
uint32 chance = uint32(iter->probability);
uint32 r = std::rand() % 100;
++offset;
if (r <= chance)
break;
}
}
uint32 pos = 0;
if (isEqualChanced || offset < 0)
pos = std::rand() % count;
else if (offset >= 0)
pos = offset;
CreatureTextGroup::const_iterator iter = tempGroup.begin() + pos;
ChatMsg finalType = (msgType == ChatMsg::CHAT_MSG_ADDON) ? iter->type : msgType;
Language finalLang = (language == Language::LANG_ADDON) ? iter->lang : language;
uint32 finalSound = sound ? sound : iter->sound;
if (finalSound)
SendSound(source, finalSound, finalType, whisperTarget, range, team, gmOnly);
Unit* finalSource = source;
if (srcPlr)
finalSource = srcPlr;
if (iter->emote)
SendEmote(finalSource, iter->emote);
if (srcPlr)
{
PlayerTextBuilder builder(source, finalSource, finalType, iter->group, iter->id, finalLang, whisperTarget);
SendChatPacket(finalSource, builder, finalType, whisperTarget, range, team, gmOnly);
}
else
{
CreatureTextBuilder builder(finalSource, finalType, iter->group, iter->id, finalLang, whisperTarget);
SendChatPacket(finalSource, builder, finalType, whisperTarget, range, team, gmOnly);
}
if (isEqualChanced || (!isEqualChanced && totalChance == 100.0f))
SetRepeatId(source, textGroup, iter->id);
return iter->duration;
}
float CreatureTextMgr::GetRangeForChatType(ChatMsg msgType) const
{
float dist = sWorld->GetFloatConfig(WorldFloatConfigs::CONFIG_LISTEN_RANGE_SAY);
switch (msgType)
{
case ChatMsg::CHAT_MSG_MONSTER_YELL:
dist = sWorld->GetFloatConfig(WorldFloatConfigs::CONFIG_LISTEN_RANGE_YELL);
break;
case ChatMsg::CHAT_MSG_MONSTER_EMOTE:
case ChatMsg::CHAT_MSG_RAID_BOSS_EMOTE:
dist = sWorld->GetFloatConfig(WorldFloatConfigs::CONFIG_LISTEN_RANGE_TEXTEMOTE);
break;
default:
break;
}
return dist;
}
void CreatureTextMgr::SendSound(Creature* source, uint32 sound, ChatMsg msgType, WorldObject const* whisperTarget, CreatureTextRange range, Team team, bool gmOnly)
{
if (!sound || !source)
return;
ObjectGuid guid = source->GetGUID();
WorldPacket data(SMSG_PLAY_SOUND, 4 + 9);
data.WriteBit(guid[2]);
data.WriteBit(guid[3]);
data.WriteBit(guid[7]);
data.WriteBit(guid[6]);
data.WriteBit(guid[0]);
data.WriteBit(guid[5]);
data.WriteBit(guid[4]);
data.WriteBit(guid[1]);
data << uint32(sound);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[1]);
SendNonChatPacket(source, &data, msgType, whisperTarget, range, team, gmOnly);
}
void CreatureTextMgr::SendNonChatPacket(WorldObject* source, WorldPacket* data, ChatMsg msgType, WorldObject const* whisperTarget, CreatureTextRange range, Team team, bool gmOnly) const
{
float dist = GetRangeForChatType(msgType);
switch (msgType)
{
case ChatMsg::CHAT_MSG_MONSTER_WHISPER:
case ChatMsg::CHAT_MSG_RAID_BOSS_WHISPER:
{
if (range == TEXT_RANGE_NORMAL)//ignores team and gmOnly
{
if (!whisperTarget || whisperTarget->GetTypeId() != TypeID::TYPEID_PLAYER)
return;
whisperTarget->ToPlayer()->GetSession()->SendPacket(data);
return;
}
break;
}
default:
break;
}
switch (range)
{
case TEXT_RANGE_AREA:
{
uint32 areaId = source->GetAreaId();
Map::PlayerList const& players = source->GetMap()->GetPlayers();
for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
if (itr->GetSource()->GetAreaId() == areaId && (!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster()))
itr->GetSource()->GetSession()->SendPacket(data);
return;
}
case TEXT_RANGE_ZONE:
{
uint32 zoneId = source->GetZoneId();
Map::PlayerList const& players = source->GetMap()->GetPlayers();
for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
if (itr->GetSource()->GetZoneId() == zoneId && (!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster()))
itr->GetSource()->GetSession()->SendPacket(data);
return;
}
case TEXT_RANGE_MAP:
{
Map::PlayerList const& players = source->GetMap()->GetPlayers();
for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
if ((!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster()))
itr->GetSource()->GetSession()->SendPacket(data);
return;
}
case TEXT_RANGE_WORLD:
{
SessionMap const& smap = sWorld->GetAllSessions();
for (SessionMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter)
if (Player* player = iter->second->GetPlayer())
if (player->GetSession() && (!team || Team(player->GetTeam()) == team) && (!gmOnly || player->IsGameMaster()))
player->GetSession()->SendPacket(data);
return;
}
case TEXT_RANGE_NORMAL:
default:
break;
}
source->SendMessageToSetInRange(data, dist, true);
}
void CreatureTextMgr::SendEmote(Unit* source, uint32 emote)
{
if (!source)
return;
source->HandleEmoteCommand(emote);
}
void CreatureTextMgr::SetRepeatId(Creature* source, uint8 textGroup, uint8 id)
{
if (!source)
return;
CreatureTextRepeatIds& repeats = mTextRepeatMap[source->GetGUID()][textGroup];
if (std::find(repeats.begin(), repeats.end(), id) == repeats.end())
repeats.push_back(id);
else
SF_LOG_ERROR("sql.sql", "CreatureTextMgr: TextGroup %u for Creature(%s) GuidLow %u Entry %u, id %u already added", uint32(textGroup), source->GetName().c_str(), source->GetGUIDLow(), source->GetEntry(), uint32(id));
}
CreatureTextRepeatIds CreatureTextMgr::GetRepeatGroup(Creature* source, uint8 textGroup)
{
ASSERT(source);//should never happen
CreatureTextRepeatIds ids;
CreatureTextRepeatMap::const_iterator mapItr = mTextRepeatMap.find(source->GetGUID());
if (mapItr != mTextRepeatMap.end())
{
CreatureTextRepeatGroup::const_iterator groupItr = (*mapItr).second.find(textGroup);
if (groupItr != mapItr->second.end())
ids = groupItr->second;
}
return ids;
}
bool CreatureTextMgr::TextExist(uint32 sourceEntry, uint8 textGroup)
{
if (!sourceEntry)
return false;
CreatureTextMap::const_iterator sList = mTextMap.find(sourceEntry);
if (sList == mTextMap.end())
{
SF_LOG_DEBUG("entities.unit", "CreatureTextMgr::TextExist: Could not find Text for Creature (entry %u) in 'creature_text' table.", sourceEntry);
return false;
}
CreatureTextHolder const& textHolder = sList->second;
CreatureTextHolder::const_iterator itr = textHolder.find(textGroup);
if (itr == textHolder.end())
{
SF_LOG_DEBUG("entities.unit", "CreatureTextMgr::TextExist: Could not find TextGroup %u for Creature (entry %u).", uint32(textGroup), sourceEntry);
return false;
}
return true;
}
std::string CreatureTextMgr::GetLocalizedChatString(uint32 entry, uint8 textGroup, uint32 id, LocaleConstant locale) const
{
CreatureTextMap::const_iterator mapitr = mTextMap.find(entry);
if (mapitr == mTextMap.end())
return "";
CreatureTextHolder::const_iterator holderItr = mapitr->second.find(textGroup);
if (holderItr == mapitr->second.end())
return "";
CreatureTextGroup::const_iterator groupItr = holderItr->second.begin();
for (; groupItr != holderItr->second.end(); ++groupItr)
if (groupItr->id == id)
break;
if (groupItr == holderItr->second.end())
return "";
std::string baseText = groupItr->text;
if (locale == DEFAULT_LOCALE)
return baseText;
if (locale > MAX_LOCALES)
return baseText;
LocaleCreatureTextMap::const_iterator locItr = mLocaleTextMap.find(CreatureTextId(entry, uint32(textGroup), id));
if (locItr == mLocaleTextMap.end())
return baseText;
ObjectMgr::GetLocaleString(locItr->second.Text, locale, baseText);
return baseText;
}
| 0 | 0.877038 | 1 | 0.877038 | game-dev | MEDIA | 0.81707 | game-dev | 0.974204 | 1 | 0.974204 |
AmiBlitz/AmiBlitz3 | 6,532 | Sourcecodes/Examples/blitzmode examples/darts_wire.ab3 | ;
; Darts program by Simon Armstrong
;
; Please note copyright notice on the projection algorithm
;
; increase the dart variable if you have an accelerated machine
;
; press esc to quit
darts=10
NPrint "Setting up, please wait..."
; processor cls for extra speed
Statement mycls{a.l}
MOVE.l d0,a0:ADD.l#40*256,a0
MOVEQ#0,d0:MOVEQ#0,d1:MOVEQ#0,d2:MOVEQ#0,d3:MOVEQ#0,d4
MOVEQ#0,d5:MOVEQ#0,d6:MOVE.ld0,a1:MOVE.ld0,a2:MOVE.ld0,a3
MOVE#255,d7
loop1:MOVEM.l d0-d6/a1-a3,-(a0):DBRA d7,loop1
AsmExit
End Statement
Macro p {SizeOf.object\`1}(a5):End Macro
Statement calcid{object.l,rottable.l}
MOVEM.l a4-a6,-(a7):MOVE.l d0,a5:MOVE.l d1,a3
MOVEM.l!p{rotx-2},d0-d2:MOVE#4092,d3:AND d3,d0:AND d3,d1
AND d3,d2:LEA !p{id},a4
MOVEM 0(a3,d2.w),d4-d5
MOVEM 0(a3,d1.w),d2-d3
MOVEM 0(a3,d0.w),d0-d1
MOVE d5,d6:MULS d3,d6:MOVE.l d6,a0:MOVE d4,d7:MULS d0,d7
SWAP d7:ADD d7,d7:MOVE d7,a1:MULS d2,d7:ADD.l d6,d7:SWAP d7
ADD d7,d7:MOVE d7,(a4)+
MOVE d4,d7:MULS d1,d7:SWAP d7:ADD d7,d7:MOVE d7,(a4)+
MOVE d5,d6:MULS d2,d6:MOVE.l d6,a2:MOVE a1,d7:MULS d3,d7
SUB.l d6,d7:SWAP d7:ADD d7,d7:MOVE d7,(a4)+
MOVE d4,d6:MULS d3,d6:MOVE.l a2,d7:SWAP d7:ADD d7,d7
MULS d0,d7:SUB.l d6,d7:SWAP d7:ADD d7,d7:MOVE d7,(a4)+
MOVE d5,d7:MULS d1,d7:SWAP d7:ADD d7,d7:MOVE d7,(a4)+
MOVE d2,d6:MULS d4,d6:MOVE.l a0,d7:SWAP d7:ADD d7,d7
MULS d0,d7:ADD.l d6,d7:SWAP d7:ADD d7,d7:MOVE d7,(a4)+
MULS d1,d2:SWAP d2:ADD d2,d2:MOVE d2,(a4)+
NEG d0:MOVE d0,(a4)+:MULS d1,d3:SWAP d3:ADD d3,d3:MOVE d3,(a4)+
MOVEM.l (a7)+,a4-a6:AsmExit
End Statement
Statement moveonz{object.l,shift.w}
EXG d0,a5
MOVEM !p{id+12},d3-d5:ASL.l d1,d3:ASL.l d1,d4:ASL.l d1,d5
MOVEM.l d3-d5,!p{vx}
EXG d0,a5:AsmExit
End Statement
Macro genvert
MOVEM.l !p{x},d0-d2:ASR.l#2,d0:ASR.l#2,d1
CNIF `1<>0
MOVEM !p{id+0},d3-d5:ASL.l#`1,d3:ASL.l#`1,d4:ASL.l#`1,d5
`2.ld3,d0:`2.ld4,d1:`2.ld5,d2
CEND
CNIF `3<>0
MOVEM !p{id+6},d3-d5:ASL.l#`3,d3:ASL.l#`3,d4:ASL.l#`3,d5
`4.ld3,d0:`4.ld4,d1:`4.ld5,d2
CEND
CNIF `5<>0
MOVEM !p{id+12},d3-d5:ASL.l#`5,d3:ASL.l#`5,d4:ASL.l#`5,d5
`6.ld3,d0:`6.ld4,d1:`6.ld5,d2
CEND
SWAP d2:TST d2:BLE flow:DIVS d2,d0:BVS flow:DIVS d2,d1:BVS flow
MULS#640,d0:MULS#512,d1
SWAP d0:SWAP d1:ADD#160,d0:ADD#128,d1:MOVEM d0-d1,(a6):ADDQ#4,a6
End Macro
Function.w gendart{object.l}
MOVEM.l a4-a6,-(a7):MOVE.l d0,a5:LEA !p{v},a6
!genvert{0,0,0,0,8,ADD}
!genvert{0,0,7,SUB,8,SUB}
!genvert{8,SUB,0,0,8,SUB}:!genvert{8,ADD,0,0,8,SUB}
!genvert{7,SUB,0,0,8,SUB}:!genvert{7,ADD,0,0,8,SUB}
MOVEM.l (a7)+,a4-a6:MOVEQ#-1,d0:AsmExit
flow:MOVEM.l (a7)+,a4-a6:MOVEQ#0,d0:AsmExit
End Statement
Function.w genstar{object.l}
MOVEM.l a4-a6,-(a7):MOVE.l d0,a5:LEA !p{v},a6
!genvert{8,ADD,0,0,0,0}:!genvert{8,SUB,0,0,0,0}
!genvert{0,0,8,ADD,0,0}:!genvert{0,0,8,SUB,0,0}
!genvert{0,0,0,0,8,ADD}:!genvert{0,0,0,0,8,SUB}
MOVEM.l (a7)+,a4-a6:AsmExit
End Statement
Statement genline{object.l}
MOVEM.l a4-a6,-(a7):MOVE.l d0,a5:LEA !p{v},a6
MOVEM.l (a6),d0-d7:MOVEM.l d0-d7,4(a6)
MOVEM.l !p{x},d0-d2
ASR.l#2,d0:ASR.l#2,d1:SWAP d2:DIVS d2,d0:DIVS d2,d1
MULS#640,d0:MULS#512,d1:SWAP d0:SWAP d1
ADD#160,d0:ADD#128,d1:MOVEM d0-d1,(a6)
MOVEM.l (a7)+,a4-a6:AsmExit
End Statement
;-------------------------------------------------------------
NEWTYPE .vert
x.w:y
End NEWTYPE
NEWTYPE .object
x.q:y:z
vx:vy:vz
thrust
rotx:roty:rotz
rvx:rvy:rvz
v.vert[64] ;verticies go here
id.w[9]
End NEWTYPE
Dim List nme.object(darts) ;wow variable dimensioning in a compiler!
Dim List bul.object(20)
Dim List fire.object(5)
Dim List bang.object(10)
;generate sin_cos table
Dim rots.w(2049):rt.l=&rots(0)
For i=0 To 2048 Step 2
rots(i)=Sin(i*2*Pi/2048)*32766
rots(i+1)=Cos(i*2*Pi/2048)*32766
Next
;setup display
BitMap 0,320,256,1
BitMap 1,320,256,1
For i=0 To 7
BitMap 2+i,320,256,1
BitMapOutput 2+i:Locate 2,0
NPrint "BLITZ DARTS BY SIMON ESC TO EXIT"
For r=0 To 2*Pi-Pi/32 Step Pi/32
j=r+i*Pi/256
Circle 160,128,Tan(j/4)*50,1
Line 160,128,160+Sin(j)*320,128+Cos(j)*256,1
Circlef 160,128,12,1
Next
Next
BLITZ
InitCopList 0,$22
PalRGB 0,1,15,12,15
PalRGB 0,9,4,4,8
DisplayPalette 0,0
CreateDisplay 0
f=2 ;frame of anim
xo=1000 ;current laser
Mouse On:MouseArea -150,-150,120,120:BlitzKeys On
.mainloop
Repeat
VWait:DisplayBitMap 0,db,f
db=1-db:Use BitMap db ;double buffer
f+1:If f=10 Then f=2
mycls{Peek.l (Addr BitMap(db)+8)}
;do you
x=MouseX:y=MouseY
Line x+155,y+128,x+165,y+128,1:Line x+160,y+123,x+160,y+133,1
If Joyb(0)=1 AND reload<1 Then Gosub addfire:reload=15
Gosub dofire:reload-1:If Joyb(0)=0 Then reload=-1
;do nme
Gosub addnme
Gosub movenme
Gosub dobang
Until RawStatus($45)
End
Macro myline Line \v[`1]\x,\v[`1]\y,\v[`2]\x,\v[`2]\y,1:End Macro
USEPATH bang()
.dobang
ResetList bang()
While NextItem(bang())
\x+\vx:\y+\vy:\z+\vz
\rotx+\rvx:\roty+\rvy:\rotz+\rvz
calcid{bang(),rt}
If genstar{bang()}
For i=0 To 4 Step 2:!myline {i,i+1}:Next
Else
KillItem bang()
EndIf
Wend
Return
USEPATH nme()
.addnme:
newnme-1
If newnme<0
If AddItem(nme())
newnme=5
\x=Rnd(8000)-4000,Rnd(24000)-12000,6000
\rotx=0,Rnd(4096),512
\rvx=0,Rnd(16)+16,0
\thrust=Rnd(4)+6
EndIf
EndIf
Return
.movenme:
ResetList nme()
While NextItem(nme())
calcid{nme(),rt}
moveonz{nme(),\thrust}
\x+\vx:\y+\vy:\z+\vz:
\rotx+\rvx:\roty+\rvy:\rotz+\rvz
If \z>1000
If gendart{nme()}
For i=1 To 5:!myline {0,i}:Next
!myline {2,3}:!myline {1,4}:!myline {1,5}
ResetList fire()
While NextItem(fire())
If Abs(\x-fire()\x)<1000
If Abs(\y-fire()\y)<1000
If Abs(\z-fire()\z)<1000
If AddItem(bang())
bang()\x=\x,\y,\z,\vx,\vy,\vz
bang()\rvx=100,130,90
EndIf
KillItem nme():KillItem fire():Goto popout
EndIf
EndIf
EndIf
Wend:popout
EndIf
Else
KillItem nme()
EndIf
Wend
Return
USEPATH fire()
.addfire:
If AddItem(fire())
xo=-xo
\x=xo,1000,1000
calcid{fire(),rt}
genline{fire()}:xx.w=\v[0]\x:yy.w=\v[0]\y
For i=1 To 7:\v[i]\x=xx,yy:Next
EndIf
\vx=x*6.5-xo/24,y*8-32,1000
Return
.dofire:
ResetList fire()
While NextItem(fire())
\x+\vx:\y+\vy:\z+\vz
If \z<16000
genline{fire()}:!myline{0,7}
Else
KillItem fire()
EndIf
Wend
Return
| 0 | 0.893987 | 1 | 0.893987 | game-dev | MEDIA | 0.716716 | game-dev,graphics-rendering | 0.981958 | 1 | 0.981958 |
aemisigna/hololiveid-kaela-event-public | 8,584 | src/main/java/com/covercorp/kaelaevent/minigame/games/glass/GlassMiniGame.java | package com.covercorp.kaelaevent.minigame.games.glass;
import com.covercorp.kaelaevent.KaelaEvent;
import com.covercorp.kaelaevent.minigame.MiniGame;
import com.covercorp.kaelaevent.minigame.announcer.Announcer;
import com.covercorp.kaelaevent.minigame.announcer.AnnouncerImpl;
import com.covercorp.kaelaevent.minigame.games.glass.arena.GlassArena;
import com.covercorp.kaelaevent.minigame.games.glass.arena.state.GlassMatchState;
import com.covercorp.kaelaevent.minigame.games.glass.arena.ui.GlassTeamChooseUI;
import com.covercorp.kaelaevent.minigame.games.glass.command.GlassChooseTeamCommand;
import com.covercorp.kaelaevent.minigame.games.glass.config.GlassConfigHelper;
import com.covercorp.kaelaevent.minigame.games.glass.listener.GlassAccessListener;
import com.covercorp.kaelaevent.minigame.games.glass.listener.GlassStatsListener;
import com.covercorp.kaelaevent.minigame.games.glass.player.GlassPlayer;
import com.covercorp.kaelaevent.minigame.games.glass.team.GlassTeam;
import com.covercorp.kaelaevent.minigame.player.PlayerHelper;
import com.covercorp.kaelaevent.minigame.player.PlayerHelperImpl;
import com.covercorp.kaelaevent.minigame.player.player.MiniGamePlayer;
import com.covercorp.kaelaevent.minigame.team.TeamHelper;
import com.covercorp.kaelaevent.minigame.team.TeamHelperImpl;
import com.covercorp.kaelaevent.minigame.team.team.MiniGameTeam;
import com.covercorp.kaelaevent.minigame.type.MiniGameType;
import com.covercorp.kaelaevent.util.PlayerUtils;
import com.google.common.collect.ImmutableList;
import fr.minuskube.inv.SmartInventory;
import lombok.AccessLevel;
import lombok.Getter;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.ScoreboardManager;
import org.bukkit.scoreboard.Team;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.UUID;
@Getter(AccessLevel.PUBLIC)
public final class GlassMiniGame extends MiniGame {
private GlassConfigHelper configHelper;
private PlayerHelper<GlassMiniGame> playerHelper;
private TeamHelper<GlassMiniGame, GlassPlayer> teamHelper;
private Announcer<GlassMiniGame> announcer;
private GlassArena arena;
public GlassMiniGame(KaelaEvent kaelaEvent) {
super(kaelaEvent, MiniGameType.GLASS_BRIDGE);
this.configHelper = new GlassConfigHelper(getGameConfiguration());
playerHelper = new PlayerHelperImpl<>(this) {
@Override
public MiniGamePlayer<GlassMiniGame> addPlayer(final Player player) {
final GlassPlayer glassPlayer = (GlassPlayer) players.put(player.getUniqueId(), new GlassPlayer(miniGame, player.getUniqueId(), player.getName()));
miniGame.getAnnouncer().sendGlobalComponent(miniGame.getMiniMessage().deserialize(
"<aqua>" + player.getName() + " <yellow>is now participating in the <green>Glass Bridge Crossing<yellow> game!"
));
return glassPlayer;
}
@Override
public MiniGamePlayer<GlassMiniGame> removePlayer(final UUID uuid) {
final Optional<MiniGamePlayer<GlassMiniGame>> playerOptional = getPlayer(uuid);
if (playerOptional.isEmpty()) return null;
final MiniGamePlayer<GlassMiniGame> player = playerOptional.get();
if (player.getMiniGameTeam() != null) {
MiniGameTeam<GlassPlayer> possibleTeam = (MiniGameTeam<GlassPlayer>) player.getMiniGameTeam();
final ScoreboardManager scoreboardManager = miniGame.getKaelaEvent().getServer().getScoreboardManager();
final Team scoreboardTeam = scoreboardManager.getMainScoreboard().getTeam(possibleTeam.getIdentifier());
if (scoreboardTeam != null) scoreboardTeam.removeEntry(player.getName());
possibleTeam.removePlayer((GlassPlayer) player);
}
final GlassPlayer glassPlayer = (GlassPlayer) players.remove(uuid);
miniGame.getAnnouncer().sendGlobalComponent(miniGame.getMiniMessage().deserialize(
"<aqua>" + player.getName() + " <yellow>is no longer participating in the <green>Glass Bridge Crossing<yellow> game."
));
return glassPlayer;
}
};
// Clear scoreboard
final ScoreboardManager scoreboardManager = getKaelaEvent().getServer().getScoreboardManager();
final Scoreboard scoreboard = scoreboardManager.getMainScoreboard();
teamHelper = new TeamHelperImpl<>(this) {
@Override
public void registerTeams() {
// Delete old teams
scoreboard.getTeams().forEach(Team::unregister);
final List<String> colors = ImmutableList.of(
"#6bceff",
"#77ff6b",
"#ff6bc4",
"#ffa66b",
"#776bff",
"#ff6bf5",
"#ff956b"
);
for (int i = 1; i <= configHelper.getMaxTeams(); i++) {
final String identifier = "team_" + i;
final MiniGameTeam<GlassPlayer> team = new GlassTeam(identifier);
final Component prefix = miniGame.getMiniMessage().deserialize("<" + colors.get(new Random().nextInt(colors.size())) + ">" + "[Team #" + i + "] ");
team.setPrefix(prefix);
final Component betterPrefix = getMiniMessage().deserialize(PlayerUtils.getBetterPrefix(i));
team.setBetterPrefix(betterPrefix);
final Team scoreboardTeam = scoreboard.registerNewTeam(identifier);
scoreboardTeam.prefix(betterPrefix);
teams.put(team.getIdentifier(), team);
}
}
@Override
public void unregisterTeams() {
getTeamList().forEach(registeredTeam -> {
final String teamIdentifier = registeredTeam.getIdentifier();
final Optional<MiniGameTeam<GlassPlayer>> teamOptional = getTeam(teamIdentifier);
if (teamOptional.isEmpty()) return;
final MiniGameTeam<GlassPlayer> team = teamOptional.get();
team.getPlayers().forEach(teamPlayer -> removePlayerFromTeam(teamPlayer, teamIdentifier));
final Team scoreboardTeam = scoreboard.getTeam(teamIdentifier);
if (scoreboardTeam != null) scoreboardTeam.unregister();
teams.remove(teamIdentifier);
getKaelaEvent().getLogger().info("Unregistered team " + teamIdentifier);
});
}
};
announcer = new AnnouncerImpl<>();
arena = new GlassArena(this);
}
public void onGameLoad() {
getKaelaEvent().getLogger().info("Loading game: Glass Bridge Crossing");
teamHelper.registerTeams();
announcer = new AnnouncerImpl<>();
getKaelaEvent().getServer().getPluginManager().registerEvents(new GlassAccessListener(this), getKaelaEvent());
getKaelaEvent().getServer().getPluginManager().registerEvents(new GlassStatsListener(this), getKaelaEvent());
getKaelaEvent().getServer().getPluginCommand("chooseteam").setExecutor(new GlassChooseTeamCommand(this));
}
public void onGameUnload() {
getKaelaEvent().getLogger().info("Unloading game: Glass Bridge Crossing");
arena = null;
teamHelper.unregisterTeams();
teamHelper = null;
playerHelper.clearPlayerList();
playerHelper = null;
configHelper = null;
}
public void openTeamInventory(Player player) {
if (this.arena.getState() != GlassMatchState.WAITING) {
player.sendMessage(getMiniMessage().deserialize("<red><bold>You can't choose team right now."));
player.sendMessage(getMiniMessage().deserialize("<red><bold>Please wait until the actual game ends."));
return;
}
SmartInventory teamInventory = SmartInventory.builder().id("TeamChooseUI").manager(KaelaEvent.getKaelaEvent().getInventoryManager()).title("Choose a Team").size(1, 9).provider(new GlassTeamChooseUI(this)).build();
teamInventory.open(player);
}
} | 0 | 0.825541 | 1 | 0.825541 | game-dev | MEDIA | 0.832584 | game-dev | 0.977447 | 1 | 0.977447 |
HbmMods/Hbm-s-Nuclear-Tech-GIT | 3,913 | src/main/java/com/hbm/tileentity/turret/TileEntityTurretRichard.java | package com.hbm.tileentity.turret;
import java.util.ArrayList;
import java.util.List;
import com.hbm.entity.projectile.EntityBulletBaseMK4;
import com.hbm.inventory.gui.GUITurretRichard;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import com.hbm.items.weapon.sedna.BulletConfig;
import com.hbm.items.weapon.sedna.factory.XFactoryRocket;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
public class TileEntityTurretRichard extends TileEntityTurretBaseNT {
static List<Integer> configs = new ArrayList();
static {
for(BulletConfig cfg : XFactoryRocket.rocket_ml) configs.add(cfg.id);
}
@Override
protected List<Integer> getAmmoList() {
return configs;
}
@Override
public String getName() {
return "container.turretRichard";
}
@Override
public double getTurretDepression() {
return 25D;
}
@Override
public double getTurretElevation() {
return 25D;
}
@Override
public double getBarrelLength() {
return 1.25D;
}
@Override
public long getMaxPower() {
return 10000;
}
@Override
public double getDecetorGrace() {
return 8D;
}
@Override
public double getDecetorRange() {
return 64D;
}
int timer;
public int loaded;
int reload;
@Override
public void updateEntity() {
super.updateEntity();
if(!worldObj.isRemote) {
if(reload > 0) {
reload--;
if(reload == 0)
this.loaded = 17;
}
if(loaded <= 0 && reload <= 0 && this.getFirstConfigLoaded() != null) {
reload = 100;
}
if(this.getFirstConfigLoaded() == null) {
this.loaded = 0;
}
this.isTurretPacket = true;
this.networkPackNT(250);
this.isTurretPacket = false;
}
}
// wow so descriptive, i dont wanna hear it; it solves the problem
private boolean isTurretPacket = false;
@Override
public void serialize(ByteBuf buf) {
if (this.isTurretPacket) {
buf.writeBoolean(true);
buf.writeInt(this.loaded);
} else {
buf.writeBoolean(false);
super.serialize(buf);
}
}
@Override
public void deserialize(ByteBuf buf) {
if(buf.readBoolean()) {
this.loaded = buf.readInt();
} else
super.deserialize(buf);
}
@Override
public void updateFiringTick() {
if(reload > 0)
return;
timer++;
if(timer > 0 && timer % 10 == 0) {
BulletConfig conf = this.getFirstConfigLoaded();
if(conf != null) {
this.spawnBullet(conf, 30F);
this.conusmeAmmo(conf.ammo);
this.worldObj.playSoundEffect(xCoord, yCoord, zCoord, "hbm:turret.richard_fire", 2.0F, 1.0F);
this.loaded--;
//if(conf.ammo.equals(new ComparableStack(ModItems.ammo_standard, EnumAmmo.ROCKET_DEMO))) timer = -50;
} else {
this.loaded = 0;
}
}
}
@Override
public void spawnBullet(BulletConfig bullet, float baseDamage) {
Vec3 pos = this.getTurretPos();
Vec3 vec = Vec3.createVectorHelper(this.getBarrelLength(), 0, 0);
vec.rotateAroundZ((float) -this.rotationPitch);
vec.rotateAroundY((float) -(this.rotationYaw + Math.PI * 0.5));
EntityBulletBaseMK4 proj = new EntityBulletBaseMK4(worldObj, bullet, baseDamage, bullet.spread, (float) rotationYaw, (float) rotationPitch);
proj.setPositionAndRotation(pos.xCoord + vec.xCoord, pos.yCoord + vec.yCoord, pos.zCoord + vec.zCoord, proj.rotationYaw, proj.rotationPitch);
proj.lockonTarget = this.target;
worldObj.spawnEntityInWorld(proj);
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
this.loaded = nbt.getInteger("loaded");
}
@Override
public void writeToNBT(NBTTagCompound nbt) {
super.writeToNBT(nbt);
nbt.setInteger("loaded", this.loaded);
}
@Override
@SideOnly(Side.CLIENT)
public Object provideGUI(int ID, EntityPlayer player, World world, int x, int y, int z) {
return new GUITurretRichard(player.inventory, this);
}
}
| 0 | 0.869888 | 1 | 0.869888 | game-dev | MEDIA | 0.947658 | game-dev | 0.974169 | 1 | 0.974169 |
SmokeyStack/adk-lib | 2,277 | rc/scripts/item/teleport.ts | import { Entity, Block, MolangVariableMap } from '@minecraft/server';
import * as adk from 'adk-scripts-server';
import { nextDouble } from 'utils/math';
export function teleportEntity(
entity: Entity,
location: adk.Vector3Builder,
dimension_height_range: { min: number; max: number }
): boolean {
while (location.y > dimension_height_range.min) {
const block: Block | undefined = entity.dimension.getBlock(location);
if (!block) break;
if (block.isLiquid || block.typeId === 'minecraft:air') location.y--;
else break;
}
const target_block: Block | undefined = entity.dimension.getBlock(location);
if (!target_block) return false;
const target_block_above: Block | undefined = target_block.above();
if (!target_block_above) return false;
if (
target_block.isLiquid ||
target_block.typeId === 'minecraft:air' ||
!target_block_above.isAir
)
return false;
for (let a: number = 0; a < 128; ++a) {
let delta: number = a / 127.0;
let velocity_x: number = (Math.random() - 0.5) * 0.2;
let velocity_y: number = (Math.random() - 0.5) * 0.2;
let velocity_z: number = (Math.random() - 0.5) * 0.2;
let e: number =
adk.MathHelper.lerp(entity.location.x, location.x, delta) +
(nextDouble(0, 1) - 0.5) * 1.0;
let k: number =
adk.MathHelper.lerp(entity.location.y, location.y + 1, delta) +
nextDouble(0, 1) * 2.0;
let l: number =
adk.MathHelper.lerp(entity.location.z, location.z, delta) +
(nextDouble(0, 1) - 0.5) * 1.0;
let molang: MolangVariableMap = new MolangVariableMap();
molang.setVector3('variable.direction', {
x: velocity_x,
y: velocity_y,
z: velocity_z
});
molang.setFloat('variable.particle_random_1', Math.random());
molang.setFloat('variable.particle_random_2', Math.random());
entity.dimension.spawnParticle(
'minecraft:portal_directional',
{
x: e,
y: k,
z: l
},
molang
);
}
entity.teleport(location.add(0, 1, 0));
return true;
}
| 0 | 0.731534 | 1 | 0.731534 | game-dev | MEDIA | 0.96323 | game-dev | 0.968858 | 1 | 0.968858 |
00-Evan/shattered-pixel-dungeon-gdx | 2,896 | core/src/com/shatteredpixel/shatteredpixeldungeon/levels/rooms/standard/BurnedRoom.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2019 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.levels.rooms.standard;
import com.shatteredpixel.shatteredpixeldungeon.levels.Level;
import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain;
import com.shatteredpixel.shatteredpixeldungeon.levels.painters.Painter;
import com.shatteredpixel.shatteredpixeldungeon.levels.traps.BurningTrap;
import com.watabou.utils.Point;
import com.watabou.utils.Random;
public class BurnedRoom extends PatchRoom {
@Override
public float[] sizeCatProbs() {
return new float[]{4, 1, 0};
}
@Override
public void paint(Level level) {
Painter.fill( level, this, Terrain.WALL );
Painter.fill( level, this, 1, Terrain.EMPTY );
for (Door door : connected.values()) {
door.set( Door.Type.REGULAR );
}
//past 8x8 each point of width/height decreases fill by 3%
// e.g. a 14x14 burned room has a fill of 54%
float fill = Math.min( 1f, 1.48f - (width()+height())*0.03f);
setupPatch(level, fill, 2, false );
for (int i=top + 1; i < bottom; i++) {
for (int j=left + 1; j < right; j++) {
if (!patch[xyToPatchCoords(j, i)])
continue;
int cell = i * level.width() + j;
int t;
switch (Random.Int( 5 )) {
case 0: default:
t = Terrain.EMPTY;
break;
case 1:
t = Terrain.EMBERS;
break;
case 2:
t = Terrain.TRAP;
level.setTrap(new BurningTrap().reveal(), cell);
break;
case 3:
t = Terrain.SECRET_TRAP;
level.setTrap(new BurningTrap().hide(), cell);
break;
case 4:
t = Terrain.INACTIVE_TRAP;
BurningTrap trap = new BurningTrap();
trap.reveal().active = false;
level.setTrap(trap, cell);
break;
}
level.map[cell] = t;
}
}
}
@Override
public boolean canPlaceWater(Point p) {
return super.canPlaceWater(p) && !patch[xyToPatchCoords(p.x, p.y)];
}
@Override
public boolean canPlaceGrass(Point p) {
return super.canPlaceGrass(p) && !patch[xyToPatchCoords(p.x, p.y)];
}
@Override
public boolean canPlaceTrap(Point p) {
return super.canPlaceTrap(p) && !patch[xyToPatchCoords(p.x, p.y)];
}
}
| 0 | 0.895168 | 1 | 0.895168 | game-dev | MEDIA | 0.987481 | game-dev | 0.977062 | 1 | 0.977062 |
aniketrajnish/Unity-Collider-Optimizer | 2,197 | Assets/ColliderOptimizer/Editor/1-core/2-poly/PolygonColliderMenuOps.cs | #if UNITY_EDITOR
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using ColliderOptimizer.Utils;
namespace ColliderOptimizer.Core.P
{
sealed class PolygonColliderMenuOps : IColliderMenuOps<PolygonCollider2D>
{
public void Optimize(PolygonCollider2D __pc)
{
var p = OptSettings.PolyParams;
var authoring = PolyOptHelpers.BuildAuthoringPaths(__pc);
var simplified = PolyOptHelpers.SimplifyPolys(authoring, p);
Undo.RecordObject(__pc, "Optimize PolygonCollider2D");
PolyOptHelpers.WritePaths(__pc, simplified);
EditorUtility.SetDirty(__pc);
}
public void Reset(PolygonCollider2D __pc)
{
var authoring = PolyOptHelpers.BuildAuthoringPaths(__pc);
Undo.RecordObject(__pc, "Reset PolygonCollider2D");
PolyOptHelpers.WritePaths(__pc, authoring);
EditorUtility.SetDirty(__pc);
}
public void Save(PolygonCollider2D __pc)
{
var data = ScriptableObject.CreateInstance<PathData>();
var cur = PolyOptHelpers.ReadPaths(__pc);
data.Paths = cur.ConvertAll(p => new Path2D { Pts = p.ToArray() });
var path = EditorUtility.SaveFilePanelInProject("Save Collider Paths", __pc.name + "-coll-path", "asset", "Pick a location");
if (string.IsNullOrEmpty(path)) { Object.DestroyImmediate(data); return; }
AssetDatabase.CreateAsset(data, path);
AssetDatabase.SaveAssets();
EditorGUIUtility.PingObject(data);
}
public void Load(PolygonCollider2D __pc)
{
var data = OptEditorHelpers.LoadAssetViaPanel<PathData>("Pick PathData asset", "asset");
if (!data || data.Paths == null) return;
var arr = new List<List<Vector2>>(data.Paths.Count);
foreach (var p in data.Paths)
arr.Add(new List<Vector2>(p?.Pts ?? System.Array.Empty<Vector2>()));
Undo.RecordObject(__pc, "Load Saved PolygonCollider2D");
PolyOptHelpers.WritePaths(__pc, arr);
EditorUtility.SetDirty(__pc);
}
}
}
#endif | 0 | 0.876762 | 1 | 0.876762 | game-dev | MEDIA | 0.82783 | game-dev | 0.866489 | 1 | 0.866489 |
shatteredmoon/open-rum | 3,905 | ultima/scripts/server/widgets/orb.nut | class U4_Orb_Widget extends U4_Widget
{
constructor()
{
base.constructor();
SetMoveType( MoveType.Stationary );
SetState( OrbState.Unused );
}
function Respawn()
{
// Players can once again use this orb
SetState( OrbState.Unused );
base.Respawn();
}
function Use( i_ciPlayer )
{
if( i_ciPlayer.IsDead() || i_ciPlayer.IsIncapacitated() )
{
i_ciPlayer.ActionFailed( msg_cant_client_StringID );
return;
}
local eState = GetState();
if( OrbState.Used == eState )
{
// The object cannot be used by the player because it has recently been used by someone else. This should
// not be considered a hack attempt since multiple players can attempt to touch an orb simultaneously,
// allowing multiple requests to reach the server
i_ciPlayer.ActionFailed( msg_not_here_client_StringID );
return;
}
local eOrbType = GetProperty( Widget_Orb_Type_PropertyID, 0 );
// Has the player recently touched this kind of orb?
local eLastOrbType = i_ciPlayer.GetProperty( U4_Last_Orb_Type_PropertyID, -1 );
if( eOrbType == eLastOrbType )
{
// The player is immune to this orb's effects until the player touches a different kind of orb
i_ciPlayer.ActionFailed( msg_hmmm_no_effect_client_StringID );
return;
}
// Will the player permanently benefit from touching this orb?
local bBenefit = false;
local ePlayerClassID = i_ciPlayer.GetProperty( U4_PlayerClass_PropertyID, U4_Avatar_Class_CustomID );
local ciPlayerClass = ::rumGetCustomAsset( ePlayerClassID );
local iStrength = 0;
if( eOrbType & OrbType.Strength )
{
iStrength = i_ciPlayer.GetProperty( U4_Strength_PropertyID, 0 );
if( iStrength < ciPlayerClass.GetProperty( Class_Strength_Cap_PropertyID, 99 ) )
{
bBenefit = true;
}
}
local iDexterity = 0;
if( eOrbType & OrbType.Dexterity )
{
iDexterity = i_ciPlayer.GetProperty( U4_Dexterity_PropertyID, 0 );
if( iDexterity < ciPlayerClass.GetProperty( Class_Dexterity_Cap_PropertyID, 99 ) )
{
bBenefit = true;
}
}
local iIntelligence = 0;
if( eOrbType & OrbType.Intelligence )
{
iIntelligence = i_ciPlayer.GetProperty( U4_Intelligence_PropertyID, 0 );
if( iIntelligence < ciPlayerClass.GetProperty( Class_Intelligence_Cap_PropertyID, 99 ) )
{
bBenefit = true;
}
}
if( !bBenefit )
{
// The player's stats are already capped as far as the permanent benefits this orb provides
i_ciPlayer.ActionFailed( msg_hmmm_no_effect_client_StringID );
return;
}
// Temporarily disable this orb
SetState( OrbState.Used );
ScheduleRespawn();
local iDamage = 0;
if( eOrbType & OrbType.Strength )
{
i_ciPlayer.SetProperty( U4_Strength_PropertyID, iStrength + 5 );
iDamage += 200;
local ciBroadcast = ::rumCreate( Player_Look_BroadcastID, GetAssetID(), OrbType.Strength );
i_ciPlayer.SendBroadcast( ciBroadcast );
}
if( eOrbType & OrbType.Dexterity )
{
i_ciPlayer.SetProperty( U4_Dexterity_PropertyID, iDexterity + 5 );
iDamage += 200;
local ciBroadcast = ::rumCreate( Player_Look_BroadcastID, GetAssetID(), OrbType.Dexterity );
i_ciPlayer.SendBroadcast( ciBroadcast );
}
if( eOrbType & OrbType.Intelligence )
{
i_ciPlayer.SetProperty( U4_Intelligence_PropertyID, iIntelligence + 5 );
iDamage += 200;
local ciBroadcast = ::rumCreate( Player_Look_BroadcastID, GetAssetID(), OrbType.Intelligence );
i_ciPlayer.SendBroadcast( ciBroadcast );
}
i_ciPlayer.Damage( iDamage, this )
// Save this orb type so that the player will have to touch another kind of orb to recieve benefits
i_ciPlayer.SetProperty( U4_Last_Orb_Type_PropertyID, eOrbType );
}
}
| 0 | 0.82303 | 1 | 0.82303 | game-dev | MEDIA | 0.681923 | game-dev | 0.939321 | 1 | 0.939321 |
JamBrain/JamBrain | 3,800 | src/shrub/src/jammer/constants.php | <?php
/// @defgroup Jammer
/// @brief The Jammer/Ludum Dare Plugin for Shrub
/// @cond INTERNAL
$SH_GLOBAL_DEFAULT['ludumdare-root'] = 0;
$SH_GLOBAL_DEFAULT['ludumdare-alert'] = ""; // Short alert message shown by the Ludum Dare site
$SH_GLOBAL_DEFAULT['ludumdare-event'] = 0; // Node where Ludum Dare events go
$SH_GLOBAL_DEFAULT['jammer-root'] = 0;
$SH_GLOBAL_DEFAULT['jammer-alert'] = ""; // Short alert message shown by the Jammer site
$SH_GLOBAL_DEFAULT['jammer.bio-root'] = 0;
$SH_GLOBAL_DEFAULT['jammer.bio-alert'] = ""; // Short alert message shown by the jammer.bio
$SH_GLOBAL_DEFAULT['SH_NODE_ID_ITEMS'] = 0;
$SH_GLOBAL_DEFAULT['SH_NODE_ID_TAGS'] = 0;
$SH_GLOBAL_DEFAULT['SH_NODE_ID_EVENTS'] = 0;
/// @endcond
/// @addtogroup NodeTypes
/// @name Jammer Types
/// @{
// Internal Types //
const SH_NODE_TYPE_ITEMS = 'items';
const SH_NODE_TYPE_TAGS = 'tags';
const SH_NODE_TYPE_EVENTS = 'events';
const SH_NODE_TYPE_ITEM = 'item'; // Game, Tool, Demo, Craft
const SH_NODE_TYPE_TAG = 'tag';
const SH_NODE_TYPE_EVENT = 'event';
/// @}
/*
// Item Constants //
const SH_NODE_ADMIN = 3; // Administrator Control Panel
const SH_NODE_TEAM = 4; // Teams (uncategorized only, i.e. Admin)
const SH_NODE_GAME = 5; // Games (proxy)
const SH_NODE_DEMO = 6; // Demos (proxy)
const SH_NODE_CRAFT = 7; // Crafts (proxy)
const SH_NODE_POST = 8; // Posts (proxy)
const SH_NODE_MEDIA = 9; // Media (proxy)
// --- //
const SH_NODE_EVENT = 16; // Ludum Dare Events
const SH_NODE_PLATFORM = 17; // Platforms
const SH_NODE_TAG = 18; // Tags
const SH_NODE_TOOL = 19; // Tools (Unity, etc)
const SH_NODE_OTHER = 20; // Other Games and Game Jams (GGJ)
const SH_NODE_CUSTOM = 21; // Custom User Generated Jams
const SH_NODE_HOSTED = 22; // Extra Events we host (3rd party, or sponsored)
// --- //
const SH_NODE_EVENT_LD = 32;
const SH_NODE_EVENT_MINILD = 33;
const SH_NODE_EVENT_OCTOBER = 34;
const SH_NODE_EVENT_SCENE = 35;
const SH_NODE_OTHER_GAME = 36; // Other Games (not from a Jam)
const SH_NODE_OTHER_DEMO = 37; // Other Demos (from Demoscene Events we haven't added)
const SH_NODE_OTHER_CRAFT = 38; // Other Crafts
const SH_NODE_OTHER_JAM = 39; // Other Game Jams
const SH_NODE_OTHER_SCENE = 40; // Other Demoscene Events
const SH_NODE_TOOL_DEV = 41;
const SH_NODE_TOOL_ART = 42;
const SH_NODE_TOOL_CONTENT = 43;
const SH_NODE_TOOL_OTHER = 44;
*/
global_AddReservedName(
// Content Types
'events',
'event',
'games',
'game',
'demos',
'demo',
'tools',
'tool',
'crafts',
'craft',
'extra',
'extras',
'medias',
'media',
'tags',
'tag',
'teams',
'team',
// Extended (may become content types, or may not)
'platforms',
'platform',
'arts',
'art',
'code',
'src',
'source',
'photos',
'photo',
'comics',
'comic',
'videos',
'video',
'streams',
'stream',
'radios',
'radio',
'live',
'broadcasts',
'broadcast',
'music',
'audio',
'sounds',
'sound',
'soundtracks',
'soundtrack',
'books',
'book',
'poems',
'poem',
'stories',
'story',
'novels',
'novel',
'comments',
'comment',
'theme',
'themes',
'vote',
'votes',
'result',
'results',
'top',
'winner',
'winners',
'loser',
'losers',
'trophy',
'trophies',
'award',
'awards',
'medal',
'medals',
'achievement',
'achievements',
// Groups
'help',
'unityhelp',
// Generally Reserved
'jammers',
'jammer',
'ludumdares',
'ludumdare',
'ldjams',
'ldjam',
'jams',
'jam',
'compos',
'compo',
'hackathons',
'hackathon',
'gamejams',
'gamejam',
'scenes',
'scene',
'intros',
'intro',
'gamers',
'gamer',
'players',
'player',
'hello',
'hey',
'howdy',
'love',
'hate',
'mom',
'dad',
// Tools
'unity',
'unreal',
'gamemaker',
'javascript',
'html',
'html5',
'css',
'python',
'flash',
'web'
);
| 0 | 0.607767 | 1 | 0.607767 | game-dev | MEDIA | 0.599597 | game-dev | 0.537825 | 1 | 0.537825 |
aliyun/aliyun-openapi-net-sdk | 5,623 | aliyun-net-sdk-imm/Imm/Transform/V20170906/FindSimilarFacesResponseUnmarshaller.cs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.imm.Model.V20170906;
namespace Aliyun.Acs.imm.Transform.V20170906
{
public class FindSimilarFacesResponseUnmarshaller
{
public static FindSimilarFacesResponse Unmarshall(UnmarshallerContext _ctx)
{
FindSimilarFacesResponse findSimilarFacesResponse = new FindSimilarFacesResponse();
findSimilarFacesResponse.HttpResponse = _ctx.HttpResponse;
findSimilarFacesResponse.RequestId = _ctx.StringValue("FindSimilarFaces.RequestId");
List<FindSimilarFacesResponse.FindSimilarFaces_FacesItem> findSimilarFacesResponse_faces = new List<FindSimilarFacesResponse.FindSimilarFaces_FacesItem>();
for (int i = 0; i < _ctx.Length("FindSimilarFaces.Faces.Length"); i++) {
FindSimilarFacesResponse.FindSimilarFaces_FacesItem facesItem = new FindSimilarFacesResponse.FindSimilarFaces_FacesItem();
facesItem.FaceId = _ctx.StringValue("FindSimilarFaces.Faces["+ i +"].FaceId");
facesItem.ImageUri = _ctx.StringValue("FindSimilarFaces.Faces["+ i +"].ImageUri");
facesItem.Similarity = _ctx.FloatValue("FindSimilarFaces.Faces["+ i +"].Similarity");
facesItem.ExternalId = _ctx.StringValue("FindSimilarFaces.Faces["+ i +"].ExternalId");
FindSimilarFacesResponse.FindSimilarFaces_FacesItem.FindSimilarFaces_FaceAttributes faceAttributes = new FindSimilarFacesResponse.FindSimilarFaces_FacesItem.FindSimilarFaces_FaceAttributes();
FindSimilarFacesResponse.FindSimilarFaces_FacesItem.FindSimilarFaces_FaceAttributes.FindSimilarFaces_FaceBoundary2 faceBoundary2 = new FindSimilarFacesResponse.FindSimilarFaces_FacesItem.FindSimilarFaces_FaceAttributes.FindSimilarFaces_FaceBoundary2();
faceBoundary2.Left = _ctx.IntegerValue("FindSimilarFaces.Faces["+ i +"].FaceAttributes.FaceBoundary.Left");
faceBoundary2.Top = _ctx.IntegerValue("FindSimilarFaces.Faces["+ i +"].FaceAttributes.FaceBoundary.Top");
faceBoundary2.Width = _ctx.IntegerValue("FindSimilarFaces.Faces["+ i +"].FaceAttributes.FaceBoundary.Width");
faceBoundary2.Height = _ctx.IntegerValue("FindSimilarFaces.Faces["+ i +"].FaceAttributes.FaceBoundary.Height");
faceAttributes.FaceBoundary2 = faceBoundary2;
facesItem.FaceAttributes = faceAttributes;
List<FindSimilarFacesResponse.FindSimilarFaces_FacesItem.FindSimilarFaces_SimilarFacesItem> facesItem_similarFaces = new List<FindSimilarFacesResponse.FindSimilarFaces_FacesItem.FindSimilarFaces_SimilarFacesItem>();
for (int j = 0; j < _ctx.Length("FindSimilarFaces.Faces["+ i +"].SimilarFaces.Length"); j++) {
FindSimilarFacesResponse.FindSimilarFaces_FacesItem.FindSimilarFaces_SimilarFacesItem similarFacesItem = new FindSimilarFacesResponse.FindSimilarFaces_FacesItem.FindSimilarFaces_SimilarFacesItem();
similarFacesItem.FaceId = _ctx.StringValue("FindSimilarFaces.Faces["+ i +"].SimilarFaces["+ j +"].FaceId");
similarFacesItem.ImageUri = _ctx.StringValue("FindSimilarFaces.Faces["+ i +"].SimilarFaces["+ j +"].ImageUri");
similarFacesItem.Similarity = _ctx.FloatValue("FindSimilarFaces.Faces["+ i +"].SimilarFaces["+ j +"].Similarity");
similarFacesItem.ExternalId = _ctx.StringValue("FindSimilarFaces.Faces["+ i +"].SimilarFaces["+ j +"].ExternalId");
FindSimilarFacesResponse.FindSimilarFaces_FacesItem.FindSimilarFaces_SimilarFacesItem.FindSimilarFaces_FaceAttributes1 faceAttributes1 = new FindSimilarFacesResponse.FindSimilarFaces_FacesItem.FindSimilarFaces_SimilarFacesItem.FindSimilarFaces_FaceAttributes1();
FindSimilarFacesResponse.FindSimilarFaces_FacesItem.FindSimilarFaces_SimilarFacesItem.FindSimilarFaces_FaceAttributes1.FindSimilarFaces_FaceBoundary faceBoundary = new FindSimilarFacesResponse.FindSimilarFaces_FacesItem.FindSimilarFaces_SimilarFacesItem.FindSimilarFaces_FaceAttributes1.FindSimilarFaces_FaceBoundary();
faceBoundary.Left = _ctx.IntegerValue("FindSimilarFaces.Faces["+ i +"].SimilarFaces["+ j +"].FaceAttributes.FaceBoundary.Left");
faceBoundary.Top = _ctx.IntegerValue("FindSimilarFaces.Faces["+ i +"].SimilarFaces["+ j +"].FaceAttributes.FaceBoundary.Top");
faceBoundary.Width = _ctx.IntegerValue("FindSimilarFaces.Faces["+ i +"].SimilarFaces["+ j +"].FaceAttributes.FaceBoundary.Width");
faceBoundary.Height = _ctx.IntegerValue("FindSimilarFaces.Faces["+ i +"].SimilarFaces["+ j +"].FaceAttributes.FaceBoundary.Height");
faceAttributes1.FaceBoundary = faceBoundary;
similarFacesItem.FaceAttributes1 = faceAttributes1;
facesItem_similarFaces.Add(similarFacesItem);
}
facesItem.SimilarFaces = facesItem_similarFaces;
findSimilarFacesResponse_faces.Add(facesItem);
}
findSimilarFacesResponse.Faces = findSimilarFacesResponse_faces;
return findSimilarFacesResponse;
}
}
}
| 0 | 0.531894 | 1 | 0.531894 | game-dev | MEDIA | 0.349601 | game-dev | 0.909097 | 1 | 0.909097 |
CoderJackLiu/UE5UnluaDemo | 3,493 | Plugins/UnLua/Source/UnLua/Private/MathLib/LuaLib_FColor.cpp | // Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#include "UnLuaEx.h"
#include "LuaLib_Math.h"
static int32 FColor_New(lua_State* L)
{
const int32 NumParams = lua_gettop(L);
void* Userdata = NewTypedUserdata(L, FColor);
switch (NumParams)
{
case 1:
{
new(Userdata) FColor(ForceInitToZero);
break;
}
case 2:
{
const uint32& ColorValue = lua_tointeger(L, 2);
new(Userdata) FColor(ColorValue);
break;
}
case 4:
{
const uint8& R = (uint8)lua_tointeger(L, 2);
const uint8& G = (uint8)lua_tointeger(L, 3);
const uint8& B = (uint8)lua_tointeger(L, 4);
new(Userdata) FColor(R, G, B);
break;
}
case 5:
{
const uint8& R = (uint8)lua_tointeger(L, 2);
const uint8& G = (uint8)lua_tointeger(L, 3);
const uint8& B = (uint8)lua_tointeger(L, 4);
const uint8& A = (uint8)lua_tointeger(L, 5);
new(Userdata) FColor(R, G, B, A);
break;
}
default:
{
return luaL_error(L, "invalid parameters");
}
}
return 1;
}
static int32 FColor_Set(lua_State* L)
{
const int32 NumParams = lua_gettop(L);
if (NumParams < 1)
return luaL_error(L, "invalid parameters");
FColor* A = (FColor*)GetCppInstanceFast(L, 1);
if (!A)
return luaL_error(L, "invalid FColor");
if (NumParams > 1)
{
A->R = (uint8)lua_tonumber(L, 2);
}
if (NumParams > 2)
{
A->G = (uint8)lua_tonumber(L, 3);
}
if (NumParams > 3)
{
A->B = (uint8)lua_tonumber(L, 4);
}
if (NumParams > 4)
{
A->A = (uint8)lua_tonumber(L, 5);
}
return 0;
}
static int32 FColor_Add(lua_State* L)
{
const int32 NumParams = lua_gettop(L);
if (NumParams < 2)
return luaL_error(L, "invalid parameters");
FColor* A = (FColor*)GetCppInstanceFast(L, 1);
if (!A)
return luaL_error(L, "invalid FColor A");
FColor* B = (FColor*)GetCppInstanceFast(L, 2);
if (!B)
return luaL_error(L, "invalid FColor B");
FColor C = *A;
C += (*B);
void* Userdata = NewTypedUserdata(L, FColor);
FColor* V = new(Userdata) FColor(C);
return 1;
}
static const luaL_Reg FColorLib[] =
{
{"Set", FColor_Set},
{"__add", FColor_Add},
{"__call", FColor_New},
{"__tostring", UnLua::TMathUtils<FColor>::ToString},
{nullptr, nullptr}
};
BEGIN_EXPORT_REFLECTED_CLASS(FColor)
ADD_FUNCTION_EX("Add", void, operator+=, const FColor&)
ADD_NAMED_FUNCTION("ToLinearColor", ReinterpretAsLinear)
ADD_STATIC_PROPERTY(White)
ADD_STATIC_PROPERTY(Black)
ADD_LIB(FColorLib)
END_EXPORT_CLASS()
IMPLEMENT_EXPORTED_CLASS(FColor)
| 0 | 0.900688 | 1 | 0.900688 | game-dev | MEDIA | 0.315241 | game-dev | 0.859615 | 1 | 0.859615 |
katas94/WorldSpace_UIToolkit_XR | 2,544 | Assets/Oculus/Platform/Scripts/GroupPresenceOptions.cs | // This file was @generated with LibOVRPlatform/codegen/main. Do not modify it!
namespace Oculus.Platform
{
using System;
using System.Collections;
using Oculus.Platform.Models;
using System.Collections.Generic;
using UnityEngine;
public class GroupPresenceOptions {
public GroupPresenceOptions() {
Handle = CAPI.ovr_GroupPresenceOptions_Create();
}
/// This the unique API Name that refers to an in-app destination
public void SetDestinationApiName(string value) {
CAPI.ovr_GroupPresenceOptions_SetDestinationApiName(Handle, value);
}
/// Set whether or not the person is shown as joinable or not to others. A user
/// that is joinable can invite others to join them. Set this to false if other
/// users would not be able to join this user. For example: the current session
/// is full, or only the host can invite others and the current user is not the
/// host.
public void SetIsJoinable(bool value) {
CAPI.ovr_GroupPresenceOptions_SetIsJoinable(Handle, value);
}
/// This is a session that represents a closer group/squad/party of users. It
/// is expected that all users with the same lobby session id can see or hear
/// each other. Users with the same lobby session id in their group presence
/// will show up in the roster and will show up as "Recently Played With" for
/// future invites if they aren't already Oculus friends. This must be set in
/// addition to is_joinable being true for a user to use invites.
public void SetLobbySessionId(string value) {
CAPI.ovr_GroupPresenceOptions_SetLobbySessionId(Handle, value);
}
/// This is a session that represents all the users that are playing a specific
/// instance of a map, game mode, round, etc. This can include users from
/// multiple different lobbies that joined together and the users may or may
/// not remain together after the match is over. Users with the same match
/// session id in their group presence will not show up in the Roster, but will
/// show up as "Recently Played with" for future invites.
public void SetMatchSessionId(string value) {
CAPI.ovr_GroupPresenceOptions_SetMatchSessionId(Handle, value);
}
/// For passing to native C
public static explicit operator IntPtr(GroupPresenceOptions options) {
return options != null ? options.Handle : IntPtr.Zero;
}
~GroupPresenceOptions() {
CAPI.ovr_GroupPresenceOptions_Destroy(Handle);
}
IntPtr Handle;
}
}
| 0 | 0.764025 | 1 | 0.764025 | game-dev | MEDIA | 0.272952 | game-dev | 0.745828 | 1 | 0.745828 |
alp1x/um-admin | 11,487 | client/noclip.lua | local IsNoClipping = false
local PlayerPed = nil
local NoClipEntity = nil
local Camera = nil
local NoClipAlpha = nil
local PlayerIsInVehicle = false
local ResourceName = GetCurrentResourceName()
local MinY, MaxY = -89.0, 89.0
--[[
Configurable values are commented.
]]
-- Perspective values
local PedFirstPersonNoClip = true -- No Clip in first person when not in a vehicle
local VehFirstPersonNoClip = false -- No Clip in first person when in a vehicle
local ESCEnable = false -- Access Map during NoClip
-- Speed settings
local Speed = 1 -- Default: 1
local MaxSpeed = 16.0 -- Default: 16.0
-- Key bindings
local MOVE_FORWARDS = 32 -- Default: W
local MOVE_BACKWARDS = 33 -- Default: S
local MOVE_LEFT = 34 -- Default: A
local MOVE_RIGHT = 35 -- Default: D
local MOVE_UP = 44 -- Default: Q
local MOVE_DOWN = 46 -- Default: E
local SPEED_DECREASE = 14 -- Default: Mouse wheel down
local SPEED_INCREASE = 15 -- Default: Mouse wheel up
local SPEED_RESET = 348 -- Default: Mouse wheel click
local SPEED_SLOW_MODIFIER = 36 -- Default: Left Control
local SPEED_FAST_MODIFIER = 21 -- Default: Left Shift
local SPEED_FASTER_MODIFIER = 19 -- Default: Left Alt
local DisabledControls = function()
HudWeaponWheelIgnoreSelection()
DisableAllControlActions(0)
DisableAllControlActions(1)
DisableAllControlActions(2)
EnableControlAction(0, 220, true)
EnableControlAction(0, 221, true)
EnableControlAction(0, 245, true)
if ESCEnable then
EnableControlAction(0, 200, true)
end
end
local IsControlAlwaysPressed = function(inputGroup, control)
return IsControlPressed(inputGroup, control) or IsDisabledControlPressed(inputGroup, control)
end
local IsPedDrivingVehicle = function(ped, veh)
return ped == GetPedInVehicleSeat(veh, -1)
end
local SetupCam = function()
local entityRot = GetEntityRotation(NoClipEntity)
Camera = CreateCameraWithParams("DEFAULT_SCRIPTED_CAMERA", GetEntityCoords(NoClipEntity), vector3(0.0, 0.0, entityRot.z), 75.0)
SetCamActive(Camera, true)
RenderScriptCams(true, true, 1000, false, false)
if PlayerIsInVehicle == 1 then
AttachCamToEntity(Camera, NoClipEntity, 0.0, VehFirstPersonNoClip == true and 0.5 or -4.5, VehFirstPersonNoClip == true and 1.0 or 2.0, true)
else
AttachCamToEntity(Camera, NoClipEntity, 0.0, PedFirstPersonNoClip == true and 0.0 or -2.0, PedFirstPersonNoClip == true and 1.0 or 0.5, true)
end
end
local DestroyCamera = function()
SetGameplayCamRelativeHeading(0)
RenderScriptCams(false, true, 1000, true, true)
DetachEntity(NoClipEntity, true, true)
SetCamActive(Camera, false)
DestroyCam(Camera, true)
end
local GetGroundCoords = function(coords)
local rayCast = StartShapeTestRay(coords.x, coords.y, coords.z, coords.x, coords.y, -10000.0, 1, 0)
local _, hit, hitCoords = GetShapeTestResult(rayCast)
return (hit == 1 and hitCoords) or coords
end
local CheckInputRotation = function()
local rightAxisX = GetControlNormal(0, 220)
local rightAxisY = GetControlNormal(0, 221)
local rotation = GetCamRot(Camera, 2)
local yValue = rightAxisY * -5
local newX
local newZ = rotation.z + (rightAxisX * -10)
if (rotation.x + yValue > MinY) and (rotation.x + yValue < MaxY) then
newX = rotation.x + yValue
end
if newX ~= nil and newZ ~= nil then
SetCamRot(Camera, vector3(newX, rotation.y, newZ), 2)
end
SetEntityHeading(NoClipEntity, math.max(0, (rotation.z % 360)))
end
RunNoClipThread = function()
Citizen.CreateThread(function()
while IsNoClipping do
Citizen.Wait(0)
CheckInputRotation()
DisabledControls()
if IsControlAlwaysPressed(2, SPEED_DECREASE) then
Speed = Speed - 0.5
if Speed < 0.5 then
Speed = 0.5
end
elseif IsControlAlwaysPressed(2, SPEED_INCREASE) then
Speed = Speed + 0.5
if Speed > MaxSpeed then
Speed = MaxSpeed
end
elseif IsDisabledControlJustReleased(0, SPEED_RESET) then
Speed = 1
end
local multi = 1.0
if IsControlAlwaysPressed(0, SPEED_FAST_MODIFIER) then
multi = 2
elseif IsControlAlwaysPressed(0, SPEED_FASTER_MODIFIER) then
multi = 4
elseif IsControlAlwaysPressed(0, SPEED_SLOW_MODIFIER) then
multi = 0.25
end
if IsControlAlwaysPressed(0, MOVE_FORWARDS) then
local pitch = GetCamRot(Camera, 0)
if pitch.x >= 0 then
SetEntityCoordsNoOffset(NoClipEntity, GetOffsetFromEntityInWorldCoords(NoClipEntity, 0.0, 0.5*(Speed * multi), (pitch.x*((Speed/2) * multi))/89))
else
SetEntityCoordsNoOffset(NoClipEntity, GetOffsetFromEntityInWorldCoords(NoClipEntity, 0.0, 0.5*(Speed * multi), -1*((math.abs(pitch.x)*((Speed/2) * multi))/89)))
end
elseif IsControlAlwaysPressed(0, MOVE_BACKWARDS) then
local pitch = GetCamRot(Camera, 2)
if pitch.x >= 0 then
SetEntityCoordsNoOffset(NoClipEntity, GetOffsetFromEntityInWorldCoords(NoClipEntity, 0.0, -0.5*(Speed * multi), -1*(pitch.x*((Speed/2) * multi))/89))
else
SetEntityCoordsNoOffset(NoClipEntity, GetOffsetFromEntityInWorldCoords(NoClipEntity, 0.0, -0.5*(Speed * multi), ((math.abs(pitch.x)*((Speed/2) * multi))/89)))
end
end
if IsControlAlwaysPressed(0, MOVE_LEFT) then
SetEntityCoordsNoOffset(NoClipEntity, GetOffsetFromEntityInWorldCoords(NoClipEntity, -0.5*(Speed * multi), 0.0, 0.0))
elseif IsControlAlwaysPressed(0, MOVE_RIGHT) then
SetEntityCoordsNoOffset(NoClipEntity, GetOffsetFromEntityInWorldCoords(NoClipEntity, 0.5*(Speed * multi), 0.0, 0.0))
end
if IsControlAlwaysPressed(0, MOVE_UP) then
SetEntityCoordsNoOffset(NoClipEntity, GetOffsetFromEntityInWorldCoords(NoClipEntity, 0.0, 0.0, 0.5*(Speed * multi)))
elseif IsControlAlwaysPressed(0, MOVE_DOWN) then
SetEntityCoordsNoOffset(NoClipEntity, GetOffsetFromEntityInWorldCoords(NoClipEntity, 0.0, 0.0, -0.5*(Speed * multi)))
end
local coords = GetEntityCoords(NoClipEntity)
RequestCollisionAtCoord(coords.x, coords.y, coords.z)
FreezeEntityPosition(NoClipEntity, true)
SetEntityCollision(NoClipEntity, false, false)
SetEntityVisible(NoClipEntity, false, false)
SetEntityInvincible(NoClipEntity, true)
SetLocalPlayerVisibleLocally(true)
SetEntityAlpha(NoClipEntity, NoClipAlpha, false)
if PlayerIsInVehicle == 1 then
SetEntityAlpha(PlayerPed, NoClipAlpha, false)
end
SetEveryoneIgnorePlayer(PlayerPed, true)
SetPoliceIgnorePlayer(PlayerPed, true)
end
StopNoClip()
end)
end
StopNoClip = function()
FreezeEntityPosition(NoClipEntity, false)
SetEntityCollision(NoClipEntity, true, true)
SetEntityVisible(NoClipEntity, true, false)
SetLocalPlayerVisibleLocally(true)
ResetEntityAlpha(NoClipEntity)
ResetEntityAlpha(PlayerPed)
SetEveryoneIgnorePlayer(PlayerPed, false)
SetPoliceIgnorePlayer(PlayerPed, false)
ResetEntityAlpha(NoClipEntity)
SetPoliceIgnorePlayer(PlayerPed, true)
if GetVehiclePedIsIn(PlayerPed, false) ~= 0 then
while (not IsVehicleOnAllWheels(NoClipEntity)) and not IsNoClipping do
Wait(0)
end
while not IsNoClipping do
Wait(0)
if IsVehicleOnAllWheels(NoClipEntity) then
return SetEntityInvincible(NoClipEntity, false)
end
end
else
if (IsPedFalling(NoClipEntity) and math.abs(1 - GetEntityHeightAboveGround(NoClipEntity)) > 1.00) then
while (IsPedStopped(NoClipEntity) or not IsPedFalling(NoClipEntity)) and not IsNoClipping do
Wait(0)
end
end
while not IsNoClipping do
Wait(0)
if (not IsPedFalling(NoClipEntity)) and (not IsPedRagdoll(NoClipEntity)) then
return SetEntityInvincible(NoClipEntity, false)
end
end
end
end
ToggleNoClip = function(state)
IsNoClipping = state or not IsNoClipping
PlayerPed = PlayerPedId()
PlayerIsInVehicle = IsPedInAnyVehicle(PlayerPed, false)
if PlayerIsInVehicle ~= 0 and IsPedDrivingVehicle(PlayerPed, GetVehiclePedIsIn(PlayerPed, false)) then
NoClipEntity = GetVehiclePedIsIn(PlayerPed, false)
SetVehicleEngineOn(NoClipEntity, not IsNoClipping, true, IsNoClipping)
NoClipAlpha = PedFirstPersonNoClip == true and 0 or 51
else
NoClipEntity = PlayerPed
NoClipAlpha = VehFirstPersonNoClip == true and 0 or 51
end
if IsNoClipping then
FreezeEntityPosition(PlayerPed)
SetupCam()
PlaySoundFromEntity(-1, "SELECT", PlayerPed, "HUD_LIQUOR_STORE_SOUNDSET", 0, 0)
if not PlayerIsInVehicle then
ClearPedTasksImmediately(PlayerPed)
if PedFirstPersonNoClip then
Citizen.Wait(1000) -- Wait for the cinematic effect of the camera transitioning into first person
end
else
if VehFirstPersonNoClip then
Citizen.Wait(1000) -- Wait for the cinematic effect of the camera transitioning into first person
end
end
else
local groundCoords = GetGroundCoords(GetEntityCoords(NoClipEntity))
SetEntityCoords(NoClipEntity, groundCoords.x, groundCoords.y, groundCoords.z)
Citizen.Wait(50)
DestroyCamera()
PlaySoundFromEntity(-1, "CANCEL", PlayerPed, "HUD_LIQUOR_STORE_SOUNDSET", 0, 0)
end
QBCore.Functions.Notify(IsNoClipping and Lang:t("success.noclip_enabled") or Lang:t("success.noclip_disabled"))
SetUserRadioControlEnabled(not IsNoClipping)
if IsNoClipping then
RunNoClipThread()
end
end
RegisterNetEvent('qb-admin:client:ToggleNoClip', function()
ToggleNoClip(not IsNoClipping)
TriggerServerEvent('um-admin:log:minPage',"noclip","noclip","black")
end)
AddEventHandler('onResourceStop', function(resourceName)
if resourceName == ResourceName then
FreezeEntityPosition(NoClipEntity, false)
FreezeEntityPosition(PlayerPed, false)
SetEntityCollision(NoClipEntity, true, true)
SetEntityVisible(NoClipEntity, true, false)
SetLocalPlayerVisibleLocally(true)
ResetEntityAlpha(NoClipEntity)
ResetEntityAlpha(PlayerPed)
SetEveryoneIgnorePlayer(PlayerPed, false)
SetPoliceIgnorePlayer(PlayerPed, false)
ResetEntityAlpha(NoClipEntity)
SetPoliceIgnorePlayer(PlayerPed, true)
SetEntityInvincible(NoClipEntity, false)
end
end)
| 0 | 0.901387 | 1 | 0.901387 | game-dev | MEDIA | 0.827452 | game-dev | 0.968604 | 1 | 0.968604 |
hengband/hengband | 5,121 | src/mspell/mspell-attack/mspell-particularity.cpp | /*!
* @brief ボルトでもボールでもブレスでもなく、ダメージを与える特殊なスペルの実行 /
* Performing special spells that take damage, not bolts, balls or breaths
* @date 2020/05/16
* @author Hourier
* @details 肥大化しやすいファイル名なので、関数の追加時は共通部分を別ファイルに抜き出せるか検討すること /
* This is a filename that tends to be bloated.
* So when adding a function, please consider whether you can extract the common part to another file.
*/
#include "mspell/mspell-attack/mspell-particularity.h"
#include "effect/effect-processor.h"
#include "mind/drs-types.h"
#include "monster-race/race-ability-flags.h"
#include "monster/monster-update.h"
#include "mspell/mspell-checker.h"
#include "mspell/mspell-damage-calculator.h"
#include "mspell/mspell-data.h"
#include "mspell/mspell-result.h"
#include "mspell/mspell-util.h"
#include "system/player-type-definition.h"
MSpellAttackOther::MSpellAttackOther(PlayerType *player_ptr, MONSTER_IDX m_idx, MonsterAbilityType ability, MSpellData data, int target_type, std::function<ProjectResult(POSITION, POSITION, int, AttributeType)> fire)
: AbstractMSpellAttack(player_ptr, m_idx, ability, data, target_type, fire)
{
}
MSpellAttackOther::MSpellAttackOther(PlayerType *player_ptr, MONSTER_IDX m_idx, MONSTER_IDX t_idx, MonsterAbilityType ability, MSpellData data, int target_type, std::function<ProjectResult(POSITION, POSITION, int, AttributeType)> fire)
: AbstractMSpellAttack(player_ptr, m_idx, t_idx, ability, data, target_type, fire)
{
}
/*!
* @brief RF4_ROCKETの処理。ロケット。 /
* @param player_ptr プレイヤーへの参照ポインタ
* @param y 対象の地点のy座標
* @param x 対象の地点のx座標
* @param m_idx 呪文を唱えるモンスターID
* @param t_idx 呪文を受けるモンスターID。プレイヤーの場合はdummyで0とする。
* @param target_type プレイヤーを対象とする場合MONSTER_TO_PLAYER、モンスターを対象とする場合MONSTER_TO_MONSTER
*
* プレイヤーに当たったらラーニング可。
*/
MonsterSpellResult spell_RF4_ROCKET(PlayerType *player_ptr, POSITION y, POSITION x, MONSTER_IDX m_idx, MONSTER_IDX t_idx, int target_type)
{
const auto data = MSpellData({ _("%s^が何かを射った。", "%s^ shoots something."),
_("%s^がロケットを発射した。", "%s^ fires a rocket."),
_("%s^が%sにロケットを発射した。", "%s^ fires a rocket at %s.") },
AttributeType::ROCKET, DRS_SHARD);
return MSpellAttackOther(player_ptr, m_idx, t_idx, MonsterAbilityType::ROCKET, data, target_type,
[=](auto y, auto x, int dam, auto attribute) { return rocket(player_ptr, y, x, m_idx, attribute, dam, 2, target_type); })
.shoot(y, x);
}
static bool message_hand_doom(PlayerType *player_ptr, MONSTER_IDX m_idx, MONSTER_IDX t_idx, int target_type)
{
mspell_cast_msg_simple msg(_("%s^が<破滅の手>を放った!", "%s^ invokes the Hand of Doom!"),
_("%s^が%sに<破滅の手>を放った!", "%s^ invokes the Hand of Doom upon %s!"));
simple_monspell_message(player_ptr, m_idx, t_idx, msg, target_type);
return true;
}
static auto project_hand_doom(PlayerType *player_ptr, MONSTER_IDX m_idx, POSITION y, POSITION x, int target_type)
{
ProjectResult proj_res;
auto attribute = AttributeType::HAND_DOOM;
if (target_type == MONSTER_TO_PLAYER) {
const auto dam = monspell_damage(player_ptr, MonsterAbilityType::HAND_DOOM, m_idx, DAM_ROLL);
proj_res = pointed(player_ptr, y, x, m_idx, attribute, dam, MONSTER_TO_PLAYER);
} else if (target_type == MONSTER_TO_MONSTER) {
const auto dam = 20; /* Dummy power */
proj_res = pointed(player_ptr, y, x, m_idx, attribute, dam, MONSTER_TO_MONSTER);
}
return proj_res;
}
/*!
* @brief RF6_HAND_DOOMの処理。破滅の手。 /
* @param player_ptr プレイヤーへの参照ポインタ
* @param y 対象の地点のy座標
* @param x 対象の地点のx座標
* @param m_idx 呪文を唱えるモンスターID
* @param t_idx 呪文を受けるモンスターID。プレイヤーの場合はdummyで0とする。
* @param target_type プレイヤーを対象とする場合MONSTER_TO_PLAYER、モンスターを対象とする場合MONSTER_TO_MONSTER
*
* プレイヤーに当たったらラーニング可。
*/
MonsterSpellResult spell_RF6_HAND_DOOM(PlayerType *player_ptr, POSITION y, POSITION x, MONSTER_IDX m_idx, MONSTER_IDX t_idx, int target_type)
{
return MSpellAttackOther(player_ptr, m_idx, t_idx, MonsterAbilityType::HAND_DOOM, { message_hand_doom, AttributeType::MAX }, target_type,
[=](auto y, auto x, int, AttributeType) { return project_hand_doom(player_ptr, m_idx, y, x, target_type); })
.shoot(y, x);
}
/*!
* @brief RF6_PSY_SPEARの処理。光の剣。 /
* @param y 対象の地点のy座標
* @param x 対象の地点のx座標
* @param m_idx 呪文を唱えるモンスターID
* @param t_idx 呪文を受けるモンスターID。プレイヤーの場合はdummyで0とする。
* @param target_type プレイヤーを対象とする場合MONSTER_TO_PLAYER、モンスターを対象とする場合MONSTER_TO_MONSTER
*
* プレイヤーに当たったらラーニング可。
*/
MonsterSpellResult spell_RF6_PSY_SPEAR(PlayerType *player_ptr, POSITION y, POSITION x, MONSTER_IDX m_idx, MONSTER_IDX t_idx, int target_type)
{
const auto data = MSpellData({ _("%s^が何かをつぶやいた。", "%s^ mumbles."), _("%s^が光の剣を放った。", "%s^ throws a Psycho-Spear."),
_("%s^が%sに向かって光の剣を放った。", "%s^ throws a Psycho-spear at %s.") },
AttributeType::PSY_SPEAR);
return MSpellAttackOther(player_ptr, m_idx, t_idx, MonsterAbilityType::PSY_SPEAR, data, target_type,
[=](auto y, auto x, int dam, auto attribute) { return beam(player_ptr, m_idx, y, x, attribute, dam, target_type); })
.shoot(y, x);
}
| 0 | 0.723585 | 1 | 0.723585 | game-dev | MEDIA | 0.967516 | game-dev | 0.839836 | 1 | 0.839836 |
rehlds/ReGameDLL_CS | 8,490 | regamedll/public/regamedll/API/CSPlayer.h | /*
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game Engine ("HL
* Engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL Engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#pragma once
#include <API/CSPlayerItem.h>
#include <API/CSPlayerWeapon.h>
#include <utlarray.h>
enum WeaponInfiniteAmmoMode
{
WPNMODE_INFINITE_CLIP = 1,
WPNMODE_INFINITE_BPAMMO
};
class CCSPlayer: public CCSMonster {
public:
CCSPlayer() :
m_bForceShowMenu(false),
m_flRespawnPending(0),
m_flSpawnProtectionEndTime(0),
m_iWeaponInfiniteAmmo(0),
m_iWeaponInfiniteIds(0),
m_bCanShootOverride(false),
m_bGameForcingRespawn(false),
m_bAutoBunnyHopping(false),
m_bMegaBunnyJumping(false),
m_bPlantC4Anywhere(false),
m_bSpawnProtectionEffects(false),
m_flJumpHeight(0),
m_flLongJumpHeight(0),
m_flLongJumpForce(0),
m_flDuckSpeedMultiplier(0),
m_iUserID(-1),
m_iGibDamageThreshold(GIB_PLAYER_THRESHOLD)
{
m_szModel[0] = '\0';
// Resets the kill history for this player
for (int i = 0; i < MAX_CLIENTS; i++)
{
m_iNumKilledByUnanswered[i] = 0;
m_bPlayerDominated[i] = false;
}
}
virtual bool IsConnected() const;
virtual void SetAnimation(PLAYER_ANIM playerAnim);
virtual void AddAccount(int amount, RewardType type = RT_NONE, bool bTrackChange = true);
virtual CBaseEntity *GiveNamedItem(const char *pszName);
virtual CBaseEntity *GiveNamedItemEx(const char *pszName);
virtual void GiveDefaultItems();
virtual void GiveShield(bool bDeploy = true);
virtual CBaseEntity *DropShield(bool bDeploy = true);
virtual CBaseEntity* DropPlayerItem(const char *pszItemName);
virtual bool RemoveShield();
virtual void RemoveAllItems(bool bRemoveSuit);
virtual bool RemovePlayerItem(const char* pszItemName);
virtual void SetPlayerModel(bool bHasC4);
virtual void SetPlayerModelEx(const char *modelName);
virtual void SetNewPlayerModel(const char *modelName);
virtual void ClientCommand(const char *cmd, const char *arg1 = nullptr, const char *arg2 = nullptr, const char *arg3 = nullptr);
virtual void SetProgressBarTime(int time);
virtual void SetProgressBarTime2(int time, float timeElapsed);
virtual struct edict_s *EntSelectSpawnPoint();
virtual void SetBombIcon(bool bFlash = false);
virtual void SetScoreAttrib(CBasePlayer *dest);
virtual void SendItemStatus();
virtual void ReloadWeapons(CBasePlayerItem *pWeapon = nullptr, bool bForceReload = false, bool bForceRefill = false);
virtual void Observer_SetMode(int iMode);
virtual bool SelectSpawnSpot(const char *pEntClassName, CBaseEntity* &pSpot);
virtual bool SwitchWeapon(CBasePlayerItem *pWeapon);
virtual void SwitchTeam();
virtual bool JoinTeam(TeamName team);
virtual void StartObserver(Vector& vecPosition, Vector& vecViewAngle);
virtual void TeamChangeUpdate();
virtual void DropSecondary();
virtual void DropPrimary();
virtual bool HasPlayerItem(CBasePlayerItem *pCheckItem);
virtual bool HasNamedPlayerItem(const char *pszItemName);
virtual CBasePlayerItem *GetItemById(WeaponIdType weaponID);
virtual CBasePlayerItem *GetItemByName(const char *itemName);
virtual void Disappear();
virtual void MakeVIP();
virtual bool MakeBomber();
virtual void ResetSequenceInfo();
virtual void StartDeathCam();
virtual bool RemovePlayerItemEx(const char* pszItemName, bool bRemoveAmmo);
virtual void SetSpawnProtection(float flProtectionTime);
virtual void RemoveSpawnProtection();
virtual bool HintMessageEx(const char *pMessage, float duration = 6.0f, bool bDisplayIfPlayerDead = false, bool bOverride = false);
virtual void Reset();
virtual void OnSpawnEquip(bool addDefault = true, bool equipGame = true);
virtual void SetScoreboardAttributes(CBasePlayer *destination = nullptr);
virtual void Observer_FindNextPlayer(bool bReverse, const char *name = nullptr);
virtual void TakeDamageImpulse(CBasePlayer *pAttacker, float flKnockbackForce, float flVelModifier);
bool IsPlayerDominated(int iPlayerIndex) const;
void SetPlayerDominated(CBasePlayer *pPlayer, bool bDominated);
void ResetVars();
void ResetAllStats();
void OnSpawn();
void OnKilled();
void OnConnect();
CBasePlayer *BasePlayer() const;
public:
enum EProtectionState
{
ProtectionSt_NoSet,
ProtectionSt_Active,
ProtectionSt_Expired,
};
EProtectionState GetProtectionState() const;
bool CheckActivityInGame();
const usercmd_t *GetLastUserCommand() const
{
return &m_LastCmd;
}
void SetLastUserCommand(const usercmd_t &ucmd)
{
m_LastCmd = ucmd;
}
public:
char m_szModel[32];
bool m_bForceShowMenu;
float m_flRespawnPending;
float m_flSpawnProtectionEndTime;
Vector m_vecOldvAngle;
int m_iWeaponInfiniteAmmo;
int m_iWeaponInfiniteIds;
bool m_bCanShootOverride;
bool m_bGameForcingRespawn;
bool m_bAutoBunnyHopping;
bool m_bMegaBunnyJumping;
bool m_bPlantC4Anywhere;
bool m_bSpawnProtectionEffects;
double m_flJumpHeight;
double m_flLongJumpHeight;
double m_flLongJumpForce;
double m_flDuckSpeedMultiplier;
int m_iUserID;
struct CDamageRecord_t
{
float flDamage = 0.0f;
float flFlashDurationTime = 0.0f;
int userId = -1;
};
using DamageList_t = CUtlArray<CDamageRecord_t, MAX_CLIENTS>;
DamageList_t m_DamageList; // A unified array of recorded damage that includes giver and taker in each entry
DamageList_t &GetDamageList() { return m_DamageList; }
void RecordDamage(CBasePlayer *pAttacker, float flDamage, float flFlashDurationTime = -1);
int m_iNumKilledByUnanswered[MAX_CLIENTS]; // [0-31] how many unanswered kills this player has been dealt by each other player
bool m_bPlayerDominated[MAX_CLIENTS]; // [0-31] array of state per other player whether player is dominating other players
int m_iGibDamageThreshold; // negative health to reach to gib player
usercmd_t m_LastCmd;
// Player movement version control
PlayerMovementVersion m_MovementVersion;
};
// Inlines
inline CBasePlayer *CCSPlayer::BasePlayer() const
{
return reinterpret_cast<CBasePlayer *>(this->m_pContainingEntity);
}
inline CCSPlayer::EProtectionState CCSPlayer::GetProtectionState() const
{
// no protection set
if (m_flSpawnProtectionEndTime <= 0.0f)
return ProtectionSt_NoSet;
// check if end time of protection isn't expired yet
if (m_flSpawnProtectionEndTime >= gpGlobals->time)
return ProtectionSt_Active;
// has expired
return ProtectionSt_Expired;
}
// Returns whether this player is dominating the specified other player
inline bool CCSPlayer::IsPlayerDominated(int iPlayerIndex) const
{
if (iPlayerIndex < 0 || iPlayerIndex >= MAX_CLIENTS)
return false;
return m_bPlayerDominated[iPlayerIndex];
}
// Sets whether this player is dominating the specified other player
inline void CCSPlayer::SetPlayerDominated(CBasePlayer *pPlayer, bool bDominated)
{
int iPlayerIndex = pPlayer->entindex();
Assert(iPlayerIndex > 0 && iPlayerIndex <= MAX_CLIENTS);
m_bPlayerDominated[iPlayerIndex - 1] = bDominated;
}
#ifdef REGAMEDLL_API
// Determine whether player can be gibbed or not
inline bool CBasePlayer::ShouldGibPlayer(int iGib)
{
// Always gib the player regardless of incoming damage
if (iGib == GIB_ALWAYS)
return true;
// Gib the player if health is below the gib damage threshold
if (pev->health < CSPlayer()->m_iGibDamageThreshold && iGib != GIB_NEVER)
return true;
// do not gib the player
return false;
}
#endif
| 0 | 0.923647 | 1 | 0.923647 | game-dev | MEDIA | 0.809536 | game-dev,networking | 0.567015 | 1 | 0.567015 |
kniEngine/kni | 7,585 | src/Xna.Framework.Content.Pipeline/NamedValueDictionary.cs | // MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using System.Collections;
using System.Collections.Generic;
namespace Microsoft.Xna.Framework.Content.Pipeline
{
public class NamedValueDictionary<T> : IDictionary<string, T>
{
readonly Dictionary<string, T> dict = new Dictionary<string,T>();
/// <summary>
/// Initializes an instance of NamedValueDictionary.
/// </summary>
public NamedValueDictionary()
{
}
/// <summary>
/// Adds the specified key and value to the dictionary.
/// </summary>
/// <param name="key">Identity of the key of the new data pair.</param>
/// <param name="value">The value of the new data pair.</param>
public void Add(string key, T value)
{
dict.Add(key, value);
}
/// <summary>
/// Determines whether the specified key is present in the dictionary.
/// </summary>
/// <param name="key">Identity of a key.</param>
/// <returns></returns>
public bool ContainsKey(string key)
{
return dict.ContainsKey(key);
}
/// <summary>
/// Gets all keys contained in the dictionary.
/// </summary>
public ICollection<string> Keys
{
get { return dict.Keys; }
}
/// <summary>
/// Removes the specified key and value from the dictionary.
/// </summary>
/// <param name="key">Identity of the key to be removed.</param>
/// <returns>true if the value is present; false otherwise.</returns>
public bool Remove(string key)
{
return dict.Remove(key);
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">Identity of the key of the element whose value is to be retrieved.</param>
/// <param name="value">The current value of the element.</param>
/// <returns>true if the value is present; false otherwise.</returns>
public bool TryGetValue(string key, out T value)
{
return dict.TryGetValue(key, out value);
}
/// <summary>
/// Specifies the type hint for the intermediate serializer. Values of this type do not store an explicit type attribute in the related XML source.
/// </summary>
protected internal virtual Type DefaultSerializerType
{
get { return typeof(T); }
}
/// <summary>
/// Gets all values contained in the dictionary.
/// </summary>
public ICollection<T> Values
{
get { return dict.Values; }
}
/// <summary>
/// Gets or sets the specified item.
/// </summary>
/// <param name="key">Identity of a key.</param>
public T this[string key]
{
get
{
return dict[key];
}
set
{
dict[key] = value;
}
}
/// <summary>
/// Adds an item to the collection.
/// </summary>
/// <param name="item">The item to add to the collection.</param>
void ICollection<KeyValuePair<string, T>>.Add(KeyValuePair<string, T> item)
{
((ICollection<KeyValuePair<string, T>>)dict).Add(item);
}
/// <summary>
/// Removes all keys and values from the dictionary.
/// </summary>
public void Clear()
{
dict.Clear();
}
/// <summary>
/// Determines whether the collection contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the collection.</param>
/// <returns>true if the collection contains the object; false otherwise.</returns>
bool ICollection<KeyValuePair<string, T>>.Contains(KeyValuePair<string, T> item)
{
return ((ICollection<KeyValuePair<string, T>>)dict).Contains(item);
}
/// <summary>
/// Copies the elements of the collection to an array, starting at a specified index.
/// </summary>
/// <param name="array">The destination array.</param>
/// <param name="arrayIndex">The index at which to begin the copy.</param>
void ICollection<KeyValuePair<string, T>>.CopyTo(KeyValuePair<string, T>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<string, T>>)dict).CopyTo(array, arrayIndex);
}
/// <summary>
/// Gets the number of items in the dictionary.
/// </summary>
public int Count
{
get { return dict.Count; }
}
/// <summary>
/// Gets a value indicating if this object is read-only.
/// </summary>
bool ICollection<KeyValuePair<string, T>>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Removes the first occurrence of the specified object from the collection.
/// </summary>
/// <param name="item">The item to remove from the collection.</param>
/// <returns>true if the item was successfully removed from the collection; false otherwise.</returns>
bool ICollection<KeyValuePair<string, T>>.Remove(KeyValuePair<string, T> item)
{
return ((ICollection<KeyValuePair<string, T>>)dict).Remove(item);
}
/// <summary>
/// Gets an enumerator that iterates through items in a dictionary.
/// </summary>
/// <returns>Enumerator for iterating through the dictionary.</returns>
public IEnumerator<KeyValuePair<string, T>> GetEnumerator()
{
return dict.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that can iterate through this collection.
/// </summary>
/// <returns>An enumerator that can iterate through this collection</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return dict.GetEnumerator();
}
/// <summary>
/// Adds an element to the dictionary.
/// </summary>
/// <param name="key">Identity of the key of the new element.</param>
/// <param name="value">The value of the new element.</param>
protected virtual void AddItem(string key, T value)
{
dict.Add(key, value);
}
/// <summary>
/// Removes all elements from the dictionary.
/// </summary>
protected virtual void ClearItems()
{
dict.Clear();
}
/// <summary>
/// Removes the specified element from the dictionary.
/// </summary>
/// <param name="key">Identity of the key of the data pair to be removed.</param>
/// <returns>true if the value is present; false otherwise.</returns>
protected virtual bool RemoveItem(string key)
{
return dict.Remove(key);
}
/// <summary>
/// Modifies the value of an existing element.
/// </summary>
/// <param name="key">Identity of the element to be modified.</param>
/// <param name="value">The value to be set.</param>
protected virtual void SetItem(string key, T value)
{
dict[key] = value;
}
}
}
| 0 | 0.908878 | 1 | 0.908878 | game-dev | MEDIA | 0.194734 | game-dev | 0.891916 | 1 | 0.891916 |
Sandrem/FlyCasual | 2,416 | Assets/Scripts/Model/Content/SecondEdition/Standard/Upgrades/Astromech/R4PAstromech.cs | using Upgrade;
using Ship;
using Movement;
using System;
namespace UpgradesList.SecondEdition
{
public class R4PAstromech : GenericUpgrade
{
public R4PAstromech() : base()
{
UpgradeInfo = new UpgradeCardInfo(
"R4-P Astromech",
UpgradeType.Astromech,
cost: 2,
charges: 2,
abilityType: typeof(Abilities.SecondEdition.R4PAstromechAbility),
restriction: new FactionRestriction(Faction.Republic)
);
ImageUrl = "https://images-cdn.fantasyflightgames.com/filer_public/f2/b0/f2b08b38-29fa-4be1-b96d-c09a5ac4bc7c/swz32_r4-p_astromech.png";
}
}
}
namespace Abilities.SecondEdition
{
//Before you execute a basic maneuver, you may spend 1 charge. If you do, while you execute that maneuver, reduce its difficulty.
public class R4PAstromechAbility : GenericAbility
{
public override void ActivateAbility()
{
HostShip.OnManeuverIsRevealed += RegisterAskChangeManeuver;
}
public override void DeactivateAbility()
{
HostShip.OnManeuverIsRevealed -= RegisterAskChangeManeuver;
}
private void RegisterAskChangeManeuver(GenericShip ship)
{
RegisterAbilityTrigger(TriggerTypes.OnMovementActivationStart, AskAbility);
}
private void AskAbility(object sender, EventArgs e)
{
if (HostShip.AssignedManeuver.IsBasicManeuver && HostUpgrade.State.Charges > 0)
{
AskToUseAbility(
HostUpgrade.UpgradeInfo.Name,
AlwaysUseByDefault,
UseAbility,
descriptionLong: "Do you want to spend 1 Charge to reduce difficulty of your maneuver?",
imageHolder: HostUpgrade
);
}
else
{
Triggers.FinishTrigger();
}
}
private void UseAbility(object sender, EventArgs e)
{
if (HostUpgrade.State.Charges > 0)
{
HostShip.AssignedManeuver.ColorComplexity = GenericMovement.ReduceComplexity(HostShip.AssignedManeuver.ColorComplexity);
HostUpgrade.State.SpendCharge();
}
SubPhases.DecisionSubPhase.ConfirmDecision();
}
}
} | 0 | 0.910387 | 1 | 0.910387 | game-dev | MEDIA | 0.975261 | game-dev | 0.684827 | 1 | 0.684827 |
KaijuEngine/kaiju | 4,717 | src/engine/collision/oobb.go | /******************************************************************************/
/* obb.go */
/******************************************************************************/
/* This file is part of: */
/* KAIJU ENGINE */
/* https://kaijuengine.org */
/******************************************************************************/
/* MIT License */
/* */
/* Copyright (c) 2023-present Kaiju Engine authors (AUTHORS.md). */
/* Copyright (c) 2015-present Brent Farris. */
/* */
/* May all those that this source may reach be blessed by the LORD and find */
/* peace and joy in life. */
/* Everyone who drinks of this water will be thirsty again; but whoever */
/* drinks of the water that I will give him shall never thirst; John 4:13-14 */
/* */
/* 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, blessing, biblical verse, notice and */
/* this permission notice shall be included in all copies or */
/* substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS */
/* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT */
/* OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE */
/* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/******************************************************************************/
package collision
import "kaiju/matrix"
type OOBB struct {
Center matrix.Vec3
Extent matrix.Vec3
Orientation matrix.Mat3
}
func OBBFromAABB(aabb AABB) OOBB {
return OOBB{
Center: aabb.Center,
Extent: aabb.Extent,
Orientation: matrix.Mat3Identity(),
}
}
func (o OOBB) ContainsPoint(point matrix.Vec3) bool {
localPoint := o.Orientation.Transpose().MultiplyVec3(point.Subtract(o.Center))
if matrix.Abs(localPoint.X()) <= o.Extent.X() &&
matrix.Abs(localPoint.Y()) <= o.Extent.Y() &&
matrix.Abs(localPoint.Z()) <= o.Extent.Z() {
return true
}
return false
}
func (o OOBB) Intersect(other OOBB) bool {
axes := make([]matrix.Vec3, 6, 15)
for i := 0; i < 3; i++ {
axes[i] = o.Orientation.ColumnVector(i)
axes[i+3] = other.Orientation.ColumnVector(i)
}
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
cross := matrix.Vec3Cross(o.Orientation.ColumnVector(i), other.Orientation.ColumnVector(j))
if cross.Length() > 1e-6 {
cross.Normalize()
axes = append(axes, cross)
}
}
}
for _, axis := range axes {
min1, max1 := o.projectInterval(axis)
min2, max2 := other.projectInterval(axis)
if !intervalsOverlap(min1, max1, min2, max2) {
return false
}
}
return true
}
func intervalsOverlap(min1, max1, min2, max2 float32) bool {
const epsilon = 1e-6
return max1 >= (min2-epsilon) && max2 >= (min1-epsilon)
}
func (o OOBB) projectInterval(axis matrix.Vec3) (float32, float32) {
p := matrix.Vec3Dot(o.Center, axis)
r := matrix.Abs(matrix.Vec3Dot(o.Orientation.ColumnVector(0), axis))*o.Extent.X() +
matrix.Abs(matrix.Vec3Dot(o.Orientation.ColumnVector(1), axis))*o.Extent.Y() +
matrix.Abs(matrix.Vec3Dot(o.Orientation.ColumnVector(2), axis))*o.Extent.Z()
minProj := p - r
maxProj := p + r
return minProj, maxProj
}
| 0 | 0.8241 | 1 | 0.8241 | game-dev | MEDIA | 0.668928 | game-dev | 0.866221 | 1 | 0.866221 |
CGandGameEngineLearner/IronAngel | 1,436 | Assets/Behavior Designer/Runtime/Tasks/Unity/NavMeshAgent/Move.cs | using UnityEngine;
using UnityEngine.AI;
namespace BehaviorDesigner.Runtime.Tasks.Unity.UnityNavMeshAgent
{
[TaskCategory("Unity/NavMeshAgent")]
[TaskDescription("Apply relative movement to the current position. Returns Success.")]
public class Move : Action
{
[Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")]
public SharedGameObject targetGameObject;
[Tooltip("The relative movement vector")]
public SharedVector3 offset;
// cache the navmeshagent component
private NavMeshAgent navMeshAgent;
private GameObject prevGameObject;
public override void OnStart()
{
var currentGameObject = GetDefaultGameObject(targetGameObject.Value);
if (currentGameObject != prevGameObject) {
navMeshAgent = currentGameObject.GetComponent<NavMeshAgent>();
prevGameObject = currentGameObject;
}
}
public override TaskStatus OnUpdate()
{
if (navMeshAgent == null) {
Debug.LogWarning("NavMeshAgent is null");
return TaskStatus.Failure;
}
navMeshAgent.Move(offset.Value);
return TaskStatus.Success;
}
public override void OnReset()
{
targetGameObject = null;
offset = Vector3.zero;
}
}
} | 0 | 0.808385 | 1 | 0.808385 | game-dev | MEDIA | 0.991603 | game-dev | 0.870713 | 1 | 0.870713 |
peted70/geojsontomesh | 5,814 | Samples/HoloLens/HoloLensMapSample/Assets/HoloToolkit/Input/Scripts/Cursor/AnimatedCursor.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using UnityEngine;
namespace HoloToolkit.Unity.InputModule
{
/// <summary>
/// Animated cursor is a cursor driven using an animator to inject state information
/// and animate accordingly
/// </summary>
public class AnimatedCursor : Cursor
{
/// <summary>
/// Data struct for cursor state information for the Animated Cursor, which leverages the Unity animation system..
/// This defines a modification to an Unity animation parameter, based on cursor state.
/// </summary>
[Serializable]
public struct AnimCursorDatum
{
public string Name;
public CursorStateEnum CursorState;
/// <summary>
/// Types that an animation parameter can have in the Unity animation system.
/// </summary>
public enum AnimInputTypeEnum
{
Int,
Trigger,
Bool,
Float
}
[Tooltip("Type of the animation parameter to modify.")]
public AnimInputTypeEnum AnimInputType;
[Tooltip("Name of the animation parameter to modify.")]
public string AnimParameterName;
[Tooltip("If the animation parameter type is a bool, value to set. Ignored otherwise.")]
public bool AnimBoolValue;
[Tooltip("If the animation parameter type is an int, value to set. Ignored otherwise.")]
public int AnimIntValue;
[Tooltip("If the animation parameter type is a float, value to set. Ignored otherwise.")]
public float AnimFloatValue;
}
/// <summary>
/// Serialized set of cursor state data
/// </summary>
[Header("Animated Cursor State Data")]
[Tooltip("Cursor state data to use for its various states")]
[SerializeField]
public AnimCursorDatum[] CursorStateData;
/// <summary>
/// Enabled state Data when enabling
/// </summary>
[Tooltip("Cursor State Data to use when enabling the cursor")]
public AnimCursorDatum EnableStateData;
/// <summary>
/// Disabled state Data when disabled
/// </summary>
[Tooltip("Cursor State Data to use when the cursor is disabled")]
public AnimCursorDatum DisableStateData;
/// <summary>
/// Link the the cursor animator
/// </summary>
[SerializeField]
[Tooltip("Animator for the cursor")]
protected Animator CursorAnimator = null;
/// <summary>
/// Change anim stage when enabled
/// </summary>
public override void OnInputEnabled()
{
base.OnInputEnabled();
SetCursorState(EnableStateData);
}
/// <summary>
/// Change anim stage when disabled
/// </summary>
public override void OnInputDisabled()
{
base.OnInputDisabled();
SetCursorState(DisableStateData);
}
/// <summary>
/// Override to set the cursor anim trigger
/// </summary>
/// <param name="modifier"></param>
protected override void OnActiveModifier(CursorModifier modifier)
{
base.OnActiveModifier(modifier);
if (modifier != null)
{
if(!string.IsNullOrEmpty(modifier.CursorTriggerName))
{
OnCursorStateChange(CursorStateEnum.Contextual);
CursorAnimator.SetTrigger(modifier.CursorTriggerName);
}
}
else
{
OnCursorStateChange(CursorStateEnum.None);
}
}
/// <summary>
/// Override OnCursorState change to set the correct animation
/// state for the cursor
/// </summary>
/// <param name="state"></param>
public override void OnCursorStateChange(CursorStateEnum state)
{
base.OnCursorStateChange(state);
if(state != CursorStateEnum.Contextual)
{
for(int i = 0; i < CursorStateData.Length; i++)
{
if(CursorStateData[i].CursorState == state)
{
SetCursorState(CursorStateData[i]);
}
}
}
}
/// <summary>
/// Based on the type of animator state info pass it through to the animator
/// </summary>
/// <param name="stateDatum"></param>
private void SetCursorState(AnimCursorDatum stateDatum)
{
// Return if we do not have an animator
if (CursorAnimator == null)
{
return;
}
switch (stateDatum.AnimInputType)
{
case AnimCursorDatum.AnimInputTypeEnum.Bool:
CursorAnimator.SetBool(stateDatum.AnimParameterName, stateDatum.AnimBoolValue);
break;
case AnimCursorDatum.AnimInputTypeEnum.Float:
CursorAnimator.SetFloat(stateDatum.AnimParameterName, stateDatum.AnimFloatValue);
break;
case AnimCursorDatum.AnimInputTypeEnum.Int:
CursorAnimator.SetInteger(stateDatum.AnimParameterName, stateDatum.AnimIntValue);
break;
case AnimCursorDatum.AnimInputTypeEnum.Trigger:
CursorAnimator.SetTrigger(stateDatum.AnimParameterName);
break;
}
}
}
} | 0 | 0.875397 | 1 | 0.875397 | game-dev | MEDIA | 0.795314 | game-dev | 0.604918 | 1 | 0.604918 |
GreenJAB/fixed-minecraft | 1,365 | src/main/java/net/greenjab/fixedminecraft/mixin/structure/OreFeatureMixin.java | package net.greenjab.fixedminecraft.mixin.structure;
import com.llamalad7.mixinextras.injector.ModifyExpressionValue;
import com.llamalad7.mixinextras.sugar.Local;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.registry.tag.BlockTags;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.gen.feature.OreFeature;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import java.util.function.Function;
import static net.minecraft.world.gen.feature.Feature.isExposedToAir;
@Mixin(OreFeature.class)
public abstract class OreFeatureMixin {
@ModifyExpressionValue(method = "shouldPlace", at = @At(
value = "INVOKE",
target = "Lnet/minecraft/structure/rule/RuleTest;test(Lnet/minecraft/block/BlockState;Lnet/minecraft/util/math/random/Random;)Z"
))
private static boolean genInTerracotta(boolean original, @Local(argsOnly = true) BlockState blockState, @Local(argsOnly = true) Function<BlockPos, BlockState> posToState, @Local(
argsOnly = true
) BlockPos.Mutable pos) {
if (blockState.isIn(BlockTags.TERRACOTTA) || blockState == Blocks.SANDSTONE.getDefaultState()) {
if (!isExposedToAir(posToState, pos)) {
return true;
}
}
return original;
}
}
| 0 | 0.815988 | 1 | 0.815988 | game-dev | MEDIA | 0.999334 | game-dev | 0.866063 | 1 | 0.866063 |
Sixze/ALS-Refactored | 1,208 | Source/ALS/Public/State/AlsSpineState.h | #pragma once
#include "AlsSpineState.generated.h"
USTRUCT(BlueprintType)
struct ALS_API FAlsSpineState
{
GENERATED_BODY()
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ALS")
uint8 bSpineRotationAllowed : 1 {false};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ALS", Meta = (ClampMin = 0, ClampMax = 1))
float SpineAmount{0.0f};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ALS", Meta = (ClampMin = 0, ForceUnits = "x"))
float SpineAmountScale{1.0f};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ALS")
float SpineAmountBias{0.0f};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ALS", Meta = (ClampMin = -180, ClampMax = 180, ForceUnits = "deg"))
float LastYawAngle{0.0f};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ALS", Meta = (ClampMin = -180, ClampMax = 180, ForceUnits = "deg"))
float CurrentYawAngle{0.0f};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ALS", Meta = (ClampMin = -180, ClampMax = 180, ForceUnits = "deg"))
float YawAngle{0.0f};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ALS", Meta = (ClampMin = -180, ClampMax = 180, ForceUnits = "deg"))
float LastActorYawAngle{0.0f};
};
| 0 | 0.690043 | 1 | 0.690043 | game-dev | MEDIA | 0.955279 | game-dev | 0.680741 | 1 | 0.680741 |
tvbarthel/ChaseWhisplyProject | 6,722 | ChaseWhisply/src/main/java/fr/tvbarthel/games/chasewhisply/model/TargetableItem.java | package fr.tvbarthel.games.chasewhisply.model;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
public class TargetableItem extends DisplayableItem {
//health of the item
protected int mHealth;
protected int mBasePoint;
protected int mExpPoint;
protected ArrayList<Integer> mDrop;
public TargetableItem() {
super();
mBasePoint = 1;
mHealth = 1;
mExpPoint = 0;
mDrop = new ArrayList<Integer>();
}
public TargetableItem(int x, int y, int type) {
super(x, y, type);
mBasePoint = 1;
mHealth = 1;
mExpPoint = 0;
mDrop = new ArrayList<Integer>();
}
protected TargetableItem(Parcel in) {
super(in);
}
/**
* Hit the item with damage
*
* @param damage
*/
public void hit(int damage) {
mHealth = Math.max(0, mHealth - damage);
}
@Override
public void writeToParcel(Parcel out, int i) {
super.writeToParcel(out, i);
out.writeInt(mHealth);
out.writeInt(mBasePoint);
out.writeInt(mExpPoint);
out.writeList(mDrop);
}
@Override
public void readFromParcel(Parcel in) {
super.readFromParcel(in);
mHealth = in.readInt();
mBasePoint = in.readInt();
mExpPoint = in.readInt();
mDrop = new ArrayList<Integer>();
in.readList(mDrop, Integer.class.getClassLoader());
}
public static final Parcelable.Creator<TargetableItem> CREATOR = new Parcelable.Creator<TargetableItem>() {
public TargetableItem createFromParcel(Parcel in) {
return new TargetableItem(in);
}
public TargetableItem[] newArray(int size) {
return new TargetableItem[size];
}
};
/**
* used to know if this targetable is alive
*
* @return true if alive
*/
public boolean isAlive() {
if (mHealth == 0) return false;
return true;
}
/**
* Getters and Setters
*/
public int getHealth() {
return mHealth;
}
public void setHealth(int health) {
mHealth = health;
}
public int getBasePoint() {
return mBasePoint;
}
public void setBasePoint(int basePoint) {
mBasePoint = basePoint;
}
public void setExpPoint(int expPoint) {
mExpPoint = expPoint;
}
public int getExpPoint() {
return mExpPoint;
}
public ArrayList<Integer> getDrop() {
return mDrop;
}
public void setDrop(ArrayList<Integer> drop) {
mDrop = drop;
}
public static int randomGhostTypeEasy() {
final int randomDraw = MathUtils.randomize(0, 100);
if (randomDraw < 40) {
//40%
return DisplayableItemFactory.TYPE_EASY_GHOST;
} else if (randomDraw < 80) {
//40%
return DisplayableItemFactory.TYPE_HIDDEN_GHOST;
} else if (randomDraw < 99) {
//19%
return DisplayableItemFactory.TYPE_BLOND_GHOST;
} else {
//1%
return DisplayableItemFactory.TYPE_KING_GHOST;
}
}
public static int randomGhostType() {
final int randomDraw = MathUtils.randomize(0, 100);
if (randomDraw < 40) {
//40%
return DisplayableItemFactory.TYPE_EASY_GHOST;
} else if (randomDraw < 60) {
//20%
return DisplayableItemFactory.TYPE_HIDDEN_GHOST;
} else if (randomDraw < 75) {
//15%
return DisplayableItemFactory.TYPE_BLOND_GHOST;
} else if (randomDraw < 90) {
//15%
return DisplayableItemFactory.TYPE_BABY_GHOST;
} else if (randomDraw < 99) {
//9%
return DisplayableItemFactory.TYPE_GHOST_WITH_HELMET;
} else {
//1%
return DisplayableItemFactory.TYPE_KING_GHOST;
}
}
public static int randomGhostTypeHard() {
final int randomDraw = MathUtils.randomize(0, 100);
if (randomDraw < 10) {
//10%
return DisplayableItemFactory.TYPE_EASY_GHOST;
} else if (randomDraw < 20) {
//15%
return DisplayableItemFactory.TYPE_HIDDEN_GHOST;
} else if (randomDraw < 50) {
//25%
return DisplayableItemFactory.TYPE_BLOND_GHOST;
} else if (randomDraw < 80) {
//30%
return DisplayableItemFactory.TYPE_BABY_GHOST;
} else if (randomDraw < 99) {
//19%
return DisplayableItemFactory.TYPE_GHOST_WITH_HELMET;
} else {
//1%
return DisplayableItemFactory.TYPE_KING_GHOST;
}
}
public static int randomGhostTypeHarder() {
final int randomDraw = MathUtils.randomize(0, 100);
if (randomDraw < 10) {
//10%
return DisplayableItemFactory.TYPE_EASY_GHOST;
} else if (randomDraw < 25) {
//15%
return DisplayableItemFactory.TYPE_HIDDEN_GHOST;
} else if (randomDraw < 40) {
//20%
return DisplayableItemFactory.TYPE_BLOND_GHOST;
} else if (randomDraw < 70) {
//25%
return DisplayableItemFactory.TYPE_BABY_GHOST;
} else if (randomDraw < 99) {
//29%
return DisplayableItemFactory.TYPE_GHOST_WITH_HELMET;
} else {
//1%
return DisplayableItemFactory.TYPE_KING_GHOST;
}
}
public static int randomGhostTypeHardest() {
final int randomDraw = MathUtils.randomize(0, 100);
if (randomDraw < 19) {
//19%
return DisplayableItemFactory.TYPE_BLOND_GHOST;
} else if (randomDraw < 59) {
//40%
return DisplayableItemFactory.TYPE_BABY_GHOST;
} else if (randomDraw < 99) {
//40%
return DisplayableItemFactory.TYPE_GHOST_WITH_HELMET;
} else {
//1%
return DisplayableItemFactory.TYPE_KING_GHOST;
}
}
/**
* spawn rules for all mobs exept king
*
* @return
*/
public static int randomGhostTypeWithoutKing() {
final int randomDraw = MathUtils.randomize(0, 100);
if (randomDraw < 60) {
return DisplayableItemFactory.TYPE_EASY_GHOST;
} else if (randomDraw < 75) {
return DisplayableItemFactory.TYPE_HIDDEN_GHOST;
} else if (randomDraw < 90) {
return DisplayableItemFactory.TYPE_BABY_GHOST;
} else {
return DisplayableItemFactory.TYPE_GHOST_WITH_HELMET;
}
}
}
| 0 | 0.599213 | 1 | 0.599213 | game-dev | MEDIA | 0.854932 | game-dev | 0.829166 | 1 | 0.829166 |
exmex/UnityMoba | 3,864 | Assets/Lua/Logic/M021/PVPBattleLoading/PVPBattleLoadingCtrl.lua | --author zx
require "System.Global"
require "Logic.UTGData.UTGData"
--require "Logic.UTGData.UTGDataTemporary"
class("PVPBattleLoadingCtrl")
local json = require "cjson"
function PVPBattleLoadingCtrl:Awake(this)
self.this = this
self.ownPlayerId = UTGData.Instance().PlayerData.Id
self.teamAGrid = this.transforms[0]
self.teamBGrid = this.transforms[1]
self.sceneName = ""
self.teamAData = {}
self.teamBData = {}
end
function PVPBattleLoadingCtrl:Start()
self:Init()
end
function PVPBattleLoadingCtrl:Init()
self.teamAData = PVPBattleLoadingAPI_1.Instance.TeamAData.Members
self.teamBData = PVPBattleLoadingAPI_1.Instance.TeamBData.Members
self:FilterTeamData(self.teamAData)
self:FilterTeamData(self.teamBData)
self:FillRoleLis(self.teamAGrid,self.teamAData)
self:FillRoleLis(self.teamBGrid,self.teamBData)
end
function PVPBattleLoadingCtrl:FilterTeamData(data)
for i=#data, 1, -1 do
if data[i].PlayerId ==0 and data[i].IsAi == false then
--Debugger.LogError("ffffffffffffffffff "..i)
table.remove(data,i)
end
end
end
--更新玩家进度
function PVPBattleLoadingCtrl:UpdatePlayerProgress(playerId,progress)
--Debugger.LogError("playerId "..playerId.." progress "..progress)
--刷新
for i=1,self.teamAGrid.childCount do
local temp = self.teamAGrid:GetChild(i-1)
if temp.name == playerId then
temp:FindChild("progress"):GetComponent("UnityEngine.UI.Text").text = (progress.."%")
end
end
for i=1,self.teamBGrid.childCount do
local temp = self.teamBGrid:GetChild(i-1)
if temp.name == playerId then
temp:FindChild("progress"):GetComponent("UnityEngine.UI.Text").text = (progress.."%")
end
end
end
--生成列表
function PVPBattleLoadingCtrl:FillRoleLis(grid,data)
local api = grid:GetComponent("NTGLuaScript").self
if data==nil then
api:ResetItemsSimple(0)
Debugger.LogError("没有玩家数据")
return
end
api:ResetItemsSimple(#data)
for i=1,#api.itemList do
local tempo = api.itemList[i].transform
tempo.name = tostring(data[i].PlayerId)
--召唤师技能
if data[i].IsAi then
tempo:FindChild("playerskill").gameObject:SetActive(false)
else
tempo:FindChild("playerskill").gameObject:SetActive(true)
tempo:FindChild("playerskill/icon"):GetComponent("UnityEngine.UI.Image").sprite = NTGResourceController.Instance:LoadAsset("playerskillicon",tostring(data[i].PlayerSkill.Icon),"UnityEngine.Sprite")
end
--role图片
local roleIcon = data[i].Role.Skin.Portrait
tempo:FindChild("mask/icon"):GetComponent("UnityEngine.UI.Image").sprite = NTGResourceController.Instance:LoadAsset("portrait",tostring(roleIcon),"UnityEngine.Sprite")
--玩家名称
if self.ownPlayerId == data[i].PlayerId then
self.ownPlayerObj = tempo
tempo:FindChild("playername_own"):GetComponent("UnityEngine.UI.Text").text = tostring(data[i].PlayerName)
else
tempo:FindChild("playername"):GetComponent("UnityEngine.UI.Text").text = tostring(data[i].PlayerName)
end
--if data[i].IsAi then tempo:FindChild("playername"):GetComponent("UnityEngine.UI.Text").text = "电脑" end
--role 名称
tempo:FindChild("rolename"):GetComponent("UnityEngine.UI.Text").text = tostring(data[i].Role.Name)
--role熟练度
if data[i].IsAi then
tempo:FindChild("pro").gameObject:SetActive(false)
else
tempo:FindChild("pro").gameObject:SetActive(true)
local proIcon = data[i].Role.Proficiency.Icon
tempo:FindChild("pro"):GetComponent("UnityEngine.UI.Image").sprite = NTGResourceController.Instance:LoadAsset("pvpbattleloading",tostring(proIcon),"UnityEngine.Sprite")
end
--进度
tempo:FindChild("progress"):GetComponent("UnityEngine.UI.Text").text = data[i].PreProgress.."%"
end
end
function PVPBattleLoadingCtrl:OnDestroy()
self.this = nil
self = nil
end | 0 | 0.861745 | 1 | 0.861745 | game-dev | MEDIA | 0.981602 | game-dev | 0.959747 | 1 | 0.959747 |
ClearSkyTeam/ClearSky | 2,445 | src/pocketmine/entity/Arrow.php | <?php
namespace pocketmine\entity;
use pocketmine\item\Potion;
use pocketmine\level\format\FullChunk;
use pocketmine\level\particle\CriticalParticle;
use pocketmine\level\particle\MobSpellParticle;
use pocketmine\nbt\tag\CompoundTag;
use pocketmine\nbt\tag\ShortTag;
use pocketmine\network\protocol\AddEntityPacket;
use pocketmine\Player;
class Arrow extends Projectile{
const NETWORK_ID = 80;
public $width = 0.5;
public $length = 0.5;
public $height = 0.5;
protected $gravity = 0.05;
protected $drag = 0.01;
protected $damage = 2;
protected $isCritical;
protected $potionId;
public function __construct(FullChunk $chunk, CompoundTag $nbt, Entity $shootingEntity = null, $critical = false){
$this->isCritical = (bool) $critical;
if(!isset($nbt->Potion)){
$nbt->Potion = new ShortTag("Potion", 0);
}
parent::__construct($chunk, $nbt, $shootingEntity);
$this->potionId = $this->namedtag["Potion"];
}
public function getPotionId(){
return $this->potionId;
}
public function onUpdate($currentTick){
if($this->closed){
return false;
}
$this->timings->startTiming();
$hasUpdate = parent::onUpdate($currentTick);
if(!$this->hadCollision and $this->isCritical){
$this->level->addParticle(new CriticalParticle($this->add(
$this->width / 2 + mt_rand(-100, 100) / 500,
$this->height / 2 + mt_rand(-100, 100) / 500,
$this->width / 2 + mt_rand(-100, 100) / 500)));
}elseif($this->onGround){
$this->isCritical = false;
}
if($this->potionId != 0){
if(!$this->onGround or ($this->onGround and ($currentTick % 4) == 0)){
$color = Potion::getColor($this->potionId - 1);
$this->level->addParticle(new MobSpellParticle($this->add(
$this->width / 2 + mt_rand(-100, 100) / 500,
$this->height / 2 + mt_rand(-100, 100) / 500,
$this->width / 2 + mt_rand(-100, 100) / 500), $color[0], $color[1], $color[2]));
}
$hasUpdate = true;
}
if($this->age > 1200){
$this->kill();
$hasUpdate = true;
}
$this->timings->stopTiming();
return $hasUpdate;
}
public function spawnTo(Player $player){
$pk = new AddEntityPacket();
$pk->type = Arrow::NETWORK_ID;
$pk->eid = $this->getId();
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->speedX = $this->motionX;
$pk->speedY = $this->motionY;
$pk->speedZ = $this->motionZ;
$pk->metadata = $this->dataProperties;
$player->dataPacket($pk);
parent::spawnTo($player);
}
} | 0 | 0.947221 | 1 | 0.947221 | game-dev | MEDIA | 0.981835 | game-dev | 0.978982 | 1 | 0.978982 |
MergHQ/CRYENGINE | 37,049 | Code/CryEngine/CryAnimation/AnimationManager.cpp | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
#include "stdafx.h"
#include "AnimationManager.h"
#include "LoaderTCB.h"
#include "ModelAnimationSet.h"
#include "LoaderCGA.h"
#include "LoaderDBA.h"
#include <CryCore/StlUtils.h>
#include "ControllerPQ.h"
#include "ControllerOpt.h"
#include "ParametricSampler.h"
#include "CharacterManager.h"
#include "Model.h"
#include <CryString/StringUtils.h>
#include <CryString/CryPath.h>
int CAnimationManager::GetGlobalIDbyFilePath_CAF(const char* szAnimFileName) const
{
const int id = m_AnimationMapCAF.GetValue(szAnimFileName);
if (id >= 0)
{
assert(size_t(id) < m_arrGlobalCAF.size());
assert(!stricmp(m_arrGlobalCAF[id].GetFilePath(), szAnimFileName));
return id;
}
return -1;
}
int CAnimationManager::GetGlobalIDbyFilePath_AIM(const char* szAnimFilePath) const
{
const uint32 crc32 = CCrc32::ComputeLowercase(szAnimFilePath);
const uint32 numAIM = m_arrGlobalAIM.size();
for (uint32 id = 0; id < numAIM; ++id)
{
if (m_arrGlobalAIM[id].GetFilePathCRC32() == crc32)
{
assert(!stricmp(m_arrGlobalAIM[id].GetFilePath(), szAnimFilePath));
return id;
}
}
return -1;
}
int CAnimationManager::GetGlobalIDbyFilePath_LMG(const char* szAnimFilePath) const
{
const int id = GetGlobalIDbyFilePathCRC_LMG(CCrc32::ComputeLowercase(szAnimFilePath));
assert(id == -1 || stricmp(m_arrGlobalLMG[id].GetFilePath(), szAnimFilePath) == 0);
return id;
}
int CAnimationManager::GetGlobalIDbyFilePathCRC_LMG(uint32 crc32) const
{
const uint32 numLMG = m_arrGlobalLMG.size();
for (uint32 id = 0; id < numLMG; ++id)
{
if (m_arrGlobalLMG[id].GetFilePathCRC32() == crc32)
{
return id;
}
}
return -1;
}
////////////////////////////////////////////////////////////////////////////////////
// loads the animation with the specified name; if the animation is already loaded,
// then just returns its id
// The caller MUST TAKE CARE to bind the animation if it's already loaded before it has registered itself within this manager
// RETURNS:
// The global animation id.
// -1 if the animation couldn't be loaded
// SIDE EFFECT NOTES:
// This function does not put up a warning in the case the file was not found.
// The caller must do so.
int CAnimationManager::CreateGAH_CAF(const string& strFilePath)
{
int nGlobalAnimId = GetGlobalIDbyFilePath_CAF(strFilePath);
if (nGlobalAnimId < 0)
{
nGlobalAnimId = int32(m_arrGlobalCAF.size());
// add a new animation structure that will hold the info about the new animation.
// the new animation id is the index of this structure in the array
m_arrGlobalCAF.push_back();
m_arrGlobalCAF[nGlobalAnimId] = GlobalAnimationHeaderCAF();
m_arrGlobalCAF[nGlobalAnimId].SetFilePath(strFilePath);
m_animSearchHelper.AddAnimation(strFilePath, nGlobalAnimId);
m_AnimationMapCAF.InsertValue(m_arrGlobalCAF[nGlobalAnimId].GetFilePathCRC32(), nGlobalAnimId);
}
return nGlobalAnimId;
}
int CAnimationManager::CreateGAH_AIM(const string& strFilePath)
{
int nGlobalAnimId = GetGlobalIDbyFilePath_AIM(strFilePath);
if (nGlobalAnimId < 0)
{
nGlobalAnimId = int32(m_arrGlobalAIM.size());
// add a new animation structure that will hold the info about the new animation.
// the new animation id is the index of this structure in the array
m_arrGlobalAIM.push_back(GlobalAnimationHeaderAIM());
m_arrGlobalAIM[nGlobalAnimId].SetFilePath(strFilePath);
// m_AnimationMapAIM.InsertValue(m_arrGlobalAIM[nGlobalAnimId].GetFilePathCRC32(), nGlobalAnimId);
}
return nGlobalAnimId;
}
int CAnimationManager::CreateGAH_LMG(const string& strFilePath)
{
int nGlobalAnimId = GetGlobalIDbyFilePath_LMG(strFilePath);
if (nGlobalAnimId < 0)
{
nGlobalAnimId = int32(m_arrGlobalLMG.size());
// add a new animation structure that will hold the info about the new animation.
// the new animation id is the index of this structure in the array
m_arrGlobalLMG.push_back(GlobalAnimationHeaderLMG());
m_arrGlobalLMG[nGlobalAnimId].SetFilePath(strFilePath);
// m_AnimationMapLMG.InsertValue(m_arrGlobalLMG[nGlobalAnimId].GetFilePathCRC32(), nGlobalAnimId);
}
return nGlobalAnimId;
}
CGlobalHeaderDBA* CAnimationManager::FindGlobalHeaderByCRC_DBA(uint32 crc)
{
for (size_t i = 0, c = m_arrGlobalHeaderDBA.size(); i != c; ++i)
{
if (m_arrGlobalHeaderDBA[i].m_FilePathDBACRC32 == crc)
return &m_arrGlobalHeaderDBA[i];
}
return NULL;
}
bool CAnimationManager::LoadAnimationTCB(int nAnimId, DynArray<CControllerTCB>& arrNodeAnims, CryCGALoader* pCGA, const IDefaultSkeleton* pIDefaultSkeleton)
{
if (pIDefaultSkeleton == 0)
return 0;
const CDefaultSkeleton* pDefaultSkeleton = (const CDefaultSkeleton*)pIDefaultSkeleton;
LOADING_TIME_PROFILE_SECTION(g_pISystem);
GlobalAnimationHeaderCAF& rGlobalAnim = m_arrGlobalCAF[nAnimId];
int32 nStartKey = pCGA->m_start;
int32 nEndKey = pCGA->m_end;
rGlobalAnim.m_fStartSec = nStartKey / ANIMATION_30Hz;
rGlobalAnim.m_fEndSec = nEndKey / ANIMATION_30Hz;
if (rGlobalAnim.m_fEndSec <= rGlobalAnim.m_fStartSec)
rGlobalAnim.m_fEndSec = rGlobalAnim.m_fStartSec;
rGlobalAnim.m_fTotalDuration = rGlobalAnim.m_fEndSec - rGlobalAnim.m_fStartSec;
uint32 numCtrl = rGlobalAnim.m_nControllers;
assert(numCtrl == 0);
if (numCtrl)
return true;
uint32 numController = 0;
uint32 numAnimSize = arrNodeAnims.size();
for (uint32 i = 0; i < numAnimSize; i++)
{
uint32 numPos = arrNodeAnims[i].m_posTrack.num_keys();
uint32 numRot = arrNodeAnims[i].m_rotTrack.num_keys();
uint32 numScl = arrNodeAnims[i].m_sclTrack.num_keys();
if (numPos + numRot + numScl)
numController++;
}
rGlobalAnim.m_arrController.resize(numController);
rGlobalAnim.m_nControllers = numController;
rGlobalAnim.m_nControllers2 = numController;
for (uint32 i = 0, j = 0; i < numAnimSize; i++)
{
uint32 numPos = arrNodeAnims[i].m_posTrack.num_keys();
uint32 numRot = arrNodeAnims[i].m_rotTrack.num_keys();
uint32 numScl = arrNodeAnims[i].m_sclTrack.num_keys();
if (numPos + numRot + numScl)
{
CControllerTCB* pControllerTCB = new CControllerTCB();
*pControllerTCB = arrNodeAnims[i];
pControllerTCB->m_nControllerId = pDefaultSkeleton->m_arrModelJoints[i].m_nJointCRC32;
IController* pController = (IController*)pControllerTCB;
PREFAST_SUPPRESS_WARNING(6386)
rGlobalAnim.m_arrController[j] = static_cast<IController*>(pController);
++j;
}
}
std::sort(rGlobalAnim.m_arrController.begin(), rGlobalAnim.m_arrController.end(), AnimCtrlSortPred());
rGlobalAnim.InitControllerLookup(numController);
rGlobalAnim.OnAssetCreated();
rGlobalAnim.m_nFlags |= CA_ASSET_TCB;
return true;
}
// notifies the controller manager that this client doesn't use the given animation any more.
// these calls must be balanced with AnimationAddRef() calls
void CAnimationManager::AnimationReleaseCAF(GlobalAnimationHeaderCAF& rCAF)
{
int32 RefCount = rCAF.m_nRef_by_Model;
if (RefCount == 0)
rCAF.Release();
}
void CAnimationManager::AnimationReleaseAIM(GlobalAnimationHeaderAIM& rAIM)
{
int32 RefCount = rAIM.m_nRef_by_Model;
if (RefCount == 0)
rAIM.Release();
}
void CAnimationManager::AnimationReleaseLMG(GlobalAnimationHeaderLMG& rLMG)
{
int32 RefCount = rLMG.m_nRef_by_Model;
if (RefCount == 0)
rLMG.Release();
}
//////////////////////////////////////////////////////////////////////////
IAnimEventList* CAnimationManager::GetAnimEventList(const char* animationFilePath)
{
const CAnimationManager* cThis = this;
const IAnimEventList* pAnimEventArray = cThis->GetAnimEventList(animationFilePath);
return const_cast<IAnimEventList*>(pAnimEventArray);
}
const IAnimEventList* CAnimationManager::GetAnimEventList(const char* animationFilePath) const
{
const int32 globalCafId = GetGlobalIDbyFilePath_CAF(animationFilePath);
if (0 <= globalCafId)
{
assert(globalCafId < (int32)(m_arrGlobalCAF.size()));
return &m_arrGlobalCAF[globalCafId].m_AnimEventsCAF;
}
const int32 globalLmgId = GetGlobalIDbyFilePath_LMG(animationFilePath);
if (0 <= globalLmgId)
{
assert(globalLmgId < (int32)(m_arrGlobalLMG.size()));
return &m_arrGlobalLMG[globalLmgId].m_AnimEventsLMG;
}
return NULL;
}
bool CAnimationManager::SaveAnimEventToXml(const CAnimEventData& dataIn, XmlNodeRef& dataOut)
{
if (!dataOut)
return false;
dataOut->setTag("event");
dataOut->setAttr("name", dataIn.GetName());
dataOut->setAttr("time", dataIn.GetNormalizedTime());
dataOut->setAttr("endTime", dataIn.GetNormalizedEndTime());
dataOut->setAttr("parameter", dataIn.GetCustomParameter());
dataOut->setAttr("bone", dataIn.GetBoneName());
dataOut->setAttr("offset", dataIn.GetOffset());
dataOut->setAttr("dir", dataIn.GetDirection());
dataOut->setAttr("model", dataIn.GetModelName());
return true;
}
bool CAnimationManager::LoadAnimEventFromXml(const XmlNodeRef& dataIn, CAnimEventData& dataOut)
{
if (!dataIn)
return false;
if (stack_string("event") != dataIn->getTag())
return false;
XmlString sEventName;
if (!(sEventName = dataIn->getAttr("name")))
sEventName = "__unnamed__";
float fTime = 0.f;
dataIn->getAttr("time", fTime);
float endTime = fTime;
dataIn->getAttr("endTime", endTime);
XmlString sParameter;
sParameter = dataIn->getAttr("parameter");
XmlString sBoneName;
sBoneName = dataIn->getAttr("bone");
Vec3 vOffset(0, 0, 0);
dataIn->getAttr("offset", vOffset);
Vec3 vDir(0, 0, 0);
dataIn->getAttr("dir", vDir);
XmlString sModel;
sModel = dataIn->getAttr("model");
dataOut.SetName(sEventName);
dataOut.SetNormalizedTime(fTime);
dataOut.SetNormalizedEndTime(endTime);
dataOut.SetCustomParameter(sParameter);
dataOut.SetBoneName(sBoneName);
dataOut.SetOffset(vOffset);
dataOut.SetDirection(vDir);
dataOut.SetModelName(sModel);
return true;
}
void CAnimationManager::InitializeSegmentationDataFromAnimEvents(const char* animationFilePath)
{
const int32 globalCafId = GetGlobalIDbyFilePath_CAF(animationFilePath);
if (globalCafId < 0)
return;
static const uint32 s_crc32_segment1 = CCrc32::ComputeLowercase("segment1");
static const uint32 s_crc32_segment2 = CCrc32::ComputeLowercase("segment2");
static const uint32 s_crc32_segment3 = CCrc32::ComputeLowercase("segment3");
GlobalAnimationHeaderCAF& cafHeader = m_arrGlobalCAF[globalCafId];
cafHeader.m_Segments = 1;
const IAnimEventList& animEvents = cafHeader.m_AnimEventsCAF;
const uint32 animEventCount = animEvents.GetCount();
for (uint32 i = 0; i < animEventCount; ++i)
{
const CAnimEventData& animEvent = animEvents.GetByIndex(i);
const uint32 eventNameCRC32 = animEvent.GetNameLowercaseCRC32();
float normalizedTime = animEvent.GetNormalizedTime();
uint32 ind = -1;
if (eventNameCRC32 == s_crc32_segment1)
{
ind = 1;
}
else if (eventNameCRC32 == s_crc32_segment2)
{
ind = 2;
}
else if (eventNameCRC32 == s_crc32_segment3)
{
ind = 3;
}
if (ind != -1)
{
cafHeader.m_SegmentsTime[ind] = normalizedTime;
++cafHeader.m_Segments;
}
}
}
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
bool CAnimationManager::CreateGlobalHeaderDBA(DynArray<string>& arrFilePathDBA)
{
uint32 numDBAs = arrFilePathDBA.size();
for (size_t d = 0; d < numDBAs; d++)
{
const char* pFilePathDBA = arrFilePathDBA[d];
uint32 numHeaders = m_arrGlobalHeaderDBA.size();
uint32 exits = 0;
for (uint32 dba = 0; dba < numHeaders; dba++)
{
const char* pname = m_arrGlobalHeaderDBA[dba].m_strFilePathDBA;
int32 same = stricmp(pname, pFilePathDBA);
if (same == 0)
{
exits = 1;
break;
}
}
if (exits == 0)
{
//create GloablHeaderDBA and load data
CGlobalHeaderDBA HeaderDBA;
HeaderDBA.CreateDatabaseDBA(pFilePathDBA);
m_arrGlobalHeaderDBA.push_back(HeaderDBA);
}
}
return 0;
}
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
bool CAnimationManager::DBA_PreLoad(const char* pFilePathDBA, bool highPriority)
{
stack_string strPath = pFilePathDBA;
CryStringUtils::UnifyFilePath(strPath);
uint32 numHeaders = m_arrGlobalHeaderDBA.size();
for (uint32 dba = 0; dba < numHeaders; dba++)
{
const char* pname = m_arrGlobalHeaderDBA[dba].m_strFilePathDBA;
int32 same = stricmp(pname, strPath.c_str());
if (same == 0)
{
if (Console::GetInst().ca_UseIMG_CAF)
m_arrGlobalHeaderDBA[dba].StartStreamingDBA(highPriority);
else
m_arrGlobalHeaderDBA[dba].LoadDatabaseDBA("");
return 1;
}
}
//create GloablHeaderDBA and load data
CGlobalHeaderDBA HeaderDBA;
HeaderDBA.CreateDatabaseDBA(strPath.c_str());
m_arrGlobalHeaderDBA.push_back(HeaderDBA);
uint32 lastDBA = m_arrGlobalHeaderDBA.size() - 1;
if (Console::GetInst().ca_UseIMG_CAF)
m_arrGlobalHeaderDBA[lastDBA].StartStreamingDBA(highPriority);
else
m_arrGlobalHeaderDBA[lastDBA].LoadDatabaseDBA("");
return 0;
}
bool CAnimationManager::DBA_LockStatus(const char* pFilePathDBA, uint32 status, bool highPriority)
{
stack_string strPath = pFilePathDBA;
CryStringUtils::UnifyFilePath(strPath);
uint32 numHeaders = m_arrGlobalHeaderDBA.size();
for (uint32 dba = 0; dba < numHeaders; dba++)
{
const char* pname = m_arrGlobalHeaderDBA[dba].m_strFilePathDBA;
int32 same = stricmp(pname, strPath.c_str());
if (same == 0)
{
m_arrGlobalHeaderDBA[dba].m_bDBALock = status;
if (status)
{
if (Console::GetInst().ca_UseIMG_CAF)
m_arrGlobalHeaderDBA[dba].StartStreamingDBA(highPriority);
else
m_arrGlobalHeaderDBA[dba].LoadDatabaseDBA("");
}
return 1;
}
}
return 0;
}
bool CAnimationManager::DBA_Unload(const char* pFilePathDBA)
{
stack_string strPath = pFilePathDBA;
CryStringUtils::UnifyFilePath(strPath);
uint32 numHeadersDBA = m_arrGlobalHeaderDBA.size();
if (numHeadersDBA == 0)
return 1;
CGlobalHeaderDBA* parrGlobalDBA = &m_arrGlobalHeaderDBA[0];
for (uint32 d = 0; d < numHeadersDBA; d++)
parrGlobalDBA[d].m_nUsedAnimations = 0;
uint32 numHeadersCAF = m_arrGlobalCAF.size();
if (numHeadersCAF)
{
GlobalAnimationHeaderCAF* parrGlobalCAF = &m_arrGlobalCAF[0];
for (uint32 i = 0; i < numHeadersCAF; i++)
{
if (parrGlobalCAF[i].m_nRef_at_Runtime == 0)
continue;
uint32 nCRC32 = parrGlobalCAF[i].m_FilePathDBACRC32;
if (nCRC32)
{
for (uint32 d = 0; d < numHeadersDBA; d++)
{
if (nCRC32 == parrGlobalDBA[d].m_FilePathDBACRC32)
{
parrGlobalDBA[d].m_nUsedAnimations++;
parrGlobalDBA[d].m_nLastUsedTimeDelta = 0;
}
}
}
}
}
for (uint32 dba = 0; dba < numHeadersDBA; dba++)
{
const char* pname = m_arrGlobalHeaderDBA[dba].m_strFilePathDBA;
int32 same = stricmp(pname, strPath.c_str());
if (same == 0)
{
m_arrGlobalHeaderDBA[dba].m_bDBALock = 0;
if (m_arrGlobalHeaderDBA[dba].m_pDatabaseInfo == 0)
return 1;
if (m_arrGlobalHeaderDBA[dba].m_nUsedAnimations)
{
//CryFatalError("CryAnimation: Animations still in use. Can't delete DBA: %s",m_arrGlobalHeaderDBA[dba].m_strFilePathDBA.c_str() );
continue;
}
m_arrGlobalHeaderDBA[dba].DeleteDatabaseDBA();
return 1;
}
}
return 0;
}
void CAnimationManager::InitialiseRunTimePools()
{
const int numParametrics = Console::GetInst().ca_ParametricPoolSize;
if (numParametrics != g_totalParametrics)
{
delete[] g_parametricPool;
delete[] g_usedParametrics;
g_parametricPool = new SParametricSamplerInternal[numParametrics];
g_usedParametrics = new bool[numParametrics];
g_totalParametrics = numParametrics;
}
memset(g_usedParametrics, 0, numParametrics);
}
void CAnimationManager::DestroyRunTimePools()
{
delete[] g_parametricPool;
delete[] g_usedParametrics;
g_parametricPool = NULL;
g_usedParametrics = NULL;
g_totalParametrics = 0;
}
bool CAnimationManager::Unload_All_Animation()
{
uint32 numHeadersCAF = m_arrGlobalCAF.size();
if (numHeadersCAF)
{
//remove all CAFs
GlobalAnimationHeaderCAF* parrGlobalCAF = &m_arrGlobalCAF[0];
for (uint32 i = 0; i < numHeadersCAF; i++)
{
parrGlobalCAF[i].m_nRef_at_Runtime = 0;
uint32 nCRC32 = parrGlobalCAF[i].m_FilePathDBACRC32;
if (nCRC32 == 0 || nCRC32 == -1)
parrGlobalCAF[i].ClearControllers();
}
}
uint32 numHeadersDBA = m_arrGlobalHeaderDBA.size();
for (uint32 dba = 0; dba < numHeadersDBA; dba++)
{
m_arrGlobalHeaderDBA[dba].m_nUsedAnimations = 0;
if (m_arrGlobalHeaderDBA[dba].m_pDatabaseInfo == 0)
continue;
m_arrGlobalHeaderDBA[dba].DeleteDatabaseDBA();
}
InitialiseRunTimePools();
return 1;
}
bool CAnimationManager::DBA_Unload_All()
{
uint32 numHeadersDBA = m_arrGlobalHeaderDBA.size();
if (numHeadersDBA == 0)
return 1;
CGlobalHeaderDBA* parrGlobalDBA = &m_arrGlobalHeaderDBA[0];
for (uint32 d = 0; d < numHeadersDBA; d++)
parrGlobalDBA[d].m_nUsedAnimations = 0;
for (uint32 d = 0; d < numHeadersDBA; d++) //unlock all
parrGlobalDBA[d].m_bDBALock = 0;
uint32 numHeadersCAF = m_arrGlobalCAF.size();
if (numHeadersCAF)
{
GlobalAnimationHeaderCAF* parrGlobalCAF = &m_arrGlobalCAF[0];
for (uint32 i = 0; i < numHeadersCAF; i++)
{
// parrGlobalCAF[i].m_nRef_at_Runtime=0;
uint32 nCRC32 = parrGlobalCAF[i].m_FilePathDBACRC32;
if (nCRC32 == 0 || nCRC32 == -1)
parrGlobalCAF[i].ClearControllers();
if (parrGlobalCAF[i].m_nRef_at_Runtime == 0)
continue;
if (nCRC32)
{
for (uint32 d = 0; d < numHeadersDBA; d++)
{
if (nCRC32 == parrGlobalDBA[d].m_FilePathDBACRC32)
{
parrGlobalDBA[d].m_nUsedAnimations++;
parrGlobalDBA[d].m_nLastUsedTimeDelta = 0;
}
}
}
}
}
for (uint32 dba = 0; dba < numHeadersDBA; dba++)
{
if (m_arrGlobalHeaderDBA[dba].m_pDatabaseInfo == 0)
continue;
if (m_arrGlobalHeaderDBA[dba].m_nUsedAnimations)
{
//CryFatalError("CryAnimation: Animations still in use. Can't delete DBA : %s used: %d",m_arrGlobalHeaderDBA[dba].m_strFilePathDBA.c_str(), m_arrGlobalHeaderDBA[dba].m_nUsedAnimations );
continue;
}
m_arrGlobalHeaderDBA[dba].DeleteDatabaseDBA();
}
return 1;
}
EReloadCAFResult CAnimationManager::ReloadCAF(const char* szFilePathCAF)
{
uint32 nCRC32 = CCrc32::ComputeLowercase(szFilePathCAF);
uint32 numAIM = m_arrGlobalAIM.size();
for (uint32 id = 0; id < numAIM; id++)
{
GlobalAnimationHeaderAIM& rAIM = m_arrGlobalAIM[id];
if (rAIM.m_FilePathCRC32 == nCRC32)
{
assert(!strcmp(rAIM.GetFilePath(), szFilePathCAF));
rAIM.m_nControllers = 0;
int status = rAIM.LoadAIM();
if (status)
{
CryLog("Hot loaded animation CAF-file for an Directional-Pose: %s", rAIM.m_FilePath.c_str());
CDefaultSkeleton* pDefaultSkeleton = g_pCharacterManager->GetModelByAimPoseID(id);
if (pDefaultSkeleton)
{
uint32 numDB = pDefaultSkeleton->m_poseBlenderAimDesc.m_blends.size();
for (uint32 d = 0; d < numDB; d++)
{
const char* strAnimToken = pDefaultSkeleton->m_poseBlenderAimDesc.m_blends[d].m_AnimToken;
uint32 IsAIM = (CryStringUtils::stristr(rAIM.m_FilePath.c_str(), strAnimToken) != 0);
if (IsAIM)
{
rAIM.ProcessDirectionalPoses(pDefaultSkeleton, pDefaultSkeleton->m_poseBlenderAimDesc.m_blends, pDefaultSkeleton->m_poseBlenderAimDesc.m_rotations, pDefaultSkeleton->m_poseBlenderAimDesc.m_positions);
CryLog("Re-Processed Aim-Pose: %s", rAIM.m_FilePath.c_str());
break;
}
}
uint32 numLB = pDefaultSkeleton->m_poseBlenderLookDesc.m_blends.size();
for (uint32 d = 0; d < numLB; d++)
{
const char* strAnimToken = pDefaultSkeleton->m_poseBlenderLookDesc.m_blends[d].m_AnimToken;
uint32 IsLOOK = (CryStringUtils::stristr(rAIM.m_FilePath.c_str(), strAnimToken) != 0);
if (IsLOOK)
{
rAIM.ProcessDirectionalPoses(pDefaultSkeleton, pDefaultSkeleton->m_poseBlenderLookDesc.m_blends, pDefaultSkeleton->m_poseBlenderLookDesc.m_rotations, pDefaultSkeleton->m_poseBlenderLookDesc.m_positions);
CryLog("Re-Processed Look-Pose: %s", rAIM.m_FilePath.c_str());
break;
}
}
}
else
{
CryWarning(VALIDATOR_MODULE_ANIMATION, VALIDATOR_WARNING, "Could not process aim poses from '%s' because could not find a model associated to it.", rAIM.m_FilePath.c_str());
}
}
if (g_pCharacterManager->m_pStreamingListener)
{
g_pCharacterManager->m_pStreamingListener->NotifyAnimReloaded(id);
}
return status ? CR_RELOAD_SUCCEED : CR_RELOAD_FAILED;
}
}
//asset not found in the AIM-array
//now check the CAF array
uint32 numCAF = m_arrGlobalCAF.size();
for (uint32 id = 0; id < numCAF; id++)
{
GlobalAnimationHeaderCAF& rCAF = m_arrGlobalCAF[id];
if (rCAF.m_FilePathCRC32 == nCRC32)
{
assert(!strcmp(rCAF.GetFilePath(), szFilePathCAF));
rCAF.m_nControllers = 0;
int status = rCAF.LoadCAF();
if (status)
{
uint32 numBSpaces = m_arrGlobalLMG.size();
for (uint32 bs = 0; bs < numBSpaces; bs++)
{
m_arrGlobalLMG[bs].m_DimPara[0].m_nInitialized = 0;
m_arrGlobalLMG[bs].m_DimPara[1].m_nInitialized = 0;
m_arrGlobalLMG[bs].m_DimPara[2].m_nInitialized = 0;
m_arrGlobalLMG[bs].m_DimPara[3].m_nInitialized = 0;
}
CryLog("Hot loaded animation CAF-file: %s", rCAF.GetFilePath());
}
else
{
gEnv->pLog->LogError("CAF Reloading failed: %s", szFilePathCAF);
}
if (g_pCharacterManager->m_pStreamingListener)
{
g_pCharacterManager->m_pStreamingListener->NotifyAnimReloaded(id);
}
return status != 0 ? CR_RELOAD_SUCCEED : CR_RELOAD_FAILED;
}
}
return CR_RELOAD_GAH_NOT_IN_ARRAY;
}
int CAnimationManager::ReloadLMG(const char* szFilePath)
{
CAnimationSet* pAnimationSet = g_pCharacterManager->GetAnimationSetUsedInCharEdit();
if (pAnimationSet == 0)
{
gEnv->pLog->LogError("BlendSpace reloading failed: %s", szFilePath);
return -1;
}
uint32 nCRC32 = CCrc32::ComputeLowercase(szFilePath);
uint32 numBlendSpaces = m_arrGlobalLMG.size();
for (uint32 id = 0; id < numBlendSpaces; id++)
{
GlobalAnimationHeaderLMG& rBlendSpace = m_arrGlobalLMG[id];
if (rBlendSpace.m_FilePathCRC32 == nCRC32)
{
assert(!strcmp(rBlendSpace.GetFilePath(), szFilePath));
bool status = false;
#ifdef EDITOR_PCDEBUGCODE
stack_string path = szFilePath;
path.MakeLower();
CachedBSPACES::iterator it = m_cachedBSPACES.find(path);
if (it != m_cachedBSPACES.end())
{
XmlNodeRef root = gEnv->pSystem->LoadXmlFromBuffer(it->second.data(), it->second.size());
if (root)
{
status = rBlendSpace.LoadFromXML(pAnimationSet, root);
if (!status)
{
gEnv->pLog->LogError("BlendSpace reloading failed: %s", szFilePath);
}
}
else
{
gEnv->pLog->LogError("Failed to parse cached XML: %s", szFilePath);
}
}
else
#endif
{
status = rBlendSpace.LoadAndParseXML(pAnimationSet, 1);
if (status)
CryLog("Hot loaded animation BlendSpace-file: %s", szFilePath);
else
gEnv->pLog->LogError("BlendSpace reloading failed: %s", szFilePath);
}
if (g_pCharacterManager->m_pStreamingListener)
{
g_pCharacterManager->m_pStreamingListener->NotifyAnimReloaded(id);
}
return status;
}
}
gEnv->pLog->LogError("BlendSpace reloading failed: %s", szFilePath);
return -1;
}
uint32 CAnimationManager::GetDBACRC32fromFilePath(const char* szFilePathCAF)
{
uint32 nCRC32 = CCrc32::ComputeLowercase(szFilePathCAF);
uint32 numCAF = m_arrGlobalCAF.size();
for (uint32 id = 0; id < numCAF; id++)
{
GlobalAnimationHeaderCAF& rCAF = m_arrGlobalCAF[id];
if (rCAF.m_FilePathCRC32 == nCRC32)
return rCAF.m_FilePathDBACRC32;
}
return 0;
}
bool CAnimationManager::IsDatabaseInMemory(uint32 nDBACRC32)
{
size_t numDBA_Files = m_arrGlobalHeaderDBA.size();
for (uint32 d = 0; d < numDBA_Files; d++)
{
if (nDBACRC32 == m_arrGlobalHeaderDBA[d].m_FilePathDBACRC32)
return m_arrGlobalHeaderDBA[d].InMemory();
}
return 0;
}
//------------------------------------------------------------------------------
// Unloads animation from memory and remove
//------------------------------------------------------------------------------
void CAnimationManager::UnloadAnimationCAF(GlobalAnimationHeaderCAF& rCAF)
{
if (Console::GetInst().ca_UnloadAnimationCAF == 0)
return;
uint32 requested = rCAF.IsAssetRequested();
if (requested)
return;
if (rCAF.m_nControllers2 == 0)
return;
assert(rCAF.GetControllersCount());
rCAF.ClearControllers();
if (g_pCharacterManager->m_pStreamingListener)
{
int32 globalID = GetGlobalIDbyFilePath_CAF(rCAF.GetFilePath());
g_pCharacterManager->m_pStreamingListener->NotifyAnimUnloaded(globalID);
}
// g_pISystem->Warning( VALIDATOR_MODULE_ANIMATION,VALIDATOR_WARNING, VALIDATOR_FLAG_FILE,0, "UnloadingAsset: Name: %s",rCAF.GetFilePath() );
}
void CAnimationManager::UnloadAnimationAIM(int nGLobalAnimID)
{
assert(m_arrGlobalAIM[nGLobalAnimID].GetControllersCount());
m_arrGlobalAIM[nGLobalAnimID].ClearControllers();
}
//struct AnimSearchHelper {
//
// typedef std::vector<int> TIndexVector;
// typedef std::map<uint32 /*crc*/, TIndexVector*/*vector of indexes*/> TFoldersVector;
//
// void AddAnimation(uint32 crc, uint32 gahIndex);
// void AddAnimation(const string& path, uint32 gahIndex);
//
// TIndexVector * GetAnimationsVector(uint32 crc);
// TIndexVector * GetAnimationsVector(const string& path);
//
//};
bool AnimSearchHelper::AddAnimation(uint32 crc, uint32 gahIndex)
{
bool newPath = false;
TIndexVector* vect = GetAnimationsVector(crc);
if (!vect)
{
vect = new TIndexVector;
m_AnimationsMap[crc] = vect;
newPath = true;
}
vect->push_back(gahIndex);
return newPath;
}
void AnimSearchHelper::AddAnimation(const string& path, uint32 gahIndex)
{
stack_string pathDir = PathUtil::GetPath(path);
PathUtil::ToUnixPath(pathDir);
if (strcmp(pathDir, "animations/human/male/behavior/fear/") == 0)
int A = 0;
if (strcmp(pathDir, "animations\\human\\male\\behavior\\fear\\") == 0)
int A = 0;
uint32 crc = CCrc32::ComputeLowercase(pathDir);
if (AddAnimation(crc, gahIndex))
{
for (int32 lastSlashPos = pathDir.rfind('/'); lastSlashPos >= 0; lastSlashPos = pathDir.rfind('/', lastSlashPos - 1))
{
uint32 parentDirCRC = CCrc32::ComputeLowercase(pathDir, lastSlashPos + 1);
TSubFolderCrCVector* pSubFolderVec = NULL;
TSubFoldersMap::iterator parentFolderIter = m_SubFoldersMap.find(parentDirCRC);
if (parentFolderIter == m_SubFoldersMap.end())
{
pSubFolderVec = new TSubFolderCrCVector;
m_SubFoldersMap[parentDirCRC] = pSubFolderVec;
}
else
{
pSubFolderVec = parentFolderIter->second;
}
pSubFolderVec->push_back(crc);
}
}
}
AnimSearchHelper::TSubFolderCrCVector* AnimSearchHelper::GetSubFoldersVector(uint32 crc)
{
TSubFoldersMap::iterator parentFolderIter = m_SubFoldersMap.find(crc);
if (parentFolderIter != m_SubFoldersMap.end())
{
return parentFolderIter->second;
}
else
{
return NULL;
}
}
AnimSearchHelper::TIndexVector* AnimSearchHelper::GetAnimationsVector(uint32 crc)
{
TFoldersVector::iterator it = m_AnimationsMap.find(crc);
if (it != m_AnimationsMap.end())
return it->second;
return 0;
}
AnimSearchHelper::TIndexVector* AnimSearchHelper::GetAnimationsVector(const string& path)
{
uint32 crc = CCrc32::ComputeLowercase(path);
return GetAnimationsVector(crc);
}
void AnimSearchHelper::Clear()
{
for (TFoldersVector::iterator it = m_AnimationsMap.begin(), end = m_AnimationsMap.end(); it != end; ++it)
delete it->second;
for (TSubFoldersMap::iterator it = m_SubFoldersMap.begin(), end = m_SubFoldersMap.end(); it != end; ++it)
delete it->second;
m_AnimationsMap.clear();
m_SubFoldersMap.clear();
}
size_t CAnimationManager::GetSizeOfDBA()
{
size_t nSize = 0;
uint32 numDBAs = m_arrGlobalHeaderDBA.size();
for (uint32 i = 0; i < numDBAs; i++)
nSize += m_arrGlobalHeaderDBA[i].SizeOf_DBA();
return nSize;
}
void CAnimationManager::GetMemoryUsage(class ICrySizer* pSizer) const
{
SIZER_SUBCOMPONENT_NAME(pSizer, "AnimationKeys");
pSizer->AddObject(m_AnimationMapCAF);
pSizer->AddObject(m_arrGlobalCAF);
pSizer->AddObject(m_arrGlobalAIM);
pSizer->AddObject(m_arrGlobalLMG);
pSizer->AddObject(m_arrGlobalHeaderDBA);
}
void CAnimationManager::DebugAnimUsage(uint32 printtxt)
{
DEFINE_PROFILER_FUNCTION();
#ifndef CONSOLE_CONST_CVAR_MODE
// if (Console::GetInst().ca_DebugAnimMemTracking==0)
// return;
if (m_shuttingDown)
return;
float fRed[4] = { 1, 0, 0, 1 };
float fGreen[4] = { 0, 1, 0, 1 };
float fBlue[4] = { 0, 0, 1, 1 };
size_t numDBA_Files = m_arrGlobalHeaderDBA.size();
for (uint32 d = 0; d < numDBA_Files; d++)
m_arrGlobalHeaderDBA[d].m_nEmpty = 1;
for (uint32 x = 0; x < numDBA_Files; x++)
{
uint32 biggest = 0;
int32 b = -1;
for (uint32 d = 0; d < numDBA_Files; d++)
{
uint32 nUsed = m_arrGlobalHeaderDBA[d].m_nEmpty;
size_t nSizeOfDBA = m_arrGlobalHeaderDBA[d].SizeOf_DBA();
if (biggest < nSizeOfDBA && nUsed)
{
biggest = nSizeOfDBA;
b = d;
}
}
if (b > -1)
{
m_arrGlobalHeaderDBA[b].m_nEmpty = 0;
const char* pName = m_arrGlobalHeaderDBA[b].m_strFilePathDBA;
uint32 nDBACRC32 = m_arrGlobalHeaderDBA[b].m_FilePathDBACRC32;
uint32 nUsedAssets = m_arrGlobalHeaderDBA[b].m_nUsedAnimations;
size_t nSizeOfDBA = m_arrGlobalHeaderDBA[b].SizeOf_DBA();
uint32 nLastUsedTimeSec = m_arrGlobalHeaderDBA[b].m_nLastUsedTimeDelta / 1000;
uint32 nLock = m_arrGlobalHeaderDBA[b].m_bDBALock;
if (m_arrGlobalHeaderDBA[b].m_pDatabaseInfo == 0)
{
// fColorGreen[3]=0.4f;
// g_pAuxGeom->Draw2dLabel( 1,g_YLine, 0.9f, fColorGreen, false,"UsedAssets: %04d nTCount: %08x Size: %08d FilePathDBA: %s",nUsedAssets,nTCount,nSizeOfDBA,pName );
// g_YLine+=9.0f;
}
else
{
float fColor[4] = { 0, 1, 0, 1 };
if (nLock)
{
fColor[0] = 1.0f;
fColor[1] = 0.0f;
}
if (printtxt)
{
g_pAuxGeom->Draw2dLabel(1, g_YLine, 1.1f, fColor, false, "UsedAssets: %04d nTCount: %u Size: %" PRISIZE_T " FilePathDBA: %s", nUsedAssets, nLastUsedTimeSec, nSizeOfDBA, pName);
g_YLine += 11.0f;
}
}
}
}
g_YLine += 16.0f;
size_t nAnimationManager = sizeof(CAnimationManager);
size_t nMap = m_AnimationMapCAF.GetAllocMemSize();
size_t nFilePathSize = 0;
{
uint32 numCAF = m_arrGlobalCAF.size();
for (uint32 i = 0; i < numCAF; i++)
nFilePathSize += m_arrGlobalCAF[i].m_FilePath.capacity();
uint32 numAIM = m_arrGlobalAIM.size();
for (uint32 i = 0; i < numAIM; i++)
nFilePathSize += m_arrGlobalAIM[i].m_FilePath.capacity();
uint32 numLMG = m_arrGlobalLMG.size();
for (uint32 i = 0; i < numLMG; i++)
nFilePathSize += m_arrGlobalLMG[i].m_FilePath.capacity();
numCAF = m_arrGlobalCAF.capacity();
numAIM = m_arrGlobalAIM.capacity();
numLMG = m_arrGlobalLMG.capacity();
size_t nEmptyHeaderSize = 0;
nEmptyHeaderSize += numCAF * sizeof(GlobalAnimationHeaderCAF);
nEmptyHeaderSize += numAIM * sizeof(GlobalAnimationHeaderAIM);
nEmptyHeaderSize += numLMG * sizeof(GlobalAnimationHeaderLMG);
if (printtxt)
{
g_pAuxGeom->Draw2dLabel(1, g_YLine, 2.0f, fRed, false, "size of path names: %" PRISIZE_T " bytes Empty Headers: %" PRISIZE_T " bytes", nFilePathSize, nEmptyHeaderSize);
g_YLine += 16.0f;
}
}
//calculate size of DBAs
size_t nDBAalloc = GetSizeOfDBA();
nAnimationManager += nDBAalloc;
if (printtxt)
{
g_pAuxGeom->Draw2dLabel(1, g_YLine, 2.0f, fRed, false, "DBA: %" PRISIZE_T " KBytes map: %" PRISIZE_T " KBytes", nDBAalloc / 1024, nMap / 1024);
g_YLine += 16.0f;
}
uint32 nUsedCAFs = 0;
{
uint32 numCAF = m_arrGlobalCAF.size();
size_t nSize = m_arrGlobalCAF.get_alloc_size() + nMap;
for (uint32 i = 0; i < numCAF; i++)
nSize += m_arrGlobalCAF[i].SizeOfCAF();
uint32 nNumHeaders = m_arrGlobalCAF.size();
uint32 nLoaded = 0;
uint32 nSizeOfLoadedKeys = 0;
for (uint32 i = 0; i < nNumHeaders; i++)
{
uint32 IsAssetLoaded = m_arrGlobalCAF[i].IsAssetLoaded();
uint32 IsDBAFile = m_arrGlobalCAF[i].m_FilePathDBACRC32;
if (m_arrGlobalCAF[i].m_FilePathDBACRC32 == -1)
IsDBAFile = 0;
if (IsAssetLoaded && IsDBAFile == 0)
{
nLoaded++;
uint32 nSizeOfCAF = m_arrGlobalCAF[i].SizeOfCAF();
nSizeOfLoadedKeys += nSizeOfCAF;
uint32 nRef_at_Runtime = m_arrGlobalCAF[i].m_nRef_at_Runtime;
if (printtxt && Console::GetInst().ca_DebugAnimUsage == 2)
{
g_pAuxGeom->Draw2dLabel(1, g_YLine, 1.1f, fGreen, false, "CafInMemory: %7d ref: %5d FilePath: %s", nSizeOfCAF, nRef_at_Runtime, m_arrGlobalCAF[i].GetFilePath());
g_YLine += 11.0f;
}
if (printtxt && Console::GetInst().ca_DebugAnimUsage & 4)
{
CryLogAlways("CafInMemory: %07u FilePath: %s", nSizeOfCAF, m_arrGlobalCAF[i].GetFilePath());
}
}
nUsedCAFs += (m_arrGlobalCAF[i].m_nTouchedCounter != 0);
}
if (printtxt && Console::GetInst().ca_DebugAnimUsage & 4)
{
CryLogAlways("nSizeOfLoadedKeys: %07u", nSizeOfLoadedKeys);
Console::GetInst().ca_DebugAnimUsage &= 3;
}
if (printtxt)
{
g_pAuxGeom->Draw2dLabel(1, g_YLine, 2.0f, fRed, false, "CAF: %04d Loaded: %04d Used: %04d Memory: %05" PRISIZE_T " / %05d KBytes", nNumHeaders, nLoaded, nUsedCAFs, nSize / 1024, nSizeOfLoadedKeys / 1024);
g_YLine += 16.0f;
}
nAnimationManager += nSize;
}
{
uint32 numAIM = m_arrGlobalAIM.size();
size_t nSize = m_arrGlobalAIM.get_alloc_size();
for (uint32 i = 0; i < numAIM; i++)
nSize += m_arrGlobalAIM[i].SizeOfAIM();
uint32 nNumHeaders = m_arrGlobalAIM.size();
uint32 nLoaded = 0;
uint32 nUsed = 0;
for (uint32 i = 0; i < nNumHeaders; i++)
{
nLoaded += (m_arrGlobalAIM[i].IsAssetLoaded() != 0);
nUsed += (m_arrGlobalAIM[i].m_nTouchedCounter != 0);
}
if (printtxt)
{
g_pAuxGeom->Draw2dLabel(1, g_YLine, 2.0f, fRed, false, "AIM: %04d Loaded: %04d Used: %04d Memory: %05" PRISIZE_T " KBytes", nNumHeaders, nLoaded, nUsed, nSize / 1024);
g_YLine += 16.0f;
}
nAnimationManager += nSize;
}
{
uint32 numLMG = m_arrGlobalLMG.size();
size_t nSize = m_arrGlobalLMG.get_alloc_size();
for (uint32 i = 0; i < numLMG; i++)
nSize += m_arrGlobalLMG[i].SizeOfLMG();
uint32 nNumHeaders = m_arrGlobalLMG.size();
uint32 nLoaded = 0;
uint32 nUsed = 0;
for (uint32 i = 0; i < nNumHeaders; i++)
{
nLoaded += (m_arrGlobalLMG[i].IsAssetLoaded() != 0);
nUsed += (m_arrGlobalLMG[i].m_nTouchedCounter != 0);
}
if (printtxt)
{
g_pAuxGeom->Draw2dLabel(1, g_YLine, 2.0f, fRed, false, "Blendspace: %04d Loaded: %04d Used: %04d Memory: %05" PRISIZE_T "KBytes", nNumHeaders, nLoaded, nUsed, nSize / 1024);
g_YLine += 16.0f;
}
nAnimationManager += nSize;
}
if (printtxt)
{
CControllerDefragHeap::Stats stats = g_controllerHeap.GetStats();
size_t moveableFree = stats.defragStats.nCapacity - stats.defragStats.nInUseSize;
g_pAuxGeom->Draw2dLabel(1, g_YLine, 2.0f, fRed, false, "Defrag heap: %" PRISIZE_T " KB moveable %" PRISIZE_T "KB fixed %.2f%% frag", stats.defragStats.nInUseSize / 1024, stats.bytesInFixedAllocs / 1024,
100.0f * ((moveableFree - stats.defragStats.nLargestFreeBlockSize) / (float)stats.defragStats.nCapacity));
g_YLine += 16.0f;
}
m_AnimMemoryTracker.m_nAnimsCurrent = nAnimationManager;
m_AnimMemoryTracker.m_nGlobalCAFs = m_arrGlobalCAF.size();
m_AnimMemoryTracker.m_nUsedGlobalCAFs = nUsedCAFs;
if (m_AnimMemoryTracker.m_nAnimsMax < nAnimationManager)
m_AnimMemoryTracker.m_nAnimsMax = nAnimationManager;
uint64 average = 0;
if (m_AnimMemoryTracker.m_nAnimsCounter || m_AnimMemoryTracker.m_nAnimsCurrent > 7211000)
{
m_AnimMemoryTracker.m_nAnimsCounter++;
m_AnimMemoryTracker.m_nAnimsAdd += nAnimationManager;
average = m_AnimMemoryTracker.m_nAnimsAdd / m_AnimMemoryTracker.m_nAnimsCounter;
}
static uint32 mupdate = 0x1f;
mupdate++;
mupdate &= 0x7f;
if (mupdate == 0)
g_pCharacterManager->TrackMemoryOfModels();
if (printtxt)
{
g_YLine += 10.0f;
g_pAuxGeom->Draw2dLabel(1, g_YLine, 2.2f, fBlue, false, "nAnimsPerFrame: %4d nAnimsMax: %4d nAnimsAvrg: %4d", m_AnimMemoryTracker.m_nAnimsCurrent / 1024, m_AnimMemoryTracker.m_nAnimsMax / 1024, (uint32)(average / 1024));
g_YLine += 25.0f;
g_pAuxGeom->Draw2dLabel(1, g_YLine, 2.2f, fRed, false, "CharInstances:%3d (Mem: %4dKB) SkinInstances:%3d (Mem: %4dKB) Models:%3d (Mem: %4dKB)", m_AnimMemoryTracker.m_numTCharInstances, m_AnimMemoryTracker.m_nTotalCharMemory / 1024, m_AnimMemoryTracker.m_numTSkinInstances, m_AnimMemoryTracker.m_nTotalSkinMemory / 1024, m_AnimMemoryTracker.m_numModels, m_AnimMemoryTracker.m_nTotalMMemory / 1024);
g_YLine += 25.0f;
g_pAuxGeom->Draw2dLabel(1, g_YLine, 3.0f, fRed, false, "Total: %4dKB", (m_AnimMemoryTracker.m_nTotalCharMemory + m_AnimMemoryTracker.m_nTotalSkinMemory + m_AnimMemoryTracker.m_nTotalMMemory + m_AnimMemoryTracker.m_nAnimsCurrent) / 1024);
}
#endif
}
| 0 | 0.958751 | 1 | 0.958751 | game-dev | MEDIA | 0.671375 | game-dev | 0.970781 | 1 | 0.970781 |
mangosArchives/serverZero_Rel19 | 20,717 | src/game/vmap/TileAssembler.cpp | /**
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2014 MaNGOS project <http://getmangos.eu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
#include "TileAssembler.h"
#include "MapTree.h"
#include "BIH.h"
#include "VMapDefinitions.h"
#include <set>
#include <iomanip>
#include <sstream>
#include <iomanip>
using G3D::Vector3;
using G3D::AABox;
using G3D::inf;
using std::pair;
template<> struct BoundsTrait<VMAP::ModelSpawn*>
{
static void getBounds(const VMAP::ModelSpawn* const& obj, G3D::AABox& out) { out = obj->getBounds(); }
};
namespace VMAP
{
bool readChunk(FILE* rf, char* dest, const char* compare, uint32 len)
{
if (fread(dest, sizeof(char), len, rf) != len) { return false; }
return memcmp(dest, compare, len) == 0;
}
Vector3 ModelPosition::transform(const Vector3& pIn) const
{
Vector3 out = pIn * iScale;
out = iRotation * out;
return(out);
}
//=================================================================
TileAssembler::TileAssembler(const std::string& pSrcDirName, const std::string& pDestDirName)
{
iCurrentUniqueNameId = 0;
iFilterMethod = NULL;
iSrcDir = pSrcDirName;
iDestDir = pDestDirName;
// mkdir(iDestDir);
// init();
}
TileAssembler::~TileAssembler()
{
// delete iCoordModelMapping;
}
bool TileAssembler::convertWorld2()
{
bool success = readMapSpawns();
if (!success)
{ return false; }
// export Map data
for (MapData::iterator map_iter = mapData.begin(); map_iter != mapData.end() && success; ++map_iter)
{
// build global map tree
std::vector<ModelSpawn*> mapSpawns;
UniqueEntryMap::iterator entry;
printf("Calculating model bounds for map %u...\n", map_iter->first);
for (entry = map_iter->second->UniqueEntries.begin(); entry != map_iter->second->UniqueEntries.end(); ++entry)
{
// M2 models don't have a bound set in WDT/ADT placement data, i still think they're not used for LoS at all on retail
if (entry->second.flags & MOD_M2)
{
if (!calculateTransformedBound(entry->second))
{ break; }
}
else if (entry->second.flags & MOD_WORLDSPAWN) // WMO maps and terrain maps use different origin, so we need to adapt :/
{
// TODO: remove extractor hack and uncomment below line:
// entry->second.iPos += Vector3(533.33333f*32, 533.33333f*32, 0.f);
entry->second.iBound = entry->second.iBound + Vector3(533.33333f * 32, 533.33333f * 32, 0.f);
}
mapSpawns.push_back(&(entry->second));
spawnedModelFiles.insert(entry->second.name);
}
printf("Creating map tree...\n");
BIH pTree;
pTree.build(mapSpawns, BoundsTrait<ModelSpawn*>::getBounds);
// ===> possibly move this code to StaticMapTree class
std::map<uint32, uint32> modelNodeIdx;
for (uint32 i = 0; i < mapSpawns.size(); ++i)
{ modelNodeIdx.insert(pair<uint32, uint32>(mapSpawns[i]->ID, i)); }
// write map tree file
std::stringstream mapfilename;
mapfilename << iDestDir << "/" << std::setfill('0') << std::setw(3) << map_iter->first << ".vmtree";
FILE* mapfile = fopen(mapfilename.str().c_str(), "wb");
if (!mapfile)
{
success = false;
printf("Can not open %s\n", mapfilename.str().c_str());
break;
}
// general info
if (success && fwrite(VMAP_MAGIC, 1, 8, mapfile) != 8) { success = false; }
uint32 globalTileID = StaticMapTree::packTileID(65, 65);
pair<TileMap::iterator, TileMap::iterator> globalRange = map_iter->second->TileEntries.equal_range(globalTileID);
char isTiled = globalRange.first == globalRange.second; // only maps without terrain (tiles) have global WMO
if (success && fwrite(&isTiled, sizeof(char), 1, mapfile) != 1) { success = false; }
// Nodes
if (success && fwrite("NODE", 4, 1, mapfile) != 1) { success = false; }
if (success) { success = pTree.writeToFile(mapfile); }
// global map spawns (WDT), if any (most instances)
if (success && fwrite("GOBJ", 4, 1, mapfile) != 1) { success = false; }
for (TileMap::iterator glob = globalRange.first; glob != globalRange.second && success; ++glob)
{
success = ModelSpawn::writeToFile(mapfile, map_iter->second->UniqueEntries[glob->second]);
}
fclose(mapfile);
// <====
// write map tile files, similar to ADT files, only with extra BSP tree node info
TileMap& tileEntries = map_iter->second->TileEntries;
TileMap::iterator tile;
for (tile = tileEntries.begin(); tile != tileEntries.end(); ++tile)
{
const ModelSpawn& spawn = map_iter->second->UniqueEntries[tile->second];
if (spawn.flags & MOD_WORLDSPAWN) // WDT spawn, saved as tile 65/65 currently...
{ continue; }
uint32 nSpawns = tileEntries.count(tile->first);
std::stringstream tilefilename;
tilefilename.fill('0');
tilefilename << iDestDir << "/" << std::setw(3) << map_iter->first << "_";
uint32 x, y;
StaticMapTree::unpackTileID(tile->first, x, y);
tilefilename << std::setw(2) << x << "_" << std::setw(2) << y << ".vmtile";
FILE* tilefile = fopen(tilefilename.str().c_str(), "wb");
// file header
if (success && fwrite(VMAP_MAGIC, 1, 8, tilefile) != 8) { success = false; }
// write number of tile spawns
if (success && fwrite(&nSpawns, sizeof(uint32), 1, tilefile) != 1) { success = false; }
// write tile spawns
for (uint32 s = 0; s < nSpawns; ++s)
{
if (s && tile != tileEntries.end())
{ ++tile; }
const ModelSpawn& spawn2 = map_iter->second->UniqueEntries[tile->second];
success = success && ModelSpawn::writeToFile(tilefile, spawn2);
// MapTree nodes to update when loading tile:
std::map<uint32, uint32>::iterator nIdx = modelNodeIdx.find(spawn2.ID);
if (success && fwrite(&nIdx->second, sizeof(uint32), 1, tilefile) != 1) { success = false; }
}
fclose(tilefile);
}
// break; // test, extract only first map; TODO: remvoe this line
}
// add an object models, listed in temp_gameobject_models file
exportGameobjectModels();
// export objects
std::cout << "\nConverting Model Files" << std::endl;
for (std::set<std::string>::iterator mfile = spawnedModelFiles.begin(); mfile != spawnedModelFiles.end(); ++mfile)
{
std::cout << "Converting " << *mfile << std::endl;
if (!convertRawFile(*mfile))
{
std::cout << "error converting " << *mfile << std::endl;
success = false;
break;
}
}
// cleanup:
for (MapData::iterator map_iter = mapData.begin(); map_iter != mapData.end(); ++map_iter)
{
delete map_iter->second;
}
return success;
}
bool TileAssembler::readMapSpawns()
{
std::string fname = iSrcDir + "/dir_bin";
FILE* dirf = fopen(fname.c_str(), "rb");
if (!dirf)
{
printf("Could not read dir_bin file!\n");
return false;
}
printf("Read coordinate mapping...\n");
uint32 mapID, tileX, tileY, check = 0;
G3D::Vector3 v1, v2;
ModelSpawn spawn;
while (!feof(dirf))
{
check = 0;
// read mapID, tileX, tileY, Flags, adtID, ID, Pos, Rot, Scale, Bound_lo, Bound_hi, name
check += fread(&mapID, sizeof(uint32), 1, dirf);
if (check == 0) // EoF...
{ break; }
check += fread(&tileX, sizeof(uint32), 1, dirf);
check += fread(&tileY, sizeof(uint32), 1, dirf);
if (!ModelSpawn::readFromFile(dirf, spawn))
{ break; }
MapSpawns* current;
MapData::iterator map_iter = mapData.find(mapID);
if (map_iter == mapData.end())
{
printf("spawning Map %d\n", mapID);
mapData[mapID] = current = new MapSpawns();
}
else { current = (*map_iter).second; }
current->UniqueEntries.insert(pair<uint32, ModelSpawn>(spawn.ID, spawn));
current->TileEntries.insert(pair<uint32, uint32>(StaticMapTree::packTileID(tileX, tileY), spawn.ID));
}
bool success = (ferror(dirf) == 0);
fclose(dirf);
return success;
}
bool TileAssembler::calculateTransformedBound(ModelSpawn& spawn)
{
std::string modelFilename = iSrcDir + "/" + spawn.name;
ModelPosition modelPosition;
modelPosition.iDir = spawn.iRot;
modelPosition.iScale = spawn.iScale;
modelPosition.init();
WorldModel_Raw raw_model;
if (!raw_model.Read(modelFilename.c_str()))
{ return false; }
uint32 groups = raw_model.groupsArray.size();
if (groups != 1)
{ printf("Warning: '%s' does not seem to be a M2 model!\n", modelFilename.c_str()); }
AABox modelBound;
bool boundEmpty = true;
for (uint32 g = 0; g < groups; ++g) // should be only one for M2 files...
{
std::vector<Vector3>& vertices = raw_model.groupsArray[g].vertexArray;
if (vertices.empty())
{
std::cout << "error: model '" << spawn.name << "' has no geometry!" << std::endl;
continue;
}
uint32 nvectors = vertices.size();
for (uint32 i = 0; i < nvectors; ++i)
{
Vector3 v = modelPosition.transform(vertices[i]);
if (boundEmpty)
{ modelBound = AABox(v, v), boundEmpty = false; }
else
{ modelBound.merge(v); }
}
}
spawn.iBound = modelBound + spawn.iPos;
spawn.flags |= MOD_HAS_BOUND;
return true;
}
struct WMOLiquidHeader
{
int xverts, yverts, xtiles, ytiles;
float pos_x;
float pos_y;
float pos_z;
short type;
};
//=================================================================
bool TileAssembler::convertRawFile(const std::string& pModelFilename)
{
bool success = true;
std::string filename = iSrcDir;
if (filename.length() > 0)
{ filename.append("/"); }
filename.append(pModelFilename);
WorldModel_Raw raw_model;
if (!raw_model.Read(filename.c_str()))
{ return false; }
// write WorldModel
WorldModel model;
model.setRootWmoID(raw_model.RootWMOID);
if (raw_model.groupsArray.size())
{
std::vector<GroupModel> groupsArray;
uint32 groups = raw_model.groupsArray.size();
for (uint32 g = 0; g < groups; ++g)
{
GroupModel_Raw& raw_group = raw_model.groupsArray[g];
groupsArray.push_back(GroupModel(raw_group.mogpflags, raw_group.GroupWMOID, raw_group.bounds));
groupsArray.back().setMeshData(raw_group.vertexArray, raw_group.triangles);
groupsArray.back().setLiquidData(raw_group.liquid);
}
model.setGroupModels(groupsArray);
}
success = model.writeFile(iDestDir + "/" + pModelFilename + ".vmo");
//std::cout << "readRawFile2: '" << pModelFilename << "' tris: " << nElements << " nodes: " << nNodes << std::endl;
return success;
}
void TileAssembler::exportGameobjectModels()
{
FILE* model_list = fopen((iSrcDir + "/" + GAMEOBJECT_MODELS).c_str(), "rb");
if (!model_list)
{ return; }
FILE* model_list_copy = fopen((iDestDir + "/" + GAMEOBJECT_MODELS).c_str(), "wb");
if (!model_list_copy)
{
fclose(model_list);
return;
}
uint32 name_length, displayId;
char buff[500];
while (!feof(model_list))
{
if (fread(&displayId, sizeof(uint32), 1, model_list) <= 0)
{
std::cout << "\nFile '" << GAMEOBJECT_MODELS << "' seems to be corrupted" << std::endl;
break;
}
if (fread(&name_length, sizeof(uint32), 1, model_list) <= 0)
{
std::cout << "\nFile '" << GAMEOBJECT_MODELS << "' seems to be corrupted" << std::endl;
break;
}
if (name_length >= sizeof(buff))
{
std::cout << "\nFile '" << GAMEOBJECT_MODELS << "' seems to be corrupted" << std::endl;
break;
}
if (fread(&buff, sizeof(char), name_length, model_list) <= 0)
{
std::cout << "\nFile '" << GAMEOBJECT_MODELS << "' seems to be corrupted" << std::endl;
break;
}
std::string model_name(buff, name_length);
WorldModel_Raw raw_model;
if (!raw_model.Read((iSrcDir + "/" + model_name).c_str()))
{ continue; }
spawnedModelFiles.insert(model_name);
AABox bounds;
bool boundEmpty = true;
for (uint32 g = 0; g < raw_model.groupsArray.size(); ++g)
{
std::vector<Vector3>& vertices = raw_model.groupsArray[g].vertexArray;
uint32 nvectors = vertices.size();
for (uint32 i = 0; i < nvectors; ++i)
{
Vector3& v = vertices[i];
if (boundEmpty)
{ bounds = AABox(v, v), boundEmpty = false; }
else
{ bounds.merge(v); }
}
}
fwrite(&displayId, sizeof(uint32), 1, model_list_copy);
fwrite(&name_length, sizeof(uint32), 1, model_list_copy);
fwrite(&buff, sizeof(char), name_length, model_list_copy);
fwrite(&bounds.low(), sizeof(Vector3), 1, model_list_copy);
fwrite(&bounds.high(), sizeof(Vector3), 1, model_list_copy);
}
fclose(model_list);
fclose(model_list_copy);
}
// temporary use defines to simplify read/check code (close file and return at fail)
#define READ_OR_RETURN(V,S) if(fread((V), (S), 1, rf) != 1) { \
fclose(rf); printf("readfail, op = %i\n", readOperation); return(false); }
#define CMP_OR_RETURN(V,S) if(strcmp((V),(S)) != 0) { \
fclose(rf); printf("cmpfail, %s!=%s\n", V, S);return(false); }
bool GroupModel_Raw::Read(FILE* rf)
{
char blockId[5];
blockId[4] = 0;
int blocksize;
int readOperation = 0;
READ_OR_RETURN(&mogpflags, sizeof(uint32));
READ_OR_RETURN(&GroupWMOID, sizeof(uint32));
Vector3 vec1, vec2;
READ_OR_RETURN(&vec1, sizeof(Vector3));
READ_OR_RETURN(&vec2, sizeof(Vector3));
bounds.set(vec1, vec2);
READ_OR_RETURN(&liquidflags, sizeof(uint32));
// will this ever be used? what is it good for anyway??
uint32 branches;
READ_OR_RETURN(&blockId, 4);
CMP_OR_RETURN(blockId, "GRP ");
READ_OR_RETURN(&blocksize, sizeof(int));
READ_OR_RETURN(&branches, sizeof(uint32));
for (uint32 b = 0; b < branches; ++b)
{
uint32 indexes;
// indexes for each branch (not used jet)
READ_OR_RETURN(&indexes, sizeof(uint32));
}
// ---- indexes
READ_OR_RETURN(&blockId, 4);
CMP_OR_RETURN(blockId, "INDX");
READ_OR_RETURN(&blocksize, sizeof(int));
uint32 nindexes;
READ_OR_RETURN(&nindexes, sizeof(uint32));
if (nindexes > 0)
{
uint16* indexarray = new uint16[nindexes];
if (fread(indexarray, nindexes * sizeof(uint16), 1, rf) != 1)
{
fclose(rf);
delete[] indexarray;
printf("readfail, op = %i\n", readOperation);
return false;
}
triangles.reserve(nindexes / 3);
for (uint32 i = 0; i < nindexes; i += 3)
{
triangles.push_back(MeshTriangle(indexarray[i], indexarray[i + 1], indexarray[i + 2]));
}
delete[] indexarray;
}
// ---- vectors
READ_OR_RETURN(&blockId, 4);
CMP_OR_RETURN(blockId, "VERT");
READ_OR_RETURN(&blocksize, sizeof(int));
uint32 nvectors;
READ_OR_RETURN(&nvectors, sizeof(uint32));
if (nvectors > 0)
{
float* vectorarray = new float[nvectors * 3];
if (fread(vectorarray, nvectors * sizeof(float) * 3, 1, rf) != 1)
{
fclose(rf);
delete[] vectorarray;
printf("readfail, op = %i\n", readOperation);
return false;
}
for (uint32 i = 0; i < nvectors; ++i)
{
vertexArray.push_back(Vector3(vectorarray + 3 * i));
}
delete[] vectorarray;
}
// ----- liquid
liquid = 0;
if (liquidflags & 1)
{
WMOLiquidHeader hlq;
READ_OR_RETURN(&blockId, 4);
CMP_OR_RETURN(blockId, "LIQU");
READ_OR_RETURN(&blocksize, sizeof(int));
READ_OR_RETURN(&hlq, sizeof(WMOLiquidHeader));
liquid = new WmoLiquid(hlq.xtiles, hlq.ytiles, Vector3(hlq.pos_x, hlq.pos_y, hlq.pos_z), hlq.type);
uint32 size = hlq.xverts * hlq.yverts;
READ_OR_RETURN(liquid->GetHeightStorage(), size * sizeof(float));
size = hlq.xtiles * hlq.ytiles;
READ_OR_RETURN(liquid->GetFlagsStorage(), size);
}
return true;
}
GroupModel_Raw::~GroupModel_Raw()
{
delete liquid;
}
bool WorldModel_Raw::Read(const char* path)
{
FILE* rf = fopen(path, "rb");
if (!rf)
{
printf("ERROR: Can't open raw model file: %s\n", path);
return false;
}
char ident[8];
int readOperation = 0;
READ_OR_RETURN(&ident, 8);
CMP_OR_RETURN(ident, RAW_VMAP_MAGIC);
// we have to read one int. This is needed during the export and we have to skip it here
uint32 tempNVectors;
READ_OR_RETURN(&tempNVectors, sizeof(tempNVectors));
uint32 groups;
READ_OR_RETURN(&groups, sizeof(uint32));
READ_OR_RETURN(&RootWMOID, sizeof(uint32));
groupsArray.resize(groups);
bool succeed = true;
for (uint32 g = 0; g < groups && succeed; ++g)
{ succeed = groupsArray[g].Read(rf); }
fclose(rf);
return succeed;
}
// drop of temporary use defines
#undef READ_OR_RETURN
#undef CMP_OR_RETURN
}
| 0 | 0.959343 | 1 | 0.959343 | game-dev | MEDIA | 0.760464 | game-dev | 0.962776 | 1 | 0.962776 |
LandSandBoat/server | 1,680 | scripts/battlefields/Chamber_of_Oracles/shattering_stars_nin.lua | -----------------------------------
-- Area: Chamber of Oracles
-- Name: Shattering stars - Maat Fight (NIN)
-----------------------------------
local chamberOfOraclesID = zones[xi.zone.CHAMBER_OF_ORACLES]
-----------------------------------
local content = Battlefield:new({
zoneId = xi.zone.CHAMBER_OF_ORACLES,
battlefieldId = xi.battlefield.id.SHATTERING_STARS_NIN,
maxPlayers = 1,
levelCap = 99,
allowSubjob = false,
timeLimit = utils.minutes(10),
index = 3,
entryNpc = 'SC_Entrance',
exitNpc = 'Shimmering_Circle',
requiredItems = { xi.item.NINJAS_TESTIMONY, wearMessage = chamberOfOraclesID.text.TESTIMONY_WEARS, wornMessage = chamberOfOraclesID.text.TESTIMONY_IS_TORN },
})
function content:entryRequirement(player, npc, isRegistrant, trade)
local jobRequirement = player:getMainJob() == xi.job.NIN
local levelRequirement = player:getMainLvl() >= 66
local questStatus = player:getQuestStatus(xi.questLog.JEUNO, xi.quest.id.jeuno.SHATTERING_STARS)
local questRequirement = questStatus == xi.questStatus.QUEST_COMPLETED or (questStatus == xi.questStatus.QUEST_ACCEPTED and player:getCharVar('Quest[3][132]tradedTestimony') == 1)
return jobRequirement and levelRequirement and questRequirement
end
content.groups =
{
{
mobIds =
{
{ chamberOfOraclesID.mob.MAAT + 3 },
{ chamberOfOraclesID.mob.MAAT + 4 },
{ chamberOfOraclesID.mob.MAAT + 5 },
},
allDeath = function(battlefield, mob)
battlefield:setStatus(xi.battlefield.status.WON)
end,
},
}
return content:register()
| 0 | 0.907081 | 1 | 0.907081 | game-dev | MEDIA | 0.973718 | game-dev | 0.728132 | 1 | 0.728132 |
nhn/socket.io-client-unity3d | 2,341 | Assets/Plugins/UniRx/Scripts/UnityEngineBridge/Triggers/ObservableTriggerTrigger.cs | using System; // require keep for Windows Universal App
using UnityEngine;
namespace UniRx.Triggers
{
[DisallowMultipleComponent]
public class ObservableTriggerTrigger : ObservableTriggerBase
{
Subject<Collider> onTriggerEnter;
/// <summary>OnTriggerEnter is called when the Collider other enters the trigger.</summary>
void OnTriggerEnter(Collider other)
{
if (onTriggerEnter != null) onTriggerEnter.OnNext(other);
}
/// <summary>OnTriggerEnter is called when the Collider other enters the trigger.</summary>
public IObservable<Collider> OnTriggerEnterAsObservable()
{
return onTriggerEnter ?? (onTriggerEnter = new Subject<Collider>());
}
Subject<Collider> onTriggerExit;
/// <summary>OnTriggerExit is called when the Collider other has stopped touching the trigger.</summary>
void OnTriggerExit(Collider other)
{
if (onTriggerExit != null) onTriggerExit.OnNext(other);
}
/// <summary>OnTriggerExit is called when the Collider other has stopped touching the trigger.</summary>
public IObservable<Collider> OnTriggerExitAsObservable()
{
return onTriggerExit ?? (onTriggerExit = new Subject<Collider>());
}
Subject<Collider> onTriggerStay;
/// <summary>OnTriggerStay is called once per frame for every Collider other that is touching the trigger.</summary>
void OnTriggerStay(Collider other)
{
if (onTriggerStay != null) onTriggerStay.OnNext(other);
}
/// <summary>OnTriggerStay is called once per frame for every Collider other that is touching the trigger.</summary>
public IObservable<Collider> OnTriggerStayAsObservable()
{
return onTriggerStay ?? (onTriggerStay = new Subject<Collider>());
}
protected override void RaiseOnCompletedOnDestroy()
{
if (onTriggerEnter != null)
{
onTriggerEnter.OnCompleted();
}
if (onTriggerExit != null)
{
onTriggerExit.OnCompleted();
}
if (onTriggerStay != null)
{
onTriggerStay.OnCompleted();
}
}
}
} | 0 | 0.843969 | 1 | 0.843969 | game-dev | MEDIA | 0.665593 | game-dev | 0.866765 | 1 | 0.866765 |
codebots-ltd/GLKit_TD3D | 23,029 | GLKit_TD3D/Bullet/LinearMath/btMatrix3x3.h | /*
Copyright (c) 2003-2006 Gino van den Bergen / 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_MATRIX3x3_H
#define BT_MATRIX3x3_H
#include "btVector3.h"
#include "btQuaternion.h"
#ifdef BT_USE_DOUBLE_PRECISION
#define btMatrix3x3Data btMatrix3x3DoubleData
#else
#define btMatrix3x3Data btMatrix3x3FloatData
#endif //BT_USE_DOUBLE_PRECISION
/**@brief The btMatrix3x3 class implements a 3x3 rotation matrix, to perform linear algebra in combination with btQuaternion, btTransform and btVector3.
* Make sure to only include a pure orthogonal matrix without scaling. */
class btMatrix3x3 {
///Data storage for the matrix, each vector is a row of the matrix
btVector3 m_el[3];
public:
/** @brief No initializaion constructor */
btMatrix3x3 () {}
// explicit btMatrix3x3(const btScalar *m) { setFromOpenGLSubMatrix(m); }
/**@brief Constructor from Quaternion */
explicit btMatrix3x3(const btQuaternion& q) { setRotation(q); }
/*
template <typename btScalar>
Matrix3x3(const btScalar& yaw, const btScalar& pitch, const btScalar& roll)
{
setEulerYPR(yaw, pitch, roll);
}
*/
/** @brief Constructor with row major formatting */
btMatrix3x3(const btScalar& xx, const btScalar& xy, const btScalar& xz,
const btScalar& yx, const btScalar& yy, const btScalar& yz,
const btScalar& zx, const btScalar& zy, const btScalar& zz)
{
setValue(xx, xy, xz,
yx, yy, yz,
zx, zy, zz);
}
/** @brief Copy constructor */
SIMD_FORCE_INLINE btMatrix3x3 (const btMatrix3x3& other)
{
m_el[0] = other.m_el[0];
m_el[1] = other.m_el[1];
m_el[2] = other.m_el[2];
}
/** @brief Assignment Operator */
SIMD_FORCE_INLINE btMatrix3x3& operator=(const btMatrix3x3& other)
{
m_el[0] = other.m_el[0];
m_el[1] = other.m_el[1];
m_el[2] = other.m_el[2];
return *this;
}
/** @brief Get a column of the matrix as a vector
* @param i Column number 0 indexed */
SIMD_FORCE_INLINE btVector3 getColumn(int i) const
{
return btVector3(m_el[0][i],m_el[1][i],m_el[2][i]);
}
/** @brief Get a row of the matrix as a vector
* @param i Row number 0 indexed */
SIMD_FORCE_INLINE const btVector3& getRow(int i) const
{
btFullAssert(0 <= i && i < 3);
return m_el[i];
}
/** @brief Get a mutable reference to a row of the matrix as a vector
* @param i Row number 0 indexed */
SIMD_FORCE_INLINE btVector3& operator[](int i)
{
btFullAssert(0 <= i && i < 3);
return m_el[i];
}
/** @brief Get a const reference to a row of the matrix as a vector
* @param i Row number 0 indexed */
SIMD_FORCE_INLINE const btVector3& operator[](int i) const
{
btFullAssert(0 <= i && i < 3);
return m_el[i];
}
/** @brief Multiply by the target matrix on the right
* @param m Rotation matrix to be applied
* Equivilant to this = this * m */
btMatrix3x3& operator*=(const btMatrix3x3& m);
/** @brief Adds by the target matrix on the right
* @param m matrix to be applied
* Equivilant to this = this + m */
btMatrix3x3& operator+=(const btMatrix3x3& m);
/** @brief Substractss by the target matrix on the right
* @param m matrix to be applied
* Equivilant to this = this - m */
btMatrix3x3& operator-=(const btMatrix3x3& m);
/** @brief Set from the rotational part of a 4x4 OpenGL matrix
* @param m A pointer to the beginning of the array of scalars*/
void setFromOpenGLSubMatrix(const btScalar *m)
{
m_el[0].setValue(m[0],m[4],m[8]);
m_el[1].setValue(m[1],m[5],m[9]);
m_el[2].setValue(m[2],m[6],m[10]);
}
/** @brief Set the values of the matrix explicitly (row major)
* @param xx Top left
* @param xy Top Middle
* @param xz Top Right
* @param yx Middle Left
* @param yy Middle Middle
* @param yz Middle Right
* @param zx Bottom Left
* @param zy Bottom Middle
* @param zz Bottom Right*/
void setValue(const btScalar& xx, const btScalar& xy, const btScalar& xz,
const btScalar& yx, const btScalar& yy, const btScalar& yz,
const btScalar& zx, const btScalar& zy, const btScalar& zz)
{
m_el[0].setValue(xx,xy,xz);
m_el[1].setValue(yx,yy,yz);
m_el[2].setValue(zx,zy,zz);
}
/** @brief Set the matrix from a quaternion
* @param q The Quaternion to match */
void setRotation(const btQuaternion& q)
{
btScalar d = q.length2();
btFullAssert(d != btScalar(0.0));
btScalar s = btScalar(2.0) / d;
btScalar xs = q.x() * s, ys = q.y() * s, zs = q.z() * s;
btScalar wx = q.w() * xs, wy = q.w() * ys, wz = q.w() * zs;
btScalar xx = q.x() * xs, xy = q.x() * ys, xz = q.x() * zs;
btScalar yy = q.y() * ys, yz = q.y() * zs, zz = q.z() * zs;
setValue(btScalar(1.0) - (yy + zz), xy - wz, xz + wy,
xy + wz, btScalar(1.0) - (xx + zz), yz - wx,
xz - wy, yz + wx, btScalar(1.0) - (xx + yy));
}
/** @brief Set the matrix from euler angles using YPR around YXZ respectively
* @param yaw Yaw about Y axis
* @param pitch Pitch about X axis
* @param roll Roll about Z axis
*/
void setEulerYPR(const btScalar& yaw, const btScalar& pitch, const btScalar& roll)
{
setEulerZYX(roll, pitch, yaw);
}
/** @brief Set the matrix from euler angles YPR around ZYX axes
* @param eulerX Roll about X axis
* @param eulerY Pitch around Y axis
* @param eulerZ Yaw aboud Z axis
*
* These angles are used to produce a rotation matrix. The euler
* angles are applied in ZYX order. I.e a vector is first rotated
* about X then Y and then Z
**/
void setEulerZYX(btScalar eulerX,btScalar eulerY,btScalar eulerZ) {
///@todo proposed to reverse this since it's labeled zyx but takes arguments xyz and it will match all other parts of the code
btScalar ci ( btCos(eulerX));
btScalar cj ( btCos(eulerY));
btScalar ch ( btCos(eulerZ));
btScalar si ( btSin(eulerX));
btScalar sj ( btSin(eulerY));
btScalar sh ( btSin(eulerZ));
btScalar cc = ci * ch;
btScalar cs = ci * sh;
btScalar sc = si * ch;
btScalar ss = si * sh;
setValue(cj * ch, sj * sc - cs, sj * cc + ss,
cj * sh, sj * ss + cc, sj * cs - sc,
-sj, cj * si, cj * ci);
}
/**@brief Set the matrix to the identity */
void setIdentity()
{
setValue(btScalar(1.0), btScalar(0.0), btScalar(0.0),
btScalar(0.0), btScalar(1.0), btScalar(0.0),
btScalar(0.0), btScalar(0.0), btScalar(1.0));
}
static const btMatrix3x3& getIdentity()
{
static const btMatrix3x3 identityMatrix(btScalar(1.0), btScalar(0.0), btScalar(0.0),
btScalar(0.0), btScalar(1.0), btScalar(0.0),
btScalar(0.0), btScalar(0.0), btScalar(1.0));
return identityMatrix;
}
/**@brief Fill the rotational part of an OpenGL matrix and clear the shear/perspective
* @param m The array to be filled */
void getOpenGLSubMatrix(btScalar *m) const
{
m[0] = btScalar(m_el[0].x());
m[1] = btScalar(m_el[1].x());
m[2] = btScalar(m_el[2].x());
m[3] = btScalar(0.0);
m[4] = btScalar(m_el[0].y());
m[5] = btScalar(m_el[1].y());
m[6] = btScalar(m_el[2].y());
m[7] = btScalar(0.0);
m[8] = btScalar(m_el[0].z());
m[9] = btScalar(m_el[1].z());
m[10] = btScalar(m_el[2].z());
m[11] = btScalar(0.0);
}
/**@brief Get the matrix represented as a quaternion
* @param q The quaternion which will be set */
void getRotation(btQuaternion& q) const
{
btScalar trace = m_el[0].x() + m_el[1].y() + m_el[2].z();
btScalar temp[4];
if (trace > btScalar(0.0))
{
btScalar s = btSqrt(trace + btScalar(1.0));
temp[3]=(s * btScalar(0.5));
s = btScalar(0.5) / s;
temp[0]=((m_el[2].y() - m_el[1].z()) * s);
temp[1]=((m_el[0].z() - m_el[2].x()) * s);
temp[2]=((m_el[1].x() - m_el[0].y()) * s);
}
else
{
int i = m_el[0].x() < m_el[1].y() ?
(m_el[1].y() < m_el[2].z() ? 2 : 1) :
(m_el[0].x() < m_el[2].z() ? 2 : 0);
int j = (i + 1) % 3;
int k = (i + 2) % 3;
btScalar s = btSqrt(m_el[i][i] - m_el[j][j] - m_el[k][k] + btScalar(1.0));
temp[i] = s * btScalar(0.5);
s = btScalar(0.5) / s;
temp[3] = (m_el[k][j] - m_el[j][k]) * s;
temp[j] = (m_el[j][i] + m_el[i][j]) * s;
temp[k] = (m_el[k][i] + m_el[i][k]) * s;
}
q.setValue(temp[0],temp[1],temp[2],temp[3]);
}
/**@brief Get the matrix represented as euler angles around YXZ, roundtrip with setEulerYPR
* @param yaw Yaw around Y axis
* @param pitch Pitch around X axis
* @param roll around Z axis */
void getEulerYPR(btScalar& yaw, btScalar& pitch, btScalar& roll) const
{
// first use the normal calculus
yaw = btScalar(btAtan2(m_el[1].x(), m_el[0].x()));
pitch = btScalar(btAsin(-m_el[2].x()));
roll = btScalar(btAtan2(m_el[2].y(), m_el[2].z()));
// on pitch = +/-HalfPI
if (btFabs(pitch)==SIMD_HALF_PI)
{
if (yaw>0)
yaw-=SIMD_PI;
else
yaw+=SIMD_PI;
if (roll>0)
roll-=SIMD_PI;
else
roll+=SIMD_PI;
}
};
/**@brief Get the matrix represented as euler angles around ZYX
* @param yaw Yaw around X axis
* @param pitch Pitch around Y axis
* @param roll around X axis
* @param solution_number Which solution of two possible solutions ( 1 or 2) are possible values*/
void getEulerZYX(btScalar& yaw, btScalar& pitch, btScalar& roll, unsigned int solution_number = 1) const
{
struct Euler
{
btScalar yaw;
btScalar pitch;
btScalar roll;
};
Euler euler_out;
Euler euler_out2; //second solution
//get the pointer to the raw data
// Check that pitch is not at a singularity
if (btFabs(m_el[2].x()) >= 1)
{
euler_out.yaw = 0;
euler_out2.yaw = 0;
// From difference of angles formula
btScalar delta = btAtan2(m_el[0].x(),m_el[0].z());
if (m_el[2].x() > 0) //gimbal locked up
{
euler_out.pitch = SIMD_PI / btScalar(2.0);
euler_out2.pitch = SIMD_PI / btScalar(2.0);
euler_out.roll = euler_out.pitch + delta;
euler_out2.roll = euler_out.pitch + delta;
}
else // gimbal locked down
{
euler_out.pitch = -SIMD_PI / btScalar(2.0);
euler_out2.pitch = -SIMD_PI / btScalar(2.0);
euler_out.roll = -euler_out.pitch + delta;
euler_out2.roll = -euler_out.pitch + delta;
}
}
else
{
euler_out.pitch = - btAsin(m_el[2].x());
euler_out2.pitch = SIMD_PI - euler_out.pitch;
euler_out.roll = btAtan2(m_el[2].y()/btCos(euler_out.pitch),
m_el[2].z()/btCos(euler_out.pitch));
euler_out2.roll = btAtan2(m_el[2].y()/btCos(euler_out2.pitch),
m_el[2].z()/btCos(euler_out2.pitch));
euler_out.yaw = btAtan2(m_el[1].x()/btCos(euler_out.pitch),
m_el[0].x()/btCos(euler_out.pitch));
euler_out2.yaw = btAtan2(m_el[1].x()/btCos(euler_out2.pitch),
m_el[0].x()/btCos(euler_out2.pitch));
}
if (solution_number == 1)
{
yaw = euler_out.yaw;
pitch = euler_out.pitch;
roll = euler_out.roll;
}
else
{
yaw = euler_out2.yaw;
pitch = euler_out2.pitch;
roll = euler_out2.roll;
}
}
/**@brief Create a scaled copy of the matrix
* @param s Scaling vector The elements of the vector will scale each column */
btMatrix3x3 scaled(const btVector3& s) const
{
return btMatrix3x3(m_el[0].x() * s.x(), m_el[0].y() * s.y(), m_el[0].z() * s.z(),
m_el[1].x() * s.x(), m_el[1].y() * s.y(), m_el[1].z() * s.z(),
m_el[2].x() * s.x(), m_el[2].y() * s.y(), m_el[2].z() * s.z());
}
/**@brief Return the determinant of the matrix */
btScalar determinant() const;
/**@brief Return the adjoint of the matrix */
btMatrix3x3 adjoint() const;
/**@brief Return the matrix with all values non negative */
btMatrix3x3 absolute() const;
/**@brief Return the transpose of the matrix */
btMatrix3x3 transpose() const;
/**@brief Return the inverse of the matrix */
btMatrix3x3 inverse() const;
btMatrix3x3 transposeTimes(const btMatrix3x3& m) const;
btMatrix3x3 timesTranspose(const btMatrix3x3& m) const;
SIMD_FORCE_INLINE btScalar tdotx(const btVector3& v) const
{
return m_el[0].x() * v.x() + m_el[1].x() * v.y() + m_el[2].x() * v.z();
}
SIMD_FORCE_INLINE btScalar tdoty(const btVector3& v) const
{
return m_el[0].y() * v.x() + m_el[1].y() * v.y() + m_el[2].y() * v.z();
}
SIMD_FORCE_INLINE btScalar tdotz(const btVector3& v) const
{
return m_el[0].z() * v.x() + m_el[1].z() * v.y() + m_el[2].z() * v.z();
}
/**@brief diagonalizes this matrix by the Jacobi method.
* @param rot stores the rotation from the coordinate system in which the matrix is diagonal to the original
* coordinate system, i.e., old_this = rot * new_this * rot^T.
* @param threshold See iteration
* @param iteration The iteration stops when all off-diagonal elements are less than the threshold multiplied
* by the sum of the absolute values of the diagonal, or when maxSteps have been executed.
*
* Note that this matrix is assumed to be symmetric.
*/
void diagonalize(btMatrix3x3& rot, btScalar threshold, int maxSteps)
{
rot.setIdentity();
for (int step = maxSteps; step > 0; step--)
{
// find off-diagonal element [p][q] with largest magnitude
int p = 0;
int q = 1;
int r = 2;
btScalar max = btFabs(m_el[0][1]);
btScalar v = btFabs(m_el[0][2]);
if (v > max)
{
q = 2;
r = 1;
max = v;
}
v = btFabs(m_el[1][2]);
if (v > max)
{
p = 1;
q = 2;
r = 0;
max = v;
}
btScalar t = threshold * (btFabs(m_el[0][0]) + btFabs(m_el[1][1]) + btFabs(m_el[2][2]));
if (max <= t)
{
if (max <= SIMD_EPSILON * t)
{
return;
}
step = 1;
}
// compute Jacobi rotation J which leads to a zero for element [p][q]
btScalar mpq = m_el[p][q];
btScalar theta = (m_el[q][q] - m_el[p][p]) / (2 * mpq);
btScalar theta2 = theta * theta;
btScalar cos;
btScalar sin;
if (theta2 * theta2 < btScalar(10 / SIMD_EPSILON))
{
t = (theta >= 0) ? 1 / (theta + btSqrt(1 + theta2))
: 1 / (theta - btSqrt(1 + theta2));
cos = 1 / btSqrt(1 + t * t);
sin = cos * t;
}
else
{
// approximation for large theta-value, i.e., a nearly diagonal matrix
t = 1 / (theta * (2 + btScalar(0.5) / theta2));
cos = 1 - btScalar(0.5) * t * t;
sin = cos * t;
}
// apply rotation to matrix (this = J^T * this * J)
m_el[p][q] = m_el[q][p] = 0;
m_el[p][p] -= t * mpq;
m_el[q][q] += t * mpq;
btScalar mrp = m_el[r][p];
btScalar mrq = m_el[r][q];
m_el[r][p] = m_el[p][r] = cos * mrp - sin * mrq;
m_el[r][q] = m_el[q][r] = cos * mrq + sin * mrp;
// apply rotation to rot (rot = rot * J)
for (int i = 0; i < 3; i++)
{
btVector3& row = rot[i];
mrp = row[p];
mrq = row[q];
row[p] = cos * mrp - sin * mrq;
row[q] = cos * mrq + sin * mrp;
}
}
}
/**@brief Calculate the matrix cofactor
* @param r1 The first row to use for calculating the cofactor
* @param c1 The first column to use for calculating the cofactor
* @param r1 The second row to use for calculating the cofactor
* @param c1 The second column to use for calculating the cofactor
* See http://en.wikipedia.org/wiki/Cofactor_(linear_algebra) for more details
*/
btScalar cofac(int r1, int c1, int r2, int c2) const
{
return m_el[r1][c1] * m_el[r2][c2] - m_el[r1][c2] * m_el[r2][c1];
}
void serialize(struct btMatrix3x3Data& dataOut) const;
void serializeFloat(struct btMatrix3x3FloatData& dataOut) const;
void deSerialize(const struct btMatrix3x3Data& dataIn);
void deSerializeFloat(const struct btMatrix3x3FloatData& dataIn);
void deSerializeDouble(const struct btMatrix3x3DoubleData& dataIn);
};
SIMD_FORCE_INLINE btMatrix3x3&
btMatrix3x3::operator*=(const btMatrix3x3& m)
{
setValue(m.tdotx(m_el[0]), m.tdoty(m_el[0]), m.tdotz(m_el[0]),
m.tdotx(m_el[1]), m.tdoty(m_el[1]), m.tdotz(m_el[1]),
m.tdotx(m_el[2]), m.tdoty(m_el[2]), m.tdotz(m_el[2]));
return *this;
}
SIMD_FORCE_INLINE btMatrix3x3&
btMatrix3x3::operator+=(const btMatrix3x3& m)
{
setValue(
m_el[0][0]+m.m_el[0][0],
m_el[0][1]+m.m_el[0][1],
m_el[0][2]+m.m_el[0][2],
m_el[1][0]+m.m_el[1][0],
m_el[1][1]+m.m_el[1][1],
m_el[1][2]+m.m_el[1][2],
m_el[2][0]+m.m_el[2][0],
m_el[2][1]+m.m_el[2][1],
m_el[2][2]+m.m_el[2][2]);
return *this;
}
SIMD_FORCE_INLINE btMatrix3x3
operator*(const btMatrix3x3& m, const btScalar & k)
{
return btMatrix3x3(
m[0].x()*k,m[0].y()*k,m[0].z()*k,
m[1].x()*k,m[1].y()*k,m[1].z()*k,
m[2].x()*k,m[2].y()*k,m[2].z()*k);
}
SIMD_FORCE_INLINE btMatrix3x3
operator+(const btMatrix3x3& m1, const btMatrix3x3& m2)
{
return btMatrix3x3(
m1[0][0]+m2[0][0],
m1[0][1]+m2[0][1],
m1[0][2]+m2[0][2],
m1[1][0]+m2[1][0],
m1[1][1]+m2[1][1],
m1[1][2]+m2[1][2],
m1[2][0]+m2[2][0],
m1[2][1]+m2[2][1],
m1[2][2]+m2[2][2]);
}
SIMD_FORCE_INLINE btMatrix3x3
operator-(const btMatrix3x3& m1, const btMatrix3x3& m2)
{
return btMatrix3x3(
m1[0][0]-m2[0][0],
m1[0][1]-m2[0][1],
m1[0][2]-m2[0][2],
m1[1][0]-m2[1][0],
m1[1][1]-m2[1][1],
m1[1][2]-m2[1][2],
m1[2][0]-m2[2][0],
m1[2][1]-m2[2][1],
m1[2][2]-m2[2][2]);
}
SIMD_FORCE_INLINE btMatrix3x3&
btMatrix3x3::operator-=(const btMatrix3x3& m)
{
setValue(
m_el[0][0]-m.m_el[0][0],
m_el[0][1]-m.m_el[0][1],
m_el[0][2]-m.m_el[0][2],
m_el[1][0]-m.m_el[1][0],
m_el[1][1]-m.m_el[1][1],
m_el[1][2]-m.m_el[1][2],
m_el[2][0]-m.m_el[2][0],
m_el[2][1]-m.m_el[2][1],
m_el[2][2]-m.m_el[2][2]);
return *this;
}
SIMD_FORCE_INLINE btScalar
btMatrix3x3::determinant() const
{
return btTriple((*this)[0], (*this)[1], (*this)[2]);
}
SIMD_FORCE_INLINE btMatrix3x3
btMatrix3x3::absolute() const
{
return btMatrix3x3(
btFabs(m_el[0].x()), btFabs(m_el[0].y()), btFabs(m_el[0].z()),
btFabs(m_el[1].x()), btFabs(m_el[1].y()), btFabs(m_el[1].z()),
btFabs(m_el[2].x()), btFabs(m_el[2].y()), btFabs(m_el[2].z()));
}
SIMD_FORCE_INLINE btMatrix3x3
btMatrix3x3::transpose() const
{
return btMatrix3x3(m_el[0].x(), m_el[1].x(), m_el[2].x(),
m_el[0].y(), m_el[1].y(), m_el[2].y(),
m_el[0].z(), m_el[1].z(), m_el[2].z());
}
SIMD_FORCE_INLINE btMatrix3x3
btMatrix3x3::adjoint() const
{
return btMatrix3x3(cofac(1, 1, 2, 2), cofac(0, 2, 2, 1), cofac(0, 1, 1, 2),
cofac(1, 2, 2, 0), cofac(0, 0, 2, 2), cofac(0, 2, 1, 0),
cofac(1, 0, 2, 1), cofac(0, 1, 2, 0), cofac(0, 0, 1, 1));
}
SIMD_FORCE_INLINE btMatrix3x3
btMatrix3x3::inverse() const
{
btVector3 co(cofac(1, 1, 2, 2), cofac(1, 2, 2, 0), cofac(1, 0, 2, 1));
btScalar det = (*this)[0].dot(co);
btFullAssert(det != btScalar(0.0));
btScalar s = btScalar(1.0) / det;
return btMatrix3x3(co.x() * s, cofac(0, 2, 2, 1) * s, cofac(0, 1, 1, 2) * s,
co.y() * s, cofac(0, 0, 2, 2) * s, cofac(0, 2, 1, 0) * s,
co.z() * s, cofac(0, 1, 2, 0) * s, cofac(0, 0, 1, 1) * s);
}
SIMD_FORCE_INLINE btMatrix3x3
btMatrix3x3::transposeTimes(const btMatrix3x3& m) const
{
return btMatrix3x3(
m_el[0].x() * m[0].x() + m_el[1].x() * m[1].x() + m_el[2].x() * m[2].x(),
m_el[0].x() * m[0].y() + m_el[1].x() * m[1].y() + m_el[2].x() * m[2].y(),
m_el[0].x() * m[0].z() + m_el[1].x() * m[1].z() + m_el[2].x() * m[2].z(),
m_el[0].y() * m[0].x() + m_el[1].y() * m[1].x() + m_el[2].y() * m[2].x(),
m_el[0].y() * m[0].y() + m_el[1].y() * m[1].y() + m_el[2].y() * m[2].y(),
m_el[0].y() * m[0].z() + m_el[1].y() * m[1].z() + m_el[2].y() * m[2].z(),
m_el[0].z() * m[0].x() + m_el[1].z() * m[1].x() + m_el[2].z() * m[2].x(),
m_el[0].z() * m[0].y() + m_el[1].z() * m[1].y() + m_el[2].z() * m[2].y(),
m_el[0].z() * m[0].z() + m_el[1].z() * m[1].z() + m_el[2].z() * m[2].z());
}
SIMD_FORCE_INLINE btMatrix3x3
btMatrix3x3::timesTranspose(const btMatrix3x3& m) const
{
return btMatrix3x3(
m_el[0].dot(m[0]), m_el[0].dot(m[1]), m_el[0].dot(m[2]),
m_el[1].dot(m[0]), m_el[1].dot(m[1]), m_el[1].dot(m[2]),
m_el[2].dot(m[0]), m_el[2].dot(m[1]), m_el[2].dot(m[2]));
}
SIMD_FORCE_INLINE btVector3
operator*(const btMatrix3x3& m, const btVector3& v)
{
return btVector3(m[0].dot(v), m[1].dot(v), m[2].dot(v));
}
SIMD_FORCE_INLINE btVector3
operator*(const btVector3& v, const btMatrix3x3& m)
{
return btVector3(m.tdotx(v), m.tdoty(v), m.tdotz(v));
}
SIMD_FORCE_INLINE btMatrix3x3
operator*(const btMatrix3x3& m1, const btMatrix3x3& m2)
{
return btMatrix3x3(
m2.tdotx( m1[0]), m2.tdoty( m1[0]), m2.tdotz( m1[0]),
m2.tdotx( m1[1]), m2.tdoty( m1[1]), m2.tdotz( m1[1]),
m2.tdotx( m1[2]), m2.tdoty( m1[2]), m2.tdotz( m1[2]));
}
/*
SIMD_FORCE_INLINE btMatrix3x3 btMultTransposeLeft(const btMatrix3x3& m1, const btMatrix3x3& m2) {
return btMatrix3x3(
m1[0][0] * m2[0][0] + m1[1][0] * m2[1][0] + m1[2][0] * m2[2][0],
m1[0][0] * m2[0][1] + m1[1][0] * m2[1][1] + m1[2][0] * m2[2][1],
m1[0][0] * m2[0][2] + m1[1][0] * m2[1][2] + m1[2][0] * m2[2][2],
m1[0][1] * m2[0][0] + m1[1][1] * m2[1][0] + m1[2][1] * m2[2][0],
m1[0][1] * m2[0][1] + m1[1][1] * m2[1][1] + m1[2][1] * m2[2][1],
m1[0][1] * m2[0][2] + m1[1][1] * m2[1][2] + m1[2][1] * m2[2][2],
m1[0][2] * m2[0][0] + m1[1][2] * m2[1][0] + m1[2][2] * m2[2][0],
m1[0][2] * m2[0][1] + m1[1][2] * m2[1][1] + m1[2][2] * m2[2][1],
m1[0][2] * m2[0][2] + m1[1][2] * m2[1][2] + m1[2][2] * m2[2][2]);
}
*/
/**@brief Equality operator between two matrices
* It will test all elements are equal. */
SIMD_FORCE_INLINE bool operator==(const btMatrix3x3& m1, const btMatrix3x3& m2)
{
return ( m1[0][0] == m2[0][0] && m1[1][0] == m2[1][0] && m1[2][0] == m2[2][0] &&
m1[0][1] == m2[0][1] && m1[1][1] == m2[1][1] && m1[2][1] == m2[2][1] &&
m1[0][2] == m2[0][2] && m1[1][2] == m2[1][2] && m1[2][2] == m2[2][2] );
}
///for serialization
struct btMatrix3x3FloatData
{
btVector3FloatData m_el[3];
};
///for serialization
struct btMatrix3x3DoubleData
{
btVector3DoubleData m_el[3];
};
SIMD_FORCE_INLINE void btMatrix3x3::serialize(struct btMatrix3x3Data& dataOut) const
{
for (int i=0;i<3;i++)
m_el[i].serialize(dataOut.m_el[i]);
}
SIMD_FORCE_INLINE void btMatrix3x3::serializeFloat(struct btMatrix3x3FloatData& dataOut) const
{
for (int i=0;i<3;i++)
m_el[i].serializeFloat(dataOut.m_el[i]);
}
SIMD_FORCE_INLINE void btMatrix3x3::deSerialize(const struct btMatrix3x3Data& dataIn)
{
for (int i=0;i<3;i++)
m_el[i].deSerialize(dataIn.m_el[i]);
}
SIMD_FORCE_INLINE void btMatrix3x3::deSerializeFloat(const struct btMatrix3x3FloatData& dataIn)
{
for (int i=0;i<3;i++)
m_el[i].deSerializeFloat(dataIn.m_el[i]);
}
SIMD_FORCE_INLINE void btMatrix3x3::deSerializeDouble(const struct btMatrix3x3DoubleData& dataIn)
{
for (int i=0;i<3;i++)
m_el[i].deSerializeDouble(dataIn.m_el[i]);
}
#endif //BT_MATRIX3x3_H
| 0 | 0.931622 | 1 | 0.931622 | game-dev | MEDIA | 0.831704 | game-dev | 0.978286 | 1 | 0.978286 |
virtualglobebook/OpenGlobe | 60,776 | ThirdParty/OpenTK.1.0/Source/Compatibility/Audio/OpenAL/AL/EffectsExtension.cs | #region --- OpenTK.OpenAL License ---
/* EfxFunctions.cs
* C headers: \OpenAL 1.1 SDK\include\ "efx.h", "efx-creative.h", "Efx-Util.h"
* Spec: Effects Extension Guide.pdf (bundled with OpenAL SDK)
* Copyright (c) 2008 Christoph Brandtner and Stefanos Apostolopoulos
* See license.txt for license details
* http://www.OpenTK.net */
#endregion
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace OpenTK.Audio
{
/// <summary>
/// Provides access to the OpenAL effects extension.
/// </summary>
public partial class EffectsExtension
{
#region Helpers
#region BindEffect
/// <summary>(Helper) Selects the Effect type used by this Effect handle.</summary>
/// <param name="eid">Effect id returned from a successful call to GenEffects.</param>
/// <param name="type">Effect type.</param>
[CLSCompliant(false)]
public void BindEffect(uint eid, EfxEffectType type)
{
Imported_alEffecti(eid, EfxEffecti.EffectType, (int)type);
}
/// <summary>(Helper) Selects the Effect type used by this Effect handle.</summary>
/// <param name="eid">Effect id returned from a successful call to GenEffects.</param>
/// <param name="type">Effect type.</param>
public void BindEffect(int eid, EfxEffectType type)
{
Imported_alEffecti((uint)eid, EfxEffecti.EffectType, (int)type);
}
#endregion BindEffect
#region BindFilterToSource
/// <summary>(Helper) reroutes the output of a Source through a Filter.</summary>
/// <param name="source">A valid Source handle.</param>
/// <param name="filter">A valid Filter handle.</param>
[CLSCompliant(false)]
public void BindFilterToSource(uint source, uint filter)
{
AL.Source(source, ALSourcei.EfxDirectFilter, (int)filter);
}
/// <summary>(Helper) reroutes the output of a Source through a Filter.</summary>
/// <param name="source">A valid Source handle.</param>
/// <param name="filter">A valid Filter handle.</param>
public void BindFilterToSource(int source, int filter)
{
AL.Source((uint)source, ALSourcei.EfxDirectFilter, (int)filter);
}
#endregion BindFilterToSource
#region BindEffectToAuxiliarySlot
/// <summary>(Helper) Attaches an Effect to an Auxiliary Effect Slot.</summary>
/// <param name="auxiliaryeffectslot">The slot handle to attach the Effect to.</param>
/// <param name="effect">The Effect handle that is being attached.</param>
[CLSCompliant(false)]
public void BindEffectToAuxiliarySlot(uint auxiliaryeffectslot, uint effect)
{
AuxiliaryEffectSlot(auxiliaryeffectslot, EfxAuxiliaryi.EffectslotEffect, (int)effect);
}
/// <summary>(Helper) Attaches an Effect to an Auxiliary Effect Slot.</summary>
/// <param name="auxiliaryeffectslot">The slot handle to attach the Effect to.</param>
/// <param name="effect">The Effect handle that is being attached.</param>
public void BindEffectToAuxiliarySlot(int auxiliaryeffectslot, int effect)
{
AuxiliaryEffectSlot((uint)auxiliaryeffectslot, EfxAuxiliaryi.EffectslotEffect, (int)effect);
}
#endregion BindEffectToAuxiliarySlot
#region BindSourceToAuxiliarySlot
/// <summary>(Helper) Reroutes a Source's output into an Auxiliary Effect Slot.</summary>
/// <param name="source">The Source handle who's output is forwarded.</param>
/// <param name="slot">The Auxiliary Effect Slot handle that receives input from the Source.</param>
/// <param name="slotnumber">Every Source has only a limited number of slots it can feed buffer to. The number must stay below AlcContextAttributes.EfxMaxAuxiliarySends</param>
/// <param name="filter">Filter handle to be attached between Source ouput and Auxiliary Slot input. Use 0 or EfxFilterType.FilterNull for no filter. </param>
[CLSCompliant(false)]
public void BindSourceToAuxiliarySlot(uint source, uint slot, int slotnumber, uint filter)
{
AL.Source(source, ALSource3i.EfxAuxiliarySendFilter, (int)slot, (int)slotnumber, (int)filter);
}
/// <summary>(Helper) Reroutes a Source's output into an Auxiliary Effect Slot.</summary>
/// <param name="source">The Source handle who's output is forwarded.</param>
/// <param name="slot">The Auxiliary Effect Slot handle that receives input from the Source.</param>
/// <param name="slotnumber">Every Source has only a limited number of slots it can feed buffer to. The number must stay below AlcContextAttributes.EfxMaxAuxiliarySends</param>
/// <param name="filter">Filter handle to be attached between Source ouput and Auxiliary Slot input. Use 0 or EfxFilterType.FilterNull for no filter. </param>
public void BindSourceToAuxiliarySlot(int source, int slot, int slotnumber, int filter)
{
AL.Source((uint)source, ALSource3i.EfxAuxiliarySendFilter, (int)slot, (int)slotnumber, (int)filter);
}
#endregion BindSourceToAuxiliarySlot
#endregion Helpers
#region Effect Object
#region alGenEffects
//[CLSCompliant(false)]
unsafe private delegate void Delegate_alGenEffects(int n, [Out] uint* effects);
// typedef void (__cdecl *LPALGENEFFECTS)( ALsizei n, ALuint* effects );
//[CLSCompliant(false)]
private Delegate_alGenEffects Imported_alGenEffects;
/// <summary>The GenEffects function is used to create one or more Effect objects. An Effect object stores an effect type and a set of parameter values to control that Effect. In order to use an Effect it must be attached to an Auxiliary Effect Slot object</summary>
/// <remarks>After creation an Effect has no type (EfxEffectType.Null), so before it can be used to store a set of parameters, the application must specify what type of effect should be stored in the object, using Effect() with EfxEffecti.</remarks>
/// <param name="n">Number of Effects to be created.</param>
/// <param name="effects">Pointer addressing sufficient memory to store n Effect object identifiers.</param>
[CLSCompliant(false)]
public void GenEffects(int n, out uint effects)
{
unsafe
{
fixed (uint* ptr = &effects)
{
Imported_alGenEffects(n, ptr);
effects = *ptr;
}
}
}
/// <summary>The GenEffects function is used to create one or more Effect objects. An Effect object stores an effect type and a set of parameter values to control that Effect. In order to use an Effect it must be attached to an Auxiliary Effect Slot object</summary>
/// <remarks>After creation an Effect has no type (EfxEffectType.Null), so before it can be used to store a set of parameters, the application must specify what type of effect should be stored in the object, using Effect() with EfxEffecti.</remarks>
/// <param name="n">Number of Effects to be created.</param>
/// <param name="effects">Pointer addressing sufficient memory to store n Effect object identifiers.</param>
public void GenEffects(int n, out int effects)
{
unsafe
{
fixed (int* ptr = &effects)
{
Imported_alGenEffects(n, (uint*)ptr);
effects = *ptr;
}
}
}
/// <summary>Generates one or more effect objects.</summary>
/// <param name="n">Number of Effect object identifiers to generate.</param>
/// <remarks>
/// <para>The GenEffects function is used to create one or more Effect objects. An Effect object stores an effect type and a set of parameter values to control that Effect. In order to use an Effect it must be attached to an Auxiliary Effect Slot object.</para>
/// <para>After creation an Effect has no type (EfxEffectType.Null), so before it can be used to store a set of parameters, the application must specify what type of effect should be stored in the object, using Effect() with EfxEffecti.</para>
/// </remarks>
public int[] GenEffects(int n)
{
if (n <= 0) throw new ArgumentOutOfRangeException("n", "Must be higher than 0.");
int[] effects = new int[n];
GenEffects(n, out effects[0]);
return effects;
}
/// <summary>Generates a single effect object.</summary>
/// <returns>A handle to the generated effect object.</returns>
/// <remarks>
/// <para>The GenEffects function is used to create one or more Effect objects. An Effect object stores an effect type and a set of parameter values to control that Effect. In order to use an Effect it must be attached to an Auxiliary Effect Slot object.</para>
/// <para>After creation an Effect has no type (EfxEffectType.Null), so before it can be used to store a set of parameters, the application must specify what type of effect should be stored in the object, using Effect() with EfxEffecti.</para>
/// </remarks>
public int GenEffect()
{
int temp;
GenEffects(1, out temp);
return temp;
}
/// <summary>Generates a single effect object.</summary>
/// <param name="effect">A handle to the generated effect object.</param>
[CLSCompliant(false)]
public void GenEffect(out uint effect)
{
unsafe
{
fixed (uint* ptr = &effect)
{
Imported_alGenEffects(1, ptr);
effect = *ptr;
}
}
}
#endregion alGenEffects
#region alDeleteEffects
//[CLSCompliant(false)]
unsafe private delegate void Delegate_alDeleteEffects(int n, [In] uint* effects);
// typedef void (__cdecl *LPALDELETEEFFECTS)( ALsizei n, ALuint* effects );
//[CLSCompliant(false)]
private Delegate_alDeleteEffects Imported_alDeleteEffects;
/// <summary>The DeleteEffects function is used to delete and free resources for Effect objects previously created with GenEffects.</summary>
/// <param name="n">Number of Effects to be deleted.</param>
/// <param name="effects">Pointer to n Effect object identifiers.</param>
[CLSCompliant(false)]
public void DeleteEffects(int n, ref uint effects)
{
unsafe
{
fixed (uint* ptr = &effects)
{
Imported_alDeleteEffects(n, ptr);
}
}
}
/// <summary>The DeleteEffects function is used to delete and free resources for Effect objects previously created with GenEffects.</summary>
/// <param name="n">Number of Effects to be deleted.</param>
/// <param name="effects">Pointer to n Effect object identifiers.</param>
public void DeleteEffects(int n, ref int effects)
{
unsafe
{
fixed (int* ptr = &effects)
{
Imported_alDeleteEffects(n, (uint*)ptr);
}
}
}
/// <summary>The DeleteEffects function is used to delete and free resources for Effect objects previously created with GenEffects.</summary>
/// <param name="effects">Pointer to n Effect object identifiers.</param>
public void DeleteEffects(int[] effects)
{
if (effects == null) throw new ArgumentNullException("effects");
DeleteEffects(effects.Length, ref effects[0]);
}
/// <summary>The DeleteEffects function is used to delete and free resources for Effect objects previously created with GenEffects.</summary>
/// <param name="effects">Pointer to n Effect object identifiers.</param>
[CLSCompliant(false)]
public void DeleteEffects(uint[] effects)
{
if (effects == null) throw new ArgumentNullException("effects");
DeleteEffects(effects.Length, ref effects[0]);
}
/// <summary>This function deletes one Effect only.</summary>
/// <param name="effect">Pointer to an effect name/handle identifying the Effect Object to be deleted.</param>
public void DeleteEffect(int effect)
{
DeleteEffects(1, ref effect);
}
/// <summary>This function deletes one Effect only.</summary>
/// <param name="effect">Pointer to an effect name/handle identifying the Effect Object to be deleted.</param>
[CLSCompliant(false)]
public void DeleteEffect(ref uint effect)
{
unsafe
{
fixed (uint* ptr = &effect)
{
Imported_alDeleteEffects(1, ptr);
}
}
}
#endregion alDeleteEffects
#region alIsEffect
//[CLSCompliant(false)]
private delegate bool Delegate_alIsEffect(uint eid);
// typedef ALboolean (__cdecl *LPALISEFFECT)( ALuint eid );
//[CLSCompliant(false)]
private Delegate_alIsEffect Imported_alIsEffect;
/// <summary>The IsEffect function is used to determine if an object identifier is a valid Effect object.</summary>
/// <param name="eid">Effect identifier to validate.</param>
/// <returns>True if the identifier is a valid Effect, False otherwise.</returns>
[CLSCompliant(false)]
public bool IsEffect(uint eid)
{
return Imported_alIsEffect(eid);
}
/// <summary>The IsEffect function is used to determine if an object identifier is a valid Effect object.</summary>
/// <param name="eid">Effect identifier to validate.</param>
/// <returns>True if the identifier is a valid Effect, False otherwise.</returns>
public bool IsEffect(int eid)
{
return Imported_alIsEffect((uint)eid);
}
#endregion alIsEffect
#region alEffecti
//[CLSCompliant(false)]
private delegate void Delegate_alEffecti(uint eid, EfxEffecti param, int value);
// typedef void (__cdecl *LPALEFFECTI)( ALuint eid, ALenum param, ALint value);
//[CLSCompliant(false)]
private Delegate_alEffecti Imported_alEffecti;
/// <summary>This function is used to set integer properties on Effect objects.</summary>
/// <param name="eid">Effect object identifier.</param>
/// <param name="param">Effect property to set.</param>
/// <param name="value">Integer value.</param>
[CLSCompliant(false)]
public void Effect(uint eid, EfxEffecti param, int value)
{
Imported_alEffecti(eid, param, value);
}
/// <summary>This function is used to set integer properties on Effect objects.</summary>
/// <param name="eid">Effect object identifier.</param>
/// <param name="param">Effect property to set.</param>
/// <param name="value">Integer value.</param>
public void Effect(int eid, EfxEffecti param, int value)
{
Imported_alEffecti((uint)eid, param, value);
}
#endregion alEffecti
#region alEffectf
//[CLSCompliant(false)]
private delegate void Delegate_alEffectf(uint eid, EfxEffectf param, float value);
// typedef void (__cdecl *LPALEFFECTF)( ALuint eid, ALenum param, ALfloat value);
//[CLSCompliant(false)]
private Delegate_alEffectf Imported_alEffectf;
/// <summary>This function is used to set floating-point properties on Effect objects.</summary>
/// <param name="eid">Effect object identifier.</param>
/// <param name="param">Effect property to set.</param>
/// <param name="value">Floating-point value.</param>
[CLSCompliant(false)]
public void Effect(uint eid, EfxEffectf param, float value)
{
Imported_alEffectf(eid, param, value);
}
/// <summary>This function is used to set floating-point properties on Effect objects.</summary>
/// <param name="eid">Effect object identifier.</param>
/// <param name="param">Effect property to set.</param>
/// <param name="value">Floating-point value.</param>
public void Effect(int eid, EfxEffectf param, float value)
{
Imported_alEffectf((uint)eid, param, value);
}
#endregion alEffectf
#region alEffectfv
//[CLSCompliant(false)]
unsafe private delegate void Delegate_alEffectfv(uint eid, EfxEffect3f param, [In] float* values);
// typedef void (__cdecl *LPALEFFECTFV)( ALuint eid, ALenum param, ALfloat* values );
//[CLSCompliant(false)]
private Delegate_alEffectfv Imported_alEffectfv;
/// <summary>This function is used to set 3 floating-point properties on Effect objects.</summary>
/// <param name="eid">Effect object identifier.</param>
/// <param name="param">Effect property to set.</param>
/// <param name="values">Pointer to Math.Vector3.</param>
[CLSCompliant(false)]
public void Effect(uint eid, EfxEffect3f param, ref Vector3 values)
{
unsafe
{
fixed (float* ptr = &values.X)
{
Imported_alEffectfv(eid, param, ptr);
}
}
}
/// <summary>This function is used to set 3 floating-point properties on Effect objects.</summary>
/// <param name="eid">Effect object identifier.</param>
/// <param name="param">Effect property to set.</param>
/// <param name="values">Pointer to Math.Vector3.</param>
public void Effect(int eid, EfxEffect3f param, ref Vector3 values)
{
Effect((uint)eid, param, ref values);
}
#endregion alEffectfv
#region alGetEffecti
//[CLSCompliant(false)]
unsafe private delegate void Delegate_alGetEffecti(uint eid, EfxEffecti pname, [Out] int* value);
// typedef void (__cdecl *LPALGETEFFECTI)( ALuint eid, ALenum pname, ALint* value );
//[CLSCompliant(false)]
private Delegate_alGetEffecti Imported_alGetEffecti;
/// <summary>This function is used to retrieve integer properties from Effect objects.</summary>
/// <param name="eid">Effect object identifier.</param>
/// <param name="pname">Effect property to retrieve.</param>
/// <param name="value">Address where integer value will be stored.</param>
[CLSCompliant(false)]
public void GetEffect(uint eid, EfxEffecti pname, out int value)
{
unsafe
{
fixed (int* ptr = &value)
{
Imported_alGetEffecti(eid, pname, ptr);
}
}
}
/// <summary>This function is used to retrieve integer properties from Effect objects.</summary>
/// <param name="eid">Effect object identifier.</param>
/// <param name="pname">Effect property to retrieve.</param>
/// <param name="value">Address where integer value will be stored.</param>
public void GetEffect(int eid, EfxEffecti pname, out int value)
{
GetEffect((uint)eid, pname, out value);
}
#endregion alGetEffecti
#region alGetEffectf
//[CLSCompliant(false)]
unsafe private delegate void Delegate_alGetEffectf(uint eid, EfxEffectf pname, [Out]float* value);
// typedef void (__cdecl *LPALGETEFFECTF)( ALuint eid, ALenum pname, ALfloat* value );
//[CLSCompliant(false)]
private Delegate_alGetEffectf Imported_alGetEffectf;
/// <summary>This function is used to retrieve floating-point properties from Effect objects.</summary>
/// <param name="eid">Effect object identifier.</param>
/// <param name="pname">Effect property to retrieve.</param>
/// <param name="value">Address where floating-point value will be stored.</param>
[CLSCompliant(false)]
public void GetEffect(uint eid, EfxEffectf pname, out float value)
{
unsafe
{
fixed (float* ptr = &value)
{
Imported_alGetEffectf(eid, pname, ptr);
}
}
}
/// <summary>This function is used to retrieve floating-point properties from Effect objects.</summary>
/// <param name="eid">Effect object identifier.</param>
/// <param name="pname">Effect property to retrieve.</param>
/// <param name="value">Address where floating-point value will be stored.</param>
public void GetEffect(int eid, EfxEffectf pname, out float value)
{
GetEffect((uint)eid, pname, out value);
}
#endregion alGetEffectf
#region alGetEffectfv
//[CLSCompliant(false)]
unsafe private delegate void Delegate_alGetEffectfv(uint eid, EfxEffect3f param, [Out] float* values);
// typedef void (__cdecl *LPALGETEFFECTFV)( ALuint eid, ALenum pname, ALfloat* values );
//[CLSCompliant(false)]
private Delegate_alGetEffectfv Imported_alGetEffectfv;
/// <summary>This function is used to retrieve 3 floating-point properties from Effect objects.</summary>
/// <param name="eid">Effect object identifier.</param>
/// <param name="param">Effect property to retrieve.</param>
/// <param name="values">A Math.Vector3 to hold the values.</param>
[CLSCompliant(false)]
public void GetEffect(uint eid, EfxEffect3f param, out Vector3 values)
{
unsafe
{
fixed (float* ptr = &values.X)
{
Imported_alGetEffectfv(eid, param, ptr);
values.X = ptr[0];
values.Y = ptr[1];
values.Z = ptr[2];
}
}
}
/// <summary>This function is used to retrieve 3 floating-point properties from Effect objects.</summary>
/// <param name="eid">Effect object identifier.</param>
/// <param name="param">Effect property to retrieve.</param>
/// <param name="values">A Math.Vector3 to hold the values.</param>
public void GetEffect(int eid, EfxEffect3f param, out Vector3 values)
{
GetEffect((uint)eid, param, out values);
}
#endregion alGetEffectfv
// Not used:
// typedef void (__cdecl *LPALEFFECTIV)( ALuint eid, ALenum param, ALint* values );
// typedef void (__cdecl *LPALGETEFFECTIV)( ALuint eid, ALenum pname, ALint* values );
#endregion Effect Object
#region Filter Object
#region alGenFilters
//[CLSCompliant(false)]
unsafe private delegate void Delegate_alGenFilters(int n, [Out] uint* filters);
// typedef void (__cdecl *LPALGENFILTERS)( ALsizei n, ALuint* filters );
//[CLSCompliant(false)]
private Delegate_alGenFilters Imported_alGenFilters;
/// <summary>The GenFilters function is used to create one or more Filter objects. A Filter object stores a filter type and a set of parameter values to control that Filter. Filter objects can be attached to Sources as Direct Filters or Auxiliary Send Filters.</summary>
/// <remarks>After creation a Filter has no type (EfxFilterType.Null), so before it can be used to store a set of parameters, the application must specify what type of filter should be stored in the object, using Filter() with EfxFilteri.</remarks>
/// <param name="n">Number of Filters to be created.</param>
/// <param name="filters">Pointer addressing sufficient memory to store n Filter object identifiers.</param>
[CLSCompliant(false)]
public void GenFilters(int n, out uint filters)
{
unsafe
{
fixed (uint* ptr = &filters)
{
Imported_alGenFilters(n, ptr);
filters = *ptr;
}
}
}
/// <summary>The GenFilters function is used to create one or more Filter objects. A Filter object stores a filter type and a set of parameter values to control that Filter. Filter objects can be attached to Sources as Direct Filters or Auxiliary Send Filters.</summary>
/// <remarks>After creation a Filter has no type (EfxFilterType.Null), so before it can be used to store a set of parameters, the application must specify what type of filter should be stored in the object, using Filter() with EfxFilteri.</remarks>
/// <param name="n">Number of Filters to be created.</param>
/// <param name="filters">Pointer addressing sufficient memory to store n Filter object identifiers.</param>
public void GenFilters(int n, out int filters)
{
unsafe
{
fixed (int* ptr = &filters)
{
Imported_alGenFilters(n, (uint*)ptr);
filters = *ptr;
}
}
}
/// <summary>The GenFilters function is used to create one or more Filter objects. A Filter object stores a filter type and a set of parameter values to control that Filter. Filter objects can be attached to Sources as Direct Filters or Auxiliary Send Filters.</summary>
/// <remarks>After creation a Filter has no type (EfxFilterType.Null), so before it can be used to store a set of parameters, the application must specify what type of filter should be stored in the object, using Filter() with EfxFilteri.</remarks>
/// <param name="n">Number of Filters to be created.</param>
/// <returns>Pointer addressing sufficient memory to store n Filter object identifiers.</returns>
public int[] GenFilters(int n)
{
if (n <= 0) throw new ArgumentOutOfRangeException("n", "Must be higher than 0.");
int[] filters = new int[n];
GenFilters(filters.Length, out filters[0]);
return filters;
}
/// <summary>This function generates only one Filter.</summary>
/// <returns>Storage Int32 for the new filter name/handle.</returns>
public int GenFilter()
{
int filter;
GenFilters(1, out filter);
return filter;
}
/// <summary>This function generates only one Filter.</summary>
/// <param name="filter">Storage UInt32 for the new filter name/handle.</param>
[CLSCompliant(false)]
unsafe public void GenFilter(out uint filter)
{
unsafe
{
fixed (uint* ptr = &filter)
{
Imported_alGenFilters(1, ptr);
filter = *ptr;
}
}
}
#endregion alGenFilters
#region alDeleteFilters
//[CLSCompliant(false)]
unsafe private delegate void Delegate_alDeleteFilters(int n, [In] uint* filters);
// typedef void (__cdecl *LPALDELETEFILTERS)( ALsizei n, ALuint* filters );
//[CLSCompliant(false)]
private Delegate_alDeleteFilters Imported_alDeleteFilters;
/// <summary>The DeleteFilters function is used to delete and free resources for Filter objects previously created with GenFilters.</summary>
/// <param name="n">Number of Filters to be deleted.</param>
/// <param name="filters">Pointer to n Filter object identifiers.</param>
[CLSCompliant(false)]
public void DeleteFilters(int n, ref uint filters)
{
unsafe
{
fixed (uint* ptr = &filters)
{
Imported_alDeleteFilters(n, ptr);
}
}
}
/// <summary>The DeleteFilters function is used to delete and free resources for Filter objects previously created with GenFilters.</summary>
/// <param name="n">Number of Filters to be deleted.</param>
/// <param name="filters">Pointer to n Filter object identifiers.</param>
public void DeleteFilters(int n, ref int filters)
{
unsafe
{
fixed (int* ptr = &filters)
{
Imported_alDeleteFilters(n, (uint*)ptr);
}
}
}
/// <summary>This function deletes one Filter only.</summary>
/// <param name="filters">Pointer to an filter name/handle identifying the Filter Object to be deleted.</param>
[CLSCompliant(false)]
public void DeleteFilters(uint[] filters)
{
if (filters == null) throw new ArgumentNullException("filters");
DeleteFilters(filters.Length, ref filters[0]);
}
/// <summary>This function deletes one Filter only.</summary>
/// <param name="filters">Pointer to an filter name/handle identifying the Filter Object to be deleted.</param>
public void DeleteFilters(int[] filters)
{
if (filters == null) throw new ArgumentNullException("filters");
DeleteFilters(filters.Length, ref filters[0]);
}
/// <summary>This function deletes one Filter only.</summary>
/// <param name="filter">Pointer to an filter name/handle identifying the Filter Object to be deleted.</param>
public void DeleteFilter(int filter)
{
DeleteFilters(1, ref filter);
}
/// <summary>This function deletes one Filter only.</summary>
/// <param name="filter">Pointer to an filter name/handle identifying the Filter Object to be deleted.</param>
[CLSCompliant(false)]
public void DeleteFilter(ref uint filter)
{
unsafe
{
fixed (uint* ptr = &filter)
{
Imported_alDeleteFilters(1, ptr);
}
}
}
#endregion alDeleteFilters
#region alIsFilter
//[CLSCompliant(false)]
private delegate bool Delegate_alIsFilter(uint fid);
// typedef ALboolean (__cdecl *LPALISFILTER)( ALuint fid );
//[CLSCompliant(false)]
private Delegate_alIsFilter Imported_alIsFilter;
/// <summary>The IsFilter function is used to determine if an object identifier is a valid Filter object.</summary>
/// <param name="fid">Effect identifier to validate.</param>
/// <returns>True if the identifier is a valid Filter, False otherwise.</returns>
[CLSCompliant(false)]
public bool IsFilter(uint fid)
{
return Imported_alIsFilter(fid);
}
/// <summary>The IsFilter function is used to determine if an object identifier is a valid Filter object.</summary>
/// <param name="fid">Effect identifier to validate.</param>
/// <returns>True if the identifier is a valid Filter, False otherwise.</returns>
public bool IsFilter(int fid)
{
return Imported_alIsFilter((uint)fid);
}
#endregion alIsFilter
#region alFilteri
//[CLSCompliant(false)]
private delegate void Delegate_alFilteri(uint fid, EfxFilteri param, int value);
// typedef void (__cdecl *LPALFILTERI)( ALuint fid, ALenum param, ALint value );
//[CLSCompliant(false)]
private Delegate_alFilteri Imported_alFilteri;
/// <summary>This function is used to set integer properties on Filter objects.</summary>
/// <param name="fid">Filter object identifier.</param>
/// <param name="param">Effect property to set.</param>
/// <param name="value">Integer value.</param>
[CLSCompliant(false)]
public void Filter(uint fid, EfxFilteri param, int value)
{
Imported_alFilteri(fid, param, value);
}
/// <summary>This function is used to set integer properties on Filter objects.</summary>
/// <param name="fid">Filter object identifier.</param>
/// <param name="param">Effect property to set.</param>
/// <param name="value">Integer value.</param>
public void Filter(int fid, EfxFilteri param, int value)
{
Imported_alFilteri((uint)fid, param, value);
}
#endregion alFilteri
#region alFilterf
//[CLSCompliant(false)]
private delegate void Delegate_alFilterf(uint fid, EfxFilterf param, float value);
// typedef void (__cdecl *LPALFILTERF)( ALuint fid, ALenum param, ALfloat value);
//[CLSCompliant(false)]
private Delegate_alFilterf Imported_alFilterf;
/// <summary>This function is used to set floating-point properties on Filter objects.</summary>
/// <param name="fid">Filter object identifier.</param>
/// <param name="param">Effect property to set.</param>
/// <param name="value">Floating-point value.</param>
[CLSCompliant(false)]
public void Filter(uint fid, EfxFilterf param, float value)
{
Imported_alFilterf(fid, param, value);
}
/// <summary>This function is used to set floating-point properties on Filter objects.</summary>
/// <param name="fid">Filter object identifier.</param>
/// <param name="param">Effect property to set.</param>
/// <param name="value">Floating-point value.</param>
public void Filter(int fid, EfxFilterf param, float value)
{
Imported_alFilterf((uint)fid, param, value);
}
#endregion alFilterf
#region alGetFilteri
//[CLSCompliant(false)]
unsafe private delegate void Delegate_alGetFilteri(uint fid, EfxFilteri pname, [Out] int* value);
// typedef void (__cdecl *LPALGETFILTERI)( ALuint fid, ALenum pname, ALint* value );
//[CLSCompliant(false)]
private Delegate_alGetFilteri Imported_alGetFilteri;
/// <summary>This function is used to retrieve integer properties from Filter objects.</summary>
/// <param name="fid">Filter object identifier.</param>
/// <param name="pname">Effect property to retrieve.</param>
/// <param name="value">Address where integer value will be stored.</param>
[CLSCompliant(false)]
public void GetFilter(uint fid, EfxFilteri pname, out int value)
{
unsafe
{
fixed (int* ptr = &value)
{
Imported_alGetFilteri(fid, pname, ptr);
}
}
}
/// <summary>This function is used to retrieve integer properties from Filter objects.</summary>
/// <param name="fid">Filter object identifier.</param>
/// <param name="pname">Effect property to retrieve.</param>
/// <param name="value">Address where integer value will be stored.</param>
public void GetFilter(int fid, EfxFilteri pname, out int value)
{
GetFilter((uint)fid, pname, out value);
}
#endregion alGetFilteri
#region alGetFilterf
//[CLSCompliant(false)]
unsafe private delegate void Delegate_alGetFilterf(uint fid, EfxFilterf pname, [Out] float* value);
// typedef void (__cdecl *LPALGETFILTERF)( ALuint fid, ALenum pname, ALfloat* value );
//[CLSCompliant(false)]
private Delegate_alGetFilterf Imported_alGetFilterf;
/// <summary>This function is used to retrieve floating-point properties from Filter objects.</summary>
/// <param name="fid">Filter object identifier.</param>
/// <param name="pname">Effect property to retrieve.</param>
/// <param name="value">Address where floating-point value will be stored.</param>
[CLSCompliant(false)]
public void GetFilter(uint fid, EfxFilterf pname, out float value)
{
unsafe
{
fixed (float* ptr = &value)
{
Imported_alGetFilterf(fid, pname, ptr);
}
}
}
/// <summary>This function is used to retrieve floating-point properties from Filter objects.</summary>
/// <param name="fid">Filter object identifier.</param>
/// <param name="pname">Effect property to retrieve.</param>
/// <param name="value">Address where floating-point value will be stored.</param>
public void GetFilter(int fid, EfxFilterf pname, out float value)
{
GetFilter((uint)fid, pname, out value);
}
#endregion alGetFilterf
// Not used:
// typedef void (__cdecl *LPALFILTERIV)( ALuint fid, ALenum param, ALint* values );
// typedef void (__cdecl *LPALFILTERFV)( ALuint fid, ALenum param, ALfloat* values );
// typedef void (__cdecl *LPALGETFILTERIV)( ALuint fid, ALenum pname, ALint* values );
// typedef void (__cdecl *LPALGETFILTERFV)( ALuint fid, ALenum pname, ALfloat* values );
#endregion Filter Object
#region Auxiliary Effect Slot Object
#region alGenAuxiliaryEffectSlots
//[CLSCompliant(false)]
unsafe private delegate void Delegate_alGenAuxiliaryEffectSlots(int n, [Out] uint* slots);
// typedef void (__cdecl *LPALGENAUXILIARYEFFECTSLOTS)( ALsizei n, ALuint* slots );
//[CLSCompliant(false)]
private Delegate_alGenAuxiliaryEffectSlots Imported_alGenAuxiliaryEffectSlots;
/// <summary>The GenAuxiliaryEffectSlots function is used to create one or more Auxiliary Effect Slots. The number of slots that can be created will be dependant upon the Open AL device used.</summary>
/// <remarks>An application should check the OpenAL error state after making this call to determine if the Effect Slot was successfully created. If the function call fails then none of the requested Effect Slots are created. A good strategy for creating any OpenAL object is to use a for-loop and generate one object each loop iteration and then check for an error condition. If an error is set then the loop can be broken and the application can determine if sufficient resources are available.</remarks>
/// <param name="n">Number of Auxiliary Effect Slots to be created.</param>
/// <param name="slots">Pointer addressing sufficient memory to store n Effect Slot object identifiers.</param>
[CLSCompliant(false)]
public void GenAuxiliaryEffectSlots(int n, out uint slots)
{
unsafe
{
fixed (uint* ptr = &slots)
{
Imported_alGenAuxiliaryEffectSlots(n, ptr);
slots = *ptr;
}
}
}
/// <summary>The GenAuxiliaryEffectSlots function is used to create one or more Auxiliary Effect Slots. The number of slots that can be created will be dependant upon the Open AL device used.</summary>
/// <remarks>An application should check the OpenAL error state after making this call to determine if the Effect Slot was successfully created. If the function call fails then none of the requested Effect Slots are created. A good strategy for creating any OpenAL object is to use a for-loop and generate one object each loop iteration and then check for an error condition. If an error is set then the loop can be broken and the application can determine if sufficient resources are available.</remarks>
/// <param name="n">Number of Auxiliary Effect Slots to be created.</param>
/// <param name="slots">Pointer addressing sufficient memory to store n Effect Slot object identifiers.</param>
public void GenAuxiliaryEffectSlots(int n, out int slots)
{
unsafe
{
fixed (int* ptr = &slots)
{
Imported_alGenAuxiliaryEffectSlots(n, (uint*)ptr);
slots = *ptr;
}
}
}
/// <summary>The GenAuxiliaryEffectSlots function is used to create one or more Auxiliary Effect Slots. The number of slots that can be created will be dependant upon the Open AL device used.</summary>
/// <remarks>An application should check the OpenAL error state after making this call to determine if the Effect Slot was successfully created. If the function call fails then none of the requested Effect Slots are created. A good strategy for creating any OpenAL object is to use a for-loop and generate one object each loop iteration and then check for an error condition. If an error is set then the loop can be broken and the application can determine if sufficient resources are available.</remarks>
/// <param name="n">Number of Auxiliary Effect Slots to be created.</param>
/// <returns>Pointer addressing sufficient memory to store n Effect Slot object identifiers.</returns>
public int[] GenAuxiliaryEffectSlots(int n)
{
if (n <= 0) throw new ArgumentOutOfRangeException("n", "Must be higher than 0.");
int[] slots = new int[n];
GenAuxiliaryEffectSlots(slots.Length, out slots[0]);
return slots;
}
/// <summary>This function generates only one Auxiliary Effect Slot.</summary>
/// <returns>Storage Int32 for the new auxiliary effect slot name/handle.</returns>
public int GenAuxiliaryEffectSlot()
{
int temp;
GenAuxiliaryEffectSlots(1, out temp);
return temp;
}
/// <summary>This function generates only one Auxiliary Effect Slot.</summary>
/// <returns>Storage UInt32 for the new auxiliary effect slot name/handle.</returns>
[CLSCompliant(false)]
public void GenAuxiliaryEffectSlot(out uint slot)
{
unsafe
{
fixed (uint* ptr = &slot)
{
Imported_alGenAuxiliaryEffectSlots(1, ptr);
slot = *ptr;
}
}
}
#endregion alGenAuxiliaryEffectSlots
#region DeleteAuxiliaryEffectSlots
unsafe private delegate void Delegate_alDeleteAuxiliaryEffectSlots(int n, [In] uint* slots);
// typedef void (__cdecl *LPALDELETEAUXILIARYEFFECTSLOTS)( ALsizei n, ALuint* slots );
private Delegate_alDeleteAuxiliaryEffectSlots Imported_alDeleteAuxiliaryEffectSlots;
/// <summary>The DeleteAuxiliaryEffectSlots function is used to delete and free resources for Auxiliary Effect Slots previously created with GenAuxiliaryEffectSlots.</summary>
/// <param name="n">Number of Auxiliary Effect Slots to be deleted.</param>
/// <param name="slots">Pointer to n Effect Slot object identifiers.</param>
[CLSCompliant(false)]
public void DeleteAuxiliaryEffectSlots(int n, ref uint slots)
{
unsafe
{
fixed (uint* ptr = &slots)
{
Imported_alDeleteAuxiliaryEffectSlots(n, ptr);
}
}
}
/// <summary>The DeleteAuxiliaryEffectSlots function is used to delete and free resources for Auxiliary Effect Slots previously created with GenAuxiliaryEffectSlots.</summary>
/// <param name="n">Number of Auxiliary Effect Slots to be deleted.</param>
/// <param name="slots">Pointer to n Effect Slot object identifiers.</param>
public void DeleteAuxiliaryEffectSlots(int n, ref int slots)
{
unsafe
{
fixed (int* ptr = &slots)
{
Imported_alDeleteAuxiliaryEffectSlots(n, (uint*)ptr);
}
}
}
/// <summary>The DeleteAuxiliaryEffectSlots function is used to delete and free resources for Auxiliary Effect Slots previously created with GenAuxiliaryEffectSlots.</summary>
/// <param name="slots">Pointer to n Effect Slot object identifiers.</param>
public void DeleteAuxiliaryEffectSlots(int[] slots)
{
if (slots == null) throw new ArgumentNullException("slots");
DeleteAuxiliaryEffectSlots(slots.Length, ref slots[0]);
}
/// <summary>This function deletes one AuxiliaryEffectSlot only.</summary>
/// <param name="slots">Pointer to an auxiliary effect slot name/handle identifying the Auxiliary Effect Slot Object to be deleted.</param>
[CLSCompliant(false)]
public void DeleteAuxiliaryEffectSlots(uint[] slots)
{
if (slots == null) throw new ArgumentNullException("slots");
DeleteAuxiliaryEffectSlots(slots.Length, ref slots[0]);
}
/// <summary>This function deletes one AuxiliaryEffectSlot only.</summary>
/// <param name="slot">Pointer to an auxiliary effect slot name/handle identifying the Auxiliary Effect Slot Object to be deleted.</param>
public void DeleteAuxiliaryEffectSlot(int slot)
{
DeleteAuxiliaryEffectSlots(1, ref slot);
}
/// <summary>This function deletes one AuxiliaryEffectSlot only.</summary>
/// <param name="slot">Pointer to an auxiliary effect slot name/handle identifying the Auxiliary Effect Slot Object to be deleted.</param>
[CLSCompliant(false)]
public void DeleteAuxiliaryEffectSlot(ref uint slot)
{
unsafe
{
fixed (uint* ptr = &slot)
{
Imported_alDeleteAuxiliaryEffectSlots(1, ptr);
}
}
}
#endregion alDeleteAuxiliaryEffectSlots
#region alIsAuxiliaryEffectSlot
//[CLSCompliant(false)]
private delegate bool Delegate_alIsAuxiliaryEffectSlot(uint slot);
// typedef ALboolean (__cdecl *LPALISAUXILIARYEFFECTSLOT)( ALuint slot );
//[CLSCompliant(false)]
private Delegate_alIsAuxiliaryEffectSlot Imported_alIsAuxiliaryEffectSlot;
/// <summary>The IsAuxiliaryEffectSlot function is used to determine if an object identifier is a valid Auxiliary Effect Slot object.</summary>
/// <param name="slot">Effect Slot object identifier to validate.</param>
/// <returns>True if the identifier is a valid Auxiliary Effect Slot, False otherwise.</returns>
[CLSCompliant(false)]
public bool IsAuxiliaryEffectSlot(uint slot)
{
return Imported_alIsAuxiliaryEffectSlot(slot);
}
/// <summary>The IsAuxiliaryEffectSlot function is used to determine if an object identifier is a valid Auxiliary Effect Slot object.</summary>
/// <param name="slot">Effect Slot object identifier to validate.</param>
/// <returns>True if the identifier is a valid Auxiliary Effect Slot, False otherwise.</returns>
public bool IsAuxiliaryEffectSlot(int slot)
{
return Imported_alIsAuxiliaryEffectSlot((uint)slot);
}
#endregion alIsAuxiliaryEffectSlot
#region alAuxiliaryEffectSloti
//[CLSCompliant(false)]
private delegate void Delegate_alAuxiliaryEffectSloti(uint asid, EfxAuxiliaryi param, int value);
// typedef void (__cdecl *LPALAUXILIARYEFFECTSLOTI)( ALuint asid, ALenum param, ALint value );
//[CLSCompliant(false)]
private Delegate_alAuxiliaryEffectSloti Imported_alAuxiliaryEffectSloti;
/// <summary>This function is used to set integer properties on Auxiliary Effect Slot objects.</summary>
/// <param name="asid">Auxiliary Effect Slot object identifier.</param>
/// <param name="param">Auxiliary Effect Slot property to set.</param>
/// <param name="value">Integer value.</param>
[CLSCompliant(false)]
public void AuxiliaryEffectSlot(uint asid, EfxAuxiliaryi param, int value)
{
Imported_alAuxiliaryEffectSloti(asid, param, value);
}
/// <summary>This function is used to set integer properties on Auxiliary Effect Slot objects.</summary>
/// <param name="asid">Auxiliary Effect Slot object identifier.</param>
/// <param name="param">Auxiliary Effect Slot property to set.</param>
/// <param name="value">Integer value.</param>
public void AuxiliaryEffectSlot(int asid, EfxAuxiliaryi param, int value)
{
Imported_alAuxiliaryEffectSloti((uint)asid, param, value);
}
#endregion alAuxiliaryEffectSloti
#region alAuxiliaryEffectSlotf
//[CLSCompliant(false)]
private delegate void Delegate_alAuxiliaryEffectSlotf(uint asid, EfxAuxiliaryf param, float value);
// typedef void (__cdecl *LPALAUXILIARYEFFECTSLOTF)( ALuint asid, ALenum param, ALfloat value );
//[CLSCompliant(false)]
private Delegate_alAuxiliaryEffectSlotf Imported_alAuxiliaryEffectSlotf;
/// <summary>This function is used to set floating-point properties on Auxiliary Effect Slot objects.</summary>
/// <param name="asid">Auxiliary Effect Slot object identifier.</param>
/// <param name="param">Auxiliary Effect Slot property to set.</param>
/// <param name="value">Floating-point value.</param>
[CLSCompliant(false)]
public void AuxiliaryEffectSlot(uint asid, EfxAuxiliaryf param, float value)
{
Imported_alAuxiliaryEffectSlotf(asid, param, value);
}
/// <summary>This function is used to set floating-point properties on Auxiliary Effect Slot objects.</summary>
/// <param name="asid">Auxiliary Effect Slot object identifier.</param>
/// <param name="param">Auxiliary Effect Slot property to set.</param>
/// <param name="value">Floating-point value.</param>
public void AuxiliaryEffectSlot(int asid, EfxAuxiliaryf param, float value)
{
Imported_alAuxiliaryEffectSlotf((uint)asid, param, value);
}
#endregion alAuxiliaryEffectSlotf
#region alGetAuxiliaryEffectSloti
//[CLSCompliant(false)]
unsafe private delegate void Delegate_alGetAuxiliaryEffectSloti(uint asid, EfxAuxiliaryi pname, [Out] int* value);
// typedef void (__cdecl *LPALGETAUXILIARYEFFECTSLOTI)( ALuint asid, ALenum pname, ALint* value );
//[CLSCompliant(false)]
private Delegate_alGetAuxiliaryEffectSloti Imported_alGetAuxiliaryEffectSloti;
/// <summary>This function is used to retrieve integer properties on Auxiliary Effect Slot objects.</summary>
/// <param name="asid">Auxiliary Effect Slot object identifier.</param>
/// <param name="pname">Auxiliary Effect Slot property to retrieve.</param>
/// <param name="value">Address where integer value will be stored.</param>
[CLSCompliant(false)]
public void GetAuxiliaryEffectSlot(uint asid, EfxAuxiliaryi pname, out int value)
{
unsafe
{
fixed (int* ptr = &value)
{
Imported_alGetAuxiliaryEffectSloti(asid, pname, ptr);
}
}
}
/// <summary>This function is used to retrieve integer properties on Auxiliary Effect Slot objects.</summary>
/// <param name="asid">Auxiliary Effect Slot object identifier.</param>
/// <param name="pname">Auxiliary Effect Slot property to retrieve.</param>
/// <param name="value">Address where integer value will be stored.</param>
public void GetAuxiliaryEffectSlot(int asid, EfxAuxiliaryi pname, out int value)
{
GetAuxiliaryEffectSlot((uint)asid, pname, out value);
}
#endregion alGetAuxiliaryEffectSloti
#region alGetAuxiliaryEffectSlotf
//[CLSCompliant(false)]
unsafe private delegate void Delegate_alGetAuxiliaryEffectSlotf(uint asid, EfxAuxiliaryf pname, [Out] float* value);
// typedef void (__cdecl *LPALGETAUXILIARYEFFECTSLOTF)( ALuint asid, ALenum pname, ALfloat* value );
//[CLSCompliant(false)]
private Delegate_alGetAuxiliaryEffectSlotf Imported_alGetAuxiliaryEffectSlotf;
/// <summary>This function is used to retrieve floating properties on Auxiliary Effect Slot objects.</summary>
/// <param name="asid">Auxiliary Effect Slot object identifier.</param>
/// <param name="pname">Auxiliary Effect Slot property to retrieve.</param>
/// <param name="value">Address where floating-point value will be stored.</param>
[CLSCompliant(false)]
public void GetAuxiliaryEffectSlot(uint asid, EfxAuxiliaryf pname, out float value)
{
unsafe
{
fixed (float* ptr = &value)
{
Imported_alGetAuxiliaryEffectSlotf(asid, pname, ptr);
}
}
}
/// <summary>This function is used to retrieve floating properties on Auxiliary Effect Slot objects.</summary>
/// <param name="asid">Auxiliary Effect Slot object identifier.</param>
/// <param name="pname">Auxiliary Effect Slot property to retrieve.</param>
/// <param name="value">Address where floating-point value will be stored.</param>
public void GetAuxiliaryEffectSlot(int asid, EfxAuxiliaryf pname, out float value)
{
GetAuxiliaryEffectSlot((uint)asid, pname, out value);
}
#endregion alGetAuxiliaryEffectSlotf
// Not used:
// typedef void (__cdecl *LPALAUXILIARYEFFECTSLOTIV)( ALuint asid, ALenum param, ALint* values );
// typedef void (__cdecl *LPALAUXILIARYEFFECTSLOTFV)( ALuint asid, ALenum param, ALfloat* values );
// typedef void (__cdecl *LPALGETAUXILIARYEFFECTSLOTIV)( ALuint asid, ALenum pname, ALint* values );
// typedef void (__cdecl *LPALGETAUXILIARYEFFECTSLOTFV)( ALuint asid, ALenum pname, ALfloat* values );
#endregion Auxiliary Effect Slot Object
#region Constructor / Extension Loading
private bool _valid;
/// <summary>Returns True if the EFX Extension has been found and could be initialized.</summary>
public bool IsInitialized
{
get
{
return _valid;
}
}
/// <summary>
/// Constructs a new EffectsExtension instance.
/// </summary>
public EffectsExtension()
{
_valid = false;
if (AudioContext.CurrentContext == null)
throw new InvalidOperationException("AL.LoadAll() needs a current AudioContext.");
if (!AudioContext.CurrentContext.SupportsExtension("ALC_EXT_EFX"))
{
Debug.WriteLine("EFX Extension (ALC_EXT_EFX) is not supported(AudioContext: {0}).", AudioContext.CurrentContext.ToString());
return;
}
// Console.WriteLine("ALC_EXT_EFX found. Efx can be used.");
try
{
Imported_alGenEffects = (Delegate_alGenEffects)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGenEffects"), typeof(Delegate_alGenEffects));
Imported_alDeleteEffects = (Delegate_alDeleteEffects)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alDeleteEffects"), typeof(Delegate_alDeleteEffects));
Imported_alIsEffect = (Delegate_alIsEffect)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alIsEffect"), typeof(Delegate_alIsEffect));
Imported_alEffecti = (Delegate_alEffecti)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alEffecti"), typeof(Delegate_alEffecti));
Imported_alEffectf = (Delegate_alEffectf)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alEffectf"), typeof(Delegate_alEffectf));
Imported_alEffectfv = (Delegate_alEffectfv)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alEffectfv"), typeof(Delegate_alEffectfv));
Imported_alGetEffecti = (Delegate_alGetEffecti)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGetEffecti"), typeof(Delegate_alGetEffecti));
Imported_alGetEffectf = (Delegate_alGetEffectf)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGetEffectf"), typeof(Delegate_alGetEffectf));
Imported_alGetEffectfv = (Delegate_alGetEffectfv)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGetEffectfv"), typeof(Delegate_alGetEffectfv));
}
catch (Exception e)
{
Debug.WriteLine("Failed to marshal Effect functions. " + e.ToString());
return;
}
// Console.WriteLine("Effect functions appear to be ok.");
try
{
Imported_alGenFilters = (Delegate_alGenFilters)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGenFilters"), typeof(Delegate_alGenFilters));
Imported_alDeleteFilters = (Delegate_alDeleteFilters)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alDeleteFilters"), typeof(Delegate_alDeleteFilters));
Imported_alIsFilter = (Delegate_alIsFilter)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alIsFilter"), typeof(Delegate_alIsFilter));
Imported_alFilteri = (Delegate_alFilteri)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alFilteri"), typeof(Delegate_alFilteri));
Imported_alFilterf = (Delegate_alFilterf)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alFilterf"), typeof(Delegate_alFilterf));
Imported_alGetFilteri = (Delegate_alGetFilteri)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGetFilteri"), typeof(Delegate_alGetFilteri));
Imported_alGetFilterf = (Delegate_alGetFilterf)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGetFilterf"), typeof(Delegate_alGetFilterf));
}
catch (Exception e)
{
Debug.WriteLine("Failed to marshal Filter functions. " + e.ToString());
return;
}
// Console.WriteLine("Filter functions appear to be ok.");
try
{
Imported_alGenAuxiliaryEffectSlots = (Delegate_alGenAuxiliaryEffectSlots)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGenAuxiliaryEffectSlots"), typeof(Delegate_alGenAuxiliaryEffectSlots));
Imported_alDeleteAuxiliaryEffectSlots = (Delegate_alDeleteAuxiliaryEffectSlots)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alDeleteAuxiliaryEffectSlots"), typeof(Delegate_alDeleteAuxiliaryEffectSlots));
Imported_alIsAuxiliaryEffectSlot = (Delegate_alIsAuxiliaryEffectSlot)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alIsAuxiliaryEffectSlot"), typeof(Delegate_alIsAuxiliaryEffectSlot));
Imported_alAuxiliaryEffectSloti = (Delegate_alAuxiliaryEffectSloti)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alAuxiliaryEffectSloti"), typeof(Delegate_alAuxiliaryEffectSloti));
Imported_alAuxiliaryEffectSlotf = (Delegate_alAuxiliaryEffectSlotf)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alAuxiliaryEffectSlotf"), typeof(Delegate_alAuxiliaryEffectSlotf));
Imported_alGetAuxiliaryEffectSloti = (Delegate_alGetAuxiliaryEffectSloti)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGetAuxiliaryEffectSloti"), typeof(Delegate_alGetAuxiliaryEffectSloti));
Imported_alGetAuxiliaryEffectSlotf = (Delegate_alGetAuxiliaryEffectSlotf)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGetAuxiliaryEffectSlotf"), typeof(Delegate_alGetAuxiliaryEffectSlotf));
}
catch (Exception e)
{
Debug.WriteLine("Failed to marshal AuxiliaryEffectSlot functions. " + e.ToString());
return;
}
// Console.WriteLine("Auxiliary Effect Slot functions appear to be ok.");
// didn't return so far, everything went fine.
_valid = true;
}
#endregion Constructor / Extension Loading
}
} | 0 | 0.896338 | 1 | 0.896338 | game-dev | MEDIA | 0.232631 | game-dev | 0.676469 | 1 | 0.676469 |
k21971/EvilHack | 51,340 | src/attrib.c | /* NetHack 3.6 attrib.c $NHDT-Date: 1575245050 2019/12/02 00:04:10 $ $NHDT-Branch: NetHack-3.6 $:$NHDT-Revision: 1.66 $ */
/* Copyright 1988, 1989, 1990, 1992, M. Stephenson */
/* NetHack may be freely redistributed. See license for details. */
/* attribute modification routines. */
#include "hack.h"
#include <ctype.h>
/* part of the output on gain or loss of attribute */
static const char
*const plusattr[] = { "strong", "smart", "wise",
"agile", "tough", "charismatic" },
*const minusattr[] = { "weak", "stupid",
"foolish", "clumsy",
"fragile", "repulsive" };
/* also used by enlightenment for non-abbreviated status info */
const char
*const attrname[] = { "strength", "intelligence", "wisdom",
"dexterity", "constitution", "charisma" };
static const struct innate {
schar ulevel;
long *ability;
const char *gainstr, *losestr;
} arc_abil[] = { { 1, &(HStealth), "", "" },
{ 1, &(HFast), "", "" },
{ 10, &(HSearching), "perceptive", "unaware" },
{ 0, 0, 0, 0 } },
bar_abil[] = { { 1, &(HPoison_resistance), "", "" },
{ 7, &(HFast), "quick", "slow" },
{ 15, &(HStealth), "stealthy", "" },
{ 0, 0, 0, 0 } },
cav_abil[] = { { 7, &(HFast), "quick", "slow" },
{ 15, &(HWarning), "sensitive", "" },
{ 0, 0, 0, 0 } },
con_abil[] = { { 1, &(HSick_resistance), "", "" },
{ 7, &(HPoison_resistance), "healthy", "" },
{ 20, &(HSearching), "perceptive", "unaware" },
{ 0, 0, 0, 0 } },
dru_abil[] = { { 1, &(HStealth), "", "" },
{ 7, &(HSleep_resistance), "awake", "tired" },
{ 10, &(HSearching), "perceptive", "unaware" },
{ 14, &(HPasses_trees), "less solid", "more solid" },
{ 0, 0, 0, 0 } },
hea_abil[] = { { 3, &(HPoison_resistance), "healthy", "" },
{ 15, &(HSick_resistance), "hale", "" },
{ 0, 0, 0, 0 } },
inf_abil[] = { { 1, &(HFire_resistance), "", "" },
{ 15, &(HWarning), "sensitive", "" },
{ 20, &(HShock_resistance), "insulated", "conductive" },
{ 0, 0, 0, 0 } },
kni_abil[] = { { 7, &(HFast), "quick", "slow" }, { 0, 0, 0, 0 } },
mon_abil[] = { { 1, &(HFast), "", "" },
{ 1, &(HSleep_resistance), "", "" },
{ 1, &(HSee_invisible), "", "" },
{ 3, &(HPoison_resistance), "healthy", "" },
{ 5, &(HStealth), "stealthy", "" },
{ 7, &(HWarning), "sensitive", "" },
{ 9, &(HSearching), "perceptive", "unaware" },
{ 11, &(HFire_resistance), "cool", "warmer" },
{ 13, &(HCold_resistance), "warm", "cooler" },
{ 15, &(HShock_resistance), "insulated", "conductive" },
{ 17, &(HTeleport_control), "controlled", "uncontrolled" },
{ 20, &(HTelepat), "a strange mental acuity", "mentally dulled" },
{ 23, &(HWwalking), "unsinkable", "like you might sink" },
{ 25, &(HStone_resistance), "limber", "stiff" },
{ 27, &(HDisint_resistance), "firm", "less firm" },
{ 30, &(HSick_resistance), "hale", "" },
{ 0, 0, 0, 0 } },
pri_abil[] = { { 15, &(HWarning), "sensitive", "" },
{ 20, &(HFire_resistance), "cool", "warmer" },
{ 0, 0, 0, 0 } },
ran_abil[] = { { 1, &(HSearching), "", "" },
{ 7, &(HStealth), "stealthy", "" },
{ 15, &(HSee_invisible), "", "" },
{ 0, 0, 0, 0 } },
rog_abil[] = { { 1, &(HStealth), "", "" },
{ 10, &(HSearching), "perceptive", "unaware" },
{ 0, 0, 0, 0 } },
sam_abil[] = { { 1, &(HFast), "", "" },
{ 15, &(HStealth), "stealthy", "" },
{ 0, 0, 0, 0 } },
tou_abil[] = { { 10, &(HSearching), "perceptive", "unaware" },
{ 20, &(HPoison_resistance), "hardy", "" },
{ 0, 0, 0, 0 } },
val_abil[] = { { 1, &(HCold_resistance), "", "" },
{ 1, &(HStealth), "", "" },
{ 7, &(HFast), "quick", "slow" },
{ 0, 0, 0, 0 } },
wiz_abil[] = { { 15, &(HWarning), "sensitive", "" },
{ 17, &(HTeleport_control), "controlled", "uncontrolled" },
{ 0, 0, 0, 0 } },
/* Intrinsics conferred by race */
dwa_abil[] = { { 1, &(HInfravision), "", "" },
{ 0, 0, 0, 0 } },
elf_abil[] = { { 1, &(HInfravision), "", "" },
{ 4, &(HSleep_resistance), "awake", "tired" },
{ 9, &(HSearching), "perceptive", "unaware" },
{ 0, 0, 0, 0 } },
gno_abil[] = { { 1, &(HInfravision), "", "" },
{ 0, 0, 0, 0 } },
orc_abil[] = { { 1, &(HInfravision), "", "" },
{ 1, &(HPoison_resistance), "", "" },
{ 0, 0, 0, 0 } },
/* giants had it FROMFORM - make it FROMRACE like other races */
gia_abil[] = { { 1, &(HInfravision), "", "" },
{ 1, &(HAggravate_monster), "", "" },
{ 12, &(HRegeneration), "resilient", "less resilient" },
{ 0, 0, 0, 0 } },
hob_abil[] = { { 1, &(HFood_sense), "", "" },
{ 1, &(HHunger), "", "" },
{ 4, &(HFast), "quick", "slow" },
{ 7, &(HSearching), "perceptive", "unaware" },
{ 0, 0, 0, 0 } },
cen_abil[] = { { 1, &(HFast), "", "" },
/* use EJumping here, otherwise centaurs would only
be able to jump the same way as knights */
{ 5, &(EJumping), "light on your hooves", "weighted down" },
{ 10, &(HWarning), "sensitive", "" },
{ 0, 0, 0, 0 } },
ill_abil[] = { { 1, &(HInfravision), "", "" },
{ 1, &(HTelepat), "", "" },
{ 1, &(HPsychic_resistance), "", "" },
{ 12, &(HFlying), "lighter than air", "gravity's pull" },
{ 0, 0, 0, 0 } },
/* remove drain res and flying - they are FROMFORM.
add sick res to remain consistent with previous behavior */
dem_abil[] = { { 1, &(HInfravision), "", "" },
{ 1, &(HFire_resistance), "", "" },
{ 1, &(HPoison_resistance), "", "" },
{ 1, &(HSee_invisible), "", "" },
{ 1, &(HSick_resistance), "hale", "" },
/* also inediate */
{ 0, 0, 0, 0 } },
trt_abil[] = { { 1, &(HSwimming), "", "" },
{ 5, &(HWarning), "sensitive", "" },
{ 12, &(HRegeneration), "resilient", "less resilient" },
{ 0, 0, 0, 0 } },
dro_abil[] = { { 1, &(HUltravision), "", "" },
{ 1, &(HSleep_resistance), "", "" },
{ 5, &(HPoison_resistance), "hardy", "" },
{ 9, &(HSearching), "perceptive", "unaware" },
{ 0, 0, 0, 0 } },
dra_abil[] = { { 1, &(HInfravision), "", "" },
{ 1, &(HSick_resistance), "", "" },
{ 1, &(HCold_resistance), "", "" },
{ 1, &(HSleep_resistance), "", "" },
{ 1, &(HPoison_resistance), "", "" },
{ 1, &(HLycan_resistance), "", "" },
{ 1, &(HAggravate_monster), "", "" },
{ 1, &(HLifesaved), "", "" }, /* only a random number of times */
{ 0, 0, 0, 0 } },
vam_abil[] = { { 1, &(HInfravision), "", "" },
{ 1, &(HSick_resistance), "", "" },
{ 1, &(HCold_resistance), "", "" },
{ 1, &(HSleep_resistance), "", "" },
{ 1, &(HPoison_resistance), "", "" },
{ 1, &(HLycan_resistance), "", "" },
{ 7, &(HFlying), "lighter than air", "gravity's pull" },
{ 12, &(HRegeneration), "resilient", "less resilient" },
{ 0, 0, 0, 0 } },
hum_abil[] = { { 0, 0, 0, 0 } };
STATIC_DCL void NDECL(exerper);
STATIC_DCL void FDECL(postadjabil, (long *));
STATIC_DCL const struct innate *FDECL(role_abil, (int));
STATIC_DCL const struct innate *FDECL(check_innate_abil, (long *, long));
STATIC_DCL int FDECL(innately, (long *));
/* adjust an attribute; return TRUE if change is made, FALSE otherwise */
boolean
adjattrib(ndx, incr, msgflg)
int ndx, incr;
int msgflg; /* positive => no message, zero => message, and */
{ /* negative => conditional (msg if change made) */
int old_acurr, old_abase, old_amax, decr;
boolean abonflg;
const char *attrstr;
if (Fixed_abil || !incr)
return FALSE;
if ((ndx == A_INT || ndx == A_WIS) && uarmh && uarmh->otyp == DUNCE_CAP) {
if (msgflg == 0)
Your("cap constricts briefly, then relaxes again.");
return FALSE;
}
old_acurr = ACURR(ndx);
old_abase = ABASE(ndx);
old_amax = AMAX(ndx);
ABASE(ndx) += incr; /* when incr is negative, this reduces ABASE() */
if (incr > 0) {
if (ABASE(ndx) > AMAX(ndx)) {
AMAX(ndx) = ABASE(ndx);
if (AMAX(ndx) > ATTRMAX(ndx))
ABASE(ndx) = AMAX(ndx) = ATTRMAX(ndx);
}
attrstr = plusattr[ndx];
abonflg = (ABON(ndx) < 0);
} else { /* incr is negative */
if (ABASE(ndx) < ATTRMIN(ndx)) {
/*
* If base value has dropped so low that it is trying to be
* taken below the minimum, reduce max value (peak reached)
* instead. That means that restore ability and repeated
* applications of unicorn horn will not be able to recover
* all the lost value. As of 3.6.2, we only take away
* some (average half, possibly zero) of the excess from max
* instead of all of it, but without intervening recovery, it
* can still eventually drop to the minimum allowed. After
* that, it can't be recovered, only improved with new gains.
*
* This used to assign a new negative value to incr and then
* add it, but that could affect messages below, possibly
* making a large decrease be described as a small one.
*
* decr = rn2(-(ABASE - ATTRMIN) + 1);
*/
decr = rn2(ATTRMIN(ndx) - ABASE(ndx) + 1);
ABASE(ndx) = ATTRMIN(ndx);
AMAX(ndx) -= decr;
if (AMAX(ndx) < ATTRMIN(ndx))
AMAX(ndx) = ATTRMIN(ndx);
}
attrstr = minusattr[ndx];
abonflg = (ABON(ndx) > 0);
}
if (ACURR(ndx) == old_acurr) {
if (msgflg == 0 && flags.verbose) {
if (ABASE(ndx) == old_abase && AMAX(ndx) == old_amax) {
pline("You're %s as %s as you can get.",
abonflg ? "currently" : "already", attrstr);
} else {
/* current stayed the same but base value changed, or
base is at minimum and reduction caused max to drop */
Your("innate %s has %s.", attrname[ndx],
(incr > 0) ? "improved" : "declined");
}
}
return FALSE;
}
if (msgflg <= 0)
You_feel("%s%s!", (incr > 1 || incr < -1) ? "very " : "", attrstr);
context.botl = TRUE;
if (program_state.in_moveloop && (ndx == A_STR || ndx == A_CON))
(void) encumber_msg();
return TRUE;
}
boolean
gainstr(otmp, incr, msgflg)
struct obj *otmp;
int incr;
int msgflg;
{
int num = incr;
if ((!num) || ((Race_if(PM_GIANT) || Race_if(PM_CENTAUR)
|| Race_if(PM_TORTLE) || Race_if(PM_DRAUGR)
|| Race_if(PM_VAMPIRE))
&& (!(otmp && otmp->cursed)))) {
if (ABASE(A_STR) < 18)
num = (rn2(4) ? 1 : rnd(6));
else if (ABASE(A_STR) < STR18(85))
num = rnd(10);
else
num = 1;
if (Race_if(PM_GIANT) && (ABASE(A_STR) < STR18(100)))
num += d(2, 2);
if ((ABASE(A_STR) < STR18(100)) && (ABASE(A_STR) + num > STR18(100)))
num = STR18(100) - ABASE(A_STR);
}
return adjattrib(A_STR, (otmp && otmp->cursed) ? -num : num,
msgflg);
}
/* may kill you; cause may be poison or monster like 'a' */
void
losestr(num)
register int num;
{
int ustr = ABASE(A_STR) - num;
while (ustr < 3) {
++ustr;
--num;
if (Upolyd) {
u.mh -= 6;
u.mhmax -= 6;
} else {
u.uhp -= 6;
u.uhpmax -= 6;
}
}
(void) adjattrib(A_STR, -num, 1);
}
static const struct poison_effect_message {
void VDECL((*delivery_func), (const char *, ...));
const char *effect_msg;
} poiseff[] = {
{ You_feel, "weaker" }, /* A_STR */
{ Your, "brain is on fire" }, /* A_INT */
{ Your, "judgement is impaired" }, /* A_WIS */
{ Your, "muscles won't obey you" }, /* A_DEX */
{ You_feel, "very sick" }, /* A_CON */
{ You, "break out in hives" } /* A_CHA */
};
/* feedback for attribute loss due to poisoning */
void
poisontell(typ, exclaim)
int typ; /* which attribute */
boolean exclaim; /* emphasis */
{
void VDECL((*func), (const char *, ...)) = poiseff[typ].delivery_func;
const char *msg_txt = poiseff[typ].effect_msg;
/*
* "You feel weaker" or "you feel very sick" aren't appropriate when
* wearing or wielding something (gauntlets of power, Ogresmasher)
* which forces the attribute to maintain its maximum value.
* Phrasing for other attributes which might have fixed values
* (dunce cap) is such that we don't need message fixups for them.
*/
if (typ == A_STR && ACURR(A_STR) == STR19(25))
msg_txt = "innately weaker";
else if (typ == A_CON && ACURR(A_CON) == 25)
msg_txt = "sick inside";
(*func)("%s%c", msg_txt, exclaim ? '!' : '.');
}
/* called when an attack or trap has poisoned hero (used to be in mon.c) */
void
poisoned(reason, typ, pkiller, fatal, thrown_weapon)
const char *reason, /* controls what messages we display */
*pkiller; /* for score+log file if fatal */
int typ, fatal; /* if fatal is 0, limit damage to adjattrib */
boolean thrown_weapon; /* thrown weapons are less deadly */
{
int i, loss, kprefix = KILLED_BY_AN;
/* inform player about being poisoned unless that's already been done;
"blast" has given a "blast of poison gas" message; "poison arrow",
"poison dart", etc have implicitly given poison messages too... */
if (strcmp(reason, "blast") && !strstri(reason, "poison")) {
boolean plural = (reason[strlen(reason) - 1] == 's') ? 1 : 0;
/* avoid "The" Orcus's sting was poisoned... */
pline("%s%s %s poisoned!",
isupper((uchar) *reason) ? "" : "The ", reason,
plural ? "were" : "was");
}
if (how_resistant(POISON_RES) == 100) {
if (!strcmp(reason, "blast"))
shieldeff(u.ux, u.uy);
pline_The("poison doesn't seem to affect you.");
return;
}
/* suppress killer prefix if it already has one */
i = name_to_mon(pkiller, (int *) 0);
if (i >= LOW_PM && (mons[i].geno & G_UNIQ)) {
kprefix = KILLED_BY;
if (!type_is_pname(&mons[i]))
pkiller = the(pkiller);
} else if (!strncmpi(pkiller, "the ", 4) || !strncmpi(pkiller, "an ", 3)
|| !strncmpi(pkiller, "a ", 2)) {
/*[ does this need a plural check too? ]*/
kprefix = KILLED_BY;
}
i = !fatal ? 1 : rn2(fatal + (thrown_weapon ? 20 : 0));
if (i == 0 && typ != A_CHA) {
if (how_resistant(POISON_RES) >= 35) {
pline_The("poison was extremely toxic!");
i = resist_reduce(d(4, 6), POISON_RES);
losehp(i, pkiller, kprefix);
u.uhpmax -= (i / 2);
} else {
/* instant kill */
u.uhp = -1;
context.botl = TRUE;
pline_The("poison was deadly...");
}
} else if (i > 5) {
/* HP damage; more likely--but less severe--with missiles */
loss = resist_reduce(thrown_weapon ? rnd(6) : rn1(10, 6), POISON_RES);
losehp(loss, pkiller, kprefix); /* poison damage */
} else {
/* attribute loss; if typ is A_STR, reduction in current and
maximum HP will occur once strength has dropped down to 3 */
loss = (thrown_weapon || !fatal) ? 1 : resist_reduce(d(2, 2), POISON_RES); /* was rn1(3,3) */
/* check that a stat change was made */
if (adjattrib(typ, -loss, 1))
poisontell(typ, TRUE);
}
if (u.uhp < 1) {
killer.format = kprefix;
Strcpy(killer.name, pkiller);
/* "Poisoned by a poisoned ___" is redundant */
done(strstri(pkiller, "poison") ? DIED : POISONING);
}
(void) encumber_msg();
}
void
change_luck(n)
register schar n;
{
u.uluck += n;
if (u.uluck < 0 && u.uluck < LUCKMIN)
u.uluck = LUCKMIN;
if (u.uluck > 0 && u.uluck > LUCKMAX)
u.uluck = LUCKMAX;
}
int
stone_luck(parameter)
boolean parameter; /* So I can't think up of a good name. So sue me. --KAA */
{
struct obj *otmp;
register long bonchance = 0;
for (otmp = invent; otmp; otmp = otmp->nobj)
if (confers_luck(otmp)) {
if (otmp->cursed)
bonchance -= otmp->quan;
else if (otmp->blessed)
bonchance += otmp->quan;
else if (parameter)
bonchance += otmp->quan;
}
return sgn((int) bonchance);
}
boolean
has_luckitem()
{
struct obj *otmp;
for (otmp = invent; otmp; otmp = otmp->nobj)
if (confers_luck(otmp)) return TRUE;
return FALSE;
}
/* there has just been an inventory change affecting a luck-granting item */
void
set_moreluck()
{
if (!has_luckitem())
u.moreluck = 0;
else if (stone_luck(TRUE) >= 0)
u.moreluck = LUCKADD;
else
u.moreluck = -LUCKADD;
}
void
restore_attrib()
{
int i, equilibrium;;
/*
* Note: this gets called on every turn but ATIME() is never set
* to non-zero anywhere, and ATEMP() is only used for strength loss
* from hunger, so it doesn't actually do anything.
*/
for (i = 0; i < A_MAX; i++) { /* all temporary losses/gains */
equilibrium = (i == A_STR && u.uhs >= WEAK) ? -1 : 0;
if (ATEMP(i) != equilibrium && ATIME(i) != 0) {
if (!(--(ATIME(i)))) { /* countdown for change */
ATEMP(i) += (ATEMP(i) > 0) ? -1 : 1;
context.botl = TRUE;
if (ATEMP(i)) /* reset timer */
ATIME(i) = 100 / ACURR(A_CON);
}
}
}
if (context.botl)
(void) encumber_msg();
}
#define AVAL 50 /* tune value for exercise gains */
void
exercise(i, inc_or_dec)
int i;
boolean inc_or_dec;
{
debugpline0("Exercise:");
if (i == A_CHA)
return; /* can't exercise charisma */
/* no physical exercise while polymorphed; the body's temporary */
if (Upolyd && !(i == A_WIS || i == A_INT))
return;
if (abs(AEXE(i)) < AVAL) {
/*
* Law of diminishing returns (Part I):
*
* Gain is harder at higher attribute values.
* 79% at "3" --> 0% at "18"
* Loss is even at all levels (50%).
*
* Note: *YES* ACURR is the right one to use.
*/
AEXE(i) += (inc_or_dec) ? (rn2(19) > ACURR(i)) : -rn2(2);
debugpline3("%s, %s AEXE = %d",
(i == A_STR) ? "Str" : (i == A_WIS) ? "Wis" : (i == A_DEX)
? "Dex"
: "Con",
(inc_or_dec) ? "inc" : "dec", AEXE(i));
}
if (moves > 0 && (i == A_STR || i == A_CON))
(void) encumber_msg();
}
STATIC_OVL void
exerper()
{
if (!(moves % 10)) {
/* Hunger Checks */
unsigned hs;
boolean hungerlvl = (u.uhunger > (Race_if(PM_HOBBIT) ? 3000 : 1000));
if (!racial_vampire(&youmonst))
hs = hungerlvl
? SATIATED : (u.uhunger > 150)
? NOT_HUNGRY : (u.uhunger > 50)
? HUNGRY : (u.uhunger > 0)
? WEAK : FAINTING;
else
hs = (u.uhunger > 1000)
? SATIATED : (u.uhunger > 150)
? NOT_HUNGRY : (u.uhunger > 50)
? HUNGRY : (u.uhunger > -100)
? WEAK : (u.uhunger > -300)
? FRAIL : STARVED;
debugpline0("exerper: Hunger checks");
switch (hs) {
case SATIATED:
if (!(maybe_polyd(is_zombie(youmonst.data),
Race_if(PM_DRAUGR))
|| maybe_polyd(is_vampire(youmonst.data),
Race_if(PM_VAMPIRE))))
exercise(A_DEX, FALSE);
if (Role_if(PM_MONK))
exercise(A_WIS, FALSE);
break;
case NOT_HUNGRY:
exercise(A_CON, TRUE);
break;
case WEAK:
exercise(A_STR, FALSE);
if (Role_if(PM_MONK)) /* fasting */
exercise(A_WIS, TRUE);
break;
case FAINTING:
case FAINTED:
exercise(A_CON, FALSE);
break;
case FRAIL:
case STARVED:
exercise(A_STR, FALSE);
exercise(A_CON, FALSE);
break;
}
/* Encumbrance Checks */
debugpline0("exerper: Encumber checks");
switch (near_capacity()) {
case MOD_ENCUMBER:
exercise(A_STR, TRUE);
break;
case HVY_ENCUMBER:
exercise(A_STR, TRUE);
exercise(A_DEX, FALSE);
break;
case EXT_ENCUMBER:
exercise(A_DEX, FALSE);
exercise(A_CON, FALSE);
break;
}
}
/* status checks */
if (!(moves % 5)) {
debugpline0("exerper: Status checks");
if ((HClairvoyant & (INTRINSIC | TIMEOUT)) && !BClairvoyant)
exercise(A_WIS, TRUE);
if (HRegeneration)
exercise(A_STR, TRUE);
if (Sick || Vomiting)
exercise(A_CON, FALSE);
if (Confusion || (Hallucination && !u.uroleplay.hallu))
exercise(A_WIS, FALSE);
if ((Wounded_legs && !u.usteed) || Fumbling || HStun)
exercise(A_DEX, FALSE);
}
}
/* exercise/abuse text (must be in attribute order, not botl order);
phrased as "You must have been [][0]." or "You haven't been [][1]." */
static NEARDATA const char *const exertext[A_MAX][2] = {
{ "exercising diligently", "exercising properly" }, /* Str */
{ "studying hard", "focusing properly" }, /* Int */
{ "very observant", "paying attention" }, /* Wis */
{ "working on your reflexes", "working on reflexes lately" }, /* Dex */
{ "leading a healthy life-style", "watching your health" }, /* Con */
{ 0, 0 }, /* Cha */
};
void
exerchk()
{
int i, ax, mod_val, lolim, hilim;
/* Check out the periodic accumulations */
exerper();
if (moves >= context.next_attrib_check) {
debugpline1("exerchk: ready to test. multi = %d.", multi);
}
/* Are we ready for a test? */
if (moves >= context.next_attrib_check && !multi) {
debugpline0("exerchk: testing.");
/*
* Law of diminishing returns (Part II):
*
* The effects of "exercise" and "abuse" wear
* off over time. Even if you *don't* get an
* increase/decrease, you lose some of the
* accumulated effects.
*/
for (i = 0; i < A_MAX; ++i) {
ax = AEXE(i);
/* nothing to do here if no exercise or abuse has occurred
(Int and Cha always fall into this category) */
if (!ax)
continue; /* ok to skip nextattrib */
mod_val = sgn(ax); /* +1 or -1; used below */
/* no further effect for exercise if at max or abuse if at min;
can't exceed 18 via exercise even if actual max is higher */
lolim = ATTRMIN(i); /* usually 3; might be higher */
hilim = ATTRMAX(i); /* usually 18; maybe lower or higher */
if (hilim > 18)
hilim = 18;
if ((ax < 0) ? (ABASE(i) <= lolim) : (ABASE(i) >= hilim))
goto nextattrib;
/* can't exercise non-Wisdom while polymorphed; previous
exercise/abuse gradually wears off without impact then */
if (Upolyd && i != A_WIS)
goto nextattrib;
debugpline2("exerchk: testing %s (%d).",
(i == A_STR)
? "Str"
: (i == A_INT)
? "Int?"
: (i == A_WIS)
? "Wis"
: (i == A_DEX)
? "Dex"
: (i == A_CON)
? "Con"
: (i == A_CHA)
? "Cha?"
: "???",
ax);
/*
* Law of diminishing returns (Part III):
*
* You don't *always* gain by exercising.
* [MRS 92/10/28 - Treat Wisdom specially for balance.]
*/
if (rn2(AVAL) > ((i != A_WIS) ? (abs(ax) * 2 / 3) : abs(ax)))
goto nextattrib;
debugpline1("exerchk: changing %d.", i);
if (adjattrib(i, mod_val, -1)) {
debugpline1("exerchk: changed %d.", i);
/* if you actually changed an attrib - zero accumulation */
AEXE(i) = ax = 0;
/* then print an explanation */
You("%s %s.",
(mod_val > 0) ? "must have been" : "haven't been",
exertext[i][(mod_val > 0) ? 0 : 1]);
}
nextattrib:
/* this used to be ``AEXE(i) /= 2'' but that would produce
platform-dependent rounding/truncation for negative vals */
AEXE(i) = (abs(ax) / 2) * mod_val;
}
context.next_attrib_check += rn1(200, 800);
debugpline1("exerchk: next check at %ld.", context.next_attrib_check);
}
}
void
init_attr(np)
register int np;
{
register int i, x, tryct;
for (i = 0; i < A_MAX; i++) {
ABASE(i) = AMAX(i) = urole.attrbase[i];
/* If the minimum role stat exceeds the maximum race stat
* (e.g. Giant Barbarian: Giant has max 14 dex, B has min 15)
* reduce it. This is not an off-by-one error: it intentionally
* goes one further to give more variety (i.e. Giant Barbarians
* don't always have 14 DEX, but may also have 13.)
*/
while (ABASE(i) >= ATTRMAX(i)) {
ABASE(i)--;
AMAX(i)--;
}
ATEMP(i) = ATIME(i) = 0;
np -= ABASE(i);
}
tryct = 0;
while (np > 0 && tryct < 100) {
x = rn2(100);
for (i = 0; (i < A_MAX) && ((x -= urole.attrdist[i]) > 0); i++)
;
if (i >= A_MAX)
continue; /* impossible */
if (ABASE(i) >= ATTRMAX(i)) {
tryct++;
continue;
}
tryct = 0;
ABASE(i)++;
AMAX(i)++;
np--;
}
tryct = 0;
while (np < 0 && tryct < 100) { /* for redistribution */
x = rn2(100);
for (i = 0; (i < A_MAX) && ((x -= urole.attrdist[i]) > 0); i++)
;
if (i >= A_MAX)
continue; /* impossible */
if (ABASE(i) <= ATTRMIN(i)) {
tryct++;
continue;
}
tryct = 0;
ABASE(i)--;
AMAX(i)--;
np++;
}
}
void
redist_attr()
{
register int i, tmp;
for (i = 0; i < A_MAX; i++) {
if (i == A_INT || i == A_WIS)
continue;
/* Polymorphing doesn't change your mind */
tmp = AMAX(i);
AMAX(i) += (rn2(5) - 2);
if (AMAX(i) > ATTRMAX(i))
AMAX(i) = ATTRMAX(i);
if (AMAX(i) < ATTRMIN(i))
AMAX(i) = ATTRMIN(i);
ABASE(i) = ABASE(i) * AMAX(i) / tmp;
/* ABASE(i) > ATTRMAX(i) is impossible */
if (ABASE(i) < ATTRMIN(i))
ABASE(i) = ATTRMIN(i);
}
(void) encumber_msg();
}
STATIC_OVL
void
postadjabil(ability)
long *ability;
{
if (!ability)
return;
if (ability == &(HWarning) || ability == &(HSee_invisible)
|| (ability == &(HTelepat) && Blind))
see_monsters();
}
STATIC_OVL const struct innate *
role_abil(r)
int r;
{
const struct {
short role;
const struct innate *abil;
} roleabils[] = {
{ PM_ARCHEOLOGIST, arc_abil },
{ PM_BARBARIAN, bar_abil },
{ PM_CAVEMAN, cav_abil },
{ PM_CONVICT, con_abil},
{ PM_DRUID, dru_abil },
{ PM_HEALER, hea_abil },
{ PM_INFIDEL, inf_abil },
{ PM_KNIGHT, kni_abil },
{ PM_MONK, mon_abil },
{ PM_PRIEST, pri_abil },
{ PM_RANGER, ran_abil },
{ PM_ROGUE, rog_abil },
{ PM_SAMURAI, sam_abil },
{ PM_TOURIST, tou_abil },
{ PM_VALKYRIE, val_abil },
{ PM_WIZARD, wiz_abil },
{ 0, 0 }
};
int i;
for (i = 0; roleabils[i].abil && roleabils[i].role != r; i++)
continue;
return roleabils[i].abil;
}
STATIC_OVL const struct innate *
check_innate_abil(ability, frommask)
long *ability;
long frommask;
{
const struct innate *abil = 0;
if (frommask == FROMEXPER)
abil = role_abil(Role_switch);
else if (frommask == FROMRACE)
switch (Race_switch) {
case PM_DWARF:
abil = dwa_abil;
break;
case PM_ELF:
abil = elf_abil;
break;
case PM_GNOME:
abil = gno_abil;
break;
case PM_ORC:
abil = orc_abil;
break;
case PM_GIANT:
abil = gia_abil;
break;
case PM_HOBBIT:
abil = hob_abil;
break;
case PM_CENTAUR:
abil = cen_abil;
break;
case PM_ILLITHID:
abil = ill_abil;
break;
case PM_DEMON:
abil = dem_abil;
break;
case PM_TORTLE:
abil = trt_abil;
break;
case PM_DROW:
abil = dro_abil;
break;
case PM_DRAUGR:
abil = dra_abil;
break;
case PM_VAMPIRE:
abil = vam_abil;
break;
case PM_HUMAN:
abil = hum_abil;
break;
default:
break;
}
while (abil && abil->ability) {
if ((abil->ability == ability) && (u.ulevel >= abil->ulevel))
return abil;
abil++;
}
return (struct innate *) 0;
}
/* reasons for innate ability */
#define FROM_NONE 0
#define FROM_ROLE 1 /* from experience at level 1 */
#define FROM_RACE 2
#define FROM_INTR 3 /* intrinsically (eating some corpse or prayer reward) */
#define FROM_EXP 4 /* from experience for some level > 1 */
#define FROM_FORM 5
#define FROM_LYCN 6
/* check whether particular ability has been obtained via innate attribute */
STATIC_OVL int
innately(ability)
long *ability;
{
const struct innate *iptr;
if ((iptr = check_innate_abil(ability, FROMEXPER)) != 0)
return (iptr->ulevel == 1) ? FROM_ROLE : FROM_EXP;
if ((iptr = check_innate_abil(ability, FROMRACE)) != 0)
return FROM_RACE;
if ((*ability & FROMOUTSIDE) != 0L)
return FROM_INTR;
if ((*ability & FROMFORM) != 0L)
return FROM_FORM;
return FROM_NONE;
}
int
is_innate(propidx)
int propidx;
{
int innateness;
/* innately() would report FROM_FORM for this; caller wants specificity */
if (propidx == DRAIN_RES && u.ulycn >= LOW_PM)
return FROM_LYCN;
if (propidx == FAST && Very_fast)
return FROM_NONE; /* can't become very fast innately */
if (propidx == FLYING && (BFlying & W_ARMOR))
return FROM_NONE; /* not from form, as that is blocked */
if ((innateness = innately(&u.uprops[propidx].intrinsic)) != FROM_NONE)
return innateness;
if (propidx == JUMPING && Role_if(PM_KNIGHT)
/* knight has intrinsic jumping, but extrinsic is more versatile so
ignore innateness if equipment is going to claim responsibility */
&& !u.uprops[propidx].extrinsic)
return FROM_ROLE;
if (propidx == BLINDED && !haseyes(youmonst.data))
return FROM_FORM;
return FROM_NONE;
}
char *
from_what(propidx)
int propidx; /* special cases can have negative values */
{
static char buf[BUFSZ];
buf[0] = '\0';
/*
* Restrict the source of the attributes just to debug mode for now
*/
if (wizard) {
static NEARDATA const char because_of[] = " because of %s";
if (propidx >= 0) {
char *p;
struct obj *obj = (struct obj *) 0;
int innateness = is_innate(propidx);
/*
* Properties can be obtained from multiple sources and we
* try to pick the most significant one. Classification
* priority is not set in stone; current precedence is:
* "from the start" (from role or race at level 1),
* "from outside" (eating corpse, divine reward, blessed potion),
* "from experience" (from role or race at level 2+),
* "from current form" (while polymorphed),
* "from timed effect" (potion or spell),
* "from worn/wielded equipment" (Firebrand, elven boots, &c),
* "from carried equipment" (mainly quest artifacts).
* There are exceptions. Versatile jumping from spell or boots
* takes priority over knight's innate but limited jumping.
*/
if ((propidx == BLINDED && u.uroleplay.blind)
|| (propidx == DEAF && u.uroleplay.deaf))
Strcpy(buf, " from birth");
else if (propidx == HALLUC && u.uroleplay.hallu)
Strcpy(buf, " permanently");
else if (innateness == FROM_ROLE || innateness == FROM_RACE)
Strcpy(buf, " innately");
else if (innateness == FROM_INTR) /* [].intrinsic & FROMOUTSIDE */
Strcpy(buf, " intrinsically");
else if (innateness == FROM_EXP)
Strcpy(buf, " because of your experience");
else if (innateness == FROM_LYCN)
Strcpy(buf, " due to your lycanthropy");
else if (innateness == FROM_FORM)
Strcpy(buf, " from current creature form");
else if (propidx == FAST && Very_fast)
Sprintf(buf, because_of,
((HFast & TIMEOUT) != 0L) ? "a potion or spell"
: ((EFast & W_ARMF) != 0L && uarmf->dknown
&& objects[uarmf->otyp].oc_name_known)
? ysimple_name(uarmf) /* speed boots */
: EFast ? "worn equipment"
: something);
else if (wizard
&& (obj = what_gives(&u.uprops[propidx].extrinsic)) != 0)
Sprintf(buf, because_of, obj->oartifact
? bare_artifactname(obj)
: ysimple_name(obj));
else if (propidx == BLINDED && Blindfolded_only)
Sprintf(buf, because_of, ysimple_name(ublindf));
/* remove some verbosity and/or redundancy */
if ((p = strstri(buf, " pair of ")) != 0)
copynchars(p + 1, p + 9, BUFSZ); /* overlapping buffers ok */
else if (propidx == STRANGLED
&& (p = strstri(buf, " of strangulation")) != 0)
*p = '\0';
} else { /* negative property index */
/* if more blocking capabilities get implemented we'll need to
replace this with what_blocks() comparable to what_gives() */
switch (-propidx) {
case BLINDED:
if (ublindf
&& ublindf->oartifact == ART_EYES_OF_THE_OVERWORLD)
Sprintf(buf, because_of, bare_artifactname(ublindf));
break;
case INVIS:
if (u.uprops[INVIS].blocked & W_ARMC)
Sprintf(buf, because_of,
ysimple_name(uarmc)); /* mummy wrapping */
break;
case CLAIRVOYANT:
if (wizard && (u.uprops[CLAIRVOYANT].blocked & W_ARMH))
Sprintf(buf, because_of,
ysimple_name(uarmh)); /* cornuthaum */
break;
}
}
} /*wizard*/
return buf;
}
void
adjabil(oldlevel, newlevel)
int oldlevel, newlevel;
{
register const struct innate *abil, *rabil;
long prevabil, mask = FROMEXPER;
/* don't give resistance messages when demon crowning.
* they aren't given in normal crowning, and you can
* e.g. lose and regain warning, so you don't want
* messages about that. */
boolean verbose = !(oldlevel == 0 || newlevel == 0);
abil = role_abil(Role_switch);
switch (Race_switch) {
case PM_ELF:
rabil = elf_abil;
break;
case PM_ORC:
rabil = orc_abil;
break;
case PM_GIANT:
rabil = gia_abil;
break;
case PM_HOBBIT:
rabil = hob_abil;
break;
case PM_CENTAUR:
rabil = cen_abil;
break;
case PM_ILLITHID:
rabil = ill_abil;
break;
case PM_TORTLE:
rabil = trt_abil;
break;
case PM_DROW:
rabil = dro_abil;
break;
case PM_DRAUGR:
rabil = dra_abil;
break;
case PM_VAMPIRE:
rabil = vam_abil;
break;
case PM_DEMON:
rabil = dem_abil;
break;
case PM_HUMAN:
rabil = hum_abil;
break;
/* explicitly write these out or else infravision will be FROMFORM
(though ^x will show it as innate) */
case PM_DWARF:
rabil = dwa_abil;
break;
case PM_GNOME:
rabil = gno_abil;
break;
default:
rabil = 0;
break;
}
while (abil || rabil) {
/* Have we finished with the intrinsics list? */
if (!abil || !abil->ability) {
/* Try the race intrinsics */
if (!rabil || !rabil->ability)
break;
abil = rabil;
rabil = 0;
mask = FROMRACE;
}
prevabil = *(abil->ability);
if (!(Race_if(PM_GIANT) && (abil->ability == &HStealth))
&& !(Race_if(PM_VAMPIRE) && (abil->ability == &HFire_resistance))
&& !(Race_if(PM_DRAUGR) && (abil->ability == &HFire_resistance))
&& !(Race_if(PM_DRAUGR) && (abil->ability == &HTelepat))) {
if (oldlevel < abil->ulevel && newlevel >= abil->ulevel) {
/* Abilities gained at level 1 can never be lost
* via level loss, but can be lost by race change via
* infidel crowning. So, track separately from corpses.
*/
*(abil->ability) |= mask;
if (!(*(abil->ability) & INTRINSIC & ~HAVEPARTIAL & ~mask)
&& (!(*(abil->ability) & HAVEPARTIAL & ~mask)
|| (*(abil->ability) & TIMEOUT) < 100)
&& verbose) {
if (*(abil->gainstr))
You_feel("%s!", abil->gainstr);
}
} else if (oldlevel >= abil->ulevel && newlevel < abil->ulevel) {
*(abil->ability) &= ~mask;
if (!(*(abil->ability) & INTRINSIC & ~HAVEPARTIAL)
&& (!(*(abil->ability) & HAVEPARTIAL)
|| (*(abil->ability) & TIMEOUT) < 100)
&& verbose) {
if (*(abil->losestr))
You_feel("%s!", abil->losestr);
else if (*(abil->gainstr))
You_feel("less %s!", abil->gainstr);
}
}
}
if (prevabil != *(abil->ability)) /* it changed */
postadjabil(abil->ability);
abil++;
if (Role_if(PM_MONK) && newlevel >= 25 && Stoned)
make_stoned(0L, "You no longer seem to be petrifying.",
0, (char *) 0);
}
/* don't lose infidel skill slots when crowning. probably good to have
* the symmetry regardless. (newlevel == 0 should never happen elsewhere,
* but if it does we probably don't want lost skill slots there either). */
if (oldlevel > 0 && newlevel > 0) {
if (newlevel > oldlevel)
add_weapon_skill(newlevel - oldlevel);
else
lose_weapon_skill(oldlevel - newlevel);
}
}
int
newhp()
{
int hp, conplus, tempnum;
if (u.ulevel == 0) {
/* Initialize hit points */
hp = urole.hpadv.infix + urace.hpadv.infix;
if (urole.hpadv.inrnd > 0)
hp += rnd(urole.hpadv.inrnd);
if (urace.hpadv.inrnd > 0)
hp += rnd(urace.hpadv.inrnd);
if (moves <= 1L) { /* initial hero; skip for polyself to new man */
/* Initialize alignment stuff */
u.ualign.type = aligns[flags.initalign].value;
u.ualign.record = urole.initrecord;
}
/* no Con adjustment for initial hit points */
} else {
if (u.ulevel < urole.xlev) {
hp = urole.hpadv.lofix + urace.hpadv.lofix;
if (urole.hpadv.lornd > 0)
hp += rnd(urole.hpadv.lornd);
if (urace.hpadv.lornd > 0)
hp += rnd(urace.hpadv.lornd);
} else {
hp = urole.hpadv.hifix + urace.hpadv.hifix;
if (urole.hpadv.hirnd > 0)
hp += rnd(urole.hpadv.hirnd);
if (urace.hpadv.hirnd > 0)
hp += rnd(urace.hpadv.hirnd);
}
/* Cavemen get a random HP boost if they've remained
illiterate conduct, as well as a tiny wisdom boost.
The longer they remain illiterate, the bigger the
HP boost gets */
if (Role_if(PM_CAVEMAN)) {
tempnum = 0;
if (u.uconduct.literate < 1) {
if (u.ulevel < 3) {
/* 1st rank */
tempnum += rn1(3, 2);
} else if (u.ulevel < 10) {
/* 2nd and 3rd ranks */
tempnum += rn1(4, 3);
} else if (u.ulevel < 18) {
/* 4th and 5th ranks */
tempnum += rn1(6, 3);
} else {
/* 6th through 9th ranks */
tempnum += rn1(8, 5);
}
exercise(A_WIS, TRUE);
}
hp += tempnum;
}
if (ACURR(A_CON) <= 3)
conplus = -2;
else if (ACURR(A_CON) <= 6)
conplus = -1;
else if (ACURR(A_CON) <= 14)
conplus = 0;
else if (ACURR(A_CON) <= 16)
conplus = 1;
else if (ACURR(A_CON) == 17)
conplus = 2;
else if (ACURR(A_CON) == 18)
conplus = 3;
else
conplus = 4;
hp += conplus;
}
if (hp <= 0)
hp = 1;
if (u.ulevel < MAXULEV) {
/* remember increment; future level drain could take it away again */
u.uhpinc[u.ulevel] = (xchar) hp;
} else {
/* after level 30, throttle hit point gains from extra experience;
once max reaches 1200, further increments will be just 1 more */
char lim = 5 - u.uhpmax / 300;
lim = max(lim, 1);
if (hp > lim)
hp = lim;
}
return hp;
}
schar
acurr(x)
int x;
{
register int tmp = (u.abon.a[x] + u.atemp.a[x] + u.acurr.a[x]);
if (x == A_STR) {
if (tmp >= 125 || (uarmg && uarmg->otyp == GAUNTLETS_OF_POWER)
|| (uarmg && uarmg->oartifact == ART_HAND_OF_VECNA)
|| wielding_artifact(ART_GIANTSLAYER)
|| wielding_artifact(ART_HARBINGER)
|| wielding_artifact(ART_SWORD_OF_KAS))
return (schar) 125;
else
#ifdef WIN32_BUG
return (x = ((tmp <= 3) ? 3 : tmp));
#else
return (schar) ((tmp <= 3) ? 3 : tmp);
#endif
} else if (x == A_CHA) {
if (tmp < 18
&& (youmonst.data->mlet == S_NYMPH || u.umonnum == PM_SUCCUBUS
|| u.umonnum == PM_INCUBUS))
return (schar) 18;
if ((uwep && (uwep->oprops & ITEM_EXCEL))
|| (u.twoweap && (uswapwep->oprops & ITEM_EXCEL))) {
if (tmp > 6 && (uwep->cursed || (u.twoweap && uswapwep->cursed)))
return (schar) 6;
else if (tmp < 18 && (!uwep->blessed || (u.twoweap && !uswapwep->blessed)))
return (schar) 18;
else if (uwep->blessed || (u.twoweap && uswapwep->blessed))
return (schar) 25;
}
} else if (x == A_CON) {
if (wielding_artifact(ART_OGRESMASHER)
|| (uarms && uarms->oartifact == ART_ASHMAR)
|| (uarm && uarm->oartifact == ART_ARMOR_OF_RETRIBUTION))
return (schar) 25;
} else if (x == A_INT || x == A_WIS) {
/* yes, this may raise int/wis if player is sufficiently
* stupid. there are lower levels of cognition than "dunce".
*/
if (uarmh && uarmh->otyp == DUNCE_CAP)
return (schar) 6;
}
#ifdef WIN32_BUG
return (x = ((tmp >= 25) ? 25 : (tmp <= 3) ? 3 : tmp));
#else
return (schar) ((tmp >= 25) ? 25 : (tmp <= 3) ? 3 : tmp);
#endif
}
/* condense clumsy ACURR(A_STR) value into value that fits into game formulas
*/
schar
acurrstr()
{
register int str = ACURR(A_STR);
if (str <= 18)
return (schar) str;
if (str <= 121)
return (schar) (19 + str / 50); /* map to 19..21 */
else
return (schar) (min(str, 125) - 100); /* 22..25 */
}
/* when wearing (or taking off) an unID'd item, this routine is used
to distinguish between observable +0 result and no-visible-effect
due to an attribute not being able to exceed maximum or minimum */
boolean
extremeattr(attrindx) /* does attrindx's value match its max or min? */
int attrindx;
{
/* Fixed_abil and racial MINATTR/MAXATTR aren't relevant here */
int lolimit = 3, hilimit = 25, curval = ACURR(attrindx);
/* upper limit for Str is 25 but its value is encoded differently */
if (attrindx == A_STR) {
hilimit = STR19(25); /* 125 */
/* lower limit for Str can also be 25 */
if ((uarmg && uarmg->otyp == GAUNTLETS_OF_POWER)
|| (uarmg && uarmg->oartifact == ART_HAND_OF_VECNA)
|| wielding_artifact(ART_GIANTSLAYER)
|| wielding_artifact(ART_HARBINGER)
|| wielding_artifact(ART_SWORD_OF_KAS))
lolimit = hilimit;
} else if (attrindx == A_CON) {
if (wielding_artifact(ART_OGRESMASHER)
|| (uarms && uarms->oartifact == ART_ASHMAR)
|| (uarm && uarm->oartifact == ART_ARMOR_OF_RETRIBUTION))
lolimit = hilimit;
}
/* this exception is hypothetical; the only other worn item affecting
Int or Wis is another helmet so can't be in use at the same time */
if (attrindx == A_INT || attrindx == A_WIS) {
if (uarmh && uarmh->otyp == DUNCE_CAP)
hilimit = lolimit = 6;
}
/* are we currently at either limit? */
return (curval == lolimit || curval == hilimit) ? TRUE : FALSE;
}
/* avoid possible problems with alignment overflow, and provide a centralized
location for any future alignment limits */
void
adjalign(n)
int n;
{
int newalign = u.ualign.record + n;
int newabuse = u.ualign.abuse + n;
if (n < 0) {
if (newalign < u.ualign.record) {
u.ualign.record = newalign;
}
if (newabuse < u.ualign.abuse) {
u.ualign.abuse = newabuse;
}
} else if (newalign > u.ualign.record) {
u.ualign.record = newalign;
if (u.ualign.record > ALIGNLIM)
u.ualign.record = ALIGNLIM;
}
}
/* change hero's alignment type, possibly losing use of artifacts */
void
uchangealign(newalign, reason)
int newalign;
int reason; /* 0==conversion, 1==helm-of-OA on, 2==helm-of-OA off */
{
aligntyp oldalign = u.ualign.type;
u.ublessed = 0; /* lose divine protection */
/* You/Your/pline message with call flush_screen(), triggering bot(),
so the actual data change needs to come before the message */
context.botl = TRUE; /* status line needs updating */
if (reason == 0) {
/* conversion via altar */
livelog_printf(LL_ALIGNMENT, "permanently converted to %s",
aligns[1 - newalign].adj);
u.ualignbase[A_CURRENT] = (aligntyp) newalign;
/* worn helm of opposite alignment might block change */
if (!uarmh || uarmh->otyp != HELM_OF_OPPOSITE_ALIGNMENT)
u.ualign.type = u.ualignbase[A_CURRENT];
You("have a %ssense of a new direction.",
(u.ualign.type != oldalign) ? "sudden " : "");
} else {
/* putting on or taking off a helm of opposite alignment */
if (reason == 1) {
/* don't livelog taking it back off */
livelog_printf(LL_ALIGNMENT, "used a helm to turn %s",
aligns[1 - newalign].adj);
}
u.ualign.type = (aligntyp) newalign;
if (reason == 1)
Your("mind oscillates %s.", Hallucination ? "wildly" : "briefly");
else if (reason == 2)
Your("mind is %s.", Hallucination
? "much of a muchness"
: "back in sync with your body");
}
if (u.ualign.type != oldalign) {
u.ualign.record = 0; /* slate is wiped clean */
retouch_equipment(0);
}
}
/*attrib.c*/
| 0 | 0.930234 | 1 | 0.930234 | game-dev | MEDIA | 0.96615 | game-dev | 0.902878 | 1 | 0.902878 |
GaleMC/Gale | 2,216 | patches/server/0085-Replace-AI-goal-set-with-optimized-collection.patch | From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Martijn Muijsers <martijnmuijsers@live.nl>
Date: Wed, 30 Nov 2022 13:49:11 +0100
Subject: [PATCH] Replace AI goal set with optimized collection
License: LGPL-3.0 (https://www.gnu.org/licenses/lgpl-3.0.html)
Gale - https://galemc.org
This patch is based on the following mixin:
"me/jellysquid/mods/lithium/mixin/collections/goals/GoalSelectorMixin.java"
By: 2No2Name <2No2Name@web.de>
As part of: Lithium (https://github.com/CaffeineMC/lithium-fabric)
Licensed under: LGPL-3.0 (https://www.gnu.org/licenses/lgpl-3.0.html)
diff --git a/src/main/java/net/minecraft/world/entity/ai/goal/GoalSelector.java b/src/main/java/net/minecraft/world/entity/ai/goal/GoalSelector.java
index ce2804271bb67803c60c9121aec6c8dc0e99a1d9..86fc528551c2c90c78783d4d46a4a2c52e4efe41 100644
--- a/src/main/java/net/minecraft/world/entity/ai/goal/GoalSelector.java
+++ b/src/main/java/net/minecraft/world/entity/ai/goal/GoalSelector.java
@@ -11,6 +11,8 @@ import java.util.Set;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
+
+import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet;
import org.slf4j.Logger;
public class GoalSelector {
@@ -27,7 +29,7 @@ public class GoalSelector {
}
};
private final Map<Goal.Flag, WrappedGoal> lockedFlags = new EnumMap<>(Goal.Flag.class);
- private final Set<WrappedGoal> availableGoals = Sets.newLinkedHashSet();
+ private final Set<WrappedGoal> availableGoals = new ObjectLinkedOpenHashSet<>(); // Gale - Lithium - replace AI goal set with optimized collection
private final EnumSet<Goal.Flag> disabledFlags = EnumSet.noneOf(Goal.Flag.class); // Paper unused, but dummy to prevent plugins from crashing as hard. Theyll need to support paper in a special case if this is super important, but really doesn't seem like it would be.
private final com.destroystokyo.paper.util.set.OptimizedSmallEnumSet<net.minecraft.world.entity.ai.goal.Goal.Flag> goalTypes = new com.destroystokyo.paper.util.set.OptimizedSmallEnumSet<>(Goal.Flag.class); // Paper - remove streams from pathfindergoalselector
private int tickCount;
| 0 | 0.693971 | 1 | 0.693971 | game-dev | MEDIA | 0.951335 | game-dev | 0.799734 | 1 | 0.799734 |
lua9520/source-engine-2018-cstrike15_src | 153,706 | game/server/nav_generate.cpp | //========= Copyright � 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
// nav_generate.cpp
// Auto-generate a Navigation Mesh by sampling the current map
// Author: Michael S. Booth (mike@turtlerockstudios.com), 2003
#include "cbase.h"
#include "util_shared.h"
#include "nav_mesh.h"
#include "nav_node.h"
#include "nav_pathfind.h"
#include "viewport_panel_names.h"
//#include "terror/TerrorShared.h"
#include "fmtstr.h"
#include "usermessages.h"
#ifdef TERROR
#include "func_simpleladder.h"
#endif
// NOTE: This has to be the last file included!
#include "tier0/memdbgon.h"
enum { MAX_BLOCKED_AREAS = 256 };
static unsigned int blockedID[ MAX_BLOCKED_AREAS ];
static int blockedIDCount = 0;
static float lastMsgTime = 0.0f;
bool TraceAdjacentNode( int depth, const Vector& start, const Vector& end, trace_t *trace, float zLimit = DeathDrop );
bool StayOnFloor( trace_t *trace, float zLimit = DeathDrop );
ConVar nav_slope_limit( "nav_slope_limit", "0.7", FCVAR_CHEAT, "The ground unit normal's Z component must be greater than this for nav areas to be generated." );
ConVar nav_slope_tolerance( "nav_slope_tolerance", "0.1", FCVAR_CHEAT, "The ground unit normal's Z component must be this close to the nav area's Z component to be generated." );
ConVar nav_displacement_test( "nav_displacement_test", "10000", FCVAR_CHEAT, "Checks for nodes embedded in displacements (useful for in-development maps)" );
ConVar nav_generate_fencetops( "nav_generate_fencetops", "1", FCVAR_CHEAT, "Autogenerate nav areas on fence and obstacle tops" );
ConVar nav_generate_fixup_jump_areas( "nav_generate_fixup_jump_areas", "1", FCVAR_CHEAT, "Convert obsolete jump areas into 2-way connections" );
ConVar nav_generate_incremental_range( "nav_generate_incremental_range", "2000", FCVAR_CHEAT );
ConVar nav_generate_incremental_tolerance( "nav_generate_incremental_tolerance", "0", FCVAR_CHEAT, "Z tolerance for adding new nav areas." );
ConVar nav_area_max_size( "nav_area_max_size", "50", FCVAR_CHEAT, "Max area size created in nav generation" );
// Common bounding box for traces
Vector NavTraceMins( -0.45, -0.45, 0 );
Vector NavTraceMaxs( 0.45, 0.45, HumanCrouchHeight );
bool FindGroundForNode( Vector *pos, Vector *normal ); // find a ground Z for pos that is clear for NavTraceMins -> NavTraceMaxs
const float MaxTraversableHeight = StepHeight; // max internal obstacle height that can occur between nav nodes and safely disregarded
const float MinObstacleAreaWidth = 10.0f; // min width of a nav area we will generate on top of an obstacle
//--------------------------------------------------------------------------------------------------------------
/**
* Shortest path cost, paying attention to "blocked" areas
*/
class ApproachAreaCost
{
public:
float operator() ( CNavArea *area, CNavArea *fromArea, const CNavLadder *ladder, const CFuncElevator *elevator )
{
// check if this area is "blocked"
for( int i=0; i<blockedIDCount; ++i )
{
if (area->GetID() == blockedID[i])
{
return -1.0f;
}
}
if (fromArea == NULL)
{
// first area in path, no cost
return 0.0f;
}
else
{
// compute distance traveled along path so far
float dist;
if (ladder)
{
dist = ladder->m_length;
}
else
{
dist = (area->GetCenter() - fromArea->GetCenter()).Length();
}
float cost = dist + fromArea->GetCostSoFar();
return cost;
}
}
};
//--------------------------------------------------------------------------------------------------------------
/**
* Start at given position and find first area in given direction
*/
inline CNavArea *findFirstAreaInDirection( const Vector *start, NavDirType dir, float range, float beneathLimit, CBaseEntity *traceIgnore = NULL, Vector *closePos = NULL )
{
CNavArea *area = NULL;
Vector pos = *start;
int end = (int)((range / GenerationStepSize) + 0.5f);
for( int i=1; i<=end; i++ )
{
AddDirectionVector( &pos, dir, GenerationStepSize );
// make sure we dont look thru the wall
trace_t result;
UTIL_TraceHull( *start, pos, NavTraceMins, NavTraceMaxs, TheNavMesh->GetGenerationTraceMask(), traceIgnore, COLLISION_GROUP_NONE, &result );
if (result.fraction < 1.0f)
break;
area = TheNavMesh->GetNavArea( pos, beneathLimit );
if (area)
{
if (closePos)
{
closePos->x = pos.x;
closePos->y = pos.y;
closePos->z = area->GetZ( pos.x, pos.y );
}
break;
}
}
return area;
}
//--------------------------------------------------------------------------------------------------------------
/**
* For each ladder in the map, create a navigation representation of it.
*/
void CNavMesh::BuildLadders( void )
{
// remove any left-over ladders
DestroyLadders();
#ifdef TERROR
CFuncSimpleLadder *ladder = NULL;
while( (ladder = dynamic_cast< CFuncSimpleLadder * >(gEntList.FindEntityByClassname( ladder, "func_simpleladder" ))) != NULL )
{
Vector mins, maxs;
ladder->CollisionProp()->WorldSpaceSurroundingBounds( &mins, &maxs );
CreateLadder( mins, maxs, 0.0f );
}
#endif
}
//--------------------------------------------------------------------------------------------------------------
/**
* Create a navigation representation of a ladder.
*/
void CNavMesh::CreateLadder( const Vector& absMin, const Vector& absMax, float maxHeightAboveTopArea )
{
CNavLadder *ladder = new CNavLadder;
// compute top & bottom of ladder
ladder->m_top.x = (absMin.x + absMax.x) / 2.0f;
ladder->m_top.y = (absMin.y + absMax.y) / 2.0f;
ladder->m_top.z = absMax.z;
ladder->m_bottom.x = ladder->m_top.x;
ladder->m_bottom.y = ladder->m_top.y;
ladder->m_bottom.z = absMin.z;
// determine facing - assumes "normal" runged ladder
float xSize = absMax.x - absMin.x;
float ySize = absMax.y - absMin.y;
trace_t result;
if (xSize > ySize)
{
// ladder is facing north or south - determine which way
// "pull in" traceline from bottom and top in case ladder abuts floor and/or ceiling
Vector from = ladder->m_bottom + Vector( 0.0f, GenerationStepSize, GenerationStepSize/2 );
Vector to = ladder->m_top + Vector( 0.0f, GenerationStepSize, -GenerationStepSize/2 );
UTIL_TraceLine( from, to, GetGenerationTraceMask(), NULL, COLLISION_GROUP_NONE, &result );
if (result.fraction != 1.0f || result.startsolid)
ladder->SetDir( NORTH );
else
ladder->SetDir( SOUTH );
ladder->m_width = xSize;
}
else
{
// ladder is facing east or west - determine which way
Vector from = ladder->m_bottom + Vector( GenerationStepSize, 0.0f, GenerationStepSize/2 );
Vector to = ladder->m_top + Vector( GenerationStepSize, 0.0f, -GenerationStepSize/2 );
UTIL_TraceLine( from, to, GetGenerationTraceMask(), NULL, COLLISION_GROUP_NONE, &result );
if (result.fraction != 1.0f || result.startsolid)
ladder->SetDir( WEST );
else
ladder->SetDir( EAST );
ladder->m_width = ySize;
}
// adjust top and bottom of ladder to make sure they are reachable
// (cs_office has a crate right in front of the base of a ladder)
Vector along = ladder->m_top - ladder->m_bottom;
float length = along.NormalizeInPlace();
Vector on, out;
const float minLadderClearance = 32.0f;
// adjust bottom to bypass blockages
const float inc = 10.0f;
float t;
for( t = 0.0f; t <= length; t += inc )
{
on = ladder->m_bottom + t * along;
out = on + ladder->GetNormal() * minLadderClearance;
UTIL_TraceLine( on, out, GetGenerationTraceMask(), NULL, COLLISION_GROUP_NONE, &result );
if (result.fraction == 1.0f && !result.startsolid)
{
// found viable ladder bottom
ladder->m_bottom = on;
break;
}
}
// adjust top to bypass blockages
for( t = 0.0f; t <= length; t += inc )
{
on = ladder->m_top - t * along;
out = on + ladder->GetNormal() * minLadderClearance;
UTIL_TraceLine( on, out, GetGenerationTraceMask(), NULL, COLLISION_GROUP_NONE, &result );
if (result.fraction == 1.0f && !result.startsolid)
{
// found viable ladder top
ladder->m_top = on;
break;
}
}
ladder->m_length = (ladder->m_top - ladder->m_bottom).Length();
ladder->SetDir( ladder->GetDir() ); // now that we've adjusted the top and bottom, re-check the normal
ladder->m_bottomArea = NULL;
ladder->m_topForwardArea = NULL;
ladder->m_topLeftArea = NULL;
ladder->m_topRightArea = NULL;
ladder->m_topBehindArea = NULL;
ladder->ConnectGeneratedLadder( maxHeightAboveTopArea );
// add ladder to global list
m_ladders.AddToTail( ladder );
}
//--------------------------------------------------------------------------------------------------------------
/**
* Create a navigation representation of a ladder.
*/
void CNavMesh::CreateLadder( const Vector &top, const Vector &bottom, float width, const Vector2D &ladderDir, float maxHeightAboveTopArea )
{
CNavLadder *ladder = new CNavLadder;
ladder->m_top = top;
ladder->m_bottom = bottom;
ladder->m_width = width;
if ( fabs( ladderDir.x ) > fabs( ladderDir.y ) )
{
if ( ladderDir.x > 0.0f )
{
ladder->SetDir( EAST );
}
else
{
ladder->SetDir( WEST );
}
}
else
{
if ( ladderDir.y > 0.0f )
{
ladder->SetDir( SOUTH );
}
else
{
ladder->SetDir( NORTH );
}
}
// adjust top and bottom of ladder to make sure they are reachable
// (cs_office has a crate right in front of the base of a ladder)
Vector along = ladder->m_top - ladder->m_bottom;
float length = along.NormalizeInPlace();
Vector on, out;
const float minLadderClearance = 32.0f;
// adjust bottom to bypass blockages
const float inc = 10.0f;
float t;
trace_t result;
for( t = 0.0f; t <= length; t += inc )
{
on = ladder->m_bottom + t * along;
out = on + ladder->GetNormal() * minLadderClearance;
UTIL_TraceLine( on, out, GetGenerationTraceMask(), NULL, COLLISION_GROUP_NONE, &result );
if (result.fraction == 1.0f && !result.startsolid)
{
// found viable ladder bottom
ladder->m_bottom = on;
break;
}
}
// adjust top to bypass blockages
for( t = 0.0f; t <= length; t += inc )
{
on = ladder->m_top - t * along;
out = on + ladder->GetNormal() * minLadderClearance;
UTIL_TraceLine( on, out, GetGenerationTraceMask(), NULL, COLLISION_GROUP_NONE, &result );
if (result.fraction == 1.0f && !result.startsolid)
{
// found viable ladder top
ladder->m_top = on;
break;
}
}
ladder->m_length = (ladder->m_top - ladder->m_bottom).Length();
ladder->SetDir( ladder->GetDir() ); // now that we've adjusted the top and bottom, re-check the normal
ladder->m_bottomArea = NULL;
ladder->m_topForwardArea = NULL;
ladder->m_topLeftArea = NULL;
ladder->m_topRightArea = NULL;
ladder->m_topBehindArea = NULL;
ladder->ConnectGeneratedLadder( maxHeightAboveTopArea );
// add ladder to global list
m_ladders.AddToTail( ladder );
}
//--------------------------------------------------------------------------------------------------------------
void CNavLadder::ConnectGeneratedLadder( float maxHeightAboveTopArea )
{
const float nearLadderRange = 75.0f; // 50
//
// Find naviagtion area at bottom of ladder
//
// get approximate postion of player on ladder
Vector center = m_bottom + Vector( 0, 0, GenerationStepSize );
AddDirectionVector( ¢er, m_dir, HalfHumanWidth );
m_bottomArea = TheNavMesh->GetNearestNavArea( center, true );
if (!m_bottomArea)
{
DevMsg( "ERROR: Unconnected ladder bottom at ( %g, %g, %g )\n", m_bottom.x, m_bottom.y, m_bottom.z );
}
else
{
// store reference to ladder in the area
m_bottomArea->AddLadderUp( this );
}
//
// Find adjacent navigation areas at the top of the ladder
//
// get approximate postion of player on ladder
center = m_top + Vector( 0, 0, GenerationStepSize );
AddDirectionVector( ¢er, m_dir, HalfHumanWidth );
float beneathLimit = MIN( 120.0f, m_top.z - m_bottom.z + HalfHumanWidth );
// find "ahead" area
m_topForwardArea = findFirstAreaInDirection( ¢er, OppositeDirection( m_dir ), nearLadderRange, beneathLimit, NULL );
if (m_topForwardArea == m_bottomArea)
m_topForwardArea = NULL;
// find "left" area
m_topLeftArea = findFirstAreaInDirection( ¢er, DirectionLeft( m_dir ), nearLadderRange, beneathLimit, NULL );
if (m_topLeftArea == m_bottomArea)
m_topLeftArea = NULL;
// find "right" area
m_topRightArea = findFirstAreaInDirection( ¢er, DirectionRight( m_dir ), nearLadderRange, beneathLimit, NULL );
if (m_topRightArea == m_bottomArea)
m_topRightArea = NULL;
// find "behind" area - must look farther, since ladder is against the wall away from this area
m_topBehindArea = findFirstAreaInDirection( ¢er, m_dir, 2.0f*nearLadderRange, beneathLimit, NULL );
if (m_topBehindArea == m_bottomArea)
m_topBehindArea = NULL;
// can't include behind area, since it is not used when going up a ladder
if (!m_topForwardArea && !m_topLeftArea && !m_topRightArea)
DevMsg( "ERROR: Unconnected ladder top at ( %g, %g, %g )\n", m_top.x, m_top.y, m_top.z );
// store reference to ladder in the area(s)
if (m_topForwardArea)
m_topForwardArea->AddLadderDown( this );
if (m_topLeftArea)
m_topLeftArea->AddLadderDown( this );
if (m_topRightArea)
m_topRightArea->AddLadderDown( this );
if (m_topBehindArea)
{
m_topBehindArea->AddLadderDown( this );
Disconnect( m_topBehindArea );
}
// adjust top of ladder to highest connected area
float topZ = m_bottom.z + 5.0f;
bool topAdjusted = false;
CNavArea *topAreaList[4];
topAreaList[0] = m_topForwardArea;
topAreaList[1] = m_topLeftArea;
topAreaList[2] = m_topRightArea;
topAreaList[3] = m_topBehindArea;
for( int a=0; a<4; ++a )
{
CNavArea *topArea = topAreaList[a];
if (topArea == NULL)
continue;
Vector close;
topArea->GetClosestPointOnArea( m_top, &close );
if (topZ < close.z)
{
topZ = close.z;
topAdjusted = true;
}
}
if (topAdjusted)
{
if ( maxHeightAboveTopArea > 0.0f )
{
m_top.z = MIN( topZ + maxHeightAboveTopArea, m_top.z );
}
else
{
m_top.z = topZ; // not manually specifying a top, so snap exactly
}
}
//
// Determine whether this ladder is "dangling" or not
// "Dangling" ladders are too high to go up
//
if (m_bottomArea)
{
Vector bottomSpot;
m_bottomArea->GetClosestPointOnArea( m_bottom, &bottomSpot );
if (m_bottom.z - bottomSpot.z > HumanHeight)
{
m_bottomArea->Disconnect( this );
}
}
}
//--------------------------------------------------------------------------------------------------------
class JumpConnector
{
public:
bool operator()( CNavArea *jumpArea )
{
if ( !(jumpArea->GetAttributes() & NAV_MESH_JUMP) )
{
return true;
}
for ( int i=0; i<NUM_DIRECTIONS; ++i )
{
NavDirType incomingDir = (NavDirType)i;
NavDirType outgoingDir = OppositeDirection( incomingDir );
const NavConnectVector *incoming = jumpArea->GetIncomingConnections( incomingDir );
const NavConnectVector *from = jumpArea->GetAdjacentAreas( incomingDir );
const NavConnectVector *dest = jumpArea->GetAdjacentAreas( outgoingDir );
TryToConnect( jumpArea, incoming, dest, outgoingDir );
TryToConnect( jumpArea, from, dest, outgoingDir );
}
return true;
}
private:
struct Connection
{
CNavArea *source;
CNavArea *dest;
NavDirType direction;
};
void TryToConnect( CNavArea *jumpArea, const NavConnectVector *source, const NavConnectVector *dest, NavDirType outgoingDir )
{
FOR_EACH_VEC( (*source), sourceIt )
{
CNavArea *sourceArea = const_cast< CNavArea * >( (*source)[ sourceIt ].area );
if ( !sourceArea->IsConnected( jumpArea, outgoingDir ) )
{
continue;
}
if ( sourceArea->HasAttributes( NAV_MESH_JUMP ) )
{
NavDirType incomingDir = OppositeDirection( outgoingDir );
const NavConnectVector *in1 = sourceArea->GetIncomingConnections( incomingDir );
const NavConnectVector *in2 = sourceArea->GetAdjacentAreas( incomingDir );
TryToConnect( jumpArea, in1, dest, outgoingDir );
TryToConnect( jumpArea, in2, dest, outgoingDir );
continue;
}
TryToConnect( jumpArea, sourceArea, dest, outgoingDir );
}
}
void TryToConnect( CNavArea *jumpArea, CNavArea *sourceArea, const NavConnectVector *dest, NavDirType outgoingDir )
{
FOR_EACH_VEC( (*dest), destIt )
{
CNavArea *destArea = const_cast< CNavArea * >( (*dest)[ destIt ].area );
if ( destArea->HasAttributes( NAV_MESH_JUMP ) )
{
// Don't connect areas across 2 jump areas. This means we'll have some missing links due to sampling errors.
// This is preferable to generating incorrect links across multiple jump areas, which is far more common.
continue;
}
Vector center;
float halfWidth;
sourceArea->ComputePortal( destArea, outgoingDir, ¢er, &halfWidth );
// Don't create corner-to-corner connections
if ( halfWidth <= 0.0f )
{
continue;
}
Vector dir( vec3_origin );
AddDirectionVector( &dir, outgoingDir, 5.0f );
if ( halfWidth > 0.0f )
{
Vector sourcePos, destPos;
sourceArea->GetClosestPointOnArea( center, &sourcePos );
destArea->GetClosestPointOnArea( center, &destPos );
// No jumping up from stairs.
if ( sourceArea->HasAttributes( NAV_MESH_STAIRS ) && sourcePos.z + StepHeight < destPos.z )
{
continue;
}
if ( (sourcePos-destPos).AsVector2D().IsLengthLessThan( GenerationStepSize * 3 ) )
{
sourceArea->ConnectTo( destArea, outgoingDir );
// DevMsg( "Connected %d->%d via %d (len %f)\n",
// sourceArea->GetID(), destArea->GetID(), jumpArea->GetID(), sourcePos.DistTo( destPos ) );
}
}
}
}
};
//--------------------------------------------------------------------------------------------------------------
void CNavMesh::MarkPlayerClipAreas( void )
{
#ifdef TERROR
FOR_EACH_VEC( TheNavAreas, it )
{
TerrorNavArea *area = static_cast< TerrorNavArea * >(TheNavAreas[it]);
// Trace upward a bit from our center point just colliding wtih PLAYERCLIP to see if we're in one, if we are, mark us as accordingly.
trace_t trace;
Vector start = area->GetCenter() + Vector(0.0f, 0.0f, 16.0f );
Vector end = area->GetCenter() + Vector(0.0f, 0.0f, 32.0f );
UTIL_TraceHull( start, end, Vector(0,0,0), Vector(0,0,0), CONTENTS_PLAYERCLIP, NULL, &trace);
if ( trace.fraction < 1.0 )
{
area->SetAttributes( area->GetAttributes() | TerrorNavArea::NAV_PLAYERCLIP );
}
}
#endif
}
//--------------------------------------------------------------------------------------------------------------
/**
* Mark all areas that require a jump to get through them.
* This currently relies on jump areas having extreme slope.
*/
void CNavMesh::MarkJumpAreas( void )
{
FOR_EACH_VEC( TheNavAreas, it )
{
CNavArea *area = TheNavAreas[ it ];
if ( !area->HasNodes() )
continue;
Vector normal, otherNormal;
area->ComputeNormal( &normal );
area->ComputeNormal( &otherNormal, true );
float lowestNormalZ = MIN( normal.z, otherNormal.z );
if (lowestNormalZ < nav_slope_limit.GetFloat())
{
// The area is a jump area, and we don't merge jump areas together
area->SetAttributes( area->GetAttributes() | NAV_MESH_JUMP | NAV_MESH_NO_MERGE );
}
else if ( lowestNormalZ < nav_slope_limit.GetFloat() + nav_slope_tolerance.GetFloat() )
{
Vector testPos = area->GetCenter();
testPos.z += HalfHumanHeight;
Vector groundNormal;
float dummy;
if ( GetSimpleGroundHeight( testPos, &dummy, &groundNormal ) )
{
// If the ground normal is divergent from the area's normal, mark it as a jump area - it's not
// really representative of the ground.
float deltaNormalZ = fabs( groundNormal.z - lowestNormalZ );
if ( deltaNormalZ > nav_slope_tolerance.GetFloat() )
{
// The area is a jump area, and we don't merge jump areas together
area->SetAttributes( area->GetAttributes() | NAV_MESH_JUMP | NAV_MESH_NO_MERGE );
}
}
}
}
}
//--------------------------------------------------------------------------------------------------------------
/**
* Remove all areas marked as jump areas and connect the areas connecting to them
*
*/
void CNavMesh::StichAndRemoveJumpAreas( void )
{
// Now, go through and remove jump areas, connecting areas to make up for it
JumpConnector connector;
ForAllAreas( connector );
RemoveJumpAreas();
}
//--------------------------------------------------------------------------------------------------------------
/**
* Adjusts obstacle start and end distances such that obstacle width (end-start) is not less than MinObstacleAreaWidth,
* and end distance is not greater than maxAllowedDist
*/
void AdjustObstacleDistances( float *pObstacleStartDist, float *pObstacleEndDist, float maxAllowedDist )
{
float obstacleWidth = *pObstacleEndDist - *pObstacleStartDist;
// is the obstacle width too narrow?
if ( obstacleWidth < MinObstacleAreaWidth )
{
float halfDelta = ( MinObstacleAreaWidth - obstacleWidth ) /2;
// move start so it's half of min width from center, but no less than zero
*pObstacleStartDist = MAX( *pObstacleStartDist - halfDelta, 0 );
// move end so it's min width from start
*pObstacleEndDist = *pObstacleStartDist + MinObstacleAreaWidth;
// if this pushes the end past max allowed distance, pull start and end back so that end is within allowed distance
if ( *pObstacleEndDist > maxAllowedDist )
{
float delta = *pObstacleEndDist - maxAllowedDist;
*pObstacleStartDist -= delta;
*pObstacleEndDist -= delta;
}
}
}
//--------------------------------------------------------------------------------------------------------------
/**
* Makes sure tall, slim obstacles like fencetops, railings and narrow walls have nav areas placed on top of them
* to allow climbing & traversal
*/
void CNavMesh::HandleObstacleTopAreas( void )
{
if ( !nav_generate_fencetops.GetBool() )
return;
// For any 1x1 area that is internally blocked by an obstacle, raise it on top of the obstacle and size to fit.
RaiseAreasWithInternalObstacles();
// Create new areas as required
CreateObstacleTopAreas();
// It's possible for obstacle top areas to wind up overlapping one another, fix any such cases
RemoveOverlappingObstacleTopAreas();
}
//--------------------------------------------------------------------------------------------------------------
/**
* For any nav area that has internal obstacles between its corners of greater than traversable height,
* raise that nav area to sit at the top of the obstacle, and shrink it to fit the obstacle. Such nav
* areas are already restricted to be 1x1 so this will only be performed on areas that are already small.
*/
void CNavMesh::RaiseAreasWithInternalObstacles()
{
// obstacle areas next to stairs are bad - delete them
CUtlVector< CNavArea * > areasToDelete;
FOR_EACH_VEC( TheNavAreas, it )
{
CNavArea *area = TheNavAreas[ it ];
// any nav area with internal obstacles will be 1x1 (width and height = GenerationStepSize), so
// only need to consider areas of that size
if ( ( area->GetSizeX() != GenerationStepSize ) || (area->GetSizeY() != GenerationStepSize ) )
continue;
float obstacleZ[2] = { -FLT_MAX, -FLT_MAX };
float obstacleZMax = -FLT_MAX;
NavDirType obstacleDir = NORTH;
float obstacleStartDist = GenerationStepSize;
float obstacleEndDist = 0;
bool isStairNeighbor = false;
// Look at all 4 directions and determine if there are obstacles in that direction. Find the direction with the highest obstacle, if any.
for ( int i = 0; i < NUM_DIRECTIONS; i++ )
{
NavDirType dir = (NavDirType) i;
// For this direction, look at the left and right edges of the nav area relative to this direction and determined if they are both blocked
// by obstacles. We only consider this area obstructed if both edges are blocked (e.g. fence runs all the way through it).
NavCornerType corner[2];
int iEdgesBlocked = 0;
corner[0] = (NavCornerType) ( ( i + 3 ) % NUM_CORNERS ); // lower left-hand corner relative to current direction
corner[1] = (NavCornerType) ( ( i + 2 ) % NUM_CORNERS ); // lower right-hand corner relative to current direction
float obstacleZThisDir[2] = { -FLT_MAX, -FLT_MAX }; // absolute Z pos of obstacle for left and right edge in this direction
float obstacleStartDistThisDir = GenerationStepSize; // closest obstacle start distance in this direction
float obstacleEndDistThisDir = 0; // farthest obstacle end distance in this direction
// consider left and right edges of nav area relative to current direction
for ( int iEdge = 0; iEdge < 2; iEdge++ )
{
NavCornerType cornerType = corner[iEdge];
CNavNode *nodeFrom = area->m_node[cornerType];
if ( nodeFrom )
{
// is there an obstacle going from corner to corner along this edge?
float obstacleHeight = nodeFrom->m_obstacleHeight[dir];
if ( obstacleHeight > MaxTraversableHeight )
{
// yes, this edge is blocked
iEdgesBlocked++;
// keep track of obstacle height and start and end distance for this edge
float obstacleZ = nodeFrom->GetPosition()->z + obstacleHeight;
if ( obstacleZ > obstacleZThisDir[iEdge] )
{
obstacleZThisDir[iEdge] = obstacleZ;
}
obstacleStartDistThisDir = MIN( nodeFrom->m_obstacleStartDist[dir], obstacleStartDistThisDir );
obstacleEndDistThisDir = MAX( nodeFrom->m_obstacleEndDist[dir], obstacleEndDistThisDir );
}
}
}
int BlockedEdgeCutoff = 2;
const NavConnectVector *connections = area->GetAdjacentAreas( dir );
if ( connections )
{
for ( int conIndex=0; conIndex<connections->Count(); ++conIndex )
{
const CNavArea *connectedArea = connections->Element( conIndex ).area;
if ( connectedArea && connectedArea->HasAttributes( NAV_MESH_STAIRS ) )
{
isStairNeighbor = true;
BlockedEdgeCutoff = 1; // one blocked edge is already too much when we're next to a stair
break;
}
}
}
// are both edged blocked in this direction, and is the obstacle height in this direction the tallest we've seen?
if ( (iEdgesBlocked >= BlockedEdgeCutoff ) && ( MAX( obstacleZThisDir[0], obstacleZThisDir[1] ) ) > obstacleZMax )
{
// this is the tallest obstacle we've encountered so far, remember its details
obstacleZ[0] = obstacleZThisDir[0];
obstacleZ[1] = obstacleZThisDir[1];
obstacleZMax = MAX( obstacleZ[0], obstacleZ[1] );
obstacleDir = dir;
obstacleStartDist = obstacleStartDistThisDir;
obstacleEndDist = obstacleStartDistThisDir;
}
}
if ( isStairNeighbor && obstacleZMax > -FLT_MAX )
{
areasToDelete.AddToTail( area );
continue;
}
// if we found an obstacle, raise this nav areas and size it to fit
if ( obstacleZMax > -FLT_MAX )
{
// enforce minimum obstacle width so we don't shrink to become a teensy nav area
AdjustObstacleDistances( &obstacleStartDist, &obstacleEndDist, GenerationStepSize );
Assert( obstacleEndDist - obstacleStartDist >= MinObstacleAreaWidth );
// get current corner coords
Vector corner[4];
for ( int i = NORTH_WEST; i < NUM_CORNERS; i++ )
{
corner[i] = area->GetCorner( (NavCornerType) i );
}
// adjust our size to fit the obstacle
switch ( obstacleDir )
{
case NORTH:
corner[NORTH_WEST].y = corner[SOUTH_WEST].y - obstacleEndDist;
corner[NORTH_EAST].y = corner[SOUTH_EAST].y - obstacleEndDist;
corner[SOUTH_WEST].y -= obstacleStartDist;
corner[SOUTH_EAST].y -= obstacleStartDist;
break;
case SOUTH:
corner[SOUTH_WEST].y = corner[NORTH_WEST].y + obstacleEndDist;
corner[SOUTH_EAST].y = corner[NORTH_EAST].y + obstacleEndDist;
corner[NORTH_WEST].y += obstacleStartDist;
corner[NORTH_EAST].y += obstacleStartDist;
V_swap( obstacleZ[0], obstacleZ[1] ); // swap left and right Z heights for obstacle so we can run common code below
break;
case EAST:
corner[NORTH_EAST].x = corner[NORTH_WEST].x + obstacleEndDist;
corner[SOUTH_EAST].x = corner[SOUTH_WEST].x + obstacleEndDist;
corner[NORTH_WEST].x += obstacleStartDist;
corner[SOUTH_WEST].x += obstacleStartDist;
case WEST:
corner[NORTH_WEST].x = corner[NORTH_EAST].x - obstacleEndDist;
corner[SOUTH_WEST].x = corner[SOUTH_EAST].x - obstacleEndDist;
corner[NORTH_EAST].x -= obstacleStartDist;
corner[SOUTH_EAST].x -= obstacleStartDist;
V_swap( obstacleZ[0], obstacleZ[1] ); // swap left and right Z heights for obstacle so we can run common code below
break;
}
// adjust Z positions to be z pos of obstacle top
corner[NORTH_WEST].z = obstacleZ[0];
corner[NORTH_EAST].z = obstacleZ[1];
corner[SOUTH_EAST].z = obstacleZ[1];
corner[SOUTH_WEST].z = obstacleZ[0];
// move the area
area->Build( corner[NORTH_WEST], corner[NORTH_EAST], corner[SOUTH_EAST], corner[SOUTH_WEST] );
Assert( !area->IsDegenerate() );
// AddToSelectedSet( area );
// remove side-to-side connections if there are any so AI does try to do things like run along fencetops
area->RemoveOrthogonalConnections( obstacleDir );
area->SetAttributes( area->GetAttributes() | NAV_MESH_NO_MERGE | NAV_MESH_OBSTACLE_TOP );
area->SetAttributes( area->GetAttributes() & ( ~NAV_MESH_JUMP ) );
// clear out the nodes associated with this area's corners -- corners don't match the node positions any more
for ( int i = 0; i < NUM_CORNERS; i++ )
{
area->m_node[i] = NULL;
}
}
}
for ( int i=0; i<areasToDelete.Count(); ++i )
{
TheNavAreas.FindAndRemove( areasToDelete[i] );
DestroyArea( areasToDelete[i] );
}
}
//--------------------------------------------------------------------------------------------------------------
/**
* For any two nav areas that have an obstacle between them such as a fence, railing or small wall, creates a new
* nav area on top of the obstacle and connects it between the areas
*/
void CNavMesh::CreateObstacleTopAreas()
{
// enumerate all areas
FOR_EACH_VEC( TheNavAreas, it )
{
CNavArea *area = TheNavAreas[ it ];
// if this is a jump node (which will ultimately get removed) or is an obstacle top, ignore it
if ( area->GetAttributes() & ( NAV_MESH_JUMP | NAV_MESH_OBSTACLE_TOP ) )
return;
// Look in all directions
for ( int i = NORTH; i < NUM_DIRECTIONS; i++ )
{
NavDirType dir = (NavDirType) i;
// Look at all adjacent areas in this direction
int iConnections = area->GetAdjacentCount( dir );
for ( int j = 0; j < iConnections; j++ )
{
CNavArea *areaOther = area->GetAdjacentArea( dir, j );
// if this is a jump node (which will ultimately get removed) or is an obstacle top, ignore it
if ( areaOther->GetAttributes() & ( NAV_MESH_JUMP | NAV_MESH_OBSTACLE_TOP ) )
continue;
// create an obstacle top if there is a one-node separation between the areas and there is an intra-node obstacle within that separation
if ( !CreateObstacleTopAreaIfNecessary( area, areaOther, dir, false ) )
{
// if not, create an obstacle top if there is a two-node separation between the areas and the intermediate node is significantly
// higher than the two areas, which means there's some geometry there that causes the middle node to be higher
CreateObstacleTopAreaIfNecessary( area, areaOther, dir, true );
}
}
}
}
}
//--------------------------------------------------------------------------------------------------------------
/**
* Creates a new nav area if an obstacle exists between the two nav areas. If bMultiNode is false, this checks
* if there's a one-node separation between the areas, and if so if there is an obstacle detected between the nodes.
* If bMultiNode is true, checks if there is a two-node separation between the areas, and if so if the middle node is
* higher than the two areas, suggesting an obstacle in the middle.
*/
bool CNavMesh::CreateObstacleTopAreaIfNecessary( CNavArea *area, CNavArea *areaOther, NavDirType dir, bool bMultiNode )
{
float obstacleHeightMin = FLT_MAX;
float obstacleHeightMax = 0;
float obstacleHeightStart = 0;
float obstacleHeightEnd = 0;
float obstacleDistMin = GenerationStepSize;
float obstacleDistMax = 0;
Vector center;
float halfPortalWidth;
area->ComputePortal( areaOther, dir, ¢er, &halfPortalWidth );
if ( halfPortalWidth > 0 )
{
// get the corners to left and right of direction toward other area
NavCornerType cornerStart = (NavCornerType) dir;
NavCornerType cornerEnd = (NavCornerType) ( ( dir + 1 ) % NUM_CORNERS );
CNavNode *node = area->m_node[cornerStart];
CNavNode *nodeEnd = area->m_node[cornerEnd];
NavDirType dirEdge = (NavDirType) ( ( dir + 1 ) % NUM_DIRECTIONS );
obstacleHeightMin = FLT_MAX;
float zStart = 0, zEnd = 0;
// along the edge of this area that faces the other area, look at every node that's in the portal between the two
while ( node )
{
Vector vecToPortalCenter = *node->GetPosition() - center;
vecToPortalCenter.z = 0;
if ( vecToPortalCenter.IsLengthLessThan( halfPortalWidth + 1.0f ) )
{
// this node is in the portal
float obstacleHeight = 0;
float obstacleDistStartCur = node->m_obstacleStartDist[dir];
float obstacleDistEndCur = node->m_obstacleEndDist[dir];
if ( !bMultiNode )
{
// use the inter-node obstacle height from this node toward the next area
obstacleHeight = node->m_obstacleHeight[dir];
}
else
{
if ( !areaOther->Contains( *node->GetPosition() ) )
{
// step one node toward the other area
CNavNode *nodeTowardOtherArea = node->GetConnectedNode( dir );
if ( nodeTowardOtherArea )
{
// see if that step took us upward a significant amount
float deltaZ = nodeTowardOtherArea->GetPosition()->z - node->GetPosition()->z;
if ( deltaZ > MaxTraversableHeight )
{
// see if we've arrived in the other area
bool bInOtherArea = false;
if ( areaOther->Contains( *nodeTowardOtherArea->GetPosition() ) )
{
float z = areaOther->GetZ( nodeTowardOtherArea->GetPosition()->x, nodeTowardOtherArea->GetPosition()->y );
float deltaZ = fabs( nodeTowardOtherArea->GetPosition()->z - z );
if ( deltaZ < 2.0f )
{
bInOtherArea = true;
}
}
// if we have not arrived in the other area yet, take one more step in the same direction
if ( !bInOtherArea )
{
CNavNode *nodeTowardOtherArea2 = nodeTowardOtherArea->GetConnectedNode( dir );
if ( nodeTowardOtherArea2 && areaOther->Contains( *nodeTowardOtherArea2->GetPosition() ) )
{
float areaDeltaZ = node->GetPosition()->z - nodeTowardOtherArea2->GetPosition()->z;
if ( fabs( areaDeltaZ ) <= MaxTraversableHeight )
{
// if we arrived in the other area, the obstacle height to get here was the peak deltaZ of the node above to get here
obstacleHeight = deltaZ;
// make a nav area MinObstacleAreaWidth wide centered on the peak node, which is GenerationStepSize away from where we started
obstacleDistStartCur = GenerationStepSize - (MinObstacleAreaWidth / 2);
obstacleDistEndCur = GenerationStepSize + (MinObstacleAreaWidth / 2);
}
}
}
}
}
}
}
obstacleHeightMin = MIN( obstacleHeight, obstacleHeightMin );
obstacleHeightMax = MAX( obstacleHeight, obstacleHeightMax );
obstacleDistMin = MIN( obstacleDistStartCur, obstacleDistMin );
obstacleDistMax = MAX( obstacleDistEndCur, obstacleDistMax );
if ( obstacleHeightStart == 0 )
{
// keep track of the obstacle height and node z pos at the start of the edge
obstacleHeightStart = obstacleHeight;
zStart = node->GetPosition()->z;
}
// keep track of the obstacle height and node z pos at the end of the edge
obstacleHeightEnd = obstacleHeight;
zEnd = node->GetPosition()->z;
}
if ( node == nodeEnd )
break;
node = node->GetConnectedNode( dirEdge );
}
// if we had some obstacle height from EVERY node along the portal, then getting from this area to the other requires scaling an obstacle,
// need to generate a nav area on top of it
if ( ( obstacleHeightMax > MaxTraversableHeight ) && ( obstacleHeightMin > MaxTraversableHeight ) )
{
// If the maximum obstacle height was greater than both the height at start and end of the edge, then the obstacle is highest somewhere
// in the middle. Use that as the height of both ends.
if ( ( obstacleHeightMax > obstacleHeightStart ) && ( obstacleHeightMax > obstacleHeightEnd ) )
{
obstacleHeightStart = obstacleHeightMax;
obstacleHeightEnd = obstacleHeightMax;
}
// for south and west, swap "start" and "end" values of edges so we can use common code below
if ( dir == SOUTH || dir == WEST )
{
V_swap( obstacleHeightStart, obstacleHeightEnd );
V_swap( zStart, zEnd );
}
// Enforce min area width for new area
AdjustObstacleDistances( &obstacleDistMin, &obstacleDistMax, bMultiNode ? GenerationStepSize * 2 : GenerationStepSize );
Assert( obstacleDistMin < obstacleDistMax );
Assert( obstacleDistMax - obstacleDistMin >= MinObstacleAreaWidth );
float newAreaWidth = obstacleDistMax - obstacleDistMin;
Assert( newAreaWidth > 0 );
// Calculate new area coordinates
AddDirectionVector( ¢er, dir, obstacleDistMin + (newAreaWidth/2) );
Vector cornerNW, cornerNE, cornerSE, cornerSW;
switch ( dir )
{
case NORTH:
case SOUTH:
cornerNW.Init( center.x - halfPortalWidth, center.y - (newAreaWidth/2), zStart + obstacleHeightStart );
cornerNE.Init( center.x + halfPortalWidth, center.y - (newAreaWidth/2), zEnd + obstacleHeightEnd );
cornerSE.Init( center.x + halfPortalWidth, center.y + (newAreaWidth/2), zEnd + obstacleHeightEnd );
cornerSW.Init( center.x - halfPortalWidth, center.y + (newAreaWidth/2), zStart + obstacleHeightStart );
break;
case EAST:
case WEST:
cornerNW.Init( center.x - (newAreaWidth/2), center.y - halfPortalWidth, zStart + obstacleHeightStart );
cornerNE.Init( center.x + (newAreaWidth/2), center.y - halfPortalWidth, zEnd + obstacleHeightEnd );
cornerSE.Init( center.x + (newAreaWidth/2), center.y + halfPortalWidth, zEnd + obstacleHeightEnd );
cornerSW.Init( center.x - (newAreaWidth/2), center.y + halfPortalWidth, zStart + obstacleHeightStart );
break;
}
CNavArea *areaNew = CreateArea();
areaNew->Build( cornerNW, cornerNE, cornerSE, cornerSW );
// add it to the nav area list
TheNavAreas.AddToTail( areaNew );
AddNavArea( areaNew );
Assert( !areaNew->IsDegenerate() );
Msg( "Created new fencetop area %d(%x) between %d(%x) and %d(%x)\n", areaNew->GetID(), areaNew->GetDebugID(), area->GetID(), area->GetDebugID(), areaOther->GetID(), areaOther->GetDebugID() );
areaNew->SetAttributes( area->GetAttributes() );
areaNew->SetAttributes( area->GetAttributes() | NAV_MESH_NO_MERGE | NAV_MESH_OBSTACLE_TOP );
area->Disconnect( areaOther );
area->ConnectTo( areaNew, dir );
areaNew->ConnectTo( area, OppositeDirection( dir ) );
areaNew->ConnectTo( areaOther, dir );
if ( areaOther->IsConnected( area, OppositeDirection( dir ) ) )
{
areaOther->Disconnect( area );
areaOther->ConnectTo( areaNew, OppositeDirection( dir ) );
}
// AddToSelectedSet( areaNew );
return true;
}
}
return false;
}
//--------------------------------------------------------------------------------------------------------------
/**
* Remove any obstacle top areas which overlap.
*/
void CNavMesh::RemoveOverlappingObstacleTopAreas()
{
// What we really want is the union of all obstacle top areas that get generated. That would be hard to compute exactly,
// so instead we'll just remove any that overlap. The obstacle top areas don't have to be exact, we just need enough of
// them so there is generally a path to get over any obstacle.
// make a list of just the obstacle top areas to reduce the N of the N squared operation we're about to do
CUtlVector<CNavArea *> vecObstacleTopAreas;
FOR_EACH_VEC( TheNavAreas, it )
{
CNavArea *area = TheNavAreas[ it ];
if ( area->GetAttributes() & NAV_MESH_OBSTACLE_TOP )
{
vecObstacleTopAreas.AddToTail( area );
}
}
// look at every pair of obstacle top areas
CUtlVector<CNavArea *> vecAreasToRemove;
FOR_EACH_VEC( vecObstacleTopAreas, it )
{
CNavArea *area = vecObstacleTopAreas[it];
Vector normal, otherNormal;
area->ComputeNormal( &normal );
area->ComputeNormal( &otherNormal, true );
// Remove any obstacle areas that are steep enough to be jump areas
float lowestNormalZ = MIN( normal.z, otherNormal.z );
if ( lowestNormalZ < nav_slope_limit.GetFloat() )
{
vecAreasToRemove.AddToTail( area );
}
for ( int it2 = it+1; it2 < vecObstacleTopAreas.Count(); it2++ )
{
CNavArea *areaOther = vecObstacleTopAreas[it2];
if ( area->IsOverlapping( areaOther ) )
{
if ( area->Contains( areaOther ) )
{
// if one entirely contains the other, mark the other for removal
vecAreasToRemove.AddToTail( areaOther );
}
else if ( areaOther->Contains( area ) )
{
// if one entirely contains the other, mark the other for removal
vecAreasToRemove.AddToTail( area );
}
else
{
// if they overlap without one being a superset of the other, just remove the smaller area
CNavArea *areaToRemove = ( area->GetSizeX() * area->GetSizeY() > areaOther->GetSizeX() * areaOther->GetSizeY() ? areaOther : area );
vecAreasToRemove.AddToTail( areaToRemove );
}
}
}
}
// now go delete all the areas we want to remove
while ( vecAreasToRemove.Count() > 0 )
{
CNavArea *areaToDelete = vecAreasToRemove[0];
RemoveFromSelectedSet( areaToDelete );
TheNavMesh->OnEditDestroyNotify( areaToDelete );
TheNavAreas.FindAndRemove( areaToDelete );
TheNavMesh->DestroyArea( areaToDelete );
// remove duplicates so we don't double-delete
while ( vecAreasToRemove.FindAndRemove( areaToDelete ) );
}
}
static void CommandNavCheckStairs( void )
{
TheNavMesh->MarkStairAreas();
}
static ConCommand nav_check_stairs( "nav_check_stairs", CommandNavCheckStairs, "Update the nav mesh STAIRS attribute", FCVAR_CHEAT );
//--------------------------------------------------------------------------------------------------------------
/**
* Mark all areas that are on stairs.
*/
void CNavMesh::MarkStairAreas( void )
{
FOR_EACH_VEC( TheNavAreas, it )
{
CNavArea *area = TheNavAreas[ it ];
area->TestStairs();
}
}
//--------------------------------------------------------------------------------------------------------------
enum StairTestType
{
STAIRS_NO,
STAIRS_YES,
STAIRS_MAYBE,
};
//--------------------------------------------------------------------------------------------------------
// Test if a line across a nav area could be part of a stairway
StairTestType IsStairs( const Vector &start, const Vector &end, StairTestType ret )
{
if ( ret == STAIRS_NO )
return ret;
const float inc = 5.0f;
// the minimum height change each step to be a step and not a slope
const float minStepZ = inc * tan( acos( nav_slope_limit.GetFloat() ) );
const float MinStairNormal = 0.97f; // we don't care about ramps, just actual flat steps
float t;
Vector pos, normal;
float height, priorHeight;
// walk the line, checking for step height discontinuities
float length = start.AsVector2D().DistTo( end.AsVector2D() );
trace_t trace;
CTraceFilterNoNPCsOrPlayer filter( NULL, COLLISION_GROUP_PLAYER_MOVEMENT );
Vector hullMins( -inc/2, -inc/2, 0 );
Vector hullMaxs( inc/2, inc/2, 0 );
hullMaxs.z = 1; // don't care about vertical clearance
if ( fabs( start.x - end.x ) > fabs( start.y - end.y ) )
{
hullMins.x = -8;
hullMaxs.x = 8;
}
else
{
hullMins.y = -8;
hullMaxs.y = 8;
}
Vector traceOffset( 0, 0, VEC_DUCK_HULL_MAX.z );
// total height change must exceed a single step to be stairs
if ( abs( start.z - end.z ) > StepHeight )
{
// initialize the height delta
UTIL_TraceHull( start + traceOffset, start - traceOffset, hullMins, hullMaxs, MASK_NPCSOLID, &filter, &trace );
if ( trace.startsolid || trace.IsDispSurface() )
{
return STAIRS_NO;
}
priorHeight = trace.endpos.z;
// Save a copy for debug overlays
Vector prevGround = start;
prevGround.z = priorHeight;
float traceIncrement = inc / length;
for( t = 0.0f; t <= 1.0f; t += traceIncrement )
{
pos = start + t * ( end - start );
UTIL_TraceHull( pos + traceOffset, pos - traceOffset, hullMins, hullMaxs, MASK_NPCSOLID, &filter, &trace );
if ( trace.startsolid || trace.IsDispSurface() )
{
return STAIRS_NO;
}
height = trace.endpos.z;
normal = trace.plane.normal;
// Save a copy for debug overlays
Vector ground( pos );
ground.z = height;
//NDebugOverlay::Cross3D( ground, 3, 0, 0, 255, true, 100.0f );
//NDebugOverlay::Box( ground, hullMins, hullMaxs, 0, 0, 255, 0.0f, 100.0f );
if ( t == 0.0f && fabs( height - start.z ) > StepHeight )
{
// Discontinuity at start
return STAIRS_NO;
}
if ( t == 1.0f && fabs( height - end.z ) > StepHeight )
{
// Discontinuity at end
return STAIRS_NO;
}
if ( normal.z < MinStairNormal )
{
// too steep here
return STAIRS_NO;
}
float deltaZ = abs( height - priorHeight );
if ( deltaZ >= minStepZ && deltaZ <= StepHeight )
{
// found a step
ret = STAIRS_YES;
}
else if ( deltaZ > StepHeight )
{
// too steep here
//NDebugOverlay::Cross3D( ground, 5, 255, 0, 0, true, 10.0f );
//NDebugOverlay::Cross3D( prevGround, 5, 0, 255, 0, true, 10.0f );
return STAIRS_NO;
}
// Save a copy for debug overlays
prevGround = pos;
prevGround.z = height;
priorHeight = height;
}
}
return ret;
}
//--------------------------------------------------------------------------------------------------------------
/**
* Test an area for being on stairs
* NOTE: This assumes a globally constant "step height",
* and walkable surface normal, which really should be locomotor-specific.
*/
bool CNavArea::TestStairs( void )
{
// clear STAIRS attribute
SetAttributes( GetAttributes() & ~NAV_MESH_STAIRS );
if ( GetSizeX() <= GenerationStepSize && GetSizeY() <= GenerationStepSize )
{
// Don't bother with stairs on small areas
return false;
}
const float MatchingNormalDot = 0.95f;
Vector firstNormal, secondNormal;
ComputeNormal( &firstNormal );
ComputeNormal( &secondNormal, true );
if ( firstNormal.Dot( secondNormal ) < MatchingNormalDot )
{
// area corners aren't coplanar - no stairs
return false;
}
// test center and edges north-to-south, and east-to-west
StairTestType ret = STAIRS_MAYBE;
Vector from, to;
const float inset = 5.0f; // inset to keep the tests completely inside the nav area
from = GetCorner( NORTH_WEST ) + Vector( inset, inset, 0 );
to = GetCorner( NORTH_EAST ) + Vector( -inset, inset, 0 );
ret = IsStairs( from, to, ret );
from = GetCorner( SOUTH_WEST ) + Vector( inset, -inset, 0 );
to = GetCorner( SOUTH_EAST ) + Vector( -inset, -inset, 0 );
ret = IsStairs( from, to, ret );
from = GetCorner( NORTH_WEST ) + Vector( inset, inset, 0 );
to = GetCorner( SOUTH_WEST ) + Vector( inset, -inset, 0 );
ret = IsStairs( from, to, ret );
from = GetCorner( NORTH_EAST ) + Vector( -inset, inset, 0 );
to = GetCorner( SOUTH_EAST ) + Vector( -inset, -inset, 0 );
ret = IsStairs( from, to, ret );
from = ( GetCorner( NORTH_WEST ) + GetCorner( NORTH_EAST ) ) / 2.0f + Vector( 0, inset, 0 );
to = ( GetCorner( SOUTH_WEST ) + GetCorner( SOUTH_EAST ) ) / 2.0f + Vector( 0, -inset, 0 );
ret = IsStairs( from, to, ret );
from = ( GetCorner( NORTH_EAST ) + GetCorner( SOUTH_EAST ) ) / 2.0f + Vector( -inset, 0, 0 );
to = ( GetCorner( NORTH_WEST ) + GetCorner( SOUTH_WEST ) ) / 2.0f + Vector( inset, 0, 0 );
ret = IsStairs( from, to, ret );
if ( ret == STAIRS_YES )
{
SetAttributes( NAV_MESH_STAIRS );
return true;
}
return false;
}
//--------------------------------------------------------------------------------------------------------------
CON_COMMAND_F( nav_test_stairs, "Test the selected set for being on stairs", FCVAR_CHEAT )
{
int count = 0;
const NavAreaVector &selectedSet = TheNavMesh->GetSelectedSet();
for ( int i=0; i<selectedSet.Count(); ++i )
{
CNavArea *area = selectedSet[i];
if ( area->TestStairs() )
{
++count;
}
}
Msg( "Marked %d areas as stairs\n", count );
}
//--------------------------------------------------------------------------------------------------------------
/**
* Jump areas aren't used by the NextBot. Delete them, connecting adjacent areas.
*/
void CNavMesh::RemoveJumpAreas( void )
{
if ( !nav_generate_fixup_jump_areas.GetBool() )
{
return;
}
CUtlVector< CNavArea * > unusedAreas;
int i;
for ( i=0; i<TheNavAreas.Count(); ++i )
{
CNavArea *testArea = TheNavAreas[i];
if ( !(testArea->GetAttributes() & NAV_MESH_JUMP) )
{
continue;
}
unusedAreas.AddToTail( testArea );
}
for ( i=0; i<unusedAreas.Count(); ++i )
{
CNavArea *areaToDelete = unusedAreas[i];
TheNavMesh->OnEditDestroyNotify( areaToDelete );
TheNavAreas.FindAndRemove( areaToDelete );
TheNavMesh->DestroyArea( areaToDelete );
}
StripNavigationAreas();
SetMarkedArea( NULL ); // unmark the mark area
m_markedCorner = NUM_CORNERS; // clear the corner selection
}
//--------------------------------------------------------------------------------------------------------------
void CNavMesh::CommandNavRemoveJumpAreas( void )
{
JumpConnector connector;
ForAllAreas( connector );
int before = TheNavAreas.Count();
RemoveJumpAreas();
int after = TheNavAreas.Count();
Msg( "Removed %d jump areas\n", before - after );
}
//--------------------------------------------------------------------------------------------------------------
/**
* Recursively chop area in half along X until child areas are roughly square
*/
static void splitX( CNavArea *area )
{
if (area->IsRoughlySquare())
return;
float split = area->GetSizeX();
split /= 2.0f;
split += area->GetCorner( NORTH_WEST ).x;
split = TheNavMesh->SnapToGrid( split );
const float epsilon = 0.1f;
if (fabs(split - area->GetCorner( NORTH_WEST ).x) < epsilon ||
fabs(split - area->GetCorner( SOUTH_EAST ).x) < epsilon)
{
// too small to subdivide
return;
}
CNavArea *alpha, *beta;
if (area->SplitEdit( false, split, &alpha, &beta ))
{
// split each new area until square
splitX( alpha );
splitX( beta );
}
}
//--------------------------------------------------------------------------------------------------------------
/**
* Recursively chop area in half along Y until child areas are roughly square
*/
static void splitY( CNavArea *area )
{
if (area->IsRoughlySquare())
return;
float split = area->GetSizeY();
split /= 2.0f;
split += area->GetCorner( NORTH_WEST ).y;
split = TheNavMesh->SnapToGrid( split );
const float epsilon = 0.1f;
if (fabs(split - area->GetCorner( NORTH_WEST ).y) < epsilon ||
fabs(split - area->GetCorner( SOUTH_EAST ).y) < epsilon)
{
// too small to subdivide
return;
}
CNavArea *alpha, *beta;
if (area->SplitEdit( true, split, &alpha, &beta ))
{
// split each new area until square
splitY( alpha );
splitY( beta );
}
}
//--------------------------------------------------------------------------------------------------------------
/**
* Split any long, thin, areas into roughly square chunks.
*/
void CNavMesh::SquareUpAreas( void )
{
int it = 0;
while( it < TheNavAreas.Count() )
{
CNavArea *area = TheNavAreas[ it ];
// move the iterator in case the current area is split and deleted
++it;
if (area->HasNodes() && !area->IsRoughlySquare())
{
// chop this area into square pieces
if (area->GetSizeX() > area->GetSizeY())
splitX( area );
else
splitY( area );
}
}
}
//--------------------------------------------------------------------------------------------------------------
static bool testStitchConnection( CNavArea *source, CNavArea *target, const Vector &sourcePos, const Vector &targetPos )
{
trace_t result;
Vector from( sourcePos );
Vector pos( targetPos );
CTraceFilterWalkableEntities filter( NULL, COLLISION_GROUP_NONE, WALK_THRU_EVERYTHING );
Vector to, toNormal;
bool success = false;
if ( TraceAdjacentNode( 0, from, pos, &result ) )
{
to = result.endpos;
toNormal = result.plane.normal;
success = true;
}
else
{
// test going up ClimbUpHeight
bool success = false;
for ( float height = StepHeight; height <= ClimbUpHeight; height += 1.0f )
{
trace_t tr;
Vector start( from );
Vector end( pos );
start.z += height;
end.z += height;
UTIL_TraceHull( start, end, NavTraceMins, NavTraceMaxs, TheNavMesh->GetGenerationTraceMask(), &filter, &tr );
if ( !tr.startsolid && tr.fraction == 1.0f )
{
if ( !StayOnFloor( &tr ) )
{
break;
}
to = tr.endpos;
toNormal = tr.plane.normal;
start = end = from;
end.z += height;
UTIL_TraceHull( start, end, NavTraceMins, NavTraceMaxs, TheNavMesh->GetGenerationTraceMask(), &filter, &tr );
if ( tr.fraction < 1.0f )
{
break;
}
success = true;
break;
}
}
}
return success;
}
//--------------------------------------------------------------------------------------------------------
class IncrementallyGeneratedAreas
{
public:
bool operator()( CNavArea *area )
{
return area->HasNodes();
}
};
//--------------------------------------------------------------------------------------------------------
/**
* Incremental generation fixup for where edges lap up against the existing nav mesh:
* we have nodes, but the surrounding areas don't. So, we trace outward, to see if we
* can walk/fall to an adjacent area. This handles dropping down into existing areas etc.
* TODO: test pre-existing areas for drop-downs into the newly-generated areas.
*/
void CNavMesh::StitchGeneratedAreas( void )
{
if ( m_generationMode == GENERATE_INCREMENTAL )
{
IncrementallyGeneratedAreas incrementalAreas;
StitchMesh( incrementalAreas );
}
}
//--------------------------------------------------------------------------------------------------------
class AreaSet
{
public:
AreaSet( CUtlVector< CNavArea * > *areas )
{
m_areas = areas;
}
bool operator()( CNavArea *area )
{
return ( m_areas->HasElement( area ) );
}
private:
CUtlVector< CNavArea * > *m_areas;
};
//--------------------------------------------------------------------------------------------------------
/**
* Stitches an arbitrary set of areas (newly-merged, for example) into the existing mesh
*/
void CNavMesh::StitchAreaSet( CUtlVector< CNavArea * > *areas )
{
AreaSet areaSet( areas );
StitchMesh( areaSet );
}
//--------------------------------------------------------------------------------------------------------------
/**
* Determine if we can "jump down" from given point
*/
inline bool testJumpDown( const Vector *fromPos, const Vector *toPos )
{
float dz = fromPos->z - toPos->z;
// drop can't be too far, or too short (or nonexistant)
if (dz <= JumpCrouchHeight || dz >= DeathDrop)
return false;
//
// Check LOS out and down
//
// +-----+
// | |
// F |
// |
// T
//
Vector from, to;
float up;
trace_t result;
// Try to go up and out, up to ClimbUpHeight, to get over obstacles
for ( up=1.0f; up<=ClimbUpHeight; up += 1.0f )
{
from = *fromPos;
to.Init( fromPos->x, fromPos->y, fromPos->z + up );
UTIL_TraceHull( from, to, NavTraceMins, NavTraceMaxs, TheNavMesh->GetGenerationTraceMask(), NULL, COLLISION_GROUP_NONE, &result );
if (result.fraction <= 0.0f || result.startsolid)
continue;
from.Init( fromPos->x, fromPos->y, result.endpos.z - 0.5f );
to.Init( toPos->x, toPos->y, from.z );
UTIL_TraceHull( from, to, NavTraceMins, NavTraceMaxs, TheNavMesh->GetGenerationTraceMask(), NULL, COLLISION_GROUP_NONE, &result );
if (result.fraction != 1.0f || result.startsolid)
continue;
// Success!
break;
}
if ( up > ClimbUpHeight )
return false;
// We've made it up and out, so see if we can drop down
from = to;
to.z = toPos->z + 2.0f;
UTIL_TraceHull( from, to, NavTraceMins, NavTraceMaxs, TheNavMesh->GetGenerationTraceMask(), NULL, COLLISION_GROUP_NONE, &result );
if (result.fraction <= 0.0f || result.startsolid)
return false;
// Allow a little fudge so we can drop down onto stairs
if ( result.endpos.z > to.z + StepHeight )
return false;
return true;
}
//--------------------------------------------------------------------------------------------------------------
inline CNavArea *findJumpDownArea( const Vector *fromPos, NavDirType dir )
{
Vector start( fromPos->x, fromPos->y, fromPos->z + HalfHumanHeight );
AddDirectionVector( &start, dir, GenerationStepSize/2.0f );
Vector toPos;
CNavArea *downArea = findFirstAreaInDirection( &start, dir, 4.0f * GenerationStepSize, DeathDrop, NULL, &toPos );
if (downArea && testJumpDown( fromPos, &toPos ))
return downArea;
return NULL;
}
//--------------------------------------------------------------------------------------------------------------
template < typename Functor >
void CNavMesh::StitchAreaIntoMesh( CNavArea *area, NavDirType dir, Functor &func )
{
Vector corner1, corner2;
switch ( dir )
{
case NORTH:
corner1 = area->GetCorner( NORTH_WEST );
corner2 = area->GetCorner( NORTH_EAST );
break;
case SOUTH:
corner1 = area->GetCorner( SOUTH_WEST );
corner2 = area->GetCorner( SOUTH_EAST );
break;
case EAST:
corner1 = area->GetCorner( NORTH_EAST );
corner2 = area->GetCorner( SOUTH_EAST );
break;
case WEST:
corner1 = area->GetCorner( NORTH_WEST );
corner2 = area->GetCorner( SOUTH_WEST );
break;
}
Vector edgeDir = corner2 - corner1;
edgeDir.z = 0.0f;
float edgeLength = edgeDir.NormalizeInPlace();
for ( float n=0; n<edgeLength - 1.0f; n += GenerationStepSize )
{
Vector sourcePos = corner1 + edgeDir * ( n + 0.5f );
sourcePos.z += HalfHumanHeight;
Vector targetPos = sourcePos;
switch ( dir )
{
case NORTH: targetPos.y -= GenerationStepSize * 0.5f; break;
case SOUTH: targetPos.y += GenerationStepSize * 0.5f; break;
case EAST: targetPos.x += GenerationStepSize * 0.5f; break;
case WEST: targetPos.x -= GenerationStepSize * 0.5f; break;
}
CNavArea *targetArea = TheNavMesh->GetNavArea( targetPos );
if ( targetArea && !func( targetArea ) )
{
targetPos.z = targetArea->GetZ( targetPos.x, targetPos.y ) + HalfHumanHeight;
// outgoing connection
if ( testStitchConnection( area, targetArea, sourcePos, targetPos ) )
{
area->ConnectTo( targetArea, dir );
}
// incoming connection
if ( testStitchConnection( targetArea, area, targetPos, sourcePos ) )
{
targetArea->ConnectTo( area, OppositeDirection( dir ) );
}
}
else
{
sourcePos.z -= HalfHumanHeight;
sourcePos.z += 1;
CNavArea *downArea = findJumpDownArea( &sourcePos, dir );
if ( downArea && downArea != area && !func( downArea ) )
{
area->ConnectTo( downArea, dir );
}
}
}
}
//--------------------------------------------------------------------------------------------------------------
/**
* Checks to see if there is a cliff - a drop of at least CliffHeight - in specified direction.
*/
inline bool CheckCliff( const Vector *fromPos, NavDirType dir, bool bExhaustive = true )
{
// cliffs are half-baked, not used by any existing AI, and create poorly behaved nav areas (ie: long, thin, strips) (MSB 8/7/09)
return false;
Vector toPos( fromPos->x, fromPos->y, fromPos->z );
AddDirectionVector( &toPos, dir, GenerationStepSize );
trace_t trace;
// trace a step in specified direction and see where we'd find up
if ( TraceAdjacentNode( 0, *fromPos, toPos, &trace, DeathDrop * 10 ) && !trace.allsolid && !trace.startsolid )
{
float deltaZ = fromPos->z - trace.endpos.z;
// would we fall off a cliff?
if ( deltaZ > CliffHeight )
return true;
// if not, special case for south and east. South and east edges are not considered part of a nav area, so
// we look ahead two steps for south and east. This ensures that the n-1th row and column of nav nodes
// on the south and east sides of a nav area reflect any cliffs on the nth row and column.
// if we're looking to south or east, and the first node we found was approximately flat, and this is the top-level
// call, recurse one level to check one more step in this direction
if ( ( dir == SOUTH || dir == EAST ) && ( fabs( deltaZ ) < StepHeight ) && bExhaustive )
{
return CheckCliff( &trace.endpos, dir, false );
}
}
return false;
}
//--------------------------------------------------------------------------------------------------------------
/**
* Define connections between adjacent generated areas
*/
void CNavMesh::ConnectGeneratedAreas( void )
{
Msg( "Connecting navigation areas...\n" );
FOR_EACH_VEC( TheNavAreas, it )
{
CNavArea *area = TheNavAreas[ it ];
// scan along edge nodes, stepping one node over into the next area
// for now, only use bi-directional connections
// north edge
CNavNode *node;
for( node = area->m_node[ NORTH_WEST ]; node != area->m_node[ NORTH_EAST ]; node = node->GetConnectedNode( EAST ) )
{
CNavNode *adj = node->GetConnectedNode( NORTH );
if (adj && adj->GetArea() && adj->GetConnectedNode( SOUTH ) == node )
{
area->ConnectTo( adj->GetArea(), NORTH );
}
else
{
CNavArea *downArea = findJumpDownArea( node->GetPosition(), NORTH );
if (downArea && downArea != area)
area->ConnectTo( downArea, NORTH );
}
}
// west edge
for( node = area->m_node[ NORTH_WEST ]; node != area->m_node[ SOUTH_WEST ]; node = node->GetConnectedNode( SOUTH ) )
{
CNavNode *adj = node->GetConnectedNode( WEST );
if (adj && adj->GetArea() && adj->GetConnectedNode( EAST ) == node )
{
area->ConnectTo( adj->GetArea(), WEST );
}
else
{
CNavArea *downArea = findJumpDownArea( node->GetPosition(), WEST );
if (downArea && downArea != area)
area->ConnectTo( downArea, WEST );
}
}
// south edge - this edge's nodes are actually part of adjacent areas
// move one node north, and scan west to east
/// @todo This allows one-node-wide areas - do we want this?
node = area->m_node[ SOUTH_WEST ];
if ( node ) // pre-existing areas in incremental generates won't have nodes
{
node = node->GetConnectedNode( NORTH );
}
if (node)
{
CNavNode *end = area->m_node[ SOUTH_EAST ]->GetConnectedNode( NORTH );
/// @todo Figure out why cs_backalley gets a NULL node in here...
for( ; node && node != end; node = node->GetConnectedNode( EAST ) )
{
CNavNode *adj = node->GetConnectedNode( SOUTH );
if (adj && adj->GetArea() && adj->GetConnectedNode( NORTH ) == node )
{
area->ConnectTo( adj->GetArea(), SOUTH );
}
else
{
CNavArea *downArea = findJumpDownArea( node->GetPosition(), SOUTH );
if (downArea && downArea != area)
area->ConnectTo( downArea, SOUTH );
}
}
}
// south edge part 2 - scan the actual south edge. If the node is not part of an adjacent area, then it
// really belongs to us. This will happen if our area runs right up against a ledge.
for( node = area->m_node[ SOUTH_WEST ]; node != area->m_node[ SOUTH_EAST ]; node = node->GetConnectedNode( EAST ) )
{
if ( node->GetArea() )
continue; // some other area owns this node, pay no attention to it
CNavNode *adj = node->GetConnectedNode( SOUTH );
if ( node->IsBlockedInAnyDirection() || (adj && adj->IsBlockedInAnyDirection()) )
continue; // The space around this node is blocked, so don't connect across it
// Don't directly connect to adj's area, since it's already 1 cell removed from our area.
// There was no area in between, presumably for good reason. Only look for jump down links.
if ( !adj || !adj->GetArea() )
{
CNavArea *downArea = findJumpDownArea( node->GetPosition(), SOUTH );
if (downArea && downArea != area)
area->ConnectTo( downArea, SOUTH );
}
}
// east edge - this edge's nodes are actually part of adjacent areas
node = area->m_node[ NORTH_EAST ];
if ( node ) // pre-existing areas in incremental generates won't have nodes
{
node = node->GetConnectedNode( WEST );
}
if (node)
{
CNavNode *end = area->m_node[ SOUTH_EAST ]->GetConnectedNode( WEST );
for( ; node && node != end; node = node->GetConnectedNode( SOUTH ) )
{
CNavNode *adj = node->GetConnectedNode( EAST );
if (adj && adj->GetArea() && adj->GetConnectedNode( WEST ) == node )
{
area->ConnectTo( adj->GetArea(), EAST );
}
else
{
CNavArea *downArea = findJumpDownArea( node->GetPosition(), EAST );
if (downArea && downArea != area)
area->ConnectTo( downArea, EAST );
}
}
}
// east edge part 2 - scan the actual east edge. If the node is not part of an adjacent area, then it
// really belongs to us. This will happen if our area runs right up against a ledge.
for( node = area->m_node[ NORTH_EAST ]; node != area->m_node[ SOUTH_EAST ]; node = node->GetConnectedNode( SOUTH ) )
{
if ( node->GetArea() )
continue; // some other area owns this node, pay no attention to it
CNavNode *adj = node->GetConnectedNode( EAST );
if ( node->IsBlockedInAnyDirection() || (adj && adj->IsBlockedInAnyDirection()) )
continue; // The space around this node is blocked, so don't connect across it
// Don't directly connect to adj's area, since it's already 1 cell removed from our area.
// There was no area in between, presumably for good reason. Only look for jump down links.
if ( !adj || !adj->GetArea() )
{
CNavArea *downArea = findJumpDownArea( node->GetPosition(), EAST );
if (downArea && downArea != area)
area->ConnectTo( downArea, EAST );
}
}
}
StitchGeneratedAreas();
}
//--------------------------------------------------------------------------------------------------------------
bool CNavArea::IsAbleToMergeWith( CNavArea *other ) const
{
if ( !HasNodes() || ( GetAttributes() & NAV_MESH_NO_MERGE ) )
return false;
if ( !other->HasNodes() || ( other->GetAttributes() & NAV_MESH_NO_MERGE ) )
return false;
return true;
}
//--------------------------------------------------------------------------------------------------------------
/**
* Merge areas together to make larger ones (must remain rectangular - convex).
* Areas can only be merged if their attributes match.
*/
void CNavMesh::MergeGeneratedAreas( void )
{
Msg( "Merging navigation areas...\n" );
bool merged;
do
{
merged = false;
FOR_EACH_VEC( TheNavAreas, it )
{
CNavArea *area = TheNavAreas[ it ];
if ( !area->HasNodes() || ( area->GetAttributes() & NAV_MESH_NO_MERGE ) )
continue;
// north edge
FOR_EACH_VEC( area->m_connect[ NORTH ], nit )
{
CNavArea *adjArea = area->m_connect[ NORTH ][ nit ].area;
if ( !area->IsAbleToMergeWith( adjArea ) ) // pre-existing areas in incremental generates won't have nodes
continue;
if ( area->GetSizeY() + adjArea->GetSizeY() > GenerationStepSize * nav_area_max_size.GetInt() )
continue;
if (area->m_node[ NORTH_WEST ] == adjArea->m_node[ SOUTH_WEST ] &&
area->m_node[ NORTH_EAST ] == adjArea->m_node[ SOUTH_EAST ] &&
area->GetAttributes() == adjArea->GetAttributes() &&
area->IsCoplanar( adjArea ))
{
// merge vertical
area->m_node[ NORTH_WEST ] = adjArea->m_node[ NORTH_WEST ];
area->m_node[ NORTH_EAST ] = adjArea->m_node[ NORTH_EAST ];
merged = true;
//CONSOLE_ECHO( " Merged (north) areas #%d and #%d\n", area->m_id, adjArea->m_id );
area->FinishMerge( adjArea );
// restart scan - iterator is invalidated
break;
}
}
if (merged)
break;
// south edge
FOR_EACH_VEC( area->m_connect[ SOUTH ], sit )
{
CNavArea *adjArea = area->m_connect[ SOUTH ][ sit ].area;
if ( !area->IsAbleToMergeWith( adjArea ) ) // pre-existing areas in incremental generates won't have nodes
continue;
if ( area->GetSizeY() + adjArea->GetSizeY() > GenerationStepSize * nav_area_max_size.GetInt() )
continue;
if (adjArea->m_node[ NORTH_WEST ] == area->m_node[ SOUTH_WEST ] &&
adjArea->m_node[ NORTH_EAST ] == area->m_node[ SOUTH_EAST ] &&
area->GetAttributes() == adjArea->GetAttributes() &&
area->IsCoplanar( adjArea ))
{
// merge vertical
area->m_node[ SOUTH_WEST ] = adjArea->m_node[ SOUTH_WEST ];
area->m_node[ SOUTH_EAST ] = adjArea->m_node[ SOUTH_EAST ];
merged = true;
//CONSOLE_ECHO( " Merged (south) areas #%d and #%d\n", area->m_id, adjArea->m_id );
area->FinishMerge( adjArea );
// restart scan - iterator is invalidated
break;
}
}
if (merged)
break;
// west edge
FOR_EACH_VEC( area->m_connect[ WEST ], wit )
{
CNavArea *adjArea = area->m_connect[ WEST ][ wit ].area;
if ( !area->IsAbleToMergeWith( adjArea ) ) // pre-existing areas in incremental generates won't have nodes
continue;
if ( area->GetSizeX() + adjArea->GetSizeX() > GenerationStepSize * nav_area_max_size.GetInt() )
continue;
if (area->m_node[ NORTH_WEST ] == adjArea->m_node[ NORTH_EAST ] &&
area->m_node[ SOUTH_WEST ] == adjArea->m_node[ SOUTH_EAST ] &&
area->GetAttributes() == adjArea->GetAttributes() &&
area->IsCoplanar( adjArea ))
{
// merge horizontal
area->m_node[ NORTH_WEST ] = adjArea->m_node[ NORTH_WEST ];
area->m_node[ SOUTH_WEST ] = adjArea->m_node[ SOUTH_WEST ];
merged = true;
//CONSOLE_ECHO( " Merged (west) areas #%d and #%d\n", area->m_id, adjArea->m_id );
area->FinishMerge( adjArea );
// restart scan - iterator is invalidated
break;
}
}
if (merged)
break;
// east edge
FOR_EACH_VEC( area->m_connect[ EAST ], eit )
{
CNavArea *adjArea = area->m_connect[ EAST ][ eit ].area;
if ( !area->IsAbleToMergeWith( adjArea ) ) // pre-existing areas in incremental generates won't have nodes
continue;
if ( area->GetSizeX() + adjArea->GetSizeX() > GenerationStepSize * nav_area_max_size.GetInt() )
continue;
if (adjArea->m_node[ NORTH_WEST ] == area->m_node[ NORTH_EAST ] &&
adjArea->m_node[ SOUTH_WEST ] == area->m_node[ SOUTH_EAST ] &&
area->GetAttributes() == adjArea->GetAttributes() &&
area->IsCoplanar( adjArea ))
{
// merge horizontal
area->m_node[ NORTH_EAST ] = adjArea->m_node[ NORTH_EAST ];
area->m_node[ SOUTH_EAST ] = adjArea->m_node[ SOUTH_EAST ];
merged = true;
//CONSOLE_ECHO( " Merged (east) areas #%d and #%d\n", area->m_id, adjArea->m_id );
area->FinishMerge( adjArea );
// restart scan - iterator is invalidated
break;
}
}
if (merged)
break;
}
}
while( merged );
}
//--------------------------------------------------------------------------------------------------------------
/**
* Given arbitrary corners of a compass grid-aligned rectangle, classify them by compass direction.
* Input: vec[4]: arbitrary corners
* Output: vecNW, vecNE, vecSE, vecSW: filled in with which corner is in which compass direction
*/
void ClassifyCorners( Vector vec[4], Vector &vecNW, Vector &vecNE, Vector &vecSE, Vector &vecSW )
{
vecNW = vecNE = vecSE = vecSW = vec[0];
for ( int i = 0; i < 4; i++ )
{
if ( ( vec[i].x <= vecNW.x ) && ( vec[i].y <= vecNW.y ) )
{
vecNW = vec[i];
}
if ( ( vec[i].x >= vecNE.x ) && ( vec[i].y <= vecNE.y ) )
{
vecNE = vec[i];
}
if ( ( vec[i].x >= vecSE.x ) && ( vec[i].y >= vecSE.y ) )
{
vecSE = vec[i];
}
if ( ( vec[i].x <= vecSW.x ) && ( vec[i].y >= vecSW.y ) )
{
vecSW = vec[i];
}
}
}
//--------------------------------------------------------------------------------------------------------------
/**
* Perform miscellaneous fixups to generated mesh
*/
void CNavMesh::FixUpGeneratedAreas( void )
{
FixCornerOnCornerAreas();
FixConnections();
}
//--------------------------------------------------------------------------------------------------------------
void CNavMesh::FixConnections( void )
{
// Test the steep sides of stairs for any outgoing links that cross nodes that were partially obstructed.
FOR_EACH_VEC( TheNavAreas, it )
{
CNavArea *area = TheNavAreas[ it ];
if ( !area->HasAttributes( NAV_MESH_STAIRS ) )
continue;
if ( !area->HasNodes() )
continue;
for ( int dir=0; dir<NUM_DIRECTIONS; ++dir )
{
NavCornerType cornerType[2];
GetCornerTypesInDirection( (NavDirType)dir, &cornerType[0], &cornerType[1] );
// Flat edges of stairs need to connect. It's the slopes we don't want to climb over things for.
float cornerDeltaZ = fabs( area->GetCorner( cornerType[0] ).z - area->GetCorner( cornerType[1] ).z );
if ( cornerDeltaZ < StepHeight )
continue;
const NavConnectVector *connectedAreas = area->GetAdjacentAreas( (NavDirType)dir );
CUtlVector< CNavArea * > areasToDisconnect;
for ( int i=0; i<connectedAreas->Count(); ++i )
{
CNavArea *adjArea = connectedAreas->Element(i).area;
if ( !adjArea->HasNodes() )
continue;
Vector pos, adjPos;
float width;
area->ComputePortal( adjArea, (NavDirType)dir, &pos, &width );
adjArea->GetClosestPointOnArea( pos, &adjPos );
CNavNode *node = area->FindClosestNode( pos, (NavDirType)dir );
CNavNode *adjNode = adjArea->FindClosestNode( adjPos, OppositeDirection( (NavDirType)dir ) );
pos = *node->GetPosition();
adjPos = *adjNode->GetPosition();
if ( !node || !adjNode )
continue;
NavCornerType adjCornerType[2];
GetCornerTypesInDirection( OppositeDirection((NavDirType)dir), &adjCornerType[0], &adjCornerType[1] );
// From the stair's perspective, we can't go up more than step height to reach the adjacent area.
// Also, if the adjacent area has to jump up higher than StepHeight above the stair area to reach the stairs,
// there's an obstruction close to the adjacent area that could prevent walking from the stairs down.
if ( node->GetGroundHeightAboveNode( cornerType[0] ) > StepHeight )
{
areasToDisconnect.AddToTail( adjArea );
}
else if ( node->GetGroundHeightAboveNode( cornerType[1] ) > StepHeight )
{
areasToDisconnect.AddToTail( adjArea );
}
else if ( adjPos.z + adjNode->GetGroundHeightAboveNode( adjCornerType[0] ) > pos.z + StepHeight )
{
areasToDisconnect.AddToTail( adjArea );
}
else if ( adjPos.z + adjNode->GetGroundHeightAboveNode( adjCornerType[1] ) > pos.z + StepHeight )
{
areasToDisconnect.AddToTail( adjArea );
}
}
for ( int i=0; i<areasToDisconnect.Count(); ++i )
{
area->Disconnect( areasToDisconnect[i] );
}
}
}
// Test to prevent A->C if A->B->C. This can happen in doorways and dropdowns from rooftops.
// @TODO: find the root cause of A->C links.
FOR_EACH_VEC( TheNavAreas, it )
{
CNavArea *area = TheNavAreas[ it ];
CUtlVector< CNavArea * > areasToDisconnect;
for ( int dir=0; dir<NUM_DIRECTIONS; ++dir )
{
const NavConnectVector *connectedAreas = area->GetAdjacentAreas( (NavDirType)dir );
for ( int i=0; i<connectedAreas->Count(); ++i )
{
CNavArea *adjArea = connectedAreas->Element(i).area;
const NavConnectVector *adjConnectedAreas = adjArea->GetAdjacentAreas( (NavDirType)dir );
for ( int j=0; j<adjConnectedAreas->Count(); ++j )
{
CNavArea *farArea = adjConnectedAreas->Element(j).area;
if ( area->IsConnected( farArea, (NavDirType)dir ) )
{
areasToDisconnect.AddToTail( farArea );
}
}
}
}
for ( int i=0; i<areasToDisconnect.Count(); ++i )
{
area->Disconnect( areasToDisconnect[i] );
}
}
}
//--------------------------------------------------------------------------------------------------------------
/**
* Fix any spots where we there are nav nodes touching only corner-on-corner but we intend bots to be able to traverse
*/
void CNavMesh::FixCornerOnCornerAreas( void )
{
const float MaxDrop = StepHeight; // don't make corner on corner areas that are too steep
FOR_EACH_VEC( TheNavAreas, it )
{
CNavArea *area = TheNavAreas[ it ];
// determine if we have any corners where the only nav area we touch is diagonally corner-to-corner.
// if there are, generate additional small (0.5 x 0.5 grid size) nav areas in the corners between
// them if map geometry allows and make connections in cardinal compass directions to create a path
// between the two areas.
//
// XXXXXXXXX XXXXXXXXX
// X X X X
// X other X ****X other X
// X X *newX X
// XXXXXXXXXXXXXXXXX => XXXXXXXXXXXXXXXXX
// X X X Xnew*
// X area X X area X****
// X X X X
// XXXXXXXXX XXXXXXXXX
//
// check each corner
for ( int iCorner = NORTH_WEST; iCorner < NUM_CORNERS; iCorner++ )
{
// get cardinal direction to right and left of this corner
NavDirType dirToRight = (NavDirType) iCorner;
NavDirType dirToLeft = (NavDirType) ( ( iCorner+3 ) % NUM_DIRECTIONS );
// if we have any connections on cardinal compass directions on edge on either side of corner we're OK, skip this nav area
if ( area->GetAdjacentCount( dirToLeft ) > 0 || area->GetAdjacentCount( dirToRight ) > 0 ||
area->GetIncomingConnections( dirToLeft )->Count() > 0 || area->GetIncomingConnections( dirToRight )->Count() > 0 )
continue;
Vector cornerPos = area->GetCorner( (NavCornerType) iCorner );
NavDirType dirToRightTwice = DirectionRight( dirToRight );
NavDirType dirToLeftTwice = DirectionLeft( dirToLeft );
NavDirType dirsAlongOtherEdge[2] = { dirToLeft, dirToRight };
NavDirType dirsAlongOurEdge[2] = { dirToLeftTwice, dirToRightTwice };
// consider 2 potential new nav areas, to left and right of the corner we're considering
for ( int iDir = 0; iDir < ARRAYSIZE( dirsAlongOtherEdge ); iDir++ )
{
NavDirType dirAlongOtherEdge = dirsAlongOtherEdge[iDir];
NavDirType dirAlongOurEdge = dirsAlongOurEdge[iDir];
// look at the point 0.5 grid units along edge of other nav area
Vector vecDeltaOtherEdge;
DirectionToVector2D( dirAlongOtherEdge, (Vector2D *) &vecDeltaOtherEdge );
vecDeltaOtherEdge.z = 0;
vecDeltaOtherEdge *= GenerationStepSize * 0.5;
Vector vecOtherEdgePos = cornerPos + vecDeltaOtherEdge;
// see if there is a nav area at that location
CNavArea *areaOther = GetNavArea( vecOtherEdgePos );
Assert( areaOther != area );
if ( !areaOther )
continue; // no other area in that location, we're not touching on corner
// see if we can move from our corner in that direction
trace_t result;
if ( !TraceAdjacentNode( 0, cornerPos, vecOtherEdgePos, &result, MaxDrop ) )
continue; // something is blocking movement, don't create additional nodes to aid movement
// get the corner of the other nav area that might touch our corner
int iCornerOther = ( ( iCorner + 2 ) % NUM_CORNERS );
Vector cornerPosOther = areaOther->GetCorner( (NavCornerType) iCornerOther );
if ( cornerPos != cornerPosOther )
continue; // that nav area does not touch us on corner
// we are touching corner-to-corner with the other nav area and don't have connections in cardinal directions around
// the corner that touches, this is a candidate to generate new small helper nav areas.
// calculate the corners of the 0.5 x 0.5 nav area we would consider building between us and the other nav area whose corner we touch
Vector vecDeltaOurEdge;
DirectionToVector2D( dirAlongOurEdge, (Vector2D *) &vecDeltaOurEdge );
vecDeltaOurEdge.z = 0;
vecDeltaOurEdge *= GenerationStepSize * 0.5;
Vector vecOurEdgePos = cornerPos + vecDeltaOurEdge;
Vector vecCorner[4];
vecCorner[0] = cornerPos + vecDeltaOtherEdge + vecDeltaOurEdge; // far corner of new nav area
vecCorner[1] = cornerPos + vecDeltaOtherEdge; // intersection of far edge of new nav area with other nav area we touch
vecCorner[2] = cornerPos; // common corner of this nav area, nav area we touch, and new nav area
vecCorner[3] = cornerPos + vecDeltaOurEdge; // intersection of far edge of new nav area with this nav area
CTraceFilterWalkableEntities filter( NULL, COLLISION_GROUP_NONE, WALK_THRU_EVERYTHING );
if ( !TraceAdjacentNode( 0, vecCorner[1], vecCorner[0], &result, MaxDrop ) || // can we move from edge of other area to far corner of new node
!TraceAdjacentNode( 0, vecCorner[3], vecCorner[0], &result, MaxDrop ) ) // can we move from edge of this area to far corner of new node
continue; // new node would not fit
// as sanity check, make sure there's not already a nav area there, shouldn't be
CNavArea *areaTest = GetNavArea( vecCorner[0] );
Assert ( !areaTest );
if ( areaTest )
continue;
vecCorner[0] = result.endpos;
// create a new nav area
CNavArea *areaNew = CreateArea();
// arrange the corners of the new nav area by compass direction
Vector vecNW, vecNE, vecSE, vecSW;
ClassifyCorners( vecCorner, vecNW, vecNE, vecSE, vecSW );
areaNew->Build( vecNW, vecNE, vecSE, vecSW );
// add it to the nav area list
TheNavAreas.AddToTail( areaNew );
AddNavArea( areaNew );
areaNew->SetAttributes( area->GetAttributes() );
// reciprocally connect between this area and new area
area->ConnectTo( areaNew, dirAlongOtherEdge );
areaNew->ConnectTo( area, OppositeDirection( dirAlongOtherEdge ) );
// reciprocally connect between other area and new area
areaOther->ConnectTo( areaNew, dirAlongOurEdge );
areaNew->ConnectTo( areaOther, OppositeDirection( dirAlongOurEdge ) );
}
}
}
}
//--------------------------------------------------------------------------------------------------------------
/**
* Fix any areas where one nav area overhangs another and the two nav areas are connected. Subdivide the lower
* nav area such that the upper nav area doesn't overhang any area it's connected to.
*/
void CNavMesh::SplitAreasUnderOverhangs( void )
{
// restart the whole process whenever this gets set to true
bool bRestartProcessing = false;
do
{
bRestartProcessing = false;
// iterate all nav areas
for ( int it = 0; it < TheNavAreas.Count() && !bRestartProcessing; it++ )
{
CNavArea *area = TheNavAreas[ it ];
Extent areaExtent;
area->GetExtent( &areaExtent );
// iterate all directions
for ( int dir = NORTH; dir < NUM_DIRECTIONS && !bRestartProcessing; dir++ )
{
// iterate all connections in that direction
const NavConnectVector *pConnections = area->GetAdjacentAreas( (NavDirType) dir );
for ( int iConnection = 0; iConnection < pConnections->Count() && !bRestartProcessing; iConnection++ )
{
CNavArea *otherArea = (*pConnections)[iConnection].area;
Extent otherAreaExtent;
otherArea->GetExtent( &otherAreaExtent );
// see if the area we are connected to overlaps our X/Y extents
if ( area->IsOverlapping( otherArea ) )
{
// if the upper area isn't at least crouch height above the lower area, this is some weird minor
// overlap, disregard it
const float flMinSeparation = HumanCrouchHeight;
if ( !( areaExtent.lo.z > otherAreaExtent.hi.z + flMinSeparation ) &&
!( otherAreaExtent.lo.z > areaExtent.hi.z + flMinSeparation ) )
continue;
// figure out which area is above and which is below
CNavArea *areaBelow = area, *areaAbove = otherArea;
NavDirType dirFromAboveToBelow = OppositeDirection( (NavDirType) dir );
if ( otherAreaExtent.lo.z < areaExtent.lo.z )
{
areaBelow = otherArea;
areaAbove = area;
dirFromAboveToBelow = OppositeDirection( dirFromAboveToBelow );
}
NavDirType dirFromBelowToAbove = OppositeDirection( dirFromAboveToBelow );
// Msg( "area %d overhangs area %d and is connected\n", areaAbove->GetID(), areaBelow->GetID() );
Extent extentBelow, extentAbove;
areaBelow->GetExtent( &extentBelow );
areaAbove->GetExtent( &extentAbove );
float splitCoord; // absolute world coordinate along which we will split lower nav area (X or Y, depending on axis we split on)
float splitLen; // length of the segment of lower nav area that is in shadow of the upper nav area
float splitEdgeSize; // current length of the edge of nav area that is getting split
bool bSplitAlongX = false;
// determine along what edge we are splitting and make some key measurements
if ( ( dirFromAboveToBelow == EAST ) || ( dirFromAboveToBelow == WEST ) )
{
splitEdgeSize = extentBelow.hi.x - extentBelow.lo.x;
if ( extentAbove.hi.x < extentBelow.hi.x )
{
splitCoord = extentAbove.hi.x;
splitLen = splitCoord - extentBelow.lo.x;
}
else
{
splitCoord = extentAbove.lo.x;
splitLen = extentBelow.hi.x - splitCoord;
}
}
else
{
splitEdgeSize = extentBelow.hi.y - extentBelow.lo.y;
bSplitAlongX = true;
if ( extentAbove.hi.y < extentBelow.hi.y )
{
splitCoord = extentAbove.hi.y;
splitLen = splitCoord - extentBelow.lo.y;
}
else
{
splitCoord = extentAbove.lo.y;
splitLen = extentBelow.hi.y - splitCoord;
}
}
Assert( splitLen >= 0 );
Assert( splitEdgeSize > 0 );
// if we split the lower nav area right where it's in shadow of the upper nav area, will it create a really tiny strip?
if ( splitLen < GenerationStepSize )
{
// if the "in shadow" part of the lower nav area is really small or the lower nav area is really small to begin with,
// don't split it, we're better off as is
if ( ( splitLen < GenerationStepSize*0.3 ) || ( splitEdgeSize <= GenerationStepSize * 2 ) )
continue;
// Move our split point so we don't create a really tiny strip on the lower nav area. Move the split point away from
// the upper nav area so the "in shadow" area expands to be GenerationStepSize. The checks above ensure we have room to do this.
float splitDelta = GenerationStepSize - splitLen;
splitCoord += splitDelta * ( ( ( dirFromAboveToBelow == NORTH ) || ( dirFromAboveToBelow == WEST ) ) ? -1 : 1 );
}
// remove any connections between the two areas (so they don't get inherited by the new areas when we split the lower area),
// but remember what the connections were.
bool bConnectionFromBelow = false, bConnectionFromAbove = false;
if ( areaBelow->IsConnected( areaAbove, dirFromBelowToAbove ) )
{
bConnectionFromBelow = true;
areaBelow->Disconnect( areaAbove );
}
if ( areaAbove->IsConnected( areaBelow, dirFromAboveToBelow ) )
{
bConnectionFromAbove = true;
areaAbove->Disconnect( areaBelow );
}
CNavArea *pNewAlpha = NULL,*pNewBeta = NULL;
// int idBelow = areaBelow->GetID();
// AddToSelectedSet( areaBelow );
// split the lower nav area
if ( areaBelow->SplitEdit( bSplitAlongX, splitCoord, &pNewAlpha, &pNewBeta ) )
{
// Msg( "Split area %d into %d and %d\n", idBelow, pNewAlpha->GetID(), pNewBeta->GetID() );
// determine which of the two new lower areas is the one *not* in shadow of the upper nav area. This is the one we want to
// reconnect to
CNavArea *pNewNonoverlappedArea = ( ( dirFromAboveToBelow == NORTH ) || ( dirFromAboveToBelow == WEST ) ) ? pNewAlpha : pNewBeta;
// restore the previous connections from the upper nav area to the new lower nav area that is not in shadow of the upper
if ( bConnectionFromAbove )
{
areaAbove->ConnectTo( pNewNonoverlappedArea, dirFromAboveToBelow );
}
if ( bConnectionFromBelow )
{
areaBelow->ConnectTo( pNewNonoverlappedArea, OppositeDirection( dirFromAboveToBelow ) );
}
// Now we need to just start the whole process over. We've just perturbed the list we're iterating on (removed a nav area, added two
// new ones, when we did the split), and it's possible we may have to subdivide a lower nav area twice if the upper nav area
// overhangs a corner of the lower area. We just start all over again each time we do a split until no more overhangs occur.
bRestartProcessing = true;
}
else
{
// Msg( "Failed to split area %d\n", idBelow );
}
}
}
}
}
}
while ( bRestartProcessing );
}
//--------------------------------------------------------------------------------------------------------------
bool TestForValidCrouchArea( CNavNode *node )
{
// must make sure we don't have a bogus crouch area. check up to JumpCrouchHeight above
// the node for a HumanCrouchHeight space.
CTraceFilterWalkableEntities filter( NULL, COLLISION_GROUP_PLAYER_MOVEMENT, WALK_THRU_EVERYTHING );
trace_t tr;
Vector start( *node->GetPosition() );
Vector end( *node->GetPosition() );
end.z += JumpCrouchHeight;
Vector mins( 0, 0, 0 );
Vector maxs( GenerationStepSize, GenerationStepSize, HumanCrouchHeight );
UTIL_TraceHull(
start,
end,
mins,
maxs,
TheNavMesh->GetGenerationTraceMask(),
&filter,
&tr );
return ( !tr.allsolid );
}
//--------------------------------------------------------------------------------------------------------------
/**
* Make sure that if other* are similar, test is also close. Used in TestForValidJumpArea.
*/
bool IsHeightDifferenceValid( float test, float other1, float other2, float other3 )
{
// Make sure the other nodes are level.
const float CloseDelta = StepHeight / 2;
if ( fabs( other1 - other2 ) > CloseDelta )
return true;
if ( fabs( other1 - other3 ) > CloseDelta )
return true;
if ( fabs( other2 - other3 ) > CloseDelta )
return true;
// Now make sure the test node is near the others. If it is more than StepHeight away,
// it'll form a distorted jump area.
const float MaxDelta = StepHeight;
if ( fabs( test - other1 ) > MaxDelta )
return false;
if ( fabs( test - other2 ) > MaxDelta )
return false;
if ( fabs( test - other3 ) > MaxDelta )
return false;
return true;
}
//--------------------------------------------------------------------------------------------------------------
/**
* Check that a 1x1 area with 'node' at the northwest corner has a valid shape - if 3 corners
* are flat, and the 4th is significantly higher or lower, it would form a jump area that bots
* can't navigate over well.
*/
bool TestForValidJumpArea( CNavNode *node )
{
return true;
CNavNode *east = node->GetConnectedNode( EAST );
CNavNode *south = node->GetConnectedNode( SOUTH );
if ( !east || !south )
return false;
CNavNode *southEast = east->GetConnectedNode( SOUTH );
if ( !southEast )
return false;
if ( !IsHeightDifferenceValid(
node->GetPosition()->z,
south->GetPosition()->z,
southEast->GetPosition()->z,
east->GetPosition()->z ) )
return false;
if ( !IsHeightDifferenceValid(
south->GetPosition()->z,
node->GetPosition()->z,
southEast->GetPosition()->z,
east->GetPosition()->z ) )
return false;
if ( !IsHeightDifferenceValid(
southEast->GetPosition()->z,
south->GetPosition()->z,
node->GetPosition()->z,
east->GetPosition()->z ) )
return false;
if ( !IsHeightDifferenceValid(
east->GetPosition()->z,
south->GetPosition()->z,
southEast->GetPosition()->z,
node->GetPosition()->z ) )
return false;
return true;
}
//--------------------------------------------------------------------------------------------------------------
class TestOverlapping
{
Vector m_nw;
Vector m_ne;
Vector m_sw;
Vector m_se;
public:
TestOverlapping( const Vector &nw, const Vector &ne, const Vector &sw, const Vector &se ) :
m_nw( nw ), m_ne( ne ), m_sw( sw ), m_se( se )
{
}
// This approximates CNavArea::GetZ, so we can pretend our four corners delineate a nav area
float GetZ( const Vector &pos ) const
{
float dx = m_se.x - m_nw.x;
float dy = m_se.y - m_nw.y;
// guard against division by zero due to degenerate areas
if (dx == 0.0f || dy == 0.0f)
return m_ne.z;
float u = (pos.x - m_nw.x) / dx;
float v = (pos.y - m_nw.y) / dy;
// clamp Z values to (x,y) volume
if (u < 0.0f)
u = 0.0f;
else if (u > 1.0f)
u = 1.0f;
if (v < 0.0f)
v = 0.0f;
else if (v > 1.0f)
v = 1.0f;
float northZ = m_nw.z + u * (m_ne.z - m_nw.z);
float southZ = m_sw.z + u * (m_se.z - m_sw.z);
return northZ + v * (southZ - northZ);
}
bool OverlapsExistingArea( void )
{
CNavArea *overlappingArea = NULL;
CNavLadder *overlappingLadder = NULL;
Vector nw = m_nw;
Vector se = m_se;
Vector start = nw;
start.x += GenerationStepSize/2;
start.y += GenerationStepSize/2;
while ( start.x < se.x )
{
start.y = nw.y + GenerationStepSize/2;
while ( start.y < se.y )
{
start.z = GetZ( start );
Vector end = start;
start.z -= StepHeight;
end.z += HalfHumanHeight;
if ( TheNavMesh->FindNavAreaOrLadderAlongRay( start, end, &overlappingArea, &overlappingLadder, NULL ) )
{
if ( overlappingArea )
{
return true;
}
}
start.y += GenerationStepSize;
}
start.x += GenerationStepSize;
}
return false;
}
};
//--------------------------------------------------------------------------------------------------------------
/**
* Check if an rectangular area of the given size can be
* made starting from the given node as the NW corner.
* Only consider fully connected nodes for this check.
* All of the nodes within the test area must have the same attributes.
* All of the nodes must be approximately co-planar w.r.t the NW node's normal, with the
* exception of 1x1 areas which can be any angle.
*/
bool CNavMesh::TestArea( CNavNode *node, int width, int height )
{
Vector normal = *node->GetNormal();
float d = -DotProduct( normal, *node->GetPosition() );
bool nodeCrouch = node->m_crouch[ SOUTH_EAST ];
// The area's interior will be the south-east side of this north-west node.
// If that interior space is blocked, there's no space to build an area.
if ( node->m_isBlocked[ SOUTH_EAST ] )
{
return false;
}
int nodeAttributes = node->GetAttributes() & ~NAV_MESH_CROUCH;
const float offPlaneTolerance = 5.0f;
CNavNode *vertNode, *horizNode;
vertNode = node;
int x,y;
for( y=0; y<height; y++ )
{
horizNode = vertNode;
for( x=0; x<width; x++ )
{
//
// Compute the crouch attributes for the test node, taking into account only the side(s) of the node
// that are in the area
// NOTE: The nodes on the south and east borders of an area aren't contained in the area. This means that
// crouch attributes and blocked state need to be checked to the south and east of the southEdge and eastEdge nodes.
bool horizNodeCrouch = false;
bool westEdge = (x == 0);
bool eastEdge = (x == width - 1);
bool northEdge = (y == 0);
bool southEdge = (y == height - 1);
// Check corners first
if ( northEdge && westEdge )
{
// The area's interior will be the south-east side of this north-west node.
// If that interior space is blocked, there's no space to build an area.
horizNodeCrouch = horizNode->m_crouch[ SOUTH_EAST ];
if ( horizNode->m_isBlocked[ SOUTH_EAST ] )
{
return false;
}
}
else if ( northEdge && eastEdge )
{
// interior space of the area extends one more cell to the east past the easternmost nodes.
// This means we need to check to the southeast as well as the southwest.
horizNodeCrouch = horizNode->m_crouch[ SOUTH_EAST ] || horizNode->m_crouch[ SOUTH_WEST ];
if ( horizNode->m_isBlocked[ SOUTH_EAST ] || horizNode->m_isBlocked[ SOUTH_WEST ] )
{
return false;
}
}
else if ( southEdge && westEdge )
{
// The interior space of the area extends one more cell to the south past the southernmost nodes.
// This means we need to check to the southeast as well as the southwest.
horizNodeCrouch = horizNode->m_crouch[ SOUTH_EAST ] || horizNode->m_crouch[ NORTH_EAST ];
if ( horizNode->m_isBlocked[ SOUTH_EAST ] || horizNode->m_isBlocked[ NORTH_EAST ] )
{
return false;
}
}
else if ( southEdge && eastEdge )
{
// This node is completely in the interior of the area, so we need to check in all directions.
horizNodeCrouch = (horizNode->GetAttributes() & NAV_MESH_CROUCH) != 0;
if ( horizNode->IsBlockedInAnyDirection() )
{
return false;
}
}
// check sides next
else if ( northEdge )
{
horizNodeCrouch = horizNode->m_crouch[ SOUTH_EAST ] || horizNode->m_crouch[ SOUTH_WEST ];
if ( horizNode->m_isBlocked[ SOUTH_EAST ] || horizNode->m_isBlocked[ SOUTH_WEST ] )
{
return false;
}
}
else if ( southEdge )
{
// This node is completely in the interior of the area, so we need to check in all directions.
horizNodeCrouch = (horizNode->GetAttributes() & NAV_MESH_CROUCH) != 0;
if ( horizNode->IsBlockedInAnyDirection() )
{
return false;
}
}
else if ( eastEdge )
{
// This node is completely in the interior of the area, so we need to check in all directions.
horizNodeCrouch = (horizNode->GetAttributes() & NAV_MESH_CROUCH) != 0;
if ( horizNode->IsBlockedInAnyDirection() )
{
return false;
}
}
else if ( westEdge )
{
horizNodeCrouch = horizNode->m_crouch[ SOUTH_EAST ] || horizNode->m_crouch[ NORTH_EAST ];
if ( horizNode->m_isBlocked[ SOUTH_EAST ] || horizNode->m_isBlocked[ NORTH_EAST ] )
{
return false;
}
}
// finally, we have a center node
else
{
// This node is completely in the interior of the area, so we need to check in all directions.
horizNodeCrouch = (horizNode->GetAttributes() & NAV_MESH_CROUCH) != 0;
if ( horizNode->IsBlockedInAnyDirection() )
{
return false;
}
}
// all nodes must be crouch/non-crouch
if ( nodeCrouch != horizNodeCrouch )
return false;
// all nodes must have the same non-crouch attributes
int horizNodeAttributes = horizNode->GetAttributes() & ~NAV_MESH_CROUCH;
if (horizNodeAttributes != nodeAttributes)
return false;
if (horizNode->IsCovered())
return false;
if (!horizNode->IsClosedCell())
return false;
if ( !CheckObstacles( horizNode, width, height, x, y ) )
return false;
horizNode = horizNode->GetConnectedNode( EAST );
if (horizNode == NULL)
return false;
// nodes must lie on/near the plane
if (width > 1 || height > 1)
{
float dist = (float)fabs( DotProduct( *horizNode->GetPosition(), normal ) + d );
if (dist > offPlaneTolerance)
return false;
}
}
// Check the final (x=width) node, the above only checks thru x=width-1
if ( !CheckObstacles( horizNode, width, height, x, y ) )
return false;
vertNode = vertNode->GetConnectedNode( SOUTH );
if (vertNode == NULL)
return false;
// nodes must lie on/near the plane
if (width > 1 || height > 1)
{
float dist = (float)fabs( DotProduct( *vertNode->GetPosition(), normal ) + d );
if (dist > offPlaneTolerance)
return false;
}
}
// check planarity of southern edge
if (width > 1 || height > 1)
{
horizNode = vertNode;
for( x=0; x<width; x++ )
{
if ( !CheckObstacles( horizNode, width, height, x, y ) )
return false;
horizNode = horizNode->GetConnectedNode( EAST );
if (horizNode == NULL)
return false;
// nodes must lie on/near the plane
float dist = (float)fabs( DotProduct( *horizNode->GetPosition(), normal ) + d );
if (dist > offPlaneTolerance)
return false;
}
// Check the final (x=width) node, the above only checks thru x=width-1
if ( !CheckObstacles( horizNode, width, height, x, y ) )
return false;
}
vertNode = node;
for( y=0; y<height; ++y )
{
horizNode = vertNode;
for( int x=0; x<width; ++x )
{
// look for odd jump areas (3 points on the ground, 1 point floating much higher or lower)
if ( !TestForValidJumpArea( horizNode ) )
{
return false;
}
// Now that we've done the quick checks, test for a valid crouch area.
// This finds pillars etc in the middle of 4 nodes, that weren't found initially.
if ( nodeCrouch && !TestForValidCrouchArea( horizNode ) )
{
return false;
}
horizNode = horizNode->GetConnectedNode( EAST );
}
vertNode = vertNode->GetConnectedNode( SOUTH );
}
if ( m_generationMode == GENERATE_INCREMENTAL )
{
// Incremental generation needs to check that it's not overlapping existing areas...
const Vector *nw = node->GetPosition();
vertNode = node;
for( int y=0; y<height; ++y )
{
vertNode = vertNode->GetConnectedNode( SOUTH );
}
const Vector *sw = vertNode->GetPosition();
horizNode = node;
for( int x=0; x<width; ++x )
{
horizNode = horizNode->GetConnectedNode( EAST );
}
const Vector *ne = horizNode->GetPosition();
vertNode = horizNode;
for( int y=0; y<height; ++y )
{
vertNode = vertNode->GetConnectedNode( SOUTH );
}
const Vector *se = vertNode->GetPosition();
TestOverlapping test( *nw, *ne, *sw, *se );
if ( test.OverlapsExistingArea() )
return false;
}
return true;
}
//--------------------------------------------------------------------------------------------------------------
/**
* Checks if a node has an untraversable obstacle in any direction to a neighbor.
* width and height are size of nav area this node would be a part of, x and y are node's position
* within that grid
*/
bool CNavMesh::CheckObstacles( CNavNode *node, int width, int height, int x, int y )
{
// any area bigger than 1x1 can't have obstacles in any connection between nodes
if ( width > 1 || height > 1 )
{
if ( ( x > 0 ) && ( node->m_obstacleHeight[WEST] > MaxTraversableHeight ) )
return false;
if ( ( y > 0 ) && ( node->m_obstacleHeight[NORTH] > MaxTraversableHeight ) )
return false;
if ( ( x < width-1 ) && ( node->m_obstacleHeight[EAST] > MaxTraversableHeight ) )
return false;
if ( ( y < height-1 ) && ( node->m_obstacleHeight[SOUTH] > MaxTraversableHeight ) )
return false;
}
// 1x1 area can have obstacles, that area will get fixed up later
return true;
}
//--------------------------------------------------------------------------------------------------------------
/**
* Create a nav area, and mark all nodes it overlaps as "covered"
* NOTE: Nodes on the east and south edges are not included.
* Returns number of nodes covered by this area, or -1 for error;
*/
int CNavMesh::BuildArea( CNavNode *node, int width, int height )
{
CNavNode *nwNode = node;
CNavNode *neNode = NULL;
CNavNode *swNode = NULL;
CNavNode *seNode = NULL;
CNavNode *vertNode = node;
CNavNode *horizNode;
int coveredNodes = 0;
for( int y=0; y<height; y++ )
{
horizNode = vertNode;
for( int x=0; x<width; x++ )
{
horizNode->Cover();
++coveredNodes;
horizNode = horizNode->GetConnectedNode( EAST );
}
if (y == 0)
neNode = horizNode;
vertNode = vertNode->GetConnectedNode( SOUTH );
}
swNode = vertNode;
horizNode = vertNode;
for( int x=0; x<width; x++ )
{
horizNode = horizNode->GetConnectedNode( EAST );
}
seNode = horizNode;
if (!nwNode || !neNode || !seNode || !swNode)
{
Error( "BuildArea - NULL node.\n" );
return -1;
}
CNavArea *area = CreateArea();
if (area == NULL)
{
Error( "BuildArea: Out of memory.\n" );
return -1;
}
area->Build( nwNode, neNode, seNode, swNode );
TheNavAreas.AddToTail( area );
// since all internal nodes have the same attributes, set this area's attributes
area->SetAttributes( node->GetAttributes() );
// If any of the corners have an obstacle in the direction of another corner, then there's an internal obstruction of this nav node.
// Mark it as not mergable so it doesn't become a part of anything else and we will fix it up later.
if ( nwNode->m_obstacleHeight[SOUTH] > MaxTraversableHeight || nwNode->m_obstacleHeight[EAST] > MaxTraversableHeight ||
neNode->m_obstacleHeight[WEST] > MaxTraversableHeight || neNode->m_obstacleHeight[SOUTH] > MaxTraversableHeight ||
seNode->m_obstacleHeight[NORTH] > MaxTraversableHeight || seNode->m_obstacleHeight[WEST] > MaxTraversableHeight ||
swNode->m_obstacleHeight[EAST] > MaxTraversableHeight || swNode->m_obstacleHeight[NORTH] > MaxTraversableHeight )
{
Assert( width == 1 ); // We should only ever try to build a 1x1 area out of any two nodes that have an obstruction between them
Assert( height == 1 );
area->SetAttributes( area->GetAttributes() | NAV_MESH_NO_MERGE );
}
// Check that the node was crouch in the right direction
bool nodeCrouch = node->m_crouch[ SOUTH_EAST ];
if ( (area->GetAttributes() & NAV_MESH_CROUCH) && !nodeCrouch )
{
area->SetAttributes( area->GetAttributes() & ~NAV_MESH_CROUCH );
}
return coveredNodes;
}
//--------------------------------------------------------------------------------------------------------------
/**
* This function uses the CNavNodes that have been sampled from the map to
* generate CNavAreas - rectangular areas of "walkable" space. These areas
* are connected to each other, proving information on know how to move from
* area to area.
*
* This is a "greedy" algorithm that attempts to cover the walkable area
* with the fewest, largest, rectangles.
*/
void CNavMesh::CreateNavAreasFromNodes( void )
{
// haven't yet seen a map use larger than 30...
int tryWidth = nav_area_max_size.GetInt();
int tryHeight = tryWidth;
int uncoveredNodes = CNavNode::GetListLength();
while( uncoveredNodes > 0 )
{
for( CNavNode *node = CNavNode::GetFirst(); node; node = node->GetNext() )
{
if (node->IsCovered())
continue;
if (TestArea( node, tryWidth, tryHeight ))
{
int covered = BuildArea( node, tryWidth, tryHeight );
if (covered < 0)
{
Error( "Generate: Error - Data corrupt.\n" );
return;
}
uncoveredNodes -= covered;
}
}
if (tryWidth >= tryHeight)
--tryWidth;
else
--tryHeight;
if (tryWidth <= 0 || tryHeight <= 0)
break;
}
if ( !TheNavAreas.Count() )
{
// If we somehow have no areas, don't try to create an impossibly-large grid
AllocateGrid( 0, 0, 0, 0 );
return;
}
Extent extent;
extent.lo.x = 9999999999.9f;
extent.lo.y = 9999999999.9f;
extent.hi.x = -9999999999.9f;
extent.hi.y = -9999999999.9f;
// compute total extent
FOR_EACH_VEC( TheNavAreas, it )
{
CNavArea *area = TheNavAreas[ it ];
Extent areaExtent;
area->GetExtent( &areaExtent );
if (areaExtent.lo.x < extent.lo.x)
extent.lo.x = areaExtent.lo.x;
if (areaExtent.lo.y < extent.lo.y)
extent.lo.y = areaExtent.lo.y;
if (areaExtent.hi.x > extent.hi.x)
extent.hi.x = areaExtent.hi.x;
if (areaExtent.hi.y > extent.hi.y)
extent.hi.y = areaExtent.hi.y;
}
// add the areas to the grid
AllocateGrid( extent.lo.x, extent.hi.x, extent.lo.y, extent.hi.y );
FOR_EACH_VEC( TheNavAreas, git )
{
AddNavArea( TheNavAreas[ git ] );
}
ConnectGeneratedAreas();
MarkPlayerClipAreas();
MarkJumpAreas(); // mark jump areas before we merge generated areas, so we don't merge jump and non-jump areas
MergeGeneratedAreas();
SplitAreasUnderOverhangs();
SquareUpAreas();
MarkStairAreas();
#ifndef CSTRIKE_DLL // CSBots use jump areas
StichAndRemoveJumpAreas();
#endif
HandleObstacleTopAreas();
FixUpGeneratedAreas();
/// @TODO: incremental generation doesn't create ladders yet
if ( m_generationMode != GENERATE_INCREMENTAL )
{
for ( int i=0; i<m_ladders.Count(); ++i )
{
CNavLadder *ladder = m_ladders[i];
ladder->ConnectGeneratedLadder( 0.0f );
}
}
}
//--------------------------------------------------------------------------------------------------------------
// adds walkable positions for any/all positions a mod specifies
void CNavMesh::AddWalkableSeeds( void )
{
CBaseEntity *spawn = gEntList.FindEntityByClassname( NULL, GetPlayerSpawnName() );
if (spawn )
{
// snap it to the sampling grid
Vector pos = spawn->GetAbsOrigin();
pos.x = TheNavMesh->SnapToGrid( pos.x );
pos.y = TheNavMesh->SnapToGrid( pos.y );
Vector normal;
if ( FindGroundForNode( &pos, &normal ) )
{
AddWalkableSeed( pos, normal );
}
}
}
//--------------------------------------------------------------------------------------------------------------
/**
* Initiate the generation process
*/
void CNavMesh::BeginGeneration( bool incremental )
{
IGameEvent *event = gameeventmanager->CreateEvent( "nav_generate" );
if ( event )
{
gameeventmanager->FireEvent( event );
}
#ifdef TERROR
engine->ServerCommand( "director_stop\nnb_delete_all\n" );
if ( !incremental && !engine->IsDedicatedServer() )
{
CBasePlayer *host = UTIL_GetListenServerHost();
if ( host )
{
host->ChangeTeam( TEAM_SPECTATOR );
}
}
#else
engine->ServerCommand( "bot_kick\n" );
#endif
// Right now, incrementally-generated areas won't connect to existing areas automatically.
// Since this means hand-editing will be necessary, don't do a full analyze.
if ( incremental )
{
nav_quicksave.SetValue( 1 );
}
m_generationState = SAMPLE_WALKABLE_SPACE;
m_sampleTick = 0;
m_generationMode = (incremental) ? GENERATE_INCREMENTAL : GENERATE_FULL;
lastMsgTime = 0.0f;
// clear any previous mesh
DestroyNavigationMesh( incremental );
SetNavPlace( UNDEFINED_PLACE );
// build internal representations of ladders, which are used to find new walkable areas
if ( !incremental ) ///< @incremental update doesn't build ladders to avoid overlapping existing ones
{
BuildLadders();
}
// start sampling from a spawn point
if ( !incremental )
{
AddWalkableSeeds();
}
// the system will see this NULL and select the next walkable seed
m_currentNode = NULL;
// if there are no seed points, we can't generate
if (m_walkableSeeds.Count() == 0)
{
m_generationMode = GENERATE_NONE;
Msg( "No valid walkable seed positions. Cannot generate Navigation Mesh.\n" );
return;
}
// initialize seed list index
m_seedIdx = 0;
Msg( "Generating Navigation Mesh...\n" );
m_generationStartTime = Plat_FloatTime();
}
//--------------------------------------------------------------------------------------------------------------
/**
* Re-analyze an existing Mesh. Determine Hiding Spots, Encounter Spots, etc.
*/
void CNavMesh::BeginAnalysis( bool quitWhenFinished )
{
#ifdef TERROR
if ( !engine->IsDedicatedServer() )
{
CBasePlayer *host = UTIL_GetListenServerHost();
if ( host )
{
host->ChangeTeam( TEAM_SPECTATOR );
engine->ServerCommand( "director_no_death_check 1\ndirector_stop\nnb_delete_all\n" );
ConVarRef mat_fullbright( "mat_fullbright" );
ConVarRef mat_hdr_level( "mat_hdr_level" );
if( mat_fullbright.GetBool() )
{
Warning( "Setting mat_fullbright 0\n" );
mat_fullbright.SetValue( 0 );
}
if ( mat_hdr_level.GetInt() < 2 )
{
Warning( "Enabling HDR and reloading materials\n" );
mat_hdr_level.SetValue( 2 );
engine->ClientCommand( host->edict(), "mat_reloadallmaterials\n" );
}
// Running a threaded server breaks our lighting calculations
ConVarRef host_thread_mode( "host_thread_mode" );
m_hostThreadModeRestoreValue = host_thread_mode.GetInt();
host_thread_mode.SetValue( 0 );
ConVarRef mat_queue_mode( "mat_queue_mode" );
mat_queue_mode.SetValue( 0 );
}
}
#endif
// Remove and re-add elements in TheNavAreas, to ensure indices are useful for progress feedback
NavAreaVector tmpSet;
{
FOR_EACH_VEC( TheNavAreas, it )
{
tmpSet.AddToTail( TheNavAreas[it] );
}
}
TheNavAreas.RemoveAll();
{
FOR_EACH_VEC( tmpSet, it )
{
TheNavAreas.AddToTail( tmpSet[it] );
}
}
CBaseEntity* pEnt = NULL;
while ( (pEnt = gEntList.FindEntityByClassname( pEnt, "point_hiding_spot" )) != NULL )
{
UTIL_Remove( pEnt );
}
DestroyHidingSpots();
m_generationState = FIND_HIDING_SPOTS;
m_generationIndex = 0;
m_generationMode = GENERATE_ANALYSIS_ONLY;
m_bQuitWhenFinished = quitWhenFinished;
lastMsgTime = 0.0f;
m_generationStartTime = Plat_FloatTime();
}
//--------------------------------------------------------------------------------------------------------------
void ShowViewPortPanelToAll( const char * name, bool bShow, KeyValues *data )
{
CRecipientFilter filter;
filter.AddAllPlayers();
filter.MakeReliable();
int count = 0;
KeyValues *subkey = NULL;
if ( data )
{
subkey = data->GetFirstSubKey();
while ( subkey )
{
count++; subkey = subkey->GetNextKey();
}
subkey = data->GetFirstSubKey(); // reset
}
CCSUsrMsg_VGUIMenu msg;
msg.set_name( name );
msg.set_show( bShow );
// write additional data (be careful not more than 192 bytes!)
while ( subkey )
{
CCSUsrMsg_VGUIMenu::Subkey *pMsgSubkey = msg.add_subkeys();
pMsgSubkey->set_name( subkey->GetName() );
pMsgSubkey->set_str( subkey-> GetString() );
subkey = subkey->GetNextKey();
}
SendUserMessage( filter, CS_UM_VGUIMenu, msg );
}
//--------------------------------------------------------------------------------------------------------------
static void AnalysisProgress( const char *msg, int ticks, int current, bool showPercent = true )
{
const float MsgInterval = 10.0f;
float now = Plat_FloatTime();
if ( now > lastMsgTime + MsgInterval )
{
if ( showPercent && ticks )
{
Msg( "%s %.0f%%\n", msg, current*100.0f/ticks );
}
else
{
Msg( "%s\n", msg );
}
lastMsgTime = now;
}
KeyValues *data = new KeyValues("data");
data->SetString( "msg", msg );
data->SetInt( "total", ticks );
data->SetInt( "current", current );
ShowViewPortPanelToAll( PANEL_NAV_PROGRESS, true, data );
data->deleteThis();
}
//--------------------------------------------------------------------------------------------------------------
static void HideAnalysisProgress( void )
{
KeyValues *data = new KeyValues("data");
ShowViewPortPanelToAll( PANEL_NAV_PROGRESS, false, data );
data->deleteThis();
}
//--------------------------------------------------------------------------------------------------------------
/**
* Process the auto-generation for 'maxTime' seconds. return false if generation is complete.
*/
bool CNavMesh::UpdateGeneration( float maxTime )
{
double startTime = Plat_FloatTime();
static unsigned int s_movedPlayerToArea = 0; // Last area we moved a player to for lighting calcs
static CountdownTimer s_playerSettleTimer; // Settle time after moving the player for lighting calcs
static CUtlVector<CNavArea *> s_unlitAreas;
static CUtlVector<CNavArea *> s_unlitSeedAreas;
static ConVarRef host_thread_mode( "host_thread_mode" );
switch( m_generationState )
{
//---------------------------------------------------------------------------
case SAMPLE_WALKABLE_SPACE:
{
AnalysisProgress( "Sampling walkable space...", 100, m_sampleTick / 10, false );
m_sampleTick = ( m_sampleTick + 1 ) % 1000;
while ( SampleStep() )
{
if ( Plat_FloatTime() - startTime > maxTime )
{
return true;
}
}
// sampling is complete, now build nav areas
m_generationState = CREATE_AREAS_FROM_SAMPLES;
return true;
}
//---------------------------------------------------------------------------
case CREATE_AREAS_FROM_SAMPLES:
{
Msg( "Creating navigation areas from sampled data...\n" );
// Select all pre-existing areas
if ( m_generationMode == GENERATE_INCREMENTAL )
{
ClearSelectedSet();
FOR_EACH_VEC( TheNavAreas, nit )
{
CNavArea *area = TheNavAreas[nit];
AddToSelectedSet( area );
}
}
// Create new areas
CreateNavAreasFromNodes();
// And toggle the selection, so we end up with the new areas
if ( m_generationMode == GENERATE_INCREMENTAL )
{
CommandNavToggleSelectedSet();
}
DestroyHidingSpots();
// Remove and re-add elements in TheNavAreas, to ensure indices are useful for progress feedback
NavAreaVector tmpSet;
{
FOR_EACH_VEC( TheNavAreas, it )
{
tmpSet.AddToTail( TheNavAreas[it] );
}
}
TheNavAreas.RemoveAll();
{
FOR_EACH_VEC( tmpSet, it )
{
TheNavAreas.AddToTail( tmpSet[it] );
}
}
m_generationState = FIND_HIDING_SPOTS;
m_generationIndex = 0;
return true;
}
//---------------------------------------------------------------------------
case FIND_HIDING_SPOTS:
{
while( m_generationIndex < TheNavAreas.Count() )
{
CNavArea *area = TheNavAreas[ m_generationIndex ];
++m_generationIndex;
area->ComputeHidingSpots();
// don't go over our time allotment
if( Plat_FloatTime() - startTime > maxTime )
{
AnalysisProgress( "Finding hiding spots...", 100, 100 * m_generationIndex / TheNavAreas.Count() );
return true;
}
}
Msg( "Finding hiding spots...DONE\n" );
m_generationState = FIND_ENCOUNTER_SPOTS;
m_generationIndex = 0;
return true;
}
//---------------------------------------------------------------------------
case FIND_ENCOUNTER_SPOTS:
{
while( m_generationIndex < TheNavAreas.Count() )
{
CNavArea *area = TheNavAreas[ m_generationIndex ];
++m_generationIndex;
area->ComputeSpotEncounters();
// don't go over our time allotment
if( Plat_FloatTime() - startTime > maxTime )
{
AnalysisProgress( "Finding encounter spots...", 100, 100 * m_generationIndex / TheNavAreas.Count() );
return true;
}
}
Msg( "Finding encounter spots...DONE\n" );
m_generationState = FIND_SNIPER_SPOTS;
m_generationIndex = 0;
return true;
}
//---------------------------------------------------------------------------
case FIND_SNIPER_SPOTS:
{
while( m_generationIndex < TheNavAreas.Count() )
{
CNavArea *area = TheNavAreas[ m_generationIndex ];
++m_generationIndex;
area->ComputeSniperSpots();
// don't go over our time allotment
if( Plat_FloatTime() - startTime > maxTime )
{
AnalysisProgress( "Finding sniper spots...", 100, 100 * m_generationIndex / TheNavAreas.Count() );
return true;
}
}
Msg( "Finding sniper spots...DONE\n" );
if ( IsMeshVisibilityGenerated() )
{
m_generationState = COMPUTE_MESH_VISIBILITY;
m_generationIndex = 0;
BeginVisibilityComputations();
Msg( "Computing mesh visibility...\n" );
}
else
{
// no visibility data desired - skip directly to next analyze step
FOR_EACH_VEC( TheNavAreas, it )
{
CNavArea *area = TheNavAreas[ it ];
area->ResetPotentiallyVisibleAreas();
}
m_generationState = FIND_EARLIEST_OCCUPY_TIMES;
m_generationIndex = 0;
}
return true;
}
//---------------------------------------------------------------------------
case COMPUTE_MESH_VISIBILITY:
{
while( m_generationIndex < TheNavAreas.Count() )
{
CNavArea *area = TheNavAreas[ m_generationIndex ];
++m_generationIndex;
area->ComputeVisibilityToMesh();
// don't go over our time allotment
if ( Plat_FloatTime() - startTime > maxTime )
{
AnalysisProgress( "Computing mesh visibility...", 100, 100 * m_generationIndex / TheNavAreas.Count() );
return true;
}
}
Msg( "Optimizing mesh visibility...\n" );
EndVisibilityComputations();
Msg( "Computing mesh visibility...DONE\n" );
m_generationState = FIND_EARLIEST_OCCUPY_TIMES;
m_generationIndex = 0;
return true;
}
//---------------------------------------------------------------------------
case FIND_EARLIEST_OCCUPY_TIMES:
{
while( m_generationIndex < TheNavAreas.Count() )
{
CNavArea *area = TheNavAreas[ m_generationIndex ];
++m_generationIndex;
area->ComputeEarliestOccupyTimes();
// don't go over our time allotment
if( Plat_FloatTime() - startTime > maxTime )
{
AnalysisProgress( "Finding earliest occupy times...", 100, 100 * m_generationIndex / TheNavAreas.Count() );
return true;
}
}
Msg( "Finding earliest occupy times...DONE\n" );
#ifdef NAV_ANALYZE_LIGHT_INTENSITY
bool shouldSkipLightComputation = ( m_generationMode == GENERATE_INCREMENTAL || engine->IsDedicatedServer() );
#else
bool shouldSkipLightComputation = true;
#endif
if ( shouldSkipLightComputation )
{
m_generationState = CUSTOM; // no light intensity calcs for incremental generation or dedicated servers
}
else
{
m_generationState = FIND_LIGHT_INTENSITY;
s_playerSettleTimer.Invalidate();
CNavArea::MakeNewMarker();
s_unlitAreas.RemoveAll();
FOR_EACH_VEC( TheNavAreas, nit )
{
s_unlitAreas.AddToTail( TheNavAreas[nit] );
s_unlitSeedAreas.AddToTail( TheNavAreas[nit] );
}
}
m_generationIndex = 0;
return true;
}
//---------------------------------------------------------------------------
case FIND_LIGHT_INTENSITY:
{
host_thread_mode.SetValue( 0 ); // need non-threaded server for light calcs
CBasePlayer *host = UTIL_GetListenServerHost();
if ( !s_unlitAreas.Count() || !host )
{
Msg( "Finding light intensity...DONE\n" );
m_generationState = CUSTOM;
m_generationIndex = 0;
return true;
}
if ( !s_playerSettleTimer.IsElapsed() )
return true; // wait for eyePos to settle
// Now try to compute lighting for remaining areas
int sit = 0;
while( sit < s_unlitAreas.Count() )
{
CNavArea *area = s_unlitAreas[sit];
if ( area->ComputeLighting() )
{
s_unlitSeedAreas.FindAndRemove( area );
s_unlitAreas.Remove( sit );
continue;
}
else
{
++sit;
}
}
if ( s_unlitAreas.Count() )
{
if ( s_unlitSeedAreas.Count() )
{
CNavArea *moveArea = s_unlitSeedAreas[0];
s_unlitSeedAreas.FastRemove( 0 );
//Msg( "Moving to new area %d to compute lighting for %d/%d areas\n", moveArea->GetID(), s_unlitAreas.Count(), TheNavAreas.Count() );
Vector eyePos = moveArea->GetCenter();
float height;
if ( GetGroundHeight( eyePos, &height ) )
{
eyePos.z = height + HalfHumanHeight - StepHeight; // players light from their centers, and we light from slightly below that, to allow for low ceilings
}
else
{
eyePos.z += HalfHumanHeight - StepHeight; // players light from their centers, and we light from slightly below that, to allow for low ceilings
}
host->SetAbsOrigin( eyePos );
AnalysisProgress( "Finding light intensity...", 100, 100 * (TheNavAreas.Count() - s_unlitAreas.Count()) / TheNavAreas.Count() );
s_movedPlayerToArea = moveArea->GetID();
s_playerSettleTimer.Start( 0.1f );
return true;
}
else
{
Msg( "Finding light intensity...DONE (%d unlit areas)\n", s_unlitAreas.Count() );
if ( s_unlitAreas.Count() )
{
Warning( "To see unlit areas:\n" );
for ( int sit=0; sit<s_unlitAreas.Count(); ++sit )
{
CNavArea *area = s_unlitAreas[ sit ];
Warning( "nav_unmark; nav_mark %d; nav_warp_to_mark;\n", area->GetID() );
}
}
m_generationState = CUSTOM;
m_generationIndex = 0;
}
}
Msg( "Finding light intensity...DONE\n" );
m_generationState = CUSTOM;
m_generationIndex = 0;
return true;
}
//---------------------------------------------------------------------------
case CUSTOM:
{
if ( m_generationIndex == 0 )
{
BeginCustomAnalysis( m_generationMode == GENERATE_INCREMENTAL );
Msg( "Start custom...\n ");
}
while( m_generationIndex < TheNavAreas.Count() )
{
CNavArea *area = TheNavAreas[ m_generationIndex ];
++m_generationIndex;
area->CustomAnalysis( m_generationMode == GENERATE_INCREMENTAL );
// don't go over our time allotment
if( Plat_FloatTime() - startTime > maxTime )
{
AnalysisProgress( "Custom game-specific analysis...", 100, 100 * m_generationIndex / TheNavAreas.Count() );
return true;
}
}
Msg( "Post custom...\n ");
PostCustomAnalysis();
EndCustomAnalysis();
Msg( "Custom game-specific analysis...DONE\n" );
m_generationState = SAVE_NAV_MESH;
m_generationIndex = 0;
ConVarRef mat_queue_mode( "mat_queue_mode" );
mat_queue_mode.SetValue( -1 );
host_thread_mode.SetValue( m_hostThreadModeRestoreValue ); // restore this
return true;
}
//---------------------------------------------------------------------------
case SAVE_NAV_MESH:
{
if ( m_generationMode == GENERATE_ANALYSIS_ONLY || m_generationMode == GENERATE_FULL )
{
m_isAnalyzed = true;
}
// generation complete!
float generationTime = Plat_FloatTime() - m_generationStartTime;
Msg( "Generation complete! %0.1f seconds elapsed.\n", generationTime );
bool restart = m_generationMode != GENERATE_INCREMENTAL;
m_generationMode = GENERATE_NONE;
m_isLoaded = true;
ClearWalkableSeeds();
HideAnalysisProgress();
// save the mesh
if (Save())
{
Msg( "Navigation map '%s' saved.\n", GetFilename() );
}
else
{
const char *filename = GetFilename();
Msg( "ERROR: Cannot save navigation map '%s'.\n", (filename) ? filename : "(null)" );
}
if ( m_bQuitWhenFinished )
{
engine->ServerCommand( "quit\n" );
}
else if ( restart )
{
engine->ChangeLevel( STRING( gpGlobals->mapname ), NULL );
}
else
{
FOR_EACH_VEC( TheNavAreas, it )
{
TheNavAreas[ it ]->ResetNodes();
}
#if !(DEBUG_NAV_NODES)
// destroy navigation nodes created during map generation
CNavNode *node, *next;
for( node = CNavNode::m_list; node; node = next )
{
next = node->m_next;
delete node;
}
CNavNode::m_list = NULL;
CNavNode::m_listLength = 0;
CNavNode::m_nextID = 1;
#endif // !(DEBUG_NAV_NODES)
}
return false;
}
}
return false;
}
//--------------------------------------------------------------------------------------------------------------
/**
* Define the name of player spawn entities
*/
void CNavMesh::SetPlayerSpawnName( const char *name )
{
if (m_spawnName)
{
delete [] m_spawnName;
}
m_spawnName = new char [ strlen(name) + 1 ];
strcpy( m_spawnName, name );
}
//--------------------------------------------------------------------------------------------------------------
/**
* Return name of player spawn entity
*/
const char *CNavMesh::GetPlayerSpawnName( void ) const
{
if (m_spawnName)
return m_spawnName;
// default value
return "info_player_start";
}
//--------------------------------------------------------------------------------------------------------------
/**
* Add a nav node and connect it.
* Node Z positions are ground level.
*/
CNavNode *CNavMesh::AddNode( const Vector &destPos, const Vector &normal, NavDirType dir, CNavNode *source, bool isOnDisplacement,
float obstacleHeight, float obstacleStartDist, float obstacleEndDist )
{
// check if a node exists at this location
CNavNode *node = CNavNode::GetNode( destPos );
// if no node exists, create one
bool useNew = false;
if (node == NULL)
{
node = new CNavNode( destPos, normal, source, isOnDisplacement );
OnNodeAdded( node );
useNew = true;
}
// connect source node to new node
source->ConnectTo( node, dir, obstacleHeight, obstacleStartDist, obstacleEndDist );
// optimization: if deltaZ changes very little, assume connection is commutative
const float zTolerance = 50.0f;
float deltaZ = source->GetPosition()->z - destPos.z;
if (fabs( deltaZ ) < zTolerance)
{
if ( obstacleHeight > 0 )
{
obstacleHeight = MAX( obstacleHeight + deltaZ, 0 );
Assert( obstacleHeight > 0 );
}
node->ConnectTo( source, OppositeDirection( dir ), obstacleHeight, GenerationStepSize - obstacleEndDist, GenerationStepSize - obstacleStartDist );
node->MarkAsVisited( OppositeDirection( dir ) );
}
if (useNew)
{
// new node becomes current node
m_currentNode = node;
}
node->CheckCrouch();
// determine if there's a cliff nearby and set an attribute on this node
for ( int i = 0; i < NUM_DIRECTIONS; i++ )
{
NavDirType dir = (NavDirType) i;
if ( CheckCliff( node->GetPosition(), dir ) )
{
node->SetAttributes( node->GetAttributes() | NAV_MESH_CLIFF );
break;
}
}
return node;
}
//--------------------------------------------------------------------------------------------------------------
inline CNavNode *LadderEndSearch( const Vector *pos, NavDirType mountDir )
{
Vector center = *pos;
AddDirectionVector( ¢er, mountDir, HalfHumanWidth );
//
// Test the ladder dismount point first, then each cardinal direction one and two steps away
//
for( int d=(-1); d<2*NUM_DIRECTIONS; ++d )
{
Vector tryPos = center;
if (d >= NUM_DIRECTIONS)
AddDirectionVector( &tryPos, (NavDirType)(d - NUM_DIRECTIONS), 2.0f*GenerationStepSize );
else if (d >= 0)
AddDirectionVector( &tryPos, (NavDirType)d, GenerationStepSize );
// step up a rung, to ensure adjacent floors are below us
tryPos.z += GenerationStepSize;
tryPos.x = TheNavMesh->SnapToGrid( tryPos.x );
tryPos.y = TheNavMesh->SnapToGrid( tryPos.y );
// adjust height to account for sloping areas
Vector tryNormal;
if (TheNavMesh->GetGroundHeight( tryPos, &tryPos.z, &tryNormal ) == false)
continue;
// make sure this point is not on the other side of a wall
const float fudge = 4.0f;
trace_t result;
UTIL_TraceHull( center + Vector( 0, 0, fudge ), tryPos + Vector( 0, 0, fudge ), NavTraceMins, NavTraceMaxs, TheNavMesh->GetGenerationTraceMask(), NULL, COLLISION_GROUP_NONE, &result );
if (result.fraction != 1.0f || result.startsolid)
continue;
// if no node exists here, create one and continue the search
if (CNavNode::GetNode( tryPos ) == NULL)
{
return new CNavNode( tryPos, tryNormal, NULL, false );
}
}
return NULL;
}
//--------------------------------------------------------------------------------------------------------------
bool CNavMesh::FindGroundForNode( Vector *pos, Vector *normal )
{
CTraceFilterWalkableEntities filter( NULL, COLLISION_GROUP_PLAYER_MOVEMENT, WALK_THRU_EVERYTHING );
trace_t tr;
Vector start( pos->x, pos->y, pos->z + VEC_DUCK_HULL_MAX.z - 0.1f );
Vector end( *pos );
end.z -= DeathDrop;
UTIL_TraceHull(
start,
end,
NavTraceMins,
NavTraceMaxs,
GetGenerationTraceMask(),
&filter,
&tr );
*pos = tr.endpos;
*normal = tr.plane.normal;
return ( !tr.allsolid );
}
//--------------------------------------------------------------------------------------------------------------
void DrawTrace( const trace_t *trace )
{
/*
if ( trace->fraction > 0.0f && !trace->startsolid )
{
NDebugOverlay::SweptBox( trace->startpos, trace->endpos, NavTraceMins, NavTraceMaxs, vec3_angle, 0, 255, 0, 45, 100 );
}
else
{
NDebugOverlay::SweptBox( trace->startpos, trace->endpos, NavTraceMins, NavTraceMaxs, vec3_angle, 255, 0, 0, 45, 100 );
}
*/
}
//--------------------------------------------------------------------------------------------------------------
bool StayOnFloor( trace_t *trace, float zLimit /* = DeathDrop */ )
{
Vector start( trace->endpos );
Vector end( start );
end.z -= zLimit;
CTraceFilterWalkableEntities filter( NULL, COLLISION_GROUP_NONE, WALK_THRU_EVERYTHING );
UTIL_TraceHull( start, end, NavTraceMins, NavTraceMaxs, TheNavMesh->GetGenerationTraceMask(), &filter, trace );
DrawTrace( trace );
if ( trace->startsolid || trace->fraction >= 1.0f )
{
return false;
}
if ( trace->plane.normal.z < nav_slope_limit.GetFloat() )
{
return false;
}
return true;
}
//--------------------------------------------------------------------------------------------------------------
bool TraceAdjacentNode( int depth, const Vector& start, const Vector& end, trace_t *trace, float zLimit /* = DeathDrop */ )
{
const float MinDistance = 1.0f; // if we can't move at least this far, don't bother stepping up.
CTraceFilterWalkableEntities filter( NULL, COLLISION_GROUP_NONE, WALK_THRU_EVERYTHING );
UTIL_TraceHull( start, end, NavTraceMins, NavTraceMaxs, TheNavMesh->GetGenerationTraceMask(), &filter, trace );
DrawTrace( trace );
// If we started in the ground for some reason, bail
if ( trace->startsolid )
return false;
// If we made it, so try to find the floor
if ( end.x == trace->endpos.x && end.y == trace->endpos.y )
{
return StayOnFloor( trace, zLimit );
}
// If we didn't make enough progress, bail
if ( depth && start.AsVector2D().DistToSqr( trace->endpos.AsVector2D() ) < MinDistance * MinDistance )
{
return false;
}
// We made it more than MinDistance. If the slope is too steep, we can't go on.
if ( !StayOnFloor( trace, zLimit ) )
{
return false;
}
// Try to go up as if we stepped up, forward, and down.
Vector testStart( trace->endpos );
Vector testEnd( testStart );
testEnd.z += StepHeight;
UTIL_TraceHull( testStart, testEnd, NavTraceMins, NavTraceMaxs, TheNavMesh->GetGenerationTraceMask(), &filter, trace );
DrawTrace( trace );
Vector forwardTestStart = trace->endpos;
Vector forwardTestEnd = end;
forwardTestEnd.z = forwardTestStart.z;
return TraceAdjacentNode( depth+1, forwardTestStart, forwardTestEnd, trace );
}
//--------------------------------------------------------------------------------------------------------
static bool IsNodeOverlapped( const Vector& pos, const Vector& offset )
{
bool overlap = TheNavMesh->GetNavArea( pos + offset, HumanHeight ) != NULL;
if ( !overlap )
{
Vector mins( -0.5f, -0.5f, -0.5f );
Vector maxs( 0.5f, 0.5f, 0.5f );
Vector start = pos;
start.z += HalfHumanHeight;
Vector end = start;
end.x += offset.x * GenerationStepSize;
end.y += offset.y * GenerationStepSize;
trace_t trace;
CTraceFilterWalkableEntities filter( NULL, COLLISION_GROUP_NONE, WALK_THRU_EVERYTHING );
UTIL_TraceHull( start, end, mins, maxs, TheNavMesh->GetGenerationTraceMask(), &filter, &trace );
if ( trace.startsolid || trace.allsolid )
{
return true;
}
if ( trace.fraction < 0.1f )
{
return true;
}
start = trace.endpos;
end.z -= HalfHumanHeight * 2;
UTIL_TraceHull( start, end, mins, maxs, TheNavMesh->GetGenerationTraceMask(), &filter, &trace );
if ( trace.startsolid || trace.allsolid )
{
return true;
}
if ( trace.fraction == 1.0f )
{
return true;
}
if ( trace.plane.normal.z < 0.7f )
{
return true;
}
}
return overlap;
}
//--------------------------------------------------------------------------------------------------------------
/**
* Search the world and build a map of possible movements.
* The algorithm begins at the bot's current location, and does a recursive search
* outwards, tracking all valid steps and generating a directed graph of CNavNodes.
*
* Sample the map one "step" in a cardinal direction to learn the map.
*
* Returns true if sampling needs to continue, or false if done.
*/
bool CNavMesh::SampleStep( void )
{
// take a step
while( true )
{
if (m_currentNode == NULL)
{
// sampling is complete from current seed, try next one
m_currentNode = GetNextWalkableSeedNode();
if (m_currentNode == NULL)
{
if ( m_generationMode == GENERATE_INCREMENTAL || m_generationMode == GENERATE_SIMPLIFY )
{
return false;
}
// search is exhausted - continue search from ends of ladders
for ( int i=0; i<m_ladders.Count(); ++i )
{
CNavLadder *ladder = m_ladders[i];
// check ladder bottom
if ((m_currentNode = LadderEndSearch( &ladder->m_bottom, ladder->GetDir() )) != 0)
break;
// check ladder top
if ((m_currentNode = LadderEndSearch( &ladder->m_top, ladder->GetDir() )) != 0)
break;
}
if (m_currentNode == NULL)
{
// all seeds exhausted, sampling complete
return false;
}
}
}
//
// Take a step from this node
//
for( int dir = NORTH; dir < NUM_DIRECTIONS; dir++ )
{
if (!m_currentNode->HasVisited( (NavDirType)dir ))
{
// have not searched in this direction yet
// start at current node position
Vector pos = *m_currentNode->GetPosition();
// snap to grid
int cx = SnapToGrid( pos.x );
int cy = SnapToGrid( pos.y );
// attempt to move to adjacent node
switch( dir )
{
case NORTH: cy -= GenerationStepSize; break;
case SOUTH: cy += GenerationStepSize; break;
case EAST: cx += GenerationStepSize; break;
case WEST: cx -= GenerationStepSize; break;
}
pos.x = cx;
pos.y = cy;
m_generationDir = (NavDirType)dir;
// mark direction as visited
m_currentNode->MarkAsVisited( m_generationDir );
// sanity check to not generate across the world for incremental generation
const float incrementalRange = nav_generate_incremental_range.GetFloat();
if ( m_generationMode == GENERATE_INCREMENTAL && incrementalRange > 0 )
{
bool inRange = false;
for ( int i=0; i<m_walkableSeeds.Count(); ++i )
{
const Vector &seedPos = m_walkableSeeds[i].pos;
if ( (seedPos - pos).IsLengthLessThan( incrementalRange ) )
{
inRange = true;
break;
}
}
if ( !inRange )
{
return true;
}
}
if ( m_generationMode == GENERATE_SIMPLIFY )
{
if ( !m_simplifyGenerationExtent.Contains( pos ) )
{
return true;
}
}
// test if we can move to new position
trace_t result;
Vector from( *m_currentNode->GetPosition() );
CTraceFilterWalkableEntities filter( NULL, COLLISION_GROUP_NONE, WALK_THRU_EVERYTHING );
Vector to, toNormal;
float obstacleHeight = 0, obstacleStartDist = 0, obstacleEndDist = GenerationStepSize;
if ( TraceAdjacentNode( 0, from, pos, &result ) )
{
to = result.endpos;
toNormal = result.plane.normal;
}
else
{
// test going up ClimbUpHeight
bool success = false;
for ( float height = StepHeight; height <= ClimbUpHeight; height += 1.0f )
{
trace_t tr;
Vector start( from );
Vector end( pos );
start.z += height;
end.z += height;
UTIL_TraceHull( start, end, NavTraceMins, NavTraceMaxs, GetGenerationTraceMask(), &filter, &tr );
if ( !tr.startsolid && tr.fraction == 1.0f )
{
if ( !StayOnFloor( &tr ) )
{
break;
}
to = tr.endpos;
toNormal = tr.plane.normal;
start = end = from;
end.z += height;
UTIL_TraceHull( start, end, NavTraceMins, NavTraceMaxs, GetGenerationTraceMask(), &filter, &tr );
if ( tr.fraction < 1.0f )
{
break;
}
// keep track of far up we had to go to find a path to the next node
obstacleHeight = height;
success = true;
break;
}
else
{
// Could not trace from node to node at this height, something is in the way.
// Trace in the other direction to see if we hit something
Vector vecToObstacleStart = tr.endpos - start;
Assert( vecToObstacleStart.LengthSqr() <= Square( GenerationStepSize ) );
if ( vecToObstacleStart.LengthSqr() <= Square( GenerationStepSize ) )
{
UTIL_TraceHull( end, start, NavTraceMins, NavTraceMaxs, GetGenerationTraceMask(), &filter, &tr );
if ( !tr.startsolid && tr.fraction < 1.0 )
{
// We hit something going the other direction. There is some obstacle between the two nodes.
Vector vecToObstacleEnd = tr.endpos - start;
Assert( vecToObstacleEnd.LengthSqr() <= Square( GenerationStepSize ) );
if ( vecToObstacleEnd.LengthSqr() <= Square( GenerationStepSize ) )
{
// Remember the distances to start and end of the obstacle (with respect to the "from" node).
// Keep track of the last distances to obstacle as we keep increasing the height we do a trace for.
// If we do eventually clear the obstacle, these values will be the start and end distance to the
// very tip of the obstacle.
obstacleStartDist = vecToObstacleStart.Length();
obstacleEndDist = vecToObstacleEnd.Length();
if ( obstacleEndDist == 0 )
{
obstacleEndDist = GenerationStepSize;
}
}
}
}
}
}
if ( !success )
{
return true;
}
}
// Don't generate nodes if we spill off the end of the world onto skybox
if ( result.surface.flags & ( SURF_SKY|SURF_SKY2D ) )
{
return true;
}
// If we're incrementally generating, don't overlap existing nav areas.
Vector testPos( to );
bool overlapSE = IsNodeOverlapped( testPos, Vector( 1, 1, HalfHumanHeight ) );
bool overlapSW = IsNodeOverlapped( testPos, Vector( -1, 1, HalfHumanHeight ) );
bool overlapNE = IsNodeOverlapped( testPos, Vector( 1, -1, HalfHumanHeight ) );
bool overlapNW = IsNodeOverlapped( testPos, Vector( -1, -1, HalfHumanHeight ) );
if ( overlapSE && overlapSW && overlapNE && overlapNW && m_generationMode != GENERATE_SIMPLIFY )
{
return true;
}
int nTolerance = nav_generate_incremental_tolerance.GetInt();
if ( nTolerance > 0 && m_generationMode == GENERATE_INCREMENTAL )
{
bool bValid = false;
int zPos = to.z;
for ( int i=0; i<m_walkableSeeds.Count(); ++i )
{
const Vector &seedPos = m_walkableSeeds[i].pos;
int zMin = seedPos.z - nTolerance;
int zMax = seedPos.z + nTolerance;
if ( zPos >= zMin && zPos <= zMax )
{
bValid = true;
break;
}
}
if ( !bValid )
return true;
}
bool isOnDisplacement = result.IsDispSurface();
if ( nav_displacement_test.GetInt() > 0 )
{
// Test for nodes under displacement surfaces.
// This happens during development, and is a pain because the space underneath a displacement
// is not 'solid'.
Vector start = to + Vector( 0, 0, 0 );
Vector end = start + Vector( 0, 0, nav_displacement_test.GetInt() );
UTIL_TraceHull( start, end, NavTraceMins, NavTraceMaxs, GetGenerationTraceMask(), &filter, &result );
if ( result.fraction > 0 )
{
end = start;
start = result.endpos;
UTIL_TraceHull( start, end, NavTraceMins, NavTraceMaxs, GetGenerationTraceMask(), &filter, &result );
if ( result.fraction < 1 )
{
// if we made it down to within StepHeight, maybe we're on a static prop
if ( result.endpos.z > to.z + StepHeight )
{
return true;
}
}
}
}
float deltaZ = to.z - m_currentNode->GetPosition()->z;
// If there's an obstacle in the way and it's traversable, or the obstacle is not higher than the destination node itself minus a small epsilon
// (meaning the obstacle was just the height change to get to the destination node, no extra obstacle between the two), clear obstacle height
// and distances
if ( ( obstacleHeight < MaxTraversableHeight ) || ( deltaZ > ( obstacleHeight - 2.0f ) ) )
{
obstacleHeight = 0;
obstacleStartDist = 0;
obstacleEndDist = GenerationStepSize;
}
// we can move here
// create a new navigation node, and update current node pointer
AddNode( to, toNormal, m_generationDir, m_currentNode, isOnDisplacement, obstacleHeight, obstacleStartDist, obstacleEndDist );
return true;
}
}
// all directions have been searched from this node - pop back to its parent and continue
m_currentNode = m_currentNode->GetParent();
}
}
//--------------------------------------------------------------------------------------------------------------
/**
* Add given walkable position to list of seed positions for map sampling
*/
void CNavMesh::AddWalkableSeed( const Vector &pos, const Vector &normal )
{
WalkableSeedSpot seed;
seed.pos.x = RoundToUnits( pos.x, GenerationStepSize );
seed.pos.y = RoundToUnits( pos.y, GenerationStepSize );
seed.pos.z = pos.z;
seed.normal = normal;
m_walkableSeeds.AddToTail( seed );
}
//--------------------------------------------------------------------------------------------------------------
/**
* Return the next walkable seed as a node
*/
CNavNode *CNavMesh::GetNextWalkableSeedNode( void )
{
if ( m_seedIdx >= m_walkableSeeds.Count() )
return NULL;
WalkableSeedSpot spot = m_walkableSeeds[ m_seedIdx ];
++m_seedIdx;
// check if a node exists at this location
CNavNode *node = CNavNode::GetNode( spot.pos );
if ( node )
return NULL;
return new CNavNode( spot.pos, spot.normal, NULL, false );
}
//--------------------------------------------------------------------------------------------------------------
/**
* Check LOS, ignoring any entities that we can walk through
*/
bool IsWalkableTraceLineClear( const Vector &from, const Vector &to, unsigned int flags )
{
trace_t result;
CBaseEntity *ignore = NULL;
Vector useFrom = from;
CTraceFilterWalkableEntities traceFilter( NULL, COLLISION_GROUP_NONE, flags );
result.fraction = 0.0f;
const int maxTries = 50;
for( int t=0; t<maxTries; ++t )
{
UTIL_TraceLine( useFrom, to, MASK_PLAYERSOLID, &traceFilter, &result );
// if we hit a walkable entity, try again
if (result.fraction != 1.0f && IsEntityWalkable( result.m_pEnt, flags ))
{
ignore = result.m_pEnt;
// start from just beyond where we hit to avoid infinite loops
Vector dir = to - from;
dir.NormalizeInPlace();
useFrom = result.endpos + 5.0f * dir;
}
else
{
break;
}
}
if (result.fraction == 1.0f)
return true;
return false;
}
//--------------------------------------------------------------------------------------------------------------
/**
* Trace a hull, ignoring any entities that we can walk through
*/
bool IsWalkableTraceHullClear( const Vector &from, const Vector &to, const Vector &mins, const Vector &maxs, unsigned int flags )
{
trace_t result;
CTraceFilterWalkableEntities traceFilter( NULL, COLLISION_GROUP_NONE, flags );
UTIL_TraceHull( from, to, mins, maxs, MASK_PLAYERSOLID, &traceFilter, &result );
if ( result.DidHitNonWorldEntity() && IsEntityWalkable( result.m_pEnt, flags ) )
{
return true;
}
return !result.DidHit();
}
//--------------------------------------------------------------------------------------------------------------
class Subdivider
{
public:
Subdivider( int depth )
{
m_depth = depth;
}
bool operator() ( CNavArea *area )
{
SubdivideX( area, true, true, m_depth );
return true;
}
void SubdivideX( CNavArea *area, bool canDivideX, bool canDivideY, int depth )
{
if (!canDivideX || depth <= 0)
return;
float split = area->GetSizeX() / 2.0f;
if (split < GenerationStepSize)
{
if (canDivideY)
{
SubdivideY( area, false, canDivideY, depth );
}
return;
}
split += area->GetCorner( NORTH_WEST ).x;
split = TheNavMesh->SnapToGrid( split );
CNavArea *alpha, *beta;
if (area->SplitEdit( false, split, &alpha, &beta ))
{
SubdivideY( alpha, canDivideX, canDivideY, depth );
SubdivideY( beta, canDivideX, canDivideY, depth );
}
}
void SubdivideY( CNavArea *area, bool canDivideX, bool canDivideY, int depth )
{
if (!canDivideY)
return;
float split = area->GetSizeY() / 2.0f;
if (split < GenerationStepSize)
{
if (canDivideX)
{
SubdivideX( area, canDivideX, false, depth-1 );
}
return;
}
split += area->GetCorner( NORTH_WEST ).y;
split = TheNavMesh->SnapToGrid( split );
CNavArea *alpha, *beta;
if (area->SplitEdit( true, split, &alpha, &beta ))
{
SubdivideX( alpha, canDivideX, canDivideY, depth-1 );
SubdivideX( beta, canDivideX, canDivideY, depth-1 );
}
}
int m_depth;
};
//--------------------------------------------------------------------------------------------------------------
/**
* Subdivide each nav area in X and Y to create 4 new areas
*/
void CNavMesh::CommandNavSubdivide( const CCommand &args )
{
int depth = 1;
if (args.ArgC() == 2)
{
depth = atoi( args[1] );
}
Subdivider chop( depth );
TheNavMesh->ForAllSelectedAreas( chop );
}
CON_COMMAND_F( nav_subdivide, "Subdivides all selected areas.", FCVAR_GAMEDLL | FCVAR_CHEAT )
{
if ( !UTIL_IsCommandIssuedByServerAdmin() )
return;
TheNavMesh->CommandNavSubdivide( args );
}
//--------------------------------------------------------------------------------------------------------------
/**
* Debugging code to verify that all nav area connections are internally consistent
*/
void CNavMesh::ValidateNavAreaConnections( void )
{
// iterate all nav areas
NavConnect connect;
for ( int it = 0; it < TheNavAreas.Count(); it++ )
{
CNavArea *area = TheNavAreas[ it ];
for ( NavDirType dir = NORTH; dir < NUM_DIRECTIONS; dir = (NavDirType) ( ( (int) dir ) +1 ) )
{
const NavConnectVector *pOutgoing = area->GetAdjacentAreas( dir );
const NavConnectVector *pIncoming = area->GetIncomingConnections( dir );
for ( int iConnect = 0; iConnect < pOutgoing->Count(); iConnect++ )
{
// make sure no area is on both the connection and incoming list
CNavArea *areaOther = (*pOutgoing)[iConnect].area;
connect.area = areaOther;
if ( pIncoming->Find( connect ) != pIncoming->InvalidIndex() )
{
Msg( "Area %d has area %d on both 2-way and incoming list, should only be on one\n", area->GetID(), areaOther->GetID() );
Assert( false );
}
// make sure there are no duplicate connections on the list
for ( int iConnectCheck = iConnect+1; iConnectCheck < pOutgoing->Count(); iConnectCheck++ )
{
CNavArea *areaCheck = (*pOutgoing)[iConnectCheck].area;
if ( areaOther == areaCheck )
{
Msg( "Area %d has multiple outgoing connections to area %d in direction %d\n", area->GetID(), areaOther->GetID(), dir );
Assert( false );
}
}
const NavConnectVector *pOutgoingOther = areaOther->GetAdjacentAreas( OppositeDirection( dir ) );
const NavConnectVector *pIncomingOther = areaOther->GetIncomingConnections( OppositeDirection( dir ) );
// if we have a one-way outgoing connection, make sure we are on the other area's incoming list
connect.area = area;
bool bIsTwoWay = pOutgoingOther->Find( connect ) != pOutgoingOther->InvalidIndex();
if ( !bIsTwoWay )
{
connect.area = area;
bool bOnOthersIncomingList = pIncomingOther->Find( connect ) != pIncomingOther->InvalidIndex();
if ( !bOnOthersIncomingList )
{
Msg( "Area %d has one-way connect to area %d but does not appear on the latter's incoming list\n", area->GetID(), areaOther->GetID() );
}
}
}
for ( int iConnect = 0; iConnect < pIncoming->Count(); iConnect++ )
{
CNavArea *areaOther = (*pIncoming)[iConnect].area;
// make sure there are not duplicate areas on the incoming list
for ( int iConnectCheck = iConnect+1; iConnectCheck < pIncoming->Count(); iConnectCheck++ )
{
CNavArea *areaCheck = (*pIncoming)[iConnectCheck].area;
if ( areaOther == areaCheck )
{
Msg( "Area %d has multiple incoming connections to area %d in direction %d\n", area->GetID(), areaOther->GetID(), dir );
Assert( false );
}
}
const NavConnectVector *pOutgoingOther = areaOther->GetAdjacentAreas( OppositeDirection( dir ) );
connect.area = area;
bool bOnOthersOutgoingList = pOutgoingOther->Find( connect ) != pOutgoingOther->InvalidIndex();
if ( !bOnOthersOutgoingList )
{
Msg( "Area %d has incoming connection from area %d but does not appear on latter's outgoing connection list\n", area->GetID(), areaOther->GetID() );
Assert( false );
}
}
}
}
}
//--------------------------------------------------------------------------------------------------------------
/**
* Temp way to mark cliff areas after generation without regen'ing. Any area that is adjacent to a cliff
* gets marked as a cliff. This will leave some big areas marked as cliff just because one edge is adjacent to
* a cliff so it's not great. The code that does this at generation time is better because it ensures that
* areas next to cliffs don't get merged with no-cliff areas.
*/
void CNavMesh::PostProcessCliffAreas()
{
for ( int it = 0; it < TheNavAreas.Count(); it++ )
{
CNavArea *area = TheNavAreas[ it ];
if ( area->GetAttributes() & NAV_MESH_CLIFF )
continue;
for ( int i = 0; i < NUM_DIRECTIONS; i++ )
{
bool bHasCliff = false;
NavDirType dir = (NavDirType) i;
NavCornerType corner[2];
// look at either corner along this edge
corner[0] = (NavCornerType) i;
corner[1] = (NavCornerType) ( ( i+ 1 ) % NUM_CORNERS );
for ( int j = 0; j < 2; j++ )
{
Vector cornerPos = area->GetCorner( corner[j] );
if ( CheckCliff( &cornerPos, dir ) )
{
bHasCliff = true;
break;
}
}
if ( bHasCliff )
{
area->SetAttributes( area->GetAttributes() | NAV_MESH_CLIFF );
break;
}
}
}
}
CON_COMMAND_F( nav_gen_cliffs_approx, "Mark cliff areas, post-processing approximation", FCVAR_CHEAT )
{
TheNavMesh->PostProcessCliffAreas();
}
| 0 | 0.966357 | 1 | 0.966357 | game-dev | MEDIA | 0.493607 | game-dev,graphics-rendering | 0.948198 | 1 | 0.948198 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.