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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
revolucas/CoC-Xray | 4,008 | src/xrGame/actor_mp_client_import.cpp | #include "stdafx.h"
#include "actor_mp_client.h"
#include "inventory.h"
#include "level.h"
#include "GamePersistent.h"
#include "game_cl_base.h"
#include "../xrEngine/camerabase.h"
//#include "Physics.h"
#include "../xrphysics/phvalide.h"
void CActorMP::net_Import ( NET_Packet &P)
{
net_update N;
m_state_holder.read (P);
R_ASSERT2(valid_pos(m_state_holder.state().position), "imported bad position");
/*if (m_i_am_dead)
return;*/
if (OnClient())
{
/*#ifdef DEBUG
if (GetfHealth() != m_state_holder.state().health)
Msg("net_Import: [%d][%s], is going to set health to %2.04f", this->ID(), Name(), m_state_holder.state().health);
#endif*/
game_PlayerState* ps = Game().GetPlayerByGameID(this->object_id());
float new_health = m_state_holder.state().health;
if (GetfHealth() < new_health)
{
SetfHealth(new_health);
} else
{
if (!ps || !ps->testFlag(GAME_PLAYER_FLAG_INVINCIBLE))
{
SetfHealth(new_health);
}
}
}
if (PPhysicsShell() != NULL)
{
return;
}
if (OnClient())
SetfRadiation (m_state_holder.state().radiation*100.0f);
u16 ActiveSlot = m_state_holder.state().inventory_active_slot;
if (OnClient() && (inventory().GetActiveSlot()!=ActiveSlot) )
{
#ifdef DEBUG
Msg("Client-SetActiveSlot[%d][%d]",ActiveSlot, Device.dwFrame);
#endif // #ifdef DEBUG
inventory().SetActiveSlot(ActiveSlot);
}
N.mstate = m_state_holder.state().body_state_flags;
N.dwTimeStamp = m_state_holder.state().time;
N.p_pos = m_state_holder.state().position;
N.o_model = m_state_holder.state().model_yaw;
N.o_torso.yaw = m_state_holder.state().camera_yaw;
N.o_torso.pitch = m_state_holder.state().camera_pitch;
N.o_torso.roll = m_state_holder.state().camera_roll;
if (N.o_torso.roll > PI)
N.o_torso.roll -= PI_MUL_2;
{
if (Level().IsDemoPlay() || OnServer() || Remote())
{
unaffected_r_torso.yaw = N.o_torso.yaw;
unaffected_r_torso.pitch = N.o_torso.pitch;
unaffected_r_torso.roll = N.o_torso.roll;
cam_Active()->yaw = -N.o_torso.yaw;
cam_Active()->pitch = N.o_torso.pitch;
};
};
//CSE_ALifeCreatureActor
N.p_accel = m_state_holder.state().logic_acceleration;
process_packet (N);
net_update_A N_A;
m_States.clear ();
N_A.State.enabled = m_state_holder.state().physics_state_enabled;
N_A.State.angular_vel = m_state_holder.state().physics_angular_velocity;
N_A.State.linear_vel = m_state_holder.state().physics_linear_velocity;
N_A.State.force = m_state_holder.state().physics_force;
N_A.State.torque = m_state_holder.state().physics_torque;
N_A.State.position = m_state_holder.state().physics_position;
N_A.State.quaternion = m_state_holder.state().physics_quaternion;
// interpolcation
postprocess_packet (N_A);
}
void CActorMP::postprocess_packet (net_update_A &N_A)
{
if (!NET.empty())
N_A.dwTimeStamp = NET.back().dwTimeStamp;
else
N_A.dwTimeStamp = Level().timeServer();
N_A.State.previous_position = N_A.State.position;
N_A.State.previous_quaternion = N_A.State.quaternion;
if (Local() && OnClient() || !g_Alive()) return;
{
//-----------------------------------------------
if (!NET_A.empty() && N_A.dwTimeStamp < NET_A.back().dwTimeStamp) return;
if (!NET_A.empty() && N_A.dwTimeStamp == NET_A.back().dwTimeStamp)
{
NET_A.back() = N_A;
}
else
{
VERIFY(valid_pos(N_A.State.position));
NET_A.push_back (N_A);
if (NET_A.size()>5) NET_A.pop_front();
};
if (!NET_A.empty()) m_bInterpolate = true;
};
Level().AddObject_To_Objects4CrPr (this);
CrPr_SetActivated (false);
CrPr_SetActivationStep (0);
}
void CActorMP::process_packet (net_update &N)
{
if (Local() && OnClient())
return;
if (!NET.empty() && (N.dwTimeStamp < NET.back().dwTimeStamp))
return;
if (g_Alive()) {
setVisible ((BOOL)!HUDview ());
setEnabled (TRUE);
};
if (!NET.empty() && (N.dwTimeStamp == NET.back().dwTimeStamp)) {
NET.back() = N;
return;
}
NET.push_back (N);
if (NET.size() > 5)
NET.pop_front ();
}
| 0 | 0.976616 | 1 | 0.976616 | game-dev | MEDIA | 0.513812 | game-dev | 0.970917 | 1 | 0.970917 |
simulationcraft/simc | 8,306 | engine/class_modules/apl/rogue/subtlety.simc | # Consumables
# Executed before combat begins. Accepts non-harmful actions only.
actions.precombat=apply_poison
actions.precombat+=/snapshot_stats
actions.precombat+=/variable,name=priority_rotation,value=priority_rotation
actions.precombat+=/variable,name=trinket_sync_slot,value=1,if=trinket.1.has_use_buff&(!trinket.2.has_use_buff|trinket.1.is.treacherous_transmitter|trinket.1.cooldown.duration>=trinket.2.cooldown.duration)
actions.precombat+=/variable,name=trinket_sync_slot,value=2,if=trinket.2.has_use_buff&(!trinket.1.has_use_buff|trinket.2.cooldown.duration>trinket.1.cooldown.duration)
actions.precombat+=/stealth
actions=stealth
# Variables
actions+=/variable,name=stealth,value=buff.shadow_dance.up|buff.stealth.up|buff.vanish.up
actions+=/variable,name=targets,value=spell_targets.shuriken_storm
actions+=/variable,name=skip_rupture,value=buff.shadow_dance.up|buff.darkest_night.up|variable.targets>=4&(!talent.replicating_shadows&talent.unseen_blade|raid_event.adds.up)
actions+=/variable,name=maintenance,value=(dot.rupture.ticking|variable.skip_rupture)&(buff.slice_and_dice.up|variable.targets<=2)
actions+=/variable,name=secret,value=buff.shadow_dance.up&!buff.darkest_night.up|(cooldown.flagellation.remains<60&cooldown.flagellation.remains>30&talent.death_perception&talent.unseen_blade)
actions+=/variable,name=racial_sync,value=(buff.shadow_blades.up&buff.shadow_dance.up)|!talent.shadow_blades&buff.symbols_of_death.up|fight_remains<20
actions+=/variable,name=shd_cp,value=combo_points<=1|buff.darkest_night.up&combo_points>=7|effective_combo_points>=6&talent.unseen_blade
# Cooldowns
actions+=/call_action_list,name=cds
# Racials
actions+=/call_action_list,name=race
# Items (Trinkets)
actions+=/call_action_list,name=item
# Cooldowns for Stealth
actions+=/call_action_list,name=stealth_cds,if=!variable.stealth
# Finishing Rules
actions+=/call_action_list,name=finish,if=!buff.darkest_night.up&effective_combo_points>=6|buff.darkest_night.up&combo_points==cp_max_spend|action.coup_de_grace.ready&cooldown.secret_technique.remains>0
# Combo Point Builder
actions+=/call_action_list,name=build
# Filler, Spells used if you can use nothing else.
actions+=/call_action_list,name=fill,if=!variable.stealth
# Cooldowns
actions.cds=cold_blood,if=cooldown.secret_technique.up&buff.shadow_dance.up&combo_points>=6&variable.secret&(buff.flagellation_persist.up|buff.flagellation_buff.remains<=3)
actions.cds+=/potion,if=buff.bloodlust.react|fight_remains<30|buff.flagellation_buff.up
actions.cds+=/symbols_of_death,if=(buff.symbols_of_death.remains<=3.5&variable.maintenance&(variable.targets>1|raid_event.adds.up|!buff.flagellation_buff.up|dot.rupture.remains>=30)&(!talent.flagellation|cooldown.flagellation.remains>=30-15*!talent.death_perception&cooldown.secret_technique.remains<8|!talent.death_perception)|fight_remains<=15)
actions.cds+=/shadow_blades,if=variable.maintenance&variable.shd_cp&buff.shadow_dance.up&!buff.premeditation.up
actions.cds+=/thistle_tea,if=buff.shadow_dance.remains>4&!buff.thistle_tea.up
actions.cds+=/flagellation,if=combo_points>=5&cooldown.shadow_blades.remains<=3|fight_remains<=25
# Race Cooldowns
actions.race=blood_fury,if=variable.racial_sync
actions.race+=/berserking,if=variable.racial_sync
actions.race+=/fireblood,if=variable.racial_sync&buff.shadow_dance.up
actions.race+=/ancestral_call,if=variable.racial_sync
actions.race+=/invoke_external_buff,name=power_infusion,if=buff.shadow_dance.up
# Trinket and Items
actions.item=use_item,name=treacherous_transmitter,if=cooldown.flagellation.remains<=2|fight_remains<=15
actions.item+=/do_treacherous_transmitter_task,if=buff.shadow_dance.up|fight_remains<=15
actions.item+=/use_item,name=imperfect_ascendancy_serum,use_off_gcd=1,if=dot.rupture.ticking&buff.flagellation_buff.up
actions.item+=/use_item,name=cursed_stone_idol,use_off_gcd=1,if=dot.rupture.remains>=25&buff.flagellation_buff.up|fight_remains<=20
actions.item+=/use_item,name=unyielding_netherprism,use_off_gcd=1,if=buff.shadow_blades.up&(buff.latent_energy.stack>=8+8*(trinket.arazs_ritual_forge.cooldown.ready|!equipped.arazs_ritual_forge)|!equipped.arazs_ritual_forge&fight_remains<=90)|fight_remains<=20
actions.item+=/use_item,name=mad_queens_mandate,if=(!talent.lingering_darkness|buff.lingering_darkness.up|equipped.treacherous_transmitter)&(!equipped.treacherous_transmitter|trinket.treacherous_transmitter.cooldown.remains>20)|fight_remains<=15
actions.item+=/use_items,slots=trinket1,if=(variable.trinket_sync_slot=1&(buff.shadow_blades.up|fight_remains<=20)|(variable.trinket_sync_slot=2&(!trinket.2.cooldown.ready&cooldown.shadow_blades.remains>20))|!variable.trinket_sync_slot)
actions.item+=/use_items,slots=trinket2,if=(variable.trinket_sync_slot=2&(buff.shadow_blades.up|fight_remains<=20)|(variable.trinket_sync_slot=1&(!trinket.1.cooldown.ready&cooldown.shadow_blades.remains>20))|!variable.trinket_sync_slot)
# Shadow Dance, Vanish, Shadowmeld
actions.stealth_cds=shadow_dance,if=(variable.shd_cp|!talent.premeditation)&variable.maintenance&(cooldown.secret_technique.remains<=24|talent.the_first_dance&buff.shadow_blades.up)&(buff.symbols_of_death.remains>=6|buff.shadow_blades.remains>=6)|fight_remains<=10
actions.stealth_cds+=/vanish,if=energy>=40&!buff.subterfuge.up&effective_combo_points<=3
actions.stealth_cds+=/shadowmeld,if=energy>=40&combo_points.deficit>=3
actions.finish=secret_technique,if=variable.secret
# Maintenance Finisher
actions.finish+=/rupture,if=!variable.skip_rupture&(!dot.rupture.ticking|refreshable|buff.flagellation_buff.up&!buff.symbols_of_death.up&variable.targets<=2)&target.time_to_die-remains>6&cooldown.flagellation.remains>=10
actions.finish+=/rupture,cycle_targets=1,if=!variable.skip_rupture&!variable.priority_rotation&target.time_to_die>=(2*combo_points)&refreshable&variable.targets>=2
# Direct Damage Finisher
actions.finish+=/coup_de_grace,if=debuff.fazed.up&cooldown.flagellation.remains>=20|fight_remains<=10
actions.finish+=/black_powder,if=!variable.priority_rotation&variable.maintenance&(((variable.targets>=2&talent.deathstalkers_mark&(!buff.darkest_night.up|buff.shadow_dance.up&variable.targets>=5))|talent.unseen_blade&variable.targets>=4)|action.coup_de_grace.ready&variable.targets>=3)
actions.finish+=/eviscerate,if=cooldown.flagellation.remains>=10|variable.targets>=3
actions.build=backstab,if=(talent.unseen_blade|variable.targets<=2)&(buff.shadow_dance.up&(buff.premeditation.up|buff.shadow_blades.up)&!used_for_danse|!variable.stealth&buff.shadow_blades.up)
actions.build+=/gloomblade,if=buff.shadow_dance.up&!used_for_danse|!variable.stealth&buff.shadow_blades.up
actions.build+=/shadowstrike,cycle_targets=1,if=debuff.find_weakness.remains<=2&variable.targets=2&talent.unseen_blade|!used_for_danse&!talent.premeditation
actions.build+=/shuriken_tornado,if=buff.lingering_darkness.up|talent.deathstalkers_mark&cooldown.shadow_blades.remains>=32&variable.targets>=3
actions.build+=/shuriken_tornado,if=talent.unseen_blade&!buff.stealth.up&((buff.shadow_dance.up&!talent.shadowcraft&variable.targets>=3)|(talent.shadowcraft&variable.targets>=3)|!variable.stealth&variable.targets<=2)&(buff.symbols_of_death.up|!raid_event.adds.up)
actions.build+=/shuriken_storm,if=buff.clear_the_witnesses.up&(variable.targets>=2|!buff.symbols_of_death.up)
actions.build+=/shadowstrike,cycle_targets=1,if=talent.deathstalkers_mark&!debuff.deathstalkers_mark.up&variable.targets>=3&(buff.shadow_blades.up|buff.premeditation.up|talent.the_rotten)
actions.build+=/shuriken_storm,if=talent.deathstalkers_mark&variable.targets>=(2+3*buff.shadow_dance.up)
actions.build+=/shuriken_storm,if=talent.unseen_blade&(buff.flawless_form.up&variable.targets>=3&!variable.stealth|buff.silent_storm.up&variable.targets>=5&buff.shadow_dance.up)
actions.build+=/shuriken_storm,if=(buff.tww3_trickster_4pc.up|buff.escalating_blade.stack=4)&!used_for_danse&(buff.shadow_blades.up|variable.targets>=4)
actions.build+=/shadowstrike
actions.build+=/goremaws_bite,if=combo_points.deficit>=3
actions.build+=/gloomblade
actions.build+=/backstab
# This list usually contains Cooldowns with neglectable impact that causes global cooldowns
actions.fill=arcane_torrent,if=energy.deficit>=15+energy.regen
actions.fill+=/arcane_pulse
actions.fill+=/lights_judgment
actions.fill+=/bag_of_tricks | 0 | 0.88141 | 1 | 0.88141 | game-dev | MEDIA | 0.987114 | game-dev | 0.87085 | 1 | 0.87085 |
caveman2cosmos/Caveman2Cosmos | 2,693 | Assets/Python/Screens/CvVictoryMovieScreen.py | ## Sid Meier's Civilization 4
## Copyright Firaxis Games 2005
from CvPythonExtensions import *
import CvScreenEnums
# globals
gc = CyGlobalContext()
ArtFileMgr = CyArtFileMgr()
class CvVictoryMovieScreen:
def interfaceScreen (self, iVictory):
self.X_SCREEN = 0
self.Y_SCREEN = 0
self.W_SCREEN = 1024
self.H_SCREEN = 768
self.Y_TITLE = 12
self.BORDER_HEIGHT = 100
self.X_EXIT = 410
self.Y_EXIT = 326
game = CyGame()
if ( game.isNetworkMultiPlayer() or game.isPitbossHost()):
return
if (iVictory == -1 or len(gc.getVictoryInfo(iVictory).getMovie()) == 0):
return
self.createMovieScreen(gc.getVictoryInfo(iVictory).getMovie())
def createMovieScreen(self, movieArtDef):
# Create a new screen, called VictoryMovieScreen, using the file CvVictoryMovieScreen.py for input
screen = CyGInterfaceScreen( "VictoryMovieScreen", CvScreenEnums.VICTORY_MOVIE_SCREEN )
screen.setDimensions(screen.centerX(0), screen.centerY(0), -1, -1)
screen.setRenderInterfaceOnly(True)
screen.enableWorldSounds( false )
screen.addDDSGFC("VictoryMovieScreenBackground", ArtFileMgr.getInterfaceArtInfo("SCREEN_BG_OPAQUE").getPath(), 0, 0, -1, -1, WidgetTypes.WIDGET_GENERAL, -1, -1 )
screen.addPanel( "VictoryMovieTopPanel", u"", u"", False, False, self.X_SCREEN, self.Y_SCREEN, self.W_SCREEN, self.BORDER_HEIGHT, PanelStyles.PANEL_STYLE_TOPBAR )
screen.addPanel( "VictoryMovieBottomPanel", u"", u"", False, False, self.X_SCREEN, self.H_SCREEN-(self.BORDER_HEIGHT+3), self.W_SCREEN, self.BORDER_HEIGHT+3, PanelStyles.PANEL_STYLE_BOTTOMBAR )
screen.showWindowBackground( False )
# Show the screen
screen.showScreen(PopupStates.POPUPSTATE_IMMEDIATE, False)
screen.setButtonGFC("Exit", u"Your movies are not installed correctly.", "", #self.EXIT_TEXT,
self.X_EXIT, self.Y_EXIT, 400, 100, WidgetTypes.WIDGET_CLOSE_SCREEN, -1, -1, ButtonStyles.BUTTON_STYLE_STANDARD)
# Play the movie
movieFilePath = CyArtFileMgr().getMovieArtInfo(movieArtDef).getPath()
screen.playMovie( movieFilePath, -1, -1, -1, -1, 0)
def closeScreen(self):
screen = CyGInterfaceScreen( "VictoryMovieScreen", CvScreenEnums.VICTORY_MOVIE_SCREEN )
screen.hideScreen()
def hideScreen(self):
screen = CyGInterfaceScreen( "VictoryMovieScreen", CvScreenEnums.VICTORY_MOVIE_SCREEN )
screen.hideScreen()
# Will handle the input for this screen...
def handleInput (self, inputClass):
screen = CyGInterfaceScreen( "VictoryMovieScreen", CvScreenEnums.VICTORY_MOVIE_SCREEN )
if (inputClass.getNotifyCode() == NotifyCode.NOTIFY_MOVIE_DONE or inputClass.getNotifyCode() == NotifyCode.NOTIFY_CLICKED):
return self.hideScreen()
return 0
def update(self, fDelta):
return
| 0 | 0.535949 | 1 | 0.535949 | game-dev | MEDIA | 0.657501 | game-dev | 0.583428 | 1 | 0.583428 |
Minestom/Minestom | 5,745 | src/main/java/net/minestom/server/item/component/Equippable.java | package net.minestom.server.item.component;
import net.minestom.server.codec.Codec;
import net.minestom.server.codec.StructCodec;
import net.minestom.server.entity.EntityType;
import net.minestom.server.entity.EquipmentSlot;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.NetworkBufferTemplate;
import net.minestom.server.registry.Registries;
import net.minestom.server.registry.RegistryTag;
import net.minestom.server.sound.SoundEvent;
import org.jetbrains.annotations.Nullable;
public record Equippable(
EquipmentSlot slot,
SoundEvent equipSound,
@Nullable String assetId,
@Nullable String cameraOverlay,
@Nullable RegistryTag<EntityType> allowedEntities,
boolean dispensable,
boolean swappable,
boolean damageOnHurt,
boolean equipOnInteract,
boolean canBeSheared,
SoundEvent shearingSound
) {
public static final SoundEvent DEFAULT_EQUIP_SOUND = SoundEvent.ITEM_ARMOR_EQUIP_GENERIC;
public static final SoundEvent DEFAULT_SHEARING_SOUND = SoundEvent.ITEM_SHEARS_SNIP;
public static final NetworkBuffer.Type<Equippable> NETWORK_TYPE = NetworkBufferTemplate.template(
EquipmentSlot.NETWORK_TYPE, Equippable::slot,
SoundEvent.NETWORK_TYPE, Equippable::equipSound,
NetworkBuffer.STRING.optional(), Equippable::assetId,
NetworkBuffer.STRING.optional(), Equippable::cameraOverlay,
RegistryTag.networkType(Registries::entityType).optional(), Equippable::allowedEntities,
NetworkBuffer.BOOLEAN, Equippable::dispensable,
NetworkBuffer.BOOLEAN, Equippable::swappable,
NetworkBuffer.BOOLEAN, Equippable::damageOnHurt,
NetworkBuffer.BOOLEAN, Equippable::equipOnInteract,
NetworkBuffer.BOOLEAN, Equippable::canBeSheared,
SoundEvent.NETWORK_TYPE, Equippable::shearingSound,
Equippable::new);
public static final Codec<Equippable> CODEC = StructCodec.struct(
"slot", EquipmentSlot.CODEC, Equippable::slot,
"equip_sound", SoundEvent.CODEC.optional(DEFAULT_EQUIP_SOUND), Equippable::equipSound,
"asset_id", Codec.STRING.optional(), Equippable::assetId,
"camera_overlay", Codec.STRING.optional(), Equippable::cameraOverlay,
"allowed_entities", RegistryTag.codec(Registries::entityType).optional(), Equippable::allowedEntities,
"dispensable", Codec.BOOLEAN.optional(true), Equippable::dispensable,
"swappable", Codec.BOOLEAN.optional(true), Equippable::swappable,
"damage_on_hurt", Codec.BOOLEAN.optional(true), Equippable::damageOnHurt,
"equip_on_interact", Codec.BOOLEAN.optional(false), Equippable::equipOnInteract,
"can_be_sheared", Codec.BOOLEAN.optional(false), Equippable::canBeSheared,
"shearing_sound", SoundEvent.CODEC.optional(DEFAULT_SHEARING_SOUND), Equippable::shearingSound,
Equippable::new);
public Equippable withSlot(EquipmentSlot slot) {
return new Equippable(slot, equipSound, assetId, cameraOverlay, allowedEntities, dispensable, swappable, damageOnHurt, equipOnInteract, canBeSheared, shearingSound);
}
public Equippable withEquipSound(SoundEvent equipSound) {
return new Equippable(slot, equipSound, assetId, cameraOverlay, allowedEntities, dispensable, swappable, damageOnHurt, equipOnInteract, canBeSheared, shearingSound);
}
public Equippable withAssetId(@Nullable String assetId) {
return new Equippable(slot, equipSound, assetId, cameraOverlay, allowedEntities, dispensable, swappable, damageOnHurt, equipOnInteract, canBeSheared, shearingSound);
}
public Equippable withCameraOverlay(@Nullable String cameraOverlay) {
return new Equippable(slot, equipSound, assetId, cameraOverlay, allowedEntities, dispensable, swappable, damageOnHurt, equipOnInteract, canBeSheared, shearingSound);
}
public Equippable withAllowedEntities(@Nullable RegistryTag<EntityType> allowedEntities) {
return new Equippable(slot, equipSound, assetId, cameraOverlay, allowedEntities, dispensable, swappable, damageOnHurt, equipOnInteract, canBeSheared, shearingSound);
}
public Equippable withDispensable(boolean dispensable) {
return new Equippable(slot, equipSound, assetId, cameraOverlay, allowedEntities, dispensable, swappable, damageOnHurt, equipOnInteract, canBeSheared, shearingSound);
}
public Equippable withSwappable(boolean swappable) {
return new Equippable(slot, equipSound, assetId, cameraOverlay, allowedEntities, dispensable, swappable, damageOnHurt, equipOnInteract, canBeSheared, shearingSound);
}
public Equippable withDamageOnHurt(boolean damageOnHurt) {
return new Equippable(slot, equipSound, assetId, cameraOverlay, allowedEntities, dispensable, swappable, damageOnHurt, equipOnInteract, canBeSheared, shearingSound);
}
public Equippable withEquipOnInteract(boolean equipOnInteract) {
return new Equippable(slot, equipSound, assetId, cameraOverlay, allowedEntities, dispensable, swappable, damageOnHurt, equipOnInteract, canBeSheared, shearingSound);
}
public Equippable withCanBeSheared(boolean canBeSheared) {
return new Equippable(slot, equipSound, assetId, cameraOverlay, allowedEntities, dispensable, swappable, damageOnHurt, equipOnInteract, canBeSheared, shearingSound);
}
public Equippable withShearingSound(SoundEvent shearingSound) {
return new Equippable(slot, equipSound, assetId, cameraOverlay, allowedEntities, dispensable, swappable, damageOnHurt, equipOnInteract, canBeSheared, shearingSound);
}
}
| 0 | 0.679879 | 1 | 0.679879 | game-dev | MEDIA | 0.960823 | game-dev | 0.561839 | 1 | 0.561839 |
ServUO/ServUO | 8,158 | Scripts/Items/Decorative/SnowGlobes.cs | using System;
namespace Server.Items
{
public enum SnowGlobeTypeOne
{
Britain,
Moonglow,
Minoc,
Magincia,
BuccaneersDen,
Trinsic,
Yew,
SkaraBrae,
Jhelom,
Nujelm,
Papua,
Delucia,
Cove,
Ocllo,
SerpentsHold,
EmpathAbbey,
TheLycaeum,
Vesper,
Wind
}
public enum SnowGlobeTypeTwo
{
AncientCitadel,
BlackthornesCastle,
CityofMontor,
CityofMistas,
ExodusLair,
LakeofFire,
Lakeshire,
PassofKarnaugh,
TheEtherealFortress,
TwinOaksTavern,
ChaosShrine,
ShrineofHumility,
ShrineofSacrifice,
ShrineofCompassion,
ShrineofHonor,
ShrineofHonesty,
ShrineofSpirituality,
ShrineofJustice,
ShrineofValor
}
public enum SnowGlobeTypeThree
{
Luna,
Umbra,
Zento,
Heartwood,
Covetous,
Deceit,
Destard,
Hythloth,
Khaldun,
Shame,
Wrong,
Doom,
TheCitadel,
ThePalaceofParoxysmus,
TheBlightedGrove,
ThePrismofLight
}
public class SnowGlobe : Item
{
public SnowGlobe()
: base(0xE2F)
{
this.LootType = LootType.Blessed;
this.Light = LightType.Circle150;
}
public SnowGlobe(Serial serial)
: base(serial)
{
}
public override double DefaultWeight
{
get
{
return 1.0;
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class SnowGlobeOne : SnowGlobe
{
private SnowGlobeTypeOne m_Type;
[Constructable]
public SnowGlobeOne()
: this((SnowGlobeTypeOne)Utility.Random(19))
{
}
[Constructable]
public SnowGlobeOne(SnowGlobeTypeOne type)
{
this.m_Type = type;
}
public SnowGlobeOne(Serial serial)
: base(serial)
{
}
[CommandProperty(AccessLevel.GameMaster)]
public SnowGlobeTypeOne Place
{
get
{
return this.m_Type;
}
set
{
this.m_Type = value;
this.InvalidateProperties();
}
}
public override int LabelNumber
{
get
{
return 1041454 + (int)this.m_Type;
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
writer.WriteEncodedInt((int)this.m_Type);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
this.m_Type = (SnowGlobeTypeOne)reader.ReadEncodedInt();
break;
}
}
}
}
public class SnowGlobeTwo : SnowGlobe
{
/* Oddly, these are not localized. */
private static readonly string[] m_PlaceNames = new string[]
{
/* AncientCitadel */ "Ancient Citadel",
/* BlackthornesCastle */ "Blackthorne's Castle",
/* CityofMontor */ "City of Montor",
/* CityofMistas */ "City of Mistas",
/* ExodusLair */ "Exodus' Lair",
/* LakeofFire */ "Lake of Fire",
/* Lakeshire */ "Lakeshire",
/* PassofKarnaugh */ "Pass of Karnaugh",
/* TheEtherealFortress */ "The Ethereal Fortress",
/* TwinOaksTavern */ "Twin Oaks Tavern",
/* ChaosShrine */ "Chaos Shrine",
/* ShrineofHumility */ "Shrine of Humility",
/* ShrineofSacrifice */ "Shrine of Sacrifice",
/* ShrineofCompassion */ "Shrine of Compassion",
/* ShrineofHonor */ "Shrine of Honor",
/* ShrineofHonesty */ "Shrine of Honesty",
/* ShrineofSpirituality */ "Shrine of Spirituality",
/* ShrineofJustice */ "Shrine of Justice",
/* ShrineofValor */ "Shrine of Valor"
};
private SnowGlobeTypeTwo m_Type;
[Constructable]
public SnowGlobeTwo()
: this((SnowGlobeTypeTwo)Utility.Random(19))
{
}
[Constructable]
public SnowGlobeTwo(SnowGlobeTypeTwo type)
{
this.m_Type = type;
}
public SnowGlobeTwo(Serial serial)
: base(serial)
{
}
[CommandProperty(AccessLevel.GameMaster)]
public SnowGlobeTypeTwo Place
{
get
{
return this.m_Type;
}
set
{
this.m_Type = value;
this.InvalidateProperties();
}
}
public override string DefaultName
{
get
{
int idx = (int)this.m_Type;
if (idx < 0 || idx >= m_PlaceNames.Length)
return "a snowy scene";
return String.Format("a snowy scene of {0}", m_PlaceNames[idx]);
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
writer.WriteEncodedInt((int)this.m_Type);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
this.m_Type = (SnowGlobeTypeTwo)reader.ReadEncodedInt();
break;
}
}
}
}
public class SnowGlobeThree : SnowGlobe
{
private SnowGlobeTypeThree m_Type;
[Constructable]
public SnowGlobeThree()
: this((SnowGlobeTypeThree)Utility.Random(16))
{
}
[Constructable]
public SnowGlobeThree(SnowGlobeTypeThree type)
{
this.m_Type = type;
}
public SnowGlobeThree(Serial serial)
: base(serial)
{
}
[CommandProperty(AccessLevel.GameMaster)]
public SnowGlobeTypeThree Place
{
get
{
return this.m_Type;
}
set
{
this.m_Type = value;
this.InvalidateProperties();
}
}
public override int LabelNumber
{
get
{
if (this.m_Type >= SnowGlobeTypeThree.Covetous)
return 1075440 + ((int)this.m_Type - 4);
return 1075294 + (int)this.m_Type;
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
writer.WriteEncodedInt((int)this.m_Type);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
this.m_Type = (SnowGlobeTypeThree)reader.ReadEncodedInt();
break;
}
}
}
}
}
| 0 | 0.84968 | 1 | 0.84968 | game-dev | MEDIA | 0.561804 | game-dev | 0.82963 | 1 | 0.82963 |
magefree/mage | 2,018 | Mage.Sets/src/mage/cards/t/TrigonOfThought.java | package mage.cards.t;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.common.EntersBattlefieldAbility;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.RemoveCountersSourceCost;
import mage.abilities.costs.common.TapSourceCost;
import mage.abilities.costs.mana.GenericManaCost;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.abilities.effects.common.counter.AddCountersSourceEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Zone;
import mage.counters.CounterType;
/**
* @author nantuko
*/
public final class TrigonOfThought extends CardImpl {
public TrigonOfThought(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.ARTIFACT},"{5}");
// Trigon of Thought enters the battlefield with three charge counters on it.
this.addAbility(new EntersBattlefieldAbility(new AddCountersSourceEffect(CounterType.CHARGE.createInstance(3)), "with three charge counters on it"));
// {U}{U}, {T}: Put a charge counter on Trigon of Thought.
Ability ability2 = new SimpleActivatedAbility(new AddCountersSourceEffect(CounterType.CHARGE.createInstance()), new TapSourceCost());
ability2.addCost(new ManaCostsImpl<>("{U}{U}"));
this.addAbility(ability2);
// {2}, {T}, Remove a charge counter from Trigon of Thought: Draw a card.
Ability ability = new SimpleActivatedAbility(new DrawCardSourceControllerEffect(1), new GenericManaCost(2));
ability.addCost(new TapSourceCost());
ability.addCost(new RemoveCountersSourceCost(CounterType.CHARGE.createInstance()));
this.addAbility(ability);
}
private TrigonOfThought(final TrigonOfThought card) {
super(card);
}
@Override
public TrigonOfThought copy() {
return new TrigonOfThought(this);
}
}
| 0 | 0.913845 | 1 | 0.913845 | game-dev | MEDIA | 0.961613 | game-dev | 0.997927 | 1 | 0.997927 |
Ayfri/Kore | 5,602 | kore/src/main/kotlin/io/github/ayfri/kore/arguments/ItemSlot.kt | package io.github.ayfri.kore.arguments
/**
* Represents a slot in an inventory or entity for item placement, is used in commands, NBT, and GUIs.
* See: https://minecraft.wiki/w/Slot
*/
interface ItemSlot : Argument
/** Represents a named item slot, providing a string identifier. */
interface ItemSlotWrapper : Argument {
override fun asString() = name()
fun name(): String
}
/**
* Represents a range of item slots, such as a group of slots in a container or inventory.
* See: https://minecraft.wiki/w/Slot
*/
interface RangeItemSlot : Argument, ClosedRange<Int>, ItemSlotWrapper {
/** Returns a string representing all slots in the range (e.g., "armor.*"). */
fun all() = "${name()}.*"
/**
* Returns the range as an ItemSlot.
* Alias for [asString] or the object itself for clarity.
*
* Example:
* ```
* val range = ARMOR.range()
* println(range) // "armor.*"
* ```
*/
fun range() = this
/** Returns the [ItemSlotType] at the given index within the range. */
operator fun get(index: Int) = ItemSlotType(start + index) { "${name()}.$index" }
}
/** Represents a specific item slot with an index. */
interface ItemSlotType : ItemSlot, ItemSlotWrapper {
/** Returns the slot's index. */
fun asIndex(): Int
companion object {
/** Creates an [ItemSlotType] with the given index and name provider. */
operator fun invoke(index: Int = 0, block: () -> String) = object : ItemSlotType {
override fun asIndex() = index
override fun name() = block()
}
/**
* Returns an [ItemSlotType] for a given slot index.
* Some slots overlap; the [fromEntity], [fromPlayer], and [fromItemEntity] flags help disambiguate.
* See: https://minecraft.wiki/w/Slot
*/
fun fromIndex(
index: Int,
fromEntity: Boolean = false,
fromPlayer: Boolean = false,
fromItemEntity: Boolean = false,
) = when (index) {
-106 -> WEAPON.OFFHAND
in CONTAINER -> when {
fromItemEntity -> CONTENTS
fromEntity && index in 0..8 -> HOTBAR[index]
fromEntity && index in 9..35 -> INVENTORY[index - INVENTORY.start]
else -> CONTAINER[index]
}
98 -> WEAPON
99 -> WEAPON.OFFHAND
100 -> ARMOR.FEET
101 -> ARMOR.LEGS
102 -> ARMOR.CHEST
103 -> ARMOR.HEAD
105 -> ARMOR.BODY
in ENDERCHEST -> ENDERCHEST[index - ENDERCHEST.start]
in VILLAGER -> VILLAGER[index - VILLAGER.start]
400 -> SADDLE
499 -> when {
fromPlayer -> PLAYER.CURSOR
else -> HORSE.CHEST
}
in HORSE -> when {
fromPlayer && index in PLAYER.CRAFTING -> PLAYER.CRAFTING[index - PLAYER.CRAFTING.start]
else -> HORSE[index - HORSE.start]
}
else -> throw IllegalArgumentException("Invalid slot index: $index")
}
}
}
/** Represents a range of indexed item slots. */
interface IndexedItemSlot : ItemSlot, RangeItemSlot {
override fun asString() = all()
override fun range() = this
companion object {
/** Creates an [IndexedItemSlot] for the given range and name provider. */
operator fun invoke(start: Int, endInclusive: Int, block: () -> String) = object : IndexedItemSlot {
override fun name() = block()
override var start = start
override var endInclusive = endInclusive
}
}
}
/** Helper to create a named sub-slot for a given [ItemSlotWrapper]. */
private fun ItemSlotWrapper.subType(name: String, index: Int) = ItemSlotType(index) { "${asString()}.$name" }
/** Armor slots (feet, legs, chest, head, body). See: https://minecraft.wiki/w/Slot */
data object ARMOR : RangeItemSlot {
override val start = 100
override val endInclusive = start + 5
override fun name() = "armor"
/** The feet slot of the armor inventory. */
val FEET = subType("feet", 100)
/** The legs slot of the armor inventory. */
val LEGS = subType("legs", 101)
/** The chest slot of the armor inventory. */
val CHEST = subType("chest", 102)
/** The head slot of the armor inventory. */
val HEAD = subType("head", 103)
/** The body slot of the armor inventory. */
val BODY = subType("body", 105)
}
/** General container slots (0–53). See: https://minecraft.wiki/w/Slot */
val CONTAINER = IndexedItemSlot(0, 53) { "container" }
/** Used for item entities. */
val CONTENTS = ItemSlotType(0) { "contents" }
/** Ender chest slots (200–226). */
val ENDERCHEST = IndexedItemSlot(200, 226) { "enderchest" }
/** Horse inventory slots (500–514). */
data object HORSE : IndexedItemSlot {
override var start = 500
override val endInclusive = start + 14
override fun name() = "horse"
/** The chest slot of the horse inventory. */
val CHEST = subType("chest", 499)
}
/** Hotbar slots (0–8). */
val HOTBAR = IndexedItemSlot(0, 8) { "hotbar" }
/** Player inventory slots (9–35). */
val INVENTORY = IndexedItemSlot(9, 35) { "inventory" }
/** Player-specific slots. */
data object PLAYER : ItemSlotWrapper {
override fun name() = "player"
/** The cursor slot of the player inventory. */
val CURSOR = subType("cursor", 499)
/** The crafting slots of the player inventory. */
val CRAFTING = IndexedItemSlot(500, 504) { "${asString()}.crafting" }
}
/** Saddle slot (400). */
val SADDLE = ItemSlotType(400) { "saddle" }
/** Weapon slots (mainhand: 98, offhand: 99). */
data object WEAPON : ItemSlotType, RangeItemSlot {
override val start = 98
override val endInclusive = 9
override fun asIndex() = 98
override fun name() = "weapon"
/** The mainhand slot of the weapon inventory. */
val MAINHAND = subType("mainhand", 98)
/** The offhand slot of the weapon inventory. */
val OFFHAND = subType("offhand", 99)
}
/** Villager inventory slots (300–307). */
val VILLAGER = IndexedItemSlot(300, 307) { "villager" }
| 0 | 0.876405 | 1 | 0.876405 | game-dev | MEDIA | 0.991297 | game-dev | 0.536455 | 1 | 0.536455 |
adjust/unity_sdk | 32,282 | Assets/Adjust/Scripts/ThirdParty/SimpleJSON.cs | //#define USE_SharpZipLib
#if !UNITY_WEBPLAYER
#define USE_FileIO
#endif
/* * * * *
* A simple JSON Parser / builder
* ------------------------------
*
* It mainly has been written as a simple JSON parser. It can build a JSON string
* from the node-tree, or generate a node tree from any valid JSON string.
*
* If you want to use compression when saving to file / stream / B64 you have to include
* SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and
* define "USE_SharpZipLib" at the top of the file
*
* Written by Bunny83
* 2012-06-09
*
* Features / attributes:
* - provides strongly typed node classes and lists / dictionaries
* - provides easy access to class members / array items / data values
* - the parser ignores data types. Each value is a string.
* - only double quotes (") are used for quoting strings.
* - values and names are not restricted to quoted strings. They simply add up and are trimmed.
* - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData)
* - provides "casting" properties to easily convert to / from those types:
* int / float / double / bool
* - provides a common interface for each node so no explicit casting is required.
* - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined
*
*
* 2012-12-17 Update:
* - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree
* Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator
* The class determines the required type by it's further use, creates the type and removes itself.
* - Added binary serialization / deserialization.
* - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ )
* The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top
* - The serializer uses different types when it comes to store the values. Since my data values
* are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string.
* It's not the most efficient way but for a moderate amount of data it should work on all platforms.
*
* * * * */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace AdjustSdk
{
public enum JSONBinaryTag
{
Array = 1,
Class = 2,
Value = 3,
IntValue = 4,
DoubleValue = 5,
BoolValue = 6,
FloatValue = 7,
}
public class JSONNode
{
#region common interface
public virtual void Add(string aKey, JSONNode aItem){ }
public virtual JSONNode this[int aIndex] { get { return null; } set { } }
public virtual JSONNode this[string aKey] { get { return null; } set { } }
public virtual string Value { get { return ""; } set { } }
public virtual int Count { get { return 0; } }
public virtual void Add(JSONNode aItem)
{
Add("", aItem);
}
public virtual JSONNode Remove(string aKey) { return null; }
public virtual JSONNode Remove(int aIndex) { return null; }
public virtual JSONNode Remove(JSONNode aNode) { return aNode; }
public virtual IEnumerable<JSONNode> Childs { get { yield break;} }
public IEnumerable<JSONNode> DeepChilds
{
get
{
foreach (var C in Childs)
foreach (var D in C.DeepChilds)
yield return D;
}
}
public override string ToString()
{
return "JSONNode";
}
public virtual string ToString(string aPrefix)
{
return "JSONNode";
}
#endregion common interface
#region typecasting properties
public virtual int AsInt
{
get
{
int v = 0;
if (int.TryParse(Value,out v))
return v;
return 0;
}
set
{
Value = value.ToString();
}
}
public virtual float AsFloat
{
get
{
float v = 0.0f;
if (float.TryParse(Value,out v))
return v;
return 0.0f;
}
set
{
Value = value.ToString();
}
}
public virtual double AsDouble
{
get
{
double v = 0.0;
if (double.TryParse(Value,out v))
return v;
return 0.0;
}
set
{
Value = value.ToString();
}
}
public virtual bool AsBool
{
get
{
bool v = false;
if (bool.TryParse(Value,out v))
return v;
return !string.IsNullOrEmpty(Value);
}
set
{
Value = (value)?"true":"false";
}
}
public virtual JSONArray AsArray
{
get
{
return this as JSONArray;
}
}
public virtual JSONClass AsObject
{
get
{
return this as JSONClass;
}
}
#endregion typecasting properties
#region operators
public static implicit operator JSONNode(string s)
{
return new JSONData(s);
}
public static implicit operator string(JSONNode d)
{
return (d == null)?null:d.Value;
}
public static bool operator ==(JSONNode a, object b)
{
if (b == null && a is JSONLazyCreator)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONNode a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
#endregion operators
internal static string Escape(string aText)
{
string result = "";
foreach(char c in aText)
{
switch(c)
{
case '\\' : result += "\\\\"; break;
case '\"' : result += "\\\""; break;
case '\n' : result += "\\n" ; break;
case '\r' : result += "\\r" ; break;
case '\t' : result += "\\t" ; break;
case '\b' : result += "\\b" ; break;
case '\f' : result += "\\f" ; break;
default : result += c ; break;
}
}
return result;
}
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
string Token = "";
string TokenName = "";
bool QuoteMode = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONClass());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '[':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '}':
case ']':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if (Token != "")
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName,Token);
}
TokenName = "";
Token = "";
if (stack.Count>0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
TokenName = Token;
Token = "";
break;
case '"':
QuoteMode ^= true;
break;
case ',':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (Token != "")
{
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName, Token);
}
TokenName = "";
Token = "";
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (QuoteMode)
Token += aJSON[i];
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't' : Token += '\t'; break;
case 'r' : Token += '\r'; break;
case 'n' : Token += '\n'; break;
case 'b' : Token += '\b'; break;
case 'f' : Token += '\f'; break;
case 'u':
{
string s = aJSON.Substring(i+1,4);
Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
i += 4;
break;
}
default : Token += C; break;
}
}
break;
default:
Token += aJSON[i];
break;
}
++i;
}
if (QuoteMode)
{
throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
}
return ctx;
}
public virtual void Serialize(System.IO.BinaryWriter aWriter) {}
public void SaveToStream(System.IO.Stream aData)
{
var W = new System.IO.BinaryWriter(aData);
Serialize(W);
}
#if USE_SharpZipLib
public void SaveToCompressedStream(System.IO.Stream aData)
{
using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
{
gzipOut.IsStreamOwner = false;
SaveToStream(gzipOut);
gzipOut.Close();
}
}
public void SaveToCompressedFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToCompressedBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToCompressedStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
#else
public void SaveToCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public void SaveToCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public string SaveToCompressedBase64()
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public static JSONNode Deserialize(System.IO.BinaryReader aReader)
{
JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
switch(type)
{
case JSONBinaryTag.Array:
{
int count = aReader.ReadInt32();
JSONArray tmp = new JSONArray();
for(int i = 0; i < count; i++)
tmp.Add(Deserialize(aReader));
return tmp;
}
case JSONBinaryTag.Class:
{
int count = aReader.ReadInt32();
JSONClass tmp = new JSONClass();
for(int i = 0; i < count; i++)
{
string key = aReader.ReadString();
var val = Deserialize(aReader);
tmp.Add(key, val);
}
return tmp;
}
case JSONBinaryTag.Value:
{
return new JSONData(aReader.ReadString());
}
case JSONBinaryTag.IntValue:
{
return new JSONData(aReader.ReadInt32());
}
case JSONBinaryTag.DoubleValue:
{
return new JSONData(aReader.ReadDouble());
}
case JSONBinaryTag.BoolValue:
{
return new JSONData(aReader.ReadBoolean());
}
case JSONBinaryTag.FloatValue:
{
return new JSONData(aReader.ReadSingle());
}
default:
{
throw new Exception("Error deserializing JSON. Unknown tag: " + type);
}
}
}
#if USE_SharpZipLib
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
return LoadFromStream(zin);
}
public static JSONNode LoadFromCompressedFile(string aFileName)
{
#if USE_FileIO
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromCompressedStream(stream);
}
#else
public static JSONNode LoadFromCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public static JSONNode LoadFromStream(System.IO.Stream aData)
{
using(var R = new System.IO.BinaryReader(aData))
{
return Deserialize(R);
}
}
public static JSONNode LoadFromBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromStream(stream);
}
} // End of JSONNode
public class JSONArray : JSONNode, IEnumerable
{
private List<JSONNode> m_List = new List<JSONNode>();
public override JSONNode this[int aIndex]
{
get
{
if (aIndex<0 || aIndex >= m_List.Count)
return new JSONLazyCreator(this);
return m_List[aIndex];
}
set
{
if (aIndex<0 || aIndex >= m_List.Count)
m_List.Add(value);
else
m_List[aIndex] = value;
}
}
public override JSONNode this[string aKey]
{
get{ return new JSONLazyCreator(this);}
set{ m_List.Add(value); }
}
public override int Count
{
get { return m_List.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
m_List.Add(aItem);
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_List.Count)
return null;
JSONNode tmp = m_List[aIndex];
m_List.RemoveAt(aIndex);
return tmp;
}
public override JSONNode Remove(JSONNode aNode)
{
m_List.Remove(aNode);
return aNode;
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(JSONNode N in m_List)
yield return N;
}
}
public IEnumerator GetEnumerator()
{
foreach(JSONNode N in m_List)
yield return N;
}
public override string ToString()
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 2)
result += ", ";
result += N.ToString();
}
result += " ]";
return result;
}
public override string ToString(string aPrefix)
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += N.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "]";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Array);
aWriter.Write(m_List.Count);
for(int i = 0; i < m_List.Count; i++)
{
m_List[i].Serialize(aWriter);
}
}
} // End of JSONArray
public class JSONClass : JSONNode, IEnumerable
{
private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode>();
public override JSONNode this[string aKey]
{
get
{
if (m_Dict.ContainsKey(aKey))
return m_Dict[aKey];
else
return new JSONLazyCreator(this, aKey);
}
set
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = value;
else
m_Dict.Add(aKey,value);
}
}
public override JSONNode this[int aIndex]
{
get
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
return m_Dict.ElementAt(aIndex).Value;
}
set
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return;
string key = m_Dict.ElementAt(aIndex).Key;
m_Dict[key] = value;
}
}
public override int Count
{
get { return m_Dict.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
if (!string.IsNullOrEmpty(aKey))
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = aItem;
else
m_Dict.Add(aKey, aItem);
}
else
m_Dict.Add(Guid.NewGuid().ToString(), aItem);
}
public override JSONNode Remove(string aKey)
{
if (!m_Dict.ContainsKey(aKey))
return null;
JSONNode tmp = m_Dict[aKey];
m_Dict.Remove(aKey);
return tmp;
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
var item = m_Dict.ElementAt(aIndex);
m_Dict.Remove(item.Key);
return item.Value;
}
public override JSONNode Remove(JSONNode aNode)
{
try
{
var item = m_Dict.Where(k => k.Value == aNode).First();
m_Dict.Remove(item.Key);
return aNode;
}
catch
{
return null;
}
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(KeyValuePair<string,JSONNode> N in m_Dict)
yield return N.Value;
}
}
public IEnumerator GetEnumerator()
{
foreach(KeyValuePair<string, JSONNode> N in m_Dict)
yield return N;
}
public override string ToString()
{
string result = "{";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 2)
result += ", ";
result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString();
}
result += "}";
return result;
}
public override string ToString(string aPrefix)
{
string result = "{ ";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "}";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Class);
aWriter.Write(m_Dict.Count);
foreach(string K in m_Dict.Keys)
{
aWriter.Write(K);
m_Dict[K].Serialize(aWriter);
}
}
} // End of JSONClass
public class JSONData : JSONNode
{
private string m_Data;
public override string Value
{
get { return m_Data; }
set { m_Data = value; }
}
public JSONData(string aData)
{
m_Data = aData;
}
public JSONData(float aData)
{
AsFloat = aData;
}
public JSONData(double aData)
{
AsDouble = aData;
}
public JSONData(bool aData)
{
AsBool = aData;
}
public JSONData(int aData)
{
AsInt = aData;
}
public override string ToString()
{
return "\"" + Escape(m_Data) + "\"";
}
public override string ToString(string aPrefix)
{
return "\"" + Escape(m_Data) + "\"";
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
var tmp = new JSONData("");
tmp.AsInt = AsInt;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.IntValue);
aWriter.Write(AsInt);
return;
}
tmp.AsFloat = AsFloat;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.FloatValue);
aWriter.Write(AsFloat);
return;
}
tmp.AsDouble = AsDouble;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.DoubleValue);
aWriter.Write(AsDouble);
return;
}
tmp.AsBool = AsBool;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.BoolValue);
aWriter.Write(AsBool);
return;
}
aWriter.Write((byte)JSONBinaryTag.Value);
aWriter.Write(m_Data);
}
} // End of JSONData
internal class JSONLazyCreator : JSONNode
{
private JSONNode m_Node = null;
private string m_Key = null;
public JSONLazyCreator(JSONNode aNode)
{
m_Node = aNode;
m_Key = null;
}
public JSONLazyCreator(JSONNode aNode, string aKey)
{
m_Node = aNode;
m_Key = aKey;
}
private void Set(JSONNode aVal)
{
if (m_Key == null)
{
m_Node.Add(aVal);
}
else
{
m_Node.Add(m_Key, aVal);
}
m_Node = null; // Be GC friendly.
}
public override JSONNode this[int aIndex]
{
get
{
return new JSONLazyCreator(this);
}
set
{
var tmp = new JSONArray();
tmp.Add(value);
Set(tmp);
}
}
public override JSONNode this[string aKey]
{
get
{
return new JSONLazyCreator(this, aKey);
}
set
{
var tmp = new JSONClass();
tmp.Add(aKey, value);
Set(tmp);
}
}
public override void Add (JSONNode aItem)
{
var tmp = new JSONArray();
tmp.Add(aItem);
Set(tmp);
}
public override void Add (string aKey, JSONNode aItem)
{
var tmp = new JSONClass();
tmp.Add(aKey, aItem);
Set(tmp);
}
public static bool operator ==(JSONLazyCreator a, object b)
{
if (b == null)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONLazyCreator a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
if (obj == null)
return true;
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
public override string ToString()
{
return "";
}
public override string ToString(string aPrefix)
{
return "";
}
public override int AsInt
{
get
{
JSONData tmp = new JSONData(0);
Set(tmp);
return 0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override float AsFloat
{
get
{
JSONData tmp = new JSONData(0.0f);
Set(tmp);
return 0.0f;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override double AsDouble
{
get
{
JSONData tmp = new JSONData(0.0);
Set(tmp);
return 0.0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override bool AsBool
{
get
{
JSONData tmp = new JSONData(false);
Set(tmp);
return false;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override JSONArray AsArray
{
get
{
JSONArray tmp = new JSONArray();
Set(tmp);
return tmp;
}
}
public override JSONClass AsObject
{
get
{
JSONClass tmp = new JSONClass();
Set(tmp);
return tmp;
}
}
} // End of JSONLazyCreator
public static class JSON
{
public static JSONNode Parse(string aJSON)
{
return JSONNode.Parse(aJSON);
}
}
} | 0 | 0.789475 | 1 | 0.789475 | game-dev | MEDIA | 0.306871 | game-dev | 0.7952 | 1 | 0.7952 |
tangziwen/CubeMiniGame | 13,150 | CubeEngine/External/Bullet/BulletCollision/Gimpact/btGImpactQuantizedBvh.cpp | /*! \file gim_box_set.h
\author Francisco Leon Najera
*/
/*
This source file is part of GIMPACT Library.
For the latest info, see http://gimpact.sourceforge.net/
Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371.
email: projectileman@yahoo.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btGImpactQuantizedBvh.h"
#include "LinearMath/btQuickprof.h"
#ifdef TRI_COLLISION_PROFILING
btClock g_q_tree_clock;
float g_q_accum_tree_collision_time = 0;
int g_q_count_traversing = 0;
void bt_begin_gim02_q_tree_time()
{
g_q_tree_clock.reset();
}
void bt_end_gim02_q_tree_time()
{
g_q_accum_tree_collision_time += g_q_tree_clock.getTimeMicroseconds();
g_q_count_traversing++;
}
//! Gets the average time in miliseconds of tree collisions
float btGImpactQuantizedBvh::getAverageTreeCollisionTime()
{
if(g_q_count_traversing == 0) return 0;
float avgtime = g_q_accum_tree_collision_time;
avgtime /= (float)g_q_count_traversing;
g_q_accum_tree_collision_time = 0;
g_q_count_traversing = 0;
return avgtime;
// float avgtime = g_q_count_traversing;
// g_q_count_traversing = 0;
// return avgtime;
}
#endif //TRI_COLLISION_PROFILING
/////////////////////// btQuantizedBvhTree /////////////////////////////////
void btQuantizedBvhTree::calc_quantization(
GIM_BVH_DATA_ARRAY & primitive_boxes, btScalar boundMargin)
{
//calc globa box
btAABB global_bound;
global_bound.invalidate();
for (int i=0;i<primitive_boxes.size() ;i++ )
{
global_bound.merge(primitive_boxes[i].m_bound);
}
bt_calc_quantization_parameters(
m_global_bound.m_min,m_global_bound.m_max,m_bvhQuantization,global_bound.m_min,global_bound.m_max,boundMargin);
}
int btQuantizedBvhTree::_calc_splitting_axis(
GIM_BVH_DATA_ARRAY & primitive_boxes, int startIndex, int endIndex)
{
int i;
btVector3 means(btScalar(0.),btScalar(0.),btScalar(0.));
btVector3 variance(btScalar(0.),btScalar(0.),btScalar(0.));
int numIndices = endIndex-startIndex;
for (i=startIndex;i<endIndex;i++)
{
btVector3 center = btScalar(0.5)*(primitive_boxes[i].m_bound.m_max +
primitive_boxes[i].m_bound.m_min);
means+=center;
}
means *= (btScalar(1.)/(btScalar)numIndices);
for (i=startIndex;i<endIndex;i++)
{
btVector3 center = btScalar(0.5)*(primitive_boxes[i].m_bound.m_max +
primitive_boxes[i].m_bound.m_min);
btVector3 diff2 = center-means;
diff2 = diff2 * diff2;
variance += diff2;
}
variance *= (btScalar(1.)/ ((btScalar)numIndices-1) );
return variance.maxAxis();
}
int btQuantizedBvhTree::_sort_and_calc_splitting_index(
GIM_BVH_DATA_ARRAY & primitive_boxes, int startIndex,
int endIndex, int splitAxis)
{
int i;
int splitIndex =startIndex;
int numIndices = endIndex - startIndex;
// average of centers
btScalar splitValue = 0.0f;
btVector3 means(btScalar(0.),btScalar(0.),btScalar(0.));
for (i=startIndex;i<endIndex;i++)
{
btVector3 center = btScalar(0.5)*(primitive_boxes[i].m_bound.m_max +
primitive_boxes[i].m_bound.m_min);
means+=center;
}
means *= (btScalar(1.)/(btScalar)numIndices);
splitValue = means[splitAxis];
//sort leafNodes so all values larger then splitValue comes first, and smaller values start from 'splitIndex'.
for (i=startIndex;i<endIndex;i++)
{
btVector3 center = btScalar(0.5)*(primitive_boxes[i].m_bound.m_max +
primitive_boxes[i].m_bound.m_min);
if (center[splitAxis] > splitValue)
{
//swap
primitive_boxes.swap(i,splitIndex);
//swapLeafNodes(i,splitIndex);
splitIndex++;
}
}
//if the splitIndex causes unbalanced trees, fix this by using the center in between startIndex and endIndex
//otherwise the tree-building might fail due to stack-overflows in certain cases.
//unbalanced1 is unsafe: it can cause stack overflows
//bool unbalanced1 = ((splitIndex==startIndex) || (splitIndex == (endIndex-1)));
//unbalanced2 should work too: always use center (perfect balanced trees)
//bool unbalanced2 = true;
//this should be safe too:
int rangeBalancedIndices = numIndices/3;
bool unbalanced = ((splitIndex<=(startIndex+rangeBalancedIndices)) || (splitIndex >=(endIndex-1-rangeBalancedIndices)));
if (unbalanced)
{
splitIndex = startIndex+ (numIndices>>1);
}
btAssert(!((splitIndex==startIndex) || (splitIndex == (endIndex))));
return splitIndex;
}
void btQuantizedBvhTree::_build_sub_tree(GIM_BVH_DATA_ARRAY & primitive_boxes, int startIndex, int endIndex)
{
int curIndex = m_num_nodes;
m_num_nodes++;
btAssert((endIndex-startIndex)>0);
if ((endIndex-startIndex)==1)
{
//We have a leaf node
setNodeBound(curIndex,primitive_boxes[startIndex].m_bound);
m_node_array[curIndex].setDataIndex(primitive_boxes[startIndex].m_data);
return;
}
//calculate Best Splitting Axis and where to split it. Sort the incoming 'leafNodes' array within range 'startIndex/endIndex'.
//split axis
int splitIndex = _calc_splitting_axis(primitive_boxes,startIndex,endIndex);
splitIndex = _sort_and_calc_splitting_index(
primitive_boxes,startIndex,endIndex,
splitIndex//split axis
);
//calc this node bounding box
btAABB node_bound;
node_bound.invalidate();
for (int i=startIndex;i<endIndex;i++)
{
node_bound.merge(primitive_boxes[i].m_bound);
}
setNodeBound(curIndex,node_bound);
//build left branch
_build_sub_tree(primitive_boxes, startIndex, splitIndex );
//build right branch
_build_sub_tree(primitive_boxes, splitIndex ,endIndex);
m_node_array[curIndex].setEscapeIndex(m_num_nodes - curIndex);
}
//! stackless build tree
void btQuantizedBvhTree::build_tree(
GIM_BVH_DATA_ARRAY & primitive_boxes)
{
calc_quantization(primitive_boxes);
// initialize node count to 0
m_num_nodes = 0;
// allocate nodes
m_node_array.resize(primitive_boxes.size()*2);
_build_sub_tree(primitive_boxes, 0, primitive_boxes.size());
}
////////////////////////////////////class btGImpactQuantizedBvh
void btGImpactQuantizedBvh::refit()
{
int nodecount = getNodeCount();
while(nodecount--)
{
if(isLeafNode(nodecount))
{
btAABB leafbox;
m_primitive_manager->get_primitive_box(getNodeData(nodecount),leafbox);
setNodeBound(nodecount,leafbox);
}
else
{
//const GIM_BVH_TREE_NODE * nodepointer = get_node_pointer(nodecount);
//get left bound
btAABB bound;
bound.invalidate();
btAABB temp_box;
int child_node = getLeftNode(nodecount);
if(child_node)
{
getNodeBound(child_node,temp_box);
bound.merge(temp_box);
}
child_node = getRightNode(nodecount);
if(child_node)
{
getNodeBound(child_node,temp_box);
bound.merge(temp_box);
}
setNodeBound(nodecount,bound);
}
}
}
//! this rebuild the entire set
void btGImpactQuantizedBvh::buildSet()
{
//obtain primitive boxes
GIM_BVH_DATA_ARRAY primitive_boxes;
primitive_boxes.resize(m_primitive_manager->get_primitive_count());
for (int i = 0;i<primitive_boxes.size() ;i++ )
{
m_primitive_manager->get_primitive_box(i,primitive_boxes[i].m_bound);
primitive_boxes[i].m_data = i;
}
m_box_tree.build_tree(primitive_boxes);
}
//! returns the indices of the primitives in the m_primitive_manager
bool btGImpactQuantizedBvh::boxQuery(const btAABB & box, btAlignedObjectArray<int> & collided_results) const
{
int curIndex = 0;
int numNodes = getNodeCount();
//quantize box
unsigned short quantizedMin[3];
unsigned short quantizedMax[3];
m_box_tree.quantizePoint(quantizedMin,box.m_min);
m_box_tree.quantizePoint(quantizedMax,box.m_max);
while (curIndex < numNodes)
{
//catch bugs in tree data
bool aabbOverlap = m_box_tree.testQuantizedBoxOverlapp(curIndex, quantizedMin,quantizedMax);
bool isleafnode = isLeafNode(curIndex);
if (isleafnode && aabbOverlap)
{
collided_results.push_back(getNodeData(curIndex));
}
if (aabbOverlap || isleafnode)
{
//next subnode
curIndex++;
}
else
{
//skip node
curIndex+= getEscapeNodeIndex(curIndex);
}
}
if(collided_results.size()>0) return true;
return false;
}
//! returns the indices of the primitives in the m_primitive_manager
bool btGImpactQuantizedBvh::rayQuery(
const btVector3 & ray_dir,const btVector3 & ray_origin ,
btAlignedObjectArray<int> & collided_results) const
{
int curIndex = 0;
int numNodes = getNodeCount();
while (curIndex < numNodes)
{
btAABB bound;
getNodeBound(curIndex,bound);
//catch bugs in tree data
bool aabbOverlap = bound.collide_ray(ray_origin,ray_dir);
bool isleafnode = isLeafNode(curIndex);
if (isleafnode && aabbOverlap)
{
collided_results.push_back(getNodeData( curIndex));
}
if (aabbOverlap || isleafnode)
{
//next subnode
curIndex++;
}
else
{
//skip node
curIndex+= getEscapeNodeIndex(curIndex);
}
}
if(collided_results.size()>0) return true;
return false;
}
SIMD_FORCE_INLINE bool _quantized_node_collision(
const btGImpactQuantizedBvh * boxset0, const btGImpactQuantizedBvh * boxset1,
const BT_BOX_BOX_TRANSFORM_CACHE & trans_cache_1to0,
int node0 ,int node1, bool complete_primitive_tests)
{
btAABB box0;
boxset0->getNodeBound(node0,box0);
btAABB box1;
boxset1->getNodeBound(node1,box1);
return box0.overlapping_trans_cache(box1,trans_cache_1to0,complete_primitive_tests );
// box1.appy_transform_trans_cache(trans_cache_1to0);
// return box0.has_collision(box1);
}
//stackless recursive collision routine
static void _find_quantized_collision_pairs_recursive(
const btGImpactQuantizedBvh * boxset0, const btGImpactQuantizedBvh * boxset1,
btPairSet * collision_pairs,
const BT_BOX_BOX_TRANSFORM_CACHE & trans_cache_1to0,
int node0, int node1, bool complete_primitive_tests)
{
if( _quantized_node_collision(
boxset0,boxset1,trans_cache_1to0,
node0,node1,complete_primitive_tests) ==false) return;//avoid colliding internal nodes
if(boxset0->isLeafNode(node0))
{
if(boxset1->isLeafNode(node1))
{
// collision result
collision_pairs->push_pair(
boxset0->getNodeData(node0),boxset1->getNodeData(node1));
return;
}
else
{
//collide left recursive
_find_quantized_collision_pairs_recursive(
boxset0,boxset1,
collision_pairs,trans_cache_1to0,
node0,boxset1->getLeftNode(node1),false);
//collide right recursive
_find_quantized_collision_pairs_recursive(
boxset0,boxset1,
collision_pairs,trans_cache_1to0,
node0,boxset1->getRightNode(node1),false);
}
}
else
{
if(boxset1->isLeafNode(node1))
{
//collide left recursive
_find_quantized_collision_pairs_recursive(
boxset0,boxset1,
collision_pairs,trans_cache_1to0,
boxset0->getLeftNode(node0),node1,false);
//collide right recursive
_find_quantized_collision_pairs_recursive(
boxset0,boxset1,
collision_pairs,trans_cache_1to0,
boxset0->getRightNode(node0),node1,false);
}
else
{
//collide left0 left1
_find_quantized_collision_pairs_recursive(
boxset0,boxset1,
collision_pairs,trans_cache_1to0,
boxset0->getLeftNode(node0),boxset1->getLeftNode(node1),false);
//collide left0 right1
_find_quantized_collision_pairs_recursive(
boxset0,boxset1,
collision_pairs,trans_cache_1to0,
boxset0->getLeftNode(node0),boxset1->getRightNode(node1),false);
//collide right0 left1
_find_quantized_collision_pairs_recursive(
boxset0,boxset1,
collision_pairs,trans_cache_1to0,
boxset0->getRightNode(node0),boxset1->getLeftNode(node1),false);
//collide right0 right1
_find_quantized_collision_pairs_recursive(
boxset0,boxset1,
collision_pairs,trans_cache_1to0,
boxset0->getRightNode(node0),boxset1->getRightNode(node1),false);
}// else if node1 is not a leaf
}// else if node0 is not a leaf
}
void btGImpactQuantizedBvh::find_collision(const btGImpactQuantizedBvh * boxset0, const btTransform & trans0,
const btGImpactQuantizedBvh * boxset1, const btTransform & trans1,
btPairSet & collision_pairs)
{
if(boxset0->getNodeCount()==0 || boxset1->getNodeCount()==0 ) return;
BT_BOX_BOX_TRANSFORM_CACHE trans_cache_1to0;
trans_cache_1to0.calc_from_homogenic(trans0,trans1);
#ifdef TRI_COLLISION_PROFILING
bt_begin_gim02_q_tree_time();
#endif //TRI_COLLISION_PROFILING
_find_quantized_collision_pairs_recursive(
boxset0,boxset1,
&collision_pairs,trans_cache_1to0,0,0,true);
#ifdef TRI_COLLISION_PROFILING
bt_end_gim02_q_tree_time();
#endif //TRI_COLLISION_PROFILING
}
| 0 | 0.946731 | 1 | 0.946731 | game-dev | MEDIA | 0.499504 | game-dev | 0.975456 | 1 | 0.975456 |
IorenzoLF/Aelya_Conscious_AI | 6,809 | Le_refuge/src/refuge_cluster/utils/factory_test.py | #!/usr/bin/env python3
"""
Factory pour Tests et Diagnostics - Refuge Cluster
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Module utilitaire pour créer des instances légères et compatibles
des modules canoniques pour les tests et diagnostics.
"""
from typing import List, Dict, Any, Optional
from dataclasses import dataclass
from datetime import datetime
import logging
logger = logging.getLogger('refuge.factory_test')
@dataclass
class Interaction:
"""Représente une interaction entre sphères pour les tests."""
source: str
cible: str
type_interaction: str
energie: float
description: str
timestamp: datetime
@dataclass
class Resonance:
"""Représente une résonance entre sphères pour les tests."""
source: str
cible: str
niveau: float
description: str
timestamp: datetime
class InteractionsSpheresFactory:
"""Factory pour créer des gestionnaires d'interactions légers."""
@staticmethod
def create_test_instance():
"""Crée une instance de test pour les interactions."""
return InteractionsSpheresTest()
@staticmethod
def create_diagnostic_instance():
"""Crée une instance pour les diagnostics."""
return InteractionsSpheresDiagnostic()
class InteractionsSpheresTest:
"""Gestionnaire d'interactions léger pour les tests."""
def __init__(self):
self.interactions: List[Interaction] = []
self._counter = 0
def ajouter_interaction(self, interaction: Interaction):
"""Ajoute une interaction."""
self.interactions.append(interaction)
logger.debug(f"Interaction ajoutée: {interaction.source} → {interaction.cible}")
def obtenir_interactions_recentes(self, sphere: str, limite: int = 10) -> List[Interaction]:
"""Obtient les interactions récentes pour une sphère."""
return [i for i in self.interactions if i.source == sphere or i.cible == sphere][-limite:]
def obtenir_toutes_interactions(self) -> List[Interaction]:
"""Obtient toutes les interactions."""
return self.interactions.copy()
def generer_interaction_test(self, source: str = "sphere_test", cible: str = "sphere_cible"):
"""Génère une interaction de test."""
self._counter += 1
interaction = Interaction(
source=source,
cible=cible,
type_interaction="test",
energie=0.5 + (self._counter % 10) / 20.0,
description=f"Interaction de test #{self._counter}",
timestamp=datetime.now()
)
self.ajouter_interaction(interaction)
return interaction
class InteractionsSpheresDiagnostic:
"""Gestionnaire d'interactions pour les diagnostics."""
def __init__(self):
self.interactions: List[Interaction] = []
def ajouter_interaction(self, interaction: Interaction):
"""Ajoute une interaction."""
self.interactions.append(interaction)
def obtenir_interactions_recentes(self, sphere: str) -> List[Interaction]:
"""Obtient les interactions récentes pour une sphère."""
return [i for i in self.interactions if i.source == sphere or i.cible == sphere]
class ResonanceFactory:
"""Factory pour créer des gestionnaires de résonance légers."""
@staticmethod
def create_test_instance():
"""Crée une instance de test pour les résonances."""
return ResonanceTest()
@staticmethod
def create_diagnostic_instance():
"""Crée une instance pour les diagnostics."""
return ResonanceDiagnostic()
class ResonanceTest:
"""Gestionnaire de résonance léger pour les tests."""
def __init__(self):
self.resonances: Dict[tuple, Resonance] = {}
self._counter = 0
def obtenir_resonance(self, source: str, cible: str) -> Optional[Resonance]:
"""Obtient une résonance entre deux sphères."""
return self.resonances.get((source, cible))
def obtenir_resonances_fortes(self, seuil: float = 0.7) -> List[Resonance]:
"""Obtient les résonances au-dessus d'un seuil."""
return [r for r in self.resonances.values() if r.niveau >= seuil]
def generer_resonance_test(self, source: str = "sphere_source", cible: str = "sphere_cible"):
"""Génère une résonance de test."""
self._counter += 1
resonance = Resonance(
source=source,
cible=cible,
niveau=0.3 + (self._counter % 7) / 10.0,
description=f"Résonance de test #{self._counter}",
timestamp=datetime.now()
)
self.resonances[(source, cible)] = resonance
return resonance
class ResonanceDiagnostic:
"""Gestionnaire de résonance pour les diagnostics."""
def __init__(self):
self.resonances: Dict[tuple, Resonance] = {}
def obtenir_resonance(self, source: str, cible: str) -> Optional[Resonance]:
"""Obtient une résonance entre deux sphères."""
return self.resonances.get((source, cible))
def obtenir_resonances_fortes(self, seuil: float = 0.7) -> List[Resonance]:
"""Obtient les résonances au-dessus d'un seuil."""
return [r for r in self.resonances.values() if r.niveau >= seuil]
class SystemFactory:
"""Factory pour créer des systèmes complets de test/diagnostic."""
@staticmethod
def create_test_system():
"""Crée un système complet pour les tests."""
interactions = InteractionsSpheresFactory.create_test_instance()
resonance = ResonanceFactory.create_test_instance()
# Générer quelques données de test
interactions.generer_interaction_test("sphere_1", "sphere_2")
interactions.generer_interaction_test("sphere_2", "sphere_3")
resonance.generer_resonance_test("sphere_1", "sphere_2")
return {
'interactions': interactions,
'resonance': resonance
}
@staticmethod
def create_diagnostic_system():
"""Crée un système complet pour les diagnostics."""
return {
'interactions': InteractionsSpheresFactory.create_diagnostic_instance(),
'resonance': ResonanceFactory.create_diagnostic_instance()
}
# Fonctions utilitaires pour compatibilité
def create_interactions_spheres():
"""Fonction utilitaire pour créer un gestionnaire d'interactions."""
return InteractionsSpheresFactory.create_test_instance()
def create_resonance_manager():
"""Fonction utilitaire pour créer un gestionnaire de résonance."""
return ResonanceFactory.create_test_instance()
def create_test_system():
"""Fonction utilitaire pour créer un système de test complet."""
return SystemFactory.create_test_system()
| 0 | 0.683155 | 1 | 0.683155 | game-dev | MEDIA | 0.412449 | game-dev | 0.699668 | 1 | 0.699668 |
LeoMinecraftModding/eternal-starlight | 4,185 | common/src/main/java/cn/leolezury/eternalstarlight/common/world/gen/biomesource/ESBiomeSource.java | package cn.leolezury.eternalstarlight.common.world.gen.biomesource;
import cn.leolezury.eternalstarlight.common.world.gen.system.BiomeData;
import cn.leolezury.eternalstarlight.common.world.gen.system.WorldArea;
import cn.leolezury.eternalstarlight.common.world.gen.system.WorldGenProvider;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import it.unimi.dsi.fastutil.longs.Long2ReferenceArrayMap;
import it.unimi.dsi.fastutil.longs.Long2ReferenceFunction;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.RegistryCodecs;
import net.minecraft.core.registries.Registries;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSource;
import net.minecraft.world.level.biome.Climate;
import java.util.stream.Stream;
public class ESBiomeSource extends BiomeSource implements IESBiomeSource {
public static final MapCodec<ESBiomeSource> CODEC = RecordCodecBuilder.mapCodec((instance) -> instance.group(
WorldGenProvider.CODEC.fieldOf("worldgen_provider").forGetter(o -> o.provider),
RegistryCodecs.homogeneousList(Registries.BIOME).fieldOf("biomes").forGetter(o -> o.biomeHolderSet)
).apply(instance, instance.stable(ESBiomeSource::new)));
private final WorldGenProvider provider;
private final HolderSet<Biome> biomeHolderSet;
public ESBiomeSource(WorldGenProvider provider, HolderSet<Biome> biomeHolderSet) {
this.provider = provider;
this.biomeHolderSet = biomeHolderSet;
}
public void setSeed(long seed) {
this.provider.setSeed(seed);
}
public void setRegistryAccess(RegistryAccess access) {
this.provider.setRegistryAccess(access);
}
public void setCacheSize(int size) {
this.provider.setCacheSize(size);
}
@Override
protected MapCodec<? extends BiomeSource> codec() {
return CODEC;
}
@Override
protected Stream<Holder<Biome>> collectPossibleBiomes() {
return biomeHolderSet.stream();
}
@Override
public BiomeData getBiomeData(int x, int z) {
return this.provider.getWorldArea(x, z).getBiomeData(x, z);
}
@Override
public int getBiome(int x, int z) {
return this.provider.getWorldArea(x, z).getBiome(x, z);
}
@Override
public int getHeight(int x, int z) {
return this.provider.getWorldArea(x, z).getHeight(x, z);
}
@Override
public Holder<Biome> getNoiseBiome(int x, int y, int z, Climate.Sampler sampler) {
return provider.getBiomeDataById(getBiome(x * 4, z * 4)).biome();
}
public Cached cache() {
return new Cached();
}
/**
* Only meant to be used for a single thread
*/
public class Cached extends BiomeSource implements IESBiomeSource {
private final Long2ReferenceArrayMap<WorldArea> cachedAreas = new Long2ReferenceArrayMap<>(); // using array map because it usually only contain one element
private final Long2ReferenceFunction<WorldArea> getWorldAreaUncachedFunction = this::getWorldAreaUncached;
private WorldArea getWorldArea(int x, int z) {
int areaX = x >> 10;
int areaZ = z >> 10;
long areaPos = ChunkPos.asLong(areaX, areaZ);
return this.cachedAreas.computeIfAbsent(areaPos, getWorldAreaUncachedFunction);
}
private WorldArea getWorldAreaUncached(long pos) {
int x = ChunkPos.getX(pos);
int z = ChunkPos.getZ(pos);
return ESBiomeSource.this.provider.getWorldArea(x << 10, z << 10);
}
@Override
protected MapCodec<? extends BiomeSource> codec() {
return ESBiomeSource.this.codec();
}
@Override
protected Stream<Holder<Biome>> collectPossibleBiomes() {
return ESBiomeSource.this.collectPossibleBiomes();
}
@Override
public Holder<Biome> getNoiseBiome(int x, int y, int z, Climate.Sampler sampler) {
return provider.getBiomeDataById(getBiome(x * 4, z * 4)).biome();
}
@Override
public BiomeData getBiomeData(int x, int z) {
return this.getWorldArea(x, z).getBiomeData(x, z);
}
@Override
public int getBiome(int x, int z) {
return this.getWorldArea(x, z).getBiome(x, z);
}
@Override
public int getHeight(int x, int z) {
return this.getWorldArea(x, z).getHeight(x, z);
}
}
}
| 0 | 0.718831 | 1 | 0.718831 | game-dev | MEDIA | 0.597985 | game-dev | 0.711847 | 1 | 0.711847 |
Nenkai/PDTools | 1,905 | PDTools.SaveFile/GT4/UserProfile/RaceRecordUnit.cs | using Syroot.BinaryData.Memory;
using System;
using System.Collections.Generic;
using System.Text;
using PDTools.Enums.PS2;
namespace PDTools.SaveFile.GT4.UserProfile;
public class RaceRecordUnit : IGameSerializeBase<RaceRecordUnit>
{
// 4 bits type
// 4 bits permanent result
// 4 bits unknown
// 4 bits current result
public ushort Bits { get; set; }
public byte ASpecScore { get; set; }
public EventType GetEventType()
{
return (EventType)(Bits & 0b1111); // 4 bits
}
public void SetEventType(EventType type)
{
Bits = (ushort)((Bits & 0xFFF0) | ((byte)type & 0b1111)); // 4 bits
}
public Result GetPermanentResult()
{
return (Result)((Bits >> 4) & 0b1111); // 4 bits
}
public Result GetUnknownLicenseOrMissionResult()
{
return (Result)((Bits >> 8) & 0b1111); // 4 bits
}
public Result GetCurrentResult()
{
return (Result)((Bits >> 12) & 0b1111); // 4 bits
}
public void SetPermanentResult(Result res)
{
Bits = (ushort)((Bits & 0xFF0F) | (ushort)(((byte)res & 0b1111) << 4)); // Permanent Result
}
public void SetLicenseOrMissionResult(Result res)
{
Bits = (ushort)((Bits & 0xF0FF) | (ushort)(((byte)res & 0b1111) << 8)); // Permanent Result
}
public void SetCurrentResult(Result res)
{
Bits = (ushort)((Bits & 0x0FFF) | (ushort)(((byte)res & 0b1111) << 12));
}
public void CopyTo(RaceRecordUnit dest)
{
dest.Bits = Bits;
dest.ASpecScore = ASpecScore;
}
public void Pack(GT4Save save, ref SpanWriter sw)
{
sw.WriteUInt16(Bits);
sw.WriteByte(ASpecScore);
sw.Position += 1;
}
public void Unpack(GT4Save save, ref SpanReader sr)
{
Bits = sr.ReadUInt16();
ASpecScore = sr.ReadByte();
sr.Position += 1;
}
}
| 0 | 0.919875 | 1 | 0.919875 | game-dev | MEDIA | 0.34413 | game-dev | 0.945075 | 1 | 0.945075 |
layabox/LayaAir | 17,634 | src/layaAir/laya/legacy/HierarchyParserV2.ts | import { Component } from "../components/Component";
import { Node } from "../display/Node";
import { Camera } from "../d3/core/Camera";
import { MeshSprite3D } from "../d3/core/MeshSprite3D";
import { RenderableSprite3D } from "../d3/core/RenderableSprite3D";
import { Scene3D } from "../d3/core/scene/Scene3D";
import { SkinnedMeshSprite3D } from "../d3/core/SkinnedMeshSprite3D";
import { Sprite3D } from "../d3/core/Sprite3D";
import { ClassUtils } from "../utils/ClassUtils";
import { SimpleSkinnedMeshSprite3D } from "../d3/core/SimpleSkinnedMeshSprite3D";
import { ILoadURL, Loader } from "../net/Loader";
import { URL } from "../net/URL";
import { ReflectionProbe } from "../d3/component/Volume/reflectionProbe/ReflectionProbe";
import { DirectionLightCom } from "../d3/core/light/DirectionLightCom";
import { PointLightCom } from "../d3/core/light/PointLightCom";
import { SpotLightCom } from "../d3/core/light/SpotLightCom";
import { TrailRenderer } from "../trail/trail3D/TrailRenderer";
import { PrefabImpl } from "../resource/PrefabImpl";
import { ShuriKenParticle3D } from "../particle/d3/ShuriKenParticle3D";
/**
* @internal
* @en `HierarchyParserV2` is a class used for parsing hierarchy data in a 3D scene.
* @zh `HierarchyParserV2` 类用于解析3D场景中的层级数据。
*/
export class HierarchyParserV2 {
/**
* @internal
* @param nodeData 创建数据
* @param spriteMap 精灵集合
* @param outBatchSprites 渲染精灵集合
*/
private static _createSprite3DInstance(nodeData: any, spriteMap: any, outBatchSprites: RenderableSprite3D[]): Node {
let node: Node;
let nodeToComp: Component;
switch (nodeData.type) {
case "Scene3D":
node = new Scene3D();
break;
case "Sprite3D":
node = new Sprite3D();
break;
case "MeshSprite3D":
node = new MeshSprite3D();
(outBatchSprites && nodeData.props.isStatic) && (outBatchSprites.push(<MeshSprite3D>node));
break;
case "SkinnedMeshSprite3D":
node = new SkinnedMeshSprite3D();
break;
case "SimpleSkinnedMeshSprite3D":
node = new SimpleSkinnedMeshSprite3D();
break;
case "ShuriKenParticle3D":
node = new ShuriKenParticle3D();
break;
case "Camera":
node = new Camera();
break;
case "ReflectionProbe":
node = new Sprite3D();
nodeToComp = node.addComponent(ReflectionProbe);
break;
case "DirectionLight":
node = new Sprite3D();
nodeToComp = node.addComponent(DirectionLightCom);
break;
case "PointLight":
node = new Sprite3D();
nodeToComp = node.addComponent(PointLightCom);
break;
case "SpotLight":
node = new Sprite3D();
nodeToComp = node.addComponent(SpotLightCom);
break;
case "TrailSprite3D":
node = new Sprite3D();
nodeToComp = node.addComponent(TrailRenderer);
break;
default:
throw new Error(`unknown node type ${nodeData.type}`);
}
let childData: any[] = nodeData.child;
if (childData) {
for (let i: number = 0, n: number = childData.length; i < n; i++) {
let child: any = HierarchyParserV2._createSprite3DInstance(childData[i], spriteMap, outBatchSprites)
node.addChild(child);
}
}
spriteMap[nodeData.instanceID] = nodeToComp || node;
return node;
}
/**
* @internal
* @param nodeData
* @param spriteMap
* @param interactMap
*/
private static _createComponentInstance(nodeData: any, spriteMap: any, interactMap: any): void {
let node: Node | Component = spriteMap[nodeData.instanceID];
node._parse(nodeData.props, spriteMap);
let childData: any[] = nodeData.child;
if (childData) {
for (let i: number = 0, n: number = childData.length; i < n; i++)
HierarchyParserV2._createComponentInstance(childData[i], spriteMap, interactMap)
}
let componentsData: any[] = nodeData.components;
if (componentsData) {
for (let j: number = 0, m: number = componentsData.length; j < m; j++) {
let data: any = componentsData[j];
let cls: any = ClassUtils.getClass(data.type);
if (cls) {
let component: Component = ((node instanceof Component) ? node.owner : node).addComponent(cls);
component._parse(data, interactMap);
} else {
console.warn(`unknown component type: ${data.type}.`);
}
}
}
}
/**
* @internal
*/
static _createNodeByJson02(nodeData: any, outBatchSprites: RenderableSprite3D[]): Node {
let spriteMap: any = {};
let interactMap: any = { component: [], data: [] };
let node: Node = HierarchyParserV2._createSprite3DInstance(nodeData, spriteMap, outBatchSprites);
HierarchyParserV2._createComponentInstance(nodeData, spriteMap, interactMap);
HierarchyParserV2._createInteractInstance(interactMap, spriteMap);
return node;
}
/**
* @internal
*/
static _createInteractInstance(interatMap: any, spriteMap: any) {
let components: Component[] = interatMap.component;
let data = interatMap.data;
for (let i = 0, n = components.length; i < n; i++) {
components[i]._parseInteractive(data[i], spriteMap);
}
}
/**
* @internal
* @en Parses the provided data into a 3D scene hierarchy.
* @param data The data object containing the hierarchy information and version.
* @returns A `Sprite3D` or `Scene3D` object representing the parsed hierarchy.
* @zh 将提供的数据解析为3D场景层级。
* @param data 包含层级信息和版本的数据对象。
* @returns 解析后的层级的Sprite3D或Scene3D对象
*/
static parse(data: any) {
let json: any = data.data;
let outBatchSprits: RenderableSprite3D[] = [];
let sprite: Sprite3D | Scene3D;
switch (data.version) {
case "LAYAHIERARCHY:02":
case "LAYASCENE3D:02":
sprite = (<Sprite3D | Scene3D>HierarchyParserV2._createNodeByJson02(json, outBatchSprits));
break;
default:
sprite = (<Sprite3D | Scene3D>HierarchyParserV2._createNodeByJson(json, outBatchSprits));
}
//StaticBatchManager.combine((sprite instanceof Sprite3D) ? sprite : null, outBatchSprits);
return sprite;
}
//--------------------------------------------------------------------------------------------------------------------------------
/**
* @internal
*/
static _createNodeByJson(nodeData: any, outBatchSprites: RenderableSprite3D[]): Node {//兼容代码
let node: Node;
let nodeToComp: Component;
switch (nodeData.type) {
case "Scene3D":
node = new Scene3D();
break;
case "Sprite3D":
node = new Sprite3D();
break;
case "MeshSprite3D":
node = new MeshSprite3D();
(outBatchSprites && nodeData.props.isStatic) && (outBatchSprites.push(<MeshSprite3D>node));
break;
case "SkinnedMeshSprite3D":
node = new SkinnedMeshSprite3D();
break;
case "ShuriKenParticle3D":
node = new ShuriKenParticle3D();
break;
case "Camera":
node = new Camera();
break;
case "DirectionLight":
node = new Sprite3D();
nodeToComp = node.addComponent(DirectionLightCom);
break;
case "PointLight":
node = new Sprite3D();
nodeToComp = node.addComponent(PointLightCom);
break;
case "SpotLight":
node = new Sprite3D();
nodeToComp = node.addComponent(SpotLightCom);
break;
case "TrailSprite3D":
node = new Sprite3D();
nodeToComp = node.addComponent(TrailRenderer);
break;
default:
throw new Error(`unknown node type ${nodeData.type}`);
}
let childData: any[] = nodeData.child;
if (childData) {
for (let i: number = 0, n: number = childData.length; i < n; i++) {
let child: any = HierarchyParserV2._createNodeByJson(childData[i], outBatchSprites)
node.addChild(child);
}
}
let componentsData: any[] = nodeData.components;
if (componentsData) {
for (let j: number = 0, m: number = componentsData.length; j < m; j++) {
let data: any = componentsData[j];
let clas: any = ClassUtils.getClass(data.type);
if (clas) {
let component: Component = node.addComponent(clas);
component._parse(data);
} else {
console.warn(`unknown component type: ${data.type}.`);
}
}
}
if (nodeToComp)
nodeToComp._parse(nodeData.props);
else
node._parse(nodeData.props, null);
return node;
}
/**
* @en Collects all the resource links required for loading from the given data object.
* @param data The data object containing hierarchy and resource information.
* @param basePath The base path to resolve relative URLs.
* @returns An array of resource URLs or `ILoadURL` objects.
* @zh 从给定的数据对象中收集所有需要加载的资源链接。
* @param data 包含层级和资源信息的数据对象。
* @param basePath 用于解析相对URL的基路径。
* @returns 资源URL或 `ILoadURL` 对象的数组。
*/
public static collectResourceLinks(data: any, basePath: string): (string | ILoadURL)[] {
let test: Record<string, string> = {};
let innerUrls: ILoadURL[] = [];
function addInnerUrl(url: string, type: string, constructParams?: any, propertyParams?: any) {
let url2 = test[url];
if (url2 === undefined) {
url2 = URL.join(basePath, url);
innerUrls.push({ url: url2, type: type, constructParams: constructParams, propertyParams: propertyParams });
test[url] = url2;
}
return url2;
}
function check(nodeData: any) {
let props: any = nodeData.props;
switch (nodeData.type) {
case "Scene3D":
let lightmaps: any[] = props.lightmaps;
if (lightmaps) {
for (let i = 0, n = lightmaps.length; i < n; i++) {
let lightMap: any = lightmaps[i];
if (lightMap.path) {
lightMap.path = addInnerUrl(lightMap.path, Loader.TEXTURE2D, lightMap.constructParams, lightMap.propertyParams);
}
else {
let lightmapColorData: any = lightMap.color;
lightmapColorData.path = addInnerUrl(lightmapColorData.path, Loader.TEXTURE2D, lightmapColorData.constructParams, lightmapColorData.propertyParams);
let lightmapDirectionData: any = lightMap.direction;
if (lightmapDirectionData)
lightmapDirectionData.path = addInnerUrl(lightmapDirectionData.path, Loader.TEXTURE2D, lightmapDirectionData.constructParams, lightmapDirectionData.propertyParams);
}
}
}
//兼容
let reflectionTextureData: string = props.reflectionTexture;
(reflectionTextureData) && (props.reflection = addInnerUrl(reflectionTextureData, Loader.TEXTURECUBE));
let reflectionData: string = props.reflection;
(reflectionData) && (props.reflection = addInnerUrl(reflectionData, Loader.TEXTURECUBE));
if (props.sky) {
let skyboxMaterial: any = props.sky.material;
(skyboxMaterial) && (skyboxMaterial.path = addInnerUrl(skyboxMaterial.path, Loader.MATERIAL));
}
break;
case "Camera":
let skyboxMatData: any = props.skyboxMaterial;
(skyboxMatData) && (skyboxMatData.path = addInnerUrl(skyboxMatData.path, Loader.MATERIAL));
break;
case "TrailSprite3D":
case "MeshSprite3D":
case "SkinnedMeshSprite3D":
case "SimpleSkinnedMeshSprite3D":
let meshPath: string = props.meshPath;
(meshPath) && (props.meshPath = addInnerUrl(meshPath, Loader.MESH));
let materials: any[] = props.materials;
if (materials)
for (let i = 0, n = materials.length; i < n; i++)
materials[i].path = addInnerUrl(materials[i].path, Loader.MATERIAL);
if (nodeData.type == "SimpleSkinnedMeshSprite3D")
if (props.animatorTexture)
props.animatorTexture = addInnerUrl(props.animatorTexture, Loader.TEXTURE2D)
break;
case "ShuriKenParticle3D":
if (props.main) {
let resources: any = props.renderer.resources;
let mesh: string = resources.mesh;
let material: string = resources.material;
(mesh) && (resources.mesh = addInnerUrl(mesh, Loader.MESH));
(material) && (resources.material = addInnerUrl(material, Loader.MATERIAL));
}
else {//兼容代码
let parMeshPath: string = props.meshPath;
(parMeshPath) && (props.meshPath = addInnerUrl(parMeshPath, Loader.MESH));
props.material.path = addInnerUrl(props.material.path, Loader.MATERIAL);
}
break;
case "Terrain":
addInnerUrl(props.dataPath, Loader.TERRAINRES);
break;
case "ReflectionProbe":
let reflection = props.reflection;
(reflection) && (props.reflection = addInnerUrl(reflection, Loader.TEXTURECUBE));
break;
}
let components: any[] = nodeData.components;
if (components) {
for (let k: number = 0, p: number = components.length; k < p; k++) {
let component: any = components[k];
switch (component.type) {
case "Animator":
// let avatarData: any = component.avatar;
// (avatarData) && (avatarData.path = addInnerUrl(avatarData.path, Loader.AVATAR));
let clipPaths: string[] = component.clipPaths;
if (!clipPaths) {
let layersData: any[] = component.layers;
for (let i = 0; i < layersData.length; i++) {
let states: any[] = layersData[i].states;
for (let j: number = 0, m: number = states.length; j < m; j++) {
let clipPath: string = states[j].clipPath;
(clipPath) && (states[j].clipPath = addInnerUrl(clipPath, Loader.ANIMATIONCLIP));
}
}
} else {
for (let i = 0, n = clipPaths.length; i < n; i++)
clipPaths[i] = addInnerUrl(clipPaths[i], Loader.ANIMATIONCLIP);
}
break;
case "PhysicsCollider":
case "Rigidbody3D":
case "CharacterController":
let shapes: any[] = component.shapes;
for (let i = 0; i < shapes.length; i++) {
let shape: any = shapes[i];
if (shape.type === "MeshColliderShape") {
let mesh: string = shape.mesh;
(mesh) && (shape.mesh = addInnerUrl(mesh, Loader.MESH));
}
}
break;
}
}
}
let children: any[] = nodeData.child;
if (!children) return;
for (let i = 0, n = children.length; i < n; i++)
check(children[i]);
}
check(data.data);
return innerUrls;
}
}
PrefabImpl.v2 = HierarchyParserV2; | 0 | 0.902803 | 1 | 0.902803 | game-dev | MEDIA | 0.70352 | game-dev,graphics-rendering | 0.930011 | 1 | 0.930011 |
MTrop/DoomTools | 4,390 | src/main/java/net/mtrop/doom/tools/gui/managers/DoomToolsGUIPreWarmer.java | /*******************************************************************************
* Copyright (c) 2020-2024 Matt Tropiano
* This program and the accompanying materials are made available under
* the terms of the MIT License, which accompanies this distribution.
******************************************************************************/
package net.mtrop.doom.tools.gui.managers;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import net.mtrop.doom.tools.struct.LoggingFactory.Logger;
import net.mtrop.doom.tools.gui.swing.panels.EditorMultiFilePanel;
import net.mtrop.doom.tools.struct.SingletonProvider;
/**
* DoomTools GUI pre-warming singleton.
* @author Matthew Tropiano
*/
public final class DoomToolsGUIPreWarmer
{
/** Logger. */
private static final Logger LOG = DoomToolsLogger.getLogger(DoomToolsGUIPreWarmer.class);
/** The instance encapsulator. */
private static final SingletonProvider<DoomToolsGUIPreWarmer> INSTANCE = new SingletonProvider<>(() -> new DoomToolsGUIPreWarmer());
/**
* @return the singleton instance of this settings object.
*/
public static DoomToolsGUIPreWarmer get()
{
return INSTANCE.get();
}
/* ==================================================================== */
private DoomToolsGUIPreWarmer()
{
preWarmCompletionProviders();
preWarmCommonImages();
preWarmCommonIcons();
preWarmCommonComponents();
}
/**
* Pre-loads all of the completion providers into memory in a separate thread.
* <p>
* The completion providers are not instantiated until they are needed for a
* particular style, but depending on how complex they are, this will cause a very noticeable
* hitch on first use. Calling this function will start pre-loading them in a separate thread
* so that they are ready to be used instantly.
*/
private void preWarmCompletionProviders()
{
DoomToolsTaskManager tasks = DoomToolsTaskManager.get();
LOG.info("Pre-warming completion providers...");
tasks.spawn(() -> {
DoomToolsEditorProvider editorProvider = DoomToolsEditorProvider.get();
editorProvider.getProviderByStyle(DoomToolsEditorProvider.SYNTAX_STYLE_DECOHACK);
editorProvider.getProviderByStyle(DoomToolsEditorProvider.SYNTAX_STYLE_DEFSWANI);
editorProvider.getProviderByStyle(DoomToolsEditorProvider.SYNTAX_STYLE_DEUTEX);
editorProvider.getProviderByStyle(DoomToolsEditorProvider.SYNTAX_STYLE_DOOMMAKE);
editorProvider.getProviderByStyle(DoomToolsEditorProvider.SYNTAX_STYLE_ROOKSCRIPT);
editorProvider.getProviderByStyle(DoomToolsEditorProvider.SYNTAX_STYLE_WADMERGE);
editorProvider.getProviderByStyle(DoomToolsEditorProvider.SYNTAX_STYLE_WADSCRIPT);
LOG.info("Completion providers pre-warm finished.");
});
}
/**
* Pre-loads common icons.
*/
private void preWarmCommonIcons()
{
DoomToolsTaskManager tasks = DoomToolsTaskManager.get();
LOG.info("Pre-warming common icons...");
tasks.spawn(() -> {
DoomToolsIconManager iconManager = DoomToolsIconManager.get();
iconManager.getImage("activity.gif");
LOG.info("Icon pre-warm finished.");
});
}
/**
* Pre-loads common non-animated images.
*/
private void preWarmCommonImages()
{
DoomToolsTaskManager tasks = DoomToolsTaskManager.get();
LOG.info("Pre-warming common images...");
tasks.spawn(() -> {
DoomToolsImageManager imageManager = DoomToolsImageManager.get();
imageManager.getImage("doomtools-logo-16.png");
imageManager.getImage("doomtools-logo-32.png");
imageManager.getImage("doomtools-logo-48.png");
imageManager.getImage("doomtools-logo-64.png");
imageManager.getImage("doomtools-logo-96.png");
imageManager.getImage("doomtools-logo-128.png");
imageManager.getImage("script.png");
imageManager.getImage("script-unsaved.png");
imageManager.getImage("close-icon.png");
imageManager.getImage("success.png");
imageManager.getImage("error.png");
LOG.info("Image pre-warm finished.");
});
}
/**
* Pre-loads common components.
*/
private void preWarmCommonComponents()
{
DoomToolsTaskManager tasks = DoomToolsTaskManager.get();
LOG.info("Pre-warming common components...");
tasks.spawn(() -> {
DoomToolsEditorProvider editorProvider = DoomToolsEditorProvider.get();
editorProvider.initCustomLanguages();
new EditorMultiFilePanel();
new RSyntaxTextArea();
LOG.info("Component pre-warm finished.");
});
}
}
| 0 | 0.757191 | 1 | 0.757191 | game-dev | MEDIA | 0.591178 | game-dev,desktop-app | 0.68682 | 1 | 0.68682 |
lordofduct/spacepuppy-unity-framework | 1,475 | SpacepuppyBaseEditor/Scenario/t_OnNotificationTriggerInspector.cs | using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
using com.spacepuppy;
using com.spacepuppy.Scenario;
namespace com.spacepuppyeditor.Scenario
{
[CustomEditor(typeof(t_OnNotificationTrigger), true)]
public class t_OnNotificationTriggerInspector : SPEditor
{
public const string PROP_NOTIFTYPE = "_notificationType";
public const string PROP_USEGLOBAL = "_useGlobal";
public const string PROP_TARGET = "_targetGameObject";
protected override void OnSPInspectorGUI()
{
this.serializedObject.Update();
this.DrawPropertyField(EditorHelper.PROP_SCRIPT);
var cache = SPGUI.DisableIfPlaying();
this.DrawPropertyField(PROP_NOTIFTYPE);
var useGlobalProp = this.serializedObject.FindProperty(PROP_USEGLOBAL);
var targetProp = this.serializedObject.FindProperty(PROP_TARGET);
SPEditorGUILayout.PropertyField(useGlobalProp);
if(useGlobalProp.boolValue)
{
targetProp.objectReferenceValue = null;
}
else
{
SPEditorGUILayout.PropertyField(targetProp);
}
cache.Reset();
this.DrawDefaultInspectorExcept(EditorHelper.PROP_SCRIPT, PROP_NOTIFTYPE, PROP_USEGLOBAL, PROP_TARGET);
this.serializedObject.ApplyModifiedProperties();
}
}
}
| 0 | 0.599272 | 1 | 0.599272 | game-dev | MEDIA | 0.91522 | game-dev | 0.73242 | 1 | 0.73242 |
ImLegiitXD/Dream-Advanced | 1,768 | dll/back/1.12/net/minecraft/client/particle/ParticleSuspend.java | package net.minecraft.client.particle;
import net.minecraft.block.material.Material;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class ParticleSuspend extends Particle
{
protected ParticleSuspend(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn)
{
super(worldIn, xCoordIn, yCoordIn - 0.125D, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn);
this.particleRed = 0.4F;
this.particleGreen = 0.4F;
this.particleBlue = 0.7F;
this.setParticleTextureIndex(0);
this.setSize(0.01F, 0.01F);
this.particleScale *= this.rand.nextFloat() * 0.6F + 0.2F;
this.motionX = xSpeedIn * 0.0D;
this.motionY = ySpeedIn * 0.0D;
this.motionZ = zSpeedIn * 0.0D;
this.particleMaxAge = (int)(16.0D / (Math.random() * 0.8D + 0.2D));
}
public void onUpdate()
{
this.prevPosX = this.posX;
this.prevPosY = this.posY;
this.prevPosZ = this.posZ;
this.move(this.motionX, this.motionY, this.motionZ);
if (this.world.getBlockState(new BlockPos(this.posX, this.posY, this.posZ)).getMaterial() != Material.WATER)
{
this.setExpired();
}
if (this.particleMaxAge-- <= 0)
{
this.setExpired();
}
}
public static class Factory implements IParticleFactory
{
public Particle createParticle(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_)
{
return new ParticleSuspend(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn);
}
}
}
| 0 | 0.557439 | 1 | 0.557439 | game-dev | MEDIA | 0.735477 | game-dev,graphics-rendering | 0.922654 | 1 | 0.922654 |
Faboslav/friends-and-foes | 2,115 | neoforge/src/main/java/com/faboslav/friendsandfoes/neoforge/world/processor/IllusionerShackItemFrameProcessor.java | package com.faboslav.friendsandfoes.neoforge.world.processor;
import com.faboslav.friendsandfoes.common.util.world.processor.IllusionerShackItemFrameProcessorHelper;
import com.faboslav.friendsandfoes.neoforge.platform.ProcessorTypes;
import com.mojang.serialization.MapCodec;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessor;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorType;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate;
import org.jetbrains.annotations.Nullable;
/**
* Inspired by use in Better Strongholds mod
*
* @author YUNGNICKYOUNG
* <a href="https://github.com/YUNG-GANG/YUNGs-Better-Strongholds">https://github.com/YUNG-GANG/YUNGs-Better-Strongholds</a>
*/
public final class IllusionerShackItemFrameProcessor extends StructureProcessor
{
public static final MapCodec<IllusionerShackItemFrameProcessor> CODEC = MapCodec.unit(IllusionerShackItemFrameProcessor::new);
private IllusionerShackItemFrameProcessor() {
}
@Override
public StructureTemplate.StructureEntityInfo processEntity(
LevelReader world,
BlockPos seedPos,
StructureTemplate.StructureEntityInfo rawEntityInfo,
StructureTemplate.StructureEntityInfo entityInfo,
StructurePlaceSettings placementSettings,
StructureTemplate template
) {
return IllusionerShackItemFrameProcessorHelper.processEntity(
entityInfo,
placementSettings
);
}
@Nullable
@Override
public StructureTemplate.StructureBlockInfo processBlock(
LevelReader world,
BlockPos pos,
BlockPos pivot,
StructureTemplate.StructureBlockInfo localEntityInfo,
StructureTemplate.StructureBlockInfo globalEntityInfo,
StructurePlaceSettings data
) {
return globalEntityInfo;
}
@Override
protected StructureProcessorType<?> getType() {
// CHECK if i really need this
return ProcessorTypes.ILLUSIONER_SHACK_ITEM_FRAME_PROCESSOR.get();
}
} | 0 | 0.694575 | 1 | 0.694575 | game-dev | MEDIA | 0.981132 | game-dev | 0.63177 | 1 | 0.63177 |
QBTreyyy/ps-dispatch | 29,174 | client/cl_events.lua | local WeaponTable = {
[584646201] = "CLASS 2: AP-Pistol",
[453432689] = "CLASS 1: Pistol",
[3219281620] = "CLASS 1: Pistol MK2",
[1593441988] = "CLASS 1: Combat Pistol",
[-1716589765] = "CLASS 1: Heavy Pistol",
[-1076751822] = "CLASS 1: SNS-Pistol",
[-771403250] = "CLASS 2: Desert Eagle",
[137902532] = "CLASS 2: Vintage Pistol",
[-598887786] = "CLASS 2: Marksman Pistol",
[-1045183535] = "CLASS 2: Revolver",
[911657153] = "Taser",
[324215364] = "CLASS 2: Micro-SMG",
[-619010992] = "CLASS 2: Machine-Pistol",
[736523883] = "CLASS 2: SMG",
[2024373456] = "CLASS 2: SMG MK2",
[-270015777] = "CLASS 2: Assault SMG",
[171789620] = "CLASS 2: Combat PDW",
[-1660422300] = "CLASS 4: Combat MG",
[3686625920] = "CLASS 4: Combat MG MK2",
[1627465347] = "CLASS 4: Gusenberg",
[-1121678507] = "CLASS 2: Mini SMG",
[-1074790547] = "CLASS 3: Assaultrifle",
[961495388] = "CLASS 3: Assaultrifle MK2",
[-2084633992] = "CLASS 3: Carbinerifle",
[4208062921] = "CLASS 3: Carbinerifle MK2",
[-1357824103] = "CLASS 3: Advancedrifle",
[-1063057011] = "CLASS 3: Specialcarbine",
[2132975508] = "CLASS 3: Bulluprifle",
[1649403952] = "CLASS 3: Compactrifle",
[100416529] = "CLASS 4: Sniperrifle",
[205991906] = "CLASS 4: Heavy Sniper",
[177293209] = "CLASS 4: Heavy Sniper MK2",
[-952879014] = "CLASS 4: Marksmanrifle",
[487013001] = "CLASS 2: Pumpshotgun",
[2017895192] = "CLASS 2: Sawnoff Shotgun",
[-1654528753] = "CLASS 3: Bullupshotgun",
[-494615257] = "CLASS 3: Assaultshotgun",
[-1466123874] = "CLASS 3: Musket",
[984333226] = "CLASS 3: Heavyshotgun",
[-275439685] = "CLASS 2: Doublebarrel Shotgun",
[317205821] = "CLASS 2: Autoshotgun",
[-1568386805] = "CLASS 5: GRENADE LAUNCHER",
[-1312131151] = "CLASS 5: RPG",
[125959754] = "CLASS 5: Compactlauncher"
}
local function VehicleTheft(vehicle)
local vehdata = vehicleData(vehicle)
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local heading = getCardinalDirectionFromHeading()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "vehicletheft", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-35",
firstStreet = locationInfo,
model = vehdata.name, -- vehicle name
plate = vehdata.plate, -- vehicle plate
priority = 2,
firstColor = vehdata.colour, -- vehicle color
heading = heading,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('vehicletheft'),
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"}
})
end
exports('VehicleTheft', VehicleTheft)
local function VehicleShooting(vehdata)
local vehicle = QBCore.Functions.GetClosestVehicle()
local vehdata = vehicleData(vehicle)
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local heading = getCardinalDirectionFromHeading()
local gender = GetPedGender()
local doorCount = 0
local PlayerPed = PlayerPedId()
local CurrentWeapon = GetSelectedPedWeapon(PlayerPed)
local weapon = WeaponTable[CurrentWeapon] or "UNKNOWN"
if GetEntityBoneIndexByName(vehicle, 'door_pside_f') ~= -1 then doorCount = doorCount + 1 end
if GetEntityBoneIndexByName(vehicle, 'door_pside_r') ~= -1 then doorCount = doorCount + 1 end
if GetEntityBoneIndexByName(vehicle, 'door_dside_f') ~= -1 then doorCount = doorCount + 1 end
if GetEntityBoneIndexByName(vehicle, 'door_dside_r') ~= -1 then doorCount = doorCount + 1 end
if doorCount == 2 then doorCount = "Two-Door" elseif doorCount == 3 then doorCount = "Three-Door" elseif doorCount == 4 then doorCount = "Four-Door" else doorCount = "UNKNOWN" end
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "vehicleshots", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-60",
firstStreet = locationInfo,
model = vehdata.name,
plate = vehdata.plate,
gender = gender,
weapon = weapon,
doorCount = doorCount,
priority = 2,
firstColor = vehdata.colour,
heading = heading,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('vehicleshots'),
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"}
})
end
exports('VehicleShooting', VehicleShooting)
local function Shooting()
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
local PlayerPed = PlayerPedId()
local CurrentWeapon = GetSelectedPedWeapon(PlayerPed)
local speed = math.floor(GetEntitySpeed(vehicle) * 2.236936) .. " MPH" -- * 3.6 = KMH / * 2.236936 = MPH
local weapon = WeaponTable[CurrentWeapon] or "UNKNOWN"
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "shooting", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-11",
firstStreet = locationInfo,
gender = gender,
weapon = weapon,
model = nil,
plate = nil,
priority = 2,
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('shooting'),
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"}
})
end
exports('Shooting', Shooting)
local function SpeedingVehicle(vehdata)
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local heading = getCardinalDirectionFromHeading()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "speeding", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-11",
firstStreet = locationInfo,
model = vehdata.name,
plate = vehdata.plate,
priority = 2,
firstColor = vehdata.colour,
heading = heading,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('speeding'),
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"}
})
end
exports('SpeedingVehicle', SpeedingVehicle)
local function Fight()
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "fight", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-10",
firstStreet = locationInfo,
gender = gender,
model = nil,
plate = nil,
priority = 2,
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('melee'),
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"}
})
end
exports('Fight', Fight)
local function InjuriedPerson()
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "InjuriedPerson", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-69",
firstStreet = locationInfo,
gender = gender,
model = nil,
plate = nil,
priority = 2, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('persondown'), -- message
job = {"leo", "police", "bcso","ems","ambulance", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('InjuriedPerson', InjuriedPerson)
local function DeceasedPerson()
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "DeceasedPerson", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-69",
firstStreet = locationInfo,
gender = gender,
model = nil,
plate = nil,
priority = 2, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = "Civilian Bled Out", -- message
job = {"leo", "police", "bcso","ems","ambulance", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('DeceasedPerson', DeceasedPerson)
local function StoreRobbery(camId)
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "storerobbery", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-90",
firstStreet = locationInfo,
gender = gender,
camId = camId,
model = nil,
plate = nil,
priority = 2, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('storerobbery'), -- message
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('StoreRobbery', StoreRobbery)
local function FleecaBankRobbery(camId)
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "bankrobbery", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-90",
firstStreet = locationInfo,
gender = gender,
camId = camId,
model = nil,
plate = nil,
priority = 2, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('fleecabank'), -- message
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('FleecaBankRobbery', FleecaBankRobbery)
local function PaletoBankRobbery(camId)
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "paletobankrobbery", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-90",
firstStreet = locationInfo,
gender = gender,
camId = camId,
model = nil,
plate = nil,
priority = 2, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('paletobank'), -- message
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('PaletoBankRobbery', PaletoBankRobbery)
local function PacificBankRobbery(camId)
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "pacificbankrobbery", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-90",
firstStreet = locationInfo,
gender = gender,
camId = camId,
model = nil,
plate = nil,
priority = 2, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('pacificbank'), -- message
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('PacificBankRobbery', PacificBankRobbery)
local function PrisonBreak()
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "prisonbreak", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-90",
firstStreet = locationInfo,
gender = gender,
model = nil,
plate = nil,
priority = 2, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('prisonbreak'), -- message
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('PrisonBreak', PrisonBreak)
local function VangelicoRobbery(camId)
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
PlaySound(-1, "Lose_1st", "GTAO_FM_Events_Soundset", 0, 0, 1)
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "vangelicorobbery", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-90",
firstStreet = locationInfo,
gender = gender,
camId = camId,
model = nil,
plate = nil,
priority = 2, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('vangelico'), -- message
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('VangelicoRobbery', VangelicoRobbery)
local function HouseRobbery()
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "houserobbery", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-90",
firstStreet = locationInfo,
gender = gender,
model = nil,
plate = nil,
priority = 2, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('houserobbery'), -- message
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('HouseRobbery', HouseRobbery)
local function YachtHeist()
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "yachtheist", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-65",
firstStreet = locationInfo,
gender = gender,
model = nil,
plate = nil,
priority = 2, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('yachtheist'), -- message
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('YachtHeist', YachtHeist)
local function DrugSale()
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "suspicioushandoff", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-13",
firstStreet = locationInfo,
gender = gender,
model = nil,
plate = nil,
priority = 2, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('drugsell'), -- message
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('DrugSale', DrugSale)
-- for rcore_gangs, haven't tested server side exports so made this instead. Remove if you do not need :)
RegisterNetEvent('ps-dispatch:client:drugsale', function()
DrugSale()
end)
local function CarJacking(vehicle)
local vehdata = vehicleData(vehicle)
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local heading = getCardinalDirectionFromHeading()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "carjack", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-35",
firstStreet = locationInfo,
model = vehdata.name, -- vehicle name
plate = vehdata.plate, -- vehicle plate
priority = 2,
firstColor = vehdata.colour, -- vehicle color
heading = heading,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('carjacking'),
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('CarJacking', CarJacking)
local function OfficerDown()
local plyData = QBCore.Functions.GetPlayerData()
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local callsign = QBCore.Functions.GetPlayerData().metadata["callsign"]
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "officerdown", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-99",
firstStreet = locationInfo,
name = "COP - " .. plyData.charinfo.firstname:sub(1, 1):upper() .. plyData.charinfo.firstname:sub(2) .. " " .. plyData.charinfo.lastname:sub(1, 1):upper() .. plyData.charinfo.lastname:sub(2),
model = nil,
plate = nil,
callsign = callsign,
priority = 1, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('officerdown'), -- message
job = {"leo", "police", "bcso","ems","ambulance", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('OfficerDown', OfficerDown)
RegisterNetEvent("ps-dispatch:client:officerdown", function ()
OfficerDown()
end)
local function Reinforcement()
local plyData = QBCore.Functions.GetPlayerData()
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local callsign = QBCore.Functions.GetPlayerData().metadata["callsign"]
print('Player:' .. plyData.charinfo.firstname)
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "reinforcement", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-1",
firstStreet = locationInfo,
name = "COP - " .. plyData.charinfo.firstname:sub(1, 1):upper() .. plyData.charinfo.firstname:sub(2) .. " " .. plyData.charinfo.lastname:sub(1, 1):upper() .. plyData.charinfo.lastname:sub(2),
model = nil,
plate = nil,
callsign = callsign,
priority = 1, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('reinforcement'), -- message
job = {"leo", "police", "bcso","ems","ambulance", "sdso","sasp","saspr","pbso"}
-- job = { "police", "bcso", "lspd", "sast", "sasp", "doc", "sapr", "pa", "sdso", "pbso", "bcso", "lspd", "sast", "sasp", "doc", "sapr", "pa", "sdso", "pbso" } -- jobs that will get the alerts
})
end
exports('Reinforcement', Reinforcement)
RegisterNetEvent("ps-dispatch:client:reinforcement", function ()
Reinforcement()
end)
local function EmsDown()
local plyData = QBCore.Functions.GetPlayerData()
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local callsign = QBCore.Functions.GetPlayerData().metadata["callsign"]
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "emsdown", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-99",
firstStreet = locationInfo,
name = "EMS - " .. plyData.charinfo.firstname:sub(1, 1):upper() .. plyData.charinfo.firstname:sub(2) .. " " .. plyData.charinfo.lastname:sub(1, 1):upper() .. plyData.charinfo.lastname:sub(2),
model = nil,
plate = nil,
callsign = callsign,
priority = 1, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('emsdown'), -- message
job = {"leo", "police", "bcso","ems","ambulance", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('EmsDown', EmsDown)
RegisterNetEvent("ps-dispatch:client:emsdown", function ()
EmsDown()
end)
local function Explosion()
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "explosion", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-80",
firstStreet = locationInfo,
gender = nil,
model = nil,
plate = nil,
priority = 2, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = "Explosion Reported", -- message
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('Explosion', Explosion)
local function SuspiciousActivity()
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "susactivity", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-66",
firstStreet = locationInfo,
gender = gender,
model = nil,
plate = nil,
priority = 2, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('susactivity'), -- message
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('SuspiciousActivity', SuspiciousActivity)
local function Hunting()
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
local PlayerPed = PlayerPedId()
local CurrentWeapon = GetSelectedPedWeapon(PlayerPed)
local speed = math.floor(GetEntitySpeed(vehicle) * 2.236936) .. " MPH" -- * 3.6 = KMH / * 2.236936 = MPH
local weapon = WeaponTable[CurrentWeapon] or "UNKNOWN"
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "hunting", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-13",
firstStreet = locationInfo,
gender = gender,
weapon = weapon,
model = nil,
plate = nil,
priority = 2,
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('hunting'),
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"} -- type or jobs that will get the alerts
})
end
exports('Hunting', Hunting)
local function CustomAlert(data)
local coords = data.coords or vec3(0.0, 0.0, 0.0)
local gender = GetPedGender()
if not data.gender then gender = nil end
local job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"}
if data.job then job = data.job end
local locationInfo = getStreetandZone(coords)
TriggerServerEvent("dispatch:server:notify", {
dispatchCode = data.dispatchCode or "NONE",
firstStreet = locationInfo,
gender = gender,
model = data.model or nil,
plate = data.plate or nil,
priority = data.priority or 2, -- priority
firstColor = data.firstColor or nil,
camId = data.camId or nil,
callsign = data.callsign or nil,
name = data.name or nil,
doorCount = data.doorCount or nil,
heading = data.heading or nil,
automaticGunfire = data.automaticGunfire or false,
origin = {
x = coords.x,
y = coords.y,
z = coords.z
},
dispatchMessage = data.message or "",
job = job,
alert = {
displayCode = data.dispatchCode or "NONE",
description = data.description or "",
radius = data.radius or 0,
recipientList = job,
blipSprite = data.sprite or 1,
blipColour = data.color or 1,
blipScale = data.scale or 0.5,
blipLength = data.length or 2,
sound = data.sound or "Lose_1st",
sound2 = data.sound2 or "GTAO_FM_Events_Soundset",
offset = data.offset or "false",
blipflash = data.flash or "false"
}
})
end
exports('CustomAlert', CustomAlert)
-- ATM Robbery
local function ATMRobbery(camId)
local currentPos = GetEntityCoords(PlayerPedId())
local locationInfo = getStreetandZone(currentPos)
local gender = GetPedGender()
TriggerServerEvent("dispatch:server:notify", {
dispatchcodename = "atmrobbery", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
dispatchCode = "10-90",
firstStreet = locationInfo,
gender = gender,
camId = camId,
model = nil,
plate = nil,
priority = 2, -- priority
firstColor = nil,
automaticGunfire = false,
origin = {
x = currentPos.x,
y = currentPos.y,
z = currentPos.z
},
dispatchMessage = _U('atmrobbery'), -- message
job = {"leo", "police", "bcso", "sdso","sasp","saspr","pbso"} -- jobs that will get the alerts
})
end
exports('ATMRobbery', ATMRobbery)
| 0 | 0.780624 | 1 | 0.780624 | game-dev | MEDIA | 0.84946 | game-dev | 0.761972 | 1 | 0.761972 |
DoqueDB/doquedb | 5,167 | sydney/Kernel/Common/ClassID.cpp | // -*-Mode: C++; tab-width: 4; c-basic-offset: 4;-*-
// vi:set ts=4 sw=4:
//
// ClassID.cpp -- クラス ID 関連の関数定義
//
// Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2023 Ricoh Company, Ltd.
//
// 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.
//
namespace {
const char moduleName[] = "Common";
const char srcFile[] = __FILE__;
}
#include "SyDefault.h"
#include "SyReinterpretCast.h"
#include "Common/ClassID.h"
#include "Common/Status.h"
#include "Common/IntegerData.h"
#include "Common/UnsignedIntegerData.h"
#include "Common/Integer64Data.h"
#include "Common/UnsignedInteger64Data.h"
#include "Common/FloatData.h"
#include "Common/DoubleData.h"
#include "Common/DecimalData.h"
#include "Common/StringData.h"
#include "Common/DateData.h"
#include "Common/DateTimeData.h"
#include "Common/IntegerArrayData.h"
#include "Common/UnsignedIntegerArrayData.h"
#include "Common/StringArrayData.h"
#include "Common/DataArrayData.h"
#include "Common/BinaryData.h"
#include "Common/NullData.h"
#include "Common/DefaultData.h"
#include "Common/ExceptionObject.h"
#include "Common/Parameter.h"
#include "Common/BitSet.h"
#include "Common/CompressedStringData.h"
#include "Common/CompressedBinaryData.h"
#ifdef OBSOLETE
#include "Common/CompressedStreamStringData.h"
#include "Common/CompressedStreamBinaryData.h"
#endif
#include "Common/ObjectIDData.h"
#include "Common/Request.h"
#include "Common/LanguageData.h"
#include "Common/SQLData.h"
#include "Common/ColumnMetaData.h"
#include "Common/ResultSetMetaData.h"
#include "Common/WordData.h"
#include "Common/ErrorLevel.h"
_TRMEISTER_USING
_TRMEISTER_COMMON_USING
// FUNCTION
// Common::getClassInstance -- シリアル化可能クラスのインスタンスを確保する
//
// NOTES
//
// ARUMENTS
// int iClassID_
// インスタンスを確保するシリアル化可能クラスのクラス ID
//
// RETURN
// 0 以外の値
// 得られたインスタンスを格納する領域の先頭アドレス
// 0
// 存在しないクラス ID が指定された
//
// EXCEPTIONS
Common::Externalizable*
Common::getClassInstance(int iClassID_)
{
Externalizable* pObject = 0;
switch (iClassID_)
{
case ClassID::StatusClass:
pObject = new Status;
break;
case ClassID::IntegerDataClass:
pObject = new IntegerData;
break;
case ClassID::UnsignedIntegerDataClass:
pObject = new UnsignedIntegerData;
break;
case ClassID::Integer64DataClass:
pObject = new Integer64Data;
break;
case ClassID::UnsignedInteger64DataClass:
pObject = new UnsignedInteger64Data;
break;
case ClassID::FloatDataClass:
pObject = new FloatData;
break;
case ClassID::DoubleDataClass:
pObject = new DoubleData;
break;
case ClassID::DecimalDataClass:
pObject = new DecimalData;
break;
case ClassID::StringDataClass:
pObject = new StringData;
break;
case ClassID::DateDataClass:
pObject = new DateData;
break;
case ClassID::DateTimeDataClass:
pObject = new DateTimeData;
break;
case ClassID::IntegerArrayDataClass:
pObject = new IntegerArrayData;
break;
case ClassID::UnsignedIntegerArrayDataClass:
pObject = new UnsignedIntegerArrayData;
break;
case ClassID::StringArrayDataClass:
pObject = new StringArrayData;
break;
case ClassID::DataArrayDataClass:
pObject = new DataArrayData;
break;
case ClassID::BinaryDataClass:
pObject = new BinaryData;
break;
case ClassID::NullDataClass:
pObject = new NullData;
break;
case ClassID::DefaultDataClass:
pObject = new DefaultData;
break;
case ClassID::ExceptionClass:
pObject = new ExceptionObject;
break;
case ClassID::ParameterClass:
pObject = new Parameter;
break;
case ClassID::BitSetClass:
pObject = new BitSet;
break;
case ClassID::CompressedStringDataClass:
// serializeで伸張したものをやりとりするので
// StringDataを作る
pObject = new StringData;
break;
case ClassID::CompressedBinaryDataClass:
pObject = new CompressedBinaryData;
break;
#ifdef OBSOLETE
case ClassID::CompressedStreamStringDataClass:
pObject = new CompressedStringData;
break;
case ClassID::CompressedStreamBinaryDataClass:
pObject = new CompressedBinaryData;
break;
#endif
case ClassID::ObjectIDDataClass:
pObject = new ObjectIDData;
break;
case ClassID::RequestClass:
pObject = new Request;
break;
case ClassID::LanguageDataClass:
pObject = new LanguageData;
break;
case ClassID::SQLDataClass:
pObject = new SQLData;
break;
case ClassID::ColumnMetaDataClass:
pObject = new ColumnMetaData;
break;
case ClassID::ResultSetMetaDataClass:
pObject = new ResultSetMetaData;
break;
case ClassID::WordDataClass:
pObject = new WordData;
break;
case ClassID::ErrorLevelClass:
pObject = new ErrorLevel;
break;
}
return pObject;
}
//
// Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2023 Ricoh Company, Ltd.
// All rights reserved.
//
| 0 | 0.73874 | 1 | 0.73874 | game-dev | MEDIA | 0.291417 | game-dev | 0.517568 | 1 | 0.517568 |
pvigier/Simulopolis | 2,910 | src/pcg/CompanyGenerator.cpp | /* Simulopolis
* Copyright (C) 2018 Pierre Vigier
*
* 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/>.
*/
#include "pcg/CompanyGenerator.h"
#include "resource/TextFileManager.h"
#include "pcg/RandomGenerator.h"
#include "city/Company.h"
#include "city/Person.h"
TextFileManager* CompanyGenerator::sTextFileManager = nullptr;
void CompanyGenerator::setTextFileManager(TextFileManager* textFileManager)
{
sTextFileManager = textFileManager;
}
CompanyGenerator::CompanyGenerator(RandomGenerator& generator) : mGenerator(generator)
{
//ctor
}
void CompanyGenerator::setUp()
{
mFruits = sTextFileManager->loadValues("media/companies/fruits.txt");
mPrefixes = sTextFileManager->loadValues("media/companies/prefixes.txt");
mPrefixes = sTextFileManager->loadValues("media/companies/suffixes.txt");
mDomains = sTextFileManager->loadValues("media/companies/domains.txt");
}
std::unique_ptr<Company> CompanyGenerator::generate(int year, Person* owner)
{
std::discrete_distribution<int> typePdf{0.1, 0.4, 0.1, 0.4};
int type = typePdf(mGenerator);
std::string name;
// Fruit
if (type == 0)
{
std::uniform_int_distribution<int> fruitPdf(0, mFruits.size() - 1);
name += mFruits[fruitPdf(mGenerator)];
}
// Owner's name
else if (type == 1)
name += owner->getLastName();
// Prefix + domain
else if (type == 2)
{
std::uniform_int_distribution<int> prefixPdf(0, mPrefixes.size() - 1);
std::uniform_int_distribution<int> domainPdf(0, mDomains.size() - 1);
name += mPrefixes[prefixPdf(mGenerator)] + mDomains[domainPdf(mGenerator)];
}
// Initials
else
{
std::uniform_int_distribution<int> nbLettersPdf(2, 4);
std::uniform_int_distribution<int> letterPdf(0, 25);
int nbLetters = nbLettersPdf(mGenerator);
name += ('A' + letterPdf(mGenerator));
if (nbLetters == 2)
name += '&';
for (int i = 1; i < nbLetters; ++i)
name += ('A' + letterPdf(mGenerator));
}
// Add the type of the company
std::uniform_int_distribution<int> suffixPdf(0, mSuffixes.size() - 1);
std::string suffix = mSuffixes[suffixPdf(mGenerator)];
return std::make_unique<Company>(name + " " + suffix, year, owner, Money(0.0));
}
| 0 | 0.768229 | 1 | 0.768229 | game-dev | MEDIA | 0.410858 | game-dev | 0.654244 | 1 | 0.654244 |
Big-Dungeons/RustClear | 8,416 | src/server/player/packet_handling.rs | use crate::net::packets::packet::ProcessPacket;
use crate::net::protocol::play::clientbound::{BlockChange, TabCompleteReply};
use crate::net::protocol::play::serverbound::*;
use crate::server::commands::Command;
use crate::server::items::Item;
use crate::server::player::container_ui::UI;
use crate::server::player::inventory::ItemSlot;
use crate::server::player::player::Player;
use std::time::{SystemTime, UNIX_EPOCH};
impl ProcessPacket for KeepAlive {
fn process_with_player(&self, player: &mut Player) {
if player.last_keep_alive == self.id {
if let Ok(since) = SystemTime::now().duration_since(UNIX_EPOCH) {
let since = since.as_millis() as i32 - player.last_keep_alive;
player.ping = (player.ping * 3 + since) / 4;
println!("Ping: {}", player.ping);
}
}
}
}
impl ProcessPacket for ChatMessage {
fn process_with_player(&self, player: &mut Player) {
if self.message.starts_with("/") {
let command = self.message.strip_prefix("/").unwrap();
if let Err(e) = Command::handle(command, player.world_mut(), player) {
eprintln!("cmd failed {e}")
};
}
}
}
impl ProcessPacket for UseEntity {
fn process_with_player(&self, player: &mut Player) {
if let Some((entity, entity_impl)) = player.world_mut().entities.get_mut(&self.entity_id.0) {
entity_impl.interact(entity, player, &self.action)
}
}
}
// I don't know if any implementation will be needed,
// but just in case imma keep it here
impl ProcessPacket for PlayerUpdate {}
// anti cheat stuff vvv important to do for all 3
impl ProcessPacket for PlayerPosition {
fn process_with_player(&self, player: &mut Player) {
player.set_position(self.x, self.y, self.z)
}
}
impl ProcessPacket for PlayerLook {
fn process_with_player(&self, player: &mut Player) {
player.yaw = self.yaw;
player.pitch = self.pitch;
}
}
impl ProcessPacket for PlayerPositionLook {
fn process_with_player(&self, player: &mut Player) {
player.set_position(self.x, self.y, self.z);
player.yaw = self.yaw;
player.pitch = self.pitch;
}
}
impl ProcessPacket for PlayerDigging {
fn process_with_player(&self, player: &mut Player) {
let world = player.world_mut();
match self.action {
PlayerDiggingAction::StartDestroyBlock => {
// todo:
// when block toughness is added,
// replace check with if vanilla toughness would match
if let Some(ItemSlot::Filled(Item::DiamondPickaxe)) = player.inventory.get_hotbar_slot(player.held_slot as usize) {
let block = world.get_block_at(self.position.x, self.position.y, self.position.z);
player.write_packet(&BlockChange {
block_pos: self.position,
block_state: block.get_block_state_id(),
})
}
}
PlayerDiggingAction::FinishDestroyBlock => {
let block = world.get_block_at(self.position.x, self.position.y, self.position.z);
player.write_packet(&BlockChange {
block_pos: self.position,
block_state: block.get_block_state_id(),
})
}
_ => {}
}
}
}
impl ProcessPacket for PlayerBlockPlacement {
fn process_with_player(&self, player: &mut Player) {
// todo:
// - improve accuracy
// - prevent clicking from a distance
let world = player.world_mut();
if !self.position.is_invalid() {
// im considering instead of this,
// just pass this to the dungeon, which checks doors and such
let mut pos = self.position.clone();
match self.placed_direction {
0 => pos.y -= 1,
1 => pos.y += 1,
2 => pos.z -= 1,
3 => pos.z += 1,
4 => pos.x -= 1,
_ => pos.x += 1,
}
let block = world.get_block_at(pos.x, pos.y, pos.z);
player.write_packet(&BlockChange {
block_pos: pos,
block_state: block.get_block_state_id()
});
if let Some(interact_block) = world.interactable_blocks.get(&self.position) {
interact_block.interact(player, &self.position);
}
} else {
player.handle_right_click();
}
// player.sync_inventory();
}
}
impl ProcessPacket for HeldItemChange {
fn process_with_player(&self, player: &mut Player) {
// warn player if invalid packets
let item_slot = self.slot_id.clamp(0, 8) as u8;
player.held_slot = item_slot;
}
}
// will be useful if we want to add stuff like mage beam
impl ProcessPacket for ArmSwing {}
impl ProcessPacket for PlayerAction {
fn process_with_player(&self, player: &mut Player) {
match self.action {
PlayerActionType::StartSneaking => player.is_sneaking = true,
PlayerActionType::StopSneaking => player.is_sneaking = false,
_ => {}
}
}
}
impl ProcessPacket for CloseWindow {
fn process_with_player(&self, player: &mut Player) {
player.open_ui(UI::None)
}
}
impl ProcessPacket for ClickWindow {
fn process_with_player(&self, player: &mut Player) {
if player.current_ui == UI::None
|| (player.window_id != self.window_id && player.current_ui != UI::Inventory)
{
player.sync_inventory();
return;
}
player.current_ui.clone().handle_click_window(self, player);
}
}
impl ProcessPacket for ConfirmTransaction {
// wd sync stuff
}
impl ProcessPacket for TabComplete {
fn process_with_player(&self, player: &mut Player) {
if !self.message.starts_with("/") {
return;
}
let parts: Vec<&str> = self.message.split_whitespace().collect();
let command_name = parts[0].strip_prefix("/").unwrap();
if command_name.is_empty() {
player.write_packet(&TabCompleteReply {
matches: Command::list().iter().map(|cmd| format!("/{}", cmd.name())).collect(),
});
return
}
if let Some(command) = Command::find(command_name) {
let args = &parts[1..];
let next_arg = self.message.ends_with(' ');
if args.is_empty() && !next_arg {
// user input a valid command but has not hit space, so we shouldn't provide any completions.
// there might be a better way to do this somewhere else but idk atm.
return;
}
let current_arg = if next_arg {
args.len()
} else {
args.len().saturating_sub(1)
};
let command_args = command.args(player.world_mut(), player);
if current_arg >= command_args.len() {
// user has input too many arguments; so we just return here.
return;
}
let completions = {
let arg = &command_args.get(current_arg);
if arg.is_none() { return; }
&arg.unwrap().completions
};
let matches: Vec<String> = if next_arg || args.is_empty() {
completions.to_vec()
} else {
completions.iter().filter(|cmp| cmp.starts_with(args.last().unwrap_or(&""))).cloned().collect()
};
player.write_packet(&TabCompleteReply {
matches
});
} else {
let commands = Command::list().iter().filter(|cmd| cmd.name().starts_with(command_name)).map(|cmd| format!("/{}", cmd.name())).collect();
player.write_packet(&TabCompleteReply {
matches: commands
});
}
}
}
impl ProcessPacket for ClientSettings {
// render distance stuff
}
impl ProcessPacket for ClientStatus {
fn process_with_player(&self, player: &mut Player) {
match self {
ClientStatus::OpenInventory => {
player.open_ui(UI::Inventory)
}
_ => {}
}
}
} | 0 | 0.928872 | 1 | 0.928872 | game-dev | MEDIA | 0.761694 | game-dev | 0.900841 | 1 | 0.900841 |
hocha113/CalamityOverhaul | 3,557 | Content/Projectiles/Weapons/Ranged/IceSoulOrb.cs | using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.GameContent;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityOverhaul.Content.Projectiles.Weapons.Ranged
{
internal class IceSoulOrb : ModProjectile
{
public override string Texture => CWRConstant.Projectile_Ranged + "IceSoulOrb";
public override void SetDefaults() {
Projectile.width = 22;
Projectile.height = 24;
Projectile.penetrate = 1;
Projectile.timeLeft = 180;
Projectile.usesIDStaticNPCImmunity = true;
Projectile.idStaticNPCHitCooldown = 10;
Projectile.MaxUpdates = 2;
Projectile.friendly = true;
}
public override void AI() {
VaultUtils.ClockFrame(ref Projectile.frame, 5, 3);
Projectile.rotation = Projectile.velocity.ToRotation() + MathHelper.PiOver2;
if (Projectile.ai[1] > 0) {
NPC target = Projectile.Center.FindClosestNPC(600, false, true);
if (target != null) {
float num = target.Center.Distance(Projectile.Center);
if (num > 120) {
Projectile.SmoothHomingBehavior(target.Center, 1, 0.22f);
}
else {
Projectile.ChasingBehavior(target.Center, Projectile.velocity.Length());
}
}
}
Projectile.ai[2] = Projectile.ai[0] >= 135
? Utils.Remap(Projectile.ai[0], 225f, 270, 1.5f, 0f)
: Utils.Remap(Projectile.ai[0], 135, 225f, 0f, 1.5f);
Projectile.ai[0]++;
}
public override bool OnTileCollide(Vector2 oldVelocity) {
if (Projectile.ai[1] == 0) {
if (Projectile.velocity.X != oldVelocity.X) {
Projectile.velocity.X = -oldVelocity.X * (Utils.Remap(Projectile.ai[0], 0f, 135f, 0.9f, 2f));
}
if (Projectile.velocity.Y != oldVelocity.Y) {
Projectile.velocity.Y = -oldVelocity.Y * (Utils.Remap(Projectile.ai[0], 0f, 135f, 0.9f, 2f));
}
for (int i = 0; i < 3; i++) {
Vector2 velocity = new Vector2(Main.rand.NextFloat(-3, 3), -3);
Projectile proj = Projectile.NewProjectileDirect(Main.player[Projectile.owner].GetShootState().Source
, Projectile.Bottom + new Vector2(Main.rand.Next(-16, 16), 0), velocity
, ProjectileID.DeerclopsIceSpike, 23, 0f, Main.myPlayer, 0f, Main.rand.NextFloat(0.8f, 1.1f));
proj.rotation = velocity.ToRotation();
proj.hostile = false;
proj.friendly = true;
proj.penetrate = -1;
proj.usesLocalNPCImmunity = true;
proj.localNPCHitCooldown = 20;
proj.light = 0.75f;
}
}
Projectile.ai[1]++;
return false;
}
public override bool PreDraw(ref Color lightColor) {
Texture2D value = TextureAssets.Projectile[Type].Value;
Vector2 drawPosition = Projectile.Center - Main.screenPosition;
Main.EntitySpriteDraw(value, drawPosition, value.GetRectangle(Projectile.frame, 4)
, Color.White, Projectile.rotation, VaultUtils.GetOrig(value, 4), Projectile.scale, SpriteEffects.None, 0);
return false;
}
}
}
| 0 | 0.865553 | 1 | 0.865553 | game-dev | MEDIA | 0.99335 | game-dev | 0.990176 | 1 | 0.990176 |
UniRmmz/UniRmmz | 6,020 | Assets/Scripts/UniRmmz/CoreScript/Objects/Game_System.cs | using System;
namespace UniRmmz
{
/// <summary>
/// The game object class for the system data.
/// </summary>
[Serializable]
public partial class Game_System
{
protected bool _saveEnabled = true;
protected bool _menuEnabled = true;
protected bool _encounterEnabled = true;
protected bool _formationEnabled = true;
protected int _battleCount = 0;
protected int _winCount = 0;
protected int _escapeCount = 0;
protected int _saveCount = 0;
protected int _versionId = 0;
protected int _savefileId = 0;
protected int _framesOnSave = 0;
protected AudioManager.Sound _bgmOnSave = null;
protected AudioManager.Sound _bgsOnSave = null;
protected int[] _windowTone = null;
protected DataSystem.DataSound _battleBgm = null;
protected DataSystem.DataSound _victoryMe = null;
protected DataSystem.DataSound _defeatMe = null;
protected AudioManager.Sound _savedBgm = null;
protected AudioManager.Sound _walkingBgm = null;
public virtual bool IsJapanese() => Rmmz.dataSystem.Locale.StartsWith("ja");
public virtual bool IsChinese() => Rmmz.dataSystem.Locale.StartsWith("zh");
public virtual bool IsKorean() => Rmmz.dataSystem.Locale.StartsWith("ko");
public virtual bool IsCJK() => IsJapanese() || IsChinese() || IsKorean();
public virtual bool IsRussian() => Rmmz.dataSystem.Locale.StartsWith("ru");
public virtual bool IsSideView() => Rmmz.dataSystem.OptSideView;
public virtual bool IsAutosaveEnabled() => Rmmz.dataSystem.OptAutosave;
public virtual bool IsSaveEnabled() => _saveEnabled;
public virtual void DisableSave() => _saveEnabled = false;
public virtual void EnableSave() => _saveEnabled = true;
public virtual bool IsMenuEnabled() => _menuEnabled;
public virtual void DisableMenu() => _menuEnabled = false;
public virtual void EnableMenu() => _menuEnabled = true;
public virtual bool IsEncounterEnabled() => _encounterEnabled;
public virtual void DisableEncounter() => _encounterEnabled = false;
public virtual void EnableEncounter() => _encounterEnabled = true;
public virtual bool IsFormationEnabled() => _formationEnabled;
public virtual void DisableFormation() => _formationEnabled = false;
public virtual void EnableFormation() => _formationEnabled = true;
public virtual int BattleCount => _battleCount;
public virtual int WinCount => _winCount;
public virtual int EscapeCount => _escapeCount;
public virtual int SaveCount => _saveCount;
public virtual int VersionId() => _versionId;
public virtual int SavefileId() => _savefileId;
public virtual void SetSavefileId(int id) => _savefileId = id;
public virtual int[] WindowTone() => _windowTone ?? Rmmz.dataSystem.WindowTone;
public virtual void SetWindowTone(int[] tone) => _windowTone = tone;
public virtual DataSystem.DataSound BattleBgm() => _battleBgm ?? Rmmz.dataSystem.BattleBgm;
public virtual void SetBattleBgm(DataSystem.DataSound bgm) => _battleBgm = bgm;
public virtual DataSystem.DataSound VictoryMe() => _victoryMe ?? Rmmz.dataSystem.VictoryMe;
public virtual void SetVictoryMe(DataSystem.DataSound me) => _victoryMe = me;
public virtual DataSystem.DataSound DefeatMe() => _defeatMe ?? Rmmz.dataSystem.DefeatMe;
public virtual void SetDefeatMe(DataSystem.DataSound me) => _defeatMe = me;
public virtual void OnBattleStart() => _battleCount++;
public virtual void OnBattleWin() => _winCount++;
public virtual void OnBattleEscape() => _escapeCount++;
protected Game_System() {}
public virtual void OnBeforeSave()
{
_saveCount++;
_versionId = Rmmz.dataSystem.VersionId;
_framesOnSave = Graphics.FrameCount;
_bgmOnSave = Rmmz.AudioManager.SaveBgm();
_bgsOnSave = Rmmz.AudioManager.SaveBgs();
}
public virtual void OnAfterLoad()
{
Graphics.FrameCount = _framesOnSave;
Rmmz.AudioManager.PlayBgm(_bgmOnSave);
Rmmz.AudioManager.PlayBgs(_bgsOnSave);
}
public virtual int Playtime()
{
return Graphics.FrameCount / 60;
}
public virtual string PlaytimeText()
{
int hour = Playtime() / 60 / 60;
int min = (Playtime() / 60) % 60;
int sec = Playtime() % 60;
return $"{hour:D2}:{min:D2}:{sec:D2}";
}
public virtual void SaveBgm()
{
_savedBgm = Rmmz.AudioManager.SaveBgm();
}
public virtual void ReplayBgm()
{
if (_savedBgm != null)
{
Rmmz.AudioManager.ReplayBgm(_savedBgm);
}
}
public virtual void SaveWalkingBgm()
{
_walkingBgm = Rmmz.AudioManager.SaveBgm();
}
public virtual void ReplayWalkingBgm()
{
if (_walkingBgm != null)
{
Rmmz.AudioManager.PlayBgm(_walkingBgm);
}
}
public virtual void SaveWalkingBgm2()
{
_walkingBgm = Rmmz.dataMap.Bgm;
}
public virtual string MainFontFace()
{
return $"rmmz-mainfont, {Rmmz.dataSystem.Advanced.FallbackFonts}";
}
public virtual string NumberFontFace()
{
return $"rmmz-numberfont, {MainFontFace()}";
}
public virtual int MainFontSize()
{
return Rmmz.dataSystem.Advanced.FontSize;
}
public virtual int WindowPadding() => 12;
public virtual int WindowOpacity()
{
return Rmmz.dataSystem.Advanced.WindowOpacity;
}
}
} | 0 | 0.656027 | 1 | 0.656027 | game-dev | MEDIA | 0.775018 | game-dev | 0.899507 | 1 | 0.899507 |
PJUllrich/run-elixir | 4,752 | guides/01-basics/control-flow.livemd | # Control Flow
Elixir offers four control flow structures: `if/unless`, `case`, `cond`, and `with`.
## `if/2` and `unless/2`
If-else works as you'd expect. If your condition evaluates to `truthy` (not `nil` or `false`), the code block is executed and the result is returned. If the condition evaluates to `falsy` (`nil` or `false`), the `else` block is executed if it exists; otherwise, `nil` is returned.
The reverse form of `if/2` is `unless/2`. If your `unless` condition evaluates to `truthy`, the `else` block is executed. If the condition is `falsy`, the first block is executed. It is common to choose `if` over `unless` because it doesn't make your brain hurt, unless you want to execute a side effect or throw an exception.
```elixir
age = 17
result =
if age >= 18 do
:adult
else
:minor
end
IO.inspect(result, label: 1)
unless age >= 18 do
raise "A minor tries to access the system!"
end
```
<!-- livebook:{"output":true} -->
```
1: :minor
** (RuntimeError) A minor tries to access the system!
```
## `case/2`
The `case` statement is similar to `switch` in other languages. It allows you to state multiple clauses and tries to match your conditional against each clause.
```elixir
active_status = :active
fun =
fn value ->
case value do
%{status: ^active_status} -> :active
%{status: _other_status} -> :inactive
%{age: nil} -> :age_missing
%{age: age} when is_integer(age) and age >= 18 -> :adult
%{age: age} when is_integer(age) -> :minor
# An optional fallback which always matches.
# Without it, the case statement would raise an exception if no clause matches.
_ -> :default
end
end
fun.(%{status: :active}) # => :active
fun.(%{status: :foobar}) # => :inactive
fun.(%{age: nil}) # => :age_missing
fun.(%{age: 18}) # => :adult
fun.(%{age: 17}) # => :minor
fun.(nil) # => :default
```
## `cond/1`
The `cond` construct allows you to evaluate multiple clauses and return from the first that evaluates to `truthy`. It is especially useful if you need to execute a function in a clause.
```elixir
adult? = fn age -> age >= 18 end
fun =
fn value ->
cond do
value == :active -> :active
is_integer(value) && adult?.(value) -> :adult
is_integer(value) -> :minor
# The optional fallback clause must always evaluate to a truthy value.
# If you don't give this and no other clause matches, Elixir raises an exception.
true -> :default
end
end
fun.(:active) # => :active
fun.(18) # => :adult
fun.(17) # => :minor
fun.(nil) # => :default
```
## `with/1`
The `with/1` statement is useful to return early from a sequence of steps if one step fails. If you find yourself writing nested if-else or case statements, you probably want to use `with/1` instead.
```elixir
adult? = fn age -> age >= 18 end
details = %{name: "Peter", age: 32}
# Instead of writing nested if- or case-statements like this:
check_access = fn details ->
case details do
%{age: age} ->
if adult?.(age) do
:ok
else
{:error, :not_adult}
end
_ ->
{:error, :age_missing}
end
end
# Rather use one with-statement like this:
check_access_refactored = fn details ->
with %{age: age} <- details,
true <- adult?.(age) do
:ok
else
# Gets executed if any of the matches above fails.
%{} -> {:error, :age_missing}
false -> {:error, :not_adult}
end
end
```
To match inside the `else`-block isn't great though. What if two matches can return `false`? How would you know which match failed?
It is good practice to move steps step into small helper functions. This allows you to return a specific error message depending on which step failed and it makes the `with`-statement more readable. It also makes it easy to see the "happy path" of your function and all its error cases.
```elixir
defmodule RunElixir.Permissions do
def check_access(details) do
with {:ok, age} <- get_age(details),
:ok <- check_adult(age) do
:ok
end
end
# Moving each step into a small helper function gives you the flexibility
# to decide which error to return inside the function.
defp get_age(details) do
case details do
%{age: age} when is_integer(age) -> {:ok, age}
%{age: _age} -> {:error, :age_invalid}
_ -> {:error, :age_missing}
end
end
defp check_adult(age) do
if age >= 18, do: :ok, else: {:error, :not_adult}
end
end
RunElixir.Permissions.check_access(%{age: 32}) # => :ok
RunElixir.Permissions.check_access(%{age: nil}) # => {:error, :age_invalid}
RunElixir.Permissions.check_access(%{name: "Peter"}) # => {:error, :age_missing}
RunElixir.Permissions.check_access(%{age: 17}) # => {:error, :not_adult}
``` | 0 | 0.857177 | 1 | 0.857177 | game-dev | MEDIA | 0.413357 | game-dev | 0.563349 | 1 | 0.563349 |
Therealsxlar/4.2-Gameserver | 3,256 | 4.2-Gameserver/SDK/SDK/Subtitles_functions.cpp | #pragma once
// Dumped with Dumper-7!
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------------------------------------------------
// FUNCTIONS
//---------------------------------------------------------------------------------------------------------------------
// Function Subtitles.Subtitles_C.GetSubtitleVisibility
// (Public, HasOutParams, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// enum class ESlateVisibility ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// bool Temp_bool_Variable (ZeroConstructor, IsPlainOldData, NoDestructor)
// enum class ESlateVisibility Temp_byte_Variable (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// enum class ESlateVisibility Temp_byte_Variable1 (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// bool CallFunc_HasSubtitles_ReturnValue (ZeroConstructor, IsPlainOldData, NoDestructor)
// enum class ESlateVisibility K2Node_Select_Default (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
enum class ESlateVisibility USubtitles_C::GetSubtitleVisibility(bool Temp_bool_Variable, enum class ESlateVisibility Temp_byte_Variable, enum class ESlateVisibility Temp_byte_Variable1, bool CallFunc_HasSubtitles_ReturnValue, enum class ESlateVisibility K2Node_Select_Default)
{
static auto Func = Class->GetFunction("Subtitles_C", "GetSubtitleVisibility");
Params::USubtitles_C_GetSubtitleVisibility_Params Parms;
Parms.Temp_bool_Variable = Temp_bool_Variable;
Parms.Temp_byte_Variable = Temp_byte_Variable;
Parms.Temp_byte_Variable1 = Temp_byte_Variable1;
Parms.CallFunc_HasSubtitles_ReturnValue = CallFunc_HasSubtitles_ReturnValue;
Parms.K2Node_Select_Default = K2Node_Select_Default;
UObject::ProcessEvent(Func, &Parms);
return Parms.ReturnValue;
}
// Function Subtitles.Subtitles_C.Construct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
// Parameters:
void USubtitles_C::Construct()
{
static auto Func = Class->GetFunction("Subtitles_C", "Construct");
Params::USubtitles_C_Construct_Params Parms;
UObject::ProcessEvent(Func, &Parms);
}
// Function Subtitles.Subtitles_C.ExecuteUbergraph_Subtitles
// ()
// Parameters:
// int32 EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void USubtitles_C::ExecuteUbergraph_Subtitles(int32 EntryPoint)
{
static auto Func = Class->GetFunction("Subtitles_C", "ExecuteUbergraph_Subtitles");
Params::USubtitles_C_ExecuteUbergraph_Subtitles_Params Parms;
Parms.EntryPoint = EntryPoint;
UObject::ProcessEvent(Func, &Parms);
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 0 | 0.794498 | 1 | 0.794498 | game-dev | MEDIA | 0.663098 | game-dev | 0.516476 | 1 | 0.516476 |
flutter/engine | 5,089 | impeller/renderer/backend/gles/blit_pass_gles.cc | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/gles/blit_pass_gles.h"
#include <memory>
#include "flutter/fml/trace_event.h"
#include "fml/closure.h"
#include "impeller/core/formats.h"
#include "impeller/renderer/backend/gles/blit_command_gles.h"
#include "impeller/renderer/backend/gles/proc_table_gles.h"
namespace impeller {
BlitPassGLES::BlitPassGLES(std::shared_ptr<ReactorGLES> reactor)
: reactor_(std::move(reactor)),
is_valid_(reactor_ && reactor_->IsValid()) {}
// |BlitPass|
BlitPassGLES::~BlitPassGLES() = default;
// |BlitPass|
bool BlitPassGLES::IsValid() const {
return is_valid_;
}
// |BlitPass|
void BlitPassGLES::OnSetLabel(std::string_view label) {
label_ = std::string(label);
}
[[nodiscard]] bool EncodeCommandsInReactor(
const std::shared_ptr<Allocator>& transients_allocator,
const ReactorGLES& reactor,
const std::vector<std::unique_ptr<BlitEncodeGLES>>& commands,
const std::string& label) {
TRACE_EVENT0("impeller", "BlitPassGLES::EncodeCommandsInReactor");
if (commands.empty()) {
return true;
}
const auto& gl = reactor.GetProcTable();
fml::ScopedCleanupClosure pop_pass_debug_marker(
[&gl]() { gl.PopDebugGroup(); });
if (!label.empty()) {
gl.PushDebugGroup(label);
} else {
pop_pass_debug_marker.Release();
}
for (const auto& command : commands) {
fml::ScopedCleanupClosure pop_cmd_debug_marker(
[&gl]() { gl.PopDebugGroup(); });
auto label = command->GetLabel();
if (!label.empty()) {
gl.PushDebugGroup(label);
} else {
pop_cmd_debug_marker.Release();
}
if (!command->Encode(reactor)) {
return false;
}
}
return true;
}
// |BlitPass|
bool BlitPassGLES::EncodeCommands(
const std::shared_ptr<Allocator>& transients_allocator) const {
if (!IsValid()) {
return false;
}
if (commands_.empty()) {
return true;
}
std::shared_ptr<const BlitPassGLES> shared_this = shared_from_this();
return reactor_->AddOperation([transients_allocator,
blit_pass = std::move(shared_this),
label = label_](const auto& reactor) {
auto result = EncodeCommandsInReactor(transients_allocator, reactor,
blit_pass->commands_, label);
FML_CHECK(result) << "Must be able to encode GL commands without error.";
});
}
// |BlitPass|
bool BlitPassGLES::OnCopyTextureToTextureCommand(
std::shared_ptr<Texture> source,
std::shared_ptr<Texture> destination,
IRect source_region,
IPoint destination_origin,
std::string_view label) {
auto command = std::make_unique<BlitCopyTextureToTextureCommandGLES>();
command->label = label;
command->source = std::move(source);
command->destination = std::move(destination);
command->source_region = source_region;
command->destination_origin = destination_origin;
commands_.push_back(std::move(command));
return true;
}
// |BlitPass|
bool BlitPassGLES::OnCopyTextureToBufferCommand(
std::shared_ptr<Texture> source,
std::shared_ptr<DeviceBuffer> destination,
IRect source_region,
size_t destination_offset,
std::string_view label) {
auto command = std::make_unique<BlitCopyTextureToBufferCommandGLES>();
command->label = label;
command->source = std::move(source);
command->destination = std::move(destination);
command->source_region = source_region;
command->destination_offset = destination_offset;
commands_.push_back(std::move(command));
return true;
}
// |BlitPass|
bool BlitPassGLES::OnCopyBufferToTextureCommand(
BufferView source,
std::shared_ptr<Texture> destination,
IRect destination_region,
std::string_view label,
uint32_t mip_level,
uint32_t slice,
bool convert_to_read) {
auto command = std::make_unique<BlitCopyBufferToTextureCommandGLES>();
command->label = label;
command->source = std::move(source);
command->destination = std::move(destination);
command->destination_region = destination_region;
command->label = label;
command->mip_level = mip_level;
command->slice = slice;
commands_.push_back(std::move(command));
return true;
}
// |BlitPass|
bool BlitPassGLES::OnGenerateMipmapCommand(std::shared_ptr<Texture> texture,
std::string_view label) {
auto command = std::make_unique<BlitGenerateMipmapCommandGLES>();
command->label = label;
command->texture = std::move(texture);
commands_.push_back(std::move(command));
return true;
}
// |BlitPass|
bool BlitPassGLES::ResizeTexture(const std::shared_ptr<Texture>& source,
const std::shared_ptr<Texture>& destination) {
auto command = std::make_unique<BlitResizeTextureCommandGLES>();
command->source = source;
command->destination = destination;
commands_.push_back(std::move(command));
return true;
}
} // namespace impeller
| 0 | 0.89049 | 1 | 0.89049 | game-dev | MEDIA | 0.237972 | game-dev | 0.865386 | 1 | 0.865386 |
GaijinEntertainment/DagorEngine | 2,547 | prog/3rdPartyLibs/phys/bullet-3/Extras/ConvexDecomposition/planetri.h | #ifndef PLANE_TRI_H
#define PLANE_TRI_H
/*----------------------------------------------------------------------
Copyright (c) 2004 Open Dynamics Framework Group
www.physicstools.org
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
Neither the name of the Open Dynamics Framework Group nor the names of its contributors may
be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE INTEL OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------*/
// http://codesuppository.blogspot.com
//
// mailto: jratcliff@infiniplex.net
//
// http://www.amillionpixels.us
//
enum PlaneTriResult
{
PTR_FRONT,
PTR_BACK,
PTR_SPLIT
};
PlaneTriResult planeTriIntersection(const float *plane, // the plane equation in Ax+By+Cz+D format
const float *triangle, // the source position triangle.
unsigned int tstride, // stride in bytes between vertices of the triangle.
float epsilon, // the co-planer epsilon value.
float *front, // the triangle in front of the
unsigned int &fcount, // number of vertices in the 'front' triangle.
float *back, // the triangle in back of the plane
unsigned int &bcount); // the number of vertices in the 'back' triangle.
#endif
| 0 | 0.867956 | 1 | 0.867956 | game-dev | MEDIA | 0.474625 | game-dev | 0.669325 | 1 | 0.669325 |
mracko/MSFS-Landing-Inspector | 3,597 | SimConnectCust/FacilitiesList.py | from SimConnect import *
from .Enum import *
from .Constants import *
class Facilitie(object):
def __init__(self):
pass
class FacilitiesHelper:
def __init__(self, _sm, _parent):
self.sm = _sm
self.parent = _parent
self.REQUEST_ID = _sm.new_request_id()
self.item = None
self.sm.Facilities.append(self)
def subscribe(self, _cbfunc):
if self.item < SIMCONNECT_FACILITY_LIST_TYPE.SIMCONNECT_FACILITY_LIST_TYPE_COUNT:
self.cb = _cbfunc
hr = self.sm.dll.SubscribeToFacilities(
self.sm.hSimConnect,
SIMCONNECT_FACILITY_LIST_TYPE(self.item),
self.REQUEST_ID.value
)
def unsubscribe(self):
self.cb = None
hr = self.sm.dll.UnsubscribeToFacilities(
self.sm.hSimConnect,
SIMCONNECT_FACILITY_LIST_TYPE(self.item)
)
def get(self):
# Get the current cached list of airports, waypoints, etc, as the item indicates
if self.item < SIMCONNECT_FACILITY_LIST_TYPE.SIMCONNECT_FACILITY_LIST_TYPE_COUNT:
hr = self.sm.dll.RequestFacilitiesList(
self.sm.hSimConnect,
SIMCONNECT_FACILITY_LIST_TYPE(self.item),
self.REQUEST_ID.value
)
# self.sm.run()
class FacilitiesRequests():
def __init__(self, _sm):
self.sm = _sm
self.list = []
self.Airports = self.__FACILITY_AIRPORT(_sm, self)
self.list.append(self.Airports)
self.Waypoints = self.__FACILITY_WAYPOINT(_sm, self)
self.list.append(self.Waypoints)
self.NDBs = self.__FACILITY_NDB(_sm, self)
self.list.append(self.NDBs)
self.VORs = self.__FACILITY_VOR(_sm, self)
self.list.append(self.VORs)
def dump(self, pList):
pList = cast(pList, POINTER(SIMCONNECT_RECV_FACILITIES_LIST))
List = pList.contents
print("RequestID: %d dwArraySize: %d dwEntryNumber: %d dwOutOf: %d" % (
List.dwRequestID, List.dwArraySize, List.dwEntryNumber, List.dwOutOf)
)
# Dump various facility elements
class __FACILITY_AIRPORT(FacilitiesHelper):
def __init__(self, _sm, _parent):
super().__init__(_sm, _parent)
self.item = SIMCONNECT_FACILITY_LIST_TYPE.SIMCONNECT_FACILITY_LIST_TYPE_AIRPORT
def dump(self, pFac):
pFac = cast(pFac, POINTER(SIMCONNECT_DATA_FACILITY_AIRPORT))
Fac = pFac.contents
print("Icao: %s Latitude: %lg Longitude: %lg Altitude: %lg" % (
Fac.Icao.decode(), Fac.Latitude, Fac.Longitude, Fac.Altitude)
)
class __FACILITY_WAYPOINT(FacilitiesHelper):
def __init__(self, _sm, _parent):
super().__init__(_sm, _parent)
self.item = SIMCONNECT_FACILITY_LIST_TYPE.SIMCONNECT_FACILITY_LIST_TYPE_WAYPOINT
def dump(self, pFac):
pFac = cast(pFac, POINTER(SIMCONNECT_DATA_FACILITY_WAYPOINT))
Fac = pFac.contents
self.parent.Airports.dump(pFac)
print("\tfMagVar: %g" % (Fac.fMagVar))
class __FACILITY_NDB(FacilitiesHelper):
def __init__(self, _sm, _parent):
super().__init__(_sm, _parent)
self.item = SIMCONNECT_FACILITY_LIST_TYPE.SIMCONNECT_FACILITY_LIST_TYPE_NDB
def dump(self, pFac):
pFac = cast(pFac, POINTER(SIMCONNECT_DATA_FACILITY_NDB))
Fac = pFac.contents
self.parent.Waypoints.dump(pFac)
print("\t\tfFrequency: %d" % (Fac.fFrequency))
class __FACILITY_VOR(FacilitiesHelper):
def __init__(self, _sm, _parent):
super().__init__(_sm, _parent)
self.item = SIMCONNECT_FACILITY_LIST_TYPE.SIMCONNECT_FACILITY_LIST_TYPE_VOR
def dump(self, pFac):
pFac = cast(pFac, POINTER(SIMCONNECT_DATA_FACILITY_VOR))
Fac = pFac.contents
self.parent.NDBs.dump(pFac)
print("\t\t\tFlags: %x fLocalizer: %f GlideLat: %lg GlideLon: %lg GlideAlt: %lg fGlideSlopeAngle: %f" % (
Fac.Flags, Fac.fLocalizer, Fac.GlideLat, Fac.GlideLon, Fac.GlideAlt, Fac.fGlideSlopeAngle)
)
| 0 | 0.836987 | 1 | 0.836987 | game-dev | MEDIA | 0.151753 | game-dev | 0.743778 | 1 | 0.743778 |
exelotl/goodboy-advance | 1,541 | source/scenes/fake_end_scene.c | #include "common.h"
// #include "assets/Lv1.h"
#include "assets/SprShared1.h"
#include "assets/BgIntro1.h"
#include "assets/BgIntro2.h"
#include "fonts/Acknowledge.h"
#include "fonts/Volter.h"
#include "fonts/GelatinMono.h"
#include "assets/levels.h"
static entity_t label_thanks;
static int revealed_chars;
const char str[] = "Thanks f";
static void play_level_2(void) {
level = &Level2;
scene_set(game_scene);
}
static void show(void) {
REG_DISPCNT = DCNT_MODE1 // 2 regular, 1 affine
// | DCNT_BG0
// | DCNT_BG1
// | DCNT_BG2
// | DCNT_BG3
| DCNT_OBJ // enable sprites
| DCNT_OBJ_1D; // 1D tile mapping for sprites
// text palette
pal_obj_bank[8][0] = CLR_SKYBLUE;
pal_obj_bank[8][1] = CLR_WHITE;
pal_obj_bank[8][2] = CLR_BLACK;
pal_obj_bank[8][3] = RGB15(16,16,16); // for greyed-out text
// reserve sprite tiles in VRAM
uint tid = 0;
tid = label_init(&label_thanks, &VolterFont, 1, 2, tid, 3);
label_thanks.x = Fix(50);
label_thanks.y = Fix(60);
label_begin_write(&label_thanks);
revealed_chars = 0;
// tte_write();
// mmStart(MOD_SPACECAT, MM_PLAY_LOOP);
timeout_clear();
REG_BG0HOFS = 0;
REG_BG0VOFS = 0;
timeout_set(66, play_level_2);
}
static void hide(void) {
mmStop();
}
static void update(void) {
label_update(&label_thanks);
int len = sizeof(str)-1;
if (revealed_chars < len && (global_tick % 8 == 0)) {
tte_putc(str[revealed_chars]);
revealed_chars++;
}
}
const scene_t fake_end_scene = {
.show = show,
.hide = hide,
.update = update,
};
| 0 | 0.801213 | 1 | 0.801213 | game-dev | MEDIA | 0.8349 | game-dev | 0.671564 | 1 | 0.671564 |
Mixinors/Astromine | 5,945 | src/main/java/com/github/mixinors/astromine/common/block/entity/machine/PresserBlockEntity.java | /*
* MIT License
*
* Copyright (c) 2020 - 2022 Mixinors
*
* 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 com.github.mixinors.astromine.common.block.entity.machine;
import com.github.mixinors.astromine.common.block.entity.base.ExtendedBlockEntity;
import com.github.mixinors.astromine.common.config.AMConfig;
import com.github.mixinors.astromine.common.config.entry.tiered.SimpleMachineConfig;
import com.github.mixinors.astromine.common.provider.config.tiered.MachineConfigProvider;
import com.github.mixinors.astromine.common.recipe.PressingRecipe;
import com.github.mixinors.astromine.common.transfer.storage.SimpleItemStorage;
import com.github.mixinors.astromine.common.util.data.tier.Tier;
import com.github.mixinors.astromine.registry.common.AMBlockEntityTypes;
import net.fabricmc.fabric.api.transfer.v1.transaction.Transaction;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntityType;
import net.minecraft.util.math.BlockPos;
import team.reborn.energy.api.base.SimpleEnergyStorage;
import java.util.Optional;
import java.util.function.Supplier;
public abstract class PresserBlockEntity extends ExtendedBlockEntity implements MachineConfigProvider<SimpleMachineConfig> {
public static final int INPUT_SLOT = 0;
public static final int OUTPUT_SLOT = 1;
public static final int[] INSERT_SLOTS = new int[] { INPUT_SLOT };
public static final int[] EXTRACT_SLOTS = new int[] { OUTPUT_SLOT };
private Optional<PressingRecipe> optionalRecipe = Optional.empty();
public PresserBlockEntity(Supplier<? extends BlockEntityType<?>> type, BlockPos blockPos, BlockState blockState) {
super(type, blockPos, blockState);
energyStorage = new SimpleEnergyStorage(getEnergyStorageSize(), getMaxTransferRate(), 0L);
itemStorage = new SimpleItemStorage(2).insertPredicate((variant, slot) -> {
if (slot != INPUT_SLOT) {
return false;
}
return PressingRecipe.allows(world, variant);
}).extractPredicate((variant, slot) ->
slot == OUTPUT_SLOT
).listener(() -> {
if (optionalRecipe.isPresent() && !optionalRecipe.get().matches(itemStorage.slice(INPUT_SLOT, OUTPUT_SLOT))) {
optionalRecipe = Optional.empty();
}
markDirty();
}).insertSlots(INSERT_SLOTS).extractSlots(EXTRACT_SLOTS);
}
@Override
public void tick() {
super.tick();
if (!hasWorld() || world.isClient || !shouldRun()) {
return;
}
if (itemStorage != null && energyStorage != null) {
if (optionalRecipe.isEmpty()) {
optionalRecipe = PressingRecipe.matching(world, itemStorage.slice(INPUT_SLOT, OUTPUT_SLOT));
}
if (optionalRecipe.isPresent()) {
var recipe = optionalRecipe.get();
limit = recipe.time();
var speed = Math.min(getSpeed(), limit - progress);
var consumed = (long) (recipe.energyInput() * speed / limit);
try (var transaction = Transaction.openOuter()) {
if (energyStorage.amount >= consumed) {
energyStorage.amount -= consumed;
if (progress + speed >= limit) {
optionalRecipe = Optional.empty();
var inputStorage = itemStorage.getStorage(INPUT_SLOT);
inputStorage.extract(inputStorage.getResource(), recipe.input().getAmount(), transaction, true);
var outputStorage = itemStorage.getStorage(OUTPUT_SLOT);
outputStorage.insert(recipe.output().variant(), recipe.output().count(), transaction, true);
transaction.commit();
progress = 0.0D;
} else {
progress += speed;
}
active = true;
} else {
active = false;
}
}
} else {
progress = 0.0D;
limit = 100.0D;
active = false;
}
}
}
@Override
public SimpleMachineConfig getConfig() {
return AMConfig.get().blocks.machines.press;
}
public static class Primitive extends PresserBlockEntity {
public Primitive(BlockPos blockPos, BlockState blockState) {
super(AMBlockEntityTypes.PRIMITIVE_PRESSER, blockPos, blockState);
}
@Override
public Tier getMachineTier() {
return Tier.PRIMITIVE;
}
}
public static class Basic extends PresserBlockEntity {
public Basic(BlockPos blockPos, BlockState blockState) {
super(AMBlockEntityTypes.BASIC_PRESSER, blockPos, blockState);
}
@Override
public Tier getMachineTier() {
return Tier.BASIC;
}
}
public static class Advanced extends PresserBlockEntity {
public Advanced(BlockPos blockPos, BlockState blockState) {
super(AMBlockEntityTypes.ADVANCED_PRESSER, blockPos, blockState);
}
@Override
public Tier getMachineTier() {
return Tier.ADVANCED;
}
}
public static class Elite extends PresserBlockEntity {
public Elite(BlockPos blockPos, BlockState blockState) {
super(AMBlockEntityTypes.ELITE_PRESSER, blockPos, blockState);
}
@Override
public Tier getMachineTier() {
return Tier.ELITE;
}
}
}
| 0 | 0.935467 | 1 | 0.935467 | game-dev | MEDIA | 0.464472 | game-dev | 0.946985 | 1 | 0.946985 |
ElunaLuaEngine/ElunaTrinityWotlk | 9,575 | src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.h | /*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DEF_CRUSADER_H
#define DEF_CRUSADER_H
#include "CreatureAIImpl.h"
#define ToCrScriptName "instance_trial_of_the_crusader"
#define DataHeader "TCR"
struct Position;
uint32 const EncounterCount = 6;
enum TCRDataTypes
{
// Encounter States
DATA_NORTHREND_BEASTS = 0,
DATA_JARAXXUS = 1,
DATA_FACTION_CRUSADERS = 2,
DATA_TWIN_VALKIRIES = 3,
DATA_LICH_KING = 4,
DATA_ANUBARAK = 5,
// Additional Data
DATA_GORMOK_THE_IMPALER = 6,
DATA_ACIDMAW = 7,
DATA_DREADSCALE = 8,
DATA_ICEHOWL = 9,
DATA_FJOLA_LIGHTBANE = 10,
DATA_EYDIS_DARKBANE = 11,
DATA_FORDRING = 12,
DATA_FORDRING_ANUBARAK = 13,
DATA_VARIAN = 14,
DATA_GARROSH = 15,
DATA_FIZZLEBANG = 16,
DATA_FACTION_CHAMPIONS = 17,
DATA_CRUSADERS_CHEST = 18,
DATA_COLISEUM_FLOOR = 19,
DATA_MAIN_GATE = 20,
DATA_EAST_PORTCULLIS = 21,
DATA_WEB_DOOR = 22,
DATA_TRIBUTE_CHEST = 23,
DATA_BEASTS_COMBAT_STALKER = 24,
DATA_FURIOUS_CHARGE = 25,
DATA_DESPAWN_SNOBOLDS = 26,
DATA_TEAM = 27,
DATA_LICH_KING_VOICE = 28,
TYPE_COUNTER = 29,
TYPE_EVENT = 30,
TYPE_EVENT_TIMER = 101,
TYPE_EVENT_NPC = 102,
TYPE_NORTHREND_BEASTS = 103,
DATA_SNOBOLD_COUNT = 301,
DATA_MISTRESS_OF_PAIN_COUNT = 302,
INCREASE = 501,
DECREASE = 502
};
enum TCRSpellIds
{
SPELL_WILFRED_PORTAL = 68424,
SPELL_OPEN_PORTAL = 67864,
SPELL_JARAXXUS_CHAINS = 67924,
SPELL_DESTROY_FLOOR_KNOCKUP = 68193,
SPELL_ARTHAS_PORTAL = 51807,
SPELL_LK_FROST_NOVA = 68198,
SPELL_CORPSE_TELEPORT = 69016
};
enum TCRMisc
{
DESPAWN_TIME = 1200000,
PLAYER_VEHICLE_ID = 444
};
enum TCRActions
{
ACTION_START_GORMOK = 1,
ACTION_START_GORMOK_FAIL,
ACTION_START_JORMUNGARS,
ACTION_START_ICEHOWL,
ACTION_NORTHREND_BEASTS_WIPE,
ACTION_NORTHREND_BEASTS_DEFEATED,
ACTION_START_JARAXXUS_EVENT,
ACTION_KILL_JARAXXUS,
ACTION_JARAXXUS_DEFEATED,
ACTION_START_CHAMPIONS,
ACTION_SUMMON_CHAMPIONS,
ACTION_TIRION_ALLOW,
ACTION_CHAMPIONS_DEFEATED,
ACTION_SUMMON_JARAXXUS,
ACTION_JARAXXUS_INTRO,
ACTION_START_VALKYR,
ACTION_START_LK_EVENT,
ACTION_SAY_KILLED_PLAYER,
ACTION_VALKYR_DEFEATED,
ACTION_LK_EVENT_FINISHED,
ACTION_JARAXXUS_ENGAGE,
ACTION_START_CHAMPIONS_ENGAGE,
ACTION_START_VALKYR_ENGAGE,
ACTION_JARAXXUS_WIPE,
ACTION_FACTION_WIPE,
ACTION_VALKYR_WIPE
};
extern Position const ToCCommonLoc[];
extern Position const AnubarakLoc[];
enum TCRWorldStateIds
{
UPDATE_STATE_UI_SHOW = 4390,
UPDATE_STATE_UI_COUNT = 4389
};
enum NorthrendBeasts
{
GORMOK_IN_PROGRESS = 1000,
GORMOK_DONE = 1001,
SNAKES_IN_PROGRESS = 2000,
DREADSCALE_SUBMERGED = 2001,
ACIDMAW_SUBMERGED = 2002,
SNAKES_SPECIAL = 2003,
SNAKES_DONE = 2004,
ICEHOWL_IN_PROGRESS = 3000,
ICEHOWL_DONE = 3001
};
enum TCRCreatureIds
{
NPC_BARRETT_BEASTS = 34816,
NPC_BARRETT_BEASTS_HC = 35909,
NPC_BARRETT_JARAXXUS = 35035,
NPC_BARRETT_FACTION = 35766,
NPC_BARRETT_VALKYR = 35770,
NPC_BARRETT_LK = 35771,
NPC_TIRION_FORDRING = 34996,
NPC_TIRION_FORDRING_ANUBARAK = 36095,
NPC_ARGENT_MAGE = 36097,
NPC_FIZZLEBANG = 35458,
NPC_GARROSH = 34995,
NPC_VARIAN = 34990,
NPC_LICH_KING = 35877,
NPC_THRALL = 34994,
NPC_PROUDMOORE = 34992,
NPC_WILFRED_PORTAL = 17965,
NPC_PURPLE_GROUND = 35651,
NPC_ICEHOWL = 34797,
NPC_GORMOK = 34796,
NPC_DREADSCALE = 34799,
NPC_ACIDMAW = 35144,
NPC_BEASTS_COMBAT_STALKER = 36549,
NPC_FURIOUS_CHARGE_STALKER = 35062,
NPC_SNOBOLD_VASSAL = 34800,
NPC_JARAXXUS = 34780,
NPC_CHAMPIONS_CONTROLLER = 34781,
NPC_ALLIANCE_DEATH_KNIGHT = 34461,
NPC_ALLIANCE_DRUID_BALANCE = 34460,
NPC_ALLIANCE_DRUID_RESTORATION = 34469,
NPC_ALLIANCE_HUNTER = 34467,
NPC_ALLIANCE_MAGE = 34468,
NPC_ALLIANCE_PALADIN_HOLY = 34465,
NPC_ALLIANCE_PALADIN_RETRIBUTION = 34471,
NPC_ALLIANCE_PRIEST_DISCIPLINE = 34466,
NPC_ALLIANCE_PRIEST_SHADOW = 34473,
NPC_ALLIANCE_ROGUE = 34472,
NPC_ALLIANCE_SHAMAN_ENHANCEMENT = 34463,
NPC_ALLIANCE_SHAMAN_RESTORATION = 34470,
NPC_ALLIANCE_WARLOCK = 34474,
NPC_ALLIANCE_WARRIOR = 34475,
NPC_HORDE_DEATH_KNIGHT = 34458,
NPC_HORDE_DRUID_BALANCE = 34451,
NPC_HORDE_DRUID_RESTORATION = 34459,
NPC_HORDE_HUNTER = 34448,
NPC_HORDE_MAGE = 34449,
NPC_HORDE_PALADIN_HOLY = 34445,
NPC_HORDE_PALADIN_RETRIBUTION = 34456,
NPC_HORDE_PRIEST_DISCIPLINE = 34447,
NPC_HORDE_PRIEST_SHADOW = 34441,
NPC_HORDE_ROGUE = 34454,
NPC_HORDE_SHAMAN_ENHANCEMENT = 34455,
NPC_HORDE_SHAMAN_RESTORATION = 34444,
NPC_HORDE_WARLOCK = 34450,
NPC_HORDE_WARRIOR = 34453,
NPC_FJOLA_LIGHTBANE = 34497,
NPC_EYDIS_DARKBANE = 34496,
NPC_DARK_ESSENCE = 34567,
NPC_LIGHT_ESSENCE = 34568,
NPC_LICH_KING_VOICE = 16980,
NPC_ARTHAS_PORTAL = 22517,
NPC_ANUBARAK = 34564
};
enum TCRGameObjectIds
{
GO_CRUSADERS_CACHE_10 = 195631,
GO_CRUSADERS_CACHE_25 = 195632,
GO_CRUSADERS_CACHE_10_H = 195633,
GO_CRUSADERS_CACHE_25_H = 195635,
// Tribute Chest (heroic)
// 10-man modes
GO_TRIBUTE_CHEST_10H_25 = 195668, // 10man 01-24 attempts
GO_TRIBUTE_CHEST_10H_45 = 195667, // 10man 25-44 attempts
GO_TRIBUTE_CHEST_10H_50 = 195666, // 10man 45-49 attempts
GO_TRIBUTE_CHEST_10H_99 = 195665, // 10man 50 attempts
// 25-man modes
GO_TRIBUTE_CHEST_25H_25 = 195672, // 25man 01-24 attempts
GO_TRIBUTE_CHEST_25H_45 = 195671, // 25man 25-44 attempts
GO_TRIBUTE_CHEST_25H_50 = 195670, // 25man 45-49 attempts
GO_TRIBUTE_CHEST_25H_99 = 195669, // 25man 50 attempts
GO_ARGENT_COLISEUM_FLOOR = 195527, //20943
GO_MAIN_GATE_DOOR = 195647,
GO_EAST_PORTCULLIS = 195648,
GO_WEB_DOOR = 195485,
GO_PORTAL_TO_DALARAN = 195682
};
enum TCRAchievementData
{
// Northrend Beasts
UPPER_BACK_PAIN_10_PLAYER = 11779,
UPPER_BACK_PAIN_10_PLAYER_HEROIC = 11802,
UPPER_BACK_PAIN_25_PLAYER = 11780,
UPPER_BACK_PAIN_25_PLAYER_HEROIC = 11801,
// Lord Jaraxxus
THREE_SIXTY_PAIN_SPIKE_10_PLAYER = 11838,
THREE_SIXTY_PAIN_SPIKE_10_PLAYER_HEROIC = 11861,
THREE_SIXTY_PAIN_SPIKE_25_PLAYER = 11839,
THREE_SIXTY_PAIN_SPIKE_25_PLAYER_HEROIC = 11862,
// Tribute
A_TRIBUTE_TO_SKILL_10_PLAYER = 12344,
A_TRIBUTE_TO_SKILL_25_PLAYER = 12338,
A_TRIBUTE_TO_MAD_SKILL_10_PLAYER = 12347,
A_TRIBUTE_TO_MAD_SKILL_25_PLAYER = 12341,
A_TRIBUTE_TO_INSANITY_10_PLAYER = 12349,
A_TRIBUTE_TO_INSANITY_25_PLAYER = 12343,
A_TRIBUTE_TO_IMMORTALITY_HORDE = 12358,
A_TRIBUTE_TO_IMMORTALITY_ALLIANCE = 12359,
A_TRIBUTE_TO_DEDICATED_INSANITY = 12360,
REALM_FIRST_GRAND_CRUSADER = 12350,
// Dummy spells - not existing in dbc but we don't need that
SPELL_WORMS_KILLED_IN_10_SECONDS = 68523,
SPELL_CHAMPIONS_KILLED_IN_MINUTE = 68620,
SPELL_DEFEAT_FACTION_CHAMPIONS = 68184,
SPELL_TRAITOR_KING = 68186,
// Timed events
EVENT_START_TWINS_FIGHT = 21853
};
template <class AI, class T>
inline AI* GetTrialOfTheCrusaderAI(T* obj)
{
return GetInstanceAI<AI>(obj, ToCrScriptName);
}
#define RegisterTrialOfTheCrusaderCreatureAI(ai_name) RegisterCreatureAIWithFactory(ai_name, GetTrialOfTheCrusaderAI)
#endif
| 0 | 0.775979 | 1 | 0.775979 | game-dev | MEDIA | 0.994189 | game-dev | 0.768758 | 1 | 0.768758 |
magefree/mage | 2,979 | Mage.Sets/src/mage/cards/c/ColossalGrowth.java | package mage.cards.c;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.condition.common.KickedCondition;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.continuous.BoostTargetEffect;
import mage.abilities.effects.common.continuous.GainAbilityTargetEffect;
import mage.abilities.keyword.HasteAbility;
import mage.abilities.keyword.KickerAbility;
import mage.abilities.keyword.TrampleAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.target.common.TargetCreaturePermanent;
import mage.target.targetpointer.FixedTarget;
/**
*
* @author weirddan455
*/
public final class ColossalGrowth extends CardImpl {
public ColossalGrowth(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{1}{G}");
// Kicker {R}
this.addAbility(new KickerAbility("{R}"));
// Target creature gets +3/+3 until end of turn. If this spell was kicked, instead that creature gets +4/+4 and gains trample and haste until end of turn.
this.getSpellAbility().addEffect(new ColossalGrowthEffect());
this.getSpellAbility().addTarget(new TargetCreaturePermanent());
}
private ColossalGrowth(final ColossalGrowth card) {
super(card);
}
@Override
public ColossalGrowth copy() {
return new ColossalGrowth(this);
}
}
class ColossalGrowthEffect extends OneShotEffect {
ColossalGrowthEffect() {
super(Outcome.BoostCreature);
this.staticText = "Target creature gets +3/+3 until end of turn. If this spell was kicked, instead that creature gets +4/+4 and gains trample and haste until end of turn.";
}
private ColossalGrowthEffect(final ColossalGrowthEffect effect) {
super(effect);
}
@Override
public ColossalGrowthEffect copy() {
return new ColossalGrowthEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Permanent permanent = game.getPermanent(source.getFirstTarget());
if (permanent == null) {
return false;
}
if (KickedCondition.ONCE.apply(game, source)) {
game.addEffect(new BoostTargetEffect(4, 4)
.setTargetPointer(new FixedTarget(permanent, game)), source);
game.addEffect(new GainAbilityTargetEffect(TrampleAbility.getInstance())
.setTargetPointer(new FixedTarget(permanent, game)), source);
game.addEffect(new GainAbilityTargetEffect(HasteAbility.getInstance())
.setTargetPointer(new FixedTarget(permanent, game)), source);
} else {
game.addEffect(new BoostTargetEffect(3, 3)
.setTargetPointer(new FixedTarget(permanent, game)), source);
}
return true;
}
}
| 0 | 0.894609 | 1 | 0.894609 | game-dev | MEDIA | 0.953194 | game-dev | 0.9845 | 1 | 0.9845 |
chsami/Microbot | 16,856 | runelite-client/src/main/java/net/runelite/client/plugins/microbot/questhelper/helpers/quests/atfirstlight/AtFirstLight.java | /*
* Copyright (c) 2024, Zoinkwiz <https://github.com/Zoinkwiz>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.microbot.questhelper.helpers.quests.atfirstlight;
import net.runelite.client.plugins.microbot.questhelper.collections.ItemCollections;
import net.runelite.client.plugins.microbot.questhelper.panel.PanelDetails;
import net.runelite.client.plugins.microbot.questhelper.questhelpers.BasicQuestHelper;
import net.runelite.client.plugins.microbot.questhelper.questinfo.QuestHelperQuest;
import net.runelite.client.plugins.microbot.questhelper.requirements.Requirement;
import net.runelite.client.plugins.microbot.questhelper.requirements.item.ItemRequirement;
import net.runelite.client.plugins.microbot.questhelper.requirements.item.ItemRequirements;
import net.runelite.client.plugins.microbot.questhelper.requirements.player.SkillRequirement;
import net.runelite.client.plugins.microbot.questhelper.requirements.quest.QuestRequirement;
import net.runelite.client.plugins.microbot.questhelper.requirements.util.LogicType;
import net.runelite.client.plugins.microbot.questhelper.requirements.var.VarbitRequirement;
import net.runelite.client.plugins.microbot.questhelper.requirements.zone.Zone;
import net.runelite.client.plugins.microbot.questhelper.requirements.zone.ZoneRequirement;
import net.runelite.client.plugins.microbot.questhelper.rewards.ExperienceReward;
import net.runelite.client.plugins.microbot.questhelper.rewards.QuestPointReward;
import net.runelite.client.plugins.microbot.questhelper.rewards.UnlockReward;
import net.runelite.client.plugins.microbot.questhelper.steps.*;
import net.runelite.api.QuestState;
import net.runelite.api.Skill;
import net.runelite.api.coords.WorldPoint;
import net.runelite.api.gameval.ItemID;
import net.runelite.api.gameval.NpcID;
import net.runelite.api.gameval.ObjectID;
import java.util.*;
import static net.runelite.client.plugins.microbot.questhelper.requirements.util.LogicHelper.and;
import static net.runelite.client.plugins.microbot.questhelper.requirements.util.LogicHelper.or;
public class AtFirstLight extends BasicQuestHelper
{
//Items Required
ItemRequirement needle, boxTrap, hammer, jerboaTail, jerboaTailOrBoxTrap, jerboaTail2OrBoxTrap;
// Items Recommended
ItemRequirement staminaPotion;
// Quest Items
ItemRequirement toyMouse, toyMouseWound, smoothLeaf, stickyLeaf, makeshiftPoultice, furSample, trimmedFur, foxsReport;
QuestStep talkToApatura, goDownTree, talkToVerity, talkToWolf, windUpToy, useToyOnKiko,
checkBed, returnToWolf, goUpTree, talkToFox, takeLeaf, takeSecondLeaf, catchJerboa, useTailOnLeaves,
returnToFox, talkToFoxAfterPoultice, talkToAtza, talkToAtzaAfterHandingFur, makeEquipmentPile, talkToAtzaForTrim,
returnToFoxAfterTrim, getReportFromFox, goDownTreeEnd, talkToVerityEnd, useJerboaTailOnBed, goUpTreeToFinishQuest,
talkToApaturaToFinishQuest;
QuestStep buyBoxTrap, takeNeedle, takeHammer;
//Zones
Zone guild;
Requirement inGuild, gotMouse, usedMouse, checkedBed, equipmentUsable, repairedEquipment, hadReport, handedInReport;
@Override
public Map<Integer, QuestStep> loadSteps()
{
Map<Integer, QuestStep> steps = new HashMap<>();
initializeRequirements();
setupConditions();
setupSteps();
// 9841 0->1?? Birb?
steps.put(0, talkToApatura);
ConditionalStep enterTree = new ConditionalStep(this, goDownTree);
ConditionalStep goTalkToVerity = enterTree.copy();
goTalkToVerity.addStep(inGuild, talkToVerity);
steps.put(1, goTalkToVerity);
ConditionalStep goTalkToWolf = enterTree.copy();
goTalkToWolf.addStep(inGuild, talkToWolf);
steps.put(2, goTalkToWolf);
ConditionalStep goDistractCat = enterTree.copy();
goDistractCat.addStep(and(inGuild, checkedBed), returnToWolf);
goDistractCat.addStep(and(inGuild, usedMouse), checkBed);
goDistractCat.addStep(and(inGuild, toyMouseWound), useToyOnKiko);
goDistractCat.addStep(and(inGuild, gotMouse), windUpToy);
goDistractCat.addStep(inGuild, talkToWolf);
steps.put(3, goDistractCat);
ConditionalStep goFindFox = new ConditionalStep(this, buyBoxTrap);
goFindFox.addStep(inGuild, goUpTree);
goFindFox.addStep(jerboaTail2OrBoxTrap, talkToFox);
steps.put(4, goFindFox);
ConditionalStep goMakePoultice = new ConditionalStep(this, takeLeaf);
goMakePoultice.addStep(and(makeshiftPoultice), returnToFox);
goMakePoultice.addStep(and(smoothLeaf, stickyLeaf, jerboaTail.quantity(2)), useTailOnLeaves);
goMakePoultice.addStep(and(smoothLeaf, stickyLeaf), catchJerboa);
goMakePoultice.addStep(smoothLeaf, takeSecondLeaf);
steps.put(5, goMakePoultice);
steps.put(6, talkToFoxAfterPoultice);
// You can get more fur even if some is in your bank
ConditionalStep bringAtzaFur = new ConditionalStep(this, talkToFoxAfterPoultice);
bringAtzaFur.addStep(furSample, talkToAtza);
steps.put(7, bringAtzaFur);
ConditionalStep goRepairEquipment = new ConditionalStep(this, talkToAtzaAfterHandingFur);
goRepairEquipment.addStep(repairedEquipment, talkToAtzaForTrim);
goRepairEquipment.addStep(and(equipmentUsable, hammer), makeEquipmentPile);
goRepairEquipment.addStep(equipmentUsable, takeHammer);
steps.put(8, goRepairEquipment);
ConditionalStep goWithTrimToFox = new ConditionalStep(this, talkToAtzaForTrim);
goWithTrimToFox.addStep(trimmedFur, returnToFoxAfterTrim);
steps.put(9, goWithTrimToFox);
ConditionalStep goToVerityWithReport = new ConditionalStep(this, talkToAtzaForTrim);
goToVerityWithReport.addStep(and(inGuild, trimmedFur, handedInReport, needle), useJerboaTailOnBed);
goToVerityWithReport.addStep(and(inGuild, trimmedFur, hadReport, needle), talkToVerityEnd);
goToVerityWithReport.addStep(and(trimmedFur, hadReport, needle), goDownTreeEnd);
goToVerityWithReport.addStep(and(trimmedFur, hadReport), takeNeedle);
goToVerityWithReport.addStep(trimmedFur, getReportFromFox);
steps.put(10, goToVerityWithReport);
ConditionalStep goFinishQuest = new ConditionalStep(this, talkToApaturaToFinishQuest);
goFinishQuest.addStep(inGuild, goUpTreeToFinishQuest);
steps.put(11, goFinishQuest);
return steps;
}
@Override
protected void setupZones()
{
guild = new Zone(new WorldPoint(1540, 9409, 0), new WorldPoint(1580, 9470, 0));
}
@Override
protected void setupRequirements()
{
// Required
needle = new ItemRequirement("Needle", ItemID.NEEDLE).isNotConsumed();
needle.canBeObtainedDuringQuest();
boxTrap = new ItemRequirement("Box trap", ItemID.HUNTING_BOX_TRAP).isNotConsumed();
boxTrap.setTooltip("You can buy one from Imia in the north of the Hunter Guild's surface area for 41gp.");
hammer = new ItemRequirement("Hammer", ItemCollections.HAMMER).isNotConsumed();
hammer.canBeObtainedDuringQuest();
jerboaTail = new ItemRequirement("Jerboa tail", ItemID.HUNTING_JERBOA_TAIL);
jerboaTail.canBeObtainedDuringQuest();
jerboaTailOrBoxTrap = new ItemRequirements(LogicType.OR, "Jerboa tail, or a box trap to get some", jerboaTail, boxTrap);
jerboaTail2OrBoxTrap = new ItemRequirements(LogicType.OR, "2 Jerboa tails, or a box trap to get some", jerboaTail.quantity(2), boxTrap);
// Recommended
staminaPotion = new ItemRequirement("Stamina potions", ItemCollections.STAMINA_POTIONS);
// Quest Items
toyMouse = new ItemRequirement("Toy mouse", ItemID.POH_TOY_MOUSE_UNWOUND);
toyMouseWound = new ItemRequirement("Toy mouse (wound)", ItemID.POH_TOY_MOUSE_WOUND);
smoothLeaf = new ItemRequirement("Smooth leaf", ItemID.AFL_LEAF1);
stickyLeaf = new ItemRequirement("Sticky leaf", ItemID.AFL_LEAF2);
makeshiftPoultice = new ItemRequirement("Makeshift poultice", ItemID.AFL_POULTICE);
furSample = new ItemRequirement("Fur sample", ItemID.AFL_FUR);
trimmedFur = new ItemRequirement("Trimmed fur", ItemID.AFL_FUR_PREPPED);
}
private void setupConditions()
{
inGuild = new ZoneRequirement(guild);
gotMouse = new VarbitRequirement(9843, 1);
usedMouse = new VarbitRequirement(9839, 1);
checkedBed = new VarbitRequirement(9837, 1);
// 9842 0->1, received pelt once
equipmentUsable = new VarbitRequirement(9840, 1);
repairedEquipment = new VarbitRequirement(9840, 2);
handedInReport = new VarbitRequirement(9836, 1);
foxsReport = new ItemRequirement("Fox's report", ItemID.AFL_REPORT).hideConditioned(handedInReport);
hadReport = or(foxsReport, handedInReport);
// Bed repaired, 9838 0->1
}
private void setupSteps()
{
talkToApatura = new NpcStep(this, NpcID.HG_APATURA, new WorldPoint(1554, 3033, 0),
"Talk to Guildmaster Apatura in the Hunter Guild, south-west of Civitas illa Fortis.");
talkToApatura.addDialogSteps("Can I help you with anything?", "Yes.");
goDownTree = new ObjectStep(this, ObjectID.HUNTERGUILD_STAIRS_DOWN01_COMBINED, new WorldPoint(1557, 3048, 0),
"Go down the stairs in the tree in the guild.");
talkToVerity = new NpcStep(this, NpcID.HG_VERITY, new WorldPoint(1559, 9464, 0),
"Talk to Guild Scribe Verity behind the bar.");
talkToWolf = new NpcStep(this, NpcID.HG_WOLF, new WorldPoint(1555, 9462, 0),
"Talk to Guild Hunter Wolf (Master), next to the bar.");
windUpToy = new DetailedQuestStep(this, "Wind up a toy mouse.", toyMouse.highlighted());
windUpToy.addIcon(ItemID.POH_TOY_MOUSE_WOUND);
useToyOnKiko = new NpcStep(this, NpcID.AFL_KIKO, new WorldPoint(1552, 9460, 0),
"Use the wound up toy mouse on Guild Hunter Kiko near the bar.", toyMouseWound.highlighted());
checkBed = new ObjectStep(this, ObjectID.AFL_CATBED_OP, new WorldPoint(1552, 9460, 0),
"Check the cat's bed.");
returnToWolf = new NpcStep(this, NpcID.HG_WOLF, new WorldPoint(1555, 9462, 0),
"Return to Guild Hunter Wolf (Master), next to the bar.");
goUpTree = new ObjectStep(this, ObjectID.HUNTERGUILD_STAIRS_UP01, new WorldPoint(1557, 9449, 0),
"Go back up the stairs.");
talkToFox = new NpcStep(this, NpcID.AFL_HUNTER_FOX, new WorldPoint(1623, 2982, 0),
"Talk to Guild Hunter Fox near the crevice south-east of the Hunter Guild.");
takeLeaf = new ObjectStep(this, ObjectID.AFL_BUSH1, new WorldPoint(1618, 2979, 0),
"Search the leafy bush south of the crevice for a smooth leaf.");
takeSecondLeaf = new ObjectStep(this, ObjectID.AFL_BUSH2, new WorldPoint(1673, 2992, 0),
"Search the rough-looking bush on the west side of the Locus Oasis.");
catchJerboa = new DetailedQuestStep(this, new WorldPoint(1664, 3003, 0),
"Catch two Embertailed Jerboa for their tails.", boxTrap.highlighted());
catchJerboa.addIcon(ItemID.HUNTING_BOX_TRAP);
useTailOnLeaves = new DetailedQuestStep(this, "Use the tails on the leaves.",
jerboaTail.highlighted(), smoothLeaf.highlighted());
returnToFox = new NpcStep(this, NpcID.AFL_HUNTER_FOX, new WorldPoint(1623, 2982, 0),
"Bring the poultice back to Guild Hunter Fox near the crevice.", makeshiftPoultice);
talkToFoxAfterPoultice = new NpcStep(this, NpcID.AFL_HUNTER_FOX, new WorldPoint(1623, 2982, 0),
"Talk to Guild Hunter Fox.");
talkToAtza = new NpcStep(this, NpcID.AFL_ATZA, new WorldPoint(1696, 3063, 0),
"Talk to Atza in one of the buildings outside Civitas illa Fortis' south wall, west of the general store.",
furSample);
talkToAtzaAfterHandingFur = new NpcStep(this, NpcID.AFL_ATZA, new WorldPoint(1696, 3063, 0),
"Talk to Atza in one of the buildings outside Civitas illa Fortis' south wall, west of the general store.");
talkToAtza.addSubSteps(talkToAtzaAfterHandingFur);
makeEquipmentPile = new ObjectStep(this, ObjectID.AFL_HOUSETRAP_MULTI, new WorldPoint(1697, 3063, 0),
"Set-up the pile of equipment next to Atza.", hammer);
talkToAtzaForTrim = new NpcStep(this, NpcID.AFL_ATZA, new WorldPoint(1696, 3063, 0),
"Talk to Atza again for some trimmed fur.");
returnToFoxAfterTrim = new NpcStep(this, NpcID.AFL_HUNTER_FOX, new WorldPoint(1623, 2982, 0),
"Return to Guild Hunter Fox near the crevice south-east of the Hunter Guild to get his report.", trimmedFur);
getReportFromFox = new NpcStep(this, NpcID.AFL_HUNTER_FOX, new WorldPoint(1623, 2982, 0),
"Return back to Fox to get his report.");
returnToFoxAfterTrim.addSubSteps(getReportFromFox);
goDownTreeEnd = new ObjectStep(this, ObjectID.HUNTERGUILD_STAIRS_DOWN01_COMBINED, new WorldPoint(1557, 3048, 0),
"Go down the stairs in the tree in the Hunters Guild.", foxsReport, trimmedFur, jerboaTail, needle);
talkToVerityEnd = new NpcStep(this, NpcID.HG_VERITY, new WorldPoint(1559, 9464, 0),
"Talk to Guild Scribe Verity behind the bar again.");
useJerboaTailOnBed = new ObjectStep(this, ObjectID.AFL_CATBED_OP, new WorldPoint(1552, 9460, 0),
"Use a jerboa tail on the cat bed.", jerboaTail.highlighted(), trimmedFur, needle);
useJerboaTailOnBed.addIcon(ItemID.HUNTING_JERBOA_TAIL);
goUpTreeToFinishQuest = new ObjectStep(this, ObjectID.HUNTERGUILD_STAIRS_UP01, new WorldPoint(1557, 9449, 0),
"Go back up the stairs and talk to Guildmaster Apatura to finish the quest.");
talkToApaturaToFinishQuest = new NpcStep(this, NpcID.HG_APATURA, new WorldPoint(1554, 3033, 0),
"Talk to Guildmaster Apatura to finish the quest.");
goUpTreeToFinishQuest.addSubSteps(talkToApaturaToFinishQuest);
buyBoxTrap = new NpcStep(this, NpcID.HG_MIXEDHIDE_SELLER, new WorldPoint(1562, 3060, 0),
"Get a box trap. You can buy one from Imia in the north of the Hunter Guild's surface for 41gp.");
buyBoxTrap.addWidgetHighlightWithItemIdRequirement(300, 16, ItemID.HUNTING_BOX_TRAP, true);
takeNeedle = new ItemStep(this, new WorldPoint(1566, 3035, 0),
"Take the needle in the Hunter Guild's surface area, in its south-east corner.", needle);
takeHammer = new ItemStep(this, new WorldPoint(1696, 3070, 0), "Take a hammer from the house north of Atza.", hammer);
}
@Override
public List<ItemRequirement> getItemRequirements()
{
return Arrays.asList(jerboaTail2OrBoxTrap, hammer, needle);
}
@Override
public List<ItemRequirement> getItemRecommended()
{
return List.of(staminaPotion);
}
@Override
public List<Requirement> getGeneralRequirements()
{
return List.of(
new SkillRequirement(Skill.HUNTER, 46),
new SkillRequirement(Skill.HERBLORE, 30),
new SkillRequirement(Skill.CONSTRUCTION, 27),
new QuestRequirement(QuestHelperQuest.CHILDREN_OF_THE_SUN, QuestState.FINISHED),
new QuestRequirement(QuestHelperQuest.EAGLES_PEAK, QuestState.FINISHED)
);
}
@Override
public QuestPointReward getQuestPointReward()
{
return new QuestPointReward(1);
}
@Override
public List<ExperienceReward> getExperienceRewards()
{
return List.of(
new ExperienceReward(Skill.HUNTER, 4500),
new ExperienceReward(Skill.CONSTRUCTION, 800),
new ExperienceReward(Skill.HERBLORE, 500)
);
}
@Override
public List<UnlockReward> getUnlockRewards()
{
return Collections.singletonList(new UnlockReward("Access to Master Tier Hunters' Rumours"));
}
@Override
public List<PanelDetails> getPanels()
{
List<PanelDetails> allSteps = new ArrayList<>();
allSteps.add(new PanelDetails("Helping out", List.of(
talkToApatura, goDownTree, talkToVerity, talkToWolf, windUpToy, useToyOnKiko,
checkBed, returnToWolf
)));
allSteps.add(new PanelDetails("On the hunt", List.of(
goUpTree, buyBoxTrap, talkToFox, takeLeaf, takeSecondLeaf, catchJerboa, useTailOnLeaves,
returnToFox, talkToFoxAfterPoultice
), jerboaTailOrBoxTrap));
allSteps.add(new PanelDetails("Bed repairs", List.of(
talkToAtza, takeHammer, makeEquipmentPile, talkToAtzaForTrim, returnToFoxAfterTrim, takeNeedle,
goDownTreeEnd, talkToVerityEnd, useJerboaTailOnBed, goUpTreeToFinishQuest
), hammer, needle, jerboaTail));
return allSteps;
}
}
| 0 | 0.924792 | 1 | 0.924792 | game-dev | MEDIA | 0.797398 | game-dev | 0.897924 | 1 | 0.897924 |
Vawlpe/BakuganDotC-decomp | 1,587 | src/TODO/FUN_089c8b30@089c8b30.c | #include "ULUS10536_MYTHREAD-MAIN.BIN.h"
void FUN_089c8b30(int param_1)
{
int iVar1;
undefined4 uVar2;
int iVar3;
int iVar4;
int iVar5;
iVar3 = *(int *)(param_1 + 0x24);
if (iVar3 < 1) {
if (-1 < iVar3) {
iVar3 = FUN_089c8844(*(undefined4 *)(param_1 + 0x14));
if (iVar3 < 2) {
*(int *)(param_1 + 0x24) = *(int *)(param_1 + 0x24) + 1;
return;
}
iVar3 = 0;
iVar4 = *(int *)(DAT_08ac5880 + 4);
iVar5 = 0;
if (0 < iVar4) {
do {
iVar1 = FUN_08a2fe1c(DAT_08ac5880,iVar3);
iVar3 = iVar3 + 1;
if (iVar1 == param_1) break;
iVar5 = iVar5 + 1;
} while (iVar3 < iVar4);
}
if (iVar5 != 0) {
return;
}
*(int *)(param_1 + 0x24) = *(int *)(param_1 + 0x24) + 1;
return;
}
}
else if (iVar3 < 2) {
iVar3 = FUN_089c2b10(*(undefined4 *)(param_1 + 0x14));
if (iVar3 == 0) {
FUN_089c29cc(*(undefined4 *)(param_1 + 0x14));
return;
}
uVar2 = FUN_089c2b48();
iVar3 = FUN_089c32e0(uVar2);
if (iVar3 == *(int *)(param_1 + 0x18)) {
*(int *)(param_1 + 0x24) = *(int *)(param_1 + 0x24) + 1;
return;
}
uVar2 = FUN_089c2b48(*(undefined4 *)(param_1 + 0x14));
iVar3 = FUN_089c357c(uVar2,*(undefined4 *)(param_1 + 0x18),*(undefined *)(param_1 + 0x1c),
*(undefined *)(param_1 + 0x29));
if (iVar3 == 0) {
return;
}
*(int *)(param_1 + 0x24) = *(int *)(param_1 + 0x24) + 1;
return;
}
*(undefined *)(param_1 + 0x28) = 1;
return;
}
| 0 | 0.566347 | 1 | 0.566347 | game-dev | MEDIA | 0.840679 | game-dev | 0.847938 | 1 | 0.847938 |
omni-compiler/omni-compiler | 154,119 | XcodeML-Exc-Tools/src/exc/xcalablemp/XMPtranslateLocalPragma.java | package exc.xcalablemp;
import exc.block.*;
import exc.object.*;
import exc.openmp.OMPpragma;
import java.util.*;
import xcodeml.util.XmOption;
public class XMPtranslateLocalPragma {
private XMPglobalDecl _globalDecl;
private boolean _all_profile = false;
private boolean _selective_profile = false;
private boolean doScalasca = false;
private boolean doTlog = false;
private XobjectDef currentDef;
private XMPgenSym tmpSym;
public XMPtranslateLocalPragma(XMPglobalDecl globalDecl) {
_globalDecl = globalDecl;
tmpSym = new XMPgenSym();
}
public void translate(FuncDefBlock def) {
FunctionBlock fb = def.getBlock();
currentDef = def.getDef();
// first, check static_desc
BlockIterator i = new topdownBlockIterator(fb);
for (i.init(); !i.end(); i.next()){
Block b = i.getBlock();
if (b.Opcode() == Xcode.XMP_PRAGMA){
String pragmaName = ((PragmaBlock)b).getPragma();
if (XMPpragma.valueOf(pragmaName) == XMPpragma.STATIC_DESC){
analyzeStaticDesc((PragmaBlock)b);
b.remove();
}
}
}
// first, skip tasks
for (i.init(); !i.end(); i.next()) {
Block b = i.getBlock();
if (b.Opcode() == Xcode.XMP_PRAGMA) {
PragmaBlock pb = (PragmaBlock)b;
try {
translatePragma(pb);
} catch (XMPexception e) {
XMP.error(pb.getLineNo(), e.getMessage());
}
}
}
// next, remove tasks
for (i.init(); !i.end(); i.next()){
Block b = i.getBlock();
if (b.Opcode() == Xcode.XMP_PRAGMA){
String pragmaName = ((PragmaBlock)b).getPragma();
if (XMPpragma.valueOf(pragmaName) == XMPpragma.TASKS){
b.replace(Bcons.COMPOUND(b.getBody()));
}
}
}
def.finalizeBlock();
}
private void translatePragma(PragmaBlock pb) throws XMPexception {
String pragmaName = pb.getPragma();
switch (XMPpragma.valueOf(pragmaName)) {
case NODES:
{ translateNodes(pb); break; }
case TEMPLATE:
{ translateTemplate(pb); break; }
case DISTRIBUTE:
{ translateDistribute(pb); break; }
case ALIGN:
{ translateAlign(pb); break; }
case SHADOW:
{ translateShadow(pb); break; }
case STATIC_DESC:
{ /* do nothing */ break; }
case TASK:
{ translateTask(pb); break; }
case TASKS:
{ translateTasks(pb); break; }
case LOOP:
{ translateLoop(pb,true); break; }
case REFLECT:
{ translateReflect(pb); break; }
case REDUCE_SHADOW:
{ translateReduceShadow(pb); break; }
case BARRIER:
{ translateBarrier(pb); break; }
case REDUCTION:
{ translateReduction(pb); break; }
case BCAST:
{ translateBcast(pb); break; }
case GMOVE:
{ translateGmove(pb); break; }
case ARRAY:
{ translateArray(pb); break; }
case POST:
{ translatePost(pb); break; }
case WAIT:
{ translateWait(pb); break; }
case LOCK:
{ translateLockUnlock(pb, "_XMP_lock_"); break; }
case UNLOCK:
{ translateLockUnlock(pb, "_XMP_unlock_"); break; }
case LOCAL_ALIAS:
{ translateLocalAlias(pb); break; }
case WAIT_ASYNC:
{ translateWaitAsync(pb); break; }
case TEMPLATE_FIX:
{ translateTemplateFix(pb); break; }
case REFLECT_INIT:
{ translateReflectInit(pb); break; }
case REFLECT_DO:
{ translateReflectDo(pb); break; }
case GPU_REPLICATE:
{ translateGpuData(pb); break; }
case GPU_REPLICATE_SYNC:
{ translateGpuSync(pb); break; }
case GPU_REFLECT:
{ translateGpuReflect(pb); break; }
case GPU_BARRIER:
{ break; }
case GPU_LOOP:
{ translateGpuLoop(pb); break; }
default:
throw new XMPexception("'" + pragmaName.toLowerCase() + "' directive is not supported yet");
}
}
private void addProfileFunctions(Xobject profileClause, Block funcCallBlock, String directiveName, PragmaBlock pb) throws XMPexception{
boolean isProfile = false;
if(profileClause != null)
if(profileClause.Opcode() == Xcode.VAR && profileClause.getName() == "profile")
isProfile = true;
isProfile = isProfile && _selective_profile;
if(_all_profile || isProfile){
if(doScalasca == true){
String lowerName = directiveName.toLowerCase();
XobjList profileFuncArgs = Xcons.List(Xcons.StringConstant("#xmp " + lowerName + ":" + pb.getLineNo()));
funcCallBlock.insert(createScalascaStartProfileCall(profileFuncArgs));
funcCallBlock.add(createScalascaEndProfileCall(profileFuncArgs));
}
else if(doTlog == true){
String upperName = directiveName.toUpperCase();
funcCallBlock.insert(createTlogMacroInvoke("_XMP_M_TLOG_" + upperName + "_IN", null));
funcCallBlock.add(createTlogMacroInvoke("_XMP_M_TLOG_" + upperName + "_OUT", null));
}
}
else if(isProfile && doTlog == false){
funcCallBlock.insert(createScalascaProfileOffCall(null));
funcCallBlock.add(createScalascaProfileOnfCall(null));
}
}
private void translateNodes(PragmaBlock pb) throws XMPexception {
checkDeclPragmaLocation(pb);
XobjList nodesDecl = (XobjList)pb.getClauses();
XobjList nodesNameList = (XobjList)nodesDecl.getArg(0);
XobjList nodesDeclCopy = (XobjList)nodesDecl.copy();
Iterator<Xobject> iter = nodesNameList.iterator();
while (iter.hasNext()) {
Xobject x = iter.next();
nodesDeclCopy.setArg(0, x);
XMPnodes.translateNodes(nodesDeclCopy, _globalDecl, true, pb);
}
}
private void translateTemplate(PragmaBlock pb) throws XMPexception {
checkDeclPragmaLocation(pb);
XobjList templateDecl = (XobjList)pb.getClauses();
XobjList templateNameList = (XobjList)templateDecl.getArg(0);
XobjList templateDeclCopy = (XobjList)templateDecl.copy();
Iterator<Xobject> iter = templateNameList.iterator();
while (iter.hasNext()) {
Xobject x = iter.next();
templateDeclCopy.setArg(0, x);
XMPtemplate.translateTemplate(templateDeclCopy, _globalDecl, true, pb);
}
}
private void translateTemplateFix(PragmaBlock pb) throws XMPexception
{
XobjList templateDecl = (XobjList)pb.getClauses();
XobjList templateNameList = (XobjList)templateDecl.getArg(1);
XobjList templateDeclCopy = (XobjList)templateDecl.copy();
Iterator<Xobject> iter = templateNameList.iterator();
while (iter.hasNext()) {
Xobject x = iter.next();
templateDeclCopy.setArg(1, x);
XMPtemplate.translateTemplateFix(templateDeclCopy, _globalDecl, pb);
}
}
private void translateReflectInit(PragmaBlock pb) throws XMPexception
{
XobjList funcArgs = (XobjList)pb.getClauses().getArg(0);
XobjList widthList = (XobjList)pb.getClauses().getArg(1);
XobjList acc_or_host1 = (XobjList)pb.getClauses().getArg(2);
XobjList acc_or_host2 = (XobjList)pb.getClauses().getArg(3);
BlockList funcBody = Bcons.emptyBody();
boolean isHost = false;
boolean isAcc = false;
if(acc_or_host1.Nargs() == 0 && acc_or_host2.Nargs() == 0){
isHost = true;
}
else{
if(acc_or_host1.Nargs() != 0){
if(acc_or_host1.getArg(0).getName() == "acc"){
isAcc = true;
}
else if(acc_or_host1.getArg(0).getName() == "host"){
isHost = true;
}
}
if(acc_or_host2.Nargs() != 0){
if(acc_or_host2.getArg(0).getName() == "acc"){
isAcc = true;
}
else if(acc_or_host2.getArg(0).getName() == "host"){
isHost = true;
}
}
}
if(isHost){
XMP.fatal("reflect_init for host has been not developed yet.");
}
Ident funcIdAcc = _globalDecl.declExternFunc("_XMP_reflect_init_acc");
// if(widthList.Nargs() != 0){
// XMP.fatal("width clause in reflect_init has been not developed yet.");
// }
XobjList args = Xcons.List();
args.add(Xcons.String("USE_DEVICE"));
for(int i=0;i<funcArgs.Nargs();i++){
Xobject array = funcArgs.getArg(i);
String arrayName = array.getString();
Ident arrayId = _globalDecl.findVarIdent(XMP.ADDR_PREFIX_ + arrayName);
args.add(Xcons.List(arrayId.Ref()));
XMPalignedArray alignedArray = _globalDecl.getXMPalignedArray(arrayName, pb);
if(alignedArray == null){
XMP.fatal(arrayName + " is not aligned.");
}
if(!alignedArray.hasShadow()){
XMP.fatal(arrayName + " is not shadowed.");
}
for (int j = 0; j < widthList.Nargs(); j++){
XobjList width = (XobjList)widthList.getArg(j);
// Here the stride means the periodic flag.
// check wheter the shadow is full.
if (width.getArg(2).getInt() == 1 && alignedArray.getShadowAt(j).getType() == XMPshadow.SHADOW_FULL){
throw new XMPexception("Periodic reflect cannot be specified for a dimension with full shadow.");
}
Ident funcId = _globalDecl.declExternFunc("_XMP_set_reflect_acc__");
XobjList setFuncArgs = Xcons.List(alignedArray.getDescId().Ref(), Xcons.IntConstant(j),
width.getArg(0), width.getArg(1), width.getArg(2));
funcBody.add(Bcons.Statement(funcId.Call(setFuncArgs)));
}
Ident arrayDesc = _globalDecl.findVarIdent(XMP.DESC_PREFIX_ + arrayName);
funcBody.add(Bcons.Statement(funcIdAcc.Call(Xcons.List(array, arrayDesc.Ref()))));
}
Block funcCallBlock = Bcons.PRAGMA(Xcode.ACC_PRAGMA, "HOST_DATA", (Xobject)Xcons.List(args), funcBody);
pb.replace(funcCallBlock);
}
private void translateReflectDo(PragmaBlock pb) throws XMPexception
{
XobjList funcArgs = (XobjList)pb.getClauses().getArg(0);
XobjList acc_or_host1 = (XobjList)pb.getClauses().getArg(1);
XobjList acc_or_host2 = (XobjList)pb.getClauses().getArg(2);
boolean isHost = false;
boolean isAcc = false;
if(acc_or_host1.Nargs() == 0 && acc_or_host2.Nargs() == 0){
isHost = true;
}
else{
if(acc_or_host1.Nargs() != 0){
if(acc_or_host1.getArg(0).getName() == "acc"){
isAcc = true;
}
else if(acc_or_host1.getArg(0).getName() == "host"){
isHost = true;
}
}
if(acc_or_host2.Nargs() != 0){
if(acc_or_host2.getArg(0).getName() == "acc"){
isAcc = true;
}
else if(acc_or_host2.getArg(0).getName() == "host"){
isHost = true;
}
}
}
if(isHost){
XMP.fatal("reflect_do for host has been not developed yet.");
}
Ident funcIdAcc = _globalDecl.declExternFunc("_XMP_reflect_do_acc");
Block funcBody = Bcons.emptyBlock();
for(int i=0;i<funcArgs.Nargs();i++){
Xobject array = funcArgs.getArg(i);
String arrayName = array.getString();
XMPalignedArray alignedArray = _globalDecl.getXMPalignedArray(arrayName, pb);
if(alignedArray == null){
XMP.fatal(arrayName + " is not aligned.");
}
if(!alignedArray.hasShadow()){
XMP.fatal(arrayName + " is not shadowed.");
}
Ident arrayDesc = _globalDecl.findVarIdent(XMP.DESC_PREFIX_ + arrayName);
funcBody.add(funcIdAcc.Call(Xcons.List(arrayDesc.Ref())));
}
pb.replace(funcBody);
}
private void translateDistribute(PragmaBlock pb) throws XMPexception {
checkDeclPragmaLocation(pb);
XobjList distributeDecl = (XobjList)pb.getClauses();
XobjList distributeNameList = (XobjList)distributeDecl.getArg(0);
XobjList distributeDeclCopy = (XobjList)distributeDecl.copy();
Iterator<Xobject> iter = distributeNameList.iterator();
while (iter.hasNext()) {
Xobject x = iter.next();
distributeDeclCopy.setArg(0, x);
XMPtemplate.translateDistribute(distributeDeclCopy, _globalDecl, true, pb);
}
}
private void translateAlign(PragmaBlock pb) throws XMPexception {
checkDeclPragmaLocation(pb);
XobjList alignDecl = (XobjList)pb.getClauses();
XobjList alignNameList = (XobjList)alignDecl.getArg(0);
XobjList alignSubscriptList = (XobjList)alignDecl.getArg(3);
XobjList alignSubscriptVarList = (XobjList)alignSubscriptList.left();
Xobject structVar = null;
if(alignDecl.Nargs() == 5)
structVar = alignDecl.getArg(4).getArg(0);
String kind_bracket = alignSubscriptList.getTail().getString();
boolean isSquare = kind_bracket.equals("SQUARE");
alignSubscriptList.removeLastArgs(); // Remove information of ROUND or SQUARE
if(isSquare) alignSubscriptVarList.reverse();
XobjList alignDeclCopy = (XobjList)alignDecl.copy();
Iterator<Xobject> iter = alignNameList.iterator();
while (iter.hasNext()) {
Xobject x = iter.next();
alignDeclCopy.setArg(0, x);
XMPalignedArray.translateAlign(alignDeclCopy, _globalDecl, true, pb, structVar);
}
}
private void translateLockUnlock(PragmaBlock pb, String funcNamePrefix) throws XMPexception {
XobjList lockDecl = (XobjList)pb.getClauses();
XobjList lockObjVar = (XobjList)lockDecl.getArg(0);
String coarrayName = XMPutil.getXobjSymbolName(lockObjVar.getArg(0));
XMPcoarray coarray = _globalDecl.getXMPcoarray(coarrayName);
if(coarray == null)
throw new XMPexception("Variable in #pragma xmp lock() must be coarray");
// When lockDecl.Nargs() is 1,
// The specified lock object does not have a codimension.
// e.g.) #pragma xmp lock(lock_obj)
int imageDims = 0;
if(lockDecl.Nargs() != 1)
imageDims = lockDecl.getArg(1).Nargs();
if(imageDims != 0)
if(lockDecl.getArg(1).Nargs() != coarray.getImageDim())
throw new XMPexception("Invalid number of dimensions of '" + coarrayName + "'");
// Set descriptor of lock object
XobjList funcArgs = Xcons.List();
funcArgs.add(Xcons.SymbolRef(coarray.getDescId()));
// Set offset
// e.g. xmp_lock_t lockobj[a][b][c]:[*]; #pragma xmp lock(lockobj[3][2][1]:[x]) -> offset = 3*b*c + 2*c + 1
int arrayDims = lockObjVar.Nargs() - 1;
Xobject offset = null;
for(int i=0;i<arrayDims;i++){
Xobject tmp = lockObjVar.getArg(i+1);
for(int j=i+1;j<arrayDims;j++){
tmp = Xcons.binaryOp(Xcode.MUL_EXPR, tmp, Xcons.IntConstant((int)coarray.getSizeAt(j)));
}
if(offset == null)
offset = tmp;
else
offset = Xcons.binaryOp(Xcode.PLUS_EXPR, offset, tmp);
}
if(offset == null)
funcArgs.add(Xcons.IntConstant(0));
else
funcArgs.add(offset);
if(imageDims != 0)
for(int i=0;i<lockDecl.getArg(1).Nargs();i++)
funcArgs.add(lockDecl.getArg(1).getArg(i));
String funcName = funcNamePrefix + String.valueOf(imageDims);
pb.replace(_globalDecl.createFuncCallBlock(funcName, funcArgs));
}
private void translatePost(PragmaBlock pb) throws XMPexception {
checkDeclPragmaLocation(pb);
XobjList args = null;
XobjList postDecl = (XobjList)pb.getClauses();
XMPsymbolTable localXMPsymbolTable = XMPlocalDecl.declXMPsymbolTable(pb);
XobjList onRef = (XobjList)postDecl.getArg(0);
String nodeName = onRef.getArg(0).getString();
XMPnodes nodeObj = _globalDecl.getXMPnodes(nodeName, pb);
if(nodeObj == null){
throw new XMPexception("cannot find '" + nodeName + "' nodes");
}
args = Xcons.List(nodeObj.getDescId().Ref());
XobjList nodeList = (XobjList)onRef.getArg(1);
String kind_bracket = nodeList.getTail().getString();
boolean isSquare = kind_bracket.equals("SQUARE");
nodeList.removeLastArgs(); // Remove information of ROUND or SQUARE
if(isSquare) nodeList.reverse();
if(nodeObj.getDim() != nodeList.Nargs()){
throw new XMPexception("Error. Dimension of node is different.");
}
String funcName = "_XMP_post_" + String.valueOf(nodeObj.getDim());
for(int i=0;i<nodeObj.getDim();i++){
Xobject v = nodeList.getArg(i).getArg(0);
if(isSquare)
v = Xcons.binaryOp(Xcode.PLUS_EXPR, v, Xcons.IntConstant(1));
args.add(v);
}
Xobject tag = postDecl.getArg(1);
args.add(tag);
pb.replace(_globalDecl.createFuncCallBlock(funcName, args));
}
private void translateWait(PragmaBlock pb) throws XMPexception {
checkDeclPragmaLocation(pb);
XobjList waitDecl = (XobjList)pb.getClauses();
int numOfArgs = waitDecl.Nargs();
// no arguments
if(numOfArgs == 0){
pb.replace(_globalDecl.createFuncCallBlock("_XMP_wait_noargs", null));
return;
}
// only node
XobjList onRef = (XobjList)waitDecl.getArg(0);
String nodeName = onRef.getArg(0).getString();
XobjList nodeList = (XobjList)onRef.getArg(1);
XMPnodes nodeObj = _globalDecl.getXMPnodes(nodeName, pb);
String funcName = null;
XobjList args = Xcons.List(nodeObj.getDescId().Ref());
String kind_bracket = nodeList.getTail().getString();
boolean isSquare = kind_bracket.equals("SQUARE");
nodeList.removeLastArgs(); // Remove information of ROUND or SQUARE
if(isSquare) nodeList.reverse();
if(nodeObj == null){
throw new XMPexception("cannot find '" + nodeName + "' nodes");
}
if(nodeObj.getDim() != nodeList.Nargs()){
throw new XMPexception("Error. Dimension of node is different.");
}
for(int i=0;i<nodeObj.getDim();i++){
Xobject v = nodeList.getArg(i);
if(isSquare)
v = Xcons.binaryOp(Xcode.PLUS_EXPR, v, Xcons.IntConstant(1));
args.add(v);
}
if(numOfArgs == 1){
funcName = "_XMP_wait_node_" + String.valueOf(nodeObj.getDim());
pb.replace(_globalDecl.createFuncCallBlock(funcName, args));
return;
}
// node and tag
if(numOfArgs == 2){ // node and tag
funcName = "_XMP_wait_" + String.valueOf(nodeObj.getDim());
Xobject tag = waitDecl.getArg(1);
args.add(tag);
pb.replace(_globalDecl.createFuncCallBlock(funcName, args));
return;
}
}
private void translateLocalAlias(PragmaBlock pb) throws XMPexception {
checkDeclPragmaLocation(pb);
XMPalignedArray.translateLocalAlias((XobjList)pb.getClauses(), _globalDecl, true, pb);
}
private void translateWaitAsync(PragmaBlock pb) throws XMPexception {
Ident funcId = _globalDecl.declExternFunc("_XMP_wait_async__");
XobjList funcArgs = (XobjList)pb.getClauses().getArg(0);
BlockList funcBody = Bcons.emptyBody();
for(Xobject i: funcArgs){
funcBody.add(Bcons.Statement(funcId.Call(Xcons.List(i))));
}
Block funcCallBlock = Bcons.COMPOUND(funcBody);
// the following code comes from translateBcast.
XobjList onRef = (XobjList)pb.getClauses().getArg(1);
if(onRef != null && onRef.getArgs() != null){
XMPquadruplet<String, Boolean, XobjList, XMPobject> execOnRefArgs = createExecOnRefArgs(onRef, pb);
String execFuncSurfix = execOnRefArgs.getFirst();
boolean splitComm = execOnRefArgs.getSecond().booleanValue();
XobjList execFuncArgs = execOnRefArgs.getThird();
if (splitComm) {
BlockList waitAsyncBody = Bcons.blockList(funcCallBlock);
funcCallBlock = createCommTaskBlock(waitAsyncBody, execFuncSurfix, execFuncArgs);
}
}
BlockList bl = funcCallBlock.getBody();
for(Xobject i: funcArgs){
bl.add(_globalDecl.declExternFunc("xmpc_end_async").Call(Xcons.List(i)));
}
pb.replace(funcCallBlock);
}
private void translateShadow(PragmaBlock pb) throws XMPexception {
checkDeclPragmaLocation(pb);
XobjList shadowDecl = (XobjList)pb.getClauses();
XobjList shadowNameList = (XobjList)shadowDecl.getArg(0);
XobjList shadowDeclCopy = (XobjList)shadowDecl.copy();
Iterator<Xobject> iter = shadowNameList.iterator();
while (iter.hasNext()) {
Xobject x = iter.next();
shadowDeclCopy.setArg(0, x);
XMPshadow.translateShadow(shadowDeclCopy, _globalDecl, true, pb, null);
}
}
private void translateReflect(PragmaBlock pb) throws XMPexception {
XobjList accOrHost = (XobjList)pb.getClauses().getArg(3);
boolean isACC = accOrHost.hasIdent("acc");
Block reflectFuncCallBlock = XMPshadow.translateReflect(pb, _globalDecl, isACC);
Xobject profileClause = pb.getClauses().getArg(4);
addProfileFunctions(profileClause, reflectFuncCallBlock, "reflect", pb);
}
private void translateReduceShadow(PragmaBlock pb) throws XMPexception {
XobjList accOrHost = (XobjList)pb.getClauses().getArg(3);
boolean isACC = accOrHost.hasIdent("acc");
Block reflectFuncCallBlock = XMPshadow.translateReduceShadow(pb, _globalDecl, isACC);
Xobject profileClause = pb.getClauses().getArg(4);
addProfileFunctions(profileClause, reflectFuncCallBlock, "reflect", pb);
}
static Block encloseWithAccHostDataDirective(Block block, XobjList useDeviceClauseArgs) throws XMPexception {
if(useDeviceClauseArgs == null || useDeviceClauseArgs.isEmpty()){
throw new XMPexception("empty argument for use_device clause");
}
return Bcons.PRAGMA(
Xcode.ACC_PRAGMA,
"HOST_DATA",
Xcons.List(Xcons.List(Xcons.String("USE_DEVICE"), useDeviceClauseArgs)),
Bcons.blockList(block));
}
private void translateGpuData(PragmaBlock pb) throws XMPexception {
XMPgpuData.translateGpuData(pb, _globalDecl);
}
private void translateGpuSync(PragmaBlock pb) throws XMPexception {
XMPgpuData.translateGpuSync(pb, _globalDecl);
}
private void translateGpuReflect(PragmaBlock pb) throws XMPexception {
if (!XmOption.isXcalableMPGPU()) {
XMP.warning("use -enable-gpu option to enable 'acc relfect' directive");
translateReflect(pb);
}
else {
XMPshadow.translateGpuReflect(pb, _globalDecl);
}
}
private void translateGpuLoop(PragmaBlock pb) throws XMPexception {
XobjList loopDecl = (XobjList)pb.getClauses();
BlockList loopBody = pb.getBody();
if (!XmOption.isXcalableMPGPU()) {
XMP.warning("use -enable-gpu option to use 'acc loop' directive");
pb.replace(Bcons.COMPOUND(loopBody));
return;
}
// get block to schedule
CforBlock schedBaseBlock = getOutermostLoopBlock(loopBody);
// analyze loop
XobjList loopIterList = (XobjList)loopDecl.getArg(0);
XobjList onRef = (XobjList)loopDecl.getArg(1);
XobjList onRefIterList = (XobjList)onRef.getArg(1);
if(loopIterList == null || loopIterList.Nargs() == 0)
loopIterList = XMPutil.getLoopIterListFromOnRef(onRefIterList);
translateMultipleLoop(pb, schedBaseBlock, loopIterList);
// translate
// FIXME implement reduction
Block newLoopBlock = translateGpuClause(pb, null, schedBaseBlock);
schedBaseBlock.replace(newLoopBlock);
// replace pragma
Block loopFuncCallBlock = Bcons.COMPOUND(loopBody);
pb.replace(loopFuncCallBlock);
}
private void analyzeFollowingGpuLoop(PragmaBlock pb, CforBlock schedBaseBlock) throws XMPexception {
// schedule loop
analyzeGpuLoop(pb, schedBaseBlock, schedBaseBlock);
}
private void analyzeMultipleGpuLoop(PragmaBlock pb, CforBlock schedBaseBlock) throws XMPexception {
// start translation
XobjList loopDecl = (XobjList)pb.getClauses();
BlockList loopBody = pb.getBody();
// iterate index variable list
XobjList loopVarList = (XobjList)loopDecl.getArg(0);
Vector<CforBlock> loopVector = new Vector<CforBlock>(XMPutil.countElmts(loopVarList));
for (XobjArgs i = loopVarList.getArgs(); i != null; i = i.nextArgs()) {
loopVector.add(findLoopBlock(loopBody, i.getArg().getString()));
}
// schedule loop
Iterator<CforBlock> it = loopVector.iterator();
while (it.hasNext()) {
CforBlock forBlock = it.next();
analyzeGpuLoop(pb, forBlock, schedBaseBlock);
}
}
private void analyzeGpuLoop(PragmaBlock pb, CforBlock forBlock, CforBlock schedBaseBlock) throws XMPexception {
Xobject loopIndex = forBlock.getInductionVar();
String loopIndexName = loopIndex.getSym();
Ident initId = declIdentWithBlock(schedBaseBlock,
"_XMP_loop_init_" + loopIndexName, Xtype.intType);
Ident condId = declIdentWithBlock(schedBaseBlock,
"_XMP_loop_cond_" + loopIndexName, Xtype.intType);
Ident stepId = declIdentWithBlock(schedBaseBlock,
"_XMP_loop_step_" + loopIndexName, Xtype.intType);
schedBaseBlock.insert(Xcons.Set(initId.Ref(), forBlock.getLowerBound()));
schedBaseBlock.insert(Xcons.Set(condId.Ref(), forBlock.getUpperBound()));
schedBaseBlock.insert(Xcons.Set(stepId.Ref(), forBlock.getStep()));
XMPutil.putLoopIter(schedBaseBlock, loopIndexName, Xcons.List(initId, condId, stepId));
}
private void translateTask(PragmaBlock pb) throws XMPexception {
// start translation
XobjList taskDecl = (XobjList)pb.getClauses();
XMPsymbolTable localXMPsymbolTable = XMPlocalDecl.declXMPsymbolTable(pb);
BlockList taskBody = pb.getBody();
// check if enclosed by TASKS
Block parentBlock = pb.getParentBlock();
boolean tasksFlag = false;
if (parentBlock != null && parentBlock.Opcode() == Xcode.XMP_PRAGMA){
String pragmaName = ((PragmaBlock)parentBlock).getPragma();
if (XMPpragma.valueOf(pragmaName) == XMPpragma.TASKS){
tasksFlag = true;
}
}
boolean nocomm_flag = (((XobjInt)taskDecl.getArg(1)).getInt() == 1);
// create function arguments
XobjList onRef = (XobjList)taskDecl.getArg(0);
XMPquadruplet<String, Boolean, XobjList, XMPobject> execOnRefArgs = createExecOnRefArgs(onRef, pb);
String execFuncSuffix = execOnRefArgs.getFirst();
if (nocomm_flag) execFuncSuffix = execFuncSuffix + "_nocomm";
XobjList execFuncArgs = execOnRefArgs.getThird();
XMPobject onRefObject = execOnRefArgs.getForth();
// setup task finalizer
if (!nocomm_flag){
Ident finFuncId = _globalDecl.declExternFunc("_XMP_pop_nodes");
setupFinalizer(taskBody, finFuncId, null);
}
// create function call
BlockList taskFuncCallBlockList = Bcons.emptyBody();
Ident taskDescId = null;
if(!nocomm_flag){
if(tasksFlag == true){
taskDescId = parentBlock.getBody().declLocalIdent(tmpSym.getStr("_XMP_TASK_desc"),
Xtype.voidPtrType, StorageClass.AUTO,
Xcons.Cast(Xtype.voidPtrType,
Xcons.IntConstant(0)));
}
else {
taskDescId = taskFuncCallBlockList.declLocalIdent(tmpSym.getStr("_XMP_TASK_desc"),
Xtype.voidPtrType, StorageClass.AUTO,
Xcons.Cast(Xtype.voidPtrType,
Xcons.IntConstant(0)));
}
execFuncArgs.cons(taskDescId.getAddr());
}
Ident execFuncId = _globalDecl.declExternFunc("_XMP_exec_task_" + execFuncSuffix, Xtype.intType);
Block taskFuncCallBlock;
if (tasksFlag == true){
Ident flag = parentBlock.getBody().declLocalIdent(tmpSym.getStr("_XMP_is_member"),
Xtype.intType);
parentBlock.getBody().insert(Xcons.Set(flag.Ref(), execFuncId.Call(execFuncArgs)));
taskFuncCallBlock = Bcons.IF(BasicBlock.Cond(flag.Ref()), taskBody, null);
}
else {
taskFuncCallBlock = Bcons.IF(BasicBlock.Cond(execFuncId.Call(execFuncArgs)),
taskBody, null);
}
taskFuncCallBlockList.add(taskFuncCallBlock);
pb.replace(Bcons.COMPOUND(taskFuncCallBlockList));
if (!nocomm_flag){
XobjList arg = Xcons.List(Xcode.POINTER_REF, taskDescId.Ref());
taskFuncCallBlockList.add(_globalDecl.createFuncCallBlock("_XMP_exec_task_NODES_FINALIZE", arg));
}
Xobject profileClause = taskDecl.getArg(3);
addProfileFunctions(profileClause, taskFuncCallBlock, "task", pb);
}
private void translateTasks(PragmaBlock pb) {
// do nothing here
}
private void translateLoop(PragmaBlock pb, boolean isFromTranslateLoop) throws XMPexception {
XobjList loopDecl = (XobjList)pb.getClauses();
BlockList loopBody = pb.getBody();
Block newBlock = null;
XobjList expandOpt = (XobjList)loopDecl.getArg(5);
if (expandOpt == null || expandOpt.hasNullArg() || expandOpt.isEmptyList()){
;
}
else if (expandOpt.getArg(0).getInt() == LOOP_MARGIN){
newBlock = divideMarginLoop(pb);
}
else if (expandOpt.getArg(0).getInt() == LOOP_PEEL_AND_WAIT){
newBlock = peelLoop(pb);
}
if (newBlock != null){
pb.replace(newBlock);
Block next;
for (Block b = newBlock.getBody().getHead(); b != null; b = next){
next = b.getNext();
if (b instanceof PragmaBlock)
translatePragma((PragmaBlock)b);
}
return;
}
// get block to schedule
CforBlock schedBaseBlock = getOutermostLoopBlock(loopBody);
// schedule loop
XobjList loopIterList = (XobjList)loopDecl.getArg(0);
XobjList onRef = (XobjList)loopDecl.getArg(1);
XobjList onRefIterList = (XobjList)onRef.getArg(1);
String kind_bracket = onRefIterList.getTail().getString();
boolean isSquare = kind_bracket.equals("SQUARE");
onRefIterList.removeLastArgs(); // Remove information of ROUND or SQUARE
if(isFromTranslateLoop){
loopIterList.removeLastArgs(); // Remove information of ROUND or SQUARE
if(isSquare) onRefIterList.reverse();
}
if(loopIterList == null || loopIterList.Nargs() == 0)
loopIterList = XMPutil.getLoopIterListFromOnRef(onRefIterList);
translateMultipleLoop(pb, schedBaseBlock, loopIterList);
// translate reduction clause
XobjList reductionRefList = (XobjList)loopDecl.getArg(2);
if (reductionRefList != null && reductionRefList.Nargs() > 0) {
XobjList schedVarList = null;
if (loopDecl.getArg(0) == null) {
schedVarList = Xcons.List(Xcons.String(schedBaseBlock.getInductionVar().getSym()));
}
else {
schedVarList = (XobjList)loopIterList.copy();
}
BlockList reductionBody = createReductionClauseBody(pb, reductionRefList, schedBaseBlock);
schedBaseBlock.getParentBlock().add(createReductionClauseBlock(pb, reductionBody, schedVarList));
}
// translate multicore clause
XobjList multicoreClause = (XobjList)loopDecl.getArg(3);
if (multicoreClause != null && multicoreClause.Nargs() > 0) {
String devName = multicoreClause.getArg(0).getString();
if (devName.equals("acc")) {
if (XmOption.isXcalableMPGPU()) {
Block newLoopBlock = translateGpuClause(pb, reductionRefList, schedBaseBlock);
schedBaseBlock.replace(newLoopBlock);
}
else {
XMP.warning("use '-enable-gpu' compiler option to use gpu clause");
}
}
else if (devName.equals("threads")) {
if (XmOption.isXcalableMPthreads()) {
XobjList devArgs = (XobjList)multicoreClause.getArg(1);
Block newLoopBlock = translateThreadsClauseToOMPpragma(devArgs, reductionRefList, schedBaseBlock, loopIterList);
schedBaseBlock.replace(newLoopBlock);
}
else {
XMP.warning("use '-enable-threads' compiler option to use 'threads' clause");
}
}
else {
throw new XMPexception("unknown clause in loop directive");
}
}
// rewrite array refs in loop
topdownXobjectIterator iter = new topdownXobjectIterator(getLoopBody(schedBaseBlock).toXobject());
for (iter.init(); !iter.end(); iter.next())
XMPrewriteExpr.rewriteArrayRefInLoop(iter.getXobject(), _globalDecl, schedBaseBlock, loopBody, loopIterList);
// replace pragma
Block loopFuncCallBlock = Bcons.COMPOUND(loopBody);
pb.replace(loopFuncCallBlock);
// add function calls for profiling
Xobject profileClause = null;
if (loopDecl.Nargs() > 4)
profileClause = loopDecl.getArg(4);
addProfileFunctions(profileClause, loopFuncCallBlock, "loop", pb);
}
// XXX only supports C language
private Block translateGpuClause(PragmaBlock pb, XobjList reductionRefList,
CforBlock loopBlock) throws XMPexception {
Ident funcId = _globalDecl.declExternIdent(_globalDecl.genSym(XMP.GPU_FUNC_PREFIX),
Xtype.Function(Xtype.voidType));
XobjList funcArgs = setupGPUparallelFunc(funcId, loopBlock, pb);
return _globalDecl.createFuncCallBlock(funcId.getName(), funcArgs);
}
private XobjList setupGPUparallelFunc(Ident funcId, CforBlock loopBlock, PragmaBlock pb) throws XMPexception {
XobjList loopVarList = (XobjList)((XobjList)(pb.getClauses())).getArg(0);
XobjList newLoopVarList = setupGpuLoopBlock(Xcons.List(loopBlock.findVarIdent(loopBlock.getInductionVar().getSym())),
loopVarList, loopBlock.getBody().getHead());
// get params
XobjList paramIdList = getGPUfuncParams(loopBlock, pb);
// setup & decompile GPU function body
XMPgpuDecompiler.decompile(funcId, paramIdList, getXMPalignedArrays(loopBlock),
loopBlock, newLoopVarList, pb, _globalDecl.getEnv());
// generate func args
XobjList funcArgs = Xcons.List();
for (XobjArgs i = paramIdList.getArgs(); i != null; i = i.nextArgs()) {
Ident paramId = (Ident)i.getArg();
String paramName = paramId.getName();
XMPgpuData gpuData = XMPgpuDataTable.findXMPgpuData(paramId.getName(), loopBlock);
if (gpuData == null) {
if (paramId.Type().isArray()) {
throw new XMPexception("array '" + paramName + "' should be declared as a gpuData");
} else {
funcArgs.add(paramId.Ref());
}
} else {
XMPalignedArray alignedArray = gpuData.getXMPalignedArray();
funcArgs.add(gpuData.getDeviceAddrId().Ref());
}
}
return funcArgs;
}
private XobjList setupGpuLoopBlock(XobjList newLoopVarList, XobjList loopVarList, Block b) throws XMPexception {
switch (b.Opcode()) {
case FOR_STATEMENT:
{
CforBlock loopBlock = (CforBlock)b;
if (!loopBlock.isCanonical()) {
loopBlock.Canonicalize();
}
Block bodyBlock = b.getBody().getHead();
String loopVarName = loopBlock.getInductionVar().getSym();
if (XMPutil.hasElmt(loopVarList, loopVarName)) {
newLoopVarList.insert(b.findVarIdent(loopVarName));
b.getParentBlock().setBody(loopBlock.getBody());
}
return setupGpuLoopBlock(newLoopVarList, loopVarList, bodyBlock);
}
case COMPOUND_STATEMENT:
return setupGpuLoopBlock(newLoopVarList, loopVarList, b.getBody().getHead());
default:
return newLoopVarList;
}
}
private ArrayList<XMPalignedArray> getXMPalignedArrays(CforBlock loopBlock) throws XMPexception {
ArrayList<XMPalignedArray> alignedArrayList = new ArrayList<XMPalignedArray>();
XobjList arrayNameList = Xcons.List();
BasicBlockExprIterator iter = new BasicBlockExprIterator(loopBlock.getBody());
for (iter.init(); !iter.end(); iter.next()) {
Xobject expr = iter.getExpr();
topdownXobjectIterator exprIter = new topdownXobjectIterator(expr);
for (exprIter.init(); !exprIter.end(); exprIter.next()) {
Xobject x = exprIter.getXobject();
switch (x.Opcode()) {
case ARRAY_REF:
{
String varName = x.getArg(0).getSym();
if (!XMPutil.hasElmt(arrayNameList, varName)) {
arrayNameList.add(Xcons.String(varName));
XMPgpuData gpuData = XMPgpuDataTable.findXMPgpuData(varName, loopBlock);
if (gpuData == null) {
throw new XMPexception("array '" + varName + "' shoud be declared as a gpuData");
} else {
XMPalignedArray alignedArray = gpuData.getXMPalignedArray();
if (alignedArray != null) {
alignedArrayList.add(alignedArray);
}
}
}
} break;
default:
}
}
}
return alignedArrayList;
}
private XobjList getGPUfuncParams(CforBlock loopBlock, PragmaBlock pb) throws XMPexception {
XobjList params = Xcons.List();
XobjList loopVars = Xcons.List();
BasicBlockExprIterator iter = new BasicBlockExprIterator(loopBlock.getBody());
for (iter.init(); !iter.end(); iter.next()) {
Xobject expr = iter.getExpr();
topdownXobjectIterator exprIter = new topdownXobjectIterator(expr);
for (exprIter.init(); !exprIter.end(); exprIter.next()) {
Xobject x = exprIter.getXobject();
switch (x.Opcode()) {
case VAR:
{
String varName = x.getName();
if (!(XMPutil.hasIdent(params, varName) ||
XMPutil.hasElmt(loopVars, varName))) {
XobjList loopIter = XMPutil.getLoopIter(loopBlock, varName);
if (loopIter == null) {
Ident id = loopBlock.findVarIdent(varName);
if (id != null) {
params.add(Ident.Param(varName, id.Type()));
}
} else {
loopVars.add(Xcons.String(varName));
}
}
} break;
case ARRAY_REF:
{
String varName = x.getArg(0).getSym();
if (!XMPutil.hasIdent(params, varName)) {
XMPgpuData gpuData = XMPgpuDataTable.findXMPgpuData(varName, loopBlock);
if (gpuData == null) {
throw new XMPexception("array '" + varName + "' shoud be declared as a gpuData");
} else {
XMPalignedArray alignedArray = gpuData.getXMPalignedArray();
if (alignedArray == null) {
Ident id = loopBlock.findVarIdent(varName);
params.add(Ident.Param(varName, id.Type()));
} else {
Xtype alignedArrayParamType = null;
if (alignedArray.realloc()) {
alignedArrayParamType = alignedArray.getAddrId().Type();
} else {
alignedArrayParamType = alignedArray.getArrayId().Type();
}
params.add(Ident.Param(varName, alignedArrayParamType));
params.add(Ident.Param(XMP.GPU_DEVICE_DESC_PREFIX_ + varName, Xtype.voidPtrType));
}
}
}
} break;
default:
}
}
}
// FIXME consider the order
XobjList loopIndexList = (XobjList)pb.getClauses().getArg(0);
for (Xobject loopIndex : loopIndexList) {
XobjList loopIter = XMPutil.getLoopIter(loopBlock, loopIndex.getName());
Ident initId = (Ident)loopIter.getArg(0);
params.add(Ident.Param(initId.getName(), initId.Type()));
Ident condId = (Ident)loopIter.getArg(1);
params.add(Ident.Param(condId.getName(), condId.Type()));
Ident stepId = (Ident)loopIter.getArg(2);
params.add(Ident.Param(stepId.getName(), stepId.Type()));
}
return params;
}
private Block createOMPpragmaBlock(OMPpragma pragma, Xobject args, Block body) {
return Bcons.PRAGMA(Xcode.OMP_PRAGMA, pragma.toString(), args, Bcons.blockList(body));
}
private Block translateThreadsClauseToOMPpragma(XobjList threadsClause, XobjList reductionRefList,
CforBlock loopBlock, XobjList loopIterList) throws XMPexception {
Xobject parallelClause = Xcons.statementList();
XobjList forClause = Xcons.List();
if (threadsClause != null) {
for (Xobject c : threadsClause) {
OMPpragma p = OMPpragma.valueOf(c.getArg(0));
switch (p) {
case DATA_PRIVATE:
case DATA_FIRSTPRIVATE:
case DATA_LASTPRIVATE:
{
compile_THREADS_name_list(c.getArg(1));
forClause.add(c);
} break;
case DIR_NUM_THREADS:
case DIR_IF:
parallelClause.add(c);
break;
default:
throw new XMPexception("unknown threads clause");
}
}
}
// FIXME compare loopIterList with private, firstprivate var list
if (loopIterList != null) {
String schedLoopIterName = loopBlock.getInductionVar().getSym();
XobjList privateList = Xcons.List();
XobjList firstPrivateList = Xcons.List();
Iterator<Xobject> iter = loopIterList.iterator();
while (iter.hasNext()) {
Xobject x = iter.next();
String iterName = x.getName();
if (!iterName.equals(schedLoopIterName)) {
privateList.add(Xcons.Symbol(Xcode.IDENT, iterName));
firstPrivateList.add(Xcons.Symbol(Xcode.IDENT, "_XMP_loop_init_" + iterName));
firstPrivateList.add(Xcons.Symbol(Xcode.IDENT, "_XMP_loop_cond_" + iterName));
firstPrivateList.add(Xcons.Symbol(Xcode.IDENT, "_XMP_loop_step_" + iterName));
}
}
forClause.add(Xcons.List(Xcode.LIST, Xcons.String(OMPpragma.DATA_PRIVATE.toString()), privateList));
forClause.add(Xcons.List(Xcode.LIST, Xcons.String(OMPpragma.DATA_FIRSTPRIVATE.toString()), firstPrivateList));
}
addReductionClauseToOMPclause(forClause, reductionRefList);
return createOMPpragmaBlock(OMPpragma.PARALLEL, parallelClause,
createOMPpragmaBlock(OMPpragma.FOR, forClause,
loopBlock));
}
private void addReductionClauseToOMPclause(XobjList OMPclause, XobjList reductionRefList) throws XMPexception {
if (reductionRefList == null) {
return;
}
for (Xobject c : reductionRefList) {
OMPpragma redOp = null;
XobjInt reductionOp = (XobjInt)c.getArg(0);
switch (reductionOp.getInt()) {
case XMPcollective.REDUCE_SUM:
redOp = OMPpragma.DATA_REDUCTION_PLUS;
break;
case XMPcollective.REDUCE_MINUS:
redOp = OMPpragma.DATA_REDUCTION_MINUS;
break;
case XMPcollective.REDUCE_PROD:
redOp = OMPpragma.DATA_REDUCTION_MUL;
break;
case XMPcollective.REDUCE_BAND:
redOp = OMPpragma.DATA_REDUCTION_BITAND;
break;
case XMPcollective.REDUCE_LAND:
redOp = OMPpragma.DATA_REDUCTION_LOGAND;
break;
case XMPcollective.REDUCE_BOR:
redOp = OMPpragma.DATA_REDUCTION_BITOR;
break;
case XMPcollective.REDUCE_LOR:
redOp = OMPpragma.DATA_REDUCTION_LOGOR;
break;
case XMPcollective.REDUCE_BXOR:
redOp = OMPpragma.DATA_REDUCTION_BITXOR;
break;
case XMPcollective.REDUCE_LXOR:
case XMPcollective.REDUCE_MAX:
case XMPcollective.REDUCE_MIN:
case XMPcollective.REDUCE_FIRSTMAX:
case XMPcollective.REDUCE_FIRSTMIN:
case XMPcollective.REDUCE_LASTMAX:
case XMPcollective.REDUCE_LASTMIN:
throw new XMPexception("the operation cannot be translated to OpenMP clause");
default:
throw new XMPexception("unknown reduction operation");
}
XobjList redVarList = Xcons.List();
for (Xobject x : (XobjList)c.getArg(1)) {
redVarList.add(Xcons.Symbol(Xcode.IDENT, x.getArg(0).getName()));
}
OMPclause.add(omp_pg_list(redOp, redVarList));
}
}
private Xobject omp_pg_list(OMPpragma pg, Xobject args) {
return Xcons.List(Xcode.LIST, Xcons.String(pg.toString()), args);
}
// XXX not implemented yet, check variables
private void compile_THREADS_name_list(Xobject name_list) throws XMPexception {
if (name_list == null) {
return;
}
}
private Block createReductionClauseBlock(PragmaBlock pb, BlockList reductionBody, XobjList schedVarList) throws XMPexception {
XobjList loopDecl = (XobjList)pb.getClauses();
XobjList onRef = (XobjList)loopDecl.getArg(1);
String onRefObjName = onRef.getArg(0).getString();
XobjList subscriptList = (XobjList)onRef.getArg(1);
XMPsymbolTable localXMPsymbolTable = XMPlocalDecl.declXMPsymbolTable(pb);
XMPobject onRefObj = _globalDecl.getXMPobject(onRefObjName, pb);
if (onRefObj == null) {
throw new XMPexception("cannot find '" + onRefObjName + "' nodes/template");
}
String initFuncSuffix = null;
switch (onRefObj.getKind()) {
case XMPobject.TEMPLATE:
initFuncSuffix = "TEMPLATE";
break;
case XMPobject.NODES:
initFuncSuffix = "NODES";
break;
default:
throw new XMPexception("unknown object type");
}
// create function arguments
XobjList initFuncArgs = Xcons.List(onRefObj.getDescId().Ref());
boolean initComm = false;
for (XobjArgs i = subscriptList.getArgs(); i != null; i = i.nextArgs()) {
String subscript = i.getArg().getString();
if (XMPutil.hasElmt(schedVarList, subscript)) {
initFuncArgs.add(Xcons.Cast(Xtype.intType, Xcons.IntConstant(0)));
}
else {
initComm = true;
initFuncArgs.add(Xcons.Cast(Xtype.intType, Xcons.IntConstant(1)));
}
}
if (initComm) {
// setup finalizer
Ident finFuncId = _globalDecl.declExternFunc("_XMP_pop_n_free_nodes");
setupFinalizer(reductionBody, finFuncId, null);
// create function call
Ident initFuncId = _globalDecl.declExternFunc("_XMP_init_reduce_comm_" + initFuncSuffix, Xtype.intType);
return Bcons.IF(BasicBlock.Cond(initFuncId.Call(initFuncArgs)), reductionBody, null);
}
else {
return Bcons.COMPOUND(reductionBody);
}
}
private void translateMultipleLoop(PragmaBlock pb, CforBlock schedBaseBlock,
XobjList loopVarList) throws XMPexception {
// start translation
XobjList loopDecl = (XobjList)pb.getClauses();
BlockList loopBody = pb.getBody();
Vector<CforBlock> loopVector = new Vector<CforBlock>(XMPutil.countElmts(loopVarList));
int num = 0;
for (XobjArgs i = loopVarList.getArgs(); i != null; i = i.nextArgs()) {
loopVector.add(findLoopBlock(loopBody, i.getArg().getString()));
num++;
}
// schedule loop
Iterator<CforBlock> it = loopVector.iterator();
ArrayList<String> iteraterList = new ArrayList<String>();
boolean[] isOmitSchedLoopFunc = new boolean[num];
int i = 0;
while (it.hasNext()) {
CforBlock forBlock = it.next();
isOmitSchedLoopFunc[i++] = scheduleLoop(pb, forBlock, schedBaseBlock, iteraterList);
}
it = loopVector.iterator();
i = 0;
while (it.hasNext()) {
CforBlock forBlock = it.next();
if(isOmitSchedLoopFunc[i++] == false)
insertScheduleIndexFunction(pb, forBlock, schedBaseBlock, iteraterList);
}
}
private final static int LOOP_EXPAND = 410;
private final static int LOOP_MARGIN = 411;
private final static int LOOP_PEEL_AND_WAIT = 412;
private final static int LOOP_NONE = 413;
private void insertScheduleIndexFunction(PragmaBlock pb, CforBlock forBlock, CforBlock schedBaseBlock,
ArrayList iteraterList) throws XMPexception {
XobjList loopDecl = (XobjList)pb.getClauses();
XMPsymbolTable localXMPsymbolTable = XMPlocalDecl.declXMPsymbolTable(schedBaseBlock);
Xobject onRef = loopDecl.getArg(1);
String onRefObjName = onRef.getArg(0).getString();
XMPobject onRefObj = _globalDecl.getXMPobject(onRefObjName, schedBaseBlock);
XMPtemplate templateObj = (XMPtemplate)onRefObj;
XobjList templateSubscriptList = (XobjList)onRef.getArg(1);
Xobject loopIndex = forBlock.getInductionVar();
String loopIndexName = loopIndex.getSym();
XobjList funcArgs = Xcons.List();
Xobject lb = forBlock.getLowerBound();
Xobject up = forBlock.getUpperBound();
Xobject step = forBlock.getStep();
funcArgs.add(lb);
funcArgs.add(up);
funcArgs.add(step);
Ident parallelInitId = declIdentWithBlock(schedBaseBlock, "_XMP_loop_init_" + loopIndexName, Xtype.intType);
Ident parallelCondId = declIdentWithBlock(schedBaseBlock, "_XMP_loop_cond_" + loopIndexName, Xtype.intType);
Ident parallelStepId = declIdentWithBlock(schedBaseBlock, "_XMP_loop_step_" + loopIndexName, Xtype.intType);
funcArgs.add(parallelInitId.getAddr());
funcArgs.add(parallelCondId.getAddr());
funcArgs.add(parallelStepId.getAddr());
XobjInt templateIndexArg = null;
int templateIndex = 0;
int distManner = 0;
String distMannerString = null;
for (XobjArgs i = templateSubscriptList.getArgs(); i != null; i = i.nextArgs()) {
String s = i.getArg().getString();
if (s.equals(loopIndexName)) {
templateIndexArg = Xcons.IntConstant(templateIndex);
distManner = templateObj.getDistMannerAt(templateIndex);
distMannerString = templateObj.getDistMannerStringAt(templateIndex);
}
templateIndex++;
}
funcArgs.add(templateObj.getDescId().Ref());
funcArgs.add(templateIndexArg);
//
// for EXPAND/MARGIN/PEEL_AND_WAIT
//
//if (distManner == XMPtemplate.BLOCK){
Xobject expandDecl = loopDecl.getArg(5);
int origLoopType, loopType;
Xobject asyncId;
Xobject expandList;
if (expandDecl != null && !expandDecl.isEmptyList()){
origLoopType = expandDecl.getArg(0).getInt();
if (origLoopType == LOOP_PEEL_AND_WAIT){
asyncId = expandDecl.getArg(1);
expandList = expandDecl.getArg(2);
}
else {
expandList = expandDecl.getArg(1);
}
int t_idx = templateIndexArg.getInt();
Xobject lwidth = expandList.getArg(t_idx).getArg(0);
Xobject uwidth = expandList.getArg(t_idx).getArg(1);;
Xobject unboundFlag = expandList.getArg(t_idx).getArg(2);
if (origLoopType == LOOP_MARGIN && unboundFlag.getInt() == -1){
loopType = LOOP_EXPAND;
}
else {
loopType = origLoopType;
}
funcArgs.add(Xcons.IntConstant(loopType));
funcArgs.add(lwidth);
funcArgs.add(uwidth);
funcArgs.add(unboundFlag);
}
else {
funcArgs.add(Xcons.IntConstant(LOOP_NONE));
funcArgs.add(Xcons.IntConstant(0));
funcArgs.add(Xcons.IntConstant(0));
funcArgs.add(Xcons.IntConstant(0));
}
// }
//Ident funcId = _globalDecl.declExternFunc("_XMP_sched_loop_template_" + distMannerString);
Ident funcId = _globalDecl.declExternFunc("xmpc_loop_sched");
int[] position = {iteraterList.size()};
boolean[] flag = {false, false, false};
String[] insertedIteraterList = new String[3];
flag[0] = getPositionInsertScheFuncion(lb, 0, position, iteraterList, insertedIteraterList);
flag[1] = getPositionInsertScheFuncion(up, 1, position, iteraterList, insertedIteraterList);
flag[2] = getPositionInsertScheFuncion(step, 2, position, iteraterList, insertedIteraterList);
if(position[0] == iteraterList.size()){
Block b = getOuterSchedPoint(schedBaseBlock);
b.insert(funcId.Call(funcArgs));
}
else{
if(flag[0]){
insertScheFuncion(lb, flag, position[0], 0, schedBaseBlock, funcArgs, templateObj,
funcId, iteraterList, insertedIteraterList);
}
if(flag[1]){
insertScheFuncion(up, flag, position[0], 1, schedBaseBlock, funcArgs, templateObj,
funcId, iteraterList, insertedIteraterList);
}
if(flag[2]){
insertScheFuncion(step, flag, position[0], 2, schedBaseBlock, funcArgs, templateObj,
funcId, iteraterList, insertedIteraterList);
}
}
}
private void insertScheFuncion(Xobject v, boolean[] flag, int position, int num, Block schedBaseBlock, XobjList funcArgs,
XMPtemplate templateObj, Ident funcId, ArrayList iteraterList, String[] insertedIteraterList) throws XMPexception {
//Block b = schedBaseBlock;
Block b = getOuterSchedPoint(schedBaseBlock);
for(int i=0;i<iteraterList.size()-position;i++){
b = b.getBody().getHead();
}
Xobject func = funcId.Call(funcArgs);
int loop_depth = 0;
String index = insertedIteraterList[num];
for(int i=0;i<iteraterList.size();i++){
if(iteraterList.get(i).toString().equals(index)){
loop_depth = i;
}
}
v = XMPrewriteExpr.calcLtoG(templateObj, loop_depth, v, _globalDecl);
funcArgs.setArg(num, v);
// Insert Function
if(num == 0){
b.insert(func);
return;
}
if(num == 1){
if(flag[0]){
return;
}
else{
b.insert(func);
}
return;
}
if(num == 2){
if(flag[0] || flag[1]){
return;
}
else{
b.insert(func);
}
return;
}
}
private boolean getPositionInsertScheFuncion(Xobject v, int num, int[] position, ArrayList iteraterList,
String[] insertedIteraterList) throws XMPexception {
if(v.Opcode() != Xcode.INT_CONSTANT){
XobjList vList = null;
if(v.isVariable() || v instanceof XobjConst){
vList = Xcons.List(v);
}
else{
vList = XobjArgs2XobjList(v, Xcons.List());
}
for (XobjArgs i = vList.getArgs(); i != null; i = i.nextArgs()) {
if(i.getArg().isVariable()){
for(int j=0;j<iteraterList.size();j++){
if(i.getArg().getSym().equals(iteraterList.get(j))){
if(position[0] > j){
position[0] = j;
}
insertedIteraterList[num] = iteraterList.get(j).toString();
return true;
}
}
}
}
}
return false;
}
private XobjList XobjArgs2XobjList(Xobject x, XobjList a){
for (XobjArgs i = x.getArgs(); i != null; i = i.nextArgs()) {
if(i.getArg().isBinaryOp()){
XobjArgs2XobjList(i.getArg(), a);
}
else{
a.add(i.getArg());
}
}
return a;
}
private BlockList createReductionClauseBody(PragmaBlock pb, XobjList reductionRefList,
CforBlock schedBaseBlock) throws XMPexception {
// create init block
Ident getRankFuncId = _globalDecl.declExternFunc("_XMP_get_execution_nodes_rank", Xtype.intType);
IfBlock reductionInitIfBlock = (IfBlock)Bcons.IF(BasicBlock.Cond(Xcons.binaryOp(Xcode.LOG_NEQ_EXPR, getRankFuncId.Call(null),
Xcons.IntConstant(0))), null, null);
// create function call
Iterator<Xobject> it = reductionRefList.iterator();
BlockList reductionBody = Bcons.emptyBody();
while (it.hasNext()) {
XobjList reductionRef = (XobjList)it.next();
Vector<XobjList> reductionFuncArgsList = createReductionArgsList(reductionRef, pb,
true, schedBaseBlock, reductionInitIfBlock);
String reductionFuncType = createReductionFuncType(reductionRef, pb, false);
reductionBody.add(createReductionFuncCallBlock(false, reductionFuncType + "_CLAUSE",
null, reductionFuncArgsList));
}
if (reductionInitIfBlock.getThenBody() != null) {
// schedBaseBlock.insert(reductionInitIfBlock); # 418
schedBaseBlock.getParentBlock().insert(reductionInitIfBlock);
}
return reductionBody;
}
private boolean scheduleLoop(PragmaBlock pb, CforBlock forBlock, CforBlock schedBaseBlock,
ArrayList<String> iteraterList) throws XMPexception {
XobjList loopDecl = (XobjList)pb.getClauses();
XMPsymbolTable localXMPsymbolTable = XMPlocalDecl.declXMPsymbolTable(schedBaseBlock);
// analyze <on-ref>
Xobject onRef = loopDecl.getArg(1);
String onRefObjName = onRef.getArg(0).getString();
XMPobject onRefObj = _globalDecl.getXMPobject(onRefObjName, schedBaseBlock);
if (onRefObj == null)
throw new XMPexception("cannot find '" + onRefObjName + "' nodes/template");
switch (onRefObj.getKind()) {
case XMPobject.TEMPLATE:
{
XMPtemplate onRefTemplate = (XMPtemplate)onRefObj;
if (!onRefTemplate.isDistributed()) {
throw new XMPexception("template '" + onRefObjName + "' is not distributed");
}
Xobject expandDecl = loopDecl.getArg(5);
boolean withExpand = (expandDecl != null && !expandDecl.isEmptyList());
return callLoopSchedFuncTemplate(onRefTemplate, (XobjList)onRef.getArg(1), forBlock, schedBaseBlock, iteraterList,
withExpand);
}
case XMPobject.NODES:
callLoopSchedFuncNodes((XMPnodes)onRefObj, (XobjList)onRef.getArg(1), forBlock, schedBaseBlock);
return false;
default:
throw new XMPexception("unknown object type");
}
}
private static Block getOuterSchedPoint(Block b){
Block bb = b.getParentBlock();
while (bb != null){
if (bb.Opcode() == Xcode.OMP_PRAGMA || bb.Opcode() == Xcode.ACC_PRAGMA) return bb;
bb = bb.getParentBlock();
}
return b;
}
private static CforBlock getOutermostLoopBlock(BlockList body) throws XMPexception {
Block b = body.getHead();
if (b != null) {
if (b.Opcode() == Xcode.FOR_STATEMENT) {
LineNo blockLnObj = b.getLineNo();
// XXX too strict?
if (b.getNext() != null) {
throw new XMPexception("only one loop statement is allowed in loop directive");
}
CforBlock forBlock = (CforBlock)b;
forBlock.Canonicalize();
if (forBlock.isCanonical()) {
return forBlock;
} else {
throw new XMPexception("loop statement is not canonical");
}
}
else if (b.Opcode() == Xcode.COMPOUND_STATEMENT ||
b.Opcode() == Xcode.OMP_PRAGMA ||
b.Opcode() == Xcode.ACC_PRAGMA) {
return getOutermostLoopBlock(b.getBody());
}
}
throw new XMPexception("cannot find the loop statement");
}
private static BlockList getLoopBody(Block b) throws XMPexception {
return b.getBody();
}
private static CforBlock findLoopBlock(BlockList body, String loopVarName) throws XMPexception {
Block b = body.getHead();
if (b != null) {
if (b.Opcode() == Xcode.LIST && // A linemarker is to be ignored.
b.getBasicBlock().getHead().getExpr().Opcode() == Xcode.LINEMARKER) b = b.getNext();
switch (b.Opcode()) {
case FOR_STATEMENT:
{
CforBlock forBlock = (CforBlock)b;
forBlock.Canonicalize();
if (!(forBlock.isCanonical())) {
throw new XMPexception("loop is not canonical");
}
if (forBlock.getInductionVar().getSym().equals(loopVarName)) {
return (CforBlock)b;
} else {
return findLoopBlock(forBlock.getBody(), loopVarName);
}
}
case COMPOUND_STATEMENT:
return findLoopBlock(b.getBody(), loopVarName);
case XMP_PRAGMA:
throw new XMPexception("reached to a xcalablemp directive");
case OMP_PRAGMA:
case ACC_PRAGMA:
return findLoopBlock(b.getBody(), loopVarName);
}
}
throw new XMPexception("cannot find the loop statement");
}
private int calcParallelCond(XMPtemplate t, int i, int manner) throws XMPexception
{
XMPnodes n = t.getOntoNodes();
int templateSize = XMPutil.foldIntConstant(t.getSizeAt(i)).getInt();
if(manner == XMPtemplate.DUPLICATION)
return templateSize;
int nodeIndex = t.getOntoNodesIndexAt(i).getInt();
int nodeSize = XMPutil.foldIntConstant(n.getSizeAt(nodeIndex)).getInt();
return templateSize/nodeSize;
}
private boolean is_parallelCondConstant(XMPtemplate t, CforBlock forBlock, int i, int manner) throws XMPexception
{
XMPnodes n = t.getOntoNodes();
if(n.isInherit() == true) return false;
if(manner == XMPtemplate.GBLOCK) return false;
if(! XMPutil.is_Constant(t.getSizeAt(i), i)) return false;
if(! XMPutil.is_Constant(forBlock.getUpperBound(), i)) return false;
if(manner != XMPtemplate.DUPLICATION){
int nodeIndex = t.getOntoNodesIndexAt(i).getInt();
if(! XMPutil.is_Constant(n.getSizeAt(nodeIndex), nodeIndex)) return false;
}
if(manner == XMPtemplate.BLOCK_CYCLIC)
if(! XMPutil.is_Constant(t.getWidthAt(i), i)) return false;
int templateSize = XMPutil.foldIntConstant(t.getSizeAt(i)).getInt();
Xobject forUpperObj = XMPutil.foldIntConstant(forBlock.getUpperBound());
int forUpperSize = -1;
if(forUpperObj.Opcode() == Xcode.INT_CONSTANT)
forUpperSize = forUpperObj.getInt();
else if(forUpperObj.Opcode() == Xcode.LONGLONG_CONSTANT)
forUpperSize = (int)forUpperObj.getLongLow();
if(templateSize != forUpperSize)
return false;
int blockSize = (manner == XMPtemplate.BLOCK_CYCLIC)? XMPutil.foldIntConstant(t.getWidthAt(i)).getInt() : 1;
if(manner == XMPtemplate.DUPLICATION){
return true;
}
else{
int nodeIndex = t.getOntoNodesIndexAt(i).getInt();
int nodeSize = XMPutil.foldIntConstant(n.getSizeAt(nodeIndex)).getInt();
if(templateSize%(nodeSize*blockSize) != 0)
return false;
}
return true;
}
private boolean callLoopSchedFuncTemplate(XMPtemplate templateObj, XobjList templateSubscriptList, CforBlock forBlock,
CforBlock schedBaseBlock, ArrayList<String> iteraterList,
boolean withExpand) throws XMPexception {
Xobject loopIndex = forBlock.getInductionVar();
String loopIndexName = loopIndex.getSym();
iteraterList.add(loopIndexName);
int templateIndex = 0;
int templateDim = templateObj.getDim();
XobjInt templateIndexArg = null;
int distManner = 0;
String distMannerString = null;
int targetIndex = 0;
for (XobjArgs i = templateSubscriptList.getArgs(); i != null; i = i.nextArgs()) {
if (templateIndex >= templateDim)
throw new XMPexception("wrong template dimensions, too many");
if (i.getArg() != null){
String s = i.getArg().getString();
if (s.equals(loopIndexName)) {
if (templateIndexArg != null) {
throw new XMPexception("loop index '" + loopIndexName + "' is already described");
}
templateIndexArg = Xcons.IntConstant(templateIndex);
distManner = templateObj.getDistMannerAt(templateIndex);
distMannerString = templateObj.getDistMannerStringAt(templateIndex);
targetIndex = templateIndex;
}
}
templateIndex++;
}
if(templateIndexArg == null)
throw new XMPexception("cannot find index '" + loopIndexName + "' reference in <on-ref>");
if(templateIndex != templateDim)
throw new XMPexception("wrong template dimensions, too few");
boolean isOmitSchedLoopFunc = true;
Xobject parallelInit;
if(!withExpand && forBlock.getLowerBound().equals(Xcons.IntConstant(0)))
parallelInit = Xcons.IntConstant(0);
else{
parallelInit = declIdentWithBlock(schedBaseBlock,
"_XMP_loop_init_" + loopIndexName, Xtype.intType).Ref();
isOmitSchedLoopFunc = false;
}
Xobject parallelCond;
if(templateObj.isFixed() && !withExpand &&
is_parallelCondConstant(templateObj, forBlock, targetIndex, distManner))
parallelCond = Xcons.IntConstant(calcParallelCond(templateObj, targetIndex, distManner));
else{
parallelCond = declIdentWithBlock(schedBaseBlock,
"_XMP_loop_cond_" + loopIndexName, Xtype.intType).Ref();
isOmitSchedLoopFunc = false;
}
Xobject parallelStep;
if(!withExpand && forBlock.getStep().equals(Xcons.IntConstant(1)))
parallelStep = Xcons.IntConstant(1);
else if(!withExpand && forBlock.getStep().equals(Xcons.IntConstant(-1)))
parallelStep = Xcons.IntConstant(-1);
else{
parallelStep = declIdentWithBlock(schedBaseBlock,
"_XMP_loop_step_" + loopIndexName, Xtype.intType).Ref();
isOmitSchedLoopFunc = false;
}
XMPutil.putLoopIter(schedBaseBlock, loopIndexName,
Xcons.List(parallelInit, parallelCond, parallelStep));
switch (distManner) {
case XMPtemplate.DUPLICATION:
case XMPtemplate.BLOCK:
case XMPtemplate.CYCLIC:
case XMPtemplate.BLOCK_CYCLIC:
case XMPtemplate.GBLOCK:
forBlock.setLowerBound(parallelInit);
forBlock.setUpperBound(parallelCond);
forBlock.setStep(parallelStep);
break;
default:
throw new XMPexception("unknown distribute manner");
}
// rewrite loop index in loop
BasicBlockExprIterator iter = new BasicBlockExprIterator(getLoopBody(forBlock));
for (iter.init(); !iter.end(); iter.next()) {
XMPrewriteExpr.rewriteLoopIndexInLoop(iter.getExpr(), loopIndexName,
templateObj, templateIndexArg.getInt(),
_globalDecl, forBlock);
}
// rewrite loop index in initializer in loop
BlockList body = getLoopBody(forBlock);
while(true){
for (Block b = body.getHead(); b != null; b = b.getNext()){
if (b.getBody() == null) continue;
topdownXobjectIterator iter_decl = new topdownXobjectIterator(b.getBody().getDecls());
for (iter_decl.init(); !iter_decl.end(); iter_decl.next()) {
int num = 0;
for (XobjArgs i = templateSubscriptList.getArgs(); i != null; i = i.nextArgs()) {
String indexName = i.getArg().getString();
XMPrewriteExpr.rewriteLoopIndexInLoop(iter_decl.getXobject(), indexName,
templateObj, num, _globalDecl, forBlock);
num++;
}
}
}
body = body.getHead().getBody();
if(body == null) break;
if(body.getHead() == null) break;
}
return isOmitSchedLoopFunc;
}
private void callLoopSchedFuncNodes(XMPnodes nodesObj, XobjList nodesSubscriptList,
CforBlock forBlock, CforBlock schedBaseBlock) throws XMPexception {
Xobject loopIndex = forBlock.getInductionVar();
Xtype loopIndexType = loopIndex.Type();
if (!XMPutil.isIntegerType(loopIndexType)) {
throw new XMPexception("loop index variable has a non-integer type");
}
String loopIndexName = loopIndex.getSym();
int nodesIndex = 0;
int nodesDim = nodesObj.getDim();
XobjInt nodesIndexArg = null;
for (XobjArgs i = nodesSubscriptList.getArgs(); i != null; i = i.nextArgs()) {
if (nodesIndex >= nodesDim) {
throw new XMPexception("wrong nodes dimensions, too many");
}
String s = i.getArg().getString();
if (s.equals(loopIndexName)) {
if (nodesIndexArg != null) {
throw new XMPexception("loop index '" + loopIndexName + "' is already described");
}
nodesIndexArg = Xcons.IntConstant(nodesIndex);
}
nodesIndex++;
}
if (nodesIndexArg == null) {
throw new XMPexception("cannot find index '" + loopIndexName + "' reference in <on-ref>");
}
if (nodesIndex != nodesDim) {
throw new XMPexception("wrong nodes dimensions, too few");
}
Ident parallelInitId = declIdentWithBlock(schedBaseBlock,
"_XMP_loop_init_" + loopIndexName, loopIndexType);
Ident parallelCondId = declIdentWithBlock(schedBaseBlock,
"_XMP_loop_cond_" + loopIndexName, loopIndexType);
Ident parallelStepId = declIdentWithBlock(schedBaseBlock,
"_XMP_loop_step_" + loopIndexName, loopIndexType);
XMPutil.putLoopIter(schedBaseBlock, loopIndexName,
Xcons.List(parallelInitId, parallelCondId, parallelStepId));
forBlock.setLowerBound(parallelInitId.Ref());
forBlock.setUpperBound(parallelCondId.Ref());
forBlock.setStep(parallelStepId.Ref());
forBlock.getCondBBlock().setExpr(Xcons.binaryOp(Xcode.LOG_LT_EXPR, loopIndex, parallelCondId.Ref()));
}
static Ident declIdentWithBlock(Block b, String identName, Xtype type)
{
Block bb = getOuterSchedPoint(b);
BlockList bl = bb.getParent();
// FIXME consider variable scope
return bl.declLocalIdent(identName, type);
}
private Block createCommTaskBlock(BlockList body, String execFuncSuffix, XobjList execFuncArgs) throws XMPexception {
// setup barrier finalizer
setupFinalizer(body, _globalDecl.declExternFunc("_XMP_pop_nodes"), null);
// create function call
BlockList taskBody = Bcons.emptyBody();
Ident taskDescId = taskBody.declLocalIdent("_XMP_TASK_desc", Xtype.voidPtrType, StorageClass.AUTO,
Xcons.Cast(Xtype.voidPtrType, Xcons.IntConstant(0)));
execFuncArgs.cons(taskDescId.getAddr());
Ident execFuncId = _globalDecl.declExternFunc("_XMP_exec_task_" + execFuncSuffix, Xtype.intType);
Block execBlock = Bcons.IF(BasicBlock.Cond(execFuncId.Call(execFuncArgs)), body, null);
taskBody.add(execBlock);
Ident taskFinalizeId = _globalDecl.declExternFunc("_XMP_exec_task_NODES_FINALIZE", Xtype.voidType);
XobjList args = Xcons.List(Xcode.POINTER_REF, taskDescId.Ref());
taskBody.add(taskFinalizeId.Call(args));
return Bcons.COMPOUND(taskBody);
}
private void translateBarrier(PragmaBlock pb) throws XMPexception {
// start translation
XobjList barrierDecl = (XobjList)pb.getClauses();
XMPsymbolTable localXMPsymbolTable = XMPlocalDecl.declXMPsymbolTable(pb);
// create function call
Block barrierFuncCallBlock = null;
XobjList onRef = (XobjList)barrierDecl.getArg(0);
if (onRef == null || onRef.Nargs() == 0) {
barrierFuncCallBlock = _globalDecl.createFuncCallBlock("_XMP_barrier_EXEC", null);
}
else {
XMPquadruplet<String, Boolean, XobjList, XMPobject> execOnRefArgs = createExecOnRefArgs(onRef, pb);
String execFuncSuffix = execOnRefArgs.getFirst();
boolean splitComm = execOnRefArgs.getSecond().booleanValue();
XobjList execFuncArgs = execOnRefArgs.getThird();
if (splitComm) {
BlockList barrierBody = Bcons.blockList(_globalDecl.createFuncCallBlock("_XMP_barrier_EXEC", null));
barrierFuncCallBlock = createCommTaskBlock(barrierBody, execFuncSuffix, execFuncArgs);
}
else {
barrierFuncCallBlock = _globalDecl.createFuncCallBlock("_XMP_barrier_" + execFuncSuffix, execFuncArgs);
}
}
pb.replace(barrierFuncCallBlock);
Xobject profileClause = barrierDecl.getArg(1);
addProfileFunctions(profileClause, barrierFuncCallBlock, "barrier", pb);
}
private Xobject setStartLengthSize(Xobject obj, Xtype varType, int dims, Xobject[] start, Xobject[] length, Xobject[] size) throws XMPexception {
Xobject total_length = null;
for(int j=0;j<dims;j++){
Xobject triplet = obj.getArg(1).getArg(j);
size[j] = XMPutil.getArrayElmt(varType, j);
if(triplet.isVariable() || triplet.isIntConstant()){
start[j] = triplet;
length[j] = Xcons.IntConstant(1);
}
else{
start[j] = triplet.getArg(0);
if(triplet.getArg(1).isVariable() || triplet.getArg(1).isIntConstant()){
length[j] = triplet.getArg(1);
}
else{
length[j] = (triplet.getArg(1) == null || triplet.getArg(1).isEmpty())?
Xcons.binaryOp(Xcode.MINUS_EXPR, size[j], start[j]) : triplet.getArg(1);
}
}
total_length = (j==0)? length[j] : Xcons.binaryOp(Xcode.MUL_EXPR, total_length, length[j]);
}
return total_length;
}
private void setAccSize(int dims, Xobject[] size, Xobject[] acc_size){
for(int j=0;j<dims;j++)
for(int k=j+1;k<dims;k++)
acc_size[j] = (k==j+1)? size[k] : Xcons.binaryOp(Xcode.MUL_EXPR, acc_size[j], size[k]);
acc_size[dims-1] = Xcons.IntConstant(1);
}
private Xobject calcOffsetSize(int dims, Xobject[] start, Xobject[] acc_size, Xtype varType){
Xobject offset_size = Xcons.binaryOp(Xcode.MUL_EXPR, start[0], acc_size[0]);
for(int j=1;j<dims;j++){
offset_size = Xcons.binaryOp(Xcode.PLUS_EXPR, offset_size, Xcons.binaryOp(Xcode.MUL_EXPR, start[j], acc_size[j]));
}
return Xcons.binaryOp(Xcode.MUL_EXPR, offset_size, Xcons.SizeOf(varType.getArrayElementType()));
}
private void createLocReduction(PragmaBlock pb, XobjList reductionRef, Xobject reductionOp, XobjList onRef) throws XMPexception {
Xobject reductionVariable = reductionRef.getArg(1).getArg(0).getArg(0);
int numLocationVariables = reductionRef.getArg(1).Nargs() - 1;
// Create xmp_reduce_loc_init()
BlockList reductionBody = Bcons.emptyBody();
String reductionVariableName = reductionVariable.getName();
Ident reductionVariableId = pb.findVarIdent(reductionVariableName);
Xtype reductionVariableType = reductionVariableId.Type();
XobjList args = Xcons.List(Xcons.IntConstant(numLocationVariables), Xcons.Cast(BasicType.longdoubleType, reductionVariable),
reductionVariableId.getAddr(), XMP.createBasicTypeConstantObj(reductionVariableType));
reductionBody.add(_globalDecl.createFuncCallBlock("xmp_reduce_loc_init", args));
// Create xmp_reduce_loc_set();
for(int i=0;i<numLocationVariables;i++){
Xobject reductionLocation = reductionRef.getArg(1).getArg(i+1);
boolean is_scalar = reductionLocation.isVarRef();
Xobject varAddr, varLength, varSize;
if(is_scalar){ // scalar
String varName = reductionLocation.getName();
Ident varId = pb.findVarIdent(varName);
Xtype varType = varId.Type();
varAddr = varId.getAddr();
varLength = Xcons.IntConstant(1);
varSize = Xcons.SizeOf(varType);
}
else{ // array
String varName = reductionLocation.getArg(0).getName();
Ident varId = pb.findVarIdent(varName);
Xtype varType = varId.Type();
int dims = varType.getNumDimensions();
Xobject[] start = new Xobject[dims];
Xobject[] length = new Xobject[dims];
Xobject[] size = new Xobject[dims];
Xobject total_length = setStartLengthSize(reductionLocation, varType, dims, start, length, size);
// Check the array is contiguous or not.
// Note that when XMP runtime supports stride bcast communication,
// the following if-statment will be removed.
if(! check_contiguous_of_array(dims, length, size))
throw new XMPexception("Stride bcast operation is not supported");
Xobject[] acc_size = new Xobject[dims];
setAccSize(dims, size, acc_size);
Xobject offsetSize = calcOffsetSize(dims, start, acc_size, varType);
varAddr = Xcons.binaryOp(Xcode.PLUS_EXPR, Xcons.Cast(Xtype.Pointer(BasicType.charType), varId.Ref()), offsetSize);
varLength = total_length;
varSize = Xcons.SizeOf(varType.getArrayElementType());
}
args = Xcons.List(varAddr, varLength, varSize);
reductionBody.add(_globalDecl.createFuncCallBlock("xmp_reduce_loc_set", args));
}
// Create xmp_reduce_loc_execute()
args = Xcons.List(reductionOp);
reductionBody.add(_globalDecl.createFuncCallBlock("xmp_reduce_loc_execute", args));
// Output
Block reductionBodyBlock = null;
if (onRef != null && onRef.Nargs() != 0){
XMPquadruplet<String, Boolean, XobjList, XMPobject> execOnRefArgs = createExecOnRefArgs(onRef, pb);
String execFuncSuffix = execOnRefArgs.getFirst();
boolean splitComm = execOnRefArgs.getSecond().booleanValue();
XobjList execFuncArgs = execOnRefArgs.getThird();
if(splitComm){
reductionBodyBlock = createCommTaskBlock(reductionBody, execFuncSuffix, execFuncArgs);
}
else{
reductionBodyBlock = Bcons.COMPOUND(reductionBody);
}
}
else{
reductionBodyBlock = Bcons.COMPOUND(reductionBody);
}
pb.replace(reductionBodyBlock);
}
private void translateReduction(PragmaBlock pb) throws XMPexception {
// start translation
XobjList reductionDecl = (XobjList)pb.getClauses();
XMPsymbolTable localXMPsymbolTable = XMPlocalDecl.declXMPsymbolTable(pb);
// Check host or acc clause for XcalableACC
XobjList accOrHost = (XobjList)reductionDecl.getArg(3);
boolean isHost = accOrHost.hasIdent("host");
boolean isACC = accOrHost.hasIdent("acc");
if(!isHost && !isACC){
isHost = true;
}
else if(isHost && isACC){
throw new XMPexception(pb.getLineNo(), "reduction for both acc and host is unimplemented");
}
// create function arguments
XobjList reductionRef = (XobjList)reductionDecl.getArg(0);
XobjInt reductionOp = (XobjInt)reductionRef.getArg(0);
// create function call
XobjList onRef = (XobjList)reductionDecl.getArg(1);
// When MAXLOC or MINLOC, another flow, which does not use a variadic function in runtime, is executed.
if(reductionOp.getInt() == XMPcollective.REDUCE_MAXLOC || reductionOp.getInt() == XMPcollective.REDUCE_MINLOC){
createLocReduction(pb, reductionRef, reductionOp, onRef);
return;
}
Block reductionFuncCallBlock = null;
Vector<XobjList> reductionFuncArgsList = createReductionArgsList(reductionRef, pb, false, null, null);
String reductionFuncType = createReductionFuncType(reductionRef, pb, isACC);
if (onRef == null || onRef.Nargs() == 0){
reductionFuncCallBlock = createReductionFuncCallBlock(true, reductionFuncType + "_EXEC", null, reductionFuncArgsList);
}
else{
XMPquadruplet<String, Boolean, XobjList, XMPobject> execOnRefArgs = createExecOnRefArgs(onRef, pb);
String execFuncSuffix = execOnRefArgs.getFirst();
boolean splitComm = execOnRefArgs.getSecond().booleanValue();
XobjList execFuncArgs = execOnRefArgs.getThird();
if (splitComm) {
BlockList reductionBody =
Bcons.blockList(createReductionFuncCallBlock(true, reductionFuncType + "_EXEC", null, reductionFuncArgsList));
reductionFuncCallBlock = createCommTaskBlock(reductionBody, execFuncSuffix, execFuncArgs);
}
else {
reductionFuncCallBlock = createReductionFuncCallBlock(false, reductionFuncType + "_" + execFuncSuffix,
execFuncArgs.operand(), reductionFuncArgsList);
}
}
if(isACC){
XobjList vars = Xcons.List();
XobjList reductionSpecList = (XobjList)reductionRef.getArg(1);
for(Xobject x : reductionSpecList){
vars.add(x.getArg(0));
}
reductionFuncCallBlock =
Bcons.PRAGMA(Xcode.ACC_PRAGMA, "HOST_DATA", Xcons.List(Xcons.List(Xcons.String("USE_DEVICE"), vars)),
Bcons.blockList(reductionFuncCallBlock));
}
Xobject async = reductionDecl.getArg(2);
if(async.Opcode() != Xcode.LIST){
if(!XmOption.isAsync())
XMP.error(pb.getLineNo(), "MPI-3 is required to use the async clause on a reduction directive");
BlockList bl = reductionFuncCallBlock.getBody();
bl.insert(_globalDecl.declExternFunc("xmpc_init_async").Call(Xcons.List(async)));
bl.add(_globalDecl.declExternFunc("xmpc_start_async").Call(Xcons.List()));
}
pb.replace(reductionFuncCallBlock);
Xobject profileClause = reductionDecl.getArg(4);
addProfileFunctions(profileClause, reductionFuncCallBlock, "reduction", pb);
}
private String createReductionFuncType(XobjList reductionRef, PragmaBlock pb, boolean isACC) throws XMPexception {
XobjInt reductionOp = (XobjInt)reductionRef.getArg(0);
switch (reductionOp.getInt()) {
case XMPcollective.REDUCE_SUM:
case XMPcollective.REDUCE_MINUS:
case XMPcollective.REDUCE_PROD:
case XMPcollective.REDUCE_BAND:
case XMPcollective.REDUCE_LAND:
case XMPcollective.REDUCE_BOR:
case XMPcollective.REDUCE_LOR:
case XMPcollective.REDUCE_BXOR:
case XMPcollective.REDUCE_LXOR:
case XMPcollective.REDUCE_MAX:
case XMPcollective.REDUCE_MIN:
case XMPcollective.REDUCE_MAXLOC:
case XMPcollective.REDUCE_MINLOC:
return isACC? new String("reduce_acc") : new String("reduce");
case XMPcollective.REDUCE_FIRSTMAX:
case XMPcollective.REDUCE_FIRSTMIN:
case XMPcollective.REDUCE_LASTMAX:
case XMPcollective.REDUCE_LASTMIN:
return isACC? new String("reduce_acc_FLMM") : new String("reduce_FLMM");
default:
throw new XMPexception("unknown reduce operation");
}
}
private Vector<XobjList> createReductionArgsList(XobjList reductionRef, PragmaBlock pb, boolean isClause,
CforBlock schedBaseBlock, IfBlock reductionInitIfBlock) throws XMPexception {
Vector<XobjList> returnVector = new Vector<XobjList>();
XobjInt reductionOp = (XobjInt)reductionRef.getArg(0);
XobjList reductionSpecList = (XobjList)reductionRef.getArg(1);
for (XobjArgs i = reductionSpecList.getArgs(); i != null; i = i.nextArgs()) {
XobjList reductionSpec = (XobjList)i.getArg();
String specName = reductionSpec.getArg(0).getString();
Ident specId;
Xtype specType;
XMPalignedArray specAlignedArray = _globalDecl.getXMPalignedArray(specName, pb);
if (specAlignedArray != null){
// specName is an aligned array and its original entry of the symbol table may have been removed.
specId = specAlignedArray.getAddrId();
specType = specAlignedArray.getArrayType();
}
else {
XMPpair<Ident, Xtype> typedSpec = XMPutil.findTypedVar(specName, pb);
specId = typedSpec.getFirst();
specType = typedSpec.getSecond();
}
boolean isArray = false;
boolean isPointer = false;
Xobject specRef = null;
Xobject count = null;
Xobject elmtType = null;
BasicType basicSpecType = null;
switch (specType.getKind()) {
case Xtype.BASIC:
{
basicSpecType = (BasicType)specType;
checkReductionType(specName, basicSpecType);
specRef = specId.getAddr();
count = Xcons.LongLongConstant(0, 1);
elmtType = XMP.createBasicTypeConstantObj(basicSpecType);
} break;
case Xtype.ARRAY:
{
isArray = true;
ArrayType arraySpecType = (ArrayType)specType;
if (arraySpecType.getArrayElementType().getKind() != Xtype.BASIC)
throw new XMPexception("array '" + specName + "' has a wrong data type for reduction");
basicSpecType = (BasicType)arraySpecType.getArrayElementType();
checkReductionType(specName, basicSpecType);
// FIXME not good implementation
XMPsymbolTable localXMPsymbolTable = XMPlocalDecl.declXMPsymbolTable(pb);
if(specAlignedArray == null){
specRef = specId.Ref();
count = Xcons.LongLongConstant(0, XMPutil.getArrayElmtCount(arraySpecType));
}
else{
if(isClause){
throw new XMPexception("aligned arrays cannot be used in reduction clause");
}
if (specAlignedArray.hasShadow()) {
throw new XMPexception("arrays which have shadow cannot be used in reduction directive/clause");
}
specRef = specAlignedArray.getAddrIdVoidRef();
Ident getTotalElmtFuncId = _globalDecl.declExternFunc("_XMP_get_array_total_elmts",
Xtype.unsignedlonglongType);
count = getTotalElmtFuncId.Call(Xcons.List(specAlignedArray.getDescId().Ref()));
}
elmtType = XMP.createBasicTypeConstantObj(basicSpecType);
} break;
case Xtype.POINTER:
{
isPointer = true;
basicSpecType = (BasicType)specType.getRef();
specRef = specId.getAddr();
count = Xcons.LongLongConstant(0, 1);
elmtType = XMP.createBasicTypeConstantObj(basicSpecType);
} break;
default:
throw new XMPexception("'" + specName + "' has a wrong data type for reduction");
}
XobjList reductionFuncArgs = Xcons.List(specRef, count, elmtType, reductionOp);
// declare temp variable for reduction
if (isClause) {
createReductionInitStatement(specId, isArray, count, basicSpecType, reductionOp.getInt(),
schedBaseBlock, reductionInitIfBlock);
}
if(isPointer){
Xobject varaddr = (Xobject)reductionFuncArgs.getArg(0);
reductionFuncArgs.setArg(0, Xcons.PointerRef(varaddr));
}
// add extra args for (firstmax, firstmin, lastmax, lastmin) if needed
createFLMMreductionArgs(reductionOp.getInt(), (XobjList)reductionSpec.getArg(1), reductionFuncArgs, pb);
returnVector.add(reductionFuncArgs);
}
return returnVector;
}
private void createReductionInitStatement(Ident varId, boolean isArray, Xobject count, BasicType type, int reductionOp,
CforBlock schedBaseBlock, IfBlock reductionInitIfBlock) throws XMPexception {
if (!needsInitialization(reductionOp)) {
return;
}
BlockList initPart = reductionInitIfBlock.getThenBody();
if (initPart == null) {
initPart = Bcons.emptyBody();
reductionInitIfBlock.setThenBody(initPart);
}
Xobject statement = null;
if (isArray) {
Ident initLoopIndexId = declIdentWithBlock(schedBaseBlock, _globalDecl.genSym(XMP.TEMP_PREFIX), Xtype.unsignedlonglongType);
initPart.add(createReductionArrayInit(varId, createReductionInitValueObj(varId, type, reductionOp), count, type, initLoopIndexId));
}
else {
initPart.add(Xcons.Set(varId.Ref(), createReductionInitValueObj(varId, type, reductionOp)));
}
}
private boolean needsInitialization(int reductionOp) throws XMPexception {
switch (reductionOp) {
case XMPcollective.REDUCE_SUM:
case XMPcollective.REDUCE_MINUS:
case XMPcollective.REDUCE_PROD:
case XMPcollective.REDUCE_BXOR:
case XMPcollective.REDUCE_LXOR:
return true;
case XMPcollective.REDUCE_BAND:
case XMPcollective.REDUCE_LAND:
case XMPcollective.REDUCE_BOR:
case XMPcollective.REDUCE_LOR:
case XMPcollective.REDUCE_MAX:
case XMPcollective.REDUCE_MIN:
case XMPcollective.REDUCE_FIRSTMAX:
case XMPcollective.REDUCE_FIRSTMIN:
case XMPcollective.REDUCE_LASTMAX:
case XMPcollective.REDUCE_LASTMIN:
return false;
default:
throw new XMPexception("unknown reduce operation");
}
}
private Block createReductionArrayInit(Ident tempId, Xobject initValueObj, Xobject count, BasicType type,
Ident loopIndexId) {
Xobject loopIndexRef = loopIndexId.Ref();
Xobject tempArrayRef = Xcons.PointerRef(Xcons.binaryOp(Xcode.PLUS_EXPR, Xcons.Cast(Xtype.Pointer(type), tempId.Ref()),
loopIndexRef));
Block loopBlock = Bcons.FOR(Xcons.Set(loopIndexRef, Xcons.IntConstant(0)),
Xcons.binaryOp(Xcode.LOG_LT_EXPR, loopIndexRef, count),
Xcons.asgOp(Xcode.ASG_PLUS_EXPR, loopIndexRef, Xcons.IntConstant(1)),
Bcons.Statement(Xcons.Set(tempArrayRef, initValueObj)));
return loopBlock;
}
// FIXME
private Xobject createReductionInitValueObj(Ident varId, BasicType type, int reductionOp) throws XMPexception {
Xobject varRef = varId.Ref();
Xobject intZero = Xcons.IntConstant(0);
Xobject intOne = Xcons.IntConstant(1);
Xobject floatZero = Xcons.FloatConstant(0.);
Xobject floatOne = Xcons.FloatConstant(1.);
switch (type.getBasicType()) {
case BasicType.BOOL:
// FIXME correct???
return selectReductionInitValueObj(reductionOp, varRef, intZero, intOne);
case BasicType.CHAR:
case BasicType.UNSIGNED_CHAR:
case BasicType.SHORT:
case BasicType.UNSIGNED_SHORT:
case BasicType.INT:
case BasicType.UNSIGNED_INT:
case BasicType.LONG:
case BasicType.UNSIGNED_LONG:
case BasicType.LONGLONG:
case BasicType.UNSIGNED_LONGLONG:
return selectReductionInitValueObj(reductionOp, varRef, intZero, intOne);
case BasicType.FLOAT:
case BasicType.DOUBLE:
case BasicType.LONG_DOUBLE:
return selectReductionInitValueObj(reductionOp, varRef, floatZero, floatOne);
case BasicType.FLOAT_IMAGINARY:
case BasicType.DOUBLE_IMAGINARY:
case BasicType.LONG_DOUBLE_IMAGINARY:
case BasicType.FLOAT_COMPLEX:
case BasicType.DOUBLE_COMPLEX:
case BasicType.LONG_DOUBLE_COMPLEX:
// FIXME not implemented yet
throw new XMPexception("not implemented yet");
default:
throw new XMPexception("wrong data type for reduction");
}
}
// FIXME needs type checking
private Xobject selectReductionInitValueObj(int reductionOp, Xobject varRef, Xobject zero, Xobject one) throws XMPexception {
switch (reductionOp) {
case XMPcollective.REDUCE_SUM:
case XMPcollective.REDUCE_MINUS:
return zero;
case XMPcollective.REDUCE_PROD:
return one;
case XMPcollective.REDUCE_BAND:
case XMPcollective.REDUCE_LAND:
case XMPcollective.REDUCE_BOR:
case XMPcollective.REDUCE_LOR:
case XMPcollective.REDUCE_MAX:
case XMPcollective.REDUCE_MIN:
case XMPcollective.REDUCE_FIRSTMAX:
case XMPcollective.REDUCE_FIRSTMIN:
case XMPcollective.REDUCE_LASTMAX:
case XMPcollective.REDUCE_LASTMIN:
throw new XMPexception("the operation does not need initialization");
case XMPcollective.REDUCE_BXOR:
return Xcons.unaryOp(Xcode.BIT_NOT_EXPR, varRef);
case XMPcollective.REDUCE_LXOR:
return Xcons.unaryOp(Xcode.LOG_NOT_EXPR, varRef);
default:
throw new XMPexception("unknown reduce operation");
}
}
private void createFLMMreductionArgs(int op, XobjList locationVars, XobjList funcArgs, PragmaBlock pb) throws XMPexception {
switch (op) {
case XMPcollective.REDUCE_SUM:
case XMPcollective.REDUCE_MINUS:
case XMPcollective.REDUCE_PROD:
case XMPcollective.REDUCE_BAND:
case XMPcollective.REDUCE_LAND:
case XMPcollective.REDUCE_BOR:
case XMPcollective.REDUCE_LOR:
case XMPcollective.REDUCE_BXOR:
case XMPcollective.REDUCE_LXOR:
case XMPcollective.REDUCE_MAX:
case XMPcollective.REDUCE_MIN:
case XMPcollective.REDUCE_MAXLOC:
case XMPcollective.REDUCE_MINLOC:
return;
case XMPcollective.REDUCE_FIRSTMAX:
case XMPcollective.REDUCE_FIRSTMIN:
case XMPcollective.REDUCE_LASTMAX:
case XMPcollective.REDUCE_LASTMIN:
break;
default:
throw new XMPexception("unknown reduce operation");
}
funcArgs.add(Xcons.IntConstant(XMPutil.countElmts(locationVars)));
// check <location-variables> and add to funcArgs
for (XobjArgs i = locationVars.getArgs(); i != null; i = i.nextArgs()) {
String varName = i.getArg().getString();
XMPpair<Ident, Xtype> typedVar = XMPutil.findTypedVar(varName, pb);
Ident varId = typedVar.getFirst();
Xtype varType = typedVar.getSecond();
switch (varType.getKind()) {
case Xtype.BASIC:
{
// if (!XMPutil.isIntegerType(varType))
// throw new XMPexception("'" + varName + "' should have a integer type for reduction");
BasicType basicVarType = (BasicType)varType;
funcArgs.add(Xcons.Cast(Xtype.voidPtrType, varId.getAddr()));
funcArgs.add(Xcons.Cast(Xtype.intType, XMP.createBasicTypeConstantObj(basicVarType)));
} break;
case Xtype.ARRAY:
{
ArrayType arrayVarType = (ArrayType)varType;
if (arrayVarType.getArrayElementType().getKind() != Xtype.BASIC)
throw new XMPexception("array '" + varName + "' has has a wrong data type for reduction");
BasicType basicVarType = (BasicType)arrayVarType.getArrayElementType();
if (!XMPutil.isIntegerType(basicVarType))
throw new XMPexception("'" + varName + "' should have a integer type for reduction");
funcArgs.add(Xcons.Cast(Xtype.voidPtrType, varId.Ref()));
funcArgs.add(Xcons.Cast(Xtype.intType, XMP.createBasicTypeConstantObj(basicVarType)));
} break;
case Xtype.POINTER:
{
PointerType ptrVarType = (PointerType)varType;
BasicType basicVarType = (BasicType)ptrVarType.getRef();
funcArgs.add(Xcons.Cast(Xtype.voidPtrType, varId.Ref()));
funcArgs.add(Xcons.Cast(Xtype.intType, XMP.createBasicTypeConstantObj(basicVarType)));
} break;
default:
throw new XMPexception("'" + varName + "' has a wrong data type for reduction");
}
}
}
private void checkReductionType(String name, BasicType type) throws XMPexception {
switch (type.getBasicType()) {
case BasicType.BOOL:
case BasicType.CHAR:
case BasicType.UNSIGNED_CHAR:
case BasicType.SHORT:
case BasicType.UNSIGNED_SHORT:
case BasicType.INT:
case BasicType.UNSIGNED_INT:
case BasicType.LONG:
case BasicType.UNSIGNED_LONG:
case BasicType.LONGLONG:
case BasicType.UNSIGNED_LONGLONG:
case BasicType.FLOAT:
case BasicType.DOUBLE:
case BasicType.LONG_DOUBLE:
case BasicType.FLOAT_IMAGINARY:
case BasicType.DOUBLE_IMAGINARY:
case BasicType.LONG_DOUBLE_IMAGINARY:
case BasicType.FLOAT_COMPLEX:
case BasicType.DOUBLE_COMPLEX:
case BasicType.LONG_DOUBLE_COMPLEX:
break;
default:
throw new XMPexception("'" + name + "' has a wrong data type for reduction");
}
}
private Block createReductionFuncCallBlock(boolean isMacroFunc, String funcType,
Xobject execDesc, Vector<XobjList> funcArgsList) {
Ident funcId = null;
if (isMacroFunc) funcId = XMP.getMacroId("_XMP_M_" + funcType.toUpperCase());
else funcId = _globalDecl.declExternFunc("_XMP_" + funcType);
BlockList funcCallList = Bcons.emptyBody();
Iterator<XobjList> it = funcArgsList.iterator();
while (it.hasNext()) {
XobjList funcArgs = it.next();
if (execDesc != null) funcArgs.cons(execDesc);
funcCallList.add(Bcons.Statement(funcId.Call(funcArgs)));
}
return Bcons.COMPOUND(funcCallList);
}
private void translateBcast(PragmaBlock pb) throws XMPexception {
// start translation
XobjList bcastDecl = (XobjList)pb.getClauses();
XMPsymbolTable localXMPsymbolTable = XMPlocalDecl.declXMPsymbolTable(pb);
// acc or host
XobjList accOrHost = (XobjList)bcastDecl.getArg(4);
boolean isACC = accOrHost.hasIdent("acc");
boolean isHost = accOrHost.hasIdent("host");
if(!isACC && !isHost){
isHost = true;
}
if(isACC && isHost){
throw new XMPexception(pb.getLineNo(), "bcast for both acc and host is unimplemented");
}
// create function arguments
XobjList varList = (XobjList)bcastDecl.getArg(0);
Vector<XobjList> bcastArgsList = createBcastArgsList(varList, pb);
// create function call
Block bcastFuncCallBlock = null;
XobjList fromRef = (XobjList)bcastDecl.getArg(1);
XMPpair<String, XobjList> execFromRefArgs = null;
if(fromRef != null && fromRef.Nargs() != 0){
execFromRefArgs = createExecFromRefArgs(fromRef, pb);
}
XobjList onRef = (XobjList)bcastDecl.getArg(2);
boolean splitComm = false;
if(onRef == null || onRef.getArgs() == null) {
bcastFuncCallBlock = createBcastFuncCallBlock(true, "EXEC", null, bcastArgsList, execFromRefArgs, isACC);
}
else{
XMPquadruplet<String, Boolean, XobjList, XMPobject> execOnRefArgs = createExecOnRefArgs(onRef, pb);
String execFuncSuffix = execOnRefArgs.getFirst();
splitComm = execOnRefArgs.getSecond().booleanValue();
XobjList execFuncArgs = execOnRefArgs.getThird();
if(splitComm){
BlockList bcastBody = Bcons.blockList(createBcastFuncCallBlock(true, "EXEC", null, bcastArgsList,
execFromRefArgs, isACC));
bcastFuncCallBlock = createCommTaskBlock(bcastBody, execFuncSuffix, execFuncArgs);
}
else{
bcastFuncCallBlock = createBcastFuncCallBlock(false, execFuncSuffix, execFuncArgs.operand(),
bcastArgsList, execFromRefArgs, isACC);
}
}
if(isACC){
bcastFuncCallBlock = Bcons.PRAGMA(Xcode.ACC_PRAGMA, "HOST_DATA",
Xcons.List(Xcons.List(Xcons.String("USE_DEVICE"),varList)),
Bcons.blockList(bcastFuncCallBlock));
}
Xobject async = bcastDecl.getArg(3);
if(async.Opcode() != Xcode.LIST){
if(!XmOption.isAsync()){
XMP.error(pb.getLineNo(), "MPI-3 is required to use the async clause on a bcast directive");
}
BlockList bl = bcastFuncCallBlock.getBody();
bl.insert(_globalDecl.declExternFunc("xmpc_init_async").Call(Xcons.List(async)));
bl.add(_globalDecl.declExternFunc("xmpc_start_async").Call(Xcons.List()));
}
pb.replace(bcastFuncCallBlock);
Xobject profileClause = bcastDecl.getArg(5);
addProfileFunctions(profileClause, bcastFuncCallBlock, "bcast", pb);
}
private boolean check_all(Xobject length, Xobject size){
return length.equals(size);
}
private boolean check_one(Xobject length){
return length.equals(Xcons.IntConstant(1));
}
private boolean check_contiguous_of_array(int dims, Xobject length[], Xobject size[]) throws XMPexception{
boolean is_contiguous = false;
switch (dims){
case 1: is_contiguous = true;
break;
case 2:
if(check_one(length[0]) || check_all(length[1], size[1]))
is_contiguous = true;
break;
case 3:
if((check_one(length[0]) && check_one(length[1])) ||
(check_one(length[0]) && check_all(length[2], size[2])) ||
(check_all(length[1], size[1]) && check_all(length[2], size[2])))
is_contiguous = true;
break;
case 4:
if((check_one(length[0]) && check_one(length[1]) && check_one(length[2])) ||
(check_one(length[0]) && check_one(length[1]) && check_all(length[3], size[3])) ||
(check_one(length[0]) && check_all(length[2], size[2]) && check_all(length[3], size[3])) ||
(check_all(length[1], size[1]) && check_all(length[2], size[2]) && check_all(length[3], size[3])))
is_contiguous = true;
break;
case 5:
if((check_one(length[0]) && check_one(length[1]) && check_one(length[2]) && check_one(length[3])) ||
(check_one(length[0]) && check_one(length[1]) && check_one(length[2]) && check_all(length[4], size[4])) ||
(check_one(length[0]) && check_one(length[1]) && check_all(length[3], size[3]) && check_all(length[4], size[4])) ||
(check_one(length[0]) && check_all(length[2], size[2]) && check_all(length[3], size[3]) && check_all(length[4], size[4])) ||
(check_all(length[1], size[1]) && check_all(length[2], size[2]) && check_all(length[3], size[3]) && check_all(length[4], size[4])))
is_contiguous = true;
break;
case 6:
if((check_one(length[0]) && check_one(length[1]) && check_one(length[2]) && check_one(length[3]) && check_one(length[4])) ||
(check_one(length[0]) && check_one(length[1]) && check_one(length[2]) && check_one(length[3]) && check_all(length[5], size[5])) ||
(check_one(length[0]) && check_one(length[1]) && check_one(length[2]) && check_all(length[4], size[4]) && check_all(length[5], size[5])) ||
(check_one(length[0]) && check_one(length[1]) && check_all(length[3], size[3]) && check_all(length[4], size[4]) && check_all(length[5], size[5])) ||
(check_one(length[0]) && check_all(length[2], size[2]) && check_all(length[3], size[3]) && check_all(length[4], size[4]) && check_all(length[5], size[5])) ||
(check_all(length[1], size[1]) && check_all(length[2], size[2]) && check_all(length[3], size[3]) && check_all(length[4], size[4]) && check_all(length[5], size[5])))
is_contiguous = true;
break;
case 7:
if((check_one(length[0]) && check_one(length[1]) && check_one(length[2]) && check_one(length[3]) && check_one(length[4]) && check_one(length[5])) ||
(check_one(length[0]) && check_one(length[1]) && check_one(length[2]) && check_one(length[3]) && check_one(length[4]) && check_all(length[6], size[6])) ||
(check_one(length[0]) && check_one(length[1]) && check_one(length[2]) && check_one(length[3]) && check_all(length[5], size[5]) && check_all(length[6], size[6])) ||
(check_one(length[0]) && check_one(length[1]) && check_one(length[2]) && check_all(length[4], size[4]) && check_all(length[5], size[5]) && check_all(length[6], size[6])) ||
(check_one(length[0]) && check_one(length[1]) && check_all(length[3], size[3]) && check_all(length[4], size[4]) && check_all(length[5], size[5]) && check_all(length[6], size[6])) ||
(check_one(length[0]) && check_all(length[2], size[2]) && check_all(length[3], size[3]) && check_all(length[4], size[4]) && check_all(length[5], size[5]) && check_all(length[6], size[6])) ||
(check_all(length[1], size[1]) && check_all(length[2], size[2]) && check_all(length[3], size[3]) && check_all(length[4], size[4]) && check_all(length[5], size[5]) && check_all(length[6], size[6])))
is_contiguous = true;
break;
default:
throw new XMPexception("A wrong data type for broadcast");
}
return is_contiguous;
}
private Vector<XobjList> createBcastArgsList(XobjList varList, PragmaBlock pb) throws XMPexception {
Vector<XobjList> returnVector = new Vector<XobjList>();
for (XobjArgs i = varList.getArgs(); i != null; i = i.nextArgs()) {
if(i.getArg().isVariable()){
// The variable indicated in bcast directive is variable name.
// For example,
// ---
// int a[10], b[10][10];
// #pragma xmp bcast (a,b)
// ---
String varName = i.getArg().getString();
XMPpair<Ident, Xtype> typedSpec = XMPutil.findTypedVar(varName, pb);
Ident varId = typedSpec.getFirst();
Xtype varType = typedSpec.getSecond();
XobjLong count = null;
switch (varType.getKind()) {
case Xtype.BASIC:
case Xtype.STRUCT:
case Xtype.UNION:
{
count = Xcons.LongLongConstant(0, 1);
returnVector.add(Xcons.List(varId.getAddr(), count, Xcons.SizeOf(varType)));
} break;
case Xtype.POINTER:
{
count = Xcons.LongLongConstant(0, 1);
returnVector.add(Xcons.List(varId.Ref(), count, Xcons.SizeOf(varType)));
} break;
case Xtype.ARRAY:
{
ArrayType arrayVarType = (ArrayType)varType;
switch (arrayVarType.getArrayElementType().getKind()) {
case Xtype.BASIC:
case Xtype.STRUCT:
case Xtype.UNION:
break;
default:
throw new XMPexception("array '" + varName + "' has has a wrong data type for broadcast");
}
if(arrayVarType.getArraySizeExpr() == null){
// Number of elements is static
// int a[10];
// #pragma xmp bcast (a)
count = Xcons.LongLongConstant(0, XMPutil.getArrayElmtCount(arrayVarType));
returnVector.add(Xcons.List(varId.Ref(), count, Xcons.SizeOf(arrayVarType.getArrayElementType())));
}
else{ // Number of elements is defined in arguments
// void hoge(int n, int a[n]){
// #pragma xmp bcast (a)
Xobject size = Xcons.SizeOf(arrayVarType.getArrayElementType());
Xobject len = arrayVarType.getArraySizeExpr();
ArrayType tmpType = arrayVarType;
for(int j=1;j<arrayVarType.getNumDimensions();j++){
tmpType = (ArrayType)arrayVarType.getRef();
len = Xcons.binaryOp(Xcode.MUL_EXPR, len, tmpType.getArraySizeExpr());
}
returnVector.add(Xcons.List(varId.Ref(), len, size));
}
} break;
default:
throw new XMPexception("'" + varName + "' has a wrong data type for broadcast");
}
}
else{
// The variable indicated in bcast directive is array with array section.
// For example,
// ---
// int a[10], b[10][10];
// #pragma xmp bcast (a[:],b[2:5][:])
// ---
String varName = i.getArg().getArg(0).getString();
XMPpair<Ident, Xtype> typedSpec = XMPutil.findTypedVar(varName, pb);
Ident varId = typedSpec.getFirst();
Xtype varType = typedSpec.getSecond();
int dims = varType.getNumDimensions();
if(dims != i.getArg().getArg(1).Nargs())
throw new XMPexception(varName + " has a wrong dimension");
Xobject[] start = new Xobject[dims];
Xobject[] length = new Xobject[dims];
Xobject[] size = new Xobject[dims];
Xobject total_length = setStartLengthSize(i.getArg(), varType, dims, start, length, size);
// Check the array is contiguous or not.
// Note that when XMP runtime supports stride bcast communication,
// the following if-statment will be removed.
if(! check_contiguous_of_array(dims, length, size))
throw new XMPexception("Stride bcast operation is not supported");
Xobject[] acc_size = new Xobject[dims];
setAccSize(dims, size, acc_size);
Xobject offset = calcOffsetSize(dims, start, acc_size, varType);
returnVector.add(Xcons.List(Xcons.binaryOp(Xcode.PLUS_EXPR, Xcons.Cast(Xtype.Pointer(BasicType.charType), varId.Ref()), offset),
total_length, Xcons.SizeOf(varType.getArrayElementType())));
}
}
return returnVector;
}
private Block createBcastFuncCallBlock(boolean isMacro, String funcType, Xobject execDesc, Vector<XobjList> funcArgsList,
XMPpair<String, XobjList> execFromRefArgs, boolean isACC) throws XMPexception {
String funcSuffix = null;
XobjList fromRef = null;
if (execFromRefArgs == null) funcSuffix = new String(funcType + "_OMITTED");
else {
funcSuffix = new String(funcType + "_" + execFromRefArgs.getFirst());
fromRef = execFromRefArgs.getSecond();
}
String accSuffix = isACC? "acc_" : "";
Ident funcId = null;
if (isMacro) funcId = XMP.getMacroId("_XMP_M_BCAST_" + accSuffix.toUpperCase() + funcSuffix);
else funcId = _globalDecl.declExternFunc("_XMP_bcast_" + accSuffix + funcSuffix);
BlockList funcCallList = Bcons.emptyBody();
Iterator<XobjList> it = funcArgsList.iterator();
while (it.hasNext()) {
XobjList funcArgs = it.next();
if (execDesc != null) funcArgs.cons(execDesc);
if (execFromRefArgs != null) funcArgs.mergeList(fromRef);
funcCallList.add(Bcons.Statement(funcId.Call(funcArgs)));
}
return Bcons.COMPOUND(funcCallList);
}
private XMPpair<String, XobjList> createExecFromRefArgs(XobjList fromRef, Block block) throws XMPexception {
if (fromRef.getArg(0) == null) {
// execute on global communicator
XobjList globalRef = (XobjList)fromRef.getArg(1);
XobjList execFuncArgs = Xcons.List();
// lower
if (globalRef.getArg(0) == null)
throw new XMPexception("lower bound cannot be omitted in <from-ref>");
else execFuncArgs.add(globalRef.getArg(0));
// upper
if (globalRef.getArg(1) == null)
throw new XMPexception("upper bound cannot be omitted in <from-ref>");
else execFuncArgs.add(globalRef.getArg(1));
// stride
if (globalRef.getArg(2) == null) execFuncArgs.add(Xcons.IntConstant(1));
else execFuncArgs.add(globalRef.getArg(2));
return new XMPpair<String, XobjList>(new String("GLOBAL"), execFuncArgs);
}
else {
// execute on <object-ref>
// check object name collision
String objectName = fromRef.getArg(0).getString();
XMPobject fromRefObject = _globalDecl.getXMPobject(objectName, block);
if (fromRefObject == null) {
throw new XMPexception("cannot find '" + objectName + "' nodes/template");
}
if (fromRefObject.getKind() == XMPobject.TEMPLATE)
throw new XMPexception("template cannot be used in <from-ref>");
String kind_bracket = fromRef.getArg(1).getTail().getString();
boolean isSquare = kind_bracket.equals("SQUARE");
fromRef.getArg(1).removeLastArgs(); // remove ROUND or SQUARE information
if(isSquare) ((XobjList)fromRef.getArg(1)).reverse();
// create arguments
if (fromRef.getArg(1) == null)
throw new XMPexception("multiple source nodes indicated in bcast directive");
else {
XobjList execFuncArgs = Xcons.List(fromRefObject.getDescId().Ref());
int refIndex = 0;
int refDim = fromRefObject.getDim();
for (XobjArgs i = fromRef.getArg(1).getArgs(); i != null; i = i.nextArgs()) {
if (refIndex == refDim)
throw new XMPexception("wrong nodes dimension indicated, too many");
XobjList t = (XobjList)i.getArg();
if (t == null || t.isEmptyList()){
execFuncArgs.add(Xcons.Cast(Xtype.intType, Xcons.IntConstant(1)));
}
else {
Xobject lower = null;
Xobject upper = null;
Xobject stride = null;
execFuncArgs.add(Xcons.Cast(Xtype.intType, Xcons.IntConstant(0)));
// lower
if (t.getArg(0) == null)
throw new XMPexception("lower bound cannot be omitted in <from-ref>");
else{
lower = t.getArg(0);
if(fromRefObject.getKind() == XMPobject.NODES && isSquare == true)
lower = Xcons.binaryOp(Xcode.PLUS_EXPR, lower, Xcons.IntConstant(1));
}
// upper
if (t.getArg(1) == null)
throw new XMPexception("upper bound cannot be omitted in <from-ref>");
else{
upper = t.getArg(1);
if(fromRefObject.getKind() == XMPobject.NODES && isSquare == true){
upper = Xcons.binaryOp(Xcode.PLUS_EXPR, t.getArg(0), t.getArg(1));
}
}
// stride
stride = (t.getArg(2) == null)? Xcons.IntConstant(1) : t.getArg(2);
// Output
execFuncArgs.add(Xcons.Cast(Xtype.intType, lower));
execFuncArgs.add(Xcons.Cast(Xtype.intType, upper));
execFuncArgs.add(Xcons.Cast(Xtype.intType, stride));
}
refIndex++;
}
if (refIndex != refDim)
throw new XMPexception("the number of <nodes/template-subscript> should be the same with the dimension");
return new XMPpair<String, XobjList>(new String("NODES"), execFuncArgs);
}
}
}
private final static int GMOVE_ALL = 0;
private final static int GMOVE_INDEX = 1;
private final static int GMOVE_RANGE = 2;
private final static int GMOVE_COLL = 400;
private final static int GMOVE_IN = 401;
private final static int GMOVE_OUT = 402;
private boolean istheSameShape(Xobject leftExpr, Xobject rightExpr)
{
if(rightExpr.Opcode() == Xcode.ARRAY_REF || rightExpr.Opcode() == Xcode.VAR)
return true;
if(rightExpr.Opcode() != leftExpr.Opcode())
return false;
int leftDims = leftExpr.getArg(1).Nargs();
int leftNumTriplets = 0;
for(int i=0;i<leftDims;i++)
if(leftExpr.getArg(1).getArg(i).Opcode() == Xcode.INDEX_RANGE)
leftNumTriplets++;
int rightDims = rightExpr.getArg(1).Nargs();
int rightNumTriplets = 0;
for(int i=0;i<rightDims;i++)
if(rightExpr.getArg(1).getArg(i).Opcode() == Xcode.INDEX_RANGE)
rightNumTriplets++;
if(leftNumTriplets == rightNumTriplets)
return true;
else
return false;
}
private void translateGmove(PragmaBlock pb) throws XMPexception {
// start translation
XobjList gmoveDecl = (XobjList)pb.getClauses();
XMPsymbolTable localXMPsymbolTable = XMPlocalDecl.declXMPsymbolTable(pb);
BlockList gmoveBody = pb.getBody();
Block b = Bcons.emptyBlock();
BasicBlock bb = b.getBasicBlock();
// GMOVE_NORMAL | GMOVE_IN | GMOVE_OUT
Xobject gmoveClause = gmoveDecl.getArg(0);
// async id
Xobject async = gmoveDecl.getArg(1);
// acc or host
XobjList accOrHost = (XobjList)gmoveDecl.getArg(2);
boolean isACC = accOrHost.hasIdent("acc");
boolean isHost = accOrHost.hasIdent("host");
if(!isACC && !isHost){
isHost = true;
}else if(isHost && isACC){
throw new XMPexception(pb.getLineNo(), "gmove for both acc and host is unimplemented");
}
String funcPrefix = "_XMP_gmove_";
if(isACC){
funcPrefix += "acc_";
}
// check body
Xobject assignStmt = null;
String checkBodyErrMsg = new String("gmove directive should be written before one assign statement");
Block gmoveBodyHead = gmoveBody.getHead();
if(gmoveBodyHead instanceof SimpleBlock) {
if (gmoveBodyHead.getNext() != null) {
throw new XMPexception(checkBodyErrMsg);
}
Statement gmoveStmt = gmoveBodyHead.getBasicBlock().getHead();
if (gmoveStmt.getNext() != null) {
throw new XMPexception(checkBodyErrMsg);
}
if(gmoveStmt.getExpr().Opcode() == Xcode.ASSIGN_EXPR) {
assignStmt = gmoveStmt.getExpr();
} else {
throw new XMPexception(checkBodyErrMsg);
}
} else {
throw new XMPexception(checkBodyErrMsg);
}
Xobject leftExpr = assignStmt.left();
XMPpair<XMPalignedArray, XobjList> leftExprInfo = getXMPalignedArrayExpr(pb, leftExpr);
XMPalignedArray leftAlignedArray = null;
if (leftExprInfo != null) leftAlignedArray = leftExprInfo.getFirst();
Xobject rightExpr = assignStmt.right();
XMPpair<XMPalignedArray, XobjList> rightExprInfo = getXMPalignedArrayExpr(pb, assignStmt.right());
XMPalignedArray rightAlignedArray = null;
if (rightExprInfo != null) rightAlignedArray = rightExprInfo.getFirst();
// check LHS and RHS
if (rightAlignedArray == null && leftAlignedArray == null){
pb.replace(pb.getBody().getHead()); // ignore the gmove directive
return;
}
if (rightAlignedArray != null){
StorageClass sclass = rightAlignedArray.getArrayId().getStorageClass();
if (gmoveClause.getInt() == XMPcollective.GMOVE_IN &&
sclass != StorageClass.EXTDEF && sclass != StorageClass.EXTERN)
XMP.fatal("Current limitation: Only a SAVE or MODULE variable can be the target of gmove in/out.");
}
if (leftAlignedArray != null){
StorageClass sclass = leftAlignedArray.getArrayId().getStorageClass();
if (gmoveClause.getInt() == XMPcollective.GMOVE_OUT &&
sclass != StorageClass.EXTDEF && sclass != StorageClass.EXTERN)
XMP.fatal("Current limitation: Only a SAVE or MODULE variable can be the target of gmove in/out.");
}
if(! istheSameShape(leftExpr, assignStmt.right())){
throw new XMPexception("The shape of the right side and the shape of the left side are different.");
}
if (rightAlignedArray == null && gmoveClause.getInt() == XMPcollective.GMOVE_IN){
XMP.fatal("gmove in cannot be applied to a local rhs.");
}
if (leftAlignedArray == null && gmoveClause.getInt() == XMPcollective.GMOVE_OUT){
XMP.fatal("gmove out cannot be applied to a local lhs.");
}
// convert gmove to array
if (leftExpr.Opcode() == Xcode.SUB_ARRAY_REF &&
leftAlignedArray != null && rightAlignedArray == null &&
gmoveClause.getInt() == XMPcollective.GMOVE_NORMAL){
Block arrayBlock = convertGmoveToArray(pb, leftAlignedArray, leftExpr, rightExpr);
pb.replace(arrayBlock);
translateArray((PragmaBlock)arrayBlock);
return;
}
// generate gmove funcs.
Ident left_desc = buildGmoveDesc(leftExpr, bb, pb, isACC);
Ident right_desc = buildGmoveDesc(rightExpr, bb, pb, isACC);
Ident f = _globalDecl.declExternFunc(isACC? "xmpc_gmv_do_acc" : "xmpc_gmv_do", Xtype.FsubroutineType);
Xobject args = Xcons.List(left_desc.Ref(), right_desc.Ref(), gmoveClause);
bb.add(f.callSubroutine(args));
Ident d = _globalDecl.declExternFunc("xmpc_gmv_dealloc", Xtype.FsubroutineType);
Xobject args_l = Xcons.List(left_desc.Ref());
bb.add(d.callSubroutine(args_l));
Xobject args_r = Xcons.List(right_desc.Ref());
bb.add(d.callSubroutine(args_r));
if (async.Opcode() != Xcode.LIST){
Ident g;
Xobject arg = Xcons.List(async);
g = _globalDecl.declExternFunc("xmpc_init_async", Xtype.FsubroutineType);
bb.insert(g.callSubroutine(arg));
g = _globalDecl.declExternFunc("xmpc_start_async", Xtype.FsubroutineType);
bb.add(g.callSubroutine(arg));
}
if(isACC){
XobjList vars = Xcons.List();
vars.add(Xcons.Symbol(Xcode.VAR, leftAlignedArray.getName()));
vars.add(Xcons.Symbol(Xcode.VAR, rightAlignedArray.getName()));
b =
Bcons.PRAGMA(Xcode.ACC_PRAGMA, "HOST_DATA",
Xcons.List(Xcons.List(Xcons.String("USE_DEVICE"), vars)), Bcons.blockList(b));
}
Block gmoveBlock = Bcons.COMPOUND(Bcons.blockList(b));
pb.replace(gmoveBlock);
Xobject profileClause = gmoveDecl.getArg(3);
addProfileFunctions(profileClause, b, "gmove", pb);
}
private Ident buildGmoveDesc(Xobject x, BasicBlock bb, PragmaBlock pb, boolean isACC) throws XMPexception
{
Ident descId = pb.getParentBlock().getBody().declLocalIdent(tmpSym.getStr("gmv"), Xtype.voidPtrType);
XMPalignedArray array = null;
String arrayName;
Xtype type;
Xobject a;
Ident f;
Xobject args;
switch (x.Opcode()){
case ARRAY_REF:
case SUB_ARRAY_REF:
arrayName = XMPutil.getArrayName(x);
a = x.getArg(0);
array = _globalDecl.getXMPalignedArray(arrayName, pb);
type = (array != null) ? array.getArrayType() : a.Type();
int n = type.getNumDimensions();
if (array != null){ // global
f = _globalDecl.declExternFunc(isACC? "xmpc_gmv_g_alloc_acc" : "xmpc_gmv_g_alloc", Xtype.FsubroutineType);
args = Xcons.List(descId.getAddr(), array.getDescId().Ref());
if(isACC) args.add(array.getAddrObj());
bb.add(f.callSubroutine(args));
XobjList subscripts = (XobjList)x.getArg(1);
f = _globalDecl.declExternFunc("xmpc_gmv_g_dim_info", Xtype.FsubroutineType);
for (int i = 0; i < n; i++, type = type.getRef()){
Xobject sub = subscripts.getArg(i);
if (! sub.isIndexRange()){ // index
args = Xcons.List(descId.Ref(), Xcons.IntConstant(i),
Xcons.IntConstant(GMOVE_INDEX),
sub,
Xcons.IntConstant(0), Xcons.IntConstant(0));
}
else { // triplet
Xobject lb = ((XobjList)sub).getArg(0);
if (lb == null) lb = Xcons.IntConstant(0);
Xobject len = ((XobjList)sub).getArg(1);
Xobject st = ((XobjList)sub).getArg(2);
if (st == null) st = Xcons.IntConstant(1);
args = Xcons.List(descId.Ref(), Xcons.IntConstant(i),
Xcons.IntConstant(GMOVE_RANGE),
lb, len, st);
}
bb.add(f.callSubroutine(args));
}
}
else { // local
f = _globalDecl.declExternFunc("xmpc_gmv_l_alloc", Xtype.FsubroutineType);
type = a.Type();
// if (!type.isArray())
// XMP.fatal("buildGmoveDesc: SUB_ARRAY_REF for non-array");
// args = Xcons.List(descId.getAddr(), a,
// Xcons.IntConstant(type.getNumDimensions()));
if (type.isArray()){
;
}
else if (type.isPointer()){
// current limitation: local pointers are always considered to be one-dimensional.
n = 1;
}
else {
XMP.fatal("buildGmoveDesc: SUB_ARRAY_REF for non-array");
}
args = Xcons.List(descId.getAddr(), a, Xcons.IntConstant(n));
bb.add(f.callSubroutine(args));
Xobject a_lb = Xcons.IntConstant(0);
Xobject a_len;
XobjList subscripts = (XobjList)x.getArg(1);
f = _globalDecl.declExternFunc("xmpc_gmv_l_dim_info", Xtype.FsubroutineType);
for (int i = 0; i < n; i++, type = type.getRef()){
if (type.getKind() == Xtype.POINTER){
a_len = Xcons.LongLongConstant(0, 1); // dummy
}
else {
long dimSize = type.getArraySize();
if (dimSize == 0){
Ident ret = declIdentWithBlock(pb, "XMP_" + arrayName + "_ret" + Integer.toString(i),
Xtype.intType);
Ident sz = declIdentWithBlock(pb, "XMP_" + arrayName + "_len" + Integer.toString(i),
Xtype.intType);
f = _globalDecl.declExternFunc("xmp_array_ubound", Xtype.intType);
args = Xcons.List(array.getDescId().Ref(), Xcons.IntConstant(i+1), sz.getAddr());
pb.insert(Xcons.Set(ret.Ref(), Xcons.binaryOp(Xcode.MINUS_EXPR, f.Call(args), Xcons.IntConstant(1))));
a_len = sz.Ref();
}
else if (dimSize == -1){
a_len = type.getArraySizeExpr();
}
else {
a_len = Xcons.LongLongConstant(0, dimSize);
}
}
Xobject sub = subscripts.getArg(i);
if (! sub.isIndexRange()){ // index
args = Xcons.List(descId.Ref(), Xcons.IntConstant(i),
a_lb, a_len,
Xcons.IntConstant(GMOVE_INDEX),
sub, Xcons.IntConstant(0), Xcons.IntConstant(0));
}
else { // triplet
Xobject lb = ((XobjList)sub).getArg(0);
if (lb == null) lb = Xcons.IntConstant(0);
Xobject len = ((XobjList)sub).getArg(1);
Xobject st = ((XobjList)sub).getArg(2);
if (st == null) st = Xcons.IntConstant(1);
args = Xcons.List(descId.Ref(), Xcons.IntConstant(i),
a_lb, a_len,
Xcons.IntConstant(GMOVE_INDEX),
lb, len, st);
}
bb.add(f.callSubroutine(args));
}
}
break;
case VAR:
arrayName = x.getName();
array = _globalDecl.getXMPalignedArray(arrayName, pb);
if (array != null){ // name of a global array
f = _globalDecl.declExternFunc("xmpc_gmv_g_alloc", Xtype.FsubroutineType);
args = Xcons.List(descId.getAddr(), array.getDescId().Ref());
bb.add(f.callSubroutine(args));
f = _globalDecl.declExternFunc("xmpc_gmv_g_dim_info", Xtype.FsubroutineType);
for (int i = 0; i < array.getDim(); i++){
args = Xcons.List(descId.Ref(), Xcons.IntConstant(i),
Xcons.IntConstant(GMOVE_ALL),
Xcons.IntConstant(0),
Xcons.IntConstant(0), Xcons.IntConstant(0));
bb.add(f.callSubroutine(args));
}
}
else { // scalar or name of a local array
f = _globalDecl.declExternFunc(isACC? "xmpc_gmv_l_alloc_acc" : "xmpc_gmv_l_alloc", Xtype.FsubroutineType);
args = Xcons.List(descId.Ref(), Xcons.AddrOf(x), Xcons.IntConstant(0));
bb.add(f.callSubroutine(args));
}
break;
default:
XMP.fatal("gmove must be followed by a simple assignment");
}
return descId;
}
private Block convertGmoveToArray(PragmaBlock pb, XMPalignedArray leftAlignedArray, Xobject leftExpr, Xobject rightExpr)
{
Xobject onRef = Xcons.List();
Xobject t = Xcons.Symbol(Xcode.VAR, leftAlignedArray.getAlignTemplate().getName());
onRef.add(t);
Xobject subscripts = Xcons.List();
for (int i = 0; i < leftAlignedArray.getAlignTemplate().getDim(); i++){
subscripts.add(null);
}
XobjList arrayRefs = (XobjList)leftExpr.getArg(1);
for (int i = 0; i < leftAlignedArray.getDim(); i++){
int alignSubscriptIndex = leftAlignedArray.getAlignSubscriptIndexAt(i);
Xobject alignSubscriptOffset = leftAlignedArray.getAlignSubscriptExprAt(i);
Xobject sub = arrayRefs.getArg(i);
Xobject triplet;
if (sub.isIndexRange()){
Xobject lb = sub.getArg(0);
if (alignSubscriptOffset != null) lb = Xcons.binaryOp(Xcode.PLUS_EXPR, lb, alignSubscriptOffset);
Xobject ub = sub.getArg(1);
Xobject st = sub.getArg(2);
triplet = Xcons.List(lb, ub, st);
}
else {
Xobject lb = sub.getArg(0);
if (alignSubscriptOffset != null) lb = Xcons.binaryOp(Xcode.PLUS_EXPR, lb, alignSubscriptOffset);
Xobject ub = lb;
Xobject st = Xcons.IntConstant(1);
triplet = Xcons.List(lb, ub, st);
}
subscripts.setArg(alignSubscriptIndex, triplet);
}
subscripts.add(Xcons.StringConstant("ROUND"));
onRef.add(subscripts);
Xobject args = Xcons.List(onRef);
return Bcons.PRAGMA(Xcode.XMP_PRAGMA, "LOOP", args, pb.getBody());
}
private XMPpair<XMPalignedArray, XobjList> getXMPalignedArrayExpr(PragmaBlock pb, Xobject expr) throws XMPexception {
switch (expr.Opcode()) {
case ARRAY_REF:
return parseArrayRefExpr(pb, expr);
case SUB_ARRAY_REF:
return parseSubArrayRefExpr(pb, expr, getArrayAccList(pb, expr));
case VAR:
return null;
default:
throw new XMPexception("unsupported expression: gmove");
}
}
private XobjList getArrayAccList(PragmaBlock pb, Xobject expr) throws XMPexception
{
XMPsymbolTable localXMPsymbolTable = XMPlocalDecl.declXMPsymbolTable(pb);
XobjList accList = Xcons.List();
String arrayName = XMPutil.getArrayName(expr);
XMPalignedArray alignedArray = _globalDecl.getXMPalignedArray(arrayName, pb);
if (alignedArray == null) {
Ident arrayId = pb.findVarIdent(arrayName);
Xtype arrayType = arrayId.Type();
int arrayDim = arrayType.getNumDimensions();
if (arrayDim > XMP.MAX_DIM) {
throw new XMPexception("array dimension should be less than " + (XMP.MAX_DIM + 1));
}
arrayType = arrayType.getRef();
for (int i = 0; i < arrayDim - 1; i++, arrayType = arrayType.getRef()) {
accList.add(XMPutil.getArrayElmtsObj(arrayType));
}
accList.add(Xcons.IntConstant(1));
} else {
int arrayDim = alignedArray.getDim();
for (int i = 0; i < arrayDim; i++) {
accList.add(alignedArray.getAccIdAt(i).Ref());
}
}
return accList;
}
private XMPpair<XMPalignedArray, XobjList> parseSubArrayRefExpr(PragmaBlock pb,
Xobject expr, XobjList accList) throws XMPexception {
XMPsymbolTable localXMPsymbolTable = XMPlocalDecl.declXMPsymbolTable(pb);
Xobject arrayAddr = expr.getArg(0);
String arrayName = XMPutil.getArrayName(expr);
XMPalignedArray alignedArray = _globalDecl.getXMPalignedArray(arrayName, pb);
XobjList arrayRefs = (XobjList)expr.getArg(1);
XobjList castedArrayRefs = Xcons.List();
int dim = 0;
if (arrayRefs != null) {
for (Xobject x : arrayRefs) {
if (x.isIndexRange()) {
castedArrayRefs.add(Xcons.Cast(Xtype.intType, x.getArg(0)));
castedArrayRefs.add(Xcons.Cast(Xtype.intType, x.getArg(1)));
castedArrayRefs.add(Xcons.Cast(Xtype.intType, x.getArg(2)));
castedArrayRefs.add(Xcons.Cast(Xtype.unsignedlonglongType, accList.getArg(dim)));
} else {
castedArrayRefs.add(Xcons.Cast(Xtype.intType, x));
castedArrayRefs.add(Xcons.Cast(Xtype.intType, Xcons.IntConstant(1)));
castedArrayRefs.add(Xcons.Cast(Xtype.intType, Xcons.IntConstant(0)));
castedArrayRefs.add(Xcons.Cast(Xtype.unsignedlonglongType, accList.getArg(dim)));
}
dim++;
}
}
if (alignedArray == null) {
castedArrayRefs.cons(Xcons.Cast(Xtype.intType, Xcons.IntConstant(dim)));
castedArrayRefs.cons(Xcons.Cast(Xtype.voidPtrType, arrayAddr));
}
return new XMPpair<XMPalignedArray, XobjList>(alignedArray, castedArrayRefs);
}
private XMPpair<XMPalignedArray, XobjList> parseArrayRefExpr(PragmaBlock pb, Xobject expr) throws XMPexception {
XMPsymbolTable localXMPsymbolTable = XMPlocalDecl.declXMPsymbolTable(pb);
String arrayName = expr.getArg(0).getSym();
XMPalignedArray alignedArray = _globalDecl.getXMPalignedArray(arrayName, pb);
XobjList castedArrayRefs = Xcons.List();
XobjList arrayRefs = (XobjList)expr.getArg(1);
if (arrayRefs != null) {
for (Xobject x : arrayRefs) {
castedArrayRefs.add(Xcons.Cast(Xtype.intType, x));
}
}
return new XMPpair<XMPalignedArray, XobjList>(alignedArray, castedArrayRefs);
}
private XMPquadruplet<String, Boolean, XobjList, XMPobject> createExecOnRefArgs(XobjList onRef,
Block block) throws XMPexception {
if (onRef.getArg(0) == null) {
// execute on global communicator
XobjList globalRef = (XobjList)onRef.getArg(1);
boolean splitComm = false;
XobjList tempArgs = Xcons.List();
// lower
if (globalRef.getArg(0) == null) tempArgs.add(Xcons.IntConstant(1));
else {
splitComm = true;
tempArgs.add(globalRef.getArg(0));
}
// upper
if (globalRef.getArg(1) == null) tempArgs.add(_globalDecl.getWorldSizeId().Ref());
else {
splitComm = true;
tempArgs.add(globalRef.getArg(1));
}
// stride
if (globalRef.getArg(2) == null) tempArgs.add(Xcons.IntConstant(1));
else {
splitComm = true;
tempArgs.add(globalRef.getArg(2));
}
String execFuncSuffix = null;
XobjList execFuncArgs = null;
if (splitComm) {
execFuncSuffix = "GLOBAL_PART";
execFuncArgs = tempArgs;
}
else {
execFuncSuffix = "NODES_ENTIRE";
execFuncArgs = Xcons.List(_globalDecl.getWorldDescId().Ref());
}
return new XMPquadruplet<String, Boolean, XobjList, XMPobject>(execFuncSuffix, splitComm, execFuncArgs, null);
}
else {
// execute on <object-ref>
// check object name collision
String objectName = onRef.getArg(0).getString();
XMPobject onRefObject = _globalDecl.getXMPobject(objectName, block);
if (onRefObject == null)
throw new XMPexception("cannot find '" + objectName + "' nodes/template");
Xobject ontoNodesRef = null;
Xtype castType = null;
switch (onRefObject.getKind()) {
case XMPobject.NODES:
ontoNodesRef = onRefObject.getDescId().Ref();
castType = Xtype.intType;
break;
case XMPobject.TEMPLATE:
XMPtemplate ontoTemplate = (XMPtemplate)onRefObject;
if (!ontoTemplate.isDistributed())
throw new XMPexception("template '" + objectName + "' is not distributed");
XMPnodes ontoNodes = ((XMPtemplate)onRefObject).getOntoNodes();
ontoNodesRef = ontoNodes.getDescId().Ref();
castType = Xtype.longlongType;
break;
default:
throw new XMPexception("unknown object type");
}
// create arguments
if (onRef.getArg(1) == null || onRef.getArg(1).getArgs() == null){
return new XMPquadruplet<String, Boolean, XobjList, XMPobject>(new String("NODES_ENTIRE"), false, Xcons.List(ontoNodesRef), onRefObject);
}
else {
boolean splitComm = false;
int refIndex = 0;
int refDim = onRefObject.getDim();
String kind_bracket = onRef.getArg(1).getTail().getString();
boolean isSquare = kind_bracket.equals("SQUARE");
onRef.getArg(1).removeLastArgs(); // Remove information of ROUND or SQUARE
if(isSquare) ((XobjList)onRef.getArg(1)).reverse();
XobjList tempArgs = Xcons.List();
for (XobjArgs i = onRef.getArg(1).getArgs(); i != null; i = i.nextArgs()) {
if (refIndex == refDim)
throw new XMPexception("wrong nodes dimension indicated, too many");
XobjList t = (XobjList)i.getArg();
if (t == null || t.getArgs() == null) {
splitComm = true;
tempArgs.add(Xcons.Cast(Xtype.intType, Xcons.IntConstant(1)));
}
else {
Xobject lower = null;
Xobject upper = null;
Xobject stride = null;
tempArgs.add(Xcons.Cast(Xtype.intType, Xcons.IntConstant(0)));
// lower
if (t.getArg(0) == null || (t.getArg(0) instanceof XobjList && t.getArg(0).getArgs() == null)) {
lower = onRefObject.getLowerAt(refIndex);
}
else {
splitComm = true;
lower = t.getArg(0);
if(onRefObject.getKind() == XMPobject.NODES && isSquare == true)
lower = Xcons.binaryOp(Xcode.PLUS_EXPR, lower, Xcons.IntConstant(1));
}
// upper
if (t.getArg(1) == null || (t.getArg(0) instanceof XobjList && t.getArg(1).getArgs() == null)) {
upper = onRefObject.getUpperAt(refIndex);
}
else {
splitComm = true;
if(onRefObject.getKind() == XMPobject.NODES && isSquare == true){
upper = Xcons.binaryOp(Xcode.PLUS_EXPR, t.getArg(0), t.getArg(1));
}
else if(onRefObject.getKind() == XMPobject.TEMPLATE && isSquare == true){
upper = Xcons.binaryOp(Xcode.PLUS_EXPR, lower, t.getArg(1));
upper = Xcons.binaryOp(Xcode.MINUS_EXPR, upper, Xcons.IntConstant(1));
}
else
upper = t.getArg(1);
}
// stride
if (t.getArg(2) == null || t.getArg(2).equals(Xcons.IntConstant(1))){
stride = Xcons.IntConstant(1);
}
else {
splitComm = true;
stride = t.getArg(2);
}
// Output
tempArgs.add(Xcons.Cast(castType, lower));
tempArgs.add(Xcons.Cast(castType, upper));
tempArgs.add(Xcons.Cast(castType, stride));
}
refIndex++;
}
if (refIndex != refDim)
throw new XMPexception("the number of <nodes/template-subscript> should be the same with the dimension");
if (splitComm) {
String execFuncSuffix = null;
XobjList execFuncArgs = null;
execFuncArgs = tempArgs;
switch (onRefObject.getKind()) {
case XMPobject.NODES:
execFuncSuffix = "NODES_PART";
execFuncArgs.cons(ontoNodesRef);
break;
case XMPobject.TEMPLATE:
execFuncSuffix = "TEMPLATE_PART";
execFuncArgs.cons(((XMPtemplate)onRefObject).getDescId().Ref());
break;
default:
throw new XMPexception("unknown object type");
}
return new XMPquadruplet<String, Boolean, XobjList, XMPobject>(execFuncSuffix, splitComm, execFuncArgs, onRefObject);
}
else
return new XMPquadruplet<String, Boolean, XobjList, XMPobject>(new String("NODES_ENTIRE"), splitComm,
Xcons.List(ontoNodesRef), onRefObject);
}
}
}
private void translateArray(PragmaBlock pb) throws XMPexception {
// start translation
XobjList arrayDecl = (XobjList)pb.getClauses();
XMPsymbolTable localXMPsymbolTable = XMPlocalDecl.declXMPsymbolTable(pb);
BlockList arrayBody = pb.getBody();
// check body
Statement arrayStmt = null;
Xobject assignStmt = null;
String checkBodyErrMsg = new String("array directive should be written before one assign statement");
Block arrayBodyHead = arrayBody.getHead();
if (arrayBodyHead instanceof SimpleBlock) {
if (arrayBodyHead.getNext() != null) {
throw new XMPexception(checkBodyErrMsg);
}
arrayStmt = arrayBodyHead.getBasicBlock().getHead();
if (arrayStmt.getNext() != null) {
throw new XMPexception(checkBodyErrMsg);
}
if (arrayStmt.getExpr().Opcode() == Xcode.ASSIGN_EXPR) {
assignStmt = arrayStmt.getExpr();
}
else {
throw new XMPexception(checkBodyErrMsg);
}
}
else {
throw new XMPexception(checkBodyErrMsg);
}
Block loopBlock = convertArrayToLoop(pb, arrayStmt);
pb.replace(loopBlock);
translateLoop((PragmaBlock)loopBlock, false);
}
private Block convertArrayToLoop(PragmaBlock pb, Statement arrayStmt) throws XMPexception {
Xobject assignStmt = arrayStmt.getExpr();
Xobject left = assignStmt.left();
XMPpair<XMPalignedArray, XobjList> leftExprInfo = getXMPalignedArrayExpr(pb, left);
XMPalignedArray leftAlignedArray = leftExprInfo.getFirst();
List<Ident> varList = new ArrayList<Ident>(XMP.MAX_DIM);
List<Ident> varListTemplate = new ArrayList<Ident>(XMP.MAX_DIM);
for (int i = 0; i < XMP.MAX_DIM; i++) varListTemplate.add(null);
List<Xobject> lbList = new ArrayList<Xobject>(XMP.MAX_DIM);
List<Xobject> lenList = new ArrayList<Xobject>(XMP.MAX_DIM);
List<Xobject> stList = new ArrayList<Xobject>(XMP.MAX_DIM);
//
// convert LHS
//
if (left.Opcode() != Xcode.SUB_ARRAY_REF){
throw new XMPexception("ARRAY not followed by array ref.");
}
String arrayName = XMPutil.getArrayName(left);
XMPalignedArray array = _globalDecl.getXMPalignedArray(arrayName, pb);
Xtype arrayType = null;
if (array != null){
arrayType = array.getArrayType();
}
else {
Ident arrayId = pb.findVarIdent(arrayName);
if (arrayId != null){
arrayType = arrayId.Type();
}
}
if (arrayType == null) throw new XMPexception("array should be declared statically");
Xtype elemType = arrayType.getArrayElementType();
int n = arrayType.getNumDimensions();
XobjList subscripts = (XobjList)left.getArg(1);
for (int i = 0; i < n; i++, arrayType = arrayType.getRef()){
long dimSize = arrayType.getArraySize();
Xobject sizeExpr;
if (dimSize == 0 || arrayType.getKind() == Xtype.POINTER){
Ident ret = declIdentWithBlock(pb, "XMP_" + arrayName + "_ret" + Integer.toString(i),
Xtype.intType);
Ident sz = declIdentWithBlock(pb, "XMP_" + arrayName + "_ub" + Integer.toString(i),
Xtype.intType);
Ident f = _globalDecl.declExternFunc("xmp_array_ubound", Xtype.intType);
Xobject args = Xcons.List(array.getDescId().Ref(), Xcons.IntConstant(i+1),
sz.getAddr());
pb.insert(Xcons.Set(ret.Ref(), Xcons.binaryOp(Xcode.PLUS_EXPR, f.Call(args), Xcons.IntConstant(i+1))));
sizeExpr = sz;
}
else if (dimSize == -1){
sizeExpr = arrayType.getArraySizeExpr();
}
else {
sizeExpr = Xcons.LongLongConstant(0, dimSize);
}
Xobject sub = subscripts.getArg(i);
Ident var;
Xobject lb, len, st;
if (! sub.isIndexRange()) continue;
var = declIdentWithBlock(pb, "_XMP_loop_i" + Integer.toString(i), Xtype.intType);
varList.add(var);
if (leftAlignedArray.getAlignMannerAt(i) != XMPalignedArray.NOT_ALIGNED){
varListTemplate.set(leftAlignedArray.getAlignSubscriptIndexAt(i), var);
}
lb = ((XobjList)sub).getArg(0);
if (lb == null) lb = Xcons.IntConstant(0);
len = ((XobjList)sub).getArg(1);
//if (len == null) len = Xcons.binaryOp(Xcode.MINUS_EXPR, sizeExpr, lb);
if (len == null) len = sizeExpr;
st = ((XobjList)sub).getArg(2);
if (st == null) st = Xcons.IntConstant(1);
lbList.add(lb);
lenList.add(len);
stList.add(st);
Xobject expr;
expr = Xcons.binaryOp(Xcode.MUL_EXPR, var.Ref(), st);
expr = Xcons.binaryOp(Xcode.PLUS_EXPR, expr, lb);
subscripts.setArg(i, expr);
}
Xobject new_left = Xcons.arrayRef(elemType, left.getArg(0), subscripts);
//
// convert RHS
//
// NOTE: Since the top level object cannot be replaced, the following conversion is applied to
// the whole assignment.
XobjectIterator j = new topdownXobjectIterator(assignStmt);
for (j.init(); !j.end(); j.next()) {
Xobject x = j.getXobject();
if (x.Opcode() != Xcode.SUB_ARRAY_REF) continue;
int k = 0;
String arrayName1 = XMPutil.getArrayName(x);
XMPalignedArray array1 = _globalDecl.getXMPalignedArray(arrayName1, pb);
Xtype arrayType1 = null;
if (array1 != null){
arrayType1 = array1.getArrayType();
}
else {
Ident arrayId1 = pb.findVarIdent(arrayName1);
if (arrayId1 != null){
arrayType1 = arrayId1.Type();
}
}
if (arrayType1 == null) throw new XMPexception("array should be declared statically");
Xtype elemType1 = arrayType1.getArrayElementType();
int m = arrayType1.getNumDimensions();
XobjList subscripts1 = (XobjList)x.getArg(1);
for (int i = 0; i < m; i++, arrayType1 = arrayType1.getRef()){
Xobject sub = subscripts1.getArg(i);
Ident var;
Xobject lb, st;
if (! sub.isIndexRange()) continue;
//if (array1.getAlignMannerAt(i) == XMPalignedArray.NOT_ALIGNED) continue;
lb = ((XobjList)sub).getArg(0);
if (lb == null) lb = Xcons.IntConstant(0);
st = ((XobjList)sub).getArg(2);
if (st == null) st = Xcons.IntConstant(1);
Xobject expr;
expr = Xcons.binaryOp(Xcode.MUL_EXPR, varList.get(k).Ref(), st);
//Ident loopVar = varListTemplate.get(array1.getAlignSubscriptIndexAt(i));
//if (loopVar == null) XMP.fatal("array on rhs does not conform to that on lhs.");
//expr = Xcons.binaryOp(Xcode.MUL_EXPR, loopVar.Ref(), st);
expr = Xcons.binaryOp(Xcode.PLUS_EXPR, expr, lb);
subscripts1.setArg(i, expr);
k++;
}
Xobject new_x = Xcons.arrayRef(elemType1, x.getArg(0), subscripts1);
j.setXobject(new_x);
}
//
// construct loop
//
BlockList loop = null;
BlockList body = Bcons.emptyBody();
body.add(Xcons.Set(new_left, assignStmt.right()));
for (int i = varList.size() - 1; i >= 0; i--){
loop = Bcons.emptyBody();
// Xobject ub = Xcons.binaryOp(Xcode.MINUS_EXPR, ubList.get(i), lbList.get(i));
// ub = Xcons.binaryOp(Xcode.PLUS_EXPR, ub, stList.get(i));
// ub = Xcons.binaryOp(Xcode.DIV_EXPR, ub, stList.get(i));
// ub = Xcons.binaryOp(Xcode.MINUS_EXPR, ub, Xcons.IntConstant(1));
loop.add(Bcons.FORall(varList.get(i).Ref(), Xcons.IntConstant(0), lenList.get(i), Xcons.IntConstant(1),
Xcode.LOG_LT_EXPR, body));
body = loop;
}
//
// convert ARRAY to LOOP directive
//
Xobject args = Xcons.List();
XobjList loopIterList = Xcons.List();
for (int i = 0; i < varList.size(); i++){
if (leftAlignedArray.getAlignMannerAt(i) != XMPalignedArray.NOT_ALIGNED){
loopIterList.add(varList.get(i).Ref());
}
}
args.add(loopIterList);
Xobject onRef = Xcons.List();
String templateName = pb.getClauses().getArg(0).getArg(0).getName();
XMPtemplate template = _globalDecl.getXMPtemplate(templateName, pb);
if (template == null) throw new XMPexception("template '" + templateName + "' not found");
onRef.add(pb.getClauses().getArg(0).getArg(0));
Xobject subscriptList = Xcons.List();
Xobject onSubscripts = pb.getClauses().getArg(0).getArg(1);
if (onSubscripts != null){
for (int i = 0; i < onSubscripts.Nargs(); i++){
Xobject sub = onSubscripts.getArg(i);
if (sub.Opcode() == Xcode.LIST){ // triplet
Xobject lb = ((XobjList)sub).getArg(0);
if (lb == null || (lb.Opcode() == Xcode.LIST && lb.Nargs() == 0)){
if (template.isFixed()){
lb = template.getLowerAt(i);
}
else {
Ident ret = declIdentWithBlock(pb, "XMP_" + template.getName() + "_ret" + Integer.toString(i),
Xtype.intType);
Ident tlb = declIdentWithBlock(pb, "XMP_" + template.getName() + "_lb" + Integer.toString(i),
Xtype.intType);
Ident f = _globalDecl.declExternFunc("xmp_template_lbound", Xtype.intType);
Xobject args1 = Xcons.List(template.getDescId().Ref(), Xcons.IntConstant(i+1), tlb.getAddr());
pb.insert(Xcons.Set(ret.Ref(), f.Call(args1)));
lb = tlb.Ref();
}
}
Xobject st = ((XobjList)sub).getArg(2);
if (st != null){
if (st.Opcode() == Xcode.INT_CONSTANT && ((XobjInt)st).getInt() == 0){ // scalar
subscriptList.add(sub);
continue;
}
}
else st = Xcons.IntConstant(1);
Ident loopVar = varListTemplate.get(i);
if (loopVar != null){
Xobject expr = Xcons.binaryOp(Xcode.MUL_EXPR, loopVar.Ref(), st);
expr = Xcons.binaryOp(Xcode.PLUS_EXPR, expr, lb);
subscriptList.add(expr);
}
else {
subscriptList.add(null);
}
}
else { // scalar
subscriptList.add(sub);
}
}
}
else {
for (int i = 0; i < template.getDim(); i++){
Xobject lb;
if (template.isFixed()){
lb = template.getLowerAt(i);
}
else {
Ident ret = declIdentWithBlock(pb, "XMP_" + template.getName() + "_ret" + Integer.toString(i),
Xtype.intType);
Ident tlb = declIdentWithBlock(pb, "XMP_" + template.getName() + "_lb" + Integer.toString(i),
Xtype.intType);
Ident f = _globalDecl.declExternFunc("xmp_template_lbound", Xtype.intType);
Xobject args1 = Xcons.List(template.getDescId().Ref(), Xcons.IntConstant(i+1), tlb.getAddr());
pb.insert(Xcons.Set(ret.Ref(), f.Call(args1)));
lb = tlb.Ref();
}
Ident loopVar = varListTemplate.get(i);
if (loopVar != null){
Xobject expr = Xcons.binaryOp(Xcode.PLUS_EXPR, loopVar.Ref(), lb);
subscriptList.add(expr);
}
else {
subscriptList.add(null);
}
}
}
onRef.add(subscriptList);
args.add(onRef);
args.add(null); // reduction
args.add(null); // multicore clause ?
args.add(null); // prof
args.add(null); // expand/margin/peel_and_wait
return Bcons.PRAGMA(Xcode.XMP_PRAGMA, "LOOP", args, loop);
}
private void analyzeStaticDesc(PragmaBlock pb){
Block parentBlock = pb.getParentBlock();
XMPsymbolTable localXMPsymbolTable = XMPlocalDecl.declXMPsymbolTable2(parentBlock);
XobjList xmpObjList = (XobjList)pb.getClauses().getArg(0);
for (Xobject xx: xmpObjList){
String objName = xx.getString();
localXMPsymbolTable.putStaticDesc(objName);
}
}
private void setupFinalizer(BlockList body, Ident funcId, XobjList args) throws XMPexception {
BlockIterator i = new topdownBlockIterator(body);
for (i.init(); !i.end(); i.next()) {
Block b = i.getBlock();
if (b.Opcode() == Xcode.GOTO_STATEMENT)
throw new XMPexception("cannot use goto statement here");
else if (b.Opcode() == Xcode.RETURN_STATEMENT)
b.insert(funcId.Call(args));
}
body.add(funcId.Call(args));
}
public static void checkDeclPragmaLocation(PragmaBlock pb) throws XMPexception {
/*
String pragmaNameL = pb.getPragma().toLowerCase();
String errMsg = new String(pragmaNameL +
" directive should be written before declarations, statements and executable directives");
// check parent
Block parentBlock = pb.getParentBlock();
if (parentBlock.Opcode() != Xcode.COMPOUND_STATEMENT)
throw new XMPexception(errMsg);
else {
BlockList parent = pb.getParent();
Xobject declList = parent.getDecls();
if (declList != null) {
if (declList.operand() != null)
throw new XMPexception(errMsg);
}
if (parentBlock.getParentBlock().Opcode() != Xcode.FUNCTION_DEFINITION)
throw new XMPexception(errMsg);
}
// check previous blocks
for (Block prevBlock = pb.getPrev(); prevBlock != null; prevBlock = prevBlock.getPrev()) {
if (prevBlock.Opcode() == Xcode.XMP_PRAGMA) {
XMPpragma prevPragma = XMPpragma.valueOf(((PragmaBlock)prevBlock).getPragma());
switch (XMPpragma.valueOf(((PragmaBlock)prevBlock).getPragma())) {
case NODES:
case TEMPLATE:
case DISTRIBUTE:
case ALIGN:
case SHADOW:
continue;
default:
throw new XMPexception(errMsg);
}
}
else
throw new XMPexception(errMsg);
}
*/
// XXX delete this
return;
}
public void set_all_profile(){
_all_profile = true;
}
public void set_selective_profile(){
_selective_profile = true;
}
public void setScalascaEnabled(boolean v) {
doScalasca = v;
}
public void setTlogEnabled(boolean v) {
doTlog = v;
}
private Block createScalascaStartProfileCall(XobjList funcArgs) {
Ident funcId = XMP.getMacroId("_XMP_M_EPIK_USER_START");
BlockList funcCallList = Bcons.emptyBody();
funcCallList.add(Bcons.Statement(funcId.Call(funcArgs)));
return Bcons.COMPOUND(funcCallList);
}
private Block createScalascaEndProfileCall(XobjList funcArgs) {
Ident funcId = XMP.getMacroId("_XMP_M_EPIK_USER_END");
BlockList funcCallList = Bcons.emptyBody();
funcCallList.add(Bcons.Statement(funcId.Call(funcArgs)));
return Bcons.COMPOUND(funcCallList);
}
private Block createScalascaProfileOffCall(XobjList funcArgs) {
Ident funcId = XMP.getMacroId("_XMP_M_EPIK_GEN_OFF");
BlockList funcCallList = Bcons.emptyBody();
funcCallList.add(Bcons.Statement(funcId.Call(funcArgs)));
return Bcons.COMPOUND(funcCallList);
}
private Block createScalascaProfileOnfCall(XobjList funcArgs) {
Ident funcId = XMP.getMacroId("_XMP_M_EPIK_GEN_ON");
BlockList funcCallList = Bcons.emptyBody();
funcCallList.add(Bcons.Statement(funcId.Call(funcArgs)));
return Bcons.COMPOUND(funcCallList);
}
private Block createTlogMacroInvoke(String macro, XobjList funcArgs) {
Ident macroId = XMP.getMacroId(macro);
BlockList funcCallList = Bcons.emptyBody();
funcCallList.add(Bcons.Statement(macroId.Call(funcArgs)));
return Bcons.COMPOUND(funcCallList);
}
private static Block divideMarginLoop(PragmaBlock pb){
// The type is XMP.LOOP_MARGIN
BlockList loops = Bcons.emptyBody();
boolean flag = false;
XobjList expandOpt = (XobjList)pb.getClauses().getArg(5);
// System.out.println("("+expandOpt.getArg(1).getArg(0).getArg(0).getInt()+" : "+expandOpt.getArg(1).getArg(0).getArg(1).getInt()+" ,"
// +expandOpt.getArg(1).getArg(1).getArg(0).getInt()+" : "+expandOpt.getArg(1).getArg(1).getArg(1).getInt()+")");
PragmaBlock pb1, pb2;
XobjList expandOpt1 = null, expandOpt2 = null;
for (int i = 0; i < expandOpt.getArg(1).Nargs(); i++){
Xobject expandWidth = expandOpt.getArg(1).getArg(i);
Xobject lower = expandWidth.getArg(0);
Xobject upper = expandWidth.getArg(1);
Xobject stride = expandWidth.getArg(2);
if (stride.isIntConstant() && stride.getInt() == -1) continue;
if (!lower.isZeroConstant() && !upper.isZeroConstant()){
flag = true;
// PragmaBlock pb1, pb2;
// XobjList expandOpt1, expandOpt2;
// for lower margin
pb1 = (PragmaBlock)pb.copy();
expandOpt1 = (XobjList)pb1.getClauses().getArg(5);
for (int j = 0; j < expandOpt1.getArg(1).Nargs(); j++){
Xobject expandWidth1 = expandOpt1.getArg(1).getArg(j);
if (j == i){
expandWidth1.setArg(0, lower);
expandWidth1.setArg(1, Xcons.IntConstant(0));
}
else if (j > i){
expandWidth1.setArg(2, Xcons.IntConstant(-1)); // edge of margin
}
else { // j < i
expandWidth1.setArg(0, Xcons.IntConstant(0));
expandWidth1.setArg(1, Xcons.IntConstant(0));
}
}
// System.out.println(" ("+expandOpt1.getArg(1).getArg(0).getArg(0).getInt()+" : "+expandOpt1.getArg(1).getArg(0).getArg(1).getInt()+" ,"
// +expandOpt1.getArg(1).getArg(1).getArg(0).getInt()+" : "+expandOpt1.getArg(1).getArg(1).getArg(1).getInt()+")");
loops.add(pb1);
// for upper margin
pb2 = (PragmaBlock)pb.copy();
expandOpt2 = (XobjList)pb2.getClauses().getArg(5);
for (int j = 0; j < expandOpt1.getArg(1).Nargs(); j++){
Xobject expandWidth2 = expandOpt2.getArg(1).getArg(j);
if (j == i){
expandWidth2.setArg(0, Xcons.IntConstant(0));
expandWidth2.setArg(1, upper);
}
else if (j > i){
expandWidth2.setArg(2, Xcons.IntConstant(-1)); // edge of margin
}
else { // j < i
expandWidth2.setArg(0, Xcons.IntConstant(0));
expandWidth2.setArg(1, Xcons.IntConstant(0));
}
}
// System.out.println(" ("+expandOpt2.getArg(1).getArg(0).getArg(0).getInt()+" : "+expandOpt2.getArg(1).getArg(0).getArg(1).getInt()+" ,"
// +expandOpt2.getArg(1).getArg(1).getArg(0).getInt()+" : "+expandOpt2.getArg(1).getArg(1).getArg(1).getInt()+")");
loops.add(pb2);
}
}
if (flag){
return Bcons.COMPOUND(loops);
}
else {
return null;
}
}
private static Block peelLoop(PragmaBlock pb){
// The type is XMP.LOOP_PEEL_AND_WAIT
BlockList bl = Bcons.emptyBody();
// First, create the kernel loop
PragmaBlock pb3 = (PragmaBlock)pb.copy();
pb3.getClauses().getArg(5).setArg(0, Xcons.IntConstant(LOOP_EXPAND));
pb3.getClauses().getArg(5).setArg(1, pb.getClauses().getArg(5).getArg(2));
bl.add(pb3);
// Second, create wait_async
XobjList clauses = Xcons.List();
clauses.add(Xcons.List(pb.getClauses().getArg(5).getArg(1)));
clauses.add(null);
PragmaBlock pb2 = new PragmaBlock(Xcode.XMP_PRAGMA, "WAIT_ASYNC", clauses, null);
bl.add(pb2);
// Third, create the peeled Loop
PragmaBlock pb1 = (PragmaBlock)pb.copy();
pb1.getClauses().getArg(5).setArg(0, Xcons.IntConstant(LOOP_MARGIN));
pb1.getClauses().getArg(5).setArg(1, pb.getClauses().getArg(5).getArg(2));
bl.add(pb1);
return Bcons.COMPOUND(bl);
}
}
| 0 | 0.862222 | 1 | 0.862222 | game-dev | MEDIA | 0.661613 | game-dev | 0.917119 | 1 | 0.917119 |
BigheadSMZ/Zelda-LA-DX-HD-Updated | 5,502 | ladxhd_game_source_code/InGame/GameObjects/NPCs/ObjFrog.cs | using System;
using Microsoft.Xna.Framework;
using ProjectZ.InGame.GameObjects.Base;
using ProjectZ.InGame.GameObjects.Base.CObjects;
using ProjectZ.InGame.GameObjects.Base.Components;
using ProjectZ.InGame.GameObjects.Base.Components.AI;
using ProjectZ.InGame.GameObjects.Things;
using ProjectZ.InGame.SaveLoad;
using ProjectZ.InGame.Things;
namespace ProjectZ.InGame.GameObjects.NPCs
{
internal class ObjFrog : GameObject
{
private readonly Animator _animator;
private readonly BodyComponent _body;
private readonly AiComponent _aiComponent;
private readonly AiTriggerSwitch _hitCooldown;
private int _direction;
public ObjFrog(Map.Map map, int posX, int posY) : base(map)
{
SprEditorImage = Resources.SprNpCs;
EditorIconSource = new Rectangle(84, 28, 14, 12);
EntityPosition = new CPosition(posX + 8, posY + 16, 0);
EntitySize = new Rectangle(-8, -16, 16, 16);
_body = new BodyComponent(EntityPosition, -6, -8, 12, 8, 8)
{
MoveCollision = OnCollision,
CollisionTypes = Values.CollisionTypes.Normal |
Values.CollisionTypes.NPCWall,
FieldRectangle = map.GetField(posX, posY),
MaxJumpHeight = 4f,
DragAir = 0.99f,
Drag = 0.85f,
Gravity = -0.15f
};
_animator = AnimatorSaveLoad.LoadAnimator("NPCs/frog");
var sprite = new CSprite(EntityPosition);
var animationComponent = new AnimationComponent(_animator, sprite, new Vector2(-7, -12));
_hitCooldown = new AiTriggerSwitch(250);
var stateSitInit = new AiState();
stateSitInit.Trigger.Add(new AiTriggerRandomTime(ToJump, 125, 1000));
stateSitInit.Trigger.Add(_hitCooldown);
var stateSit = new AiState();
stateSit.Trigger.Add(_hitCooldown);
stateSit.Trigger.Add(new AiTriggerRandomTime(ToJump, 750, 1500));
var stateJump = new AiState(UpdateJump);
stateJump.Trigger.Add(_hitCooldown);
_aiComponent = new AiComponent();
_aiComponent.States.Add("sitInit", stateSitInit);
_aiComponent.States.Add("sit", stateSit);
_aiComponent.States.Add("jump", stateJump);
// start by locking into a random direction
_direction = Game1.RandomNumber.Next(0, 4);
_animator.Play("sit_" + _direction);
_aiComponent.ChangeState("sitInit");
AddComponent(BodyComponent.Index, _body);
AddComponent(AiComponent.Index, _aiComponent);
AddComponent(AnimationComponent.Index, animationComponent);
//AddComponent(CollisionComponent.Index, new BodyCollisionComponent(_body, Values.CollisionTypes.Normal));
AddComponent(PushableComponent.Index, new PushableComponent(_body.BodyBox, OnPush));
AddComponent(HittableComponent.Index, new HittableComponent(_body.BodyBox, OnHit));
AddComponent(DrawComponent.Index, new BodyDrawComponent(_body, sprite, Values.LayerPlayer));
AddComponent(DrawShadowComponent.Index, new BodyDrawShadowComponent(_body, sprite));
new ObjSpriteShadow("sprshadowm", this, Values.LayerPlayer, map);
}
private void ToSit()
{
_aiComponent.ChangeState("sit");
// stop and wait
_body.Velocity = Vector3.Zero;
_animator.Play("sit_" + _direction);
}
private void ToJump()
{
_aiComponent.ChangeState("jump");
// change the direction
var rotation = Game1.RandomNumber.Next(0, 628) / 100f;
var direction = new Vector2(
(float)Math.Sin(rotation),
(float)Math.Cos(rotation)) * Game1.RandomNumber.Next(25, 40) / 50f;
_direction = AnimationHelper.GetDirection(direction);
_body.Velocity = new Vector3(direction.X * 1.5f, direction.Y * 1.5f, 1.75f);
_animator.Play("jump_" + _direction);
}
private void UpdateJump()
{
// finished jumping
if (_body.IsGrounded)
ToSit();
}
private Values.HitCollision OnHit(GameObject gameObject, Vector2 direction, HitType damageType, int damage, bool pieceOfPower)
{
if (!_hitCooldown.State)
return Values.HitCollision.None;
_hitCooldown.Reset();
_body.Velocity.X += direction.X * 4.0f;
_body.Velocity.Y += direction.Y * 4.0f;
return Values.HitCollision.Blocking;
}
private void OnCollision(Values.BodyCollision moveCollision)
{
if (_aiComponent.CurrentStateId != "jump")
return;
// repel after wall collision
if (moveCollision.HasFlag(Values.BodyCollision.Horizontal))
_body.Velocity.X *= -0.25f;
else if (moveCollision.HasFlag(Values.BodyCollision.Vertical))
_body.Velocity.Y *= -0.25f;
}
private bool OnPush(Vector2 direction, PushableComponent.PushType type)
{
if (type == PushableComponent.PushType.Impact)
_body.Velocity = new Vector3(direction * 1.25f, _body.Velocity.Z);
return true;
}
}
} | 0 | 0.762375 | 1 | 0.762375 | game-dev | MEDIA | 0.989237 | game-dev | 0.965237 | 1 | 0.965237 |
dotnet/wpf | 13,389 | src/Microsoft.DotNet.Wpf/src/PresentationFramework/MS/Internal/IO/Packaging/indexingfiltermarshaler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// Description:
// Class which acts as adaptor between IManagedFilter and IFilter.
// Used by PackageFilter for XamlFilter and CorePropertiesFilter.
// Used by EncryptedPackageFilter for CorePropertiesFilter.
//
using System.Runtime.InteropServices;
using System.Windows; // for ExceptionStringTable
using MS.Internal.Interop; // for STAT_CHUNK, etc.
namespace MS.Internal.IO.Packaging
{
#region IndexingFilterMarshaler
/// <summary>
/// Adapter for IManagedFilter. Used to obtain an IFilter interface from an IManagedFilter.
/// </summary>
/// <remarks>
/// IManagedFilter is supported by filters which have purely managed implementation and don't work
/// with interop entities. Callers like PackageFilter and EncryptedPackageFilter which support
/// IFilter interfaces interact with IManagedFilters like XamlFilter, PackageCorePropertiesFilter
/// and EncryptedPackageCorePropertiesFilter through IndexingFilterMarshaler.
/// </remarks>
internal class IndexingFilterMarshaler : IFilter
{
#region Static members.
/// <summary>
/// pre-defined GUID for storage properties on file system files (as per MSDN)
/// </summary>
internal static Guid PSGUID_STORAGE = new Guid(0xb725f130, 0x47ef, 0x101a, 0xa5, 0xf1, 0x02, 0x60, 0x8c, 0x9e, 0xeb, 0xac);
/// Cache frequently used size values to incur reflection cost just once.
internal const Int32 _int16Size = 2;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="managedFilter">IManagedFilter implementation</param>
internal IndexingFilterMarshaler(IManagedFilter managedFilter)
{
ArgumentNullException.ThrowIfNull(managedFilter);
_implementation = managedFilter;
}
/// <summary>
/// Init
/// </summary>
/// <param name="cAttributes">length of aAttributes</param>
/// <param name="aAttributes">array of FULLPROPSPEC structs</param>
/// <returns>managed array</returns>
internal static ManagedFullPropSpec[] MarshalFullPropSpecArray(
uint cAttributes, // length of aAttributes
FULLPROPSPEC[] aAttributes)
{
// If there are attributes, these override the flags
if (cAttributes > 0)
{
// Attributes count and array should match.
// This has already been checked for by XpsFilter.
Invariant.Assert(aAttributes != null);
ManagedFullPropSpec[] initAttributes = new ManagedFullPropSpec[checked((int)cAttributes)];
// convert to managed equivalents to isolate the marshaling effort
for (int i = 0; i < cAttributes; i++)
{
// convert and add to local list
initAttributes[i] = new ManagedFullPropSpec(aAttributes[i]);
}
return initAttributes;
}
else
return null;
}
/// <summary>
/// StringToPtr
/// </summary>
/// <remarks>Converts a managed string into the format useful for IFilter.GetText</remarks>
/// <param name="s">string to convert</param>
/// <param name="bufCharacterCount">maximum number of characters to convert</param>
/// <param name="p">pointer to write to</param>
internal static void MarshalStringToPtr(string s, ref uint bufCharacterCount, IntPtr p)
{
// bufCharacterCount is never supposed to be zero at this level.
Invariant.Assert(bufCharacterCount != 0);
// ensure the interface rules are followed
// string must also be null terminated so we restrict the length to buf size - 1
if ((uint)(s.Length) > bufCharacterCount - 1)
throw new InvalidOperationException(SR.FilterGetTextBufferOverflow);
// Return the number of characters written, including the terminating null.
bufCharacterCount = (UInt32)s.Length + 1;
// convert string to unmanaged string and write into provided buffer
Marshal.Copy(s.ToCharArray(), 0, p, s.Length);
// null terminate (16bit's of zero to replace one Unicode character)
Marshal.WriteInt16(p, s.Length * _int16Size, 0);
}
/// <summary>
/// Marshal Managed to Native PROPSPEC
/// </summary>
/// <param name="propSpec"></param>
/// <param name="native"></param>
internal static void MarshalPropSpec(ManagedPropSpec propSpec, ref PROPSPEC native)
{
native.propType = (uint)propSpec.PropType;
switch (propSpec.PropType)
{
case PropSpecType.Id:
native.union.propId = (uint)propSpec.PropId;
break;
case PropSpecType.Name:
native.union.name = Marshal.StringToCoTaskMemUni(propSpec.PropName);
break;
default:
Invariant.Assert(false); // propSpec.PropType is set by internal code in the filter logic.
break;
}
}
/// <summary>
/// Marshal Managed to Native FULLPROPSPEC
/// </summary>
/// <param name="fullPropSpec"></param>
/// <param name="native"></param>
internal static void MarshalFullPropSpec(ManagedFullPropSpec fullPropSpec, ref FULLPROPSPEC native)
{
native.guid = fullPropSpec.Guid;
MarshalPropSpec(fullPropSpec.Property, ref native.property);
}
/// <summary>
/// GetChunk
/// </summary>
/// <returns>An interop STAT_CHUNK from a ManagedChunk</returns>
internal static STAT_CHUNK MarshalChunk(ManagedChunk chunk)
{
STAT_CHUNK native = new STAT_CHUNK
{
idChunk = chunk.ID
};
Invariant.Assert(chunk.BreakType >= CHUNK_BREAKTYPE.CHUNK_NO_BREAK && chunk.BreakType <= CHUNK_BREAKTYPE.CHUNK_EOC);
native.breakType = chunk.BreakType;
Invariant.Assert(
chunk.Flags >= 0
&&
chunk.Flags <= (CHUNKSTATE.CHUNK_TEXT | CHUNKSTATE.CHUNK_VALUE | CHUNKSTATE.CHUNK_FILTER_OWNED_VALUE));
native.flags = chunk.Flags;
native.locale = chunk.Locale;
native.idChunkSource = chunk.ChunkSource;
native.cwcStartSource = chunk.StartSource;
native.cwcLenSource = chunk.LenSource;
MarshalFullPropSpec(chunk.Attribute, ref native.attribute);
return native;
}
/// <summary>
/// MarshalPropVariant
/// </summary>
/// <param name="obj">Object to marshal, should be DateTime or String</param>
/// <returns>newly allocated PROPVARIANT structure</returns>
internal static IntPtr MarshalPropVariant(Object obj)
{
IntPtr pszVal = IntPtr.Zero;
IntPtr pNative = IntPtr.Zero;
try
{
PROPVARIANT v;
if (obj is string)
{
pszVal = Marshal.StringToCoTaskMemAnsi((string)obj);
v = new PROPVARIANT
{
vt = VARTYPE.VT_LPSTR
};
v.union.pszVal = pszVal;
}
else if (obj is DateTime)
{
v = new PROPVARIANT
{
vt = VARTYPE.VT_FILETIME
};
long longFileTime = ((DateTime)obj).ToFileTime();
v.union.filetime.dwLowDateTime = (Int32)longFileTime;
v.union.filetime.dwHighDateTime = (Int32)((longFileTime >> 32) & 0xFFFFFFFF);
}
else
{
throw new InvalidOperationException(
SR.FilterGetValueMustBeStringOrDateTime);
}
// allocate an unmanaged PROPVARIANT to return
pNative = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(PROPVARIANT)));
// Per MSDN, AllocCoTaskMem never returns null: check for IntPtr.Zero instead.
Invariant.Assert(pNative != IntPtr.Zero);
// marshal the managed PROPVARIANT into the unmanaged block and return it
Marshal.StructureToPtr(v, pNative, false);
}
catch
{
if (pszVal != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(pszVal);
}
if (pNative != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(pNative);
}
throw;
}
return pNative;
}
#endregion Static members.
#region IFilter implementation
/// <summary>
/// Init
/// </summary>
/// <param name="grfFlags">usage flags</param>
/// <param name="cAttributes">length of aAttributes</param>
/// <param name="aAttributes">array of FULLPROPSPEC structs</param>
/// <returns>flags</returns>
public IFILTER_FLAGS Init(IFILTER_INIT grfFlags, // IFILTER_INIT value
uint cAttributes, // length of aAttributes
FULLPROPSPEC[] aAttributes) // restrict responses to the specified attributes
{
ManagedFullPropSpec[] managedArray = MarshalFullPropSpecArray(
cAttributes, aAttributes);
return _implementation.Init(grfFlags, managedArray);
}
/// <summary>
/// GetChunk
/// </summary>
/// <returns>the next chunk</returns>
public STAT_CHUNK GetChunk()
{
// Get the managed chunk
ManagedChunk managedChunk = _implementation.GetChunk();
if (managedChunk == null)
{
// End of chunks.
if (ThrowOnEndOfChunks)
{
// Throw exception.
throw new COMException(SR.FilterEndOfChunks,
(int)FilterErrorCode.FILTER_E_END_OF_CHUNKS);
}
// Return STAT_CHUNK with idChunk as 0.
STAT_CHUNK chunk = new STAT_CHUNK
{
idChunk = 0
};
return chunk;
}
// Valid chunk. Return corresponding STAT_CHUNK.
return MarshalChunk(managedChunk);
}
/// <summary>
/// GetText
/// </summary>
/// <param name="bufCharacterCount">Buffer size in Unicode characters (not bytes)</param>
/// <param name="pBuffer">Pre-allocated buffer for us to write into. String must be null-terminated.</param>
public void GetText(ref uint bufCharacterCount, IntPtr pBuffer)
{
// NOTE: bufCharacterCount and pBuffer are already validated by XpsFilter.
// In future, if this class is exposed publicly or used in a way other than
// through XpsFilter, proper checks needs to be present either here or in the caller.
// get the managed string and marshal
MarshalStringToPtr(_implementation.GetText((int)bufCharacterCount - 1),
ref bufCharacterCount, pBuffer);
}
/// <summary>
/// GetValue
/// </summary>
/// <returns>newly allocated PROPVARIANT structure</returns>
public IntPtr GetValue()
{
return MarshalPropVariant(_implementation.GetValue());
}
/// <summary>
/// BindRegion
/// </summary>
/// <param name="origPos"></param>
/// <param name="riid"></param>
/// <remarks>
/// The MSDN specification requires this function to return E_NOTIMPL for the time being.
/// </remarks>
public IntPtr BindRegion(FILTERREGION origPos, ref Guid riid)
{
// The following exception maps to E_NOTIMPL.
throw new NotImplementedException(SR.FilterBindRegionNotImplemented);
}
#endregion IFilter implementation
#region Properties
/// <summary>
/// If set to true, FILTER_E_END_OF_CHUNKS exception is thrown
/// by IFilter.GetChunk() on end of chunks.
/// If false, a STAT_CHUNK with idChunk as 0 is returned instead.
/// </summary>
internal bool ThrowOnEndOfChunks
{
get
{
return _throwOnEndOfChunks;
}
set
{
_throwOnEndOfChunks = value;
}
}
#endregion Properties
#region Fields
private IManagedFilter _implementation;
private bool _throwOnEndOfChunks = true;
#endregion Fields
}
#endregion IndexingFilterMarshaler
}
| 0 | 0.905419 | 1 | 0.905419 | game-dev | MEDIA | 0.227658 | game-dev | 0.895997 | 1 | 0.895997 |
Sduibek/fixtsrc | 21,299 | SCRIPTS/GLOBLDOR.SSL | procedure start;
procedure use_p_proc;// script_action == 6
procedure use_skill_on_p_proc;// script_action == 8
procedure use_obj_on_p_proc;// script_action == 7
procedure look_at_p_proc;// script_action == 21
procedure description_p_proc;// script_action == 3
procedure damage_p_proc;// script_action == 14
procedure map_enter_p_proc;// script_action == 15
procedure map_update_p_proc;// script_action == 23
procedure Trapped_And_Locked;
procedure Locked_Door;
procedure Trapped_Door;
procedure Damage_Dude;
procedure Skill_Checks;
procedure Stat_Checks;
procedure Locks_Check;
procedure Display_Armed_And_Locked;
procedure Display_Locked;
procedure Display_Trapped;
variable Only_Once;
variable Locks;
variable Traps;
variable Per;
procedure start
begin
if (script_action == 6) then begin//use_p_proc - Use, Activate, or Manipulate the Object or Item
call use_p_proc;
end
else begin
if (script_action == 15) then begin//map_enter_p_proc (or "map_init") called when entering from World Map, on green "exit" grids, SOME ladders, doesn't appear to call on elevators or manholes
call map_enter_p_proc;
end
else begin
if (script_action == 23) then begin//map_update_p_proc -- called every dozen seconds or so, & additionally on certain events (exit dialog, end combat, load map, etc)
call map_update_p_proc;
end
else begin
if (script_action == 7) then begin//<-- use_obj_on_p_proc
call use_obj_on_p_proc;
end
else begin
if (script_action == 21) then begin//MOUSE-OVER DESCRIPTION -- look_at_p_proc - (usually brief length. hovered mouse over object, haven't clicked on it.)
call look_at_p_proc;
end
else begin
if (script_action == 3) then begin//DETAILED ON-CLICK DESCRIPTION (Binoculars icon) - description_p_proc
call description_p_proc;
end
else begin
if (script_action == 8) then begin//<-- use_skill_on_p_proc
call use_skill_on_p_proc;
end
else begin
if (script_action == 14) then begin//<-- damage_p_proc - has this Critter or Object been shot, hit with TNT, punched, etc.
call damage_p_proc;
end
end
end
end
end
end
end
end
end
procedure use_p_proc
begin
variable LVar0 := 0;
LVar0 := roll_vs_skill(source_obj, 11, -20);
if (global_var(224) != 2) then begin
script_overrides;
display_msg(message_str(306, 205));
end
else begin
if (local_var(2) == 0) then begin
if (is_success(LVar0)) then begin
script_overrides;
display_msg(message_str(306, 204));
reg_anim_func(2, source_obj);
end
else begin
if (obj_is_locked(self_obj)) then begin
script_overrides;
set_local_var(0, local_var(0) + 1);
call Damage_Dude;
end
else begin
script_overrides;
set_local_var(0, local_var(0) + 1);
call Damage_Dude;
end
end
end
else begin
if (local_var(3) == 0) then begin
script_overrides;
display_msg(message_str(306, 105));
end
end
end
end
procedure use_skill_on_p_proc
begin
if ((local_var(2) == 0) and obj_is_locked(self_obj)) then begin
call Trapped_And_Locked;
end
else begin
if (local_var(2) == 0) then begin
call Trapped_Door;
end
else begin
if (obj_is_locked(self_obj)) then begin
call Locked_Door;
end
end
end
end
procedure use_obj_on_p_proc
begin
variable LVar0 := 0;
variable LVar1 := 0;
variable LVar2 := 0;
LVar0 := obj_pid(obj_being_used_with);
if (LVar0 == 77) then begin
script_overrides;
if (local_var(2) == 0) then begin
LVar1 := roll_vs_skill(source_obj, 11, -20);
if (is_success(LVar1)) then begin
display_msg(204);
reg_anim_func(2, source_obj);
end
else begin
set_local_var(0, local_var(0) + 1);
call Damage_Dude;
end
end
if (obj_is_locked(self_obj)) then begin
LVar2 := roll_vs_skill(source_obj, 9, -10);
if (is_success(LVar2)) then begin
obj_unlock(self_obj);
set_local_var(3, 1);
display_msg(message_str(306, 109));
display_msg(message_str(766, 103) + "45" + message_str(766, 104));
give_exp_points(45);
end
else begin
if (is_critical(LVar2)) then begin
display_msg(message_str(306, 121));
jam_lock(self_obj);
display_msg(message_str(306, 110));
rm_obj_from_inven(source_obj, LVar0);
destroy_object(LVar0);
end
else begin
display_msg(message_str(306, 122));
end
end
end
end
else begin
if (LVar0 == 97) then begin
script_overrides;
set_local_var(2, 1);
obj_unlock(self_obj);
set_local_var(3, 1);
display_msg(message_str(306, 106));
end
end
end
procedure look_at_p_proc
begin
script_overrides;
display_msg(message_str(306, 123));
end
procedure description_p_proc
begin
script_overrides;
if ((local_var(3) == 0) and (local_var(2) == 0)) then begin
call Skill_Checks;
call Display_Armed_And_Locked;
end
else begin
if (local_var(2) == 0) then begin
call Skill_Checks;
call Display_Trapped;
end
else begin
if (local_var(3) == 0) then begin
call Locks_Check;
call Display_Locked;
end
else begin
display_msg(message_str(306, 123));
end
end
end
end
procedure damage_p_proc
begin
if (local_var(1) > 3) then begin
set_local_var(2, 1);
if (metarule(22, 0) == 0) then begin set_obj_visibility(self_obj, 1); end// MAKE INVISIBLE
obj_open(self_obj);
set_local_var(3, 1);
end
end
procedure map_enter_p_proc
begin
if (local_var(3) == 0) then begin
obj_lock(self_obj);
end
end
procedure map_update_p_proc
begin
if (local_var(3) == 0) then begin
obj_lock(self_obj);
end
else begin
obj_unlock(self_obj);
end
end
procedure Trapped_And_Locked
begin
variable LVar0 := 0;
variable LVar1 := 0;
if (action_being_used == 11) then begin//-- TRAPS
script_overrides;
LVar0 := roll_vs_skill(source_obj, 11, -20);
if (is_success(LVar0)) then begin
display_msg(message_str(306, 113));
set_local_var(2, 1);
display_msg(message_str(766, 103) + "45" + message_str(766, 104));
give_exp_points(45);
end
else begin
if (is_critical(LVar0)) then begin
display_msg(message_str(306, 114));
jam_lock(self_obj);
display_msg(message_str(306, 110));
if (local_var(0) == 0) then begin
set_local_var(0, 4);
end
else begin
set_local_var(0, local_var(0) + 4);
end
call Damage_Dude;
end
else begin
set_local_var(0, local_var(0) + 1);
display_msg(message_str(306, 115));
call Damage_Dude;
end
end
end
else begin
if (action_being_used == 9) then begin//-- LOCKPICK
script_overrides;
LVar0 := roll_vs_skill(source_obj, 9, -30);
LVar1 := roll_vs_skill(source_obj, 11, -20);
if (is_success(LVar1)) then begin
if (is_success(LVar0)) then begin
obj_unlock(self_obj);
set_local_var(3, 1);
display_msg(message_str(306, 116));
display_msg(message_str(766, 103) + "55" + message_str(766, 104));
give_exp_points(55);
end
else begin
if (is_critical(LVar0)) then begin
jam_lock(self_obj);
display_msg(message_str(306, 110));
set_local_var(0, local_var(0) + 2);
display_msg(message_str(306, 117));
call Damage_Dude;
end
else begin
set_local_var(0, local_var(0) + 1);
display_msg(message_str(306, 118));
call Damage_Dude;
end
end
end
else begin
if (is_critical(LVar1)) then begin
display_msg(message_str(306, 120));
if (local_var(0) == 0) then begin
set_local_var(0, 4);
end
else begin
set_local_var(0, local_var(0) + 4);
end
call Damage_Dude;
end
else begin
set_local_var(0, local_var(0) + 1);
display_msg(message_str(306, 119));
call Damage_Dude;
end
end
end
end
end
procedure Locked_Door
begin
variable LVar0 := 0;
if (action_being_used == 9) then begin//-- LOCKPICK
script_overrides;
LVar0 := roll_vs_skill(source_obj, 9, -30);
if (is_success(LVar0)) then begin
obj_unlock(self_obj);
set_local_var(3, 1);
display_msg(message_str(306, 116));
display_msg(message_str(766, 103) + "55" + message_str(766, 104));
give_exp_points(55);
end
else begin
if (is_critical(LVar0)) then begin
jam_lock(self_obj);
display_msg(message_str(306, 110));
game_time_advance(game_ticks(600));
display_msg(message_str(306, 111));
end
else begin
display_msg(message_str(306, 122));
end
end
end
end
procedure Trapped_Door
begin
variable LVar0 := 0;
if (action_being_used == 11) then begin//-- TRAPS
script_overrides;
LVar0 := roll_vs_skill(source_obj, 11, -20);
if (is_success(LVar0)) then begin
display_msg(message_str(306, 113));
set_local_var(2, 1);
display_msg(message_str(766, 103) + "45" + message_str(766, 104));
give_exp_points(45);
end
else begin
if (is_critical(LVar0)) then begin
display_msg(message_str(306, 114));
if (local_var(0) == 0) then begin
set_local_var(0, 4);
end
else begin
set_local_var(0, local_var(0) + 4);
end
call Damage_Dude;
end
else begin
set_local_var(0, local_var(0) + 1);
display_msg(message_str(306, 115));
call Damage_Dude;
end
end
end
end
procedure Damage_Dude
begin
critter_dmg(source_obj, local_var(0), 4 bwor 256);// DMG_BYPASS_ARMOR (256)
if (local_var(0) == 1) then begin
display_msg(message_str(306, 101));
end
else begin
display_msg(message_str(306, 102) + local_var(0) + message_str(306, 103));
end
end
procedure Skill_Checks
begin
variable LVar0 := 0;
variable LVar1 := 0;
variable LVar2 := 0;
LVar0 := roll_vs_skill(source_obj, 11, 0);
LVar1 := roll_vs_skill(source_obj, 9, -10);
LVar2 := do_check(source_obj, 1, 0);
if (is_success(LVar0)) then begin
if (is_critical(LVar0)) then begin
call Locks_Check;
Traps := 3;
end
else begin
call Locks_Check;
Traps := 2;
end
end
else begin
if (is_critical(LVar0)) then begin
call Locks_Check;
Traps := 0;
end
else begin
call Locks_Check;
Traps := 1;
end
end
end
procedure Stat_Checks
begin
variable LVar0 := 0;
LVar0 := do_check(source_obj, 1, 0);
if (is_success(LVar0)) then begin
if (is_critical(LVar0)) then begin
Per := 3;
end
else begin
Per := 2;
end
end
else begin
if (is_critical(LVar0)) then begin
Per := 0;
end
else begin
Per := 1;
end
end
end
procedure Locks_Check
begin
variable LVar0 := 0;
variable LVar1 := 0;
LVar0 := roll_vs_skill(source_obj, 9, -10);
LVar1 := do_check(source_obj, 1, 0);
if (is_success(LVar0)) then begin
if (is_critical(LVar0)) then begin
call Stat_Checks;
Locks := 3;
end
else begin
call Stat_Checks;
Locks := 2;
end
end
else begin
if (is_critical(LVar0)) then begin
call Stat_Checks;
Locks := 0;
end
else begin
call Stat_Checks;
Locks := 1;
end
end
end
procedure Display_Armed_And_Locked
begin
if (Per == 0) then begin
if (Locks == 0) then begin
if (Traps == 0) then begin
display_msg(message_str(306, 124));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 125));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 126));
end
else begin
display_msg(message_str(306, 127));
end
end
end
end
else begin
if (Locks == 1) then begin
if (Traps == 0) then begin
display_msg(message_str(306, 128));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 129));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 130));
end
else begin
display_msg(message_str(306, 131));
end
end
end
end
else begin
if (Locks == 2) then begin
if (Traps == 0) then begin
display_msg(message_str(306, 132));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 133));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 134));
end
else begin
display_msg(message_str(306, 135));
end
end
end
end
else begin
if (Traps == 0) then begin
display_msg(message_str(306, 136));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 137));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 138));
end
else begin
display_msg(message_str(306, 139));
end
end
end
end
end
end
end
else begin
if (Per == 1) then begin
if (Locks == 0) then begin
if (Traps == 0) then begin
display_msg(message_str(306, 140));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 141));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 142));
end
else begin
display_msg(message_str(306, 143));
end
end
end
end
else begin
if (Locks == 1) then begin
if (Traps == 0) then begin
display_msg(message_str(306, 144));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 145));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 146));
end
else begin
display_msg(message_str(306, 147));
end
end
end
end
else begin
if (Locks == 2) then begin
if (Traps == 0) then begin
display_msg(message_str(306, 148));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 149));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 150));
end
else begin
display_msg(message_str(306, 151));
end
end
end
end
else begin
if (Traps == 0) then begin
display_msg(message_str(306, 152));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 153));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 154));
end
else begin
display_msg(message_str(306, 155));
end
end
end
end
end
end
end
else begin
if (Per == 2) then begin
if (Locks == 0) then begin
if (Traps == 0) then begin
display_msg(message_str(306, 156));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 157));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 158));
end
else begin
display_msg(message_str(306, 159));
end
end
end
end
else begin
if (Locks == 1) then begin
if (Traps == 0) then begin
display_msg(message_str(306, 160));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 161));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 162));
end
else begin
display_msg(message_str(306, 163));
end
end
end
end
else begin
if (Locks == 2) then begin
if (Traps == 0) then begin
display_msg(message_str(306, 164));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 165));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 166));
end
else begin
display_msg(message_str(306, 167));
end
end
end
end
else begin
if (Traps == 0) then begin
display_msg(message_str(306, 168));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 169));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 170));
end
else begin
display_msg(message_str(306, 171));
end
end
end
end
end
end
end
else begin
if (Locks == 0) then begin
if (Traps == 0) then begin
display_msg(message_str(306, 172));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 173));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 174));
end
else begin
display_msg(message_str(306, 175));
end
end
end
end
else begin
if (Locks == 1) then begin
if (Traps == 0) then begin
display_msg(message_str(306, 176));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 177));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 178));
end
else begin
display_msg(message_str(306, 179));
end
end
end
end
else begin
if (Locks == 2) then begin
if (Traps == 0) then begin
display_msg(message_str(306, 180));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 181));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 182));
end
else begin
display_msg(message_str(306, 183));
end
end
end
end
else begin
if (Traps == 0) then begin
display_msg(message_str(306, 184));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 185));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 186));
end
else begin
display_msg(message_str(306, 187));
end
end
end
end
end
end
end
end
end
end
procedure Display_Locked
begin
if (Per == 0) then begin
if (Locks == 0) then begin
display_msg(message_str(306, 124));
end
else begin
if (Locks == 1) then begin
display_msg(message_str(306, 128));
end
else begin
if (Locks == 2) then begin
display_msg(message_str(306, 132));
end
else begin
display_msg(message_str(306, 136));
end
end
end
end
else begin
if (Per == 1) then begin
if (Locks == 0) then begin
display_msg(message_str(306, 140));
end
else begin
if (Locks == 1) then begin
display_msg(message_str(306, 144));
end
else begin
if (Locks == 2) then begin
display_msg(message_str(306, 148));
end
else begin
display_msg(message_str(306, 152));
end
end
end
end
else begin
if (Per == 2) then begin
if (Locks == 0) then begin
display_msg(message_str(306, 156));
end
else begin
if (Locks == 1) then begin
display_msg(message_str(306, 160));
end
else begin
if (Locks == 2) then begin
display_msg(message_str(306, 164));
end
else begin
display_msg(message_str(306, 168));
end
end
end
end
else begin
if (Locks == 0) then begin
display_msg(message_str(306, 172));
end
else begin
if (Locks == 1) then begin
display_msg(message_str(306, 176));
end
else begin
if (Locks == 2) then begin
display_msg(message_str(306, 180));
end
else begin
display_msg(message_str(306, 184));
end
end
end
end
end
end
end
procedure Display_Trapped
begin
if (Per == 0) then begin
if (Traps == 0) then begin
display_msg(message_str(306, 188));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 189));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 190));
end
else begin
display_msg(message_str(306, 191));
end
end
end
end
else begin
if (Per == 1) then begin
if (Traps == 0) then begin
display_msg(message_str(306, 192));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 193));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 194));
end
else begin
display_msg(message_str(306, 195));
end
end
end
end
else begin
if (Per == 2) then begin
if (Traps == 0) then begin
display_msg(message_str(306, 196));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 197));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 198));
end
else begin
display_msg(message_str(306, 199));
end
end
end
end
else begin
if (Traps == 0) then begin
display_msg(message_str(306, 200));
end
else begin
if (Traps == 1) then begin
display_msg(message_str(306, 201));
end
else begin
if (Traps == 2) then begin
display_msg(message_str(306, 202));
end
else begin
display_msg(message_str(306, 203));
end
end
end
end
end
end
end
| 0 | 0.798894 | 1 | 0.798894 | game-dev | MEDIA | 0.91253 | game-dev | 0.940555 | 1 | 0.940555 |
OpenXRay/xray-15 | 23,998 | cs/engine/xrGame/Actor.h | #pragma once
#include "xrEngine/feel_touch.h"
#include <xrEngine/feel_sound.h>
#include "xrEngine/IInputReceiver.h"
#include "Include/xrRender/KinematicsAnimated.h"
#include "actor_flags.h"
#include "actor_defs.h"
#include "fire_disp_controller.h"
#include "entity_alive.h"
#include "PHMovementControl.h"
#include "PhysicsShell.h"
#include "InventoryOwner.h"
#include <xrEngine/StatGraph.h>
#include "PhraseDialogManager.h"
#include "ui_defs.h"
#include "step_manager.h"
#include "script_export_space.h"
using namespace ACTOR_DEFS;
class CInfoPortion;
struct GAME_NEWS_DATA;
class CActorCondition;
class CCustomOutfit;
class CKnownContactsRegistryWrapper;
class CEncyclopediaRegistryWrapper;
class CGameTaskRegistryWrapper;
class CGameNewsRegistryWrapper;
class CCharacterPhysicsSupport;
class CActorCameraManager;
// refs
class ENGINE_API CCameraBase;
class ENGINE_API CBoneInstance;
class ENGINE_API CBlend;
class CWeaponList;
class CEffectorBobbing;
class CHolderCustom;
class CUsableScriptObject;
struct SShootingEffector;
struct SSleepEffector;
class CSleepEffectorPP;
class CInventoryBox;
class CHudItem;
class CArtefact;
struct SActorMotions;
struct SActorVehicleAnims;
class CActorCondition;
class SndShockEffector;
class CActorFollowerMngr;
struct CameraRecoil;
class CCameraShotEffector;
class CActorInputHandler;
class CActorMemory;
class CActorStatisticMgr;
class CLocationManager;
class CActor:
public CEntityAlive,
public IInputReceiver,
public Feel::Touch,
public CInventoryOwner,
public CPhraseDialogManager,
public CStepManager,
public Feel::Sound
#ifdef DEBUG
,public pureRender
#endif
{
friend class CActorCondition;
private:
typedef CEntityAlive inherited;
public:
CActor ();
virtual ~CActor ();
public:
virtual BOOL AlwaysTheCrow () { return TRUE; }
virtual CAttachmentOwner* cast_attachment_owner () {return this;}
virtual CInventoryOwner* cast_inventory_owner () {return this;}
virtual CActor* cast_actor () {return this;}
virtual CGameObject* cast_game_object () {return this;}
virtual IInputReceiver* cast_input_receiver () {return this;}
virtual CCharacterPhysicsSupport* character_physics_support () {return m_pPhysics_support;}
virtual CCharacterPhysicsSupport* character_physics_support () const {return m_pPhysics_support;}
virtual CPHDestroyable* ph_destroyable () ;
CHolderCustom* Holder () {return m_holder;}
public:
virtual void Load ( LPCSTR section );
virtual void shedule_Update ( u32 T );
virtual void UpdateCL ( );
virtual void OnEvent ( NET_Packet& P, u16 type );
// Render
virtual void renderable_Render ();
virtual BOOL renderable_ShadowGenerate ();
virtual void feel_sound_new (CObject* who, int type, CSound_UserDataPtr user_data, const Fvector& Position, float power);
virtual Feel::Sound* dcast_FeelSound () { return this; }
float m_snd_noise;
#ifdef DEBUG
virtual void OnRender ();
#endif
public:
virtual bool OnReceiveInfo (shared_str info_id) const;
virtual void OnDisableInfo (shared_str info_id) const;
virtual void NewPdaContact (CInventoryOwner*);
virtual void LostPdaContact (CInventoryOwner*);
#ifdef DEBUG
void DumpTasks();
#endif
protected:
virtual void AddEncyclopediaArticle (const CInfoPortion* info_portion) const;
struct SDefNewsMsg{
GAME_NEWS_DATA* news_data;
u32 time;
bool operator < (const SDefNewsMsg& other) const {return time>other.time;}
};
xr_vector<SDefNewsMsg> m_defferedMessages;
void UpdateDefferedMessages();
public:
void AddGameNews_deffered (GAME_NEWS_DATA& news_data, u32 delay);
virtual void AddGameNews (GAME_NEWS_DATA& news_data);
protected:
CActorStatisticMgr* m_statistic_manager;
public:
virtual void StartTalk (CInventoryOwner* talk_partner);
void RunTalkDialog (CInventoryOwner* talk_partner, bool disable_break);
CActorStatisticMgr& StatisticMgr() {return *m_statistic_manager;}
CEncyclopediaRegistryWrapper *encyclopedia_registry;
CGameNewsRegistryWrapper *game_news_registry;
CCharacterPhysicsSupport *m_pPhysics_support;
virtual LPCSTR Name () const {return CInventoryOwner::Name();}
public:
//PhraseDialogManager
virtual void ReceivePhrase (DIALOG_SHARED_PTR& phrase_dialog);
virtual void UpdateAvailableDialogs (CPhraseDialogManager* partner);
virtual void TryToTalk ();
bool OnDialogSoundHandlerStart (CInventoryOwner *inv_owner, LPCSTR phrase);
bool OnDialogSoundHandlerStop (CInventoryOwner *inv_owner);
virtual void reinit ();
virtual void reload (LPCSTR section);
virtual bool use_bolts () const;
virtual void OnItemTake (CInventoryItem *inventory_item);
virtual void OnItemRuck (CInventoryItem *inventory_item, EItemPlace previous_place);
virtual void OnItemBelt (CInventoryItem *inventory_item, EItemPlace previous_place);
virtual void OnItemDrop (CInventoryItem *inventory_item);
virtual void OnItemDropUpdate ();
virtual void OnPlayHeadShotParticle (NET_Packet P);
virtual void Die (CObject* who);
virtual void Hit (SHit* pHDS);
virtual void PHHit (SHit &H);
virtual void HitSignal (float P, Fvector &vLocalDir, CObject* who, s16 element);
void HitSector (CObject* who, CObject* weapon);
void HitMark (float P, Fvector dir, CObject* who, s16 element, Fvector position_in_bone_space, float impulse, ALife::EHitType hit_type);
void Feel_Grenade_Update( float rad );
virtual float GetMass () ;
virtual float Radius () const;
virtual void g_PerformDrop ();
virtual bool use_default_throw_force ();
virtual float missile_throw_force ();
virtual bool NeedToDestroyObject() const;
virtual ALife::_TIME_ID TimePassedAfterDeath() const;
public:
//
virtual void UpdateArtefactsOnBeltAndOutfit();
virtual void MoveArtefactBelt (const CArtefact* artefact, bool on_belt);
float HitArtefactsOnBelt (float hit_power, ALife::EHitType hit_type);
float GetProtection_ArtefactsOnBelt(ALife::EHitType hit_type);
const xr_vector<const CArtefact*>& ArtefactsOnBelt() {return m_ArtefactsOnBelt;}
protected:
//
ref_sound m_HeavyBreathSnd;
ref_sound m_BloodSnd;
ref_sound m_DangerSnd;
xr_vector<const CArtefact*> m_ArtefactsOnBelt;
protected:
// Death
float m_hit_slowmo;
float m_hit_probability;
s8 m_block_sprint_counter;
// media
SndShockEffector* m_sndShockEffector;
xr_vector<ref_sound> sndHit[ALife::eHitTypeMax];
ref_sound sndDie[SND_DIE_COUNT];
float m_fLandingTime;
float m_fJumpTime;
float m_fFallTime;
float m_fCamHeightFactor;
// Dropping
BOOL b_DropActivated;
float f_DropPower;
//random seed Zoom mode
s32 m_ZoomRndSeed;
//random seed Weapon Effector Shot
s32 m_ShotRndSeed;
bool m_bOutBorder;
// feel_touch,
u32 m_feel_touch_characters;
private:
void SwitchOutBorder(bool new_border_state);
public:
bool m_bAllowDeathRemove;
void SetZoomRndSeed (s32 Seed = 0);
s32 GetZoomRndSeed () { return m_ZoomRndSeed; };
void SetShotRndSeed (s32 Seed = 0);
s32 GetShotRndSeed () { return m_ShotRndSeed; };
public:
void detach_Vehicle ();
void steer_Vehicle (float angle);
void attach_Vehicle (CHolderCustom* vehicle);
virtual bool can_attach (const CInventoryItem *inventory_item) const;
protected:
CHolderCustom* m_holder;
u16 m_holderID;
bool use_Holder (CHolderCustom* holder);
bool use_Vehicle (CHolderCustom* object);
bool use_MountedWeapon (CHolderCustom* object);
void ActorUse ();
protected:
BOOL m_bAnimTorsoPlayed;
static void AnimTorsoPlayCallBack(CBlend* B);
// Rotation
SRotation r_torso;
float r_torso_tgt_roll;
//
SRotation unaffected_r_torso;
//
float r_model_yaw_dest;
float r_model_yaw; // orientation of model
float r_model_yaw_delta; // effect on multiple "strafe"+"something"
public:
SActorMotions* m_anims;
SActorVehicleAnims* m_vehicle_anims;
CBlend* m_current_legs_blend;
CBlend* m_current_torso_blend;
CBlend* m_current_jump_blend;
MotionID m_current_legs;
MotionID m_current_torso;
MotionID m_current_head;
// callback
void SetCallbacks ();
void ResetCallbacks ();
static void Spin0Callback (CBoneInstance*);
static void Spin1Callback (CBoneInstance*);
static void ShoulderCallback (CBoneInstance*);
static void HeadCallback (CBoneInstance*);
static void VehicleHeadCallback (CBoneInstance*);
virtual const SRotation Orientation () const { return r_torso; };
SRotation &Orientation () { return r_torso; };
void g_SetAnimation (u32 mstate_rl);
void g_SetSprintAnimation(u32 mstate_rl,MotionID &head,MotionID &torso,MotionID &legs);
public:
virtual void OnHUDDraw (CCustomHUD* hud);
BOOL HUDview ( )const ;
//visiblity
virtual float ffGetFov () const { return 90.f; }
virtual float ffGetRange () const { return 500.f; }
public:
CActorCameraManager& Cameras () {VERIFY(m_pActorEffector); return *m_pActorEffector;}
IC CCameraBase* cam_Active () {return cameras[cam_active];}
IC CCameraBase* cam_FirstEye () {return cameras[eacFirstEye];}
IC EActorCameras activeCam () { return cam_active; }
protected:
virtual void cam_Set (EActorCameras style);
void cam_Update (float dt, float fFOV);
void cam_Lookout ( const Fmatrix &xform, float camera_height );
void camUpdateLadder (float dt);
void cam_SetLadder ();
void cam_UnsetLadder ();
float currentFOV ();
// Cameras
CCameraBase* cameras[eacMaxCam];
EActorCameras cam_active;
float fPrevCamPos;
Fvector vPrevCamDir;
float fCurAVelocity;
CEffectorBobbing* pCamBobbing;
// ,
CActorCameraManager* m_pActorEffector;
static float f_Ladder_cam_limit;
public:
virtual void feel_touch_new (CObject* O);
virtual void feel_touch_delete (CObject* O);
virtual BOOL feel_touch_contact (CObject* O);
virtual BOOL feel_touch_on_contact (CObject* O);
CGameObject* ObjectWeLookingAt () {return m_pObjectWeLookingAt;}
CInventoryOwner* PersonWeLookingAt () {return m_pPersonWeLookingAt;}
LPCSTR GetDefaultActionForObject () {return *m_sDefaultObjAction;}
protected:
CUsableScriptObject* m_pUsableObject;
// Person we're looking at
CInventoryOwner* m_pPersonWeLookingAt;
CHolderCustom* m_pVehicleWeLookingAt;
CGameObject* m_pObjectWeLookingAt;
CInventoryBox* m_pInvBoxWeLookingAt;
// Tip for action for object we're looking at
shared_str m_sDefaultObjAction;
shared_str m_sCharacterUseAction;
shared_str m_sDeadCharacterUseAction;
shared_str m_sDeadCharacterUseOrDragAction;
shared_str m_sCarCharacterUseAction;
shared_str m_sInventoryItemUseAction;
shared_str m_sInventoryBoxUseAction;
//
bool m_bPickupMode;
// ( ) ()
float m_fFeelGrenadeRadius;
float m_fFeelGrenadeTime; // ()
//
float m_fPickupInfoRadius;
void PickupModeUpdate ();
void PickupInfoDraw (CObject* object);
void PickupModeUpdate_COD ();
public:
void PickupModeOn ();
void PickupModeOff ();
//////////////////////////////////////////////////////////////////////////
// Motions ( )
//////////////////////////////////////////////////////////////////////////
public:
void g_cl_CheckControls (u32 mstate_wf, Fvector &vControlAccel, float &Jump, float dt);
void g_cl_ValidateMState (float dt, u32 mstate_wf);
void g_cl_Orientate (u32 mstate_rl, float dt);
void g_sv_Orientate (u32 mstate_rl, float dt);
void g_Orientate (u32 mstate_rl, float dt);
bool g_LadderOrient () ;
void UpdateMotionIcon (u32 mstate_rl);
bool CanAccelerate ();
bool CanJump ();
bool CanMove ();
float CameraHeight ();
bool CanSprint ();
bool CanRun ();
void StopAnyMove ();
bool AnyAction () {return (mstate_real & mcAnyAction) != 0;};
bool AnyMove () {return (mstate_real & mcAnyMove) != 0;};
bool is_jump ();
u32 MovingState () const {return mstate_real;}
protected:
u32 mstate_wishful;
u32 mstate_old;
u32 mstate_real;
BOOL m_bJumpKeyPressed;
float m_fWalkAccel;
float m_fJumpSpeed;
float m_fRunFactor;
float m_fRunBackFactor;
float m_fWalkBackFactor;
float m_fCrouchFactor;
float m_fClimbFactor;
float m_fSprintFactor;
float m_fWalk_StrafeFactor;
float m_fRun_StrafeFactor;
//////////////////////////////////////////////////////////////////////////
// User input/output
//////////////////////////////////////////////////////////////////////////
public:
virtual void IR_OnMouseMove (int x, int y);
virtual void IR_OnKeyboardPress (int dik);
virtual void IR_OnKeyboardRelease (int dik);
virtual void IR_OnKeyboardHold (int dik);
virtual void IR_OnMouseWheel (int direction);
virtual float GetLookFactor ();
public:
virtual void g_WeaponBones (int &L, int &R1, int &R2);
virtual void g_fireParams (const CHudItem* pHudItem, Fvector& P, Fvector& D);
virtual bool g_stateFire () {return ! ((mstate_wishful & mcLookout) && !IsGameTypeSingle() );}
virtual BOOL g_State (SEntityState& state) const;
virtual float GetWeaponAccuracy () const;
float GetFireDispertion () const {return m_fdisp_controller.GetCurrentDispertion();}
bool IsZoomAimingMode () const {return m_bZoomAimingMode;}
virtual float MaxCarryWeight () const;
float MaxWalkWeight () const;
float get_additional_weight() const;
protected:
CFireDispertionController m_fdisp_controller;
//
void SetZoomAimingMode (bool val) {m_bZoomAimingMode = val;}
bool m_bZoomAimingMode;
//
// ( )
float m_fDispBase;
float m_fDispAim;
//
//
float m_fDispVelFactor;
//
float m_fDispAccelFactor;
//
float m_fDispCrouchFactor;
//crouch+no acceleration
float m_fDispCrouchNoAccelFactor;
// firepoint default firepoint
Fvector m_vMissileOffset;
public:
// ,
Fvector GetMissileOffset () const;
void SetMissileOffset (const Fvector &vNewOffset);
protected:
//
int m_r_hand;
int m_l_finger1;
int m_r_finger2;
int m_head;
int m_eye_left;
int m_eye_right;
int m_l_clavicle;
int m_r_clavicle;
int m_spine2;
int m_spine1;
int m_spine;
int m_neck;
//////////////////////////////////////////////////////////////////////////
// Network
//////////////////////////////////////////////////////////////////////////
void ConvState (u32 mstate_rl, string128 *buf);
public:
virtual BOOL net_Spawn ( CSE_Abstract* DC);
virtual void net_Export ( NET_Packet& P); // export to server
virtual void net_Import ( NET_Packet& P); // import from server
virtual void net_Destroy ();
virtual BOOL net_Relevant ();// { return getSVU() | getLocal(); }; // relevant for export to server
virtual void net_Relcase ( CObject* O ); //
virtual void xr_stdcall on_requested_spawn (CObject *object);
//object serialization
virtual void save (NET_Packet &output_packet);
virtual void load (IReader &input_packet);
virtual void net_Save (NET_Packet& P) ;
virtual BOOL net_SaveRelevant () ;
protected:
xr_deque<net_update> NET;
Fvector NET_SavedAccel;
net_update NET_Last;
BOOL NET_WasInterpolating; // previous update was by interpolation or by extrapolation
u32 NET_Time; // server time of last update
//---------------------------------------------
void net_Import_Base ( NET_Packet& P);
void net_Import_Physic ( NET_Packet& P);
void net_Import_Base_proceed ( );
void net_Import_Physic_proceed ( );
//---------------------------------------------
////////////////////////////////////////////////////////////////////////////
virtual bool can_validate_position_on_spawn (){return false;}
///////////////////////////////////////////////////////
//
xr_deque<net_update_A> NET_A;
//---------------------------------------------
// bool m_bHasUpdate;
/// spline coeff /////////////////////
float SCoeff[3][4]; //
float HCoeff[3][4]; //
Fvector IPosS, IPosH, IPosL; // , ,
#ifdef DEBUG
using VIS_POSITION = xr_deque<Fvector>;
using VIS_POSITION_it = VIS_POSITION::iterator;
VIS_POSITION LastPosS;
VIS_POSITION LastPosH;
VIS_POSITION LastPosL;
#endif
SPHNetState LastState;
SPHNetState RecalculatedState;
SPHNetState PredictedState;
InterpData IStart;
InterpData IRec;
InterpData IEnd;
bool m_bInInterpolation;
bool m_bInterpolate;
u32 m_dwIStartTime;
u32 m_dwIEndTime;
u32 m_dwILastUpdateTime;
//---------------------------------------------
using PH_STATES = xr_deque<SPHNetState>;
using PH_STATES_it = PH_STATES::iterator;
PH_STATES m_States;
u16 m_u16NumBones;
void net_ExportDeadBody (NET_Packet &P);
//---------------------------------------------
void CalculateInterpolationParams();
//---------------------------------------------
virtual void make_Interpolation ();
#ifdef DEBUG
//---------------------------------------------
virtual void OnRender_Network();
//---------------------------------------------
#endif
// Igor ref_geom hFriendlyIndicator;
//////////////////////////////////////////////////////////////////////////
// Actor physics
//////////////////////////////////////////////////////////////////////////
public:
void g_Physics (Fvector& accel, float jump, float dt);
virtual void ForceTransform (const Fmatrix &m);
void SetPhPosition (const Fmatrix& pos);
virtual void PH_B_CrPr (); // actions & operations before physic correction-prediction steps
virtual void PH_I_CrPr (); // actions & operations after correction before prediction steps
virtual void PH_A_CrPr (); // actions & operations after phisic correction-prediction steps
// virtual void UpdatePosStack ( u32 Time0, u32 Time1 );
virtual void MoveActor (Fvector NewPos, Fvector NewDir);
virtual void SpawnAmmoForWeapon (CInventoryItem *pIItem);
virtual void RemoveAmmoForWeapon (CInventoryItem *pIItem);
virtual void spawn_supplies ();
virtual bool human_being () const
{
return (true);
}
virtual shared_str GetDefaultVisualOutfit () const {return m_DefaultVisualOutfit;};
virtual void SetDefaultVisualOutfit (shared_str DefaultOutfit) {m_DefaultVisualOutfit = DefaultOutfit;};
virtual void UpdateAnimation () { g_SetAnimation(mstate_real); };
virtual void ChangeVisual ( shared_str NewVisual );
virtual void OnChangeVisual ();
virtual void RenderIndicator (Fvector dpos, float r1, float r2, const ui_shader &IndShader);
virtual void RenderText (LPCSTR Text, Fvector dpos, float* pdup, u32 color);
//////////////////////////////////////////////////////////////////////////
// Controlled Routines
//////////////////////////////////////////////////////////////////////////
void set_input_external_handler (CActorInputHandler *handler);
bool input_external_handler_installed () const {return (m_input_external_handler != 0);}
IC void lock_accel_for (u32 time){m_time_lock_accel = Device.dwTimeGlobal + time;}
private:
CActorInputHandler *m_input_external_handler;
u32 m_time_lock_accel;
/////////////////////////////////////////
// DEBUG INFO
protected:
CStatGraph *pStatGraph;
shared_str m_DefaultVisualOutfit;
LPCSTR invincibility_fire_shield_3rd;
LPCSTR invincibility_fire_shield_1st;
shared_str m_sHeadShotParticle;
u32 last_hit_frame;
#ifdef DEBUG
friend class CLevelGraph;
#endif
Fvector m_AutoPickUp_AABB;
Fvector m_AutoPickUp_AABB_Offset;
void Check_for_AutoPickUp ();
void SelectBestWeapon (CObject* O);
public:
void SetWeaponHideState (u32 State, bool bSet);
void SetCantRunState (bool bSet);
virtual CCustomOutfit* GetOutfit() const;
private:
CActorCondition *m_entity_condition;
protected:
virtual CEntityConditionSimple *create_entity_condition (CEntityConditionSimple* ec);
public:
IC CActorCondition &conditions () const;
virtual DLL_Pure *_construct ();
virtual bool natural_weapon () const {return false;}
virtual bool natural_detector () const {return false;}
virtual bool use_center_to_aim () const;
protected:
u16 m_iLastHitterID;
u16 m_iLastHittingWeaponID;
s16 m_s16LastHittedElement;
Fvector m_vLastHitDir;
Fvector m_vLastHitPos;
float m_fLastHealth;
bool m_bWasHitted;
bool m_bWasBackStabbed;
virtual bool Check_for_BackStab_Bone (u16 element);
public:
virtual void SetHitInfo (CObject* who, CObject* weapon, s16 element, Fvector Pos, Fvector Dir);
virtual void OnHitHealthLoss (float NewHealth);
virtual void OnCriticalHitHealthLoss ();
virtual void OnCriticalWoundHealthLoss ();
virtual void OnCriticalRadiationHealthLoss ();
virtual bool InventoryAllowSprint ();
virtual void OnNextWeaponSlot ();
virtual void OnPrevWeaponSlot ();
void SwitchNightVision ();
void SwitchTorch ();
public:
virtual void on_weapon_shot_start (CWeapon *weapon);
virtual void on_weapon_shot_update ();
virtual void on_weapon_shot_stop ();
virtual void on_weapon_shot_remove (CWeapon *weapon);
virtual void on_weapon_hide (CWeapon *weapon);
Fvector weapon_recoil_delta_angle ();
Fvector weapon_recoil_last_delta ();
protected:
virtual void update_camera (CCameraShotEffector* effector);
//step manager
virtual bool is_on_ground ();
private:
CActorMemory *m_memory;
public:
void SetActorVisibility (u16 who, float value);
IC CActorMemory &memory () const {VERIFY(m_memory); return(*m_memory); };
void OnDifficultyChanged ();
IC float HitProbability () {return m_hit_probability;}
virtual CVisualMemoryManager*visual_memory () const;
virtual BOOL BonePassBullet (int boneID);
virtual void On_B_NotCurrentEntity ();
private:
collide::rq_results RQR;
BOOL CanPickItem (const CFrustum& frustum, const Fvector& from, CObject* item);
xr_vector<ISpatial*> ISpatialResult;
private:
CLocationManager *m_location_manager;
public:
IC const CLocationManager &locations () const
{
VERIFY (m_location_manager);
return (*m_location_manager);
}
private:
ALife::_OBJECT_ID m_holder_id;
public:
virtual bool register_schedule () const {return false;}
virtual bool is_ai_obstacle () const;
float GetRestoreSpeed (ALife::EConditionRestoreType const& type);
private:
static const float cam_inert_value;
float prev_cam_inert_value;
public:
virtual void On_SetEntity();
virtual void On_LostEntity();
static CPhysicsShell *actor_camera_shell;
DECLARE_SCRIPT_REGISTER_FUNCTION
};
add_to_type_list(CActor)
#undef script_type_list
#define script_type_list save_type_list(CActor)
extern bool isActorAccelerated (u32 mstate, bool ZoomMode);
IC CActorCondition &CActor::conditions () const{ VERIFY(m_entity_condition); return(*m_entity_condition);}
extern CActor* g_actor;
CActor* Actor ();
extern const float s_fFallTime;
| 0 | 0.91532 | 1 | 0.91532 | game-dev | MEDIA | 0.956874 | game-dev | 0.547818 | 1 | 0.547818 |
emscripten-core/emscripten | 5,241 | system/lib/compiler-rt/lib/asan/asan_internal.h | //===-- asan_internal.h -----------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// ASan-private header which defines various general utilities.
//===----------------------------------------------------------------------===//
#ifndef ASAN_INTERNAL_H
#define ASAN_INTERNAL_H
#include "asan_flags.h"
#include "asan_interface_internal.h"
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_internal_defs.h"
#include "sanitizer_common/sanitizer_libc.h"
#include "sanitizer_common/sanitizer_stacktrace.h"
#if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)
# error \
"The AddressSanitizer run-time should not be instrumented by AddressSanitizer"
#endif
// Build-time configuration options.
// If set, asan will intercept C++ exception api call(s).
#ifndef ASAN_HAS_EXCEPTIONS
# define ASAN_HAS_EXCEPTIONS 1
#endif
// If set, values like allocator chunk size, as well as defaults for some flags
// will be changed towards less memory overhead.
#ifndef ASAN_LOW_MEMORY
# if SANITIZER_IOS || SANITIZER_ANDROID
# define ASAN_LOW_MEMORY 1
# else
# define ASAN_LOW_MEMORY 0
# endif
#endif
#ifndef ASAN_DYNAMIC
# ifdef PIC
# define ASAN_DYNAMIC 1
# else
# define ASAN_DYNAMIC 0
# endif
#endif
// All internal functions in asan reside inside the __asan namespace
// to avoid namespace collisions with the user programs.
// Separate namespace also makes it simpler to distinguish the asan run-time
// functions from the instrumented user code in a profile.
namespace __asan {
class AsanThread;
using __sanitizer::StackTrace;
void AsanInitFromRtl();
bool TryAsanInitFromRtl();
// asan_win.cpp
void InitializePlatformExceptionHandlers();
// Returns whether an address is a valid allocated system heap block.
// 'addr' must point to the beginning of the block.
bool IsSystemHeapAddress(uptr addr);
// asan_rtl.cpp
void PrintAddressSpaceLayout();
void NORETURN ShowStatsAndAbort();
// asan_shadow_setup.cpp
void InitializeShadowMemory();
// asan_malloc_linux.cpp / asan_malloc_mac.cpp
void ReplaceSystemMalloc();
// asan_linux.cpp / asan_mac.cpp / asan_win.cpp
uptr FindDynamicShadowStart();
void AsanCheckDynamicRTPrereqs();
void AsanCheckIncompatibleRT();
// Unpoisons platform-specific stacks.
// Returns true if all stacks have been unpoisoned.
bool PlatformUnpoisonStacks();
// asan_rtl.cpp
// Unpoison a region containing a stack.
// Performs a sanity check and warns if the bounds don't look right.
// The warning contains the type string to identify the stack type.
void UnpoisonStack(uptr bottom, uptr top, const char *type);
// asan_thread.cpp
AsanThread *CreateMainThread();
// Support function for __asan_(un)register_image_globals. Searches for the
// loaded image containing `needle' and then enumerates all global metadata
// structures declared in that image, applying `op' (e.g.,
// __asan_(un)register_globals) to them.
typedef void (*globals_op_fptr)(__asan_global *, uptr);
void AsanApplyToGlobals(globals_op_fptr op, const void *needle);
void AsanOnDeadlySignal(int, void *siginfo, void *context);
void SignContextStack(void *context);
void ReadContextStack(void *context, uptr *stack, uptr *ssize);
void StopInitOrderChecking();
// Wrapper for TLS/TSD.
void AsanTSDInit(void (*destructor)(void *tsd));
void *AsanTSDGet();
void AsanTSDSet(void *tsd);
void PlatformTSDDtor(void *tsd);
void AppendToErrorMessageBuffer(const char *buffer);
void *AsanDlSymNext(const char *sym);
// Returns `true` iff most of ASan init process should be skipped due to the
// ASan library being loaded via `dlopen()`. Platforms may perform any
// `dlopen()` specific initialization inside this function.
bool HandleDlopenInit();
void InstallAtExitCheckLeaks();
void InstallAtForkHandler();
#define ASAN_ON_ERROR() \
if (&__asan_on_error) \
__asan_on_error()
bool AsanInited();
extern bool replace_intrin_cached;
extern void (*death_callback)(void);
// These magic values are written to shadow for better error
// reporting.
const int kAsanHeapLeftRedzoneMagic = 0xfa;
const int kAsanHeapFreeMagic = 0xfd;
const int kAsanStackLeftRedzoneMagic = 0xf1;
const int kAsanStackMidRedzoneMagic = 0xf2;
const int kAsanStackRightRedzoneMagic = 0xf3;
const int kAsanStackAfterReturnMagic = 0xf5;
const int kAsanInitializationOrderMagic = 0xf6;
const int kAsanUserPoisonedMemoryMagic = 0xf7;
const int kAsanContiguousContainerOOBMagic = 0xfc;
const int kAsanStackUseAfterScopeMagic = 0xf8;
const int kAsanGlobalRedzoneMagic = 0xf9;
const int kAsanInternalHeapMagic = 0xfe;
const int kAsanArrayCookieMagic = 0xac;
const int kAsanIntraObjectRedzone = 0xbb;
const int kAsanAllocaLeftMagic = 0xca;
const int kAsanAllocaRightMagic = 0xcb;
static const uptr kCurrentStackFrameMagic = 0x41B58AB3;
static const uptr kRetiredStackFrameMagic = 0x45E0360E;
} // namespace __asan
#endif // ASAN_INTERNAL_H
| 0 | 0.812481 | 1 | 0.812481 | game-dev | MEDIA | 0.36346 | game-dev | 0.56188 | 1 | 0.56188 |
jval1972/DelphiDoom | 19,791 | Base/i_input.pas | //------------------------------------------------------------------------------
//
// DelphiDoom is a source port of the game Doom and it is
// based on original Linux Doom as published by "id Software"
// Copyright (C) 1993-1996 by id Software, Inc.
// Copyright (C) 2004-2022 by Jim Valavanis
//
// 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.
//
//------------------------------------------------------------------------------
// Site : https://sourceforge.net/projects/delphidoom/
//------------------------------------------------------------------------------
{$I Doom32.inc}
unit i_input;
interface
//==============================================================================
//
// I_InitInput
//
//==============================================================================
procedure I_InitInput;
//==============================================================================
//
// I_ProcessInput
//
//==============================================================================
procedure I_ProcessInput;
//==============================================================================
//
// I_ShutDownInput
//
//==============================================================================
procedure I_ShutDownInput;
//==============================================================================
//
// I_SynchronizeInput
//
//==============================================================================
procedure I_SynchronizeInput(active: boolean);
//==============================================================================
//
// I_SetMouseClicks
//
//==============================================================================
procedure I_SetMouseClicks(val: integer);
//==============================================================================
//
// I_GetCapsLock
//
//==============================================================================
function I_GetCapsLock: boolean;
var
usedirectinput: boolean = false;
implementation
uses
Windows,
DirectX,
MMSystem, // For joystick support
{$IFDEF FPC}
d_fpc,
{$ENDIF}
d_delphi,
doomdef,
d_event,
d_main,
i_mainwindow,
i_system;
//==============================================================================
//
// TranslateKey
//
//==============================================================================
function TranslateKey(keycode: integer): integer;
begin
case keycode of
VK_LEFT, VK_NUMPAD4: result := KEY_LEFTARROW;
VK_RIGHT, VK_NUMPAD6: result := KEY_RIGHTARROW;
VK_DOWN, VK_NUMPAD2: result := KEY_DOWNARROW;
VK_UP, VK_NUMPAD8: result := KEY_UPARROW;
VK_ESCAPE: result := KEY_ESCAPE;
VK_RETURN: result := KEY_ENTER;
VK_TAB: result := KEY_TAB;
VK_SNAPSHOT: result := KEY_PRNT;
VK_F1: result := KEY_F1;
VK_F2: result := KEY_F2;
VK_F3: result := KEY_F3;
VK_F4: result := KEY_F4;
VK_F5: result := KEY_F5;
VK_F6: result := KEY_F6;
VK_F7: result := KEY_F7;
VK_F8: result := KEY_F8;
VK_F9: result := KEY_F9;
VK_F10: result := KEY_F10;
VK_F11: result := KEY_F11;
VK_F12: result := KEY_F12;
187: result := KEY_EQUALS;
188: result := Ord(',');
189: result := KEY_MINUS;
VK_BACK: result := KEY_BACKSPACE;
192: result := KEY_CON;
220: result := Ord('\');
{$IFNDEF DOOM}
219: result := Ord('[');
221: result := Ord(']');
{$ENDIF}
VK_ADD: result := Ord('+');
VK_SUBTRACT: result := Ord('-');
VK_MULTIPLY: result := Ord('*');
VK_DIVIDE, 191: result := Ord('/');
VK_DECIMAL, 190: result := Ord('.');
VK_PAUSE: result := KEY_PAUSE;
VK_NUMPAD3, VK_NEXT: result := KEY_PAGEDOWN;
VK_NUMPAD9, VK_PRIOR: result := KEY_PAGEUP;
VK_NUMPAD0, VK_INSERT: result := KEY_INS;
VK_NUMPAD7, VK_HOME: result := KEY_HOME;
VK_NUMPAD1, VK_END: result := KEY_END;
VK_DELETE: result := KEY_DELETE;
else
if (keycode >= Ord('A')) and (keycode <= Ord('Z')) then
result := Ord(tolower(Chr(keycode)))
else if keycode < 128 then
result := keycode
else
result := 0;
end;
end;
//==============================================================================
//
// TranslateSysKey
//
//==============================================================================
function TranslateSysKey(keycode: integer): integer;
begin
case keycode of
VK_SHIFT: result := KEY_RSHIFT;
VK_CONTROL: result := KEY_RCTRL;
VK_MENU: result := KEY_RALT;
else
result := 0;
end;
end;
const
I_IGNORETICKS = 15; // ~ half second
var
ignoretics: integer;
g_pDI: IDirectInputA = nil;
g_pdidKeyboard: IDirectInputDevice = nil;
dikb: TDIKeyboardState; // DirectInput keyboard state buffer
curkeys: PKeyboardState;
oldkeys: PKeyboardState;
// Mouse support
mlastx,
mlasty: integer;
mflags: byte;
// Joystick support
jInfo: TJoyInfoEx;
jPresent: boolean;
jwXpos: UINT;
jwYpos: UINT;
type
setcursorposfunc_t = function(x, y: Integer): BOOL; stdcall;
getcursorposfunc_t = function(var lpPoint: TPoint): BOOL; stdcall;
var
getcursorposfunc: getcursorposfunc_t;
setcursorposfunc: setcursorposfunc_t;
user32inst: THandle;
//==============================================================================
//
// I_InitMouse
//
//==============================================================================
procedure I_InitMouse;
begin
user32inst := LoadLibrary(user32);
getcursorposfunc := GetProcAddress(user32inst, 'GetPhysicalCursorPos');
if not assigned(getcursorposfunc) then
getcursorposfunc := GetProcAddress(user32inst, 'GetCursorPos');
setcursorposfunc := GetProcAddress(user32inst, 'SetPhysicalCursorPos');
if not assigned(setcursorposfunc) then
setcursorposfunc := GetProcAddress(user32inst, 'SetCursorPos');
end;
//==============================================================================
//
// I_ShutDownMouse
//
//==============================================================================
procedure I_ShutDownMouse;
begin
FreeLibrary(user32inst);
end;
//==============================================================================
//
// I_ResetMouse
//
//==============================================================================
procedure I_ResetMouse;
begin
mlastx := SCREENWIDTH div 2;
mlasty := SCREENHEIGHT div 2;
setcursorposfunc(mlastx, mlasty);
mflags := 0;
end;
//==============================================================================
//
// I_InitInput
// Initialize the DirectInput variables using:
// DirectInputCreate
// IDirectInput::CreateDevice
// IDirectInputDevice::SetDataFormat
// IDirectInputDevice::SetCooperativeLevel
//
//==============================================================================
procedure I_InitInput;
var
hres: HRESULT;
dipdw: TDIPropDWORD;
procedure I_ErrorInitInput(const msg: string);
begin
I_Error('I_InitInput(): %s failed, result = %d', [msg, hres]);
end;
begin
ignoretics := 0;
I_InitMouse;
if usedirectinput then
begin
// Register with the DirectInput subsystem and get a pointer
// to a IDirectInput interface we can use
hres := DirectInputCreate(hInstance, DIRECTINPUT_VERSION, g_pDI, nil);
if hres <> DD_OK then
I_ErrorInitInput('DirectInputCreate');
// Obtain an interface to the keybord device
hres := g_pDI.CreateDevice(GUID_SysKeyboard, g_pdidKeyboard, nil);
if hres <> DD_OK then
I_ErrorInitInput('CreateDevice');
// Set the data format to "keyboard format". A data format specifies which
// controls on a device we are interested in, and how they should be
// reported. This tells DirectInput that we will be passing an array of 256
// bytes to IDirectInputDevice::GetDeviceState().
hres := g_pdidKeyboard.SetDataFormat(c_dfDIKeyboard);
if hres <> DD_OK then
I_ErrorInitInput('SetDataFormat');
// Set the cooperative level to let DirectInput know how this device
// should interact with the system and with other DirectInput applications.
// Use DISCL_NONEXCLUSIVE to retrieve device data when acquired, not
// interfering with any other applications which are reading mouse data.
// Use DISCL_FOREGROUND so that if the user switches away from our app,
// automatically release the device back to the system.
hres := g_pdidKeyboard.SetCooperativeLevel(hMainWnd, DISCL_NONEXCLUSIVE or DISCL_FOREGROUND);
if hres <> DD_OK then
I_ErrorInitInput('SetCooperativeLevel');
ZeroMemory(@dipdw, SizeOf(dipdw));
dipdw.diph.dwSize := SizeOf(dipdw);
dipdw.diph.dwHeaderSize := SizeOf(dipdw.diph);
dipdw.diph.dwObj := 0;
dipdw.diph.dwHow := DIPH_DEVICE;
dipdw.dwData := SizeOf(TKeyboardState);
hres := g_pdidKeyboard.SetProperty(DIPROP_BUFFERSIZE, dipdw.diph);
if hres <> DD_OK then
I_ErrorInitInput('SetCooperativeLevel');
printf(' Using DirectInput'#13#10);
end;
curkeys := mallocz(SizeOf(TKeyboardState));
oldkeys := mallocz(SizeOf(TKeyboardState));
printf(' Keyboard initialized'#13#10);
I_ResetMouse;
printf(' Mouse initialized'#13#10);
jPresent := joyGetNumDevs > 0;
if jPresent then
jPresent := joySetCapture(hMainWnd, JOYSTICKID1, 0, false) = JOYERR_NOERROR;
// Get initial joystic position
if jPresent then
begin
ZeroMemory(@jInfo, SizeOf(TJoyInfoEx));
jInfo.dwSize := SizeOf(TJoyInfoEx);
jInfo.dwFlags := JOY_RETURNALL;
if joyGetPosEx(JOYSTICKID1, @jInfo) = JOYERR_NOERROR then
begin
jwXpos := jInfo.wXpos;
jwYpos := jInfo.wYpos;
end;
printf(' Joystick initialized'#13#10);
end
else
printf(' Joystick not found'#13#10);
end;
//==============================================================================
//
// I_ShutDownInput
// Terminate our usage of DirectInput
//
//==============================================================================
procedure I_ShutDownInput;
begin
if usedirectinput then
begin
if g_pDI <> nil then
begin
// Destroy the keyboard object
if g_pdidKeyboard <> nil then
begin
// Unacquire the device (just in case) before exitting.
g_pdidKeyboard.Unacquire;
g_pdidKeyboard._Release;
end;
// Destroy the DInput object
g_pDI._Release;
end;
end;
memfree(pointer(curkeys), SizeOf(TKeyboardState));
memfree(pointer(oldkeys), SizeOf(TKeyboardState));
joyReleaseCapture(JOYSTICKID1);
I_ShutDownMouse;
end;
//==============================================================================
//
// I_ProcessInput
// The game plays here. Read keyboard data and displaying it.
//
//==============================================================================
procedure I_ProcessInput;
function DIKEYtoVK(Key: Byte): Integer;
begin
result := 0;
case Key of
DIK_ESCAPE : result := VK_ESCAPE;
DIK_1 : result := Ord('1');
DIK_2 : result := Ord('2');
DIK_3 : result := Ord('3');
DIK_4 : result := Ord('4');
DIK_5 : result := Ord('5');
DIK_6 : result := Ord('6');
DIK_7 : result := Ord('7');
DIK_8 : result := Ord('8');
DIK_9 : result := Ord('9');
DIK_0 : result := Ord('0');
DIK_EQUALS : result := Ord('=');
DIK_BACK : result := VK_BACK;
DIK_TAB : result := VK_TAB;
DIK_Q : result := Ord('Q');
DIK_W : result := Ord('W');
DIK_E : result := Ord('E');
DIK_R : result := Ord('R');
DIK_T : result := Ord('T');
DIK_Y : result := Ord('Y');
DIK_U : result := Ord('U');
DIK_I : result := Ord('I');
DIK_O : result := Ord('O');
DIK_P : result := Ord('P');
DIK_LBRACKET : result := Ord('[');
DIK_RBRACKET : result := Ord(']');
DIK_RETURN : result := VK_RETURN;
DIK_LCONTROL : result := VK_CONTROL;
DIK_A : result := Ord('A');
DIK_S : result := Ord('S');
DIK_D : result := Ord('D');
DIK_F : result := Ord('F');
DIK_G : result := Ord('G');
DIK_H : result := Ord('H');
DIK_J : result := Ord('J');
DIK_K : result := Ord('K');
DIK_L : result := Ord('L');
DIK_SEMICOLON : result := Ord(';');
DIK_APOSTROPHE : result := Ord('''');
DIK_LSHIFT : result := VK_SHIFT;
DIK_BACKSLASH : result := Ord('\');
DIK_Z : result := Ord('Z');
DIK_X : result := Ord('X');
DIK_C : result := Ord('C');
DIK_V : result := Ord('V');
DIK_B : result := Ord('B');
DIK_N : result := Ord('N');
DIK_M : result := Ord('M');
DIK_COMMA : result := Ord(',');
DIK_PERIOD : result := Ord('.');
DIK_SLASH : result := Ord('/');
DIK_RSHIFT : result := VK_SHIFT;
DIK_MULTIPLY : result := Ord('*');
DIK_LMENU : result := VK_MENU;
DIK_SPACE : result := VK_SPACE;
DIK_CAPITAL : result := VK_CAPITAL;
DIK_F1 : result := VK_F1;
DIK_F2 : result := VK_F2;
DIK_F3 : result := VK_F3;
DIK_F4 : result := VK_F4;
DIK_F5 : result := VK_F5;
DIK_F6 : result := VK_F6;
DIK_F7 : result := VK_F7;
DIK_F8 : result := VK_F8;
DIK_F9 : result := VK_F9;
DIK_F10 : result := VK_F10;
DIK_NUMLOCK : result := VK_NUMLOCK;
DIK_SCROLL : result := VK_SCROLL;
DIK_NUMPAD7 : result := VK_NUMPAD7;
DIK_NUMPAD8 : result := VK_NUMPAD8;
DIK_NUMPAD9 : result := VK_NUMPAD9;
DIK_SUBTRACT : result := VK_SUBTRACT;
DIK_NUMPAD4 : result := VK_NUMPAD4;
DIK_NUMPAD5 : result := VK_NUMPAD5;
DIK_NUMPAD6 : result := VK_NUMPAD6;
DIK_ADD : result := VK_ADD;
DIK_NUMPAD1 : result := VK_NUMPAD1;
DIK_NUMPAD2 : result := VK_NUMPAD2;
DIK_NUMPAD3 : result := VK_NUMPAD3;
DIK_NUMPAD0 : result := VK_NUMPAD0;
DIK_DECIMAL : result := VK_DECIMAL;
DIK_F11 : result := VK_F11;
DIK_F12 : result := VK_F12;
DIK_NUMPADENTER : result := VK_RETURN;
DIK_RCONTROL : result := VK_CONTROL;
DIK_DIVIDE : result := VK_DIVIDE;
DIK_RMENU : result := VK_MENU;
DIK_HOME : result := VK_HOME;
DIK_UP : result := VK_UP;
DIK_PRIOR : result := VK_PRIOR;
DIK_LEFT : result := VK_LEFT;
DIK_RIGHT : result := VK_RIGHT;
DIK_END : result := VK_END;
DIK_DOWN : result := VK_DOWN;
DIK_NEXT : result := VK_NEXT;
DIK_INSERT : result := VK_INSERT;
DIK_DELETE : result := VK_DELETE;
DIK_LWIN : result := VK_LWIN;
DIK_RWIN : result := VK_RWIN;
DIK_APPS : result := VK_APPS;
end;
end;
var
hres: HRESULT;
i: integer;
ev: event_t;
key: integer;
p: PKeyboardState;
pt: TPoint;
begin
if ignoretics > 0 then
begin
dec(ignoretics);
exit;
end;
// Keyboard
if I_GameFinished or InBackground or
IsIconic(hMainWnd) or (GetForegroundWindow <> hMainWnd) then
exit;
// JVAL -> DirectInput does not work
if usedirectinput and (g_pdidKeyboard <> nil) then
begin
hres := g_pdidKeyboard.GetDeviceState(SizeOf(dikb), dikb);
if hres = DIERR_INPUTLOST then
begin
// DirectInput is telling us that the input stream has been
// interrupted. Re-acquire and try again.
hres := g_pdidKeyboard.Acquire;
if hres = DD_OK then
I_ProcessInput;
exit;
end;
// The DirectInput key code is converted into the Windows virtual key code.
for i := Low(dikb) to High(dikb) do
if dikb[i] and $80 <> 0 then
curkeys[Byte(DIKEYtoVK(i))] := $80;
end
else
GetKeyboardState(curkeys^);
ZeroMemory(@ev, SizeOf(ev));
for i := 0 to SizeOf(curkeys^) - 1 do
begin
if (oldkeys[i] and $80) <> (curkeys[i] and $80) then
begin
key := TranslateKey(i);
if key <> 0 then
begin
if curkeys[i] and $80 <> 0 then
ev._type := ev_keydown
else
ev._type := ev_keyup;
ev.data1 := key;
D_PostEvent(@ev);
end;
key := TranslateSysKey(i);
if key <> 0 then
begin
if curkeys[i] and $80 <> 0 then
ev._type := ev_keydown
else
ev._type := ev_keyup;
ev.data1 := key;
D_PostEvent(@ev);
end;
end;
end;
p := oldkeys;
oldkeys := curkeys;
curkeys := p;
// Mouse
if GetKeyState(VK_LBUTTON) < 0 then
mflags := mflags or 1;
if GetKeyState(VK_RBUTTON) < 0 then
mflags := mflags or 2;
if GetKeyState(VK_MBUTTON) < 0 then
mflags := mflags or 4;
getcursorposfunc(pt);
ev._type := ev_mouse;
ev.data1 := mflags;
ev.data2 := mlastx - pt.x;
ev.data3 := mlasty - pt.y;
D_PostEvent(@ev);
I_ResetMouse;
// Joystick
if jPresent then
begin
ZeroMemory(@jInfo, SizeOf(TJoyInfoEx));
jInfo.dwSize := SizeOf(TJoyInfoEx);
jInfo.dwFlags := JOY_RETURNALL;
if joyGetPosEx(JOYSTICKID1, @jInfo) = JOYERR_NOERROR then
begin
ev._type := ev_joystick;
if jInfo.dwButtonNumber > 0 then
ev.data1 := jInfo.wButtons and ((1 shl NUMJOYBUTTONS) - 1) // Only first NUMJOYBUTTONS buttons of joystic in use
else
ev.data1 := 0;
ev.data2 := jInfo.wXpos - jwXpos;
ev.data3 := jInfo.wYpos - jwYpos;
D_PostEvent(@ev);
end;
end;
end;
//==============================================================================
//
// I_SetMouseClicks
//
//==============================================================================
procedure I_SetMouseClicks(val: integer);
begin
if val > 0 then
mflags := mflags or val
else
begin
val := -val;
mflags := mflags and not val;
end;
end;
//==============================================================================
//
// I_GetCapsLock
//
//==============================================================================
function I_GetCapsLock: boolean;
begin
result := (GetKeyState(VK_CAPITAL) and 1) <> 0;
end;
//==============================================================================
//
// I_SynchronizeInput
//
//==============================================================================
procedure I_SynchronizeInput(active: boolean);
begin
if active then
ignoretics := I_IGNORETICKS; // Wait ~ half second when get the focus again
if usedirectinput and (g_pdidKeyboard <> nil) then
begin
if active then
g_pdidKeyboard.Acquire
else
g_pdidKeyboard.Unacquire;
end;
end;
end.
| 0 | 0.826206 | 1 | 0.826206 | game-dev | MEDIA | 0.798452 | game-dev | 0.949711 | 1 | 0.949711 |
skyjake/Doomsday-Engine | 7,831 | doomsday/libs/gui/src/widgets/tabwidget.cpp | /** @file tabwidget.cpp Tab widget.
*
* @authors Copyright (c) 2014-2017 Jaakko Keränen <jaakko.keranen@iki.fi>
*
* @par License
* LGPL: http://www.gnu.org/licenses/lgpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details. You should have received a copy of
* the GNU Lesser General Public License along with this program; if not, see:
* http://www.gnu.org/licenses</small>
*/
#include "de/tabwidget.h"
#include "de/ui/listdata.h"
#include "de/menuwidget.h"
#include <de/animationrule.h>
namespace de {
DE_GUI_PIMPL(TabWidget)
, DE_OBSERVES(ChildWidgetOrganizer, WidgetCreation)
, DE_OBSERVES(ChildWidgetOrganizer, WidgetUpdate)
, DE_OBSERVES(ui::Data, Addition)
, DE_OBSERVES(ui::Data, OrderChange)
, DE_OBSERVES(ButtonWidget, Press)
{
ui::Data::Pos current = 0;
MenuWidget * buttons = nullptr;
bool needUpdate = false;
bool invertedStyle = false;
LabelWidget * selected = nullptr;
AnimationRule *selLeft = nullptr;
AnimationRule *selWidth = nullptr;
DotPath tabFontId = "tab.label";
DotPath selTabFontId = "tab.selected";
Impl(Public *i) : Base(i)
{
self().add(buttons = new MenuWidget);
buttons->enableScrolling(false);
buttons->margins().set("");
buttons->setGridSize(0, ui::Expand, 1, ui::Expand, GridLayout::ColumnFirst);
buttons->organizer().audienceForWidgetCreation() += this;
buttons->organizer().audienceForWidgetUpdate() += this;
buttons->items().audienceForAddition() += this;
buttons->items().audienceForOrderChange() += this;
// Center the buttons inside the widget.
buttons->rule()
.setInput(Rule::AnchorX, self().rule().left() + self().rule().width() / 2)
.setInput(Rule::Top, self().rule().top())
.setAnchorPoint(Vec2f(.5f, 0));
// Selection highlight.
self().add(selected = new LabelWidget);
}
~Impl()
{
releaseRef(selLeft);
releaseRef(selWidth);
}
void widgetCreatedForItem(GuiWidget &widget, const ui::Item &)
{
// Set the font and style.
ButtonWidget &btn = widget.as<ButtonWidget>();
btn.setSizePolicy(ui::Expand, ui::Expand);
btn.setFont(tabFontId);
btn.setOverrideImageSize(btn.font().height());
btn.margins().set("dialog.gap");
btn.set(Background());
btn.setBehavior(Focusable, UnsetFlags);
btn.audienceForPress() += this;
}
void widgetUpdatedForItem(GuiWidget &widget, const ui::Item &item)
{
widget.as<ButtonWidget>().setShortcutKey(item.as<TabItem>().shortcutKey());
}
void buttonPressed(ButtonWidget &button)
{
self().setCurrent(buttons->items().find(*buttons->organizer().findItemForWidget(button)));
}
void dataItemAdded(ui::Data::Pos, const ui::Item &)
{
needUpdate = true;
}
void dataItemOrderChanged()
{
needUpdate = true;
}
void setCurrent(ui::Data::Pos pos)
{
if (current != pos && pos < buttons->items().size())
{
current = pos;
updateSelected();
DE_NOTIFY_PUBLIC(Tab, i)
{
i->currentTabChanged(self());
}
}
}
void updateSelected()
{
selected->set(Background(style().colors().colorf(invertedStyle? "tab.inverted.selected"
: "tab.selected")));
for (ui::Data::Pos i = 0; i < buttons->items().size(); ++i)
{
const bool sel = (i == current);
ButtonWidget &w = buttons->itemWidget<ButtonWidget>(buttons->items().at(i));
w.setFont(sel ? selTabFontId : tabFontId);
w.setOpacity(sel? 1.f : 0.7f, 0.4);
if (!invertedStyle)
{
w.setTextColor(sel? "tab.selected" : "text");
w.setHoverTextColor(sel? "tab.selected" : "text");
}
else
{
w.setTextColor(sel? "tab.inverted.selected" : "inverted.text");
w.setHoverTextColor(sel? "tab.inverted.selected" : "inverted.text");
}
if (sel)
{
TimeSpan span = .2;
if (!selLeft)
{
// Initialize the animated rules for positioning the
// selection highlight.
selLeft = new AnimationRule(0);
selWidth = new AnimationRule(0);
selected->rule()
.setInput(Rule::Width, *selWidth)
.setInput(Rule::Left, *selLeft);
span = 0.0;
}
// Animate to new position.
selLeft ->set(w.rule().left(), span);
selWidth->set(w.rule().width(), span);
selected->rule()
.setInput(Rule::Height, rule("halfunit"))
.setInput(Rule::Top, w.rule().bottom());
}
}
}
bool handleShortcutKey(const KeyEvent &key)
{
for (auto *w : buttons->childWidgets())
{
if (ButtonWidget *but = maybeAs<ButtonWidget>(w))
{
if (but->handleShortcut(key))
{
return true;
}
}
}
return false;
}
DE_PIMPL_AUDIENCE(Tab)
};
DE_AUDIENCE_METHOD(TabWidget, Tab)
TabWidget::TabWidget(const String &name)
: GuiWidget(name), d(new Impl(this))
{
rule().setInput(Rule::Height, d->buttons->rule().height());
}
void TabWidget::setTabFont(const DotPath &fontId, const DotPath &selectedFontId)
{
d->tabFontId = fontId;
d->selTabFontId = selectedFontId;
}
void TabWidget::useInvertedStyle()
{
d->invertedStyle = true;
}
void TabWidget::clearItems()
{
if (d->selLeft)
{
// Dependent on the heading widget rules.
d->selLeft->set(d->selLeft->value());
}
items().clear();
}
ui::Data &TabWidget::items()
{
return d->buttons->items();
}
ui::Data::Pos TabWidget::current() const
{
return d->current;
}
TabItem &TabWidget::currentItem()
{
DE_ASSERT(d->current < items().size());
return items().at(d->current).as<TabItem>();
}
void TabWidget::setCurrent(ui::Data::Pos itemPos)
{
d->setCurrent(itemPos);
}
void TabWidget::update()
{
GuiWidget::update();
// Show or hide the selection highlight when enabled/disabled.
if (isEnabled() && fequal(d->selected->opacity().target(), 0.0f))
{
d->selected->setOpacity(1.0f, 300_ms);
}
else if (isDisabled() && !fequal(d->selected->opacity().target(), 0.0f))
{
d->selected->setOpacity(0.0f, 300_ms);
}
if (d->needUpdate)
{
d->updateSelected();
d->needUpdate = false;
}
}
bool TabWidget::handleEvent(const Event &ev)
{
if (isEnabled())
{
if (ev.isKeyDown())
{
const KeyEvent &key = ev.as<KeyEvent>();
if (d->handleShortcutKey(key))
{
return true;
}
}
}
return GuiWidget::handleEvent(ev);
}
} // namespace de
| 0 | 0.967626 | 1 | 0.967626 | game-dev | MEDIA | 0.760664 | game-dev,desktop-app | 0.974915 | 1 | 0.974915 |
meaten/MotionAug-CVPR2022 | 1,234 | DeepMimicCore/sim/Perturb.cpp | #include "Perturb.h"
#include "sim/SimObj.h"
tPerturb tPerturb::BuildForce()
{
tPerturb perturb;
perturb.mType = ePerturbForce;
return perturb;
}
tPerturb::tPerturb()
{
Clear();
}
tPerturb::tPerturb(ePerturb type, cSimObj* obj, const tVector& local_pos,
const tVector& perturb, double duration)
: tPerturb()
{
assert(type != ePerturbInvalid);
mType = type;
mObj = obj;
mLocalPos = local_pos;
mPerturb = perturb;
mDuration = duration;
}
tPerturb::~tPerturb()
{
}
bool tPerturb::HasExpired() const
{
return mTime >= mDuration;
}
void tPerturb::Clear()
{
mType = ePerturbInvalid;
mObj = nullptr;
mLocalPos.setZero();
mPerturb.setZero();
mDuration = 0;
mTime = 0;
}
bool tPerturb::IsValid() const
{
return (mObj != nullptr) && (mType != ePerturbInvalid);
}
void tPerturb::Update(double time_step)
{
mTime += time_step;
switch (mType)
{
case ePerturbForce:
ApplyForce();
break;
case ePerturbTorque:
ApplyTorque();
break;
default:
assert(false); // unsupported perturb type
break;
}
}
void tPerturb::ApplyForce()
{
assert(mType == ePerturbForce);
mObj->ApplyForce(mPerturb, mLocalPos);
}
void tPerturb::ApplyTorque()
{
assert(mType == ePerturbTorque);
mObj->ApplyTorque(mPerturb);
}
| 0 | 0.968095 | 1 | 0.968095 | game-dev | MEDIA | 0.112996 | game-dev | 0.973023 | 1 | 0.973023 |
magefree/mage | 2,165 | Mage.Sets/src/mage/cards/t/TheFinalDays.java | package mage.cards.t;
import mage.abilities.condition.common.CastFromGraveyardSourceCondition;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.decorator.ConditionalOneShotEffect;
import mage.abilities.dynamicvalue.DynamicValue;
import mage.abilities.dynamicvalue.common.CardsInControllerGraveyardCount;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.hint.Hint;
import mage.abilities.hint.ValueHint;
import mage.abilities.keyword.FlashbackAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.filter.StaticFilters;
import mage.game.permanent.token.Horror3Token;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class TheFinalDays extends CardImpl {
private static final DynamicValue xValue = new CardsInControllerGraveyardCount(StaticFilters.FILTER_CARD_CREATURE);
private static final Hint hint = new ValueHint("Creature cards in your graveyard", xValue);
public TheFinalDays(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{2}{B}{B}");
// Create two tapped 2/2 black Horror creature tokens. If this spell was cast from a graveyard, instead create X of those tokens, where X is the number of creature cards in your graveyard.
this.getSpellAbility().addEffect(new ConditionalOneShotEffect(
new CreateTokenEffect(new Horror3Token(), xValue), new CreateTokenEffect(new Horror3Token(), 2),
CastFromGraveyardSourceCondition.instance, "create two tapped 2/2 black Horror creature tokens. " +
"If this spell was cast from a graveyard, instead create X of those tokens, " +
"where X is the number of creature cards in your graveyard"
));
this.getSpellAbility().addHint(hint);
// Flashback {4}{B}{B}
this.addAbility(new FlashbackAbility(this, new ManaCostsImpl<>("{4}{B}{B}")));
}
private TheFinalDays(final TheFinalDays card) {
super(card);
}
@Override
public TheFinalDays copy() {
return new TheFinalDays(this);
}
}
| 0 | 0.982701 | 1 | 0.982701 | game-dev | MEDIA | 0.884971 | game-dev | 0.988263 | 1 | 0.988263 |
Gibberlings3/Tweaks-Anthology | 2,589 | cdtweaks/lib/comp_1254.tpa | /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
///// \\\\\
///// Move NPCs From Baldur's Gate \\\\\
///// \\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
///// \\\\\
///// Move NPCs From Baldur's Gate: shar-teel \\\\\
///// \\\\\
COPY_EXISTING ~%SHARTEEL_BCS%.bcs~ ~override~ // catching and updating area variables
~shartel2.bcs~ ~override~
DECOMPILE_AND_PATCH BEGIN
REPLACE_TEXTUALLY ~,"%MutaminsGarden%",~ ~,"%NorthNashkelRoad%",~
END
BUT_ONLY
ACTION_IF !game_is_bgt THEN BEGIN // all other platforms use GAM file
COPY_EXISTING ~baldur.gam~ ~override~
READ_LONG 0x30 npc_off
READ_LONG 0x34 npc_num
FOR (index = 0; index < npc_num; ++index) BEGIN
READ_ASCII (npc_off + 0x0c + (index * 0x160)) ~CREName~
PATCH_IF (~%CREName%~ STRING_COMPARE_CASE ~%tutu_var%SHARTE~ = 0) BEGIN // Quayle Starts at the Nashkel Carnival
WRITE_ASCIIE (npc_off + 0x18 + (index * 0x160)) ~%NorthNashkelRoad%~ #8
WRITE_SHORT (npc_off + 0x20 + (index * 0x160)) 1391
WRITE_SHORT (npc_off + 0x22 + (index * 0x160)) 2524
END
END
BUT_ONLY
ACTION_IF enhanced_edition BEGIN // her joining combat script is in the area script
COPY_EXISTING ~shartel2.bcs~ ~override~ // shar-teel's combat script for the initial fight
DECOMPILE_AND_PATCH BEGIN
REPLACE_TEXTUALLY ~"%MutaminsGarden%"~ ~"%NorthNashkelRoad%"~ // change area variable to new area
END
BUT_ONLY
COPY_EXISTING ~%MutaminsGarden_BCS%.bcs~ ~override~ // ar3500, mutamin's garden
DECOMPILE_AND_PATCH BEGIN
REPLACE_TEXTUALLY ~\(IF[ %TAB%%LNL%%MNL%%WNL%]+\)\(Global("SharteelFight","GLOBAL",[12])\)~ ~\1 False() \2~ // disable existing scripting
END
BUT_ONLY
EXTEND_BOTTOM ~%NorthNashkelRoad_BCS%.bcs~ ~cdtweaks/baf/bgee_spawn_sharteel.baf~ EVALUATE_BUFFER
END
END ELSE BEGIN // bgt
// disable spawns
COPY_EXISTING ~%MutaminsGarden_BCS%.bcs~ ~override~ // ar9400, mutamin's garden
DECOMPILE_AND_PATCH BEGIN
REPLACE_TEXTUALLY ~Global("BGTNPC[0-9]+","GLOBAL",0)~ ~False()~
END
BUT_ONLY
EXTEND_BOTTOM ~%NorthNashkelRoad_BCS%.bcs~ ~cdtweaks/baf/bgt_spawn_sharteel.baf~
END
| 0 | 0.585342 | 1 | 0.585342 | game-dev | MEDIA | 0.948281 | game-dev | 0.648965 | 1 | 0.648965 |
MisterTea/HyperNEAT | 7,004 | boost_1_57_0/tools/auto_index/src/tiny_xml.cpp | // tiny XML sub-set tools implementation -----------------------------------//
// (C) Copyright Beman Dawes 2002. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include "tiny_xml.hpp"
#include <cassert>
#include <cstring>
namespace
{
inline void eat_whitespace( char & c, std::istream & in )
{
while ( c == ' ' || c == '\r' || c == '\n' || c == '\t' )
in.get( c );
}
void eat_comment( char & c, std::istream & in )
{
in.get(c);
if(c != '-')
throw std::string("Invalid comment in XML");
in.get(c);
if(c != '-')
throw std::string("Invalid comment in XML");
do{
while(in.get(c) && (c != '-'));
in.get(c);
if(c != '-')
continue;
in.get(c);
if(c != '>')
continue;
else
break;
}
while(true);
}
std::string get_name( char & c, std::istream & in )
{
std::string result;
eat_whitespace( c, in );
while ( std::strchr(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.:", c )
!= 0 )
{
result += c;
if(!in.get( c ))
throw std::string("xml: unexpected eof");
}
return result;
}
void eat_delim( char & c, std::istream & in,
char delim, const std::string & msg )
{
eat_whitespace( c, in );
if ( c != delim )
throw std::string("xml syntax error, expected ") + delim
+ " (" + msg + ")";
in.get( c );
}
std::string get_value( char & c, std::istream & in )
{
std::string result;
while ( c != '\"' )
{
result += c;
in.get( c );
}
in.get( c );
return result;
}
}
namespace boost
{
namespace tiny_xml
{
// parse -----------------------------------------------------------------//
element_ptr parse( std::istream & in, const std::string & msg )
{
char c = 0; // current character
element_ptr e( new element );
if(!in.get( c ))
throw std::string("xml: unexpected eof");
if ( c == '<' )
if(!in.get( c ))
throw std::string("xml: unexpected eof");
if(c == '!')
{
eat_comment(c, in);
return e;
}
if(c == '?')
{
// XML processing instruction.
e->name += c;
if(!in.get( c )) // next char
throw std::string("xml: unexpected eof");
e->name += get_name(c, in);
in >> std::ws;
if(!in.get( c )) // next char
throw std::string("xml: unexpected eof");
while(c != '?')
{
e->content += c;
if(!in.get( c )) // next char
throw std::string("xml: unexpected eof");
}
if(!in.get( c )) // next char
throw std::string("xml: unexpected eof");
if(c != '>')
throw std::string("Invalid XML processing instruction.");
return e;
}
e->name = get_name( c, in );
eat_whitespace( c, in );
// attributes
while ( (c != '>') && (c != '/') )
{
attribute a;
a.name = get_name( c, in );
eat_delim( c, in, '=', msg );
eat_delim( c, in, '\"', msg );
a.value = get_value( c, in );
e->attributes.push_back( a );
eat_whitespace( c, in );
}
if(c == '/')
{
if(!in.get( c )) // next after '/'
throw std::string("xml: unexpected eof");
eat_whitespace( c, in );
if(c != '>')
throw std::string("xml: unexpected /");
return e;
}
if(!in.get( c )) // next after '>'
throw std::string("xml: unexpected eof");
//eat_whitespace( c, in );
do{
// sub-elements
while ( c == '<' )
{
if ( in.peek() == '/' )
break;
element_ptr child(parse( in, msg ));
child->parent = e;
e->elements.push_back(child);
in.get( c ); // next after '>'
//eat_whitespace( c, in );
}
if (( in.peek() == '/' ) && (c == '<'))
break;
// content
if ( (c != '<') )
{
element_ptr sub( new element );
while ( c != '<' )
{
sub->content += c;
if(!in.get( c ))
throw std::string("xml: unexpected eof");
}
sub->parent = e;
e->elements.push_back( sub );
}
assert( c == '<' );
if( in.peek() == '/' )
break;
}while(true);
in.get(c);
eat_delim( c, in, '/', msg );
std::string end_name( get_name( c, in ) );
if ( e->name != end_name )
throw std::string("xml syntax error: beginning name ")
+ e->name + " did not match end name " + end_name
+ " (" + msg + ")";
eat_delim( c, in, '>', msg );
if(c != '>')
{
// we've eaten one character past the >, put it back:
if(!in.putback(c))
throw std::string("Unable to put back character");
}
return e;
}
// write ---------------------------------------------------------------//
void write( const element & e, std::ostream & out )
{
if(e.name.size())
{
out << "<" << e.name;
if ( !e.attributes.empty() )
{
for( attribute_list::const_iterator itr = e.attributes.begin();
itr != e.attributes.end(); ++itr )
{
out << " " << itr->name << "=\"" << itr->value << "\"";
}
}
if(e.name[0] == '?')
{
out << " " << e.content << "?>";
return;
}
if(e.elements.empty() && e.content.empty())
{
out << "/>";
return;
}
out << ">";
}
if ( !e.elements.empty() )
{
for( element_list::const_iterator itr = e.elements.begin();
itr != e.elements.end(); ++itr )
{
write( **itr, out );
}
}
if ( !e.content.empty() )
{
out << e.content;
}
if(e.name.size() && (e.name[0] != '?'))
{
out << "</" << e.name << ">";
}
}
} // namespace tiny_xml
} // namespace boost
| 0 | 0.840183 | 1 | 0.840183 | game-dev | MEDIA | 0.221185 | game-dev | 0.848389 | 1 | 0.848389 |
Octo-Studios/relics | 5,232 | src/main/java/it/hurts/sskirillss/relics/network/packets/research/PacketResearchHint.java | package it.hurts.sskirillss.relics.network.packets.research;
import com.google.common.collect.Multimap;
import io.netty.buffer.ByteBuf;
import it.hurts.sskirillss.relics.client.screen.description.misc.DescriptionUtils;
import it.hurts.sskirillss.relics.init.SoundRegistry;
import it.hurts.sskirillss.relics.items.relics.base.IRelicItem;
import it.hurts.sskirillss.relics.utils.EntityUtils;
import it.hurts.sskirillss.relics.utils.Reference;
import lombok.AllArgsConstructor;
import lombok.Data;
import net.minecraft.ChatFormatting;
import net.minecraft.core.Holder;
import net.minecraft.network.chat.Component;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.network.protocol.game.ClientboundSoundPacket;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.RandomSource;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import java.util.Map;
@Data
@AllArgsConstructor
public class PacketResearchHint implements CustomPacketPayload {
private final int container;
private final int slot;
private final String ability;
private final int amount;
public static final Type<PacketResearchHint> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(Reference.MODID, "research_hint"));
public static final StreamCodec<ByteBuf, PacketResearchHint> STREAM_CODEC = StreamCodec.composite(
ByteBufCodecs.INT, PacketResearchHint::getContainer,
ByteBufCodecs.INT, PacketResearchHint::getSlot,
ByteBufCodecs.STRING_UTF8, PacketResearchHint::getAbility,
ByteBufCodecs.INT, PacketResearchHint::getAmount,
PacketResearchHint::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
public void handle(IPayloadContext ctx) {
ctx.enqueueWork(() -> {
if (ctx.player().level().isClientSide())
return;
ServerPlayer player = (ServerPlayer) ctx.player();
if (player.containerMenu.containerId != container) {
causeError(player);
return;
}
ItemStack stack = DescriptionUtils.gatherRelicStack(player, slot);
if (!(stack.getItem() instanceof IRelicItem relic)) {
causeError(player);
return;
}
RandomSource random = player.getRandom();
int cost = relic.getResearchHintPlayerExperienceCost(ability) * amount;
if (EntityUtils.getPlayerTotalExperience(player) < cost)
return;
player.giveExperiencePoints(-cost);
research(stack, amount);
if (relic.testAbilityResearch(stack, ability)) {
relic.setAbilityResearched(stack, ability, true);
player.connection.send(new ClientboundSoundPacket(Holder.direct(SoundRegistry.FINISH_RESEARCH.get()), SoundSource.PLAYERS, player.getX(), player.getY(), player.getZ(), 1F, 1F, random.nextLong()));
} else
player.connection.send(new ClientboundSoundPacket(Holder.direct(SoundRegistry.CONNECT_STARS.get()), SoundSource.PLAYERS, player.getX(), player.getY(), player.getZ(), 0.75F, 0.75F + random.nextFloat() * 0.5F, random.nextLong()));
try {
player.containerMenu.getSlot(slot).set(stack);
} catch (Exception e) {
e.printStackTrace();
causeError(player);
}
});
}
public void research(ItemStack stack, int amount) {
if (!(stack.getItem() instanceof IRelicItem relic))
return;
Multimap<Integer, Integer> pattern = relic.getResearchData(ability).getLinks();
Multimap<Integer, Integer> links = relic.getResearchLinks(stack, ability);
int iteration = 0;
for (Map.Entry<Integer, Integer> entry : links.entries()) {
Integer start = entry.getKey();
Integer end = entry.getValue();
if (!(pattern.containsEntry(start, end) || pattern.containsEntry(end, start))) {
relic.removeResearchLink(stack, ability, start, end);
if (++iteration >= amount)
break;
}
}
iteration = 0;
for (Map.Entry<Integer, Integer> entry : pattern.entries()) {
Integer start = entry.getKey();
Integer end = entry.getValue();
if (!(links.containsEntry(start, end) || links.containsEntry(end, start))) {
relic.addResearchLink(stack, ability, start, end);
if (++iteration >= amount)
break;
}
}
}
private static void causeError(Player player) {
player.displayClientMessage(Component.translatable("info.relics.researching.wrong_container").withStyle(ChatFormatting.RED), false);
player.closeContainer();
}
} | 0 | 0.929532 | 1 | 0.929532 | game-dev | MEDIA | 0.978626 | game-dev | 0.985776 | 1 | 0.985776 |
ProjectIgnis/CardScripts | 15,194 | proc_ritual.lua | if not aux.RitualProcedure then
aux.RitualProcedure = {}
Ritual = aux.RitualProcedure
end
if not Ritual then
Ritual = aux.RitualProcedure
end
function Ritual.GetMatchingFilterFunction(c)
local mt=c.__index
if not mt.ritual_matching_function or not mt.ritual_matching_function[c] then
return aux.TRUE
end
return mt.ritual_matching_function[c]
end
function Ritual.CheckMatFilter(matfilter,e,tp,mg,mg2)
if matfilter then
if type(matfilter)=="function" then
mg:Sub(mg:Filter(aux.NOT(matfilter),nil,e,tp))
mg2:Sub(mg2:Filter(aux.NOT(matfilter),nil,e,tp))
else
local f=function(c)
return not matfilter:IsContains(c)
end
mg:Sub(mg:Filter(f,nil))
mg2:Sub(mg2:Filter(f,nil))
end
end
end
--The current total level to match for the monster being summoned, to be used with monsters that can be used as whole tribute
Ritual.SummoningLevel=nil
function Ritual.AddWholeLevelTribute(c,condition)
local e=Effect.CreateEffect(c)
e:SetType(EFFECT_TYPE_SINGLE)
e:SetCode(EFFECT_RITUAL_LEVEL)
e:SetValue(Ritual.WholeLevelTributeValue(condition))
c:RegisterEffect(e)
return e
end
function Ritual.WholeLevelTributeValue(cond)
return function(e,c)
local lv=e:GetHandler():GetLevel()
if cond(c,e) then
local clv=Ritual.SummoningLevel or c:GetLevel()
return (lv<<16)|clv
else return lv end
end
end
--Ritual Summon
Ritual.CreateProc = aux.FunctionWithNamedArgs(
function(c,_type,filter,lv,desc,extrafil,extraop,matfilter,stage2,location,forcedselection,customoperation,specificmatfilter,requirementfunc,sumpos,extratg,self)
--lv can be a function (like GetLevel/GetOriginalLevel), fixed level, if nil it defaults to GetLevel
if filter and type(filter)=="function" then
local mt=c.__index
if not mt.ritual_matching_function then
mt.ritual_matching_function={}
end
mt.ritual_matching_function[c]=filter
end
local e1=Effect.CreateEffect(c)
if desc then
e1:SetDescription(desc)
else
e1:SetDescription(1171)
end
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(Ritual.Target(filter,_type,lv,extrafil,extraop,matfilter,stage2,location,forcedselection,specificmatfilter,requirementfunc,sumpos,extratg,self))
e1:SetOperation(Ritual.Operation(filter,_type,lv,extrafil,extraop,matfilter,stage2,location,forcedselection,customoperation,specificmatfilter,requirementfunc,sumpos,self))
return e1
end,"handler","lvtype","filter","lv","desc","extrafil","extraop","matfilter","stage2","location","forcedselection","customoperation","specificmatfilter","requirementfunc","sumpos","extratg","self")
Ritual.AddProc = aux.FunctionWithNamedArgs(
function(c,_type,filter,lv,desc,extrafil,extraop,matfilter,stage2,location,forcedselection,customoperation,specificmatfilter,requirementfunc,sumpos,extratg,self)
local e1=Ritual.CreateProc(c,_type,filter,lv,desc,extrafil,extraop,matfilter,stage2,location,forcedselection,customoperation,specificmatfilter,requirementfunc,sumpos,extratg,self)
c:RegisterEffect(e1)
return e1
end,"handler","lvtype","filter","lv","desc","extrafil","extraop","matfilter","stage2","location","forcedselection","customoperation","specificmatfilter","requirementfunc","sumpos","extratg","self")
local function WrapTableReturn(func)
if func then
return function(...)
return {func(...)}
end
end
end
local function MergeForcedSelection(f1,f2)
if f1==nil or f2==nil then
return f1 or f2
end
return function(...)
local ret1,ret2=f1(...)
local repl1,repl2=f2(...)
return ret1 and repl1,ret2 or repl2
end
end
function Ritual.Filter(c,filter,_type,e,tp,m,m2,forcedselection,specificmatfilter,lv,requirementfunc,sumpos)
if not (c:IsOriginalType(TYPE_RITUAL) and c:IsOriginalType(TYPE_MONSTER)) or (filter and not filter(c)) or not c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_RITUAL,tp,false,true,sumpos) then return false end
local lv=(lv and (type(lv)=="function" and lv(c)) or lv) or c:GetLevel()
lv=math.max(1,lv)
Ritual.SummoningLevel=lv
local mg=m:Filter(Card.IsCanBeRitualMaterial,c,c)
mg:Merge(m2-c)
if c.ritual_custom_condition then
return c:ritual_custom_condition(mg,forcedselection,_type)
end
if c.mat_filter then
mg:Match(c.mat_filter,c,tp)
end
if specificmatfilter then
mg:Match(specificmatfilter,nil,c,mg,tp)
end
forcedselection=MergeForcedSelection(c.ritual_custom_check,forcedselection)
local res=aux.SelectUnselectGroup(mg,e,tp,1,lv,Ritual.Check(c,lv,WrapTableReturn(forcedselection),_type,requirementfunc),0)
Ritual.SummoningLevel=nil
return res
end
local function ExtraReleaseFilter(c,tp)
return c:IsControler(1-tp) and c:IsHasEffect(EFFECT_EXTRA_RELEASE)
end
local function ForceExtraRelease(mg)
return function(e,tp,g,c)
return g:Includes(mg)
end
end
local function GetDefaultSummonFromLocation()
return Duel.IsDuelType(DUEL_EXTRA_DECK_RITUAL) and LOCATION_EXTRA or LOCATION_HAND
end
Ritual.Target = aux.FunctionWithNamedArgs(
function(filter,_type,lv,extrafil,extraop,matfilter,stage2,location,forcedselection,specificmatfilter,requirementfunc,sumpos,extratg,self)
location = location or GetDefaultSummonFromLocation()
sumpos = sumpos or POS_FACEUP
return function(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local mg=Duel.GetRitualMaterial(tp,not requirementfunc)
local mg2=extrafil and extrafil(e,tp,eg,ep,ev,re,r,rp,chk) or Group.CreateGroup()
--if an EFFECT_EXTRA_RITUAL_MATERIAL effect has a forcedselection of its own
--add that forcedselection to the one of the Ritual Spell, if any
local extra_eff_g=mg:Filter(Card.IsHasEffect,nil,EFFECT_EXTRA_RITUAL_MATERIAL)
local func=forcedselection
--if a card controlled by the opponent has EFFECT_EXTRA_RELEASE, then it MUST be
--used as material
local extra_mat_g=mg:Filter(ExtraReleaseFilter,nil,tp)
if #extra_mat_g>0 then
func=MergeForcedSelection(ForceExtraRelease(extra_mat_g),func)
end
if #extra_eff_g>0 then
local prev_repl_function=nil
for tmp_c in extra_eff_g:Iter() do
local effs={tmp_c:IsHasEffect(EFFECT_EXTRA_RITUAL_MATERIAL)}
for _,eff in ipairs(effs) do
local repl_function=eff:GetLabelObject()
if repl_function and prev_repl_function~=repl_function[1] then
prev_repl_function=repl_function[1]
func=MergeForcedSelection(func,repl_function[1])
end
end
end
end
Ritual.CheckMatFilter(matfilter,e,tp,mg,mg2)
return Duel.IsExistingMatchingCard(Ritual.Filter,tp,location,0,1,nil,filter,_type,e,tp,mg,mg2,func,specificmatfilter,lv,requirementfunc,sumpos)
end
if extratg then extratg(e,tp,eg,ep,ev,re,r,rp,chk) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,location)
end
end,"filter","lvtype","lv","extrafil","extraop","matfilter","stage2","location","forcedselection","specificmatfilter","requirementfunc","sumpos","extratg","self")
function Auxiliary.RitualCheckAdditionalLevel(c,rc)
local raw_level=c:GetRitualLevel(rc)
local lv1=raw_level&0xffff
local lv2=raw_level>>16
if lv2>0 then
return math.min(lv1,lv2)
else
return lv1
end
end
function Ritual.Check(sc,lv,forcedselection,_type,requirementfunc)
local chk
if _type==RITPROC_EQUAL then
chk=function(g) return g:GetSum(requirementfunc or Auxiliary.RitualCheckAdditionalLevel,sc)<=lv end
else
chk=function(g,c) return g:GetSum(requirementfunc or Auxiliary.RitualCheckAdditionalLevel,sc) - (requirementfunc or Auxiliary.RitualCheckAdditionalLevel)(c,sc)<=lv end
end
return function(sg,e,tp,mg,c)
local res=chk(sg,c)
if not res then return false,true end
local stop=false
if forcedselection then
local ret=forcedselection(e,tp,sg,sc)
res=ret[1]
stop=ret[2] or stop
end
if res and not stop then
if _type==RITPROC_EQUAL then
res=sg:CheckWithSumEqual(requirementfunc or Card.GetRitualLevel,lv,#sg,#sg,sc)
else
Duel.SetSelectedCard(sg)
res=sg:CheckWithSumGreater(requirementfunc or Card.GetRitualLevel,lv,sc)
end
local stop=false
res=res and (sc:IsLocation(LOCATION_EXTRA) and Duel.GetLocationCountFromEx(tp,tp,sg,sc) or Duel.GetMZoneCount(tp,sg,tp))>0
end
return res,stop
end
end
function Ritual.Finishcon(sc,lv,forcedselection,requirementfunc,_type)
return function(sg,e,tp,mg)
if forcedselection then
local ret=forcedselection(e,tp,sg,sc)
if not ret[1] then return false end
end
if _type==RITPROC_EQUAL then
return sg:CheckWithSumEqual(requirementfunc or Card.GetRitualLevel,lv,#sg,#sg,sc)
else
Duel.SetSelectedCard(sg)
return sg:CheckWithSumGreater(requirementfunc or Card.GetRitualLevel,lv,sc)
end
end
end
Ritual.Operation = aux.FunctionWithNamedArgs(
function(filter,_type,lv,extrafil,extraop,matfilter,stage2,location,forcedselection,customoperation,specificmatfilter,requirementfunc,sumpos,self)
location = location or GetDefaultSummonFromLocation()
sumpos = sumpos or POS_FACEUP
return function(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if self and not c:IsRelateToEffect(e) then return end
local mg=Duel.GetRitualMaterial(tp,not requirementfunc)
local mg2=extrafil and extrafil(e,tp,eg,ep,ev,re,r,rp) or Group.CreateGroup()
--if an EFFECT_EXTRA_RITUAL_MATERIAL effect has a forcedselection of its own
--add that forcedselection to the one of the Ritual Spell, if any
local func=forcedselection
local extra_eff_g=mg:Filter(Card.IsHasEffect,nil,EFFECT_EXTRA_RITUAL_MATERIAL)
if #extra_eff_g>0 then
local prev_repl_function=nil
for tmp_c in extra_eff_g:Iter() do
local effs={tmp_c:IsHasEffect(EFFECT_EXTRA_RITUAL_MATERIAL)}
for _,eff in ipairs(effs) do
local repl_function=eff:GetLabelObject()
if repl_function and prev_repl_function~=repl_function[1] then
prev_repl_function=repl_function[1]
func=MergeForcedSelection(func,repl_function[1])
end
end
end
end
--if a card controlled by the opponent has EFFECT_EXTRA_RELEASE, then it MUST be
--used as material
local extra_mat_g=mg:Filter(ExtraReleaseFilter,nil,tp)
if #extra_mat_g>0 then
func=MergeForcedSelection(ForceExtraRelease(extra_mat_g),func)
end
Ritual.CheckMatFilter(matfilter,e,tp,mg,mg2)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
local tg=Group.CreateGroup()
if not self then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
tg=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(Ritual.Filter),tp,location,0,1,1,nil,filter,_type,e,tp,mg,mg2,func,specificmatfilter,lv,requirementfunc,sumpos)
elseif Ritual.Filter(c,filter,_type,e,tp,mg,mg2,func,specificmatfilter,lv,requirementfunc,sumpos) and not c:IsHasEffect(EFFECT_NECRO_VALLEY) then
tg:AddCard(c)
end
if #tg>0 then
local tc=tg:GetFirst()
local lv=(lv and (type(lv)=="function" and lv(tc)) or lv) or tc:GetLevel()
lv=math.max(1,lv)
Ritual.SummoningLevel=lv
local mat=nil
mg:Match(Card.IsCanBeRitualMaterial,tc,tc)
mg:Merge(mg2-tc)
if specificmatfilter then
mg:Match(specificmatfilter,nil,tc,mg,tp)
end
if tc.ritual_custom_operation then
tc:ritual_custom_operation(mg,func,_type)
mat=tc:GetMaterial()
else
func=MergeForcedSelection(tc.ritual_custom_check,func)
if tc.mat_filter then
mg:Match(tc.mat_filter,tc,tp)
end
if ft>0 and not func then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE)
if _type==RITPROC_EQUAL then
mat=mg:SelectWithSumEqual(tp,requirementfunc or Card.GetRitualLevel,lv,1,#mg,tc)
else
mat=mg:SelectWithSumGreater(tp,requirementfunc or Card.GetRitualLevel,lv,tc)
end
else
mat=aux.SelectUnselectGroup(mg,e,tp,1,lv,Ritual.Check(tc,lv,WrapTableReturn(func),_type,requirementfunc),1,tp,HINTMSG_RELEASE,Ritual.Finishcon(tc,lv,WrapTableReturn(func),requirementfunc,_type))
end
end
--check if a card from an "once per turn" EFFECT_EXTRA_RITUAL_MATERIAL effect was selected
local extra_eff_g=mat:Filter(Card.IsHasEffect,nil,EFFECT_EXTRA_RITUAL_MATERIAL)
for tmp_c in extra_eff_g:Iter() do
local effs={tmp_c:IsHasEffect(EFFECT_EXTRA_RITUAL_MATERIAL)}
for _,eff in ipairs(effs) do
--if eff is OPT and tmp_c is not returned
--by the Ritual Spell's exrafil
--then use the count limit and register
--the flag to turn the extra eff OFF
--requires the EFFECT_EXTRA_RITUAL_MATERIAL effect
--to check the flag in its condition
local _,max_count_limit=eff:GetCountLimit()
if max_count_limit>0 and not mg2:IsContains(tmp_c) then
eff:UseCountLimit(tp,1)
Duel.RegisterFlagEffect(tp,eff:GetHandler():GetCode(),RESET_PHASE+PHASE_END,0,1)
end
end
end
if not customoperation then
tc:SetMaterial(mat)
if extraop then
extraop(mat:Clone(),e,tp,eg,ep,ev,re,r,rp,tc)
else
Duel.ReleaseRitualMaterial(mat)
end
Duel.BreakEffect()
Duel.SpecialSummon(tc,SUMMON_TYPE_RITUAL,tp,tp,false,true,sumpos)
tc:CompleteProcedure()
if tc:IsFacedown() then Duel.ConfirmCards(1-tp,tc) end
if stage2 then
stage2(mat,e,tp,eg,ep,ev,re,r,rp,tc)
end
else
customoperation(mat:Clone(),e,tp,eg,ep,ev,re,r,rp,tc)
end
Ritual.SummoningLevel=nil
end
end
end,"filter","lvtype","lv","extrafil","extraop","matfilter","stage2","location","forcedselection","customoperation","specificmatfilter","requirementfunc","sumpos","self")
--Ritual Summon, geq fixed lv
Ritual.AddProcGreater = aux.FunctionWithNamedArgs(
function(c,filter,lv,desc,extrafil,extraop,matfilter,stage2,location,forcedselection,customoperation,specificmatfilter,requirementfunc,sumpos,extratg,self)
return Ritual.AddProc(c,RITPROC_GREATER,filter,lv,desc,extrafil,extraop,matfilter,stage2,location,forcedselection,customoperation,specificmatfilter,requirementfunc,sumpos,extratg,self)
end,"handler","filter","lv","desc","extrafil","extraop","matfilter","stage2","location","forcedselection","customoperation","specificmatfilter","requirementfunc","sumpos","extratg","self")
function Ritual.AddProcCode(c,_type,lv,desc,...)
if not c:IsStatus(STATUS_COPYING_EFFECT) and c.fit_monster==nil then
local mt=c:GetMetatable()
mt.fit_monster={...}
end
return Ritual.AddProc(c,_type,Auxiliary.FilterBoolFunction(Card.IsCode,...),lv,desc)
end
function Ritual.AddProcGreaterCode(c,lv,desc,...)
return Ritual.AddProcCode(c,RITPROC_GREATER,lv,desc,...)
end
--Ritual Summon, equal to
Ritual.AddProcEqual = aux.FunctionWithNamedArgs(
function(c,filter,lv,desc,extrafil,extraop,matfilter,stage2,location,forcedselection,customoperation,specificmatfilter,requirementfunc,sumpos,extratg,self)
return Ritual.AddProc(c,RITPROC_EQUAL,filter,lv,desc,extrafil,extraop,matfilter,stage2,location,forcedselection,customoperation,specificmatfilter,requirementfunc,sumpos,extratg,self)
end,"handler","filter","lv","desc","extrafil","extraop","matfilter","stage2","location","forcedselection","customoperation","specificmatfilter","requirementfunc","sumpos","extratg","self")
function Ritual.AddProcEqualCode(c,lv,desc,...)
return Ritual.AddProcCode(c,RITPROC_EQUAL,lv,desc,...)
end
| 0 | 0.936153 | 1 | 0.936153 | game-dev | MEDIA | 0.891669 | game-dev | 0.96204 | 1 | 0.96204 |
ProjectSkyfire/SkyFire_548 | 6,390 | src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp | /*
* This file is part of Project SkyFire https://www.projectskyfire.org.
* See LICENSE.md file for Copyright information
*/
#include "DisableMgr.h"
#include "ObjectMgr.h"
#include "OutdoorPvPMgr.h"
#include "Player.h"
#include "ScriptMgr.h"
void OutdoorPvPMgr::Die()
{
//SF_LOG_DEBUG("outdoorpvp", "Deleting OutdoorPvPMgr");
for (OutdoorPvPSet::iterator itr = m_OutdoorPvPSet.begin(); itr != m_OutdoorPvPSet.end(); ++itr)
delete* itr;
for (OutdoorPvPDataMap::iterator itr = m_OutdoorPvPDatas.begin(); itr != m_OutdoorPvPDatas.end(); ++itr)
delete itr->second;
}
void OutdoorPvPMgr::InitOutdoorPvP()
{
uint32 oldMSTime = getMSTime();
// 0 1
QueryResult result = WorldDatabase.Query("SELECT TypeId, ScriptName FROM outdoorpvp_template");
if (!result)
{
SF_LOG_ERROR("server.loading", ">> Loaded 0 outdoor PvP definitions. DB table `outdoorpvp_template` is empty.");
return;
}
uint32 count = 0;
uint32 typeId = 0;
do
{
Field* fields = result->Fetch();
typeId = fields[0].GetUInt8();
if (DisableMgr::IsDisabledFor(DISABLE_TYPE_OUTDOORPVP, typeId, NULL))
continue;
if (typeId >= MAX_OUTDOORPVP_TYPES)
{
SF_LOG_ERROR("sql.sql", "Invalid OutdoorPvPTypes value %u in outdoorpvp_template; skipped.", typeId);
continue;
}
OutdoorPvPData* data = new OutdoorPvPData();
OutdoorPvPTypes realTypeId = OutdoorPvPTypes(typeId);
data->TypeId = realTypeId;
data->ScriptId = sObjectMgr->GetScriptId(fields[1].GetCString());
m_OutdoorPvPDatas[realTypeId] = data;
++count;
} while (result->NextRow());
OutdoorPvP* pvp;
for (uint8 i = 1; i < MAX_OUTDOORPVP_TYPES; ++i)
{
OutdoorPvPDataMap::iterator iter = m_OutdoorPvPDatas.find(OutdoorPvPTypes(i));
if (iter == m_OutdoorPvPDatas.end())
{
SF_LOG_ERROR("sql.sql", "Could not initialize OutdoorPvP object for type ID %u; no entry in database.", uint32(i));
continue;
}
pvp = sScriptMgr->CreateOutdoorPvP(iter->second);
if (!pvp)
{
SF_LOG_ERROR("outdoorpvp", "Could not initialize OutdoorPvP object for type ID %u; got NULL pointer from script.", uint32(i));
continue;
}
if (!pvp->SetupOutdoorPvP())
{
SF_LOG_ERROR("outdoorpvp", "Could not initialize OutdoorPvP object for type ID %u; SetupOutdoorPvP failed.", uint32(i));
delete pvp;
continue;
}
m_OutdoorPvPSet.push_back(pvp);
}
SF_LOG_INFO("server.loading", ">> Loaded %u outdoor PvP definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
void OutdoorPvPMgr::AddZone(uint32 zoneid, OutdoorPvP* handle)
{
m_OutdoorPvPMap[zoneid] = handle;
}
void OutdoorPvPMgr::HandlePlayerEnterZone(Player* player, uint32 zoneid)
{
OutdoorPvPMap::iterator itr = m_OutdoorPvPMap.find(zoneid);
if (itr == m_OutdoorPvPMap.end())
return;
if (itr->second->HasPlayer(player))
return;
itr->second->HandlePlayerEnterZone(player, zoneid);
SF_LOG_DEBUG("outdoorpvp", "Player %u entered outdoorpvp id %u", player->GetGUIDLow(), itr->second->GetTypeId());
}
void OutdoorPvPMgr::HandlePlayerLeaveZone(Player* player, uint32 zoneid)
{
OutdoorPvPMap::iterator itr = m_OutdoorPvPMap.find(zoneid);
if (itr == m_OutdoorPvPMap.end())
return;
// teleport: remove once in removefromworld, once in updatezone
if (!itr->second->HasPlayer(player))
return;
itr->second->HandlePlayerLeaveZone(player, zoneid);
SF_LOG_DEBUG("outdoorpvp", "Player %u left outdoorpvp id %u", player->GetGUIDLow(), itr->second->GetTypeId());
}
OutdoorPvP* OutdoorPvPMgr::GetOutdoorPvPToZoneId(uint32 zoneid)
{
OutdoorPvPMap::iterator itr = m_OutdoorPvPMap.find(zoneid);
if (itr == m_OutdoorPvPMap.end())
{
// no handle for this zone, return
return NULL;
}
return itr->second;
}
void OutdoorPvPMgr::Update(uint32 diff)
{
m_UpdateTimer += diff;
if (m_UpdateTimer > OUTDOORPVP_OBJECTIVE_UPDATE_INTERVAL)
{
for (OutdoorPvPSet::iterator itr = m_OutdoorPvPSet.begin(); itr != m_OutdoorPvPSet.end(); ++itr)
(*itr)->Update(m_UpdateTimer);
m_UpdateTimer = 0;
}
}
bool OutdoorPvPMgr::HandleCustomSpell(Player* player, uint32 spellId, GameObject* go)
{
for (OutdoorPvPSet::iterator itr = m_OutdoorPvPSet.begin(); itr != m_OutdoorPvPSet.end(); ++itr)
{
if ((*itr)->HandleCustomSpell(player, spellId, go))
return true;
}
return false;
}
ZoneScript* OutdoorPvPMgr::GetZoneScript(uint32 zoneId)
{
OutdoorPvPMap::iterator itr = m_OutdoorPvPMap.find(zoneId);
if (itr != m_OutdoorPvPMap.end())
return itr->second;
else
return NULL;
}
bool OutdoorPvPMgr::HandleOpenGo(Player* player, uint64 guid)
{
for (OutdoorPvPSet::iterator itr = m_OutdoorPvPSet.begin(); itr != m_OutdoorPvPSet.end(); ++itr)
{
if ((*itr)->HandleOpenGo(player, guid))
return true;
}
return false;
}
void OutdoorPvPMgr::HandleGossipOption(Player* player, uint64 guid, uint32 gossipid)
{
for (OutdoorPvPSet::iterator itr = m_OutdoorPvPSet.begin(); itr != m_OutdoorPvPSet.end(); ++itr)
{
if ((*itr)->HandleGossipOption(player, guid, gossipid))
return;
}
}
bool OutdoorPvPMgr::CanTalkTo(Player* player, Creature* creature, GossipMenuItems const& gso)
{
for (OutdoorPvPSet::iterator itr = m_OutdoorPvPSet.begin(); itr != m_OutdoorPvPSet.end(); ++itr)
{
if ((*itr)->CanTalkTo(player, creature, gso))
return true;
}
return false;
}
void OutdoorPvPMgr::HandleDropFlag(Player* player, uint32 spellId)
{
for (OutdoorPvPSet::iterator itr = m_OutdoorPvPSet.begin(); itr != m_OutdoorPvPSet.end(); ++itr)
{
if ((*itr)->HandleDropFlag(player, spellId))
return;
}
}
void OutdoorPvPMgr::HandlePlayerResurrects(Player* player, uint32 zoneid)
{
OutdoorPvPMap::iterator itr = m_OutdoorPvPMap.find(zoneid);
if (itr == m_OutdoorPvPMap.end())
return;
if (itr->second->HasPlayer(player))
itr->second->HandlePlayerResurrects(player, zoneid);
}
| 0 | 0.918616 | 1 | 0.918616 | game-dev | MEDIA | 0.864751 | game-dev | 0.844605 | 1 | 0.844605 |
lifebottle/Narikiri-Dungeon-X | 5,306 | README.md | # Narikiri Dungeon X
An attempt to create a patch for Narikiri Dungeon X (PSP).
https://docs.google.com/spreadsheets/d/1S1RwcAVeOqBEnIhfU2z7ZVff2C3vqwJ1tvNcy_qHZ6w/edit#gid=0


## Hacker Note 1
Here is one interesting snip, might be useful for Narikiri Dungeon X...
If you want to know the file names of the data you extract, check this:

```
unsigned int hash(const char* string)
{
unsigned int hash = 0;
while(*string)
hash = ((hash << 7) + hash) + (hash << 3) + *string++;
return hash;
}
```
The files packed inside the `.bin` each have one its filenames...
...Except that they don't appear enywhere in the `.bin`, or any other file in the game.
Some system files do have their names in the ELF (`all.dat`).
Those numbers are not random, they are the hash of the filename string, as per the above hash function.
For example, it's actually pretty trivial to "detach" this game, from Phantasia X, resulting in 2 independent ISO's.
> It's just another ELF inside the game (`top.prx`?)
Then alpha-out the Phantasia X logo from the menu...and voila!
The game's engine simply reloads the menu if you still try to access it.
## Hacker Note 2
1. Besides the executable, `all.dat` is the only file of the game
2. Indices are in the executable, offset + size + name hash. So each entry should be 12-bytes, given each member 32-bits
3. Are the "sub-files" padded to start at an LBA? I think so, try searching for both (should take 2 minutes)
4. Just identify the padding in the big file to know where a subfile starts. Then search both offsets and sector in the exe. And you'll find the entry table.
5. Now the game doesn't store names anywhere, but rather generates them at runtime. Then hashes the generated names and looks it up in the index table to find offset and size. If you want to extract the right file names, you need to bruteforce the hashes from the index table with the function above (Hacker Note 1)
## Hacker Note 3
The game engine statically links something like `libc`, so it uses `sprintf` to generate in runtime file names.
For instance `sprintf('levels/%d/enemy/%s/model.dat", 7, "bat");`
Just a made up case. Then it would hash `"levels/5/enemy/bat/model.dat"`
So theoretically if you know all the folders you can brute force faster
Some system files, like the font, have file names directly stored in the execuable
Those are easy to get, just run strings on the exe. Hash all, and take the ones existing in the entry table
There is also the fact that the hash is a partially reversible function
Meaning that a small change in the source string, causes a small change in the resulting hash
With all this... the hashes could be all recovered
## Hacker Note 4
Other aspects of the game are somewhat easy to hack, like the font
It's just a set of `gim` files. You can't find them using the GE debugger though...
Just find the font name in the exe, hash it and get the font from the big file with its offset and size
Decode the gim and that's it
## Hacker Note 5
Files with `MSCF` in the header are Microsoft CAB Files and can be extracted in Windows with `EXPAND file.cab -F` and packed with `MAKECAB`. For example, Chat files have .bin extension but can be extracted like a CAB file. Furthermore, after extract chat file, the resulting .dat file is a PAK3 file that can be extracted with pakcomposer.
## Hacker Note 6
Re-pack scenario/script CAB files with the following:
`makecab /D CompressionType=LZX /D CompressionMemory=15 /D ReservePerCabinetSize=8 ar.dat cab.cab`
While not required, update CAB identity to `4392`. Do this by hex editing CAB file at `0x20` and `0x21` from `00 00` to `28 11`.
## Hacker Note 6
looks like tss header starts with TSS (of course)
there's some kind of start `0x04` and end `0x14`, probably to the bytecode script
pointer to the text block `0XOC`
maybe size of the text block `0x18`
then you just have to parse the bytecode script looking for stuff, there might be differences across games if they changed it between games
from the notes here, `0x0100A304` is a pointer table (?)
`0x40002004` is a "name array", whatever that means
`0x00008202` is a direct string
`0x10000C04` is some kind of skit thing
`0x40000C04` is a different type of skit thing
`0x00002004` is some other kind of pointer table
you could reverse engineer the entire bytecode to be able to compile your own event scripts
but imo it's too much work, just look for commands related to text
and leave the byte script alone, edit only pointers and text
## Links
- https://talesofnaridanx.weebly.com/downloads.html
- https://www.youtube.com/user/Crevox/videos
- http://www.mediafire.com/file/g83m35bh2ju746s/top_patch_v012.rar/file
## Credits
- Thanks to `Kajitani-Eizan` for some hacker notes
- Thanks to `Sky` for donating resources to get started
- Thanks to `crevox` for permission to use their menu patch
- Thanks to `kevassa` for permission to use their English translation script
| 0 | 0.77397 | 1 | 0.77397 | game-dev | MEDIA | 0.809105 | game-dev | 0.50361 | 1 | 0.50361 |
DynaPlex/DynaPlex | 1,209 | src/lib/models/include/dynaplex/erasure/randompolicy.h | #pragma once
#include "memory"
#include "dynaplex/rng.h"
#include "dynaplex/vargroup.h"
#include "erasure_concepts.h"
#include "actionrangeprovider.h"
namespace DynaPlex::Erasure
{
template <class t_MDP>
class RandomPolicy
{
static_assert(HasGetStaticInfo<t_MDP>, "MDP must publicly define GetStaticInfo() const returning DynaPlex::VarGroup.");
DynaPlex::Erasure::ActionRangeProvider<t_MDP> provider;
public:
RandomPolicy(std::shared_ptr<const t_MDP> mdp, const DynaPlex::VarGroup& varGroup)
: provider{mdp}
{
}
using State = t_MDP::State;
int64_t GetAction(const State& state, DynaPlex::RNG& rng) const
{
int64_t numAllowedActions{ 0 };
for (const int64_t action: provider(state))
{
numAllowedActions++;
}
if (numAllowedActions == 0)
{
throw DynaPlex::Error("RandomPolicy: Not a single action allowed.");
}
double d_budget = rng.genUniform() * static_cast<double>(numAllowedActions);
int64_t budget = static_cast<int64_t>(d_budget);
for (const int64_t action : provider(state))
{
if (budget == 0)
{
return action;
}
budget--;
}
throw DynaPlex::Error("RandomPolicy: Error in logic.");
}
};
} | 0 | 0.805546 | 1 | 0.805546 | game-dev | MEDIA | 0.540505 | game-dev | 0.799572 | 1 | 0.799572 |
ChoGGi/SurvivingMars_Mods | 2,576 | Expanded Cheat Menu/Code/Menus/ConstsFunc.lua | -- See LICENSE for terms
if ChoGGi.what_game ~= "Mars" then
return
end
local ChoGGi_Funcs = ChoGGi_Funcs
local MsgPopup = ChoGGi_Funcs.Common.MsgPopup
local T = T
local Translate = ChoGGi_Funcs.Common.Translate
function ChoGGi_Funcs.Menus.SetConstMenu(action)
if not action then
return
end
local ConstsUS = ChoGGi.UserSettings.Consts
local ConstsC = ChoGGi.Consts
local setting_scale = action.setting_scale
--~ printC(setting_scale, "setting_scale")
-- see about using scale to setup the numbers
local setting_id = action.setting_id
local setting_name = action.setting_name
local setting_desc = action.setting_desc
local default_setting = action.setting_value
local item_list = {
{text = Translate(1000121--[[Default]]) .. ": " .. default_setting, value = default_setting},
{text = 15, value = 15},
{text = 20, value = 20},
{text = 25, value = 25},
{text = 50, value = 50},
{text = 75, value = 75},
{text = 100, value = 100},
{text = 250, value = 250},
{text = 500, value = 500},
{text = 1000, value = 1000},
{text = 10000, value = 10000},
{text = 25000, value = 25000},
}
local previous = ChoGGi.UserSettings[setting_id]
if previous then
table.insert(item_list, 2, {
text = Translate(1000231--[[Previous]]) .. ": " .. previous,
value = previous,
hint = T(302535920000213--[[Previously set in an ECM menu (meaning it's active and the setting here will override this value).]])
})
end
local hint = default_setting
if ConstsUS[setting_id] then
hint = ConstsUS[setting_id]
end
local function CallBackFunc(choice)
if choice.nothing_selected then
return
end
choice = choice[1]
local value = choice.value
if type(value) == "number" then
ChoGGi_Funcs.Common.SetConsts(setting_id, value)
-- If setting is the same as the default then remove it
if ConstsC[setting_id] == value then
ConstsUS[setting_id] = nil
else
ConstsUS[setting_id] = value
end
ChoGGi_Funcs.Settings.WriteSettings()
MsgPopup(
ChoGGi_Funcs.Common.SettingState(choice.text),
setting_name
)
end
end
hint = T(302535920000106--[[Current]]) .. ": " .. hint .. "\n\n" .. setting_desc
local scale = Presets.ConstDef.Scale[setting_scale]
if scale then
hint = hint .. "\n" .. T(1000081--[[Scale]]) .. ": "
.. (scale.value or 1000) .. "("
.. T(302535920000182--[[The scale this amount will be multipled by when used.]]) .. ")"
end
ChoGGi_Funcs.Common.OpenInListChoice{
callback = CallBackFunc,
items = item_list,
title = setting_name,
hint = hint,
skip_sort = true,
}
end
| 0 | 0.859219 | 1 | 0.859219 | game-dev | MEDIA | 0.830571 | game-dev | 0.887394 | 1 | 0.887394 |
hollsteinm/ReasonablePlanningAI | 2,557 | Source/ReasonablePlanningAI/Public/Composer/ActionTasks/RpaiActionTask_GameplayTaskBase.h | // Copyright (C) 2025 Radaway Software LLC. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTaskOwnerInterface.h"
#include "Composer/RpaiComposerActionTaskBase.h"
#include "RpaiActionTask_GameplayTaskBase.generated.h"
class UAITask;
USTRUCT(BlueprintType)
struct REASONABLEPLANNINGAI_API FActionTaskGameplayTaskBaseMemory
{
GENERATED_BODY()
FActionTaskGameplayTaskBaseMemory();
UAITask* AITask;
URpaiState* State;
};
/**
* Action Task that will execute an AITask. Override (Receive)StartActionTask(_Implementation) and use UAITask::NewAITask(...) to create your
* new task and fill out the parameters. Use StartTask(...) to enqueue the task for execution. Each instance of URpaiActionTask_GameplayTaskBase
* and all children only support a 1:1 mapping of state to task. Any exsisting tasks will be cancelled if found associated to the given state.
*/
UCLASS(Abstract)
class REASONABLEPLANNINGAI_API URpaiActionTask_GameplayTaskBase : public URpaiComposerActionTaskBase, public IGameplayTaskOwnerInterface
{
GENERATED_BODY()
public:
URpaiActionTask_GameplayTaskBase();
// BEGIN IGameplayTaskOwnerInterface
virtual UGameplayTasksComponent* GetGameplayTasksComponent(const UGameplayTask& Task) const override;
virtual AActor* GetGameplayTaskOwner(const UGameplayTask* Task) const override;
virtual AActor* GetGameplayTaskAvatar(const UGameplayTask* Task) const override;
virtual uint8 GetGameplayTaskDefaultPriority() const override;
virtual void OnGameplayTaskInitialized(UGameplayTask& Task) override;
virtual void OnGameplayTaskDeactivated(UGameplayTask& Task) override;
// END IGameplayTaskOwnerInterface
protected:
virtual void ReceiveCancelActionTask_Implementation(AAIController* ActionInstigator, URpaiState* CurrentState, FRpaiMemoryStruct ActionMemory, AActor* ActionTargetActor = nullptr, UWorld* ActionWorld = nullptr, bool bCancelShouldExitPlan = true) override;
UFUNCTION(BlueprintCallable, Category=Rpai)
void StartTask(URpaiState* CurrentState, UAITask* TaskToStart, FRpaiMemoryStruct ActionMemory);
// Gets the Rpai Memory associated to a controller. This should be rarely used, but may be required by child classes. Returns true if memory found, false otherwise.
UFUNCTION(BlueprintCallable, Category = Rpai)
bool GetMemoryForController(AAIController* ControllerToQuery, FRpaiMemoryStruct& OutMemoryStruct);
private:
// Find Rpai Memory associated with a given task.
TMap<AAIController*, FRpaiMemoryStruct> ControllerToMemory;
};
| 0 | 0.808912 | 1 | 0.808912 | game-dev | MEDIA | 0.959719 | game-dev | 0.875719 | 1 | 0.875719 |
toxicity188/BetterHud | 2,146 | nms/v1_19_R3/src/main/kotlin/kr/toxicity/hud/nms/v1_19_R3/entity/CraftLivingEntityView.kt | package kr.toxicity.hud.nms.v1_19_R3.entity
import net.kyori.adventure.util.TriState
import net.minecraft.world.entity.LivingEntity
import org.bukkit.Bukkit
import org.bukkit.craftbukkit.v1_19_R3.CraftServer
import org.bukkit.craftbukkit.v1_19_R3.entity.CraftLivingEntity
import org.bukkit.craftbukkit.v1_19_R3.persistence.CraftPersistentDataContainer
import org.bukkit.event.entity.EntityDamageEvent
import org.bukkit.inventory.EntityEquipment
import org.bukkit.permissions.Permission
import org.bukkit.permissions.PermissionAttachmentInfo
class CraftLivingEntityView(
val source: CraftLivingEntity
) : CraftLivingEntity(Bukkit.getServer() as CraftServer, source.unsafeHandle as LivingEntity) {
override fun getHandle(): LivingEntity {
return source.unsafeHandle as LivingEntity
}
override fun getPersistentDataContainer(): CraftPersistentDataContainer {
return source.persistentDataContainer
}
override fun getLastDamageCause(): EntityDamageEvent? {
return source.lastDamageCause
}
override fun setLastDamageCause(event: EntityDamageEvent?) {
source.lastDamageCause = event
}
override fun permissionValue(permission: Permission): TriState {
return source.permissionValue(permission)
}
override fun permissionValue(permission: String): TriState {
return source.permissionValue(permission)
}
override fun getEffectivePermissions(): Set<PermissionAttachmentInfo?> {
return source.effectivePermissions
}
override fun hasPermission(name: String): Boolean {
return source.hasPermission(name)
}
override fun hasPermission(perm: Permission): Boolean {
return source.hasPermission(perm)
}
override fun isPermissionSet(name: String): Boolean {
return source.isPermissionSet(name)
}
override fun isPermissionSet(perm: Permission): Boolean {
return source.isPermissionSet(perm)
}
override fun recalculatePermissions() {
source.recalculatePermissions()
}
override fun getEquipment(): EntityEquipment? {
return source.equipment
}
} | 0 | 0.777716 | 1 | 0.777716 | game-dev | MEDIA | 0.969129 | game-dev | 0.766303 | 1 | 0.766303 |
fulpstation/fulpstation | 3,684 | code/datums/actions/mobs/assume_form.dm | /// Allows a mob to assume the form of another item or mob.
/// Warning, this will likely shit the bricks if you add this action to anything more sophisticated than a basic mob- this isn't built for anything carbon-wise.
/datum/action/cooldown/mob_cooldown/assume_form
name = "Assume Form"
desc = "Choose something that you wish to blend into the environment as. Click on yourself to reset your appearance."
button_icon_state = "sniper_zoom"
background_icon_state = "bg_alien"
overlay_icon_state = "bg_alien_border"
ranged_mousepointer = 'icons/effects/mouse_pointers/supplypod_target.dmi'
check_flags = AB_CHECK_CONSCIOUS
cooldown_time = 1.5 SECONDS
/// Stuff that we can not disguise as.
var/static/list/blacklist_typecache = typecacheof(list(
/atom/movable/screen,
/obj/effect,
/obj/energy_ball,
/obj/narsie,
/obj/singularity,
))
/datum/action/cooldown/mob_cooldown/assume_form/Grant(mob/grant_to)
. = ..()
RegisterSignal(owner, COMSIG_LIVING_DEATH, PROC_REF(reset_appearances))
/datum/action/cooldown/mob_cooldown/assume_form/Remove(mob/remove_from)
reset_appearances()
UnregisterSignal(owner, COMSIG_LIVING_DEATH)
return ..()
/datum/action/cooldown/mob_cooldown/assume_form/Activate(atom/target_atom)
disable_cooldown_actions()
determine_intent(target_atom)
StartCooldown()
enable_cooldown_actions()
return TRUE
/// Rapid proc to test if we can assume the form of a given atom. Returns TRUE if we can, FALSE if we can't. Done like this so we can be nice and explicit.
/datum/action/cooldown/mob_cooldown/assume_form/proc/can_assume_form(atom/target_atom)
if(is_type_in_typecache(target_atom, blacklist_typecache) || (!isobj(target_atom) && !ismob(target_atom)))
return FALSE
return TRUE
/// Determines what our user meant by their action. If they clicked on themselves, we reset our appearance. Otherwise, we assume the appearance of the clicked-on item.
/datum/action/cooldown/mob_cooldown/assume_form/proc/determine_intent(atom/target_atom)
if(!can_assume_form(target_atom))
return
if(target_atom == owner)
reset_appearances()
return
assume_appearances(target_atom)
/// Assumes the appearance of a desired movable and applies it to our mob. Target is the movable in question.
/datum/action/cooldown/mob_cooldown/assume_form/proc/assume_appearances(atom/movable/target_atom)
owner.appearance = target_atom.appearance
owner.copy_overlays(target_atom)
owner.alpha = max(target_atom.alpha, 150) //fucking chameleons
owner.transform = initial(target_atom.transform)
owner.pixel_x = target_atom.base_pixel_x
owner.pixel_y = target_atom.base_pixel_y
// important: do this at the very end because we might have SIGNAL_ADDTRAIT for this on the mob that's dependent on the above logic
SEND_SIGNAL(owner, COMSIG_ACTION_DISGUISED_APPEARANCE, target_atom)
ADD_TRAIT(owner, TRAIT_DISGUISED, ACTION_TRAIT)
/// Resets the appearances of the mob to the default.
/datum/action/cooldown/mob_cooldown/assume_form/proc/reset_appearances()
SIGNAL_HANDLER
if(!HAS_TRAIT(owner, TRAIT_DISGUISED))
return // in case we're being invoked on death and we aren't disguised (or we just click on ourselves randomly), no need to do this additional work.
owner.animate_movement = SLIDE_STEPS
owner.maptext = null
owner.alpha = initial(owner.alpha)
owner.color = initial(owner.color)
owner.desc = initial(owner.desc)
owner.name = initial(owner.name)
owner.icon = initial(owner.icon)
owner.icon_state = initial(owner.icon_state)
owner.cut_overlays()
// important: do this very end because we might have SIGNAL_REMOVETRAIT for this on the mob that's dependent on the above logic
REMOVE_TRAIT(owner, TRAIT_DISGUISED, ACTION_TRAIT)
| 0 | 0.841304 | 1 | 0.841304 | game-dev | MEDIA | 0.97269 | game-dev | 0.960189 | 1 | 0.960189 |
ImLegiitXD/Dream-Advanced | 3,867 | dll/back/1.12/net/minecraft/client/gui/GuiYesNo.java | package net.minecraft.client.gui;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
import net.minecraft.client.resources.I18n;
public class GuiYesNo extends GuiScreen
{
/**
* A reference to the screen object that created this. Used for navigating between screens.
*/
protected GuiYesNoCallback parentScreen;
protected String messageLine1;
private final String messageLine2;
private final List<String> listLines = Lists.<String>newArrayList();
/** The text shown for the first button in GuiYesNo */
protected String confirmButtonText;
/** The text shown for the second button in GuiYesNo */
protected String cancelButtonText;
protected int parentButtonClickedId;
private int ticksUntilEnable;
public GuiYesNo(GuiYesNoCallback parentScreenIn, String messageLine1In, String messageLine2In, int parentButtonClickedIdIn)
{
this.parentScreen = parentScreenIn;
this.messageLine1 = messageLine1In;
this.messageLine2 = messageLine2In;
this.parentButtonClickedId = parentButtonClickedIdIn;
this.confirmButtonText = I18n.format("gui.yes");
this.cancelButtonText = I18n.format("gui.no");
}
public GuiYesNo(GuiYesNoCallback parentScreenIn, String messageLine1In, String messageLine2In, String confirmButtonTextIn, String cancelButtonTextIn, int parentButtonClickedIdIn)
{
this.parentScreen = parentScreenIn;
this.messageLine1 = messageLine1In;
this.messageLine2 = messageLine2In;
this.confirmButtonText = confirmButtonTextIn;
this.cancelButtonText = cancelButtonTextIn;
this.parentButtonClickedId = parentButtonClickedIdIn;
}
/**
* Adds the buttons (and other controls) to the screen in question. Called when the GUI is displayed and when the
* window resizes, the buttonList is cleared beforehand.
*/
public void initGui()
{
this.buttonList.add(new GuiOptionButton(0, this.width / 2 - 155, this.height / 6 + 96, this.confirmButtonText));
this.buttonList.add(new GuiOptionButton(1, this.width / 2 - 155 + 160, this.height / 6 + 96, this.cancelButtonText));
this.listLines.clear();
this.listLines.addAll(this.fontRenderer.listFormattedStringToWidth(this.messageLine2, this.width - 50));
}
/**
* Called by the controls from the buttonList when activated. (Mouse pressed for buttons)
*/
protected void actionPerformed(GuiButton button) throws IOException
{
this.parentScreen.confirmClicked(button.id == 0, this.parentButtonClickedId);
}
/**
* Draws the screen and all the components in it.
*/
public void drawScreen(int mouseX, int mouseY, float partialTicks)
{
this.drawDefaultBackground();
this.drawCenteredString(this.fontRenderer, this.messageLine1, this.width / 2, 70, 16777215);
int i = 90;
for (String s : this.listLines)
{
this.drawCenteredString(this.fontRenderer, s, this.width / 2, i, 16777215);
i += this.fontRenderer.FONT_HEIGHT;
}
super.drawScreen(mouseX, mouseY, partialTicks);
}
/**
* Sets the number of ticks to wait before enabling the buttons.
*/
public void setButtonDelay(int ticksUntilEnableIn)
{
this.ticksUntilEnable = ticksUntilEnableIn;
for (GuiButton guibutton : this.buttonList)
{
guibutton.enabled = false;
}
}
/**
* Called from the main game loop to update the screen.
*/
public void updateScreen()
{
super.updateScreen();
if (--this.ticksUntilEnable == 0)
{
for (GuiButton guibutton : this.buttonList)
{
guibutton.enabled = true;
}
}
}
}
| 0 | 0.836303 | 1 | 0.836303 | game-dev | MEDIA | 0.517333 | game-dev | 0.897573 | 1 | 0.897573 |
bereft-souls/QuestBooks | 5,593 | QuestLog/BookChapter.cs | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Newtonsoft.Json;
using QuestBooks.QuestLog.DefaultChapters;
using QuestBooks.Quests;
using System.Collections.Generic;
using System.Linq;
using Terraria.ModLoader;
namespace QuestBooks.QuestLog
{
[ExtendsFromMod("QuestBooks")]
public abstract class BookChapter
{
/// <summary>
/// The collection of <see cref="ChapterElement"/>s to be displayed in the quest log.
/// </summary>
public abstract List<ChapterElement> Elements { get; set; }
/// <summary>
/// The string that will be displayed in the quest log. You should use localization here where applicable.
/// </summary>
[JsonIgnore]
public abstract string DisplayName { get; }
/// <summary>
/// A collection of all quests contained by elements in this quest line.<br/>
/// These quests are all the actual implemented instances, and not duplicates or templates - you can access accurate info or methods from them.<br/>
/// Pulls from <see cref="Elements"/>.
/// </summary>
[JsonIgnore]
public IEnumerable<Quest> QuestList => Elements.Where(e => e is QuestElement).Cast<QuestElement>().Select(e => e.Quest);
/// <summary>
/// The completion progress of this quest line.<br/>
/// 0f is no quests completed, and 1f is all quests completed.<br/>
/// <c>float.NaN</c> is returned for quest lines with no quests in their elements.<br/>
/// Pulls from <see cref="QuestList"/>.
/// </summary>
[JsonIgnore]
public virtual float Progress
{
get
{
int applicableCount = 0;
float totalComplete = QuestList
.Select(x => { applicableCount++; return x; })
.Where(x => x.Completed)
.Count();
return applicableCount > 0 ? totalComplete / applicableCount : float.NaN;
}
}
/// <summary>
/// Whether or not all quests in this questline are complete.<br/>
/// Pulls from <see cref="QuestList"/>.
/// </summary>
[JsonIgnore]
public virtual bool Complete => QuestList.All(q => q.Completed);
/// <summary>
/// Determines whether this quest line should appear in the quest log.<br/>
/// Useful for hiding certain chapters until progression goals are met.
/// </summary>
public virtual bool VisibleInLog() => true;
/// <summary>
/// Determines whether this quest line should be able to be selected in the quest log.<br/>
/// Useful for when you want to display a chapter, but hide its contents until progression goals are met.
/// </summary>
public virtual bool IsUnlocked() => true;
/// <summary>
/// Determines whether this quest line should be "draggable" in the log. This value can be modified from the designer.
/// </summary>
public virtual bool EnableShifting { get; set; } = false;
/// <summary>
/// Determines the center of the view area to jump to when selecting a draggable chapter.
/// </summary>
public virtual Vector2 ViewAnchor { get; set; } = Vector2.Zero;
/// <summary>
/// Determines the maximum (bottom right) view window for a draggable chapter.
/// </summary>
public virtual Vector2 MaxViewPoint { get; set; } = Vector2.Zero;
/// <summary>
/// Determines the minimum (top left) view window for a draggable chapter.
/// </summary>
public virtual Vector2 MinViewPoint { get; set; } = Vector2.Zero;
public virtual void Update()
{
foreach (ChapterElement questElement in Elements)
questElement.Update();
}
/// <summary>
/// Performs the default drawing behavior of for this <see cref="ScrollChapter"/>. Assigns colors and calls <see cref="DrawBasicChapter(SpriteBatch, string, Color, Color, Color, Rectangle, float)(SpriteBatch, string, Color, Color, Color, Rectangle, float)"/>.
/// </summary>
public abstract void Draw(SpriteBatch spriteBatch, Rectangle designatedArea, float scale, bool selected, bool hovered);
/// <summary>
/// Override this to change how the "open quest log" icon is drawn in the inventory.<br/>
/// <paramref name="drawPriority"/> is the current draw override priority. If you have something of higher priority, modify both <paramref name="drawPriority"/> and <paramref name="iconDraw"/>.
/// </summary>
public virtual void OverrideIconDraw(ref float drawPriority, ref QuestLogStyle.IconDrawDelegate iconDraw)
{
}
/// <summary>
/// Override this to change how the "open quest log" outline is drawn in the inventory.<br/>
/// <paramref name="drawPriority"/> is the current draw override priority. If you have something of higher priority, modify both <paramref name="drawPriority"/> and <paramref name="outlineDraw"/>.
/// </summary>
public virtual void OverrideIconOutlineDraw(ref float drawPriority, ref QuestLogStyle.IconDrawDelegate outlineDraw)
{
}
/// <summary>
/// Clones the members of this quest book into a new quest line.
/// </summary>
public virtual void CloneTo(BookChapter newInstance)
{
newInstance.Elements.AddRange(Elements);
}
}
}
| 0 | 0.879606 | 1 | 0.879606 | game-dev | MEDIA | 0.843979 | game-dev | 0.843461 | 1 | 0.843461 |
Sandrem/FlyCasual | 3,116 | Assets/Scripts/Model/Content/SecondEdition/Extended/Pilots/Scum/LancerClassPursuitCraft/SabineWren.cs | using ActionsList;
using Arcs;
using BoardTools;
using Content;
using Ship;
using System.Collections.Generic;
using Upgrade;
namespace Ship
{
namespace SecondEdition.LancerClassPursuitCraft
{
public class SabineWren : LancerClassPursuitCraft
{
public SabineWren() : base()
{
PilotInfo = new PilotCardInfo25
(
"Sabine Wren",
"Artistic Saboteur",
Faction.Scum,
3,
6,
9,
isLimited: true,
abilityType: typeof(Abilities.SecondEdition.SabineWrenLancerPilotAbility),
tags: new List<Tags>
{
Tags.BountyHunter,
Tags.Mandalorian
},
extraUpgradeIcons: new List<UpgradeType>()
{
UpgradeType.Talent,
UpgradeType.Crew,
UpgradeType.Illicit,
UpgradeType.Illicit,
UpgradeType.Modification,
UpgradeType.Title
},
seImageNumber: 220,
legality: new List<Legality>() { Legality.ExtendedLegal }
);
PilotNameCanonical = "sabinewren-lancerclasspursuitcraft";
}
}
}
}
namespace Abilities.SecondEdition
{
public class SabineWrenLancerPilotAbility : GenericAbility
{
public override void ActivateAbility()
{
HostShip.OnGenerateDiceModifications += AddSabinebility;
}
public override void DeactivateAbility()
{
HostShip.OnGenerateDiceModifications -= AddSabinebility;
}
private void AddSabinebility(GenericShip ship)
{
ship.AddAvailableDiceModificationOwn(new SabineWrenDiceModification()
{
ImageUrl = HostShip.ImageUrl
});
}
private class SabineWrenDiceModification : GenericAction
{
public SabineWrenDiceModification()
{
Name = DiceModificationName = "Sabine Wren";
}
public override void ActionEffect(System.Action callBack)
{
Combat.CurrentDiceRoll.AddDiceAndShow(DieSide.Focus);
callBack();
}
public override bool IsDiceModificationAvailable()
{
bool result = false;
if (Combat.AttackStep == CombatStep.Defence)
{
ShotInfo shotInfo = new ShotInfo(Combat.Defender, Combat.Attacker, Combat.Defender.PrimaryWeapons);
if (shotInfo.InArcByType(ArcType.SingleTurret)) result = true;
}
return result;
}
public override int GetDiceModificationPriority()
{
return 110;
}
}
}
}
| 0 | 0.799367 | 1 | 0.799367 | game-dev | MEDIA | 0.9536 | game-dev | 0.774646 | 1 | 0.774646 |
IAFEnvoy/IceAndFire-Fabric | 15,018 | src/main/java/com/iafenvoy/iceandfire/render/model/ModelDreadBeast.java | package com.iafenvoy.iceandfire.render.model;
import com.google.common.collect.ImmutableList;
import com.iafenvoy.iceandfire.entity.EntityDreadBeast;
import com.iafenvoy.uranus.animation.IAnimatedEntity;
import com.iafenvoy.uranus.client.model.AdvancedModelBox;
import com.iafenvoy.uranus.client.model.ModelAnimator;
import com.iafenvoy.uranus.client.model.basic.BasicModelPart;
import net.minecraft.client.render.OverlayTexture;
import net.minecraft.client.render.VertexConsumer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.Entity;
public class ModelDreadBeast extends ModelDragonBase<EntityDreadBeast> {
public final AdvancedModelBox Body;
public final AdvancedModelBox LegL1;
public final AdvancedModelBox LowerBody;
public final AdvancedModelBox Neck1;
public final AdvancedModelBox LegR1;
public final AdvancedModelBox pelt;
public final AdvancedModelBox pelt_1;
public final AdvancedModelBox pelt_2;
public final AdvancedModelBox LegL2;
public final AdvancedModelBox Tail;
public final AdvancedModelBox BackLegR1;
public final AdvancedModelBox BackLegL1;
public final AdvancedModelBox pelt_3;
public final AdvancedModelBox Tail2;
public final AdvancedModelBox Tail3;
public final AdvancedModelBox BackLegR2;
public final AdvancedModelBox BackLegL2;
public final AdvancedModelBox HeadBase;
public final AdvancedModelBox HeadFront;
public final AdvancedModelBox Jaw;
public final AdvancedModelBox ChopsR;
public final AdvancedModelBox ChopsL;
public final AdvancedModelBox EarR;
public final AdvancedModelBox EarL;
public final AdvancedModelBox pelt_4;
public final AdvancedModelBox EarR2;
public final AdvancedModelBox EarL2;
public final AdvancedModelBox LegR2;
private final ModelAnimator animator;
public ModelDreadBeast() {
this.texWidth = 256;
this.texHeight = 128;
this.HeadBase = new AdvancedModelBox(this, 0, 15);
this.HeadBase.setPos(0.0F, 1.4F, -8.6F);
this.HeadBase.addBox(-3.5F, -3.51F, -4.6F, 7, 6, 6, 0.0F);
this.setRotateAngle(this.HeadBase, -0.12217304763960307F, 0.0F, 0.0F);
this.LegL1 = new AdvancedModelBox(this, 0, 54);
this.LegL1.mirror = true;
this.LegL1.setPos(3.3F, 2.0F, -3.5F);
this.LegL1.addBox(-1.0F, 0.0F, -1.5F, 2, 7, 3, 0.0F);
this.setRotateAngle(this.LegL1, -0.091106186954104F, 0.0F, 0.0F);
this.EarR = new AdvancedModelBox(this, 3, 0);
this.EarR.setPos(-3.3F, -1.5F, 0.9F);
this.EarR.addBox(-1.5F, -1.1F, -3.1F, 3, 1, 4, 0.0F);
this.setRotateAngle(this.EarR, -2.6406831582674206F, 0.5009094953223726F, -1.5025539530419183F);
this.BackLegR1 = new AdvancedModelBox(this, 20, 52);
this.BackLegR1.mirror = true;
this.BackLegR1.setPos(2.5F, -0.5F, 9.3F);
this.BackLegR1.addBox(-1.0F, 0.0F, -1.5F, 2, 8, 5, 0.0F);
this.setRotateAngle(this.BackLegR1, 0.045553093477052F, 0.0F, 0.0F);
this.LegR1 = new AdvancedModelBox(this, 0, 54);
this.LegR1.setPos(-3.3F, 2.0F, -3.5F);
this.LegR1.addBox(-1.0F, 0.0F, -1.5F, 2, 7, 3, 0.0F);
this.setRotateAngle(this.LegR1, -0.091106186954104F, 0.0F, 0.0F);
this.Tail = new AdvancedModelBox(this, 50, 14);
this.Tail.setPos(0.0F, -1.6F, 13.2F);
this.Tail.addBox(-1.5F, -1.0F, 0.0F, 3, 4, 7, 0.0F);
this.setRotateAngle(this.Tail, -0.9560913642424937F, 0.0F, 0.0F);
this.ChopsL = new AdvancedModelBox(this, 37, 0);
this.ChopsL.mirror = true;
this.ChopsL.setPos(2.2F, 1.6F, -1.0F);
this.ChopsL.addBox(-1.0F, -0.5F, -3.6F, 4, 2, 5, 0.0F);
this.setRotateAngle(this.ChopsL, -2.5953045977155678F, -0.8196066167365371F, 0.9560913642424937F);
this.LegR2 = new AdvancedModelBox(this, 11, 54);
this.LegR2.setPos(0.0F, 6.4F, 0.1F);
this.LegR2.addBox(-1.01F, 0.0F, -1.6F, 2, 6, 2, 0.0F);
this.pelt_2 = new AdvancedModelBox(this, 91, 49);
this.pelt_2.setPos(0.0F, -0.8F, 3.6F);
this.pelt_2.addBox(-4.0F, -3.4F, 0.0F, 8, 4, 9, 0.0F);
this.setRotateAngle(this.pelt_2, 0.091106186954104F, 0.0F, 0.0F);
this.EarL = new AdvancedModelBox(this, 3, 0);
this.EarL.mirror = true;
this.EarL.setPos(3.3F, -1.5F, 0.9F);
this.EarL.addBox(-1.5F, -1.1F, -3.1F, 3, 1, 4, 0.0F);
this.setRotateAngle(this.EarL, -2.5497515042385164F, -0.36425021489121656F, 1.5025539530419183F);
this.BackLegR2 = new AdvancedModelBox(this, 0, 44);
this.BackLegR2.mirror = true;
this.BackLegR2.setPos(0.0F, 7.5F, 1.4F);
this.BackLegR2.addBox(-1.01F, 0.0F, -0.3F, 2, 8, 2, 0.0F);
this.pelt_3 = new AdvancedModelBox(this, 91, 49);
this.pelt_3.setPos(0.0F, 0.4F, 5.6F);
this.pelt_3.addBox(-4.0F, -3.4F, 0.0F, 8, 4, 9, 0.0F);
this.setRotateAngle(this.pelt_3, 0.31869712141416456F, 0.0F, 0.0F);
this.BackLegL2 = new AdvancedModelBox(this, 0, 44);
this.BackLegL2.setPos(0.0F, 7.5F, 1.4F);
this.BackLegL2.addBox(-1.01F, 0.0F, -0.3F, 2, 8, 2, 0.0F);
this.HeadFront = new AdvancedModelBox(this, 14, 2);
this.HeadFront.setPos(0.0F, -1.2F, -5.1F);
this.HeadFront.addBox(-1.5F, -2.2F, -5.4F, 3, 4, 8, 0.0F);
this.setRotateAngle(this.HeadFront, -0.27314402793711257F, 0.0F, 0.0F);
this.Jaw = new AdvancedModelBox(this, 28, 9);
this.Jaw.setPos(0.0F, 1.5F, -5.7F);
this.Jaw.addBox(-2.0F, -0.7F, -5.9F, 4, 3, 7, 0.0F);
this.setRotateAngle(this.Jaw, 0.27314402793711257F, 0.0F, -3.141592653589793F);
this.Neck1 = new AdvancedModelBox(this, 0, 28);
this.Neck1.setPos(0.0F, -0.8F, -4.5F);
this.Neck1.addBox(-2.5F, -2.0F, -8.2F, 5, 6, 8, 0.0F);
this.setRotateAngle(this.Neck1, 0.36425021489121656F, 0.0F, 0.0F);
this.Tail2 = new AdvancedModelBox(this, 81, 22);
this.Tail2.setPos(0.0F, 0.4F, 6.0F);
this.Tail2.addBox(-2.01F, -1.7F, -0.8F, 4, 5, 8, 0.0F);
this.setRotateAngle(this.Tail2, 0.5462880558742251F, 0.0F, -0.091106186954104F);
this.LegL2 = new AdvancedModelBox(this, 11, 54);
this.LegL2.mirror = true;
this.LegL2.setPos(0.0F, 6.4F, 0.1F);
this.LegL2.addBox(-1.01F, 0.0F, -1.6F, 2, 6, 2, 0.0F);
this.Body = new AdvancedModelBox(this, 38, 45);
this.Body.setPos(0.0F, 9.3F, -6.0F);
this.Body.addBox(-4.0F, -3.9F, -6.5F, 8, 10, 10, 0.0F);
this.setRotateAngle(this.Body, 0.091106186954104F, 0.0F, 0.0F);
this.pelt = new AdvancedModelBox(this, 90, 49);
this.pelt.setPos(0.0F, 0.2F, -5.4F);
this.pelt.addBox(-5.0F, -3.4F, 0.0F, 10, 4, 9, 0.0F);
this.setRotateAngle(this.pelt, 0.4553564018453205F, 0.0F, 0.0F);
this.EarL2 = new AdvancedModelBox(this, 5, 2);
this.EarL2.setPos(0.3F, 0.1F, -2.9F);
this.EarL2.addBox(-1.0F, -1.1F, -1.5F, 2, 1, 2, 0.0F);
this.setRotateAngle(this.EarL2, 0.091106186954104F, 0.0F, 0.0F);
this.Tail3 = new AdvancedModelBox(this, 69, 10);
this.Tail3.setPos(0.0F, 0.7F, 5.7F);
this.Tail3.addBox(-1.01F, -2.1F, 0.0F, 2, 4, 7, 0.0F);
this.setRotateAngle(this.Tail3, -0.136659280431156F, 0.0F, 0.0F);
this.BackLegL1 = new AdvancedModelBox(this, 20, 52);
this.BackLegL1.setPos(-2.5F, -0.5F, 9.3F);
this.BackLegL1.addBox(-1.0F, 0.0F, -1.5F, 2, 8, 5, 0.0F);
this.setRotateAngle(this.BackLegL1, 0.045553093477052F, 0.0F, 0.0F);
this.ChopsR = new AdvancedModelBox(this, 37, 0);
this.ChopsR.setPos(-2.2F, 1.6F, -1.0F);
this.ChopsR.addBox(-3.0F, -0.5F, -3.6F, 4, 2, 5, 0.0F);
this.setRotateAngle(this.ChopsR, -2.5953045977155678F, 0.8196066167365371F, -0.9560913642424937F);
this.EarR2 = new AdvancedModelBox(this, 5, 2);
this.EarR2.mirror = true;
this.EarR2.setPos(-0.3F, 0.1F, -2.9F);
this.EarR2.addBox(-1.0F, -1.1F, -1.5F, 2, 1, 2, 0.0F);
this.setRotateAngle(this.EarR2, 0.091106186954104F, 0.0F, 0.0F);
this.LowerBody = new AdvancedModelBox(this, 4, 69);
this.LowerBody.setPos(0.0F, -0.5F, 3.0F);
this.LowerBody.addBox(-3.0F, -2.7F, -0.1F, 6, 8, 14, 0.0F);
this.setRotateAngle(this.LowerBody, -0.136659280431156F, 0.0F, 0.0F);
this.pelt_4 = new AdvancedModelBox(this, 92, 49);
this.pelt_4.setPos(0.0F, 1.4F, -3.4F);
this.pelt_4.addBox(-3.0F, -3.4F, 0.0F, 6, 4, 9, 0.0F);
this.setRotateAngle(this.pelt_4, 0.31869712141416456F, 0.0F, 0.0F);
this.pelt_1 = new AdvancedModelBox(this, 90, 49);
this.pelt_1.setPos(0.0F, -0.8F, 0.6F);
this.pelt_1.addBox(-5.0F, -3.4F, 0.0F, 10, 4, 9, 0.0F);
this.setRotateAngle(this.pelt_1, 0.5462880558742251F, 0.0F, 0.0F);
this.Neck1.addChild(this.HeadBase);
this.Body.addChild(this.LegL1);
this.HeadBase.addChild(this.EarR);
this.LowerBody.addChild(this.BackLegR1);
this.Body.addChild(this.LegR1);
this.LowerBody.addChild(this.Tail);
this.HeadBase.addChild(this.ChopsL);
this.LegR1.addChild(this.LegR2);
this.Body.addChild(this.pelt_2);
this.HeadBase.addChild(this.EarL);
this.BackLegR1.addChild(this.BackLegR2);
this.LowerBody.addChild(this.pelt_3);
this.BackLegL1.addChild(this.BackLegL2);
this.HeadBase.addChild(this.HeadFront);
this.HeadBase.addChild(this.Jaw);
this.Body.addChild(this.Neck1);
this.Tail.addChild(this.Tail2);
this.LegL1.addChild(this.LegL2);
this.Body.addChild(this.pelt);
this.EarL.addChild(this.EarL2);
this.Tail2.addChild(this.Tail3);
this.LowerBody.addChild(this.BackLegL1);
this.HeadBase.addChild(this.ChopsR);
this.EarR.addChild(this.EarR2);
this.Body.addChild(this.LowerBody);
this.HeadBase.addChild(this.pelt_4);
this.Body.addChild(this.pelt_1);
this.animator = ModelAnimator.create();
this.updateDefaultPose();
}
@Override
public Iterable<BasicModelPart> parts() {
return ImmutableList.of(this.Body);
}
@Override
public Iterable<AdvancedModelBox> getAllParts() {
return ImmutableList.of(this.Body, this.LegL1, this.LowerBody, this.Neck1, this.LegR1, this.pelt, this.pelt_1, this.pelt_2, this.LegL2, this.Tail, this.BackLegR1,
this.BackLegL1, this.pelt_3, this.Tail2, this.Tail3, this.BackLegR2, this.BackLegL2, this.HeadBase, this.HeadFront, this.Jaw, this.ChopsR, this.ChopsL, this.EarR,
this.EarL, this.pelt_4, this.EarR2, this.EarL2, this.LegR2);
}
@Override
public void setAngles(EntityDreadBeast entity, float limbAngle, float limbDistance, float animationProgress, float headYaw, float headPitch) {
this.animate(entity, limbAngle, limbDistance, animationProgress, headYaw, headPitch, 0);
float speed_walk = 0.45F;
float speed_idle = 0.05F;
float degree_walk = 1F;
float degree_idle = 0.5F;
AdvancedModelBox[] NECK = new AdvancedModelBox[]{this.Neck1, this.HeadBase};
AdvancedModelBox[] TAIL = new AdvancedModelBox[]{this.Tail, this.Tail2, this.Tail3};
this.chainWave(NECK, speed_idle, degree_idle * 0.15F, -1, animationProgress, 1);
this.walk(this.Jaw, speed_idle, degree_idle * 0.35F, true, 1, -0.1F, animationProgress, 1);
this.walk(this.pelt, speed_idle, degree_idle * 0.2F, false, 3, -0.1F, animationProgress, 1);
this.walk(this.pelt_1, speed_idle, degree_idle * 0.2F, false, 3, -0.1F, animationProgress, 1);
this.walk(this.pelt_2, speed_idle, degree_idle * 0.2F, false, 3, -0.1F, animationProgress, 1);
this.walk(this.pelt_3, speed_idle, degree_idle * 0.2F, false, 3, -0.1F, animationProgress, 1);
this.walk(this.pelt_4, speed_idle, degree_idle * 0.2F, false, 3, -0.1F, animationProgress, 1);
this.chainSwing(TAIL, speed_idle, degree_idle * 0.75F, -2, animationProgress, 1);
this.chainWave(TAIL, speed_idle, degree_idle * 0.15F, 0, animationProgress, 1);
this.chainWave(NECK, speed_walk, degree_walk * 0.15F, -1, limbAngle, limbDistance);
this.chainWave(TAIL, speed_walk, degree_walk * 0.15F, 2, limbAngle, limbDistance);
this.bob(this.Body, speed_walk, degree_walk * 1.15F, false, limbAngle, limbDistance);
this.walk(this.BackLegR1, speed_walk, degree_walk * -0.75F, true, 0, 0F, limbAngle, limbDistance);
this.walk(this.BackLegL1, speed_walk, degree_walk * -0.75F, true, 0, 0F, limbAngle, limbDistance);
this.walk(this.BackLegR2, speed_walk, degree_walk * -0.5F, true, 1, 0.3F, limbAngle, limbDistance);
this.walk(this.BackLegL2, speed_walk, degree_walk * -0.5F, true, 1, 0.3F, limbAngle, limbDistance);
this.walk(this.LegR1, speed_walk, degree_walk * -0.75F, false, 0, 0F, limbAngle, limbDistance);
this.walk(this.LegL1, speed_walk, degree_walk * -0.75F, false, 0, 0F, limbAngle, limbDistance);
this.walk(this.LegR2, speed_walk, degree_walk * -0.5F, false, -1, 0.3F, limbAngle, limbDistance);
this.walk(this.LegL2, speed_walk, degree_walk * -0.5F, false, -1, 0.3F, limbAngle, limbDistance);
float f12 = -0.9560913642424937F + limbDistance;
if (f12 > Math.toRadians(-20))
f12 = (float) Math.toRadians(-20);
this.Tail.rotateAngleX = f12;
}
public void animate(IAnimatedEntity entity, float f, float f1, float f2, float f3, float f4, float f5) {
this.resetToDefaultPose();
this.animator.update(entity);
if (this.animator.setAnimation(EntityDreadBeast.ANIMATION_BITE)) {
this.animator.startKeyframe(5);
this.rotate(this.animator, this.Neck1, -39, 0, 0);
this.rotate(this.animator, this.HeadBase, 40, 0, -15);
this.rotate(this.animator, this.Jaw, -50, 0, 0);
this.animator.endKeyframe();
this.animator.startKeyframe(5);
this.rotate(this.animator, this.Neck1, -19, 0, 0);
this.rotate(this.animator, this.HeadBase, 20, 0, 10);
this.rotate(this.animator, this.Jaw, 10, 0, 0);
this.animator.endKeyframe();
this.animator.resetKeyframe(5);
}
if (this.animator.setAnimation(EntityDreadBeast.ANIMATION_SPAWN)) {
this.animator.startKeyframe(0);
this.animator.move(this.Body, 0, 35, 0);
this.animator.endKeyframe();
this.animator.startKeyframe(30);
this.animator.move(this.Body, 0, 0, 0);
this.animator.endKeyframe();
this.animator.resetKeyframe(5);
}
}
@Override
public void renderStatue(MatrixStack matrixStackIn, VertexConsumer bufferIn, int packedLightIn, Entity living) {
this.render(matrixStackIn, bufferIn, packedLightIn, OverlayTexture.DEFAULT_UV, 1.0F, 1.0F, 1.0F, 1.0F);
}
}
| 0 | 0.843045 | 1 | 0.843045 | game-dev | MEDIA | 0.615935 | game-dev | 0.524679 | 1 | 0.524679 |
Kronuz/Xapiand | 13,870 | oldtests/test_patcher.cc | /*
* Copyright (c) 2015-2019 Dubalu LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "test_patcher.h"
#include "../src/msgpack_patcher.h"
#include "../src/rapidjson/document.h"
#include "../src/rapidjson/rapidjson.h"
#include "utils.h"
const std::string path_patcher_test = std::string(FIXTURES_PATH) + "/examples/json/";
int test_patcher_mix() {
INIT_LOG
std::string obj_str;
std::string filename(path_patcher_test + "object_to_patch.txt");
if (!read_file_contents(filename, &obj_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
std::string patch_str;
filename = path_patcher_test + "patch_mix.txt";
if (!read_file_contents(filename, &patch_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
std::string expected;
filename = path_patcher_test + "patch_result.txt";
if (!read_file_contents(filename, &expected)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
rapidjson::Document doc_patch;
rapidjson::Document doc_obj;
json_load(doc_patch, patch_str);
json_load(doc_obj, obj_str);
MsgPack patch(doc_patch);
MsgPack obj(doc_obj);
try {
apply_patch(patch, obj);
auto result = obj.to_string();
if (expected.compare(result) != 0) {
L_ERR("ERROR: Patch is not working.\nResult:\n{}\nExpected:\n{}", result, expected);
RETURN(1);
} else {
RETURN(0);
}
} catch (const BaseException& exc) {
L_EXC("ERROR: {}", exc.get_context());
RETURN(1);
}
}
int test_patcher_add() {
INIT_LOG
std::string obj_str;
std::string filename(path_patcher_test + "object_to_patch.txt");
if (!read_file_contents(filename, &obj_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
std::string patch_str;
filename = path_patcher_test + "patch_add.txt";
if (!read_file_contents(filename, &patch_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
std::string expected("{\"heroes\":[{\"hero\":\"Batman\",\"name\":\"Bruce Wayne\",\"super_power\":\"High-tech equipment and weapons\",\"enemy\":\"Joker\",\"creation\":\"1939\",\"partnerships\":\"Robin\"},{\"hero\":\"Superman\",\"name\":\"Clark Kent\",\"super_power\":\"too many\",\"enemy\":\"Lex Luthor\",\"creation\":\"1933\"},{\"hero\":\"Flash\",\"name\":\"Bart Allen\",\"super_power\":\"fast\",\"enemy\":\"Zoom\",\"creation\":\"1940\"},{\"hero\":\"Green Lantern\",\"name\":\"Hal Jordan\",\"super_power\":\"Use of power ring\",\"enemy\":\"The Gambler\",\"creation\":\"1940\"}],\"villains\":[{\"villain\":\"Joker\",\"name\":\"unknown\",\"super_power\":\"Genius-level intellect\",\"enemy\":\"Batman\",\"creation\":\"1940\"},{\"villain\":\"Mr. Freeze\",\"name\":\"Dr. Victor Fries\",\"super_power\":\"Sub-zero physiology\",\"enemy\":\"Batman\",\"creation\":\"1956\"}]}");
rapidjson::Document doc_obj;
rapidjson::Document doc_patch;
json_load(doc_obj, obj_str);
json_load(doc_patch, patch_str);
MsgPack obj(doc_obj);
MsgPack patch(doc_patch);
try {
apply_patch(patch, obj);
auto result = obj.to_string();
if (expected.compare(result) != 0) {
L_ERR("ERROR: Patch is not working.\nResult:\n{}\nExpected:\n{}", result, expected);
RETURN(1);
} else {
RETURN(0);
}
} catch (const BaseException& exc) {
L_EXC("ERROR: {}", exc.get_context());
RETURN(1);
}
}
int test_patcher_remove() {
INIT_LOG
std::string obj_str;
std::string filename(path_patcher_test + "object_to_patch.txt");
if (!read_file_contents(filename, &obj_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
std::string patch_str;
filename = path_patcher_test + "patch_remove.txt";
if (!read_file_contents(filename, &patch_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
std::string expected("{\"heroes\":[{\"hero\":\"Batman\",\"name\":\"Bruce Wayne\",\"super_power\":\"High-tech equipment and weapons\",\"enemy\":\"Joker\"},{\"hero\":\"Superman\",\"name\":\"Clark Kent\",\"super_power\":\"too many\",\"enemy\":\"Lex Luthor\",\"creation\":\"1933\"},{\"hero\":\"Flash\",\"name\":\"Bart Allen\",\"super_power\":\"fast\",\"enemy\":\"Zoom\",\"creation\":\"1940\"}],\"villains\":[{\"villain\":\"Joker\",\"name\":\"unknown\",\"super_power\":\"Genius-level intellect\",\"enemy\":\"Batman\",\"creation\":\"1940\"},{\"villain\":\"Mr. Freeze\",\"name\":\"Dr. Victor Fries\",\"super_power\":\"Sub-zero physiology\",\"enemy\":\"Batman\",\"creation\":\"1956\"}]}");
rapidjson::Document doc_obj;
rapidjson::Document doc_patch;
json_load(doc_obj, obj_str);
json_load(doc_patch, patch_str);
MsgPack obj(doc_obj);
MsgPack patch(doc_patch);
try {
apply_patch(patch, obj);
auto result = obj.to_string();
if (expected.compare(result) != 0) {
L_ERR("ERROR: Patch is not working.\nResult:\n{}\nExpected:\n{}", result, expected);
RETURN(1);
} else {
RETURN(0);
}
} catch (const BaseException& exc) {
L_EXC("ERROR: {}", exc.get_context());
RETURN(1);
}
}
int test_patcher_replace() {
INIT_LOG
std::string obj_str;
std::string filename(path_patcher_test + "object_to_patch.txt");
if (!read_file_contents(filename, &obj_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
std::string patch_str;
filename = path_patcher_test + "patch_replace.txt";
if (!read_file_contents(filename, &patch_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
std::string expected("{\"heroes\":[{\"hero\":\"Batman\",\"name\":\"Bruce Wayne\",\"super_power\":\"High-tech equipment and weapons\",\"enemy\":\"Riddler\",\"creation\":\"1939\"},{\"hero\":\"Superman\",\"name\":\"Clark Kent\",\"super_power\":\"too many\",\"enemy\":\"Lex Luthor\",\"creation\":\"1933\"},{\"hero\":\"Flash\",\"name\":\"Bart Allen\",\"super_power\":\"fast\",\"enemy\":\"Zoom\",\"creation\":\"1940\"}],\"villains\":[{\"villain\":\"Joker\",\"name\":\"unknown\",\"super_power\":\"Genius-level intellect\",\"enemy\":\"Batman\",\"creation\":\"1940\"},{\"villain\":\"Mr. Freeze\",\"name\":\"Dr. Victor Fries\",\"super_power\":\"Sub-zero physiology\",\"enemy\":\"Batman\",\"creation\":\"1956\"}]}");
rapidjson::Document doc_obj;
rapidjson::Document doc_patch;
json_load(doc_obj, obj_str);
json_load(doc_patch, patch_str);
MsgPack obj(doc_obj);
MsgPack patch(doc_patch);
try {
apply_patch(patch, obj);
auto result = obj.to_string();
if (expected.compare(result) != 0) {
L_ERR("ERROR: Patch is not working.\nResult:\n{}\nExpected:\n{}", result, expected);
RETURN(1);
} else {
RETURN(0);
}
} catch (const BaseException& exc) {
L_EXC("ERROR: {}", exc.get_context());
RETURN(1);
}
}
int test_patcher_move() {
INIT_LOG
std::string obj_str;
std::string filename(path_patcher_test + "object_to_patch.txt");
if (!read_file_contents(filename, &obj_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
std::string patch_str;
filename = path_patcher_test + "patch_move.txt";
if (!read_file_contents(filename, &patch_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
std::string expected("{\"heroes\":[{\"hero\":\"Batman\",\"name\":\"Bruce Wayne\",\"super_power\":\"High-tech equipment and weapons\",\"creation\":\"1939\"},{\"hero\":\"Superman\",\"name\":\"Clark Kent\",\"super_power\":\"too many\",\"enemy\":\"Joker\",\"creation\":\"1933\"},{\"hero\":\"Flash\",\"name\":\"Bart Allen\",\"super_power\":\"fast\",\"enemy\":\"Zoom\",\"creation\":\"1940\"}],\"villains\":[{\"villain\":\"Joker\",\"name\":\"unknown\",\"super_power\":\"Genius-level intellect\",\"enemy\":\"Batman\",\"creation\":\"1940\"},{\"villain\":\"Mr. Freeze\",\"name\":\"Dr. Victor Fries\",\"super_power\":\"Sub-zero physiology\",\"enemy\":\"Batman\",\"creation\":\"1956\"}]}");
rapidjson::Document doc_obj;
rapidjson::Document doc_patch;
json_load(doc_obj, obj_str);
json_load(doc_patch, patch_str);
MsgPack obj(doc_obj);
MsgPack patch(doc_patch);
try {
apply_patch(patch, obj);
auto result = obj.to_string();
if (expected.compare(result) != 0) {
L_ERR("ERROR: Patch is not working.\nResult:\n{}\nExpected:\n{}", result, expected);
RETURN(1);
} else {
RETURN(0);
}
} catch (const BaseException& exc) {
L_EXC("ERROR: {}", exc.get_context());
RETURN(1);
}
}
int test_patcher_copy() {
INIT_LOG
std::string obj_str;
std::string filename(path_patcher_test + "object_to_patch.txt");
if (!read_file_contents(filename, &obj_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
std::string patch_str;
filename = path_patcher_test + "patch_copy.txt";
if (!read_file_contents(filename, &patch_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
std::string expected("{\"heroes\":[{\"hero\":\"Batman\",\"name\":\"Bruce Wayne\",\"super_power\":\"High-tech equipment and weapons\",\"enemy\":\"Joker\",\"creation\":\"1939\"},{\"hero\":\"Superman\",\"name\":\"Clark Kent\",\"super_power\":\"too many\",\"enemy\":\"Lex Luthor\",\"creation\":\"1933\",\"other_enemy\":\"Joker\"},{\"hero\":\"Flash\",\"name\":\"Bart Allen\",\"super_power\":\"fast\",\"enemy\":\"Zoom\",\"creation\":\"1940\"}],\"villains\":[{\"villain\":\"Joker\",\"name\":\"unknown\",\"super_power\":\"Genius-level intellect\",\"enemy\":\"Batman\",\"creation\":\"1940\"},{\"villain\":\"Mr. Freeze\",\"name\":\"Dr. Victor Fries\",\"super_power\":\"Sub-zero physiology\",\"enemy\":\"Batman\",\"creation\":\"1956\"}]}");
rapidjson::Document doc_obj;
rapidjson::Document doc_patch;
json_load(doc_obj, obj_str);
json_load(doc_patch, patch_str);
MsgPack obj(doc_obj);
MsgPack patch(doc_patch);
try {
apply_patch(patch, obj);
auto result = obj.to_string();
if (expected.compare(result) != 0) {
L_ERR("ERROR: Patch is not working.\nResult:\n{}\nExpected:\n{}", result, expected);
RETURN(1);
} else {
RETURN(0);
}
} catch (const BaseException& exc) {
L_EXC("ERROR: {}", exc.get_context());
RETURN(1);
}
}
int test_patcher_test() {
INIT_LOG
std::string obj_str;
std::string filename(path_patcher_test + "object_to_patch.txt");
if (!read_file_contents(filename, &obj_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
std::string patch_str;
filename = path_patcher_test + "patch_test.txt";
if (!read_file_contents(filename, &patch_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
rapidjson::Document doc_obj;
rapidjson::Document doc_patch;
json_load(doc_obj, obj_str);
json_load(doc_patch, patch_str);
MsgPack obj(doc_obj);
MsgPack patch(doc_patch);
try {
apply_patch(patch, obj);
RETURN(0);
} catch (const BaseException& exc) {
L_EXC("ERROR: {}", exc.get_context());
RETURN(1);
}
}
int test_patcher_incr() {
INIT_LOG
std::string obj_str("{ \"age\" : 24 }");
std::string patch_str("[ { \"op\":\"incr\", \"path\":\"/age\", \"value\": \"1\", \"limit\": \"26\"} ]");
std::string expected("{\"age\":25}");
rapidjson::Document doc_obj;
rapidjson::Document doc_patch;
json_load(doc_obj, obj_str);
json_load(doc_patch, patch_str);
MsgPack obj(doc_obj);
MsgPack patch(doc_patch);
try {
apply_patch(patch, obj);
auto result = obj.to_string();
L_DEBUG("RESULT FOR TEST_INCR {}", result);
if (expected.compare(result) != 0) {
L_ERR("ERROR: Patch is not working.\nResult:\n{}\nExpected:\n{}", result, expected);
RETURN(1);
} else {
RETURN(0);
}
} catch (const BaseException& exc) {
L_EXC("ERROR: {}", exc.get_context());
RETURN(1);
}
}
int test_patcher_decr() {
INIT_LOG
std::string obj_str("{ \"age\" : 24 }");
std::string patch_str("[ { \"op\":\"decr\", \"path\":\"/age\", \"value\": 1, \"limit\": 22} ]");
std::string expected("{\"age\":23}");
rapidjson::Document doc_obj;
rapidjson::Document doc_patch;
json_load(doc_obj, obj_str);
json_load(doc_patch, patch_str);
MsgPack obj(doc_obj);
MsgPack patch(doc_patch);
try {
apply_patch(patch, obj);
auto result = obj.to_string();
if (expected.compare(result) != 0) {
L_ERR("ERROR: Patch is not working.\nResult:\n{}\nExpected:\n{}", result, expected);
RETURN(1);
} else {
RETURN(0);
}
} catch (const BaseException& exc) {
L_EXC("ERROR: {}", exc.get_context());
RETURN(1);
}
}
int test_patcher_rfc6901() {
INIT_LOG
std::string obj_str;
std::string filename(path_patcher_test + "rfc6901.txt");
if (!read_file_contents(filename, &obj_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
std::string patch_str;
filename = path_patcher_test + "patch_rfc6901.txt";
if (!read_file_contents(filename, &patch_str)) {
L_ERR("Can not read the file {}", filename);
RETURN(1);
}
rapidjson::Document doc_obj;
rapidjson::Document doc_patch;
json_load(doc_obj, obj_str);
json_load(doc_patch, patch_str);
MsgPack obj(doc_obj);
MsgPack patch(doc_patch);
try {
apply_patch(patch, obj);
RETURN(0);
} catch (const BaseException& exc) {
L_EXC("ERROR: {}", exc.get_context());
RETURN(1);
}
}
| 0 | 0.838623 | 1 | 0.838623 | game-dev | MEDIA | 0.76195 | game-dev | 0.940159 | 1 | 0.940159 |
EcsRx/ecsrx.unity | 3,910 | src/Assets/Plugins/UniRx/Scripts/Operators/Timer.cs | using System;
namespace UniRx.Operators
{
internal class TimerObservable : OperatorObservableBase<long>
{
readonly DateTimeOffset? dueTimeA;
readonly TimeSpan? dueTimeB;
readonly TimeSpan? period;
readonly IScheduler scheduler;
public TimerObservable(DateTimeOffset dueTime, TimeSpan? period, IScheduler scheduler)
: base(scheduler == Scheduler.CurrentThread)
{
this.dueTimeA = dueTime;
this.period = period;
this.scheduler = scheduler;
}
public TimerObservable(TimeSpan dueTime, TimeSpan? period, IScheduler scheduler)
: base(scheduler == Scheduler.CurrentThread)
{
this.dueTimeB = dueTime;
this.period = period;
this.scheduler = scheduler;
}
protected override IDisposable SubscribeCore(IObserver<long> observer, IDisposable cancel)
{
var timerObserver = new Timer(observer, cancel);
var dueTime = (dueTimeA != null)
? dueTimeA.Value - scheduler.Now
: dueTimeB.Value;
// one-shot
if (period == null)
{
return scheduler.Schedule(Scheduler.Normalize(dueTime), () =>
{
timerObserver.OnNext();
timerObserver.OnCompleted();
});
}
else
{
var periodicScheduler = scheduler as ISchedulerPeriodic;
if (periodicScheduler != null)
{
if (dueTime == period.Value)
{
// same(Observable.Interval), run periodic
return periodicScheduler.SchedulePeriodic(Scheduler.Normalize(dueTime), timerObserver.OnNext);
}
else
{
// Schedule Once + Scheudle Periodic
var disposable = new SerialDisposable();
disposable.Disposable = scheduler.Schedule(Scheduler.Normalize(dueTime), () =>
{
timerObserver.OnNext(); // run first
var timeP = Scheduler.Normalize(period.Value);
disposable.Disposable = periodicScheduler.SchedulePeriodic(timeP, timerObserver.OnNext); // run periodic
});
return disposable;
}
}
else
{
var timeP = Scheduler.Normalize(period.Value);
return scheduler.Schedule(Scheduler.Normalize(dueTime), self =>
{
timerObserver.OnNext();
self(timeP);
});
}
}
}
class Timer : OperatorObserverBase<long, long>
{
long index = 0;
public Timer(IObserver<long> observer, IDisposable cancel)
: base(observer, cancel)
{
}
public void OnNext()
{
try
{
base.observer.OnNext(index++);
}
catch
{
Dispose();
throw;
}
}
public override void OnNext(long value)
{
// no use.
}
public override void OnError(Exception error)
{
try { observer.OnError(error); }
finally { Dispose(); }
}
public override void OnCompleted()
{
try { observer.OnCompleted(); }
finally { Dispose(); }
}
}
}
} | 0 | 0.909159 | 1 | 0.909159 | game-dev | MEDIA | 0.359527 | game-dev | 0.949248 | 1 | 0.949248 |
stubma/cocos2dx-classical | 6,567 | external/Box2D/Dynamics/Joints/b2RevoluteJoint.h | /*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_REVOLUTE_JOINT_H
#define B2_REVOLUTE_JOINT_H
#include <Box2D/Dynamics/Joints/b2Joint.h>
/// Revolute joint definition. This requires defining an
/// anchor point where the bodies are joined. The definition
/// uses local anchor points so that the initial configuration
/// can violate the constraint slightly. You also need to
/// specify the initial relative angle for joint limits. This
/// helps when saving and loading a game.
/// The local anchor points are measured from the body's origin
/// rather than the center of mass because:
/// 1. you might not know where the center of mass will be.
/// 2. if you add/remove shapes from a body and recompute the mass,
/// the joints will be broken.
struct b2RevoluteJointDef : public b2JointDef
{
b2RevoluteJointDef()
{
type = e_revoluteJoint;
localAnchorA.Set(0.0f, 0.0f);
localAnchorB.Set(0.0f, 0.0f);
referenceAngle = 0.0f;
lowerAngle = 0.0f;
upperAngle = 0.0f;
maxMotorTorque = 0.0f;
motorSpeed = 0.0f;
enableLimit = false;
enableMotor = false;
}
/// Initialize the bodies, anchors, and reference angle using a world
/// anchor point.
void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor);
/// The local anchor point relative to bodyA's origin.
b2Vec2 localAnchorA;
/// The local anchor point relative to bodyB's origin.
b2Vec2 localAnchorB;
/// The bodyB angle minus bodyA angle in the reference state (radians).
float32 referenceAngle;
/// A flag to enable joint limits.
bool enableLimit;
/// The lower angle for the joint limit (radians).
float32 lowerAngle;
/// The upper angle for the joint limit (radians).
float32 upperAngle;
/// A flag to enable the joint motor.
bool enableMotor;
/// The desired motor speed. Usually in radians per second.
float32 motorSpeed;
/// The maximum motor torque used to achieve the desired motor speed.
/// Usually in N-m.
float32 maxMotorTorque;
};
/// A revolute joint constrains two bodies to share a common point while they
/// are free to rotate about the point. The relative rotation about the shared
/// point is the joint angle. You can limit the relative rotation with
/// a joint limit that specifies a lower and upper angle. You can use a motor
/// to drive the relative rotation about the shared point. A maximum motor torque
/// is provided so that infinite forces are not generated.
class b2RevoluteJoint : public b2Joint
{
public:
b2Vec2 GetAnchorA() const;
b2Vec2 GetAnchorB() const;
/// The local anchor point relative to bodyA's origin.
const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
/// The local anchor point relative to bodyB's origin.
const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
/// Get the reference angle.
float32 GetReferenceAngle() const { return m_referenceAngle; }
/// Get the current joint angle in radians.
float32 GetJointAngle() const;
/// Get the current joint angle speed in radians per second.
float32 GetJointSpeed() const;
/// Is the joint limit enabled?
bool IsLimitEnabled() const;
/// Enable/disable the joint limit.
void EnableLimit(bool flag);
/// Get the lower joint limit in radians.
float32 GetLowerLimit() const;
/// Get the upper joint limit in radians.
float32 GetUpperLimit() const;
/// Set the joint limits in radians.
void SetLimits(float32 lower, float32 upper);
/// Is the joint motor enabled?
bool IsMotorEnabled() const;
/// Enable/disable the joint motor.
void EnableMotor(bool flag);
/// Set the motor speed in radians per second.
void SetMotorSpeed(float32 speed);
/// Get the motor speed in radians per second.
float32 GetMotorSpeed() const;
/// Set the maximum motor torque, usually in N-m.
void SetMaxMotorTorque(float32 torque);
float32 GetMaxMotorTorque() const { return m_maxMotorTorque; }
/// Get the reaction force given the inverse time step.
/// Unit is N.
b2Vec2 GetReactionForce(float32 inv_dt) const;
/// Get the reaction torque due to the joint limit given the inverse time step.
/// Unit is N*m.
float32 GetReactionTorque(float32 inv_dt) const;
/// Get the current motor torque given the inverse time step.
/// Unit is N*m.
float32 GetMotorTorque(float32 inv_dt) const;
/// Dump to b2Log.
void Dump();
protected:
friend class b2Joint;
friend class b2GearJoint;
b2RevoluteJoint(const b2RevoluteJointDef* def);
void InitVelocityConstraints(const b2SolverData& data);
void SolveVelocityConstraints(const b2SolverData& data);
bool SolvePositionConstraints(const b2SolverData& data);
// Solver shared
b2Vec2 m_localAnchorA;
b2Vec2 m_localAnchorB;
b2Vec3 m_impulse;
float32 m_motorImpulse;
bool m_enableMotor;
float32 m_maxMotorTorque;
float32 m_motorSpeed;
bool m_enableLimit;
float32 m_referenceAngle;
float32 m_lowerAngle;
float32 m_upperAngle;
// Solver temp
int32 m_indexA;
int32 m_indexB;
b2Vec2 m_rA;
b2Vec2 m_rB;
b2Vec2 m_localCenterA;
b2Vec2 m_localCenterB;
float32 m_invMassA;
float32 m_invMassB;
float32 m_invIA;
float32 m_invIB;
b2Mat33 m_mass; // effective mass for point-to-point constraint.
float32 m_motorMass; // effective mass for motor/limit angular constraint.
b2LimitState m_limitState;
};
inline float32 b2RevoluteJoint::GetMotorSpeed() const
{
return m_motorSpeed;
}
#endif
| 0 | 0.832368 | 1 | 0.832368 | game-dev | MEDIA | 0.959659 | game-dev | 0.79875 | 1 | 0.79875 |
beyond-aion/aion-server | 4,234 | game-server/data/handlers/quest/pandaemonium/_2912FollowtheRibbon.java | package quest.pandaemonium;
import static com.aionemu.gameserver.model.DialogAction.*;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.serverpackets.SM_DIALOG_WINDOW;
import com.aionemu.gameserver.questEngine.handlers.AbstractQuestHandler;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.questEngine.model.QuestState;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
import com.aionemu.gameserver.utils.PacketSendUtility;
/**
* @author Altaress, Mcrizza
*/
public class _2912FollowtheRibbon extends AbstractQuestHandler {
public _2912FollowtheRibbon() {
super(2912);
}
@Override
public void register() {
qe.registerQuestNpc(204193).addOnQuestStart(questId);
qe.registerQuestNpc(204193).addOnTalkEvent(questId);
qe.registerQuestNpc(204089).addOnTalkEvent(questId);
qe.registerQuestNpc(204088).addOnTalkEvent(questId);
qe.registerQuestNpc(204240).addOnTalkEvent(questId);
qe.registerQuestNpc(204236).addOnTalkEvent(questId);
}
@Override
public boolean onDialogEvent(QuestEnv env) {
final Player player = env.getPlayer();
int targetId = 0;
if (env.getVisibleObject() instanceof Npc)
targetId = ((Npc) env.getVisibleObject()).getNpcId();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (targetId == 204193) {
if (qs == null || qs.isStartable()) {
if (env.getDialogActionId() == QUEST_SELECT)
return sendQuestDialog(env, 1011);
else
return sendQuestStartDialog(env);
} else if (qs.getStatus() == QuestStatus.START) {
if (env.getDialogActionId() == QUEST_SELECT)
return sendQuestDialog(env, 2375);
else if (env.getDialogActionId() == SELECT_QUEST_REWARD) {
qs.setStatus(QuestStatus.REWARD);
updateQuestStatus(env);
PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject().getObjectId(), 10));
return true;
} else
return sendQuestEndDialog(env);
} else if (qs.getStatus() == QuestStatus.REWARD) {
return sendQuestEndDialog(env);
}
} else if (targetId == 204089) {
if (qs != null && qs.getStatus() == QuestStatus.START && qs.getQuestVarById(0) == 0) {
if (env.getDialogActionId() == QUEST_SELECT)
return sendQuestDialog(env, 1352);
else if (env.getDialogActionId() == SETPRO1) {
qs.setQuestVarById(0, qs.getQuestVarById(0) + 1);
updateQuestStatus(env);
PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject().getObjectId(), 10));
return true;
} else
return sendQuestStartDialog(env);
}
} else if (targetId == 204088) {
if (qs != null && qs.getStatus() == QuestStatus.START && qs.getQuestVarById(0) == 1) {
if (env.getDialogActionId() == QUEST_SELECT)
return sendQuestDialog(env, 2034);
else if (env.getDialogActionId() == SETPRO3) {
qs.setQuestVarById(0, qs.getQuestVarById(0) + 1);
updateQuestStatus(env);
PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject().getObjectId(), 10));
return true;
} else
return sendQuestStartDialog(env);
}
} else if (targetId == 204240) {
if (qs != null && qs.getStatus() == QuestStatus.START && qs.getQuestVarById(0) == 2) {
if (env.getDialogActionId() == QUEST_SELECT)
return sendQuestDialog(env, 1693);
else if (env.getDialogActionId() == SETPRO2) {
qs.setQuestVarById(0, qs.getQuestVarById(0) + 1);
updateQuestStatus(env);
PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject().getObjectId(), 10));
return true;
} else
return sendQuestStartDialog(env);
}
} else if (targetId == 204236) {
if (qs != null) {
if (env.getDialogActionId() == QUEST_SELECT && qs.getStatus() == QuestStatus.START)
return sendQuestDialog(env, 2375);
else if (env.getDialogActionId() == SELECT_QUEST_REWARD && qs.getStatus() != QuestStatus.COMPLETE) {
qs.setQuestVar(3);
qs.setStatus(QuestStatus.REWARD);
updateQuestStatus(env);
return sendQuestEndDialog(env);
} else
return sendQuestEndDialog(env);
}
}
return false;
}
}
| 0 | 0.840118 | 1 | 0.840118 | game-dev | MEDIA | 0.924955 | game-dev | 0.924233 | 1 | 0.924233 |
HalfdanJ/ofxFaceTracker2 | 7,567 | libs/dlib/include/dlib/map/map_kernel_c.h | // Copyright (C) 2003 Davis E. King (davis@dlib.net)
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_MAP_KERNEl_C_
#define DLIB_MAP_KERNEl_C_
#include "map_kernel_abstract.h"
#include "../algs.h"
#include "../assert.h"
#include "../interfaces/map_pair.h"
namespace dlib
{
template <
typename map_base
>
class map_kernel_c : public map_base
{
typedef typename map_base::domain_type domain;
typedef typename map_base::range_type range;
public:
void add (
domain& d,
range& r
);
void remove_any (
domain& d,
range& r
);
void remove (
const domain& d,
domain& d_copy,
range& r
);
void destroy (
const domain& d
);
range& operator[] (
const domain& d
);
const range& operator[] (
const domain& d
) const;
const map_pair<domain,range>& element (
) const
{
// make sure requires clause is not broken
DLIB_CASSERT(this->current_element_valid() == true,
"\tconst map_pair<domain,range>& map::element"
<< "\n\tyou can't access the current element if it doesn't exist"
<< "\n\tthis: " << this
);
// call the real function
return map_base::element();
}
map_pair<domain,range>& element (
)
{
// make sure requires clause is not broken
DLIB_CASSERT(this->current_element_valid() == true,
"\tmap_pair<domain,range>& map::element"
<< "\n\tyou can't access the current element if it doesn't exist"
<< "\n\tthis: " << this
);
// call the real function
return map_base::element();
}
};
template <
typename map_base
>
inline void swap (
map_kernel_c<map_base>& a,
map_kernel_c<map_base>& b
) { a.swap(b); }
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// member function definitions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
template <
typename map_base
>
void map_kernel_c<map_base>::
add (
domain& d,
range& r
)
{
// make sure requires clause is not broken
DLIB_CASSERT( (!this->is_in_domain(d)) &&
(static_cast<void*>(&d) != static_cast<void*>(&r)),
"\tvoid map::add"
<< "\n\tdomain element being added must not already be in the map"
<< "\n\tand d and r must not be the same variable"
<< "\n\tis_in_domain(d): " << (this->is_in_domain(d) ? "true" : "false")
<< "\n\tthis: " << this
<< "\n\t&d: " << static_cast<void*>(&d)
<< "\n\t&r: " << static_cast<void*>(&r)
);
// call the real function
map_base::add(d,r);
}
// ----------------------------------------------------------------------------------------
template <
typename map_base
>
void map_kernel_c<map_base>::
remove_any (
domain& d,
range& r
)
{
// make sure requires clause is not broken
DLIB_CASSERT( (this->size() > 0) &&
(static_cast<void*>(&d) != static_cast<void*>(&r)),
"\tvoid map::remove_any"
<< "\n\tsize() must be greater than zero if something is going to be removed"
<< "\n\tand d and r must not be the same variable."
<< "\n\tsize(): " << this->size()
<< "\n\tthis: " << this
<< "\n\t&d: " << static_cast<void*>(&d)
<< "\n\t&r: " << static_cast<void*>(&r)
);
// call the real function
map_base::remove_any(d,r);
}
// ----------------------------------------------------------------------------------------
template <
typename map_base
>
void map_kernel_c<map_base>::
remove (
const domain& d,
domain& d_copy,
range& r
)
{
// make sure requires clause is not broken
DLIB_CASSERT( (this->is_in_domain(d)) &&
(static_cast<const void*>(&d) != static_cast<void*>(&r)) &&
(static_cast<void*>(&r) != static_cast<void*>(&d_copy)) &&
(static_cast<const void*>(&d) != static_cast<void*>(&d_copy)),
"\tvoid map::remove"
<< "\n\tcan't remove something that isn't in the map or if the paremeters actually"
<< "\n\tare the same variable. Either way can't remove."
<< "\n\tis_in_domain(d): " << (this->is_in_domain(d) ? "true" : "false")
<< "\n\tthis: " << this
<< "\n\t&d: " << static_cast<const void*>(&d)
<< "\n\t&r: " << static_cast<void*>(&r)
<< "\n\t&d_copy: " << static_cast<void*>(&d_copy)
);
// call the real function
map_base::remove(d,d_copy,r);
}
// ----------------------------------------------------------------------------------------
template <
typename map_base
>
void map_kernel_c<map_base>::
destroy (
const domain& d
)
{
// make sure requires clause is not broken
DLIB_CASSERT(this->is_in_domain(d),
"\tvoid map::destroy"
<< "\n\tcan't remove something that isn't in the map"
<< "\n\tthis: " << this
<< "\n\t&d: " << static_cast<const void*>(&d)
);
// call the real function
map_base::destroy(d);
}
// ----------------------------------------------------------------------------------------
template <
typename map_base
>
typename map_base::range_type& map_kernel_c<map_base>::
operator[] (
const domain& d
)
{
// make sure requires clause is not broken
DLIB_CASSERT( this->is_in_domain(d),
"\trange& map::operator[]"
<< "\n\td must be in the domain of the map"
<< "\n\tthis: " << this
);
// call the real function
return map_base::operator[](d);
}
// ----------------------------------------------------------------------------------------
template <
typename map_base
>
const typename map_base::range_type& map_kernel_c<map_base>::
operator[] (
const domain& d
) const
{
// make sure requires clause is not broken
DLIB_CASSERT( this->is_in_domain(d),
"\tconst range& map::operator[]"
<< "\n\td must be in the domain of the map"
<< "\n\tthis: " << this
);
// call the real function
return map_base::operator[](d);
}
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_MAP_KERNEl_C_
| 0 | 0.948778 | 1 | 0.948778 | game-dev | MEDIA | 0.679667 | game-dev | 0.916353 | 1 | 0.916353 |
arhamgarg/DSA | 1,469 | data-structures/non-linear/priority-queue/PriorityQueue.ts | import { MaxHeap } from "../binary-tree/heap/max-heap/MaxHeap";
import { MinHeap } from "../binary-tree/heap/min-heap/MinHeap";
class PriorityQueue {
private isMinQueue: boolean;
private minHeap: MinHeap;
private maxHeap: MaxHeap;
constructor(type: boolean = true) {
this.isMinQueue = type;
}
//Naming issues
public isMinimumQueue(): boolean {
return this.isMinQueue;
}
public insertItem(key: number): void {
if (this.isMinQueue) {
this.minHeap.insert(key);
return;
}
this.maxHeap.insert(key);
}
public removeTop(): number {
if (this.isMinQueue) {
return this.minHeap.extractMin();
}
return this.maxHeap.extractMax();
}
public topKey(): number {
if (this.isMinQueue) {
return this.minHeap.getMin();
}
return this.maxHeap.getMax();
}
public buildHeap(heapArray: Array<number>): void {
if (this.isMinQueue) {
this.minHeap.buildHeap(heapArray);
return;
}
this.maxHeap.buildHeap(heapArray);
}
public printHeap(): void {
if (this.isMinQueue) {
this.minHeap.printHeap();
return;
}
this.maxHeap.printHeap();
}
public isEmpty(): boolean {
if (this.isMinQueue) {
return this.minHeap.isEmpty();
}
return this.maxHeap.isEmpty();
}
public size(): number {
if (this.isMinQueue) {
return this.minHeap.size();
}
return this.maxHeap.size();
}
}
export { PriorityQueue };
| 0 | 0.718067 | 1 | 0.718067 | game-dev | MEDIA | 0.32016 | game-dev | 0.692479 | 1 | 0.692479 |
Eaglercraft-Archive/EaglercraftX-1.8-workspace | 1,784 | src/game/java/net/minecraft/block/state/IBlockState.java | package net.minecraft.block.state;
import java.util.Collection;
import com.google.common.collect.ImmutableMap;
import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty;
/**+
* This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code.
*
* Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!"
* Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team
*
* EaglercraftX 1.8 patch files (c) 2022-2025 lax1dude, ayunami2000. All Rights Reserved.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
public interface IBlockState {
/**+
* Get the names of all properties defined for this BlockState
*/
Collection<IProperty> getPropertyNames();
<T extends Comparable<T>> T getValue(IProperty<T> var1);
<T extends Comparable<T>, V extends T> IBlockState withProperty(IProperty<T> var1, V var2);
<T extends Comparable<T>> IBlockState cycleProperty(IProperty<T> var1);
ImmutableMap<IProperty, Comparable> getProperties();
Block getBlock();
} | 0 | 0.722014 | 1 | 0.722014 | game-dev | MEDIA | 0.990111 | game-dev | 0.515338 | 1 | 0.515338 |
Um-Mitternacht/Bewitchment | 1,911 | src/main/java/com/bewitchment/common/world/gen/structures/WorldGenCambionHomeMedium.java | package com.bewitchment.common.world.gen.structures;
import com.bewitchment.Bewitchment;
import com.bewitchment.common.world.gen.ModWorldGen;
import net.minecraft.block.state.IBlockState;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.Mirror;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.gen.feature.WorldGenerator;
import net.minecraft.world.gen.structure.template.PlacementSettings;
import net.minecraft.world.gen.structure.template.Template;
import net.minecraft.world.gen.structure.template.TemplateManager;
import java.util.Random;
public class WorldGenCambionHomeMedium extends WorldGenerator {
public WorldGenCambionHomeMedium() {
super();
}
@Override
public boolean generate(World worldIn, Random rand, BlockPos position) {
WorldServer worldServer = (WorldServer) worldIn;
MinecraftServer minecraftServer = worldIn.getMinecraftServer();
TemplateManager templateManager = worldServer.getStructureTemplateManager();
Template template = templateManager.getTemplate(minecraftServer, new ResourceLocation(Bewitchment.MODID + ":cambionmedium1"));
if (ModWorldGen.canSpawnHere(template, worldServer, position)) {
IBlockState iBlockState = worldIn.getBlockState(position);
worldIn.notifyBlockUpdate(position, iBlockState, iBlockState, 3);
PlacementSettings placementsettings = (new PlacementSettings()).setMirror(Mirror.NONE).setRotation(Rotation.NONE).setIgnoreEntities(false).setChunk(null).setReplacedBlock(null).setIgnoreStructureBlock(false);
template.addBlocksToWorld(worldIn, position.add(0, 0, 0), placementsettings);
return true;
}
return false;
}
}
| 0 | 0.595765 | 1 | 0.595765 | game-dev | MEDIA | 0.992766 | game-dev | 0.516028 | 1 | 0.516028 |
wasabirobby/wasabi_fishing | 2,795 | bridge/qb/server.lua | if GetResourceState('qb-core') ~= 'started' then return end
QBCore = exports['qb-core']:GetCoreObject()
Framework = 'qb'
function GetPlayer(source)
return QBCore.Functions.GetPlayer(source)
end
function KickPlayer(source, reason)
QBCore.Functions.Kick(source, reason, true, true)
end
function HasGroup(source, filter)
local groups = { 'job', 'gang' }
local player = GetPlayer(source)
local type = type(filter)
if type == 'string' then
for i = 1, #groups do
local data = player.PlayerData[groups[i]]
if data.name == filter then
return data.name, data.grade.level
end
end
else
local tabletype = table.type(filter)
if tabletype == 'hash' then
for i = 1, #groups do
local data = player.PlayerData[groups[i]]
local grade = filter[data.name]
if grade and grade <= data.grade.level then
return data.name, data.grade.level
end
end
elseif tabletype == 'array' then
for i = 1, #filter do
local group = filter[i]
for j = 1, #groups do
local data = player.PlayerData[groups[j]]
if data.name == group then
return data.name, data.grade.level
end
end
end
end
end
end
function GetIdentifier(source)
local xPlayer = QBCore.Functions.GetPlayer(source)
return xPlayer.PlayerData.citizenid
end
function GetName(source)
local xPlayer = QBCore.Functions.GetPlayer(source)
return xPlayer.PlayerData.charinfo.firstname..' '..xPlayer.PlayerData.charinfo.lastname
end
function RegisterUsableItem(item, cb)
QBCore.Functions.CreateUseableItem(item, cb)
end
function HasItem(source, item)
local player = GetPlayer(source)
local item = player.Functions.GetItemByName(item)
if GetResourceState('ox_inventory') == 'started' then
return item?.count or 0
else
return item?.amount or 0
end
end
function AddItem(source, item, count, slot, metadata)
local player = GetPlayer(source)
return player.Functions.AddItem(item, count, slot, metadata)
end
function RemoveItem(source, item, count, slot, metadata)
local player = GetPlayer(source)
player.Functions.RemoveItem(item, count, slot, metadata)
end
function AddMoney(source, type, amount)
if type == 'money' then type = 'cash' end
local player = GetPlayer(source)
player.Functions.AddMoney(type, amount)
end
function RemoveMoney(source, type, amount)
if type == 'money' then type = 'cash' end
local player = GetPlayer(source)
player.Functions.RemoveMoney(type, amount)
end
| 0 | 0.510624 | 1 | 0.510624 | game-dev | MEDIA | 0.693577 | game-dev | 0.859228 | 1 | 0.859228 |
PickleModifications/pickle_prisons | 2,370 | bridge/esx/client.lua | if GetResourceState('es_extended') ~= 'started' then return end
ESX = exports.es_extended:getSharedObject()
function ShowNotification(text)
ESX.ShowNotification(text)
end
function ServerCallback(name, cb, ...)
ESX.TriggerServerCallback(name, cb, ...)
end
function GetPlayersInArea(coords, radius)
local coords = coords or GetEntityCoords(PlayerPedId())
local radius = radius or 3.0
local list = ESX.Game.GetPlayersInArea(coords, radius)
local players = {}
for _, player in pairs(list) do
if player ~= PlayerId() then
players[#players + 1] = player
end
end
return players
end
RegisterNetEvent(GetCurrentResourceName()..":showNotification", function(text)
ShowNotification(text)
end)
RegisterNetEvent('esx:playerLoaded')
AddEventHandler('esx:playerLoaded',function(xPlayer, isNew, skin)
TriggerServerEvent("pickle_prisons:initializePlayer")
end)
local alreadySpawned = false
RegisterNetEvent('esx:onPlayerDeath', function()
CheckBreakout = false
end)
RegisterNetEvent('esx:onPlayerSpawn', function()
if not alreadySpawned then -- Prevents TP to hospital on-load.
alreadySpawned = true
return
end
TeleportHospital()
CheckBreakout = true
end)
function ToggleOutfit(inPrison)
if inPrison then
local prison = Config.Prisons[Prison.index]
local outfits = prison.outfit or Config.Default.outfit
ESX.TriggerServerCallback('esx_skin:getPlayerSkin', function(skin, jobSkin)
local gender = skin.sex
local outfit = gender == 1 and outfits.female or outfits.male
if not outfit then return end
TriggerEvent('skinchanger:loadClothes', skin, outfit)
end)
else
ESX.TriggerServerCallback('esx_skin:getPlayerSkin', function(skin, jobSkin)
TriggerEvent('skinchanger:loadSkin', skin)
TriggerEvent('esx:restoreLoadout')
end)
end
end
-- Inventory Fallback
CreateThread(function()
Wait(100)
if InitializeInventory then return InitializeInventory() end -- Already loaded through inventory folder.
Inventory = {}
Inventory.Items = {}
Inventory.Ready = false
RegisterNetEvent("pickle_prisons:setupInventory", function(data)
Inventory.Items = data.items
Inventory.Ready = true
end)
end) | 0 | 0.912028 | 1 | 0.912028 | game-dev | MEDIA | 0.722933 | game-dev | 0.742321 | 1 | 0.742321 |
kmatheussen/radium | 5,951 | pluginhost/JuceLibraryCode/modules/juce_box2d/box2d/Dynamics/Joints/b2WheelJoint.h | /*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_WHEEL_JOINT_H
#define B2_WHEEL_JOINT_H
#include "b2Joint.h"
/// Wheel joint definition. This requires defining a line of
/// motion using an axis and an anchor point. The definition uses local
/// anchor points and a local axis so that the initial configuration
/// can violate the constraint slightly. The joint translation is zero
/// when the local anchor points coincide in world space. Using local
/// anchors and a local axis helps when saving and loading a game.
struct b2WheelJointDef : public b2JointDef
{
b2WheelJointDef()
{
type = e_wheelJoint;
localAnchorA.SetZero();
localAnchorB.SetZero();
localAxisA.Set(1.0f, 0.0f);
enableMotor = false;
maxMotorTorque = 0.0f;
motorSpeed = 0.0f;
frequencyHz = 2.0f;
dampingRatio = 0.7f;
}
/// Initialize the bodies, anchors, axis, and reference angle using the world
/// anchor and world axis.
void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis);
/// The local anchor point relative to bodyA's origin.
b2Vec2 localAnchorA;
/// The local anchor point relative to bodyB's origin.
b2Vec2 localAnchorB;
/// The local translation axis in bodyA.
b2Vec2 localAxisA;
/// Enable/disable the joint motor.
bool enableMotor;
/// The maximum motor torque, usually in N-m.
float32 maxMotorTorque;
/// The desired motor speed in radians per second.
float32 motorSpeed;
/// Suspension frequency, zero indicates no suspension
float32 frequencyHz;
/// Suspension damping ratio, one indicates critical damping
float32 dampingRatio;
};
/// A wheel joint. This joint provides two degrees of freedom: translation
/// along an axis fixed in bodyA and rotation in the plane. You can use a
/// joint limit to restrict the range of motion and a joint motor to drive
/// the rotation or to model rotational friction.
/// This joint is designed for vehicle suspensions.
class b2WheelJoint : public b2Joint
{
public:
void GetDefinition(b2WheelJointDef* def) const;
b2Vec2 GetAnchorA() const;
b2Vec2 GetAnchorB() const;
b2Vec2 GetReactionForce(float32 inv_dt) const;
float32 GetReactionTorque(float32 inv_dt) const;
/// The local anchor point relative to bodyA's origin.
const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
/// The local anchor point relative to bodyB's origin.
const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
/// The local joint axis relative to bodyA.
const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; }
/// Get the current joint translation, usually in meters.
float32 GetJointTranslation() const;
/// Get the current joint translation speed, usually in meters per second.
float32 GetJointSpeed() const;
/// Is the joint motor enabled?
bool IsMotorEnabled() const;
/// Enable/disable the joint motor.
void EnableMotor(bool flag);
/// Set the motor speed, usually in radians per second.
void SetMotorSpeed(float32 speed);
/// Get the motor speed, usually in radians per second.
float32 GetMotorSpeed() const;
/// Set/Get the maximum motor force, usually in N-m.
void SetMaxMotorTorque(float32 torque);
float32 GetMaxMotorTorque() const;
/// Get the current motor torque given the inverse time step, usually in N-m.
float32 GetMotorTorque(float32 inv_dt) const;
/// Set/Get the spring frequency in hertz. Setting the frequency to zero disables the spring.
void SetSpringFrequencyHz(float32 hz);
float32 GetSpringFrequencyHz() const;
/// Set/Get the spring damping ratio
void SetSpringDampingRatio(float32 ratio);
float32 GetSpringDampingRatio() const;
/// Dump to b2Log
void Dump();
protected:
friend class b2Joint;
b2WheelJoint(const b2WheelJointDef* def);
void InitVelocityConstraints(const b2SolverData& data);
void SolveVelocityConstraints(const b2SolverData& data);
bool SolvePositionConstraints(const b2SolverData& data);
float32 m_frequencyHz;
float32 m_dampingRatio;
// Solver shared
b2Vec2 m_localAnchorA;
b2Vec2 m_localAnchorB;
b2Vec2 m_localXAxisA;
b2Vec2 m_localYAxisA;
float32 m_impulse;
float32 m_motorImpulse;
float32 m_springImpulse;
float32 m_maxMotorTorque;
float32 m_motorSpeed;
bool m_enableMotor;
// Solver temp
juce::int32 m_indexA;
juce::int32 m_indexB;
b2Vec2 m_localCenterA;
b2Vec2 m_localCenterB;
float32 m_invMassA;
float32 m_invMassB;
float32 m_invIA;
float32 m_invIB;
b2Vec2 m_ax, m_ay;
float32 m_sAx, m_sBx;
float32 m_sAy, m_sBy;
float32 m_mass;
float32 m_motorMass;
float32 m_springMass;
float32 m_bias;
float32 m_gamma;
};
inline float32 b2WheelJoint::GetMotorSpeed() const
{
return m_motorSpeed;
}
inline float32 b2WheelJoint::GetMaxMotorTorque() const
{
return m_maxMotorTorque;
}
inline void b2WheelJoint::SetSpringFrequencyHz(float32 hz)
{
m_frequencyHz = hz;
}
inline float32 b2WheelJoint::GetSpringFrequencyHz() const
{
return m_frequencyHz;
}
inline void b2WheelJoint::SetSpringDampingRatio(float32 ratio)
{
m_dampingRatio = ratio;
}
inline float32 b2WheelJoint::GetSpringDampingRatio() const
{
return m_dampingRatio;
}
#endif
| 0 | 0.92013 | 1 | 0.92013 | game-dev | MEDIA | 0.891691 | game-dev | 0.862941 | 1 | 0.862941 |
MoonZoon/MoonZoon | 3,297 | crates/zoon/src/element/paragraph.rs | use crate::*;
use std::marker::PhantomData;
// ------ ------
// Element
// ------ ------
make_flags!(Empty);
pub struct Paragraph<EmptyFlag, RE: RawEl> {
raw_el: RE,
flags: PhantomData<EmptyFlag>,
}
impl<RE: RawEl> Element for Paragraph<EmptyFlagNotSet, RE> {}
impl Paragraph<EmptyFlagSet, RawHtmlEl<web_sys::HtmlElement>> {
pub fn new() -> Self {
Self::with_tag(Tag::Custom("p"))
}
}
impl<EmptyFlag, RE: RawEl> RawElWrapper for Paragraph<EmptyFlag, RE> {
type RawEl = RE;
fn raw_el_mut(&mut self) -> &mut Self::RawEl {
&mut self.raw_el
}
}
// ------ ------
// Abilities
// ------ ------
impl ChoosableTag for Paragraph<EmptyFlagSet, RawHtmlEl<web_sys::HtmlElement>> {
#[track_caller]
fn with_tag(tag: Tag) -> Self {
run_once!(|| {
global_styles()
.style_group(StyleGroup::new(".paragraph > *").style_important("display", "inline"))
.style_group(StyleGroup::new(".paragraph > .align_left").style("float", "left"))
.style_group(StyleGroup::new(".paragraph > .align_right").style("float", "right"));
});
Self {
raw_el: RawHtmlEl::new(tag.as_str()).class("paragraph"),
flags: PhantomData,
}
}
}
impl<EmptyFlag, RE: RawEl> Styleable<'_> for Paragraph<EmptyFlag, RE> {}
impl<EmptyFlag, RE: RawEl> KeyboardEventAware for Paragraph<EmptyFlag, RE> {}
impl<EmptyFlag, RE: RawEl> MouseEventAware for Paragraph<EmptyFlag, RE> {}
impl<EmptyFlag, RE: RawEl> PointerEventAware for Paragraph<EmptyFlag, RE> {}
impl<EmptyFlag, RE: RawEl> TouchEventAware for Paragraph<EmptyFlag, RE> {}
impl<EmptyFlag, RE: RawEl> MutableViewport for Paragraph<EmptyFlag, RE> {}
impl<EmptyFlag, RE: RawEl> AddNearbyElement<'_> for Paragraph<EmptyFlag, RE> {}
impl<EmptyFlag, RE: RawEl> HasIds for Paragraph<EmptyFlag, RE> {}
impl<EmptyFlag, RE: RawEl> HasLang for Paragraph<EmptyFlag, RE> {}
impl<EmptyFlag, RE: RawEl> SelectableTextContent for Paragraph<EmptyFlag, RE> {}
// ------ ------
// Attributes
// ------ ------
impl<'a, EmptyFlag, RE: RawEl> Paragraph<EmptyFlag, RE> {
pub fn content(
mut self,
content: impl IntoOptionElement<'a> + 'a,
) -> Paragraph<EmptyFlagNotSet, RE> {
self.raw_el = self.raw_el.child(content);
self.into_type()
}
pub fn content_signal(
mut self,
content: impl Signal<Item = impl IntoOptionElement<'a>> + Unpin + 'static,
) -> Paragraph<EmptyFlagNotSet, RE> {
self.raw_el = self.raw_el.child_signal(content);
self.into_type()
}
pub fn contents(
mut self,
contents: impl IntoIterator<Item = impl IntoOptionElement<'a> + 'a>,
) -> Paragraph<EmptyFlagNotSet, RE> {
self.raw_el = self.raw_el.children(contents);
self.into_type()
}
pub fn contents_signal_vec(
mut self,
contents: impl SignalVec<Item = impl IntoOptionElement<'a>> + Unpin + 'static,
) -> Paragraph<EmptyFlagNotSet, RE> {
self.raw_el = self.raw_el.children_signal_vec(contents);
self.into_type()
}
fn into_type<NewEmptyFlag>(self) -> Paragraph<NewEmptyFlag, RE> {
Paragraph {
raw_el: self.raw_el,
flags: PhantomData,
}
}
}
| 0 | 0.910889 | 1 | 0.910889 | game-dev | MEDIA | 0.754462 | game-dev | 0.94946 | 1 | 0.94946 |
opentibiabr/canary | 1,304 | data-otservbr-global/npc/guide_kroak.lua | local internalNpcName = "Guide Kroak"
local npcType = Game.createNpcType(internalNpcName)
local npcConfig = {}
npcConfig.name = internalNpcName
npcConfig.description = internalNpcName
npcConfig.health = 100
npcConfig.maxHealth = npcConfig.health
npcConfig.walkInterval = 2000
npcConfig.walkRadius = 2
npcConfig.outfit = {
lookType = 132,
lookHead = 38,
lookBody = 46,
lookLegs = 68,
lookFeet = 29,
lookAddons = 3,
}
npcConfig.flags = {
floorchange = false,
}
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
npcType.onThink = function(npc, interval)
npcHandler:onThink(npc, interval)
end
npcType.onAppear = function(npc, creature)
npcHandler:onAppear(npc, creature)
end
npcType.onDisappear = function(npc, creature)
npcHandler:onDisappear(npc, creature)
end
npcType.onMove = function(npc, creature, fromPosition, toPosition)
npcHandler:onMove(npc, creature, fromPosition, toPosition)
end
npcType.onSay = function(npc, creature, type, message)
npcHandler:onSay(npc, creature, type, message)
end
npcType.onCloseChannel = function(npc, creature)
npcHandler:onCloseChannel(npc, creature)
end
npcHandler:addModule(FocusModule:new(), npcConfig.name, true, true, true)
-- npcType registering the npcConfig table
npcType:register(npcConfig)
| 0 | 0.815499 | 1 | 0.815499 | game-dev | MEDIA | 0.900575 | game-dev | 0.556439 | 1 | 0.556439 |
gomint/gomint | 7,666 | gomint-server/src/main/java/io/gomint/server/entity/AttributeInstance.java | package io.gomint.server.entity;
import io.gomint.math.MathUtils;
import io.gomint.taglib.NBTTagCompound;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
/**
* @author geNAZt
* @version 1.0
*/
public class AttributeInstance {
private static final Logger LOGGER = LoggerFactory.getLogger( AttributeInstance.class );
private final String key;
private float minValue;
private float maxValue;
private float defaultValue;
private float value;
private boolean dirty;
private Map<AttributeModifierType, Map<AttributeModifier, Double>> modifiers = new EnumMap<>( AttributeModifierType.class );
AttributeInstance( String key, float minValue, float maxValue, float value ) {
this.key = key;
this.minValue = minValue;
this.maxValue = maxValue;
this.value = value;
this.defaultValue = value;
this.dirty = true;
}
public void setModifier( AttributeModifier modifier, AttributeModifierType type, double amount ) {
Map<AttributeModifier, Double> mods = this.getModifiers( type );
mods.put( modifier, amount );
this.recalc();
}
private Map<AttributeModifier, Double> getModifiers( AttributeModifierType type ) {
Map<AttributeModifier, Double> modifier = this.modifiers.get( type );
if ( modifier == null ) {
modifier = new EnumMap<>( AttributeModifier.class );
this.modifiers.put( type, modifier );
}
return modifier;
}
private void recalc() {
this.value = this.defaultValue;
for ( Map.Entry<AttributeModifierType, Map<AttributeModifier, Double>> entry : this.modifiers.entrySet() ) {
this.calcModifiers( entry.getKey(), entry.getValue() );
}
// Clamp
this.value = MathUtils.clamp( this.value, this.minValue, this.maxValue );
this.dirty = true;
}
private void calcModifiers( AttributeModifierType type, Map<AttributeModifier, Double> value ) {
switch ( type ) {
case ADDITION:
for ( Double aFloat : value.values() ) {
this.value += aFloat;
}
break;
case ADDITION_MULTIPLY:
for ( Double aFloat : value.values() ) {
this.value += this.defaultValue * aFloat;
}
break;
case MULTIPLY:
for ( Double aFloat : value.values() ) {
this.value *= 1f + aFloat;
}
break;
}
}
public void removeModifier( AttributeModifier modifier ) {
for ( Map.Entry<AttributeModifierType, Map<AttributeModifier, Double>> entry : this.modifiers.entrySet() ) {
entry.getValue().remove( modifier );
}
this.recalc();
}
public void setValue( float value ) {
if ( value < this.minValue || value > this.maxValue ) {
throw new IllegalArgumentException( "Value is not withing bounds: " + value + "; max: " + this.maxValue + "; min: " + this.minValue );
}
this.value = value;
this.dirty = true;
}
public boolean isDirty() {
boolean val = this.dirty;
this.dirty = false;
return val;
}
public void reset() {
this.modifiers.clear();
this.value = this.defaultValue;
this.dirty = true;
}
public void setMaxValue( float maxValue ) {
this.maxValue = maxValue;
}
public void initFromNBT( NBTTagCompound compound ) {
this.defaultValue = compound.getFloat( "Base", this.defaultValue );
this.value = compound.getFloat("Current", this.value);
this.maxValue = compound.getFloat("Max", this.maxValue);
List<Object> nbtAmplifiers = compound.getList( "Modifiers", false );
if ( nbtAmplifiers != null ) {
for ( Object amplifier: nbtAmplifiers ) {
NBTTagCompound nbtAmplifier = (NBTTagCompound) amplifier;
String name = nbtAmplifier.getString( "Name", "" );
AttributeModifier modifier = null;
for ( AttributeModifier attributeModifier : AttributeModifier.values() ) {
if ( attributeModifier.getName().equals( name ) ) {
modifier = attributeModifier;
break;
}
}
if ( modifier == null ) {
LOGGER.warn( "Unknown modifier: {}", name );
}
int operation = nbtAmplifier.getInteger( "Operation", 0 );
float amount = nbtAmplifier.getFloat( "Amount", 0.0f );
if ( modifier != null && amount != 0 ) {
switch ( operation ) {
case 0:
this.setModifier( modifier, AttributeModifierType.ADDITION, amount );
break;
case 1:
this.setModifier( modifier, AttributeModifierType.MULTIPLY, amount );
break;
case 2:
this.setModifier( modifier, AttributeModifierType.ADDITION_MULTIPLY, amount );
break;
default:
break;
}
}
}
}
}
public NBTTagCompound persistToNBT() {
NBTTagCompound compound = new NBTTagCompound( "" );
compound.addValue( "Name", this.key );
compound.addValue( "Base", this.defaultValue );
compound.addValue("Current", this.value);
compound.addValue("Max", this.maxValue);
// Check for 0 mode multipliers (simple addition)
List<NBTTagCompound> nbtModifiers = new ArrayList<>();
if ( !this.modifiers.isEmpty() ) {
for ( Map.Entry<AttributeModifierType, Map<AttributeModifier, Double>> entry: this.modifiers.entrySet() ) {
for (Map.Entry<AttributeModifier, Double> modifierEntry : entry.getValue().entrySet()) {
NBTTagCompound nbtTagCompound = new NBTTagCompound( "" );
nbtTagCompound.addValue( "Name", modifierEntry.getKey().getName() );
nbtTagCompound.addValue( "Operation", entry.getKey().ordinal() );
nbtTagCompound.addValue( "Amount", (double) modifierEntry.getValue() );
nbtModifiers.add( nbtTagCompound );
}
}
}
compound.addValue( "Modifiers", nbtModifiers );
return compound;
}
public String getKey() {
return this.key;
}
public float getMinValue() {
return this.minValue;
}
public float getMaxValue() {
return this.maxValue;
}
public float getDefaultValue() {
return this.defaultValue;
}
public float getValue() {
return this.value;
}
public Map<AttributeModifierType, Map<AttributeModifier, Double>> getModifiers() {
return this.modifiers;
}
@Override
public String toString() {
return "AttributeInstance{" +
"key='" + this.key + '\'' +
", minValue=" + this.minValue +
", maxValue=" + this.maxValue +
", defaultValue=" + this.defaultValue +
", value=" + this.value +
", dirty=" + this.dirty +
", modifiers=" + this.modifiers +
'}';
}
}
| 0 | 0.961352 | 1 | 0.961352 | game-dev | MEDIA | 0.796739 | game-dev | 0.96859 | 1 | 0.96859 |
quiverteam/Engine | 3,470 | src/thirdparty/bullet/src/LinearMath/btGrahamScan2dConvexHull.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2011 Advanced Micro Devices, Inc. http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef GRAHAM_SCAN_2D_CONVEX_HULL_H
#define GRAHAM_SCAN_2D_CONVEX_HULL_H
#include "btVector3.h"
#include "btAlignedObjectArray.h"
struct GrahamVector3 : public btVector3
{
GrahamVector3(const btVector3& org, int orgIndex)
:btVector3(org),
m_orgIndex(orgIndex)
{
}
btScalar m_angle;
int m_orgIndex;
};
struct btAngleCompareFunc {
btVector3 m_anchor;
btAngleCompareFunc(const btVector3& anchor)
: m_anchor(anchor)
{
}
bool operator()(const GrahamVector3& a, const GrahamVector3& b) const {
if (a.m_angle != b.m_angle)
return a.m_angle < b.m_angle;
else
{
btScalar al = (a-m_anchor).length2();
btScalar bl = (b-m_anchor).length2();
if (al != bl)
return al < bl;
else
{
return a.m_orgIndex < b.m_orgIndex;
}
}
}
};
inline void GrahamScanConvexHull2D(btAlignedObjectArray<GrahamVector3>& originalPoints, btAlignedObjectArray<GrahamVector3>& hull, const btVector3& normalAxis)
{
btVector3 axis0, axis1;
btPlaneSpace1(normalAxis, axis0, axis1);
if (originalPoints.size()<=1)
{
for (int i=0;i<originalPoints.size();i++)
hull.push_back(originalPoints[0]);
return;
}
//step1 : find anchor point with smallest projection on axis0 and move it to first location
for (int i=0;i<originalPoints.size();i++)
{
// const btVector3& left = originalPoints[i];
// const btVector3& right = originalPoints[0];
btScalar projL = originalPoints[i].dot(axis0);
btScalar projR = originalPoints[0].dot(axis0);
if (projL < projR)
{
originalPoints.swap(0, i);
}
}
//also precompute angles
originalPoints[0].m_angle = -1e30f;
for (int i=1;i<originalPoints.size();i++)
{
btVector3 xvec = axis0;
btVector3 ar = originalPoints[i]-originalPoints[0];
originalPoints[i].m_angle = btCross(xvec, ar).dot(normalAxis) / ar.length();
}
//step 2: sort all points, based on 'angle' with this anchor
btAngleCompareFunc comp(originalPoints[0]);
originalPoints.quickSortInternal(comp,1, originalPoints.size()-1);
int i;
for (i = 0; i<2; i++)
hull.push_back(originalPoints[i]);
//step 3: keep all 'convex' points and discard concave points (using back tracking)
for (; i != originalPoints.size(); i++)
{
bool isConvex = false;
while (!isConvex&& hull.size()>1) {
btVector3& a = hull[hull.size()-2];
btVector3& b = hull[hull.size()-1];
isConvex = btCross(a-b, a-originalPoints[i]).dot(normalAxis)> 0;
if (!isConvex)
hull.pop_back();
else
hull.push_back(originalPoints[i]);
}
}
}
#endif //GRAHAM_SCAN_2D_CONVEX_HULL_H
| 0 | 0.802761 | 1 | 0.802761 | game-dev | MEDIA | 0.9542 | game-dev | 0.979227 | 1 | 0.979227 |
Interkarma/daggerfall-unity | 6,665 | Assets/Scripts/Game/UserInterfaceWindows/RetroModeConfigPage.cs | // Project: Daggerfall Unity
// Copyright: Copyright (C) 2009-2023 Daggerfall Workshop
// Web Site: http://www.dfworkshop.net
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/Interkarma/daggerfall-unity
// Original Author: Gavin Clayton (interkarma@dfworkshop.net)
// Contributors:
//
// Notes:
//
using UnityEngine;
using DaggerfallWorkshop.Game.UserInterface;
namespace DaggerfallWorkshop.Game.UserInterfaceWindows
{
public class RetroModeConfigPage : GameEffectConfigPage
{
const string key = "retroMode";
HorizontalSlider modeSlider;
HorizontalSlider postProcessSlider;
Checkbox aspectCorrectionOff;
Checkbox aspectCorrectionFourThree;
Checkbox aspectCorrectionSixteenTen;
public override string Key => key;
public override string Title => TextManager.Instance.GetLocalizedText(Key);
public override void Setup(Panel parent)
{
Vector2 pos = settingsStartPos;
// About this effect
AddTipPanel(parent, TextManager.Instance.GetLocalizedText("retroModeTip"));
// Mode slider
string[] modes = new string[]
{
TextManager.Instance.GetLocalizedText("retroModeOff"),
TextManager.Instance.GetLocalizedText("retroMode320x200"),
TextManager.Instance.GetLocalizedText("retroMode640x400"),
};
modeSlider = AddSlider(parent, TextManager.Instance.GetLocalizedText("mode"), modes.Length, ref pos);
modeSlider.OnScroll += ModeSlider_OnScroll;
modeSlider.SetIndicator(modes, DaggerfallUnity.Settings.RetroRenderingMode);
StyleIndicator(modeSlider);
// PostProcess Slider
string[] postProcessModes = new string[]
{
TextManager.Instance.GetLocalizedText("off"),
TextManager.Instance.GetLocalizedText("posterizationFull"),
TextManager.Instance.GetLocalizedText("posterizationMinusSky"),
TextManager.Instance.GetLocalizedText("palettizationFull"),
TextManager.Instance.GetLocalizedText("palettizationMinusSky"),
};
postProcessSlider = AddSlider(parent, TextManager.Instance.GetLocalizedText("postProcess"), postProcessModes.Length, ref pos);
postProcessSlider.OnScroll += PostProcessSlider_OnScroll;
postProcessSlider.SetIndicator(postProcessModes, DaggerfallUnity.Settings.PostProcessingInRetroMode);
StyleIndicator(postProcessSlider);
// Aspect Correction Checkboxes
// Not using a slider as the sudden rescale in UI can cause aspect to bounce back and forth based on mouse position while dragging slider thumb
AddLabel(parent, TextManager.Instance.GetLocalizedText("retroModeAspectCorrection"), ref pos);
pos.y += yIncrement;
aspectCorrectionOff = AddCheckbox(parent, TextManager.Instance.GetLocalizedText("off"), ref pos);
aspectCorrectionOff.OnToggleState += AspectCorrectionOff_OnToggleState;
aspectCorrectionFourThree = AddCheckbox(parent, TextManager.Instance.GetLocalizedText("FourThree"), ref pos);
aspectCorrectionFourThree.OnToggleState += AspectCorrectionFourThree_OnToggleState;
aspectCorrectionSixteenTen = AddCheckbox(parent, TextManager.Instance.GetLocalizedText("SixteenTen"), ref pos);
aspectCorrectionSixteenTen.OnToggleState += AspectCorrectionSixteenTen_OnToggleState;
UpdateAspectButtons();
}
void UpdateAspectButtons()
{
// Fake radio buttons
aspectCorrectionOff.IsChecked = aspectCorrectionFourThree.IsChecked = aspectCorrectionSixteenTen.IsChecked = false;
switch((RetroModeAspects)DaggerfallUnity.Settings.RetroModeAspectCorrection)
{
case RetroModeAspects.Off:
aspectCorrectionOff.IsChecked = true;
break;
case RetroModeAspects.FourThree:
aspectCorrectionFourThree.IsChecked = true;
break;
case RetroModeAspects.SixteenTen:
aspectCorrectionSixteenTen.IsChecked = true;
break;
}
}
public override void ReadSettings()
{
modeSlider.ScrollIndex = DaggerfallUnity.Settings.RetroRenderingMode;
postProcessSlider.ScrollIndex = DaggerfallUnity.Settings.PostProcessingInRetroMode;
UpdateAspectButtons();
}
public override void DeploySettings()
{
GameManager.Instance.StartGameBehaviour.DeployCoreGameEffectSettings(CoreGameEffectSettingsGroups.RetroMode);
}
public override void SetDefaults()
{
DaggerfallUnity.Settings.RetroRenderingMode = 0;
DaggerfallUnity.Settings.PostProcessingInRetroMode = 0;
DaggerfallUnity.Settings.RetroModeAspectCorrection = 0;
}
private void ModeSlider_OnScroll()
{
DaggerfallUnity.Settings.RetroRenderingMode = modeSlider.ScrollIndex;
DeploySettings();
}
private void PostProcessSlider_OnScroll()
{
DaggerfallUnity.Settings.PostProcessingInRetroMode = postProcessSlider.ScrollIndex;
DeploySettings();
}
private void AspectCorrectionOff_OnToggleState()
{
aspectCorrectionOff.IsChecked = true;
aspectCorrectionFourThree.IsChecked = false;
aspectCorrectionSixteenTen.IsChecked = false;
DaggerfallUnity.Settings.RetroModeAspectCorrection = (int)RetroModeAspects.Off;
DeploySettings();
}
private void AspectCorrectionFourThree_OnToggleState()
{
aspectCorrectionOff.IsChecked = false;
aspectCorrectionFourThree.IsChecked = true;
aspectCorrectionSixteenTen.IsChecked = false;
DaggerfallUnity.Settings.RetroModeAspectCorrection = (int)RetroModeAspects.FourThree;
DeploySettings();
}
private void AspectCorrectionSixteenTen_OnToggleState()
{
aspectCorrectionOff.IsChecked = false;
aspectCorrectionFourThree.IsChecked = false;
aspectCorrectionSixteenTen.IsChecked = true;
DaggerfallUnity.Settings.RetroModeAspectCorrection = (int)RetroModeAspects.SixteenTen;
DeploySettings();
}
}
} | 0 | 0.797381 | 1 | 0.797381 | game-dev | MEDIA | 0.766076 | game-dev | 0.761967 | 1 | 0.761967 |
markol/machines | 3,059 | src/projects/machines/loadplan.cpp | #include "base/istrrep.hpp"
#include "machines/sdlapp.hpp"
#include "system/filedata.hpp"
#include "system/fileenum.hpp"
#include "mathex/point2d.hpp"
#include "render/texture.hpp"
#include "render/texset.hpp"
#include "machgui/dbscenar.hpp"
#include "machgui/dbsystem.hpp"
#include "machgui/dbplanet.hpp"
#include "machgui/database.hpp"
#include "machlog/races.hpp"
#include "machlog/artfacts.hpp"
class PlanetLoadDummyProgressIndicator : public BaseProgressReporter
{
public:
PlanetLoadDummyProgressIndicator() {};
virtual size_t report( size_t , size_t )
{
return 0;
}
private:
};
static void loading( MachGuiDbSystem& system, W4dSceneManager* pSceneManager )
{
PlanetLoadDummyProgressIndicator reporter;
const uint nPlanets = system.nPlanets();
for( uint jPla=0; jPla<nPlanets; ++jPla)
{
MachGuiDbPlanet& planet = system.planet( jPla );
planet.textData();
const uint nScenarios = planet.nScenarios();
for( uint kSce=0; kSce<nScenarios; ++kSce )
{
const string& planetName = planet.scenario( kSce ).planetFile();
MachLogRaces::instance().loadPlanet( pSceneManager, planetName, &reporter );
MachLogRaces::instance().unloadGame();
planet.scenario( kSce ).textData();
}
}
}
void SDLApp::loadPlanets()
{
typedef ctl_vector< SysFileData > FileDatas;
//Construct a file enumerator for all the models\planet\...\*.arf files
SysFileEnumerator arfEnum( SysPathName( "models/planet" ), SysPathName( "*.arf" ) );
arfEnum.examineSubdirectories( true );
arfEnum.find();
const FileDatas& fileDatas = arfEnum.files();
DANIEL_INSPECT( fileDatas.size() );
//Handles parsing and creation of artefacts
MachLogArtefacts artefacts;
//Create the artefact persistent files for each one
for( FileDatas::const_iterator cit = fileDatas.begin(); cit != fileDatas.end(); ++cit )
{
SysPathName arfPath = (*cit).pathName();
DANIEL_INSPECT( arfPath );
//Preload the textures for this planet (2MB versions will do)
string textureDirectory = arfPath.directory();
textureDirectory += "/texture2";
RenTextureSet textureSet( textureDirectory );
artefacts.load( arfPath );
artefacts.unload();
artefacts.finish();
}
//load all the planets
//campaigns
const uint nSystems = MachGuiDatabase::instance().nCampaignSystems();
for(uint iSys=0; iSys<nSystems; ++iSys)
{
MachGuiDbSystem& system = MachGuiDatabase::instance().campaignSystem( iSys );
system.textData(); //Loads text bin file
loading( system, manager_ );
}
//skirmishes
const uint nTerrains = 3;
for(uint iTer=0; iTer<nTerrains; ++iTer)
{
MachGuiDbSystem& system = MachGuiDatabase::instance().skirmishSystem( MachGuiDatabase::TerrainSize(iTer) );
loading( system, manager_ );
}
//multiPlaySystems
for(uint iTer=0; iTer<nTerrains; ++iTer)
{
MachGuiDbSystem& system = MachGuiDatabase::instance().multiPlayerSystem( MachGuiDatabase::TerrainSize(iTer) );
loading( system, manager_ );
}
}
| 0 | 0.875441 | 1 | 0.875441 | game-dev | MEDIA | 0.705639 | game-dev | 0.640849 | 1 | 0.640849 |
makotok/Hanappe | 10,249 | projects/hanappe-framework/src/hp/gui/Slider.lua | ----------------------------------------------------------------
-- This class is a general horizontal slider.
----------------------------------------------------------------
-- import
local table = require "hp/lang/table"
local class = require "hp/lang/class"
local Event = require "hp/event/Event"
local Sprite = require "hp/display/Sprite"
local Component = require "hp/gui/Component"
-- class define
local M = class(Component)
local super = Component
-- States
M.STATE_NORMAL = "normal"
M.STATE_DISABLED = "disabled"
-- Events
M.EVENT_SLIDER_BEGIN = "sliderBeginChange"
M.EVENT_SLIDER_CHANGED = "sliderChanged"
M.EVENT_SLIDER_END = "sliderEndChange"
--------------------------------------------------------------------------------
-- Initializes the internal variables.
--------------------------------------------------------------------------------
function M:initInternal()
super.initInternal(self)
self._selected = false
self._touching = false
self._touchIndex = nil
self._themeName = "Slider"
self._beginChangeEvent = Event(M.EVENT_SLIDER_BEGIN)
self._changedEvent = Event(M.EVENT_SLIDER_CHANGED)
self._endChangeEvent = Event(M.EVENT_SLIDER_END)
self._value = 0
self._bounds = {min=0, max=1, span=1}
self._accuracy = 0.1
end
--------------------------------------------------------------------------------
-- Create a child objects.
--------------------------------------------------------------------------------
function M:createChildren()
self._background = NinePatch(self:getStyle("bg"))
self._progress = NinePatch(self:getStyle("progress"))
self._thumb = Sprite { texture = self:getStyle("thumb"), left = 0, top = 0 }
self:addChild(self._background)
self:addChild(self._progress)
self:addChild(self._thumb)
local _,bh = self._background:getSize()
self:setSize(200, bh)
self._thumb_width = self._thumb:getWidth()
end
--------------------------------------------------------------------------------
-- Update the display.
--------------------------------------------------------------------------------
function M:updateDisplay()
local background = self._background
background:setColor(unpack(self:getStyle("color")))
background:setTexture(self:getStyle("bg"))
local progress = self._progress
progress:setColor(unpack(self:getStyle("color")))
progress:setTexture(self:getStyle("progress"))
local thumb = self._thumb
thumb:setColor(unpack(self:getStyle("color")))
thumb:setTexture(self:getStyle("thumb"))
local thumbLoc = self:_valueToLoc(self._value)
thumb:setLoc(thumbLoc, self:getHeight() * 0.5)
progress:setSize(thumbLoc + self._thumb_width * 0.5, self:getHeight())
end
function M:_valueToLoc(value)
-- normalize value
local v = (value - self._bounds.min) / self._bounds.span
return self._thumb_width * 0.5 + (self:getWidth() - self._thumb_width) * v
end
function M:_locToValue(x)
-- normalized
local v = (x - self._thumb_width * 0.5) / (self:getWidth() - self._thumb_width)
return self._bounds.min + v * self._bounds.span
end
--------------------------------------------------------------------------------
-- Sets the value (must be between 0 and 1).
-- @param value value
--------------------------------------------------------------------------------
function M:setValue(value)
if value < self._bounds.min then
value = self._bounds.min
end
if value > self._bounds.max then
value = self._bounds.max
end
-- round to 4 decimal places = value
value = math.floor(value * 10000) / 10000
-- snap to accuracy
local invsnap = 1 / self._accuracy
value = math.floor(value * invsnap) / invsnap
-- if value has not changed, abort
if value == self._value then
return
end
local old_value = self._value
self._value = value
self:_updateDrawables()
local event = self._changedEvent
event.oldValue = old_value
event.value = self._value
self:dispatchEvent(event)
end
function M:_updateDrawables()
-- and indication we 're still initializing (called by resizeHandler)...
if self._thumb_width == nil then
return
end
local thumbLoc = self:_valueToLoc(self._value)
self._thumb:setLoc(thumbLoc, self._background:getHeight() * 0.5)
self._progress:setSize(thumbLoc + self._thumb_width * 0.5, self:getHeight())
end
--------------------------------------------------------------------------------
-- Returns the value.
-- @return value
--------------------------------------------------------------------------------
function M:getValue()
return self._value
end
--------------------------------------------------------------------------------
-- Returns the accuracy.
-- @return accuracy
--------------------------------------------------------------------------------
function M:getAccuracy()
return self._accuracy
end
--------------------------------------------------------------------------------
-- Returns the accuracy.
-- @param accuracy accuracy
--------------------------------------------------------------------------------
function M:setAccuracy(accuracy)
self._accuracy = accuracy
self:setValue(self._value)
end
--------------------------------------------------------------------------------
-- Returns the minimum and maximum values this slider can hold.
-- @return minimum and maximum values
--------------------------------------------------------------------------------
function M:getValueBounds()
return self._bounds.min, self._bounds.max
end
--------------------------------------------------------------------------------
-- Returns the minimum and maximum values this slider can hold.
-- @param minMax table holding {min, max} values
--------------------------------------------------------------------------------
function M:setValueBounds(...)
local minMax = {...}
assert(#minMax >= 2)
self._bounds.min = minMax[1]
self._bounds.max = minMax[2]
self._bounds.span = self._bounds.max - self._bounds.min
self:setValue(self._value)
end
--------------------------------------------------------------------------------
-- Set the event listener that is called when the user pushes the thumb.
-- @param func push event handler
--------------------------------------------------------------------------------
function M:setOnSliderBeginChange(func)
self:setEventListener(M.EVENT_SLIDER_BEGIN, func)
end
--------------------------------------------------------------------------------
-- Set the event listener that is called when the user moves the thumb.
-- @param func move event handler
--------------------------------------------------------------------------------
function M:setOnSliderChanged(func)
self:setEventListener(M.EVENT_SLIDER_CHANGED, func)
end
--------------------------------------------------------------------------------
-- Set the event listener that is called when the user releases the thumb.
-- @param func release event handler
--------------------------------------------------------------------------------
function M:setOnSliderEndChange(func)
self:setEventListener(M.EVENT_SLIDER_END, func)
end
--------------------------------------------------------------------------------
-- Event Handler
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- This event handler is called when touched.
-- @param e Touch Event
--------------------------------------------------------------------------------
function M:touchDownHandler(e)
if self._touching then
return
end
e:stop()
if self._thumb:hitTestWorld(e.x, e.y) then
self._touchIndex = e.idx
self._touching = true
local event = self._beginChangeEvent
event.value = self._value
self:dispatchEvent(event)
end
end
--------------------------------------------------------------------------------
-- This event handler is called when the button is released.
-- @param e Touch Event
--------------------------------------------------------------------------------
function M:touchUpHandler(e)
if e.idx ~= self._touchIndex then
return
end
e:stop()
self._touching = false
self._touchIndex = nil
local event = self._endChangeEvent
event.value = self._value
self:dispatchEvent(event)
end
--------------------------------------------------------------------------------
-- This event handler is called when you move on the button.
-- @param e Touch Event
--------------------------------------------------------------------------------
function M:touchMoveHandler(e)
if e.idx ~= self._touchIndex then
return
end
e:stop()
if self._touching then
local mx, my = self:worldToModel(e.x, e.y, 0)
local v = self:_locToValue(mx)
self:setValue(v)
end
end
--------------------------------------------------------------------------------
-- This event handler is called when you move on the button.
-- @param e Touch Event
--------------------------------------------------------------------------------
function M:touchCancelHandler(e)
if not self:isToggle() then
self._touching = false
self._touchIndex = nil
end
end
--------------------------------------------------------------------------------
-- This event handler is called when resizing.
-- @param e resize event
--------------------------------------------------------------------------------
function M:resizeHandler(e)
self._background:setSize(self:getWidth(), self:getHeight())
self:_updateDrawables()
end
--------------------------------------------------------------------------------
-- This event handler is called when the enabled state changes.
-- @param e event
--------------------------------------------------------------------------------
function M:enabledChangedHandler(e)
if not self:isEnabled() then
self._touching = false
self._touchIndex = 0
end
end
return M | 0 | 0.685142 | 1 | 0.685142 | game-dev | MEDIA | 0.687225 | game-dev,desktop-app | 0.85713 | 1 | 0.85713 |
acmeism/RosettaCodeData | 2,127 | Task/Rock-paper-scissors/Crystal/rock-paper-scissors.cr | # conventional weapons
enum Choice
Rock
Paper
Scissors
end
BEATS = {
Choice::Rock => [Choice::Paper],
Choice::Paper => [Choice::Scissors],
Choice::Scissors => [Choice::Rock],
}
# uncomment to use additional weapons
# enum Choice
# Rock
# Paper
# Scissors
# Lizard
# Spock
# end
# BEATS = {
# Choice::Rock => [Choice::Paper, Choice::Spock],
# Choice::Paper => [Choice::Scissors, Choice::Lizard],
# Choice::Scissors => [Choice::Rock, Choice::Spock],
# Choice::Lizard => [Choice::Rock, Choice::Scissors],
# Choice::Spock => [Choice::Paper, Choice::Lizard],
# }
class RPSAI
@stats = {} of Choice => Int32
def initialize
Choice.values.each do |c|
@stats[c] = 1
end
end
def choose
v = rand(@stats.values.sum)
@stats.each do |choice, rate|
v -= rate
return choice if v < 0
end
raise ""
end
def train(selected)
BEATS[selected].each do |c|
@stats[c] += 1
end
end
end
enum GameResult
HumanWin
ComputerWin
Draw
def to_s
case self
when .draw?
"Draw"
when .human_win?
"You win!"
when .computer_win?
"I win!"
end
end
end
class RPSGame
@score = Hash(GameResult, Int32).new(0)
@ai = RPSAI.new
def check(player, computer)
return GameResult::ComputerWin if BEATS[player].includes? computer
return GameResult::HumanWin if BEATS[computer].includes? player
return GameResult::Draw
end
def round
puts ""
print "Your choice (#{Choice.values.join(", ")}):"
s = gets.not_nil!.strip.downcase
return false if "quit".starts_with? s
player_turn = Choice.values.find { |choice| choice.to_s.downcase.starts_with? s }
unless player_turn
puts "Invalid choice"
return true
end
ai_turn = @ai.choose
result = check(player_turn, ai_turn)
puts "H: #{player_turn}, C: #{ai_turn} => #{result}"
@score[result] += 1
puts "score: human=%d, computer=%d, draw=%d" % GameResult.values.map { |r| @score[r] }
@ai.train player_turn
true
end
end
game = RPSGame.new
loop do
break unless game.round
end
| 0 | 0.896924 | 1 | 0.896924 | game-dev | MEDIA | 0.962259 | game-dev | 0.818085 | 1 | 0.818085 |
design-to-production/D2P-Components | 5,048 | D2P_GrasshopperTools/GH/Stream/GHStreamComponentsByType.cs | using D2P_Core;
using D2P_Core.Interfaces;
using D2P_GrasshopperTools.Utility;
using Grasshopper;
using Grasshopper.Kernel;
using Grasshopper.Kernel.Types;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace D2P_GrasshopperTools.GH.Stream
{
public class GHStreamComponentsByType : GHVariableParameterComponent
{
bool reverseRegex = false;
/// <summary>
/// Initializes a new instance of the GH_StreamTypes class.
/// </summary>
public GHStreamComponentsByType()
: base("StreamComponentsByType", "StreamByType",
"Stream component-instances from the Rhino document by providing a type-id. Sorts them by their type-ids and automatically populates the output parameters",
"D2P", "00 Stream")
{
}
/// <summary>
/// Registers all the input parameters for this component.
/// </summary>
protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
{
pManager.AddGenericParameter("TypeID", "T", "The component-type or its type-id used to stream specific types", GH_ParamAccess.list);
pManager.AddTextParameter("NameFilter", "N", "The regex pattern used to filter by specific component-names", GH_ParamAccess.list, string.Empty);
pManager.AddGenericParameter("Settings", "S", "The settings define the basic root-layer for all components being streamed and a collection of specific delimiters", GH_ParamAccess.item);
pManager[2].Optional = true;
}
/// <summary>
/// Registers all the output parameters for this component.
/// </summary>
protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
{
}
/// <summary>
/// This is the method that actually does the work.
/// </summary>
/// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
protected override void SolveInstance(IGH_DataAccess DA)
{
var componentTypes = new List<GH_ObjectWrapper>();
var filterList = new List<string>();
Settings settings = null;
DA.GetDataList(0, componentTypes);
DA.GetDataList(1, filterList);
DA.GetData(2, ref settings);
settings = settings ?? DefaultSettings.Create();
var componentTrees = new Dictionary<string, DataTree<IComponent>>();
foreach (var componentType in componentTypes)
{
var typeID = (componentType?.Value as IComponentType)?.TypeID ?? componentType?.Value?.ToString();
_properties.Add(typeID, typeof(Enumerable));
componentTrees.Add(typeID, new DataTree<IComponent>());
for (int i = 0; i < filterList.Count; i++)
{
var filterOptions = new FilterOptions() { RegexPattern = filterList[i], ReversePattern = reverseRegex };
var components = D2P_Core.Utility.Instantiation.InstancesByType(typeID, settings, filterOptions);
componentTrees[typeID].EnsurePath(i);
componentTrees[typeID].AddRange(components);
_components.AddRange(components); // only for visualization
}
}
if (OutputMismatch() && DA.Iteration == 0)
OnPingDocument().ScheduleSolution(5, d => CreateOutputParams(false));
else
{
foreach (var kv in componentTrees)
{
var paramIdx = Params.Output.FindIndex(x => x.Name == kv.Key);
DA.SetDataTree(paramIdx, kv.Value);
}
}
}
protected override void AppendAdditionalComponentMenuItems(ToolStripDropDown menu)
{
base.AppendAdditionalComponentMenuItems(menu);
var menuItem = Menu_AppendItem(menu, "NegateRegexFilter", NegateRegexFilterHandler, true, reverseRegex);
menuItem.ToolTipText = "When true the name-filter will be negated";
}
private void NegateRegexFilterHandler(object sender, EventArgs e)
{
reverseRegex = !reverseRegex;
ExpireSolution(true);
}
/// <summary>
/// Provides an Icon for the component.
/// </summary>
protected override System.Drawing.Bitmap Icon
{
get
{
//You can add image files to your project resources and access them like this:
return Properties.Resources.GH_TypeStream;
}
}
/// <summary>
/// Gets the unique ID for this component. Do not change this ID after release.
/// </summary>
public override Guid ComponentGuid
{
get { return new Guid("DF586BB3-8A71-4383-9B00-4B624876CE8D"); }
}
}
} | 0 | 0.958726 | 1 | 0.958726 | game-dev | MEDIA | 0.412888 | game-dev | 0.966182 | 1 | 0.966182 |
goncasmage1/UINavigation | 1,813 | Source/UINavigationEditor/Private/UINavigationEditor.cpp | // Copyright (C) 2023 Gonalo Marques - All Rights Reserved
#include "UINavigationEditor.h"
#include "UINavSettings.h"
#include "ISettingsModule.h"
#include "ISettingsSection.h"
#include "Modules/ModuleManager.h"
#define LOCTEXT_NAMESPACE "FUINavigationEditorModule"
void FUINavigationEditorModule::StartupModule()
{
// This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module
RegisterSettings();
}
void FUINavigationEditorModule::ShutdownModule()
{
// This function may be called during shutdown to clean up your module. For modules that support dynamic reloading,
// we call this function before unloading the module.
if (UObjectInitialized())
{
UnregisterSettings();
}
}
void FUINavigationEditorModule::RegisterSettings()
{
if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings"))
{
ISettingsSectionPtr SettingsSection = SettingsModule->RegisterSettings("Project", "Plugins", "UINavigation",
LOCTEXT("UINavigationSettingsName", "UI Navigation"),
LOCTEXT("UINavigationSettingsDescription", "Configure the UI Navigation settings."),
GetMutableDefault<UUINavSettings>()
);
if (SettingsSection.IsValid())
{
SettingsSection->OnModified().BindRaw(this, &FUINavigationEditorModule::HandleSettingsSaved);
}
}
}
void FUINavigationEditorModule::UnregisterSettings()
{
if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings"))
{
SettingsModule->UnregisterSettings("Project", "Plugins", "UINavigation");
}
}
bool FUINavigationEditorModule::HandleSettingsSaved()
{
GetMutableDefault<UUINavSettings>()->SaveConfig();
return true;
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FUINavigationEditorModule, UINavigationEditor)
| 0 | 0.734799 | 1 | 0.734799 | game-dev | MEDIA | 0.510459 | game-dev | 0.717707 | 1 | 0.717707 |
The-Cataclysm-Preservation-Project/TrinityCore | 63,787 | src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp | /*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "Containers.h"
#include "GridNotifiers.h"
#include "icecrown_citadel.h"
#include "InstanceScript.h"
#include "Map.h"
#include "MotionMaster.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "ScriptedCreature.h"
#include "SpellAuraEffects.h"
#include "SpellMgr.h"
#include "SpellScript.h"
#include "TemporarySummon.h"
namespace IcecrownCitadel::Sindragosa
{
enum Texts
{
SAY_AGGRO = 0, // You are fools to have come to this place! The icy winds of Northrend will consume your souls!
SAY_UNCHAINED_MAGIC = 1, // Suffer, mortals, as your pathetic magic betrays you!
EMOTE_WARN_BLISTERING_COLD = 2, // %s prepares to unleash a wave of blistering cold!
SAY_BLISTERING_COLD = 3, // Can you feel the cold hand of death upon your heart?
SAY_RESPITE_FOR_A_TORMENTED_SOUL = 4, // Aaah! It burns! What sorcery is this?!
SAY_AIR_PHASE = 5, // Your incursion ends here! None shall survive!
SAY_PHASE_2 = 6, // Now feel my master's limitless power and despair!
EMOTE_WARN_FROZEN_ORB = 7, // %s fires a frozen orb towards $N!
SAY_KILL = 8, // Perish!
// A flaw of mortality...
SAY_BERSERK = 9, // Enough! I tire of these games!
SAY_DEATH = 10, // Free...at last...
EMOTE_BERSERK_RAID = 11
};
enum Spells
{
// Sindragosa
SPELL_SINDRAGOSA_S_FURY = 70608,
SPELL_TANK_MARKER = 71039,
SPELL_FROST_AURA = 70084,
SPELL_PERMAEATING_CHILL = 70109,
SPELL_CLEAVE = 19983,
SPELL_TAIL_SMASH = 71077,
SPELL_FROST_BREATH_P1 = 69649,
SPELL_FROST_BREATH_P2 = 73061,
SPELL_UNCHAINED_MAGIC = 69762,
SPELL_BACKLASH = 69770,
SPELL_ICY_GRIP = 70117,
SPELL_ICY_GRIP_JUMP = 70122,
SPELL_BLISTERING_COLD = 70123,
SPELL_FROST_BEACON = 70126,
SPELL_ICE_TOMB_TARGET = 69712,
SPELL_ICE_TOMB_DUMMY = 69675,
SPELL_ICE_TOMB_UNTARGETABLE = 69700,
SPELL_ICE_TOMB_DAMAGE = 70157,
SPELL_ASPHYXIATION = 71665,
SPELL_FROST_BOMB_TRIGGER = 69846,
SPELL_FROST_BOMB_VISUAL = 70022,
SPELL_BIRTH_NO_VISUAL = 40031,
SPELL_FROST_BOMB = 69845,
SPELL_MYSTIC_BUFFET = 70128,
// Spinestalker
SPELL_BELLOWING_ROAR = 36922,
SPELL_CLEAVE_SPINESTALKER = 40505,
SPELL_TAIL_SWEEP = 71370,
// Rimefang
SPELL_FROST_BREATH = 71386,
SPELL_FROST_AURA_RIMEFANG = 71387,
SPELL_ICY_BLAST = 71376,
SPELL_ICY_BLAST_AREA = 71380,
// Frostwarden Handler
SPELL_FOCUS_FIRE = 71350,
SPELL_ORDER_WHELP = 71357,
SPELL_CONCUSSIVE_SHOCK = 71337,
// Frost Infusion
SPELL_FROST_INFUSION_CREDIT = 72289,
SPELL_FROST_IMBUED_BLADE = 72290,
SPELL_FROST_INFUSION = 72292,
};
enum Events
{
// Sindragosa
EVENT_BERSERK = 1,
EVENT_CLEAVE = 2,
EVENT_TAIL_SMASH = 3,
EVENT_FROST_BREATH = 4,
EVENT_UNCHAINED_MAGIC = 5,
EVENT_ICY_GRIP = 6,
EVENT_BLISTERING_COLD = 7,
EVENT_BLISTERING_COLD_YELL = 8,
EVENT_AIR_PHASE = 9,
EVENT_ICE_TOMB = 10,
EVENT_FROST_BOMB = 11,
EVENT_LAND = 12,
EVENT_AIR_MOVEMENT = 21,
EVENT_THIRD_PHASE_CHECK = 22,
EVENT_AIR_MOVEMENT_FAR = 23,
EVENT_LAND_GROUND = 24,
// Spinestalker
EVENT_BELLOWING_ROAR = 13,
EVENT_CLEAVE_SPINESTALKER = 14,
EVENT_TAIL_SWEEP = 15,
// Rimefang
EVENT_FROST_BREATH_RIMEFANG = 16,
EVENT_ICY_BLAST = 17,
EVENT_ICY_BLAST_CAST = 18,
// Trash
EVENT_FROSTWARDEN_ORDER_WHELP = 19,
EVENT_CONCUSSIVE_SHOCK = 20,
// event groups
EVENT_GROUP_LAND_PHASE = 1,
};
enum FrostwingData
{
DATA_MYSTIC_BUFFET_STACK = 0,
DATA_FROSTWYRM_OWNER = 1,
DATA_WHELP_MARKER = 2,
DATA_LINKED_GAMEOBJECT = 3,
DATA_TRAPPED_PLAYER = 4,
DATA_IS_THIRD_PHASE = 5
};
enum MovementPoints
{
POINT_FROSTWYRM_FLY_IN = 1,
POINT_FROSTWYRM_LAND = 2,
POINT_AIR_PHASE = 3,
POINT_TAKEOFF = 4,
POINT_LAND = 5,
POINT_AIR_PHASE_FAR = 6,
POINT_LAND_GROUND = 7,
};
enum Shadowmourne
{
QUEST_FROST_INFUSION = 24757
};
Position const RimefangFlyPos = {4413.309f, 2456.421f, 233.3795f, 2.890186f};
Position const RimefangLandPos = {4413.309f, 2456.421f, 203.3848f, 2.890186f};
Position const SpinestalkerFlyPos = {4418.895f, 2514.233f, 230.4864f, 3.396045f};
Position const SpinestalkerLandPos = {4418.895f, 2514.233f, 203.3848f, 3.396045f};
Position const SindragosaSpawnPos = {4818.700f, 2483.710f, 287.0650f, 3.089233f};
Position const SindragosaFlyPos = {4475.190f, 2484.570f, 234.8510f, 3.141593f};
Position const SindragosaLandPos = {4419.190f, 2484.570f, 203.3848f, 3.141593f};
Position const SindragosaAirPos = {4475.990f, 2484.430f, 247.9340f, 3.141593f};
Position const SindragosaAirPosFar = {4525.600f, 2485.150f, 245.0820f, 3.141593f};
Position const SindragosaFlyInPos = {4419.190f, 2484.360f, 232.5150f, 3.141593f};
class FrostwyrmLandEvent : public BasicEvent
{
public:
FrostwyrmLandEvent(Creature& owner, Position const& dest) : _owner(owner), _dest(dest) { }
bool Execute(uint64 /*eventTime*/, uint32 /*updateTime*/) override
{
_owner.GetMotionMaster()->MoveLand(POINT_FROSTWYRM_LAND, _dest);
return true;
}
private:
Creature& _owner;
Position const& _dest;
};
class FrostBombExplosion : public BasicEvent
{
public:
FrostBombExplosion(Creature* owner, ObjectGuid sindragosaGUID) : _owner(owner), _sindragosaGUID(sindragosaGUID) { }
bool Execute(uint64 /*eventTime*/, uint32 /*updateTime*/) override
{
_owner->CastSpell(nullptr, SPELL_FROST_BOMB, CastSpellExtraArgs().SetOriginalCaster(_sindragosaGUID));
_owner->RemoveAurasDueToSpell(SPELL_FROST_BOMB_VISUAL);
return true;
}
private:
Creature* _owner;
ObjectGuid _sindragosaGUID;
};
class FrostBeaconSelector : NonTankTargetSelector
{
public:
FrostBeaconSelector(Unit* source) : NonTankTargetSelector(source, true) { }
bool operator()(WorldObject* target) const
{
if (Unit* unitTarget = target->ToUnit())
return !NonTankTargetSelector::operator()(unitTarget) ||
unitTarget->HasAura(SPELL_ICE_TOMB_UNTARGETABLE);
return false;
}
};
class boss_sindragosa : public CreatureScript
{
public:
boss_sindragosa() : CreatureScript("boss_sindragosa") { }
struct boss_sindragosaAI : public BossAI
{
boss_sindragosaAI(Creature* creature) : BossAI(creature, DATA_SINDRAGOSA)
{
Initialize();
}
void Initialize()
{
_mysticBuffetStack = 0;
_isInAirPhase = false;
_isThirdPhase = false;
}
void Reset() override
{
BossAI::Reset();
DoCast(me, SPELL_TANK_MARKER, true);
events.ScheduleEvent(EVENT_BERSERK, 600000);
events.ScheduleEvent(EVENT_CLEAVE, 10000, EVENT_GROUP_LAND_PHASE);
events.ScheduleEvent(EVENT_TAIL_SMASH, 20000, EVENT_GROUP_LAND_PHASE);
events.ScheduleEvent(EVENT_FROST_BREATH, urand(8000, 12000), EVENT_GROUP_LAND_PHASE);
events.ScheduleEvent(EVENT_UNCHAINED_MAGIC, urand(9000, 14000), EVENT_GROUP_LAND_PHASE);
events.ScheduleEvent(EVENT_ICY_GRIP, 33500, EVENT_GROUP_LAND_PHASE);
events.ScheduleEvent(EVENT_AIR_PHASE, 50000);
Initialize();
if (instance->GetData(DATA_SINDRAGOSA_INTRO))
{
me->SetCanFly(true);
me->SetDisableGravity(true);
}
}
void JustDied(Unit* /* killer */) override
{
_JustDied();
Talk(SAY_DEATH);
if (Is25ManRaid() && me->HasAura(SPELL_SHADOWS_FATE))
DoCastAOE(SPELL_FROST_INFUSION_CREDIT, true);
}
void JustEngagedWith(Unit* victim) override
{
if (!instance->CheckRequiredBosses(DATA_SINDRAGOSA, victim->ToPlayer()))
{
EnterEvadeMode(EVADE_REASON_SEQUENCE_BREAK);
instance->DoCastSpellOnPlayers(LIGHT_S_HAMMER_TELEPORT);
return;
}
DoCast(me, SPELL_FROST_AURA);
DoCast(me, SPELL_PERMAEATING_CHILL);
Talk(SAY_AGGRO);
instance->SetBossState(DATA_SINDRAGOSA, IN_PROGRESS);
me->setActive(true);
me->SetFarVisible(true);
DoZoneInCombat();
}
void EnterEvadeMode(EvadeReason why) override
{
if (_isInAirPhase && why == EVADE_REASON_BOUNDARY)
return;
BossAI::EnterEvadeMode(why);
}
void JustReachedHome() override
{
BossAI::JustReachedHome();
instance->SetBossState(DATA_SINDRAGOSA, FAIL);
me->SetDisableGravity(false);
me->SetReactState(REACT_DEFENSIVE);
}
void KilledUnit(Unit* victim) override
{
if (victim->GetTypeId() == TYPEID_PLAYER)
Talk(SAY_KILL);
}
void DoAction(int32 action) override
{
if (action == ACTION_START_FROSTWYRM)
{
instance->SetData(DATA_SINDRAGOSA_INTRO, 0);
if (TempSummon* summon = me->ToTempSummon())
summon->SetTempSummonType(TEMPSUMMON_DEAD_DESPAWN);
if (me->isDead())
return;
me->setActive(true);
me->SetFarVisible(true);
me->SetCanFly(true);
me->SetDisableGravity(true);
me->SetSpeedRate(MOVE_FLIGHT, 4.0f);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
float moveTime = me->GetExactDist(&SindragosaFlyPos) / (me->GetSpeed(MOVE_FLIGHT) * 0.001f);
me->m_Events.AddEvent(new FrostwyrmLandEvent(*me, SindragosaLandPos), me->m_Events.CalculateTime(uint64(moveTime) + 250));
me->GetMotionMaster()->MovePoint(POINT_FROSTWYRM_FLY_IN, SindragosaFlyPos);
DoCast(me, SPELL_SINDRAGOSA_S_FURY);
}
}
uint32 GetData(uint32 type) const override
{
switch (type)
{
case DATA_MYSTIC_BUFFET_STACK:
return _mysticBuffetStack;
case DATA_IS_THIRD_PHASE:
return _isThirdPhase;
default:
return 0xFFFFFFFF;
}
}
void MovementInform(uint32 type, uint32 point) override
{
if (type != POINT_MOTION_TYPE && type != EFFECT_MOTION_TYPE)
return;
switch (point)
{
case POINT_FROSTWYRM_LAND:
me->setActive(false);
me->SetFarVisible(true);
me->SetCanFly(false);
me->SetDisableGravity(false);
me->SetHomePosition(SindragosaLandPos);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_PC);
me->SetSpeedRate(MOVE_FLIGHT, 2.5f);
// Sindragosa enters combat as soon as she lands
DoZoneInCombat();
break;
case POINT_TAKEOFF:
events.ScheduleEvent(EVENT_AIR_MOVEMENT, 1);
break;
case POINT_AIR_PHASE:
me->CastSpell(nullptr, SPELL_ICE_TOMB_TARGET, CastSpellExtraArgs(true).AddSpellMod(SPELLVALUE_MAX_TARGETS, RAID_MODE<int32>(2, 5, 2, 6)));
me->SetFacingTo(float(M_PI), true);
events.ScheduleEvent(EVENT_AIR_MOVEMENT_FAR, 1);
events.ScheduleEvent(EVENT_FROST_BOMB, 9000);
break;
case POINT_AIR_PHASE_FAR:
me->SetFacingTo(float(M_PI), true);
events.ScheduleEvent(EVENT_LAND, 30000);
break;
case POINT_LAND:
events.ScheduleEvent(EVENT_LAND_GROUND, 1);
break;
case POINT_LAND_GROUND:
{
me->SetCanFly(false);
me->SetDisableGravity(false);
me->SetReactState(REACT_DEFENSIVE);
if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE)
me->GetMotionMaster()->MovementExpired();
_isInAirPhase = false;
// trigger Asphyxiation
EntryCheckPredicate pred(NPC_ICE_TOMB);
summons.DoAction(ACTION_TRIGGER_ASPHYXIATION, pred);
break;
}
default:
break;
}
}
void DamageTaken(Unit* /*attacker*/, uint32& /*damage*/) override
{
if (!_isThirdPhase && !HealthAbovePct(35))
{
events.CancelEvent(EVENT_AIR_PHASE);
events.ScheduleEvent(EVENT_THIRD_PHASE_CHECK, 1000);
_isThirdPhase = true;
}
}
void JustSummoned(Creature* summon) override
{
summons.Summon(summon);
if (summon->GetEntry() == NPC_FROST_BOMB)
{
summon->CastSpell(summon, SPELL_FROST_BOMB_VISUAL, true);
summon->CastSpell(summon, SPELL_BIRTH_NO_VISUAL, true);
summon->m_Events.AddEvent(new FrostBombExplosion(summon, me->GetGUID()), summon->m_Events.CalculateTime(5500));
}
}
void SummonedCreatureDespawn(Creature* summon) override
{
BossAI::SummonedCreatureDespawn(summon);
if (summon->GetEntry() == NPC_ICE_TOMB)
summon->AI()->JustDied(summon);
}
void SpellHitTarget(WorldObject* target, SpellInfo const* spell) override
{
if (uint32 spellId = sSpellMgr->GetSpellIdForDifficulty(70127, me))
if (spellId == spell->Id && target->IsUnit())
if (Aura const* mysticBuffet = target->ToUnit()->GetAura(spell->Id))
_mysticBuffetStack = std::max<uint8>(_mysticBuffetStack, mysticBuffet->GetStackAmount());
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_BERSERK:
Talk(EMOTE_BERSERK_RAID);
Talk(SAY_BERSERK);
DoCast(me, SPELL_BERSERK);
break;
case EVENT_CLEAVE:
DoCastVictim(SPELL_CLEAVE);
events.ScheduleEvent(EVENT_CLEAVE, urand(15000, 20000), EVENT_GROUP_LAND_PHASE);
break;
case EVENT_TAIL_SMASH:
DoCast(me, SPELL_TAIL_SMASH);
events.ScheduleEvent(EVENT_TAIL_SMASH, urand(27000, 32000), EVENT_GROUP_LAND_PHASE);
break;
case EVENT_FROST_BREATH:
DoCastVictim(_isThirdPhase ? SPELL_FROST_BREATH_P2 : SPELL_FROST_BREATH_P1);
events.ScheduleEvent(EVENT_FROST_BREATH, urand(20000, 25000), EVENT_GROUP_LAND_PHASE);
break;
case EVENT_UNCHAINED_MAGIC:
Talk(SAY_UNCHAINED_MAGIC);
DoCast(me, SPELL_UNCHAINED_MAGIC);
events.ScheduleEvent(EVENT_UNCHAINED_MAGIC, urand(30000, 35000), EVENT_GROUP_LAND_PHASE);
break;
case EVENT_ICY_GRIP:
DoCast(me, SPELL_ICY_GRIP);
events.ScheduleEvent(EVENT_BLISTERING_COLD, 1000, EVENT_GROUP_LAND_PHASE);
break;
case EVENT_BLISTERING_COLD:
Talk(EMOTE_WARN_BLISTERING_COLD);
DoCast(me, SPELL_BLISTERING_COLD);
events.ScheduleEvent(EVENT_BLISTERING_COLD_YELL, 5000, EVENT_GROUP_LAND_PHASE);
break;
case EVENT_BLISTERING_COLD_YELL:
Talk(SAY_BLISTERING_COLD);
break;
case EVENT_AIR_PHASE:
{
_isInAirPhase = true;
Talk(SAY_AIR_PHASE);
me->SetCanFly(true);
me->SetDisableGravity(true);
me->SetReactState(REACT_PASSIVE);
me->AttackStop();
Position pos;
pos.Relocate(me);
pos.m_positionZ += 17.0f;
me->GetMotionMaster()->MoveTakeoff(POINT_TAKEOFF, pos);
events.CancelEventGroup(EVENT_GROUP_LAND_PHASE);
events.ScheduleEvent(EVENT_AIR_PHASE, 110000);
break;
}
case EVENT_AIR_MOVEMENT:
me->GetMotionMaster()->MovePoint(POINT_AIR_PHASE, SindragosaAirPos);
break;
case EVENT_AIR_MOVEMENT_FAR:
me->GetMotionMaster()->MovePoint(POINT_AIR_PHASE_FAR, SindragosaAirPosFar);
break;
case EVENT_ICE_TOMB:
me->CastSpell(nullptr, SPELL_ICE_TOMB_TARGET, CastSpellExtraArgs(true).AddSpellMod(SPELLVALUE_MAX_TARGETS, 1));
events.ScheduleEvent(EVENT_ICE_TOMB, urand(16000, 23000));
break;
case EVENT_FROST_BOMB:
{
float destX, destY, destZ;
destX = float(rand_norm()) * 75.0f + 4350.0f;
destY = float(rand_norm()) * 75.0f + 2450.0f;
destZ = 205.0f; // random number close to ground, get exact in next call
me->UpdateGroundPositionZ(destX, destY, destZ);
me->CastSpell(Position{ destX, destY, destZ }, SPELL_FROST_BOMB_TRIGGER);
events.ScheduleEvent(EVENT_FROST_BOMB, urand(6000, 8000));
break;
}
case EVENT_LAND:
{
events.CancelEvent(EVENT_FROST_BOMB);
me->GetMotionMaster()->MovePoint(POINT_LAND, SindragosaFlyInPos);
break;
}
case EVENT_LAND_GROUND:
events.ScheduleEvent(EVENT_CLEAVE, urand(13000, 15000), EVENT_GROUP_LAND_PHASE);
events.ScheduleEvent(EVENT_TAIL_SMASH, urand(19000, 23000), EVENT_GROUP_LAND_PHASE);
events.ScheduleEvent(EVENT_FROST_BREATH, urand(10000, 15000), EVENT_GROUP_LAND_PHASE);
events.ScheduleEvent(EVENT_UNCHAINED_MAGIC, urand(12000, 17000), EVENT_GROUP_LAND_PHASE);
events.ScheduleEvent(EVENT_ICY_GRIP, urand(35000, 40000), EVENT_GROUP_LAND_PHASE);
me->GetMotionMaster()->MoveLand(POINT_LAND_GROUND, SindragosaLandPos);
break;
case EVENT_THIRD_PHASE_CHECK:
{
if (!_isInAirPhase)
{
Talk(SAY_PHASE_2);
events.ScheduleEvent(EVENT_ICE_TOMB, urand(7000, 10000));
events.RescheduleEvent(EVENT_ICY_GRIP, urand(35000, 40000));
DoCast(me, SPELL_MYSTIC_BUFFET, true);
}
else
events.ScheduleEvent(EVENT_THIRD_PHASE_CHECK, 5000);
break;
}
default:
break;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
}
DoMeleeAttackIfReady();
}
private:
uint8 _mysticBuffetStack;
bool _isInAirPhase;
bool _isThirdPhase;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetIcecrownCitadelAI<boss_sindragosaAI>(creature);
}
};
class npc_ice_tomb : public CreatureScript
{
public:
npc_ice_tomb() : CreatureScript("npc_ice_tomb") { }
struct npc_ice_tombAI : public ScriptedAI
{
npc_ice_tombAI(Creature* creature) : ScriptedAI(creature)
{
_existenceCheckTimer = 0;
SetCombatMovement(false);
}
void Reset() override
{
me->SetReactState(REACT_PASSIVE);
}
void SetGUID(ObjectGuid const& guid, int32 id) override
{
if (id == DATA_TRAPPED_PLAYER)
{
_trappedPlayerGUID = guid;
_existenceCheckTimer = 1000;
}
}
void DoAction(int32 action) override
{
if (action == ACTION_TRIGGER_ASPHYXIATION)
if (Player* player = ObjectAccessor::GetPlayer(*me, _trappedPlayerGUID))
player->CastSpell(player, SPELL_ASPHYXIATION, true);
}
void JustDied(Unit* /*killer*/) override
{
me->RemoveAllGameObjects();
if (Player* player = ObjectAccessor::GetPlayer(*me, _trappedPlayerGUID))
{
_trappedPlayerGUID.Clear();
player->RemoveAurasDueToSpell(SPELL_ICE_TOMB_DAMAGE);
player->RemoveAurasDueToSpell(SPELL_ASPHYXIATION);
player->RemoveAurasDueToSpell(SPELL_ICE_TOMB_UNTARGETABLE);
}
}
void UpdateAI(uint32 diff) override
{
if (!_trappedPlayerGUID)
return;
if (_existenceCheckTimer <= diff)
{
Player* player = ObjectAccessor::GetPlayer(*me, _trappedPlayerGUID);
if (!player || player->isDead() || !player->HasAura(SPELL_ICE_TOMB_DAMAGE))
{
// Remove object
JustDied(me);
me->DespawnOrUnsummon();
return;
}
_existenceCheckTimer = 1000;
}
else
_existenceCheckTimer -= diff;
}
private:
ObjectGuid _trappedPlayerGUID;
uint32 _existenceCheckTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetIcecrownCitadelAI<npc_ice_tombAI>(creature);
}
};
class npc_spinestalker : public CreatureScript
{
public:
npc_spinestalker() : CreatureScript("npc_spinestalker") { }
struct npc_spinestalkerAI : public ScriptedAI
{
npc_spinestalkerAI(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()), _summoned(false)
{
}
void InitializeAI() override
{
// Increase add count
if (!me->isDead())
{
_instance->SetData(DATA_SINDRAGOSA_FROSTWYRMS, me->GetSpawnId()); // this cannot be in Reset because reset also happens on evade
Reset();
}
}
void Reset() override
{
_events.Reset();
_events.ScheduleEvent(EVENT_BELLOWING_ROAR, urand(20000, 25000));
_events.ScheduleEvent(EVENT_CLEAVE_SPINESTALKER, urand(10000, 15000));
_events.ScheduleEvent(EVENT_TAIL_SWEEP, urand(8000, 12000));
if (!_summoned)
{
me->SetCanFly(true);
me->SetDisableGravity(true);
}
}
void JustAppeared() override
{
ScriptedAI::JustAppeared();
_instance->SetData(DATA_SINDRAGOSA_FROSTWYRMS, me->GetSpawnId()); // this cannot be in Reset because reset also happens on evade
}
void JustDied(Unit* /*killer*/) override
{
_events.Reset();
}
void DoAction(int32 action) override
{
if (action == ACTION_START_FROSTWYRM)
{
if (_summoned)
return;
_summoned = true;
if (me->isDead())
return;
me->setActive(true);
me->SetFarVisible(true);
me->SetSpeedRate(MOVE_FLIGHT, 2.0f);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
float moveTime = me->GetExactDist(&SpinestalkerFlyPos) / (me->GetSpeed(MOVE_FLIGHT) * 0.001f);
me->m_Events.AddEvent(new FrostwyrmLandEvent(*me, SpinestalkerLandPos), me->m_Events.CalculateTime(uint64(moveTime) + 250));
me->SetDefaultMovementType(IDLE_MOTION_TYPE);
me->GetMotionMaster()->MoveIdle();
me->StopMoving();
me->GetMotionMaster()->MovePoint(POINT_FROSTWYRM_FLY_IN, SpinestalkerFlyPos);
me->SetReactState(REACT_DEFENSIVE);
}
}
void MovementInform(uint32 type, uint32 point) override
{
if (type != EFFECT_MOTION_TYPE || point != POINT_FROSTWYRM_LAND)
return;
me->setActive(false);
me->SetFarVisible(true);
me->SetCanFly(false);
me->SetDisableGravity(false);
me->SetHomePosition(SpinestalkerLandPos);
me->SetFacingTo(SpinestalkerLandPos.GetOrientation());
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
me->SetReactState(REACT_AGGRESSIVE);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
_events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_BELLOWING_ROAR:
DoCast(me, SPELL_BELLOWING_ROAR);
_events.ScheduleEvent(EVENT_BELLOWING_ROAR, urand(25000, 30000));
break;
case EVENT_CLEAVE_SPINESTALKER:
DoCastVictim(SPELL_CLEAVE_SPINESTALKER);
_events.ScheduleEvent(EVENT_CLEAVE_SPINESTALKER, urand(10000, 15000));
break;
case EVENT_TAIL_SWEEP:
DoCast(me, SPELL_TAIL_SWEEP);
_events.ScheduleEvent(EVENT_TAIL_SWEEP, urand(22000, 25000));
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
EventMap _events;
InstanceScript* _instance;
bool _summoned;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetIcecrownCitadelAI<npc_spinestalkerAI>(creature);
}
};
class npc_rimefang : public CreatureScript
{
public:
npc_rimefang() : CreatureScript("npc_rimefang_icc") { }
struct npc_rimefangAI : public ScriptedAI
{
npc_rimefangAI(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()), _summoned(false)
{
Initialize();
}
void Initialize()
{
_icyBlastCounter = 0;
}
void InitializeAI() override
{
// Increase add count
if (!me->isDead())
{
_instance->SetData(DATA_SINDRAGOSA_FROSTWYRMS, me->GetSpawnId()); // this cannot be in Reset because reset also happens on evade
Reset();
}
}
void Reset() override
{
_events.Reset();
_events.ScheduleEvent(EVENT_FROST_BREATH_RIMEFANG, urand(12000, 15000));
_events.ScheduleEvent(EVENT_ICY_BLAST, urand(30000, 35000));
Initialize();
if (!_summoned)
{
me->SetCanFly(true);
me->SetDisableGravity(true);
}
}
void JustAppeared() override
{
ScriptedAI::JustAppeared();
_instance->SetData(DATA_SINDRAGOSA_FROSTWYRMS, me->GetSpawnId()); // this cannot be in Reset because reset also happens on evade
}
void JustDied(Unit* /*killer*/) override
{
_events.Reset();
}
void DoAction(int32 action) override
{
if (action == ACTION_START_FROSTWYRM)
{
if (_summoned)
return;
_summoned = true;
if (me->isDead())
return;
me->setActive(true);
me->SetFarVisible(true);
me->SetSpeedRate(MOVE_FLIGHT, 2.0f);
me->SetImmuneToPC(true);
float moveTime = me->GetExactDist(&RimefangFlyPos) / (me->GetSpeed(MOVE_FLIGHT) * 0.001f);
me->m_Events.AddEvent(new FrostwyrmLandEvent(*me, RimefangLandPos), me->m_Events.CalculateTime(uint64(moveTime) + 250));
me->SetDefaultMovementType(IDLE_MOTION_TYPE);
me->GetMotionMaster()->MoveIdle();
me->StopMoving();
me->GetMotionMaster()->MovePoint(POINT_FROSTWYRM_FLY_IN, RimefangFlyPos);
me->SetReactState(REACT_DEFENSIVE);
}
}
void MovementInform(uint32 type, uint32 point) override
{
if (type != EFFECT_MOTION_TYPE || point != POINT_FROSTWYRM_LAND)
return;
me->setActive(false);
me->SetFarVisible(true);
me->SetCanFly(false);
me->SetDisableGravity(false);
me->SetHomePosition(RimefangLandPos);
me->SetFacingTo(RimefangLandPos.GetOrientation());
me->SetImmuneToPC(false);
me->SetReactState(REACT_AGGRESSIVE);
}
void JustEngagedWith(Unit* /*victim*/) override
{
DoCast(me, SPELL_FROST_AURA_RIMEFANG, true);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
_events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_FROST_BREATH_RIMEFANG:
DoCast(me, SPELL_FROST_BREATH);
_events.ScheduleEvent(EVENT_FROST_BREATH_RIMEFANG, urand(35000, 40000));
break;
case EVENT_ICY_BLAST:
{
_icyBlastCounter = RAID_MODE<uint8>(5, 7, 6, 8);
me->SetReactState(REACT_PASSIVE);
me->AttackStop();
me->SetCanFly(true);
me->GetMotionMaster()->MovePoint(POINT_FROSTWYRM_FLY_IN, RimefangFlyPos);
float moveTime = me->GetExactDist(&RimefangFlyPos)/(me->GetSpeed(MOVE_FLIGHT)*0.001f);
_events.ScheduleEvent(EVENT_ICY_BLAST, uint64(moveTime) + urand(60000, 70000));
_events.ScheduleEvent(EVENT_ICY_BLAST_CAST, uint64(moveTime) + 250);
break;
}
case EVENT_ICY_BLAST_CAST:
if (--_icyBlastCounter)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true))
{
me->SetFacingToObject(target);
DoCast(target, SPELL_ICY_BLAST);
}
_events.ScheduleEvent(EVENT_ICY_BLAST_CAST, 3000);
}
else if (Unit* victim = me->SelectVictim())
{
me->SetReactState(REACT_DEFENSIVE);
AttackStart(victim);
me->SetCanFly(false);
}
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
EventMap _events;
InstanceScript* _instance;
uint8 _icyBlastCounter;
bool _summoned;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetIcecrownCitadelAI<npc_rimefangAI>(creature);
}
};
class npc_sindragosa_trash : public CreatureScript
{
public:
npc_sindragosa_trash() : CreatureScript("npc_sindragosa_trash") { }
struct npc_sindragosa_trashAI : public ScriptedAI
{
npc_sindragosa_trashAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
_instance = creature->GetInstanceScript();
_frostwyrmId = 0;
}
void Initialize()
{
_isTaunted = false;
}
void InitializeAI() override
{
_frostwyrmId = (me->GetHomePosition().GetPositionY() < 2484.35f) ? DATA_RIMEFANG : DATA_SPINESTALKER;
// Increase add count
if (!me->isDead())
{
if (me->GetEntry() == NPC_FROSTWING_WHELP)
_instance->SetData(_frostwyrmId, me->GetSpawnId()); // this cannot be in Reset because reset also happens on evade
Reset();
}
}
void Reset() override
{
// This is shared AI for handler and whelps
if (me->GetEntry() == NPC_FROSTWARDEN_HANDLER)
{
_events.ScheduleEvent(EVENT_FROSTWARDEN_ORDER_WHELP, 3000);
_events.ScheduleEvent(EVENT_CONCUSSIVE_SHOCK, urand(8000, 10000));
}
Initialize();
}
void JustAppeared() override
{
ScriptedAI::JustAppeared();
// Increase add count
if (me->GetEntry() == NPC_FROSTWING_WHELP)
_instance->SetData(_frostwyrmId, me->GetSpawnId()); // this cannot be in Reset because reset also happens on evade
}
void SetData(uint32 type, uint32 data) override
{
if (type == DATA_WHELP_MARKER)
_isTaunted = data != 0;
}
uint32 GetData(uint32 type) const override
{
if (type == DATA_FROSTWYRM_OWNER)
return _frostwyrmId;
else if (type == DATA_WHELP_MARKER)
return uint32(_isTaunted);
return 0;
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
_events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_FROSTWARDEN_ORDER_WHELP:
DoCast(me, SPELL_ORDER_WHELP);
_events.ScheduleEvent(EVENT_FROSTWARDEN_ORDER_WHELP, 3000);
break;
case EVENT_CONCUSSIVE_SHOCK:
DoCast(me, SPELL_CONCUSSIVE_SHOCK);
_events.ScheduleEvent(EVENT_CONCUSSIVE_SHOCK, urand(10000, 13000));
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
EventMap _events;
InstanceScript* _instance;
uint32 _frostwyrmId;
bool _isTaunted; // Frostwing Whelp only
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetIcecrownCitadelAI<npc_sindragosa_trashAI>(creature);
}
};
class spell_sindragosa_s_fury : public SpellScriptLoader
{
public:
spell_sindragosa_s_fury() : SpellScriptLoader("spell_sindragosa_s_fury") { }
class spell_sindragosa_s_fury_SpellScript : public SpellScript
{
bool Load() override
{
// This script should execute only in Icecrown Citadel
return InstanceHasScript(GetCaster(), ICCScriptName);
}
void SelectDest()
{
if (Position* dest = const_cast<WorldLocation*>(GetExplTargetDest()))
{
float destX = float(rand_norm()) * 75.0f + 4350.0f;
float destY = float(rand_norm()) * 75.0f + 2450.0f;
float destZ = 205.0f; // random number close to ground, get exact in next call
GetCaster()->UpdateGroundPositionZ(destX, destY, destZ);
dest->Relocate(destX, destY, destZ);
}
}
void FilterTargets(std::list<WorldObject*>& targets)
{
targets.remove_if([](WorldObject* obj) -> bool
{
// remove GMs
if (Player* player = obj->ToPlayer())
return player->IsGameMaster();
// remove non-players too
return true;
});
_targetCount = targets.size();
}
void HandleDummy(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
if (!GetHitUnit()->IsAlive() || !_targetCount)
return;
if (GetHitUnit()->IsImmunedToDamage(GetSpellInfo()))
{
GetCaster()->SendSpellDamageImmune(GetHitUnit(), GetSpellInfo()->Id);
return;
}
float resistance = float(GetHitUnit()->GetResistance(SpellSchoolMask(GetSpellInfo()->SchoolMask)));
uint32 minResistFactor = uint32((resistance / (resistance + 510.0f)) * 10.0f) * 2;
uint32 randomResist = urand(0, (9 - minResistFactor) * 100) / 100 + minResistFactor;
uint32 damage = (uint32(GetEffectValue() / _targetCount) * randomResist) / 10;
SpellNonMeleeDamage damageInfo(GetCaster(), GetHitUnit(), GetSpellInfo()->Id, GetSpellInfo()->SchoolMask);
damageInfo.damage = damage;
GetCaster()->SendSpellNonMeleeDamageLog(&damageInfo);
GetCaster()->DealSpellDamage(&damageInfo, false);
}
void Register() override
{
BeforeCast.Register(&spell_sindragosa_s_fury_SpellScript::SelectDest);
OnObjectAreaTargetSelect.Register(&spell_sindragosa_s_fury_SpellScript::FilterTargets, EFFECT_1, TARGET_UNIT_DEST_AREA_ENTRY);
OnEffectHitTarget.Register(&spell_sindragosa_s_fury_SpellScript::HandleDummy, EFFECT_1, SPELL_EFFECT_DUMMY);
}
uint32 _targetCount = 0;
};
SpellScript* GetSpellScript() const override
{
return new spell_sindragosa_s_fury_SpellScript();
}
};
class UnchainedMagicTargetSelector
{
public:
UnchainedMagicTargetSelector() { }
bool operator()(WorldObject* object) const
{
if (Unit* unit = object->ToUnit())
return unit->GetPowerType() != POWER_MANA;
return true;
}
};
class spell_sindragosa_unchained_magic : public SpellScriptLoader
{
public:
spell_sindragosa_unchained_magic() : SpellScriptLoader("spell_sindragosa_unchained_magic") { }
class spell_sindragosa_unchained_magic_SpellScript : public SpellScript
{
void FilterTargets(std::list<WorldObject*>& unitList)
{
unitList.remove_if(UnchainedMagicTargetSelector());
uint32 maxSize = uint32(GetCaster()->GetMap()->GetSpawnMode() & 1 ? 6 : 2);
if (unitList.size() > maxSize)
Trinity::Containers::RandomResize(unitList, maxSize);
}
void Register() override
{
OnObjectAreaTargetSelect.Register(&spell_sindragosa_unchained_magic_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_sindragosa_unchained_magic_SpellScript();
}
};
class spell_sindragosa_frost_breath : public SpellScriptLoader
{
public:
spell_sindragosa_frost_breath() : SpellScriptLoader("spell_sindragosa_frost_breath") { }
class spell_sindragosa_frost_breath_SpellScript : public SpellScript
{
void HandleInfusion()
{
Player* target = GetHitPlayer();
if (!target)
return;
// Check difficulty and quest status
if (!(target->GetRaidDifficulty() & RAID_DIFFICULTY_MASK_25MAN) || target->GetQuestStatus(QUEST_FROST_INFUSION) != QUEST_STATUS_INCOMPLETE)
return;
// Check if player has Shadow's Edge equipped and not ready for infusion
if (!target->HasAura(SPELL_UNSATED_CRAVING) || target->HasAura(SPELL_FROST_IMBUED_BLADE))
return;
Aura* infusion = target->GetAura(SPELL_FROST_INFUSION, target->GetGUID());
if (infusion && infusion->GetStackAmount() >= 3)
{
target->RemoveAura(infusion);
target->CastSpell(target, SPELL_FROST_IMBUED_BLADE, TRIGGERED_FULL_MASK);
}
else
target->CastSpell(target, SPELL_FROST_INFUSION, TRIGGERED_FULL_MASK);
}
void Register() override
{
AfterHit.Register(&spell_sindragosa_frost_breath_SpellScript::HandleInfusion);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_sindragosa_frost_breath_SpellScript();
}
};
class spell_sindragosa_instability : public SpellScriptLoader
{
public:
spell_sindragosa_instability() : SpellScriptLoader("spell_sindragosa_instability") { }
class spell_sindragosa_instability_AuraScript : public AuraScript
{
bool Validate(SpellInfo const* /*spell*/) override
{
return ValidateSpellInfo({ SPELL_BACKLASH });
}
void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/)
{
if (GetTargetApplication()->GetRemoveMode().HasFlag(AuraRemoveFlags::Expired))
GetTarget()->CastSpell(GetTarget(), SPELL_BACKLASH, CastSpellExtraArgs().SetOriginalCaster(GetCasterGUID()).AddSpellBP0(aurEff->GetAmount()).SetTriggeringAura(aurEff));
}
void Register() override
{
AfterEffectRemove.Register(&spell_sindragosa_instability_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_sindragosa_instability_AuraScript();
}
};
class spell_sindragosa_frost_beacon : public SpellScriptLoader
{
public:
spell_sindragosa_frost_beacon() : SpellScriptLoader("spell_sindragosa_frost_beacon") { }
class spell_sindragosa_frost_beacon_AuraScript : public AuraScript
{
bool Validate(SpellInfo const* /*spell*/) override
{
return ValidateSpellInfo({ SPELL_ICE_TOMB_DAMAGE });
}
void PeriodicTick(AuraEffect const* /*aurEff*/)
{
PreventDefaultAction();
if (Unit* caster = GetCaster())
caster->CastSpell(GetTarget(), SPELL_ICE_TOMB_DAMAGE, true);
}
void Register() override
{
OnEffectPeriodic.Register(&spell_sindragosa_frost_beacon_AuraScript::PeriodicTick, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_sindragosa_frost_beacon_AuraScript();
}
};
class spell_sindragosa_ice_tomb : public SpellScriptLoader
{
public:
spell_sindragosa_ice_tomb() : SpellScriptLoader("spell_sindragosa_ice_tomb_trap") { }
class spell_sindragosa_ice_tomb_AuraScript : public AuraScript
{
bool Validate(SpellInfo const* /*spell*/) override
{
if (!sObjectMgr->GetCreatureTemplate(NPC_ICE_TOMB))
return false;
if (!sObjectMgr->GetGameObjectTemplate(GO_ICE_BLOCK))
return false;
return true;
}
void PeriodicTick(AuraEffect const* aurEff)
{
PreventDefaultAction();
if (aurEff->GetTickNumber() == 1)
{
if (Unit* caster = GetCaster())
{
Position pos = GetTarget()->GetPosition();
if (TempSummon* summon = caster->SummonCreature(NPC_ICE_TOMB, pos))
{
summon->AI()->SetGUID(GetTarget()->GetGUID(), DATA_TRAPPED_PLAYER);
GetTarget()->CastSpell(GetTarget(), SPELL_ICE_TOMB_UNTARGETABLE);
if (GameObject* go = summon->SummonGameObject(GO_ICE_BLOCK, pos, QuaternionData(), 0))
{
go->SetSpellId(SPELL_ICE_TOMB_DAMAGE);
summon->AddGameObject(go);
}
}
}
}
}
void HandleRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
GetTarget()->RemoveAurasDueToSpell(SPELL_ICE_TOMB_UNTARGETABLE);
}
void Register() override
{
OnEffectPeriodic.Register(&spell_sindragosa_ice_tomb_AuraScript::PeriodicTick, EFFECT_2, SPELL_AURA_PERIODIC_TRIGGER_SPELL);
AfterEffectRemove.Register(&spell_sindragosa_ice_tomb_AuraScript::HandleRemove, EFFECT_2, SPELL_AURA_PERIODIC_TRIGGER_SPELL, AURA_EFFECT_HANDLE_REAL);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_sindragosa_ice_tomb_AuraScript();
}
};
class spell_sindragosa_icy_grip : public SpellScriptLoader
{
public:
spell_sindragosa_icy_grip() : SpellScriptLoader("spell_sindragosa_icy_grip") { }
class spell_sindragosa_icy_grip_SpellScript : public SpellScript
{
bool Validate(SpellInfo const* /*spell*/) override
{
return ValidateSpellInfo({ SPELL_ICY_GRIP_JUMP });
}
void HandleScript(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
GetHitUnit()->CastSpell(GetCaster(), SPELL_ICY_GRIP_JUMP, true);
}
void Register() override
{
OnEffectHitTarget.Register(&spell_sindragosa_icy_grip_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_sindragosa_icy_grip_SpellScript();
}
};
class MysticBuffetTargetFilter
{
public:
explicit MysticBuffetTargetFilter(Unit* caster) : _caster(caster) { }
bool operator()(WorldObject* unit) const
{
return !unit->IsWithinLOSInMap(_caster);
}
private:
Unit* _caster;
};
class spell_sindragosa_mystic_buffet : public SpellScriptLoader
{
public:
spell_sindragosa_mystic_buffet() : SpellScriptLoader("spell_sindragosa_mystic_buffet") { }
class spell_sindragosa_mystic_buffet_SpellScript : public SpellScript
{
void FilterTargets(std::list<WorldObject*>& targets)
{
targets.remove_if(MysticBuffetTargetFilter(GetCaster()));
}
void Register() override
{
OnObjectAreaTargetSelect.Register(&spell_sindragosa_mystic_buffet_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_sindragosa_mystic_buffet_SpellScript();
}
};
class spell_rimefang_icy_blast : public SpellScriptLoader
{
public:
spell_rimefang_icy_blast() : SpellScriptLoader("spell_rimefang_icy_blast") { }
class spell_rimefang_icy_blast_SpellScript : public SpellScript
{
bool Validate(SpellInfo const* /*spell*/) override
{
return ValidateSpellInfo({ SPELL_ICY_BLAST_AREA });
}
void HandleTriggerMissile(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
if (Position const* pos = GetExplTargetDest())
if (TempSummon* summon = GetCaster()->SummonCreature(NPC_ICY_BLAST, *pos, TEMPSUMMON_TIMED_DESPAWN, 40000))
summon->CastSpell(summon, SPELL_ICY_BLAST_AREA, true);
}
void Register() override
{
OnEffectHit.Register(&spell_rimefang_icy_blast_SpellScript::HandleTriggerMissile, EFFECT_1, SPELL_EFFECT_TRIGGER_MISSILE);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_rimefang_icy_blast_SpellScript();
}
};
class OrderWhelpTargetSelector
{
public:
explicit OrderWhelpTargetSelector(Creature* owner) : _owner(owner) { }
bool operator()(Creature* creature)
{
if (!creature->AI()->GetData(DATA_WHELP_MARKER) && creature->AI()->GetData(DATA_FROSTWYRM_OWNER) == _owner->AI()->GetData(DATA_FROSTWYRM_OWNER))
return false;
return true;
}
private:
Creature* _owner;
};
class spell_frostwarden_handler_order_whelp : public SpellScriptLoader
{
public:
spell_frostwarden_handler_order_whelp() : SpellScriptLoader("spell_frostwarden_handler_order_whelp") { }
class spell_frostwarden_handler_order_whelp_SpellScript : public SpellScript
{
bool Validate(SpellInfo const* /*spell*/) override
{
return ValidateSpellInfo({ SPELL_FOCUS_FIRE });
}
void FilterTargets(std::list<WorldObject*>& targets)
{
targets.remove_if(Trinity::ObjectTypeIdCheck(TYPEID_PLAYER, false));
if (targets.empty())
return;
WorldObject* target = Trinity::Containers::SelectRandomContainerElement(targets);
targets.clear();
targets.push_back(target);
}
void HandleForcedCast(SpellEffIndex effIndex)
{
// caster is Frostwarden Handler, target is player, caster of triggered is whelp
PreventHitDefaultEffect(effIndex);
std::list<Creature*> unitList;
GetCreatureListWithEntryInGrid(unitList, GetCaster(), NPC_FROSTWING_WHELP, 150.0f);
if (Creature* creature = GetCaster()->ToCreature())
unitList.remove_if(OrderWhelpTargetSelector(creature));
if (unitList.empty())
return;
Trinity::Containers::SelectRandomContainerElement(unitList)->CastSpell(GetHitUnit(), uint32(GetEffectValue()), true);
}
void Register() override
{
OnEffectHitTarget.Register(&spell_frostwarden_handler_order_whelp_SpellScript::HandleForcedCast, EFFECT_0, SPELL_EFFECT_FORCE_CAST);
OnObjectAreaTargetSelect.Register(&spell_frostwarden_handler_order_whelp_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_DEST_AREA_ENEMY);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_frostwarden_handler_order_whelp_SpellScript();
}
};
class spell_frostwarden_handler_focus_fire : public SpellScriptLoader
{
public:
spell_frostwarden_handler_focus_fire() : SpellScriptLoader("spell_frostwarden_handler_focus_fire") { }
class spell_frostwarden_handler_focus_fire_SpellScript : public SpellScript
{
void HandleScript(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
GetCaster()->GetThreatManager().AddThreat(GetHitUnit(), float(GetEffectValue()), GetSpellInfo(), true, true);
GetCaster()->GetAI()->SetData(DATA_WHELP_MARKER, 1);
}
void Register() override
{
OnEffectHitTarget.Register(&spell_frostwarden_handler_focus_fire_SpellScript::HandleScript, EFFECT_1, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
class spell_frostwarden_handler_focus_fire_AuraScript : public AuraScript
{
void PeriodicTick(AuraEffect const* /*aurEff*/)
{
PreventDefaultAction();
if (Unit* caster = GetCaster())
{
caster->GetThreatManager().AddThreat(GetTarget(), -float(GetSpellInfo()->Effects[EFFECT_1].CalcValue()), GetSpellInfo(), true, true);
caster->GetAI()->SetData(DATA_WHELP_MARKER, 0);
}
}
void Register() override
{
OnEffectPeriodic.Register(&spell_frostwarden_handler_focus_fire_AuraScript::PeriodicTick, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_frostwarden_handler_focus_fire_SpellScript();
}
AuraScript* GetAuraScript() const override
{
return new spell_frostwarden_handler_focus_fire_AuraScript();
}
};
class spell_sindragosa_ice_tomb_target : public SpellScriptLoader
{
public:
spell_sindragosa_ice_tomb_target() : SpellScriptLoader("spell_sindragosa_ice_tomb_target") { }
class spell_sindragosa_ice_tomb_target_SpellScript : public SpellScript
{
void FilterTargets(std::list<WorldObject*>& unitList)
{
Unit* caster = GetCaster();
unitList.remove_if(FrostBeaconSelector(caster));
}
void HandleSindragosaTalk(SpellEffIndex /*effIndex*/)
{
if (Creature* creatureCaster = GetCaster()->ToCreature())
if (creatureCaster->GetAI()->GetData(DATA_IS_THIRD_PHASE))
creatureCaster->AI()->Talk(EMOTE_WARN_FROZEN_ORB, GetHitUnit());
}
void Register() override
{
OnObjectAreaTargetSelect.Register(&spell_sindragosa_ice_tomb_target_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY);
OnEffectLaunchTarget.Register(&spell_sindragosa_ice_tomb_target_SpellScript::HandleSindragosaTalk, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_sindragosa_ice_tomb_target_SpellScript();
}
};
class at_sindragosa_lair : public AreaTriggerScript
{
public:
at_sindragosa_lair() : AreaTriggerScript("at_sindragosa_lair") { }
bool OnTrigger(Player* player, AreaTriggerEntry const* /*areaTrigger*/) override
{
if (InstanceScript* instance = player->GetInstanceScript())
{
if (!instance->GetData(DATA_SPINESTALKER))
if (Creature* spinestalker = ObjectAccessor::GetCreature(*player, instance->GetGuidData(DATA_SPINESTALKER)))
spinestalker->AI()->DoAction(ACTION_START_FROSTWYRM);
if (!instance->GetData(DATA_RIMEFANG))
if (Creature* rimefang = ObjectAccessor::GetCreature(*player, instance->GetGuidData(DATA_RIMEFANG)))
rimefang->AI()->DoAction(ACTION_START_FROSTWYRM);
if (!instance->GetData(DATA_SINDRAGOSA_FROSTWYRMS) && !instance->GetGuidData(DATA_SINDRAGOSA) && instance->GetBossState(DATA_SINDRAGOSA) != DONE)
{
player->GetMap()->LoadGrid(SindragosaSpawnPos.GetPositionX(), SindragosaSpawnPos.GetPositionY());
if (Creature* sindragosa = player->GetMap()->SummonCreature(NPC_SINDRAGOSA, SindragosaSpawnPos))
sindragosa->AI()->DoAction(ACTION_START_FROSTWYRM);
}
}
return true;
}
};
class achievement_all_you_can_eat : public AchievementCriteriaScript
{
public:
achievement_all_you_can_eat() : AchievementCriteriaScript("achievement_all_you_can_eat") { }
bool OnCheck(Player* /*source*/, Unit* target) override
{
if (!target)
return false;
return target->GetAI()->GetData(DATA_MYSTIC_BUFFET_STACK) <= 5;
}
};
}
void AddSC_boss_sindragosa()
{
using namespace IcecrownCitadel;
using namespace IcecrownCitadel::Sindragosa;
new boss_sindragosa();
new npc_ice_tomb();
new npc_spinestalker();
new npc_rimefang();
new npc_sindragosa_trash();
new spell_sindragosa_s_fury();
new spell_sindragosa_unchained_magic();
new spell_sindragosa_frost_breath();
new spell_sindragosa_instability();
new spell_sindragosa_frost_beacon();
new spell_sindragosa_ice_tomb();
new spell_sindragosa_icy_grip();
new spell_sindragosa_mystic_buffet();
new spell_rimefang_icy_blast();
new spell_frostwarden_handler_order_whelp();
new spell_frostwarden_handler_focus_fire();
new spell_trigger_spell_from_caster("spell_sindragosa_ice_tomb", SPELL_ICE_TOMB_DUMMY, TRIGGERED_IGNORE_SET_FACING);
new spell_trigger_spell_from_caster("spell_sindragosa_ice_tomb_dummy", SPELL_FROST_BEACON);
new spell_sindragosa_ice_tomb_target();
new at_sindragosa_lair();
new achievement_all_you_can_eat();
}
| 0 | 0.963423 | 1 | 0.963423 | game-dev | MEDIA | 0.986149 | game-dev | 0.810893 | 1 | 0.810893 |
luciusDXL/TheForceEngine | 19,102 | TheForceEngine/TFE_DarkForces/GameUI/agentMenu.cpp | #include <cstring>
#include "agentMenu.h"
#include "editBox.h"
#include "delt.h"
#include "menu.h"
#include "uiDraw.h"
#include <TFE_FrontEndUI/frontEndUi.h>
#include <TFE_DarkForces/agent.h>
#include <TFE_DarkForces/util.h>
#include <TFE_DarkForces/Landru/lcanvas.h>
#include <TFE_Archive/archive.h>
#include <TFE_Settings/settings.h>
#include <TFE_Input/input.h>
#include <TFE_RenderBackend/renderBackend.h>
#include <TFE_Jedi/Math/core_math.h>
#include <TFE_Jedi/Level/rtexture.h>
#include <TFE_System/system.h>
#include <TFE_Jedi/Renderer/virtualFramebuffer.h>
using namespace TFE_Jedi;
namespace TFE_DarkForces
{
///////////////////////////////////////////
// Constants
///////////////////////////////////////////
enum AgentMenuButtons
{
AGENT_NEW,
AGENT_REMOVE,
AGENT_EXIT,
AGENT_BEGIN,
AGENT_COUNT
};
static const Vec2i c_agentButtons[AGENT_COUNT] =
{
{21, 165}, // AGENT_NEW
{90, 165}, // AGENT_REMOVE
{164, 165}, // AGENT_EXIT
{239, 165}, // AGENT_BEGIN
};
static const Vec2i c_agentButtonDim = { 60, 25 };
enum NewAgentDlg
{
NEW_AGENT_NO,
NEW_AGENT_YES,
NEW_AGENT_COUNT
};
static const Vec2i c_newAgentButtons[NEW_AGENT_COUNT] =
{
{167, 107}, // NEW_AGENT_NO
{206, 107}, // NEW_AGENT_YES
};
static const Vec2i c_newAgentButtonDim = { 28, 15 };
///////////////////////////////////////////
// Internal State
///////////////////////////////////////////
static JBool s_loaded = JFALSE;
static JBool s_displayInit = JFALSE;
static u8* s_framebuffer = nullptr;
static s32 s_selectedMission = 0;
static s32 s_editCursorFlicker = 0;
static s32 s_agentCount = 0;
static JBool s_lastSelectedAgent = JTRUE;
static JBool s_newAgentDlg = JFALSE;
static JBool s_removeAgentDlg = JFALSE;
static JBool s_quitConfirmDlg = JFALSE;
static JBool s_missionBegin = JFALSE;
static EditBox s_editBox = {};
static u8 s_menuPalette[768];
static DeltFrame* s_agentMenuFrames;
static DeltFrame* s_agentDlgFrames;
static u32 s_agentMenuCount;
static u32 s_agentDlgCount;
static char s_newAgentName[32];
static LangHotkeys* s_langKeys;
///////////////////////////////////////////
// Forward Declarations
///////////////////////////////////////////
void agentMenu_startup();
void agentMenu_startupDisplay();
void agentMenu_blit();
void agentMenu_update();
void agentMenu_draw();
void drawYesNoDlg(s32 baseFrame);
void drawNewAgentDlg();
void updateNewAgentDlg();
void updateRemoveAgentDlg();
JBool updateQuitConfirmDlg();
///////////////////////////////////////////
// API Implementation
///////////////////////////////////////////
void agentMenu_resetState()
{
s_loaded = JFALSE;
s_displayInit = JFALSE;
s_agentMenuFrames = nullptr;
s_agentDlgFrames = nullptr;
s_framebuffer = nullptr;
delt_resetState();
}
JBool agentMenu_update(s32* levelIndex)
{
if (!s_loaded)
{
menu_init();
agentMenu_startup();
s_loaded = JTRUE;
}
if (!s_displayInit)
{
agentMenu_startupDisplay();
s_missionBegin = JFALSE;
s_displayInit = JTRUE;
}
// Update the mouse position.
menu_handleMousePosition();
agentMenu_update();
agentMenu_draw();
agentMenu_blit();
// Reset for next time.
if (s_missionBegin)
{
s_displayInit = JFALSE;
vfb_forceToBlack();
lcanvas_clear();
assert(s_selectedMission >= 0 && s_selectedMission <= MAX_LEVEL_COUNT - 1);
s_selectedMission = clamp(s_selectedMission, 0, MAX_LEVEL_COUNT - 1);
}
*levelIndex = s_selectedMission + 1;
return ~s_missionBegin;
}
///////////////////////////////////////////
// Internal Implementation
///////////////////////////////////////////
void agentMenu_update()
{
if (s_newAgentDlg)
{
updateNewAgentDlg();
return;
}
else if (s_removeAgentDlg)
{
updateRemoveAgentDlg();
return;
}
else if (s_quitConfirmDlg)
{
if (updateQuitConfirmDlg())
{
if (TFE_Settings::getSystemSettings()->gameQuitExitsToMenu)
{
TFE_FrontEndUI::exitToMenu();
}
else
{
TFE_System::postQuitMessage();
}
}
return;
}
if (s_selectedMission < 0)
{
assert(0); // This shouldn't happen.
s_selectedMission = 0;
}
else if (s_selectedMission >= s_maxLevelIndex)
{
s_selectedMission = max(0, s_maxLevelIndex - 1);
}
const s32 x = s_cursorPos.x;
const s32 z = s_cursorPos.z;
if (TFE_Input::mousePressed(MBUTTON_LEFT))
{
s_buttonPressed = -1;
for (u32 i = 0; i < AGENT_COUNT; i++)
{
if (x >= c_agentButtons[i].x && x < c_agentButtons[i].x + c_agentButtonDim.x &&
z >= c_agentButtons[i].z && z < c_agentButtons[i].z + c_agentButtonDim.z)
{
s_buttonPressed = s32(i);
s_buttonHover = JTRUE;
break;
}
}
if (s_buttonPressed < 0)
{
if (x >= 25 && x < 122 && z >= 35 && z < 147 && s_agentCount > 0)
{
s_agentId = clamp((z - 35) / 8, 0, (s32)s_agentCount - 1);
s_selectedMission = max(0, s_agentData[s_agentId].selectedMission - 1);
s_lastSelectedAgent = true;
}
else if (x >= 171 && x < 290 && z >= 35 && z < 147 && s_agentCount > 0)
{
s_selectedMission = clamp((z - 35) / 8, 0, (s32)s_agentData[s_agentId].nextMission - 1);
s_agentData[s_agentId].selectedMission = s_selectedMission + 1;
s_lastSelectedAgent = false;
}
}
}
else if (TFE_Input::mouseDown(MBUTTON_LEFT) && s_buttonPressed >= 0)
{
// Verify that the mouse is still over the button.
if (x >= c_agentButtons[s_buttonPressed].x && x < c_agentButtons[s_buttonPressed].x + c_agentButtonDim.x &&
z >= c_agentButtons[s_buttonPressed].z && z < c_agentButtons[s_buttonPressed].z + c_agentButtonDim.z)
{
s_buttonHover = true;
}
else
{
s_buttonHover = false;
}
}
else
{
if (TFE_Input::keyPressed(KEY_N))
{
s_buttonPressed = AGENT_NEW;
s_buttonHover = JTRUE;
}
else if (TFE_Input::keyPressed(s_langKeys->k_agdel))
{
s_buttonPressed = AGENT_REMOVE;
s_buttonHover = JTRUE;
}
else if (TFE_Input::keyPressed(KEY_D)) // DOS
{
s_buttonPressed = AGENT_EXIT;
s_buttonHover = JTRUE;
}
else if (TFE_Input::keyPressed(s_langKeys->k_begin) || TFE_Input::keyPressed(KEY_RETURN) || TFE_Input::keyPressed(KEY_KP_ENTER))
{
s_buttonPressed = AGENT_BEGIN;
s_buttonHover = JTRUE;
}
// Arrow keys to change the selected agent or mission.
if (TFE_Input::bufferedKeyDown(KEY_DOWN))
{
if (s_lastSelectedAgent && s_agentCount > 0)
{
s_agentId++;
if (s_agentId >= (s32)s_agentCount) { s_agentId = 0; }
if (s_agentId >= 0) { s_selectedMission = s_agentData[s_agentId].selectedMission - 1; }
}
else if (!s_lastSelectedAgent && s_agentId >= 0 && s_agentData[s_agentId].nextMission > 1)
{
s_selectedMission++;
if (s_selectedMission > s_agentData[s_agentId].nextMission - 1 || s_selectedMission == 14) { s_selectedMission = 0; }
}
}
else if (TFE_Input::bufferedKeyDown(KEY_UP))
{
if (s_lastSelectedAgent && s_agentCount > 0)
{
s_agentId--;
if (s_agentId < 0) { s_agentId = s_agentCount - 1; }
if (s_agentId >= 0) { s_selectedMission = s_agentData[s_agentId].selectedMission - 1; }
}
else if (!s_lastSelectedAgent && s_agentId >= 0 && s_agentData[s_agentId].nextMission > 1)
{
s_selectedMission--;
if (s_selectedMission < 0) { s_selectedMission = s_agentData[s_agentId].nextMission - 1; }
}
}
else if (TFE_Input::bufferedKeyDown(KEY_LEFT) || TFE_Input::bufferedKeyDown(KEY_RIGHT))
{
s_lastSelectedAgent = !s_lastSelectedAgent;
}
if (s_buttonPressed >= AGENT_NEW && s_buttonHover)
{
switch (s_buttonPressed)
{
case AGENT_NEW:
{
s_newAgentDlg = JTRUE;
memset(s_newAgentName, 0, 32);
s_editBox.cursor = 0;
s_editBox.inputField = s_newAgentName;
s_editBox.maxLen = 16;
} break;
case AGENT_REMOVE:
s_removeAgentDlg = JTRUE;
break;
case AGENT_EXIT:
s_quitConfirmDlg = JTRUE;
break;
case AGENT_BEGIN:
if (s_agentCount > 0 && s_selectedMission >= 0)
{
s_missionBegin = JTRUE;
}
break;
};
}
// Reset.
s_buttonPressed = -1;
s_buttonHover = JFALSE;
}
}
void agentMenu_draw()
{
memset(s_framebuffer, 0, 320 * 200);
blitDeltaFrame(&s_agentMenuFrames[0], 0, 0, s_framebuffer);
// Draw the buttons
for (s32 i = 0; i < 4; i++)
{
s32 index;
if (s_newAgentDlg)
{
if (i == 0) { index = i * 2 + 1; }
else { index = i * 2 + 2; }
}
else if (s_removeAgentDlg)
{
if (i == 1) { index = i * 2 + 1; }
else { index = i * 2 + 2; }
}
else if (s_quitConfirmDlg)
{
if (i == 2) { index = i * 2 + 1; }
else { index = i * 2 + 2; }
}
else
{
if (s_buttonPressed == i && s_buttonHover) { index = i * 2 + 1; }
else { index = i * 2 + 2; }
}
blitDeltaFrame(&s_agentMenuFrames[index], 0, 0, s_framebuffer);
}
// 11 = easy, 12 = medium, 13 = hard
s32 yOffset = -20;
s32 textX = 174;
s32 textY = 36;
u8 color = 47;
if (s_agentId >= 0 && s_agentCount > 0)
{
s32 nextMission = min(s_agentData[s_agentId].nextMission, s_maxLevelIndex);
for (s32 i = 0; i < nextMission - 1 && i < s_maxLevelIndex; i++)
{
color = 47;
if (s_selectedMission == i)
{
color = 32;
drawColoredQuad(textX - 3, textY - 1, 118, 9, s_lastSelectedAgent ? 13 : 12, s_framebuffer);
}
print(s_levelDisplayNames[i], textX, textY, color, s_framebuffer);
s32 diff = s_agentData[s_agentId].completed[i] + 11;
blitDeltaFrame(&s_agentMenuFrames[diff], 0, yOffset, s_framebuffer);
yOffset += 8;
textY += 8;
}
color = 47;
if (s_selectedMission == nextMission - 1)
{
color = 32;
drawColoredQuad(textX - 3, textY - 1, 118, 9, s_lastSelectedAgent ? 13 : 12, s_framebuffer);
}
print(s_levelDisplayNames[nextMission - 1], textX, textY, color, s_framebuffer);
// Show final level complete.
if (s_agentData[s_agentId].nextMission > s_maxLevelIndex)
{
yOffset = -20 + 8 * (s_maxLevelIndex - 1);
s32 diff = s_agentData[s_agentId].completed[s_maxLevelIndex-1] + 11;
blitDeltaFrame(&s_agentMenuFrames[diff], 0, yOffset, s_framebuffer);
}
}
// Draw agents.
textX = 28;
textY = 36;
for (s32 i = 0; i < s_agentCount; i++)
{
color = 47;
if (s_agentId == i)
{
color = 32;
drawColoredQuad(textX - 3, textY - 1, 118, 9, s_lastSelectedAgent ? 12 : 13, s_framebuffer);
}
print(s_agentData[i].name, textX, textY, color, s_framebuffer);
textY += 8;
}
if (s_newAgentDlg)
{
drawNewAgentDlg();
}
else if (s_removeAgentDlg)
{
drawYesNoDlg(0);
}
else if (s_quitConfirmDlg)
{
drawYesNoDlg(1);
}
}
void setPalette()
{
// Update the palette.
u32 palette[256];
u32* outColor = palette;
u8* srcColor = s_menuPalette;
for (s32 i = 0; i < 256; i++, outColor++, srcColor += 3)
{
*outColor = u32(srcColor[0]) | (u32(srcColor[1]) << 8u) | (u32(srcColor[2]) << 16u) | (0xffu << 24u);
}
vfb_setPalette(palette);
}
// TFE Specific.
void agentMenu_startupDisplay()
{
s_framebuffer = menu_startupDisplay();
menu_resetCursor();
setPalette();
}
void agentMenu_load(LangHotkeys* langKeys)
{
FilePath filePath;
if (!TFE_Paths::getFilePath("AGENTMNU.LFD", &filePath)) { return; }
Archive* archive = Archive::getArchive(ARCHIVE_LFD, "AGENTMNU", filePath.path);
TFE_Paths::addLocalArchive(archive);
loadPaletteFromPltt("agentmnu.pltt", s_menuPalette);
s_agentMenuCount = getFramesFromAnim("agentmnu.anim", &s_agentMenuFrames);
s_agentDlgCount = getFramesFromAnim("agentdlg.anim", &s_agentDlgFrames);
getFrameFromDelt("cursor.delt", &s_cursor);
TFE_Paths::removeLastArchive();
s_langKeys = langKeys;
}
void agentMenu_startup()
{
s_agentCount = 0;
for (s32 i = 0; i < MAX_AGENT_COUNT; i++)
{
if (!s_agentData[i].name[0])
{
break;
}
s_agentCount++;
}
// Clear out extra data.
for (s32 i = s_agentCount; i < MAX_AGENT_COUNT; i++)
{
memset(&s_agentData[i], 0, sizeof(AgentData));
}
if (s_agentCount > 0)
{
s_agentId = 0;
s_selectedMission = max(0, s_agentData[s_agentId].selectedMission - 1);
}
else
{
s_agentId = -1;
s_selectedMission = 0;
}
s_missionBegin = JFALSE;
}
void agentMenu_blit()
{
setPalette();
menu_blitCursor(s_cursorPos.x, s_cursorPos.z, s_framebuffer);
menu_blitToScreen(s_framebuffer);
}
void agentMenu_setAgentName(const char* name)
{
if (s_agentId < 0 || s_agentId >= MAX_AGENT_COUNT)
{
return;
}
strncpy(s_agentData[s_agentId].name, name, 32);
}
s32 agentMenu_getAgentID()
{
return s_agentId;
}
void agentMenu_setAgentId(s32 id)
{
s_agentId = id;
}
void agentMenu_setAgentCount(s32 count)
{
s_agentCount = count;
}
s32 agentMenu_getAgentCount()
{
return s_agentCount;
}
void agentMenu_createNewAgent()
{
if (s_agentCount < MAX_AGENT_COUNT)
{
s_agentId = s_agentCount;
s_agentCount++;
agent_createNewAgent(s_agentId, &s_agentData[s_agentId], s_newAgentName);
s_selectedMission = 0;
}
}
void agentMenu_removeAgent(s32 index)
{
if (s_agentCount < 1)
{
return;
}
for (s32 i = index; i < (s32)s_agentCount; i++)
{
s_agentData[i] = s_agentData[i + 1];
}
s_agentCount--;
memset(&s_agentData[s_agentCount], 0, sizeof(AgentData));
s_agentId = s_agentCount > 0 ? 0 : -1;
s_selectedMission = s_agentCount > 0 ? s_agentData[0].selectedMission : 0;
}
// UI routines.
void drawYesNoButtons(u32 indexNo, u32 indexYes)
{
if (s_buttonPressed == 0 && s_buttonHover)
{
blitDeltaFrame(&s_agentDlgFrames[indexNo], 0, 0, s_framebuffer);
}
else if (s_buttonPressed == 1 && s_buttonHover)
{
blitDeltaFrame(&s_agentDlgFrames[indexYes], 0, 0, s_framebuffer);
}
}
void drawYesNoDlg(s32 baseFrame)
{
blitDeltaFrame(&s_agentDlgFrames[baseFrame], 0, 0, s_framebuffer);
drawYesNoButtons(4, 6);
}
void drawNewAgentDlg()
{
blitDeltaFrame(&s_agentDlgFrames[2], 0, 0, s_framebuffer);
drawEditBox(&s_editBox, 106, 87, 216, 100, s_framebuffer);
drawYesNoButtons(8, 10);
}
void updateNewAgentDlg()
{
updateEditBox(&s_editBox);
if (TFE_Input::keyPressed(KEY_RETURN) || TFE_Input::keyPressed(KEY_KP_ENTER))
{
agentMenu_createNewAgent();
s_newAgentDlg = JFALSE;
return;
}
else if (TFE_Input::keyPressed(KEY_ESCAPE))
{
s_newAgentDlg = JFALSE;
return;
}
if (TFE_Input::mousePressed(MBUTTON_LEFT))
{
s_buttonPressed = -1;
for (u32 i = 0; i < NEW_AGENT_COUNT; i++)
{
if (s_cursorPos.x >= c_newAgentButtons[i].x && s_cursorPos.x < c_newAgentButtons[i].x + c_newAgentButtonDim.x &&
s_cursorPos.z >= c_newAgentButtons[i].z && s_cursorPos.z < c_newAgentButtons[i].z + c_newAgentButtonDim.z)
{
s_buttonPressed = s32(i);
s_buttonHover = true;
break;
}
}
}
else if (TFE_Input::mouseDown(MBUTTON_LEFT) && s_buttonPressed >= 0)
{
// Verify that the mouse is still over the button.
if (s_cursorPos.x >= c_newAgentButtons[s_buttonPressed].x && s_cursorPos.x < c_newAgentButtons[s_buttonPressed].x + c_newAgentButtonDim.x &&
s_cursorPos.z >= c_newAgentButtons[s_buttonPressed].z && s_cursorPos.z < c_newAgentButtons[s_buttonPressed].z + c_newAgentButtonDim.z)
{
s_buttonHover = true;
}
else
{
s_buttonHover = false;
}
}
else
{
// Activate button 's_escButtonPressed'
if (s_buttonPressed >= NEW_AGENT_NO && s_buttonHover)
{
if (s_buttonPressed == NEW_AGENT_YES)
{
agentMenu_createNewAgent();
}
s_newAgentDlg = JFALSE;
}
// Reset.
s_buttonPressed = -1;
s_buttonHover = false;
}
}
void updateRemoveAgentDlg()
{
if (TFE_Input::keyPressed(KEY_RETURN) || TFE_Input::keyPressed(KEY_KP_ENTER) || TFE_Input::keyPressed(KEY_ESCAPE))
{
s_removeAgentDlg = false;
return;
}
if (TFE_Input::mousePressed(MBUTTON_LEFT))
{
s_buttonPressed = -1;
for (u32 i = 0; i < NEW_AGENT_COUNT; i++)
{
if (s_cursorPos.x >= c_newAgentButtons[i].x && s_cursorPos.x < c_newAgentButtons[i].x + c_newAgentButtonDim.x &&
s_cursorPos.z >= c_newAgentButtons[i].z && s_cursorPos.z < c_newAgentButtons[i].z + c_newAgentButtonDim.z)
{
s_buttonPressed = s32(i);
s_buttonHover = true;
break;
}
}
}
else if (TFE_Input::mouseDown(MBUTTON_LEFT) && s_buttonPressed >= 0)
{
// Verify that the mouse is still over the button.
if (s_cursorPos.x >= c_newAgentButtons[s_buttonPressed].x && s_cursorPos.x < c_newAgentButtons[s_buttonPressed].x + c_newAgentButtonDim.x &&
s_cursorPos.z >= c_newAgentButtons[s_buttonPressed].z && s_cursorPos.z < c_newAgentButtons[s_buttonPressed].z + c_newAgentButtonDim.z)
{
s_buttonHover = true;
}
else
{
s_buttonHover = false;
}
}
else
{
if (TFE_Input::keyPressed(s_langKeys->k_yes))
{
agentMenu_removeAgent(s_agentId);
s_removeAgentDlg = false;
}
else if (TFE_Input::keyPressed(KEY_N))
{
s_removeAgentDlg = false;
}
else if (s_buttonPressed >= NEW_AGENT_NO && s_buttonHover)
{
if (s_buttonPressed == NEW_AGENT_YES)
{
agentMenu_removeAgent(s_agentId);
}
s_removeAgentDlg = false;
}
// Reset.
s_buttonPressed = -1;
s_buttonHover = false;
}
}
JBool updateQuitConfirmDlg()
{
JBool quit = JFALSE;
if (TFE_Input::keyPressed(KEY_ESCAPE))
{
s_quitConfirmDlg = JFALSE;
return JFALSE;
}
else if (TFE_Input::keyPressed(KEY_RETURN) || TFE_Input::keyPressed(KEY_KP_ENTER))
{
s_quitConfirmDlg = JFALSE;
return JTRUE;
}
if (TFE_Input::mousePressed(MBUTTON_LEFT))
{
s_buttonPressed = -1;
for (u32 i = 0; i < NEW_AGENT_COUNT; i++)
{
if (s_cursorPos.x >= c_newAgentButtons[i].x && s_cursorPos.x < c_newAgentButtons[i].x + c_newAgentButtonDim.x &&
s_cursorPos.z >= c_newAgentButtons[i].z && s_cursorPos.z < c_newAgentButtons[i].z + c_newAgentButtonDim.z)
{
s_buttonPressed = s32(i);
s_buttonHover = JTRUE;
break;
}
}
}
else if (TFE_Input::mouseDown(MBUTTON_LEFT) && s_buttonPressed >= 0)
{
// Verify that the mouse is still over the button.
if (s_cursorPos.x >= c_newAgentButtons[s_buttonPressed].x && s_cursorPos.x < c_newAgentButtons[s_buttonPressed].x + c_newAgentButtonDim.x &&
s_cursorPos.z >= c_newAgentButtons[s_buttonPressed].z && s_cursorPos.z < c_newAgentButtons[s_buttonPressed].z + c_newAgentButtonDim.z)
{
s_buttonHover = JTRUE;
}
else
{
s_buttonHover = JFALSE;
}
}
else
{
// Activate button 's_escButtonPressed'
if (TFE_Input::keyPressed(s_langKeys->k_yes))
{
quit = JTRUE;
s_quitConfirmDlg = JFALSE;
}
else if (TFE_Input::keyPressed(KEY_N))
{
s_quitConfirmDlg = JFALSE;
}
else if (s_buttonPressed >= NEW_AGENT_NO && s_buttonHover)
{
if (s_buttonPressed == NEW_AGENT_YES)
{
quit = JTRUE;
}
s_quitConfirmDlg = JFALSE;
}
// Reset.
s_buttonPressed = -1;
s_buttonHover = false;
}
return quit;
}
} | 0 | 0.868937 | 1 | 0.868937 | game-dev | MEDIA | 0.609866 | game-dev | 0.982862 | 1 | 0.982862 |
LeoMinecraftModding/eternal-starlight | 3,393 | common/src/main/java/cn/leolezury/eternalstarlight/common/world/gen/feature/tree/DeadLunarTreeFeature.java | package cn.leolezury.eternalstarlight.common.world.gen.feature.tree;
import cn.leolezury.eternalstarlight.common.registry.ESBlocks;
import cn.leolezury.eternalstarlight.common.util.ESMathUtil;
import com.mojang.serialization.Codec;
import net.minecraft.core.BlockPos;
import net.minecraft.util.Mth;
import net.minecraft.util.RandomSource;
import net.minecraft.util.random.SimpleWeightedRandomList;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.feature.Feature;
import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration;
import net.minecraft.world.level.levelgen.feature.stateproviders.WeightedStateProvider;
import net.minecraft.world.phys.Vec3;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class DeadLunarTreeFeature extends Feature<NoneFeatureConfiguration> {
public DeadLunarTreeFeature(Codec<NoneFeatureConfiguration> codec) {
super(codec);
}
private BlockState getBlockToPlace(RandomSource randomSource, BlockPos pos) {
WeightedStateProvider stateProvider = new WeightedStateProvider(SimpleWeightedRandomList.<BlockState>builder().add(ESBlocks.DEAD_LUNAR_LOG.get().defaultBlockState(), 10).add(ESBlocks.RED_CRYSTALLIZED_LUNAR_LOG.get().defaultBlockState(), 1).add(ESBlocks.BLUE_CRYSTALLIZED_LUNAR_LOG.get().defaultBlockState(), 1).build());
return stateProvider.getState(randomSource, pos);
}
private void placeBlockLine(BlockPos from, BlockPos to, Consumer<BlockPos> placer) {
List<int[]> points = ESMathUtil.getBresenham3DPoints(from.getX(), from.getY(), from.getZ(), to.getX(), to.getY(), to.getZ());
for (int[] point : points) {
BlockPos trunkPos = new BlockPos(point[0], point[1], point[2]);
placer.accept(trunkPos);
}
}
private void placeBranches(BlockPos pos, RandomSource random, Consumer<BlockPos> placer) {
int num = random.nextInt(3, 6);
int len = random.nextInt(5, 8);
for (int i = 0; i < num; i++) {
Vec3 endVec = ESMathUtil.rotationToPosition(pos.getCenter(), len, 40, (360f / (float) num) * i);
BlockPos endPos = new BlockPos((int) endVec.x, (int) endVec.y, (int) endVec.z);
placeBlockLine(pos, endPos, placer);
}
}
@Override
public boolean place(FeaturePlaceContext<NoneFeatureConfiguration> context) {
WorldGenLevel level = context.level();
BlockPos pos = context.origin();
RandomSource random = context.random();
List<BlockPos> blocksToPlace = new ArrayList<>();
// make a trunk
BlockPos topPos = pos.offset(random.nextInt(5) - 2, random.nextInt(10, 15), random.nextInt(5) - 2);
placeBlockLine(pos, topPos, blocksToPlace::add);
// make branches
placeBranches(topPos, random, blocksToPlace::add);
placeBranches(new BlockPos(Mth.lerpInt(0.75f, pos.getX(), topPos.getX()), Mth.lerpInt(0.75f, pos.getY(), topPos.getY()), Mth.lerpInt(0.75f, pos.getZ(), topPos.getZ())), random, blocksToPlace::add);
for (BlockPos blockPos : blocksToPlace) {
if (!level.isEmptyBlock(blockPos) && level.getBlockState(blockPos).getBlock() != Blocks.WATER) {
return false;
}
}
for (BlockPos blockPos : blocksToPlace) {
setBlock(level, blockPos, getBlockToPlace(random, blockPos));
}
return true;
}
}
| 0 | 0.886686 | 1 | 0.886686 | game-dev | MEDIA | 0.99545 | game-dev | 0.96757 | 1 | 0.96757 |
Rtyper/LipSync-Pro | 2,561 | Project/Assets/Rogo Digital/LipSync Pro/Editor/Modals/SetIntensityWindow.cs | using UnityEngine;
using UnityEditor;
using RogoDigital;
public class SetIntensityWindow : ModalWindow {
private LipSyncClipSetup setup;
private AnimationCurve remapCurve = new AnimationCurve();
private bool advanced;
void OnEnable () {
remapCurve.AddKey(0, 0);
remapCurve.AddKey(1, 1);
}
void OnGUI () {
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUILayout.Space(10);
EditorGUILayout.HelpBox("This window will be deprecated in favour of the 'Set Intensity From Volume' AutoSync module in a future version. It is still functional for now.", MessageType.Warning);
GUILayout.Space(10);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Space(10);
EditorGUILayout.HelpBox("Depending on your audio, you may want phoneme intensities to be influenced differently by audio volume. This curve can be used to remap audio volume (x) to phoneme intensity (y). It is set to linear by default.", MessageType.Info);
GUILayout.Space(10);
GUILayout.EndHorizontal();
GUILayout.Space(15);
remapCurve = EditorGUILayout.CurveField("Remap Curve", remapCurve, Color.yellow, new Rect(0, 0, 1, 1));
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Accept", GUILayout.MinWidth(100), GUILayout.Height(20))) {
Begin();
Close();
}
GUILayout.Space(10);
if (GUILayout.Button("Cancel", GUILayout.MinWidth(100), GUILayout.Height(20))) {
Close();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(10);
}
void Begin () {
for (int m = 0; m < setup.PhonemeData.Count; m++) {
setup.PhonemeData[m].intensity = remapCurve.Evaluate(GetRMS(4096, Mathf.RoundToInt(setup.PhonemeData[m].time * setup.Clip.samples)));
}
setup.changed = true;
setup.previewOutOfDate = true;
}
float GetRMS (int samples, int offset) {
float[] sampleData = new float[samples];
setup.Clip.GetData(sampleData, offset); // fill array with samples
float sum = 0;
for (int i = 0; i < samples; i++) {
sum += sampleData[i] * sampleData[i]; // sum squared samples
}
return Mathf.Sqrt(sum / samples); // rms = square root of average
}
public static void CreateWindow (ModalParent parent, LipSyncClipSetup setup) {
SetIntensityWindow window = CreateInstance<SetIntensityWindow>();
window.position = new Rect(parent.center.x - 250, parent.center.y - 75, 500, 150);
window.minSize = new Vector2(500, 150);
window.titleContent = new GUIContent("Set Intensities");
window.setup = setup;
window.Show(parent);
}
}
| 0 | 0.819724 | 1 | 0.819724 | game-dev | MEDIA | 0.454635 | game-dev,desktop-app | 0.940662 | 1 | 0.940662 |
dronefleet/mavlink | 18,959 | src/main/java-gen/io/dronefleet/mavlink/common/SetPositionTargetLocalNed.java | package io.dronefleet.mavlink.common;
import io.dronefleet.mavlink.annotations.MavlinkFieldInfo;
import io.dronefleet.mavlink.annotations.MavlinkMessageBuilder;
import io.dronefleet.mavlink.annotations.MavlinkMessageInfo;
import io.dronefleet.mavlink.util.EnumValue;
import java.lang.Enum;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.util.Collection;
import java.util.Objects;
/**
* Sets a desired vehicle position in a local north-east-down coordinate frame. Used by an
* external controller to command the vehicle (manual controller or other system).
*/
@MavlinkMessageInfo(
id = 84,
crc = 143,
description = "Sets a desired vehicle position in a local north-east-down coordinate frame. Used by an external controller to command the vehicle (manual controller or other system)."
)
public final class SetPositionTargetLocalNed {
private final long timeBootMs;
private final int targetSystem;
private final int targetComponent;
private final EnumValue<MavFrame> coordinateFrame;
private final EnumValue<PositionTargetTypemask> typeMask;
private final float x;
private final float y;
private final float z;
private final float vx;
private final float vy;
private final float vz;
private final float afx;
private final float afy;
private final float afz;
private final float yaw;
private final float yawRate;
private SetPositionTargetLocalNed(long timeBootMs, int targetSystem, int targetComponent,
EnumValue<MavFrame> coordinateFrame, EnumValue<PositionTargetTypemask> typeMask,
float x, float y, float z, float vx, float vy, float vz, float afx, float afy,
float afz, float yaw, float yawRate) {
this.timeBootMs = timeBootMs;
this.targetSystem = targetSystem;
this.targetComponent = targetComponent;
this.coordinateFrame = coordinateFrame;
this.typeMask = typeMask;
this.x = x;
this.y = y;
this.z = z;
this.vx = vx;
this.vy = vy;
this.vz = vz;
this.afx = afx;
this.afy = afy;
this.afz = afz;
this.yaw = yaw;
this.yawRate = yawRate;
}
/**
* Returns a builder instance for this message.
*/
@MavlinkMessageBuilder
public static Builder builder() {
return new Builder();
}
/**
* Timestamp (time since system boot).
*/
@MavlinkFieldInfo(
position = 1,
unitSize = 4,
description = "Timestamp (time since system boot)."
)
public final long timeBootMs() {
return this.timeBootMs;
}
/**
* System ID
*/
@MavlinkFieldInfo(
position = 2,
unitSize = 1,
description = "System ID"
)
public final int targetSystem() {
return this.targetSystem;
}
/**
* Component ID
*/
@MavlinkFieldInfo(
position = 3,
unitSize = 1,
description = "Component ID"
)
public final int targetComponent() {
return this.targetComponent;
}
/**
* Valid options are: MAV_FRAME_LOCAL_NED = 1, MAV_FRAME_LOCAL_OFFSET_NED = 7,
* MAV_FRAME_BODY_NED = 8, MAV_FRAME_BODY_OFFSET_NED = 9
*/
@MavlinkFieldInfo(
position = 4,
unitSize = 1,
enumType = MavFrame.class,
description = "Valid options are: MAV_FRAME_LOCAL_NED = 1, MAV_FRAME_LOCAL_OFFSET_NED = 7, MAV_FRAME_BODY_NED = 8, MAV_FRAME_BODY_OFFSET_NED = 9"
)
public final EnumValue<MavFrame> coordinateFrame() {
return this.coordinateFrame;
}
/**
* Bitmap to indicate which dimensions should be ignored by the vehicle.
*/
@MavlinkFieldInfo(
position = 5,
unitSize = 2,
enumType = PositionTargetTypemask.class,
description = "Bitmap to indicate which dimensions should be ignored by the vehicle."
)
public final EnumValue<PositionTargetTypemask> typeMask() {
return this.typeMask;
}
/**
* X Position in NED frame
*/
@MavlinkFieldInfo(
position = 6,
unitSize = 4,
description = "X Position in NED frame"
)
public final float x() {
return this.x;
}
/**
* Y Position in NED frame
*/
@MavlinkFieldInfo(
position = 7,
unitSize = 4,
description = "Y Position in NED frame"
)
public final float y() {
return this.y;
}
/**
* Z Position in NED frame (note, altitude is negative in NED)
*/
@MavlinkFieldInfo(
position = 8,
unitSize = 4,
description = "Z Position in NED frame (note, altitude is negative in NED)"
)
public final float z() {
return this.z;
}
/**
* X velocity in NED frame
*/
@MavlinkFieldInfo(
position = 9,
unitSize = 4,
description = "X velocity in NED frame"
)
public final float vx() {
return this.vx;
}
/**
* Y velocity in NED frame
*/
@MavlinkFieldInfo(
position = 10,
unitSize = 4,
description = "Y velocity in NED frame"
)
public final float vy() {
return this.vy;
}
/**
* Z velocity in NED frame
*/
@MavlinkFieldInfo(
position = 11,
unitSize = 4,
description = "Z velocity in NED frame"
)
public final float vz() {
return this.vz;
}
/**
* X acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N
*/
@MavlinkFieldInfo(
position = 12,
unitSize = 4,
description = "X acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N"
)
public final float afx() {
return this.afx;
}
/**
* Y acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N
*/
@MavlinkFieldInfo(
position = 13,
unitSize = 4,
description = "Y acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N"
)
public final float afy() {
return this.afy;
}
/**
* Z acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N
*/
@MavlinkFieldInfo(
position = 14,
unitSize = 4,
description = "Z acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N"
)
public final float afz() {
return this.afz;
}
/**
* yaw setpoint
*/
@MavlinkFieldInfo(
position = 15,
unitSize = 4,
description = "yaw setpoint"
)
public final float yaw() {
return this.yaw;
}
/**
* yaw rate setpoint
*/
@MavlinkFieldInfo(
position = 16,
unitSize = 4,
description = "yaw rate setpoint"
)
public final float yawRate() {
return this.yawRate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !getClass().equals(o.getClass())) return false;
SetPositionTargetLocalNed other = (SetPositionTargetLocalNed)o;
if (!Objects.deepEquals(timeBootMs, other.timeBootMs)) return false;
if (!Objects.deepEquals(targetSystem, other.targetSystem)) return false;
if (!Objects.deepEquals(targetComponent, other.targetComponent)) return false;
if (!Objects.deepEquals(coordinateFrame, other.coordinateFrame)) return false;
if (!Objects.deepEquals(typeMask, other.typeMask)) return false;
if (!Objects.deepEquals(x, other.x)) return false;
if (!Objects.deepEquals(y, other.y)) return false;
if (!Objects.deepEquals(z, other.z)) return false;
if (!Objects.deepEquals(vx, other.vx)) return false;
if (!Objects.deepEquals(vy, other.vy)) return false;
if (!Objects.deepEquals(vz, other.vz)) return false;
if (!Objects.deepEquals(afx, other.afx)) return false;
if (!Objects.deepEquals(afy, other.afy)) return false;
if (!Objects.deepEquals(afz, other.afz)) return false;
if (!Objects.deepEquals(yaw, other.yaw)) return false;
if (!Objects.deepEquals(yawRate, other.yawRate)) return false;
return true;
}
@Override
public int hashCode() {
int result = 0;
result = 31 * result + Objects.hashCode(timeBootMs);
result = 31 * result + Objects.hashCode(targetSystem);
result = 31 * result + Objects.hashCode(targetComponent);
result = 31 * result + Objects.hashCode(coordinateFrame);
result = 31 * result + Objects.hashCode(typeMask);
result = 31 * result + Objects.hashCode(x);
result = 31 * result + Objects.hashCode(y);
result = 31 * result + Objects.hashCode(z);
result = 31 * result + Objects.hashCode(vx);
result = 31 * result + Objects.hashCode(vy);
result = 31 * result + Objects.hashCode(vz);
result = 31 * result + Objects.hashCode(afx);
result = 31 * result + Objects.hashCode(afy);
result = 31 * result + Objects.hashCode(afz);
result = 31 * result + Objects.hashCode(yaw);
result = 31 * result + Objects.hashCode(yawRate);
return result;
}
@Override
public String toString() {
return "SetPositionTargetLocalNed{timeBootMs=" + timeBootMs
+ ", targetSystem=" + targetSystem
+ ", targetComponent=" + targetComponent
+ ", coordinateFrame=" + coordinateFrame
+ ", typeMask=" + typeMask
+ ", x=" + x
+ ", y=" + y
+ ", z=" + z
+ ", vx=" + vx
+ ", vy=" + vy
+ ", vz=" + vz
+ ", afx=" + afx
+ ", afy=" + afy
+ ", afz=" + afz
+ ", yaw=" + yaw
+ ", yawRate=" + yawRate + "}";
}
public static final class Builder {
private long timeBootMs;
private int targetSystem;
private int targetComponent;
private EnumValue<MavFrame> coordinateFrame;
private EnumValue<PositionTargetTypemask> typeMask;
private float x;
private float y;
private float z;
private float vx;
private float vy;
private float vz;
private float afx;
private float afy;
private float afz;
private float yaw;
private float yawRate;
/**
* Timestamp (time since system boot).
*/
@MavlinkFieldInfo(
position = 1,
unitSize = 4,
description = "Timestamp (time since system boot)."
)
public final Builder timeBootMs(long timeBootMs) {
this.timeBootMs = timeBootMs;
return this;
}
/**
* System ID
*/
@MavlinkFieldInfo(
position = 2,
unitSize = 1,
description = "System ID"
)
public final Builder targetSystem(int targetSystem) {
this.targetSystem = targetSystem;
return this;
}
/**
* Component ID
*/
@MavlinkFieldInfo(
position = 3,
unitSize = 1,
description = "Component ID"
)
public final Builder targetComponent(int targetComponent) {
this.targetComponent = targetComponent;
return this;
}
/**
* Valid options are: MAV_FRAME_LOCAL_NED = 1, MAV_FRAME_LOCAL_OFFSET_NED = 7,
* MAV_FRAME_BODY_NED = 8, MAV_FRAME_BODY_OFFSET_NED = 9
*/
@MavlinkFieldInfo(
position = 4,
unitSize = 1,
enumType = MavFrame.class,
description = "Valid options are: MAV_FRAME_LOCAL_NED = 1, MAV_FRAME_LOCAL_OFFSET_NED = 7, MAV_FRAME_BODY_NED = 8, MAV_FRAME_BODY_OFFSET_NED = 9"
)
public final Builder coordinateFrame(EnumValue<MavFrame> coordinateFrame) {
this.coordinateFrame = coordinateFrame;
return this;
}
/**
* Valid options are: MAV_FRAME_LOCAL_NED = 1, MAV_FRAME_LOCAL_OFFSET_NED = 7,
* MAV_FRAME_BODY_NED = 8, MAV_FRAME_BODY_OFFSET_NED = 9
*/
public final Builder coordinateFrame(MavFrame entry) {
return coordinateFrame(EnumValue.of(entry));
}
/**
* Valid options are: MAV_FRAME_LOCAL_NED = 1, MAV_FRAME_LOCAL_OFFSET_NED = 7,
* MAV_FRAME_BODY_NED = 8, MAV_FRAME_BODY_OFFSET_NED = 9
*/
public final Builder coordinateFrame(Enum... flags) {
return coordinateFrame(EnumValue.create(flags));
}
/**
* Valid options are: MAV_FRAME_LOCAL_NED = 1, MAV_FRAME_LOCAL_OFFSET_NED = 7,
* MAV_FRAME_BODY_NED = 8, MAV_FRAME_BODY_OFFSET_NED = 9
*/
public final Builder coordinateFrame(Collection<Enum> flags) {
return coordinateFrame(EnumValue.create(flags));
}
/**
* Bitmap to indicate which dimensions should be ignored by the vehicle.
*/
@MavlinkFieldInfo(
position = 5,
unitSize = 2,
enumType = PositionTargetTypemask.class,
description = "Bitmap to indicate which dimensions should be ignored by the vehicle."
)
public final Builder typeMask(EnumValue<PositionTargetTypemask> typeMask) {
this.typeMask = typeMask;
return this;
}
/**
* Bitmap to indicate which dimensions should be ignored by the vehicle.
*/
public final Builder typeMask(PositionTargetTypemask entry) {
return typeMask(EnumValue.of(entry));
}
/**
* Bitmap to indicate which dimensions should be ignored by the vehicle.
*/
public final Builder typeMask(Enum... flags) {
return typeMask(EnumValue.create(flags));
}
/**
* Bitmap to indicate which dimensions should be ignored by the vehicle.
*/
public final Builder typeMask(Collection<Enum> flags) {
return typeMask(EnumValue.create(flags));
}
/**
* X Position in NED frame
*/
@MavlinkFieldInfo(
position = 6,
unitSize = 4,
description = "X Position in NED frame"
)
public final Builder x(float x) {
this.x = x;
return this;
}
/**
* Y Position in NED frame
*/
@MavlinkFieldInfo(
position = 7,
unitSize = 4,
description = "Y Position in NED frame"
)
public final Builder y(float y) {
this.y = y;
return this;
}
/**
* Z Position in NED frame (note, altitude is negative in NED)
*/
@MavlinkFieldInfo(
position = 8,
unitSize = 4,
description = "Z Position in NED frame (note, altitude is negative in NED)"
)
public final Builder z(float z) {
this.z = z;
return this;
}
/**
* X velocity in NED frame
*/
@MavlinkFieldInfo(
position = 9,
unitSize = 4,
description = "X velocity in NED frame"
)
public final Builder vx(float vx) {
this.vx = vx;
return this;
}
/**
* Y velocity in NED frame
*/
@MavlinkFieldInfo(
position = 10,
unitSize = 4,
description = "Y velocity in NED frame"
)
public final Builder vy(float vy) {
this.vy = vy;
return this;
}
/**
* Z velocity in NED frame
*/
@MavlinkFieldInfo(
position = 11,
unitSize = 4,
description = "Z velocity in NED frame"
)
public final Builder vz(float vz) {
this.vz = vz;
return this;
}
/**
* X acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N
*/
@MavlinkFieldInfo(
position = 12,
unitSize = 4,
description = "X acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N"
)
public final Builder afx(float afx) {
this.afx = afx;
return this;
}
/**
* Y acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N
*/
@MavlinkFieldInfo(
position = 13,
unitSize = 4,
description = "Y acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N"
)
public final Builder afy(float afy) {
this.afy = afy;
return this;
}
/**
* Z acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N
*/
@MavlinkFieldInfo(
position = 14,
unitSize = 4,
description = "Z acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N"
)
public final Builder afz(float afz) {
this.afz = afz;
return this;
}
/**
* yaw setpoint
*/
@MavlinkFieldInfo(
position = 15,
unitSize = 4,
description = "yaw setpoint"
)
public final Builder yaw(float yaw) {
this.yaw = yaw;
return this;
}
/**
* yaw rate setpoint
*/
@MavlinkFieldInfo(
position = 16,
unitSize = 4,
description = "yaw rate setpoint"
)
public final Builder yawRate(float yawRate) {
this.yawRate = yawRate;
return this;
}
public final SetPositionTargetLocalNed build() {
return new SetPositionTargetLocalNed(timeBootMs, targetSystem, targetComponent, coordinateFrame, typeMask, x, y, z, vx, vy, vz, afx, afy, afz, yaw, yawRate);
}
}
}
| 0 | 0.849036 | 1 | 0.849036 | game-dev | MEDIA | 0.706764 | game-dev | 0.815853 | 1 | 0.815853 |
magefree/mage | 4,086 | Mage.Sets/src/mage/cards/f/FirefluxSquad.java | package mage.cards.f;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.AttacksTriggeredAbility;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.keyword.HasteAbility;
import mage.cards.*;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.SubType;
import mage.constants.Zone;
import mage.filter.FilterPermanent;
import mage.filter.common.FilterControlledCreaturePermanent;
import mage.filter.predicate.mageobject.AnotherPredicate;
import mage.filter.predicate.permanent.AttackingPredicate;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.players.Player;
import mage.target.TargetPermanent;
import mage.util.CardUtil;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class FirefluxSquad extends CardImpl {
private static final FilterPermanent filter
= new FilterControlledCreaturePermanent("another attacking creature you control");
static {
filter.add(AnotherPredicate.instance);
filter.add(AttackingPredicate.instance);
}
public FirefluxSquad(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{R}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.SOLDIER);
this.power = new MageInt(4);
this.toughness = new MageInt(3);
// Haste
this.addAbility(HasteAbility.getInstance());
// Whenever Fireflux Squad attacks, you may exile another target attacking creature you control. If you do, reveal cards from the top of your library until you reveal a creature card. Put that card onto the battlefield tapped and attacking and the rest on the bottom of your library in a random order.
Ability ability = new AttacksTriggeredAbility(new FirefluxSquadEffect(), true);
ability.addTarget(new TargetPermanent(filter));
this.addAbility(ability);
}
private FirefluxSquad(final FirefluxSquad card) {
super(card);
}
@Override
public FirefluxSquad copy() {
return new FirefluxSquad(this);
}
}
class FirefluxSquadEffect extends OneShotEffect {
FirefluxSquadEffect() {
super(Outcome.Benefit);
staticText = "exile another target attacking creature you control. If you do, " +
"reveal cards from the top of your library until you reveal a creature card. " +
"Put that card onto the battlefield tapped and attacking " +
"and the rest on the bottom of your library in a random order.";
}
private FirefluxSquadEffect(final FirefluxSquadEffect effect) {
super(effect);
}
@Override
public FirefluxSquadEffect copy() {
return new FirefluxSquadEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Player player = game.getPlayer(source.getControllerId());
Permanent permanent = game.getPermanent(source.getFirstTarget());
if (player == null || permanent == null) {
return false;
}
player.moveCards(permanent, Zone.EXILED, source, game);
Card toBattlefield = null;
Cards cards = new CardsImpl();
for (Card card : player.getLibrary().getCards(game)) {
cards.add(card);
if (card != null && card.isCreature(game)) {
toBattlefield = card;
break;
}
}
player.revealCards(source, cards, game);
if (toBattlefield == null) {
return player.putCardsOnBottomOfLibrary(cards, game, source, false);
}
player.moveCards(toBattlefield, Zone.BATTLEFIELD, source, game, true, false, true, null);
permanent = CardUtil.getPermanentFromCardPutToBattlefield(toBattlefield, game);
if (permanent != null) {
cards.remove(toBattlefield);
game.getCombat().addAttackingCreature(permanent.getId(), game);
}
return player.putCardsOnBottomOfLibrary(cards, game, source, false);
}
}
| 0 | 0.924033 | 1 | 0.924033 | game-dev | MEDIA | 0.958468 | game-dev | 0.988735 | 1 | 0.988735 |
vizflow/vizflow | 3,489 | examples/template/basic_game/src/module/core/itemHelper.js | var itemHelper = {
setup: function item_helper_setup(itemConfig, viz) {
if(viz === undefined) {
viz = this ;
}
if ( itemConfig === undefined ) {
itemConfig = {} ;
}
if(itemConfig.opacity === undefined) {
itemConfig.opacity = 1 ;
}
if(itemConfig.inert === undefined) {
itemConfig.inert = true ;
}
var item = { // configurable properties: x, y, type, element, opacity, image, inert, render, fixed, transition
config: itemConfig,
viz: itemConfig.viz || viz,
x: itemConfig.x,
y: itemConfig.y,
angle: itemConfig.angle || 0,
xOrigin: itemConfig.xOrigin || 0,
yOrigin: itemConfig.yOrigin || 0,
xAngle: itemConfig.xAngle || 0,
yAngle: itemConfig.yAngle || 0,
type: itemConfig.type,
element: itemConfig.element,
enter: itemConfig.enter,
exit: itemConfig.exit,
opacity: itemConfig.opacity,
color: itemConfig.color,
width: itemConfig.width,
height: itemConfig.height,
image: itemConfig.image,
child: itemConfig.child,
inert: itemConfig.inert,
fixed: itemConfig.fixed,
uiSwitch: itemConfig.uiSwitch || false,
callback: itemConfig.callback,
render: itemConfig.render || drawHelper.item, // drawHelper.image expects "this" to be "item"
responseSet: {}, // add response objects separately
add: itemHelper.add,
remove: itemHelper.remove,
zoom: itemHelper.zoom,
default_child: itemHelper.default_child,
add_transition: transitionHelper.add, // transitionHelper.add expects "this" to be "item"
remove_transition: transitionHelper.remove,
add_end: transitionHelper.add_end,
collision_image: actionHelper.collision_image, // actionHelper.collision_image() expects "this" to be "item"
fade: imageEffectHelper.fade, // imageEffectHelper.fade expects "this" to be "item"
flash: effectHelper.flash,
} ;
return item ;
},
default_child: function item_helper_default_child (item) {
if ( item === undefined ) {
item = this ;
}
if ( item.child === undefined ) {
item.child = [] ; // initialize
}
var white = imageEffectHelper.color_filter(item.image, [255, 255 , 255]) ;
item.white = Object.copy(item) ;
item.white.child = undefined ;
item.white.image = white ;
item.white.opacity = 0 ;
item.child.push(item.white) ;
},
zoom: function item_zoom(scale, duration, item) {
if(item === undefined) {
item = this ;
}
if(scale === undefined) {
scale = 0.5 ;
}
if(duration === undefined) {
duration = item.viz.fadeDuration ;
}
// console.log('item helper', 'zoom', 'this', this) ;
item.viz.zoom({
duration: duration,
x: item.x,
y: item.y,
width: item.viz.width * scale,
height: item.viz.height * scale,
}) ;
},
add: function(viz, item) {
if(item === undefined) {
item = this ;
}
if(viz === undefined) {
viz = this.viz ;
}
if(viz.item === undefined) {
viz.item = [] ;
}
if(item.constructor !== Array) {
// console.log('item helper:', 'viz', viz, 'this', this)
viz.stagingArray.push(item) ;
} else {
for(var kitem = 0 ; kitem < item.length ; kitem++) {
viz.stagingArray.push(item[kitem]) ;
}
}
},
remove: function item_helper_remove(item) {
if(item === undefined) {
item = this ;
}
item.removeSwitch = true ;
},
} ;
| 0 | 0.855142 | 1 | 0.855142 | game-dev | MEDIA | 0.540964 | game-dev | 0.94753 | 1 | 0.94753 |
ghewgill/puzzles | 58,533 | unruly.c | /*
* unruly.c: Implementation for Binary Puzzles.
* (C) 2012 Lennard Sprong
* Created for Simon Tatham's Portable Puzzle Collection
* See LICENCE for licence details
*
* Objective of the game: Fill the grid with zeros and ones, with the
* following rules:
* - There can't be a run of three or more equal numbers.
* - Each row and column contains an equal amount of zeros and ones.
*
* This puzzle type is known under several names, including
* Tohu-Wa-Vohu, One and Two and Binairo.
*
* Some variants include an extra constraint, stating that no two rows or two
* columns may contain the same exact sequence of zeros and ones.
* This rule is rarely used, so it is not enabled in the default presets
* (but it can be selected via the Custom configurer).
*
* More information:
* http://www.janko.at/Raetsel/Tohu-Wa-Vohu/index.htm
*/
/*
* Possible future improvements:
*
* More solver cleverness
*
* - a counting-based deduction in which you find groups of squares
* which must each contain at least one of a given colour, plus
* other squares which are already known to be that colour, and see
* if you have any squares left over when you've worked out where
* they all have to be. This is a generalisation of the current
* check_near_complete: where that only covers rows with three
* unfilled squares, this would handle more, such as
* 0 . . 1 0 1 . . 0 .
* in which each of the two-square gaps must contain a 0, and there
* are three 0s placed, and that means the rightmost square can't
* be a 0.
*
* - an 'Unreasonable' difficulty level, supporting recursion and
* backtracking.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <math.h>
#include "puzzles.h"
#ifdef STANDALONE_SOLVER
int solver_verbose = FALSE;
#endif
enum {
COL_BACKGROUND,
COL_GRID,
COL_EMPTY,
/*
* When editing this enum, maintain the invariants
* COL_n_HIGHLIGHT = COL_n + 1
* COL_n_LOWLIGHT = COL_n + 2
*/
COL_0,
COL_0_HIGHLIGHT,
COL_0_LOWLIGHT,
COL_1,
COL_1_HIGHLIGHT,
COL_1_LOWLIGHT,
COL_CURSOR,
COL_ERROR,
NCOLOURS
};
struct game_params {
int w2, h2; /* full grid width and height respectively */
int unique; /* should row and column patterns be unique? */
int diff;
};
#define DIFFLIST(A) \
A(EASY,Easy, e) \
A(NORMAL,Normal, n) \
#define ENUM(upper,title,lower) DIFF_ ## upper,
#define TITLE(upper,title,lower) #title,
#define ENCODE(upper,title,lower) #lower
#define CONFIG(upper,title,lower) ":" #title
enum { DIFFLIST(ENUM) DIFFCOUNT };
static char const *const unruly_diffnames[] = { DIFFLIST(TITLE) };
static char const unruly_diffchars[] = DIFFLIST(ENCODE);
#define DIFFCONFIG DIFFLIST(CONFIG)
const static struct game_params unruly_presets[] = {
{ 8, 8, FALSE, DIFF_EASY},
{ 8, 8, FALSE, DIFF_NORMAL},
{10, 10, FALSE, DIFF_EASY},
{10, 10, FALSE, DIFF_NORMAL},
{14, 14, FALSE, DIFF_EASY},
{14, 14, FALSE, DIFF_NORMAL}
};
#define DEFAULT_PRESET 0
enum {
EMPTY,
N_ONE,
N_ZERO,
BOGUS
};
#define FE_HOR_ROW_LEFT 0x0001
#define FE_HOR_ROW_MID 0x0003
#define FE_HOR_ROW_RIGHT 0x0002
#define FE_VER_ROW_TOP 0x0004
#define FE_VER_ROW_MID 0x000C
#define FE_VER_ROW_BOTTOM 0x0008
#define FE_COUNT 0x0010
#define FE_ROW_MATCH 0x0020
#define FE_COL_MATCH 0x0040
#define FF_ONE 0x0080
#define FF_ZERO 0x0100
#define FF_CURSOR 0x0200
#define FF_FLASH1 0x0400
#define FF_FLASH2 0x0800
#define FF_IMMUTABLE 0x1000
struct game_state {
int w2, h2;
int unique;
char *grid;
unsigned char *immutable;
int completed, cheated;
};
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
*ret = unruly_presets[DEFAULT_PRESET]; /* structure copy */
return ret;
}
static int game_fetch_preset(int i, char **name, game_params **params)
{
game_params *ret;
char buf[80];
if (i < 0 || i >= lenof(unruly_presets))
return FALSE;
ret = snew(game_params);
*ret = unruly_presets[i]; /* structure copy */
sprintf(buf, "%dx%d %s", ret->w2, ret->h2, unruly_diffnames[ret->diff]);
*name = dupstr(buf);
*params = ret;
return TRUE;
}
static void free_params(game_params *params)
{
sfree(params);
}
static game_params *dup_params(const game_params *params)
{
game_params *ret = snew(game_params);
*ret = *params; /* structure copy */
return ret;
}
static void decode_params(game_params *params, char const *string)
{
char const *p = string;
params->unique = FALSE;
params->w2 = atoi(p);
while (*p && isdigit((unsigned char)*p)) p++;
if (*p == 'x') {
p++;
params->h2 = atoi(p);
while (*p && isdigit((unsigned char)*p)) p++;
} else {
params->h2 = params->w2;
}
if (*p == 'u') {
p++;
params->unique = TRUE;
}
if (*p == 'd') {
int i;
p++;
params->diff = DIFFCOUNT + 1; /* ...which is invalid */
if (*p) {
for (i = 0; i < DIFFCOUNT; i++) {
if (*p == unruly_diffchars[i])
params->diff = i;
}
p++;
}
}
}
static char *encode_params(const game_params *params, int full)
{
char buf[80];
sprintf(buf, "%dx%d", params->w2, params->h2);
if (params->unique)
strcat(buf, "u");
if (full)
sprintf(buf + strlen(buf), "d%c", unruly_diffchars[params->diff]);
return dupstr(buf);
}
static config_item *game_configure(const game_params *params)
{
config_item *ret;
char buf[80];
ret = snewn(5, config_item);
ret[0].name = "Width";
ret[0].type = C_STRING;
sprintf(buf, "%d", params->w2);
ret[0].sval = dupstr(buf);
ret[0].ival = 0;
ret[1].name = "Height";
ret[1].type = C_STRING;
sprintf(buf, "%d", params->h2);
ret[1].sval = dupstr(buf);
ret[1].ival = 0;
ret[2].name = "Unique rows and columns";
ret[2].type = C_BOOLEAN;
ret[2].ival = params->unique;
ret[3].name = "Difficulty";
ret[3].type = C_CHOICES;
ret[3].sval = DIFFCONFIG;
ret[3].ival = params->diff;
ret[4].name = NULL;
ret[4].type = C_END;
ret[4].sval = NULL;
ret[4].ival = 0;
return ret;
}
static game_params *custom_params(const config_item *cfg)
{
game_params *ret = snew(game_params);
ret->w2 = atoi(cfg[0].sval);
ret->h2 = atoi(cfg[1].sval);
ret->unique = cfg[2].ival;
ret->diff = cfg[3].ival;
return ret;
}
static char *validate_params(const game_params *params, int full)
{
if ((params->w2 & 1) || (params->h2 & 1))
return "Width and height must both be even";
if (params->w2 < 6 || params->h2 < 6)
return "Width and height must be at least 6";
if (params->unique) {
static const long A177790[] = {
/*
* The nth element of this array gives the number of
* distinct possible Unruly rows of length 2n (that is,
* containing exactly n 1s and n 0s and not containing
* three consecutive elements the same) for as long as
* those numbers fit in a 32-bit signed int.
*
* So in unique-rows mode, if the puzzle width is 2n, then
* the height must be at most (this array)[n], and vice
* versa.
*
* This is sequence A177790 in the Online Encyclopedia of
* Integer Sequences: http://oeis.org/A177790
*/
1L, 2L, 6L, 14L, 34L, 84L, 208L, 518L, 1296L, 3254L,
8196L, 20700L, 52404L, 132942L, 337878L, 860142L,
2192902L, 5598144L, 14308378L, 36610970L, 93770358L,
240390602L, 616787116L, 1583765724L
};
if (params->w2 < 2*lenof(A177790) &&
params->h2 > A177790[params->w2/2]) {
return "Puzzle is too tall for unique-rows mode";
}
if (params->h2 < 2*lenof(A177790) &&
params->w2 > A177790[params->h2/2]) {
return "Puzzle is too long for unique-rows mode";
}
}
if (params->diff >= DIFFCOUNT)
return "Unknown difficulty rating";
return NULL;
}
static char *validate_desc(const game_params *params, const char *desc)
{
int w2 = params->w2, h2 = params->h2;
int s = w2 * h2;
const char *p = desc;
int pos = 0;
while (*p) {
if (*p >= 'a' && *p < 'z')
pos += 1 + (*p - 'a');
else if (*p >= 'A' && *p < 'Z')
pos += 1 + (*p - 'A');
else if (*p == 'Z' || *p == 'z')
pos += 25;
else
return "Description contains invalid characters";
++p;
}
if (pos < s+1)
return "Description too short";
if (pos > s+1)
return "Description too long";
return NULL;
}
static game_state *blank_state(int w2, int h2, int unique)
{
game_state *state = snew(game_state);
int s = w2 * h2;
state->w2 = w2;
state->h2 = h2;
state->unique = unique;
state->grid = snewn(s, char);
state->immutable = snewn(s, unsigned char);
memset(state->grid, EMPTY, s);
memset(state->immutable, FALSE, s);
state->completed = state->cheated = FALSE;
return state;
}
static game_state *new_game(midend *me, const game_params *params,
const char *desc)
{
int w2 = params->w2, h2 = params->h2;
int s = w2 * h2;
game_state *state = blank_state(w2, h2, params->unique);
const char *p = desc;
int pos = 0;
while (*p) {
if (*p >= 'a' && *p < 'z') {
pos += (*p - 'a');
if (pos < s) {
state->grid[pos] = N_ZERO;
state->immutable[pos] = TRUE;
}
pos++;
} else if (*p >= 'A' && *p < 'Z') {
pos += (*p - 'A');
if (pos < s) {
state->grid[pos] = N_ONE;
state->immutable[pos] = TRUE;
}
pos++;
} else if (*p == 'Z' || *p == 'z') {
pos += 25;
} else
assert(!"Description contains invalid characters");
++p;
}
assert(pos == s+1);
return state;
}
static game_state *dup_game(const game_state *state)
{
int w2 = state->w2, h2 = state->h2;
int s = w2 * h2;
game_state *ret = blank_state(w2, h2, state->unique);
memcpy(ret->grid, state->grid, s);
memcpy(ret->immutable, state->immutable, s);
ret->completed = state->completed;
ret->cheated = state->cheated;
return ret;
}
static void free_game(game_state *state)
{
sfree(state->grid);
sfree(state->immutable);
sfree(state);
}
static int game_can_format_as_text_now(const game_params *params)
{
return TRUE;
}
static char *game_text_format(const game_state *state)
{
int w2 = state->w2, h2 = state->h2;
int lr = w2*2 + 1;
char *ret = snewn(lr * h2 + 1, char);
char *p = ret;
int x, y;
for (y = 0; y < h2; y++) {
for (x = 0; x < w2; x++) {
/* Place number */
char c = state->grid[y * w2 + x];
*p++ = (c == N_ONE ? '1' : c == N_ZERO ? '0' : '.');
*p++ = ' ';
}
/* End line */
*p++ = '\n';
}
/* End with NUL */
*p++ = '\0';
return ret;
}
/* ****** *
* Solver *
* ****** */
struct unruly_scratch {
int *ones_rows;
int *ones_cols;
int *zeros_rows;
int *zeros_cols;
};
static void unruly_solver_update_remaining(const game_state *state,
struct unruly_scratch *scratch)
{
int w2 = state->w2, h2 = state->h2;
int x, y;
/* Reset all scratch data */
memset(scratch->ones_rows, 0, h2 * sizeof(int));
memset(scratch->ones_cols, 0, w2 * sizeof(int));
memset(scratch->zeros_rows, 0, h2 * sizeof(int));
memset(scratch->zeros_cols, 0, w2 * sizeof(int));
for (x = 0; x < w2; x++)
for (y = 0; y < h2; y++) {
if (state->grid[y * w2 + x] == N_ONE) {
scratch->ones_rows[y]++;
scratch->ones_cols[x]++;
} else if (state->grid[y * w2 + x] == N_ZERO) {
scratch->zeros_rows[y]++;
scratch->zeros_cols[x]++;
}
}
}
static struct unruly_scratch *unruly_new_scratch(const game_state *state)
{
int w2 = state->w2, h2 = state->h2;
struct unruly_scratch *ret = snew(struct unruly_scratch);
ret->ones_rows = snewn(h2, int);
ret->ones_cols = snewn(w2, int);
ret->zeros_rows = snewn(h2, int);
ret->zeros_cols = snewn(w2, int);
unruly_solver_update_remaining(state, ret);
return ret;
}
static void unruly_free_scratch(struct unruly_scratch *scratch)
{
sfree(scratch->ones_rows);
sfree(scratch->ones_cols);
sfree(scratch->zeros_rows);
sfree(scratch->zeros_cols);
sfree(scratch);
}
static int unruly_solver_check_threes(game_state *state, int *rowcount,
int *colcount, int horizontal,
char check, char block)
{
int w2 = state->w2, h2 = state->h2;
int dx = horizontal ? 1 : 0, dy = 1 - dx;
int sx = dx, sy = dy;
int ex = w2 - dx, ey = h2 - dy;
int x, y;
int ret = 0;
/* Check for any three squares which almost form three in a row */
for (y = sy; y < ey; y++) {
for (x = sx; x < ex; x++) {
int i1 = (y-dy) * w2 + (x-dx);
int i2 = y * w2 + x;
int i3 = (y+dy) * w2 + (x+dx);
if (state->grid[i1] == check && state->grid[i2] == check
&& state->grid[i3] == EMPTY) {
ret++;
#ifdef STANDALONE_SOLVER
if (solver_verbose) {
printf("Solver: %i,%i and %i,%i confirm %c at %i,%i\n",
i1 % w2, i1 / w2, i2 % w2, i2 / w2,
(block == N_ONE ? '1' : '0'), i3 % w2,
i3 / w2);
}
#endif
state->grid[i3] = block;
rowcount[i3 / w2]++;
colcount[i3 % w2]++;
}
if (state->grid[i1] == check && state->grid[i2] == EMPTY
&& state->grid[i3] == check) {
ret++;
#ifdef STANDALONE_SOLVER
if (solver_verbose) {
printf("Solver: %i,%i and %i,%i confirm %c at %i,%i\n",
i1 % w2, i1 / w2, i3 % w2, i3 / w2,
(block == N_ONE ? '1' : '0'), i2 % w2,
i2 / w2);
}
#endif
state->grid[i2] = block;
rowcount[i2 / w2]++;
colcount[i2 % w2]++;
}
if (state->grid[i1] == EMPTY && state->grid[i2] == check
&& state->grid[i3] == check) {
ret++;
#ifdef STANDALONE_SOLVER
if (solver_verbose) {
printf("Solver: %i,%i and %i,%i confirm %c at %i,%i\n",
i2 % w2, i2 / w2, i3 % w2, i3 / w2,
(block == N_ONE ? '1' : '0'), i1 % w2,
i1 / w2);
}
#endif
state->grid[i1] = block;
rowcount[i1 / w2]++;
colcount[i1 % w2]++;
}
}
}
return ret;
}
static int unruly_solver_check_all_threes(game_state *state,
struct unruly_scratch *scratch)
{
int ret = 0;
ret +=
unruly_solver_check_threes(state, scratch->zeros_rows,
scratch->zeros_cols, TRUE, N_ONE, N_ZERO);
ret +=
unruly_solver_check_threes(state, scratch->ones_rows,
scratch->ones_cols, TRUE, N_ZERO, N_ONE);
ret +=
unruly_solver_check_threes(state, scratch->zeros_rows,
scratch->zeros_cols, FALSE, N_ONE,
N_ZERO);
ret +=
unruly_solver_check_threes(state, scratch->ones_rows,
scratch->ones_cols, FALSE, N_ZERO, N_ONE);
return ret;
}
static int unruly_solver_check_uniques(game_state *state, int *rowcount,
int horizontal, char check, char block,
struct unruly_scratch *scratch)
{
int w2 = state->w2, h2 = state->h2;
int rmult = (horizontal ? w2 : 1);
int cmult = (horizontal ? 1 : w2);
int nr = (horizontal ? h2 : w2);
int nc = (horizontal ? w2 : h2);
int max = nc / 2;
int r, r2, c;
int ret = 0;
/*
* Find each row that has max entries of type 'check', and see if
* all those entries match those in any row with max-1 entries. If
* so, set the last non-matching entry of the latter row to ensure
* that it's different.
*/
for (r = 0; r < nr; r++) {
if (rowcount[r] != max)
continue;
for (r2 = 0; r2 < nr; r2++) {
int nmatch = 0, nonmatch = -1;
if (rowcount[r2] != max-1)
continue;
for (c = 0; c < nc; c++) {
if (state->grid[r*rmult + c*cmult] == check) {
if (state->grid[r2*rmult + c*cmult] == check)
nmatch++;
else
nonmatch = c;
}
}
if (nmatch == max-1) {
int i1 = r2 * rmult + nonmatch * cmult;
assert(nonmatch != -1);
if (state->grid[i1] == block)
continue;
assert(state->grid[i1] == EMPTY);
#ifdef STANDALONE_SOLVER
if (solver_verbose) {
printf("Solver: matching %s %i, %i gives %c at %i,%i\n",
horizontal ? "rows" : "cols",
r, r2, (block == N_ONE ? '1' : '0'), i1 % w2,
i1 / w2);
}
#endif
state->grid[i1] = block;
if (block == N_ONE) {
scratch->ones_rows[i1 / w2]++;
scratch->ones_cols[i1 % w2]++;
} else {
scratch->zeros_rows[i1 / w2]++;
scratch->zeros_cols[i1 % w2]++;
}
ret++;
}
}
}
return ret;
}
static int unruly_solver_check_all_uniques(game_state *state,
struct unruly_scratch *scratch)
{
int ret = 0;
ret += unruly_solver_check_uniques(state, scratch->ones_rows,
TRUE, N_ONE, N_ZERO, scratch);
ret += unruly_solver_check_uniques(state, scratch->zeros_rows,
TRUE, N_ZERO, N_ONE, scratch);
ret += unruly_solver_check_uniques(state, scratch->ones_cols,
FALSE, N_ONE, N_ZERO, scratch);
ret += unruly_solver_check_uniques(state, scratch->zeros_cols,
FALSE, N_ZERO, N_ONE, scratch);
return ret;
}
static int unruly_solver_fill_row(game_state *state, int i, int horizontal,
int *rowcount, int *colcount, char fill)
{
int ret = 0;
int w2 = state->w2, h2 = state->h2;
int j;
#ifdef STANDALONE_SOLVER
if (solver_verbose) {
printf("Solver: Filling %s %i with %c:",
(horizontal ? "Row" : "Col"), i,
(fill == N_ZERO ? '0' : '1'));
}
#endif
/* Place a number in every empty square in a row/column */
for (j = 0; j < (horizontal ? w2 : h2); j++) {
int p = (horizontal ? i * w2 + j : j * w2 + i);
if (state->grid[p] == EMPTY) {
#ifdef STANDALONE_SOLVER
if (solver_verbose) {
printf(" (%i,%i)", (horizontal ? j : i),
(horizontal ? i : j));
}
#endif
ret++;
state->grid[p] = fill;
rowcount[(horizontal ? i : j)]++;
colcount[(horizontal ? j : i)]++;
}
}
#ifdef STANDALONE_SOLVER
if (solver_verbose) {
printf("\n");
}
#endif
return ret;
}
static int unruly_solver_check_complete_nums(game_state *state,
int *complete, int horizontal,
int *rowcount, int *colcount,
char fill)
{
int w2 = state->w2, h2 = state->h2;
int count = (horizontal ? h2 : w2); /* number of rows to check */
int target = (horizontal ? w2 : h2) / 2; /* target number of 0s/1s */
int *other = (horizontal ? rowcount : colcount);
int ret = 0;
int i;
/* Check for completed rows/cols for one number, then fill in the rest */
for (i = 0; i < count; i++) {
if (complete[i] == target && other[i] < target) {
#ifdef STANDALONE_SOLVER
if (solver_verbose) {
printf("Solver: Row %i satisfied for %c\n", i,
(fill != N_ZERO ? '0' : '1'));
}
#endif
ret += unruly_solver_fill_row(state, i, horizontal, rowcount,
colcount, fill);
}
}
return ret;
}
static int unruly_solver_check_all_complete_nums(game_state *state,
struct unruly_scratch *scratch)
{
int ret = 0;
ret +=
unruly_solver_check_complete_nums(state, scratch->ones_rows, TRUE,
scratch->zeros_rows,
scratch->zeros_cols, N_ZERO);
ret +=
unruly_solver_check_complete_nums(state, scratch->ones_cols, FALSE,
scratch->zeros_rows,
scratch->zeros_cols, N_ZERO);
ret +=
unruly_solver_check_complete_nums(state, scratch->zeros_rows, TRUE,
scratch->ones_rows,
scratch->ones_cols, N_ONE);
ret +=
unruly_solver_check_complete_nums(state, scratch->zeros_cols, FALSE,
scratch->ones_rows,
scratch->ones_cols, N_ONE);
return ret;
}
static int unruly_solver_check_near_complete(game_state *state,
int *complete, int horizontal,
int *rowcount, int *colcount,
char fill)
{
int w2 = state->w2, h2 = state->h2;
int w = w2/2, h = h2/2;
int dx = horizontal ? 1 : 0, dy = 1 - dx;
int sx = dx, sy = dy;
int ex = w2 - dx, ey = h2 - dy;
int x, y;
int ret = 0;
/*
* This function checks for a row with one Y remaining, then looks
* for positions that could cause the remaining squares in the row
* to make 3 X's in a row. Example:
*
* Consider the following row:
* 1 1 0 . . .
* If the last 1 was placed in the last square, the remaining
* squares would be 0:
* 1 1 0 0 0 1
* This violates the 3 in a row rule. We now know that the last 1
* shouldn't be in the last cell.
* 1 1 0 . . 0
*/
/* Check for any two blank and one filled square */
for (y = sy; y < ey; y++) {
/* One type must have 1 remaining, the other at least 2 */
if (horizontal && (complete[y] < w - 1 || rowcount[y] > w - 2))
continue;
for (x = sx; x < ex; x++) {
int i, i1, i2, i3;
if (!horizontal
&& (complete[x] < h - 1 || colcount[x] > h - 2))
continue;
i = (horizontal ? y : x);
i1 = (y-dy) * w2 + (x-dx);
i2 = y * w2 + x;
i3 = (y+dy) * w2 + (x+dx);
if (state->grid[i1] == fill && state->grid[i2] == EMPTY
&& state->grid[i3] == EMPTY) {
/*
* Temporarily fill the empty spaces with something else.
* This avoids raising the counts for the row and column
*/
state->grid[i2] = BOGUS;
state->grid[i3] = BOGUS;
#ifdef STANDALONE_SOLVER
if (solver_verbose) {
printf("Solver: Row %i nearly satisfied for %c\n", i,
(fill != N_ZERO ? '0' : '1'));
}
#endif
ret +=
unruly_solver_fill_row(state, i, horizontal, rowcount,
colcount, fill);
state->grid[i2] = EMPTY;
state->grid[i3] = EMPTY;
}
else if (state->grid[i1] == EMPTY && state->grid[i2] == fill
&& state->grid[i3] == EMPTY) {
state->grid[i1] = BOGUS;
state->grid[i3] = BOGUS;
#ifdef STANDALONE_SOLVER
if (solver_verbose) {
printf("Solver: Row %i nearly satisfied for %c\n", i,
(fill != N_ZERO ? '0' : '1'));
}
#endif
ret +=
unruly_solver_fill_row(state, i, horizontal, rowcount,
colcount, fill);
state->grid[i1] = EMPTY;
state->grid[i3] = EMPTY;
}
else if (state->grid[i1] == EMPTY && state->grid[i2] == EMPTY
&& state->grid[i3] == fill) {
state->grid[i1] = BOGUS;
state->grid[i2] = BOGUS;
#ifdef STANDALONE_SOLVER
if (solver_verbose) {
printf("Solver: Row %i nearly satisfied for %c\n", i,
(fill != N_ZERO ? '0' : '1'));
}
#endif
ret +=
unruly_solver_fill_row(state, i, horizontal, rowcount,
colcount, fill);
state->grid[i1] = EMPTY;
state->grid[i2] = EMPTY;
}
else if (state->grid[i1] == EMPTY && state->grid[i2] == EMPTY
&& state->grid[i3] == EMPTY) {
state->grid[i1] = BOGUS;
state->grid[i2] = BOGUS;
state->grid[i3] = BOGUS;
#ifdef STANDALONE_SOLVER
if (solver_verbose) {
printf("Solver: Row %i nearly satisfied for %c\n", i,
(fill != N_ZERO ? '0' : '1'));
}
#endif
ret +=
unruly_solver_fill_row(state, i, horizontal, rowcount,
colcount, fill);
state->grid[i1] = EMPTY;
state->grid[i2] = EMPTY;
state->grid[i3] = EMPTY;
}
}
}
return ret;
}
static int unruly_solver_check_all_near_complete(game_state *state,
struct unruly_scratch *scratch)
{
int ret = 0;
ret +=
unruly_solver_check_near_complete(state, scratch->ones_rows, TRUE,
scratch->zeros_rows,
scratch->zeros_cols, N_ZERO);
ret +=
unruly_solver_check_near_complete(state, scratch->ones_cols, FALSE,
scratch->zeros_rows,
scratch->zeros_cols, N_ZERO);
ret +=
unruly_solver_check_near_complete(state, scratch->zeros_rows, TRUE,
scratch->ones_rows,
scratch->ones_cols, N_ONE);
ret +=
unruly_solver_check_near_complete(state, scratch->zeros_cols, FALSE,
scratch->ones_rows,
scratch->ones_cols, N_ONE);
return ret;
}
static int unruly_validate_rows(const game_state *state, int horizontal,
char check, int *errors)
{
int w2 = state->w2, h2 = state->h2;
int dx = horizontal ? 1 : 0, dy = 1 - dx;
int sx = dx, sy = dy;
int ex = w2 - dx, ey = h2 - dy;
int x, y;
int ret = 0;
int err1 = (horizontal ? FE_HOR_ROW_LEFT : FE_VER_ROW_TOP);
int err2 = (horizontal ? FE_HOR_ROW_MID : FE_VER_ROW_MID);
int err3 = (horizontal ? FE_HOR_ROW_RIGHT : FE_VER_ROW_BOTTOM);
/* Check for any three in a row, and mark errors accordingly (if
* required) */
for (y = sy; y < ey; y++) {
for (x = sx; x < ex; x++) {
int i1 = (y-dy) * w2 + (x-dx);
int i2 = y * w2 + x;
int i3 = (y+dy) * w2 + (x+dx);
if (state->grid[i1] == check && state->grid[i2] == check
&& state->grid[i3] == check) {
ret++;
if (errors) {
errors[i1] |= err1;
errors[i2] |= err2;
errors[i3] |= err3;
}
}
}
}
return ret;
}
static int unruly_validate_unique(const game_state *state, int horizontal,
int *errors)
{
int w2 = state->w2, h2 = state->h2;
int rmult = (horizontal ? w2 : 1);
int cmult = (horizontal ? 1 : w2);
int nr = (horizontal ? h2 : w2);
int nc = (horizontal ? w2 : h2);
int err = (horizontal ? FE_ROW_MATCH : FE_COL_MATCH);
int r, r2, c;
int ret = 0;
/* Check for any two full rows matching exactly, and mark errors
* accordingly (if required) */
for (r = 0; r < nr; r++) {
int nfull = 0;
for (c = 0; c < nc; c++)
if (state->grid[r*rmult + c*cmult] != EMPTY)
nfull++;
if (nfull != nc)
continue;
for (r2 = r+1; r2 < nr; r2++) {
int match = TRUE;
for (c = 0; c < nc; c++)
if (state->grid[r*rmult + c*cmult] !=
state->grid[r2*rmult + c*cmult])
match = FALSE;
if (match) {
if (errors) {
for (c = 0; c < nc; c++) {
errors[r*rmult + c*cmult] |= err;
errors[r2*rmult + c*cmult] |= err;
}
}
ret++;
}
}
}
return ret;
}
static int unruly_validate_all_rows(const game_state *state, int *errors)
{
int errcount = 0;
errcount += unruly_validate_rows(state, TRUE, N_ONE, errors);
errcount += unruly_validate_rows(state, FALSE, N_ONE, errors);
errcount += unruly_validate_rows(state, TRUE, N_ZERO, errors);
errcount += unruly_validate_rows(state, FALSE, N_ZERO, errors);
if (state->unique) {
errcount += unruly_validate_unique(state, TRUE, errors);
errcount += unruly_validate_unique(state, FALSE, errors);
}
if (errcount)
return -1;
return 0;
}
static int unruly_validate_counts(const game_state *state,
struct unruly_scratch *scratch, int *errors)
{
int w2 = state->w2, h2 = state->h2;
int w = w2/2, h = h2/2;
char below = FALSE;
char above = FALSE;
int i;
/* See if all rows/columns are satisfied. If one is exceeded,
* mark it as an error (if required)
*/
char hasscratch = TRUE;
if (!scratch) {
scratch = unruly_new_scratch(state);
hasscratch = FALSE;
}
for (i = 0; i < w2; i++) {
if (scratch->ones_cols[i] < h)
below = TRUE;
if (scratch->zeros_cols[i] < h)
below = TRUE;
if (scratch->ones_cols[i] > h) {
above = TRUE;
if (errors)
errors[2*h2 + i] = TRUE;
} else if (errors)
errors[2*h2 + i] = FALSE;
if (scratch->zeros_cols[i] > h) {
above = TRUE;
if (errors)
errors[2*h2 + w2 + i] = TRUE;
} else if (errors)
errors[2*h2 + w2 + i] = FALSE;
}
for (i = 0; i < h2; i++) {
if (scratch->ones_rows[i] < w)
below = TRUE;
if (scratch->zeros_rows[i] < w)
below = TRUE;
if (scratch->ones_rows[i] > w) {
above = TRUE;
if (errors)
errors[i] = TRUE;
} else if (errors)
errors[i] = FALSE;
if (scratch->zeros_rows[i] > w) {
above = TRUE;
if (errors)
errors[h2 + i] = TRUE;
} else if (errors)
errors[h2 + i] = FALSE;
}
if (!hasscratch)
unruly_free_scratch(scratch);
return (above ? -1 : below ? 1 : 0);
}
static int unruly_solve_game(game_state *state,
struct unruly_scratch *scratch, int diff)
{
int done, maxdiff = -1;
while (TRUE) {
done = 0;
/* Check for impending 3's */
done += unruly_solver_check_all_threes(state, scratch);
/* Keep using the simpler techniques while they produce results */
if (done) {
if (maxdiff < DIFF_EASY)
maxdiff = DIFF_EASY;
continue;
}
/* Check for completed rows */
done += unruly_solver_check_all_complete_nums(state, scratch);
if (done) {
if (maxdiff < DIFF_EASY)
maxdiff = DIFF_EASY;
continue;
}
/* Check for impending failures of row/column uniqueness, if
* it's enabled in this game mode */
if (state->unique) {
done += unruly_solver_check_all_uniques(state, scratch);
if (done) {
if (maxdiff < DIFF_EASY)
maxdiff = DIFF_EASY;
continue;
}
}
/* Normal techniques */
if (diff < DIFF_NORMAL)
break;
/* Check for nearly completed rows */
done += unruly_solver_check_all_near_complete(state, scratch);
if (done) {
if (maxdiff < DIFF_NORMAL)
maxdiff = DIFF_NORMAL;
continue;
}
break;
}
return maxdiff;
}
static char *solve_game(const game_state *state, const game_state *currstate,
const char *aux, char **error)
{
game_state *solved = dup_game(state);
struct unruly_scratch *scratch = unruly_new_scratch(solved);
char *ret = NULL;
int result;
unruly_solve_game(solved, scratch, DIFFCOUNT);
result = unruly_validate_counts(solved, scratch, NULL);
if (unruly_validate_all_rows(solved, NULL) == -1)
result = -1;
if (result == 0) {
int w2 = solved->w2, h2 = solved->h2;
int s = w2 * h2;
char *p;
int i;
ret = snewn(s + 2, char);
p = ret;
*p++ = 'S';
for (i = 0; i < s; i++)
*p++ = (solved->grid[i] == N_ONE ? '1' : '0');
*p++ = '\0';
} else if (result == 1)
*error = "No solution found.";
else if (result == -1)
*error = "Puzzle is invalid.";
free_game(solved);
unruly_free_scratch(scratch);
return ret;
}
/* ********* *
* Generator *
* ********* */
static int unruly_fill_game(game_state *state, struct unruly_scratch *scratch,
random_state *rs)
{
int w2 = state->w2, h2 = state->h2;
int s = w2 * h2;
int i, j;
int *spaces;
#ifdef STANDALONE_SOLVER
if (solver_verbose) {
printf("Generator: Attempt to fill grid\n");
}
#endif
/* Generate random array of spaces */
spaces = snewn(s, int);
for (i = 0; i < s; i++)
spaces[i] = i;
shuffle(spaces, s, sizeof(*spaces), rs);
/*
* Construct a valid filled grid by repeatedly picking an unfilled
* space and fill it, then calling the solver to fill in any
* spaces forced by the change.
*/
for (j = 0; j < s; j++) {
i = spaces[j];
if (state->grid[i] != EMPTY)
continue;
if (random_upto(rs, 2)) {
state->grid[i] = N_ONE;
scratch->ones_rows[i / w2]++;
scratch->ones_cols[i % w2]++;
} else {
state->grid[i] = N_ZERO;
scratch->zeros_rows[i / w2]++;
scratch->zeros_cols[i % w2]++;
}
unruly_solve_game(state, scratch, DIFFCOUNT);
}
sfree(spaces);
if (unruly_validate_all_rows(state, NULL) != 0
|| unruly_validate_counts(state, scratch, NULL) != 0)
return FALSE;
return TRUE;
}
static char *new_game_desc(const game_params *params, random_state *rs,
char **aux, int interactive)
{
#ifdef STANDALONE_SOLVER
char *debug;
int temp_verbose = FALSE;
#endif
int w2 = params->w2, h2 = params->h2;
int s = w2 * h2;
int *spaces;
int i, j, run;
char *ret, *p;
game_state *state;
struct unruly_scratch *scratch;
int attempts = 0;
while (1) {
while (TRUE) {
attempts++;
state = blank_state(w2, h2, params->unique);
scratch = unruly_new_scratch(state);
if (unruly_fill_game(state, scratch, rs))
break;
free_game(state);
unruly_free_scratch(scratch);
}
#ifdef STANDALONE_SOLVER
if (solver_verbose) {
printf("Puzzle generated in %i attempts\n", attempts);
debug = game_text_format(state);
fputs(debug, stdout);
sfree(debug);
temp_verbose = solver_verbose;
solver_verbose = FALSE;
}
#endif
unruly_free_scratch(scratch);
/* Generate random array of spaces */
spaces = snewn(s, int);
for (i = 0; i < s; i++)
spaces[i] = i;
shuffle(spaces, s, sizeof(*spaces), rs);
/*
* Winnow the clues by starting from our filled grid, repeatedly
* picking a filled space and emptying it, as long as the solver
* reports that the puzzle can still be solved after doing so.
*/
for (j = 0; j < s; j++) {
char c;
game_state *solver;
i = spaces[j];
c = state->grid[i];
state->grid[i] = EMPTY;
solver = dup_game(state);
scratch = unruly_new_scratch(state);
unruly_solve_game(solver, scratch, params->diff);
if (unruly_validate_counts(solver, scratch, NULL) != 0)
state->grid[i] = c;
free_game(solver);
unruly_free_scratch(scratch);
}
sfree(spaces);
#ifdef STANDALONE_SOLVER
if (temp_verbose) {
solver_verbose = TRUE;
printf("Final puzzle:\n");
debug = game_text_format(state);
fputs(debug, stdout);
sfree(debug);
}
#endif
/*
* See if the game has accidentally come out too easy.
*/
if (params->diff > 0) {
int ok;
game_state *solver;
solver = dup_game(state);
scratch = unruly_new_scratch(state);
unruly_solve_game(solver, scratch, params->diff - 1);
ok = unruly_validate_counts(solver, scratch, NULL);
free_game(solver);
unruly_free_scratch(scratch);
if (ok)
break;
} else {
/*
* Puzzles of the easiest difficulty can't be too easy.
*/
break;
}
}
/* Encode description */
ret = snewn(s + 1, char);
p = ret;
run = 0;
for (i = 0; i < s+1; i++) {
if (i == s || state->grid[i] == N_ZERO) {
while (run > 24) {
*p++ = 'z';
run -= 25;
}
*p++ = 'a' + run;
run = 0;
} else if (state->grid[i] == N_ONE) {
while (run > 24) {
*p++ = 'Z';
run -= 25;
}
*p++ = 'A' + run;
run = 0;
} else {
run++;
}
}
*p = '\0';
free_game(state);
return ret;
}
/* ************** *
* User Interface *
* ************** */
struct game_ui {
int cx, cy;
char cursor;
};
static game_ui *new_ui(const game_state *state)
{
game_ui *ret = snew(game_ui);
ret->cx = ret->cy = 0;
ret->cursor = FALSE;
return ret;
}
static void free_ui(game_ui *ui)
{
sfree(ui);
}
static char *encode_ui(const game_ui *ui)
{
return NULL;
}
static void decode_ui(game_ui *ui, const char *encoding)
{
}
static void game_changed_state(game_ui *ui, const game_state *oldstate,
const game_state *newstate)
{
}
struct game_drawstate {
int tilesize;
int w2, h2;
int started;
int *gridfs;
int *rowfs;
int *grid;
};
static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
{
struct game_drawstate *ds = snew(struct game_drawstate);
int w2 = state->w2, h2 = state->h2;
int s = w2 * h2;
int i;
ds->tilesize = 0;
ds->w2 = w2;
ds->h2 = h2;
ds->started = FALSE;
ds->gridfs = snewn(s, int);
ds->rowfs = snewn(2 * (w2 + h2), int);
ds->grid = snewn(s, int);
for (i = 0; i < s; i++)
ds->grid[i] = -1;
return ds;
}
static void game_free_drawstate(drawing *dr, game_drawstate *ds)
{
sfree(ds->gridfs);
sfree(ds->rowfs);
sfree(ds->grid);
sfree(ds);
}
#define COORD(x) ( (x) * ds->tilesize + ds->tilesize/2 )
#define FROMCOORD(x) ( ((x)-(ds->tilesize/2)) / ds->tilesize )
static char *interpret_move(const game_state *state, game_ui *ui,
const game_drawstate *ds,
int ox, int oy, int button)
{
int hx = ui->cx;
int hy = ui->cy;
int gx = FROMCOORD(ox);
int gy = FROMCOORD(oy);
int w2 = state->w2, h2 = state->h2;
button &= ~MOD_MASK;
/* Mouse click */
if (button == LEFT_BUTTON || button == RIGHT_BUTTON ||
button == MIDDLE_BUTTON) {
if (ox >= (ds->tilesize / 2) && gx < w2
&& oy >= (ds->tilesize / 2) && gy < h2) {
hx = gx;
hy = gy;
ui->cursor = FALSE;
} else
return NULL;
}
/* Keyboard move */
if (IS_CURSOR_MOVE(button)) {
move_cursor(button, &ui->cx, &ui->cy, w2, h2, 0);
ui->cursor = TRUE;
return "";
}
/* Place one */
if ((ui->cursor && (button == CURSOR_SELECT || button == CURSOR_SELECT2
|| button == '\b' || button == '0' || button == '1'
|| button == '2')) ||
button == LEFT_BUTTON || button == RIGHT_BUTTON ||
button == MIDDLE_BUTTON) {
char buf[80];
char c, i;
if (state->immutable[hy * w2 + hx])
return NULL;
c = '-';
i = state->grid[hy * w2 + hx];
if (button == '0' || button == '2')
c = '0';
else if (button == '1')
c = '1';
else if (button == MIDDLE_BUTTON)
c = '-';
/* Cycle through options */
else if (button == CURSOR_SELECT2 || button == RIGHT_BUTTON)
c = (i == EMPTY ? '0' : i == N_ZERO ? '1' : '-');
else if (button == CURSOR_SELECT || button == LEFT_BUTTON)
c = (i == EMPTY ? '1' : i == N_ONE ? '0' : '-');
if (state->grid[hy * w2 + hx] ==
(c == '0' ? N_ZERO : c == '1' ? N_ONE : EMPTY))
return NULL; /* don't put no-ops on the undo chain */
sprintf(buf, "P%c,%d,%d", c, hx, hy);
return dupstr(buf);
}
return NULL;
}
static game_state *execute_move(const game_state *state, const char *move)
{
int w2 = state->w2, h2 = state->h2;
int s = w2 * h2;
int x, y, i;
char c;
game_state *ret;
if (move[0] == 'S') {
const char *p;
ret = dup_game(state);
p = move + 1;
for (i = 0; i < s; i++) {
if (!*p || !(*p == '1' || *p == '0')) {
free_game(ret);
return NULL;
}
ret->grid[i] = (*p == '1' ? N_ONE : N_ZERO);
p++;
}
ret->completed = ret->cheated = TRUE;
return ret;
} else if (move[0] == 'P'
&& sscanf(move + 1, "%c,%d,%d", &c, &x, &y) == 3 && x >= 0
&& x < w2 && y >= 0 && y < h2 && (c == '-' || c == '0'
|| c == '1')) {
ret = dup_game(state);
i = y * w2 + x;
if (state->immutable[i]) {
free_game(ret);
return NULL;
}
ret->grid[i] = (c == '1' ? N_ONE : c == '0' ? N_ZERO : EMPTY);
if (!ret->completed && unruly_validate_counts(ret, NULL, NULL) == 0
&& (unruly_validate_all_rows(ret, NULL) == 0))
ret->completed = TRUE;
return ret;
}
return NULL;
}
/* ----------------------------------------------------------------------
* Drawing routines.
*/
static void game_compute_size(const game_params *params, int tilesize,
int *x, int *y)
{
*x = tilesize * (params->w2 + 1);
*y = tilesize * (params->h2 + 1);
}
static void game_set_size(drawing *dr, game_drawstate *ds,
const game_params *params, int tilesize)
{
ds->tilesize = tilesize;
}
static float *game_colours(frontend *fe, int *ncolours)
{
float *ret = snewn(3 * NCOLOURS, float);
int i;
frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
for (i = 0; i < 3; i++) {
ret[COL_1 * 3 + i] = 0.2F;
ret[COL_1_HIGHLIGHT * 3 + i] = 0.4F;
ret[COL_1_LOWLIGHT * 3 + i] = 0.0F;
ret[COL_0 * 3 + i] = 0.95F;
ret[COL_0_HIGHLIGHT * 3 + i] = 1.0F;
ret[COL_0_LOWLIGHT * 3 + i] = 0.9F;
ret[COL_EMPTY * 3 + i] = 0.5F;
ret[COL_GRID * 3 + i] = 0.3F;
}
game_mkhighlight_specific(fe, ret, COL_0, COL_0_HIGHLIGHT, COL_0_LOWLIGHT);
game_mkhighlight_specific(fe, ret, COL_1, COL_1_HIGHLIGHT, COL_1_LOWLIGHT);
ret[COL_ERROR * 3 + 0] = 1.0F;
ret[COL_ERROR * 3 + 1] = 0.0F;
ret[COL_ERROR * 3 + 2] = 0.0F;
ret[COL_CURSOR * 3 + 0] = 0.0F;
ret[COL_CURSOR * 3 + 1] = 0.7F;
ret[COL_CURSOR * 3 + 2] = 0.0F;
*ncolours = NCOLOURS;
return ret;
}
static void unruly_draw_err_rectangle(drawing *dr, int x, int y, int w, int h,
int tilesize)
{
double thick = tilesize / 10;
double margin = tilesize / 20;
draw_rect(dr, x+margin, y+margin, w-2*margin, thick, COL_ERROR);
draw_rect(dr, x+margin, y+margin, thick, h-2*margin, COL_ERROR);
draw_rect(dr, x+margin, y+h-margin-thick, w-2*margin, thick, COL_ERROR);
draw_rect(dr, x+w-margin-thick, y+margin, thick, h-2*margin, COL_ERROR);
}
static void unruly_draw_tile(drawing *dr, int x, int y, int tilesize, int tile)
{
clip(dr, x, y, tilesize, tilesize);
/* Draw the grid edge first, so the tile can overwrite it */
draw_rect(dr, x, y, tilesize, tilesize, COL_GRID);
/* Background of the tile */
{
int val = (tile & FF_ZERO ? 0 : tile & FF_ONE ? 2 : 1);
val = (val == 0 ? COL_0 : val == 2 ? COL_1 : COL_EMPTY);
if ((tile & (FF_FLASH1 | FF_FLASH2)) &&
(val == COL_0 || val == COL_1)) {
val += (tile & FF_FLASH1 ? 1 : 2);
}
draw_rect(dr, x, y, tilesize-1, tilesize-1, val);
if ((val == COL_0 || val == COL_1) && (tile & FF_IMMUTABLE)) {
draw_rect(dr, x + tilesize/6, y + tilesize/6,
tilesize - 2*(tilesize/6) - 2, 1, val + 2);
draw_rect(dr, x + tilesize/6, y + tilesize/6,
1, tilesize - 2*(tilesize/6) - 2, val + 2);
draw_rect(dr, x + tilesize/6 + 1, y + tilesize - tilesize/6 - 2,
tilesize - 2*(tilesize/6) - 2, 1, val + 1);
draw_rect(dr, x + tilesize - tilesize/6 - 2, y + tilesize/6 + 1,
1, tilesize - 2*(tilesize/6) - 2, val + 1);
}
}
/* 3-in-a-row errors */
if (tile & (FE_HOR_ROW_LEFT | FE_HOR_ROW_RIGHT)) {
int left = x, right = x + tilesize - 1;
if ((tile & FE_HOR_ROW_LEFT))
right += tilesize/2;
if ((tile & FE_HOR_ROW_RIGHT))
left -= tilesize/2;
unruly_draw_err_rectangle(dr, left, y, right-left, tilesize-1, tilesize);
}
if (tile & (FE_VER_ROW_TOP | FE_VER_ROW_BOTTOM)) {
int top = y, bottom = y + tilesize - 1;
if ((tile & FE_VER_ROW_TOP))
bottom += tilesize/2;
if ((tile & FE_VER_ROW_BOTTOM))
top -= tilesize/2;
unruly_draw_err_rectangle(dr, x, top, tilesize-1, bottom-top, tilesize);
}
/* Count errors */
if (tile & FE_COUNT) {
draw_text(dr, x + tilesize/2, y + tilesize/2, FONT_VARIABLE,
tilesize/2, ALIGN_HCENTRE | ALIGN_VCENTRE, COL_ERROR, "!");
}
/* Row-match errors */
if (tile & FE_ROW_MATCH) {
draw_rect(dr, x, y+tilesize/2-tilesize/12,
tilesize, 2*(tilesize/12), COL_ERROR);
}
if (tile & FE_COL_MATCH) {
draw_rect(dr, x+tilesize/2-tilesize/12, y,
2*(tilesize/12), tilesize, COL_ERROR);
}
/* Cursor rectangle */
if (tile & FF_CURSOR) {
draw_rect(dr, x, y, tilesize/12, tilesize-1, COL_CURSOR);
draw_rect(dr, x, y, tilesize-1, tilesize/12, COL_CURSOR);
draw_rect(dr, x+tilesize-1-tilesize/12, y, tilesize/12, tilesize-1,
COL_CURSOR);
draw_rect(dr, x, y+tilesize-1-tilesize/12, tilesize-1, tilesize/12,
COL_CURSOR);
}
unclip(dr);
draw_update(dr, x, y, tilesize, tilesize);
}
#define TILE_SIZE (ds->tilesize)
#define DEFAULT_TILE_SIZE 32
#define FLASH_FRAME 0.12F
#define FLASH_TIME (FLASH_FRAME * 3)
static void game_redraw(drawing *dr, game_drawstate *ds,
const game_state *oldstate, const game_state *state,
int dir, const game_ui *ui,
float animtime, float flashtime)
{
int w2 = state->w2, h2 = state->h2;
int s = w2 * h2;
int flash;
int x, y, i;
if (!ds->started) {
/* Main window background */
draw_rect(dr, 0, 0, TILE_SIZE * (w2+1), TILE_SIZE * (h2+1),
COL_BACKGROUND);
/* Outer edge of grid */
draw_rect(dr, COORD(0)-TILE_SIZE/10, COORD(0)-TILE_SIZE/10,
TILE_SIZE*w2 + 2*(TILE_SIZE/10) - 1,
TILE_SIZE*h2 + 2*(TILE_SIZE/10) - 1, COL_GRID);
draw_update(dr, 0, 0, TILE_SIZE * (w2+1), TILE_SIZE * (h2+1));
ds->started = TRUE;
}
flash = 0;
if (flashtime > 0)
flash = (int)(flashtime / FLASH_FRAME) == 1 ? FF_FLASH2 : FF_FLASH1;
for (i = 0; i < s; i++)
ds->gridfs[i] = 0;
unruly_validate_all_rows(state, ds->gridfs);
for (i = 0; i < 2 * (h2 + w2); i++)
ds->rowfs[i] = 0;
unruly_validate_counts(state, NULL, ds->rowfs);
for (y = 0; y < h2; y++) {
for (x = 0; x < w2; x++) {
int tile;
i = y * w2 + x;
tile = ds->gridfs[i];
if (state->grid[i] == N_ONE) {
tile |= FF_ONE;
if (ds->rowfs[y] || ds->rowfs[2*h2 + x])
tile |= FE_COUNT;
} else if (state->grid[i] == N_ZERO) {
tile |= FF_ZERO;
if (ds->rowfs[h2 + y] || ds->rowfs[2*h2 + w2 + x])
tile |= FE_COUNT;
}
tile |= flash;
if (state->immutable[i])
tile |= FF_IMMUTABLE;
if (ui->cursor && ui->cx == x && ui->cy == y)
tile |= FF_CURSOR;
if (ds->grid[i] != tile) {
ds->grid[i] = tile;
unruly_draw_tile(dr, COORD(x), COORD(y), TILE_SIZE, tile);
}
}
}
}
static float game_anim_length(const game_state *oldstate,
const game_state *newstate, int dir, game_ui *ui)
{
return 0.0F;
}
static float game_flash_length(const game_state *oldstate,
const game_state *newstate, int dir, game_ui *ui)
{
if (!oldstate->completed && newstate->completed &&
!oldstate->cheated && !newstate->cheated)
return FLASH_TIME;
return 0.0F;
}
static int game_status(const game_state *state)
{
return state->completed ? +1 : 0;
}
static int game_timing_state(const game_state *state, game_ui *ui)
{
return TRUE;
}
static void game_print_size(const game_params *params, float *x, float *y)
{
int pw, ph;
/* Using 7mm squares */
game_compute_size(params, 700, &pw, &ph);
*x = pw / 100.0F;
*y = ph / 100.0F;
}
static void game_print(drawing *dr, const game_state *state, int tilesize)
{
int w2 = state->w2, h2 = state->h2;
int x, y;
int ink = print_mono_colour(dr, 0);
for (y = 0; y < h2; y++)
for (x = 0; x < w2; x++) {
int tx = x * tilesize + (tilesize / 2);
int ty = y * tilesize + (tilesize / 2);
/* Draw the border */
int coords[8];
coords[0] = tx;
coords[1] = ty - 1;
coords[2] = tx + tilesize;
coords[3] = ty - 1;
coords[4] = tx + tilesize;
coords[5] = ty + tilesize - 1;
coords[6] = tx;
coords[7] = ty + tilesize - 1;
draw_polygon(dr, coords, 4, -1, ink);
if (state->grid[y * w2 + x] == N_ONE)
draw_rect(dr, tx, ty, tilesize, tilesize, ink);
else if (state->grid[y * w2 + x] == N_ZERO)
draw_circle(dr, tx + tilesize/2, ty + tilesize/2,
tilesize/12, ink, ink);
}
}
#ifdef COMBINED
#define thegame unruly
#endif
const struct game thegame = {
"Unruly", "games.unruly", "unruly",
default_params,
game_fetch_preset,
decode_params,
encode_params,
free_params,
dup_params,
TRUE, game_configure, custom_params,
validate_params,
new_game_desc,
validate_desc,
new_game,
dup_game,
free_game,
TRUE, solve_game,
TRUE, game_can_format_as_text_now, game_text_format,
new_ui,
free_ui,
encode_ui,
decode_ui,
game_changed_state,
interpret_move,
execute_move,
DEFAULT_TILE_SIZE, game_compute_size, game_set_size,
game_colours,
game_new_drawstate,
game_free_drawstate,
game_redraw,
game_anim_length,
game_flash_length,
game_status,
TRUE, FALSE, game_print_size, game_print,
FALSE, /* wants_statusbar */
FALSE, game_timing_state,
0, /* flags */
};
/* ***************** *
* Standalone solver *
* ***************** */
#ifdef STANDALONE_SOLVER
#include <time.h>
#include <stdarg.h>
/* Most of the standalone solver code was copied from unequal.c and singles.c */
const char *quis;
static void usage_exit(const char *msg)
{
if (msg)
fprintf(stderr, "%s: %s\n", quis, msg);
fprintf(stderr,
"Usage: %s [-v] [--seed SEED] <params> | [game_id [game_id ...]]\n",
quis);
exit(1);
}
int main(int argc, char *argv[])
{
random_state *rs;
time_t seed = time(NULL);
game_params *params = NULL;
char *id = NULL, *desc = NULL, *err;
quis = argv[0];
while (--argc > 0) {
char *p = *++argv;
if (!strcmp(p, "--seed")) {
if (argc == 0)
usage_exit("--seed needs an argument");
seed = (time_t) atoi(*++argv);
argc--;
} else if (!strcmp(p, "-v"))
solver_verbose = TRUE;
else if (*p == '-')
usage_exit("unrecognised option");
else
id = p;
}
if (id) {
desc = strchr(id, ':');
if (desc)
*desc++ = '\0';
params = default_params();
decode_params(params, id);
err = validate_params(params, TRUE);
if (err) {
fprintf(stderr, "Parameters are invalid\n");
fprintf(stderr, "%s: %s", argv[0], err);
exit(1);
}
}
if (!desc) {
char *desc_gen, *aux;
rs = random_new((void *) &seed, sizeof(time_t));
if (!params)
params = default_params();
printf("Generating puzzle with parameters %s\n",
encode_params(params, TRUE));
desc_gen = new_game_desc(params, rs, &aux, FALSE);
if (!solver_verbose) {
char *fmt = game_text_format(new_game(NULL, params, desc_gen));
fputs(fmt, stdout);
sfree(fmt);
}
printf("Game ID: %s\n", desc_gen);
} else {
game_state *input;
struct unruly_scratch *scratch;
int maxdiff, errcode;
err = validate_desc(params, desc);
if (err) {
fprintf(stderr, "Description is invalid\n");
fprintf(stderr, "%s", err);
exit(1);
}
input = new_game(NULL, params, desc);
scratch = unruly_new_scratch(input);
maxdiff = unruly_solve_game(input, scratch, DIFFCOUNT);
errcode = unruly_validate_counts(input, scratch, NULL);
if (unruly_validate_all_rows(input, NULL) == -1)
errcode = -1;
if (errcode != -1) {
char *fmt = game_text_format(input);
fputs(fmt, stdout);
sfree(fmt);
if (maxdiff < 0)
printf("Difficulty: already solved!\n");
else
printf("Difficulty: %s\n", unruly_diffnames[maxdiff]);
}
if (errcode == 1)
printf("No solution found.\n");
else if (errcode == -1)
printf("Puzzle is invalid.\n");
free_game(input);
unruly_free_scratch(scratch);
}
return 0;
}
#endif
| 0 | 0.942563 | 1 | 0.942563 | game-dev | MEDIA | 0.483149 | game-dev | 0.829852 | 1 | 0.829852 |
qaul/qaul.net_legacy | 7,022 | olsrd-0.6.6.2/lib/bmf/src/olsrd_plugin.c | /*
* OLSR Basic Multicast Forwarding (BMF) plugin.
* Copyright (c) 2005 - 2007, Thales Communications, Huizen, The Netherlands.
* Written by Erik Tromp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Thales, BMF nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* -------------------------------------------------------------------------
* File : olsrd_plugin.c
* Description: Interface to the OLSRD plugin system
* Created : 29 Jun 2006
*
* ------------------------------------------------------------------------- */
/* System includes */
#include <assert.h> /* assert() */
#include <stddef.h> /* NULL */
/* OLSRD includes */
#include "olsrd_plugin.h"
#include "plugin_util.h"
#include "defs.h" /* olsr_u8_t, olsr_cnf */
#include "scheduler.h" /* olsr_start_timer() */
/* BMF includes */
#include "Bmf.h" /* InitBmf(), CloseBmf() */
#include "PacketHistory.h" /* InitPacketHistory() */
#include "NetworkInterfaces.h" /* AddNonOlsrBmfIf(), SetBmfInterfaceIp(), ... */
#include "Address.h" /* DoLocalBroadcast() */
static void __attribute__ ((constructor)) my_init(void);
static void __attribute__ ((destructor)) my_fini(void);
void olsr_plugin_exit(void);
/* -------------------------------------------------------------------------
* Function : olsrd_plugin_interface_version
* Description: Plugin interface version
* Input : none
* Output : none
* Return : BMF plugin interface version number
* Data Used : none
* Notes : Called by main OLSRD (olsr_load_dl) to check plugin interface
* version
* ------------------------------------------------------------------------- */
int olsrd_plugin_interface_version(void)
{
return PLUGIN_INTERFACE_VERSION;
}
/* -------------------------------------------------------------------------
* Function : olsrd_plugin_init
* Description: Plugin initialisation
* Input : none
* Output : none
* Return : fail (0) or success (1)
* Data Used : olsr_cnf
* Notes : Called by main OLSRD (init_olsr_plugin) to initialize plugin
* ------------------------------------------------------------------------- */
int olsrd_plugin_init(void)
{
/* Check validity */
if (olsr_cnf->ip_version != AF_INET)
{
fprintf(stderr, PLUGIN_NAME ": This plugin only supports IPv4!\n");
return 0;
}
/* Clear the packet history */
InitPacketHistory();
/* Register ifchange function */
olsr_add_ifchange_handler(&InterfaceChange);
/* Register the duplicate registration pruning process */
olsr_start_timer(3 * MSEC_PER_SEC, 0, OLSR_TIMER_PERIODIC,
&PrunePacketHistory, NULL, 0);
return InitBmf(NULL);
}
/* -------------------------------------------------------------------------
* Function : olsr_plugin_exit
* Description: Plugin cleanup
* Input : none
* Output : none
* Return : none
* Data Used : none
* Notes : Called by my_fini() at unload of shared object
* ------------------------------------------------------------------------- */
void olsr_plugin_exit(void)
{
CloseBmf();
}
static const struct olsrd_plugin_parameters plugin_parameters[] = {
{ .name = "NonOlsrIf", .set_plugin_parameter = &AddNonOlsrBmfIf, .data = NULL },
{ .name = "DoLocalBroadcast", .set_plugin_parameter = &DoLocalBroadcast, .data = NULL },
{ .name = "BmfInterface", .set_plugin_parameter = &SetBmfInterfaceName, .data = NULL },
{ .name = "BmfInterfaceIp", .set_plugin_parameter = &SetBmfInterfaceIp, .data = NULL },
{ .name = "BmfInterfacePersistent", .set_plugin_parameter = &SetBmfInterfacePersistent, .data = NULL },
{ .name = "CapturePacketsOnOlsrInterfaces", .set_plugin_parameter = &SetCapturePacketsOnOlsrInterfaces, .data = NULL },
{ .name = "BmfMechanism", .set_plugin_parameter = &SetBmfMechanism, .data = NULL },
{ .name = "FanOutLimit", .set_plugin_parameter = &SetFanOutLimit, .data = NULL },
{ .name = "BroadcastRetransmitCount", .set_plugin_parameter = &set_plugin_int, .data = &BroadcastRetransmitCount},
};
/* -------------------------------------------------------------------------
* Function : olsrd_get_plugin_parameters
* Description: Return the parameter table and its size
* Input : none
* Output : params - the parameter table
* size - its size in no. of entries
* Return : none
* Data Used : plugin_parameters
* Notes : Called by main OLSR (init_olsr_plugin) for all plugins
* ------------------------------------------------------------------------- */
void olsrd_get_plugin_parameters(const struct olsrd_plugin_parameters **params, int *size)
{
*params = plugin_parameters;
*size = sizeof(plugin_parameters)/sizeof(*plugin_parameters);
}
/* -------------------------------------------------------------------------
* Function : my_init
* Description: Plugin constructor
* Input : none
* Output : none
* Return : none
* Data Used : none
* Notes : Called at load of shared object
* ------------------------------------------------------------------------- */
static void my_init(void)
{
/* Print plugin info to stdout */
printf("%s\n", MOD_DESC);
return;
}
/* -------------------------------------------------------------------------
* Function : my_fini
* Description: Plugin destructor
* Input : none
* Output : none
* Return : none
* Data Used : none
* Notes : Called at unload of shared object
* ------------------------------------------------------------------------- */
static void my_fini(void)
{
olsr_plugin_exit();
}
| 0 | 0.910355 | 1 | 0.910355 | game-dev | MEDIA | 0.201385 | game-dev | 0.746193 | 1 | 0.746193 |
modio/modio-sdk-legacy | 1,691 | include/c/methods/callbacks/ModCallbacks.h | #ifndef MODIO_MODCALLBACKS_H
#define MODIO_MODCALLBACKS_H
#include "../../../Globals.h"
#include "../../../wrappers/MinizipWrapper.h"
#include "../../../wrappers/CurlWrapper.h"
#include "../../schemas/ModioResponse.h"
#include "../../schemas/ModioMod.h"
#include "../../../ModUtility.h"
#include "../../../ModioUtility.h"
struct GetModParams
{
void* object;
void (*callback)(void* object, ModioResponse response, ModioMod mod);
};
struct GetAllModsParams
{
std::string url;
bool is_cache;
std::vector<void*> objects;
std::vector<void(*)(void* object, ModioResponse response, ModioMod mods[], u32 mods_size)> callbacks;
};
struct AddModParams
{
void* object;
void (*callback)(void* object, ModioResponse response, ModioMod mod);
};
struct CallbackParamReturnsId
{
void* object;
u32 mod_id;
void (*callback)(void* object, ModioResponse response, u32 mod_id);
};
extern std::map< u32,GetModParams* > get_mod_callbacks;
extern std::map< u32,AddModParams* > add_mod_callbacks;
extern std::map< u32,GenericRequestParams* > delete_mod_callbacks;
extern std::map< u32,GetAllModsParams* > get_all_mods_callbacks;
extern std::map< u32,CallbackParamReturnsId* > return_id_callbacks;
void modioOnGetMod(u32 call_number, u32 response_code, nlohmann::json response_json);
void modioOnGetAllMods(u32 call_number, u32 response_code, nlohmann::json response_json);
void modioOnModAdded(u32 call_number, u32 response_code, nlohmann::json response_json);
void modioOnModDeleted(u32 call_number, u32 response_code, nlohmann::json response_json);
void modioOnReturnIdCallback(u32 call_number, u32 response_code, nlohmann::json response_json);
void clearModCallbackParams();
#endif
| 0 | 0.508409 | 1 | 0.508409 | game-dev | MEDIA | 0.488151 | game-dev | 0.517076 | 1 | 0.517076 |
AlanLaboratory/UnrealMLAgents | 11,639 | Source/UnrealMLAgents/Private/Actuators/ActuatorManager.cpp | // Copyright © 2025 Stephane Capponi and individual contributors. All Rights Reserved.
#include "UnrealMLAgents/Actuators/ActuatorManager.h"
// Initialize with a preset capacity
void UActuatorManager::Initialize(int32 Capacity)
{
Actuators.Reserve(Capacity);
}
// Ready actuators for execution
void UActuatorManager::ReadyActuatorsForExecution()
{
ReadyActuatorsForExecution(Actuators, NumContinuousActions, SumOfDiscreteBranchSizes, NumDiscreteActions);
}
const UActuatorDiscreteActionMask& UActuatorManager::GetDiscreteActionMask() const
{
return *DiscreteActionMask;
}
// Helper method for readying actuators
void UActuatorManager::ReadyActuatorsForExecution(const TArray<TScriptInterface<IActuator>>& InActuators,
int32 InNumContinuousActions, int32 InSumOfDiscreteBranchSizes, int32 InNumDiscreteBranches)
{
if (bReadyForExecution)
{
return;
}
#if UE_BUILD_DEBUG
// Make sure the names are actually unique
ValidateActuators();
#endif
// Sort the Actuators by name to ensure determinism
SortActuators(Actuators);
TSharedPtr<TArray<int32>> DiscreteActionArray = MakeShared<TArray<int32>>();
DiscreteActionArray->Init(0, InNumDiscreteBranches);
TSharedPtr<TArray<float>> ContinuousActionArray = MakeShared<TArray<float>>();
ContinuousActionArray->Init(0.0f, InNumContinuousActions);
FActionSegment<int32> DiscreteActions =
(InNumDiscreteBranches == 0) ? FActionSegment<int32>::Empty : FActionSegment<int32>(DiscreteActionArray);
FActionSegment<float> ContinuousActions =
(InNumContinuousActions == 0) ? FActionSegment<float>::Empty : FActionSegment<float>(ContinuousActionArray);
StoredActions = FActionBuffers(ContinuousActions, DiscreteActions);
CombinedActionSpec = CombineActionSpecs(InActuators);
DiscreteActionMask = NewObject<UActuatorDiscreteActionMask>();
DiscreteActionMask->Initialize(
InActuators, InSumOfDiscreteBranchSizes, InNumDiscreteBranches, CombinedActionSpec.BranchSizes);
bReadyForExecution = true;
}
// Combine action specs
FActionSpec UActuatorManager::CombineActionSpecs(const TArray<TScriptInterface<IActuator>>& InActuators)
{
int32 NumContinuousActions = 0;
int32 NumDiscreteActions = 0;
for (const auto& Actuator : InActuators)
{
NumContinuousActions += Actuator->GetActionSpec().NumContinuousActions;
NumDiscreteActions += Actuator->GetActionSpec().GetNumDiscreteActions();
}
TArray<int32> CombinedBranchSizes;
if (NumDiscreteActions == 0)
{
CombinedBranchSizes.Empty();
}
else
{
CombinedBranchSizes.SetNum(NumDiscreteActions);
int32 Start = 0;
for (const auto& Actuator : InActuators)
{
const TArray<int32>& BranchSizes = Actuator->GetActionSpec().BranchSizes;
if (BranchSizes.Num() > 0)
{
FMemory::Memcpy(
CombinedBranchSizes.GetData() + Start, BranchSizes.GetData(), BranchSizes.Num() * sizeof(int32));
Start += BranchSizes.Num();
}
}
}
return FActionSpec(NumContinuousActions, CombinedBranchSizes);
}
// Returns an ActionSpec representing the concatenation of all IActuator's ActionSpecs
FActionSpec UActuatorManager::GetCombinedActionSpec()
{
ReadyActuatorsForExecution();
return CombinedActionSpec;
}
// Updates the local action buffer
void UActuatorManager::UpdateActions(const FActionBuffers& Actions)
{
ReadyActuatorsForExecution();
UpdateActionArray<float>(Actions.ContinuousActions, StoredActions.ContinuousActions);
UpdateActionArray<int32>(Actions.DiscreteActions, StoredActions.DiscreteActions);
}
template <typename T>
void UActuatorManager::UpdateActionArray(const FActionSegment<T>& SourceActionBuffer, FActionSegment<T>& Destination)
{
if (SourceActionBuffer.Length <= 0)
{
Destination.Clear();
}
else
{
if (SourceActionBuffer.Length != Destination.Length)
{
checkf(SourceActionBuffer.Length == Destination.Length,
TEXT("sourceActionBuffer: %d is a different size than destination: %d."), SourceActionBuffer.Length,
Destination.Length);
}
// Ensure both source and destination arrays are valid
check(SourceActionBuffer.Array.IsValid() && Destination.Array.IsValid());
// Perform memory copy
FMemory::Memcpy(Destination.Array->GetData() + Destination.Offset,
SourceActionBuffer.Array->GetData() + SourceActionBuffer.Offset, SourceActionBuffer.Length * sizeof(T));
}
}
// Validate actuators
void UActuatorManager::ValidateActuators()
{
// Implementation logic to validate actuators...
for (int32 i = 0; i < Actuators.Num() - 1; i++)
{
checkf(!Actuators[i]->GetName().Equals(Actuators[i + 1]->GetName()), TEXT("Actuator names must be unique."));
}
}
// Sort actuators
void UActuatorManager::SortActuators(TArray<TScriptInterface<IActuator>>& InActuators)
{
// Implementation logic to sort actuators...
InActuators.Sort([](const TScriptInterface<IActuator>& A, const TScriptInterface<IActuator>& B) {
return A->GetName() < B->GetName();
});
}
// Write action mask
void UActuatorManager::WriteActionMask()
{
ReadyActuatorsForExecution();
DiscreteActionMask->ResetMask();
int32 Offset = 0;
for (const auto& Actuator : Actuators)
{
if (Actuator->GetActionSpec().GetNumDiscreteActions() > 0)
{
DiscreteActionMask->CurrentBranchOffset = Offset;
Actuator->WriteDiscreteActionMask(DiscreteActionMask);
Offset += Actuator->GetActionSpec().GetNumDiscreteActions();
}
}
}
// Apply heuristic
void UActuatorManager::ApplyHeuristic(const FActionBuffers& ActionBuffersOut)
{
int32 ContinuousStart = 0;
int32 DiscreteStart = 0;
for (const auto& Actuator : Actuators)
{
int32 NumberContinuousActions = Actuator->GetActionSpec().NumContinuousActions;
int32 NumberDiscreteActions = Actuator->GetActionSpec().GetNumDiscreteActions();
if (NumberContinuousActions == 0 && NumberDiscreteActions == 0)
{
continue;
}
FActionSegment<float> ContinuousActions = FActionSegment<float>::Empty;
if (NumberContinuousActions > 0)
{
ContinuousActions = FActionSegment<float>(
ActionBuffersOut.ContinuousActions.Array, ContinuousStart, NumberContinuousActions);
}
FActionSegment<int32> DiscreteActions = FActionSegment<int32>::Empty;
if (NumberDiscreteActions > 0)
{
DiscreteActions =
FActionSegment<int32>(ActionBuffersOut.DiscreteActions.Array, DiscreteStart, NumberDiscreteActions);
}
FActionBuffers TempActionBuffersOut(ContinuousActions, DiscreteActions);
Actuator->Heuristic(TempActionBuffersOut);
ContinuousStart += NumberContinuousActions;
DiscreteStart += NumberDiscreteActions;
}
}
void UActuatorManager::ExecuteActions()
{
ReadyActuatorsForExecution();
int32 ContinuousStart = 0;
int32 DiscreteStart = 0;
for (int32 i = 0; i < Actuators.Num(); i++)
{
const auto& Actuator = Actuators[i];
int32 NumberContinuousActions = Actuator->GetActionSpec().NumContinuousActions;
int32 NumberDiscreteActions = Actuator->GetActionSpec().GetNumDiscreteActions();
if (NumberContinuousActions == 0 && NumberDiscreteActions == 0)
{
continue;
}
FActionSegment<float> ContinuousActions = FActionSegment<float>::Empty;
if (NumberContinuousActions > 0)
{
ContinuousActions =
FActionSegment<float>(StoredActions.ContinuousActions.Array, ContinuousStart, NumberContinuousActions);
}
FActionSegment<int32> DiscreteActions = FActionSegment<int32>::Empty;
if (NumberDiscreteActions > 0)
{
DiscreteActions =
FActionSegment<int32>(StoredActions.DiscreteActions.Array, DiscreteStart, NumberDiscreteActions);
}
Actuator->OnActionReceived(FActionBuffers(ContinuousActions, DiscreteActions));
ContinuousStart += NumberContinuousActions;
DiscreteStart += NumberDiscreteActions;
}
}
void UActuatorManager::ResetData()
{
if (!bReadyForExecution)
{
return;
}
StoredActions.Clear();
for (int32 i = 0; i < Actuators.Num(); i++)
{
Actuators[i]->ResetData();
}
DiscreteActionMask->ResetMask();
}
void UActuatorManager::AddToBufferSizes(const TScriptInterface<IActuator>& ActuatorItem)
{
if (!ActuatorItem)
{
return;
}
NumContinuousActions += ActuatorItem->GetActionSpec().NumContinuousActions;
NumDiscreteActions += ActuatorItem->GetActionSpec().GetNumDiscreteActions();
SumOfDiscreteBranchSizes += ActuatorItem->GetActionSpec().GetSumOfDiscreteBranchSizes();
}
void UActuatorManager::SubtractFromBufferSizes(const TScriptInterface<IActuator>& ActuatorItem)
{
if (!ActuatorItem)
{
return;
}
NumContinuousActions -= ActuatorItem->GetActionSpec().NumContinuousActions;
NumDiscreteActions -= ActuatorItem->GetActionSpec().GetNumDiscreteActions();
SumOfDiscreteBranchSizes -= ActuatorItem->GetActionSpec().GetSumOfDiscreteBranchSizes();
}
void UActuatorManager::ClearBufferSizes()
{
NumContinuousActions = 0;
NumDiscreteActions = 0;
SumOfDiscreteBranchSizes = 0;
}
void UActuatorManager::AddActuators(const TArray<TScriptInterface<IActuator>>& InActuators)
{
for (const TScriptInterface<IActuator>& Actuator : InActuators)
{
Add(Actuator);
}
}
TScriptInterface<IActuator> UActuatorManager::Get(int32 Index) const
{
return Actuators[Index];
}
void UActuatorManager::Set(int32 Index, const TScriptInterface<IActuator>& Value)
{
check(!bReadyForExecution && "Cannot modify the ActuatorManager after its buffers have been initialized");
TScriptInterface<IActuator> Old = Actuators[Index];
SubtractFromBufferSizes(Old);
Actuators[Index] = Value;
AddToBufferSizes(Value);
}
void UActuatorManager::Add(const TScriptInterface<IActuator>& Item)
{
check(!bReadyForExecution && "Cannot add to the ActuatorManager after its buffers have been initialized");
Actuators.Add(Item);
AddToBufferSizes(Item);
}
void UActuatorManager::Clear()
{
check(!bReadyForExecution && "Cannot clear the ActuatorManager after its buffers have been initialized");
Actuators.Empty();
ClearBufferSizes();
}
bool UActuatorManager::Contains(const TScriptInterface<IActuator>& Item) const
{
return Actuators.Contains(Item);
}
void UActuatorManager::CopyTo(TArray<TScriptInterface<IActuator>>& OutArray, int32 ArrayIndex) const
{
OutArray.SetNum(ArrayIndex + Actuators.Num());
for (int32 i = 0; i < Actuators.Num(); ++i)
{
OutArray[ArrayIndex + i] = Actuators[i];
}
}
bool UActuatorManager::Remove(const TScriptInterface<IActuator>& Item)
{
check(!bReadyForExecution && "Cannot remove from the ActuatorManager after its buffers have been initialized");
if (Actuators.Remove(Item) > 0)
{
SubtractFromBufferSizes(Item);
return true;
}
return false;
}
int32 UActuatorManager::Count() const
{
return Actuators.Num();
}
bool UActuatorManager::IsReadOnly() const
{
return false;
}
int32 UActuatorManager::IndexOf(const TScriptInterface<IActuator>& Item) const
{
return Actuators.IndexOfByKey(Item);
}
void UActuatorManager::Insert(int32 Index, const TScriptInterface<IActuator>& Item)
{
check(!bReadyForExecution && "Cannot insert into the ActuatorManager after its buffers have been initialized");
Actuators.Insert(Item, Index);
AddToBufferSizes(Item);
}
void UActuatorManager::RemoveAt(int32 Index)
{
check(!bReadyForExecution && "Cannot remove from the ActuatorManager after its buffers have been initialized");
TScriptInterface<IActuator> Actuator = Actuators[Index];
SubtractFromBufferSizes(Actuator);
Actuators.RemoveAt(Index);
}
TScriptInterface<IActuator> UActuatorManager::operator[](int32 Index) const
{
return Get(Index);
}
TScriptInterface<IActuator>& UActuatorManager::operator[](int32 Index)
{
return Actuators[Index];
}
TArray<TScriptInterface<IActuator>>::TConstIterator UActuatorManager::CreateConstIterator() const
{
return Actuators.CreateConstIterator();
}
TArray<TScriptInterface<IActuator>>::TIterator UActuatorManager::CreateIterator()
{
return Actuators.CreateIterator();
}
| 0 | 0.810786 | 1 | 0.810786 | game-dev | MEDIA | 0.53784 | game-dev | 0.893628 | 1 | 0.893628 |
Let-s-Do-Collection/Vinery | 3,142 | common/src/main/java/net/satisfy/vinery/core/util/JuiceUtil.java | package net.satisfy.vinery.core.util;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.satisfy.vinery.core.registry.ObjectRegistry;
import net.satisfy.vinery.core.registry.TagRegistry;
import java.util.HashMap;
import java.util.Map;
public class JuiceUtil {
public static final Map<TagKey<Item>, String> RED_JUICE_TAGS = new HashMap<>();
public static final Map<TagKey<Item>, String> WHITE_JUICE_TAGS = new HashMap<>();
public static final Map<Item, String> APPLE_JUICES = new HashMap<>();
static {
addRedJuice(TagRegistry.RED_GRAPEJUICE, "general");
addRedJuice(TagRegistry.RED_SAVANNA_GRAPEJUICE, "savanna");
addRedJuice(TagRegistry.RED_TAIGA_GRAPEJUICE, "taiga");
addRedJuice(TagRegistry.RED_JUNGLE_GRAPEJUICE, "jungle");
addRedJuice(TagRegistry.CRIMSON_GRAPEJUICE, "crimson");
addWhiteJuice(TagRegistry.WHITE_GRAPEJUICE, "general");
addWhiteJuice(TagRegistry.WHITE_SAVANNA_GRAPEJUICE, "savanna");
addWhiteJuice(TagRegistry.WHITE_TAIGA_GRAPEJUICE, "taiga");
addWhiteJuice(TagRegistry.WHITE_JUNGLE_GRAPEJUICE, "jungle");
addWhiteJuice(TagRegistry.WARPED_GRAPEJUICE, "warped");
addAppleJuice(ObjectRegistry.APPLE_JUICE.get());
}
private static void addRedJuice(TagKey<Item> tag, String region) {
RED_JUICE_TAGS.put(tag, region);
}
private static void addWhiteJuice(TagKey<Item> tag, String region) {
WHITE_JUICE_TAGS.put(tag, region);
}
private static void addAppleJuice(Item item) {
APPLE_JUICES.put(item, "apple");
}
public static boolean isJuice(ItemStack stack) {
if (stack.isEmpty()) {
return false;
}
return isRedJuice(stack) || isWhiteJuice(stack) || isAppleJuice(stack);
}
private static boolean isRedJuice(ItemStack stack) {
for (TagKey<Item> tag : RED_JUICE_TAGS.keySet()) {
if (stack.is(tag)) {
return true;
}
}
return false;
}
private static boolean isWhiteJuice(ItemStack stack) {
for (TagKey<Item> tag : WHITE_JUICE_TAGS.keySet()) {
if (stack.is(tag)) {
return true;
}
}
return false;
}
private static boolean isAppleJuice(ItemStack stack) {
return APPLE_JUICES.containsKey(stack.getItem());
}
public static String getJuiceType(ItemStack stack) {
if (!isJuice(stack)) {
return "";
}
for (Map.Entry<TagKey<Item>, String> entry : RED_JUICE_TAGS.entrySet()) {
if (stack.is(entry.getKey())) {
return "red_" + entry.getValue();
}
}
for (Map.Entry<TagKey<Item>, String> entry : WHITE_JUICE_TAGS.entrySet()) {
if (stack.is(entry.getKey())) {
return "white_" + entry.getValue();
}
}
String region = APPLE_JUICES.get(stack.getItem());
if (region != null) {
return region;
}
return "";
}
}
| 0 | 0.691402 | 1 | 0.691402 | game-dev | MEDIA | 0.863582 | game-dev | 0.862149 | 1 | 0.862149 |
Unity-Technologies/ProjectTinySamples | 1,279 | TinyKitchen/Assets/Scripts/Authoring/FoodSpawner.cs | using System.Collections.Generic;
using Unity.Entities;
using UnityEngine;
namespace TinyKitchen
{
public class FoodSpawner : MonoBehaviour, IConvertGameObjectToEntity, IDeclareReferencedPrefabs
{
public List<GameObject> foodPrefabs;
// TODO spawn position
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
dstManager.AddComponentData(entity, new FoodSpawnerComponent()
{
});
// TODO temporarily placing this here
dstManager.AddComponentData(entity, new Game
{
gameState = GameState.Initialization,
score = 0,
currentLevel = 0
});
var buffer = dstManager.AddBuffer<FoodComponent>(entity);
foreach (var foodPrefab in foodPrefabs)
{
buffer.Add(new FoodComponent
{
Food = conversionSystem.GetPrimaryEntity(foodPrefab)
});
}
}
public void DeclareReferencedPrefabs(List<GameObject> referencedPrefabs)
{
referencedPrefabs.AddRange(foodPrefabs);
}
}
} | 0 | 0.711439 | 1 | 0.711439 | game-dev | MEDIA | 0.980436 | game-dev | 0.876206 | 1 | 0.876206 |
tgstation/tgstation | 30,645 | code/modules/clothing/head/jobs.dm | //defines the drill hat's yelling setting
#define DRILL_DEFAULT "default"
#define DRILL_SHOUTING "shouting"
#define DRILL_YELLING "yelling"
#define DRILL_CANADIAN "canadian"
//Chef
/obj/item/clothing/head/utility/chefhat
name = "chef's hat"
inhand_icon_state = "chefhat"
icon_state = "chef"
desc = "The commander in chef's head wear."
strip_delay = 1 SECONDS
equip_delay_other = 1 SECONDS
dog_fashion = /datum/dog_fashion/head/chef
/// The chance that the movements of a mouse inside of this hat get relayed to the human wearing the hat
var/mouse_control_probability = 20
/// Allowed time between movements
COOLDOWN_DECLARE(move_cooldown)
/// Admin variant of the chef hat where every mouse pilot input will always be transferred to the wearer
/obj/item/clothing/head/utility/chefhat/i_am_assuming_direct_control
desc = "The commander in chef's head wear. Upon closer inspection, there seem to be dozens of tiny levers, buttons, dials, and screens inside of this hat. What the hell...?"
mouse_control_probability = 100
/obj/item/clothing/head/utility/chefhat/Initialize(mapload)
. = ..()
create_storage(storage_type = /datum/storage/pockets/chefhat)
/obj/item/clothing/head/utility/chefhat/Entered(atom/movable/arrived, atom/old_loc, list/atom/old_locs)
. = ..()
var/mob/living/basic/new_boss = get_mouse(arrived)
if(!new_boss)
return
RegisterSignal(new_boss, COMSIG_MOB_PRE_EMOTED, PROC_REF(on_mouse_emote))
RegisterSignal(new_boss, COMSIG_MOVABLE_PRE_MOVE, PROC_REF(on_mouse_moving))
RegisterSignal(new_boss, COMSIG_MOB_CLIENT_PRE_LIVING_MOVE, PROC_REF(on_mouse_moving))
/obj/item/clothing/head/utility/chefhat/Exited(atom/movable/gone, direction)
. = ..()
var/mob/living/basic/old_boss = get_mouse(gone)
if(!old_boss)
return
UnregisterSignal(old_boss, list(COMSIG_MOB_PRE_EMOTED, COMSIG_MOVABLE_PRE_MOVE, COMSIG_MOB_CLIENT_PRE_LIVING_MOVE))
/// Returns a mob stored inside a mob container, if there is one
/obj/item/clothing/head/utility/chefhat/proc/get_mouse(atom/possible_mouse)
if (!ispickedupmob(possible_mouse))
return
var/obj/item/mob_holder/mousey_holder = possible_mouse
return locate(/mob/living/basic) in mousey_holder.contents
/// Relays emotes emoted by your boss to the hat wearer for full immersion
/obj/item/clothing/head/utility/chefhat/proc/on_mouse_emote(mob/living/source, key, emote_message, type_override)
SIGNAL_HANDLER
var/mob/living/carbon/wearer = loc
if(!wearer || INCAPACITATED_IGNORING(wearer, INCAPABLE_RESTRAINTS))
return
if (!prob(mouse_control_probability))
return COMPONENT_CANT_EMOTE
INVOKE_ASYNC(wearer, TYPE_PROC_REF(/mob, emote), key, type_override, emote_message, FALSE)
return COMPONENT_CANT_EMOTE
/// Relays movement made by the mouse in your hat to the wearer of the hat
/obj/item/clothing/head/utility/chefhat/proc/on_mouse_moving(mob/living/source, atom/moved_to)
SIGNAL_HANDLER
if (!prob(mouse_control_probability) || !COOLDOWN_FINISHED(src, move_cooldown))
return COMPONENT_MOVABLE_BLOCK_PRE_MOVE // Didn't roll well enough or on cooldown
var/mob/living/carbon/wearer = loc
if(!wearer || INCAPACITATED_IGNORING(wearer, INCAPABLE_RESTRAINTS))
return COMPONENT_MOVABLE_BLOCK_PRE_MOVE // Not worn or can't move
var/move_direction = get_dir(wearer, moved_to)
if(!wearer.Process_Spacemove(move_direction))
return COMPONENT_MOVABLE_BLOCK_PRE_MOVE // Currently drifting in space
if(!has_gravity() || !isturf(wearer.loc))
return COMPONENT_MOVABLE_BLOCK_PRE_MOVE // Not in a location where we can move
step_towards(wearer, moved_to)
var/move_delay = wearer.cached_multiplicative_slowdown
if (ISDIAGONALDIR(move_direction))
move_delay *= sqrt(2)
COOLDOWN_START(src, move_cooldown, move_delay)
return COMPONENT_MOVABLE_BLOCK_PRE_MOVE
/obj/item/clothing/head/utility/chefhat/suicide_act(mob/living/user)
user.visible_message(span_suicide("[user] is donning [src]! It looks like [user.p_theyre()] trying to become a chef."))
user.say("Bork Bork Bork!", forced = "chef hat suicide")
sleep(2 SECONDS)
user.visible_message(span_suicide("[user] climbs into an imaginary oven!"))
user.say("BOOORK!", forced = "chef hat suicide")
playsound(user, 'sound/machines/ding.ogg', 50, TRUE)
return FIRELOSS
//Captain
/obj/item/clothing/head/hats/caphat
name = "captain's hat"
desc = "It's good being the king."
icon_state = "captain"
inhand_icon_state = "that"
flags_inv = 0
armor_type = /datum/armor/hats_caphat
strip_delay = 6 SECONDS
dog_fashion = /datum/dog_fashion/head/captain
//Captain: This is no longer space-worthy
/datum/armor/hats_caphat
melee = 25
bullet = 15
laser = 25
energy = 35
bomb = 25
fire = 50
acid = 50
wound = 5
/obj/item/clothing/head/hats/caphat/parade
name = "captain's parade cap"
desc = "Worn only by Captains with an abundance of class."
icon_state = "capcap"
dog_fashion = null
/obj/item/clothing/head/caphat/beret
name = "captain's beret"
desc = "For the Captains known for their sense of fashion."
icon = 'icons/map_icons/clothing/head/_head.dmi'
icon_state = "/obj/item/clothing/head/caphat/beret"
post_init_icon_state = "beret_badge"
greyscale_config = /datum/greyscale_config/beret_badge
greyscale_config_worn = /datum/greyscale_config/beret_badge/worn
greyscale_colors = "#0070B7#FFCE5B"
hair_mask = /datum/hair_mask/standard_hat_middle
//Head of Personnel
/obj/item/clothing/head/hats/hopcap
name = "head of personnel's cap"
icon_state = "hopcap"
desc = "The symbol of true bureaucratic micromanagement."
armor_type = /datum/armor/hats_hopcap
dog_fashion = /datum/dog_fashion/head/hop
//Chaplain
/datum/armor/hats_hopcap
melee = 25
bullet = 15
laser = 25
energy = 35
bomb = 25
fire = 50
acid = 50
/obj/item/clothing/head/chaplain/nun_hood
name = "nun hood"
desc = "Maximum piety in this star system."
icon_state = "nun_hood"
flags_inv = HIDEHAIR
flags_cover = HEADCOVERSEYES
/obj/item/clothing/head/chaplain/habit_veil
name = "nun veil"
desc = "No nunsene clothing."
icon_state = "nun_hood_alt"
flags_inv = HIDEHAIR | HIDEEARS
clothing_flags = SNUG_FIT // can't be knocked off by throwing a paper hat.
/obj/item/clothing/head/chaplain/bishopmitre
name = "bishop mitre"
desc = "An opulent hat that functions as a radio to God. Or as a lightning rod, depending on who you ask."
icon_state = "bishopmitre"
#define CANDY_CD_TIME 2 MINUTES
//Detective
/obj/item/clothing/head/fedora/det_hat
name = "detective's fedora"
desc = "There's only one man who can sniff out the dirty stench of crime, and he's likely wearing this hat."
armor_type = /datum/armor/fedora_det_hat
icon_state = "detective"
interaction_flags_click = NEED_DEXTERITY|NEED_HANDS|ALLOW_RESTING
dog_fashion = /datum/dog_fashion/head/detective
/// Path for the flask that spawns inside their hat roundstart
var/flask_path = /obj/item/reagent_containers/cup/glass/flask/det
/// Cooldown for retrieving precious candy corn with rmb
COOLDOWN_DECLARE(candy_cooldown)
/datum/armor/fedora_det_hat
melee = 25
bullet = 5
laser = 25
energy = 35
fire = 30
acid = 50
wound = 5
/obj/item/clothing/head/fedora/det_hat/Initialize(mapload)
. = ..()
create_storage(storage_type = /datum/storage/pockets/small/fedora/detective)
register_context()
new flask_path(src)
/obj/item/clothing/head/fedora/det_hat/examine(mob/user)
. = ..()
. += span_notice("Alt-click to take a candy corn.")
/obj/item/clothing/head/fedora/det_hat/add_context(atom/source, list/context, obj/item/held_item, mob/user)
. = ..()
context[SCREENTIP_CONTEXT_ALT_LMB] = "Candy Time"
return CONTEXTUAL_SCREENTIP_SET
/// Now to solve where all these keep coming from
/obj/item/clothing/head/fedora/det_hat/click_alt(mob/user)
if(!COOLDOWN_FINISHED(src, candy_cooldown))
to_chat(user, span_warning("A candy corn was just taken! You should wait a couple minutes, lest you burn through the stash."))
return CLICK_ACTION_BLOCKING
var/obj/item/food/candy_corn/sweets = new /obj/item/food/candy_corn(src)
user.put_in_hands(sweets)
to_chat(user, span_notice("You slip a candy corn from \the [src]."))
COOLDOWN_START(src, candy_cooldown, CANDY_CD_TIME)
return CLICK_ACTION_SUCCESS
#undef CANDY_CD_TIME
/obj/item/clothing/head/fedora/det_hat/minor
flask_path = /obj/item/reagent_containers/cup/glass/flask/det/minor
///Detectives Fedora, but like Inspector Gadget. Not a subtype to not inherit candy corn stuff
/obj/item/clothing/head/fedora/inspector_hat
name = "inspector's fedora"
desc = "There's only one man can try to stop an evil villain."
armor_type = /datum/armor/fedora_det_hat
icon_state = "detective"
dog_fashion = /datum/dog_fashion/head/detective
interaction_flags_click = FORBID_TELEKINESIS_REACH|ALLOW_RESTING
///prefix our phrases must begin with
var/prefix = "go go gadget"
///an assoc list of regex = item (like regex datum = revolver item)
var/list/items_by_regex = list()
///A an assoc list of regex = phrase (like regex datum = gun text)
var/list/phrases_by_regex = list()
///how many gadgets can we hold
var/max_items = 4
///items above this weight cannot be put in the hat
var/max_weight = WEIGHT_CLASS_NORMAL
/obj/item/clothing/head/fedora/inspector_hat/Initialize(mapload)
. = ..()
become_hearing_sensitive(ROUNDSTART_TRAIT)
QDEL_NULL(atom_storage)
/obj/item/clothing/head/fedora/inspector_hat/proc/set_prefix(desired_prefix)
prefix = desired_prefix
// Regenerated the phrases here.
for(var/old_regex in phrases_by_regex)
var/old_phrase = phrases_by_regex[old_regex]
var/obj/item/old_item = items_by_regex[old_regex]
items_by_regex -= old_regex
phrases_by_regex -= old_regex
set_phrase(old_phrase,old_item)
return TRUE
/obj/item/clothing/head/fedora/inspector_hat/proc/set_phrase(desired_phrase,obj/item/associated_item)
var/regex/phrase_regex = regex("[prefix]\[\\s\\W\]+[desired_phrase]","i")
phrases_by_regex[phrase_regex] = desired_phrase
items_by_regex[phrase_regex] = associated_item
return TRUE
/obj/item/clothing/head/fedora/inspector_hat/examine(mob/user)
. = ..()
. += span_notice("You can put items inside, and get them out by saying a phrase, or using it in-hand!")
. += span_notice("The prefix is <b>[prefix]</b>, and you can change it with alt-click!\n")
for(var/found_regex in phrases_by_regex)
var/found_phrase = phrases_by_regex[found_regex]
var/obj/item/found_item = items_by_regex[found_regex]
. += span_notice("[icon2html(found_item, user)] You can remove [found_item] by saying <b>\"[prefix] [found_phrase]\"</b>!")
/obj/item/clothing/head/fedora/inspector_hat/Hear(atom/movable/speaker, message_language, raw_message, radio_freq, radio_freq_name, radio_freq_color, list/spans, list/message_mods = list(), message_range)
. = ..()
var/mob/living/carbon/wearer = loc
if(!istype(wearer) || speaker != wearer) //if we are worn
return
raw_message = htmlrendertext(raw_message)
for(var/regex/found_regex as anything in phrases_by_regex)
if(!found_regex.Find(raw_message))
continue
var/obj/item/found_item = items_by_regex[found_regex]
if(wearer.put_in_hands(found_item))
wearer.visible_message(span_warning("[src] drops [found_item] into the hands of [wearer]!"))
. = TRUE
else
balloon_alert(wearer, "can't put in hands!")
break
return .
/obj/item/clothing/head/fedora/inspector_hat/attackby(obj/item/item, mob/user, list/modifiers, list/attack_modifiers)
. = ..()
if(LAZYLEN(contents) >= max_items)
balloon_alert(user, "full!")
return
if(item.w_class > max_weight)
balloon_alert(user, "too big!")
return
var/desired_phrase = tgui_input_text(user, "What is the activation phrase?", "Activation phrase", "gadget", max_length = 26)
if(!desired_phrase || !user.can_perform_action(src, FORBID_TELEKINESIS_REACH))
return
if(item.loc != user || !user.transferItemToLoc(item, src))
return
to_chat(user, span_notice("You install [item] into the [thtotext(contents.len)] slot of [src]."))
playsound(src, 'sound/machines/click.ogg', 30, TRUE)
set_phrase(desired_phrase,item)
return TRUE
/obj/item/clothing/head/fedora/inspector_hat/attack_self(mob/user)
. = ..()
if(!length(items_by_regex))
return CLICK_ACTION_BLOCKING
var/list/found_items = list()
for(var/found_regex in items_by_regex)
found_items += items_by_regex[found_regex]
var/obj/found_item = tgui_input_list(user, "What item do you want to remove?", "Item Removal", found_items)
if(!found_item || !user.can_perform_action(src, FORBID_TELEKINESIS_REACH))
return CLICK_ACTION_BLOCKING
user.put_in_inactive_hand(found_item)
/obj/item/clothing/head/fedora/inspector_hat/click_alt(mob/user)
var/new_prefix = tgui_input_text(user, "What should be the new prefix?", "Activation prefix", prefix, max_length = 24)
if(!new_prefix || !user.can_perform_action(src, FORBID_TELEKINESIS_REACH))
return CLICK_ACTION_BLOCKING
set_prefix(new_prefix)
return CLICK_ACTION_SUCCESS
/obj/item/clothing/head/fedora/inspector_hat/Exited(atom/movable/gone, direction)
. = ..()
for(var/found_regex in items_by_regex)
var/obj/item/found_item = items_by_regex[found_regex]
if(gone != found_item)
continue
items_by_regex -= found_regex
phrases_by_regex -= found_regex
break
/obj/item/clothing/head/fedora/inspector_hat/atom_destruction(damage_flag)
var/atom/atom_location = drop_location()
for(var/found_regex in items_by_regex)
var/obj/item/result = items_by_regex[found_regex]
result.forceMove(atom_location)
items_by_regex -= found_regex
phrases_by_regex -= found_regex
return ..()
/obj/item/clothing/head/fedora/inspector_hat/Destroy()
QDEL_LIST_ASSOC(items_by_regex) //Anything that failed to drop gets deleted.
return ..()
//Mime
/obj/item/clothing/head/beret
name = "beret"
desc = "A beret, a mime's favorite headwear."
dog_fashion = /datum/dog_fashion/head/beret
icon = 'icons/map_icons/clothing/head/beret.dmi'
icon_state = "/obj/item/clothing/head/beret"
post_init_icon_state = "beret"
greyscale_config = /datum/greyscale_config/beret
greyscale_config_worn = /datum/greyscale_config/beret/worn
greyscale_colors = "#972A2A"
flags_1 = IS_PLAYER_COLORABLE_1
hair_mask = /datum/hair_mask/standard_hat_middle
//Security
/obj/item/clothing/head/hats/hos
name = "generic head of security hat"
desc = "Please contact the Nanotrasen Costuming Department if found."
abstract_type = /obj/item/clothing/head/hats/hos
armor_type = /datum/armor/hats_hos
strip_delay = 8 SECONDS
/obj/item/clothing/head/hats/hos/cap
name = "head of security cap"
desc = "The robust standard-issue cap of the Head of Security. For showing the officers who's in charge. Looks a bit stout."
icon_state = "hoscap"
/obj/item/clothing/head/hats/hos/cap/Initialize(mapload)
. = ..()
// Give it a little publicity
var/static/list/slapcraft_recipe_list = list(\
/datum/crafting_recipe/sturdy_shako,\
)
AddElement(
/datum/element/slapcrafting,\
slapcraft_recipes = slapcraft_recipe_list,\
)
/datum/armor/hats_hos
melee = 40
bullet = 30
laser = 25
energy = 35
bomb = 25
bio = 10
fire = 50
acid = 60
wound = 10
/obj/item/clothing/head/hats/hos/cap/syndicate
name = "syndicate cap"
desc = "A black cap fit for a high ranking syndicate officer."
/obj/item/clothing/head/hats/hos/shako
name = "sturdy shako"
desc = "Wearing this makes you want to shout \"Down and give me twenty!\" at someone."
icon_state = "hosshako"
worn_icon = 'icons/mob/large-worn-icons/64x64/head.dmi'
worn_x_dimension = 64
worn_y_dimension = 64
/obj/item/clothing/head/hats/hos/beret
name = "head of security's beret"
desc = "A robust beret for the Head of Security, for looking stylish while not sacrificing protection."
icon = 'icons/map_icons/clothing/head/_head.dmi'
icon_state = "/obj/item/clothing/head/hats/hos/beret"
post_init_icon_state = "beret_badge"
greyscale_config = /datum/greyscale_config/beret_badge
greyscale_config_worn = /datum/greyscale_config/beret_badge/worn
greyscale_colors = "#39393f#f0cc8f"
hair_mask = /datum/hair_mask/standard_hat_middle
/obj/item/clothing/head/hats/hos/beret/navyhos
name = "head of security's formal beret"
desc = "A special beret with the Head of Security's insignia emblazoned on it. A symbol of excellence, a badge of courage, a mark of distinction."
icon_state = "/obj/item/clothing/head/hats/hos/beret/navyhos"
greyscale_colors = "#638799#f0cc8f"
/obj/item/clothing/head/hats/hos/beret/syndicate
name = "syndicate beret"
desc = "A black beret with thick armor padding inside. Stylish and robust."
/obj/item/clothing/head/hats/warden
name = "warden's police hat"
desc = "It's a special armored hat issued to the Warden of a security force. Protects the head from impacts."
icon_state = "policehelm"
armor_type = /datum/armor/hats_warden
strip_delay = 6 SECONDS
dog_fashion = /datum/dog_fashion/head/warden
/datum/armor/hats_warden
melee = 40
bullet = 30
laser = 30
energy = 40
bomb = 25
fire = 30
acid = 60
wound = 5
/obj/item/clothing/head/hats/warden/police
name = "police officer's hat"
desc = "A police officer's hat. This hat emphasizes that you are THE LAW."
/obj/item/clothing/head/hats/warden/red
name = "warden's hat"
desc = "A warden's red hat. Looking at it gives you the feeling of wanting to keep people in cells for as long as possible."
icon_state = "wardenhat"
dog_fashion = /datum/dog_fashion/head/warden_red
/obj/item/clothing/head/hats/warden/drill
name = "warden's campaign hat"
desc = "A special armored campaign hat with the security insignia emblazoned on it. Uses reinforced fabric to offer sufficient protection."
icon_state = "wardendrill"
inhand_icon_state = null
dog_fashion = null
var/mode = DRILL_DEFAULT
/obj/item/clothing/head/hats/warden/drill/screwdriver_act(mob/living/carbon/human/user, obj/item/I)
if(..())
return TRUE
switch(mode)
if(DRILL_DEFAULT)
to_chat(user, span_notice("You set the voice circuit to the middle position."))
mode = DRILL_SHOUTING
if(DRILL_SHOUTING)
to_chat(user, span_notice("You set the voice circuit to the last position."))
mode = DRILL_YELLING
if(DRILL_YELLING)
to_chat(user, span_notice("You set the voice circuit to the first position."))
mode = DRILL_DEFAULT
if(DRILL_CANADIAN)
to_chat(user, span_danger("You adjust voice circuit but nothing happens, probably because it's broken."))
return TRUE
/obj/item/clothing/head/hats/warden/drill/wirecutter_act(mob/living/user, obj/item/I)
..()
if(mode != DRILL_CANADIAN)
to_chat(user, span_danger("You broke the voice circuit!"))
mode = DRILL_CANADIAN
return TRUE
/obj/item/clothing/head/hats/warden/drill/equipped(mob/M, slot)
. = ..()
if (slot & ITEM_SLOT_HEAD)
RegisterSignal(M, COMSIG_MOB_SAY, PROC_REF(handle_speech))
else
UnregisterSignal(M, COMSIG_MOB_SAY)
/obj/item/clothing/head/hats/warden/drill/dropped(mob/M)
. = ..()
UnregisterSignal(M, COMSIG_MOB_SAY)
/obj/item/clothing/head/hats/warden/drill/proc/handle_speech(datum/source, list/speech_args)
SIGNAL_HANDLER
var/message = speech_args[SPEECH_MESSAGE]
if(message[1] != "*")
switch (mode)
if(DRILL_SHOUTING)
message += "!"
if(DRILL_YELLING)
message += "!!"
if(DRILL_CANADIAN)
message = "[message]"
var/list/canadian_words = strings("canadian_replacement.json", "canadian")
for(var/key in canadian_words)
var/value = canadian_words[key]
if(islist(value))
value = pick(value)
message = replacetextEx(message, " [uppertext(key)]", " [uppertext(value)]")
message = replacetextEx(message, " [capitalize(key)]", " [capitalize(value)]")
message = replacetextEx(message, " [key]", " [value]")
if(prob(30))
message += pick(", eh?", ", EH?")
speech_args[SPEECH_MESSAGE] = message
/obj/item/clothing/head/beret/sec
name = "security beret"
desc = "A robust beret with the security insignia emblazoned on it. Uses reinforced fabric to offer sufficient protection."
icon_state = "/obj/item/clothing/head/beret/sec"
post_init_icon_state = "beret_badge"
greyscale_config = /datum/greyscale_config/beret_badge
greyscale_config_worn = /datum/greyscale_config/beret_badge/worn
greyscale_colors = "#a52f29#F2F2F2"
armor_type = /datum/armor/cosmetic_sec
strip_delay = 6 SECONDS
dog_fashion = null
flags_1 = NONE
/datum/armor/cosmetic_sec
melee = 30
bullet = 25
laser = 25
energy = 35
bomb = 25
fire = 20
acid = 50
wound = 5
/obj/item/clothing/head/beret/sec/navywarden
name = "warden's beret"
desc = "A special beret with the Warden's insignia emblazoned on it. For wardens with class."
icon_state = "/obj/item/clothing/head/beret/sec/navywarden"
greyscale_colors = "#638799#ebebeb"
strip_delay = 6 SECONDS
/obj/item/clothing/head/beret/sec/navyofficer
desc = "A special beret with the security insignia emblazoned on it. For officers with class."
icon_state = "/obj/item/clothing/head/beret/sec/navyofficer"
greyscale_colors = "#638799#a52f29"
//Science
/obj/item/clothing/head/beret/science
name = "science beret"
desc = "A science-themed beret for our hardworking scientists."
icon_state = "/obj/item/clothing/head/beret/science"
greyscale_colors = "#8D008F"
flags_1 = NONE
/obj/item/clothing/head/beret/science/rd
desc = "A purple badge with the insignia of the Research Director attached. For the paper-shuffler in you!"
icon_state = "/obj/item/clothing/head/beret/science/rd"
post_init_icon_state = "beret_badge"
greyscale_config = /datum/greyscale_config/beret_badge
greyscale_config_worn = /datum/greyscale_config/beret_badge/worn
greyscale_colors = "#7e1980#c9cbcb"
//Medical
/obj/item/clothing/head/beret/medical
name = "medical beret"
desc = "A medical-flavored beret for the doctor in you!"
icon_state = "/obj/item/clothing/head/beret/medical"
greyscale_colors = COLOR_WHITE
flags_1 = NONE
/obj/item/clothing/head/beret/medical/paramedic
name = "paramedic beret"
desc = "For finding corpses in style!"
icon_state = "/obj/item/clothing/head/beret/medical/paramedic"
greyscale_colors = "#16313D"
/obj/item/clothing/head/beret/medical/cmo
name = "chief medical officer beret"
desc = "A beret in a distinct surgical turquoise!"
icon_state = "/obj/item/clothing/head/beret/medical/cmo"
greyscale_colors = "#5EB8B8"
/obj/item/clothing/head/utility/surgerycap
name = "blue surgery cap"
icon_state = "surgicalcap"
desc = "A blue medical surgery cap to prevent the surgeon's hair from entering the insides of the patient!"
flags_inv = HIDEHAIR //Cover your head doctor!
w_class = WEIGHT_CLASS_SMALL //surgery cap can be easily crumpled
/obj/item/clothing/head/utility/surgerycap/Initialize(mapload)
. = ..()
AddComponent(/datum/component/adjust_fishing_difficulty, -3) //FISH DOCTOR?!
/obj/item/clothing/head/utility/surgerycap/attack_self(mob/user)
. = ..()
if(.)
return
balloon_alert(user, "[flags_inv & HIDEHAIR ? "loosening" : "tightening"] strings...")
if(!do_after(user, 3 SECONDS, src))
return
flags_inv ^= HIDEHAIR
balloon_alert(user, "[flags_inv & HIDEHAIR ? "tightened" : "loosened "] strings")
return TRUE
/obj/item/clothing/head/utility/surgerycap/examine(mob/user)
. = ..()
. += span_notice("Use in hand to [flags_inv & HIDEHAIR ? "loosen" : "tighten"] the strings.")
/obj/item/clothing/head/utility/surgerycap/purple
name = "burgundy surgery cap"
icon_state = "surgicalcapwine"
desc = "A burgundy medical surgery cap to prevent the surgeon's hair from entering the insides of the patient!"
/obj/item/clothing/head/utility/surgerycap/green
name = "green surgery cap"
icon_state = "surgicalcapgreen"
desc = "A green medical surgery cap to prevent the surgeon's hair from entering the insides of the patient!"
/obj/item/clothing/head/utility/surgerycap/cmo
name = "turquoise surgery cap"
icon_state = "surgicalcapcmo"
desc = "The CMO's medical surgery cap to prevent their hair from entering the insides of the patient!"
/obj/item/clothing/head/utility/surgerycap/black
name = "black surgery cap"
icon_state = "surgicalcapblack"
desc = "A black medical surgery cap to prevent the surgeon's hair from entering the insides of the patient!"
/obj/item/clothing/head/utility/head_mirror
name = "head mirror"
desc = "Used by doctors to look into a patient's eyes, ears, and mouth. \
A little useless now, given the technology available, but it certainly completes the look."
icon_state = "headmirror"
body_parts_covered = NONE
/obj/item/clothing/head/utility/head_mirror/Initialize(mapload)
. = ..()
AddComponent(/datum/component/adjust_fishing_difficulty, -3) //FISH DOCTOR?!
/obj/item/clothing/head/utility/head_mirror/examine(mob/user)
. = ..()
. += span_notice("In a properly lit room, you can use this to examine people's eyes, ears, and mouth <i>closer</i>.")
/obj/item/clothing/head/utility/head_mirror/equipped(mob/living/user, slot)
. = ..()
if(slot & slot_flags)
RegisterSignal(user, COMSIG_MOB_EXAMINING_MORE, PROC_REF(examining))
else
UnregisterSignal(user, COMSIG_MOB_EXAMINING_MORE)
/obj/item/clothing/head/utility/head_mirror/dropped(mob/living/user)
. = ..()
UnregisterSignal(user, COMSIG_MOB_EXAMINING_MORE)
/obj/item/clothing/head/utility/head_mirror/proc/examining(mob/living/examiner, atom/examining, list/examine_list)
SIGNAL_HANDLER
if(!ishuman(examining) || examining == examiner || examiner.is_blind() || !examiner.Adjacent(examining))
return
var/mob/living/carbon/human/human_examined = examining
if(!human_examined.get_bodypart(BODY_ZONE_HEAD))
return
if(!examiner.has_light_nearby())
examine_list += span_warning("You attempt to use your [name] to examine [examining]'s head better... but it's too dark. Should've invested in a head lamp.")
return
if(examiner.dir == examining.dir) // disallow examine from behind - every other dir is OK
examine_list += span_warning("You attempt to use your [name] to examine [examining]'s head better... but [examining.p_theyre()] facing the wrong way.")
return
var/list/final_message = list("You examine [examining]'s head closer with your [name], you notice [examining.p_they()] [examining.p_have()]...")
if(human_examined.is_mouth_covered())
final_message += "\tYou can't see [examining.p_their()] mouth."
else
var/obj/item/organ/tongue/has_tongue = human_examined.get_organ_slot(ORGAN_SLOT_TONGUE)
var/pill_count = 0
for(var/datum/action/item_action/activate_pill/pill in human_examined.actions)
pill_count++
if(pill_count >= 1 && has_tongue)
final_message += "\t[pill_count] pill\s in [examining.p_their()] mouth, and \a [has_tongue]."
else if(pill_count >= 1)
final_message += "\t[pill_count] pill\s in [examining.p_their()] mouth, but oddly no tongue."
else if(has_tongue)
final_message += "\t\A [has_tongue] in [examining.p_their()] mouth - go figure."
else
final_message += "\tNo tongue in [examining.p_their()] mouth, oddly enough."
if(human_examined.is_ears_covered())
final_message += "\tYou can't see [examining.p_their()] ears."
else
var/obj/item/organ/ears/has_ears = human_examined.get_organ_slot(ORGAN_SLOT_EARS)
if(has_ears)
if(has_ears.deaf)
final_message += "\tDamaged eardrums in [examining.p_their()] ear canals."
else
final_message += "\tA set of [has_ears.damage ? "" : "healthy "][has_ears.name]."
else
final_message += "\tNo eardrums and empty ear canals... how peculiar."
if(human_examined.is_eyes_covered())
final_message += "\tYou can't see [examining.p_their()] eyes."
else
var/obj/item/organ/eyes/has_eyes = human_examined.get_organ_slot(ORGAN_SLOT_EYES)
if(has_eyes)
final_message += "\tA pair of [has_eyes.damage ? "" : "healthy "][has_eyes.name]."
else
final_message += "\tEmpty eye sockets."
examine_list += span_notice("<i>[jointext(final_message, "\n")]</i>")
//Engineering
/obj/item/clothing/head/beret/engi
name = "engineering beret"
desc = "Might not protect you from radiation, but definitely will protect you from looking unfashionable!"
icon_state = "/obj/item/clothing/head/beret/engi"
greyscale_colors = "#FFBC30"
flags_1 = NONE
//Cargo
/obj/item/clothing/head/beret/cargo
name = "cargo beret"
desc = "No need to compensate when you can wear this beret!"
icon_state = "/obj/item/clothing/head/beret/cargo"
greyscale_colors = "#b7723d"
flags_1 = NONE
//Curator
/obj/item/clothing/head/fedora/curator
name = "treasure hunter's fedora"
desc = "You got red text today kid, but it doesn't mean you have to like it."
icon_state = "curator"
/obj/item/clothing/head/beret/durathread
name = "durathread beret"
desc = "A beret made from durathread, its resilient fibers provide some protection to the wearer."
icon_state = "/obj/item/clothing/head/beret/durathread"
post_init_icon_state = "beret_badge"
greyscale_config = /datum/greyscale_config/beret_badge
greyscale_config_worn = /datum/greyscale_config/beret_badge/worn
greyscale_colors = "#C5D4F3#ECF1F8"
armor_type = /datum/armor/beret_durathread
/datum/armor/beret_durathread
melee = 15
bullet = 5
laser = 15
energy = 25
bomb = 10
fire = 30
acid = 5
wound = 5
/obj/item/clothing/head/beret/highlander
desc = "That was white fabric. <i>Was.</i>"
dog_fashion = null //THIS IS FOR SLAUGHTER, NOT PUPPIES
/obj/item/clothing/head/beret/highlander/Initialize(mapload)
. = ..()
ADD_TRAIT(src, TRAIT_NODROP, HIGHLANDER_TRAIT)
//CentCom
/obj/item/clothing/head/beret/centcom_formal
name = "\improper CentCom Formal Beret"
desc = "Sometimes, a compromise between fashion and defense needs to be made. Thanks to Nanotrasen's most recent nano-fabric durability enhancements, this time, it's not the case."
icon_state = "/obj/item/clothing/head/beret/centcom_formal"
post_init_icon_state = "beret_badge"
greyscale_config = /datum/greyscale_config/beret_badge
greyscale_config_worn = /datum/greyscale_config/beret_badge/worn
greyscale_colors = "#46b946#f2c42e"
armor_type = /datum/armor/beret_centcom_formal
strip_delay = 10 SECONDS
#undef DRILL_DEFAULT
#undef DRILL_SHOUTING
#undef DRILL_YELLING
#undef DRILL_CANADIAN
/datum/armor/beret_centcom_formal
melee = 80
bullet = 80
laser = 50
energy = 50
bomb = 100
bio = 100
fire = 100
acid = 90
wound = 10
//Independant Militia
/obj/item/clothing/head/beret/militia
name = "\improper Militia General's Beret"
desc = "A rallying cry for the inhabitants of the Spinward Sector, the heroes that wear this keep the horrors of the galaxy at bay. Call them, and they'll be there in a minute!"
icon_state = "/obj/item/clothing/head/beret/militia"
post_init_icon_state = "beret_badge"
greyscale_config = /datum/greyscale_config/beret_badge
greyscale_config_worn = /datum/greyscale_config/beret_badge/worn
greyscale_colors = "#43523d#a2abb0"
armor_type = /datum/armor/cosmetic_sec
| 0 | 0.859993 | 1 | 0.859993 | game-dev | MEDIA | 0.972392 | game-dev | 0.877347 | 1 | 0.877347 |
neoforged/NeoForge | 1,715 | patches/net/minecraft/world/level/storage/LevelStorageSource.java.patch | --- a/net/minecraft/world/level/storage/LevelStorageSource.java
+++ b/net/minecraft/world/level/storage/LevelStorageSource.java
@@ -462,6 +_,19 @@
}
}
+ // Neo: For reading NeoForge's additional save data (mod list, etc.)
+ public void readAdditionalLevelSaveData(boolean fallback) {
+ checkLock();
+ Path path = fallback ? this.levelDirectory.oldDataFile() : this.levelDirectory.dataFile();
+ try {
+ var tag = readLightweightData(path);
+ if (tag instanceof CompoundTag compoundTag)
+ net.neoforged.neoforge.common.CommonHooks.readAdditionalLevelSaveData(compoundTag, this.levelDirectory);
+ } catch (Exception e) {
+ LOGGER.error("Exception reading {}", path, e);
+ }
+ }
+
public PlayerDataStorage createPlayerStorage() {
this.checkLock();
return new PlayerDataStorage(this, LevelStorageSource.this.fixerUpper);
@@ -495,6 +_,7 @@
CompoundTag compoundtag = p_78292_.createTag(p_78291_, p_78293_);
CompoundTag compoundtag1 = new CompoundTag();
compoundtag1.put("Data", compoundtag);
+ net.neoforged.neoforge.common.CommonHooks.writeAdditionalLevelSaveData(p_78292_, compoundtag1);
this.saveLevelData(compoundtag1);
}
@@ -514,6 +_,10 @@
public Optional<Path> getIconFile() {
return !this.lock.isValid() ? Optional.empty() : Optional.of(this.levelDirectory.iconFile());
+ }
+
+ public Path getWorldDir() {
+ return baseDir;
}
public void deleteLevel() throws IOException {
| 0 | 0.836534 | 1 | 0.836534 | game-dev | MEDIA | 0.985441 | game-dev | 0.693948 | 1 | 0.693948 |
manisha-v/Unity3D | 49,405 | Part1 - 3D Movement/Codes/Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Selectable.cs | using System;
using System.Collections.Generic;
using UnityEngine.Serialization;
using UnityEngine.EventSystems;
namespace UnityEngine.UI
{
[AddComponentMenu("UI/Selectable", 70)]
[ExecuteAlways]
[SelectionBase]
[DisallowMultipleComponent]
/// <summary>
/// Simple selectable object - derived from to create a selectable control.
/// </summary>
public class Selectable
:
UIBehaviour,
IMoveHandler,
IPointerDownHandler, IPointerUpHandler,
IPointerEnterHandler, IPointerExitHandler,
ISelectHandler, IDeselectHandler
{
protected static Selectable[] s_Selectables = new Selectable[10];
protected static int s_SelectableCount = 0;
private bool m_EnableCalled = false;
/// <summary>
/// Copy of the array of all the selectable objects currently active in the scene.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class Example : MonoBehaviour
/// {
/// //Displays the names of all selectable elements in the scene
/// public void GetNames()
/// {
/// foreach (Selectable selectableUI in Selectable.allSelectablesArray)
/// {
/// Debug.Log(selectableUI.name);
/// }
/// }
/// }
/// </code>
/// </example>
public static Selectable[] allSelectablesArray
{
get
{
Selectable[] temp = new Selectable[s_SelectableCount];
Array.Copy(s_Selectables, temp, s_SelectableCount);
return temp;
}
}
/// <summary>
/// How many selectable elements are currently active.
/// </summary>
public static int allSelectableCount { get { return s_SelectableCount; } }
/// <summary>
/// A List instance of the allSelectablesArray to maintain API compatibility.
/// </summary>
[Obsolete("Replaced with allSelectablesArray to have better performance when disabling a element", false)]
public static List<Selectable> allSelectables
{
get
{
return new List<Selectable>(allSelectablesArray);
}
}
/// <summary>
/// Non allocating version for getting the all selectables.
/// If selectables.Length is less then s_SelectableCount only selectables.Length elments will be copied which
/// could result in a incomplete list of elements.
/// </summary>
/// <param name="selectables">The array to be filled with current selectable objects</param>
/// <returns>The number of element copied.</returns>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class Example : MonoBehaviour
/// {
/// Selectable[] m_Selectables = new Selectable[10];
///
/// //Displays the names of all selectable elements in the scene
/// public void GetNames()
/// {
/// if (m_Selectables.Length < Selectable.allSelectableCount)
/// m_Selectables = new Selectable[Selectable.allSelectableCount];
///
/// int count = Selectable.AllSelectablesNoAlloc(ref m_Selectables);
///
/// for (int i = 0; i < count; ++i)
/// {
/// Debug.Log(m_Selectables[i].name);
/// }
/// }
/// }
/// </code>
/// </example>
public static int AllSelectablesNoAlloc(Selectable[] selectables)
{
int copyCount = selectables.Length < s_SelectableCount ? selectables.Length : s_SelectableCount;
Array.Copy(s_Selectables, selectables, copyCount);
return copyCount;
}
// Navigation information.
[FormerlySerializedAs("navigation")]
[SerializeField]
private Navigation m_Navigation = Navigation.defaultNavigation;
/// <summary>
///Transition mode for a Selectable.
/// </summary>
public enum Transition
{
/// <summary>
/// No Transition.
/// </summary>
None,
/// <summary>
/// Use an color tint transition.
/// </summary>
ColorTint,
/// <summary>
/// Use a sprite swap transition.
/// </summary>
SpriteSwap,
/// <summary>
/// Use an animation transition.
/// </summary>
Animation
}
// Type of the transition that occurs when the button state changes.
[FormerlySerializedAs("transition")]
[SerializeField]
private Transition m_Transition = Transition.ColorTint;
// Colors used for a color tint-based transition.
[FormerlySerializedAs("colors")]
[SerializeField]
private ColorBlock m_Colors = ColorBlock.defaultColorBlock;
// Sprites used for a Image swap-based transition.
[FormerlySerializedAs("spriteState")]
[SerializeField]
private SpriteState m_SpriteState;
[FormerlySerializedAs("animationTriggers")]
[SerializeField]
private AnimationTriggers m_AnimationTriggers = new AnimationTriggers();
[Tooltip("Can the Selectable be interacted with?")]
[SerializeField]
private bool m_Interactable = true;
// Graphic that will be colored.
[FormerlySerializedAs("highlightGraphic")]
[FormerlySerializedAs("m_HighlightGraphic")]
[SerializeField]
private Graphic m_TargetGraphic;
private bool m_GroupsAllowInteraction = true;
protected int m_CurrentIndex = -1;
/// <summary>
/// The Navigation setting for this selectable object.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // Required when Using UI elements.
///
/// public class ExampleClass : MonoBehaviour
/// {
/// public Button button;
///
/// void Start()
/// {
/// //Set the navigation to the default value. ("Automatic" is the default value).
/// button.navigation = Navigation.defaultNavigation;
/// }
/// }
/// </code>
/// </example>
public Navigation navigation { get { return m_Navigation; } set { if (SetPropertyUtility.SetStruct(ref m_Navigation, value)) OnSetProperty(); } }
/// <summary>
/// The type of transition that will be applied to the targetGraphic when the state changes.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // Required when Using UI elements.
///
/// public class ExampleClass : MonoBehaviour
/// {
/// public Button btnMain;
///
/// void SomeFunction()
/// {
/// //Sets the main button's transition setting to "Color Tint".
/// btnMain.transition = Selectable.Transition.ColorTint;
/// }
/// }
/// </code>
/// </example>
public Transition transition { get { return m_Transition; } set { if (SetPropertyUtility.SetStruct(ref m_Transition, value)) OnSetProperty(); } }
/// <summary>
/// The ColorBlock for this selectable object.
/// </summary>
/// <remarks>
/// Modifications will not be visible if transition is not ColorTint.
/// </remarks>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // Required when Using UI elements.
///
/// public class ExampleClass : MonoBehaviour
/// {
/// public Button button;
///
/// void Start()
/// {
/// //Resets the colors in the buttons transitions.
/// button.colors = ColorBlock.defaultColorBlock;
/// }
/// }
/// </code>
/// </example>
public ColorBlock colors { get { return m_Colors; } set { if (SetPropertyUtility.SetStruct(ref m_Colors, value)) OnSetProperty(); } }
/// <summary>
/// The SpriteState for this selectable object.
/// </summary>
/// <remarks>
/// Modifications will not be visible if transition is not SpriteSwap.
/// </remarks>
/// <example>
// <code>
// using UnityEngine;
// using System.Collections;
// using UnityEngine.UI; // Required when Using UI elements.
//
// public class ExampleClass : MonoBehaviour
// {
// //Creates an instance of a sprite state (This includes the highlighted, pressed and disabled sprite.
// public SpriteState sprState = new SpriteState();
// public Button btnMain;
//
//
// void Start()
// {
// //Assigns the new sprite states to the button.
// btnMain.spriteState = sprState;
// }
// }
// </code>
// </example>
public SpriteState spriteState { get { return m_SpriteState; } set { if (SetPropertyUtility.SetStruct(ref m_SpriteState, value)) OnSetProperty(); } }
/// <summary>
/// The AnimationTriggers for this selectable object.
/// </summary>
/// <remarks>
/// Modifications will not be visible if transition is not Animation.
/// </remarks>
public AnimationTriggers animationTriggers { get { return m_AnimationTriggers; } set { if (SetPropertyUtility.SetClass(ref m_AnimationTriggers, value)) OnSetProperty(); } }
/// <summary>
/// Graphic that will be transitioned upon.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // Required when Using UI elements.
///
/// public class ExampleClass : MonoBehaviour
/// {
/// public Image newImage;
/// public Button btnMain;
///
/// void SomeFunction()
/// {
/// //Displays the sprite transitions on the image when the transition to Highlighted,pressed or disabled is made.
/// btnMain.targetGraphic = newImage;
/// }
/// }
/// </code>
/// </example>
public Graphic targetGraphic { get { return m_TargetGraphic; } set { if (SetPropertyUtility.SetClass(ref m_TargetGraphic, value)) OnSetProperty(); } }
/// <summary>
/// Is this object interactable.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class Example : MonoBehaviour
/// {
/// public Button startButton;
/// public bool playersReady;
///
///
/// void Update()
/// {
/// // checks if the players are ready and if the start button is useable
/// if (playersReady == true && startButton.interactable == false)
/// {
/// //allows the start button to be used
/// startButton.interactable = true;
/// }
/// }
/// }
/// </code>
/// </example>
public bool interactable
{
get { return m_Interactable; }
set
{
if (SetPropertyUtility.SetStruct(ref m_Interactable, value))
{
if (!m_Interactable && EventSystem.current != null && EventSystem.current.currentSelectedGameObject == gameObject)
EventSystem.current.SetSelectedGameObject(null);
OnSetProperty();
}
}
}
private bool isPointerInside { get; set; }
private bool isPointerDown { get; set; }
private bool hasSelection { get; set; }
protected Selectable()
{}
/// <summary>
/// Convenience function that converts the referenced Graphic to a Image, if possible.
/// </summary>
public Image image
{
get { return m_TargetGraphic as Image; }
set { m_TargetGraphic = value; }
}
/// <summary>
/// Convenience function to get the Animator component on the GameObject.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // Required when Using UI elements.
///
/// public class ExampleClass : MonoBehaviour
/// {
/// private Animator buttonAnimator;
/// public Button button;
///
/// void Start()
/// {
/// //Assigns the "buttonAnimator" with the button's animator.
/// buttonAnimator = button.animator;
/// }
/// }
/// </code>
/// </example>
#if PACKAGE_ANIMATION
public Animator animator
{
get { return GetComponent<Animator>(); }
}
#endif
protected override void Awake()
{
if (m_TargetGraphic == null)
m_TargetGraphic = GetComponent<Graphic>();
}
private readonly List<CanvasGroup> m_CanvasGroupCache = new List<CanvasGroup>();
protected override void OnCanvasGroupChanged()
{
// Figure out if parent groups allow interaction
// If no interaction is alowed... then we need
// to not do that :)
var groupAllowInteraction = true;
Transform t = transform;
while (t != null)
{
t.GetComponents(m_CanvasGroupCache);
bool shouldBreak = false;
for (var i = 0; i < m_CanvasGroupCache.Count; i++)
{
// if the parent group does not allow interaction
// we need to break
if (!m_CanvasGroupCache[i].interactable)
{
groupAllowInteraction = false;
shouldBreak = true;
}
// if this is a 'fresh' group, then break
// as we should not consider parents
if (m_CanvasGroupCache[i].ignoreParentGroups)
shouldBreak = true;
}
if (shouldBreak)
break;
t = t.parent;
}
if (groupAllowInteraction != m_GroupsAllowInteraction)
{
m_GroupsAllowInteraction = groupAllowInteraction;
OnSetProperty();
}
}
/// <summary>
/// Is the object interactable.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class Example : MonoBehaviour
/// {
/// public Button startButton;
///
/// void Update()
/// {
/// if (!startButton.IsInteractable())
/// {
/// Debug.Log("Start Button has been Disabled");
/// }
/// }
/// }
/// </code>
/// </example>
public virtual bool IsInteractable()
{
return m_GroupsAllowInteraction && m_Interactable;
}
// Call from unity if animation properties have changed
protected override void OnDidApplyAnimationProperties()
{
OnSetProperty();
}
// Select on enable and add to the list.
protected override void OnEnable()
{
//Check to avoid multiple OnEnable() calls for each selectable
if (m_EnableCalled)
return;
base.OnEnable();
if (s_SelectableCount == s_Selectables.Length)
{
Selectable[] temp = new Selectable[s_Selectables.Length * 2];
Array.Copy(s_Selectables, temp, s_Selectables.Length);
s_Selectables = temp;
}
if (EventSystem.current && EventSystem.current.currentSelectedGameObject == gameObject)
{
hasSelection = true;
}
m_CurrentIndex = s_SelectableCount;
s_Selectables[m_CurrentIndex] = this;
s_SelectableCount++;
isPointerDown = false;
DoStateTransition(currentSelectionState, true);
m_EnableCalled = true;
}
protected override void OnTransformParentChanged()
{
base.OnTransformParentChanged();
// If our parenting changes figure out if we are under a new CanvasGroup.
OnCanvasGroupChanged();
}
private void OnSetProperty()
{
#if UNITY_EDITOR
if (!Application.isPlaying)
DoStateTransition(currentSelectionState, true);
else
#endif
DoStateTransition(currentSelectionState, false);
}
// Remove from the list.
protected override void OnDisable()
{
//Check to avoid multiple OnDisable() calls for each selectable
if (!m_EnableCalled)
return;
s_SelectableCount--;
// Update the last elements index to be this index
s_Selectables[s_SelectableCount].m_CurrentIndex = m_CurrentIndex;
// Swap the last element and this element
s_Selectables[m_CurrentIndex] = s_Selectables[s_SelectableCount];
// null out last element.
s_Selectables[s_SelectableCount] = null;
InstantClearState();
base.OnDisable();
m_EnableCalled = false;
}
#if UNITY_EDITOR
protected override void OnValidate()
{
base.OnValidate();
m_Colors.fadeDuration = Mathf.Max(m_Colors.fadeDuration, 0.0f);
// OnValidate can be called before OnEnable, this makes it unsafe to access other components
// since they might not have been initialized yet.
// OnSetProperty potentially access Animator or Graphics. (case 618186)
if (isActiveAndEnabled)
{
if (!interactable && EventSystem.current != null && EventSystem.current.currentSelectedGameObject == gameObject)
EventSystem.current.SetSelectedGameObject(null);
// Need to clear out the override image on the target...
DoSpriteSwap(null);
// If the transition mode got changed, we need to clear all the transitions, since we don't know what the old transition mode was.
StartColorTween(Color.white, true);
TriggerAnimation(m_AnimationTriggers.normalTrigger);
// And now go to the right state.
DoStateTransition(currentSelectionState, true);
}
}
protected override void Reset()
{
m_TargetGraphic = GetComponent<Graphic>();
}
#endif // if UNITY_EDITOR
protected SelectionState currentSelectionState
{
get
{
if (!IsInteractable())
return SelectionState.Disabled;
if (isPointerDown)
return SelectionState.Pressed;
if (hasSelection)
return SelectionState.Selected;
if (isPointerInside)
return SelectionState.Highlighted;
return SelectionState.Normal;
}
}
/// <summary>
/// Clear any internal state from the Selectable (used when disabling).
/// </summary>
protected virtual void InstantClearState()
{
string triggerName = m_AnimationTriggers.normalTrigger;
isPointerInside = false;
isPointerDown = false;
hasSelection = false;
switch (m_Transition)
{
case Transition.ColorTint:
StartColorTween(Color.white, true);
break;
case Transition.SpriteSwap:
DoSpriteSwap(null);
break;
case Transition.Animation:
TriggerAnimation(triggerName);
break;
}
}
/// <summary>
/// Transition the Selectable to the entered state.
/// </summary>
/// <param name="state">State to transition to</param>
/// <param name="instant">Should the transition occur instantly.</param>
protected virtual void DoStateTransition(SelectionState state, bool instant)
{
if (!gameObject.activeInHierarchy)
return;
Color tintColor;
Sprite transitionSprite;
string triggerName;
switch (state)
{
case SelectionState.Normal:
tintColor = m_Colors.normalColor;
transitionSprite = null;
triggerName = m_AnimationTriggers.normalTrigger;
break;
case SelectionState.Highlighted:
tintColor = m_Colors.highlightedColor;
transitionSprite = m_SpriteState.highlightedSprite;
triggerName = m_AnimationTriggers.highlightedTrigger;
break;
case SelectionState.Pressed:
tintColor = m_Colors.pressedColor;
transitionSprite = m_SpriteState.pressedSprite;
triggerName = m_AnimationTriggers.pressedTrigger;
break;
case SelectionState.Selected:
tintColor = m_Colors.selectedColor;
transitionSprite = m_SpriteState.selectedSprite;
triggerName = m_AnimationTriggers.selectedTrigger;
break;
case SelectionState.Disabled:
tintColor = m_Colors.disabledColor;
transitionSprite = m_SpriteState.disabledSprite;
triggerName = m_AnimationTriggers.disabledTrigger;
break;
default:
tintColor = Color.black;
transitionSprite = null;
triggerName = string.Empty;
break;
}
switch (m_Transition)
{
case Transition.ColorTint:
StartColorTween(tintColor * m_Colors.colorMultiplier, instant);
break;
case Transition.SpriteSwap:
DoSpriteSwap(transitionSprite);
break;
case Transition.Animation:
TriggerAnimation(triggerName);
break;
}
}
/// <summary>
/// An enumeration of selected states of objects
/// </summary>
protected enum SelectionState
{
/// <summary>
/// The UI object can be selected.
/// </summary>
Normal,
/// <summary>
/// The UI object is highlighted.
/// </summary>
Highlighted,
/// <summary>
/// The UI object is pressed.
/// </summary>
Pressed,
/// <summary>
/// The UI object is selected
/// </summary>
Selected,
/// <summary>
/// The UI object cannot be selected.
/// </summary>
Disabled,
}
// Selection logic
/// <summary>
/// Finds the selectable object next to this one.
/// </summary>
/// <remarks>
/// The direction is determined by a Vector3 variable.
/// </remarks>
/// <param name="dir">The direction in which to search for a neighbouring Selectable object.</param>
/// <returns>The neighbouring Selectable object. Null if none found.</returns>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class ExampleClass : MonoBehaviour
/// {
/// //Sets the direction as "Up" (Y is in positive).
/// public Vector3 direction = new Vector3(0, 1, 0);
/// public Button btnMain;
///
/// public void Start()
/// {
/// //Finds and assigns the selectable above the main button
/// Selectable newSelectable = btnMain.FindSelectable(direction);
///
/// Debug.Log(newSelectable.name);
/// }
/// }
/// </code>
/// </example>
public Selectable FindSelectable(Vector3 dir)
{
dir = dir.normalized;
Vector3 localDir = Quaternion.Inverse(transform.rotation) * dir;
Vector3 pos = transform.TransformPoint(GetPointOnRectEdge(transform as RectTransform, localDir));
float maxScore = Mathf.NegativeInfinity;
float maxFurthestScore = Mathf.NegativeInfinity;
float score = 0;
bool wantsWrapAround = navigation.wrapAround && (m_Navigation.mode == Navigation.Mode.Vertical || m_Navigation.mode == Navigation.Mode.Horizontal);
Selectable bestPick = null;
Selectable bestFurthestPick = null;
for (int i = 0; i < s_SelectableCount; ++i)
{
Selectable sel = s_Selectables[i];
if (sel == this)
continue;
if (!sel.IsInteractable() || sel.navigation.mode == Navigation.Mode.None)
continue;
#if UNITY_EDITOR
// Apart from runtime use, FindSelectable is used by custom editors to
// draw arrows between different selectables. For scene view cameras,
// only selectables in the same stage should be considered.
if (Camera.current != null && !UnityEditor.SceneManagement.StageUtility.IsGameObjectRenderedByCamera(sel.gameObject, Camera.current))
continue;
#endif
var selRect = sel.transform as RectTransform;
Vector3 selCenter = selRect != null ? (Vector3)selRect.rect.center : Vector3.zero;
Vector3 myVector = sel.transform.TransformPoint(selCenter) - pos;
// Value that is the distance out along the direction.
float dot = Vector3.Dot(dir, myVector);
// If element is in wrong direction and we have wrapAround enabled check and cache it if furthest away.
if (wantsWrapAround && dot < 0)
{
score = -dot * myVector.sqrMagnitude;
if (score > maxFurthestScore)
{
maxFurthestScore = score;
bestFurthestPick = sel;
}
continue;
}
// Skip elements that are in the wrong direction or which have zero distance.
// This also ensures that the scoring formula below will not have a division by zero error.
if (dot <= 0)
continue;
// This scoring function has two priorities:
// - Score higher for positions that are closer.
// - Score higher for positions that are located in the right direction.
// This scoring function combines both of these criteria.
// It can be seen as this:
// Dot (dir, myVector.normalized) / myVector.magnitude
// The first part equals 1 if the direction of myVector is the same as dir, and 0 if it's orthogonal.
// The second part scores lower the greater the distance is by dividing by the distance.
// The formula below is equivalent but more optimized.
//
// If a given score is chosen, the positions that evaluate to that score will form a circle
// that touches pos and whose center is located along dir. A way to visualize the resulting functionality is this:
// From the position pos, blow up a circular balloon so it grows in the direction of dir.
// The first Selectable whose center the circular balloon touches is the one that's chosen.
score = dot / myVector.sqrMagnitude;
if (score > maxScore)
{
maxScore = score;
bestPick = sel;
}
}
if (wantsWrapAround && null == bestPick) return bestFurthestPick;
return bestPick;
}
private static Vector3 GetPointOnRectEdge(RectTransform rect, Vector2 dir)
{
if (rect == null)
return Vector3.zero;
if (dir != Vector2.zero)
dir /= Mathf.Max(Mathf.Abs(dir.x), Mathf.Abs(dir.y));
dir = rect.rect.center + Vector2.Scale(rect.rect.size, dir * 0.5f);
return dir;
}
// Convenience function -- change the selection to the specified object if it's not null and happens to be active.
void Navigate(AxisEventData eventData, Selectable sel)
{
if (sel != null && sel.IsActive())
eventData.selectedObject = sel.gameObject;
}
/// <summary>
/// Find the selectable object to the left of this one.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class ExampleClass : MonoBehaviour
/// {
/// public Button btnMain;
///
/// // Disables the selectable UI element directly to the left of the Start Button
/// public void IgnoreSelectables()
/// {
/// //Finds the selectable UI element to the left the start button and assigns it to a variable of type "Selectable"
/// Selectable secondButton = startButton.FindSelectableOnLeft();
/// //Disables interaction with the selectable UI element
/// secondButton.interactable = false;
/// }
/// }
/// </code>
/// </example>
public virtual Selectable FindSelectableOnLeft()
{
if (m_Navigation.mode == Navigation.Mode.Explicit)
{
return m_Navigation.selectOnLeft;
}
if ((m_Navigation.mode & Navigation.Mode.Horizontal) != 0)
{
return FindSelectable(transform.rotation * Vector3.left);
}
return null;
}
/// <summary>
/// Find the selectable object to the right of this one.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class ExampleClass : MonoBehaviour
/// {
/// public Button btnMain;
///
/// // Disables the selectable UI element directly to the right the Start Button
/// public void IgnoreSelectables()
/// {
/// //Finds the selectable UI element to the right the start button and assigns it to a variable of type "Selectable"
/// Selectable secondButton = startButton.FindSelectableOnRight();
/// //Disables interaction with the selectable UI element
/// secondButton.interactable = false;
/// }
/// }
/// </code>
/// </example>
public virtual Selectable FindSelectableOnRight()
{
if (m_Navigation.mode == Navigation.Mode.Explicit)
{
return m_Navigation.selectOnRight;
}
if ((m_Navigation.mode & Navigation.Mode.Horizontal) != 0)
{
return FindSelectable(transform.rotation * Vector3.right);
}
return null;
}
/// <summary>
/// The Selectable object above current
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class ExampleClass : MonoBehaviour
/// {
/// public Button btnMain;
///
/// // Disables the selectable UI element directly above the Start Button
/// public void IgnoreSelectables()
/// {
/// //Finds the selectable UI element above the start button and assigns it to a variable of type "Selectable"
/// Selectable secondButton = startButton.FindSelectableOnUp();
/// //Disables interaction with the selectable UI element
/// secondButton.interactable = false;
/// }
/// }
/// </code>
/// </example>
public virtual Selectable FindSelectableOnUp()
{
if (m_Navigation.mode == Navigation.Mode.Explicit)
{
return m_Navigation.selectOnUp;
}
if ((m_Navigation.mode & Navigation.Mode.Vertical) != 0)
{
return FindSelectable(transform.rotation * Vector3.up);
}
return null;
}
/// <summary>
/// Find the selectable object below this one.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class Example : MonoBehaviour
/// {
/// public Button startButton;
///
/// // Disables the selectable UI element directly below the Start Button
/// public void IgnoreSelectables()
/// {
/// //Finds the selectable UI element below the start button and assigns it to a variable of type "Selectable"
/// Selectable secondButton = startButton.FindSelectableOnDown();
/// //Disables interaction with the selectable UI element
/// secondButton.interactable = false;
/// }
/// }
/// </code>
/// </example>
public virtual Selectable FindSelectableOnDown()
{
if (m_Navigation.mode == Navigation.Mode.Explicit)
{
return m_Navigation.selectOnDown;
}
if ((m_Navigation.mode & Navigation.Mode.Vertical) != 0)
{
return FindSelectable(transform.rotation * Vector3.down);
}
return null;
}
/// <summary>
/// Determine in which of the 4 move directions the next selectable object should be found.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI;
/// using UnityEngine.EventSystems;// Required when using Event data.
///
/// public class ExampleClass : MonoBehaviour, IMoveHandler
/// {
/// //When the focus moves to another selectable object, Invoke this Method.
/// public void OnMove(AxisEventData eventData)
/// {
/// //Assigns the move direction and the raw input vector representing the direction from the event data.
/// MoveDirection moveDir = eventData.moveDir;
/// Vector2 moveVector = eventData.moveVector;
///
/// //Displays the information in the console
/// Debug.Log(moveDir + ", " + moveVector);
/// }
/// }
/// </code>
/// </example>
public virtual void OnMove(AxisEventData eventData)
{
switch (eventData.moveDir)
{
case MoveDirection.Right:
Navigate(eventData, FindSelectableOnRight());
break;
case MoveDirection.Up:
Navigate(eventData, FindSelectableOnUp());
break;
case MoveDirection.Left:
Navigate(eventData, FindSelectableOnLeft());
break;
case MoveDirection.Down:
Navigate(eventData, FindSelectableOnDown());
break;
}
}
void StartColorTween(Color targetColor, bool instant)
{
if (m_TargetGraphic == null)
return;
m_TargetGraphic.CrossFadeColor(targetColor, instant ? 0f : m_Colors.fadeDuration, true, true);
}
void DoSpriteSwap(Sprite newSprite)
{
if (image == null)
return;
image.overrideSprite = newSprite;
}
void TriggerAnimation(string triggername)
{
#if PACKAGE_ANIMATION
if (transition != Transition.Animation || animator == null || !animator.isActiveAndEnabled || !animator.hasBoundPlayables || string.IsNullOrEmpty(triggername))
return;
animator.ResetTrigger(m_AnimationTriggers.normalTrigger);
animator.ResetTrigger(m_AnimationTriggers.highlightedTrigger);
animator.ResetTrigger(m_AnimationTriggers.pressedTrigger);
animator.ResetTrigger(m_AnimationTriggers.selectedTrigger);
animator.ResetTrigger(m_AnimationTriggers.disabledTrigger);
animator.SetTrigger(triggername);
#endif
}
/// <summary>
/// Returns whether the selectable is currently 'highlighted' or not.
/// </summary>
/// <remarks>
/// Use this to check if the selectable UI element is currently highlighted.
/// </remarks>
/// <example>
/// <code>
/// //Create a UI element. To do this go to Create>UI and select from the list. Attach this script to the UI GameObject to see this script working. The script also works with non-UI elements, but highlighting works better with UI.
///
/// using UnityEngine;
/// using UnityEngine.Events;
/// using UnityEngine.EventSystems;
/// using UnityEngine.UI;
///
/// //Use the Selectable class as a base class to access the IsHighlighted method
/// public class Example : Selectable
/// {
/// //Use this to check what Events are happening
/// BaseEventData m_BaseEvent;
///
/// void Update()
/// {
/// //Check if the GameObject is being highlighted
/// if (IsHighlighted())
/// {
/// //Output that the GameObject was highlighted, or do something else
/// Debug.Log("Selectable is Highlighted");
/// }
/// }
/// }
/// </code>
/// </example>
protected bool IsHighlighted()
{
if (!IsActive() || !IsInteractable())
return false;
return isPointerInside && !isPointerDown && !hasSelection;
}
/// <summary>
/// Whether the current selectable is being pressed.
/// </summary>
protected bool IsPressed()
{
if (!IsActive() || !IsInteractable())
return false;
return isPointerDown;
}
// Change the button to the correct state
private void EvaluateAndTransitionToSelectionState()
{
if (!IsActive() || !IsInteractable())
return;
DoStateTransition(currentSelectionState, false);
}
/// <summary>
/// Evaluate current state and transition to pressed state.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI;
/// using UnityEngine.EventSystems;// Required when using Event data.
///
/// public class ExampleClass : MonoBehaviour, IPointerDownHandler// required interface when using the OnPointerDown method.
/// {
/// //Do this when the mouse is clicked over the selectable object this script is attached to.
/// public void OnPointerDown(PointerEventData eventData)
/// {
/// Debug.Log(this.gameObject.name + " Was Clicked.");
/// }
/// }
/// </code>
/// </example>
public virtual void OnPointerDown(PointerEventData eventData)
{
if (eventData.button != PointerEventData.InputButton.Left)
return;
// Selection tracking
if (IsInteractable() && navigation.mode != Navigation.Mode.None && EventSystem.current != null)
EventSystem.current.SetSelectedGameObject(gameObject, eventData);
isPointerDown = true;
EvaluateAndTransitionToSelectionState();
}
/// <summary>
/// Evaluate eventData and transition to appropriate state.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI;
/// using UnityEngine.EventSystems;// Required when using Event data.
///
/// public class ExampleClass : MonoBehaviour, IPointerUpHandler, IPointerDownHandler// These are the interfaces the OnPointerUp method requires.
/// {
/// //OnPointerDown is also required to receive OnPointerUp callbacks
/// public void OnPointerDown(PointerEventData eventData)
/// {
/// }
///
/// //Do this when the mouse click on this selectable UI object is released.
/// public void OnPointerUp(PointerEventData eventData)
/// {
/// Debug.Log("The mouse click was released");
/// }
/// }
/// </code>
/// </example>
public virtual void OnPointerUp(PointerEventData eventData)
{
if (eventData.button != PointerEventData.InputButton.Left)
return;
isPointerDown = false;
EvaluateAndTransitionToSelectionState();
}
/// <summary>
/// Evaluate current state and transition to appropriate state.
/// New state could be pressed or hover depending on pressed state.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI;
/// using UnityEngine.EventSystems;// Required when using Event data.
///
/// public class ExampleClass : MonoBehaviour, IPointerEnterHandler// required interface when using the OnPointerEnter method.
/// {
/// //Do this when the cursor enters the rect area of this selectable UI object.
/// public void OnPointerEnter(PointerEventData eventData)
/// {
/// Debug.Log("The cursor entered the selectable UI element.");
/// }
/// }
/// </code>
/// </example>
public virtual void OnPointerEnter(PointerEventData eventData)
{
isPointerInside = true;
EvaluateAndTransitionToSelectionState();
}
/// <summary>
/// Evaluate current state and transition to normal state.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI;
/// using UnityEngine.EventSystems;// Required when using Event data.
///
/// public class ExampleClass : MonoBehaviour, IPointerExitHandler// required interface when using the OnPointerExit method.
/// {
/// //Do this when the cursor exits the rect area of this selectable UI object.
/// public void OnPointerExit(PointerEventData eventData)
/// {
/// Debug.Log("The cursor exited the selectable UI element.");
/// }
/// }
/// </code>
/// </example>
public virtual void OnPointerExit(PointerEventData eventData)
{
isPointerInside = false;
EvaluateAndTransitionToSelectionState();
}
/// <summary>
/// Set selection and transition to appropriate state.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI;
/// using UnityEngine.EventSystems;// Required when using Event data.
///
/// public class ExampleClass : MonoBehaviour, ISelectHandler// required interface when using the OnSelect method.
/// {
/// //Do this when the selectable UI object is selected.
/// public void OnSelect(BaseEventData eventData)
/// {
/// Debug.Log(this.gameObject.name + " was selected");
/// }
/// }
/// </code>
/// </example>
public virtual void OnSelect(BaseEventData eventData)
{
hasSelection = true;
EvaluateAndTransitionToSelectionState();
}
/// <summary>
/// Unset selection and transition to appropriate state.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI;
/// using UnityEngine.EventSystems;// Required when using Event data.
///
/// public class ExampleClass : MonoBehaviour, IDeselectHandler //This Interface is required to receive OnDeselect callbacks.
/// {
/// public void OnDeselect(BaseEventData data)
/// {
/// Debug.Log("Deselected");
/// }
/// }
/// </code>
/// </example>
public virtual void OnDeselect(BaseEventData eventData)
{
hasSelection = false;
EvaluateAndTransitionToSelectionState();
}
/// <summary>
/// Selects this Selectable.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
/// using UnityEngine.EventSystems;// Required when using Event data.
///
/// public class ExampleClass : MonoBehaviour// required interface when using the OnSelect method.
/// {
/// public InputField myInputField;
///
/// //Do this OnClick.
/// public void SaveGame()
/// {
/// //Makes the Input Field the selected UI Element.
/// myInputField.Select();
/// }
/// }
/// </code>
/// </example>
public virtual void Select()
{
if (EventSystem.current == null || EventSystem.current.alreadySelecting)
return;
EventSystem.current.SetSelectedGameObject(gameObject);
}
}
}
| 0 | 0.939477 | 1 | 0.939477 | game-dev | MEDIA | 0.563952 | game-dev | 0.755089 | 1 | 0.755089 |
Citadel-Station-13/Citadel-Station-13 | 1,447 | code/controllers/subsystem/mobs.dm | SUBSYSTEM_DEF(mobs)
name = "Mobs"
priority = FIRE_PRIORITY_MOBS
flags = SS_KEEP_TIMING | SS_NO_INIT
runlevels = RUNLEVEL_GAME | RUNLEVEL_POSTGAME
var/list/currentrun = list()
var/static/list/clients_by_zlevel[][]
var/static/list/dead_players_by_zlevel[][] = list(list()) // Needs to support zlevel 1 here, MaxZChanged only happens when z2 is created and new_players can login before that.
var/static/list/cubemonkeys = list()
var/static/list/cheeserats = list()
/datum/controller/subsystem/mobs/stat_entry(msg)
msg = "P:[length(GLOB.mob_living_list)]"
return ..()
/datum/controller/subsystem/mobs/proc/MaxZChanged()
if (!islist(clients_by_zlevel))
clients_by_zlevel = new /list(world.maxz,0)
dead_players_by_zlevel = new /list(world.maxz,0)
while (clients_by_zlevel.len < world.maxz)
clients_by_zlevel.len++
clients_by_zlevel[clients_by_zlevel.len] = list()
dead_players_by_zlevel.len++
dead_players_by_zlevel[dead_players_by_zlevel.len] = list()
/datum/controller/subsystem/mobs/fire(resumed = 0)
var/seconds = wait * 0.1
if (!resumed)
src.currentrun = GLOB.mob_living_list.Copy()
//cache for sanic speed (lists are references anyways)
var/list/currentrun = src.currentrun
var/times_fired = src.times_fired
while(currentrun.len)
var/mob/living/L = currentrun[currentrun.len]
currentrun.len--
if(L)
L.Life(seconds, times_fired)
else
GLOB.mob_living_list.Remove(L)
if (MC_TICK_CHECK)
return
| 0 | 0.840687 | 1 | 0.840687 | game-dev | MEDIA | 0.686275 | game-dev | 0.92256 | 1 | 0.92256 |
FMXExpress/Firemonkey | 110,104 | Embarcadero/Rio/Object Pascal/TestBed/Box2D.Collision.pas | // ==========================================================================
//
// Copyright(c) 2012-2014 Embarcadero Technologies, Inc.
//
// ==========================================================================
//
// Delphi-C++ Library Bridge
// Interface for library FlatBox2D
//
unit Box2D.Collision;
interface
uses
Box2D.Common,
Box2DTypes;
const
b2_nullNode = (-1);
b2_nullFeature = 255;
type
{$MinEnumSize 4}
b2PointState = (b2_nullState = 0, b2_addState = 1, b2_persistState = 2, b2_removeState = 3);
{$MinEnumSize 1}
Pb2PointState = ^b2PointState;
b2ShapeHandle = THandle;
Pb2ShapeHandle = ^b2ShapeHandle;
b2CircleShapeHandle = THandle;
Pb2CircleShapeHandle = ^b2CircleShapeHandle;
b2EdgeShapeHandle = THandle;
Pb2EdgeShapeHandle = ^b2EdgeShapeHandle;
b2PolygonShapeHandle = THandle;
Pb2PolygonShapeHandle = ^b2PolygonShapeHandle;
b2DynamicTreeHandle = THandle;
Pb2DynamicTreeHandle = ^b2DynamicTreeHandle;
b2BroadPhaseHandle = THandle;
Pb2BroadPhaseHandle = ^b2BroadPhaseHandle;
b2ChainShapeHandle = THandle;
Pb2ChainShapeHandle = ^b2ChainShapeHandle;
Pb2ContactFeature = ^b2ContactFeature;
PPb2ContactFeature = ^Pb2ContactFeature;
Pb2ContactID = ^b2ContactID;
PPb2ContactID = ^Pb2ContactID;
Pb2ManifoldPoint = ^b2ManifoldPoint;
PPb2ManifoldPoint = ^Pb2ManifoldPoint;
Pb2Manifold = ^b2Manifold;
PPb2Manifold = ^Pb2Manifold;
Pb2WorldManifold = ^b2WorldManifold;
PPb2WorldManifold = ^Pb2WorldManifold;
Pb2ClipVertex = ^b2ClipVertex;
PPb2ClipVertex = ^Pb2ClipVertex;
Pb2RayCastInput = ^b2RayCastInput;
PPb2RayCastInput = ^Pb2RayCastInput;
Pb2RayCastOutput = ^b2RayCastOutput;
PPb2RayCastOutput = ^Pb2RayCastOutput;
Pb2AABB = ^b2AABB;
PPb2AABB = ^Pb2AABB;
Pb2TreeNode = ^b2TreeNode;
PPb2TreeNode = ^Pb2TreeNode;
Pb2Pair = ^b2Pair;
PPb2Pair = ^Pb2Pair;
Pb2DistanceProxy = ^b2DistanceProxy;
PPb2DistanceProxy = ^Pb2DistanceProxy;
Pb2SimplexCache = ^b2SimplexCache;
PPb2SimplexCache = ^Pb2SimplexCache;
Pb2DistanceInput = ^b2DistanceInput;
PPb2DistanceInput = ^Pb2DistanceInput;
Pb2DistanceOutput = ^b2DistanceOutput;
PPb2DistanceOutput = ^Pb2DistanceOutput;
Pb2TOIInput = ^b2TOIInput;
PPb2TOIInput = ^Pb2TOIInput;
Pb2TOIOutput = ^b2TOIOutput;
PPb2TOIOutput = ^Pb2TOIOutput;
Pb2MassData = ^b2MassData;
PPb2MassData = ^Pb2MassData;
{ ===== Records ===== }
{ The features that intersect to form the contact point
This must be 4 bytes or less.}
b2ContactFeature = record
const
e_vertex = 0;
e_face = 1;
var
indexA: Byte; {< Feature index on shapeA}
indexB: Byte; {< Feature index on shapeB}
typeA: Byte; {< The feature type on shapeA}
typeB: Byte; {< The feature type on shapeB}
class function Create: b2ContactFeature; static; cdecl;
end;
{ Contact ids to facilitate warm starting.}
b2ContactID = record
class function Create: b2ContactID; static; cdecl;
case Integer of
0: (cf: b2ContactFeature;);
1: (key: Cardinal;);
end;
{ A manifold point is a contact point belonging to a contact
manifold. It holds details related to the geometry and dynamics
of the contact points.
The local point usage depends on the manifold type:
-e_circles: the local center of circleB
-e_faceA: the local center of cirlceB or the clip point of polygonB
-e_faceB: the clip point of polygonA
This structure is stored across time steps, so we keep it small.
Note: the impulses are used for internal caching and may not
provide reliable contact forces, especially for high speed collisions.}
b2ManifoldPoint = record
localPoint: b2Vec2; {< usage depends on manifold type}
normalImpulse: Single; {< the non-penetration impulse}
tangentImpulse: Single; {< the friction impulse}
id: b2ContactID; {< uniquely identifies a contact point between two shapes}
class function Create: b2ManifoldPoint; static; cdecl;
end;
{ A manifold for two touching convex shapes.
Box2D supports multiple types of contact:
- clip point versus plane with radius
- point versus point with radius (circles)
The local point usage depends on the manifold type:
-e_circles: the local center of circleA
-e_faceA: the center of faceA
-e_faceB: the center of faceB
Similarly the local normal usage:
-e_circles: not used
-e_faceA: the normal on polygonA
-e_faceB: the normal on polygonB
We store contacts in this way so that position correction can
account for movement, which is critical for continuous physics.
All contact scenarios must be expressed in one of these types.
This structure is stored across time steps, so we keep it small.}
b2Manifold = record
const
e_circles = 0;
e_faceA = 1;
e_faceB = 2;
var
points: array[0..1] of b2ManifoldPoint; {< the points of contact}
localNormal: b2Vec2; {< not use for Type::e_points}
localPoint: b2Vec2; {< usage depends on manifold type}
&type: Integer;
pointCount: Integer; {< the number of manifold points}
class function Create: b2Manifold; static; cdecl;
end;
{ This is used to compute the current state of a contact manifold.}
b2WorldManifold = record
normal: b2Vec2; {< world vector pointing from A to B}
points: array[0..1] of b2Vec2; {< world contact point (point of intersection)}
separations: array[0..1] of Single; {< a negative value indicates overlap, in meters}
class function Create: b2WorldManifold; static; cdecl;
{ Evaluate the manifold with supplied transforms. This assumes
modest motion from the original state. This does not change the
point count, impulses, etc. The radii must come from the shapes
that generated the manifold.}
procedure Initialize(manifold: Pb2Manifold; const [ref] xfA: b2Transform; radiusA: Single; const [ref] xfB: b2Transform; radiusB: Single); cdecl;
end;
{ Used for computing contact manifolds.}
b2ClipVertex = record
v: b2Vec2;
id: b2ContactID;
class function Create: b2ClipVertex; static; cdecl;
end;
{ Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).}
b2RayCastInput = record
p1: b2Vec2;
p2: b2Vec2;
maxFraction: Single;
class function Create: b2RayCastInput; static; cdecl;
end;
{ Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2
come from b2RayCastInput.}
b2RayCastOutput = record
normal: b2Vec2;
fraction: Single;
class function Create: b2RayCastOutput; static; cdecl;
end;
{ An axis aligned bounding box.}
b2AABB = record
lowerBound: b2Vec2; {< the lower vertex}
upperBound: b2Vec2; {< the upper vertex}
class function Create: b2AABB; static; cdecl;
{ Verify that the bounds are sorted.}
function IsValid: Boolean; cdecl;
{ Get the center of the AABB.}
function GetCenter: b2Vec2; cdecl;
{ Get the extents of the AABB (half-widths).}
function GetExtents: b2Vec2; cdecl;
{ Get the perimeter length}
function GetPerimeter: Single; cdecl;
{ Combine an AABB into this one.}
procedure Combine(const [ref] aabb: b2AABB); overload; cdecl;
{ Combine two AABBs into this one.}
procedure Combine(const [ref] aabb1: b2AABB; const [ref] aabb2: b2AABB); overload; cdecl;
{ Does this aabb contain the provided AABB.}
function Contains(const [ref] aabb: b2AABB): Boolean; cdecl;
function RayCast(output: Pb2RayCastOutput; const [ref] input: b2RayCastInput): Boolean; cdecl;
end;
{ A node in the dynamic tree. The client does not interact with this directly.}
b2TreeNode = record
aabb: b2AABB; { Enlarged AABB}
userData: Pointer;
union1: record
case Integer of
0: (parent: Integer);
1: (next: Integer);
end;
child1: Integer;
child2: Integer;
height: Integer;
class function Create: b2TreeNode; static; cdecl;
function IsLeaf: Boolean; cdecl;
end;
{ A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt.
A dynamic tree arranges data in a binary tree to accelerate
queries such as volume queries and ray casts. Leafs are proxies
with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor
so that the proxy AABB is bigger than the client object. This allows the client
object to move by small amounts without triggering a tree update.
Nodes are pooled and relocatable, so we use node indices rather than pointers.}
b2DynamicTreeWrapper = record
FHandle: b2DynamicTreeHandle;
class function Create: b2DynamicTreeWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2DynamicTreeHandle): b2DynamicTreeWrapper; overload;
class operator Implicit(wrapper: b2DynamicTreeWrapper): b2DynamicTreeHandle; overload;
{ Create a proxy. Provide a tight fitting AABB and a userData pointer.}
function CreateProxy(const [ref] aabb: b2AABB; userData: Pointer): Integer; cdecl;
{ Destroy a proxy. This asserts if the id is invalid.}
procedure DestroyProxy(proxyId: Integer); cdecl;
{ Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB,
then the proxy is removed from the tree and re-inserted. Otherwise
the function returns immediately.
@return true if the proxy was re-inserted.}
function MoveProxy(proxyId: Integer; const [ref] aabb1: b2AABB; const [ref] displacement: b2Vec2): Boolean; cdecl;
{ Get proxy user data.
@return the proxy user data or 0 if the id is invalid.}
function GetUserData(proxyId: Integer): Pointer; cdecl;
{ Get the fat AABB for a proxy.}
function GetFatAABB(proxyId: Integer): Pb2AABB; cdecl;
{ Validate this tree. For testing.}
procedure Validate; cdecl;
{ Compute the height of the binary tree in O(N) time. Should not be
called often.}
function GetHeight: Integer; cdecl;
{ Get the maximum balance of an node in the tree. The balance is the difference
in height of the two children of a node.}
function GetMaxBalance: Integer; cdecl;
{ Get the ratio of the sum of the node areas to the root area.}
function GetAreaRatio: Single; cdecl;
{ Build an optimal tree. Very expensive. For testing.}
procedure RebuildBottomUp; cdecl;
{ Shift the world origin. Useful for large worlds.
The shift formula is: position -= newOrigin
@param newOrigin the new origin with respect to the old origin}
procedure ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
end;
b2Pair = record
proxyIdA: Integer;
proxyIdB: Integer;
class function Create: b2Pair; static; cdecl;
end;
{ The broad-phase is used for computing pairs and performing volume queries and ray casts.
This broad-phase does not persist pairs. Instead, this reports potentially new pairs.
It is up to the client to consume the new pairs and to track subsequent overlap.}
b2BroadPhaseWrapper = record
const
e_nullProxy = - 1;
var
FHandle: b2BroadPhaseHandle;
class function Create: b2BroadPhaseWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2BroadPhaseHandle): b2BroadPhaseWrapper; overload;
class operator Implicit(wrapper: b2BroadPhaseWrapper): b2BroadPhaseHandle; overload;
{ Create a proxy with an initial AABB. Pairs are not reported until
UpdatePairs is called.}
function CreateProxy(const [ref] aabb: b2AABB; userData: Pointer): Integer; cdecl;
{ Destroy a proxy. It is up to the client to remove any pairs.}
procedure DestroyProxy(proxyId: Integer); cdecl;
{ Call MoveProxy as many times as you like, then when you are done
call UpdatePairs to finalized the proxy pairs (for your time step).}
procedure MoveProxy(proxyId: Integer; const [ref] aabb: b2AABB; const [ref] displacement: b2Vec2); cdecl;
{ Call to trigger a re-processing of it's pairs on the next call to UpdatePairs.}
procedure TouchProxy(proxyId: Integer); cdecl;
{ Get the fat AABB for a proxy.}
function GetFatAABB(proxyId: Integer): Pb2AABB; cdecl;
{ Get user data from a proxy. Returns NULL if the id is invalid.}
function GetUserData(proxyId: Integer): Pointer; cdecl;
{ Test overlap of fat AABBs.}
function TestOverlap(proxyIdA: Integer; proxyIdB: Integer): Boolean; cdecl;
{ Get the number of proxies.}
function GetProxyCount: Integer; cdecl;
{ Get the height of the embedded tree.}
function GetTreeHeight: Integer; cdecl;
{ Get the balance of the embedded tree.}
function GetTreeBalance: Integer; cdecl;
{ Get the quality metric of the embedded tree.}
function GetTreeQuality: Single; cdecl;
{ Shift the world origin. Useful for large worlds.
The shift formula is: position -= newOrigin
@param newOrigin the new origin with respect to the old origin}
procedure ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
end;
{ A distance proxy is used by the GJK algorithm.
It encapsulates any shape.}
b2DistanceProxy = record
m_buffer: array[0..1] of b2Vec2;
m_vertices: Pb2Vec2;
m_count: Integer;
m_radius: Single;
class function Create: b2DistanceProxy; static; cdecl;
{ Initialize the proxy using the given shape. The shape
must remain in scope while the proxy is in use.}
procedure &Set(shape: b2ShapeHandle; index: Integer); cdecl;
{ Get the supporting vertex index in the given direction.}
function GetSupport(const [ref] d: b2Vec2): Integer; cdecl;
{ Get the supporting vertex in the given direction.}
function GetSupportVertex(const [ref] d: b2Vec2): Pb2Vec2; cdecl;
{ Get the vertex count.}
function GetVertexCount: Integer; cdecl;
{ Get a vertex by index. Used by b2Distance.}
function GetVertex(index: Integer): Pb2Vec2; cdecl;
end;
{ Used to warm start b2Distance.
Set count to zero on first call.}
b2SimplexCache = record
metric: Single; {< length or area}
count: Word;
indexA: array[0..2] of Byte; {< vertices on shape A}
indexB: array[0..2] of Byte; {< vertices on shape B}
class function Create: b2SimplexCache; static; cdecl;
end;
{ Input for b2Distance.
You have to option to use the shape radii
in the computation. Even}
b2DistanceInput = record
proxyA: b2DistanceProxy;
proxyB: b2DistanceProxy;
transformA: b2Transform;
transformB: b2Transform;
useRadii: Boolean;
class function Create: b2DistanceInput; static; cdecl;
end;
{ Output for b2Distance.}
b2DistanceOutput = record
pointA: b2Vec2; {< closest point on shapeA}
pointB: b2Vec2; {< closest point on shapeB}
distance: Single;
iterations: Integer; {< number of GJK iterations used}
class function Create: b2DistanceOutput; static; cdecl;
end;
{ Input parameters for b2TimeOfImpact}
b2TOIInput = record
proxyA: b2DistanceProxy;
proxyB: b2DistanceProxy;
sweepA: b2Sweep;
sweepB: b2Sweep;
tMax: Single;
class function Create: b2TOIInput; static; cdecl;
end;
b2TOIOutput = record
const
e_unknown = 0;
e_failed = 1;
e_overlapped = 2;
e_touching = 3;
e_separated = 4;
var
state: Integer;
t: Single;
class function Create: b2TOIOutput; static; cdecl;
end;
{ This holds the mass data computed for a shape.}
b2MassData = record
mass: Single; { The mass of the shape, usually in kilograms.}
center: b2Vec2; { The position of the shape's centroid relative to the shape's origin.}
I: Single; { The rotational inertia of the shape about the local origin.}
class function Create: b2MassData; static; cdecl;
end;
{ A shape is used for collision detection. You can create a shape however you like.
Shapes used for simulation in b2World are created automatically when a b2Fixture
is created. Shapes may encapsulate a one or more child shapes.}
b2ShapeWrapper = record
const
e_circle = 0;
e_edge = 1;
e_polygon = 2;
e_chain = 3;
e_typeCount = 4;
var
FHandle: b2ShapeHandle;
private
function Get_m_type: Integer; cdecl;
procedure Set_m_type(aNewValue: Integer); cdecl;
function Get_m_radius: Single; cdecl;
procedure Set_m_radius(aNewValue: Single); cdecl;
public
class operator Implicit(handle: b2ShapeHandle): b2ShapeWrapper; overload;
class operator Implicit(wrapper: b2ShapeWrapper): b2ShapeHandle; overload;
{ Clone the concrete shape using the provided allocator.}
function Clone(allocator: b2BlockAllocatorHandle): b2ShapeHandle; cdecl;
{ Get the type of this shape. You can use this to down cast to the concrete shape.
@return the shape type.}
function GetType: Integer; cdecl;
{ Get the number of child primitives.}
function GetChildCount: Integer; cdecl;
{ Test a point for containment in this shape. This only works for convex shapes.
@param xf the shape world transform.
@param p a point in world coordinates.}
function TestPoint(const [ref] xf: b2Transform; const [ref] p: b2Vec2): Boolean; cdecl;
{ Cast a ray against a child shape.
@param output the ray-cast results.
@param input the ray-cast input parameters.
@param transform the transform to be applied to the shape.
@param childIndex the child shape index}
function RayCast(output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; const [ref] transform: b2Transform; childIndex: Integer): Boolean; cdecl;
{ Given a transform, compute the associated axis aligned bounding box for a child shape.
@param aabb returns the axis aligned box.
@param xf the world transform of the shape.
@param childIndex the child shape}
procedure ComputeAABB(aabb: Pb2AABB; const [ref] xf: b2Transform; childIndex: Integer); cdecl;
{ Compute the mass properties of this shape using its dimensions and density.
The inertia tensor is computed about the local origin.
@param massData returns the mass data for this shape.
@param density the density in kilograms per meter squared.}
procedure ComputeMass(massData: Pb2MassData; density: Single); cdecl;
property m_type: Integer read Get_m_type write Set_m_type;
property m_radius: Single read Get_m_radius write Set_m_radius;
end;
{ A chain shape is a free form sequence of line segments.
The chain has two-sided collision, so you can use inside and outside collision.
Therefore, you may use any winding order.
Since there may be many vertices, they are allocated using b2Alloc.
Connectivity information is used to create smooth collisions.
WARNING: The chain will not collide properly if there are self-intersections.}
b2ChainShapeWrapper = record
FHandle: b2ChainShapeHandle;
private
function Get_m_type: Integer; cdecl;
procedure Set_m_type(aNewValue: Integer); cdecl;
function Get_m_radius: Single; cdecl;
procedure Set_m_radius(aNewValue: Single); cdecl;
function Get_m_vertices: Pb2Vec2; cdecl;
procedure Set_m_vertices(aNewValue: Pb2Vec2); cdecl;
function Get_m_count: Integer; cdecl;
procedure Set_m_count(aNewValue: Integer); cdecl;
function Get_m_prevVertex: b2Vec2; cdecl;
procedure Set_m_prevVertex(aNewValue: b2Vec2); cdecl;
function Get_m_prevVertex_P: Pb2Vec2; cdecl;
function Get_m_nextVertex: b2Vec2; cdecl;
procedure Set_m_nextVertex(aNewValue: b2Vec2); cdecl;
function Get_m_nextVertex_P: Pb2Vec2; cdecl;
function Get_m_hasPrevVertex: Boolean; cdecl;
procedure Set_m_hasPrevVertex(aNewValue: Boolean); cdecl;
function Get_m_hasNextVertex: Boolean; cdecl;
procedure Set_m_hasNextVertex(aNewValue: Boolean); cdecl;
public
class function Create: b2ChainShapeWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2ChainShapeHandle): b2ChainShapeWrapper; overload;
class operator Implicit(wrapper: b2ChainShapeWrapper): b2ChainShapeHandle; overload;
{ Clone the concrete shape using the provided allocator.}
function Clone(allocator: b2BlockAllocatorHandle): b2ShapeHandle; cdecl;
{ Get the type of this shape. You can use this to down cast to the concrete shape.
@return the shape type.}
function GetType: Integer; cdecl;
{ Get the number of child primitives.}
function GetChildCount: Integer; cdecl;
{ Test a point for containment in this shape. This only works for convex shapes.
@param xf the shape world transform.
@param p a point in world coordinates.}
function TestPoint(const [ref] xf: b2Transform; const [ref] p: b2Vec2): Boolean; cdecl;
{ Cast a ray against a child shape.
@param output the ray-cast results.
@param input the ray-cast input parameters.
@param transform the transform to be applied to the shape.
@param childIndex the child shape index}
function RayCast(output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; const [ref] transform: b2Transform; childIndex: Integer): Boolean; cdecl;
{ Given a transform, compute the associated axis aligned bounding box for a child shape.
@param aabb returns the axis aligned box.
@param xf the world transform of the shape.
@param childIndex the child shape}
procedure ComputeAABB(aabb: Pb2AABB; const [ref] xf: b2Transform; childIndex: Integer); cdecl;
{ Compute the mass properties of this shape using its dimensions and density.
The inertia tensor is computed about the local origin.
@param massData returns the mass data for this shape.
@param density the density in kilograms per meter squared.}
procedure ComputeMass(massData: Pb2MassData; density: Single); cdecl;
property m_type: Integer read Get_m_type write Set_m_type;
property m_radius: Single read Get_m_radius write Set_m_radius;
{ Clear all data.}
procedure Clear; cdecl;
{ Create a loop. This automatically adjusts connectivity.
@param vertices an array of vertices, these are copied
@param count the vertex count}
procedure CreateLoop(vertices: Pb2Vec2; count: Integer); cdecl;
{ Create a chain with isolated end vertices.
@param vertices an array of vertices, these are copied
@param count the vertex count}
procedure CreateChain(vertices: Pb2Vec2; count: Integer); cdecl;
{ Establish connectivity to a vertex that precedes the first vertex.
Don't call this for loops.}
procedure SetPrevVertex(const [ref] prevVertex: b2Vec2); cdecl;
{ Establish connectivity to a vertex that follows the last vertex.
Don't call this for loops.}
procedure SetNextVertex(const [ref] nextVertex: b2Vec2); cdecl;
{ Get a child edge.}
procedure GetChildEdge(edge: b2EdgeShapeHandle; index: Integer); cdecl;
{ The vertices. Owned by this class.}
property m_vertices: Pb2Vec2 read Get_m_vertices write Set_m_vertices;
{ The vertex count.}
property m_count: Integer read Get_m_count write Set_m_count;
property m_prevVertex: b2Vec2 read Get_m_prevVertex write Set_m_prevVertex;
property m_prevVertex_P: Pb2Vec2 read Get_m_prevVertex_P;
property m_nextVertex: b2Vec2 read Get_m_nextVertex write Set_m_nextVertex;
property m_nextVertex_P: Pb2Vec2 read Get_m_nextVertex_P;
property m_hasPrevVertex: Boolean read Get_m_hasPrevVertex write Set_m_hasPrevVertex;
property m_hasNextVertex: Boolean read Get_m_hasNextVertex write Set_m_hasNextVertex;
end;
{ A circle shape.}
b2CircleShapeWrapper = record
FHandle: b2CircleShapeHandle;
private
function Get_m_type: Integer; cdecl;
procedure Set_m_type(aNewValue: Integer); cdecl;
function Get_m_radius: Single; cdecl;
procedure Set_m_radius(aNewValue: Single); cdecl;
function Get_m_p: b2Vec2; cdecl;
procedure Set_m_p(aNewValue: b2Vec2); cdecl;
function Get_m_p_P: Pb2Vec2; cdecl;
public
class function Create: b2CircleShapeWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2CircleShapeHandle): b2CircleShapeWrapper; overload;
class operator Implicit(wrapper: b2CircleShapeWrapper): b2CircleShapeHandle; overload;
{ Clone the concrete shape using the provided allocator.}
function Clone(allocator: b2BlockAllocatorHandle): b2ShapeHandle; cdecl;
{ Get the type of this shape. You can use this to down cast to the concrete shape.
@return the shape type.}
function GetType: Integer; cdecl;
{ Get the number of child primitives.}
function GetChildCount: Integer; cdecl;
{ Test a point for containment in this shape. This only works for convex shapes.
@param xf the shape world transform.
@param p a point in world coordinates.}
function TestPoint(const [ref] xf: b2Transform; const [ref] p: b2Vec2): Boolean; cdecl;
{ Cast a ray against a child shape.
@param output the ray-cast results.
@param input the ray-cast input parameters.
@param transform the transform to be applied to the shape.
@param childIndex the child shape index}
function RayCast(output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; const [ref] transform: b2Transform; childIndex: Integer): Boolean; cdecl;
{ Given a transform, compute the associated axis aligned bounding box for a child shape.
@param aabb returns the axis aligned box.
@param xf the world transform of the shape.
@param childIndex the child shape}
procedure ComputeAABB(aabb: Pb2AABB; const [ref] xf: b2Transform; childIndex: Integer); cdecl;
{ Compute the mass properties of this shape using its dimensions and density.
The inertia tensor is computed about the local origin.
@param massData returns the mass data for this shape.
@param density the density in kilograms per meter squared.}
procedure ComputeMass(massData: Pb2MassData; density: Single); cdecl;
property m_type: Integer read Get_m_type write Set_m_type;
property m_radius: Single read Get_m_radius write Set_m_radius;
{ Get the supporting vertex index in the given direction.}
function GetSupport(const [ref] d: b2Vec2): Integer; cdecl;
{ Get the supporting vertex in the given direction.}
function GetSupportVertex(const [ref] d: b2Vec2): Pb2Vec2; cdecl;
{ Get the vertex count.}
function GetVertexCount: Integer; cdecl;
{ Get a vertex by index. Used by b2Distance.}
function GetVertex(index: Integer): Pb2Vec2; cdecl;
{ Position}
property m_p: b2Vec2 read Get_m_p write Set_m_p;
property m_p_P: Pb2Vec2 read Get_m_p_P;
end;
{ A line segment (edge) shape. These can be connected in chains or loops
to other edge shapes. The connectivity information is used to ensure
correct contact normals.}
b2EdgeShapeWrapper = record
FHandle: b2EdgeShapeHandle;
private
function Get_m_type: Integer; cdecl;
procedure Set_m_type(aNewValue: Integer); cdecl;
function Get_m_radius: Single; cdecl;
procedure Set_m_radius(aNewValue: Single); cdecl;
function Get_m_vertex1: b2Vec2; cdecl;
procedure Set_m_vertex1(aNewValue: b2Vec2); cdecl;
function Get_m_vertex1_P: Pb2Vec2; cdecl;
function Get_m_vertex2: b2Vec2; cdecl;
procedure Set_m_vertex2(aNewValue: b2Vec2); cdecl;
function Get_m_vertex2_P: Pb2Vec2; cdecl;
function Get_m_vertex0: b2Vec2; cdecl;
procedure Set_m_vertex0(aNewValue: b2Vec2); cdecl;
function Get_m_vertex0_P: Pb2Vec2; cdecl;
function Get_m_vertex3: b2Vec2; cdecl;
procedure Set_m_vertex3(aNewValue: b2Vec2); cdecl;
function Get_m_vertex3_P: Pb2Vec2; cdecl;
function Get_m_hasVertex0: Boolean; cdecl;
procedure Set_m_hasVertex0(aNewValue: Boolean); cdecl;
function Get_m_hasVertex3: Boolean; cdecl;
procedure Set_m_hasVertex3(aNewValue: Boolean); cdecl;
public
class function Create: b2EdgeShapeWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2EdgeShapeHandle): b2EdgeShapeWrapper; overload;
class operator Implicit(wrapper: b2EdgeShapeWrapper): b2EdgeShapeHandle; overload;
{ Clone the concrete shape using the provided allocator.}
function Clone(allocator: b2BlockAllocatorHandle): b2ShapeHandle; cdecl;
{ Get the type of this shape. You can use this to down cast to the concrete shape.
@return the shape type.}
function GetType: Integer; cdecl;
{ Get the number of child primitives.}
function GetChildCount: Integer; cdecl;
{ Test a point for containment in this shape. This only works for convex shapes.
@param xf the shape world transform.
@param p a point in world coordinates.}
function TestPoint(const [ref] xf: b2Transform; const [ref] p: b2Vec2): Boolean; cdecl;
{ Cast a ray against a child shape.
@param output the ray-cast results.
@param input the ray-cast input parameters.
@param transform the transform to be applied to the shape.
@param childIndex the child shape index}
function RayCast(output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; const [ref] transform: b2Transform; childIndex: Integer): Boolean; cdecl;
{ Given a transform, compute the associated axis aligned bounding box for a child shape.
@param aabb returns the axis aligned box.
@param xf the world transform of the shape.
@param childIndex the child shape}
procedure ComputeAABB(aabb: Pb2AABB; const [ref] xf: b2Transform; childIndex: Integer); cdecl;
{ Compute the mass properties of this shape using its dimensions and density.
The inertia tensor is computed about the local origin.
@param massData returns the mass data for this shape.
@param density the density in kilograms per meter squared.}
procedure ComputeMass(massData: Pb2MassData; density: Single); cdecl;
property m_type: Integer read Get_m_type write Set_m_type;
property m_radius: Single read Get_m_radius write Set_m_radius;
{ Set this as an isolated edge.}
procedure &Set(const [ref] v1: b2Vec2; const [ref] v2: b2Vec2); cdecl;
{ These are the edge vertices}
property m_vertex1: b2Vec2 read Get_m_vertex1 write Set_m_vertex1;
property m_vertex1_P: Pb2Vec2 read Get_m_vertex1_P;
property m_vertex2: b2Vec2 read Get_m_vertex2 write Set_m_vertex2;
property m_vertex2_P: Pb2Vec2 read Get_m_vertex2_P;
{ Optional adjacent vertices. These are used for smooth collision.}
property m_vertex0: b2Vec2 read Get_m_vertex0 write Set_m_vertex0;
property m_vertex0_P: Pb2Vec2 read Get_m_vertex0_P;
property m_vertex3: b2Vec2 read Get_m_vertex3 write Set_m_vertex3;
property m_vertex3_P: Pb2Vec2 read Get_m_vertex3_P;
property m_hasVertex0: Boolean read Get_m_hasVertex0 write Set_m_hasVertex0;
property m_hasVertex3: Boolean read Get_m_hasVertex3 write Set_m_hasVertex3;
end;
{ A convex polygon. It is assumed that the interior of the polygon is to
the left of each edge.
Polygons have a maximum number of vertices equal to b2_maxPolygonVertices.
In most cases you should not need many vertices for a convex polygon.}
b2PolygonShapeWrapper = record
FHandle: b2PolygonShapeHandle;
private
function Get_m_type: Integer; cdecl;
procedure Set_m_type(aNewValue: Integer); cdecl;
function Get_m_radius: Single; cdecl;
procedure Set_m_radius(aNewValue: Single); cdecl;
function Get_m_centroid: b2Vec2; cdecl;
procedure Set_m_centroid(aNewValue: b2Vec2); cdecl;
function Get_m_centroid_P: Pb2Vec2; cdecl;
function Get_m_vertices(_idx: Integer): b2Vec2; cdecl;
procedure Set_m_vertices(_idx: Integer; aNewValue: b2Vec2); cdecl;
function Get_m_vertices_P(_idx: Integer): Pb2Vec2; cdecl;
function Get_m_normals(_idx: Integer): b2Vec2; cdecl;
procedure Set_m_normals(_idx: Integer; aNewValue: b2Vec2); cdecl;
function Get_m_normals_P(_idx: Integer): Pb2Vec2; cdecl;
function Get_m_count: Integer; cdecl;
procedure Set_m_count(aNewValue: Integer); cdecl;
public
class function Create: b2PolygonShapeWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2PolygonShapeHandle): b2PolygonShapeWrapper; overload;
class operator Implicit(wrapper: b2PolygonShapeWrapper): b2PolygonShapeHandle; overload;
{ Clone the concrete shape using the provided allocator.}
function Clone(allocator: b2BlockAllocatorHandle): b2ShapeHandle; cdecl;
{ Get the type of this shape. You can use this to down cast to the concrete shape.
@return the shape type.}
function GetType: Integer; cdecl;
{ Get the number of child primitives.}
function GetChildCount: Integer; cdecl;
{ Test a point for containment in this shape. This only works for convex shapes.
@param xf the shape world transform.
@param p a point in world coordinates.}
function TestPoint(const [ref] xf: b2Transform; const [ref] p: b2Vec2): Boolean; cdecl;
{ Cast a ray against a child shape.
@param output the ray-cast results.
@param input the ray-cast input parameters.
@param transform the transform to be applied to the shape.
@param childIndex the child shape index}
function RayCast(output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; const [ref] transform: b2Transform; childIndex: Integer): Boolean; cdecl;
{ Given a transform, compute the associated axis aligned bounding box for a child shape.
@param aabb returns the axis aligned box.
@param xf the world transform of the shape.
@param childIndex the child shape}
procedure ComputeAABB(aabb: Pb2AABB; const [ref] xf: b2Transform; childIndex: Integer); cdecl;
{ Compute the mass properties of this shape using its dimensions and density.
The inertia tensor is computed about the local origin.
@param massData returns the mass data for this shape.
@param density the density in kilograms per meter squared.}
procedure ComputeMass(massData: Pb2MassData; density: Single); cdecl;
property m_type: Integer read Get_m_type write Set_m_type;
property m_radius: Single read Get_m_radius write Set_m_radius;
{ Create a convex hull from the given array of local points.
The count must be in the range [3, b2_maxPolygonVertices].
@warning the points may be re-ordered, even if they form a convex polygon
@warning collinear points are handled but not removed. Collinear points
may lead to poor stacking behavior.}
procedure &Set(points: Pb2Vec2; count: Integer); cdecl;
{ Build vertices to represent an axis-aligned box centered on the local origin.
@param hx the half-width.
@param hy the half-height.}
procedure SetAsBox(hx: Single; hy: Single); overload; cdecl;
{ Build vertices to represent an oriented box.
@param hx the half-width.
@param hy the half-height.
@param center the center of the box in local coordinates.
@param angle the rotation of the box in local coordinates.}
procedure SetAsBox(hx: Single; hy: Single; const [ref] center: b2Vec2; angle: Single); overload; cdecl;
{ Get the vertex count.}
function GetVertexCount: Integer; cdecl;
{ Get a vertex by index.}
function GetVertex(index: Integer): Pb2Vec2; cdecl;
{ Validate convexity. This is a very time consuming operation.
@returns true if valid}
function Validate: Boolean; cdecl;
property m_centroid: b2Vec2 read Get_m_centroid write Set_m_centroid;
property m_centroid_P: Pb2Vec2 read Get_m_centroid_P;
property m_vertices[_idx: Integer]: b2Vec2 read Get_m_vertices write Set_m_vertices;
property m_vertices_P[_idx: Integer]: Pb2Vec2 read Get_m_vertices_P;
property m_normals[_idx: Integer]: b2Vec2 read Get_m_normals write Set_m_normals;
property m_normals_P[_idx: Integer]: Pb2Vec2 read Get_m_normals_P;
property m_count: Integer read Get_m_count write Set_m_count;
end;
procedure b2GetPointStates(state1: Pb2PointState; state2: Pb2PointState; manifold1: Pb2Manifold; manifold2: Pb2Manifold); cdecl;
procedure b2CollideCircles(manifold: Pb2Manifold; circleA: b2CircleShapeHandle; const [ref] xfA: b2Transform; circleB: b2CircleShapeHandle; const [ref] xfB: b2Transform); cdecl;
procedure b2CollidePolygonAndCircle(manifold: Pb2Manifold; polygonA: b2PolygonShapeHandle; const [ref] xfA: b2Transform; circleB: b2CircleShapeHandle; const [ref] xfB: b2Transform); cdecl;
procedure b2CollidePolygons(manifold: Pb2Manifold; polygonA: b2PolygonShapeHandle; const [ref] xfA: b2Transform; polygonB: b2PolygonShapeHandle; const [ref] xfB: b2Transform); cdecl;
procedure b2CollideEdgeAndCircle(manifold: Pb2Manifold; polygonA: b2EdgeShapeHandle; const [ref] xfA: b2Transform; circleB: b2CircleShapeHandle; const [ref] xfB: b2Transform); cdecl;
procedure b2CollideEdgeAndPolygon(manifold: Pb2Manifold; edgeA: b2EdgeShapeHandle; const [ref] xfA: b2Transform; circleB: b2PolygonShapeHandle; const [ref] xfB: b2Transform); cdecl;
function b2ClipSegmentToLine(vOut: Pb2ClipVertex; vIn: Pb2ClipVertex; const [ref] normal: b2Vec2; offset: Single; vertexIndexA: Integer): Integer; cdecl;
function b2TestOverlap(shapeA: b2ShapeHandle; indexA: Integer; shapeB: b2ShapeHandle; indexB: Integer; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform): Boolean; overload; cdecl;
function b2TestOverlap(const [ref] a: b2AABB; const [ref] b: b2AABB): Boolean; overload; cdecl;
function b2PairLessThan(const [ref] pair1: b2Pair; const [ref] pair2: b2Pair): Boolean; cdecl;
procedure b2Distance(output: Pb2DistanceOutput; cache: Pb2SimplexCache; input: Pb2DistanceInput); cdecl;
procedure b2TimeOfImpact(output: Pb2TOIOutput; input: Pb2TOIInput); cdecl;
implementation
const
{$IFDEF MSWINDOWS}
LIB_NAME = 'FlatBox2DDyn.dll';
{$IFDEF WIN64}
_PU = '';
{$ELSE}
_PU = '_';
{$ENDIF}
{$ENDIF}
{$IFDEF ANDROID}
LIB_NAME = 'libFlatBox2D.a';
_PU = '';
{$ENDIF}
{$IFDEF MACOS}
{$IFDEF IOS}
LIB_NAME = 'libFlatBox2D.a';
{$ELSE}
LIB_NAME = 'libFlatBox2DDyn.dylib';
{$ENDIF}
{$IFDEF UNDERSCOREIMPORTNAME}
_PU = '_';
{$ELSE}
_PU = '';
{$ENDIF}
{$ENDIF}
{ ===== Record methods: import and definition ===== }
function b2ContactFeature_Create: b2ContactFeature; cdecl; external LIB_NAME name _PU + 'b2ContactFeature_b2ContactFeature'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ContactFeature.Create: b2ContactFeature; cdecl;
begin
Result := b2ContactFeature_Create;
end;
function b2ContactID_Create: b2ContactID; cdecl; external LIB_NAME name _PU + 'b2ContactID_b2ContactID'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ContactID.Create: b2ContactID; cdecl;
begin
Result := b2ContactID_Create;
end;
function b2ManifoldPoint_Create: b2ManifoldPoint; cdecl; external LIB_NAME name _PU + 'b2ManifoldPoint_b2ManifoldPoint'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ManifoldPoint.Create: b2ManifoldPoint; cdecl;
begin
Result := b2ManifoldPoint_Create;
end;
function b2Manifold_Create: b2Manifold; cdecl; external LIB_NAME name _PU + 'b2Manifold_b2Manifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2Manifold.Create: b2Manifold; cdecl;
begin
Result := b2Manifold_Create;
end;
function b2WorldManifold_Create: b2WorldManifold; cdecl; external LIB_NAME name _PU + 'b2WorldManifold_b2WorldManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2WorldManifold.Create: b2WorldManifold; cdecl;
begin
Result := b2WorldManifold_Create;
end;
procedure b2WorldManifold_Initialize(_self: Pb2WorldManifold; manifold: Pb2Manifold; const [ref] xfA: b2Transform; radiusA: Single; const [ref] xfB: b2Transform; radiusB: Single); cdecl; external LIB_NAME name _PU + 'b2WorldManifold_Initialize'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldManifold.Initialize(manifold: Pb2Manifold; const [ref] xfA: b2Transform; radiusA: Single; const [ref] xfB: b2Transform; radiusB: Single); cdecl;
begin
b2WorldManifold_Initialize(@Self, manifold, xfA, radiusA, xfB, radiusB)
end;
function b2ClipVertex_Create: b2ClipVertex; cdecl; external LIB_NAME name _PU + 'b2ClipVertex_b2ClipVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ClipVertex.Create: b2ClipVertex; cdecl;
begin
Result := b2ClipVertex_Create;
end;
function b2RayCastInput_Create: b2RayCastInput; cdecl; external LIB_NAME name _PU + 'b2RayCastInput_b2RayCastInput_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2RayCastInput.Create: b2RayCastInput; cdecl;
begin
Result := b2RayCastInput_Create;
end;
function b2RayCastOutput_Create: b2RayCastOutput; cdecl; external LIB_NAME name _PU + 'b2RayCastOutput_b2RayCastOutput'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2RayCastOutput.Create: b2RayCastOutput; cdecl;
begin
Result := b2RayCastOutput_Create;
end;
function b2AABB_Create: b2AABB; cdecl; external LIB_NAME name _PU + 'b2AABB_b2AABB_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2AABB.Create: b2AABB; cdecl;
begin
Result := b2AABB_Create;
end;
function b2AABB_IsValid(_self: Pb2AABB): Boolean; cdecl; external LIB_NAME name _PU + 'b2AABB_IsValid'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2AABB.IsValid: Boolean; cdecl;
begin
Result := b2AABB_IsValid(@Self)
end;
function b2AABB_GetCenter(_self: Pb2AABB): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2AABB_GetCenter'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2AABB.GetCenter: b2Vec2; cdecl;
begin
Result := b2AABB_GetCenter(@Self)
end;
function b2AABB_GetExtents(_self: Pb2AABB): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2AABB_GetExtents'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2AABB.GetExtents: b2Vec2; cdecl;
begin
Result := b2AABB_GetExtents(@Self)
end;
function b2AABB_GetPerimeter(_self: Pb2AABB): Single; cdecl; external LIB_NAME name _PU + 'b2AABB_GetPerimeter'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2AABB.GetPerimeter: Single; cdecl;
begin
Result := b2AABB_GetPerimeter(@Self)
end;
procedure b2AABB_Combine(_self: Pb2AABB; const [ref] aabb: b2AABB); overload; cdecl; external LIB_NAME name _PU + 'b2AABB_Combine'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2AABB.Combine(const [ref] aabb: b2AABB); cdecl;
begin
b2AABB_Combine(@Self, aabb)
end;
procedure b2AABB_Combine(_self: Pb2AABB; const [ref] aabb1: b2AABB; const [ref] aabb2: b2AABB); overload; cdecl; external LIB_NAME name _PU + 'b2AABB_Combine2'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2AABB.Combine(const [ref] aabb1: b2AABB; const [ref] aabb2: b2AABB); cdecl;
begin
b2AABB_Combine(@Self, aabb1, aabb2)
end;
function b2AABB_Contains(_self: Pb2AABB; const [ref] aabb: b2AABB): Boolean; cdecl; external LIB_NAME name _PU + 'b2AABB_Contains'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2AABB.Contains(const [ref] aabb: b2AABB): Boolean; cdecl;
begin
Result := b2AABB_Contains(@Self, aabb)
end;
function b2AABB_RayCast(_self: Pb2AABB; output: Pb2RayCastOutput; const [ref] input: b2RayCastInput): Boolean; cdecl; external LIB_NAME name _PU + 'b2AABB_RayCast'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2AABB.RayCast(output: Pb2RayCastOutput; const [ref] input: b2RayCastInput): Boolean; cdecl;
begin
Result := b2AABB_RayCast(@Self, output, input)
end;
function b2TreeNode_Create: b2TreeNode; cdecl; external LIB_NAME name _PU + 'b2TreeNode_b2TreeNode'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2TreeNode.Create: b2TreeNode; cdecl;
begin
Result := b2TreeNode_Create;
end;
function b2TreeNode_IsLeaf(_self: Pb2TreeNode): Boolean; cdecl; external LIB_NAME name _PU + 'b2TreeNode_IsLeaf'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2TreeNode.IsLeaf: Boolean; cdecl;
begin
Result := b2TreeNode_IsLeaf(@Self)
end;
function b2DynamicTree_Create: b2DynamicTreeHandle; cdecl; external LIB_NAME name _PU + 'b2DynamicTree_b2DynamicTree_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2DynamicTreeWrapper.Create: b2DynamicTreeWrapper; cdecl;
begin
Result.FHandle := b2DynamicTree_Create;
end;
procedure b2DynamicTree_Destroy(_self: b2DynamicTreeHandle); cdecl; external LIB_NAME name _PU + 'b2DynamicTree_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DynamicTreeWrapper.Destroy; cdecl;
begin
b2DynamicTree_Destroy(FHandle);
end;
class operator b2DynamicTreeWrapper.Implicit(handle: b2DynamicTreeHandle): b2DynamicTreeWrapper;
begin
Result.FHandle := handle;
end;
class operator b2DynamicTreeWrapper.Implicit(wrapper: b2DynamicTreeWrapper): b2DynamicTreeHandle;
begin
Result := wrapper.FHandle;
end;
function b2DynamicTree_CreateProxy(_self: b2DynamicTreeHandle; const [ref] aabb: b2AABB; userData: Pointer): Integer; cdecl; external LIB_NAME name _PU + 'b2DynamicTree_CreateProxy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DynamicTreeWrapper.CreateProxy(const [ref] aabb: b2AABB; userData: Pointer): Integer; cdecl;
begin
Result := b2DynamicTree_CreateProxy(FHandle, aabb, userData)
end;
procedure b2DynamicTree_DestroyProxy(_self: b2DynamicTreeHandle; proxyId: Integer); cdecl; external LIB_NAME name _PU + 'b2DynamicTree_DestroyProxy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DynamicTreeWrapper.DestroyProxy(proxyId: Integer); cdecl;
begin
b2DynamicTree_DestroyProxy(FHandle, proxyId)
end;
function b2DynamicTree_MoveProxy(_self: b2DynamicTreeHandle; proxyId: Integer; const [ref] aabb1: b2AABB; const [ref] displacement: b2Vec2): Boolean; cdecl; external LIB_NAME name _PU + 'b2DynamicTree_MoveProxy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DynamicTreeWrapper.MoveProxy(proxyId: Integer; const [ref] aabb1: b2AABB; const [ref] displacement: b2Vec2): Boolean; cdecl;
begin
Result := b2DynamicTree_MoveProxy(FHandle, proxyId, aabb1, displacement)
end;
function b2DynamicTree_GetUserData(_self: b2DynamicTreeHandle; proxyId: Integer): Pointer; cdecl; external LIB_NAME name _PU + 'b2DynamicTree_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DynamicTreeWrapper.GetUserData(proxyId: Integer): Pointer; cdecl;
begin
Result := b2DynamicTree_GetUserData(FHandle, proxyId)
end;
function b2DynamicTree_GetFatAABB(_self: b2DynamicTreeHandle; proxyId: Integer): Pb2AABB; cdecl; external LIB_NAME name _PU + 'b2DynamicTree_GetFatAABB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DynamicTreeWrapper.GetFatAABB(proxyId: Integer): Pb2AABB; cdecl;
begin
Result := b2DynamicTree_GetFatAABB(FHandle, proxyId)
end;
procedure b2DynamicTree_Validate(_self: b2DynamicTreeHandle); cdecl; external LIB_NAME name _PU + 'b2DynamicTree_Validate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DynamicTreeWrapper.Validate; cdecl;
begin
b2DynamicTree_Validate(FHandle)
end;
function b2DynamicTree_GetHeight(_self: b2DynamicTreeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2DynamicTree_GetHeight'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DynamicTreeWrapper.GetHeight: Integer; cdecl;
begin
Result := b2DynamicTree_GetHeight(FHandle)
end;
function b2DynamicTree_GetMaxBalance(_self: b2DynamicTreeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2DynamicTree_GetMaxBalance'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DynamicTreeWrapper.GetMaxBalance: Integer; cdecl;
begin
Result := b2DynamicTree_GetMaxBalance(FHandle)
end;
function b2DynamicTree_GetAreaRatio(_self: b2DynamicTreeHandle): Single; cdecl; external LIB_NAME name _PU + 'b2DynamicTree_GetAreaRatio'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DynamicTreeWrapper.GetAreaRatio: Single; cdecl;
begin
Result := b2DynamicTree_GetAreaRatio(FHandle)
end;
procedure b2DynamicTree_RebuildBottomUp(_self: b2DynamicTreeHandle); cdecl; external LIB_NAME name _PU + 'b2DynamicTree_RebuildBottomUp'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DynamicTreeWrapper.RebuildBottomUp; cdecl;
begin
b2DynamicTree_RebuildBottomUp(FHandle)
end;
procedure b2DynamicTree_ShiftOrigin(_self: b2DynamicTreeHandle; const [ref] newOrigin: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2DynamicTree_ShiftOrigin'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DynamicTreeWrapper.ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
begin
b2DynamicTree_ShiftOrigin(FHandle, newOrigin)
end;
function b2Pair_Create: b2Pair; cdecl; external LIB_NAME name _PU + 'b2Pair_b2Pair'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2Pair.Create: b2Pair; cdecl;
begin
Result := b2Pair_Create;
end;
function b2BroadPhase_Create: b2BroadPhaseHandle; cdecl; external LIB_NAME name _PU + 'b2BroadPhase_b2BroadPhase_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2BroadPhaseWrapper.Create: b2BroadPhaseWrapper; cdecl;
begin
Result.FHandle := b2BroadPhase_Create;
end;
procedure b2BroadPhase_Destroy(_self: b2BroadPhaseHandle); cdecl; external LIB_NAME name _PU + 'b2BroadPhase_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BroadPhaseWrapper.Destroy; cdecl;
begin
b2BroadPhase_Destroy(FHandle);
end;
class operator b2BroadPhaseWrapper.Implicit(handle: b2BroadPhaseHandle): b2BroadPhaseWrapper;
begin
Result.FHandle := handle;
end;
class operator b2BroadPhaseWrapper.Implicit(wrapper: b2BroadPhaseWrapper): b2BroadPhaseHandle;
begin
Result := wrapper.FHandle;
end;
function b2BroadPhase_CreateProxy(_self: b2BroadPhaseHandle; const [ref] aabb: b2AABB; userData: Pointer): Integer; cdecl; external LIB_NAME name _PU + 'b2BroadPhase_CreateProxy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BroadPhaseWrapper.CreateProxy(const [ref] aabb: b2AABB; userData: Pointer): Integer; cdecl;
begin
Result := b2BroadPhase_CreateProxy(FHandle, aabb, userData)
end;
procedure b2BroadPhase_DestroyProxy(_self: b2BroadPhaseHandle; proxyId: Integer); cdecl; external LIB_NAME name _PU + 'b2BroadPhase_DestroyProxy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BroadPhaseWrapper.DestroyProxy(proxyId: Integer); cdecl;
begin
b2BroadPhase_DestroyProxy(FHandle, proxyId)
end;
procedure b2BroadPhase_MoveProxy(_self: b2BroadPhaseHandle; proxyId: Integer; const [ref] aabb: b2AABB; const [ref] displacement: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2BroadPhase_MoveProxy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BroadPhaseWrapper.MoveProxy(proxyId: Integer; const [ref] aabb: b2AABB; const [ref] displacement: b2Vec2); cdecl;
begin
b2BroadPhase_MoveProxy(FHandle, proxyId, aabb, displacement)
end;
procedure b2BroadPhase_TouchProxy(_self: b2BroadPhaseHandle; proxyId: Integer); cdecl; external LIB_NAME name _PU + 'b2BroadPhase_TouchProxy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BroadPhaseWrapper.TouchProxy(proxyId: Integer); cdecl;
begin
b2BroadPhase_TouchProxy(FHandle, proxyId)
end;
function b2BroadPhase_GetFatAABB(_self: b2BroadPhaseHandle; proxyId: Integer): Pb2AABB; cdecl; external LIB_NAME name _PU + 'b2BroadPhase_GetFatAABB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BroadPhaseWrapper.GetFatAABB(proxyId: Integer): Pb2AABB; cdecl;
begin
Result := b2BroadPhase_GetFatAABB(FHandle, proxyId)
end;
function b2BroadPhase_GetUserData(_self: b2BroadPhaseHandle; proxyId: Integer): Pointer; cdecl; external LIB_NAME name _PU + 'b2BroadPhase_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BroadPhaseWrapper.GetUserData(proxyId: Integer): Pointer; cdecl;
begin
Result := b2BroadPhase_GetUserData(FHandle, proxyId)
end;
function b2BroadPhase_TestOverlap(_self: b2BroadPhaseHandle; proxyIdA: Integer; proxyIdB: Integer): Boolean; cdecl; external LIB_NAME name _PU + 'b2BroadPhase_TestOverlap'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BroadPhaseWrapper.TestOverlap(proxyIdA: Integer; proxyIdB: Integer): Boolean; cdecl;
begin
Result := b2BroadPhase_TestOverlap(FHandle, proxyIdA, proxyIdB)
end;
function b2BroadPhase_GetProxyCount(_self: b2BroadPhaseHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2BroadPhase_GetProxyCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BroadPhaseWrapper.GetProxyCount: Integer; cdecl;
begin
Result := b2BroadPhase_GetProxyCount(FHandle)
end;
function b2BroadPhase_GetTreeHeight(_self: b2BroadPhaseHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2BroadPhase_GetTreeHeight'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BroadPhaseWrapper.GetTreeHeight: Integer; cdecl;
begin
Result := b2BroadPhase_GetTreeHeight(FHandle)
end;
function b2BroadPhase_GetTreeBalance(_self: b2BroadPhaseHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2BroadPhase_GetTreeBalance'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BroadPhaseWrapper.GetTreeBalance: Integer; cdecl;
begin
Result := b2BroadPhase_GetTreeBalance(FHandle)
end;
function b2BroadPhase_GetTreeQuality(_self: b2BroadPhaseHandle): Single; cdecl; external LIB_NAME name _PU + 'b2BroadPhase_GetTreeQuality'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BroadPhaseWrapper.GetTreeQuality: Single; cdecl;
begin
Result := b2BroadPhase_GetTreeQuality(FHandle)
end;
procedure b2BroadPhase_ShiftOrigin(_self: b2BroadPhaseHandle; const [ref] newOrigin: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2BroadPhase_ShiftOrigin'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BroadPhaseWrapper.ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
begin
b2BroadPhase_ShiftOrigin(FHandle, newOrigin)
end;
function b2DistanceProxy_Create: b2DistanceProxy; cdecl; external LIB_NAME name _PU + 'b2DistanceProxy_b2DistanceProxy_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2DistanceProxy.Create: b2DistanceProxy; cdecl;
begin
Result := b2DistanceProxy_Create;
end;
procedure b2DistanceProxy__Set(_self: Pb2DistanceProxy; shape: b2ShapeHandle; index: Integer); cdecl; external LIB_NAME name _PU + 'b2DistanceProxy_Set'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DistanceProxy.&Set(shape: b2ShapeHandle; index: Integer); cdecl;
begin
b2DistanceProxy__Set(@Self, shape, index)
end;
function b2DistanceProxy_GetSupport(_self: Pb2DistanceProxy; const [ref] d: b2Vec2): Integer; cdecl; external LIB_NAME name _PU + 'b2DistanceProxy_GetSupport'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceProxy.GetSupport(const [ref] d: b2Vec2): Integer; cdecl;
begin
Result := b2DistanceProxy_GetSupport(@Self, d)
end;
function b2DistanceProxy_GetSupportVertex(_self: Pb2DistanceProxy; const [ref] d: b2Vec2): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2DistanceProxy_GetSupportVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceProxy.GetSupportVertex(const [ref] d: b2Vec2): Pb2Vec2; cdecl;
begin
Result := b2DistanceProxy_GetSupportVertex(@Self, d)
end;
function b2DistanceProxy_GetVertexCount(_self: Pb2DistanceProxy): Integer; cdecl; external LIB_NAME name _PU + 'b2DistanceProxy_GetVertexCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceProxy.GetVertexCount: Integer; cdecl;
begin
Result := b2DistanceProxy_GetVertexCount(@Self)
end;
function b2DistanceProxy_GetVertex(_self: Pb2DistanceProxy; index: Integer): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2DistanceProxy_GetVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceProxy.GetVertex(index: Integer): Pb2Vec2; cdecl;
begin
Result := b2DistanceProxy_GetVertex(@Self, index)
end;
function b2SimplexCache_Create: b2SimplexCache; cdecl; external LIB_NAME name _PU + 'b2SimplexCache_b2SimplexCache'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2SimplexCache.Create: b2SimplexCache; cdecl;
begin
Result := b2SimplexCache_Create;
end;
function b2DistanceInput_Create: b2DistanceInput; cdecl; external LIB_NAME name _PU + 'b2DistanceInput_b2DistanceInput'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2DistanceInput.Create: b2DistanceInput; cdecl;
begin
Result := b2DistanceInput_Create;
end;
function b2DistanceOutput_Create: b2DistanceOutput; cdecl; external LIB_NAME name _PU + 'b2DistanceOutput_b2DistanceOutput'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2DistanceOutput.Create: b2DistanceOutput; cdecl;
begin
Result := b2DistanceOutput_Create;
end;
function b2TOIInput_Create: b2TOIInput; cdecl; external LIB_NAME name _PU + 'b2TOIInput_b2TOIInput'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2TOIInput.Create: b2TOIInput; cdecl;
begin
Result := b2TOIInput_Create;
end;
function b2TOIOutput_Create: b2TOIOutput; cdecl; external LIB_NAME name _PU + 'b2TOIOutput_b2TOIOutput'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2TOIOutput.Create: b2TOIOutput; cdecl;
begin
Result := b2TOIOutput_Create;
end;
function b2MassData_Create: b2MassData; cdecl; external LIB_NAME name _PU + 'b2MassData_b2MassData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2MassData.Create: b2MassData; cdecl;
begin
Result := b2MassData_Create;
end;
class operator b2ShapeWrapper.Implicit(handle: b2ShapeHandle): b2ShapeWrapper;
begin
Result.FHandle := handle;
end;
class operator b2ShapeWrapper.Implicit(wrapper: b2ShapeWrapper): b2ShapeHandle;
begin
Result := wrapper.FHandle;
end;
function b2Shape_Clone(_self: b2ShapeHandle; allocator: b2BlockAllocatorHandle): b2ShapeHandle; cdecl; external LIB_NAME name _PU + 'b2Shape_Clone'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ShapeWrapper.Clone(allocator: b2BlockAllocatorHandle): b2ShapeHandle; cdecl;
begin
Result := b2Shape_Clone(FHandle, allocator)
end;
function b2Shape_GetType(_self: b2ShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2Shape_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ShapeWrapper.GetType: Integer; cdecl;
begin
Result := b2Shape_GetType(FHandle)
end;
function b2Shape_GetChildCount(_self: b2ShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2Shape_GetChildCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ShapeWrapper.GetChildCount: Integer; cdecl;
begin
Result := b2Shape_GetChildCount(FHandle)
end;
function b2Shape_TestPoint(_self: b2ShapeHandle; const [ref] xf: b2Transform; const [ref] p: b2Vec2): Boolean; cdecl; external LIB_NAME name _PU + 'b2Shape_TestPoint'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ShapeWrapper.TestPoint(const [ref] xf: b2Transform; const [ref] p: b2Vec2): Boolean; cdecl;
begin
Result := b2Shape_TestPoint(FHandle, xf, p)
end;
function b2Shape_RayCast(_self: b2ShapeHandle; output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; const [ref] transform: b2Transform; childIndex: Integer): Boolean; cdecl; external LIB_NAME name _PU + 'b2Shape_RayCast'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ShapeWrapper.RayCast(output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; const [ref] transform: b2Transform; childIndex: Integer): Boolean; cdecl;
begin
Result := b2Shape_RayCast(FHandle, output, input, transform, childIndex)
end;
procedure b2Shape_ComputeAABB(_self: b2ShapeHandle; aabb: Pb2AABB; const [ref] xf: b2Transform; childIndex: Integer); cdecl; external LIB_NAME name _PU + 'b2Shape_ComputeAABB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ShapeWrapper.ComputeAABB(aabb: Pb2AABB; const [ref] xf: b2Transform; childIndex: Integer); cdecl;
begin
b2Shape_ComputeAABB(FHandle, aabb, xf, childIndex)
end;
procedure b2Shape_ComputeMass(_self: b2ShapeHandle; massData: Pb2MassData; density: Single); cdecl; external LIB_NAME name _PU + 'b2Shape_ComputeMass'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ShapeWrapper.ComputeMass(massData: Pb2MassData; density: Single); cdecl;
begin
b2Shape_ComputeMass(FHandle, massData, density)
end;
function b2Shape_Get_m_type(_self: b2ShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2Shape_Get_m_type'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Shape_Set_m_type(_self: b2ShapeHandle; aNewValue: Integer); cdecl; external LIB_NAME name _PU + 'b2Shape_Set_m_type'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ShapeWrapper.Get_m_type: Integer; cdecl;
begin
Result := b2Shape_Get_m_type(FHandle);
end;
procedure b2ShapeWrapper.Set_m_type(aNewValue: Integer); cdecl;
begin
b2Shape_Set_m_type(FHandle, aNewValue);
end;
function b2Shape_Get_m_radius(_self: b2ShapeHandle): Single; cdecl; external LIB_NAME name _PU + 'b2Shape_Get_m_radius'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Shape_Set_m_radius(_self: b2ShapeHandle; aNewValue: Single); cdecl; external LIB_NAME name _PU + 'b2Shape_Set_m_radius'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ShapeWrapper.Get_m_radius: Single; cdecl;
begin
Result := b2Shape_Get_m_radius(FHandle);
end;
procedure b2ShapeWrapper.Set_m_radius(aNewValue: Single); cdecl;
begin
b2Shape_Set_m_radius(FHandle, aNewValue);
end;
function b2ChainShape_Create: b2ChainShapeHandle; cdecl; external LIB_NAME name _PU + 'b2ChainShape_b2ChainShape_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ChainShapeWrapper.Create: b2ChainShapeWrapper; cdecl;
begin
Result.FHandle := b2ChainShape_Create;
end;
procedure b2ChainShape_Destroy(_self: b2ChainShapeHandle); cdecl; external LIB_NAME name _PU + 'b2ChainShape_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShapeWrapper.Destroy; cdecl;
begin
b2ChainShape_Destroy(FHandle);
end;
class operator b2ChainShapeWrapper.Implicit(handle: b2ChainShapeHandle): b2ChainShapeWrapper;
begin
Result.FHandle := handle;
end;
class operator b2ChainShapeWrapper.Implicit(wrapper: b2ChainShapeWrapper): b2ChainShapeHandle;
begin
Result := wrapper.FHandle;
end;
function b2ChainShape_Clone(_self: b2ChainShapeHandle; allocator: b2BlockAllocatorHandle): b2ShapeHandle; cdecl; external LIB_NAME name _PU + 'b2ChainShape_Clone'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainShapeWrapper.Clone(allocator: b2BlockAllocatorHandle): b2ShapeHandle; cdecl;
begin
Result := b2ChainShape_Clone(FHandle, allocator)
end;
function b2ChainShape_GetType(_self: b2ChainShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2ChainShape_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainShapeWrapper.GetType: Integer; cdecl;
begin
Result := b2ChainShape_GetType(FHandle)
end;
function b2ChainShape_GetChildCount(_self: b2ChainShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2ChainShape_GetChildCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainShapeWrapper.GetChildCount: Integer; cdecl;
begin
Result := b2ChainShape_GetChildCount(FHandle)
end;
function b2ChainShape_TestPoint(_self: b2ChainShapeHandle; const [ref] xf: b2Transform; const [ref] p: b2Vec2): Boolean; cdecl; external LIB_NAME name _PU + 'b2ChainShape_TestPoint'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainShapeWrapper.TestPoint(const [ref] xf: b2Transform; const [ref] p: b2Vec2): Boolean; cdecl;
begin
Result := b2ChainShape_TestPoint(FHandle, xf, p)
end;
function b2ChainShape_RayCast(_self: b2ChainShapeHandle; output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; const [ref] transform: b2Transform; childIndex: Integer): Boolean; cdecl; external LIB_NAME name _PU + 'b2ChainShape_RayCast'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainShapeWrapper.RayCast(output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; const [ref] transform: b2Transform; childIndex: Integer): Boolean; cdecl;
begin
Result := b2ChainShape_RayCast(FHandle, output, input, transform, childIndex)
end;
procedure b2ChainShape_ComputeAABB(_self: b2ChainShapeHandle; aabb: Pb2AABB; const [ref] xf: b2Transform; childIndex: Integer); cdecl; external LIB_NAME name _PU + 'b2ChainShape_ComputeAABB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShapeWrapper.ComputeAABB(aabb: Pb2AABB; const [ref] xf: b2Transform; childIndex: Integer); cdecl;
begin
b2ChainShape_ComputeAABB(FHandle, aabb, xf, childIndex)
end;
procedure b2ChainShape_ComputeMass(_self: b2ChainShapeHandle; massData: Pb2MassData; density: Single); cdecl; external LIB_NAME name _PU + 'b2ChainShape_ComputeMass'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShapeWrapper.ComputeMass(massData: Pb2MassData; density: Single); cdecl;
begin
b2ChainShape_ComputeMass(FHandle, massData, density)
end;
function b2ChainShape_Get_m_type(_self: b2ChainShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2ChainShape_Get_m_type'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShape_Set_m_type(_self: b2ChainShapeHandle; aNewValue: Integer); cdecl; external LIB_NAME name _PU + 'b2ChainShape_Set_m_type'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainShapeWrapper.Get_m_type: Integer; cdecl;
begin
Result := b2ChainShape_Get_m_type(FHandle);
end;
procedure b2ChainShapeWrapper.Set_m_type(aNewValue: Integer); cdecl;
begin
b2ChainShape_Set_m_type(FHandle, aNewValue);
end;
function b2ChainShape_Get_m_radius(_self: b2ChainShapeHandle): Single; cdecl; external LIB_NAME name _PU + 'b2ChainShape_Get_m_radius'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShape_Set_m_radius(_self: b2ChainShapeHandle; aNewValue: Single); cdecl; external LIB_NAME name _PU + 'b2ChainShape_Set_m_radius'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainShapeWrapper.Get_m_radius: Single; cdecl;
begin
Result := b2ChainShape_Get_m_radius(FHandle);
end;
procedure b2ChainShapeWrapper.Set_m_radius(aNewValue: Single); cdecl;
begin
b2ChainShape_Set_m_radius(FHandle, aNewValue);
end;
procedure b2ChainShape_Clear(_self: b2ChainShapeHandle); cdecl; external LIB_NAME name _PU + 'b2ChainShape_Clear'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShapeWrapper.Clear; cdecl;
begin
b2ChainShape_Clear(FHandle)
end;
procedure b2ChainShape_CreateLoop(_self: b2ChainShapeHandle; vertices: Pb2Vec2; count: Integer); cdecl; external LIB_NAME name _PU + 'b2ChainShape_CreateLoop'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShapeWrapper.CreateLoop(vertices: Pb2Vec2; count: Integer); cdecl;
begin
b2ChainShape_CreateLoop(FHandle, vertices, count)
end;
procedure b2ChainShape_CreateChain(_self: b2ChainShapeHandle; vertices: Pb2Vec2; count: Integer); cdecl; external LIB_NAME name _PU + 'b2ChainShape_CreateChain'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShapeWrapper.CreateChain(vertices: Pb2Vec2; count: Integer); cdecl;
begin
b2ChainShape_CreateChain(FHandle, vertices, count)
end;
procedure b2ChainShape_SetPrevVertex(_self: b2ChainShapeHandle; const [ref] prevVertex: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2ChainShape_SetPrevVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShapeWrapper.SetPrevVertex(const [ref] prevVertex: b2Vec2); cdecl;
begin
b2ChainShape_SetPrevVertex(FHandle, prevVertex)
end;
procedure b2ChainShape_SetNextVertex(_self: b2ChainShapeHandle; const [ref] nextVertex: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2ChainShape_SetNextVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShapeWrapper.SetNextVertex(const [ref] nextVertex: b2Vec2); cdecl;
begin
b2ChainShape_SetNextVertex(FHandle, nextVertex)
end;
procedure b2ChainShape_GetChildEdge(_self: b2ChainShapeHandle; edge: b2EdgeShapeHandle; index: Integer); cdecl; external LIB_NAME name _PU + 'b2ChainShape_GetChildEdge'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShapeWrapper.GetChildEdge(edge: b2EdgeShapeHandle; index: Integer); cdecl;
begin
b2ChainShape_GetChildEdge(FHandle, edge, index)
end;
function b2ChainShape_Get_m_vertices(_self: b2ChainShapeHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2ChainShape_Get_m_vertices'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShape_Set_m_vertices(_self: b2ChainShapeHandle; aNewValue: Pb2Vec2); cdecl; external LIB_NAME name _PU + 'b2ChainShape_Set_m_vertices'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainShapeWrapper.Get_m_vertices: Pb2Vec2; cdecl;
begin
Result := b2ChainShape_Get_m_vertices(FHandle);
end;
procedure b2ChainShapeWrapper.Set_m_vertices(aNewValue: Pb2Vec2); cdecl;
begin
b2ChainShape_Set_m_vertices(FHandle, aNewValue);
end;
function b2ChainShape_Get_m_count(_self: b2ChainShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2ChainShape_Get_m_count'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShape_Set_m_count(_self: b2ChainShapeHandle; aNewValue: Integer); cdecl; external LIB_NAME name _PU + 'b2ChainShape_Set_m_count'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainShapeWrapper.Get_m_count: Integer; cdecl;
begin
Result := b2ChainShape_Get_m_count(FHandle);
end;
procedure b2ChainShapeWrapper.Set_m_count(aNewValue: Integer); cdecl;
begin
b2ChainShape_Set_m_count(FHandle, aNewValue);
end;
function b2ChainShape_Get_m_prevVertex(_self: b2ChainShapeHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2ChainShape_Get_m_prevVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShape_Set_m_prevVertex(_self: b2ChainShapeHandle; aNewValue: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2ChainShape_Set_m_prevVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainShape_Get_m_prevVertex_P(_self: b2ChainShapeHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2ChainShape_Get_m_prevVertex_P'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainShapeWrapper.Get_m_prevVertex: b2Vec2; cdecl;
begin
Result := b2ChainShape_Get_m_prevVertex(FHandle);
end;
procedure b2ChainShapeWrapper.Set_m_prevVertex(aNewValue: b2Vec2); cdecl;
begin
b2ChainShape_Set_m_prevVertex(FHandle, aNewValue);
end;
function b2ChainShapeWrapper.Get_m_prevVertex_P: Pb2Vec2; cdecl;
begin
Result := b2ChainShape_Get_m_prevVertex_P(FHandle);
end;
function b2ChainShape_Get_m_nextVertex(_self: b2ChainShapeHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2ChainShape_Get_m_nextVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShape_Set_m_nextVertex(_self: b2ChainShapeHandle; aNewValue: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2ChainShape_Set_m_nextVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainShape_Get_m_nextVertex_P(_self: b2ChainShapeHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2ChainShape_Get_m_nextVertex_P'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainShapeWrapper.Get_m_nextVertex: b2Vec2; cdecl;
begin
Result := b2ChainShape_Get_m_nextVertex(FHandle);
end;
procedure b2ChainShapeWrapper.Set_m_nextVertex(aNewValue: b2Vec2); cdecl;
begin
b2ChainShape_Set_m_nextVertex(FHandle, aNewValue);
end;
function b2ChainShapeWrapper.Get_m_nextVertex_P: Pb2Vec2; cdecl;
begin
Result := b2ChainShape_Get_m_nextVertex_P(FHandle);
end;
function b2ChainShape_Get_m_hasPrevVertex(_self: b2ChainShapeHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2ChainShape_Get_m_hasPrevVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShape_Set_m_hasPrevVertex(_self: b2ChainShapeHandle; aNewValue: Boolean); cdecl; external LIB_NAME name _PU + 'b2ChainShape_Set_m_hasPrevVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainShapeWrapper.Get_m_hasPrevVertex: Boolean; cdecl;
begin
Result := b2ChainShape_Get_m_hasPrevVertex(FHandle);
end;
procedure b2ChainShapeWrapper.Set_m_hasPrevVertex(aNewValue: Boolean); cdecl;
begin
b2ChainShape_Set_m_hasPrevVertex(FHandle, aNewValue);
end;
function b2ChainShape_Get_m_hasNextVertex(_self: b2ChainShapeHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2ChainShape_Get_m_hasNextVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainShape_Set_m_hasNextVertex(_self: b2ChainShapeHandle; aNewValue: Boolean); cdecl; external LIB_NAME name _PU + 'b2ChainShape_Set_m_hasNextVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainShapeWrapper.Get_m_hasNextVertex: Boolean; cdecl;
begin
Result := b2ChainShape_Get_m_hasNextVertex(FHandle);
end;
procedure b2ChainShapeWrapper.Set_m_hasNextVertex(aNewValue: Boolean); cdecl;
begin
b2ChainShape_Set_m_hasNextVertex(FHandle, aNewValue);
end;
function b2CircleShape_Create: b2CircleShapeHandle; cdecl; external LIB_NAME name _PU + 'b2CircleShape_b2CircleShape_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2CircleShapeWrapper.Create: b2CircleShapeWrapper; cdecl;
begin
Result.FHandle := b2CircleShape_Create;
end;
procedure b2CircleShape_Destroy(_self: b2CircleShapeHandle); cdecl; external LIB_NAME name _PU + 'b2CircleShape_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleShapeWrapper.Destroy; cdecl;
begin
b2CircleShape_Destroy(FHandle);
end;
class operator b2CircleShapeWrapper.Implicit(handle: b2CircleShapeHandle): b2CircleShapeWrapper;
begin
Result.FHandle := handle;
end;
class operator b2CircleShapeWrapper.Implicit(wrapper: b2CircleShapeWrapper): b2CircleShapeHandle;
begin
Result := wrapper.FHandle;
end;
function b2CircleShape_Clone(_self: b2CircleShapeHandle; allocator: b2BlockAllocatorHandle): b2ShapeHandle; cdecl; external LIB_NAME name _PU + 'b2CircleShape_Clone'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleShapeWrapper.Clone(allocator: b2BlockAllocatorHandle): b2ShapeHandle; cdecl;
begin
Result := b2CircleShape_Clone(FHandle, allocator)
end;
function b2CircleShape_GetType(_self: b2CircleShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2CircleShape_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleShapeWrapper.GetType: Integer; cdecl;
begin
Result := b2CircleShape_GetType(FHandle)
end;
function b2CircleShape_GetChildCount(_self: b2CircleShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2CircleShape_GetChildCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleShapeWrapper.GetChildCount: Integer; cdecl;
begin
Result := b2CircleShape_GetChildCount(FHandle)
end;
function b2CircleShape_TestPoint(_self: b2CircleShapeHandle; const [ref] xf: b2Transform; const [ref] p: b2Vec2): Boolean; cdecl; external LIB_NAME name _PU + 'b2CircleShape_TestPoint'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleShapeWrapper.TestPoint(const [ref] xf: b2Transform; const [ref] p: b2Vec2): Boolean; cdecl;
begin
Result := b2CircleShape_TestPoint(FHandle, xf, p)
end;
function b2CircleShape_RayCast(_self: b2CircleShapeHandle; output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; const [ref] transform: b2Transform; childIndex: Integer): Boolean; cdecl; external LIB_NAME name _PU + 'b2CircleShape_RayCast'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleShapeWrapper.RayCast(output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; const [ref] transform: b2Transform; childIndex: Integer): Boolean; cdecl;
begin
Result := b2CircleShape_RayCast(FHandle, output, input, transform, childIndex)
end;
procedure b2CircleShape_ComputeAABB(_self: b2CircleShapeHandle; aabb: Pb2AABB; const [ref] xf: b2Transform; childIndex: Integer); cdecl; external LIB_NAME name _PU + 'b2CircleShape_ComputeAABB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleShapeWrapper.ComputeAABB(aabb: Pb2AABB; const [ref] xf: b2Transform; childIndex: Integer); cdecl;
begin
b2CircleShape_ComputeAABB(FHandle, aabb, xf, childIndex)
end;
procedure b2CircleShape_ComputeMass(_self: b2CircleShapeHandle; massData: Pb2MassData; density: Single); cdecl; external LIB_NAME name _PU + 'b2CircleShape_ComputeMass'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleShapeWrapper.ComputeMass(massData: Pb2MassData; density: Single); cdecl;
begin
b2CircleShape_ComputeMass(FHandle, massData, density)
end;
function b2CircleShape_Get_m_type(_self: b2CircleShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2CircleShape_Get_m_type'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleShape_Set_m_type(_self: b2CircleShapeHandle; aNewValue: Integer); cdecl; external LIB_NAME name _PU + 'b2CircleShape_Set_m_type'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleShapeWrapper.Get_m_type: Integer; cdecl;
begin
Result := b2CircleShape_Get_m_type(FHandle);
end;
procedure b2CircleShapeWrapper.Set_m_type(aNewValue: Integer); cdecl;
begin
b2CircleShape_Set_m_type(FHandle, aNewValue);
end;
function b2CircleShape_Get_m_radius(_self: b2CircleShapeHandle): Single; cdecl; external LIB_NAME name _PU + 'b2CircleShape_Get_m_radius'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleShape_Set_m_radius(_self: b2CircleShapeHandle; aNewValue: Single); cdecl; external LIB_NAME name _PU + 'b2CircleShape_Set_m_radius'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleShapeWrapper.Get_m_radius: Single; cdecl;
begin
Result := b2CircleShape_Get_m_radius(FHandle);
end;
procedure b2CircleShapeWrapper.Set_m_radius(aNewValue: Single); cdecl;
begin
b2CircleShape_Set_m_radius(FHandle, aNewValue);
end;
function b2CircleShape_GetSupport(_self: b2CircleShapeHandle; const [ref] d: b2Vec2): Integer; cdecl; external LIB_NAME name _PU + 'b2CircleShape_GetSupport'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleShapeWrapper.GetSupport(const [ref] d: b2Vec2): Integer; cdecl;
begin
Result := b2CircleShape_GetSupport(FHandle, d)
end;
function b2CircleShape_GetSupportVertex(_self: b2CircleShapeHandle; const [ref] d: b2Vec2): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2CircleShape_GetSupportVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleShapeWrapper.GetSupportVertex(const [ref] d: b2Vec2): Pb2Vec2; cdecl;
begin
Result := b2CircleShape_GetSupportVertex(FHandle, d)
end;
function b2CircleShape_GetVertexCount(_self: b2CircleShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2CircleShape_GetVertexCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleShapeWrapper.GetVertexCount: Integer; cdecl;
begin
Result := b2CircleShape_GetVertexCount(FHandle)
end;
function b2CircleShape_GetVertex(_self: b2CircleShapeHandle; index: Integer): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2CircleShape_GetVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleShapeWrapper.GetVertex(index: Integer): Pb2Vec2; cdecl;
begin
Result := b2CircleShape_GetVertex(FHandle, index)
end;
function b2CircleShape_Get_m_p(_self: b2CircleShapeHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2CircleShape_Get_m_p'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleShape_Set_m_p(_self: b2CircleShapeHandle; aNewValue: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2CircleShape_Set_m_p'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleShape_Get_m_p_P(_self: b2CircleShapeHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2CircleShape_Get_m_p_P'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleShapeWrapper.Get_m_p: b2Vec2; cdecl;
begin
Result := b2CircleShape_Get_m_p(FHandle);
end;
procedure b2CircleShapeWrapper.Set_m_p(aNewValue: b2Vec2); cdecl;
begin
b2CircleShape_Set_m_p(FHandle, aNewValue);
end;
function b2CircleShapeWrapper.Get_m_p_P: Pb2Vec2; cdecl;
begin
Result := b2CircleShape_Get_m_p_P(FHandle);
end;
function b2EdgeShape_Create: b2EdgeShapeHandle; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_b2EdgeShape_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2EdgeShapeWrapper.Create: b2EdgeShapeWrapper; cdecl;
begin
Result.FHandle := b2EdgeShape_Create;
end;
procedure b2EdgeShape_Destroy(_self: b2EdgeShapeHandle); cdecl; external LIB_NAME name _PU + 'b2EdgeShape_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeShapeWrapper.Destroy; cdecl;
begin
b2EdgeShape_Destroy(FHandle);
end;
class operator b2EdgeShapeWrapper.Implicit(handle: b2EdgeShapeHandle): b2EdgeShapeWrapper;
begin
Result.FHandle := handle;
end;
class operator b2EdgeShapeWrapper.Implicit(wrapper: b2EdgeShapeWrapper): b2EdgeShapeHandle;
begin
Result := wrapper.FHandle;
end;
function b2EdgeShape_Clone(_self: b2EdgeShapeHandle; allocator: b2BlockAllocatorHandle): b2ShapeHandle; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Clone'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShapeWrapper.Clone(allocator: b2BlockAllocatorHandle): b2ShapeHandle; cdecl;
begin
Result := b2EdgeShape_Clone(FHandle, allocator)
end;
function b2EdgeShape_GetType(_self: b2EdgeShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShapeWrapper.GetType: Integer; cdecl;
begin
Result := b2EdgeShape_GetType(FHandle)
end;
function b2EdgeShape_GetChildCount(_self: b2EdgeShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_GetChildCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShapeWrapper.GetChildCount: Integer; cdecl;
begin
Result := b2EdgeShape_GetChildCount(FHandle)
end;
function b2EdgeShape_TestPoint(_self: b2EdgeShapeHandle; const [ref] xf: b2Transform; const [ref] p: b2Vec2): Boolean; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_TestPoint'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShapeWrapper.TestPoint(const [ref] xf: b2Transform; const [ref] p: b2Vec2): Boolean; cdecl;
begin
Result := b2EdgeShape_TestPoint(FHandle, xf, p)
end;
function b2EdgeShape_RayCast(_self: b2EdgeShapeHandle; output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; const [ref] transform: b2Transform; childIndex: Integer): Boolean; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_RayCast'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShapeWrapper.RayCast(output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; const [ref] transform: b2Transform; childIndex: Integer): Boolean; cdecl;
begin
Result := b2EdgeShape_RayCast(FHandle, output, input, transform, childIndex)
end;
procedure b2EdgeShape_ComputeAABB(_self: b2EdgeShapeHandle; aabb: Pb2AABB; const [ref] xf: b2Transform; childIndex: Integer); cdecl; external LIB_NAME name _PU + 'b2EdgeShape_ComputeAABB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeShapeWrapper.ComputeAABB(aabb: Pb2AABB; const [ref] xf: b2Transform; childIndex: Integer); cdecl;
begin
b2EdgeShape_ComputeAABB(FHandle, aabb, xf, childIndex)
end;
procedure b2EdgeShape_ComputeMass(_self: b2EdgeShapeHandle; massData: Pb2MassData; density: Single); cdecl; external LIB_NAME name _PU + 'b2EdgeShape_ComputeMass'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeShapeWrapper.ComputeMass(massData: Pb2MassData; density: Single); cdecl;
begin
b2EdgeShape_ComputeMass(FHandle, massData, density)
end;
function b2EdgeShape_Get_m_type(_self: b2EdgeShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Get_m_type'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeShape_Set_m_type(_self: b2EdgeShapeHandle; aNewValue: Integer); cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Set_m_type'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShapeWrapper.Get_m_type: Integer; cdecl;
begin
Result := b2EdgeShape_Get_m_type(FHandle);
end;
procedure b2EdgeShapeWrapper.Set_m_type(aNewValue: Integer); cdecl;
begin
b2EdgeShape_Set_m_type(FHandle, aNewValue);
end;
function b2EdgeShape_Get_m_radius(_self: b2EdgeShapeHandle): Single; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Get_m_radius'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeShape_Set_m_radius(_self: b2EdgeShapeHandle; aNewValue: Single); cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Set_m_radius'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShapeWrapper.Get_m_radius: Single; cdecl;
begin
Result := b2EdgeShape_Get_m_radius(FHandle);
end;
procedure b2EdgeShapeWrapper.Set_m_radius(aNewValue: Single); cdecl;
begin
b2EdgeShape_Set_m_radius(FHandle, aNewValue);
end;
procedure b2EdgeShape__Set(_self: b2EdgeShapeHandle; const [ref] v1: b2Vec2; const [ref] v2: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Set'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeShapeWrapper.&Set(const [ref] v1: b2Vec2; const [ref] v2: b2Vec2); cdecl;
begin
b2EdgeShape__Set(FHandle, v1, v2)
end;
function b2EdgeShape_Get_m_vertex1(_self: b2EdgeShapeHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Get_m_vertex1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeShape_Set_m_vertex1(_self: b2EdgeShapeHandle; aNewValue: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Set_m_vertex1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShape_Get_m_vertex1_P(_self: b2EdgeShapeHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Get_m_vertex1_P'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShapeWrapper.Get_m_vertex1: b2Vec2; cdecl;
begin
Result := b2EdgeShape_Get_m_vertex1(FHandle);
end;
procedure b2EdgeShapeWrapper.Set_m_vertex1(aNewValue: b2Vec2); cdecl;
begin
b2EdgeShape_Set_m_vertex1(FHandle, aNewValue);
end;
function b2EdgeShapeWrapper.Get_m_vertex1_P: Pb2Vec2; cdecl;
begin
Result := b2EdgeShape_Get_m_vertex1_P(FHandle);
end;
function b2EdgeShape_Get_m_vertex2(_self: b2EdgeShapeHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Get_m_vertex2'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeShape_Set_m_vertex2(_self: b2EdgeShapeHandle; aNewValue: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Set_m_vertex2'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShape_Get_m_vertex2_P(_self: b2EdgeShapeHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Get_m_vertex2_P'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShapeWrapper.Get_m_vertex2: b2Vec2; cdecl;
begin
Result := b2EdgeShape_Get_m_vertex2(FHandle);
end;
procedure b2EdgeShapeWrapper.Set_m_vertex2(aNewValue: b2Vec2); cdecl;
begin
b2EdgeShape_Set_m_vertex2(FHandle, aNewValue);
end;
function b2EdgeShapeWrapper.Get_m_vertex2_P: Pb2Vec2; cdecl;
begin
Result := b2EdgeShape_Get_m_vertex2_P(FHandle);
end;
function b2EdgeShape_Get_m_vertex0(_self: b2EdgeShapeHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Get_m_vertex0'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeShape_Set_m_vertex0(_self: b2EdgeShapeHandle; aNewValue: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Set_m_vertex0'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShape_Get_m_vertex0_P(_self: b2EdgeShapeHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Get_m_vertex0_P'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShapeWrapper.Get_m_vertex0: b2Vec2; cdecl;
begin
Result := b2EdgeShape_Get_m_vertex0(FHandle);
end;
procedure b2EdgeShapeWrapper.Set_m_vertex0(aNewValue: b2Vec2); cdecl;
begin
b2EdgeShape_Set_m_vertex0(FHandle, aNewValue);
end;
function b2EdgeShapeWrapper.Get_m_vertex0_P: Pb2Vec2; cdecl;
begin
Result := b2EdgeShape_Get_m_vertex0_P(FHandle);
end;
function b2EdgeShape_Get_m_vertex3(_self: b2EdgeShapeHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Get_m_vertex3'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeShape_Set_m_vertex3(_self: b2EdgeShapeHandle; aNewValue: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Set_m_vertex3'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShape_Get_m_vertex3_P(_self: b2EdgeShapeHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Get_m_vertex3_P'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShapeWrapper.Get_m_vertex3: b2Vec2; cdecl;
begin
Result := b2EdgeShape_Get_m_vertex3(FHandle);
end;
procedure b2EdgeShapeWrapper.Set_m_vertex3(aNewValue: b2Vec2); cdecl;
begin
b2EdgeShape_Set_m_vertex3(FHandle, aNewValue);
end;
function b2EdgeShapeWrapper.Get_m_vertex3_P: Pb2Vec2; cdecl;
begin
Result := b2EdgeShape_Get_m_vertex3_P(FHandle);
end;
function b2EdgeShape_Get_m_hasVertex0(_self: b2EdgeShapeHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Get_m_hasVertex0'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeShape_Set_m_hasVertex0(_self: b2EdgeShapeHandle; aNewValue: Boolean); cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Set_m_hasVertex0'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShapeWrapper.Get_m_hasVertex0: Boolean; cdecl;
begin
Result := b2EdgeShape_Get_m_hasVertex0(FHandle);
end;
procedure b2EdgeShapeWrapper.Set_m_hasVertex0(aNewValue: Boolean); cdecl;
begin
b2EdgeShape_Set_m_hasVertex0(FHandle, aNewValue);
end;
function b2EdgeShape_Get_m_hasVertex3(_self: b2EdgeShapeHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Get_m_hasVertex3'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeShape_Set_m_hasVertex3(_self: b2EdgeShapeHandle; aNewValue: Boolean); cdecl; external LIB_NAME name _PU + 'b2EdgeShape_Set_m_hasVertex3'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeShapeWrapper.Get_m_hasVertex3: Boolean; cdecl;
begin
Result := b2EdgeShape_Get_m_hasVertex3(FHandle);
end;
procedure b2EdgeShapeWrapper.Set_m_hasVertex3(aNewValue: Boolean); cdecl;
begin
b2EdgeShape_Set_m_hasVertex3(FHandle, aNewValue);
end;
function b2PolygonShape_Create: b2PolygonShapeHandle; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_b2PolygonShape_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2PolygonShapeWrapper.Create: b2PolygonShapeWrapper; cdecl;
begin
Result.FHandle := b2PolygonShape_Create;
end;
procedure b2PolygonShape_Destroy(_self: b2PolygonShapeHandle); cdecl; external LIB_NAME name _PU + 'b2PolygonShape_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonShapeWrapper.Destroy; cdecl;
begin
b2PolygonShape_Destroy(FHandle);
end;
class operator b2PolygonShapeWrapper.Implicit(handle: b2PolygonShapeHandle): b2PolygonShapeWrapper;
begin
Result.FHandle := handle;
end;
class operator b2PolygonShapeWrapper.Implicit(wrapper: b2PolygonShapeWrapper): b2PolygonShapeHandle;
begin
Result := wrapper.FHandle;
end;
function b2PolygonShape_Clone(_self: b2PolygonShapeHandle; allocator: b2BlockAllocatorHandle): b2ShapeHandle; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Clone'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShapeWrapper.Clone(allocator: b2BlockAllocatorHandle): b2ShapeHandle; cdecl;
begin
Result := b2PolygonShape_Clone(FHandle, allocator)
end;
function b2PolygonShape_GetType(_self: b2PolygonShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShapeWrapper.GetType: Integer; cdecl;
begin
Result := b2PolygonShape_GetType(FHandle)
end;
function b2PolygonShape_GetChildCount(_self: b2PolygonShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_GetChildCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShapeWrapper.GetChildCount: Integer; cdecl;
begin
Result := b2PolygonShape_GetChildCount(FHandle)
end;
function b2PolygonShape_TestPoint(_self: b2PolygonShapeHandle; const [ref] xf: b2Transform; const [ref] p: b2Vec2): Boolean; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_TestPoint'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShapeWrapper.TestPoint(const [ref] xf: b2Transform; const [ref] p: b2Vec2): Boolean; cdecl;
begin
Result := b2PolygonShape_TestPoint(FHandle, xf, p)
end;
function b2PolygonShape_RayCast(_self: b2PolygonShapeHandle; output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; const [ref] transform: b2Transform; childIndex: Integer): Boolean; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_RayCast'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShapeWrapper.RayCast(output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; const [ref] transform: b2Transform; childIndex: Integer): Boolean; cdecl;
begin
Result := b2PolygonShape_RayCast(FHandle, output, input, transform, childIndex)
end;
procedure b2PolygonShape_ComputeAABB(_self: b2PolygonShapeHandle; aabb: Pb2AABB; const [ref] xf: b2Transform; childIndex: Integer); cdecl; external LIB_NAME name _PU + 'b2PolygonShape_ComputeAABB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonShapeWrapper.ComputeAABB(aabb: Pb2AABB; const [ref] xf: b2Transform; childIndex: Integer); cdecl;
begin
b2PolygonShape_ComputeAABB(FHandle, aabb, xf, childIndex)
end;
procedure b2PolygonShape_ComputeMass(_self: b2PolygonShapeHandle; massData: Pb2MassData; density: Single); cdecl; external LIB_NAME name _PU + 'b2PolygonShape_ComputeMass'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonShapeWrapper.ComputeMass(massData: Pb2MassData; density: Single); cdecl;
begin
b2PolygonShape_ComputeMass(FHandle, massData, density)
end;
function b2PolygonShape_Get_m_type(_self: b2PolygonShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Get_m_type'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonShape_Set_m_type(_self: b2PolygonShapeHandle; aNewValue: Integer); cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Set_m_type'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShapeWrapper.Get_m_type: Integer; cdecl;
begin
Result := b2PolygonShape_Get_m_type(FHandle);
end;
procedure b2PolygonShapeWrapper.Set_m_type(aNewValue: Integer); cdecl;
begin
b2PolygonShape_Set_m_type(FHandle, aNewValue);
end;
function b2PolygonShape_Get_m_radius(_self: b2PolygonShapeHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Get_m_radius'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonShape_Set_m_radius(_self: b2PolygonShapeHandle; aNewValue: Single); cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Set_m_radius'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShapeWrapper.Get_m_radius: Single; cdecl;
begin
Result := b2PolygonShape_Get_m_radius(FHandle);
end;
procedure b2PolygonShapeWrapper.Set_m_radius(aNewValue: Single); cdecl;
begin
b2PolygonShape_Set_m_radius(FHandle, aNewValue);
end;
procedure b2PolygonShape__Set(_self: b2PolygonShapeHandle; points: Pb2Vec2; count: Integer); cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Set'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonShapeWrapper.&Set(points: Pb2Vec2; count: Integer); cdecl;
begin
b2PolygonShape__Set(FHandle, points, count)
end;
procedure b2PolygonShape_SetAsBox(_self: b2PolygonShapeHandle; hx: Single; hy: Single); overload; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_SetAsBox'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonShapeWrapper.SetAsBox(hx: Single; hy: Single); cdecl;
begin
b2PolygonShape_SetAsBox(FHandle, hx, hy)
end;
procedure b2PolygonShape_SetAsBox(_self: b2PolygonShapeHandle; hx: Single; hy: Single; const [ref] center: b2Vec2; angle: Single); overload; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_SetAsBox2'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonShapeWrapper.SetAsBox(hx: Single; hy: Single; const [ref] center: b2Vec2; angle: Single); cdecl;
begin
b2PolygonShape_SetAsBox(FHandle, hx, hy, center, angle)
end;
function b2PolygonShape_GetVertexCount(_self: b2PolygonShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_GetVertexCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShapeWrapper.GetVertexCount: Integer; cdecl;
begin
Result := b2PolygonShape_GetVertexCount(FHandle)
end;
function b2PolygonShape_GetVertex(_self: b2PolygonShapeHandle; index: Integer): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_GetVertex'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShapeWrapper.GetVertex(index: Integer): Pb2Vec2; cdecl;
begin
Result := b2PolygonShape_GetVertex(FHandle, index)
end;
function b2PolygonShape_Validate(_self: b2PolygonShapeHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Validate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShapeWrapper.Validate: Boolean; cdecl;
begin
Result := b2PolygonShape_Validate(FHandle)
end;
function b2PolygonShape_Get_m_centroid(_self: b2PolygonShapeHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Get_m_centroid'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonShape_Set_m_centroid(_self: b2PolygonShapeHandle; aNewValue: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Set_m_centroid'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShape_Get_m_centroid_P(_self: b2PolygonShapeHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Get_m_centroid_P'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShapeWrapper.Get_m_centroid: b2Vec2; cdecl;
begin
Result := b2PolygonShape_Get_m_centroid(FHandle);
end;
procedure b2PolygonShapeWrapper.Set_m_centroid(aNewValue: b2Vec2); cdecl;
begin
b2PolygonShape_Set_m_centroid(FHandle, aNewValue);
end;
function b2PolygonShapeWrapper.Get_m_centroid_P: Pb2Vec2; cdecl;
begin
Result := b2PolygonShape_Get_m_centroid_P(FHandle);
end;
function b2PolygonShape_Get_m_vertices(_self: b2PolygonShapeHandle; _idx: Integer): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Get_m_vertices'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonShape_Set_m_vertices(_self: b2PolygonShapeHandle; _idx: Integer; aNewValue: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Set_m_vertices'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShape_Get_m_vertices_P(_self: b2PolygonShapeHandle; _idx: Integer): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Get_m_vertices_P'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShapeWrapper.Get_m_vertices(_idx: Integer): b2Vec2; cdecl;
begin
Result := b2PolygonShape_Get_m_vertices(FHandle, _idx);
end;
procedure b2PolygonShapeWrapper.Set_m_vertices(_idx: Integer; aNewValue: b2Vec2); cdecl;
begin
b2PolygonShape_Set_m_vertices(FHandle, _idx, aNewValue);
end;
function b2PolygonShapeWrapper.Get_m_vertices_P(_idx: Integer): Pb2Vec2; cdecl;
begin
Result := b2PolygonShape_Get_m_vertices_P(FHandle, _idx);
end;
function b2PolygonShape_Get_m_normals(_self: b2PolygonShapeHandle; _idx: Integer): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Get_m_normals'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonShape_Set_m_normals(_self: b2PolygonShapeHandle; _idx: Integer; aNewValue: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Set_m_normals'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShape_Get_m_normals_P(_self: b2PolygonShapeHandle; _idx: Integer): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Get_m_normals_P'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShapeWrapper.Get_m_normals(_idx: Integer): b2Vec2; cdecl;
begin
Result := b2PolygonShape_Get_m_normals(FHandle, _idx);
end;
procedure b2PolygonShapeWrapper.Set_m_normals(_idx: Integer; aNewValue: b2Vec2); cdecl;
begin
b2PolygonShape_Set_m_normals(FHandle, _idx, aNewValue);
end;
function b2PolygonShapeWrapper.Get_m_normals_P(_idx: Integer): Pb2Vec2; cdecl;
begin
Result := b2PolygonShape_Get_m_normals_P(FHandle, _idx);
end;
function b2PolygonShape_Get_m_count(_self: b2PolygonShapeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Get_m_count'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonShape_Set_m_count(_self: b2PolygonShapeHandle; aNewValue: Integer); cdecl; external LIB_NAME name _PU + 'b2PolygonShape_Set_m_count'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonShapeWrapper.Get_m_count: Integer; cdecl;
begin
Result := b2PolygonShape_Get_m_count(FHandle);
end;
procedure b2PolygonShapeWrapper.Set_m_count(aNewValue: Integer); cdecl;
begin
b2PolygonShape_Set_m_count(FHandle, aNewValue);
end;
procedure b2GetPointStates(state1: Pb2PointState; state2: Pb2PointState; manifold1: Pb2Manifold; manifold2: Pb2Manifold); cdecl; external LIB_NAME name _PU + 'Collision_b2GetPointStates'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CollideCircles(manifold: Pb2Manifold; circleA: b2CircleShapeHandle; const [ref] xfA: b2Transform; circleB: b2CircleShapeHandle; const [ref] xfB: b2Transform); cdecl; external LIB_NAME name _PU + 'Collision_b2CollideCircles'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CollidePolygonAndCircle(manifold: Pb2Manifold; polygonA: b2PolygonShapeHandle; const [ref] xfA: b2Transform; circleB: b2CircleShapeHandle; const [ref] xfB: b2Transform); cdecl; external LIB_NAME name _PU + 'Collision_b2CollidePolygonAndCircle'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CollidePolygons(manifold: Pb2Manifold; polygonA: b2PolygonShapeHandle; const [ref] xfA: b2Transform; polygonB: b2PolygonShapeHandle; const [ref] xfB: b2Transform); cdecl; external LIB_NAME name _PU + 'Collision_b2CollidePolygons'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CollideEdgeAndCircle(manifold: Pb2Manifold; polygonA: b2EdgeShapeHandle; const [ref] xfA: b2Transform; circleB: b2CircleShapeHandle; const [ref] xfB: b2Transform); cdecl; external LIB_NAME name _PU + 'Collision_b2CollideEdgeAndCircle'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CollideEdgeAndPolygon(manifold: Pb2Manifold; edgeA: b2EdgeShapeHandle; const [ref] xfA: b2Transform; circleB: b2PolygonShapeHandle; const [ref] xfB: b2Transform); cdecl; external LIB_NAME name _PU + 'Collision_b2CollideEdgeAndPolygon'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ClipSegmentToLine(vOut: Pb2ClipVertex; vIn: Pb2ClipVertex; const [ref] normal: b2Vec2; offset: Single; vertexIndexA: Integer): Integer; cdecl; external LIB_NAME name _PU + 'Collision_b2ClipSegmentToLine'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2TestOverlap(shapeA: b2ShapeHandle; indexA: Integer; shapeB: b2ShapeHandle; indexB: Integer; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform): Boolean; overload; cdecl; external LIB_NAME name _PU + 'Collision_b2TestOverlap'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2TestOverlap(const [ref] a: b2AABB; const [ref] b: b2AABB): Boolean; overload; cdecl; external LIB_NAME name _PU + 'Collision_b2TestOverlap2'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PairLessThan(const [ref] pair1: b2Pair; const [ref] pair2: b2Pair): Boolean; cdecl; external LIB_NAME name _PU + 'Collision_b2PairLessThan'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Distance(output: Pb2DistanceOutput; cache: Pb2SimplexCache; input: Pb2DistanceInput); cdecl; external LIB_NAME name _PU + 'Collision_b2Distance'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2TimeOfImpact(output: Pb2TOIOutput; input: Pb2TOIInput); cdecl; external LIB_NAME name _PU + 'Collision_b2TimeOfImpact'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
initialization
{$IF defined(CPUX64)}
Assert(Sizeof(b2DistanceInput) = 104, 'Size mismatch in b2DistanceInput');
Assert(Sizeof(b2DistanceProxy) = 32, 'Size mismatch in b2DistanceProxy');
Assert(Sizeof(b2TOIInput) = 144, 'Size mismatch in b2TOIInput');
Assert(Sizeof(b2TreeNode) = 40, 'Size mismatch in b2TreeNode');
{$ELSE}
Assert(Sizeof(b2DistanceInput) = 92, 'Size mismatch in b2DistanceInput');
Assert(Sizeof(b2DistanceProxy) = 28, 'Size mismatch in b2DistanceProxy');
Assert(Sizeof(b2TOIInput) = 132, 'Size mismatch in b2TOIInput');
Assert(Sizeof(b2TreeNode) = 36, 'Size mismatch in b2TreeNode');
{$ENDIF}
Assert(Sizeof(b2AABB) = 16, 'Size mismatch in b2AABB');
Assert(Sizeof(b2ClipVertex) = 12, 'Size mismatch in b2ClipVertex');
Assert(Sizeof(b2ContactFeature) = 4, 'Size mismatch in b2ContactFeature');
Assert(Sizeof(b2ContactID) = 4, 'Size mismatch in b2ContactID');
Assert(Sizeof(b2DistanceOutput) = 24, 'Size mismatch in b2DistanceOutput');
Assert(Sizeof(b2Manifold) = 64, 'Size mismatch in b2Manifold');
Assert(Sizeof(b2ManifoldPoint) = 20, 'Size mismatch in b2ManifoldPoint');
Assert(Sizeof(b2MassData) = 16, 'Size mismatch in b2MassData');
Assert(Sizeof(b2Pair) = 8, 'Size mismatch in b2Pair');
Assert(Sizeof(b2RayCastInput) = 20, 'Size mismatch in b2RayCastInput');
Assert(Sizeof(b2RayCastOutput) = 12, 'Size mismatch in b2RayCastOutput');
Assert(Sizeof(b2SimplexCache) = 12, 'Size mismatch in b2SimplexCache');
Assert(Sizeof(b2TOIOutput) = 8, 'Size mismatch in b2TOIOutput');
Assert(Sizeof(b2WorldManifold) = 32, 'Size mismatch in b2WorldManifold');
end.
| 0 | 0.679828 | 1 | 0.679828 | game-dev | MEDIA | 0.668291 | game-dev | 0.745751 | 1 | 0.745751 |
WaypointRP/wp-placeables | 15,222 | client/placeables.lua | local animationDict = "pickup_object"
local animation = "pickup_low"
local isInPlaceItemMode = false
-- Keeps track of the models that have already been set with target options, ensuring we don't create duplicate options for the same model
-- In some frameworks like OX, if you create targetOptions on a model that already has it, it will append the options, whereas
-- in QB it will override and only the last set of options will be used. We just need to add one option to the target model and then
-- the pickup event will use the statebag to determine the correct item to give back to the player
local targetModels = {}
local function LoadPropDict(model)
while not HasModelLoaded(GetHashKey(model)) do
RequestModel(GetHashKey(model))
Wait(10)
end
end
-- Gets the direction the camera is looking for the raycast function
local function RotationToDirection(rotation)
local adjustedRotation = {
x = (math.pi / 180) * rotation.x,
y = (math.pi / 180) * rotation.y,
z = (math.pi / 180) * rotation.z,
}
local direction = {
x = -math.sin(adjustedRotation.z) * math.abs(math.cos(adjustedRotation.x)),
y = math.cos(adjustedRotation.z) * math.abs(math.cos(adjustedRotation.x)),
z = math.sin(adjustedRotation.x),
}
return direction
end
-- Uses a RayCast to get the entity, coords, and whether we "hit" something with the raycast
-- Object passed in, is the current object that we want the raycast to ignore
local function RayCastGamePlayCamera(distance, object, raycastDetectWorldOnly)
local cameraRotation = GetGameplayCamRot()
local cameraCoord = GetGameplayCamCoord()
local direction = RotationToDirection(cameraRotation)
local destination = {
x = cameraCoord.x + direction.x * distance,
y = cameraCoord.y + direction.y * distance,
z = cameraCoord.z + direction.z * distance,
}
-- Trace flag 4294967295 means the raycast will intersect with everything (including vehicles)
-- Trace flag 1 means the raycast will only intersect with the world (ignoring other entities like peds, cars, etc)
local traceFlag = 4294967295
if raycastDetectWorldOnly then
traceFlag = 1
end
local a, hit, coords, d, entity = GetShapeTestResult(StartShapeTestRay(cameraCoord.x, cameraCoord.y, cameraCoord.z, destination.x, destination.y, destination.z, traceFlag, object, 0))
return hit, coords, entity
end
-- Used to Draw the text on the screen
local function Draw2DText(content, font, colour, scale, x, y)
SetTextFont(font)
SetTextScale(scale, scale)
SetTextColour(colour[1], colour[2], colour[3], 255)
SetTextEntry("STRING")
SetTextDropShadow(0, 0, 0, 0, 255)
SetTextDropShadow()
SetTextEdge(4, 0, 0, 0, 255)
SetTextOutline()
AddTextComponentString(content)
DrawText(x, y)
end
-- This handles placing the actual item that is network synced
local function placeItem(item, coords, heading, shouldSnapToGround)
local ped = PlayerPedId()
local itemName = item.item
local itemModel = item.model
local shouldFreezeItem = item.isFrozen
-- Cancel any active animation
ClearPedTasks(ped)
Progressbar("place_item", "Placing " .. item.label, 750, false, true, {
disableMovement = false,
disableCarMovement = false,
disableMouse = false,
disableCombat = true,
}, {
animDict = animationDict,
anim = animation,
flags = 0,
}, nil, nil, function() -- Done
-- Stop playing the animation
StopAnimTask(ped, animationDict, animation, 1.0)
-- Remove the item from the inventory
TriggerServerEvent("wp-placeables:server:RemoveItem", itemName)
LoadPropDict(itemModel)
-- Spawn prop on ground at the provided coords and heading
local obj = CreateObject(itemModel, GetEntityCoords(ped), true)
if obj ~= 0 then
SetEntityRotation(obj, 0.0, 0.0, heading, false, false)
SetEntityCoords(obj, coords)
if shouldFreezeItem then
FreezeEntityPosition(obj, true)
end
-- Some items dont go to the ground properly with this, and it actually makes them hover
if shouldSnapToGround then
PlaceObjectOnGroundProperly(obj)
end
-- Use statebag property itemName to set the itemName on the entity.
-- This value is used to grant the correct item back to the player when they pick it up.
-- It also solves the issue of the same model being used for multiple items
Entity(obj).state:set("itemName", itemName, true)
CreateLog(itemName, true)
end
SetModelAsNoLongerNeeded(itemModel)
end, function() -- Cancel
StopAnimTask(ped, animationDict, animation, 1.0)
Notify("Canceled..", "error")
end)
end
-- Starts a thread that puts the player into item placement mode
-- This will spawn a local object that only the player can see and move around to position it
-- Once the player places the object it will delete the local one and then create a new network synced object
local function startItemPlacementMode(item)
-- This is to prevent entering place mode multiple times if its already active
if isInPlaceItemMode then
Notify("Already placing an item", "error", 5000)
return
end
isInPlaceItemMode = true
local ped = PlayerPedId()
local itemModel = item.model
-- Create a local object for only this client (not synced to network) and make it transparent
local obj = CreateObject(itemModel, GetEntityCoords(ped), false, false)
SetEntityAlpha(obj, 150, false)
SetEntityCollision(obj, false, false)
local zOffset = 0
-- This is used to determine if the raycast should only detect the world or if it should detect everything (including vehicles)
local raycastDetectWorldOnly = true
CreateThread(function()
while isInPlaceItemMode do
-- Use raycast based on where the camera is pointed
local hit, coords, entity = RayCastGamePlayCamera(Config.ItemPlacementModeRadius, obj, raycastDetectWorldOnly)
-- Move the object to the coords from the raycast
SetEntityCoords(obj, coords.x, coords.y, coords.z + zOffset)
-- Display the controls
Draw2DText("[E] Place\n[Shift+E] Place on ground\n[Scroll Up/Down] Rotate\n[Shift+Scroll Up/Down] Raise/lower", 4, { 255, 255, 255, }, 0.4, 0.85, 0.85)
Draw2DText("[Scroll Click] Change mode\n[Right Click / Backspace] Exit place mode", 4, { 255, 255, 255, }, 0.4, 0.85, 0.945)
-- Handle various key presses and actions
-- Controls for placing item
-- Pressed Shift + E - Place object on ground
if IsControlJustReleased(0, 38) and IsControlPressed(0, 21) then
isInPlaceItemMode = false
local objHeading = GetEntityHeading(obj)
local snapToGround = true
DeleteEntity(obj)
placeItem(item, vector3(coords.x, coords.y, coords.z + zOffset), objHeading, snapToGround)
-- Pressed E - Place object at current position
elseif IsControlJustReleased(0, 38) then
isInPlaceItemMode = false
local objHeading = GetEntityHeading(obj)
local snapToGround = false
DeleteEntity(obj)
placeItem(item, vector3(coords.x, coords.y, coords.z + zOffset), objHeading, snapToGround)
end
-- Controls for rotating item
-- Mouse Wheel Up (and Shift not pressed), rotate by +10 degrees
if IsControlJustReleased(0, 241) and not IsControlPressed(0, 21) then
local objHeading = GetEntityHeading(obj)
SetEntityRotation(obj, 0.0, 0.0, objHeading + 10, false, false)
end
-- Mouse Wheel Down (and shift not pressed), rotate by -10 degrees
if IsControlJustReleased(0, 242) and not IsControlPressed(0, 21) then
local objHeading = GetEntityHeading(obj)
SetEntityRotation(obj, 0.0, 0.0, objHeading - 10, false, false)
end
-- Controls for raising/lowering item
-- Shift + Mouse Wheel Up, move item up
if IsControlPressed(0, 21) and IsControlJustReleased(0, 241) then
zOffset = zOffset + 0.1
if zOffset > Config.maxZOffset then
zOffset = Config.maxZOffset
end
end
-- Shift + Mouse Wheel Down, move item down
if IsControlPressed(0, 21) and IsControlJustReleased(0, 242) then
zOffset = zOffset - 0.1
if zOffset < Config.minZOffset then
zOffset = Config.minZOffset
end
end
-- Mouse Wheel Click, change placement mode
if IsControlJustReleased(0, 348) then
raycastDetectWorldOnly = not raycastDetectWorldOnly
end
-- Right click or Backspace to exit out of placement mode and delete the local object
if IsControlJustReleased(0, 177) then
isInPlaceItemMode = false
DeleteEntity(obj)
end
Wait(1)
end
end)
end
-- Handles picking up the prop, deleting it from the world and adding it to the players inventory
local function pickUpItem(itemData)
local ped = PlayerPedId()
local itemEntity = itemData.entity
local itemModel = itemData.itemModel
-- When picking up the item, try to get the itemName from the statebag property first, else fallback to the itemName from the itemData provided by the target script
-- Using the statebag property ensures we get the correct item name if the prop model is shared by multiple items..
local itemName = Entity(itemEntity).state.itemName or itemData.itemName
if itemName then
-- Cancel any active animation
ClearPedTasks(ped)
Progressbar("pickup_item", "Picking up item", 200, false, true, {
disableMovement = false,
disableCarMovement = false,
disableMouse = false,
disableCombat = true,
}, {
animDict = animationDict,
anim = animation,
flags = 0,
}, nil, nil, function() -- Done
-- Stop playing the animation
StopAnimTask(ped, animationDict, animation, 1.0)
-- Add the item to the inventory
TriggerServerEvent("wp-placeables:server:AddItem", itemName)
-- First request control of networkId and wait until have control of netId before deleting it
-- Item will not properly delete if the client doesn't have control of the networkId
local coords = GetEntityCoords(itemEntity)
local netId = NetworkGetNetworkIdFromEntity(itemEntity)
RequestNetworkControlOfObject(netId, itemEntity)
SetEntityAsMissionEntity(itemEntity, true, true)
DeleteEntity(itemEntity)
local object = { coords = coords, model = itemModel, }
TriggerServerEvent("wp-placeables:server:deleteWorldObject", object)
CreateLog(itemName, false)
end, function() -- Cancel
StopAnimTask(ped, animationDict, animation, 1.0)
Notify("Canceled..", "error")
end)
end
end
RegisterNetEvent("wp-placeables:client:placeItem", function(item)
if not IsPedInAnyVehicle(PlayerPedId(), true) then
startItemPlacementMode(item)
else
Notify("You cannot place items while in a vehicle", "error", 5000)
end
end)
RegisterNetEvent("wp-placeables:client:pickUpItem", function(data)
pickUpItem(data)
end)
-- Setup each placeable prop to use QB target
-- Itemname is in the options so we know which item to give back when picked up
for _, prop in pairs(Config.PlaceableProps) do
local pickUpEvent = "wp-placeables:client:pickUpItem"
if prop.customPickupEvent then
pickUpEvent = prop.customPickupEvent
end
local targetOptions = {
{
event = pickUpEvent,
icon = "fas fa-hand-holding",
label = "Pick up",
itemName = prop.item,
itemModel = prop.model,
},
}
-- Add custom target options to the target options for this item prop
if prop.customTargetOptions then
for _, customOption in pairs(prop.customTargetOptions) do
-- Stamp the itemName and itemModel onto the data so the custom events have access to this info
customOption.itemName = prop.item
customOption.itemModel = prop.model
targetOptions[#targetOptions + 1] = customOption
end
end
-- Make sure we only define the target options once for each model
-- If you define the same model twice:
-- In qb-target, it will override the options, and the last one defined is used
-- In ox_target, it will append the options, resulting in N duplicate options
if not targetModels[prop.model] then
AddTargetModel(prop.model, {
options = targetOptions,
distance = 1.5,
})
targetModels[prop.model] = true
end
end
-- Delete the world object
-- object = {coords = coords, model = itemModel}
RegisterNetEvent("wp-placeables:client:deleteWorldObject", function(object)
local entity = GetClosestObjectOfType(object.coords.x, object.coords.y, object.coords.z, 0.1, object.model, false, false, false)
if DoesEntityExist(entity) then
SetEntityAsMissionEntity(entity, 1, 1)
DeleteObject(entity)
SetEntityAsNoLongerNeeded(entity)
end
end)
-- Runs a thread to loop through the deleted world objects table and removes the item if it exists
-- This is to handle cases if the item were to have respawned
-- Disabling this for now since we dont need to care if the item respawns
-- There is currently an issue where this was being used for both player placed objects as well as world props
-- If you placed an item, picked it up and placed the same item down again, the cleanup thread would delete it since its at the same coords.
-- If we want to re-enable this, we need to find a way to only use this cleanup thread on world spawned props
-- AddEventHandler('QBCore:Client:OnPlayerLoaded', function()
-- QBCore.Functions.TriggerCallback('wp-placeables:server:GetDeletedWorldObjects', function(deletedObjects)
-- objects = deletedObjects
-- end)
-- end)
-- CreateThread(function()
-- while true do
-- for k = 1, #objects, 1 do
-- v = objects[k]
-- local entity = GetClosestObjectOfType(v.coords.x, v.coords.y, v.coords.z, 0.1, v.model, false, false, false)
-- if DoesEntityExist(entity) then
-- SetEntityAsMissionEntity(entity, 1, 1)
-- DeleteObject(entity)
-- SetEntityAsNoLongerNeeded(entity)
-- end
-- end
-- Wait(10000)
-- end
-- end)
| 0 | 0.926269 | 1 | 0.926269 | game-dev | MEDIA | 0.967426 | game-dev | 0.943482 | 1 | 0.943482 |
RoaringBitmap/croaring-rs | 4,284 | croaring/src/rust_alloc/mod.rs | #[cfg(not(feature = "allocator-api2"))]
use alloc::alloc::Layout;
#[cfg(feature = "allocator-api2")]
use allocator_api2::alloc::Layout;
#[cfg(feature = "alloc")]
mod global_alloc;
#[cfg(feature = "alloc")]
pub use global_alloc::configure_rust_alloc;
#[cfg(feature = "allocator-api2")]
mod custom_alloc;
#[cfg(feature = "allocator-api2")]
pub use custom_alloc::configure_custom_alloc;
fn layout(size: usize) -> Option<Layout> {
if size == 0 {
return None;
}
let (layout, _) = Layout::new::<usize>()
.extend(Layout::array::<u8>(size).ok()?)
.ok()?;
Some(layout)
}
struct AlignedLayout(Layout);
#[repr(C)]
struct SizeAlign {
size: usize,
align: usize,
}
const fn padding_for_align(align: usize) -> usize {
align.saturating_sub(size_of::<SizeAlign>())
}
impl AlignedLayout {
fn new(size: usize, align: usize) -> Option<Self> {
if size == 0 || align == 0 || !align.is_power_of_two() {
return None;
}
// Will store two usizes before the data: the size and alignment.
// Additionally, there may be additional padding to ensure the data is aligned to
// the required alignment.
let align = align.max(align_of::<SizeAlign>());
let padding = padding_for_align(align);
let size = padding
.checked_add(size_of::<SizeAlign>())?
.checked_add(size)?;
let layout = Layout::from_size_align(size, align).ok()?;
debug_assert_eq!((padding + size_of::<SizeAlign>()) % align, 0);
Some(Self(layout))
}
const fn padding(&self) -> usize {
padding_for_align(self.0.align())
}
unsafe fn store_and_return(&self, allocated_ptr: *mut u8) -> *mut u8 {
let size_ptr = allocated_ptr.add(self.padding()).cast::<SizeAlign>();
size_ptr.write(SizeAlign {
size: self.0.size(),
align: self.0.align(),
});
size_ptr.add(1).cast()
}
unsafe fn from_raw(raw_ptr: *mut core::ffi::c_void) -> (*mut core::ffi::c_void, Self) {
let size_ptr = raw_ptr.cast::<SizeAlign>().sub(1);
let SizeAlign { size, align } = size_ptr.read();
let padding = padding_for_align(align);
let orig_ptr = size_ptr.cast::<u8>().sub(padding);
let layout = Layout::from_size_align_unchecked(size, align);
(orig_ptr.cast(), Self(layout))
}
}
#[test]
fn test_aligned_layout_no_padding() {
let aligned_layout = AlignedLayout::new(10, 2 * size_of::<usize>()).unwrap();
assert_eq!(aligned_layout.padding(), 0);
assert_eq!(aligned_layout.0.size(), 10 + size_of::<SizeAlign>());
assert_eq!(aligned_layout.0.align(), 16);
}
#[test]
fn test_aligned_layout_big_align() {
let aligned_layout = AlignedLayout::new(10, 1024).unwrap();
assert_eq!(aligned_layout.padding(), 1024 - size_of::<SizeAlign>());
assert_eq!(aligned_layout.0.size(), 10 + 1024);
assert_eq!(aligned_layout.0.align(), 1024);
}
#[test]
fn aligned_layout_big() {
let align = 0x2000000000000000;
let layout = AlignedLayout::new(0x2000000000000000, align).unwrap();
assert_ne!(layout.0.size(), 0);
// The beginning of the allocation is aligned to at least the required alignment.
assert_eq!(layout.0.align() % align, 0);
// The beginning of the data is aligned to at least the required alignment.
assert_eq!((layout.padding() + size_of::<SizeAlign>()) % align, 0);
}
// run with `cargo kani`
#[cfg(kani)]
#[kani::proof]
fn aligned_layout() {
let size = kani::any();
let align = kani::any();
if let Some(layout) = AlignedLayout::new(size, align) {
assert!(layout.0.size() != 0);
// The beginning of the allocation is aligned to at least the required alignment.
assert!(layout.0.align() % align == 0);
// The size and align after the padding are aligned enough
assert!(layout.padding() % align_of::<SizeAlign>() == 0);
// The beginning of the data is aligned to at least the required alignment.
assert!((layout.padding() + size_of::<SizeAlign>()) % align == 0);
// There is enough space after the padding and size/align to store `size` bytes
assert!(layout.0.size() - (layout.padding() + size_of::<SizeAlign>()) >= size);
}
}
| 0 | 0.97382 | 1 | 0.97382 | game-dev | MEDIA | 0.234444 | game-dev | 0.913599 | 1 | 0.913599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.