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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Soft-Sprint-Studios/Tectonic-Engine | 9,873 | bullet/include/BulletDynamics/Featherstone/btMultiBodyInplaceSolverIslandCallback.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2019 Google 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 BT_MULTIBODY_INPLACE_SOLVER_ISLAND_CALLBACK_H
#define BT_MULTIBODY_INPLACE_SOLVER_ISLAND_CALLBACK_H
#include "BulletDynamics/Featherstone/btMultiBodyConstraintSolver.h"
#include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h"
#include "BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.h"
#include "btMultiBodyConstraintSolver.h"
SIMD_FORCE_INLINE int btGetConstraintIslandId2(const btTypedConstraint* lhs)
{
int islandId;
const btCollisionObject& rcolObj0 = lhs->getRigidBodyA();
const btCollisionObject& rcolObj1 = lhs->getRigidBodyB();
islandId = rcolObj0.getIslandTag() >= 0 ? rcolObj0.getIslandTag() : rcolObj1.getIslandTag();
return islandId;
}
class btSortConstraintOnIslandPredicate2
{
public:
bool operator()(const btTypedConstraint* lhs, const btTypedConstraint* rhs) const
{
int rIslandId0, lIslandId0;
rIslandId0 = btGetConstraintIslandId2(rhs);
lIslandId0 = btGetConstraintIslandId2(lhs);
return lIslandId0 < rIslandId0;
}
};
SIMD_FORCE_INLINE int btGetMultiBodyConstraintIslandId(const btMultiBodyConstraint* lhs)
{
int islandId;
int islandTagA = lhs->getIslandIdA();
int islandTagB = lhs->getIslandIdB();
islandId = islandTagA >= 0 ? islandTagA : islandTagB;
return islandId;
}
class btSortMultiBodyConstraintOnIslandPredicate
{
public:
bool operator()(const btMultiBodyConstraint* lhs, const btMultiBodyConstraint* rhs) const
{
int rIslandId0, lIslandId0;
rIslandId0 = btGetMultiBodyConstraintIslandId(rhs);
lIslandId0 = btGetMultiBodyConstraintIslandId(lhs);
return lIslandId0 < rIslandId0;
}
};
struct MultiBodyInplaceSolverIslandCallback : public btSimulationIslandManager::IslandCallback
{
btContactSolverInfo* m_solverInfo;
btMultiBodyConstraintSolver* m_solver;
btMultiBodyConstraint** m_multiBodySortedConstraints;
int m_numMultiBodyConstraints;
btTypedConstraint** m_sortedConstraints;
int m_numConstraints;
btIDebugDraw* m_debugDrawer;
btDispatcher* m_dispatcher;
btAlignedObjectArray<btCollisionObject*> m_bodies;
btAlignedObjectArray<btCollisionObject*> m_softBodies;
btAlignedObjectArray<btPersistentManifold*> m_manifolds;
btAlignedObjectArray<btTypedConstraint*> m_constraints;
btAlignedObjectArray<btMultiBodyConstraint*> m_multiBodyConstraints;
btAlignedObjectArray<btSolverAnalyticsData> m_islandAnalyticsData;
MultiBodyInplaceSolverIslandCallback(btMultiBodyConstraintSolver* solver,
btDispatcher* dispatcher)
: m_solverInfo(NULL),
m_solver(solver),
m_multiBodySortedConstraints(NULL),
m_numConstraints(0),
m_debugDrawer(NULL),
m_dispatcher(dispatcher)
{
}
MultiBodyInplaceSolverIslandCallback& operator=(const MultiBodyInplaceSolverIslandCallback& other)
{
btAssert(0);
(void)other;
return *this;
}
SIMD_FORCE_INLINE virtual void setup(btContactSolverInfo* solverInfo, btTypedConstraint** sortedConstraints, int numConstraints, btMultiBodyConstraint** sortedMultiBodyConstraints, int numMultiBodyConstraints, btIDebugDraw* debugDrawer)
{
m_islandAnalyticsData.clear();
btAssert(solverInfo);
m_solverInfo = solverInfo;
m_multiBodySortedConstraints = sortedMultiBodyConstraints;
m_numMultiBodyConstraints = numMultiBodyConstraints;
m_sortedConstraints = sortedConstraints;
m_numConstraints = numConstraints;
m_debugDrawer = debugDrawer;
m_bodies.resize(0);
m_manifolds.resize(0);
m_constraints.resize(0);
m_multiBodyConstraints.resize(0);
}
void setMultiBodyConstraintSolver(btMultiBodyConstraintSolver* solver)
{
m_solver = solver;
}
virtual void processIsland(btCollisionObject** bodies, int numBodies, btPersistentManifold** manifolds, int numManifolds, int islandId)
{
if (islandId < 0)
{
///we don't split islands, so all constraints/contact manifolds/bodies are passed into the solver regardless the island id
m_solver->solveMultiBodyGroup(bodies, numBodies, manifolds, numManifolds, m_sortedConstraints, m_numConstraints, &m_multiBodySortedConstraints[0], m_numConstraints, *m_solverInfo, m_debugDrawer, m_dispatcher);
if (m_solverInfo->m_reportSolverAnalytics&1)
{
m_solver->m_analyticsData.m_islandId = islandId;
m_islandAnalyticsData.push_back(m_solver->m_analyticsData);
}
}
else
{
//also add all non-contact constraints/joints for this island
btTypedConstraint** startConstraint = 0;
btMultiBodyConstraint** startMultiBodyConstraint = 0;
int numCurConstraints = 0;
int numCurMultiBodyConstraints = 0;
int i;
//find the first constraint for this island
for (i = 0; i < m_numConstraints; i++)
{
if (btGetConstraintIslandId2(m_sortedConstraints[i]) == islandId)
{
startConstraint = &m_sortedConstraints[i];
break;
}
}
//count the number of constraints in this island
for (; i < m_numConstraints; i++)
{
if (btGetConstraintIslandId2(m_sortedConstraints[i]) == islandId)
{
numCurConstraints++;
}
}
for (i = 0; i < m_numMultiBodyConstraints; i++)
{
if (btGetMultiBodyConstraintIslandId(m_multiBodySortedConstraints[i]) == islandId)
{
startMultiBodyConstraint = &m_multiBodySortedConstraints[i];
break;
}
}
//count the number of multi body constraints in this island
for (; i < m_numMultiBodyConstraints; i++)
{
if (btGetMultiBodyConstraintIslandId(m_multiBodySortedConstraints[i]) == islandId)
{
numCurMultiBodyConstraints++;
}
}
//if (m_solverInfo->m_minimumSolverBatchSize<=1)
//{
// m_solver->solveGroup( bodies,numBodies,manifolds, numManifolds,startConstraint,numCurConstraints,*m_solverInfo,m_debugDrawer,m_dispatcher);
//} else
{
for (i = 0; i < numBodies; i++)
{
bool isSoftBodyType = (bodies[i]->getInternalType() & btCollisionObject::CO_SOFT_BODY);
if (!isSoftBodyType)
{
m_bodies.push_back(bodies[i]);
}
else
{
m_softBodies.push_back(bodies[i]);
}
}
for (i = 0; i < numManifolds; i++)
m_manifolds.push_back(manifolds[i]);
for (i = 0; i < numCurConstraints; i++)
m_constraints.push_back(startConstraint[i]);
for (i = 0; i < numCurMultiBodyConstraints; i++)
m_multiBodyConstraints.push_back(startMultiBodyConstraint[i]);
if ((m_multiBodyConstraints.size() + m_constraints.size() + m_manifolds.size()) > m_solverInfo->m_minimumSolverBatchSize)
{
processConstraints(islandId);
}
else
{
//printf("deferred\n");
}
}
}
}
virtual void processConstraints(int islandId=-1)
{
btCollisionObject** bodies = m_bodies.size() ? &m_bodies[0] : 0;
btPersistentManifold** manifold = m_manifolds.size() ? &m_manifolds[0] : 0;
btTypedConstraint** constraints = m_constraints.size() ? &m_constraints[0] : 0;
btMultiBodyConstraint** multiBodyConstraints = m_multiBodyConstraints.size() ? &m_multiBodyConstraints[0] : 0;
//printf("mb contacts = %d, mb constraints = %d\n", mbContacts, m_multiBodyConstraints.size());
m_solver->solveMultiBodyGroup(bodies, m_bodies.size(), manifold, m_manifolds.size(), constraints, m_constraints.size(), multiBodyConstraints, m_multiBodyConstraints.size(), *m_solverInfo, m_debugDrawer, m_dispatcher);
if (m_bodies.size() && (m_solverInfo->m_reportSolverAnalytics&1))
{
m_solver->m_analyticsData.m_islandId = islandId;
m_islandAnalyticsData.push_back(m_solver->m_analyticsData);
}
m_bodies.resize(0);
m_softBodies.resize(0);
m_manifolds.resize(0);
m_constraints.resize(0);
m_multiBodyConstraints.resize(0);
}
};
#endif /*BT_MULTIBODY_INPLACE_SOLVER_ISLAND_CALLBACK_H */
| 1 | 0.881669 | 1 | 0.881669 | game-dev | MEDIA | 0.921234 | game-dev | 0.948058 | 1 | 0.948058 |
johnnemann/museum-of-mechanics-lockpicking | 1,913 | Open Museum/Library/PackageCache/com.unity.textmeshpro@3.0.4/Scripts/Editor/GlyphRectPropertyDrawer.cs | using UnityEngine;
using UnityEngine.TextCore;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomPropertyDrawer(typeof(GlyphRect))]
public class GlyphRectPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
//EditorGUI.BeginProperty(position, label, property);
SerializedProperty prop_X = property.FindPropertyRelative("m_X");
SerializedProperty prop_Y = property.FindPropertyRelative("m_Y");
SerializedProperty prop_Width = property.FindPropertyRelative("m_Width");
SerializedProperty prop_Height = property.FindPropertyRelative("m_Height");
// We get Rect since a valid position may not be provided by the caller.
Rect rect = new Rect(position.x, position.y, position.width, 49);
EditorGUI.LabelField(new Rect(rect.x, rect.y - 2.5f, rect.width, 18), new GUIContent("Glyph Rect"));
EditorGUIUtility.labelWidth = 50f;
EditorGUIUtility.fieldWidth = 20f;
//GUI.enabled = false;
float width = (rect.width - 75f) / 4;
EditorGUI.PropertyField(new Rect(rect.x + width * 0, rect.y + 20, width - 5f, 18), prop_X, new GUIContent("X:"));
EditorGUI.PropertyField(new Rect(rect.x + width * 1, rect.y + 20, width - 5f, 18), prop_Y, new GUIContent("Y:"));
EditorGUI.PropertyField(new Rect(rect.x + width * 2, rect.y + 20, width - 5f, 18), prop_Width, new GUIContent("W:"));
EditorGUI.PropertyField(new Rect(rect.x + width * 3, rect.y + 20, width - 5f, 18), prop_Height, new GUIContent("H:"));
//EditorGUI.EndProperty();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return 45f;
}
}
}
| 1 | 0.79713 | 1 | 0.79713 | game-dev | MEDIA | 0.896649 | game-dev | 0.69656 | 1 | 0.69656 |
OpenXRay/xray-15 | 4,673 | cs/engine/xrGame/UIGameCustom.h | #ifndef __XR_UIGAMECUSTOM_H__
#define __XR_UIGAMECUSTOM_H__
#pragma once
#include "script_export_space.h"
#include "object_interfaces.h"
#include "inventory_space.h"
#include "ui/KillMessageStruct.h"
#include "gametype_chooser.h"
// refs
class CUI;
class CTeamBaseZone;
class game_cl_GameState;
class CUIDialogWnd;
class CUICaption;
class CUIStatic;
class CUIWindow;
class CUIXml;
class CUIActorMenu;
class CUIPdaWnd;
struct SDrawStaticStruct :public IPureDestroyableObject{
SDrawStaticStruct ();
virtual void destroy ();
CUIStatic* m_static;
float m_endTime;
shared_str m_name;
void Draw();
void Update();
CUIStatic* wnd() {return m_static;}
bool IsActual();
bool operator ==(LPCSTR str){
return (m_name == str);
}
};
typedef xr_vector<SDrawStaticStruct> st_vec;
//#include "game_base_space.h"
struct SGameTypeMaps
{
shared_str m_game_type_name;
EGameIDs m_game_type_id;
struct SMapItm{
shared_str map_name;
shared_str map_ver;
bool operator ==(const SMapItm& other){return map_name==other.map_name && map_ver==other.map_ver;}
};
xr_vector<SMapItm> m_map_names;
};
struct SGameWeathers
{
shared_str m_weather_name;
shared_str m_start_time;
};
typedef xr_vector<SGameWeathers> GAME_WEATHERS;
typedef xr_vector<SGameWeathers>::iterator GAME_WEATHERS_IT;
typedef xr_vector<SGameWeathers>::const_iterator GAME_WEATHERS_CIT;
class CMapListHelper
{
typedef xr_vector<SGameTypeMaps> TSTORAGE;
typedef TSTORAGE::iterator TSTORAGE_IT;
typedef TSTORAGE::iterator TSTORAGE_CIT;
TSTORAGE m_storage;
GAME_WEATHERS m_weathers;
void Load ();
void LoadMapInfo (LPCSTR file_name, const xr_string& map_name, LPCSTR map_ver="1.0");
SGameTypeMaps* GetMapListInt (const shared_str& game_type);
public:
const SGameTypeMaps& GetMapListFor (const shared_str& game_type);
const SGameTypeMaps& GetMapListFor (const EGameIDs game_id);
const GAME_WEATHERS& GetGameWeathers ();
};
extern CMapListHelper gMapListHelper;
class CUIGameCustom :public DLL_Pure, public ISheduled
{
typedef ISheduled inherited;
protected:
u32 uFlags;
void SetFlag (u32 mask, BOOL flag){if (flag) uFlags|=mask; else uFlags&=~mask; }
void InvertFlag (u32 mask){if (uFlags&mask) uFlags&=~mask; else uFlags|=mask; }
BOOL GetFlag (u32 mask){return uFlags&mask;}
CUICaption* GameCaptions () {return m_pgameCaptions;}
CUICaption* m_pgameCaptions;
CUIXml* m_msgs_xml;
st_vec m_custom_statics;
CUIActorMenu* m_ActorMenu;
CUIPdaWnd* m_PdaMenu;
public:
virtual void SetClGame (game_cl_GameState* g){};
virtual void OnInventoryAction (PIItem item, u16 action_type);
virtual float shedule_Scale ();
virtual void shedule_Update (u32 dt);
CUIGameCustom ();
virtual ~CUIGameCustom ();
virtual void Init () {};
virtual void Render ();
virtual void OnFrame ();
virtual void reset_ui ();
IC CUIActorMenu& ActorMenu () const { return *m_ActorMenu; }
IC CUIPdaWnd& PdaMenu () const { return *m_PdaMenu; }
bool ShowActorMenu ();
void HideActorMenu ();
bool ShowPdaMenu ();
void HidePdaMenu ();
virtual bool IR_OnKeyboardPress (int dik);
virtual bool IR_OnKeyboardRelease (int dik);
virtual bool IR_OnMouseMove (int dx, int dy);
virtual bool IR_OnMouseWheel (int direction);
void AddDialogToRender (CUIWindow* pDialog);
void RemoveDialogToRender (CUIWindow* pDialog);
CUIDialogWnd* MainInputReceiver ();
virtual void HideShownDialogs (){};
void AddCustomMessage (LPCSTR id, float x, float y, float font_size, CGameFont *pFont, u16 alignment, u32 color);
void AddCustomMessage (LPCSTR id, float x, float y, float font_size, CGameFont *pFont, u16 alignment, u32 color/*, LPCSTR def_text*/, float flicker );
void CustomMessageOut (LPCSTR id, LPCSTR msg, u32 color);
void RemoveCustomMessage (LPCSTR id);
SDrawStaticStruct* AddCustomStatic (LPCSTR id, bool bSingleInstance);
SDrawStaticStruct* GetCustomStatic (LPCSTR id);
void RemoveCustomStatic (LPCSTR id);
virtual shared_str shedule_Name () const { return shared_str("CUIGameCustom"); };
virtual bool shedule_Needed () {return true;};
virtual void ChangeTotalMoneyIndicator (LPCSTR newMoneyString) {};
virtual void DisplayMoneyChange (LPCSTR deltaMoney) {};
virtual void DisplayMoneyBonus (KillMessageStruct bonus) {};
DECLARE_SCRIPT_REGISTER_FUNCTION
}; // class CUIGameCustom
add_to_type_list(CUIGameCustom)
#undef script_type_list
#define script_type_list save_type_list(CUIGameCustom)
#endif // __XR_UIGAMECUSTOM_H__
| 1 | 0.907455 | 1 | 0.907455 | game-dev | MEDIA | 0.945343 | game-dev | 0.577305 | 1 | 0.577305 |
PGMDev/PGM | 5,515 | platform/platform-sportpaper/src/main/java/tc/oc/pgm/platform/sportpaper/packets/SpEntityPackets.java | package tc.oc.pgm.platform.sportpaper.packets;
import static tc.oc.pgm.util.platform.Supports.Variant.SPORTPAPER;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.server.v1_8_R3.DataWatcher;
import net.minecraft.server.v1_8_R3.NBTTagCompound;
import net.minecraft.server.v1_8_R3.PacketPlayOutAttachEntity;
import net.minecraft.server.v1_8_R3.PacketPlayOutEntityDestroy;
import net.minecraft.server.v1_8_R3.PacketPlayOutEntityEquipment;
import net.minecraft.server.v1_8_R3.PacketPlayOutEntityHeadRotation;
import net.minecraft.server.v1_8_R3.PacketPlayOutEntityMetadata;
import net.minecraft.server.v1_8_R3.PacketPlayOutEntityTeleport;
import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntity;
import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntityLiving;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import tc.oc.pgm.util.nms.packets.EntityPackets;
import tc.oc.pgm.util.nms.packets.Packet;
import tc.oc.pgm.util.platform.Supports;
@Supports(SPORTPAPER)
public class SpEntityPackets implements EntityPackets {
private static final int WITHER_SKULL = 66;
@Override
public Packet spawnArmorStand(Location loc, int entityId, Vector velocity) {
DataWatcher dataWatcher = new DataWatcher(null);
// https://wiki.vg/index.php?title=Entity_metadata&oldid=7415
dataWatcher.a(0, (byte) 0x20); // 0 = Flags, 0x20 = invisible
dataWatcher.a(1, (short) 0); // 1 = air, 0
dataWatcher.a(10, (byte) 0); // 10 = armor stand flags, 0 = no gravity, nor arms, etc
return new SpPacket<>(new PacketPlayOutSpawnEntityLiving(
entityId,
(byte) EntityType.ARMOR_STAND.getTypeId(),
loc.getX(),
loc.getY(),
loc.getZ(),
loc.getYaw(),
loc.getPitch(),
loc.getPitch(),
(int) (velocity.getX() * 8000),
(int) (velocity.getY() * 8000),
(int) (velocity.getZ() * 8000),
dataWatcher));
}
@Override
public Packet spawnWitherSkull(Location loc, int entityId, Vector velocity) {
return new SpPacket<>(new PacketPlayOutSpawnEntity(
entityId,
loc.getX(),
loc.getY(),
loc.getZ(),
(int) (velocity.getX() * 8000),
(int) (velocity.getY() * 8000),
(int) (velocity.getZ() * 8000),
(int) loc.getPitch(),
(int) loc.getYaw(),
WITHER_SKULL,
0));
}
@Override
public Packet destroyEntitiesPacket(int... entityIds) {
return new SpPacket<>(new PacketPlayOutEntityDestroy(entityIds));
}
@Override
public Packet teleportEntityPacket(int entityId, Location location) {
return new SpPacket<>(new PacketPlayOutEntityTeleport(
entityId, // Entity ID
(int) (location.getX() * 32), // World X * 32
(int) (location.getY() * 32), // World Y * 32
(int) (location.getZ() * 32), // World Z * 32
(byte) (location.getYaw() * 256 / 360), // Yaw
(byte) (location.getPitch() * 256 / 360), // Pitch
true)); // On Ground + Height Correction
}
private static final EntityMock ENTITY_MOCK = new EntityMock();
@Override
public Packet updateHeadRotation(int entityId, Location location) {
return new SpPacket<>(new PacketPlayOutEntityHeadRotation(
ENTITY_MOCK.withId(entityId), (byte) (location.getYaw() * 256.0F / 360.0F)));
}
@Override
public Packet entityMount(int entityId, int vehicleId) {
return new SpPacket<>(new PacketPlayOutAttachEntity(entityId, vehicleId, false));
}
@Override
public Packet entityEquipment(
int entityId, ItemStack helmet, ItemStack chest, ItemStack legs, ItemStack feet) {
List<Packet> packets = new ArrayList<>();
if (helmet != null) packets.add(makeEquipment(entityId, EquipmentSlot.HEAD, helmet));
if (chest != null) packets.add(makeEquipment(entityId, EquipmentSlot.CHEST, chest));
if (legs != null) packets.add(makeEquipment(entityId, EquipmentSlot.LEGS, legs));
if (feet != null) packets.add(makeEquipment(entityId, EquipmentSlot.FEET, feet));
return Packet.of(packets.toArray(Packet[]::new));
}
@Override
public Packet entityHeadEquipment(int entityId, ItemStack helmet) {
return makeEquipment(entityId, EquipmentSlot.HEAD, helmet);
}
private Packet makeEquipment(int entityId, EquipmentSlot slot, ItemStack item) {
return new SpPacket<>(
new PacketPlayOutEntityEquipment(entityId, slot.ordinal(), CraftItemStack.asNMSCopy(item)));
}
@Override
public Packet entityMetadataPacket(int entityId, Entity entity, boolean complete) {
return new SpPacket<>(new PacketPlayOutEntityMetadata(
entityId,
((CraftEntity) entity).getHandle().getDataWatcher(),
complete)); // true = all values, false = only dirty values
}
private static class EntityMock extends net.minecraft.server.v1_8_R3.Entity {
private int id;
public EntityMock() {
super(null);
}
@Override
public int getId() {
return id;
}
public EntityMock withId(int id) {
this.id = id;
return this;
}
@Override
protected void h() {}
@Override
protected void a(NBTTagCompound nbtTagCompound) {}
@Override
protected void b(NBTTagCompound nbtTagCompound) {}
}
}
| 1 | 0.943034 | 1 | 0.943034 | game-dev | MEDIA | 0.972274 | game-dev | 0.950977 | 1 | 0.950977 |
ayufan/steam-deck-tools | 13,526 | SteamController/Profiles/Dynamic/Globals.cs | using Nefarius.ViGEm.Client.Targets.Xbox360;
using SteamController.ProfilesSettings;
namespace SteamController.Profiles.Dynamic
{
[Flags]
public enum KeyModifiers
{
MOD_None = 0,
MOD_SHIFT = 1,
MOD_ALT = 2,
MOD_CONTROL = 4,
MOD_WIN = 8
}
public class Globals
{
private const string Consumed = "RoslynGlobals";
private RoslynDynamicProfile _profile;
private Context _context;
public class SteamAPI
{
internal Devices.SteamController Target;
internal SteamAPI(Devices.SteamController target) { Target = target; }
public struct Button
{
internal Devices.SteamButton Target;
public static implicit operator bool(Button button) => button.Target;
public Button(Devices.SteamButton target) { Target = target; }
}
public struct Axis
{
internal Devices.SteamAxis Target;
internal short Deadzone;
public static implicit operator short(Axis button) => button.Target.GetValue(button.Deadzone);
public Axis(Devices.SteamAxis target, short deadzone = 0) { Target = target; Deadzone = deadzone; }
}
public Button BtnL5 { get => new Button(Target.BtnL5); }
public Button BtnOptions { get => new Button(Target.BtnOptions); }
public Button BtnSteam { get => new Button(Target.BtnSteam); }
public Button BtnMenu { get => new Button(Target.BtnMenu); }
public Button BtnDpadDown { get => new Button(Target.BtnDpadDown); }
public Button BtnDpadLeft { get => new Button(Target.BtnDpadLeft); }
public Button BtnDpadRight { get => new Button(Target.BtnDpadRight); }
public Button BtnDpadUp { get => new Button(Target.BtnDpadUp); }
public Button BtnA { get => new Button(Target.BtnA); }
public Button BtnX { get => new Button(Target.BtnX); }
public Button BtnB { get => new Button(Target.BtnB); }
public Button BtnY { get => new Button(Target.BtnY); }
public Button BtnL1 { get => new Button(Target.BtnL1); }
public Button BtnL2 { get => new Button(Target.BtnL2); }
public Button BtnR1 { get => new Button(Target.BtnR1); }
public Button BtnR2 { get => new Button(Target.BtnR2); }
public Button BtnLeftStickPress { get => new Button(Target.BtnLeftStickPress); }
public Button BtnLPadTouch { get => new Button(Target.BtnLPadTouch); }
public Button BtnLPadPress { get => new Button(Target.BtnLPadPress); }
public Button BtnRPadPress { get => new Button(Target.BtnRPadPress); }
public Button BtnRPadTouch { get => new Button(Target.BtnRPadTouch); }
public Button BtnR5 { get => new Button(Target.BtnR5); }
public Button BtnRightStickPress { get => new Button(Target.BtnRightStickPress); }
public Button BtnLStickTouch { get => new Button(Target.BtnLStickTouch); }
public Button BtnRStickTouch { get => new Button(Target.BtnRStickTouch); }
public Button BtnR4 { get => new Button(Target.BtnR4); }
public Button BtnL4 { get => new Button(Target.BtnL4); }
public Button BtnQuickAccess { get => new Button(Target.BtnQuickAccess); }
public Button BtnVirtualLeftThumbUp { get => new Button(Target.BtnVirtualLeftThumbUp); }
public Button BtnVirtualLeftThumbDown { get => new Button(Target.BtnVirtualLeftThumbDown); }
public Button BtnVirtualLeftThumbLeft { get => new Button(Target.BtnVirtualLeftThumbLeft); }
public Button BtnVirtualLeftThumbRight { get => new Button(Target.BtnVirtualLeftThumbRight); }
public Axis LPadX { get => new Axis(Target.LPadX); }
public Axis LPadY { get => new Axis(Target.LPadY); }
public Axis RPadX { get => new Axis(Target.RPadX); }
public Axis RPadY { get => new Axis(Target.RPadY); }
public Axis AccelX { get => new Axis(Target.AccelX); }
public Axis AccelY { get => new Axis(Target.AccelY); }
public Axis AccelZ { get => new Axis(Target.AccelZ); }
public Axis GyroPitch { get => new Axis(Target.GyroPitch); }
public Axis GyroYaw { get => new Axis(Target.GyroYaw); }
public Axis GyroRoll { get => new Axis(Target.GyroRoll); }
public Axis LeftTrigger { get => new Axis(Target.LeftTrigger); }
public Axis RightTrigger { get => new Axis(Target.RightTrigger); }
public Axis LeftThumbX { get => new Axis(Target.LeftThumbX, Settings.Default.JoystickDeadzone); }
public Axis LeftThumbY { get => new Axis(Target.LeftThumbY, Settings.Default.JoystickDeadzone); }
public Axis RightThumbX { get => new Axis(Target.RightThumbX, Settings.Default.JoystickDeadzone); }
public Axis RightThumbY { get => new Axis(Target.RightThumbY, Settings.Default.JoystickDeadzone); }
public Axis LPadPressure { get => new Axis(Target.LPadPressure); }
public Axis RPadPressure { get => new Axis(Target.RPadPressure); }
}
public class KeyboardAPI
{
internal Devices.KeyboardController Target;
internal KeyboardAPI(Devices.KeyboardController target) { Target = target; }
public bool this[VirtualKeyCode key]
{
get { return Target[key.ToWindowsInput()]; }
set { Target.Overwrite(key.ToWindowsInput(), value); }
}
public void KeyPress(params VirtualKeyCode[] keyCodes)
{
KeyPress(KeyModifiers.MOD_None, keyCodes);
}
public void KeyPress(KeyModifiers modifiers, params VirtualKeyCode[] keyCodes)
{
var virtualCodes = keyCodes.Select((code) => (WindowsInput.VirtualKeyCode)code).ToArray();
if (modifiers != KeyModifiers.MOD_None)
{
List<WindowsInput.VirtualKeyCode> modifierCodes = new List<WindowsInput.VirtualKeyCode>();
if (modifiers.HasFlag(KeyModifiers.MOD_SHIFT))
modifierCodes.Add(WindowsInput.VirtualKeyCode.SHIFT);
if (modifiers.HasFlag(KeyModifiers.MOD_CONTROL))
modifierCodes.Add(WindowsInput.VirtualKeyCode.CONTROL);
if (modifiers.HasFlag(KeyModifiers.MOD_ALT))
modifierCodes.Add(WindowsInput.VirtualKeyCode.MENU);
if (modifiers.HasFlag(KeyModifiers.MOD_WIN))
modifierCodes.Add(WindowsInput.VirtualKeyCode.LWIN);
Target.KeyPress(modifierCodes, virtualCodes);
}
else
{
Target.KeyPress(virtualCodes);
}
}
}
public class MouseAPI
{
internal Devices.MouseController Target;
internal MouseAPI(Devices.MouseController target) { Target = target; }
public struct Button
{
internal Devices.MouseController? Controller = null;
internal Devices.MouseController.Button Target = Devices.MouseController.Button.Left;
internal bool Value;
internal Button(Devices.MouseController controller, Devices.MouseController.Button target) { Controller = controller; Target = target; Value = Controller[Target]; }
internal Button(bool value) { this.Value = value; }
public void Click() { Controller?.MouseClick(Target); }
public void DoubleClick() { Controller?.MouseClick(Target); }
internal void Set(Button value) { Controller?.Overwrite(Target, value.Value); }
public static implicit operator Button(bool value) { return new Button(value); }
}
public Button BtnLeft { get => new Button(Target, Devices.MouseController.Button.Left); set => this.BtnLeft.Set(value); }
public Button BtnRight { get => new Button(Target, Devices.MouseController.Button.Right); set => this.BtnRight.Set(value); }
public Button BtnMiddle { get => new Button(Target, Devices.MouseController.Button.Middle); set => this.BtnMiddle.Set(value); }
public Button BtnX { get => new Button(Target, Devices.MouseController.Button.X); set => this.BtnX.Set(value); }
public Button BtnY { get => new Button(Target, Devices.MouseController.Button.Y); set => this.BtnY.Set(value); }
public void MoveBy(double pixelDeltaX, double pixelDeltaY) { Target.MoveBy(pixelDeltaX, pixelDeltaY); }
public void MoveTo(double absoluteX, double absoluteY) { Target.MoveTo(absoluteX, absoluteY); }
public void VerticalScroll(double scrollAmountInClicks) { Target.VerticalScroll(scrollAmountInClicks); }
public void HorizontalScroll(double scrollAmountInClicks) { Target.HorizontalScroll(scrollAmountInClicks); }
}
public class X360API
{
internal const int MinimumPresTimeMilliseconds = 30;
internal Devices.Xbox360Controller Target;
internal X360API(Devices.Xbox360Controller target) { Target = target; }
public bool Connected { set => Target.Connected = value; }
public bool BtnUp { set => Target.Overwrite(Xbox360Button.Up, value, MinimumPresTimeMilliseconds); }
public bool BtnDown { set => Target.Overwrite(Xbox360Button.Down, value, MinimumPresTimeMilliseconds); }
public bool BtnLeft { set => Target.Overwrite(Xbox360Button.Left, value, MinimumPresTimeMilliseconds); }
public bool BtnRight { set => Target.Overwrite(Xbox360Button.Right, value, MinimumPresTimeMilliseconds); }
public bool BtnA { set => Target.Overwrite(Xbox360Button.A, value, MinimumPresTimeMilliseconds); }
public bool BtnB { set => Target.Overwrite(Xbox360Button.B, value, MinimumPresTimeMilliseconds); }
public bool BtnX { set => Target.Overwrite(Xbox360Button.X, value, MinimumPresTimeMilliseconds); }
public bool BtnY { set => Target.Overwrite(Xbox360Button.Y, value, MinimumPresTimeMilliseconds); }
public bool BtnGuide { set => Target.Overwrite(Xbox360Button.Guide, value, MinimumPresTimeMilliseconds); }
public bool BtnBack { set => Target.Overwrite(Xbox360Button.Back, value, MinimumPresTimeMilliseconds); }
public bool BtnStart { set => Target.Overwrite(Xbox360Button.Start, value, MinimumPresTimeMilliseconds); }
public bool BtnLeftShoulder { set => Target.Overwrite(Xbox360Button.LeftShoulder, value, MinimumPresTimeMilliseconds); }
public bool BtnRightShoulder { set => Target.Overwrite(Xbox360Button.RightShoulder, value, MinimumPresTimeMilliseconds); }
public bool BtnLeftThumb { set => Target.Overwrite(Xbox360Button.LeftThumb, value, MinimumPresTimeMilliseconds); }
public bool BtnRightThumb { set => Target.Overwrite(Xbox360Button.RightThumb, value, MinimumPresTimeMilliseconds); }
public short AxisLeftThumbX { set => Target[Xbox360Axis.LeftThumbX] = value; }
public short AxisLeftThumbY { set => Target[Xbox360Axis.LeftThumbY] = value; }
public short AxisRightThumbX { set => Target[Xbox360Axis.RightThumbX] = value; }
public short AxisRightThumbY { set => Target[Xbox360Axis.RightThumbY] = value; }
public short SliderLeftTrigger { set => Target[Xbox360Slider.LeftTrigger] = value; }
public short SliderRightTrigger { set => Target[Xbox360Slider.RightTrigger] = value; }
}
private SteamAPI? _steamAPI;
private X360API? _x360API;
private KeyboardAPI? _keyboardAPI;
private MouseAPI? _mouseAPI;
public SteamAPI Steam { get => _steamAPI ??= new SteamAPI(_context.Steam); }
public X360API X360 { get => _x360API ??= new X360API(_context.X360); }
public KeyboardAPI Keyboard { get => _keyboardAPI ??= new KeyboardAPI(_context.Keyboard); }
public MouseAPI Mouse { get => _mouseAPI ??= new MouseAPI(_context.Mouse); }
public Globals(RoslynDynamicProfile profile, Context context)
{
this._profile = profile;
this._context = context;
}
public bool Pressed(SteamAPI.Button button)
{
return button.Target.Pressed();
}
public bool JustPressed(SteamAPI.Button button)
{
return button.Target.JustPressed();
}
public bool HoldFor(SteamAPI.Button button, int minTimeMs)
{
return button.Target.Hold(TimeSpan.FromMilliseconds(minTimeMs), null);
}
public bool Turbo(SteamAPI.Button button, int timesPerSec)
{
var interval = TimeSpan.FromMilliseconds(1000 / timesPerSec);
return button.Target.JustPressed() || button.Target.HoldRepeat(interval, interval, null);
}
public void Log(string format, params object?[] arg)
{
var output = String.Format(format, arg);
CommonHelpers.Log.TraceLine("{0}: {1}: {2}", _profile.Name, _context.Steam.ElapsedMilliseconds, output);
}
}
}
| 1 | 0.691281 | 1 | 0.691281 | game-dev | MEDIA | 0.783197 | game-dev | 0.698942 | 1 | 0.698942 |
alebcj/cs2-gsi-z | 1,409 | src/core/differs/PlayerDiffer.js | import { EVENTS } from '../../constants/events.js';
import { DifferBase } from './DifferBase.js';
export class PlayerDiffer extends DifferBase {
constructor({ logger = null } = {}) {
super();
this.logger = (logger ?? { child: () => console }).child('PlayerDiffer');
this.logger.log('⚙️ instantiated correctly.');
}
/**
* Compares main changes in the player (team, activity, observer slot) and emits events.
*
* @param {GameState} prev Previous game state
* @param {GameState} curr Current game state
* @param {Object} emitter Event emission context
* @param {Object} [options] Optional. Object with { previously, added } */
diff(prev, curr, emitter, options = {}) {
if (!prev?.player && !curr?.player) return;
const fields = [
{ path: 'player.team', event: EVENTS.player.teamChanged },
{ path: 'player.activity', event: EVENTS.player.activityChanged },
{ path: 'player.observerSlot', event: EVENTS.player.observerSlotChanged },
];
for (const { path, event } of fields) {
const prevVal = this.getFieldSafe(path, prev, this.previously);
const currVal = this.getFieldSafe(path, curr, this.added);
if (prevVal !== currVal) {
this.logger.log(`🔄 Change in ${path}: ${prevVal} → ${currVal}`);
this.emitWithContext(emitter, event, { previously: prevVal, current: currVal }, 'player');
}
}
}
}
| 1 | 0.914845 | 1 | 0.914845 | game-dev | MEDIA | 0.615224 | game-dev,web-frontend | 0.803933 | 1 | 0.803933 |
neoforged/NeoForge | 2,016 | patches/net/minecraft/nbt/CompoundTag.java.patch | --- a/net/minecraft/nbt/CompoundTag.java
+++ b/net/minecraft/nbt/CompoundTag.java
@@ -51,13 +_,19 @@
return compoundtag;
}
+ private static byte readNamedTagType(DataInput p_302338_, NbtAccounter p_302362_) throws IOException {
+ p_302362_.accountBytes(2);
+ return p_302338_.readByte();
+ }
+
private static CompoundTag loadCompound(DataInput p_302338_, NbtAccounter p_302362_) throws IOException {
p_302362_.accountBytes(48L);
Map<String, Tag> map = Maps.newHashMap();
byte b0;
- while ((b0 = p_302338_.readByte()) != 0) {
- String s = readString(p_302338_, p_302362_);
+ while((b0 = readNamedTagType(p_302338_, p_302362_)) != 0) {
+ String s = p_302362_.readUTF(p_302338_.readUTF());
+ p_302362_.accountBytes(4); //Forge: 4 extra bytes for the object allocation.
Tag tag = CompoundTag.readNamedTagData(TagTypes.getType(b0), s, p_302338_, p_302362_);
if (map.put(s, tag) == null) {
p_302362_.accountBytes(36L);
@@ -173,6 +_,17 @@
this(new HashMap<>());
}
+ /**
+ * Neo: create a compound tag that is generally suitable to hold the given amount of entries
+ * without needing to resize the internal map.
+ *
+ * @param expectedEntries the expected number of entries that the compound tag will have
+ * @see HashMap#newHashMap(int)
+ */
+ public CompoundTag(int expectedEntries) {
+ this(HashMap.newHashMap(expectedEntries));
+ }
+
@Override
public void write(DataOutput p_128341_) throws IOException {
for (String s : this.tags.keySet()) {
@@ -228,6 +_,7 @@
@Nullable
public Tag put(String p_128366_, Tag p_128367_) {
+ if (p_128367_ == null) throw new IllegalArgumentException("Invalid null NBT value with key " + p_128366_);
return this.tags.put(p_128366_, p_128367_);
}
| 1 | 0.752305 | 1 | 0.752305 | game-dev | MEDIA | 0.799787 | game-dev | 0.821904 | 1 | 0.821904 |
stalomeow/MinecraftClone-Unity | 6,710 | Assets/Scripts/Rendering/BlockMeshBuilder.cs | using System;
using Minecraft.Configurations;
using Minecraft.PhysicSystem;
using UnityEngine;
namespace Minecraft.Rendering
{
public class BlockMeshBuilder<TIndex> : MeshBuilder<BlockMeshVertexData, TIndex> where TIndex : unmanaged
{
public bool WriteBlockWSPosToVertexData { get; set; }
public bool EnableAmbientOcclusion { get; set; }
public bool EnableFaceClipping { get; set; }
public bool AggressiveBlockFaceClipping { get; set; }
public BlockMeshBuilder(int subMeshCount) : base(BlockMeshVertexData.VertexAttributes, subMeshCount) { }
public void AddBlock(Vector3Int pos, Vector3Int renderOffset, BlockData block, IWorldRAccessor accessor)
{
Quaternion rotation = accessor.GetBlockRotation(pos.x, pos.y, pos.z, Quaternion.identity);
BlockMesh mesh = accessor.World.BlockDataTable.GetMesh(block.Mesh.Value);
for (int i = 0; i < mesh.Faces.Length; i++)
{
BlockMesh.FaceData face = mesh.Faces[i];
BlockFace faceDir = RotateFace(face.Face, rotation);
if (EnableFaceClipping)
{
// 没有撑满一格的方块所有的面都渲染
Vector3 size = mesh.BoundingBox.Size;
bool neverClip = face.NeverClip | size.x < 1 | size.y < 1 | size.z < 1;
if (!neverClip && ClipFace(pos, block, faceDir, accessor))
{
continue;
}
}
int?[] texIndices = block.Textures[i];
// !!! must add indices first
for (int j = 0; j < face.Indices.Length; j++)
{
AddIndex(face.Indices[j], block.Material.Value);
}
for (int j = 0; j < face.Vertices.Length; j++)
{
BlockVertexData vertex = face.Vertices[j];
vertex.Position = MathUtility.RotatePoint(vertex.Position, rotation, mesh.Pivot);
float emission = block.GetEmissionValue();
Vector2 ambient = LightingUtility.AmbientOcclusion(pos, faceDir, vertex.CornerInFace, accessor, !EnableAmbientOcclusion);
Vector3 posWS = WriteBlockWSPosToVertexData ? (pos + accessor.WorldSpaceOrigin) : Vector3.down;
AddVertex(new BlockMeshVertexData
{
PositionOS = vertex.Position + pos + renderOffset,
UV = vertex.UV,
TexIndices = new Vector3Int(texIndices[0].Value, texIndices[1].Value, texIndices[2].Value),
Lights = new Vector3(emission, ambient.x, ambient.y),
BlockPositionWS = posWS
});
}
}
}
protected bool ClipFace(Vector3Int pos, BlockData block, BlockFace face, IWorldRAccessor accessor)
{
switch (face)
{
case BlockFace.PositiveX: pos.x++; break;
case BlockFace.PositiveY: pos.y++; break;
case BlockFace.PositiveZ: pos.z++; break;
case BlockFace.NegativeX: pos.x--; break;
case BlockFace.NegativeY: pos.y--; break;
case BlockFace.NegativeZ: pos.z--; break;
default: throw new NotSupportedException("Unknown BlockFace.");
}
BlockData neighbor = accessor.GetBlock(pos.x, pos.y, pos.z);
if (neighbor == null)
{
return AggressiveBlockFaceClipping;
}
BlockMesh mesh = accessor.World.BlockDataTable.GetMesh(neighbor.Mesh.Value);
Vector3 size = mesh.BoundingBox.Size;
if (size.x < 1 || size.y < 1 || size.z < 1)
{
return false;
}
switch (block.PhysicState)
{
case PhysicState.Fluid:
return (block == neighbor) || neighbor.IsOpaqueBlock();
case PhysicState.Solid:
return neighbor.IsOpaqueBlock();
default:
throw new NotSupportedException("Unknown BlockPhysicalState");
}
}
protected override Vector3 GetPositionOS(in BlockMeshVertexData vertex)
{
return vertex.PositionOS;
}
protected static BlockFace RotateFace(BlockFace face, Quaternion rotation)
{
if (rotation == Quaternion.identity)
{
return face;
}
Vector3 normal = face switch
{
BlockFace.PositiveX => Vector3.right,
BlockFace.PositiveY => Vector3.up,
BlockFace.PositiveZ => Vector3.forward,
BlockFace.NegativeX => Vector3.left,
BlockFace.NegativeY => Vector3.down,
BlockFace.NegativeZ => Vector3.back,
_ => throw new NotSupportedException("Unknown BlockFace.")
};
normal = Vector3.Normalize(rotation * normal).RoundToInt();
return normal switch
{
{ x: 1.0f, y: 0.0f, z: 0.0f } => BlockFace.PositiveX,
{ x: 0.0f, y: 1.0f, z: 0.0f } => BlockFace.PositiveY,
{ x: 0.0f, y: 0.0f, z: 1.0f } => BlockFace.PositiveZ,
{ x: -1.0f, y: 0.0f, z: 0.0f } => BlockFace.NegativeX,
{ x: 0.0f, y: -1.0f, z: 0.0f } => BlockFace.NegativeY,
{ x: 0.0f, y: 0.0f, z: -1.0f } => BlockFace.NegativeZ,
_ => throw new InvalidOperationException($"Invalid Rotation: {rotation.eulerAngles}.")
};
}
public static BlockMeshBuilder<TIndex> CreateBlockEntityMeshBuilder(bool ambientOcclusion)
{
return new BlockMeshBuilder<TIndex>(1)
{
WriteBlockWSPosToVertexData = false,
EnableAmbientOcclusion = ambientOcclusion,
EnableFaceClipping = false,
AggressiveBlockFaceClipping = false
};
}
public static BlockMeshBuilder<TIndex> CreateSectionMeshBuilder(int subMeshCount, bool ambientOcclusion, bool clipFace, bool aggressiveBlockFaceClipping)
{
return new BlockMeshBuilder<TIndex>(subMeshCount)
{
WriteBlockWSPosToVertexData = true,
EnableAmbientOcclusion = ambientOcclusion,
EnableFaceClipping = clipFace,
AggressiveBlockFaceClipping = aggressiveBlockFaceClipping
};
}
}
}
| 1 | 0.933395 | 1 | 0.933395 | game-dev | MEDIA | 0.783849 | game-dev,graphics-rendering | 0.987168 | 1 | 0.987168 |
dontpanic92/OpenPAL3 | 2,826 | yaobow/yaobow_editor/src/preview/panes/video_pane.rs | use crate::directors::DevToolsState;
use super::ContentPane;
use imgui::{Image, TextureId};
use radiance::{
audio::AudioEngine,
rendering::{ComponentFactory, VideoPlayer},
utils::SeekRead,
video::Codec,
video::VideoStreamState,
};
use std::{path::PathBuf, rc::Rc};
pub struct VideoPane {
video_player: Option<Box<VideoPlayer>>,
source_size: Option<(u32, u32)>,
texture_id: Option<TextureId>,
path: PathBuf,
}
impl VideoPane {
pub fn new(
factory: Rc<dyn ComponentFactory>,
audio_engine: Rc<dyn AudioEngine>,
reader: Box<dyn SeekRead>,
codec: Option<Codec>,
path: PathBuf,
) -> Self {
let mut source_size = None;
let video_player = codec.map(|c| {
let mut video_player = factory.create_video_player();
source_size = video_player.play(factory, audio_engine, reader, c, true);
video_player
});
Self {
video_player,
source_size,
texture_id: None,
path,
}
}
pub fn toggle_play_stop(&mut self) {
if let Some(video_player) = &mut self.video_player {
if video_player.get_state() == VideoStreamState::Playing {
video_player.pause();
} else {
video_player.resume();
}
}
}
}
impl ContentPane for VideoPane {
fn render(&mut self, ui: &imgui::Ui) -> Option<DevToolsState> {
if let Some((w, h)) = self.source_size {
ui.text(format!("Video: {}", self.path.to_str().unwrap()));
let video_player = self.video_player.as_ref().unwrap();
let label = if video_player.get_state() == VideoStreamState::Playing {
"Pause"
} else {
"Play"
};
if ui.button(label) {
self.toggle_play_stop();
}
let [avail_width, avail_height] = ui.content_region_avail();
let (w_scale, h_scale) = (avail_width / w as f32, avail_height / h as f32);
let scale = w_scale.min(h_scale);
let target_size = [w as f32 * scale, h as f32 * scale];
if let Some(texture_id) = self
.video_player
.as_mut()
.unwrap()
.get_texture(self.texture_id)
{
self.texture_id = Some(texture_id);
ui.set_cursor_pos([
ui.cursor_pos()[0] + (avail_width - target_size[0]) * 0.5,
ui.cursor_pos()[1] + (avail_height - target_size[1]) * 0.5,
]);
Image::new(texture_id, target_size).build(ui);
}
} else {
ui.text("Video format not supported");
}
None
}
}
| 1 | 0.756145 | 1 | 0.756145 | game-dev | MEDIA | 0.638963 | game-dev | 0.882107 | 1 | 0.882107 |
gomint/gomint | 3,042 | gomint-api/src/main/java/io/gomint/config/BaseConfig.java | /*
* Copyright (c) 2020 GoMint team
*
* This code is licensed under the BSD license found in the
* LICENSE file in the root directory of this source tree.
*/
package io.gomint.config;
import io.gomint.config.annotation.PreserveStatic;
import io.gomint.config.annotation.SerializeOptions;
import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* @author geNAZt
* @version 1.0
* @stability 3
*/
public class BaseConfig implements Serializable {
protected transient File configFile = null;
protected transient String[] configHeader = null;
protected transient ConfigMode configMode = ConfigMode.DEFAULT;
protected transient boolean skipFailedObjects = false;
protected transient InternalConverter converter = new InternalConverter( this );
/**
* This function gets called after the File has been loaded and before the converter gets it.
* This is used to manually edit the configSection when you updated the config or something
*
* @param section The root ConfigSection with all sub-nodes loaded into
*/
public void update( ConfigSection section ) {
/*
* This is a hook point for custom classes to overwrite when needed to specify a update path
*/
}
/**
* Add a Custom converter. A converter can take Objects and return a pretty Object which gets saved/loaded from
* the converter. How a converter must be build can be looked up in the converter Interface.
*
* @param converter converter to be added
* @throws InvalidConverterException If the converter has any errors this Exception tells you what
* @return base config for chaining
*/
public BaseConfig addConverter( Class<?> converter ) throws InvalidConverterException {
this.converter.addCustomConverter( converter );
return this;
}
protected void configureFromSerializeOptionsAnnotation() {
if ( !this.getClass().isAnnotationPresent( SerializeOptions.class ) ) {
return;
}
SerializeOptions options = this.getClass().getAnnotation( SerializeOptions.class );
this.configHeader = options.configHeader();
this.configMode = options.configMode();
this.skipFailedObjects = options.skipFailedObjects();
}
/**
* Check if we need to skip the given field
*
* @param field which may be skipped
* @return true when it should be skipped, false when not
*/
boolean doSkip( Field field ) {
if ( Modifier.isTransient( field.getModifiers() ) || Modifier.isFinal( field.getModifiers() ) ) {
return true;
}
if ( Modifier.isStatic( field.getModifiers() ) ) {
if ( !field.isAnnotationPresent( PreserveStatic.class ) ) {
return true;
}
PreserveStatic presStatic = field.getAnnotation( PreserveStatic.class );
return !presStatic.value();
}
return false;
}
}
| 1 | 0.934714 | 1 | 0.934714 | game-dev | MEDIA | 0.18899 | game-dev | 0.963166 | 1 | 0.963166 |
veywrn/StardewValley | 2,732 | Netcode/NetRectangle.cs | using Microsoft.Xna.Framework;
using System.IO;
namespace Netcode
{
public sealed class NetRectangle : NetField<Rectangle, NetRectangle>
{
public int X
{
get
{
return base.Value.X;
}
set
{
Rectangle rect = base.value;
if (rect.X != value)
{
Rectangle newValue = new Rectangle(value, rect.Y, rect.Width, rect.Height);
if (canShortcutSet())
{
base.value = newValue;
return;
}
cleanSet(newValue);
MarkDirty();
}
}
}
public int Y
{
get
{
return base.Value.Y;
}
set
{
Rectangle rect = base.value;
if (rect.Y != value)
{
Rectangle newValue = new Rectangle(rect.X, value, rect.Width, rect.Height);
if (canShortcutSet())
{
base.value = newValue;
return;
}
cleanSet(newValue);
MarkDirty();
}
}
}
public int Width
{
get
{
return base.Value.Width;
}
set
{
Rectangle rect = base.value;
if (rect.Width != value)
{
Rectangle newValue = new Rectangle(rect.X, rect.Y, value, rect.Height);
if (canShortcutSet())
{
base.value = newValue;
return;
}
cleanSet(newValue);
MarkDirty();
}
}
}
public int Height
{
get
{
return base.Value.Height;
}
set
{
Rectangle rect = base.value;
if (rect.Height != value)
{
Rectangle newValue = new Rectangle(rect.X, rect.Y, rect.Width, value);
if (canShortcutSet())
{
base.value = newValue;
return;
}
cleanSet(newValue);
MarkDirty();
}
}
}
public Point Center => value.Center;
public int Top => value.Top;
public int Bottom => value.Bottom;
public int Left => value.Left;
public int Right => value.Right;
public NetRectangle()
{
}
public NetRectangle(Rectangle value)
: base(value)
{
}
public void Set(int x, int y, int width, int height)
{
Set(new Rectangle(x, y, width, height));
}
public override void Set(Rectangle newValue)
{
if (canShortcutSet())
{
value = newValue;
}
else if (newValue != value)
{
cleanSet(newValue);
MarkDirty();
}
}
protected override void ReadDelta(BinaryReader reader, NetVersion version)
{
int newX = reader.ReadInt32();
int newY = reader.ReadInt32();
int newWidth = reader.ReadInt32();
int newHeight = reader.ReadInt32();
if (version.IsPriorityOver(ChangeVersion))
{
setInterpolationTarget(new Rectangle(newX, newY, newWidth, newHeight));
}
}
protected override void WriteDelta(BinaryWriter writer)
{
writer.Write(value.X);
writer.Write(value.Y);
writer.Write(value.Width);
writer.Write(value.Height);
}
}
}
| 1 | 0.811968 | 1 | 0.811968 | game-dev | MEDIA | 0.40123 | game-dev,graphics-rendering | 0.923616 | 1 | 0.923616 |
gurrhack/NetHack-Android | 34,452 | src/music.c | /* NetHack 3.6 music.c $NHDT-Date: 1573063606 2019/11/06 18:06:46 $ $NHDT-Branch: NetHack-3.6 $:$NHDT-Revision: 1.60 $ */
/* Copyright (c) 1989 by Jean-Christophe Collet */
/* NetHack may be freely redistributed. See license for details. */
/*
* This file contains the different functions designed to manipulate the
* musical instruments and their various effects.
*
* The list of instruments / effects is :
*
* (wooden) flute may calm snakes if player has enough dexterity
* magic flute may put monsters to sleep: area of effect depends
* on player level.
* (tooled) horn Will awaken monsters: area of effect depends on
* player level. May also scare monsters.
* fire horn Acts like a wand of fire.
* frost horn Acts like a wand of cold.
* bugle Will awaken soldiers (if any): area of effect depends
* on player level.
* (wooden) harp May calm nymph if player has enough dexterity.
* magic harp Charm monsters: area of effect depends on player
* level.
* (leather) drum Will awaken monsters like the horn.
* drum of earthquake Will initiate an earthquake whose intensity depends
* on player level. That is, it creates random pits
* called here chasms.
*/
#include "hack.h"
STATIC_DCL void FDECL(awaken_monsters, (int));
STATIC_DCL void FDECL(put_monsters_to_sleep, (int));
STATIC_DCL void FDECL(charm_snakes, (int));
STATIC_DCL void FDECL(calm_nymphs, (int));
STATIC_DCL void FDECL(charm_monsters, (int));
STATIC_DCL void FDECL(do_earthquake, (int));
STATIC_DCL int FDECL(do_improvisation, (struct obj *));
#ifdef UNIX386MUSIC
STATIC_DCL int NDECL(atconsole);
STATIC_DCL void FDECL(speaker, (struct obj *, char *));
#endif
#ifdef VPIX_MUSIC
extern int sco_flag_console; /* will need changing if not _M_UNIX */
STATIC_DCL void NDECL(playinit);
STATIC_DCL void FDECL(playstring, (char *, size_t));
STATIC_DCL void FDECL(speaker, (struct obj *, char *));
#endif
#ifdef PCMUSIC
void FDECL(pc_speaker, (struct obj *, char *));
#endif
#ifdef AMIGA
void FDECL(amii_speaker, (struct obj *, char *, int));
#endif
/*
* Wake every monster in range...
*/
STATIC_OVL void
awaken_monsters(distance)
int distance;
{
register struct monst *mtmp;
register int distm;
for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
if (DEADMONSTER(mtmp))
continue;
if ((distm = distu(mtmp->mx, mtmp->my)) < distance) {
mtmp->msleeping = 0;
mtmp->mcanmove = 1;
mtmp->mfrozen = 0;
/* may scare some monsters -- waiting monsters excluded */
if (!unique_corpstat(mtmp->data)
&& (mtmp->mstrategy & STRAT_WAITMASK) != 0)
mtmp->mstrategy &= ~STRAT_WAITMASK;
else if (distm < distance / 3
&& !resist(mtmp, TOOL_CLASS, 0, NOTELL)
/* some monsters are immune */
&& onscary(0, 0, mtmp))
monflee(mtmp, 0, FALSE, TRUE);
}
}
}
/*
* Make monsters fall asleep. Note that they may resist the spell.
*/
STATIC_OVL void
put_monsters_to_sleep(distance)
int distance;
{
register struct monst *mtmp;
for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
if (DEADMONSTER(mtmp))
continue;
if (distu(mtmp->mx, mtmp->my) < distance
&& sleep_monst(mtmp, d(10, 10), TOOL_CLASS)) {
mtmp->msleeping = 1; /* 10d10 turns + wake_nearby to rouse */
slept_monst(mtmp);
}
}
}
/*
* Charm snakes in range. Note that the snakes are NOT tamed.
*/
STATIC_OVL void
charm_snakes(distance)
int distance;
{
register struct monst *mtmp;
int could_see_mon, was_peaceful;
for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
if (DEADMONSTER(mtmp))
continue;
if (mtmp->data->mlet == S_SNAKE && mtmp->mcanmove
&& distu(mtmp->mx, mtmp->my) < distance) {
was_peaceful = mtmp->mpeaceful;
mtmp->mpeaceful = 1;
mtmp->mavenge = 0;
mtmp->mstrategy &= ~STRAT_WAITMASK;
could_see_mon = canseemon(mtmp);
mtmp->mundetected = 0;
newsym(mtmp->mx, mtmp->my);
if (canseemon(mtmp)) {
if (!could_see_mon)
You("notice %s, swaying with the music.", a_monnam(mtmp));
else
pline("%s freezes, then sways with the music%s.",
Monnam(mtmp),
was_peaceful ? "" : ", and now seems quieter");
}
}
}
}
/*
* Calm nymphs in range.
*/
STATIC_OVL void
calm_nymphs(distance)
int distance;
{
register struct monst *mtmp;
for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
if (DEADMONSTER(mtmp))
continue;
if (mtmp->data->mlet == S_NYMPH && mtmp->mcanmove
&& distu(mtmp->mx, mtmp->my) < distance) {
mtmp->msleeping = 0;
mtmp->mpeaceful = 1;
mtmp->mavenge = 0;
mtmp->mstrategy &= ~STRAT_WAITMASK;
if (canseemon(mtmp))
pline(
"%s listens cheerfully to the music, then seems quieter.",
Monnam(mtmp));
}
}
}
/* Awake soldiers anywhere the level (and any nearby monster). */
void
awaken_soldiers(bugler)
struct monst *bugler; /* monster that played instrument */
{
register struct monst *mtmp;
int distance, distm;
/* distance of affected non-soldier monsters to bugler */
distance = ((bugler == &youmonst) ? u.ulevel : bugler->data->mlevel) * 30;
for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
if (DEADMONSTER(mtmp))
continue;
if (is_mercenary(mtmp->data) && mtmp->data != &mons[PM_GUARD]) {
mtmp->mpeaceful = mtmp->msleeping = mtmp->mfrozen = 0;
mtmp->mcanmove = 1;
mtmp->mstrategy &= ~STRAT_WAITMASK;
if (canseemon(mtmp))
pline("%s is now ready for battle!", Monnam(mtmp));
else if (!Deaf)
Norep("%s the rattle of battle gear being readied.",
"You hear"); /* Deaf-aware */
} else if ((distm = ((bugler == &youmonst)
? distu(mtmp->mx, mtmp->my)
: dist2(bugler->mx, bugler->my, mtmp->mx,
mtmp->my))) < distance) {
mtmp->msleeping = 0;
mtmp->mcanmove = 1;
mtmp->mfrozen = 0;
/* may scare some monsters -- waiting monsters excluded */
if (!unique_corpstat(mtmp->data)
&& (mtmp->mstrategy & STRAT_WAITMASK) != 0)
mtmp->mstrategy &= ~STRAT_WAITMASK;
else if (distm < distance / 3
&& !resist(mtmp, TOOL_CLASS, 0, NOTELL))
monflee(mtmp, 0, FALSE, TRUE);
}
}
}
/* Charm monsters in range. Note that they may resist the spell.
* If swallowed, range is reduced to 0.
*/
STATIC_OVL void
charm_monsters(distance)
int distance;
{
struct monst *mtmp, *mtmp2;
if (u.uswallow) {
if (!resist(u.ustuck, TOOL_CLASS, 0, NOTELL))
(void) tamedog(u.ustuck, (struct obj *) 0);
} else {
for (mtmp = fmon; mtmp; mtmp = mtmp2) {
mtmp2 = mtmp->nmon;
if (DEADMONSTER(mtmp))
continue;
if (distu(mtmp->mx, mtmp->my) <= distance) {
if (!resist(mtmp, TOOL_CLASS, 0, NOTELL))
(void) tamedog(mtmp, (struct obj *) 0);
}
}
}
}
/* Generate earthquake :-) of desired force.
* That is: create random chasms (pits).
*/
STATIC_OVL void
do_earthquake(force)
int force;
{
register int x, y;
struct monst *mtmp;
struct obj *otmp;
struct trap *chasm, *trap_at_u = t_at(u.ux, u.uy);
int start_x, start_y, end_x, end_y;
schar filltype;
unsigned tu_pit = 0;
if (trap_at_u)
tu_pit = is_pit(trap_at_u->ttyp);
start_x = u.ux - (force * 2);
start_y = u.uy - (force * 2);
end_x = u.ux + (force * 2);
end_y = u.uy + (force * 2);
start_x = max(start_x, 1);
start_y = max(start_y, 0);
end_x = min(end_x, COLNO - 1);
end_y = min(end_y, ROWNO - 1);
for (x = start_x; x <= end_x; x++)
for (y = start_y; y <= end_y; y++) {
if ((mtmp = m_at(x, y)) != 0) {
wakeup(mtmp, TRUE); /* peaceful monster will become hostile */
if (mtmp->mundetected && is_hider(mtmp->data)) {
mtmp->mundetected = 0;
if (cansee(x, y))
pline("%s is shaken loose from the ceiling!",
Amonnam(mtmp));
else
You_hear("a thumping sound.");
if (x == u.ux && y == u.uy)
You("easily dodge the falling %s.", mon_nam(mtmp));
newsym(x, y);
}
}
if (!rn2(14 - force))
switch (levl[x][y].typ) {
case FOUNTAIN: /* Make the fountain disappear */
if (cansee(x, y))
pline_The("fountain falls into a chasm.");
goto do_pit;
case SINK:
if (cansee(x, y))
pline_The("kitchen sink falls into a chasm.");
goto do_pit;
case ALTAR:
if (Is_astralevel(&u.uz) || Is_sanctum(&u.uz))
break;
if (cansee(x, y))
pline_The("altar falls into a chasm.");
goto do_pit;
case GRAVE:
if (cansee(x, y))
pline_The("headstone topples into a chasm.");
goto do_pit;
case THRONE:
if (cansee(x, y))
pline_The("throne falls into a chasm.");
/*FALLTHRU*/
case ROOM:
case CORR: /* Try to make a pit */
do_pit:
chasm = maketrap(x, y, PIT);
if (!chasm)
break; /* no pit if portal at that location */
chasm->tseen = 1;
/* TODO:
* This ought to be split into a separate routine to
* reduce indentation and the consequent line-wraps.
*/
levl[x][y].doormask = 0;
/*
* Let liquid flow into the newly created chasm.
* Adjust corresponding code in apply.c for
* exploding wand of digging if you alter this sequence.
*/
filltype = fillholetyp(x, y, FALSE);
if (filltype != ROOM) {
levl[x][y].typ = filltype; /* flags set via doormask */
liquid_flow(x, y, filltype, chasm, (char *) 0);
}
mtmp = m_at(x, y);
if ((otmp = sobj_at(BOULDER, x, y)) != 0) {
if (cansee(x, y))
pline("KADOOM! The boulder falls into a chasm%s!",
(x == u.ux && y == u.uy) ? " below you"
: "");
if (mtmp)
mtmp->mtrapped = 0;
obj_extract_self(otmp);
(void) flooreffects(otmp, x, y, "");
break;
}
/* We have to check whether monsters or player
falls in a chasm... */
if (mtmp) {
if (!is_flyer(mtmp->data)
&& !is_clinger(mtmp->data)) {
boolean m_already_trapped = mtmp->mtrapped;
mtmp->mtrapped = 1;
if (!m_already_trapped) { /* suppress messages */
if (cansee(x, y))
pline("%s falls into a chasm!",
Monnam(mtmp));
else if (humanoid(mtmp->data))
You_hear("a scream!");
}
/* Falling is okay for falling down
within a pit from jostling too */
mselftouch(mtmp, "Falling, ", TRUE);
if (!DEADMONSTER(mtmp)) {
mtmp->mhp -= rnd(m_already_trapped ? 4 : 6);
if (DEADMONSTER(mtmp)) {
if (!cansee(x, y)) {
pline("It is destroyed!");
} else {
You("destroy %s!",
mtmp->mtame
? x_monnam(mtmp, ARTICLE_THE,
"poor",
has_mname(mtmp)
? SUPPRESS_SADDLE
: 0,
FALSE)
: mon_nam(mtmp));
}
xkilled(mtmp, XKILL_NOMSG);
}
}
}
} else if (x == u.ux && y == u.uy) {
if (u.utrap && u.utraptype == TT_BURIEDBALL) {
/* Note: the chain should break if a pit gets
created at the buried ball's location, which
is not necessarily here. But if we don't do
things this way, entering the new pit below
will override current trap anyway, but too
late to get Lev and Fly handling. */
Your("chain breaks!");
reset_utrap(TRUE);
}
if (Levitation || Flying
|| is_clinger(youmonst.data)) {
if (!tu_pit) { /* no pit here previously */
pline("A chasm opens up under you!");
You("don't fall in!");
}
} else if (!tu_pit || !u.utrap
|| (u.utrap && u.utraptype != TT_PIT)) {
/* no pit here previously, or you were
not in it even if there was */
You("fall into a chasm!");
set_utrap(rn1(6, 2), TT_PIT);
losehp(Maybe_Half_Phys(rnd(6)),
"fell into a chasm", NO_KILLER_PREFIX);
selftouch("Falling, you");
} else if (u.utrap && u.utraptype == TT_PIT) {
boolean keepfooting =
((Fumbling && !rn2(5))
|| (!rnl(Role_if(PM_ARCHEOLOGIST) ? 3 : 9))
|| ((ACURR(A_DEX) > 7) && rn2(5)));
You("are jostled around violently!");
set_utrap(rn1(6, 2), TT_PIT);
losehp(Maybe_Half_Phys(rnd(keepfooting ? 2 : 4)),
"hurt in a chasm", NO_KILLER_PREFIX);
if (keepfooting)
exercise(A_DEX, TRUE);
else
selftouch(
(Upolyd && (slithy(youmonst.data)
|| nolimbs(youmonst.data)))
? "Shaken, you"
: "Falling down, you");
}
} else
newsym(x, y);
break;
case DOOR: /* Make the door collapse */
if (levl[x][y].doormask == D_NODOOR)
goto do_pit;
if (cansee(x, y))
pline_The("door collapses.");
if (*in_rooms(x, y, SHOPBASE))
add_damage(x, y, 0L);
levl[x][y].doormask = D_NODOOR;
unblock_point(x, y);
newsym(x, y);
break;
}
}
}
const char *
generic_lvl_desc()
{
if (Is_astralevel(&u.uz))
return "astral plane";
else if (In_endgame(&u.uz))
return "plane";
else if (Is_sanctum(&u.uz))
return "sanctum";
else if (In_sokoban(&u.uz))
return "puzzle";
else if (In_V_tower(&u.uz))
return "tower";
else
return "dungeon";
}
const char *beats[] = {
"stepper", "one drop", "slow two", "triple stroke roll",
"double shuffle", "half-time shuffle", "second line", "train"
};
/*
* The player is trying to extract something from his/her instrument.
*/
STATIC_OVL int
do_improvisation(instr)
struct obj *instr;
{
int damage, mode, do_spec = !(Stunned || Confusion);
struct obj itmp;
boolean mundane = FALSE;
itmp = *instr;
itmp.oextra = (struct oextra *) 0; /* ok on this copy as instr maintains
the ptr to free at some point if
there is one */
/* if won't yield special effect, make sound of mundane counterpart */
if (!do_spec || instr->spe <= 0)
while (objects[itmp.otyp].oc_magic) {
itmp.otyp -= 1;
mundane = TRUE;
}
#ifdef MAC
mac_speaker(&itmp, "C");
#endif
#ifdef AMIGA
amii_speaker(&itmp, "Cw", AMII_OKAY_VOLUME);
#endif
#ifdef VPIX_MUSIC
if (sco_flag_console)
speaker(&itmp, "C");
#endif
#ifdef PCMUSIC
pc_speaker(&itmp, "C");
#endif
#define PLAY_NORMAL 0x00
#define PLAY_STUNNED 0x01
#define PLAY_CONFUSED 0x02
#define PLAY_HALLU 0x04
mode = PLAY_NORMAL;
if (Stunned)
mode |= PLAY_STUNNED;
if (Confusion)
mode |= PLAY_CONFUSED;
if (Hallucination)
mode |= PLAY_HALLU;
if (!rn2(2)) {
/*
* TEMPORARY? for multiple impairments, don't always
* give the generic "it's far from music" message.
*/
/* remove if STUNNED+CONFUSED ever gets its own message below */
if (mode == (PLAY_STUNNED | PLAY_CONFUSED))
mode = !rn2(2) ? PLAY_STUNNED : PLAY_CONFUSED;
/* likewise for stunned and/or confused combined with hallucination */
if (mode & PLAY_HALLU)
mode = PLAY_HALLU;
}
/* 3.6.3: most of these gave "You produce <blah>" and then many of
the instrument-specific messages below which immediately follow
also gave "You produce <something>." That looked strange so we
now use a different verb here */
switch (mode) {
case PLAY_NORMAL:
You("start playing %s.", yname(instr));
break;
case PLAY_STUNNED:
if (!Deaf)
You("radiate an obnoxious droning sound.");
else
You_feel("a monotonous vibration.");
break;
case PLAY_CONFUSED:
if (!Deaf)
You("generate a raucous noise.");
else
You_feel("a jarring vibration.");
break;
case PLAY_HALLU:
You("disseminate a kaleidoscopic display of floating butterflies.");
break;
/* TODO? give some or all of these combinations their own feedback;
hallucination ones should reference senses other than hearing... */
case PLAY_STUNNED | PLAY_CONFUSED:
case PLAY_STUNNED | PLAY_HALLU:
case PLAY_CONFUSED | PLAY_HALLU:
case PLAY_STUNNED | PLAY_CONFUSED | PLAY_HALLU:
default:
pline("What you perform is quite far from music...");
break;
}
#undef PLAY_NORMAL
#undef PLAY_STUNNED
#undef PLAY_CONFUSED
#undef PLAY_HALLU
switch (itmp.otyp) { /* note: itmp.otyp might differ from instr->otyp */
case MAGIC_FLUTE: /* Make monster fall asleep */
consume_obj_charge(instr, TRUE);
You("%sproduce %s music.", !Deaf ? "" : "seem to ",
Hallucination ? "piped" : "soft");
put_monsters_to_sleep(u.ulevel * 5);
exercise(A_DEX, TRUE);
break;
case WOODEN_FLUTE: /* May charm snakes */
do_spec &= (rn2(ACURR(A_DEX)) + u.ulevel > 25);
if (!Deaf)
pline("%s.", Tobjnam(instr, do_spec ? "trill" : "toot"));
else
You_feel("%s %s.", yname(instr), do_spec ? "trill" : "toot");
if (do_spec)
charm_snakes(u.ulevel * 3);
exercise(A_DEX, TRUE);
break;
case FIRE_HORN: /* Idem wand of fire */
case FROST_HORN: /* Idem wand of cold */
consume_obj_charge(instr, TRUE);
if (!getdir((char *) 0)) {
pline("%s.", Tobjnam(instr, "vibrate"));
break;
} else if (!u.dx && !u.dy && !u.dz) {
if ((damage = zapyourself(instr, TRUE)) != 0) {
char buf[BUFSZ];
Sprintf(buf, "using a magical horn on %sself", uhim());
losehp(damage, buf, KILLED_BY); /* fire or frost damage */
}
} else {
buzz((instr->otyp == FROST_HORN) ? AD_COLD - 1 : AD_FIRE - 1,
rn1(6, 6), u.ux, u.uy, u.dx, u.dy);
}
makeknown(instr->otyp);
break;
case TOOLED_HORN: /* Awaken or scare monsters */
if (!Deaf)
You("produce a frightful, grave sound.");
else
You("blow into the horn.");
awaken_monsters(u.ulevel * 30);
exercise(A_WIS, FALSE);
break;
case BUGLE: /* Awaken & attract soldiers */
if (!Deaf)
You("extract a loud noise from %s.", yname(instr));
else
You("blow into the bugle.");
awaken_soldiers(&youmonst);
exercise(A_WIS, FALSE);
break;
case MAGIC_HARP: /* Charm monsters */
consume_obj_charge(instr, TRUE);
if (!Deaf)
pline("%s very attractive music.", Tobjnam(instr, "produce"));
else
You_feel("very soothing vibrations.");
charm_monsters((u.ulevel - 1) / 3 + 1);
exercise(A_DEX, TRUE);
break;
case WOODEN_HARP: /* May calm Nymph */
do_spec &= (rn2(ACURR(A_DEX)) + u.ulevel > 25);
if (!Deaf)
pline("%s %s.", Yname2(instr),
do_spec ? "produces a lilting melody" : "twangs");
else
You_feel("soothing vibrations.");
if (do_spec)
calm_nymphs(u.ulevel * 3);
exercise(A_DEX, TRUE);
break;
case DRUM_OF_EARTHQUAKE: /* create several pits */
/* a drum of earthquake does not cause deafness
while still magically functional, nor afterwards
when it invokes the LEATHER_DRUM case instead and
mundane is flagged */
consume_obj_charge(instr, TRUE);
You("produce a heavy, thunderous rolling!");
pline_The("entire %s is shaking around you!", generic_lvl_desc());
do_earthquake((u.ulevel - 1) / 3 + 1);
/* shake up monsters in a much larger radius... */
awaken_monsters(ROWNO * COLNO);
makeknown(DRUM_OF_EARTHQUAKE);
break;
case LEATHER_DRUM: /* Awaken monsters */
if (!mundane) {
if (!Deaf) {
You("beat a deafening row!");
incr_itimeout(&HDeaf, rn1(20, 30));
} else {
You("pound on the drum.");
}
exercise(A_WIS, FALSE);
} else
You("%s %s.",
rn2(2) ? "butcher" : rn2(2) ? "manage" : "pull off",
an(beats[rn2(SIZE(beats))]));
awaken_monsters(u.ulevel * (mundane ? 5 : 40));
context.botl = TRUE;
break;
default:
impossible("What a weird instrument (%d)!", instr->otyp);
return 0;
}
return 2; /* That takes time */
}
/*
* So you want music...
*/
int
do_play_instrument(instr)
struct obj *instr;
{
char buf[BUFSZ] = DUMMY, c = 'y';
char *s;
int x, y;
boolean ok;
if (Underwater) {
You_cant("play music underwater!");
return 0;
} else if ((instr->otyp == WOODEN_FLUTE || instr->otyp == MAGIC_FLUTE
|| instr->otyp == TOOLED_HORN || instr->otyp == FROST_HORN
|| instr->otyp == FIRE_HORN || instr->otyp == BUGLE)
&& !can_blow(&youmonst)) {
You("are incapable of playing %s.", the(distant_name(instr, xname)));
return 0;
}
if (instr->otyp != LEATHER_DRUM && instr->otyp != DRUM_OF_EARTHQUAKE
&& !(Stunned || Confusion || Hallucination)) {
c = ynq("Improvise?");
if (c == 'q')
goto nevermind;
}
if (c == 'n') {
if (u.uevent.uheard_tune == 2)
c = ynq("Play the passtune?");
if (c == 'q') {
goto nevermind;
} else if (c == 'y') {
Strcpy(buf, tune);
} else {
getlin("What tune are you playing? [5 notes, A-G]", buf);
(void) mungspaces(buf);
if (*buf == '\033')
goto nevermind;
/* convert to uppercase and change any "H" to the expected "B" */
for (s = buf; *s; s++) {
#ifndef AMIGA
*s = highc(*s);
#else
/* The AMIGA supports two octaves of notes */
if (*s == 'h')
*s = 'b';
#endif
if (*s == 'H')
*s = 'B';
}
}
You(!Deaf ? "extract a strange sound from %s!"
: "can feel %s emitting vibrations.", the(xname(instr)));
#ifdef UNIX386MUSIC
/* if user is at the console, play through the console speaker */
if (atconsole())
speaker(instr, buf);
#endif
#ifdef VPIX_MUSIC
if (sco_flag_console)
speaker(instr, buf);
#endif
#ifdef MAC
mac_speaker(instr, buf);
#endif
#ifdef PCMUSIC
pc_speaker(instr, buf);
#endif
#ifdef AMIGA
{
char nbuf[20];
int i;
for (i = 0; buf[i] && i < 5; ++i) {
nbuf[i * 2] = buf[i];
nbuf[(i * 2) + 1] = 'h';
}
nbuf[i * 2] = 0;
amii_speaker(instr, nbuf, AMII_OKAY_VOLUME);
}
#endif
/* Check if there was the Stronghold drawbridge near
* and if the tune conforms to what we're waiting for.
*/
if (Is_stronghold(&u.uz)) {
exercise(A_WIS, TRUE); /* just for trying */
if (!strcmp(buf, tune)) {
/* Search for the drawbridge */
for (y = u.uy - 1; y <= u.uy + 1; y++)
for (x = u.ux - 1; x <= u.ux + 1; x++)
if (isok(x, y))
if (find_drawbridge(&x, &y)) {
/* tune now fully known */
u.uevent.uheard_tune = 2;
if (levl[x][y].typ == DRAWBRIDGE_DOWN)
close_drawbridge(x, y);
else
open_drawbridge(x, y);
return 1;
}
} else if (!Deaf) {
if (u.uevent.uheard_tune < 1)
u.uevent.uheard_tune = 1;
/* Okay, it wasn't the right tune, but perhaps
* we can give the player some hints like in the
* Mastermind game */
ok = FALSE;
for (y = u.uy - 1; y <= u.uy + 1 && !ok; y++)
for (x = u.ux - 1; x <= u.ux + 1 && !ok; x++)
if (isok(x, y))
if (IS_DRAWBRIDGE(levl[x][y].typ)
|| is_drawbridge_wall(x, y) >= 0)
ok = TRUE;
if (ok) { /* There is a drawbridge near */
int tumblers, gears;
boolean matched[5];
tumblers = gears = 0;
for (x = 0; x < 5; x++)
matched[x] = FALSE;
for (x = 0; x < (int) strlen(buf); x++)
if (x < 5) {
if (buf[x] == tune[x]) {
gears++;
matched[x] = TRUE;
} else {
for (y = 0; y < 5; y++)
if (!matched[y] && buf[x] == tune[y]
&& buf[y] != tune[y]) {
tumblers++;
matched[y] = TRUE;
break;
}
}
}
if (tumblers) {
if (gears)
You_hear("%d tumbler%s click and %d gear%s turn.",
tumblers, plur(tumblers), gears,
plur(gears));
else
You_hear("%d tumbler%s click.", tumblers,
plur(tumblers));
} else if (gears) {
You_hear("%d gear%s turn.", gears, plur(gears));
/* could only get `gears == 5' by playing five
correct notes followed by excess; otherwise,
tune would have matched above */
if (gears == 5)
u.uevent.uheard_tune = 2;
}
}
}
}
return 1;
} else
return do_improvisation(instr);
nevermind:
pline1(Never_mind);
return 0;
}
#ifdef UNIX386MUSIC
/*
* Play audible music on the machine's speaker if appropriate.
*/
STATIC_OVL int
atconsole()
{
/*
* Kluge alert: This code assumes that your [34]86 has no X terminals
* attached and that the console tty type is AT386 (this is always true
* under AT&T UNIX for these boxen). The theory here is that your remote
* ttys will have terminal type `ansi' or something else other than
* `AT386' or `xterm'. We'd like to do better than this, but testing
* to see if we're running on the console physical terminal is quite
* difficult given the presence of virtual consoles and other modern
* UNIX impedimenta...
*/
char *termtype = nh_getenv("TERM");
return (!strcmp(termtype, "AT386") || !strcmp(termtype, "xterm"));
}
STATIC_OVL void
speaker(instr, buf)
struct obj *instr;
char *buf;
{
/*
* For this to work, you need to have installed the PD speaker-control
* driver for PC-compatible UNIX boxes that I (esr@snark.thyrsus.com)
* posted to comp.sources.unix in Feb 1990. A copy should be included
* with your nethack distribution.
*/
int fd;
if ((fd = open("/dev/speaker", 1)) != -1) {
/* send a prefix to modify instrumental `timbre' */
switch (instr->otyp) {
case WOODEN_FLUTE:
case MAGIC_FLUTE:
(void) write(fd, ">ol", 1); /* up one octave & lock */
break;
case TOOLED_HORN:
case FROST_HORN:
case FIRE_HORN:
(void) write(fd, "<<ol", 2); /* drop two octaves & lock */
break;
case BUGLE:
(void) write(fd, "ol", 2); /* octave lock */
break;
case WOODEN_HARP:
case MAGIC_HARP:
(void) write(fd, "l8mlol", 4); /* fast, legato, octave lock */
break;
}
(void) write(fd, buf, strlen(buf));
(void) nhclose(fd);
}
}
#endif /* UNIX386MUSIC */
#ifdef VPIX_MUSIC
#if 0
#include <sys/types.h>
#include <sys/console.h>
#include <sys/vtkd.h>
#else
#define KIOC ('K' << 8)
#define KDMKTONE (KIOC | 8)
#endif
#define noDEBUG
/* emit tone of frequency hz for given number of ticks */
STATIC_OVL void
tone(hz, ticks)
unsigned int hz, ticks;
{
ioctl(0, KDMKTONE, hz | ((ticks * 10) << 16));
#ifdef DEBUG
printf("TONE: %6d %6d\n", hz, ticks * 10);
#endif
nap(ticks * 10);
}
/* rest for given number of ticks */
STATIC_OVL void
rest(ticks)
int ticks;
{
nap(ticks * 10);
#ifdef DEBUG
printf("REST: %6d\n", ticks * 10);
#endif
}
#include "interp.c" /* from snd86unx.shr */
STATIC_OVL void
speaker(instr, buf)
struct obj *instr;
char *buf;
{
/* emit a prefix to modify instrumental `timbre' */
playinit();
switch (instr->otyp) {
case WOODEN_FLUTE:
case MAGIC_FLUTE:
playstring(">ol", 1); /* up one octave & lock */
break;
case TOOLED_HORN:
case FROST_HORN:
case FIRE_HORN:
playstring("<<ol", 2); /* drop two octaves & lock */
break;
case BUGLE:
playstring("ol", 2); /* octave lock */
break;
case WOODEN_HARP:
case MAGIC_HARP:
playstring("l8mlol", 4); /* fast, legato, octave lock */
break;
}
playstring(buf, strlen(buf));
}
#ifdef VPIX_DEBUG
main(argc, argv)
int argc;
char *argv[];
{
if (argc == 2) {
playinit();
playstring(argv[1], strlen(argv[1]));
}
}
#endif
#endif /* VPIX_MUSIC */
/*music.c*/
| 1 | 0.950468 | 1 | 0.950468 | game-dev | MEDIA | 0.860502 | game-dev | 0.998651 | 1 | 0.998651 |
ragemp-pro/redage_v3 | 4,142 | dotnet/resources/NeptuneEvo/Organizations/Table/Settings/Repository.cs | using System;
using System.Linq;
using GTANetworkAPI;
using Localization;
using NeptuneEvo.Handles;
using NeptuneEvo.Organizations.Models;
using NeptuneEvo.Organizations.Player;
using NeptuneEvo.Players;
using NeptuneEvo.Table.Models;
using Redage.SDK;
namespace NeptuneEvo.Organizations.Table.Settings
{
public class Repository
{
public static void UpdateStock(ExtPlayer player)
{
try
{
if (!player.IsOrganizationAccess(RankToAccess.OpenStock)) return;
var organizationData = player.GetOrganizationData();
if (organizationData == null)
return;
organizationData.IsOpenStock = !organizationData.IsOpenStock;
if (organizationData.IsOpenStock)
{
Notify.Send(player, NotifyType.Success, NotifyPosition.BottomCenter, "Вы открыли склад семьи",
3000);
Organizations.Table.Logs.Repository.AddLogs(player, OrganizationLogsType.OpenStock, "Открыл склад");
}
else
{
Notify.Send(player, NotifyType.Success, NotifyPosition.BottomCenter, "Вы закрыли склад семьи", 3000);
Organizations.Table.Logs.Repository.AddLogs(player, OrganizationLogsType.CloseStock, "Закрыл склад");
}
Trigger.ClientEvent(player, "client.org.main.isStock", organizationData.IsOpenStock);
}
catch (Exception e)
{
Debugs.Repository.Exception(e);
}
}
public static void SaveSetting(ExtPlayer player, string slogan, byte salary, string discord, int colorR, int colorG, int colorB)
{
try
{
var sessionData = player.GetSessionData();
if (sessionData == null)
return;
if (DateTime.Now < sessionData.TimingsData.NextGlobalChat)
{
Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, LangFunc.GetText(LangType.Ru, DataName.Block10Min), 4500);
return;
}
var organizationData = player.GetOrganizationData();
if (organizationData == null)
return;
if (!organizationData.IsLeader(player.GetUUID()))
return;
slogan = Main.BlockSymbols(Main.RainbowExploit(slogan));
if (slogan.Length > 65)
{
Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Слоган слишком длинный", 4500);
return;
}
string testmsg = slogan.ToLower();
if (Main.stringGlobalBlock.Any(c => testmsg.Contains(c)))
{
sessionData.TimingsData.NextGlobalChat = DateTime.Now.AddMinutes(10);
Trigger.SendToAdmins(3, "!{#636363}[A] " + LangFunc.GetText(LangType.Ru, DataName.AdminAlertFTableNews, player.Name, player.Value, slogan));
Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, LangFunc.GetText(LangType.Ru, DataName.RestrictedWordsTableNews), 15000);
return;
}
organizationData.Slogan = slogan;
if (salary > 3)
salary = 3;
organizationData.Salary = salary;
organizationData.Discord = discord;
if (colorR != -1)
organizationData.Color = new Color(colorR, colorG, colorB);
organizationData.SaveSettings();
Table.Player.Repository.MainLoad(player);
}
catch (Exception e)
{
Debugs.Repository.Exception(e);
}
}
}
} | 1 | 0.860692 | 1 | 0.860692 | game-dev | MEDIA | 0.443256 | game-dev | 0.790257 | 1 | 0.790257 |
McJtyMods/RFTools | 5,697 | src/main/java/mcjty/rftools/blocks/storage/LevelEmitterBlock.java | package mcjty.rftools.blocks.storage;
import mcjty.lib.api.IModuleSupport;
import mcjty.lib.blocks.LogicSlabBlock;
import mcjty.lib.gui.GenericGuiContainer;
import mcjty.lib.varia.ModuleSupport;
import mcjty.rftools.RFTools;
import mcjty.rftools.blocks.screens.ScreenSetup;
import mcjty.rftools.setup.GuiProxy;
import mcjty.theoneprobe.api.ElementAlignment;
import mcjty.theoneprobe.api.IProbeHitData;
import mcjty.theoneprobe.api.IProbeInfo;
import mcjty.theoneprobe.api.ProbeMode;
import mcp.mobius.waila.api.IWailaConfigHandler;
import mcp.mobius.waila.api.IWailaDataAccessor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard;
import java.util.List;
import java.util.function.BiFunction;
public class LevelEmitterBlock extends LogicSlabBlock<LevelEmitterTileEntity, LevelEmitterContainer> {
public static final PropertyBool MODULE = PropertyBool.create("module");
public LevelEmitterBlock() {
super(RFTools.instance, Material.IRON, LevelEmitterTileEntity.class, LevelEmitterContainer::new, "level_emitter", true);
}
@SideOnly(Side.CLIENT)
@Override
public BiFunction<LevelEmitterTileEntity, LevelEmitterContainer, GenericGuiContainer<? super LevelEmitterTileEntity>> getGuiFactory() {
return GuiLevelEmitter::new;
}
@Override
protected IModuleSupport getModuleSupport() {
return new ModuleSupport(LevelEmitterContainer.SLOT_MODULE) {
@Override
public boolean isModule(ItemStack itemStack) {
return itemStack.getItem() == ScreenSetup.storageControlModuleItem;
}
};
}
@SideOnly(Side.CLIENT)
@Override
public void addInformation(ItemStack itemStack, World player, List<String> list, ITooltipFlag whatIsThis) {
super.addInformation(itemStack, player, list, whatIsThis);
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) {
list.add(TextFormatting.WHITE + "This block can be retrofitted with a");
list.add(TextFormatting.WHITE + "Storage Control Screen Module so that");
list.add(TextFormatting.WHITE + "you can count items in your storage");
} else {
list.add(TextFormatting.WHITE + GuiProxy.SHIFT_MESSAGE);
}
}
@Override
@Optional.Method(modid = "theoneprobe")
public void addProbeInfo(ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) {
super.addProbeInfo(mode, probeInfo, player, world, blockState, data);
ItemStack module = getModule(world.getTileEntity(data.getPos()));
if (module.isEmpty()) {
probeInfo.text(TextFormatting.GREEN + "Install storage control screen module first");
} else {
TileEntity te = world.getTileEntity(data.getPos());
if (te instanceof LevelEmitterTileEntity) {
LevelEmitterTileEntity emitterTileEntity = (LevelEmitterTileEntity) te;
int count = emitterTileEntity.getCurrentCount();
ItemStack toCount = emitterTileEntity.getInventoryHelper().getStackInSlot(LevelEmitterContainer.SLOT_ITEMMATCH);
if (!toCount.isEmpty()) {
probeInfo.horizontal(probeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER))
.item(toCount)
.text(TextFormatting.BLUE + "Count: " + TextFormatting.WHITE + count);
}
}
}
}
@SideOnly(Side.CLIENT)
@Override
@Optional.Method(modid = "waila")
public List<String> getWailaBody(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
super.getWailaBody(itemStack, currenttip, accessor, config);
ItemStack module = getModule(accessor.getTileEntity());
if (module.isEmpty()) {
currenttip.add(TextFormatting.GREEN + "Install storage control screen module first");
}
return currenttip;
}
@Override
public boolean needsRedstoneCheck() {
return false;
}
@Override
public int getGuiID() {
return GuiProxy.GUI_STORAGE_TERMINAL;
}
private static ItemStack getModule(TileEntity tileEntity) {
if (tileEntity instanceof LevelEmitterTileEntity) {
LevelEmitterTileEntity emitterTileEntity = (LevelEmitterTileEntity) tileEntity;
return emitterTileEntity.getStackInSlot(LevelEmitterContainer.SLOT_MODULE);
}
return ItemStack.EMPTY;
}
@Override
public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos) {
ItemStack module = getModule(world.getTileEntity(pos));
return super.getActualState(state, world, pos).withProperty(MODULE, !module.isEmpty());
}
@Override
protected BlockStateContainer createBlockState() {
return new BlockStateContainer(this, LOGIC_FACING, META_INTERMEDIATE, MODULE);
}
}
| 1 | 0.860896 | 1 | 0.860896 | game-dev | MEDIA | 0.986004 | game-dev | 0.881955 | 1 | 0.881955 |
JumpAttacker/EnsageSharp | 2,302 | ArcNew/Units/Necronomicon.cs | using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ArcAnnihilation.Units.behaviour.Abilities;
using ArcAnnihilation.Units.behaviour.Orbwalking;
using ArcAnnihilation.Utils;
using Ensage;
using Ensage.Common.Threading;
namespace ArcAnnihilation.Units
{
public class Necronomicon : UnitBase
{
public Unit Necr;
public Necronomicon(Unit necr)
{
Necr = necr;
}
public Ability ManaBurn { get; set; }
public override void InitAbilities()
{
ManaBurn = Necr.Spellbook.Spell1;
Printer.Print("init abilities: ManaBurn:" + ManaBurn.Name);
}
public override void MoveAction(Unit target)
{
var time = Game.RawGameTime;
if (time - LastMoveOrderIssuedTime < CooldownOnMoving) return;
LastMoveOrderIssuedTime = Game.RawGameTime;
if (target != null)
Necr.Move(target.Position);
/*else
Hero.Move(Game.MousePosition);*/
}
public override IEnumerable<Item> GetItems()
{
throw new NotImplementedException();
}
}
public class RangeNecr : Necronomicon
{
public RangeNecr(Unit necr) : base(necr)
{
AbilitiesBehaviour = new CanUseAbilitiesNecroArcher();
OrbwalkingBehaviour = new CanUseOrbwalking();
}
public override async Task Combo(CancellationToken cancellationToken)
{
await TargetFinder(cancellationToken);
await UseAbilities(cancellationToken);
}
}
internal class MeleeNecr : Necronomicon
{
public MeleeNecr(Unit necr) : base(necr)
{
OrbwalkingBehaviour = new CanUseOrbwalkingOnlyForPushing();
}
public override async Task Combo(CancellationToken cancellationToken)
{
await TargetFinder(cancellationToken);
await Attack(cancellationToken);
}
private async Task Attack(CancellationToken cancellationToken)
{
if (Orbwalker.CanAttack(Core.Target))
Necr.Attack(Core.Target);
await Await.Delay(250, cancellationToken);
}
}
} | 1 | 0.967559 | 1 | 0.967559 | game-dev | MEDIA | 0.930315 | game-dev | 0.965763 | 1 | 0.965763 |
Crazy-Crew/CrazyEnchantments | 2,034 | paper/src/main/java/com/badbones69/crazyenchantments/paper/api/events/BookApplyEvent.java | package com.badbones69.crazyenchantments.paper.api.events;
import com.badbones69.crazyenchantments.paper.api.objects.CEBook;
import com.badbones69.crazyenchantments.paper.api.objects.CEnchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
public class BookApplyEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Player player;
private final int level;
private boolean cancelled;
private final ItemStack enchantedItem;
private final CEnchantment enchantment;
private final CEBook ceBook;
public BookApplyEvent(@NotNull final Player player, @NotNull final ItemStack enchantedItem, @NotNull final CEBook ceBook) {
this.level = ceBook.getLevel();
this.player = player;
this.enchantment = ceBook.getEnchantment();
this.enchantedItem = enchantedItem;
this.ceBook = ceBook;
this.cancelled = false;
}
public Player getPlayer() {
return this.player;
}
public int getLevel() {
return this.level;
}
public ItemStack getEnchantedItem() {
return this.enchantedItem;
}
public CEnchantment getEnchantment() {
return this.enchantment;
}
public CEBook getCEBook() {
return this.ceBook;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(final boolean cancelled) {
this.cancelled = cancelled;
}
/**
* Gets a list of handlers handling this event.
*
* @return A list of handlers handling this event.
*/
@Override
public @NotNull HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
} | 1 | 0.678807 | 1 | 0.678807 | game-dev | MEDIA | 0.865612 | game-dev | 0.711932 | 1 | 0.711932 |
chapel-lang/chapel | 4,842 | third-party/re2/re2-src/util/strutil.cc | // Copyright 1999-2005 The RE2 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 <stdarg.h>
#include <stdio.h>
#include "util/strutil.h"
#ifdef _WIN32
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#endif
namespace re2 {
// ----------------------------------------------------------------------
// CEscapeString()
// Copies 'src' to 'dest', escaping dangerous characters using
// C-style escape sequences. 'src' and 'dest' should not overlap.
// Returns the number of bytes written to 'dest' (not including the \0)
// or (size_t)-1 if there was insufficient space.
// ----------------------------------------------------------------------
static size_t CEscapeString(const char* src, size_t src_len,
char* dest, size_t dest_len) {
const char* src_end = src + src_len;
size_t used = 0;
for (; src < src_end; src++) {
if (dest_len - used < 2) // space for two-character escape
return (size_t)-1;
unsigned char c = *src;
switch (c) {
case '\n': dest[used++] = '\\'; dest[used++] = 'n'; break;
case '\r': dest[used++] = '\\'; dest[used++] = 'r'; break;
case '\t': dest[used++] = '\\'; dest[used++] = 't'; break;
case '\"': dest[used++] = '\\'; dest[used++] = '\"'; break;
case '\'': dest[used++] = '\\'; dest[used++] = '\''; break;
case '\\': dest[used++] = '\\'; dest[used++] = '\\'; break;
default:
// Note that if we emit \xNN and the src character after that is a hex
// digit then that digit must be escaped too to prevent it being
// interpreted as part of the character code by C.
if (c < ' ' || c > '~') {
if (dest_len - used < 5) // space for four-character escape + \0
return (size_t)-1;
snprintf(dest + used, 5, "\\%03o", c);
used += 4;
} else {
dest[used++] = c; break;
}
}
}
if (dest_len - used < 1) // make sure that there is room for \0
return (size_t)-1;
dest[used] = '\0'; // doesn't count towards return value though
return used;
}
// ----------------------------------------------------------------------
// CEscape()
// Copies 'src' to result, escaping dangerous characters using
// C-style escape sequences. 'src' and 'dest' should not overlap.
// ----------------------------------------------------------------------
std::string CEscape(const StringPiece& src) {
const size_t dest_len = src.size() * 4 + 1; // Maximum possible expansion
char* dest = new char[dest_len];
const size_t used = CEscapeString(src.data(), src.size(),
dest, dest_len);
std::string s = std::string(dest, used);
delete[] dest;
return s;
}
void PrefixSuccessor(std::string* prefix) {
// We can increment the last character in the string and be done
// unless that character is 255, in which case we have to erase the
// last character and increment the previous character, unless that
// is 255, etc. If the string is empty or consists entirely of
// 255's, we just return the empty string.
while (!prefix->empty()) {
char& c = prefix->back();
if (c == '\xff') { // char literal avoids signed/unsigned.
prefix->pop_back();
} else {
++c;
break;
}
}
}
static void StringAppendV(std::string* dst, const char* format, va_list ap) {
// First try with a small fixed size buffer
char space[1024];
// It's possible for methods that use a va_list to invalidate
// the data in it upon use. The fix is to make a copy
// of the structure before using it and use that copy instead.
va_list backup_ap;
va_copy(backup_ap, ap);
int result = vsnprintf(space, sizeof(space), format, backup_ap);
va_end(backup_ap);
if ((result >= 0) && (static_cast<size_t>(result) < sizeof(space))) {
// It fit
dst->append(space, result);
return;
}
// Repeatedly increase buffer size until it fits
int length = sizeof(space);
while (true) {
if (result < 0) {
// Older behavior: just try doubling the buffer size
length *= 2;
} else {
// We need exactly "result+1" characters
length = result+1;
}
char* buf = new char[length];
// Restore the va_list before we use it again
va_copy(backup_ap, ap);
result = vsnprintf(buf, length, format, backup_ap);
va_end(backup_ap);
if ((result >= 0) && (result < length)) {
// It fit
dst->append(buf, result);
delete[] buf;
return;
}
delete[] buf;
}
}
std::string StringPrintf(const char* format, ...) {
va_list ap;
va_start(ap, format);
std::string result;
StringAppendV(&result, format, ap);
va_end(ap);
return result;
}
} // namespace re2
| 1 | 0.955083 | 1 | 0.955083 | game-dev | MEDIA | 0.162526 | game-dev | 0.990476 | 1 | 0.990476 |
Innoxia/liliths-throne-public | 11,613 | res/combatMove/dsg/gryphon_cry.xml | <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<combatMove>
<!-- GENERAL INFORMATION: If you are unsure of anything, please use the LT Discord to ask for help! -->
<!-- The category which this status effect falls into. You can omit this field if you want it to be set to SPECIAL (which should be considered to be the standard category).
Categories, along with their meanings, can be found here: https://github.com/Innoxia/liliths-throne-public/blob/dev/src/com/lilithsthrone/game/combat/moves/CombatMoveCategory.java -->
<category>SPECIAL</category>
<!-- What kind of attack this is, which primarily determines when and how often NPCs will decide to use this attack during combat.
All available values of CombatMoveType can be found here: https://github.com/Innoxia/liliths-throne-public/blob/dev/src/com/lilithsthrone/game/combat/moves/CombatMoveType.java -->
<type>ATTACK_DEFEND</type>
<!-- How likely it is that the NPC who has this move available to them will select it as one of their equipped moves.
The default weighting is 1, and if you want it to be more likely to be chosen, then give it a higher weighting. -->
<equipWeighting>10</equipWeighting>
<!-- The name of this move.
The character using this move is passed in as the 'npc' target for parsing, so commands such as [npc.name] will work. -->
<name><![CDATA[Hunting Call]]></name>
<!-- The description of this move.
The character using this move is passed in as the 'npc' target for parsing, so commands such as [npc.name] will work.
Special parsing arguments which can be used here are as follows:
'damageInflicted' will parse to the attacker's projected damage of this attack (using the defined 'baseDamage' field defined below).
'formattedDamageInflicted' will parse to a formatted damage prediction, taking into account whether or not the target is at maximum lust (therefore taking into account conversion of lust damage to health/mana damage). -->
<description><![CDATA[
Make a chilling hunting call with [npc.her] beak, granting [style.boldGood(+20)] to [npc.her] [style.boldMagenta(physique)] and [style.boldPurple(arcane ability)] for 5 turns. On [style.boldExcellent(critical)] hits, also debuffs opponent.
]]></description>
<!-- The type of damage that this move inflicts.
The parsing target of 'npc' corresponds to the character who is performing the move (and so conditional statements can be used to affect what damage type is inflicted).
The UNARMED damage type is a special case, as it will automatically use the appropriate damage type based on the attacker's body and any other effects (such as being FIRE when under the effect of the Cloak of Flames spell).
All available values of DamageType can be found here: https://github.com/Innoxia/liliths-throne-public/blob/dev/src/com/lilithsthrone/game/combat/DamageType.java -->
<damageType><![CDATA[
PHYSICAL
]]></damageType>
<!-- The amount of damage this move does to the target, assuming that no modifiers are taken into account.
The parsing target of 'npc' corresponds to the character who is performing the move. -->
<baseDamage><![CDATA[
0
]]></baseDamage>
<!-- How much damage this move blocks.
The block type corresponds to the 'damageType' defined above.
The parsing target of 'npc' corresponds to the character who is performing the move.
'isCritical' will parse to the boolean return value for isCritical, and will therefore be either 'true' or 'false', depending on if the move is critically hitting or not. -->
<blockAmount><![CDATA[
0
]]></blockAmount>
<!-- The number of turns it takes for this move to become available for use after using it.
The parsing target of 'npc' corresponds to the character who is performing the move.
A value of 0 (or less) means that it can be used as many times as the attacker wants.
The cooldown is decremented at the end of each combat round, including the current one, so a value of 1 means that this move will be available next turn (and so effectively just limits its use to once per combat turn). -->
<cooldown><![CDATA[
5
]]></cooldown>
<!-- The number of Action Points that this move costs.
The parsing target of 'npc' corresponds to the character who is performing the move.
Only exceptional abilities or circumstances will alter a character's AP, which is by default 3, so you should take that into account when deciding upon an AP cost (it would normally be best to have it as just 1). -->
<APcost><![CDATA[
1
]]></APcost>
<!-- These three values set whether or not the move can target enemies, allies, or the performer of the move themselves. -->
<canTargetEnemies>true</canTargetEnemies>
<canTargetAllies>false</canTargetAllies>
<canTargetSelf>false</canTargetSelf>
<!-- The name of the icon which should be used to represent this combat move. The icon must be an svg file, and must be placed in the same folder as this XML file. -->
<imageName>gryphon_cry.svg</imageName>
<!-- The colours which should be associated with this status effect. Just like with clothing and weapon recolouring, this is used to recolour the image you used above.
A PresetColour value should be used here, drawn from: https://github.com/Innoxia/liliths-throne-public/blob/dev/src/com/lilithsthrone/utils/colours/PresetColour.java -->
<colourPrimary>dsg_gryphonBlue</colourPrimary> <!-- This has to have a value defined, or else this XML file will fail to load. -->
<colourSecondary>dsg_gryphonOrange</colourSecondary> <!-- This can optionally be left blank, like the 'colourTertiary' element below. -->
<colourTertiary>BASE_AQUA</colourTertiary>
<!-- The StatusEffects which should be applied to the target of this move.
The 'turnLength' attribute defines for how many combat turns the effect should last.
The 'onCrit' attribute determines whether this effect is only applied on a critical hit or not. -->
<statusEffects>
<effect turnLength="5" onCrit="true">VULNERABLE</effect>
</statusEffects>
<!-- Effect logic -->
<!-- The condition upon which this move is available to characters.
You must use the game's parsing engine to get what you want.
The parsing target of 'npc' corresponds to the character who is being checked to see if they have this move available to them.
All whitespace is stripped from the returned String before it is parsed into a Boolean. -->
<availabilityCondition><![CDATA[
[#(npc.getFaceType()==FACE_TYPE_dsg_gryphon_face) && !npc.isSpeechMuffled() && !npc.isMute()]
]]>
</availabilityCondition>
<!-- A short description to let the player know what the conditions are for this move being available to them. -->
<availabilityDescription><![CDATA[
Available to characters who have a gryphon face type and are not muffled or mute.
]]></availabilityDescription>
<!-- The weighting for this action's chance of being selected by an AI combatant.
The standard value for weighting is 1.0.
The parsing target of 'npc' corresponds to the character who is using the move.
The parsing target of 'npc2' corresponds to the character who is being targeted by the move.
Note that this weighting is parsed for every combatant, enemy and ally alike, so the method npc2.isCombatAlly(npc) (or npc2.isCombatEnemy(npc)) should most likely be used to differentiate between friend and foe (if you have set this move as being able to be used on both allies and enemies).
For an interesting example, see the 'spinneret_webbing.xml' file. -->
<weighting><![CDATA[
1.0
]]></weighting>
<!-- To return true or false based on whether or not this move will be a critical hit.
The parsing target of 'npc' corresponds to the character who is using the move.
The parsing target of 'npc2' corresponds to the character who is being targeted by this move.
Special parsing arguments which can be used here are as follows:
'turnIndex' will parse to an integer corresponding to the current turn index. (i.e. The position of this move in the performing character's planned moves.)
'damageInflicted' will parse to an integer corresponding to the amount of damage that will be inflicted upon the target during the move's execution.
'damageType' will parse to this move's DamageType.
-->
<criticalCondition><![CDATA[
[#npc2.getHeightValue() < npc.getHeightValue() * 0.95]
]]></criticalCondition>
<!-- A short description to let the player know what the conditions are for this move to inflict a critical hit. -->
<criticalDescription><![CDATA[
Target's height is less than 95% of the attacker's.
]]></criticalDescription>
<!-- The description that is shown to the player to let them know what this move's effects will be.
The parsing target of 'npc' corresponds to the character who is using the move.
The parsing target of 'npc2' corresponds to the character who is being targeted by this move.
Special parsing arguments which can be used here are as follows:
'damageInflicted' will parse to the attacker's projected damage of this attack (using the defined 'baseDamage' field defined above). If isCritical is true, the damageInflicted value will represent this (via increased damage).
'formattedDamageInflicted' will parse to the same damage as the command above, but will be formatted nicely.
'isCritical' will parse to the boolean return value for isCritical, and will therefore be either 'true' or 'false'.
-->
<movePredictionDescriptionWithTarget><![CDATA[
Make a chilling hunting call with [npc.her] beak, granting [style.boldGood(+20)] to [npc.her] [style.boldMagenta(physique)] and [style.boldPurple(arcane ability)].
]]></movePredictionDescriptionWithTarget>
<!-- This is almost identical to the defined description above, with the difference being that there is no targeted character. As such, the description cannot use any 'npc2' parsing. -->
<movePredictionDescriptionNoTarget><![CDATA[
Make a chilling hunting call with [npc.her] beak, granting [style.boldGood(+20)] to [npc.her] [style.boldMagenta(physique)] and [style.boldPurple(arcane ability)].
]]></movePredictionDescriptionNoTarget>
<!-- The code that's executed when this move is performed.
The parsing target of 'npc' corresponds to the character who is using the move.
The parsing target of 'npc2' corresponds to the character who is being targeted by this move.
Special parsing arguments which can be used here are as follows:
'damageInflicted' will parse to the attacker's projected damage of this attack (using the defined 'baseDamage' field defined above). If isCritical is true, the damageInflicted value will represent this (via increased damage).
'formattedDamageInflicted' will parse to the same damage as the command above, but will be formatted nicely.
'formattedHealthDamage' will parse to a brief, formatted description of how much damage the target took. -->
<performMove>
<!-- The 'execute' section should be used for the main description of the attack, as well as any extra effects you want to apply.
NOTE: The damage is automatically applied to the target, so you don't need to handle parsing of that. -->
<execute><![CDATA[
[npc.Name] [npc.verb(open)] [npc.her] beak and [npc.verb(screech)] out a mighty hunting call.
#IF (!npc.hasStatusEffect(SE_dsg_race_gryphon_hunting_cry))
[##npc.addStatusEffect(SE_dsg_race_gryphon_hunting_cry, 3)]
#ENDIF
]]></execute>
<critDescription><![CDATA[
[npc.NamePos] hunting call was extremely effective!
]]></critDescription>
<critEffectDescription><![CDATA[
[npc2.Name] [npc2.is] feeling vulnerable in front of [npc.namePos] superior stature!
]]></critEffectDescription>
</performMove>
</combatMove>
| 1 | 0.908423 | 1 | 0.908423 | game-dev | MEDIA | 0.94009 | game-dev | 0.656535 | 1 | 0.656535 |
Overload-Technologies/Overload | 11,896 | Dependencies/bullet3/bullet/BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btMinkowskiPenetrationDepthSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h"
#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h"
#include "BulletCollision/CollisionShapes/btConvexShape.h"
#define NUM_UNITSPHERE_POINTS 42
bool btMinkowskiPenetrationDepthSolver::calcPenDepth(btSimplexSolverInterface& simplexSolver,
const btConvexShape* convexA, const btConvexShape* convexB,
const btTransform& transA, const btTransform& transB,
btVector3& v, btVector3& pa, btVector3& pb,
class btIDebugDraw* debugDraw)
{
(void)v;
bool check2d = convexA->isConvex2d() && convexB->isConvex2d();
struct btIntermediateResult : public btDiscreteCollisionDetectorInterface::Result
{
btIntermediateResult() : m_hasResult(false)
{
}
btVector3 m_normalOnBInWorld;
btVector3 m_pointInWorld;
btScalar m_depth;
bool m_hasResult;
virtual void setShapeIdentifiersA(int partId0, int index0)
{
(void)partId0;
(void)index0;
}
virtual void setShapeIdentifiersB(int partId1, int index1)
{
(void)partId1;
(void)index1;
}
void addContactPoint(const btVector3& normalOnBInWorld, const btVector3& pointInWorld, btScalar depth)
{
m_normalOnBInWorld = normalOnBInWorld;
m_pointInWorld = pointInWorld;
m_depth = depth;
m_hasResult = true;
}
};
//just take fixed number of orientation, and sample the penetration depth in that direction
btScalar minProj = btScalar(BT_LARGE_FLOAT);
btVector3 minNorm(btScalar(0.), btScalar(0.), btScalar(0.));
btVector3 minA, minB;
btVector3 separatingAxisInA, separatingAxisInB;
btVector3 pInA, qInB, pWorld, qWorld, w;
#ifndef __SPU__
#define USE_BATCHED_SUPPORT 1
#endif
#ifdef USE_BATCHED_SUPPORT
btVector3 supportVerticesABatch[NUM_UNITSPHERE_POINTS + MAX_PREFERRED_PENETRATION_DIRECTIONS * 2];
btVector3 supportVerticesBBatch[NUM_UNITSPHERE_POINTS + MAX_PREFERRED_PENETRATION_DIRECTIONS * 2];
btVector3 separatingAxisInABatch[NUM_UNITSPHERE_POINTS + MAX_PREFERRED_PENETRATION_DIRECTIONS * 2];
btVector3 separatingAxisInBBatch[NUM_UNITSPHERE_POINTS + MAX_PREFERRED_PENETRATION_DIRECTIONS * 2];
int i;
int numSampleDirections = NUM_UNITSPHERE_POINTS;
for (i = 0; i < numSampleDirections; i++)
{
btVector3 norm = getPenetrationDirections()[i];
separatingAxisInABatch[i] = (-norm) * transA.getBasis();
separatingAxisInBBatch[i] = norm * transB.getBasis();
}
{
int numPDA = convexA->getNumPreferredPenetrationDirections();
if (numPDA)
{
for (int i = 0; i < numPDA; i++)
{
btVector3 norm;
convexA->getPreferredPenetrationDirection(i, norm);
norm = transA.getBasis() * norm;
getPenetrationDirections()[numSampleDirections] = norm;
separatingAxisInABatch[numSampleDirections] = (-norm) * transA.getBasis();
separatingAxisInBBatch[numSampleDirections] = norm * transB.getBasis();
numSampleDirections++;
}
}
}
{
int numPDB = convexB->getNumPreferredPenetrationDirections();
if (numPDB)
{
for (int i = 0; i < numPDB; i++)
{
btVector3 norm;
convexB->getPreferredPenetrationDirection(i, norm);
norm = transB.getBasis() * norm;
getPenetrationDirections()[numSampleDirections] = norm;
separatingAxisInABatch[numSampleDirections] = (-norm) * transA.getBasis();
separatingAxisInBBatch[numSampleDirections] = norm * transB.getBasis();
numSampleDirections++;
}
}
}
convexA->batchedUnitVectorGetSupportingVertexWithoutMargin(separatingAxisInABatch, supportVerticesABatch, numSampleDirections);
convexB->batchedUnitVectorGetSupportingVertexWithoutMargin(separatingAxisInBBatch, supportVerticesBBatch, numSampleDirections);
for (i = 0; i < numSampleDirections; i++)
{
btVector3 norm = getPenetrationDirections()[i];
if (check2d)
{
norm[2] = 0.f;
}
if (norm.length2() > 0.01)
{
separatingAxisInA = separatingAxisInABatch[i];
separatingAxisInB = separatingAxisInBBatch[i];
pInA = supportVerticesABatch[i];
qInB = supportVerticesBBatch[i];
pWorld = transA(pInA);
qWorld = transB(qInB);
if (check2d)
{
pWorld[2] = 0.f;
qWorld[2] = 0.f;
}
w = qWorld - pWorld;
btScalar delta = norm.dot(w);
//find smallest delta
if (delta < minProj)
{
minProj = delta;
minNorm = norm;
minA = pWorld;
minB = qWorld;
}
}
}
#else
int numSampleDirections = NUM_UNITSPHERE_POINTS;
#ifndef __SPU__
{
int numPDA = convexA->getNumPreferredPenetrationDirections();
if (numPDA)
{
for (int i = 0; i < numPDA; i++)
{
btVector3 norm;
convexA->getPreferredPenetrationDirection(i, norm);
norm = transA.getBasis() * norm;
getPenetrationDirections()[numSampleDirections] = norm;
numSampleDirections++;
}
}
}
{
int numPDB = convexB->getNumPreferredPenetrationDirections();
if (numPDB)
{
for (int i = 0; i < numPDB; i++)
{
btVector3 norm;
convexB->getPreferredPenetrationDirection(i, norm);
norm = transB.getBasis() * norm;
getPenetrationDirections()[numSampleDirections] = norm;
numSampleDirections++;
}
}
}
#endif // __SPU__
for (int i = 0; i < numSampleDirections; i++)
{
const btVector3& norm = getPenetrationDirections()[i];
separatingAxisInA = (-norm) * transA.getBasis();
separatingAxisInB = norm * transB.getBasis();
pInA = convexA->localGetSupportVertexWithoutMarginNonVirtual(separatingAxisInA);
qInB = convexB->localGetSupportVertexWithoutMarginNonVirtual(separatingAxisInB);
pWorld = transA(pInA);
qWorld = transB(qInB);
w = qWorld - pWorld;
btScalar delta = norm.dot(w);
//find smallest delta
if (delta < minProj)
{
minProj = delta;
minNorm = norm;
minA = pWorld;
minB = qWorld;
}
}
#endif //USE_BATCHED_SUPPORT
//add the margins
minA += minNorm * convexA->getMarginNonVirtual();
minB -= minNorm * convexB->getMarginNonVirtual();
//no penetration
if (minProj < btScalar(0.))
return false;
btScalar extraSeparation = 0.5f; ///scale dependent
minProj += extraSeparation + (convexA->getMarginNonVirtual() + convexB->getMarginNonVirtual());
//#define DEBUG_DRAW 1
#ifdef DEBUG_DRAW
if (debugDraw)
{
btVector3 color(0, 1, 0);
debugDraw->drawLine(minA, minB, color);
color = btVector3(1, 1, 1);
btVector3 vec = minB - minA;
btScalar prj2 = minNorm.dot(vec);
debugDraw->drawLine(minA, minA + (minNorm * minProj), color);
}
#endif //DEBUG_DRAW
btGjkPairDetector gjkdet(convexA, convexB, &simplexSolver, 0);
btScalar offsetDist = minProj;
btVector3 offset = minNorm * offsetDist;
btGjkPairDetector::ClosestPointInput input;
btVector3 newOrg = transA.getOrigin() + offset;
btTransform displacedTrans = transA;
displacedTrans.setOrigin(newOrg);
input.m_transformA = displacedTrans;
input.m_transformB = transB;
input.m_maximumDistanceSquared = btScalar(BT_LARGE_FLOAT); //minProj;
btIntermediateResult res;
gjkdet.setCachedSeparatingAxis(-minNorm);
gjkdet.getClosestPoints(input, res, debugDraw);
btScalar correctedMinNorm = minProj - res.m_depth;
//the penetration depth is over-estimated, relax it
btScalar penetration_relaxation = btScalar(1.);
minNorm *= penetration_relaxation;
if (res.m_hasResult)
{
pa = res.m_pointInWorld - minNorm * correctedMinNorm;
pb = res.m_pointInWorld;
v = minNorm;
#ifdef DEBUG_DRAW
if (debugDraw)
{
btVector3 color(1, 0, 0);
debugDraw->drawLine(pa, pb, color);
}
#endif //DEBUG_DRAW
}
return res.m_hasResult;
}
btVector3* btMinkowskiPenetrationDepthSolver::getPenetrationDirections()
{
static btVector3 sPenetrationDirections[NUM_UNITSPHERE_POINTS + MAX_PREFERRED_PENETRATION_DIRECTIONS * 2] =
{
btVector3(btScalar(0.000000), btScalar(-0.000000), btScalar(-1.000000)),
btVector3(btScalar(0.723608), btScalar(-0.525725), btScalar(-0.447219)),
btVector3(btScalar(-0.276388), btScalar(-0.850649), btScalar(-0.447219)),
btVector3(btScalar(-0.894426), btScalar(-0.000000), btScalar(-0.447216)),
btVector3(btScalar(-0.276388), btScalar(0.850649), btScalar(-0.447220)),
btVector3(btScalar(0.723608), btScalar(0.525725), btScalar(-0.447219)),
btVector3(btScalar(0.276388), btScalar(-0.850649), btScalar(0.447220)),
btVector3(btScalar(-0.723608), btScalar(-0.525725), btScalar(0.447219)),
btVector3(btScalar(-0.723608), btScalar(0.525725), btScalar(0.447219)),
btVector3(btScalar(0.276388), btScalar(0.850649), btScalar(0.447219)),
btVector3(btScalar(0.894426), btScalar(0.000000), btScalar(0.447216)),
btVector3(btScalar(-0.000000), btScalar(0.000000), btScalar(1.000000)),
btVector3(btScalar(0.425323), btScalar(-0.309011), btScalar(-0.850654)),
btVector3(btScalar(-0.162456), btScalar(-0.499995), btScalar(-0.850654)),
btVector3(btScalar(0.262869), btScalar(-0.809012), btScalar(-0.525738)),
btVector3(btScalar(0.425323), btScalar(0.309011), btScalar(-0.850654)),
btVector3(btScalar(0.850648), btScalar(-0.000000), btScalar(-0.525736)),
btVector3(btScalar(-0.525730), btScalar(-0.000000), btScalar(-0.850652)),
btVector3(btScalar(-0.688190), btScalar(-0.499997), btScalar(-0.525736)),
btVector3(btScalar(-0.162456), btScalar(0.499995), btScalar(-0.850654)),
btVector3(btScalar(-0.688190), btScalar(0.499997), btScalar(-0.525736)),
btVector3(btScalar(0.262869), btScalar(0.809012), btScalar(-0.525738)),
btVector3(btScalar(0.951058), btScalar(0.309013), btScalar(0.000000)),
btVector3(btScalar(0.951058), btScalar(-0.309013), btScalar(0.000000)),
btVector3(btScalar(0.587786), btScalar(-0.809017), btScalar(0.000000)),
btVector3(btScalar(0.000000), btScalar(-1.000000), btScalar(0.000000)),
btVector3(btScalar(-0.587786), btScalar(-0.809017), btScalar(0.000000)),
btVector3(btScalar(-0.951058), btScalar(-0.309013), btScalar(-0.000000)),
btVector3(btScalar(-0.951058), btScalar(0.309013), btScalar(-0.000000)),
btVector3(btScalar(-0.587786), btScalar(0.809017), btScalar(-0.000000)),
btVector3(btScalar(-0.000000), btScalar(1.000000), btScalar(-0.000000)),
btVector3(btScalar(0.587786), btScalar(0.809017), btScalar(-0.000000)),
btVector3(btScalar(0.688190), btScalar(-0.499997), btScalar(0.525736)),
btVector3(btScalar(-0.262869), btScalar(-0.809012), btScalar(0.525738)),
btVector3(btScalar(-0.850648), btScalar(0.000000), btScalar(0.525736)),
btVector3(btScalar(-0.262869), btScalar(0.809012), btScalar(0.525738)),
btVector3(btScalar(0.688190), btScalar(0.499997), btScalar(0.525736)),
btVector3(btScalar(0.525730), btScalar(0.000000), btScalar(0.850652)),
btVector3(btScalar(0.162456), btScalar(-0.499995), btScalar(0.850654)),
btVector3(btScalar(-0.425323), btScalar(-0.309011), btScalar(0.850654)),
btVector3(btScalar(-0.425323), btScalar(0.309011), btScalar(0.850654)),
btVector3(btScalar(0.162456), btScalar(0.499995), btScalar(0.850654))};
return sPenetrationDirections;
}
| 1 | 0.792944 | 1 | 0.792944 | game-dev | MEDIA | 0.957172 | game-dev | 0.981596 | 1 | 0.981596 |
electronicarts/CnC_Generals_Zero_Hour | 135,104 | Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp | /*
** Command & Conquer Generals(tm)
** Copyright 2025 Electronic Arts Inc.
**
** 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/>.
*/
////////////////////////////////////////////////////////////////////////////////
// //
// (c) 2001-2003 Electronic Arts Inc. //
// //
////////////////////////////////////////////////////////////////////////////////
// FILE: W3DModelDraw.cpp ///////////////////////////////////////////////////////////////////////
// Author: Colin Day, November 2001
// Desc: Default w3d draw module
///////////////////////////////////////////////////////////////////////////////////////////////////
// INCLUDES ///////////////////////////////////////////////////////////////////////////////////////
#define DEFINE_W3DANIMMODE_NAMES
#define DEFINE_WEAPONSLOTTYPE_NAMES
#define NO_DEBUG_CRC
#include "Common/CRC.h"
#include "Common/CRCDebug.h"
#include "Common/GameState.h"
#include "Common/GlobalData.h"
#include "Common/PerfTimer.h"
#include "Common/RandomValue.h"
#include "Common/ThingTemplate.h"
#include "Common/GameLOD.h"
#include "Common/Xfer.h"
#include "Common/GameState.h"
#include "GameClient/Drawable.h"
#include "GameClient/FXList.h"
#include "GameClient/Shadow.h"
#include "GameLogic/GameLogic.h" // for real-time frame
#include "GameLogic/Object.h"
#include "GameLogic/WeaponSet.h"
#include "GameLogic/FPUControl.h"
#include "GameLogic/Module/AIUpdate.h"
#include "GameLogic/Module/PhysicsUpdate.h"
#include "W3DDevice/GameClient/Module/W3DModelDraw.h"
#include "W3DDevice/GameClient/W3DAssetManager.h"
#include "W3DDevice/GameClient/W3DDisplay.h"
#include "W3DDevice/GameClient/W3DScene.h"
#include "W3DDevice/GameClient/W3DShadow.h"
#include "W3DDevice/GameClient/W3DTerrainTracks.h"
#include "W3DDevice/GameClient/WorldHeightMap.h"
#include "WW3D2/HAnim.h"
#include "WW3D2/HLod.h"
#include "WW3D2/RendObj.h"
#include "WW3D2/Mesh.h"
#include "WW3D2/MeshMdl.h"
#include "Common/BitFlagsIO.h"
#ifdef _INTERNAL
// for occasional debugging...
//#pragma optimize("", off)
//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
#endif
//-------------------------------------------------------------------------------------------------
static inline Bool isValidTimeToCalcLogicStuff()
{
return (TheGameLogic && TheGameLogic->isInGameLogicUpdate()) ||
(TheGameState && TheGameState->isInLoadGame());
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
#if defined(DEBUG_CRC) && (defined(_DEBUG) || defined(_INTERNAL))
#include <cstdarg>
class LogClass
{
public:
LogClass(const char *fname);
~LogClass();
void log(const char *fmt, ...);
void dumpMatrix3D(const Matrix3D *m, AsciiString name, AsciiString fname, Int line);
void dumpReal(Real r, AsciiString name, AsciiString fname, Int line);
protected:
FILE *m_fp;
};
LogClass::LogClass(const char *fname)
{
char buffer[ _MAX_PATH ];
GetModuleFileName( NULL, buffer, sizeof( buffer ) );
char *pEnd = buffer + strlen( buffer );
while( pEnd != buffer )
{
if( *pEnd == '\\' )
{
*pEnd = 0;
break;
}
pEnd--;
}
AsciiString fullPath;
fullPath.format("%s\\%s", buffer, fname);
m_fp = fopen(fullPath.str(), "wt");
}
LogClass::~LogClass()
{
if (m_fp)
{
fclose(m_fp);
}
}
void LogClass::log(const char *fmt, ...)
{
DEBUG_ASSERTCRASH(isValidTimeToCalcLogicStuff(), ("Calc'ing logic bone pos in client!!!"));
if (!m_fp /*|| !isValidTimeToCalcLogicStuff()*/)
return;
static char buf[1024];
static Int lastFrame = 0;
static Int lastIndex = 0;
if (lastFrame != TheGameLogic->getFrame())
{
lastFrame = TheGameLogic->getFrame();
lastIndex = 0;
}
va_list va;
va_start( va, fmt );
_vsnprintf(buf, 1024, fmt, va );
buf[1023] = 0;
va_end( va );
char *tmp = buf;
while (tmp && *tmp)
{
if (*tmp == '\r' || *tmp == '\n')
{
*tmp = ' ';
}
++tmp;
}
fprintf(m_fp, "%d:%d %s\n", lastFrame, lastIndex++, buf);
fflush(m_fp);
}
void LogClass::dumpMatrix3D(const Matrix3D *m, AsciiString name, AsciiString fname, Int line)
{
fname.toLower();
fname = fname.reverseFind('\\') + 1;
const Real *matrix = (const Real *)m;
log("dumpMatrix3D() %s:%d %s\n",
fname.str(), line, name.str());
for (Int i=0; i<3; ++i)
log(" 0x%08X 0x%08X 0x%08X 0x%08X\n",
AS_INT(matrix[(i<<2)+0]), AS_INT(matrix[(i<<2)+1]), AS_INT(matrix[(i<<2)+2]), AS_INT(matrix[(i<<2)+3]));
}
void LogClass::dumpReal(Real r, AsciiString name, AsciiString fname, Int line)
{
if (!m_fp || !isValidTimeToCalcLogicStuff())
return;
fname.toLower();
fname = fname.reverseFind('\\') + 1;
log("dumpReal() %s:%d %s %8.8X (%f)\n",
fname.str(), line, name.str(), AS_INT(r), r);
}
LogClass BonePosLog("bonePositions.txt");
#define BONEPOS_LOG(x) BonePosLog.log x
#define BONEPOS_DUMPMATRIX3D(x) BONEPOS_DUMPMATRIX3DNAMED(x, #x)
#define BONEPOS_DUMPMATRIX3DNAMED(x, y) BonePosLog.dumpMatrix3D(x, y, __FILE__, __LINE__)
#define BONEPOS_DUMPREAL(x) BONEPOS_DUMPREALNAMED(x, #x)
#define BONEPOS_DUMPREALNAMED(x, y) BonePosLog.dumpReal(x, y, __FILE__, __LINE__)
#else // DEBUG_CRC
#define BONEPOS_LOG(x) {}
#define BONEPOS_DUMPMATRIX3D(x) {}
#define BONEPOS_DUMPMATRIX3DNAMED(x, y) {}
#define BONEPOS_DUMPREAL(x) {}
#define BONEPOS_DUMPREALNAMED(x, y) {}
#endif // DEBUG_CRC
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
#if defined(_DEBUG) || defined(_INTERNAL)
extern AsciiString TheThingTemplateBeingParsedName;
extern Real TheSkateDistOverride;
#endif
// flags that aren't read directly from INI, but set in response to various other situations
enum INIReadFlagsType
{
ANIMS_COPIED_FROM_DEFAULT_STATE = 0,
GOT_NONIDLE_ANIMS,
GOT_IDLE_ANIMS,
};
enum ACBits
{
RANDOMIZE_START_FRAME = 0,
START_FRAME_FIRST,
START_FRAME_LAST,
ADJUST_HEIGHT_BY_CONSTRUCTION_PERCENT,
PRISTINE_BONE_POS_IN_FINAL_FRAME,
MAINTAIN_FRAME_ACROSS_STATES,
RESTART_ANIM_WHEN_COMPLETE,
MAINTAIN_FRAME_ACROSS_STATES2,
MAINTAIN_FRAME_ACROSS_STATES3,
MAINTAIN_FRAME_ACROSS_STATES4,
};
static const char *ACBitsNames[] =
{
"RANDOMSTART",
"START_FRAME_FIRST",
"START_FRAME_LAST",
"ADJUST_HEIGHT_BY_CONSTRUCTION_PERCENT",
"PRISTINE_BONE_POS_IN_FINAL_FRAME",
"MAINTAIN_FRAME_ACROSS_STATES",
"RESTART_ANIM_WHEN_COMPLETE",
"MAINTAIN_FRAME_ACROSS_STATES2",
"MAINTAIN_FRAME_ACROSS_STATES3",
"MAINTAIN_FRAME_ACROSS_STATES4",
NULL
};
static const Int ALL_MAINTAIN_FRAME_FLAGS =
(1<<MAINTAIN_FRAME_ACROSS_STATES) |
(1<<MAINTAIN_FRAME_ACROSS_STATES2) |
(1<<MAINTAIN_FRAME_ACROSS_STATES3) |
(1<<MAINTAIN_FRAME_ACROSS_STATES4);
inline Bool isAnyMaintainFrameFlagSet(Int flags)
{
return (flags & ALL_MAINTAIN_FRAME_FLAGS) != 0;
}
inline Bool isCommonMaintainFrameFlagSet(Int a, Int b)
{
a &= ALL_MAINTAIN_FRAME_FLAGS;
b &= ALL_MAINTAIN_FRAME_FLAGS;
return (a & b) != 0;
}
/** @todo: Move this to some kind of INI file*/
//
// Note: these values are saved in save files, so you MUST NOT REMOVE OR CHANGE
// existing values!
//
static char *TerrainDecalTextureName[TERRAIN_DECAL_MAX-1]=
{
#ifdef ALLOW_DEMORALIZE
"DM_RING",//demoralized
#else
"TERRAIN_DECAL_DEMORALIZED_OBSOLETE",
#endif
"EXHorde",//enthusiastic
"EXHorde_UP", //enthusiastic with nationalism
"EXHordeB",//enthusiastic vehicle
"EXHordeB_UP", //enthusiastic vehicle with nationalism
"EXJunkCrate",//Marks a crate as special
};
const UnsignedInt NO_NEXT_DURATION = 0xffffffff;
//-------------------------------------------------------------------------------------------------
W3DAnimationInfo::W3DAnimationInfo(const AsciiString& name, Bool isIdle, Real distanceCovered) :
#ifdef RETAIN_ANIM_HANDLES
m_handle(NULL),
m_naturalDurationInMsec(0),
#else
m_naturalDurationInMsec(-1),
#endif
m_name(name),
m_isIdleAnim(isIdle),
m_distanceCovered(distanceCovered)
{
}
//-------------------------------------------------------------------------------------------------
W3DAnimationInfo::W3DAnimationInfo( const W3DAnimationInfo &r ) :
m_name(r.m_name),
#ifdef RETAIN_ANIM_HANDLES
m_handle(r.m_handle),
#endif
m_distanceCovered(r.m_distanceCovered),
m_isIdleAnim(r.m_isIdleAnim),
m_naturalDurationInMsec(r.m_naturalDurationInMsec)
{
#ifdef RETAIN_ANIM_HANDLES
if (m_handle)
m_handle->Add_Ref();
#endif
}
//-------------------------------------------------------------------------------------------------
W3DAnimationInfo& W3DAnimationInfo::operator=(const W3DAnimationInfo &r)
{
m_name = r.m_name;
m_distanceCovered = r.m_distanceCovered;
m_naturalDurationInMsec = r.m_naturalDurationInMsec;
m_isIdleAnim = r.m_isIdleAnim;
#ifdef RETAIN_ANIM_HANDLES
REF_PTR_RELEASE(m_handle);
m_handle = r.m_handle;
if (m_handle)
m_handle->Add_Ref();
#endif
return (*this);
}
//-------------------------------------------------------------------------------------------------
// note that this now returns an ADDREFED handle, which must be released by the caller!
HAnimClass* W3DAnimationInfo::getAnimHandle() const
{
#ifdef RETAIN_ANIM_HANDLES
if (m_handle == NULL)
{
// Get_HAnim addrefs it, so we'll have to release it in our dtor.
m_handle = W3DDisplay::m_assetManager->Get_HAnim(m_name.str());
DEBUG_ASSERTCRASH(m_handle, ("*** ASSET ERROR: animation %s not found\n",m_name.str()));
if (m_handle)
{
m_naturalDurationInMsec = m_handle->Get_Num_Frames() * 1000.0f / m_handle->Get_Frame_Rate();
}
}
// since we have it locally, must addref.
if (m_handle)
m_handle->Add_Ref();
return m_handle;
#else
HAnimClass* handle = W3DDisplay::m_assetManager->Get_HAnim(m_name.str());
DEBUG_ASSERTCRASH(handle, ("*** ASSET ERROR: animation %s not found\n",m_name.str()));
if (handle != NULL && m_naturalDurationInMsec < 0)
{
m_naturalDurationInMsec = handle->Get_Num_Frames() * 1000.0f / handle->Get_Frame_Rate();
}
// since Get_HAnim() returns an addrefed handle, we must NOT addref here.
//if (handle)
// handle->Add_Ref();
return handle;
#endif
}
//-------------------------------------------------------------------------------------------------
W3DAnimationInfo::~W3DAnimationInfo()
{
#ifdef RETAIN_ANIM_HANDLES
REF_PTR_RELEASE(m_handle);
m_handle = NULL;
#endif
}
//-------------------------------------------------------------------------------------------------
void ModelConditionInfo::preloadAssets( TimeOfDay timeOfDay, Real scale )
{
// load this asset
if( m_modelName.isEmpty() == FALSE )
{
TheDisplay->preloadModelAssets( m_modelName );
}
// this can be called from the client, which is problematic
// validateStuff(NULL, getDrawable()->getScale());
//validateCachedBones(NULL, scale);
//validateTurretInfo();
//validateWeaponBarrelInfo();
}
//-------------------------------------------------------------------------------------------------
void ModelConditionInfo::addPublicBone(const AsciiString& boneName) const
{
if (boneName.isEmpty() || boneName.isNone())
return;
AsciiString tmp = boneName;
tmp.toLower();
if (std::find(m_publicBones.begin(), m_publicBones.end(), tmp) == m_publicBones.end())
{
m_publicBones.push_back(tmp);
}
}
//-------------------------------------------------------------------------------------------------
Bool ModelConditionInfo::matchesMode(Bool night, Bool snowy) const
{
for (std::vector<ModelConditionFlags>::const_iterator it = m_conditionsYesVec.begin();
it != m_conditionsYesVec.end();
++it)
{
if (it->test(MODELCONDITION_NIGHT) == (night) &&
it->test(MODELCONDITION_SNOW) == (snowy))
{
return true;
}
}
return false;
}
//-------------------------------------------------------------------------------------------------
inline Bool testFlagBit(Int flags, Int bit)
{
return (flags & (1<<bit)) != 0;
}
//-------------------------------------------------------------------------------------------------
static Bool findSingleBone(RenderObjClass* robj, const AsciiString& boneName, Matrix3D& mtx, Int& boneIndex)
{
if (boneName.isNone() || boneName.isEmpty())
return false;
boneIndex = robj->Get_Bone_Index(boneName.str());
if (boneIndex != 0)
{
mtx = robj->Get_Bone_Transform(boneIndex);
return true;
}
else
{
return false;
}
}
//-------------------------------------------------------------------------------------------------
static Bool findSingleSubObj(RenderObjClass* robj, const AsciiString& boneName, Matrix3D& mtx, Int& boneIndex)
{
if (boneName.isNone() || boneName.isEmpty())
return false;
RenderObjClass* childObject = robj->Get_Sub_Object_By_Name(boneName.str());
if (childObject)
{
mtx = childObject->Get_Transform();
// you'd think this would work, but, it does not. do it the hard way.
// boneIndex = childObject->Get_Sub_Object_Bone_Index(childObject);
for (Int subObj = 0; subObj < robj->Get_Num_Sub_Objects(); subObj++)
{
RenderObjClass* test = robj->Get_Sub_Object(subObj);
if (test == childObject)
{
boneIndex = robj->Get_Sub_Object_Bone_Index(0, subObj);
#if defined(_DEBUG) || defined(_INTERNAL)
test->Release_Ref();
test = robj->Get_Sub_Object_On_Bone(0, boneIndex);
DEBUG_ASSERTCRASH(test != NULL && test == childObject, ("*** ASSET ERROR: Hmm, bone problem"));
#endif
}
if (test) test->Release_Ref();
}
childObject->Release_Ref();
return true;
}
else
{
return false;
}
}
//-------------------------------------------------------------------------------------------------
static Bool doSingleBoneName(RenderObjClass* robj, const AsciiString& boneName, PristineBoneInfoMap& map)
{
Bool foundAsBone = false;
Bool foundAsSubObj = false;
PristineBoneInfo info;
AsciiString tmp;
AsciiString boneNameTmp = boneName;
boneNameTmp.toLower(); // convert to all-lowercase to avoid case sens issues later
setFPMode();
if (findSingleBone(robj, boneNameTmp, info.mtx, info.boneIndex))
{
//DEBUG_LOG(("added bone %s\n",boneNameTmp.str()));
BONEPOS_LOG(("Caching bone %s (index %d)\n", boneNameTmp.str(), info.boneIndex));
BONEPOS_DUMPMATRIX3D(&(info.mtx));
map[NAMEKEY(boneNameTmp)] = info;
foundAsBone = true;
}
for (Int i = 1; i <= 99; ++i)
{
tmp.format("%s%02d", boneNameTmp.str(), i);
if (findSingleBone(robj, tmp, info.mtx, info.boneIndex))
{
//DEBUG_LOG(("added bone %s\n",tmp.str()));
BONEPOS_LOG(("Caching bone %s (index %d)\n", tmp.str(), info.boneIndex));
BONEPOS_DUMPMATRIX3D(&(info.mtx));
map[NAMEKEY(tmp)] = info;
foundAsBone = true;
}
else
{
break;
}
}
if (!foundAsBone)
{
if (findSingleSubObj(robj, boneNameTmp, info.mtx, info.boneIndex))
{
//DEBUG_LOG(("added subobj %s\n",boneNameTmp.str()));
BONEPOS_LOG(("Caching bone from subobject %s (index %d)\n", boneNameTmp.str(), info.boneIndex));
BONEPOS_DUMPMATRIX3D(&(info.mtx));
map[NAMEKEY(boneNameTmp)] = info;
foundAsSubObj = true;
}
for (Int i = 1; i <= 99; ++i)
{
tmp.format("%s%02d", boneNameTmp.str(), i);
if (findSingleSubObj(robj, tmp, info.mtx, info.boneIndex))
{
//DEBUG_LOG(("added subobj %s\n",tmp.str()));
BONEPOS_LOG(("Caching bone from subobject %s (index %d)\n", tmp.str(), info.boneIndex));
BONEPOS_DUMPMATRIX3D(&(info.mtx));
map[NAMEKEY(tmp)] = info;
foundAsSubObj = true;
}
else
{
break;
}
}
}
return foundAsBone || foundAsSubObj;
}
//-------------------------------------------------------------------------------------------------
void ModelConditionInfo::validateStuff(RenderObjClass* robj, Real scale, const std::vector<AsciiString>& extraPublicBones) const
{
// srj sez: hm, this doesn't make sense; I think we really do need to validate transition states.
// if (m_transition != NO_TRANSITION)
// return;
loadAnimations();
if (!(m_validStuff & PUBLIC_BONES_VALID) && isValidTimeToCalcLogicStuff())
{
for (std::vector<AsciiString>::const_iterator bone_it = extraPublicBones.begin(); bone_it != extraPublicBones.end(); ++bone_it)
{
addPublicBone(*bone_it);
}
m_validStuff |= PUBLIC_BONES_VALID;
}
validateCachedBones(robj, scale);
validateTurretInfo();
validateWeaponBarrelInfo();
}
//-------------------------------------------------------------------------------------------------
void ModelConditionInfo::validateCachedBones(RenderObjClass* robj, Real scale) const
{
//DEBUG_ASSERTCRASH(isValidTimeToCalcLogicStuff(), ("calling validateCachedBones() from in GameClient!"));
if (m_validStuff & PRISTINE_BONES_VALID)
return;
if (!isValidTimeToCalcLogicStuff())
{
m_pristineBones.clear();
m_validStuff &= ~PRISTINE_BONES_VALID;
return;
}
setFPMode();
BONEPOS_LOG(("Validating bones for %s: %s", m_modelName.str(), getDescription().str()));
//BONEPOS_LOG(("Passing in valid render obj: %d\n", (robj != 0)));
BONEPOS_DUMPREAL(scale);
m_pristineBones.clear();
// go ahead and set this here, in case we return early.
m_validStuff |= PRISTINE_BONES_VALID;
Bool tossRobj = false;
if (robj == NULL)
{
if (m_modelName.isEmpty())
{
//BONEPOS_LOG(("Bailing: model name is empty\n"));
return;
}
robj = W3DDisplay::m_assetManager->Create_Render_Obj(m_modelName.str(), scale, 0);
DEBUG_ASSERTCRASH(robj, ("*** ASSET ERROR: Model %s not found!\n",m_modelName.str()));
if (!robj)
{
//BONEPOS_LOG(("Bailing: could not load render object\n"));
return;
}
tossRobj = true;
}
Matrix3D originalTransform = robj->Get_Transform(); // save the transform
HLodClass* hlod = NULL;
HAnimClass* curAnim = NULL;
int numFrames = 0;
float frame = 0.0f;
int mode = 0;
float mult = 1.0f;
if (robj->Class_ID() == RenderObjClass::CLASSID_HLOD)
{
hlod = (HLodClass*)robj;
curAnim = hlod->Peek_Animation_And_Info(frame, numFrames, mode, mult);
}
// if we have any animations in this state, always choose the first, since the animations
// vary on a per-client basis.
HAnimClass* animToUse;
if (m_animations.size() > 0)
{
animToUse = m_animations.front().getAnimHandle(); // return an AddRef'ed handle
}
else
{
animToUse = curAnim; // Peek_Animation_And_Info does not addref, so we must do so here
if (animToUse)
animToUse->Add_Ref();
}
if (animToUse != NULL)
{
// make sure we're in frame zero.
Int whichFrame = testFlagBit(m_flags, PRISTINE_BONE_POS_IN_FINAL_FRAME) ? animToUse->Get_Num_Frames()-1 : 0;
robj->Set_Animation(animToUse, whichFrame, RenderObjClass::ANIM_MODE_MANUAL);
// must balance the addref, above
REF_PTR_RELEASE(animToUse);
animToUse = NULL;
}
Matrix3D tmp(true);
tmp.Scale(scale);
robj->Set_Transform(tmp); // set to identity transform
if (TheGlobalData)
{
for (std::vector<AsciiString>::const_iterator it = TheGlobalData->m_standardPublicBones.begin(); it != TheGlobalData->m_standardPublicBones.end(); ++it)
{
if (!doSingleBoneName(robj, *it, m_pristineBones))
{
// don't crash here, since these are catch-all global bones and won't be present in most models.
//DEBUG_CRASH(("public bone %s (and variations thereof) not found in model %s!\n",it->str(),m_modelName.str()));
}
//else
//{
// DEBUG_LOG(("global bone %s (or variations thereof) found in model %s\n",it->str(),m_modelName.str()));
//}
}
}
for (std::vector<AsciiString>::const_iterator it = m_publicBones.begin(); it != m_publicBones.end(); ++it)
{
if (!doSingleBoneName(robj, *it, m_pristineBones))
{
// DO crash here, since we specifically requested this bone for this model
DEBUG_CRASH(("*** ASSET ERROR: public bone '%s' (and variations thereof) not found in model %s!\n",it->str(),m_modelName.str()));
}
//else
//{
// DEBUG_LOG(("extra bone %s (or variations thereof) found in model %s\n",it->str(),m_modelName.str()));
//}
}
robj->Set_Transform(originalTransform); // restore previous transform
if (curAnim != NULL)
{
robj->Set_Animation(curAnim, frame, mode);
hlod->Set_Animation_Frame_Rate_Multiplier(mult);
}
if (tossRobj)
{
REF_PTR_RELEASE(robj);
}
}
//-------------------------------------------------------------------------------------------------
void ModelConditionInfo::validateWeaponBarrelInfo() const
{
//DEBUG_ASSERTCRASH(isValidTimeToCalcLogicStuff(), ("calling validateWeaponBarrelInfo() from in GameClient!"));
if (m_validStuff & BARRELS_VALID)
return;
if (!isValidTimeToCalcLogicStuff())
{
return;
}
setFPMode();
for (int wslot = 0; wslot < WEAPONSLOT_COUNT; ++wslot)
{
m_weaponBarrelInfoVec[wslot].clear();
m_hasRecoilBonesOrMuzzleFlashes[wslot] = false;
const AsciiString& fxBoneName = m_weaponFireFXBoneName[wslot];
const AsciiString& recoilBoneName = m_weaponRecoilBoneName[wslot];
const AsciiString& mfName = m_weaponMuzzleFlashName[wslot];
const AsciiString& plbName = m_weaponProjectileLaunchBoneName[wslot];
if (fxBoneName.isNotEmpty() || recoilBoneName.isNotEmpty() || mfName.isNotEmpty() || plbName.isNotEmpty())
{
Int prevFxBone = 0;
char buffer[256];
for (Int i = 1; i <= 99; ++i)
{
WeaponBarrelInfo info;
info.m_projectileOffsetMtx.Make_Identity();
if (!recoilBoneName.isEmpty())
{
sprintf(buffer, "%s%02d", recoilBoneName.str(), i);
findPristineBone(NAMEKEY(buffer), &info.m_recoilBone);
}
if (!mfName.isEmpty())
{
sprintf(buffer, "%s%02d", mfName.str(), i);
findPristineBone(NAMEKEY(buffer), &info.m_muzzleFlashBone);
#if defined(_DEBUG) || defined(_INTERNAL)
if (info.m_muzzleFlashBone)
info.m_muzzleFlashBoneName = buffer;
#endif
}
if (!fxBoneName.isEmpty())
{
sprintf(buffer, "%s%02d", fxBoneName.str(), i);
findPristineBone(NAMEKEY(buffer), &info.m_fxBone);
// special case: if we have multiple muzzleflashes, but only one fxbone, use that fxbone for everything.
if (info.m_fxBone == 0 && info.m_muzzleFlashBone != 0)
info.m_fxBone = prevFxBone;
}
Int plbBoneIndex = 0;
if (!plbName.isEmpty())
{
sprintf(buffer, "%s%02d", plbName.str(), i);
const Matrix3D* mtx = findPristineBone(NAMEKEY(buffer), &plbBoneIndex);
if (mtx != NULL)
info.m_projectileOffsetMtx = *mtx;
}
if (info.m_fxBone == 0 && info.m_recoilBone == 0 && info.m_muzzleFlashBone == 0 && plbBoneIndex == 0)
break;
CRCDEBUG_LOG(("validateWeaponBarrelInfo() - model name %s wslot %d\n", m_modelName.str(), wslot));
DUMPMATRIX3D(&(info.m_projectileOffsetMtx));
BONEPOS_LOG(("validateWeaponBarrelInfo() - model name %s wslot %d\n", m_modelName.str(), wslot));
BONEPOS_DUMPMATRIX3D(&(info.m_projectileOffsetMtx));
m_weaponBarrelInfoVec[wslot].push_back(info);
if (info.m_recoilBone != 0 || info.m_muzzleFlashBone != 0)
m_hasRecoilBonesOrMuzzleFlashes[wslot] = true;
prevFxBone = info.m_fxBone;
}
if (m_weaponBarrelInfoVec[wslot].empty())
{
// try the unadorned names
WeaponBarrelInfo info;
if (!recoilBoneName.isEmpty())
findPristineBone(NAMEKEY(recoilBoneName), &info.m_recoilBone);
if (!mfName.isEmpty())
findPristineBone(NAMEKEY(mfName), &info.m_muzzleFlashBone);
#if defined(_DEBUG) || defined(_INTERNAL)
if (info.m_muzzleFlashBone)
info.m_muzzleFlashBoneName = mfName;
#endif
const Matrix3D* plbMtx = plbName.isEmpty() ? NULL : findPristineBone(NAMEKEY(plbName), NULL);
if (plbMtx != NULL)
info.m_projectileOffsetMtx = *plbMtx;
else
info.m_projectileOffsetMtx.Make_Identity();
if (!fxBoneName.isEmpty())
findPristineBone(NAMEKEY(fxBoneName), &info.m_fxBone);
if (info.m_fxBone != 0 || info.m_recoilBone != 0 || info.m_muzzleFlashBone != 0 || plbMtx != NULL)
{
CRCDEBUG_LOG(("validateWeaponBarrelInfo() - model name %s (unadorned) wslot %d\n", m_modelName.str(), wslot));
DUMPMATRIX3D(&(info.m_projectileOffsetMtx));
BONEPOS_LOG(("validateWeaponBarrelInfo() - model name %s (unadorned) wslot %d\n", m_modelName.str(), wslot));
BONEPOS_DUMPMATRIX3D(&(info.m_projectileOffsetMtx));
m_weaponBarrelInfoVec[wslot].push_back(info);
if (info.m_recoilBone != 0 || info.m_muzzleFlashBone != 0)
m_hasRecoilBonesOrMuzzleFlashes[wslot] = true;
}
else
{
CRCDEBUG_LOG(("validateWeaponBarrelInfo() - model name %s (unadorned) found nothing\n", m_modelName.str()));
BONEPOS_LOG(("validateWeaponBarrelInfo() - model name %s (unadorned) found nothing\n", m_modelName.str()));
}
} // if empty
DEBUG_ASSERTCRASH(!(m_modelName.isNotEmpty() && m_weaponBarrelInfoVec[wslot].empty()), ("*** ASSET ERROR: No fx bone named '%s' found in model %s!\n",fxBoneName.str(),m_modelName.str()));
}
}
m_validStuff |= BARRELS_VALID;
}
//-------------------------------------------------------------------------------------------------
void ModelConditionInfo::validateTurretInfo() const
{
//DEBUG_ASSERTCRASH(isValidTimeToCalcLogicStuff(), ("calling validateTurretInfo() from in GameClient!"));
if (m_validStuff & TURRETS_VALID)
return;
setFPMode();
for (int tslot = 0; tslot < MAX_TURRETS; ++tslot)
{
TurretInfo& tur = m_turrets[tslot];
if (!isValidTimeToCalcLogicStuff() || m_modelName.isEmpty())
{
tur.m_turretAngleBone = 0;
tur.m_turretPitchBone = 0;
continue;
}
if (tur.m_turretAngleNameKey != NAMEKEY_INVALID)
{
if (findPristineBone(tur.m_turretAngleNameKey, &tur.m_turretAngleBone) == NULL)
{
DEBUG_CRASH(("*** ASSET ERROR: TurretBone %s not found! (%s)\n",KEYNAME(tur.m_turretAngleNameKey).str(),m_modelName.str()));
tur.m_turretAngleBone = 0;
}
}
else
{
tur.m_turretAngleBone = 0;
}
if (tur.m_turretPitchNameKey != NAMEKEY_INVALID)
{
if (findPristineBone(tur.m_turretPitchNameKey, &tur.m_turretPitchBone) == NULL)
{
DEBUG_CRASH(("*** ASSET ERROR: TurretBone %s not found! (%s)\n",KEYNAME(tur.m_turretPitchNameKey).str(),m_modelName.str()));
tur.m_turretPitchBone = 0;
}
}
else
{
tur.m_turretPitchBone = 0;
}
}
if (isValidTimeToCalcLogicStuff())
{
m_validStuff |= TURRETS_VALID;
}
}
//-------------------------------------------------------------------------------------------------
const Matrix3D* ModelConditionInfo::findPristineBone(NameKeyType boneName, Int* boneIndex) const
{
DEBUG_ASSERTCRASH((m_validStuff & PRISTINE_BONES_VALID), ("*** ASSET ERROR: bones are not valid"));
if (!(m_validStuff & PRISTINE_BONES_VALID))
{
// set it to zero, some callers rely on this
if (boneIndex)
*boneIndex = 0;
return NULL;
}
if (boneName == NAMEKEY_INVALID)
{
// set it to zero, some callers rely on this
if (boneIndex)
*boneIndex = 0;
return NULL;
}
PristineBoneInfoMap::const_iterator it = m_pristineBones.find(boneName);
if (it != m_pristineBones.end())
{
if (boneIndex)
*boneIndex = it->second.boneIndex;
return &it->second.mtx;
}
else
{
// set it to zero -- some callers rely on this!
if (boneIndex)
*boneIndex = 0;
return NULL;
}
}
//-------------------------------------------------------------------------------------------------
Bool ModelConditionInfo::findPristineBonePos(NameKeyType boneName, Coord3D& pos) const
{
const Matrix3D* mtx = findPristineBone(boneName, NULL);
if (mtx)
{
Vector3 v = mtx->Get_Translation();
pos.x = v.X;
pos.y = v.Y;
pos.z = v.Z;
return true;
}
else
{
pos.zero();
return false;
}
}
//-------------------------------------------------------------------------------------------------
void ModelConditionInfo::loadAnimations() const
{
#ifdef RETAIN_ANIM_HANDLES
for (W3DAnimationVector::const_iterator it2 = m_animations.begin(); it2 != m_animations.end(); ++it2)
{
HAnimClass* h = it2->getAnimHandle(); // just force it to get loaded
REF_PTR_RELEASE(h);
h = NULL;
}
#else
// srj sez: I think there is no real reason to preload these all anymore. things that need the anims
// (for bones) will force an implicit load anyway, but there's no point in forcibly loading the anims
// that don't contain interesting logical bones.
#endif
}
//-------------------------------------------------------------------------------------------------
void ModelConditionInfo::clear()
{
int i;
#if defined(_DEBUG) || defined(_INTERNAL)
m_description.clear();
#endif
m_conditionsYesVec.clear();
m_modelName.clear();
for (i = 0; i < MAX_TURRETS; ++i)
{
m_turrets[i].clear();
}
m_hideShowVec.clear();
for (i = 0; i < WEAPONSLOT_COUNT; ++i)
{
m_weaponFireFXBoneName[i].clear();
m_weaponRecoilBoneName[i].clear();
m_weaponMuzzleFlashName[i].clear();
m_weaponProjectileLaunchBoneName[i].clear();
m_weaponBarrelInfoVec[i].clear();
m_hasRecoilBonesOrMuzzleFlashes[i] = false;
}
m_particleSysBones.clear();
m_animations.clear();
m_flags = 0;
m_transitionKey = NAMEKEY_INVALID;
m_allowToFinishKey = NAMEKEY_INVALID;
m_iniReadFlags = 0;
m_mode = RenderObjClass::ANIM_MODE_ONCE;
m_transitionSig = NO_TRANSITION;
m_animMinSpeedFactor = 1.0f;
m_animMaxSpeedFactor = 1.0f;
m_pristineBones.clear();
m_validStuff = 0;
}
//-------------------------------------------------------------------------------------------------
W3DModelDrawModuleData::W3DModelDrawModuleData() :
m_validated(0),
m_okToChangeModelColor(false),
m_animationsRequirePower(true),
#ifdef CACHE_ATTACH_BONE
m_attachToDrawableBoneOffsetValid(false),
#endif
m_minLODRequired(STATIC_GAME_LOD_LOW),
m_defaultState(-1)
{
const Real MAX_SHIFT = 3.0f;
const Real INITIAL_RECOIL_RATE = 2.0f;
const Real RECOIL_DAMPING = 0.4f;
const Real SETTLE_RATE = 0.065f;
m_projectileBoneFeedbackEnabledSlots = 0;
m_initialRecoil = INITIAL_RECOIL_RATE;
m_maxRecoil = MAX_SHIFT;
m_recoilDamping = RECOIL_DAMPING;
m_recoilSettle = SETTLE_RATE;
// m_ignoreConditionStates defaults to all zero, which is what we want
}
//-------------------------------------------------------------------------------------------------
void W3DModelDrawModuleData::validateStuffForTimeAndWeather(const Drawable* draw, Bool night, Bool snowy) const
{
if (!isValidTimeToCalcLogicStuff())
return;
enum
{
NORMAL = 0x0001,
NIGHT = 0x0002,
SNOWY = 0x0004,
NIGHT_SNOWY = 0x0008
};
Int mode;
if (night)
{
mode = (snowy) ? NIGHT_SNOWY : NIGHT;
}
else
{
mode = (snowy) ? SNOWY : NORMAL;
}
if (m_validated & mode)
return;
m_validated |= mode;
for (ModelConditionVector::iterator c_it = m_conditionStates.begin(); c_it != m_conditionStates.end(); ++c_it)
{
if (!c_it->matchesMode(false, false) && !c_it->matchesMode(night, snowy))
continue;
c_it->validateStuff(NULL, draw->getScale(), m_extraPublicBones);
}
for (TransitionMap::iterator t_it = m_transitionMap.begin(); t_it != m_transitionMap.end(); ++t_it)
{
// here's the tricky part: only want to load the anims for this one if there is at least one
// source AND at least one dest state that matches the current mode
NameKeyType src = recoverSrcState(t_it->first);
NameKeyType dst = recoverDstState(t_it->first);
Bool a = false;
Bool b = false;
for (c_it = m_conditionStates.begin(); c_it != m_conditionStates.end(); ++c_it)
{
if (!a && c_it->m_transitionKey == src && c_it->matchesMode(night, snowy))
a = true;
if (!b && c_it->m_transitionKey == dst && c_it->matchesMode(night, snowy))
b = true;
}
if (a && b)
{
t_it->second.loadAnimations();
// nope -- transition states don't get public bones.
//it->addPublicBone(m_extraPublicBones);
// srj sez: hm, this doesn't make sense; I think we really do need to validate transition states.
t_it->second.validateStuff(NULL, draw->getScale(), m_extraPublicBones);
}
}
}
//-------------------------------------------------------------------------------------------------
W3DModelDrawModuleData::~W3DModelDrawModuleData()
{
m_conditionStateMap.clear();
}
//-------------------------------------------------------------------------------------------------
void W3DModelDrawModuleData::preloadAssets( TimeOfDay timeOfDay, Real scale ) const
{
for( ModelConditionVector::iterator it = m_conditionStates.begin();
it != m_conditionStates.end();
++it )
{
it->preloadAssets( timeOfDay, scale );
}
}
//-------------------------------------------------------------------------------------------------
AsciiString W3DModelDrawModuleData::getBestModelNameForWB(const ModelConditionFlags& c) const
{
const ModelConditionInfo* info = findBestInfo(c);
if (info)
return info->m_modelName;
return AsciiString::TheEmptyString;
}
#ifdef CACHE_ATTACH_BONE
//-------------------------------------------------------------------------------------------------
const Vector3* W3DModelDrawModuleData::getAttachToDrawableBoneOffset(const Drawable* draw) const
{
if (m_attachToDrawableBone.isEmpty())
{
return NULL;
}
else
{
if (!m_attachToDrawableBoneOffsetValid)
{
// must use pristine bone here since the result is used by logic
Matrix3D boneMtx;
if (draw->getPristineBonePositions(m_attachToDrawableBone.str(), 0, NULL, &boneMtx, 1) == 1)
{
m_attachToDrawableBoneOffset = boneMtx.Get_Translation();
}
else
{
m_attachToDrawableBoneOffset.X = 0;
m_attachToDrawableBoneOffset.Y = 0;
m_attachToDrawableBoneOffset.Z = 0;
}
m_attachToDrawableBoneOffsetValid = true;
}
return &m_attachToDrawableBoneOffset;
}
}
#endif
//-------------------------------------------------------------------------------------------------
enum ParseCondStateType
{
PARSE_NORMAL,
PARSE_DEFAULT,
PARSE_TRANSITION,
PARSE_ALIAS
};
//-------------------------------------------------------------------------------------------------
static void parseAsciiStringLC( INI* ini, void * /*instance*/, void *store, const void* /*userData*/ )
{
AsciiString* asciiString = (AsciiString *)store;
*asciiString = ini->getNextAsciiString();
asciiString->toLower();
}
//-------------------------------------------------------------------------------------------------
void W3DModelDrawModuleData::buildFieldParse(MultiIniFieldParse& p)
{
ModuleData::buildFieldParse(p);
static const FieldParse dataFieldParse[] =
{
{ "InitialRecoilSpeed", INI::parseVelocityReal, NULL, offsetof(W3DModelDrawModuleData, m_initialRecoil) },
{ "MaxRecoilDistance", INI::parseReal, NULL, offsetof(W3DModelDrawModuleData, m_maxRecoil) },
{ "RecoilDamping", INI::parseReal, NULL, offsetof(W3DModelDrawModuleData, m_recoilDamping) },
{ "RecoilSettleSpeed", INI::parseVelocityReal, NULL, offsetof(W3DModelDrawModuleData, m_recoilSettle) },
{ "OkToChangeModelColor", INI::parseBool, NULL, offsetof(W3DModelDrawModuleData, m_okToChangeModelColor) },
{ "AnimationsRequirePower", INI::parseBool, NULL, offsetof(W3DModelDrawModuleData, m_animationsRequirePower) },
{ "MinLODRequired", INI::parseStaticGameLODLevel, NULL, offsetof(W3DModelDrawModuleData, m_minLODRequired) },
{ "ProjectileBoneFeedbackEnabledSlots", INI::parseBitString32, TheWeaponSlotTypeNames, offsetof(W3DModelDrawModuleData, m_projectileBoneFeedbackEnabledSlots) },
{ "DefaultConditionState", W3DModelDrawModuleData::parseConditionState, (void*)PARSE_DEFAULT, 0 },
{ "ConditionState", W3DModelDrawModuleData::parseConditionState, (void*)PARSE_NORMAL, 0 },
{ "AliasConditionState", W3DModelDrawModuleData::parseConditionState, (void*)PARSE_ALIAS, 0 },
{ "TransitionState", W3DModelDrawModuleData::parseConditionState, (void*)PARSE_TRANSITION, 0 },
{ "TrackMarks", parseAsciiStringLC, NULL, offsetof(W3DModelDrawModuleData, m_trackFile) },
{ "ExtraPublicBone", INI::parseAsciiStringVectorAppend, NULL, offsetof(W3DModelDrawModuleData, m_extraPublicBones) },
{ "AttachToBoneInAnotherModule", parseAsciiStringLC, NULL, offsetof(W3DModelDrawModuleData, m_attachToDrawableBone) },
{ "IgnoreConditionStates", ModelConditionFlags::parseFromINI, NULL, offsetof(W3DModelDrawModuleData, m_ignoreConditionStates) },
{ 0, 0, 0, 0 }
};
p.add(dataFieldParse);
}
//-------------------------------------------------------------------------------------------------
enum AnimParseType
{
ANIM_NORMAL,
ANIM_IDLE
};
//-------------------------------------------------------------------------------------------------
static void parseAnimation(INI* ini, void *instance, void * /*store*/, const void* userData)
{
AnimParseType animType = (AnimParseType)(UnsignedInt)userData;
AsciiString animName = ini->getNextAsciiString();
animName.toLower();
const char* distanceCoveredToken = ini->getNextTokenOrNull();
Real distanceCovered = distanceCoveredToken ? INI::scanReal(distanceCoveredToken) : 0;
DEBUG_ASSERTCRASH(!(animType == ANIM_IDLE && distanceCovered != 0), ("You should not specify nonzero DistanceCovered values for Idle Anims"));
const char* timesToRepeatToken = ini->getNextTokenOrNull();
Int timesToRepeat = timesToRepeatToken ? INI::scanInt(timesToRepeatToken) : 1;
if (timesToRepeat < 1) timesToRepeat = 1;
W3DAnimationInfo animInfo(animName, (animType == ANIM_IDLE), distanceCovered);
ModelConditionInfo* self = (ModelConditionInfo*)instance;
if (self->m_iniReadFlags & (1<<ANIMS_COPIED_FROM_DEFAULT_STATE))
{
self->m_iniReadFlags &= ~((1<<ANIMS_COPIED_FROM_DEFAULT_STATE)|(1<<GOT_IDLE_ANIMS)|(1<<GOT_NONIDLE_ANIMS));
self->m_animations.clear();
}
if (animInfo.isIdleAnim())
self->m_iniReadFlags |= (1<<GOT_IDLE_ANIMS);
else
self->m_iniReadFlags |= (1<<GOT_NONIDLE_ANIMS);
if (!animName.isEmpty() && !animName.isNone())
{
while (timesToRepeat--)
self->m_animations.push_back(animInfo);
}
}
//-------------------------------------------------------------------------------------------------
static void parseShowHideSubObject(INI* ini, void *instance, void *store, const void* userData)
{
std::vector<ModelConditionInfo::HideShowSubObjInfo>* vec = (std::vector<ModelConditionInfo::HideShowSubObjInfo>*)store;
AsciiString subObjName = ini->getNextAsciiString();
subObjName.toLower();
// handle "None"
if (subObjName.isNone())
{
vec->clear();
return;
}
while (subObjName.isNotEmpty())
{
Bool found = false;
for (std::vector<ModelConditionInfo::HideShowSubObjInfo>::iterator it = vec->begin(); it != vec->end(); ++it)
{
if (stricmp(it->subObjName.str(), subObjName.str()) == 0)
{
it->hide = (userData != NULL);
found = true;
}
}
if (!found)
{
ModelConditionInfo::HideShowSubObjInfo info;
info.subObjName = subObjName;
info.hide = (userData != NULL);
vec->push_back(info);
}
subObjName = ini->getNextAsciiString();
subObjName.toLower();
}
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::showSubObject( const AsciiString& name, Bool show )
{
if( name.isNotEmpty() )
{
Bool found = false;
for( std::vector<ModelConditionInfo::HideShowSubObjInfo>::iterator it = m_subObjectVec.begin(); it != m_subObjectVec.end(); ++it )
{
if( stricmp( it->subObjName.str(), name.str() ) == 0 )
{
it->hide = !show;
found = true;
}
}
if( !found )
{
ModelConditionInfo::HideShowSubObjInfo info;
info.subObjName = name;
info.hide = !show;
m_subObjectVec.push_back( info );
}
}
}
//-------------------------------------------------------------------------------------------------
static void parseWeaponBoneName(INI* ini, void *instance, void * store, const void* /*userData*/)
{
ModelConditionInfo* self = (ModelConditionInfo*)instance;
AsciiString* arr = (AsciiString*)store;
WeaponSlotType wslot = (WeaponSlotType)INI::scanIndexList(ini->getNextToken(), TheWeaponSlotTypeNames);
arr[wslot] = ini->getNextAsciiString();
arr[wslot].toLower();
if (arr[wslot].isNone())
arr[wslot].clear();
if (self)
self->addPublicBone(arr[wslot]);
}
//-------------------------------------------------------------------------------------------------
static void parseParticleSysBone(INI* ini, void *instance, void * store, const void * /*userData*/)
{
ParticleSysBoneInfo info;
info.boneName = ini->getNextAsciiString();
info.boneName.toLower();
ini->parseParticleSystemTemplate(ini, instance, &(info.particleSystemTemplate), NULL);
ModelConditionInfo *self = (ModelConditionInfo *)instance;
self->m_particleSysBones.push_back(info);
}
//-------------------------------------------------------------------------------------------------
static void parseRealRange( INI *ini, void *instance, void *store, const void* /*userData*/ )
{
ModelConditionInfo *self = (ModelConditionInfo *)instance;
const char *token = ini->getNextToken();
self->m_animMinSpeedFactor = ini->scanReal( token );
token = ini->getNextToken();
self->m_animMaxSpeedFactor = ini->scanReal( token );
}
//-------------------------------------------------------------------------------------------------
static void parseLowercaseNameKey(INI* ini, void *instance, void * store, const void * /*userData*/)
{
NameKeyType* key = (NameKeyType*)store;
AsciiString tmp = ini->getNextToken();
tmp.toLower();
*key = NAMEKEY(tmp.str());
}
//-------------------------------------------------------------------------------------------------
static void parseBoneNameKey(INI* ini, void *instance, void * store, const void * /*userData*/)
{
ModelConditionInfo* self = (ModelConditionInfo*)instance;
NameKeyType* key = (NameKeyType*)store;
AsciiString tmp = ini->getNextToken();
tmp.toLower();
if (self)
self->addPublicBone(tmp);
if (tmp.isEmpty() || tmp.isNone())
*key = NAMEKEY_INVALID;
else
*key = NAMEKEY(tmp.str());
}
//-------------------------------------------------------------------------------------------------
static Bool doesStateExist(const ModelConditionVector& v, const ModelConditionFlags& f)
{
for (ModelConditionVector::const_iterator it = v.begin(); it != v.end(); ++it)
{
for (Int i = it->getConditionsYesCount()-1; i >= 0; --i)
{
if (f == it->getNthConditionsYes(i))
return true;
}
}
return false;
}
//-------------------------------------------------------------------------------------------------
void W3DModelDrawModuleData::parseConditionState(INI* ini, void *instance, void * /*store*/, const void* userData)
{
static const FieldParse myFieldParse[] =
{
{ "Model", parseAsciiStringLC, NULL, offsetof(ModelConditionInfo, m_modelName) },
{ "Turret", parseBoneNameKey, NULL, offsetof(ModelConditionInfo, m_turrets[0].m_turretAngleNameKey) },
{ "TurretArtAngle", INI::parseAngleReal, NULL, offsetof(ModelConditionInfo, m_turrets[0].m_turretArtAngle) },
{ "TurretPitch", parseBoneNameKey, NULL, offsetof(ModelConditionInfo, m_turrets[0].m_turretPitchNameKey) },
{ "TurretArtPitch", INI::parseAngleReal, NULL, offsetof(ModelConditionInfo, m_turrets[0].m_turretArtPitch) },
{ "AltTurret", parseBoneNameKey, NULL, offsetof(ModelConditionInfo, m_turrets[1].m_turretAngleNameKey) },
{ "AltTurretArtAngle", INI::parseAngleReal, NULL, offsetof(ModelConditionInfo, m_turrets[1].m_turretArtAngle) },
{ "AltTurretPitch", parseBoneNameKey, NULL, offsetof(ModelConditionInfo, m_turrets[1].m_turretPitchNameKey) },
{ "AltTurretArtPitch", INI::parseAngleReal, NULL, offsetof(ModelConditionInfo, m_turrets[1].m_turretArtPitch) },
{ "ShowSubObject", parseShowHideSubObject, (void*)0, offsetof(ModelConditionInfo, m_hideShowVec) },
{ "HideSubObject", parseShowHideSubObject, (void*)1, offsetof(ModelConditionInfo, m_hideShowVec) },
{ "WeaponFireFXBone", parseWeaponBoneName, NULL, offsetof(ModelConditionInfo, m_weaponFireFXBoneName[0]) },
{ "WeaponRecoilBone", parseWeaponBoneName, NULL, offsetof(ModelConditionInfo, m_weaponRecoilBoneName[0]) },
{ "WeaponMuzzleFlash", parseWeaponBoneName, NULL, offsetof(ModelConditionInfo, m_weaponMuzzleFlashName[0]) },
{ "WeaponLaunchBone", parseWeaponBoneName, NULL, offsetof(ModelConditionInfo, m_weaponProjectileLaunchBoneName[0]) },
{ "WeaponHideShowBone", parseWeaponBoneName, NULL, offsetof(ModelConditionInfo, m_weaponProjectileHideShowName[0]) },
{ "Animation", parseAnimation, (void*)ANIM_NORMAL, offsetof(ModelConditionInfo, m_animations) },
{ "IdleAnimation", parseAnimation, (void*)ANIM_IDLE, offsetof(ModelConditionInfo, m_animations) },
{ "AnimationMode", INI::parseIndexList, TheAnimModeNames, offsetof(ModelConditionInfo, m_mode) },
{ "TransitionKey", parseLowercaseNameKey, NULL, offsetof(ModelConditionInfo, m_transitionKey) },
{ "WaitForStateToFinishIfPossible", parseLowercaseNameKey, NULL, offsetof(ModelConditionInfo, m_allowToFinishKey) },
{ "Flags", INI::parseBitString32, ACBitsNames, offsetof(ModelConditionInfo, m_flags) },
{ "ParticleSysBone", parseParticleSysBone, NULL, 0 },
{ "AnimationSpeedFactorRange", parseRealRange, NULL, 0 },
{ 0, 0, 0, 0 }
};
ModelConditionInfo info;
W3DModelDrawModuleData* self = (W3DModelDrawModuleData*)instance;
ParseCondStateType cst = (ParseCondStateType)(UnsignedInt)userData;
switch (cst)
{
case PARSE_DEFAULT:
{
if (self->m_defaultState >= 0)
{
DEBUG_CRASH(("*** ASSET ERROR: you may have only one default state!\n"));
throw INI_INVALID_DATA;
}
else if (ini->getNextTokenOrNull())
{
DEBUG_CRASH(("*** ASSET ERROR: unknown keyword\n"));
throw INI_INVALID_DATA;
}
else
{
if (!self->m_conditionStates.empty())
{
DEBUG_CRASH(("*** ASSET ERROR: when using DefaultConditionState, it must be the first state listed (%s)\n",TheThingTemplateBeingParsedName.str()));
throw INI_INVALID_DATA;
}
// note, this is size(), not size()-1, since we haven't actually modified the list yet
self->m_defaultState = self->m_conditionStates.size();
//DEBUG_LOG(("set default state to %d\n",self->m_defaultState));
// add an empty conditionstateflag set
ModelConditionFlags blankConditions;
info.m_conditionsYesVec.clear();
info.m_conditionsYesVec.push_back(blankConditions);
#if defined(_DEBUG) || defined(_INTERNAL)
info.m_description.clear();
info.m_description.concat(TheThingTemplateBeingParsedName);
info.m_description.concat(" DEFAULT");
#endif
}
}
break;
case PARSE_TRANSITION:
{
AsciiString firstNm = ini->getNextToken(); firstNm.toLower();
AsciiString secondNm = ini->getNextToken(); secondNm.toLower();
NameKeyType firstKey = NAMEKEY(firstNm);
NameKeyType secondKey = NAMEKEY(secondNm);
if (firstKey == secondKey)
{
DEBUG_CRASH(("*** ASSET ERROR: You may not declare a transition between two identical states\n"));
throw INI_INVALID_DATA;
}
if (self->m_defaultState >= 0)
{
info = self->m_conditionStates.at(self->m_defaultState);
info.m_iniReadFlags |= (1<<ANIMS_COPIED_FROM_DEFAULT_STATE);
info.m_transitionKey = NAMEKEY_INVALID;
info.m_allowToFinishKey = NAMEKEY_INVALID;
}
info.m_transitionSig = buildTransitionSig(firstKey, secondKey);
#if defined(_DEBUG) || defined(_INTERNAL)
info.m_description.clear();
info.m_description.concat(TheThingTemplateBeingParsedName);
info.m_description.concat(" TRANSITION: ");
info.m_description.concat(firstNm);
info.m_description.concat(" ");
info.m_description.concat(secondNm);
#endif
}
break;
case PARSE_ALIAS:
{
if (self->m_conditionStates.empty())
{
DEBUG_CRASH(("*** ASSET ERROR: AliasConditionState must refer to the previous state!\n"));
throw INI_INVALID_DATA;
}
ModelConditionInfo& prevState = self->m_conditionStates.at(self->m_conditionStates.size()-1);
ModelConditionFlags conditionsYes;
#if defined(_DEBUG) || defined(_INTERNAL)
AsciiString description;
conditionsYes.parse(ini, &description);
prevState.m_description.concat("\nAKA: ");
prevState.m_description.concat(description);
#else
conditionsYes.parse(ini, NULL);
#endif
if (conditionsYes.anyIntersectionWith(self->m_ignoreConditionStates))
{
DEBUG_CRASH(("You should not specify bits in a state once they are used in IgnoreConditionStates (%s)\n", TheThingTemplateBeingParsedName.str()));
throw INI_INVALID_DATA;
}
if (doesStateExist(self->m_conditionStates, conditionsYes))
{
DEBUG_CRASH(("*** ASSET ERROR: duplicate condition states are not currently allowed"));
throw INI_INVALID_DATA;
}
if (!conditionsYes.any() && self->m_defaultState >= 0)
{
DEBUG_CRASH(("*** ASSET ERROR: you may not specify both a Default state and a Conditions=None state"));
throw INI_INVALID_DATA;
}
prevState.m_conditionsYesVec.push_back(conditionsYes);
// yes, return, NOT break!
return;
}
case PARSE_NORMAL:
{
if (self->m_defaultState >= 0 && cst != PARSE_ALIAS)
{
info = self->m_conditionStates.at(self->m_defaultState);
info.m_iniReadFlags |= (1<<ANIMS_COPIED_FROM_DEFAULT_STATE);
info.m_conditionsYesVec.clear();
}
// no, we do not currently require a default state, cuz it would break the exiting INI
// files too badly. maybe someday.
// else
// {
// DEBUG_CRASH(("*** ASSET ERROR: you must specify a default state\n"));
// throw INI_INVALID_DATA;
// }
ModelConditionFlags conditionsYes;
#if defined(_DEBUG) || defined(_INTERNAL)
AsciiString description;
conditionsYes.parse(ini, &description);
info.m_description.clear();
info.m_description.concat(TheThingTemplateBeingParsedName);
info.m_description.concat("\n ");
info.m_description.concat(description);
#else
conditionsYes.parse(ini, NULL);
#endif
if (conditionsYes.anyIntersectionWith(self->m_ignoreConditionStates))
{
DEBUG_CRASH(("You should not specify bits in a state once they are used in IgnoreConditionStates (%s)\n", TheThingTemplateBeingParsedName.str()));
throw INI_INVALID_DATA;
}
if (self->m_defaultState < 0 && self->m_conditionStates.empty() && conditionsYes.any())
{
// it doesn't actually NEED to be first, but it does need to be present, and this is the simplest way to enforce...
DEBUG_CRASH(("*** ASSET ERROR: when not using DefaultConditionState, the first ConditionState must be for NONE (%s)\n",TheThingTemplateBeingParsedName.str()));
throw INI_INVALID_DATA;
}
if (!conditionsYes.any() && self->m_defaultState >= 0)
{
DEBUG_CRASH(("*** ASSET ERROR: you may not specify both a Default state and a Conditions=None state"));
throw INI_INVALID_DATA;
}
if (doesStateExist(self->m_conditionStates, conditionsYes))
{
DEBUG_CRASH(("*** ASSET ERROR: duplicate condition states are not currently allowed (%s)",info.m_description.str()));
throw INI_INVALID_DATA;
}
DEBUG_ASSERTCRASH(info.m_conditionsYesVec.size() == 0, ("*** ASSET ERROR: nonempty m_conditionsYesVec.size(), see srj"));
info.m_conditionsYesVec.clear();
info.m_conditionsYesVec.push_back(conditionsYes);
}
break;
}
ini->initFromINI(&info, myFieldParse);
if (info.m_modelName.isEmpty())
{
DEBUG_CRASH(("*** ASSET ERROR: you must specify a model name"));
throw INI_INVALID_DATA;
}
else if (info.m_modelName.isNone())
{
info.m_modelName.clear();
}
if ((info.m_iniReadFlags & (1<<GOT_IDLE_ANIMS)) && (info.m_iniReadFlags & (1<<GOT_NONIDLE_ANIMS)))
{
DEBUG_CRASH(("*** ASSET ERROR: you should not specify both Animations and IdleAnimations for the same state"));
throw INI_INVALID_DATA;
}
if ((info.m_iniReadFlags & (1<<GOT_IDLE_ANIMS)) && (info.m_mode != RenderObjClass::ANIM_MODE_ONCE && info.m_mode != RenderObjClass::ANIM_MODE_ONCE_BACKWARDS))
{
DEBUG_CRASH(("*** ASSET ERROR: Idle Anims should always use ONCE or ONCE_BACKWARDS (%s)\n",TheThingTemplateBeingParsedName.str()));
throw INI_INVALID_DATA;
}
info.m_validStuff &= ~ModelConditionInfo::HAS_PROJECTILE_BONES;
for (int wslot = 0; wslot < WEAPONSLOT_COUNT; ++wslot)
{
if (info.m_weaponProjectileLaunchBoneName[wslot].isNotEmpty())
{
info.m_validStuff |= ModelConditionInfo::HAS_PROJECTILE_BONES;
break;
}
}
if (cst == PARSE_TRANSITION)
{
if (info.m_iniReadFlags & (1<<GOT_IDLE_ANIMS))
{
DEBUG_CRASH(("*** ASSET ERROR: Transition States should not specify Idle anims"));
throw INI_INVALID_DATA;
}
if (info.m_mode != RenderObjClass::ANIM_MODE_ONCE && info.m_mode != RenderObjClass::ANIM_MODE_ONCE_BACKWARDS)
{
DEBUG_CRASH(("*** ASSET ERROR: Transition States should always use ONCE or ONCE_BACKWARDS"));
throw INI_INVALID_DATA;
}
if (info.m_transitionKey != NAMEKEY_INVALID || info.m_allowToFinishKey != NAMEKEY_INVALID)
{
DEBUG_CRASH(("*** ASSET ERROR: Transition States must not have transition keys or m_allowToFinishKey"));
throw INI_INVALID_DATA;
}
self->m_transitionMap[info.m_transitionSig] = info;
}
else
{
self->m_conditionStates.push_back(info);
}
}
//-------------------------------------------------------------------------------------------------
static Int countOnBits(UnsignedInt val)
{
Int count = 0;
for (Int i = 0; i < 32; ++i)
{
if (val & 1)
++count;
val >>= 1;
}
return count;
}
//-------------------------------------------------------------------------------------------------
const ModelConditionInfo* W3DModelDrawModuleData::findBestInfo(const ModelConditionFlags& c) const
{
ModelConditionFlags bits = c;
bits.clear(m_ignoreConditionStates);
return m_conditionStateMap.findBestInfo(m_conditionStates, bits);
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
W3DModelDraw::W3DModelDraw(Thing *thing, const ModuleData* moduleData) : DrawModule(thing, moduleData)
{
int i;
m_animationMode = RenderObjClass::ANIM_MODE_LOOP;
m_hideHeadlights = true;
m_pauseAnimation = false;
m_curState = NULL;
m_hexColor = 0;
m_renderObject = NULL;
m_shadow = NULL;
m_shadowEnabled = TRUE;
m_terrainDecal = NULL;
m_trackRenderObject = NULL;
m_whichAnimInCurState = -1;
m_nextState = NULL;
m_nextStateAnimLoopDuration = NO_NEXT_DURATION;
for (i = 0; i < WEAPONSLOT_COUNT; ++i)
{
m_weaponRecoilInfoVec[i].clear();
}
m_needRecalcBoneParticleSystems = false;
m_fullyObscuredByShroud = false;
// only validate the current time-of-day and weather conditions by default.
getW3DModelDrawModuleData()->validateStuffForTimeAndWeather(getDrawable(),
TheGlobalData->m_timeOfDay == TIME_OF_DAY_NIGHT,
TheGlobalData->m_weather == WEATHER_SNOWY);
ModelConditionFlags emptyFlags;
const ModelConditionInfo* info = findBestInfo(emptyFlags);
if (!info)
{
DEBUG_CRASH(("*** ASSET ERROR: all draw modules must have an IDLE state\n"));
throw INI_INVALID_DATA;
}
Drawable* draw = getDrawable();
Object* obj = draw ? draw->getObject() : NULL;
if (obj)
{
if (TheGlobalData->m_timeOfDay == TIME_OF_DAY_NIGHT)
m_hexColor = obj->getNightIndicatorColor();
else
m_hexColor = obj->getIndicatorColor();
}
setModelState(info);
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::onDrawableBoundToObject(void)
{
getW3DModelDrawModuleData()->validateStuffForTimeAndWeather(getDrawable(),
TheGlobalData->m_timeOfDay == TIME_OF_DAY_NIGHT,
TheGlobalData->m_weather == WEATHER_SNOWY);
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
W3DModelDraw::~W3DModelDraw(void)
{
if (m_trackRenderObject && TheTerrainTracksRenderObjClassSystem)
{
TheTerrainTracksRenderObjClassSystem->unbindTrack(m_trackRenderObject);
m_trackRenderObject = NULL;
}
nukeCurrentRender(NULL);
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::doStartOrStopParticleSys()
{
Bool hidden = getDrawable()->isDrawableEffectivelyHidden() || m_fullyObscuredByShroud;
for (std::vector<ParticleSysTrackerType>::const_iterator it = m_particleSystemIDs.begin(); it != m_particleSystemIDs.end(); ++it)
//for (std::vector<ParticleSystemID>::const_iterator it = m_particleSystemIDs.begin(); it != m_particleSystemIDs.end(); ++it)
{
ParticleSystem *sys = TheParticleSystemManager->findParticleSystem((*it).id);
if (sys != NULL) {
// this can be NULL
if (hidden) {
sys->stop();
} else {
sys->start();
}
}
}
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::setHidden(Bool hidden)
{
if (m_renderObject)
m_renderObject->Set_Hidden(hidden);
if (m_shadow)
m_shadow->enableShadowRender(!hidden);
m_shadowEnabled = hidden;
if (m_terrainDecal)
m_terrainDecal->enableShadowRender(!hidden);
if (m_trackRenderObject && hidden)
{ const Coord3D* pos = getDrawable()->getPosition();
m_trackRenderObject->addCapEdgeToTrack(pos->x,pos->y);
}
doStartOrStopParticleSys();
}
/**Free all data used by this model's shadow. This is used to dynamically enable/disable shadows by the options screen*/
void W3DModelDraw::releaseShadows(void) ///< frees all shadow resources used by this module - used by Options screen.
{
if (m_shadow)
m_shadow->release();
m_shadow = NULL;
}
/** Create shadow resources if not already present. This is used to dynamically enable/disable shadows by the options screen*/
void W3DModelDraw::allocateShadows(void)
{
const ThingTemplate *tmplate=getDrawable()->getTemplate();
//Check if we don't already have a shadow but need one for this type of model.
if (m_shadow == NULL && m_renderObject && TheW3DShadowManager && tmplate->getShadowType() != SHADOW_NONE)
{
Shadow::ShadowTypeInfo shadowInfo;
strcpy(shadowInfo.m_ShadowName, tmplate->getShadowTextureName().str());
DEBUG_ASSERTCRASH(shadowInfo.m_ShadowName[0] != '\0', ("this should be validated in ThingTemplate now"));
shadowInfo.allowUpdates = FALSE; //shadow image will never update
shadowInfo.allowWorldAlign = TRUE; //shadow image will wrap around world objects
shadowInfo.m_type = (ShadowType)tmplate->getShadowType();
shadowInfo.m_sizeX = tmplate->getShadowSizeX();
shadowInfo.m_sizeY = tmplate->getShadowSizeY();
shadowInfo.m_offsetX = tmplate->getShadowOffsetX();
shadowInfo.m_offsetY = tmplate->getShadowOffsetY();
m_shadow = TheW3DShadowManager->addShadow(m_renderObject, &shadowInfo);
if (m_shadow)
{ m_shadow->enableShadowInvisible(m_fullyObscuredByShroud);
if (m_renderObject->Is_Hidden() || !m_shadowEnabled)
m_shadow->enableShadowRender(FALSE);
}
}
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::setShadowsEnabled(Bool enable)
{
if (m_shadow)
m_shadow->enableShadowRender(enable);
m_shadowEnabled = enable;
}
/**collect some stats about the rendering cost of this draw module */
#if defined(_DEBUG) || defined(_INTERNAL)
void W3DModelDraw::getRenderCost(RenderCost & rc) const
{
getRenderCostRecursive(rc,m_renderObject);
if (m_shadow)
m_shadow->getRenderCost(rc);
}
#endif //_DEBUG || _INTERNAL
/**recurse through sub-objs to collect stats about the rendering cost of this draw module */
#if defined(_DEBUG) || defined(_INTERNAL)
void W3DModelDraw::getRenderCostRecursive(RenderCost & rc,RenderObjClass * robj) const
{
if (robj == NULL) return;
// recurse through sub-objects
for (int i=0; i<robj->Get_Num_Sub_Objects(); i++) {
RenderObjClass * sub_obj = robj->Get_Sub_Object(i);
getRenderCostRecursive(rc,sub_obj);
REF_PTR_RELEASE(sub_obj);
}
// Only consider visible sub-objects. Some vehicles have hidden headlight cones for example
// that are not normally rendered.
if (robj->Is_Not_Hidden_At_All()) {
// collect stats from meshes
if (robj->Class_ID() == RenderObjClass::CLASSID_MESH) {
MeshClass * mesh = (MeshClass*)robj;
MeshModelClass * model = mesh->Peek_Model();
if (model != NULL)
{ if (model->Get_Flag(MeshGeometryClass::SORT))
rc.addSortedMeshes(1);
if (model->Get_Flag(MeshGeometryClass::SKIN))
rc.addSkinMeshes(1);
}
rc.addDrawCalls(mesh->Get_Draw_Call_Count());
}
// collect bone stats.
const HTreeClass * htree = robj->Get_HTree();
if (htree != NULL) {
rc.addBones(htree->Num_Pivots());
}
}
}
#endif //_DEBUG || _INTERNAL
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::setFullyObscuredByShroud(Bool fullyObscured)
{
if (m_fullyObscuredByShroud != fullyObscured)
{
m_fullyObscuredByShroud = fullyObscured;
if (m_shadow)
m_shadow->enableShadowInvisible(m_fullyObscuredByShroud);
if (m_terrainDecal)
m_terrainDecal->enableShadowInvisible(m_fullyObscuredByShroud);
doStartOrStopParticleSys();
}
}
//-------------------------------------------------------------------------------------------------
static Bool isAnimationComplete(RenderObjClass* r)
{
if (r && r->Class_ID() == RenderObjClass::CLASSID_HLOD)
{
HLodClass *hlod = (HLodClass*)r;
return hlod->Is_Animation_Complete();
}
return true;
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::adjustAnimSpeedToMovementSpeed()
{
// if the cur animation has a "distance covered" number, try to throttle
// the animation rate to match our actual speed.
Real dist = getCurAnimDistanceCovered();
if (dist > 0.0f)
{
const Object *obj = getDrawable()->getObject();
if (obj)
{
const PhysicsBehavior* physics = obj->getPhysics();
if (physics)
{
Real speed = physics->getVelocityMagnitude(); // in dist/frame
if (speed > 0.0f)
{
// if distance-covered is specified for this anim, adjust the frame rate
// so it appears to sync with our unit speed
Real desiredDurationInMsec = dist / speed * MSEC_PER_LOGICFRAME_REAL;
setCurAnimDurationInMsec(desiredDurationInMsec);
}
}
}
}
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::adjustTransformMtx(Matrix3D& mtx) const
{
const W3DModelDrawModuleData* d = getW3DModelDrawModuleData();
#ifdef CACHE_ATTACH_BONE
const Vector3* offset = d->getAttachToDrawableBoneOffset(getDrawable());
if (offset)
{
Vector3 tmp = mtx.Rotate_Vector(*offset);
mtx.Adjust_X_Translation(tmp.X);
mtx.Adjust_Y_Translation(tmp.Y);
mtx.Adjust_Z_Translation(tmp.Z);
}
#else
if (d->m_attachToDrawableBone.isNotEmpty())
{
// override the mtx in this case. yes, call drawable, since the bone in question is
// likely to be in another module!
Matrix3D boneMtx;
if (getDrawable()->getCurrentWorldspaceClientBonePositions(d->m_attachToDrawableBone.str(), boneMtx))
{
mtx = boneMtx;
}
else
{
DEBUG_LOG(("m_attachToDrawableBone %s not found\n",getW3DModelDrawModuleData()->m_attachToDrawableBone.str()));
}
}
#endif
if (m_curState->m_flags & (1<<ADJUST_HEIGHT_BY_CONSTRUCTION_PERCENT))
{
const Object *obj = getDrawable()->getObject();
if (obj)
{
Real pct = obj->getConstructionPercent();
if (pct >= 0.0f)
{
Real height = obj->getGeometryInfo().getMaxHeightAbovePosition();
mtx.Translate_Z(-height + (height * pct / 100.0f));
}
}
}
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::doDrawModule(const Matrix3D* transformMtx)
{
// update whether or not we should be animating.
setPauseAnimation( !getDrawable()->getShouldAnimate(getW3DModelDrawModuleData()->m_animationsRequirePower) );
Matrix3D scaledTransform;
if (getDrawable()->getInstanceScale() != 1.0f)
{
// do custom scaling of the W3D model.
scaledTransform = *transformMtx;
scaledTransform.Scale(getDrawable()->getInstanceScale());
transformMtx = &scaledTransform;
if (m_renderObject)
m_renderObject->Set_ObjectScale(getDrawable()->getInstanceScale());
}
if (isAnimationComplete(m_renderObject))
{
if (m_curState != NULL && m_nextState != NULL)
{
//DEBUG_LOG(("transition %s is complete\n",m_curState->m_description.str()));
const ModelConditionInfo* nextState = m_nextState;
UnsignedInt nextDuration = m_nextStateAnimLoopDuration;
m_nextState = NULL;
m_nextStateAnimLoopDuration = NO_NEXT_DURATION;
setModelState(nextState);
if (nextDuration != NO_NEXT_DURATION)
{
//DEBUG_LOG(("restoring pending duration of %d frames\n",nextDuration));
setAnimationLoopDuration(nextDuration);
}
}
if (m_renderObject &&
m_curState != NULL &&
m_whichAnimInCurState != -1)
{
if (m_curState->m_animations[m_whichAnimInCurState].isIdleAnim())
{
//DEBUG_LOG(("randomly switching to new idle state!\n"));
// state hasn't changed, if it's been awhile, switch the idle anim
// (yes, that's right: pass curState for prevState)
adjustAnimation(m_curState, -1.0);
}
else if (testFlagBit(m_curState->m_flags, RESTART_ANIM_WHEN_COMPLETE))
{
adjustAnimation(m_curState, -1.0);
}
}
}
adjustAnimSpeedToMovementSpeed();
// set our position in the render object to our position of the drawable
if (m_renderObject)
{
Matrix3D mtx = *transformMtx;
adjustTransformMtx(mtx);
m_renderObject->Set_Transform(mtx);
}
handleClientTurretPositioning();
recalcBonesForClientParticleSystems();
handleClientRecoil();
}
//-------------------------------------------------------------------------------------------------
const ModelConditionInfo* W3DModelDraw::findTransitionForSig(TransitionSig sig) const
{
const TransitionMap& transitionMap = getW3DModelDrawModuleData()->m_transitionMap;
TransitionMap::const_iterator it = transitionMap.find(sig);
if (it != transitionMap.end())
{
return &(*it).second;
}
return NULL;
}
//-------------------------------------------------------------------------------------------------
Real W3DModelDraw::getCurrentAnimFraction() const
{
if (m_curState != NULL
&& isAnyMaintainFrameFlagSet(m_curState->m_flags)
&& m_renderObject != NULL
&& m_renderObject->Class_ID() == RenderObjClass::CLASSID_HLOD)
{
float framenum, dummy;
int mode, numFrames;
HLodClass* hlod = (HLodClass*)m_renderObject;
/*HAnimClass* anim =*/ hlod->Peek_Animation_And_Info(framenum, numFrames, mode, dummy);
if (framenum < 0.0)
return 0.0;
else if (framenum >= numFrames)
return 1.0;
else
return (Real)framenum / ((Real)numFrames - 1);
}
else
{
return -1.0;
}
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::adjustAnimation(const ModelConditionInfo* prevState, Real prevAnimFraction)
{
if (!m_curState)
return;
// if the current state has m_animations associated, do the right thing
Int numAnims = m_curState->m_animations.size();
if (numAnims > 0)
{
if (numAnims == 1)
{
m_whichAnimInCurState = 0;
}
else if (prevState == m_curState)
{
// select an idle anim different than the currently playing one
Int animToAvoid = m_whichAnimInCurState;
while (m_whichAnimInCurState == animToAvoid)
m_whichAnimInCurState = GameClientRandomValue(0, numAnims-1);
}
else
{
m_whichAnimInCurState = GameClientRandomValue(0, numAnims-1);
}
const W3DAnimationInfo& animInfo = m_curState->m_animations[m_whichAnimInCurState];
HAnimClass* animHandle = animInfo.getAnimHandle(); // note that this now returns an ADDREFED handle, which must be released by the caller!
if (m_renderObject && animHandle)
{
Int startFrame = 0;
if (m_curState->m_mode == RenderObjClass::ANIM_MODE_ONCE_BACKWARDS ||
m_curState->m_mode == RenderObjClass::ANIM_MODE_LOOP_BACKWARDS)
{
startFrame = animHandle->Get_Num_Frames()-1;
}
if (testFlagBit(m_curState->m_flags, RANDOMIZE_START_FRAME))
{
startFrame = GameClientRandomValue(0, animHandle->Get_Num_Frames()-1);
}
else if (testFlagBit(m_curState->m_flags, START_FRAME_FIRST))
{
startFrame = 0;
}
else if (testFlagBit(m_curState->m_flags, START_FRAME_LAST))
{
startFrame = animHandle->Get_Num_Frames()-1;
}
// order is important here: MAINTAIN_FRAME_ACROSS_STATES is overridden by the other bits, above.
else if (isAnyMaintainFrameFlagSet(m_curState->m_flags) &&
prevState &&
prevState != m_curState &&
isAnyMaintainFrameFlagSet(prevState->m_flags) &&
isCommonMaintainFrameFlagSet(m_curState->m_flags, prevState->m_flags) &&
prevAnimFraction >= 0.0)
{
startFrame = REAL_TO_INT(prevAnimFraction * animHandle->Get_Num_Frames()-1);
}
m_renderObject->Set_Animation(animHandle, startFrame, m_curState->m_mode);
REF_PTR_RELEASE(animHandle);
animHandle = NULL;
if (m_renderObject->Class_ID() == RenderObjClass::CLASSID_HLOD)
{
HLodClass *hlod = (HLodClass*)m_renderObject;
Real factor = GameClientRandomValueReal( m_curState->m_animMinSpeedFactor, m_curState->m_animMaxSpeedFactor );
hlod->Set_Animation_Frame_Rate_Multiplier( factor );
}
}
}
else
{
m_whichAnimInCurState = -1;
}
}
//-------------------------------------------------------------------------------------------------
Bool W3DModelDraw::setCurAnimDurationInMsec(Real desiredDurationInMsec)
{
if (m_renderObject && m_renderObject->Class_ID() == RenderObjClass::CLASSID_HLOD)
{
HLodClass* hlod = (HLodClass*)m_renderObject;
HAnimClass* anim = hlod->Peek_Animation();
if (anim)
{
Real naturalDurationInMsec = anim->Get_Num_Frames() * 1000.0f / anim->Get_Frame_Rate();
if (naturalDurationInMsec > 0.0f && desiredDurationInMsec > 0.0f)
{
Real multiplier = naturalDurationInMsec / desiredDurationInMsec;
hlod->Set_Animation_Frame_Rate_Multiplier(multiplier);
return true;
}
}
}
return false;
}
//-------------------------------------------------------------------------------------------------
Real W3DModelDraw::getCurAnimDistanceCovered() const
{
if (m_curState != NULL && m_whichAnimInCurState >= 0)
{
const W3DAnimationInfo& animInfo = m_curState->m_animations[m_whichAnimInCurState];
#if defined(_DEBUG) || defined(_INTERNAL)
if (TheSkateDistOverride != 0.0f)
return TheSkateDistOverride;
#endif
return animInfo.getDistanceCovered();
}
return 0.0f;
}
//-------------------------------------------------------------------------------------------------
/**
Utility function to make it easier to recursively hide all objects connected to a certain bone.
We will hide all objects connected to bones which are children of boneIdx
*/
static void doHideShowBoneSubObjs(Bool state, Int numSubObjects, Int boneIdx, RenderObjClass *fullObject, const HTreeClass *htree)
{
#if 1 //(gth) fixed and tested this version
for (Int i=0; i < numSubObjects; i++)
{
bool is_child = false;
Int parentBoneIndex = fullObject->Get_Sub_Object_Bone_Index(0, i);
while (parentBoneIndex != 0)
{
parentBoneIndex = htree->Get_Parent_Index(parentBoneIndex);
if (parentBoneIndex == boneIdx)
{
is_child = true;
break;
}
}
if (is_child)
{
RenderObjClass* childObject = fullObject->Get_Sub_Object(i);
childObject->Set_Hidden(state);
childObject->Release_Ref();
}
}
#endif
#if 0 //old slow version
for (Int i=0; i < numSubObjects; i++)
{
Int childBoneIndex = fullObject->Get_Sub_Object_Bone_Index(0, i);
Int parentIndex = htree->Get_Parent_Index(childBoneIndex);
if (childBoneIndex == parentIndex)
continue;
if (parentIndex == boneIdx) // this object has our subobject as parent so copy hide state
{
RenderObjClass* childObject = fullObject->Get_Sub_Object(i);
// recurse down the hierarchy to hide all sub-children
doHideShowBoneSubObjs(state, numSubObjects, childBoneIndex, fullObject, htree);
childObject->Set_Hidden(state);
childObject->Release_Ref();
}
}
#endif
}
//-------------------------------------------------------------------------------------------------
void ModelConditionInfo::WeaponBarrelInfo::setMuzzleFlashHidden(RenderObjClass *fullObject, Bool hide) const
{
if (fullObject)
{
RenderObjClass* childObject = fullObject->Get_Sub_Object_On_Bone(0, m_muzzleFlashBone);
if (childObject)
{
childObject->Set_Hidden(hide);
childObject->Release_Ref();
}
else
{
DEBUG_CRASH(("*** ASSET ERROR: childObject %s not found in setMuzzleFlashHidden()\n",m_muzzleFlashBoneName.str()));
}
}
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::doHideShowSubObjs(const std::vector<ModelConditionInfo::HideShowSubObjInfo>* vec)
{
if (!m_renderObject)
return;
if (!vec->empty())
{
for (std::vector<ModelConditionInfo::HideShowSubObjInfo>::const_iterator it = vec->begin(); it != vec->end(); ++it)
{
Int objIndex;
RenderObjClass* subObj;
if ((subObj = m_renderObject->Get_Sub_Object_By_Name(it->subObjName.str(), &objIndex)) != NULL)
{
subObj->Set_Hidden(it->hide);
const HTreeClass *htree = m_renderObject->Get_HTree();
if (htree)
{
//get the bone of this subobject so we can hide all other child objects that use this bone
//as a parent.
Int boneIdx = m_renderObject->Get_Sub_Object_Bone_Index(0, objIndex);
doHideShowBoneSubObjs(it->hide, m_renderObject->Get_Num_Sub_Objects(), boneIdx, m_renderObject, htree);
}
subObj->Release_Ref();
}
else
{
DEBUG_CRASH(("*** ASSET ERROR: SubObject %s not found (%s)!\n",it->subObjName.str(),getDrawable()->getTemplate()->getName().str()));
}
}
}
//Kris (added Aug 2002)
//This is really important as it allows a person to override modelcondition show/hide objects. Used by the A10 strike
//September 2002 -- now used by the UpgradeSubObject system.
if( !m_subObjectVec.empty() )
{
updateSubObjects();
}
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::stopClientParticleSystems()
{
for (std::vector<ParticleSysTrackerType>::const_iterator it = m_particleSystemIDs.begin(); it != m_particleSystemIDs.end(); ++it)
//for (std::vector<ParticleSystemID>::const_iterator it = m_particleSystemIDs.begin(); it != m_particleSystemIDs.end(); ++it)
{
ParticleSystem *sys = TheParticleSystemManager->findParticleSystem((*it).id);
if (sys != NULL)
{
// this can be NULL
sys->destroy();
}
}
m_particleSystemIDs.clear();
}
//-------------------------------------------------------------------------------------------------
/*
DANGER WARNING READ ME
DANGER WARNING READ ME
DANGER WARNING READ ME
This function must not EVER do ANYTHING which can in any way, shape, or form
affect GameLogic in any way; if it does, net desyncs will occur and we
will all lose our jobs. This must remain pure-client-only, and ensure
that nothing it does can be detected, even in read-only form, by GameLogic!
DANGER WARNING READ ME
DANGER WARNING READ ME
DANGER WARNING READ ME
*/
void W3DModelDraw::handleClientTurretPositioning()
{
if (!m_curState || !(m_curState->m_validStuff & ModelConditionInfo::TURRETS_VALID))
return;
for (int tslot = 0; tslot < MAX_TURRETS; ++tslot)
{
const ModelConditionInfo::TurretInfo& tur = m_curState->m_turrets[tslot];
Real turretAngle = 0;
Real turretPitch = 0;
if (tur.m_turretAngleBone || tur.m_turretPitchBone)
{
const Object *obj = getDrawable()->getObject();
if (obj)
{
const AIUpdateInterface* ai = obj->getAIUpdateInterface();
if (ai)
ai->getTurretRotAndPitch((WhichTurretType)tslot, &turretAngle, &turretPitch);
}
// do turret, if any
if (tur.m_turretAngleBone != 0)
{
if (m_curState)
turretAngle += tur.m_turretArtAngle;
Matrix3D turretXfrm(1);
turretXfrm.Rotate_Z(turretAngle);
if (m_renderObject)
{
m_renderObject->Capture_Bone( tur.m_turretAngleBone );
m_renderObject->Control_Bone( tur.m_turretAngleBone, turretXfrm );
}
}
// do turret pitch, if any
if (tur.m_turretPitchBone != 0)
{
if (m_curState)
turretPitch += tur.m_turretArtPitch;
Matrix3D turretPitchXfrm(1);
turretPitchXfrm.Rotate_Y(-turretPitch);
if (m_renderObject)
{
m_renderObject->Capture_Bone( tur.m_turretPitchBone );
m_renderObject->Control_Bone( tur.m_turretPitchBone, turretPitchXfrm );
}
}
}
} // next tslot
}
//void W3DModelDraw::handleClientFlagPositioning()
//{
// const ModelConditionInfo::TurretInfo& tur = m_curState->m_turrets[tslot];
// Real turretAngle = TheGlobalData->m_downwindAngle;
// if (tur.m_flagAngleBone )
// {
// Matrix3D turretXfrm(1);
// turretXfrm.Rotate_Z(turretAngle);
// if (m_renderObject)
// {
// m_renderObject->Capture_Bone( tur.m_turretAngleBone );
// m_renderObject->Control_Bone( tur.m_turretAngleBone, turretXfrm );
// }
// }
//}
//-------------------------------------------------------------------------------------------------
/*
Note that, strictly speaking this code is WRONG, since it assumes it will get called every frame,
but in fact, will only get called every frame that it is visible. In practice, this isn't a big problem,
but...
@todo fix me someday (srj)
*/
void W3DModelDraw::handleClientRecoil()
{
const W3DModelDrawModuleData* d = getW3DModelDrawModuleData();
if (!(m_curState->m_validStuff & ModelConditionInfo::BARRELS_VALID))
{
return;
}
// do recoil, if any
for (int wslot = 0; wslot < WEAPONSLOT_COUNT; ++wslot)
{
if (!m_curState->m_hasRecoilBonesOrMuzzleFlashes[wslot])
continue;
const ModelConditionInfo::WeaponBarrelInfoVec& barrels = m_curState->m_weaponBarrelInfoVec[wslot];
WeaponRecoilInfoVec& recoils = m_weaponRecoilInfoVec[wslot];
Int count = barrels.size();
Int recoilCount = recoils.size();
DEBUG_ASSERTCRASH(count == recoilCount, ("Barrel count != recoil count!"));
count = (count>recoilCount)?recoilCount:count;
for (Int i = 0; i < count; ++i)
{
if (barrels[i].m_muzzleFlashBone != 0)
{
Bool hidden = recoils[i].m_state != WeaponRecoilInfo::RECOIL_START;
//DEBUG_LOG(("adjust muzzleflash %08lx for Draw %08lx state %s to %d at frame %d\n",subObjToHide,this,m_curState->m_description.str(),hidden?1:0,TheGameLogic->getFrame()));
barrels[i].setMuzzleFlashHidden(m_renderObject, hidden);
}
const Real TINY_RECOIL = 0.01f;
if (barrels[i].m_recoilBone != 0)
{
switch (recoils[i].m_state )
{
case WeaponRecoilInfo::IDLE:
// nothing
break;
case WeaponRecoilInfo::RECOIL_START:
case WeaponRecoilInfo::RECOIL:
recoils[i].m_shift += recoils[i].m_recoilRate;
recoils[i].m_recoilRate *= d->m_recoilDamping; // recoil decelerates
if (recoils[i].m_shift >= d->m_maxRecoil)
{
recoils[i].m_shift = d->m_maxRecoil;
recoils[i].m_state = WeaponRecoilInfo::SETTLE;
}
else if (fabs(recoils[i].m_recoilRate) < TINY_RECOIL)
{
recoils[i].m_state = WeaponRecoilInfo::SETTLE;
}
break;
case WeaponRecoilInfo::SETTLE:
recoils[i].m_shift -= d->m_recoilSettle;
if (recoils[i].m_shift <= 0.0f)
{
recoils[i].m_shift = 0.0f;
recoils[i].m_state = WeaponRecoilInfo::IDLE;
}
break;
}
Matrix3D gunXfrm;
gunXfrm.Make_Identity();
gunXfrm.Translate_X( -recoils[i].m_shift );
//DEBUG_ASSERTLOG(recoils[i].m_shift==0.0f,("adjust bone %d by %f\n",recoils[i].m_recoilBone,recoils[i].m_shift));
if (m_renderObject)
{
m_renderObject->Capture_Bone( barrels[i].m_recoilBone );
m_renderObject->Control_Bone( barrels[i].m_recoilBone, gunXfrm );
}
}
else
{
recoils[i].m_state = WeaponRecoilInfo::IDLE;
//DEBUG_LOG(("reset Draw %08lx state %08lx\n",this,m_curState));
}
}
}
}
//-------------------------------------------------------------------------------------------------
/*
DANGER WARNING READ ME
DANGER WARNING READ ME
DANGER WARNING READ ME
This function must not EVER do ANYTHING which can in any way, shape, or form
affect GameLogic in any way; if it does, net desyncs will occur and we
will all lose our jobs. This must remain pure-client-only, and ensure
that nothing it does can be detected, even in read-only form, by GameLogic!
DANGER WARNING READ ME
DANGER WARNING READ ME
DANGER WARNING READ ME
*/
void W3DModelDraw::recalcBonesForClientParticleSystems()
{
if (m_needRecalcBoneParticleSystems)
{
const Drawable* drawable = getDrawable();
if (drawable != NULL )
{
if( m_curState != NULL && drawable->testDrawableStatus( DRAWABLE_STATUS_NO_STATE_PARTICLES ) == FALSE )
{
for (std::vector<ParticleSysBoneInfo>::const_iterator it = m_curState->m_particleSysBones.begin(); it != m_curState->m_particleSysBones.end(); ++it)
{
ParticleSystem *sys = TheParticleSystemManager->createParticleSystem(it->particleSystemTemplate);
if (sys != NULL)
{
Coord3D pos;
pos.zero();
Real rotation = 0.0f;
Int boneIndex = m_renderObject ? m_renderObject->Get_Bone_Index(it->boneName.str()) : 0;
if (boneIndex != 0)
{
// ugh... kill the mtx so we get it in modelspace, not world space
Matrix3D originalTransform = m_renderObject->Get_Transform(); // save the transform
Matrix3D tmp(true);
tmp.Scale(getDrawable()->getScale());
m_renderObject->Set_Transform(tmp); // set to identity transform
const Matrix3D boneTransform = m_renderObject->Get_Bone_Transform(boneIndex);
Vector3 vpos = boneTransform.Get_Translation();
rotation = boneTransform.Get_Z_Rotation();
m_renderObject->Set_Transform(originalTransform); // restore it
pos.x = vpos.X;
pos.y = vpos.Y;
pos.z = vpos.Z;
}
// got the bone position...
sys->setPosition(&pos);
// and the direction, so that the system is oriented like the bone is
sys->rotateLocalTransformZ(rotation);
// Attatch it to the object...
sys->attachToDrawable(drawable);
// important: mark it as do-not-save, since we'll just re-create it when we reload.
sys->setSaveable(FALSE);
if (drawable->isDrawableEffectivelyHidden() || m_fullyObscuredByShroud)
{
sys->stop(); // don't start the systems for drawables that are hidden.
}
// store the particle system id so we can kill it later.
ParticleSysTrackerType tracker;
tracker.id = sys->getSystemID();
tracker.boneIndex = boneIndex;
m_particleSystemIDs.push_back( tracker );
}
}
}
}
m_needRecalcBoneParticleSystems = false;
}
}
//-------------------------------------------------------------------------------------------------
/*
DANGER WARNING READ ME
DANGER WARNING READ ME
DANGER WARNING READ ME
This function must not EVER do ANYTHING which can in any way, shape, or form
affect GameLogic in any way; if it does, net desyncs will occur and we
will all lose our jobs. This must remain pure-client-only, and ensure
that nothing it does can be detected, even in read-only form, by GameLogic!
DANGER WARNING READ ME
DANGER WARNING READ ME
DANGER WARNING READ ME
*/
Bool W3DModelDraw::updateBonesForClientParticleSystems()
{
const Drawable* drawable = getDrawable();
if (drawable != NULL && m_curState != NULL && m_renderObject != NULL )
{
for (std::vector<ParticleSysTrackerType>::const_iterator it = m_particleSystemIDs.begin(); it != m_particleSystemIDs.end(); ++it)
{
ParticleSystem *sys = TheParticleSystemManager->findParticleSystem((*it).id);
Int boneIndex = (*it).boneIndex;
if ( (sys != NULL) && (boneIndex != 0) )
{
Matrix3D originalTransform = m_renderObject->Get_Transform();
Matrix3D tmp(1);
tmp.Scale(drawable->getScale());
m_renderObject->Set_Transform(tmp);
const Matrix3D boneTransform = m_renderObject->Get_Bone_Transform(boneIndex);// just a little worried about state changes
Vector3 vpos = boneTransform.Get_Translation();
Real rotation = boneTransform.Get_Z_Rotation();
m_renderObject->Set_Transform(originalTransform);
Coord3D pos;
pos.x = vpos.X;
pos.y = vpos.Y;
pos.z = vpos.Z;
sys->setPosition(&pos);
sys->rotateLocalTransformZ(rotation);
}
}
}// end if Drawable
return TRUE;
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::setTerrainDecal(TerrainDecalType type)
{
if (m_terrainDecal)
m_terrainDecal->release();
m_terrainDecal = NULL;
if (type == TERRAIN_DECAL_NONE || type >= TERRAIN_DECAL_MAX)
//turning off decals on this object. (or bad value.)
return;
const ThingTemplate *tmplate=getDrawable()->getTemplate();
//create a new terrain decal
Shadow::ShadowTypeInfo decalInfo;
decalInfo.allowUpdates = FALSE; //shadow image will never update
decalInfo.allowWorldAlign = TRUE; //shadow image will wrap around world objects
decalInfo.m_type = SHADOW_ALPHA_DECAL;
//decalInfo.m_type = SHADOW_ADDITIVE_DECAL;//temporary kluge to test graphics
strcpy(decalInfo.m_ShadowName,TerrainDecalTextureName[type]);
decalInfo.m_sizeX = tmplate->getShadowSizeX();
decalInfo.m_sizeY = tmplate->getShadowSizeY();
decalInfo.m_offsetX = tmplate->getShadowOffsetX();
decalInfo.m_offsetY = tmplate->getShadowOffsetY();
if (TheProjectedShadowManager)
m_terrainDecal = TheProjectedShadowManager->addDecal(m_renderObject,&decalInfo);
if (m_terrainDecal)
{ m_terrainDecal->enableShadowInvisible(m_fullyObscuredByShroud);
m_terrainDecal->enableShadowRender(m_shadowEnabled);
}
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::setTerrainDecalSize(Real x, Real y)
{
if (m_terrainDecal)
{
m_terrainDecal->setSize(x,y);
}
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::setTerrainDecalOpacity(Real o)
{
if (m_terrainDecal)
{
m_terrainDecal->setOpacity((Int)(255.0f * o));
}
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::nukeCurrentRender(Matrix3D* xform)
{
// this needs to be "dirtied" so that the new pausing of the animation will be triggered.
m_pauseAnimation = false;
// changing geometry, so we need to remove shadow if present
if (m_shadow)
m_shadow->release();
m_shadow = NULL;
if(m_terrainDecal)
m_terrainDecal->release();
m_terrainDecal = NULL;
// remove existing render object from the scene
if (m_renderObject)
{
// save the transform for the new model
if (xform)
*xform = m_renderObject->Get_Transform();
W3DDisplay::m_3DScene->Remove_Render_Object(m_renderObject);
REF_PTR_RELEASE(m_renderObject);
m_renderObject = NULL;
}
else
{
if (xform)
{
*xform = *getDrawable()->getTransformMatrix();
}
}
}
//-------------------------------------------------------------------------------------------------
#if defined(_DEBUG) || defined(_INTERNAL) //art wants to see buildings without flags as a test.
void W3DModelDraw::hideGarrisonFlags(Bool hide)
{
if (!m_renderObject)
return;
Int objIndex;
RenderObjClass* subObj;
if ((subObj = m_renderObject->Get_Sub_Object_By_Name("POLE", &objIndex)) != NULL)
{
subObj->Set_Hidden(hide);
const HTreeClass *htree = m_renderObject->Get_HTree();
if (htree)
{
//get the bone of this subobject so we can hide all other child objects that use this bone
//as a parent.
Int boneIdx = m_renderObject->Get_Sub_Object_Bone_Index(0, objIndex);
doHideShowBoneSubObjs(hide, m_renderObject->Get_Num_Sub_Objects(), boneIdx, m_renderObject, htree);
}
subObj->Release_Ref();
}
}
#endif
//-------------------------------------------------------------------------------------------------
/** Hides all subobjects which are headlights. Used to disable lights on models during the day.*/
void W3DModelDraw::hideAllHeadlights(Bool hide)
{
if (m_renderObject)
{
for (Int subObj = 0; subObj < m_renderObject->Get_Num_Sub_Objects(); subObj++)
{
RenderObjClass* test = m_renderObject->Get_Sub_Object(subObj);
if (strstr(test->Get_Name(),"HEADLIGHT"))
{
test->Set_Hidden(hide);
}
test->Release_Ref();
}
}
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::hideAllMuzzleFlashes(const ModelConditionInfo* state, RenderObjClass* renderObject)
{
if (!state || !renderObject)
return;
if (!(state->m_validStuff & ModelConditionInfo::BARRELS_VALID))
{
return;
}
for (int wslot = 0; wslot < WEAPONSLOT_COUNT; ++wslot)
{
if (!state->m_hasRecoilBonesOrMuzzleFlashes[wslot])
continue;
const ModelConditionInfo::WeaponBarrelInfoVec& barrels = state->m_weaponBarrelInfoVec[wslot];
for (ModelConditionInfo::WeaponBarrelInfoVec::const_iterator it = barrels.begin(); it != barrels.end(); ++it)
{
if (it->m_muzzleFlashBone != 0)
{
it->setMuzzleFlashHidden(renderObject, true);
}
}
}
}
//-------------------------------------------------------------------------------------------------
static Bool turretNamesDiffer(const ModelConditionInfo* a, const ModelConditionInfo* b)
{
if (!(a->m_validStuff & ModelConditionInfo::TURRETS_VALID) || !(b->m_validStuff & ModelConditionInfo::TURRETS_VALID))
{
return true;
}
for (int i = 0; i < MAX_TURRETS; ++i)
if (a->m_turrets[i].m_turretAngleNameKey != b->m_turrets[i].m_turretAngleNameKey ||
a->m_turrets[i].m_turretPitchNameKey != b->m_turrets[i].m_turretPitchNameKey)
return true;
return false;
}
//-------------------------------------------------------------------------------------------------
/** Change the model for this drawable. If color is non-zero, it will also apply team color to the
model */
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::setModelState(const ModelConditionInfo* newState)
{
DEBUG_ASSERTCRASH(newState, ("invalid state in W3DModelDraw::setModelState\n"));
#ifdef DEBUG_OBJECT_ID_EXISTS
if (getDrawable() && getDrawable()->getObject() && getDrawable()->getObject()->getID() == TheObjectIDToDebug)
{
DEBUG_LOG(("REQUEST switching to state %s for obj %s %d\n",newState->m_description.str(),getDrawable()->getObject()->getTemplate()->getName().str(),getDrawable()->getObject()->getID()));
}
#endif
const ModelConditionInfo* nextState = NULL;
if (m_curState != NULL && newState != NULL)
{
// if the requested state is the current state (and nothing is pending),
// or if the requested state is pending, just punt.
//
// note that if the requested state matches the current state AND
// we also have a pending state, then we nuke both of 'em. This sounds
// weird, but is deliberate: nextState and newState will always be "real" states (or null),
// leaving us these possibilities:
//
// -- curState is a transition state
// --in this case, new state should take precedence (unless there's a wait-to-finish marking,
// which would be handled by the else clause)
//
// -- curState is a real state, nextState is a real state with a wait-to-finish clause
// -- if curState == newState, presume that we should restart curState, thus punting thepending nextState
// -- if curState != newState, presume we should switch to it, thus punting curState and nextState
//
// -- curState is a real state, nextState is a real state without a wait-to-finish clause
// -- should be impossible!
if ((m_curState == newState && m_nextState == NULL) ||
(m_curState != NULL && m_nextState == newState))
{
#ifdef DEBUG_OBJECT_ID_EXISTS
if (getDrawable() && getDrawable()->getObject() && getDrawable()->getObject()->getID() == TheObjectIDToDebug)
{
DEBUG_LOG(("IGNORE duplicate state %s for obj %s %d\n",newState->m_description.str(),getDrawable()->getObject()->getTemplate()->getName().str(),getDrawable()->getObject()->getID()));
}
#endif
// I don't think he'll be interested...
// he's already got one, you see
return;
}
// check for allow-to-finish implicit transitions
else if (newState != m_curState &&
newState->m_allowToFinishKey != NAMEKEY_INVALID &&
newState->m_allowToFinishKey == m_curState->m_transitionKey &&
m_renderObject &&
!isAnimationComplete(m_renderObject))
{
#ifdef DEBUG_OBJECT_ID_EXISTS
if (getDrawable() && getDrawable()->getObject() && getDrawable()->getObject()->getID() == TheObjectIDToDebug)
{
DEBUG_LOG(("ALLOW_TO_FINISH state %s for obj %s %d\n",newState->m_description.str(),getDrawable()->getObject()->getTemplate()->getName().str(),getDrawable()->getObject()->getID()));
}
#endif
m_nextState = newState;
m_nextStateAnimLoopDuration = NO_NEXT_DURATION;
return;
}
// check for a normal->normal state transition
else if (newState != m_curState &&
m_curState->m_transitionKey != NAMEKEY_INVALID &&
newState->m_transitionKey != NAMEKEY_INVALID)
{
TransitionSig sig = buildTransitionSig(m_curState->m_transitionKey, newState->m_transitionKey);
const ModelConditionInfo* transState = findTransitionForSig(sig);
if (transState != NULL)
{
#ifdef DEBUG_OBJECT_ID_EXISTS
if (getDrawable() && getDrawable()->getObject() && getDrawable()->getObject()->getID() == TheObjectIDToDebug)
{
DEBUG_LOG(("using TRANSITION state %s before requested state %s for obj %s %d\n",transState->m_description.str(),newState->m_description.str(),getDrawable()->getObject()->getTemplate()->getName().str(),getDrawable()->getObject()->getID()));
}
#endif
nextState = newState;
newState = transState;
}
}
}
// get this here, before we change anything... we'll need it to pass to adjustAnimation (srj)
Real prevAnimFraction = getCurrentAnimFraction();
//
// Set up any particle effects for the new model. Also stop the old ones, note that we
// will never allow the placement of new ones if the status bit is set that tells us
// we should not automatically create particle systems for the model condition states
//
if( getDrawable()->testDrawableStatus( DRAWABLE_STATUS_NO_STATE_PARTICLES ) == FALSE )
m_needRecalcBoneParticleSystems = true;
// always stop particle systems now
stopClientParticleSystems();
// and always hide muzzle flashes, in case modelstate and model have crossed at the same time
hideAllMuzzleFlashes(newState, m_renderObject);
// note that different states might use the same model; for these, don't go thru the
// expense of creating a new render-object. (exception: if color is changing, or subobjs are changing,
// or a few other things...)
if (m_curState == NULL ||
newState->m_modelName != m_curState->m_modelName ||
turretNamesDiffer(newState, m_curState)
// srj sez: I'm not sure why we want to do the "hard stuff" if we have projectile bones; I think
// it is a holdover from days gone by when bones were handled quite differently, rather than being cached.
// but doing this hard stuff is a lot more work, and I think it's unnecessary, so let's remove this.
//|| (newState->m_validStuff & ModelConditionInfo::HAS_PROJECTILE_BONES)
)
{
Matrix3D transform;
nukeCurrentRender(&transform);
Drawable* draw = getDrawable();
// create a new render object and set into drawable
if (newState->m_modelName.isEmpty())
{
m_renderObject = NULL;
}
else
{
m_renderObject = W3DDisplay::m_assetManager->Create_Render_Obj(newState->m_modelName.str(), draw->getScale(), m_hexColor);
DEBUG_ASSERTCRASH(m_renderObject, ("*** ASSET ERROR: Model %s not found!\n",newState->m_modelName.str()));
}
//BONEPOS_LOG(("validateStuff() from within W3DModelDraw::setModelState()\n"));
//BONEPOS_DUMPREAL(draw->getScale());
newState->validateStuff(m_renderObject, draw->getScale(), getW3DModelDrawModuleData()->m_extraPublicBones);
// ensure that any muzzle flashes from the *new* state, start out hidden...
// hideAllMuzzleFlashes(newState, m_renderObject);//moved to above
rebuildWeaponRecoilInfo(newState);
doHideShowSubObjs(&newState->m_hideShowVec);
#if defined(_DEBUG) || defined(_INTERNAL) //art wants to see buildings without flags as a test.
if (TheGlobalData->m_hideGarrisonFlags && draw->isKindOf(KINDOF_STRUCTURE))
hideGarrisonFlags(TRUE);
#endif
const ThingTemplate *tmplate = draw->getTemplate();
// set up tracks, if not already set.
if (m_renderObject &&
TheGlobalData->m_makeTrackMarks &&
!m_trackRenderObject &&
TheTerrainTracksRenderObjClassSystem != NULL &&
!getW3DModelDrawModuleData()->m_trackFile.isEmpty())
{
m_trackRenderObject = TheTerrainTracksRenderObjClassSystem->bindTrack(m_renderObject, 1.0f*MAP_XY_FACTOR, getW3DModelDrawModuleData()->m_trackFile.str());
if (draw && m_trackRenderObject)
m_trackRenderObject->setOwnerDrawable(draw);
}
// set up shadows
if (m_renderObject && TheW3DShadowManager && tmplate->getShadowType() != SHADOW_NONE)
{
Shadow::ShadowTypeInfo shadowInfo;
strcpy(shadowInfo.m_ShadowName, tmplate->getShadowTextureName().str());
DEBUG_ASSERTCRASH(shadowInfo.m_ShadowName[0] != '\0', ("this should be validated in ThingTemplate now"));
shadowInfo.allowUpdates = FALSE; //shadow image will never update
shadowInfo.allowWorldAlign = TRUE; //shadow image will wrap around world objects
shadowInfo.m_type = (ShadowType)tmplate->getShadowType();
shadowInfo.m_sizeX = tmplate->getShadowSizeX();
shadowInfo.m_sizeY = tmplate->getShadowSizeY();
shadowInfo.m_offsetX = tmplate->getShadowOffsetX();
shadowInfo.m_offsetY = tmplate->getShadowOffsetY();
m_shadow = TheW3DShadowManager->addShadow(m_renderObject, &shadowInfo, draw);
if (m_shadow)
{ m_shadow->enableShadowInvisible(m_fullyObscuredByShroud);
m_shadow->enableShadowRender(m_shadowEnabled);
}
}
if( m_renderObject )
{
// set collision type for render object. Used by WW3D2 collision code.
if (tmplate->isKindOf(KINDOF_SELECTABLE))
{
m_renderObject->Set_Collision_Type( PICK_TYPE_SELECTABLE );
}
if( tmplate->isKindOf( KINDOF_SHRUBBERY ))
{
m_renderObject->Set_Collision_Type( PICK_TYPE_SHRUBBERY );
}
if( tmplate->isKindOf( KINDOF_MINE ))
{
m_renderObject->Set_Collision_Type( PICK_TYPE_MINES );
}
if( tmplate->isKindOf( KINDOF_FORCEATTACKABLE ))
{
m_renderObject->Set_Collision_Type( PICK_TYPE_FORCEATTACKABLE );
}
if( tmplate->isKindOf( KINDOF_CLICK_THROUGH ))
{
m_renderObject->Set_Collision_Type( 0 );
}
Object *obj = draw->getObject();
if( obj )
{
// for non bridge objects we adjust some collision types
if( obj->isKindOf( KINDOF_BRIDGE ) == FALSE &&
obj->isKindOf( KINDOF_BRIDGE_TOWER ) == FALSE )
{
if( obj->isKindOf( KINDOF_STRUCTURE ) && draw->getModelConditionFlags().test( MODELCONDITION_RUBBLE ) )
{
//A dead building, -- don't allow the user to click on rubble! Treat it as a location instead.
m_renderObject->Set_Collision_Type( 0 );
}
else if( obj->isEffectivelyDead() )
{
//A dead object, -- don't allow the user to click on rubble/hulks! Treat it as a location instead.
m_renderObject->Set_Collision_Type( 0 );
}
}
}
// add render object to our scene
W3DDisplay::m_3DScene->Add_Render_Object(m_renderObject);
// tie in our drawable as the user data pointer in the render object
m_renderObject->Set_User_Data(draw->getDrawableInfo());
setTerrainDecal(draw->getTerrainDecalType());
//We created a new render object so we need to preserve the visibility state
//of the previous render object.
if (draw->isDrawableEffectivelyHidden())
{
m_renderObject->Set_Hidden(TRUE);
if (m_shadow)
m_shadow->enableShadowRender(FALSE);
m_shadowEnabled = FALSE;
}
//
// set the transform for the new model to that we saved before, we do this so that the
// model transition is smooth and will immediately appear at the same orientation and location
// as the previous one
//
m_renderObject->Set_Transform(transform);
onRenderObjRecreated();
}
}
else
{
//BONEPOS_LOG(("validateStuff() from within W3DModelDraw::setModelState()\n"));
//BONEPOS_DUMPREAL(getDrawable()->getScale());
newState->validateStuff(m_renderObject, getDrawable()->getScale(), getW3DModelDrawModuleData()->m_extraPublicBones);
rebuildWeaponRecoilInfo(newState);
// ensure that any muzzle flashes from the *previous* state, are hidden...
// hideAllMuzzleFlashes(m_curState, m_renderObject);// moved to above
doHideShowSubObjs(&newState->m_hideShowVec);
}
hideAllHeadlights(m_hideHeadlights);
const ModelConditionInfo* prevState = m_curState; // save, to pass to adjustAnimation (could be null)
m_curState = newState;
m_nextState = nextState;
m_nextStateAnimLoopDuration = NO_NEXT_DURATION;
adjustAnimation(prevState, prevAnimFraction);
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::replaceModelConditionState(const ModelConditionFlags& c)
{
m_hideHeadlights = c.test(MODELCONDITION_NIGHT) ? false : true;
const ModelConditionInfo* info = findBestInfo(c);
if (info)
setModelState(info);
hideAllHeadlights(m_hideHeadlights);
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::setSelectable(Bool selectable)
{
// set collision type for render object. Used by WW3D2 collision code.
if( m_renderObject )
{
int current = m_renderObject->Get_Collision_Type();
if (selectable) {
current |= PICK_TYPE_SELECTABLE;
} else {
current &= ~PICK_TYPE_SELECTABLE;
}
m_renderObject->Set_Collision_Type(current);
} // end if
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::replaceIndicatorColor(Color color)
{
if (!getW3DModelDrawModuleData()->m_okToChangeModelColor)
return;
if (getRenderObject())
{
Int newColor = (color == 0) ? 0 : (color | 0xFF000000);
if (newColor != m_hexColor)
{
m_hexColor = newColor;
// set these to NULL to force a regen of everything in setModelState.
const ModelConditionInfo* tmp = m_curState;
m_curState = NULL;
m_nextState = NULL;
m_nextStateAnimLoopDuration = NO_NEXT_DURATION;
setModelState(tmp);
}
}
}
//-------------------------------------------------------------------------------------------------
// this method must ONLY be called from the client, NEVER From the logic, not even indirectly.
Bool W3DModelDraw::clientOnly_getRenderObjInfo(Coord3D* pos, Real* boundingSphereRadius, Matrix3D* transform) const
{
if (!m_renderObject)
return false;
Vector3 objPos = m_renderObject->Get_Position(); //get position of object
pos->x = objPos.X;
pos->y = objPos.Y;
pos->z = objPos.Z;
*transform = m_renderObject->Get_Transform();
*boundingSphereRadius = m_renderObject->Get_Bounding_Sphere().Radius;
return true;
}
//-------------------------------------------------------------------------------------------------
Bool W3DModelDraw::getProjectileLaunchOffset(
const ModelConditionFlags& condition,
WeaponSlotType wslot,
Int specificBarrelToUse,
Matrix3D* launchPos,
WhichTurretType tur,
Coord3D* turretRotPos,
Coord3D* turretPitchPos
) const
{
/*
Note, this recalcs the state every time, rather than using m_curState,
because m_curState could be a transition state, and we really need
to get the pristine bone(s) for the state that logic believes to be current,
not the one the client might currently be using...
*/
const ModelConditionInfo* stateToUse = findBestInfo(condition);
if (!stateToUse)
{
CRCDEBUG_LOG(("can't find best info\n"));
//BONEPOS_LOG(("can't find best info\n"));
return false;
}
#if defined(_DEBUG) || defined(_INTERNAL)
CRCDEBUG_LOG(("W3DModelDraw::getProjectileLaunchOffset() for %s\n",
stateToUse->getDescription().str()));
#endif
#ifdef INTENSE_DEBUG
AsciiString flags;
for (Int i=0; i<condition.size(); ++i)
{
if (condition.test(i))
{
if (flags.isNotEmpty())
flags.concat(',');
flags.concat(condition.getNameFromSingleBit(i));
}
}
#endif // INTENSE_DEBUG
const W3DModelDrawModuleData* d = getW3DModelDrawModuleData();
//CRCDEBUG_LOG(("validateStuffs() from within W3DModelDraw::getProjectileLaunchOffset()\n"));
//DUMPREAL(getDrawable()->getScale());
//BONEPOS_LOG(("validateStuffs() from within W3DModelDraw::getProjectileLaunchOffset()\n"));
//BONEPOS_DUMPREAL(getDrawable()->getScale());
stateToUse->validateStuff(NULL, getDrawable()->getScale(), d->m_extraPublicBones);
DEBUG_ASSERTCRASH(stateToUse->m_transitionSig == NO_TRANSITION,
("It is never legal to getProjectileLaunchOffset from a Transition state (they vary on a per-client basis)... however, we can fix this (see srj)\n"));
DEBUG_ASSERTCRASH(specificBarrelToUse >= 0, ("specificBarrelToUse should now always be explicit"));
#ifdef CACHE_ATTACH_BONE
#else
Coord3D techOffset;
techOffset.zero();
// must use pristine bone here since the result is used by logic
Matrix3D pivot;
if (d->m_attachToDrawableBone.isNotEmpty() &&
getDrawable()->getPristineBonePositions( d->m_attachToDrawableBone.str(), 0, NULL, &pivot, 1 ) == 1)
{
pivot.Pre_Rotate_Z(getDrawable()->getOrientation());
techOffset.x = pivot.Get_X_Translation();
techOffset.y = pivot.Get_Y_Translation();
techOffset.z = pivot.Get_Z_Translation();
}
#endif
CRCDEBUG_LOG(("wslot = %d\n", wslot));
const ModelConditionInfo::WeaponBarrelInfoVec& wbvec = stateToUse->m_weaponBarrelInfoVec[wslot];
if( wbvec.empty() )
{
// Can't find the launch pos, but they might still want the other info they asked for
CRCDEBUG_LOG(("empty wbvec\n"));
//BONEPOS_LOG(("empty wbvec\n"));
launchPos = NULL;
}
else
{
if (specificBarrelToUse < 0 || specificBarrelToUse >= wbvec.size())
specificBarrelToUse = 0;
if (launchPos)
{
CRCDEBUG_LOG(("specificBarrelToUse = %d\n", specificBarrelToUse));
*launchPos = wbvec[specificBarrelToUse].m_projectileOffsetMtx;
if (tur != TURRET_INVALID)
{
launchPos->Pre_Rotate_Z(stateToUse->m_turrets[tur].m_turretArtAngle);
launchPos->Pre_Rotate_Y(-stateToUse->m_turrets[tur].m_turretArtPitch);
}
#ifdef CACHE_ATTACH_BONE
#else
launchPos->Adjust_Translation( Vector3( techOffset.x, techOffset.y, techOffset.z ) );
#endif
DUMPMATRIX3D(launchPos);
}
}
if (turretRotPos)
turretRotPos->zero();
if (turretPitchPos)
turretPitchPos->zero();
if (tur != TURRET_INVALID)
{
#ifdef CACHE_ATTACH_BONE
const Vector3* offset = d->getAttachToDrawableBoneOffset(getDrawable());
#endif
const ModelConditionInfo::TurretInfo& turInfo = stateToUse->m_turrets[tur];
if (turretRotPos)
{
if (turInfo.m_turretAngleNameKey != NAMEKEY_INVALID &&
!stateToUse->findPristineBonePos(turInfo.m_turretAngleNameKey, *turretRotPos))
{
DEBUG_CRASH(("*** ASSET ERROR: TurretBone %s not found!\n",KEYNAME(turInfo.m_turretAngleNameKey).str()));
}
#ifdef CACHE_ATTACH_BONE
if (offset)
{
turretRotPos->x += offset->X;
turretRotPos->y += offset->Y;
turretRotPos->z += offset->Z;
}
#endif
}
if (turretPitchPos)
{
if (turInfo.m_turretPitchNameKey != NAMEKEY_INVALID &&
!stateToUse->findPristineBonePos(turInfo.m_turretPitchNameKey, *turretPitchPos))
{
DEBUG_CRASH(("*** ASSET ERROR: TurretBone %s not found!\n",KEYNAME(turInfo.m_turretPitchNameKey).str()));
}
#ifdef CACHE_ATTACH_BONE
if (offset)
{
turretPitchPos->x += offset->X;
turretPitchPos->y += offset->Y;
turretPitchPos->z += offset->Z;
}
#endif
}
}
return launchPos != NULL;// return if LaunchPos is valid or not
}
//-------------------------------------------------------------------------------------------------
Int W3DModelDraw::getPristineBonePositionsForConditionState(
const ModelConditionFlags& condition,
const char* boneNamePrefix,
Int startIndex,
Coord3D* positions,
Matrix3D* transforms,
Int maxBones
) const
{
/*
Note, this recalcs the state every time, rather than using m_curState,
because m_curState could be a transition state, and we really need
to get the pristine bone(s) for the state that logic believes to be current,
not the one the client might currently be using...
*/
const ModelConditionInfo* stateToUse = findBestInfo(condition);
if (!stateToUse)
return 0;
// if (isValidTimeToCalcLogicStuff())
// {
// CRCDEBUG_LOG(("W3DModelDraw::getPristineBonePositionsForConditionState() - state = '%s'\n",
// stateToUse->getDescription().str()));
// //CRCDEBUG_LOG(("renderObject == NULL: %d\n", (stateToUse==m_curState)?(m_renderObject == NULL):1));
// }
//BONEPOS_LOG(("validateStuff() from within W3DModelDraw::getPristineBonePositionsForConditionState()\n"));
//BONEPOS_DUMPREAL(getDrawable()->getScale());
// we must call this every time we set m_nextState, to ensure cached bones are happy
stateToUse->validateStuff(
// if the state is the current state, pass in the current render object
// so that we don't have to re-create it!
stateToUse == m_curState ? m_renderObject : NULL,
getDrawable()->getScale(),
getW3DModelDrawModuleData()->m_extraPublicBones);
const int MAX_BONE_GET = 64;
Matrix3D tmpMtx[MAX_BONE_GET];
if (maxBones > MAX_BONE_GET)
maxBones = MAX_BONE_GET;
if (transforms == NULL)
transforms = tmpMtx;
Int posCount = 0;
Int endIndex = (startIndex == 0) ? 0 : 99;
char buffer[256];
for (Int i = startIndex; i <= endIndex; ++i)
{
if (i == 0)
strcpy(buffer, boneNamePrefix);
else
sprintf(buffer, "%s%02d", boneNamePrefix, i);
for (char *c = buffer; c && *c; ++c)
{
// convert to all-lowercase since that's how we filled in the map
*c = tolower(*c);
}
const Matrix3D* mtx = stateToUse->findPristineBone(NAMEKEY(buffer), NULL);
if (mtx)
{
transforms[posCount] = *mtx;
// if (isValidTimeToCalcLogicStuff())
// {
// DUMPMATRIX3D(mtx);
// }
}
else
{
//DEBUG_CRASH(("*** ASSET ERROR: Bone %s not found!\n",buffer));
const Object *obj = getDrawable()->getObject();
if (obj)
transforms[posCount] = *obj->getTransformMatrix();
else
transforms[posCount].Make_Identity();
break;
}
++posCount;
if (posCount >= maxBones)
break;
}
if (positions && transforms)
{
for (i = 0; i < posCount; ++i)
{
Vector3 pos = transforms[i].Get_Translation();
positions[i].x = pos.X;
positions[i].y = pos.Y;
positions[i].z = pos.Z;
// if (isValidTimeToCalcLogicStuff())
// {
// DUMPCOORD3D(&(positions[i]));
// }
}
}
// if (isValidTimeToCalcLogicStuff())
// {
// CRCDEBUG_LOG(("end of W3DModelDraw::getPristineBonePositionsForConditionState()\n"));
// }
return posCount;
}
//-------------------------------------------------------------------------------------------------
Bool W3DModelDraw::getCurrentWorldspaceClientBonePositions(const char* boneName, Matrix3D& transform) const
{
if (!m_renderObject)
return false;
Int boneIndex = m_renderObject->Get_Bone_Index(boneName);
if (boneIndex == 0)
return false;
transform = m_renderObject->Get_Bone_Transform(boneIndex);
return true;
}
//-------------------------------------------------------------------------------------------------
Int W3DModelDraw::getCurrentBonePositions(
const char* boneNamePrefix,
Int startIndex,
Coord3D* positions,
Matrix3D* transforms,
Int maxBones
) const
{
const int MAX_BONE_GET = 64;
Matrix3D tmpMtx[MAX_BONE_GET];
if (maxBones > MAX_BONE_GET)
maxBones = MAX_BONE_GET;
if (transforms == NULL)
transforms = tmpMtx;
if( !m_renderObject )
return 0;
// ugh... kill the mtx so we get it in modelspace, not world space
Matrix3D originalTransform = m_renderObject->Get_Transform(); // save the transform
// which is faster: slamming the xform (and invalidating the objects xforms)
// or inverting it ourself? gotta profile to see. (srj)
#define DO_INV
#ifdef DO_INV
Matrix3D inverse;
originalTransform.Get_Orthogonal_Inverse(inverse);
inverse.Scale(getDrawable()->getScale());
#else
Matrix3D tmp(true);
tmp.Scale(getDrawable()->getScale());
m_renderObject->Set_Transform(tmp); // set to identity transform
#endif
Int posCount = 0;
Int endIndex = (startIndex == 0) ? 0 : 99;
char buffer[256];
for (Int i = startIndex; i <= endIndex; ++i)
{
if (i == 0)
strcpy(buffer, boneNamePrefix);
else
sprintf(buffer, "%s%02d", boneNamePrefix, i);
Int boneIndex = m_renderObject->Get_Bone_Index(buffer);
if (boneIndex == 0)
break;
transforms[posCount] = m_renderObject->Get_Bone_Transform(boneIndex);
#ifdef DO_INV
transforms[posCount].preMul(inverse);
#endif
//DEBUG_ASSERTCRASH(!m_renderObject->Is_Bone_Captured(boneIndex), ("bone is captured!"));
++posCount;
if (posCount >= maxBones)
break;
}
if (positions && transforms)
{
for (i = 0; i < posCount; ++i)
{
Vector3 pos = transforms[i].Get_Translation();
positions[i].x = pos.X;
positions[i].y = pos.Y;
positions[i].z = pos.Z;
}
}
#ifdef DO_INV
#else
m_renderObject->Set_Transform(originalTransform); // restore it
#endif
return posCount;
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::reactToTransformChange( const Matrix3D* oldMtx,
const Coord3D* oldPos,
Real oldAngle )
{
// set the position of our render object
if( m_renderObject )
{
Matrix3D mtx = *getDrawable()->getTransformMatrix();
adjustTransformMtx(mtx);
m_renderObject->Set_Transform(mtx);
}
if (m_trackRenderObject)
{
Object *obj = getDrawable()->getObject();
const Coord3D* pos = getDrawable()->getPosition();
if (m_fullyObscuredByShroud)
{
m_trackRenderObject->addCapEdgeToTrack(pos->x, pos->y);
}
else
{
if (obj && obj->isSignificantlyAboveTerrain())
{
m_trackRenderObject->setAirborne();
}
m_trackRenderObject->addEdgeToTrack(pos->x, pos->y);
}
}
}
//-------------------------------------------------------------------------------------------------
const ModelConditionInfo* W3DModelDraw::findBestInfo(const ModelConditionFlags& c) const
{
return getW3DModelDrawModuleData()->findBestInfo(c);
}
//-------------------------------------------------------------------------------------------------
Int W3DModelDraw::getBarrelCount(WeaponSlotType wslot) const
{
return (m_curState && (m_curState->m_validStuff & ModelConditionInfo::BARRELS_VALID)) ?
m_curState->m_weaponBarrelInfoVec[wslot].size() : 0;
}
//-------------------------------------------------------------------------------------------------
Bool W3DModelDraw::handleWeaponFireFX(WeaponSlotType wslot, Int specificBarrelToUse, const FXList* fxl, Real weaponSpeed, const Coord3D* victimPos, Real damageRadius)
{
DEBUG_ASSERTCRASH(specificBarrelToUse >= 0, ("specificBarrelToUse should now always be explicit"));
if (!m_curState || !(m_curState->m_validStuff & ModelConditionInfo::BARRELS_VALID))
return false;
const ModelConditionInfo::WeaponBarrelInfoVec& wbvec = m_curState->m_weaponBarrelInfoVec[wslot];
if (wbvec.empty())
{
// don't do this... some other module of our drawable may have handled it.
// just return false and let the caller sort it out.
// FXList::doFXPos(fxl, getDrawable()->getPosition(), getDrawable()->getTransformMatrix(), weaponSpeed, victimPos);
return false;
}
Bool handled = false;
if (specificBarrelToUse < 0 || specificBarrelToUse > wbvec.size())
specificBarrelToUse = 0;
const ModelConditionInfo::WeaponBarrelInfo& info = wbvec[specificBarrelToUse];
if (fxl)
{
if (info.m_fxBone && m_renderObject)
{
const Object *logicObject = getDrawable()->getObject();// This is slow, so store it
if( ! m_renderObject->Is_Hidden() || (logicObject == NULL) )
{
// I can ask the drawable's bone position if I am not hidden (if I have no object I have no choice)
Matrix3D mtx = m_renderObject->Get_Bone_Transform(info.m_fxBone);
Coord3D pos;
pos.x = mtx.Get_X_Translation();
pos.y = mtx.Get_Y_Translation();
pos.z = mtx.Get_Z_Translation();
FXList::doFXPos(fxl, &pos, &mtx, weaponSpeed, victimPos, damageRadius);
}
else
{
// Else, I should just use my logic position for the effect placement.
// Things in transports regularly fire from inside (hidden), so this is not weird.
const Matrix3D *mtx;
Coord3D pos;
mtx = logicObject->getTransformMatrix();
pos = *(logicObject->getPosition());
/** @todo Once Firepoint bones are actually implemented, this matrix will become correct.
// Unless of course they decide to not have the tracers come out of the windows, but rather go towards the target.
// In that case, tracers will have to be rewritten to be "point towards secondary" instead of
// "point straight ahead" which assumes we are facing the target.
*/
FXList::doFXPos(fxl, &pos, mtx, weaponSpeed, victimPos, damageRadius);
}
handled = true;
}
else
{
DEBUG_LOG(("*** no FXBone found for a non-null FXL\n"));
}
}
if (info.m_recoilBone || info.m_muzzleFlashBone)
{
//DEBUG_LOG(("START muzzleflash %08lx for Draw %08lx state %s at frame %d\n",info.m_muzzleFlashBone,this,m_curState->m_description.str(),TheGameLogic->getFrame()));
WeaponRecoilInfo& recoil = m_weaponRecoilInfoVec[wslot][specificBarrelToUse];
recoil.m_state = WeaponRecoilInfo::RECOIL_START;
recoil.m_recoilRate = getW3DModelDrawModuleData()->m_initialRecoil;
if (info.m_muzzleFlashBone != 0)
info.setMuzzleFlashHidden(m_renderObject, false);
}
return handled;
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::setAnimationLoopDuration(UnsignedInt numFrames)
{
// this is never defined -- srj
#ifdef NO_DURATIONS_ON_TRANSITIONS
if (m_curState != NULL && m_curState->m_transition != NO_TRANSITION &&
m_nextState != NULL && m_nextState->m_transition == NO_TRANSITION)
{
DEBUG_LOG(("deferring pending duration of %d frames\n",numFrames));
m_nextStateAnimLoopDuration = numFrames;
return;
}
m_nextStateAnimLoopDuration = NO_NEXT_DURATION;
DEBUG_ASSERTCRASH(m_curState != NULL && m_curState->m_transition == NO_TRANSITION, ("Hmm, setAnimationLoopDuration on a transition state is probably not right... see srj"));
#else
m_nextStateAnimLoopDuration = NO_NEXT_DURATION;
#endif
Real desiredDurationInMsec = ceilf(numFrames * MSEC_PER_LOGICFRAME_REAL);
setCurAnimDurationInMsec(desiredDurationInMsec);
}
//-------------------------------------------------------------------------------------------------
/**
similar to the above, but assumes that the current state is a "ONCE",
and is smart about transition states... if there is a transition state
"inbetween", it is included in the completion time.
*/
void W3DModelDraw::setAnimationCompletionTime(UnsignedInt numFrames)
{
if (m_curState != NULL && m_curState->m_transitionSig != NO_TRANSITION && m_curState->m_animations.size() > 0 &&
m_nextState != NULL && m_nextState->m_transitionSig == NO_TRANSITION && m_nextState->m_animations.size() > 0)
{
// we have a transition; split up the time suitably.
// note that this is just a guess, and assumes that the states
// have only one anim each (or, if multiple, that they are
// all pretty close in natural duration)
const Real t1 = m_curState->m_animations.front().getNaturalDurationInMsec();
const Real t2 = m_nextState->m_animations.front().getNaturalDurationInMsec();
UnsignedInt transTime = REAL_TO_INT_FLOOR((numFrames * t1) / (t1 + t2));
setAnimationLoopDuration(transTime);
m_nextStateAnimLoopDuration = numFrames - transTime;
}
else
{
setAnimationLoopDuration(numFrames);
}
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::setPauseAnimation(Bool pauseAnim)
{
if (m_pauseAnimation == pauseAnim)
{
return;
}
m_pauseAnimation = pauseAnim;
if (m_renderObject && m_renderObject->Class_ID() == RenderObjClass::CLASSID_HLOD)
{
float framenum, dummy;
int mode, numFrames;
HLodClass* hlod = (HLodClass*)m_renderObject;
HAnimClass* anim = hlod->Peek_Animation_And_Info(framenum, numFrames, mode, dummy);
if (anim)
{
if (m_pauseAnimation)
{
m_animationMode = mode;
hlod->Set_Animation(anim, framenum, RenderObjClass::ANIM_MODE_MANUAL);
}
else
{
hlod->Set_Animation(anim, framenum, m_animationMode);
}
}
}
}
//-------------------------------------------------------------------------------------------------
#ifdef ALLOW_ANIM_INQUIRIES
// srj sez: not sure if this is a good idea, for net sync reasons...
Real W3DModelDraw::getAnimationScrubScalar( void ) const
{
return getCurAnimDistanceCovered();
}
#endif
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::rebuildWeaponRecoilInfo(const ModelConditionInfo* state)
{
Int wslot;
if (state == NULL)
{
for (wslot = 0; wslot < WEAPONSLOT_COUNT; ++wslot)
{
m_weaponRecoilInfoVec[wslot].clear();
}
}
else
{
for (wslot = 0; wslot < WEAPONSLOT_COUNT; ++wslot)
{
Int ncount = state->m_weaponBarrelInfoVec[wslot].size();
if (m_weaponRecoilInfoVec[wslot].size() != ncount)
{
WeaponRecoilInfo tmp;
m_weaponRecoilInfoVec[wslot].resize(ncount, tmp);
}
for (WeaponRecoilInfoVec::iterator it = m_weaponRecoilInfoVec[wslot].begin(); it != m_weaponRecoilInfoVec[wslot].end(); ++it)
{
it->clear();
}
}
}
}
//-------------------------------------------------------------------------------------------------
/** Preload any assets for the time of day requested */
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::preloadAssets( TimeOfDay timeOfDay )
{
const W3DModelDrawModuleData *modData = getW3DModelDrawModuleData();
if( modData )
modData->preloadAssets( timeOfDay, getDrawable()->getScale() );
}
//-------------------------------------------------------------------------------------------------
Bool W3DModelDraw::isVisible() const
{
return (m_renderObject && m_renderObject->Is_Really_Visible());
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::updateProjectileClipStatus( UnsignedInt shotsRemaining, UnsignedInt maxShots, WeaponSlotType slot )
{
if ((getW3DModelDrawModuleData()->m_projectileBoneFeedbackEnabledSlots & (1 << slot)) == 0)
return; // Only if specified.
doHideShowProjectileObjects( shotsRemaining, maxShots, slot );// Means effectively, show m of n.
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::updateDrawModuleSupplyStatus( Int , Int currentSupply )
{
// This level only cares if you have anything or not
if( currentSupply > 0 )
{
getDrawable()->setModelConditionState( MODELCONDITION_CARRYING );
}
else
{
getDrawable()->clearModelConditionState( MODELCONDITION_CARRYING );
}
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::doHideShowProjectileObjects( UnsignedInt showCount, UnsignedInt maxCount, WeaponSlotType slot )
{
// Loop through the projectile bones, and start hiding off the front. That is, 8,9 means to hide the first only.
if (maxCount < showCount)
{
DEBUG_CRASH(("Someone is trying to show more projectiles than they have.") );
return;
}
Int hideCount = maxCount - showCount;
std::vector<ModelConditionInfo::HideShowSubObjInfo> showHideVector;
ModelConditionInfo::HideShowSubObjInfo oneEntry;
if (m_curState->m_weaponProjectileHideShowName[slot].isEmpty())
{
for( Int projectileIndex = 0; projectileIndex < maxCount; projectileIndex++ )
{
oneEntry.subObjName.format("%s%02d", m_curState->m_weaponProjectileLaunchBoneName[slot].str(), (projectileIndex + 1));
oneEntry.hide = (projectileIndex < hideCount);
showHideVector.push_back( oneEntry );
}
}
else
{
oneEntry.subObjName = m_curState->m_weaponProjectileHideShowName[slot];
oneEntry.hide = (0 < hideCount);
showHideVector.push_back( oneEntry );
}
// Rather than duplicate recursive utility stuff, I will build a vector like those used by the main ShowHide setting
doHideShowSubObjs(&showHideVector);
}
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::updateSubObjects()
{
if (!m_renderObject)
return;
if (!m_subObjectVec.empty())
{
for (std::vector<ModelConditionInfo::HideShowSubObjInfo>::const_iterator it = m_subObjectVec.begin(); it != m_subObjectVec.end(); ++it)
{
Int objIndex;
RenderObjClass* subObj;
if ((subObj = m_renderObject->Get_Sub_Object_By_Name(it->subObjName.str(), &objIndex)) != NULL)
{
subObj->Set_Hidden(it->hide);
const HTreeClass *htree = m_renderObject->Get_HTree();
if (htree)
{
//get the bone of this subobject so we can hide all other child objects that use this bone
//as a parent.
Int boneIdx = m_renderObject->Get_Sub_Object_Bone_Index(0, objIndex);
doHideShowBoneSubObjs( it->hide, m_renderObject->Get_Num_Sub_Objects(), boneIdx, m_renderObject, htree);
}
subObj->Release_Ref();
}
else
{
DEBUG_CRASH(("*** ASSET ERROR: SubObject %s not found (%s)!\n",it->subObjName.str(),getDrawable()->getTemplate()->getName().str()));
}
}
}
}
// ------------------------------------------------------------------------------------------------
/** CRC */
// ------------------------------------------------------------------------------------------------
void W3DModelDraw::crc( Xfer *xfer )
{
// extend base class
DrawModule::crc( xfer );
} // end crc
// ------------------------------------------------------------------------------------------------
/** Xfer method
* Version Info:
* 1: Initial version
* 2: Added animation frame (CBD)
*/
// ------------------------------------------------------------------------------------------------
void W3DModelDraw::xfer( Xfer *xfer )
{
// version
const XferVersion currentVersion = 2;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
// extend base class
DrawModule::xfer( xfer );
// weapon recoil info vectors
UnsignedByte recoilInfoCount;
WeaponRecoilInfo weaponRecoilInfo;
for( Int i = 0; i < WEAPONSLOT_COUNT; ++i )
{
// count of data here
recoilInfoCount = m_weaponRecoilInfoVec[ i ].size();
xfer->xferUnsignedByte( &recoilInfoCount );
if( xfer->getXferMode() == XFER_SAVE )
{
WeaponRecoilInfoVec::const_iterator it;
for( it = m_weaponRecoilInfoVec[ i ].begin(); it != m_weaponRecoilInfoVec[ i ].end(); ++it )
{
// state
weaponRecoilInfo.m_state = (*it).m_state;
xfer->xferUser( &weaponRecoilInfo.m_state, sizeof( WeaponRecoilInfo::RecoilState ) );
// shift
weaponRecoilInfo.m_shift = (*it).m_shift;
xfer->xferReal( &weaponRecoilInfo.m_shift );
// recoil rate
weaponRecoilInfo.m_recoilRate = (*it).m_recoilRate;
xfer->xferReal( &weaponRecoilInfo.m_recoilRate );
} // end for, it
} // end if, save
else
{
// clear this list before loading
m_weaponRecoilInfoVec[ i ].clear();
// read each data item
for( Int j = 0; j < recoilInfoCount; ++j )
{
// read state
xfer->xferUser( &weaponRecoilInfo.m_state, sizeof( WeaponRecoilInfo::RecoilState ) );
// read shift
xfer->xferReal( &weaponRecoilInfo.m_shift );
// read recoil rate
xfer->xferReal( &weaponRecoilInfo.m_recoilRate );
// stuff it in the vector
m_weaponRecoilInfoVec[ i ].push_back( weaponRecoilInfo );
} // end for, j
} // end else, load
} // end for, i
// sub object vector
UnsignedByte subObjectCount = m_subObjectVec.size();
xfer->xferUnsignedByte( &subObjectCount );
ModelConditionInfo::HideShowSubObjInfo hideShowSubObjInfo;
if( xfer->getXferMode() == XFER_SAVE )
{
std::vector<ModelConditionInfo::HideShowSubObjInfo>::const_iterator it;
for( it = m_subObjectVec.begin(); it != m_subObjectVec.end(); ++it )
{
// sub object name
hideShowSubObjInfo.subObjName = (*it).subObjName;
xfer->xferAsciiString( &hideShowSubObjInfo.subObjName );
// hide
hideShowSubObjInfo.hide = (*it).hide;
xfer->xferBool( &hideShowSubObjInfo.hide );
} // end for, it
} // end if, save
else
{
// the vector must be emtpy
m_subObjectVec.clear();
// read each data item
for( UnsignedByte i = 0; i < subObjectCount; ++i )
{
// name
xfer->xferAsciiString( &hideShowSubObjInfo.subObjName );
// hide
xfer->xferBool( &hideShowSubObjInfo.hide );
// stuff in vector
m_subObjectVec.push_back( hideShowSubObjInfo );
} // end for, i
} // end else, load
// animation
if( version >= 2 )
{
if( xfer->getXferMode() == XFER_SAVE )
{
// srj sez: don't save info for transition states, since we can't really
// restore them effectively.
if ( m_renderObject
&& m_renderObject->Class_ID() == RenderObjClass::CLASSID_HLOD
&& m_curState
&& m_curState->m_transitionSig == NO_TRANSITION )
{
// cast to HLod
HLodClass *hlod = (HLodClass*)m_renderObject;
// get animation info
Int mode, numFrames;
Real frame, dummy;
HAnimClass *anim = hlod->Peek_Animation_And_Info( frame, numFrames, mode, dummy );
// animation data is present
Bool present = anim ? TRUE : FALSE;
xfer->xferBool( &present );
// if animation data is present
if( anim )
{
// xfer mode
xfer->xferInt( &mode );
//
// xfer frame as a fraction (this will allow the animations to change
// in future patches but will still be mostly correct)
//
Real percent = frame / INT_TO_REAL( anim->Get_Num_Frames()-1 );
xfer->xferReal( &percent );
} // end if, anim
} // end if
else
{
// animation data is *NOT* present
Bool present = FALSE;
xfer->xferBool( &present );
} // end else
} // end if, save
else
{
// read animation present flag
Bool present;
xfer->xferBool( &present );
if( present )
{
{
// read mode
Int mode;
xfer->xferInt( &mode ); // note, this will be ignored
}
// read percent
Real percent;
xfer->xferReal( &percent );
//
// cast render object to HLod, if this is no longer possible we have read the
// data already and can just ignore it
//
if( m_renderObject && m_renderObject->Class_ID() == RenderObjClass::CLASSID_HLOD )
{
HLodClass *hlod = (HLodClass *)m_renderObject;
// get anim
HAnimClass *anim = hlod->Peek_Animation();
// set animation data
if( anim )
{
// figure out frame number given percent written in file and total frames on anim
Real frame = percent * INT_TO_REAL( anim->Get_Num_Frames()-1 );
float dummy1, dummy2;
int curMode, dummy3;
hlod->Peek_Animation_And_Info(dummy1, dummy3, curMode, dummy2);
// srj sez: do not change the animation mode. it's too risky, since if you change (say) a nonlooping
// to a looping, something might break since it could rely on that anim terminating.
// set animation data
hlod->Set_Animation( anim, frame, curMode );
} // end if, anim
} // end if
} // end if
} // end else, load
} // end if, version with animation info
// when loading, update the sub objects if we have any
if( xfer->getXferMode() == XFER_LOAD && m_subObjectVec.empty() == FALSE )
updateSubObjects();
} // end xfer
// ------------------------------------------------------------------------------------------------
/** Load post process */
// ------------------------------------------------------------------------------------------------
void W3DModelDraw::loadPostProcess( void )
{
// extend base class
DrawModule::loadPostProcess();
} // end loadPostProcess
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
void W3DModelDrawModuleData::crc( Xfer *x )
{
xfer(x);
}
// ------------------------------------------------------------------------------------------------
void W3DModelDrawModuleData::xfer( Xfer *x )
{
// version
const XferVersion currentVersion = 1;
XferVersion version = currentVersion;
x->xferVersion( &version, currentVersion );
for (ModelConditionVector::iterator it = m_conditionStates.begin(); it != m_conditionStates.end(); ++it)
{
ModelConditionInfo *info = &(*it);
x->xferByte(&(info->m_validStuff));
#if defined(_DEBUG) || defined(_INTERNAL)
x->xferAsciiString(&(info->m_description));
#endif
if (info->m_validStuff)
{
for (PristineBoneInfoMap::iterator bit = info->m_pristineBones.begin(); bit != info->m_pristineBones.end(); ++bit)
{
PristineBoneInfo *bone = &(bit->second);
x->xferInt(&(bone->boneIndex));
x->xferUser(&(bone->mtx), sizeof(Matrix3D));
}
for (Int i=0; i<MAX_TURRETS; ++i)
{
x->xferInt(&(info->m_turrets[i].m_turretAngleBone));
x->xferInt(&(info->m_turrets[i].m_turretPitchBone));
}
for (i=0; i<WEAPONSLOT_COUNT; ++i)
{
for (ModelConditionInfo::WeaponBarrelInfoVec::iterator wit = info->m_weaponBarrelInfoVec[i].begin(); wit != info->m_weaponBarrelInfoVec[i].end(); ++wit)
{
x->xferUser(&(wit->m_projectileOffsetMtx), sizeof(Matrix3D));
}
}
}
}
}
// ------------------------------------------------------------------------------------------------
void W3DModelDrawModuleData::loadPostProcess( void )
{
}
| 1 | 0.981512 | 1 | 0.981512 | game-dev | MEDIA | 0.771415 | game-dev | 0.645116 | 1 | 0.645116 |
openhab/openhab1-addons | 1,457 | bundles/io/org.openhab.io.squeezeserver/src/main/java/org/openhab/io/squeezeserver/SqueezePlayerEventListener.java | /**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.io.squeezeserver;
import org.openhab.io.squeezeserver.SqueezePlayer.PlayerEvent;
/**
* @author Markus Wolters
* @author Ben Jones
* @since 1.3.0
*/
public interface SqueezePlayerEventListener {
void powerChangeEvent(PlayerEvent event);
void modeChangeEvent(PlayerEvent event);
void volumeChangeEvent(PlayerEvent event);
void muteChangeEvent(PlayerEvent event);
void currentPlaylistIndexEvent(PlayerEvent event);
void currentPlayingTimeEvent(PlayerEvent event);
void numberPlaylistTracksEvent(PlayerEvent event);
void currentPlaylistShuffleEvent(PlayerEvent event);
void currentPlaylistRepeatEvent(PlayerEvent event);
void titleChangeEvent(PlayerEvent event);
void albumChangeEvent(PlayerEvent event);
void artistChangeEvent(PlayerEvent event);
void coverArtChangeEvent(PlayerEvent event);
void yearChangeEvent(PlayerEvent event);
void genreChangeEvent(PlayerEvent event);
void remoteTitleChangeEvent(PlayerEvent event);
void irCodeChangeEvent(PlayerEvent event);
}
| 1 | 0.672251 | 1 | 0.672251 | game-dev | MEDIA | 0.608164 | game-dev,mobile | 0.597082 | 1 | 0.597082 |
hzqst/MetaHookSv | 2,652 | include/Interface/IBaseKeyValues.h | //========= Copyright ?1996-2003, Valve LLC, All rights reserved. ============
//
// The copyright to the contents herein is the property of Valve, L.L.C.
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#ifndef BASE_KEYVALUES_H
#define BASE_KEYVALUES_H
#ifdef _WIN32
#pragma once
#endif
// #include <vgui/VGUI.h>
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
class IFileSystem;
class CUtlBuffer;
class Color;
typedef void* FileHandle_t;
/*
Purpose: keep the consistency of vftable layout with GoldSrc
*/
class KeyValues;
class IBaseKeyValues
{
public:
// Data type
enum types_t
{
TYPE_NONE,
TYPE_STRING,
TYPE_INT,
TYPE_FLOAT,
TYPE_PTR,
TYPE_WSTRING,
TYPE_COLOR,
TYPE_UINT64,
TYPE_NUMTYPES,
};
public:
virtual const char* GetName(void) const = 0;
virtual int GetNameSymbol(void) const = 0;
virtual bool LoadFromFile(IFileSystem* filesystem, const char* resourceName, const char* pathID) = 0;
virtual bool SaveToFile(IFileSystem* filesystem, const char* resourceName, const char* pathID) = 0;
virtual KeyValues* FindKey2(int keySymbol) const = 0;
virtual KeyValues* FindKey(const char* keyName, bool bCreate = false) = 0;
virtual KeyValues* CreateNewKey() = 0;
virtual void RemoveSubKey(KeyValues* subKey) = 0;
virtual KeyValues* GetFirstSubKey() = 0;
virtual KeyValues* GetNextKey() = 0;
virtual int GetInt(const char* keyName, int defaultValue = 0) = 0;
virtual float GetFloat(const char* keyName, float defaultValue = 0.0f) = 0;
virtual const char* GetString(const char* keyName, const char* defaultValue = "") = 0;
virtual const wchar_t* GetWString(const char* keyName, const wchar_t* defaultValue = L"") = 0;
virtual void* GetPtr(const char* keyName, void* defaultValue = nullptr) = 0;
virtual bool IsEmpty(const char* keyName) = 0;
virtual void SetWString(const char* keyName, const wchar_t* value) = 0;
virtual void SetString(const char* keyName, const char* value) = 0;
virtual void SetInt(const char* keyName, int value) = 0;
virtual void SetFloat(const char* keyName, float value) = 0;
virtual void SetPtr(const char* keyName, void* value) = 0;
virtual KeyValues* MakeCopy(void) const = 0;
virtual void Clear(void) = 0;
virtual types_t GetDataType(const char* keyName) = 0;
virtual void deleteThis() = 0;
};
#endif // BASE_KEYVALUES_H
| 1 | 0.876813 | 1 | 0.876813 | game-dev | MEDIA | 0.356575 | game-dev | 0.508905 | 1 | 0.508905 |
malaybaku/VMagicMirror | 13,557 | VMagicMirror/Assets/Baku/VMagicMirror/Scripts/InputMonitoring/GamePadInput/XInputGamePad.cs | using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using R3;
namespace Baku.VMagicMirror
{
/// <summary>
/// ゲームパッドの状態を通知してくれるやつ
/// </summary>
public class XInputGamePad : MonoBehaviour
{
[SerializeField] private int triggerDownThreshold = 30;
private const int StickPositionDiffThreshold = 1000;
private readonly XInputCapture _xInputCapture = new();
public Observable<GamepadKeyData> ButtonUpDown => _buttonSubject;
//TODO: 動作が壊れないことを評価したうえで普通にReactivePropertyに置き換えたい…
/// <summary>
/// Position is (x, y), and both x and y are in short (MIN=-32768, MAX=+32767)
/// </summary>
public Observable<Vector2Int> RightStickPosition => _rightStick;
/// <summary>
/// Position is (x, y), and both x and y are in short (MIN=-32768, MAX=+32767)
/// </summary>
public Observable<Vector2Int> LeftStickPosition => _leftStick;
private readonly ReactiveProperty<Vector2Int> _arrowButtonsStickPosition = new(Vector2Int.zero);
/// <summary> 矢印キーの押下状態から作成した、スティック位置に相当する値 </summary>
public ReadOnlyReactiveProperty<Vector2Int> ArrowButtonsStickPosition => _arrowButtonsStickPosition;
//DirectInputによって入力キャプチャをこっそり代行してくれるやつ
private readonly DirectInputGamePad _directInputAlternative = new();
//このクラス自身がforeachで使うときはこっち
private HashSet<ObservableButton> _buttons = new();
//DirectInput入力で代わりに上書きするときはここからアクセス
private readonly List<ObservableButton> _buttonsList = new(16);
private readonly Subject<GamepadKeyData> _buttonSubject = new();
private readonly Subject<Vector2Int> _rightStick = new();
private readonly Subject<Vector2Int> _leftStick = new();
private Vector2Int _rightStickPosition = Vector2Int.zero;
private Vector2Int _leftStickPosition = Vector2Int.zero;
private bool _hasValidArrowButtons;
private ObservableButton _arrowRight;
private ObservableButton _arrowDown;
private ObservableButton _arrowLeft;
private ObservableButton _arrowUp;
private bool _isLeftTriggerDown;
private bool _isRightTriggerDown;
//Updateで実処理を呼んでもいいかどうか
private bool _updateEnabled = true;
//XInputよりもDirectInputで取得できるコントローラを使うべきかどうか(PS4コンではtrue)
private bool _preferDirectInput;
public void SetEnableGamepad(bool enableGamepad)
{
LogOutput.Instance.Write("SetEnableGamepad");
_updateEnabled = enableGamepad;
//DirectInputの場合、明示的にデバイスを捕まえる必要があるので捕まえておく
if (_preferDirectInput)
{
if (enableGamepad)
{
_directInputAlternative.ConnectToDevice(NativeMethods.GetUnityWindowHandle());
}
else
{
_directInputAlternative.Stop();
}
}
}
public void SetPreferDirectInputGamepad(bool preferDirectInput)
{
LogOutput.Instance.Write("SetPreferDirectInputGamepad");
_preferDirectInput = preferDirectInput;
//読み取り中のままXInputとDirectInputを切り替え: この場合、DirectInput側だけ読み取り開始や停止が起きる
if (_updateEnabled)
{
if (preferDirectInput)
{
_directInputAlternative.ConnectToDevice(NativeMethods.GetUnityWindowHandle());
}
else
{
_directInputAlternative.Stop();
}
}
}
public bool GetButtonDown(GamepadKey key)
=> _buttons.FirstOrDefault(b => b.Key == key)?.IsPressed ?? false;
private void Start()
{
_buttonsList.Add(new ObservableButton(GamepadKey.Start, XInputCapture.Buttons.START, _buttonSubject));
_buttonsList.Add(new ObservableButton(GamepadKey.Select, XInputCapture.Buttons.BACK, _buttonSubject));
_buttonsList.Add(new ObservableButton(GamepadKey.B, XInputCapture.Buttons.B, _buttonSubject));
_buttonsList.Add(new ObservableButton(GamepadKey.A, XInputCapture.Buttons.A, _buttonSubject));
_buttonsList.Add(new ObservableButton(GamepadKey.X, XInputCapture.Buttons.X, _buttonSubject));
_buttonsList.Add(new ObservableButton(GamepadKey.Y, XInputCapture.Buttons.Y, _buttonSubject));
_buttonsList.Add(new ObservableButton(GamepadKey.RShoulder, XInputCapture.Buttons.RIGHT_SHOULDER, _buttonSubject));
_buttonsList.Add(new ObservableButton(GamepadKey.LShoulder, XInputCapture.Buttons.LEFT_SHOULDER, _buttonSubject));
_arrowRight = new ObservableButton(GamepadKey.RIGHT, XInputCapture.Buttons.DPAD_RIGHT, _buttonSubject);
_arrowDown = new ObservableButton(GamepadKey.DOWN, XInputCapture.Buttons.DPAD_DOWN, _buttonSubject);
_arrowLeft = new ObservableButton(GamepadKey.LEFT, XInputCapture.Buttons.DPAD_LEFT, _buttonSubject);
_arrowUp = new ObservableButton(GamepadKey.UP, XInputCapture.Buttons.DPAD_UP, _buttonSubject);
_buttonsList.Add(_arrowRight);
_buttonsList.Add(_arrowDown);
_buttonsList.Add(_arrowLeft);
_buttonsList.Add(_arrowUp);
_buttons = new HashSet<ObservableButton>(_buttonsList);
_hasValidArrowButtons = true;
}
private void Update()
{
if (!_updateEnabled)
{
return;
}
if (_preferDirectInput)
{
//DirectInputの読み取り機能で更新
_directInputAlternative.Update();
UpdateByState(_directInputAlternative.CurrentState);
}
else
{
//普通にXInputの読み取り
_xInputCapture.Update();
var buttonFlags = _xInputCapture.GetButtonStates();
foreach(var button in _buttons)
{
button.UpdatePressedState(buttonFlags);
}
UpdateRightStick();
UpdateLeftStick();
UpdateTriggerAsButtons();
}
_arrowButtonsStickPosition.Value = GetArrowButtonsStickPosition();
}
private void OnDestroy() => _directInputAlternative.Stop();
private void UpdateByState(GamepadState state)
{
//NOTE: ボタンの順序はStart()で初期化してる順番と揃えてます
_buttonsList[0].IsPressed = state.Start;
_buttonsList[1].IsPressed = state.Select;
_buttonsList[2].IsPressed = state.B;
_buttonsList[3].IsPressed = state.A;
_buttonsList[4].IsPressed = state.X;
_buttonsList[5].IsPressed = state.Y;
_buttonsList[6].IsPressed = state.R1;
_buttonsList[7].IsPressed = state.L1;
_buttonsList[8].IsPressed = state.Right;
_buttonsList[9].IsPressed = state.Down;
_buttonsList[10].IsPressed = state.Left;
_buttonsList[11].IsPressed = state.Up;
var right = new Vector2Int(state.RightX, state.RightY);
if (Mathf.Abs(right.x - _rightStickPosition.x) +
Mathf.Abs(right.y - _rightStickPosition.y) > StickPositionDiffThreshold)
{
_rightStickPosition = right;
_rightStick.OnNext(right);
}
var left = new Vector2Int(state.LeftX, state.LeftY);
if (Mathf.Abs(left.x - _leftStickPosition.x) +
Mathf.Abs(left.y - _leftStickPosition.y) > StickPositionDiffThreshold)
{
_leftStickPosition = left;
_leftStick.OnNext(left);
}
//トリガー情報はDirectInputの場合ボタンベースで取得する。
//DUAL SHOCK 4のトリガーは連続値+ボタン情報で渡ってくるのでボタン情報だけ拾って使っている、という感じ。
if (_isRightTriggerDown != state.R2)
{
_isRightTriggerDown = state.R2;
_buttonSubject.OnNext(new GamepadKeyData(GamepadKey.RTrigger, _isRightTriggerDown));
}
if (_isLeftTriggerDown != state.L2)
{
_isLeftTriggerDown = state.L2;
_buttonSubject.OnNext(new GamepadKeyData(GamepadKey.LTrigger, _isLeftTriggerDown));
}
}
private void UpdateRightStick()
{
var position = _xInputCapture.GetRightThumb();
if (Mathf.Abs(_rightStickPosition.x - position.x) +
Mathf.Abs(_rightStickPosition.y - position.y) > StickPositionDiffThreshold)
{
_rightStickPosition = position;
_rightStick.OnNext(position);
}
}
private void UpdateLeftStick()
{
var position = _xInputCapture.GetLeftThumb();
if (Mathf.Abs(_leftStickPosition.x - position.x) +
Mathf.Abs(_leftStickPosition.y - position.y) > StickPositionDiffThreshold)
{
_leftStickPosition = position;
_leftStick.OnNext(position);
}
}
private void UpdateTriggerAsButtons()
{
int right = _xInputCapture.GetRightTrigger();
bool isRightDown = (right > triggerDownThreshold);
if (_isRightTriggerDown != isRightDown)
{
_isRightTriggerDown = isRightDown;
_buttonSubject.OnNext(new GamepadKeyData(GamepadKey.RTrigger, isRightDown));
}
int left = _xInputCapture.GetLeftTrigger();
bool isLeftDown = (left > triggerDownThreshold);
if (_isLeftTriggerDown != isLeftDown)
{
_isLeftTriggerDown = isLeftDown;
_buttonSubject.OnNext(new GamepadKeyData(GamepadKey.LTrigger, isLeftDown));
}
}
private Vector2Int GetArrowButtonsStickPosition()
{
if (!_hasValidArrowButtons)
{
return Vector2Int.zero;
}
return new Vector2Int(
(_arrowRight.IsPressed ? 32767 : 0) - (_arrowLeft.IsPressed ? 32768 : 0),
(_arrowUp.IsPressed ? 32767 : 0) - (_arrowDown.IsPressed ? 32768 : 0)
);
}
class ObservableButton
{
public ObservableButton(GamepadKey key, int flag, Subject<GamepadKeyData> subject)
{
Key = key;
_flag = flag;
_subject = subject;
}
private readonly int _flag;
private readonly Subject<GamepadKeyData> _subject;
public GamepadKey Key { get; }
private bool _isPressed = false;
public bool IsPressed
{
get => _isPressed;
set
{
if (_isPressed != value)
{
_isPressed = value;
_subject.OnNext(new GamepadKeyData(Key, IsPressed));
}
}
}
public void Reset()
=> _isPressed = false;
public void UpdatePressedState(int buttonStateFlags)
=> IsPressed = ((buttonStateFlags & _flag) != 0);
}
}
/// <summary>
/// NOTE: Baku.VMagicMirror内部でのボタンの呼称。DirectInputに後で対応したときもコレを使う
/// </summary>
public enum GamepadKey
{
LEFT,
RIGHT,
UP,
DOWN,
A,
B,
X,
Y,
RShoulder,
LShoulder,
//NOTE: トリガーキーも便宜的にon/offのボタン扱いする
RTrigger,
LTrigger,
Start,
Select,
//NOTE: キーアサインの話をするときに「アサイン無し」をやりたいので定義してる
Unknown,
}
/// <summary> ゲームパッドの状態を渡す用のクラス </summary>
public class GamepadState
{
public bool IsValid { get; set; }
public bool A { get; set; }
public bool B { get; set; }
public bool X { get; set; }
public bool Y { get; set; }
public bool Start { get; set; }
public bool Select { get; set; }
//NOTE: L2/R2についてはトリガーの連続値を捨ててオンオフにしてます
public bool R1 { get; set; }
public bool R2 { get; set; }
public bool R3 { get; set; }
public bool L1 { get; set; }
public bool L2 { get; set; }
public bool L3 { get; set; }
public bool Up { get; set; }
public bool Down { get; set; }
public bool Left { get; set; }
public bool Right { get; set; }
//この4つの値は-32768 ~ 32767
public int LeftX { get; set; }
public int LeftY { get; set; }
public int RightX { get; set; }
public int RightY { get; set; }
public void Reset()
{
IsValid = false;
A = false;
B = false;
X = false;
Y = false;
Start = false;
Select = false;
R1 = false;
R2 = false;
R3 = false;
L1 = false;
L2 = false;
L3 = false;
Up = false;
Right = false;
Down = false;
Left = false;
LeftX = 0;
LeftY = 0;
RightX = 0;
RightY = 0;
}
}
}
| 1 | 0.953637 | 1 | 0.953637 | game-dev | MEDIA | 0.667236 | game-dev,desktop-app | 0.882465 | 1 | 0.882465 |
oot-pc-port/oot-pc-port | 5,800 | asm/non_matchings/overlays/actors/ovl_En_Elf/func_80A03148.s | glabel func_80A03148
/* 01518 80A03148 27BDFFD8 */ addiu $sp, $sp, 0xFFD8 ## $sp = FFFFFFD8
/* 0151C 80A0314C AFBF001C */ sw $ra, 0x001C($sp)
/* 01520 80A03150 AFB00018 */ sw $s0, 0x0018($sp)
/* 01524 80A03154 AFA60030 */ sw $a2, 0x0030($sp)
/* 01528 80A03158 C486028C */ lwc1 $f6, 0x028C($a0) ## 0000028C
/* 0152C 80A0315C C4A40000 */ lwc1 $f4, 0x0000($a1) ## 00000000
/* 01530 80A03160 C48A0024 */ lwc1 $f10, 0x0024($a0) ## 00000024
/* 01534 80A03164 C7AC0038 */ lwc1 $f12, 0x0038($sp)
/* 01538 80A03168 46062200 */ add.s $f8, $f4, $f6
/* 0153C 80A0316C C4A60008 */ lwc1 $f6, 0x0008($a1) ## 00000008
/* 01540 80A03170 3C0180A0 */ lui $at, %hi(D_80A061C4) ## $at = 80A00000
/* 01544 80A03174 44877000 */ mtc1 $a3, $f14 ## $f14 = 0.00
/* 01548 80A03178 460A4101 */ sub.s $f4, $f8, $f10
/* 0154C 80A0317C C4880294 */ lwc1 $f8, 0x0294($a0) ## 00000294
/* 01550 80A03180 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000
/* 01554 80A03184 460C2402 */ mul.s $f16, $f4, $f12
/* 01558 80A03188 46083280 */ add.s $f10, $f6, $f8
/* 0155C 80A0318C C484002C */ lwc1 $f4, 0x002C($a0) ## 0000002C
/* 01560 80A03190 C42861C4 */ lwc1 $f8, %lo(D_80A061C4)($at)
/* 01564 80A03194 3C0141F0 */ lui $at, 0x41F0 ## $at = 41F00000
/* 01568 80A03198 46045181 */ sub.s $f6, $f10, $f4
/* 0156C 80A0319C 44815000 */ mtc1 $at, $f10 ## $f10 = 30.00
/* 01570 80A031A0 E7B00024 */ swc1 $f16, 0x0024($sp)
/* 01574 80A031A4 460C3482 */ mul.s $f18, $f6, $f12
/* 01578 80A031A8 46086300 */ add.s $f12, $f12, $f8
/* 0157C 80A031AC 460A7380 */ add.s $f14, $f14, $f10
/* 01580 80A031B0 44066000 */ mfc1 $a2, $f12
/* 01584 80A031B4 E7B20020 */ swc1 $f18, 0x0020($sp)
/* 01588 80A031B8 0C280AF6 */ jal func_80A02BD8
/* 0158C 80A031BC E7AE0034 */ swc1 $f14, 0x0034($sp)
/* 01590 80A031C0 C7B00024 */ lwc1 $f16, 0x0024($sp)
/* 01594 80A031C4 C7B20020 */ lwc1 $f18, 0x0020($sp)
/* 01598 80A031C8 C7A80030 */ lwc1 $f8, 0x0030($sp)
/* 0159C 80A031CC 46108102 */ mul.s $f4, $f16, $f16
/* 015A0 80A031D0 C7AE0034 */ lwc1 $f14, 0x0034($sp)
/* 015A4 80A031D4 2604005C */ addiu $a0, $s0, 0x005C ## $a0 = 0000005C
/* 015A8 80A031D8 46129182 */ mul.s $f6, $f18, $f18
/* 015AC 80A031DC 3C0640A0 */ lui $a2, 0x40A0 ## $a2 = 40A00000
/* 015B0 80A031E0 46062000 */ add.s $f0, $f4, $f6
/* 015B4 80A031E4 46000004 */ sqrt.s $f0, $f0
/* 015B8 80A031E8 4608003C */ c.lt.s $f0, $f8
/* 015BC 80A031EC 00000000 */ nop
/* 015C0 80A031F0 45020004 */ bc1fl .L80A03204
/* 015C4 80A031F4 4600703C */ c.lt.s $f14, $f0
/* 015C8 80A031F8 10000009 */ beq $zero, $zero, .L80A03220
/* 015CC 80A031FC 46004086 */ mov.s $f2, $f8
/* 015D0 80A03200 4600703C */ c.lt.s $f14, $f0
.L80A03204:
/* 015D4 80A03204 00000000 */ nop
/* 015D8 80A03208 45020004 */ bc1fl .L80A0321C
/* 015DC 80A0320C 46000306 */ mov.s $f12, $f0
/* 015E0 80A03210 10000002 */ beq $zero, $zero, .L80A0321C
/* 015E4 80A03214 46007306 */ mov.s $f12, $f14
/* 015E8 80A03218 46000306 */ mov.s $f12, $f0
.L80A0321C:
/* 015EC 80A0321C 46006086 */ mov.s $f2, $f12
.L80A03220:
/* 015F0 80A03220 46020032 */ c.eq.s $f0, $f2
/* 015F4 80A03224 E6020068 */ swc1 $f2, 0x0068($s0) ## 00000068
/* 015F8 80A03228 4503000D */ bc1tl .L80A03260
/* 015FC 80A0322C 44058000 */ mfc1 $a1, $f16
/* 01600 80A03230 44805000 */ mtc1 $zero, $f10 ## $f10 = 0.00
/* 01604 80A03234 00000000 */ nop
/* 01608 80A03238 460A0032 */ c.eq.s $f0, $f10
/* 0160C 80A0323C 00000000 */ nop
/* 01610 80A03240 45030007 */ bc1tl .L80A03260
/* 01614 80A03244 44058000 */ mfc1 $a1, $f16
/* 01618 80A03248 46001303 */ div.s $f12, $f2, $f0
/* 0161C 80A0324C 460C8402 */ mul.s $f16, $f16, $f12
/* 01620 80A03250 00000000 */ nop
/* 01624 80A03254 460C9482 */ mul.s $f18, $f18, $f12
/* 01628 80A03258 00000000 */ nop
/* 0162C 80A0325C 44058000 */ mfc1 $a1, $f16
.L80A03260:
/* 01630 80A03260 0C01DE80 */ jal Math_ApproxF
/* 01634 80A03264 E7B20020 */ swc1 $f18, 0x0020($sp)
/* 01638 80A03268 C7B20020 */ lwc1 $f18, 0x0020($sp)
/* 0163C 80A0326C 26040064 */ addiu $a0, $s0, 0x0064 ## $a0 = 00000064
/* 01640 80A03270 3C0640A0 */ lui $a2, 0x40A0 ## $a2 = 40A00000
/* 01644 80A03274 44059000 */ mfc1 $a1, $f18
/* 01648 80A03278 0C01DE80 */ jal Math_ApproxF
/* 0164C 80A0327C 00000000 */ nop
/* 01650 80A03280 0C00B5FB */ jal func_8002D7EC
/* 01654 80A03284 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
/* 01658 80A03288 8FBF001C */ lw $ra, 0x001C($sp)
/* 0165C 80A0328C 8FB00018 */ lw $s0, 0x0018($sp)
/* 01660 80A03290 27BD0028 */ addiu $sp, $sp, 0x0028 ## $sp = 00000000
/* 01664 80A03294 03E00008 */ jr $ra
/* 01668 80A03298 00000000 */ nop
| 1 | 0.77871 | 1 | 0.77871 | game-dev | MEDIA | 0.953578 | game-dev | 0.762439 | 1 | 0.762439 |
Ryan-rsm-McKenzie/CommonLibSSE | 7,815 | include/RE/H/hkbStateMachine.h | #pragma once
#include "RE/H/hkArray.h"
#include "RE/H/hkRefPtr.h"
#include "RE/H/hkReferencedObject.h"
#include "RE/H/hkbBindable.h"
#include "RE/H/hkbEvent.h"
#include "RE/H/hkbGenerator.h"
namespace RE
{
class hkbStateChooser;
class hkbStateMachine : public hkbGenerator
{
public:
inline static constexpr auto RTTI = RTTI_hkbStateMachine;
enum class StartStateMode
{
kDefault = 0,
kSync = 1,
kRandom = 2,
kChooser = 3
};
enum class StateMachineSelfTransitionMode
{
kNoTransition = 0,
kTransitionToStartState = 1,
kForceTransitionToStartState = 2
};
class StateInfo : public hkbBindable
{
public:
inline static constexpr auto RTTI = RTTI_hkbStateMachine__StateInfo;
~StateInfo() override; // 00
// members
std::uint64_t unk30; // 30
std::uint64_t unk38; // 38
std::uint64_t unk40; // 40
std::uint64_t unk48; // 48
std::uint64_t unk50; // 50
std::uint64_t unk58; // 58
std::uint64_t unk60; // 60
std::uint64_t unk68; // 68
std::uint64_t unk70; // 70
};
static_assert(sizeof(StateInfo) == 0x78);
class TransitionInfoArray : public hkReferencedObject
{
public:
inline static constexpr auto RTTI = RTTI_hkbStateMachine__TransitionInfoArray;
~TransitionInfoArray() override; // 00
// members
std::uint64_t unk10; // 10
std::uint64_t unk18; // 18
};
static_assert(sizeof(TransitionInfoArray) == 0x20);
~hkbStateMachine() override; // 00
// override (hkbGenerator)
hkClass* GetClassType() const override; // 01
void CalcContentStatistics(hkStatisticsCollector* a_collector, const hkClass* a_class) const override; // 02
void Unk_03(void) override; // 03
void Unk_04(void) override; // 04
void Unk_05(void) override; // 05
void Unk_06(void) override; // 06
void Unk_07(void) override; // 07
void Unk_08(void) override; // 08
void Unk_09(void) override; // 09
void Unk_0A(void) override; // 0A
void Unk_0C(void) override; // 0C
void Unk_0D(void) override; // 0D
void Unk_0E(void) override; // 0E
void Unk_0F(void) override; // 0F
void Unk_10(void) override; // 10
void Unk_11(void) override; // 11
void Unk_12(void) override; // 12
void Unk_14(void) override; // 14
void Unk_17(void) override; // 17
void Unk_18(void) override; // 18 - { return 1; }
void Unk_19(void) override; // 19
void Unk_1B(void) override; // 1B - { echoNextUpdate = true; }
// members
hkbEvent eventToSendWhenStateOrTransitionChanges; // 048
hkRefPtr<hkbStateChooser> startStateChooser; // 060
std::int32_t startStateID; // 068
std::int32_t returnToPreviousStateEventID; // 06C
std::int32_t randomTransitionEventID; // 070
std::int32_t transitionToNextHigherStateEventID; // 074
std::int32_t transitionToNextLowerStateEventID; // 078
std::int32_t syncVariableIndex; // 07C
std::int32_t currentStateID; // 080
bool wrapAroundStateID; // 084
std::int8_t maxSimultaneousTransitions; // 085
stl::enumeration<StartStateMode, std::uint8_t> startStateMode; // 086
stl::enumeration<StateMachineSelfTransitionMode, std::uint8_t> selfTransitionMode; // 087
bool isActive; // 088
std::uint8_t pad41; // 089
std::uint16_t pad42; // 08A
std::uint32_t pad44; // 08C
hkArray<StateInfo*> states; // 090
hkRefPtr<TransitionInfoArray> wildcardTransitions; // 0A0
hkRefVariant stateIDToIndexMap; // 0A8
hkArray<hkRefVariant> activeTransitions; // 0B0
hkArray<hkRefVariant> transitionFlags; // 0C0
hkArray<hkRefVariant> wildcardTransitionFlags; // 0D0
hkArray<hkRefVariant> delayedTransitions; // 0E0
float timeInState; // 0F0
float lastLocalTime; // 0F4
std::int32_t previousStateID; // 0F8
std::int32_t nextStartStateIndexOverride; // 0FC
bool stateOrTransitionChanged; // 100
bool echoNextUpdate; // 101
std::uint16_t currentStateIndexAndEntered; // 102
std::uint32_t pad0BC; // 104
};
static_assert(sizeof(hkbStateMachine) == 0x108);
}
| 1 | 0.765946 | 1 | 0.765946 | game-dev | MEDIA | 0.696776 | game-dev | 0.501562 | 1 | 0.501562 |
GrahamBurgers/BossReworks | 3,183 | files/boss_robot/edit.lua | dofile("mods/boss_reworks/files/lib/injection.lua")
local nxml = dofile("mods/boss_reworks/files/lib/nxml.lua")
local path = "data/entities/animals/boss_robot/boss_robot.xml"
local tree = nxml.parse(ModTextFileGetContent(path))
table.insert(tree.children,
nxml.parse('<LuaComponent script_source_file="mods/boss_reworks/files/boss_armor_init.lua"> </LuaComponent>'))
table.insert(tree.children,
nxml.parse('<LuaComponent script_source_file="mods/boss_reworks/files/healthbar_counter.lua" </LuaComponent>'))
table.insert(tree.children,
nxml.parse('<LuaComponent script_source_file="mods/boss_reworks/files/boss_robot/beam.lua"> </LuaComponent>'))
table.insert(tree.children,
nxml.parse('<GameEffectComponent frames="-1" effect="PROTECTION_FREEZE" </GameEffectComponent>'))
for k, v in ipairs(tree.children) do
if v.name == "DamageModelComponent" then
v.children[1].attr.projectile = 0.1
v.children[1].attr.explosion = 0.1
v.children[1].attr.holy = 0.2
v.attr.blood_multiplier = 0.2
end
if v.name == "Entity" then
for k2, v2 in ipairs(v.children) do
if v2.attr.effect == "PROTECTION_PROJECTILE" then
v2.attr.frames = "1"
end
end
end
end
ModTextFileSetContent(path, tostring(tree))
inject(args.SS,modes.R,"data/entities/animals/boss_robot/rocket.xml", 'fire="2.2"', 'fire="0"')
inject(args.SS,modes.R,"data/entities/animals/boss_robot/rocket.xml", 'lifetime="100"', 'lifetime="60"')
inject(args.SS,modes.R,"data/entities/animals/boss_robot/rocket.xml", 'damage="6"', 'damage="1"')
inject(args.SS,modes.R,"data/entities/animals/boss_robot/state.lua", 'EntityLoad( "data/entities/animals/robobase/healerdrone_physics.xml", x, y )', [[
local eid = EntityLoad( "data/entities/animals/robobase/healerdrone_physics.xml", x, y )
EntitySetComponentIsEnabled(eid, EntityGetFirstComponent(eid, "MaterialInventoryComponent"), false)
EntitySetComponentIsEnabled(eid, EntityGetFirstComponent(eid, "ExplodeOnDamageComponent"), false)
local dmg = EntityGetFirstComponent(eid, "DamageModelComponent")
if dmg then
ComponentSetValue2(dmg, "blood_material", "smoke")
ComponentSetValue2(dmg, "blood_spray_material", "smoke")
end
]])
inject(args.SS,modes.R,"data/entities/animals/boss_robot/rocket.xml", 'count_min="5"', 'count_min="0"')
inject(args.SS,modes.R,"data/entities/animals/boss_robot/rocket.xml", 'count_max="5"', 'count_max="1"')
inject(args.SS,modes.R,"data/entities/animals/boss_robot/rocket.xml", 'create_cell_probability="5"', 'create_cell_probability="1"')
inject(args.SS,modes.P,"data/entities/animals/boss_robot/death.lua", 'AddFlagPersistent( "miniboss_robot" )', [[
if not GameHasFlagRun("br_killed_animal_boss_robot") then
GameAddFlagRun("br_killed_animal_boss_robot")
dofile_once("mods/boss_reworks/files/soul_things.lua")
CreateItemActionEntity(Soul("BR_REWARD_ROBOT"), x, y - 20)
end
]])
path = "data/entities/items/pickup/wandstone.xml"
tree = nxml.parse(ModTextFileGetContent(path))
for k, v in ipairs(tree.children) do
if v.name == "GameEffectComponent" then
if v.attr.effect == "EDIT_WANDS_EVERYWHERE" then
v.attr._tags = v.attr._tags .. ",enabled_in_inventory"
end
end
end
ModTextFileSetContent(path, tostring(tree)) | 1 | 0.941321 | 1 | 0.941321 | game-dev | MEDIA | 0.957035 | game-dev | 0.786445 | 1 | 0.786445 |
azsdaja/Osnowa | 3,633 | Assets/Scripts/Generated/Game/Components/GamePositionListenerComponent.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentEntityApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class GameEntity {
public PositionListenerComponent positionListener { get { return (PositionListenerComponent)GetComponent(GameComponentsLookup.PositionListener); } }
public bool hasPositionListener { get { return HasComponent(GameComponentsLookup.PositionListener); } }
public void AddPositionListener(System.Collections.Generic.List<IPositionListener> newValue) {
var index = GameComponentsLookup.PositionListener;
var component = (PositionListenerComponent)CreateComponent(index, typeof(PositionListenerComponent));
component.value = newValue;
AddComponent(index, component);
}
public void ReplacePositionListener(System.Collections.Generic.List<IPositionListener> newValue) {
var index = GameComponentsLookup.PositionListener;
var component = (PositionListenerComponent)CreateComponent(index, typeof(PositionListenerComponent));
component.value = newValue;
ReplaceComponent(index, component);
}
public void RemovePositionListener() {
RemoveComponent(GameComponentsLookup.PositionListener);
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentMatcherApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public sealed partial class GameMatcher {
static Entitas.IMatcher<GameEntity> _matcherPositionListener;
public static Entitas.IMatcher<GameEntity> PositionListener {
get {
if (_matcherPositionListener == null) {
var matcher = (Entitas.Matcher<GameEntity>)Entitas.Matcher<GameEntity>.AllOf(GameComponentsLookup.PositionListener);
matcher.componentNames = GameComponentsLookup.componentNames;
_matcherPositionListener = matcher;
}
return _matcherPositionListener;
}
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.EventEntityApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class GameEntity {
public void AddPositionListener(IPositionListener value) {
var listeners = hasPositionListener
? positionListener.value
: new System.Collections.Generic.List<IPositionListener>();
listeners.Add(value);
ReplacePositionListener(listeners);
}
public void RemovePositionListener(IPositionListener value, bool removeComponentWhenEmpty = true) {
var listeners = positionListener.value;
listeners.Remove(value);
if (removeComponentWhenEmpty && listeners.Count == 0) {
RemovePositionListener();
} else {
ReplacePositionListener(listeners);
}
}
}
| 1 | 0.861311 | 1 | 0.861311 | game-dev | MEDIA | 0.909376 | game-dev | 0.930389 | 1 | 0.930389 |
Monkestation/Monkestation2.0 | 11,134 | code/__HELPERS/areas.dm | #define BP_MAX_ROOM_SIZE 300
GLOBAL_LIST_INIT(typecache_powerfailure_safe_areas, typecacheof(list(
/area/station/engineering/main,
/area/station/engineering/supermatter,
/area/station/engineering/atmospherics_engine,
/area/station/ai_monitored/turret_protected/ai,
)))
// Gets an atmos isolated contained space
// Returns an associative list of turf|dirs pairs
// The dirs are connected turfs in the same space
// break_if_found is a typecache of turf/area types to return false if found
// Please keep this proc type agnostic. If you need to restrict it do it elsewhere or add an arg.
/proc/detect_room(turf/origin, list/break_if_found = list(), max_size=INFINITY)
if(origin.blocks_air)
return list(origin)
. = list()
var/list/checked_turfs = list()
var/list/found_turfs = list(origin)
while(length(found_turfs))
var/turf/sourceT = found_turfs[1]
found_turfs.Cut(1, 2)
var/dir_flags = checked_turfs[sourceT]
for(var/dir in GLOB.alldirs)
if(length(.) > max_size)
return
if(dir_flags & dir) // This means we've checked this dir before, probably from the other turf
continue
var/turf/checkT = get_step(sourceT, dir)
if(!checkT)
continue
checked_turfs[sourceT] |= dir
checked_turfs[checkT] |= turn(dir, 180)
.[sourceT] |= dir
.[checkT] |= turn(dir, 180)
if(break_if_found[checkT.type] || break_if_found[checkT.loc.type])
return FALSE
var/static/list/cardinal_cache = list("[NORTH]"=TRUE, "[EAST]"=TRUE, "[SOUTH]"=TRUE, "[WEST]"=TRUE)
if(!cardinal_cache["[dir]"] || !TURFS_CAN_SHARE(sourceT, checkT))
continue
found_turfs += checkT // Since checkT is connected, add it to the list to be processed
/**
* Create an atmos zone (Think ZAS), similiar to [proc/detect_room] but it ignores walls and turfs which are non-[atmos_can_pass]
*
* Arguments
* source - the turf which to find all connected atmos turfs
* range - the max range to check
*
* Returns a list of turfs, which is an area of isolated atmos
*/
/proc/create_atmos_zone(turf/source, range = INFINITY)
var/counter = 1 // a counter which increment each loop
var/loops = 0
if(source.blocks_air)
return
var/list/connected_turfs = list(source)
. = connected_turfs
while(length(connected_turfs))
var/list/turf/adjacent_turfs = list(
get_step(connected_turfs[counter], NORTH),
get_step(connected_turfs[counter], SOUTH),
get_step(connected_turfs[counter], EAST),
get_step(connected_turfs[counter], WEST)
)// get a tile in each cardinal direction at once and add that to the list
for(var/turf/valid_turf in adjacent_turfs)//loop through the list and check for atmos adjacency
var/turf/reference_turf = connected_turfs[counter]
if(valid_turf in connected_turfs)//if the turf is already added, skip
loops += 1
continue
if(length(connected_turfs) >= range)
return
if(TURFS_CAN_SHARE(reference_turf, valid_turf))
loops = 0
connected_turfs |= valid_turf//add that to the original list
if(loops >= 7)//if the loop has gone 7 consecutive times with no new turfs added, return the result. Number is arbitrary, subject to change
return
counter += 1 //increment by one so the next loop will start at the next position in the list
/proc/create_area(mob/creator)
// Passed into the above proc as list/break_if_found
var/static/list/area_or_turf_fail_types = typecacheof(list(
/turf/open/space,
/area/shuttle,
))
// Ignore these areas and dont let people expand them. They can expand into them though
var/static/list/blacklisted_areas = typecacheof(list(
/area/space,
/area/station/asteroid,
))
var/error = ""
var/list/turfs = detect_room(get_turf(creator), area_or_turf_fail_types, BP_MAX_ROOM_SIZE*2)
var/turf_count = length(turfs)
if(!turf_count)
error = "The new area must be completely airtight and not a part of a shuttle."
else if(turf_count > BP_MAX_ROOM_SIZE)
error = "The room you're in is too big. It is [turf_count >= BP_MAX_ROOM_SIZE *2 ? "more than 100" : ((turf_count / BP_MAX_ROOM_SIZE)-1)*100]% larger than allowed."
if(error)
to_chat(creator, span_warning(error))
return
var/list/apc_map = list()
var/list/areas = list("New Area" = /area)
for(var/i in 1 to turf_count)
var/turf/the_turf = turfs[i]
var/area/place = get_area(the_turf)
if(blacklisted_areas[place.type])
continue
if(!place.requires_power || (place.area_flags & NOTELEPORT) || (place.area_flags & HIDDEN_AREA))
continue // No expanding powerless rooms etc
if(!TURF_SHARES(the_turf)) // No expanding areas of walls/something blocking this turf because that defeats the whole point of them used to separate areas
continue
if(!isnull(place.apc))
apc_map[place.name] = place.apc
if(length(apc_map) > 1) // When merging 2 or more areas make sure we arent merging their apc into 1 area
to_chat(creator, span_warning("Multiple APC's detected in the vicinity. only 1 is allowed."))
return
areas[place.name] = place
var/area_choice = tgui_input_list(creator, "Choose an area to expand or make a new area", "Area Expansion", areas)
if(isnull(area_choice))
to_chat(creator, span_warning("No choice selected. The area remains undefined."))
return
area_choice = areas[area_choice]
var/area/newA
var/area/oldA = get_area(get_turf(creator))
if(!isarea(area_choice))
var/str = tgui_input_text(creator, "New area name", "Blueprint Editing", max_length = MAX_NAME_LEN)
if(!str)
return
newA = new area_choice
newA.setup(str)
newA.has_gravity = oldA.has_gravity
require_area_resort() //new area registered. resort the names
else
newA = area_choice
//we haven't done anything. let's get outta here
if(newA == oldA)
to_chat(creator, span_warning("Selected choice is same as the area your standing in. No area changes were requested."))
return
/**
* A list of all machinery tied to an area along with the area itself. key=area name,value=list(area,list of machinery)
* we use this to keep track of what areas are affected by the blueprints & what machinery of these areas needs to be reconfigured accordingly
*/
var/list/area/affected_areas = list()
for(var/turf/the_turf as anything in turfs)
var/area/old_area = the_turf.loc
//keep rack of all areas affected by turf changes
affected_areas[old_area.name] = old_area
//move the turf to its new area and unregister it from the old one
the_turf.change_area(old_area, newA)
//inform atoms on the turf that their area has changed
for(var/atom/stuff as anything in the_turf)
//unregister the stuff from its old area
SEND_SIGNAL(stuff, COMSIG_EXIT_AREA, old_area)
//register the stuff to its new area. special exception for apc as its not registered to this signal
if(istype(stuff, /obj/machinery/power/apc))
var/obj/machinery/power/apc/area_apc = stuff
area_apc.assign_to_area()
else
SEND_SIGNAL(stuff, COMSIG_ENTER_AREA, newA)
newA.reg_in_areas_in_z()
if(!isarea(area_choice) && newA.static_lighting)
newA.create_area_lighting_objects()
newA.ambient_buzz = null //no
//convert map to list
var/list/area/area_list = list()
for(var/area_name in affected_areas)
area_list += affected_areas[area_name]
SEND_GLOBAL_SIGNAL(COMSIG_AREA_CREATED, newA, area_list, creator)
to_chat(creator, span_notice("You have created a new area, named [newA.name]. It is now weather proof, and constructing an APC will allow it to be powered."))
creator.log_message("created a new area: [AREACOORD(creator)] (previously \"[oldA.name]\")", LOG_GAME)
//purge old areas that had all their turfs merged into the new one i.e. old empty areas. also recompute fire doors
for(var/i in 1 to length(area_list))
var/area/merged_area = area_list[i]
//recompute fire doors affecting areas
for(var/obj/machinery/door/firedoor/FD as anything in merged_area.firedoors)
FD.CalculateAffectingAreas()
//no more turfs in this area. Time to clean up
if(!merged_area.has_contained_turfs())
qdel(merged_area)
//MONKESTATION ADDITION - force lighting update to fix lighting bugs in custom areas, this is a REALLY shitty solution please replace it at the earliest convenience
for(var/turf/unlit_turf as anything in turfs)
unlit_turf.ChangeTurf(unlit_turf.type)
//END OF ADDITION
return TRUE
#undef BP_MAX_ROOM_SIZE
/proc/require_area_resort()
GLOB.sortedAreas = null
/// Returns a sorted version of GLOB.areas, by name
/proc/get_sorted_areas()
if(!GLOB.sortedAreas)
GLOB.sortedAreas = sortTim(GLOB.areas.Copy(), /proc/cmp_name_asc)
return GLOB.sortedAreas
//Takes: Area type as a text string from a variable.
//Returns: Instance for the area in the world.
/proc/get_area_instance_from_text(areatext)
if(istext(areatext))
areatext = text2path(areatext)
return GLOB.areas_by_type[areatext]
//Takes: Area type as text string or as typepath OR an instance of the area.
//Returns: A list of all areas of that type in the world.
/proc/get_areas(areatype, subtypes=TRUE)
if(istext(areatype))
areatype = text2path(areatype)
else if(isarea(areatype))
var/area/areatemp = areatype
areatype = areatemp.type
else if(!ispath(areatype))
return null
var/list/areas = list()
if(subtypes)
var/list/cache = typecacheof(areatype)
for(var/area/area_to_check as anything in GLOB.areas)
if(cache[area_to_check.type])
areas += area_to_check
else
for(var/area/area_to_check as anything in GLOB.areas)
if(area_to_check.type == areatype)
areas += area_to_check
return areas
/// Iterates over all turfs in the target area and returns the first non-dense one
/proc/get_first_open_turf_in_area(area/target)
if(!target)
return
for(var/turf/turf in target)
if(!turf.density)
return turf
//Takes: Area type as text string or as typepath OR an instance of the area.
//Returns: A list of all turfs in areas of that type of that type in the world.
/proc/get_area_turfs(areatype, target_z = 0, subtypes=FALSE)
if(istext(areatype))
areatype = text2path(areatype)
else if(isarea(areatype))
var/area/areatemp = areatype
areatype = areatemp.type
else if(!ispath(areatype))
return null
// Pull out the areas
var/list/areas_to_pull = list()
if(subtypes)
var/list/cache = typecacheof(areatype)
for(var/area/area_to_check as anything in GLOB.areas)
if(!cache[area_to_check.type])
continue
areas_to_pull += area_to_check
else
for(var/area/area_to_check as anything in GLOB.areas)
if(area_to_check.type != areatype)
continue
areas_to_pull += area_to_check
// Now their turfs
var/list/turfs = list()
for(var/area/pull_from as anything in areas_to_pull)
if (target_z == 0)
for (var/list/zlevel_turfs as anything in pull_from.get_zlevel_turf_lists())
turfs += zlevel_turfs
else
turfs += pull_from.get_turfs_by_zlevel(target_z)
return turfs
///Takes: list of area types
///Returns: all mobs that are in an area type
/proc/mobs_in_area_type(list/area/checked_areas)
var/list/mobs_in_area = list()
for(var/mob/living/mob as anything in GLOB.mob_living_list)
if(QDELETED(mob))
continue
for(var/area in checked_areas)
if(istype(get_area(mob), area))
mobs_in_area += mob
break
return mobs_in_area
| 1 | 0.909428 | 1 | 0.909428 | game-dev | MEDIA | 0.426572 | game-dev | 0.959094 | 1 | 0.959094 |
osgcc/ryzom | 1,916 | ryzom/server/src/entities_game_service/game_item_manager/player_inv_room.h | // Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef PLAYER_INV_ROOM_H
#define PLAYER_INV_ROOM_H
#include "game_item_manager/game_item.h"
#include "game_item_manager/player_inventory.h"
/** Player room inventory */
class CPlayerRoomInventory : public CInventoryBase
{
public:
/// ctor
CPlayerRoomInventory(CCharacter * owner);
//@{
//@name Overloads from inventory base
virtual uint32 getMaxBulk() const;
virtual uint32 getMaxSlot() const;
virtual TInventoryOpResult insertItem(CGameItemPtr &item, uint32 slot = INVENTORIES::INSERT_IN_FIRST_FREE_SLOT, bool autoStack = false);
virtual CGameItemPtr removeItem(uint32 slot, uint32 quantity = INVENTORIES::REMOVE_MAX_STACK_QUANTITY, TInventoryOpResult * res = NULL);
//@}
/// return true if the given character can use inventory
//bool canUseInventory(CCharacter * c) const;
private:
/// owner of the room
CCharacter * const _Owner;
};
/** View for the player room inventory */
class CPlayerRoomInvView : public CCharacterInvView
{
public:
/// The inventory information has changed (like total bulk or weight)
virtual void onInventoryChanged(INVENTORIES::TInventoryChangeFlags changeFlags);
};
#endif
| 1 | 0.891686 | 1 | 0.891686 | game-dev | MEDIA | 0.963433 | game-dev | 0.599652 | 1 | 0.599652 |
pubnub/c-sharp | 1,460 | src/Api/PubnubApi/EventEngine/Presence/PresenceEventEngine.cs | using System;
using PubnubApi.EndPoint;
using PubnubApi.EventEngine.Core;
namespace PubnubApi.EventEngine.Presence
{
public class PresenceEventEngine : Engine
{
public PresenceEventEngine(PNConfiguration pnConfiguration, HeartbeatOperation heartbeatOperation, LeaveOperation leaveOperation)
{
var heartbeatEffectHandler = new Effects.HeartbeatEffectHandler(heartbeatOperation, EventQueue);
dispatcher.Register<Invocations.HeartbeatInvocation, Effects.HeartbeatEffectHandler>(heartbeatEffectHandler);
var delayedHeartbeatEffectHandler = new Effects.DelayedHeartbeatEffectHandler(pnConfiguration, heartbeatOperation, EventQueue);
dispatcher.Register<Invocations.DelayedHeartbeatInvocation, Effects.DelayedHeartbeatEffectHandler>(delayedHeartbeatEffectHandler);
dispatcher.Register<Invocations.CancelDelayedHeartbeatInvocation, Effects.DelayedHeartbeatEffectHandler>(delayedHeartbeatEffectHandler);
var waitEffectHandler = new Effects.WaitEffectHandler(pnConfiguration, EventQueue);
dispatcher.Register<Invocations.WaitInvocation, Effects.WaitEffectHandler>(waitEffectHandler);
dispatcher.Register<Invocations.CancelWaitInvocation, Effects.WaitEffectHandler>(waitEffectHandler);
var leaveEffectHandler = new Effects.LeaveEffectHandler(pnConfiguration,leaveOperation);
dispatcher.Register<Invocations.LeaveInvocation, Effects.LeaveEffectHandler>(leaveEffectHandler);
currentState = new States.InactiveState();
}
}
}
| 1 | 0.863185 | 1 | 0.863185 | game-dev | MEDIA | 0.808818 | game-dev | 0.737609 | 1 | 0.737609 |
glKarin/com.n0n3m4.diii4a | 6,221 | Q3E/src/main/jni/source/game/server/hl1/hl1_npc_gman.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
//=========================================================
// GMan - misunderstood servant of the people
//=========================================================
#include "cbase.h"
#include "ai_default.h"
#include "ai_task.h"
#include "ai_schedule.h"
#include "ai_node.h"
#include "ai_hull.h"
#include "ai_hint.h"
#include "ai_memory.h"
#include "ai_route.h"
#include "ai_motor.h"
#include "soundent.h"
#include "game.h"
#include "npcevent.h"
#include "entitylist.h"
#include "activitylist.h"
#include "animation.h"
#include "IEffects.h"
#include "vstdlib/random.h"
#include "ai_baseactor.h"
//=========================================================
// Monster's Anim Events Go Here
//=========================================================
class CNPC_GMan : public CAI_BaseActor
{
DECLARE_CLASS( CNPC_GMan, CAI_BaseActor );
public:
void Spawn( void );
void Precache( void );
float MaxYawSpeed( void ){ return 90.0f; }
Class_T Classify ( void );
void HandleAnimEvent( animevent_t *pEvent );
int GetSoundInterests ( void );
bool IsInC5A1();
void StartTask( const Task_t *pTask );
void RunTask( const Task_t *pTask );
int OnTakeDamage_Alive( const CTakeDamageInfo &inputInfo );
void TraceAttack( CBaseEntity *pAttacker, float flDamage, const Vector &vecDir, trace_t *ptr, int bitsDamageType);
virtual int PlayScriptedSentence( const char *pszSentence, float duration, float volume, soundlevel_t soundlevel, bool bConcurrent, CBaseEntity *pListener );
EHANDLE m_hPlayer;
EHANDLE m_hTalkTarget;
float m_flTalkTime;
};
LINK_ENTITY_TO_CLASS( monster_gman, CNPC_GMan );
//=========================================================
// Hack that tells us whether the GMan is in the final map
//=========================================================
bool CNPC_GMan::IsInC5A1()
{
const char *pMapName = STRING(gpGlobals->mapname);
if( pMapName )
{
return !Q_strnicmp( pMapName, "c5a1", 4 );
}
return false;
}
//=========================================================
// Classify - indicates this monster's place in the
// relationship table.
//=========================================================
Class_T CNPC_GMan::Classify ( void )
{
return CLASS_NONE;
}
//=========================================================
// HandleAnimEvent - catches the monster-specific messages
// that occur when tagged animation frames are played.
//=========================================================
void CNPC_GMan::HandleAnimEvent( animevent_t *pEvent )
{
switch( pEvent->event )
{
case 1:
default:
BaseClass::HandleAnimEvent( pEvent );
break;
}
}
//=========================================================
// GetSoundInterests - generic monster can't hear.
//=========================================================
int CNPC_GMan::GetSoundInterests ( void )
{
return NULL;
}
//=========================================================
// Spawn
//=========================================================
void CNPC_GMan::Spawn()
{
Precache();
BaseClass::Spawn();
SetModel( "models/gman.mdl" );
SetHullType(HULL_HUMAN);
SetHullSizeNormal();
SetSolid( SOLID_BBOX );
AddSolidFlags( FSOLID_NOT_STANDABLE );
SetMoveType( MOVETYPE_STEP );
SetBloodColor( BLOOD_COLOR_MECH );
m_iHealth = 8;
m_flFieldOfView = 0.5;// indicates the width of this NPC's forward view cone ( as a dotproduct result )
m_NPCState = NPC_STATE_NONE;
CapabilitiesAdd( bits_CAP_MOVE_GROUND | bits_CAP_OPEN_DOORS | bits_CAP_USE_WEAPONS | bits_CAP_ANIMATEDFACE | bits_CAP_TURN_HEAD);
NPCInit();
}
//=========================================================
// Precache - precaches all resources this monster needs
//=========================================================
void CNPC_GMan::Precache()
{
PrecacheModel( "models/gman.mdl" );
}
//=========================================================
// AI Schedules Specific to this monster
//=========================================================
void CNPC_GMan::StartTask( const Task_t *pTask )
{
switch( pTask->iTask )
{
case TASK_WAIT:
if (m_hPlayer == NULL)
{
m_hPlayer = gEntList.FindEntityByClassname( NULL, "player" );
}
break;
}
BaseClass::StartTask( pTask );
}
void CNPC_GMan::RunTask( const Task_t *pTask )
{
switch( pTask->iTask )
{
case TASK_WAIT:
// look at who I'm talking to
if (m_flTalkTime > gpGlobals->curtime && m_hTalkTarget != NULL)
{
AddLookTarget( m_hTalkTarget->GetAbsOrigin(), 1.0, 2.0 );
}
// look at player, but only if playing a "safe" idle animation
else if (m_hPlayer != NULL && (GetSequence() == 0 || IsInC5A1()) )
{
AddLookTarget( m_hPlayer->EyePosition(), 1.0, 3.0 );
}
else
{
// Just center the head forward.
Vector forward;
GetVectors( &forward, NULL, NULL );
AddLookTarget( GetAbsOrigin() + forward * 12.0f, 1.0, 1.0 );
SetBoneController( 0, 0 );
}
BaseClass::RunTask( pTask );
break;
}
SetBoneController( 0, 0 );
BaseClass::RunTask( pTask );
}
//=========================================================
// Override all damage
//=========================================================
int CNPC_GMan::OnTakeDamage_Alive( const CTakeDamageInfo &inputInfo )
{
m_iHealth = m_iMaxHealth / 2; // always trigger the 50% damage aitrigger
if ( inputInfo.GetDamage() > 0 )
SetCondition( COND_LIGHT_DAMAGE );
if ( inputInfo.GetDamage() >= 20 )
SetCondition( COND_HEAVY_DAMAGE );
return TRUE;
}
void CNPC_GMan::TraceAttack( CBaseEntity *pAttacker, float flDamage, const Vector &vecDir, trace_t *ptr, int bitsDamageType)
{
g_pEffects->Ricochet( ptr->endpos, ptr->plane.normal );
// AddMultiDamage( pevAttacker, this, flDamage, bitsDamageType );
}
int CNPC_GMan::PlayScriptedSentence( const char *pszSentence, float delay, float volume, soundlevel_t soundlevel, bool bConcurrent, CBaseEntity *pListener )
{
BaseClass::PlayScriptedSentence( pszSentence, delay, volume, soundlevel, bConcurrent, pListener );
m_flTalkTime = gpGlobals->curtime + delay;
m_hTalkTarget = pListener;
return 1;
}
| 1 | 0.951955 | 1 | 0.951955 | game-dev | MEDIA | 0.972655 | game-dev | 0.935617 | 1 | 0.935617 |
Tslat/Advent-Of-Ascension | 2,216 | source/content/block/functional/light/VoxLight.java | package net.tslat.aoa3.content.block.functional.light;
import net.minecraft.core.BlockPos;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.ItemInteractionResult;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.BlockHitResult;
import net.tslat.aoa3.common.registration.item.AoAItems;
import net.tslat.aoa3.common.registration.worldgen.AoADimensions;
import net.tslat.aoa3.util.WorldUtil;
import java.util.List;
public class VoxLight extends Block {
public VoxLight(BlockBehaviour.Properties properties) {
super(properties);
}
@Override
protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) {
if (stack.getItem() == AoAItems.ACTIVE_RUNE_STONE.get() && WorldUtil.isWorld(level, AoADimensions.MYSTERIUM)) {
if (!level.isClientSide) {
List<ItemEntity> itemsList = level.getEntitiesOfClass(ItemEntity.class, new AABB(pos.getX(), pos.getY() + 1, pos.getZ(), pos.getX() + 1, pos.getY() + 2, pos.getZ() + 1));
if (itemsList.size() > 1) {
ItemEntity realmstone = null;
ItemEntity runicEnergy = null;
for (ItemEntity entity : itemsList) {
Item item = entity.getItem().getItem();
if (item == AoAItems.BLANK_REALMSTONE.get()) {
realmstone = entity;
}
else if (item == AoAItems.RUNIC_ENERGY.get()) {
runicEnergy = entity;
}
if (realmstone != null && runicEnergy != null) {
player.getItemInHand(hand).shrink(1);
realmstone.setItem(new ItemStack(AoAItems.RUNANDOR_REALMSTONE.get()));
runicEnergy.discard();
}
}
}
}
return ItemInteractionResult.sidedSuccess(level.isClientSide);
}
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION;
}
}
| 1 | 0.866337 | 1 | 0.866337 | game-dev | MEDIA | 0.999068 | game-dev | 0.963146 | 1 | 0.963146 |
dboglobal/DBOGLOBAL | 12,151 | DboClient/Lib/NtlSimulation/NtlBehaviorCharAirMove.cpp | #include "precomp_ntlsimulation.h"
#include "NtlBehaviorCharAirMove.h"
// shared
#include "NtlMovement.h"
// presentation
#include "NtlPLCharacter.h"
#include "NtlPLEvent.h"
#include "NtlPLHelpers.h"
// simulation
#include "NtlFSMDef.h"
#include "NtlSLApi.h"
#include "NtlSobActor.h"
#include "NtlSobCharProxy.h"
#include "NtlSLVisualDeclear.h"
#include "NtlSLLogic.h"
#include "NtlSobManager.h"
DEFINITION_MEMORY_POOL(CNtlBehaviorCharAirMove)
CNtlBehaviorCharAirMove::CNtlBehaviorCharAirMove()
{
SetBehaviorId(NTL_BEID_CHAR_AIR_MOVE);
SetBehaviorName(NTL_BENAME_CHAR_AIR_MOVE);
m_pPLAirEffect = NULL;
}
CNtlBehaviorCharAirMove::~CNtlBehaviorCharAirMove()
{
DestroyAirEffect();
}
void CNtlBehaviorCharAirMove::Enter(void)
{
CNtlBeCharData *pBeData = reinterpret_cast<CNtlBeCharData*>(m_pActor->GetBehaviorData());
SMoveStuff *pMoveStuff = pBeData->GetMoveStuff();
memcpy(&m_MoveStuff, pMoveStuff, sizeof(SMoveStuff));
SetAnim(pMoveStuff->byMoveFlags);
// ߿ base class enter ȣѴ.
CNtlBehaviorBase::Enter();
}
void CNtlBehaviorCharAirMove::Exit(void)
{
DestroyAirEffect();
CNtlSobCharProxy *pSobProxy = reinterpret_cast<CNtlSobCharProxy*>(m_pActor->GetSobProxy());
CNtlPLCharacter *pPLCharacter = reinterpret_cast<CNtlPLCharacter*>(pSobProxy->GetPLMainEntity());
pPLCharacter->SetBlend(BLEND_TWEEN);
// ߿ base class enter ȣѴ.
CNtlBehaviorBase::Exit();
}
void CNtlBehaviorCharAirMove::Update(RwReal fElapsed)
{
// Avoid sudden splashes when the frame is low
fElapsed = min(fElapsed, 0.2f);
CNtlBeCharData *pBeData = reinterpret_cast<CNtlBeCharData*>(m_pActor->GetBehaviorData());
SMoveStuff *pMoveStuff = pBeData->GetMoveStuff();
RwBool bFinish = FALSE;
if (pMoveStuff->byFormFlag == NTL_MOVE_FLAG_FLY)
{
bFinish = UpdateAirFly(pMoveStuff, fElapsed);
}
else if (pMoveStuff->byFormFlag == NTL_MOVE_FLAG_FLY_DASH)
{
if (pMoveStuff->byType == NTL_MOVETARGET_AIR_DASH)
bFinish = UpdateAirStart(pMoveStuff, fElapsed);
else
bFinish = UpdateAirDash(pMoveStuff, fElapsed);
}
else if (pMoveStuff->byFormFlag == NTL_MOVE_FLAG_FLY_ACCEL)
{
bFinish = UpdateAirAccel(pMoveStuff, fElapsed);
}
// effect position update
if (m_pPLAirEffect)
{
RwV3d vPos = m_pActor->GetPosition();
RwV3d vDir = m_pActor->GetDirection();
vPos = vPos + m_vEffectOffset;
m_pPLAirEffect->SetPosition(&vPos);
m_pPLAirEffect->SetDirection(&vDir);
UpdateAirEffect(vDir);
}
if (bFinish)
{
Finish();
}
}
void CNtlBehaviorCharAirMove::UpdateAirEffect(RwV3d& vDir)
{
RwV3d vPos = m_pActor->GetPosition();
// Effect
RwMatrix mat;
RwMatrixSetIdentity(&mat);
RwV3dAssignMacro(&mat.at, &vDir);
RwV3dCrossProduct(&mat.right, &mat.at, &CNtlPLGlobal::m_vYAxisV3);
RwV3dNormalize(&mat.right, &mat.right);
RwV3dCrossProduct(&mat.up, &mat.at, &mat.right);
RwV3dNormalize(&mat.up, &mat.up);
RwV3dAssignMacro(&mat.up, &CNtlPLGlobal::m_vYAxisV3);
RwMatrixUpdate(&mat);
CNtlMath::MathRwV3dAssign(&m_vEffectOffset, vDir.x*0.6f, 0.5f, vDir.z*0.5f);
RwV3dAdd(&vPos, &vPos, &m_vEffectOffset);
RwMatrixTranslate(&mat, &vPos, rwCOMBINEPOSTCONCAT);
if (m_pPLAirEffect)
m_pPLAirEffect->SetMatrix(mat);
}
RwUInt32 CNtlBehaviorCharAirMove::HandleEvents(RWS::CMsg &pMsg)
{
NTL_FUNCTION("CNtlBehaviorCharAirMove::HandleEvents");
NTL_RETURN(NTL_FSM_EVENTRES_PASS);
}
void CNtlBehaviorCharAirMove::UpdateData(void)
{
CNtlBeCharData *pBeData = reinterpret_cast<CNtlBeCharData*>(m_pActor->GetBehaviorData());
SMoveStuff *pMoveStuff = pBeData->GetMoveStuff();
memcpy(&m_MoveStuff, pMoveStuff, sizeof(SMoveStuff));
SetAnim(pMoveStuff->byMoveFlags);
}
void CNtlBehaviorCharAirMove::SetAnim(RwUInt8 byMoveFlags)
{
CNtlSobCharProxy *pSobProxy = reinterpret_cast<CNtlSobCharProxy*>(m_pActor->GetSobProxy());
RwUInt32 uiCurrAnimKey = pSobProxy->GetBaseAnimationKey();
RwUInt32 uiNextAnimKey = 0;
if (m_MoveStuff.byType == NTL_MOVETARGET_AIR_DASH)
{
uiNextAnimKey = FLYING_JUMP_HIGH;
CreateAirEffect("max_fly_Up_effect_01");
UpdateAirEffect(m_MoveStuff.vDir);
}
else if (m_MoveStuff.byType == NTL_MOVETARGET_DIR)
{
if (m_MoveStuff.byFormFlag == NTL_MOVE_FLAG_FLY)
{
if (byMoveFlags == NTL_MOVE_F || byMoveFlags == NTL_MOVE_F_TURN_L || byMoveFlags == NTL_MOVE_F_TURN_R)
{
uiNextAnimKey = FLYING_MOVE_FRONT;
}
else if (byMoveFlags == NTL_MOVE_B || byMoveFlags == NTL_MOVE_B_TURN_L || byMoveFlags == NTL_MOVE_B_TURN_R)
{
uiNextAnimKey = FLYING_MOVE_BACK;
}
else if (byMoveFlags == NTL_MOVE_L || byMoveFlags == NTL_MOVE_L_TURN_L || byMoveFlags == NTL_MOVE_L_TURN_R)
{
uiNextAnimKey = FLYING_MOVE_LEFT;
}
else if (byMoveFlags == NTL_MOVE_R || byMoveFlags == NTL_MOVE_R_TURN_L || byMoveFlags == NTL_MOVE_R_TURN_R)
{
uiNextAnimKey = FLYING_MOVE_RIGHT;
}
else if (byMoveFlags == NTL_MOVE_TURN_L || byMoveFlags == NTL_MOVE_TURN_R)
{
uiNextAnimKey = FLYING_STAND_IDLE;
}
else if (byMoveFlags == NTL_MOVE_HEIGHT_DOWN)
{
uiNextAnimKey = FLYING_STAND_DOWN;
}
else if (byMoveFlags == NTL_MOVE_HEIGHT_UP)
{
uiNextAnimKey = FLYING_STAND_UP;
}
}
else if (m_MoveStuff.byFormFlag == NTL_MOVE_FLAG_FLY_DASH)
{
CreateAirEffect("max_floating_foward_01");
UpdateAirEffect(m_MoveStuff.vDir);
uiNextAnimKey = FLYING_DASH_FRONT;
}
else if (m_MoveStuff.byFormFlag == NTL_MOVE_FLAG_FLY_ACCEL)
{
CreateAirEffect(NTL_VID_DASH_ACTIVE_02);
UpdateAirEffect(m_MoveStuff.vDir);
uiNextAnimKey = FLYING_POSE_1;
}
}
else if (m_MoveStuff.byType == NTL_MOVETARGET_LOC)
{
if (m_MoveStuff.byFormFlag == NTL_MOVE_FLAG_FLY_DASH)
{
uiNextAnimKey = FLYING_DASH_FRONT;
}
else if (m_MoveStuff.byFormFlag == NTL_MOVE_FLAG_FLY_ACCEL)
{
uiNextAnimKey = FLYING_POSE_1;
}
else
{
uiNextAnimKey = FLYING_MOVE_FRONT;
}
}
if (uiCurrAnimKey != uiNextAnimKey)
{
CNtlPLCharacter *pPLCharacter = reinterpret_cast<CNtlPLCharacter*>(pSobProxy->GetPLMainEntity());
pPLCharacter->SetBlend(BLEND_TWEEN, 0.0f, 0.20f);
pSobProxy->SetBaseAnimation(uiNextAnimKey);
}
}
void CNtlBehaviorCharAirMove::CreateAirEffect(const RwChar* effectName)
{
if (!m_pActor)
return;
DestroyAirEffect();
CNtlPLAttach* pPLChar = (CNtlPLAttach*)m_pActor->GetSobProxy()->GetPLMainEntity();
m_pPLAirEffect = GetSceneManager()->CreateEntity(PLENTITY_EFFECT, effectName);
pPLChar->Attach((CNtlPLAttach*)m_pPLAirEffect);
}
void CNtlBehaviorCharAirMove::DestroyAirEffect(void)
{
if (m_pPLAirEffect)
{
m_pPLAirEffect->Finish();
m_pPLAirEffect = NULL;
}
}
RwBool CNtlBehaviorCharAirMove::UpdatePositionMove(SMoveStuff * pMoveStuff, OUT RwV3d & vPos, RwBool bIncHeight, RwReal fElapsed, RwReal fSpeed)
{
if (pMoveStuff->byMoveFlags != NTL_MOVE_NONE)
{
RwV3d vDir = m_pActor->GetDirection();
CNtlVector vHeading, vDest;
// DBO_WARNING_MESSAGE("pMoveStuff->byMoveFlags: " << (int)pMoveStuff->byMoveFlags);
NtlGetDestination_Keyboard(vDir.x, vDir.y, vDir.z, fSpeed, vPos.x, vPos.y, vPos.z, pMoveStuff->byMoveFlags, (DWORD)(fElapsed*1000.f), 1.0f, &vHeading, &vDest);
RwV3d vNewDir;
CNtlMath::MathRwV3dAssign(&vNewDir, vHeading.x, vHeading.y, vHeading.z);
m_pActor->SetDirection(&vNewDir);
vPos.x = vDest.x;
vPos.y = vDest.y;
vPos.z = vDest.z;
// If it's a player, correct Move Sync.
//if (m_pActor->GetClassID() == SLCLASS_PLAYER)
//{
//UpdateMoveSync(vPos, fElapsed);
// Apply the calculated result.
//vPos = m_pActor->GetPosition();
// return FALSE; // return, we dont need collision check on player
//}
// Collision check.
if (m_pActor->GetFlags() & SLFLAG_OBJECT_COLLISION)
{
RwReal fCurrHeight = vPos.y;
RwBool bCollMoveImPossible;
RwUInt8 byColliResult = Logic_CharacterCollisionEx(m_pActor, &vPos, fSpeed, vPos, bCollMoveImPossible, fElapsed, FALSE);
vPos.y = fCurrHeight;
if (byColliResult != NTL_CHARACTER_COLLI_NONE)
{
if (bCollMoveImPossible)
{
SetFalling();
return TRUE;
}
}
}
}
return FALSE;
}
RwBool CNtlBehaviorCharAirMove::UpdateAirStart(SMoveStuff * pMoveStuff, RwReal fElapsed)
{
RwV3d vPos = m_pActor->GetPosition();
RwReal fMoveSpeed = Logic_GetFlyDashSpeed(m_pActor);
RwBool bFinish = UpdatePositionMove(pMoveStuff, vPos, TRUE, fElapsed, fMoveSpeed);
if (!bFinish)
{
Logic_GetWorldHeight(m_pActor, &vPos, m_sHStuff);
if (vPos.y >= m_sHStuff.fWorldHeight) //check if we on height limit
{
// vPos.y = m_sHStuff.fWorldHeight;
}
}
m_pActor->SetPosition(&vPos);
return bFinish;
}
RwBool CNtlBehaviorCharAirMove::UpdateAirFly(SMoveStuff * pMoveStuff, RwReal fElapsed)
{
RwV3d vPos = m_pActor->GetPosition();
RwReal fSpeed = Logic_GetFrontFlySpeed(m_pActor);
RwBool bFinish = UpdatePositionMove(pMoveStuff, vPos, TRUE, fElapsed, fSpeed);
if (!bFinish)
{
Logic_GetWorldHeight(m_pActor, &vPos, m_sHStuff);
if (vPos.y <= m_sHStuff.fFinialHeight) //check if we land on ground
{
DBO_WARNING_MESSAGE("UF vPos.y: " << vPos.y << ", height: " << m_sHStuff.fFinialHeight << ", WATER-height: " << m_sHStuff.fWaterHeight);
vPos.y = m_sHStuff.fFinialHeight;
// if (m_pActor->GetClassID() == SLCLASS_AVATAR) // if we do this check, then when avatar fly on ground, he will keep flying (for other players)
{
SetFalling();
bFinish = TRUE;
}
}
}
m_pActor->SetPosition(&vPos);
return bFinish;
}
RwBool CNtlBehaviorCharAirMove::UpdateAirDash(SMoveStuff * pMoveStuff, RwReal fElapsed)
{
RwV3d vPos = m_pActor->GetPosition();
RwReal fSpeed = Logic_GetFlyDashSpeed(m_pActor);
RwBool bFinish = UpdatePositionMove(pMoveStuff, vPos, TRUE, fElapsed, fSpeed);
if (!bFinish)
{
Logic_GetWorldHeight(m_pActor, &vPos, m_sHStuff);
if (vPos.y <= m_sHStuff.fFinialHeight) //check if we land on ground
{
vPos.y = m_sHStuff.fFinialHeight;
// if (m_pActor->GetClassID() == SLCLASS_AVATAR)
{
SetFalling();
bFinish = TRUE;
}
}
}
m_pActor->SetPosition(&vPos);
return bFinish;
}
RwBool CNtlBehaviorCharAirMove::UpdateAirAccel(SMoveStuff * pMoveStuff, RwReal fElapsed)
{
RwV3d vPos = m_pActor->GetPosition();
RwReal fSpeed = Logic_GetFlyAccelSpeed(m_pActor);
RwBool bFinish = UpdatePositionMove(pMoveStuff, vPos, TRUE, fElapsed, fSpeed);
if (!bFinish)
{
Logic_GetWorldHeight(m_pActor, &vPos, m_sHStuff);
if (vPos.y <= m_sHStuff.fFinialHeight) //check if we land on ground
{
vPos.y = m_sHStuff.fFinialHeight;
// if (m_pActor->GetClassID() == SLCLASS_AVATAR)
{
SetFalling();
bFinish = TRUE;
}
}
}
m_pActor->SetPosition(&vPos);
return bFinish;
}
RwBool CNtlBehaviorCharAirMove::UpdateMoveSync(RwV3d vPos, RwReal fElapsedTime)
{
if (m_pActor->GetClassID() != SLCLASS_PLAYER)
return FALSE;
CNtlBeCharData *pBeData = reinterpret_cast<CNtlBeCharData*>(m_pActor->GetBehaviorData());
SMoveSyncStuff* pMoveSyncStuff = pBeData->GetMoveSyncStuff();
if (pMoveSyncStuff->m_pMoveSyncCurr == NULL)
{
if (pMoveSyncStuff->Next() == NULL) // I have not received the packet yet.
return FALSE;
}
else
{
if (!pMoveSyncStuff->m_MoveSyncQ.empty()) // Receive and process the next packet.
{
pMoveSyncStuff->Next();
}
}
// After calculating the position that should be in accordance with the original MoveSync, determine the force to go to that position.
RwV3d vSyncDir = pMoveSyncStuff->m_pMoveSyncCurr->vLoc - vPos;
/*vSyncDir.y = 0.0f;*/
RwReal vSyncDistance = RwV3dLength(&vSyncDir);
RwV3dNormalize(&vSyncDir, &vSyncDir);
vPos += vSyncDir * (vSyncDistance / MOVE_SYNC_SPEED) * fElapsedTime * 2.0f;
// Final position
m_pActor->SetPosition(&vPos);
return TRUE;
}
void CNtlBehaviorCharAirMove::SetFalling()
{
CNtlBeCharData *pBeData = reinterpret_cast<CNtlBeCharData*>(m_pActor->GetBehaviorData());
SMoveStuff *pMoveStuff = pBeData->GetMoveStuff();
pMoveStuff->byMoveResult |= NTL_MOVE_RESULT_FALLING;
SCtrlStuff *pCtrlStuff = pBeData->GetCtrlStuff();
pCtrlStuff->uExtra.sFalling.vFallingDir = m_pActor->GetDirection();
pCtrlStuff->uExtra.sFalling.byMoveDirection = m_MoveStuff.byMoveFlags;
pCtrlStuff->uExtra.sFalling.fSpeed = DBO_FALLING_SPEED;
pCtrlStuff->uExtra.sFalling.fSearchHeight = m_sHStuff.fFinialHeight;
}
| 1 | 0.952123 | 1 | 0.952123 | game-dev | MEDIA | 0.928038 | game-dev | 0.988501 | 1 | 0.988501 |
rimeinn/rime.nvim | 2,970 | src/session.nobj.lua | -- luacheck: ignore 113
---@diagnostic disable: undefined-global
object "Session" {
c_source [[
typedef RimeSessionId Session;
#define BUFFER_SIZE 1024
]],
constructor {
c_call "Session>1" "api->create_session" {}
},
destructor "destroy" {
c_method_call "bool" "api->destroy_session" {}
},
method "__str__" {
var_out { "const char *", "ret" },
c_source [[
char buf[BUFFER_SIZE];
sprintf(buf, "%d\0", ${this});
${ret} = buf;
]],
},
method "get_current_schema" {
var_out { "char *", "result" },
c_source [[
char schema_id[BUFFER_SIZE];
if(!api->get_current_schema(${this}, schema_id, BUFFER_SIZE))
return 0;
${result} = schema_id;
]]
},
method "select_schema" {
c_method_call "bool" "api->select_schema" { "char *", "schema_id" }
},
method "process_key" {
c_method_call "bool" "api->process_key" { "int", "key", "int", "mask?" }
},
method "get_context" {
var_out { "<any>", "result" },
c_source [[
RIME_STRUCT(RimeContext, context);
if (!api->get_context(${this}, &context))
return 0;
lua_createtable(L, 0, 2);
lua_createtable(L, 0, 5);
lua_pushinteger(L, context.composition.length);
lua_setfield(L, -2, "length");
lua_pushinteger(L, context.composition.cursor_pos);
lua_setfield(L, -2, "cursor_pos");
lua_pushinteger(L, context.composition.sel_start);
lua_setfield(L, -2, "sel_start");
lua_pushinteger(L, context.composition.sel_end);
lua_setfield(L, -2, "sel_end");
lua_pushstring(L, context.composition.preedit);
lua_setfield(L, -2, "preedit");
lua_setfield(L, -2, "composition");
lua_createtable(L, 0, 7);
lua_pushinteger(L, context.menu.page_size);
lua_setfield(L, -2, "page_size");
lua_pushinteger(L, context.menu.page_no);
lua_setfield(L, -2, "page_no");
lua_pushboolean(L, context.menu.is_last_page);
lua_setfield(L, -2, "is_last_page");
lua_pushinteger(L, context.menu.highlighted_candidate_index);
lua_setfield(L, -2, "highlighted_candidate_index");
lua_pushinteger(L, context.menu.num_candidates);
lua_setfield(L, -2, "num_candidates");
lua_pushstring(L, context.menu.select_keys);
lua_setfield(L, -2, "select_keys");
lua_newtable(L);
for (int i = 0; i < context.menu.num_candidates; ++i) {
lua_createtable(L, 0, 2);
lua_pushstring(L, context.menu.candidates[i].text);
lua_setfield(L, -2, "text");
lua_pushstring(L, context.menu.candidates[i].comment);
lua_setfield(L, -2, "comment");
lua_rawseti(L, -2, i + 1);
}
lua_setfield(L, -2, "candidates");
lua_setfield(L, -2, "menu");
api->free_context(&context);
]]
},
method "get_commit" {
var_out { "<any>", "result" },
c_source [[
RIME_STRUCT(RimeCommit, commit);
if(!api->get_commit(${this}, &commit))
return 0;
lua_createtable(L, 0, 1);
lua_pushstring(L, commit.text);
lua_setfield(L, -2, "text");
api->free_commit(&commit);
]]
},
method "commit_composition" {
c_method_call "bool" "api->commit_composition" {}
},
method "clear_composition" {
c_method_call "void" "api->clear_composition" {}
},
}
| 1 | 0.853579 | 1 | 0.853579 | game-dev | MEDIA | 0.499246 | game-dev | 0.830987 | 1 | 0.830987 |
TASEmulators/BizHawk | 1,504 | src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper038.cs | using BizHawk.Common;
namespace BizHawk.Emulation.Cores.Nintendo.NES
{
// Crime Busters (Brazil) (Unl)
internal sealed class Mapper038 : NesBoardBase
{
//configuraton
private int prg_mask, chr_mask;
//state
private int prg, chr;
public override bool Configure(EDetectionOrigin origin)
{
switch (Cart.BoardType)
{
case "MAPPER038":
case "UNL-PCI556":
break;
default:
return false;
}
AssertPrg(128);
AssertChr(32);
AssertVram(0);
AssertWram(0);
prg_mask = Cart.PrgSize / 32 - 1;
chr_mask = Cart.ChrSize / 8 - 1;
SetMirrorType(Cart.PadH, Cart.PadV);
return true;
}
public override byte ReadPrg(int addr)
{
return Rom[addr + (prg << 15)];
}
public override byte ReadPpu(int addr)
{
if (addr < 0x2000)
{
return Vrom[addr + (chr << 13)];
}
else return base.ReadPpu(addr);
}
private void writereg(byte value)
{
prg = value & 3 & prg_mask;
chr = (value >> 2) & 3 & chr_mask;
}
// the standard way to access this register is at 7000:7fff, but due to
// hardware design, f000:ffff also works
public override void WritePrg(int addr, byte value)
{
//if ((addr & 0x7000) == 0x7000)
// writereg(value);
}
public override void WriteWram(int addr, byte value)
{
if ((addr & 0x1000) == 0x1000)
writereg(value);
}
public override void SyncState(Serializer ser)
{
base.SyncState(ser);
ser.Sync(nameof(chr), ref chr);
ser.Sync(nameof(prg), ref prg);
}
}
}
| 1 | 0.991591 | 1 | 0.991591 | game-dev | MEDIA | 0.420047 | game-dev,drivers | 0.984818 | 1 | 0.984818 |
Oxycontn/Alani-NU | 29,812 | Alani-NU/Alani NU/src/hacks/esp.cpp | #pragma warning( disable : 4244 4312 4305 )
#include "esp.h"
#include "rcs.h"
#include "../classes/global.hpp"
#include "../overlay/overlay.hpp"
#include "../classes/bone.hpp"
#include "aimbot.h"
#include "..\mem\memory.h"
#include "..\entity\local.h"
#include "..\entity\wentity.h"
//esp
void CEntityLoop::EspThread()
{
overlay.CreateOverlay();
overlay.CreateDevice();
overlay.CreateImGui();
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
overlay.StartRender();
//menu calls
if (GetAsyncKeyState(VK_INSERT) & 1)
overlay.RenderMenu = !overlay.RenderMenu;
if (overlay.RenderMenu)
{
SetWindowLong(overlay.overlay, GWL_EXSTYLE, WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST);
menu.NewMenu();
}
else
SetWindowLong(overlay.overlay, GWL_EXSTYLE, WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_LAYERED | WS_EX_TOPMOST);
//read entites then call render inside loop
EspLoop();
overlay.EndRender();
}
}
void CEntityLoop::EspLoop()
{
//entity list varibles
uintptr_t entityList = CEntity::GetEntityList();
//local player varibles
auto localPlayerPawn = CLocal::GetLocalPawn();
view_matrix_t viewMatrix = CLocal::GetViewMatrix();
uintptr_t localPlayerController = CLocal::GetLocalController();
int localTeam = localPlayerPawn.Team();
int localHealth = localPlayerPawn.Health();
Vector localPosition = localPlayerPawn.Position();
std::string localWeaponName = localPlayerPawn.GetWeaponNameLocal();
for (int i = 1; i < 1024; ++i)
{
if (overlay.RenderMenu)
continue;
uintptr_t playerController = CEntity::GetPlayerController(entityList, localPlayerController, i);
//plyer entities
if (i <= 64)
{
if (global.features.teamenable || global.features.enemyenable)
{
auto pCSPlayerPawn = CEntity::GetpCSPlayerPawn(entityList, playerController, i, global.misc.localPlayerPawn);
int playerHealth = pCSPlayerPawn.Health();
int playerTeam = pCSPlayerPawn.Team();
int playerArmor = pCSPlayerPawn.Armor();
if (playerHealth <= 0 || playerHealth > 100)
continue;
uintptr_t gamescene = pCSPlayerPawn.Gamescene();
uintptr_t bonearray = pCSPlayerPawn.Bonearray();
Vector readFeet = pCSPlayerPawn.Feet();
Vector readBoneHead = pCSPlayerPawn.Bone(bones::head);
bool spottedState = pCSPlayerPawn.spottedState();
// made a wrapper for everything below but it was bugging out, not sure why. we'll keep this here for now i guess.
Vector head {};
head.x = readFeet.x;
head.y = readFeet.y;
head.z = readFeet.z + 75.f;
std::string playerName = CEntity::GetPlayerName(playerController);
std::string weaponName = pCSPlayerPawn.GetWeaponName();
RenderEsp(viewMatrix, readBoneHead, readFeet, head, localPosition, weaponName, localTeam, playerTeam, playerName, playerArmor, playerHealth, pCSPlayerPawn, spottedState);
}
}
//world entities
if (i >= 65)
{
if (global.features.worldenable)
{
auto entityController = CWEntity::EntityController(playerController);
auto entityOwner = entityController.EntityOwner();
if (entityOwner != -1)
continue;
auto pEntity = entityController.PEntity();
auto designerNameptr = CWEntity::DesignerNamePtr(pEntity);
std::string designerName = CWEntity::ReadDesignerName(designerNameptr);
if (designerName.find("weapon"))
continue;
auto gameScene = entityController.Gamescene();
Vector entityOrigin = CWEntity::EntityPosition(gameScene);
RenderWorld(localPosition, entityOrigin, viewMatrix, designerName);
}
}
}
int weaponGroup = CLocal::GetWeaponGroup(localWeaponName);
RenderFov(weaponGroup);
}
void CEntityLoop::Bone(view_matrix_t viewMatrix, int localTeam, int playerTeam, Vector feet, Vector head, CEntity pCSPlayerPawn)
{
int circleRadius = abs(feet.y - head.y) / 80;
for (int i = 0; i < sizeof(boneConnections) / sizeof(boneConnections[0]); ++i)
{
int bone1 = boneConnections[i].bone1;
int bone2 = boneConnections[i].bone2;
Vector VectorBone1 = pCSPlayerPawn.Bone(bone1);
Vector VectorBone2 = pCSPlayerPawn.Bone(bone2);
Vector b1;
Vector b2;
if (Vector::WTS(viewMatrix, VectorBone1, b1) &&
Vector::WTS(viewMatrix, VectorBone2, b2))
{
if (localTeam == playerTeam)
{
Render::Line(b1.x, b1.y, b2.x, b2.y, global.features.teamBoneColor, global.features.teamBoneAlpha, 1.5);
if (global.features.teamJoint)
Render::Circle(b2.x, b2.y, circleRadius, white, 255, true);
}
else if (localTeam != playerTeam)
{
Render::Line(b1.x, b1.y, b2.x, b2.y, global.features.enemyBoneColor, global.features.enemyBoneAlpha, 1.5);
if (global.features.enemyJoint)
Render::Circle(b2.x, b2.y, circleRadius, white, 255, true);
}
}
}
}
//render
void CEntityLoop::RenderWorld(Vector localPos, Vector entityPos, view_matrix_t viewMatrix, std::string designerName)
{
Vector entity;
if (Vector::WTS(viewMatrix, entityPos, entity))
{
float distance = localPos.CalculateDistance(entity) / 500;
float fontSize = 100.f / distance;
std::string weaponName = designerName.substr(7);
if (global.features.weapon)
{
if (designerName.find("weapon_molotov" || "weapon_decoy" || "weapon_flashbang" || "weapon_hegrenade" || "weapon_smokegrenade" || "weapon_incgrenade"))
{
Render::Text(fontSize, entity.x - 10, entity.y + 10, white, 255, weaponName);
Render::Rect(entity.x - 10, entity.y - 10, 40, 20, white, 255, 1.5);
}
}
if (global.features.molotov)
{
if (!designerName.find("weapon_molotov"))
{
Render::Text(fontSize, entity.x - 10, entity.y + 10, white, 255, weaponName);
Render::Rect(entity.x - 10, entity.y - 10, 40, 20, white, 255, 1.5);
}
}
if (global.features.incgrenade)
{
if (!designerName.find("weapon_incgrenade"))
{
Render::Text(fontSize, entity.x - 10, entity.y + 10, white, 255, weaponName);
Render::Rect(entity.x - 10, entity.y - 10, 40, 20, white, 255, 1.5);
}
}
if (global.features.decoy)
{
if (!designerName.find("weapon_decoy"))
{
Render::Text(fontSize, entity.x - 10, entity.y + 10, white, 255, weaponName);
Render::Rect(entity.x - 10, entity.y - 10, 40, 20, white, 255, 1.5);
}
}
if (global.features.flash)
{
if (!designerName.find("weapon_flashbang"))
{
Render::Text(fontSize, entity.x - 10, entity.y + 10, white, 255, weaponName);
Render::Rect(entity.x - 10, entity.y - 10, 40, 20, white, 255, 1.5);
}
}
if (global.features.grenade)
{
if (!designerName.find("weapon_hegrenade"))
{
Render::Text(fontSize, entity.x - 10, entity.y + 10, white, 255, weaponName);
Render::Rect(entity.x - 10, entity.y - 10, 40, 20, white, 255, 1.5);
}
}
if (global.features.smoke)
{
if (!designerName.find("weapon_smokegrenade"))
{
Render::Text(fontSize, entity.x - 10, entity.y + 10, white, 255, weaponName);
Render::Rect(entity.x - 10, entity.y - 10, 40, 20, white, 255, 1.5);
}
}
if (global.features.c4)
{
if (!designerName.find("weapon_c4"))
{
Render::Text(fontSize, entity.x - 10, entity.y + 10, white, 255, weaponName);
Render::Rect(entity.x - 10, entity.y - 10, 40, 20, white, 255, 1.5);
}
}
}
}
void CEntityLoop::RenderEsp(view_matrix_t viewMatrix, Vector playerBoneHead, Vector playerFeet, Vector playerHead, Vector localPos, std::string weaponName, int localTeam, int playerTeam, std::string playerName, int armorValue, int healthValue, CEntity pCSPlayerPawn, bool spottedState)
{
Vector feet{};
Vector head{};
Vector boneHead{};
if (Vector::WTS(viewMatrix, playerBoneHead, boneHead) &&
Vector::WTS(viewMatrix, playerFeet, feet) &&
Vector::WTS(viewMatrix, playerHead, head))
{
float height = (feet.y - boneHead.y) * 1.35;
float width = height / 1.5f;
float feetDistance = localPos.CalculateDistance(feet);
float headDistance = localPos.CalculateDistance(head);
float textDistance = feetDistance / headDistance;
float headHeight = (feet.y - boneHead.y) / 14;
std::string weaponName;
if (!weaponName.find("weapon_"))
weaponName = weaponName.substr(7);
float Rbar = min((2.0f * (100 - healthValue)) / 100.0f, 1.0f);
float Gbar = min((2.0f * healthValue) / 100.0f, 1.0f);
RGB healthBr = { Rbar, Gbar, 0 };
//team esp
if (localTeam == playerTeam && global.features.teamenable)
{
//2d box
if (global.features.teamcombo == 1)
{
if (global.features.teamVisable)
{
if (spottedState)
{
Render::RectFilled(
feet.x - width / 2,
head.y,
width,
height,
global.features.teamvisablecolor,
global.features.teamalpha);
Render::Rect(
feet.x - width / 2,
head.y,
width,
height,
white,
255,
1.5);
}
else
{
Render::RectFilled(
feet.x - width / 2,
head.y,
width,
height,
global.features.teaamcolor,
global.features.teamalpha);
Render::Rect(
feet.x - width / 2,
head.y,
width,
height,
white,
255,
1.5);
}
}
else
{
Render::RectFilled(
feet.x - width / 2,
head.y,
width,
height,
global.features.teaamcolor,
global.features.teamalpha);
Render::Rect(
feet.x - width / 2,
head.y,
width,
height,
white,
255,
1.5);
}
}
//corner
if (global.features.teamcombo == 2)
{
if (global.features.teamVisable)
{
if (spottedState)
{
Render::Line(head.x - width / 2.1, head.y, head.x - width / 5, head.y, global.features.teamvisablecolor, 255, 1.5);
Render::Line(feet.x + width / 5, head.y, feet.x + width / 2.1, head.y, global.features.teamvisablecolor, 255, 1.5);
Render::Line(head.x - width / 2.1, feet.y + height / 8.9, head.x - width / 5, feet.y + height / 8.9, global.features.teamvisablecolor, 255, 1.5);
Render::Line(feet.x + width / 5, feet.y + height / 8.9, feet.x + width / 2.1, feet.y + height / 8.9, global.features.teamvisablecolor, 255, 1.5);
Render::Line(head.x - width / 2.1, head.y + height / 10, head.x - width / 2.1, head.y, global.features.teamvisablecolor, 255, 1.5);
Render::Line(feet.x + width / 2.1, head.y + height / 10, feet.x + width / 2.1, head.y, global.features.teamvisablecolor, 255, 1.5);
Render::Line(head.x - width / 2.1, feet.y - height / 40, head.x - width / 2.1, feet.y + height / 8.9, global.features.teamvisablecolor, 255, 1.5);
Render::Line(feet.x + width / 2.1, feet.y - height / 40, feet.x + width / 2.1, feet.y + height / 8.9, global.features.teamvisablecolor, 255, 1.5);
}
else
{
Render::Line(head.x - width / 2.1, head.y, head.x - width / 5, head.y, global.features.teaamcolor, 255, 1.5);
Render::Line(feet.x + width / 5, head.y, feet.x + width / 2.1, head.y, global.features.teaamcolor, 255, 1.5);
Render::Line(head.x - width / 2.1, feet.y + height / 8.9, head.x - width / 5, feet.y + height / 8.9, global.features.teaamcolor, 255, 1.5);
Render::Line(feet.x + width / 5, feet.y + height / 8.9, feet.x + width / 2.1, feet.y + height / 8.9, global.features.teaamcolor, 255, 1.5);
Render::Line(head.x - width / 2.1, head.y + height / 10, head.x - width / 2.1, head.y, global.features.teaamcolor, 255, 1.5);
Render::Line(feet.x + width / 2.1, head.y + height / 10, feet.x + width / 2.1, head.y, global.features.teaamcolor, 255, 1.5);
Render::Line(head.x - width / 2.1, feet.y - height / 40, head.x - width / 2.1, feet.y + height / 8.9, global.features.teaamcolor, 255, 1.5);
Render::Line(feet.x + width / 2.1, feet.y - height / 40, feet.x + width / 2.1, feet.y + height / 8.9, global.features.teaamcolor, 255, 1.5);
}
}
else
{
Render::Line(head.x - width / 2.1, head.y, head.x - width / 5, head.y, global.features.teaamcolor, 255, 1.5);
Render::Line(feet.x + width / 5, head.y, feet.x + width / 2.1, head.y, global.features.teaamcolor, 255, 1.5);
Render::Line(head.x - width / 2.1, feet.y + height / 8.9, head.x - width / 5, feet.y + height / 8.9, global.features.teaamcolor, 255, 1.5);
Render::Line(feet.x + width / 5, feet.y + height / 8.9, feet.x + width / 2.1, feet.y + height / 8.9, global.features.teaamcolor, 255, 1.5);
Render::Line(head.x - width / 2.1, head.y + height / 10, head.x - width / 2.1, head.y, global.features.teaamcolor, 255, 1.5);
Render::Line(feet.x + width / 2.1, head.y + height / 10, feet.x + width / 2.1, head.y, global.features.teaamcolor, 255, 1.5);
Render::Line(head.x - width / 2.1, feet.y - height / 40, head.x - width / 2.1, feet.y + height / 8.9, global.features.teaamcolor, 255, 1.5);
Render::Line(feet.x + width / 2.1, feet.y - height / 40, feet.x + width / 2.1, feet.y + height / 8.9, global.features.teaamcolor, 255, 1.5);
}
}
//bone esp
if (global.features.teamskel)
{
entityloop.Bone(viewMatrix, localTeam, playerTeam, feet, head, pCSPlayerPawn);
}
//head
if (global.features.teamhead)
{
Render::Circle(
boneHead.x,
boneHead.y,
headHeight,
global.features.teamHeaadColor,
global.features.teamHeadAlpha,
0
);
}
//snap lines
if (global.features.teamsnap)
{
Render::Line(feet.x, feet.y, screenWidth / 2, screenHeight, global.features.teamSnapColor, global.features.teamSnapAlpha, 1.5f);
}
//health
if (global.features.teamhealth)
{
//shadow
Render::RectFilled(
feet.x - (width / 1.77),
head.y,
width / 30,
height,
white,
255
);
//health render
Render::RectFilled(
feet.x - (width / 1.78),
head.y + (height * (100 - healthValue) / 100),
width / 40,
height - (height * (100 - healthValue) / 100),
healthBr,
200
);
}
//armor
if (global.features.teamarmor)
{
//shadow
Render::RectFilled(
feet.x + (width / 1.9),
head.y,
width / 30,
height,
white,
255
);
//armor render
Render::RectFilled(
feet.x + (width / 1.890),
head.y + (height * (100 - armorValue) / 100),
width / 40,
height - (height * (100 - armorValue) / 100),
blue,
200
);
}
//weapon
if (global.features.teamweapon)
{
Render::Text(10.f / textDistance, feet.x - width / 2, head.y + height, white, 255, weaponName);
}
//name
if (global.features.teamname)
{
Render::Text(10.f / textDistance, feet.x - width / 2, head.y - 10, white, 255, playerName);
}
}
//enemy esp
if (localTeam != playerTeam && global.features.enemyenable)
{
//2d box
if (global.features.enemycombo == 1)
{
if (global.features.enemyVisable)
{
if (spottedState)
{
Render::RectFilled(
feet.x - width / 2,
head.y,
width,
height,
global.features.enemyvisablecolor,
global.features.enemyalpha);
Render::Rect(
feet.x - width / 2,
head.y,
width,
height,
white,
255,
1.5
);
}
else
{
Render::RectFilled(
feet.x - width / 2,
head.y,
width,
height,
global.features.enemycolor,
global.features.enemyalpha);
Render::Rect(
feet.x - width / 2,
head.y,
width,
height,
white,
255,
1.5
);
}
}
else
{
Render::RectFilled(
feet.x - width / 2,
head.y,
width,
height,
global.features.enemycolor,
global.features.enemyalpha);
Render::Rect(
feet.x - width / 2,
head.y,
width,
height,
white,
255,
1.5
);
}
}
//corner
if (global.features.enemycombo == 2)
{
if (global.features.enemyVisable)
{
if (spottedState)
{
Render::Line(head.x - width / 2.1, head.y, head.x - width / 5, head.y, global.features.enemyvisablecolor, 255, 1.5);
Render::Line(feet.x + width / 5, head.y, feet.x + width / 2.1, head.y, global.features.enemyvisablecolor, 255, 1.5);
Render::Line(head.x - width / 2.1, feet.y + height / 8.9, head.x - width / 5, feet.y + height / 8.9, global.features.enemyvisablecolor, 255, 1.5);
Render::Line(feet.x + width / 5, feet.y + height / 8.9, feet.x + width / 2.1, feet.y + height / 8.9, global.features.enemyvisablecolor, 255, 1.5);
Render::Line(head.x - width / 2.1, head.y + height / 10, head.x - width / 2.1, head.y, global.features.enemyvisablecolor, 255, 1.5);
Render::Line(feet.x + width / 2.1, head.y + height / 10, feet.x + width / 2.1, head.y, global.features.enemyvisablecolor, 255, 1.5);
Render::Line(head.x - width / 2.1, feet.y - height / 40, head.x - width / 2.1, feet.y + height / 8.9, global.features.enemyvisablecolor, 255, 1.5);
Render::Line(feet.x + width / 2.1, feet.y - height / 40, feet.x + width / 2.1, feet.y + height / 8.9, global.features.enemyvisablecolor, 255, 1.5);
}
else
{
Render::Line(head.x - width / 2.1, head.y, head.x - width / 5, head.y, global.features.enemycolor, 255, 1.5);
Render::Line(feet.x + width / 5, head.y, feet.x + width / 2.1, head.y, global.features.enemycolor, 255, 1.5);
Render::Line(head.x - width / 2.1, feet.y + height / 8.9, head.x - width / 5, feet.y + height / 8.9, global.features.enemycolor, 255, 1.5);
Render::Line(feet.x + width / 5, feet.y + height / 8.9, feet.x + width / 2.1, feet.y + height / 8.9, global.features.enemycolor, 255, 1.5);
Render::Line(head.x - width / 2.1, head.y + height / 10, head.x - width / 2.1, head.y, global.features.enemycolor, 255, 1.5);
Render::Line(feet.x + width / 2.1, head.y + height / 10, feet.x + width / 2.1, head.y, global.features.enemycolor, 255, 1.5);
Render::Line(head.x - width / 2.1, feet.y - height / 40, head.x - width / 2.1, feet.y + height / 8.9, global.features.enemycolor, 255, 1.5);
Render::Line(feet.x + width / 2.1, feet.y - height / 40, feet.x + width / 2.1, feet.y + height / 8.9, global.features.enemycolor, 255, 1.5);
}
}
else
{
Render::Line(head.x - width / 2.1, head.y, head.x - width / 5, head.y, global.features.enemycolor, 255, 1.5);
Render::Line(feet.x + width / 5, head.y, feet.x + width / 2.1, head.y, global.features.enemycolor, 255, 1.5);
Render::Line(head.x - width / 2.1, feet.y + height / 8.9, head.x - width / 5, feet.y + height / 8.9, global.features.enemycolor, 255, 1.5);
Render::Line(feet.x + width / 5, feet.y + height / 8.9, feet.x + width / 2.1, feet.y + height / 8.9, global.features.enemycolor, 255, 1.5);
Render::Line(head.x - width / 2.1, head.y + height / 10, head.x - width / 2.1, head.y, global.features.enemycolor, 255, 1.5);
Render::Line(feet.x + width / 2.1, head.y + height / 10, feet.x + width / 2.1, head.y, global.features.enemycolor, 255, 1.5);
Render::Line(head.x - width / 2.1, feet.y - height / 40, head.x - width / 2.1, feet.y + height / 8.9, global.features.enemycolor, 255, 1.5);
Render::Line(feet.x + width / 2.1, feet.y - height / 40, feet.x + width / 2.1, feet.y + height / 8.9, global.features.enemycolor, 255, 1.5);
}
}
//bone esp
if (global.features.enemyskel)
{
entityloop.Bone(viewMatrix, localTeam, playerTeam, feet, head, pCSPlayerPawn);
}
//head
if (global.features.enemyhead)
{
Render::Circle(
boneHead.x,
boneHead.y,
headHeight,
global.features.enemyHeaadColor,
global.features.enemyHeadAlpha,
0
);
}
//snap lines
if (global.features.enemysnap)
{
Render::Line(feet.x, feet.y, screenWidth / 2, screenHeight, global.features.enemySnapColor, global.features.enemySnapAlpha, 1.5f);
}
//health
if (global.features.enemyhealth)
{
//shadow
Render::RectFilled(
feet.x - (width / 1.77),
head.y,
width / 30,
height,
white,
255
);
//health render
Render::RectFilled(
feet.x - (width / 1.78),
head.y + (height * (100 - healthValue) / 100),
width / 40,
height - (height * (100 - healthValue) / 100),
healthBr,
200
);
}
//armor
if (global.features.enemyarmor)
{
//shadow
Render::RectFilled(
feet.x + (width / 1.9),
head.y,
width / 30,
height,
white,
255
);
//armor render
Render::RectFilled(
feet.x + (width / 1.890),
head.y + (height * (100 - armorValue) / 100),
width / 40,
height - (height * (100 - armorValue) / 100),
blue,
200
);
}
//weapon
if (global.features.enemyweapon)
{
Render::Text(10.f / textDistance, feet.x - width / 2, head.y + height, white, 255, weaponName);
}
//name
if (global.features.enemyname)
{
Render::Text(10.f / textDistance, feet.x - width / 2, head.y - 10, white, 255, playerName);
}
}
}
}
void CEntityLoop::RenderFov(int weaponGroup)
{
//AR
if (weaponGroup == 1)
if (global.features.ARaimbotfovcircle)
{
Render::Circle(screenWidth / 2, screenHeight / 2, global.features.ARaimbotfov * 1.7, white, 255, false);
if (aimbot.showBoneAngle)
Render::Line(screenWidth / 2, screenHeight / 2, aimbot.boneAngle.x, aimbot.boneAngle.y, green, 255, 1.5);
}
//SG
if (weaponGroup == 2)
if (global.features.SGaimbotfovcircle)
{
Render::Circle(screenWidth / 2, screenHeight / 2, global.features.SGaimbotfov * 1.7, white, 255, false);
if (aimbot.showBoneAngle)
Render::Line(screenWidth / 2, screenHeight / 2, aimbot.boneAngle.x, aimbot.boneAngle.y, green, 255, 1.5);
}
//Pistols
if (weaponGroup == 3)
if (global.features.PSaimbotfovcircle)
{
Render::Circle(screenWidth / 2, screenHeight / 2, global.features.PSaimbotfov * 1.7, white, 255, false);
if (aimbot.showBoneAngle)
Render::Line(screenWidth / 2, screenHeight / 2, aimbot.boneAngle.x, aimbot.boneAngle.y, green, 255, 1.5);
}
//SR
if (weaponGroup == 4)
if (global.features.SRaimbotfovcircle)
{
Render::Circle(screenWidth / 2, screenHeight / 2, global.features.SRaimbotfov * 1.7, white, 255, false);
if (aimbot.showBoneAngle)
Render::Line(screenWidth / 2, screenHeight / 2, aimbot.boneAngle.x, aimbot.boneAngle.y, green, 255, 1.5);
}
//SMG
if (weaponGroup == 5)
if (global.features.SMGaimbotfovcircle)
{
Render::Circle(screenWidth / 2, screenHeight / 2, global.features.SMGaimbotfov * 1.7, white, 255, false);
if (aimbot.showBoneAngle)
Render::Line(screenWidth / 2, screenHeight / 2, aimbot.boneAngle.x, aimbot.boneAngle.y, green, 255, 1.5);
}
} | 1 | 0.814366 | 1 | 0.814366 | game-dev | MEDIA | 0.982164 | game-dev | 0.963051 | 1 | 0.963051 |
EcsRx/EcsR3.Unity | 3,067 | src/Assets/Plugins/Zenject/Source/Providers/Decorator/DecoratorProvider.cs | using System;
using System.Collections.Generic;
using ModestTree;
namespace Zenject.Internal
{
public interface IDecoratorProvider
{
void GetAllInstances(
IProvider provider, InjectContext context, List<object> buffer);
}
[NoReflectionBaking]
public class DecoratorProvider<TContract> : IDecoratorProvider
{
readonly Dictionary<IProvider, List<object>> _cachedInstances =
new Dictionary<IProvider, List<object>>();
readonly DiContainer _container;
readonly List<Guid> _factoryBindIds = new List<Guid>();
List<IFactory<TContract, TContract>> _decoratorFactories;
#if ZEN_MULTITHREADING
readonly object _locker = new object();
#endif
public DecoratorProvider(DiContainer container)
{
_container = container;
}
public void AddFactoryId(Guid factoryBindId)
{
_factoryBindIds.Add(factoryBindId);
}
void LazyInitializeDecoratorFactories()
{
if (_decoratorFactories == null)
{
_decoratorFactories = new List<IFactory<TContract, TContract>>();
for (int i = 0; i < _factoryBindIds.Count; i++)
{
var bindId = _factoryBindIds[i];
var factory = _container.ResolveId<IFactory<TContract, TContract>>(bindId);
_decoratorFactories.Add(factory);
}
}
}
public void GetAllInstances(
IProvider provider, InjectContext context, List<object> buffer)
{
if (provider.IsCached)
{
List<object> instances;
#if ZEN_MULTITHREADING
lock (_locker)
#endif
{
if (!_cachedInstances.TryGetValue(provider, out instances))
{
instances = new List<object>();
WrapProviderInstances(provider, context, instances);
_cachedInstances.Add(provider, instances);
}
}
buffer.AllocFreeAddRange(instances);
}
else
{
WrapProviderInstances(provider, context, buffer);
}
}
void WrapProviderInstances(IProvider provider, InjectContext context, List<object> buffer)
{
LazyInitializeDecoratorFactories();
provider.GetAllInstances(context, buffer);
for (int i = 0; i < buffer.Count; i++)
{
buffer[i] = DecorateInstance(buffer[i], context);
}
}
object DecorateInstance(object instance, InjectContext context)
{
for (int i = 0; i < _decoratorFactories.Count; i++)
{
instance = _decoratorFactories[i].Create(
context.Container.IsValidating ? default(TContract) : (TContract)instance);
}
return instance;
}
}
}
| 1 | 0.931374 | 1 | 0.931374 | game-dev | MEDIA | 0.719473 | game-dev | 0.815342 | 1 | 0.815342 |
apoguita/Py4GW | 2,613 | Widgets/CustomBehaviors/skills/paragon/fall_back_utility.py | from re import S
from typing import Any, Callable, Generator, override
import random
from Py4GWCoreLib import GLOBAL_CACHE, Routines, Range
from Py4GWCoreLib.enums import Profession, Range
from Widgets.CustomBehaviors.primitives.behavior_state import BehaviorState
from Widgets.CustomBehaviors.primitives.bus.event_bus import EventBus
from Widgets.CustomBehaviors.primitives.helpers import custom_behavior_helpers
from Widgets.CustomBehaviors.primitives.helpers.behavior_result import BehaviorResult
from Widgets.CustomBehaviors.primitives.helpers.targeting_order import TargetingOrder
from Widgets.CustomBehaviors.primitives.parties.custom_behavior_party import CustomBehaviorParty
from Widgets.CustomBehaviors.primitives.scores.score_static_definition import ScoreStaticDefinition
from Widgets.CustomBehaviors.primitives.skills.custom_skill import CustomSkill
from Widgets.CustomBehaviors.primitives.skills.custom_skill_utility_base import CustomSkillUtilityBase
class FallBackUtility(CustomSkillUtilityBase):
def __init__(
self,
event_bus: EventBus,
current_build: list[CustomSkill],
score_definition: ScoreStaticDefinition = ScoreStaticDefinition(99.99),
allowed_states: list[BehaviorState] = [BehaviorState.CLOSE_TO_AGGRO, BehaviorState.FAR_FROM_AGGRO]
) -> None:
super().__init__(
event_bus=event_bus,
skill=CustomSkill("Fall_Back"),
in_game_build=current_build,
score_definition=score_definition,
allowed_states=allowed_states)
self.score_definition: ScoreStaticDefinition = score_definition
@override
def _evaluate(self, current_state: BehaviorState, previously_attempted_skills: list[CustomSkill]) -> float | None:
has_buff = Routines.Checks.Effects.HasBuff(GLOBAL_CACHE.Player.GetAgentID(), self.custom_skill.skill_id)
is_moving = GLOBAL_CACHE.Agent.IsMoving(GLOBAL_CACHE.Player.GetAgentID())
if not has_buff and is_moving: return self.score_definition.get_score()
return None
@override
def _execute(self, state: BehaviorState) -> Generator[Any, None, BehaviorResult]:
lock_key = f"Fall_Back_utility"
if CustomBehaviorParty().get_shared_lock_manager().try_aquire_lock(lock_key) == False:
yield
return BehaviorResult.ACTION_SKIPPED
result:BehaviorResult = yield from custom_behavior_helpers.Actions.cast_skill(self.custom_skill)
CustomBehaviorParty().get_shared_lock_manager().release_lock(lock_key)
return result | 1 | 0.887629 | 1 | 0.887629 | game-dev | MEDIA | 0.578617 | game-dev | 0.758933 | 1 | 0.758933 |
PaperMC/Paper | 3,663 | paper-server/patches/sources/net/minecraft/world/entity/projectile/ThrownSplashPotion.java.patch | --- a/net/minecraft/world/entity/projectile/ThrownSplashPotion.java
+++ b/net/minecraft/world/entity/projectile/ThrownSplashPotion.java
@@ -36,13 +_,14 @@
}
@Override
- public void onHitAsPotion(ServerLevel level, ItemStack stack, HitResult hitResult) {
+ public boolean onHitAsPotion(ServerLevel level, ItemStack stack, HitResult hitResult) { // Paper - More projectile API
PotionContents potionContents = stack.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY);
float orDefault = stack.getOrDefault(DataComponents.POTION_DURATION_SCALE, 1.0F);
Iterable<MobEffectInstance> allEffects = potionContents.getAllEffects();
AABB aabb = this.getBoundingBox().move(hitResult.getLocation().subtract(this.position()));
AABB aabb1 = aabb.inflate(4.0, 2.0, 4.0);
List<LivingEntity> entitiesOfClass = this.level().getEntitiesOfClass(LivingEntity.class, aabb1);
+ java.util.Map<org.bukkit.entity.LivingEntity, Double> affected = new java.util.HashMap<>(); // CraftBukkit
float f = ProjectileUtil.computeMargin(this);
if (!entitiesOfClass.isEmpty()) {
Entity effectSource = this.getEffectSource();
@@ -51,8 +_,25 @@
if (livingEntity.isAffectedByPotions()) {
double d = aabb.distanceToSqr(livingEntity.getBoundingBox().inflate(f));
if (d < 16.0) {
- double d1 = 1.0 - Math.sqrt(d) / 4.0;
-
+ double d1 = 1.0 - Math.sqrt(d) / 4.0; // Paper - diff on change, used when calling the splash event for water splash potions
+ // CraftBukkit start
+ affected.put(livingEntity.getBukkitLivingEntity(), d1);
+ }
+ }
+ }
+ }
+ org.bukkit.event.entity.PotionSplashEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callPotionSplashEvent(this, hitResult, affected);
+ if (!event.isCancelled() && !entitiesOfClass.isEmpty()) { // do not process effects if there are no effects to process
+ Entity effectSource = this.getEffectSource();
+ for (org.bukkit.entity.LivingEntity victim : event.getAffectedEntities()) {
+ if (!(victim instanceof org.bukkit.craftbukkit.entity.CraftLivingEntity craftLivingEntity)) {
+ continue;
+ }
+ LivingEntity livingEntity = craftLivingEntity.getHandle();
+ double d1 = event.getIntensity(victim);
+ {
+ {
+ // CraftBukkit end
for (MobEffectInstance mobEffectInstance : allEffects) {
Holder<MobEffect> effect = mobEffectInstance.getEffect();
if (effect.value().isInstantenous()) {
@@ -63,7 +_,7 @@
effect, i, mobEffectInstance.getAmplifier(), mobEffectInstance.isAmbient(), mobEffectInstance.isVisible()
);
if (!mobEffectInstance1.endsWithin(20)) {
- livingEntity.addEffect(mobEffectInstance1, effectSource);
+ livingEntity.addEffect(mobEffectInstance1, effectSource, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.POTION_SPLASH); // CraftBukkit
}
}
}
@@ -71,5 +_,6 @@
}
}
}
+ return !event.isCancelled(); // Paper - Fix potions splash events
}
}
| 1 | 0.712438 | 1 | 0.712438 | game-dev | MEDIA | 0.996144 | game-dev | 0.96736 | 1 | 0.96736 |
teamdfir/sift-saltstack | 16,624 | sift/files/pdf-tools/PDFTemplate.bt | //---------------------------------------------------------------------------
/*
010 Editor Template for PDF file format
2010/08/06 v0.0.1
As the PDF file format is not your usual binary file format for which it is easy to create
010 templates, I had to resort to unusual template programming techniques.
Some limitations of the 010 scripting language (like not being able to create local structures)
also explain the unusual style.
Summary of the algorithm used by this template:
- search for keywords with FindAll (%PDF, %%EOF, obj, endobj): FindAllKeywords()
- merge all found keywords into one array, and filter out found keywords that are not actual
PDF structures (like obj without preceding index and version): MergeAndFilterAllKeywords()
- loop over all keywords and prepare data needed to create PDF structures: PrepareStructures()
- create PDF structures: CreatePDFStructures()
Source code put in public domain by Didier Stevens, no Copyright
https://DidierStevens.com
Use at your own risk
History:
2010/08/03: start development with 010 Editor v3.0.6
2010/08/04: continue
2010/08/05: continue
2010/08/06: refactoring, cleanup
*/
//---------------------------------------------------------------------------
local int iCOLOR = 0x95E8FF; // Color used for highlighting PDF structures
enum int {TYPE_UNKNOWN, TYPE_HEADER, TYPE_TRAILER, TYPE_OBJ, TYPE_ENDOBJ};
// Global variables
local int iKeywordCount;
local int iStructureCount;
local TFindResults tfrHeaders;
local TFindResults tfrTrailers;
local TFindResults tfrObjs;
local TFindResults tfrEndobjs;
local int iPDFHeaderCount = 0;
local int iPDFTrailerCount = 0;
local int iPDFUnknownCount = 0;
local int iPDFCommentCount = 0;
local int iPDFWhitespaceCount = 0;
local int iPDFXrefCount = 0;
local int iPDFObjectCount = 0;
// Structures
local int iIndexLength;
local int iWhiteSpace1Length;
local int iVersionLength;
local int iWhiteSpace2Length;
local int iDataLength;
local int iFoundEndobj;
local int iWhiteSpace3Length;
typedef struct {
BYTE Index[iIndexLength];
BYTE WhiteSpace1[iWhiteSpace1Length];
BYTE Version[iVersionLength];
BYTE WhiteSpace2[iWhiteSpace2Length];
BYTE Object[3];
BYTE Data[iDataLength];
if (iFoundEndobj)
BYTE EndObject[6];
BYTE WhiteSpace3[iWhiteSpace3Length];
} PDFObj <read=ReadPDFObj>;
string ReadPDFObj(PDFObj &sPDFObj)
{
local string sResult;
SPrintf(sResult, "%s %s obj %s", sPDFObj.Index, sPDFObj.Version, sPDFObj.Data);
return sResult;
}
local int iHeaderSize;
typedef struct {
BYTE Header[iHeaderSize];
} PDFHeader;
local int iTrailerSize;
typedef struct {
BYTE Trailer[iTrailerSize];
} PDFTrailer;
local int iUnknownSize;
typedef struct {
BYTE Data[iUnknownSize];
} PDFUnknown;
local int iCommentSize;
typedef struct {
BYTE Comment[iCommentSize];
} PDFComment;
local int iWhitespaceSize;
typedef struct {
BYTE Whitespace[iWhitespaceSize];
} PDFWhitespace;
local int iXrefSize;
typedef struct {
BYTE Data[iXrefSize];
} PDFXref;
// Functions
int64 FindStartOfObj(int64 iStart, int &iIndexLength, int &iWhiteSpace1Length, int &iVersionLength, int &iWhiteSpace2Length)
{
local int iIter;
local BYTE bChar;
local int64 iIndex;
local int64 iStartIndex = -1;
local int64 iEndIndex = -1;
local int64 iStartVersion = -1;
local int64 iEndVersion = -1;
for(iIter = 1; iIter <= 20; iIter++)
{
iIndex = iStart - iIter;
if (iIndex < 0)
break;
bChar = ReadByte(iIndex);
if (iEndVersion == -1)
{
if (bChar == ' ')
;
else if (bChar >= '0' && bChar <= '9')
iEndVersion = iIndex;
else
break;
}
else if (iStartVersion == -1)
{
if (bChar >= '0' && bChar <= '9')
;
else if (bChar == ' ')
iStartVersion = iIndex + 1;
else
break;
}
else if (iEndIndex == -1)
{
if (bChar == ' ')
;
else if (bChar >= '0' && bChar <= '9')
iEndIndex = iIndex;
else
break;
}
else if (iStartIndex == -1)
{
if (bChar < '0' || bChar > '9')
{
iStartIndex = iIndex + 1;
break;
}
}
}
if (iEndIndex != -1 && iStartVersion != -1 && iEndVersion != -1)
{
if (iStartIndex == -1)
{
if (iIndex == -1)
iStartIndex = 0;
else
return -1;
}
iIndexLength = iEndIndex - iStartIndex + 1;
iWhiteSpace1Length = iStartVersion - iEndIndex - 1;
iVersionLength = iEndVersion - iStartVersion + 1;
iWhiteSpace2Length = iStart - iEndVersion;
return iStartIndex;
}
else
return -1;
}
int64 FindEOL(int64 iStart)
{
local int64 iIter;
for(iIter = iStart; iIter < FileSize(); iIter++)
if (ReadByte(iIter) == 0x0D && iIter + 1 < FileSize() && ReadByte(iIter + 1) == 0x0A)
return iIter + 1;
else if (ReadByte(iIter) == 0x0D || ReadByte(iIter) == 0x0A)
return iIter;
return -1;
}
void FindAllKeywords(void)
{
tfrHeaders = FindAll("%PDF");
tfrTrailers = FindAll("%%EOF");
tfrObjs = FindAll(" obj");
tfrEndobjs = FindAll("endobj");
iKeywordCount = tfrHeaders.count + tfrTrailers.count + tfrObjs.count + tfrEndobjs.count;
}
int MergeKeywords(int iMerge1Size, int iMerge2Size)
{
local int64 iIndex1 = 0;
local int64 iIndex2 = 0;
local int64 iIndex3 = 0;
while (true)
{
if (iIndex1 == iMerge1Size)
{
while (iIndex2 < iMerge2Size)
{
aiMerge3KeywordType[iIndex3] = aiMerge2KeywordType[iIndex2];
aiMerge3KeywordStart[iIndex3] = aiMerge2KeywordStart[iIndex2];
aiMerge3KeywordSize[iIndex3] = aiMerge2KeywordSize[iIndex2];
iIndex2++;
iIndex3++;
}
break;
}
if (iIndex2 == iMerge2Size)
{
while (iIndex1 < iMerge1Size)
{
aiMerge3KeywordType[iIndex3] = aiMerge1KeywordType[iIndex1];
aiMerge3KeywordStart[iIndex3] = aiMerge1KeywordStart[iIndex1];
aiMerge3KeywordSize[iIndex3] = aiMerge1KeywordSize[iIndex1];
iIndex1++;
iIndex3++;
}
break;
}
if (aiMerge1KeywordStart[iIndex1] < aiMerge2KeywordStart[iIndex2])
{
aiMerge3KeywordType[iIndex3] = aiMerge1KeywordType[iIndex1];
aiMerge3KeywordStart[iIndex3] = aiMerge1KeywordStart[iIndex1];
aiMerge3KeywordSize[iIndex3] = aiMerge1KeywordSize[iIndex1];
iIndex1++;
iIndex3++;
}
else
{
aiMerge3KeywordType[iIndex3] = aiMerge2KeywordType[iIndex2];
aiMerge3KeywordStart[iIndex3] = aiMerge2KeywordStart[iIndex2];
aiMerge3KeywordSize[iIndex3] = aiMerge2KeywordSize[iIndex2];
iIndex2++;
iIndex3++;
}
}
for(iIndex1 = 0; iIndex1 < iMerge1Size + iMerge2Size; iIndex1++)
{
aiMerge1KeywordType[iIndex1] = aiMerge3KeywordType[iIndex1];
aiMerge1KeywordStart[iIndex1] = aiMerge3KeywordStart[iIndex1];
aiMerge1KeywordSize[iIndex1] = aiMerge3KeywordSize[iIndex1];
}
return iMerge1Size + iMerge2Size;
}
void MergeAndFilterAllKeywords(void)
{
local int iIter;
local int iIter2;
local int iTempCount;
for(iIter = 0; iIter < tfrHeaders.count; iIter++)
{
aiMerge1KeywordType[iIter] = TYPE_HEADER;
aiMerge1KeywordStart[iIter] = tfrHeaders.start[iIter];
aiMerge1KeywordSize[iIter] = tfrHeaders.size[iIter];
}
for(iIter = 0; iIter < tfrTrailers.count; iIter++)
{
aiMerge2KeywordType[iIter] = TYPE_TRAILER;
aiMerge2KeywordStart[iIter] = tfrTrailers.start[iIter];
aiMerge2KeywordSize[iIter] = tfrTrailers.size[iIter];
}
iTempCount = MergeKeywords(tfrHeaders.count, tfrTrailers.count);
iIter2 = 0;
for(iIter = 0; iIter < tfrObjs.count; iIter++)
{
if (-1 != FindStartOfObj(tfrObjs.start[iIter], iIndexLength, iWhiteSpace1Length, iVersionLength, iWhiteSpace2Length))
{
aiMerge2KeywordType[iIter2] = TYPE_OBJ;
aiMerge2KeywordStart[iIter2] = tfrObjs.start[iIter];
aiMerge2KeywordSize[iIter2] = tfrObjs.size[iIter];
iIter2++;
}
}
iTempCount = MergeKeywords(iTempCount, iIter2);
for(iIter = 0; iIter < tfrEndobjs.count; iIter++)
{
aiMerge2KeywordType[iIter] = TYPE_ENDOBJ;
aiMerge2KeywordStart[iIter] = tfrEndobjs.start[iIter];
aiMerge2KeywordSize[iIter] = tfrEndobjs.size[iIter];
}
iKeywordCount = MergeKeywords(iTempCount, tfrEndobjs.count);
}
int CalculateSizeWithEOL(int64 iStart)
{
local int64 iIndexEOL;
iIndexEOL = FindEOL(iStart);
if (iIndexEOL == -1)
return -1;
else
return iIndexEOL - iStart + 1;
}
void PrepareStructures(void)
{
local int iIter;
local int64 iEndPreviousStructure = 0;
local int iSize;
local int64 iStartIndirectObject;
local BYTE bRead;
local int iWhitespaceCount;
iStructureCount = 0;
for(iIter = 0; iIter < iKeywordCount; iIter++)
{
if (aiMerge1KeywordType[iIter] == TYPE_OBJ)
iStartIndirectObject = FindStartOfObj(aiMerge1KeywordStart[iIter], iIndexLength, iWhiteSpace1Length, iVersionLength, iWhiteSpace2Length);
else
iStartIndirectObject = aiMerge1KeywordStart[iIter];
if (iStartIndirectObject != iEndPreviousStructure && aiMerge1KeywordType[iIter] != TYPE_ENDOBJ)
{
aiStructureType[iStructureCount] = TYPE_UNKNOWN;
aiStructureStart[iStructureCount] = iEndPreviousStructure;
aiStructureSize[iStructureCount] = iStartIndirectObject - iEndPreviousStructure;
iStructureCount++;
}
if (aiMerge1KeywordType[iIter] == TYPE_HEADER)
{
iSize = CalculateSizeWithEOL(aiMerge1KeywordStart[iIter]);
if (iSize == -1)
iSize = aiMerge1KeywordSize[iIter];
aiStructureType[iStructureCount] = TYPE_HEADER;
aiStructureStart[iStructureCount] = aiMerge1KeywordStart[iIter];
aiStructureSize[iStructureCount] = iSize;
iEndPreviousStructure = aiStructureStart[iStructureCount] + aiStructureSize[iStructureCount];
iStructureCount++;
}
else if (aiMerge1KeywordType[iIter] == TYPE_TRAILER)
{
iSize = CalculateSizeWithEOL(aiMerge1KeywordStart[iIter]);
if (iSize == -1)
iSize = aiMerge1KeywordSize[iIter];
aiStructureType[iStructureCount] = TYPE_TRAILER;
aiStructureStart[iStructureCount] = aiMerge1KeywordStart[iIter];
aiStructureSize[iStructureCount] = iSize;
iEndPreviousStructure = aiStructureStart[iStructureCount] + aiStructureSize[iStructureCount];
iStructureCount++;
}
else if (aiMerge1KeywordType[iIter] == TYPE_OBJ)
{
iSize = aiMerge1KeywordStart[iIter + 1] - iStartIndirectObject;
if (aiMerge1KeywordType[iIter + 1] == TYPE_ENDOBJ)
iSize += 6;
iWhitespaceCount = 0;
bRead = ReadByte(iStartIndirectObject + iSize);
while (bRead == 0x0D || bRead == 0x0A || bRead == 0x20)
{
iWhitespaceCount++;
bRead = ReadByte(iStartIndirectObject + iSize + iWhitespaceCount);
}
iSize += iWhitespaceCount;
aiStructureType[iStructureCount] = TYPE_OBJ;
aiStructureStart[iStructureCount] = iStartIndirectObject;
aiStructureSize[iStructureCount] = iSize;
aiStructureExtraParameter1[iStructureCount] = iIndexLength;
aiStructureExtraParameter2[iStructureCount] = iWhiteSpace1Length;
aiStructureExtraParameter3[iStructureCount] = iVersionLength;
aiStructureExtraParameter4[iStructureCount] = iWhiteSpace2Length;
aiStructureExtraParameter5[iStructureCount] = aiMerge1KeywordType[iIter + 1] == TYPE_ENDOBJ;
aiStructureExtraParameter6[iStructureCount] = iWhitespaceCount;
iEndPreviousStructure = aiStructureStart[iStructureCount] + aiStructureSize[iStructureCount];
iStructureCount++;
}
}
// code for unknown structure after last keyword
if (FileSize() - aiStructureStart[iStructureCount - 1] - aiStructureSize[iStructureCount - 1] != 0)
{
aiStructureType[iStructureCount] = TYPE_UNKNOWN;
aiStructureStart[iStructureCount] = aiStructureStart[iStructureCount - 1] + aiStructureSize[iStructureCount - 1];
aiStructureSize[iStructureCount] = FileSize() - aiStructureStart[iStructureCount - 1] - aiStructureSize[iStructureCount - 1];
iStructureCount++;
}
}
void CreatePDFHeader(int64 iStart, int iSize)
{
iPDFHeaderCount++;
FSeek(iStart);
iHeaderSize = iSize;
PDFHeader sPDFHeader;
}
void CreatePDFTrailer(int64 iStart, int iSize)
{
iPDFTrailerCount++;
FSeek(iStart);
iTrailerSize = iSize;
PDFTrailer sPDFTrailer;
}
void CreatePDFUnknown(int64 iStart, int iSize)
{
iPDFUnknownCount++;
FSeek(iStart);
iUnknownSize = iSize;
PDFUnknown sPDFUnknown;
}
void CreatePDFComment(int64 iStart, int iSize)
{
iPDFCommentCount++;
FSeek(iStart);
iCommentSize = iSize;
PDFComment sPDFComment;
}
int IsWhitespace(int64 iStart, int iSize)
{
local int64 iIter;
local BYTE bRead;
for(iIter = iStart; iIter < iStart + iSize; iIter++)
{
bRead = ReadByte(iIter);
if (bRead != 0x09 && bRead != 0x0A && bRead != 0x0D && bRead != 0x20)
return false;
}
return true;
}
void CreatePDFWhitespace(int64 iStart, int iSize)
{
iPDFWhitespaceCount++;
FSeek(iStart);
iWhitespaceSize = iSize;
PDFWhitespace sPDFWhitespace;
}
int StartsWith(int64 iStart, int iSize, string sData)
{
local int64 iIter;
if (Strlen(sData) > iSize)
return false;
for(iIter = 0; iIter < Strlen(sData); iIter++)
if (ReadByte(iStart + iIter) != sData[iIter])
return false;
return true;
}
void CreatePDFXref(int64 iStart, int iSize)
{
iPDFXrefCount++;
FSeek(iStart);
iXrefSize = iSize;
PDFXref sPDFXref;
}
void CreatePDFObject(int64 iStart, int iSize, int iIndexLengthArg, int iWhiteSpace1LengthArg, int iVersionLengthArg, int iWhiteSpace2LengthArg, int iFoundEndobjArg, int iWhiteSpace3LengthArg)
{
iPDFObjectCount++;
iIndexLength = iIndexLengthArg;
iWhiteSpace1Length = iWhiteSpace1LengthArg;
iVersionLength = iVersionLengthArg;
iWhiteSpace2Length = iWhiteSpace2LengthArg;
iFoundEndobj = iFoundEndobjArg;
iWhiteSpace3Length = iWhiteSpace3LengthArg;
FSeek(iStart);
iDataLength = iSize - iIndexLength - iWhiteSpace1Length - iVersionLength - iWhiteSpace2Length - 6 - 3 - iWhiteSpace3LengthArg;
PDFObj sPDFObj;
}
local int iToggleColor = iCOLOR;
void ToggleBackColor()
{
if (iToggleColor == iCOLOR)
iToggleColor = cNone;
else
iToggleColor = iCOLOR;
SetBackColor(iToggleColor);
}
void CreatePDFStructures(void)
{
local int iIter;
for(iIter = 0; iIter < iStructureCount; iIter++)
{
ToggleBackColor();
if (aiStructureType[iIter] == TYPE_UNKNOWN && StartsWith(aiStructureStart[iIter], aiStructureSize[iIter], "%"))
CreatePDFComment(aiStructureStart[iIter], aiStructureSize[iIter]);
else if (aiStructureType[iIter] == TYPE_UNKNOWN && StartsWith(aiStructureStart[iIter], aiStructureSize[iIter], "xref"))
CreatePDFXref(aiStructureStart[iIter], aiStructureSize[iIter]);
else if (aiStructureType[iIter] == TYPE_UNKNOWN && IsWhitespace(aiStructureStart[iIter], aiStructureSize[iIter]))
CreatePDFWhitespace(aiStructureStart[iIter], aiStructureSize[iIter]);
else if (aiStructureType[iIter] == TYPE_UNKNOWN)
CreatePDFUnknown(aiStructureStart[iIter], aiStructureSize[iIter]);
else if (aiStructureType[iIter] == TYPE_HEADER)
CreatePDFHeader(aiStructureStart[iIter], aiStructureSize[iIter]);
else if (aiStructureType[iIter] == TYPE_TRAILER)
CreatePDFTrailer(aiStructureStart[iIter], aiStructureSize[iIter]);
else if (aiStructureType[iIter] == TYPE_OBJ)
CreatePDFObject(aiStructureStart[iIter], aiStructureSize[iIter], aiStructureExtraParameter1[iIter], aiStructureExtraParameter2[iIter], aiStructureExtraParameter3[iIter], aiStructureExtraParameter4[iIter], aiStructureExtraParameter5[iIter], aiStructureExtraParameter6[iIter]);
}
SetBackColor(cNone);
}
void PrintPDFCounters(void)
{
Printf("Structure counts:\n");
Printf(" PDFHeader = %5d\n", iPDFHeaderCount);
Printf(" PDFTrailer = %5d\n", iPDFTrailerCount);
Printf(" PDFObject = %5d\n", iPDFObjectCount);
Printf(" PDFComment = %5d\n", iPDFCommentCount);
Printf(" PDFXref = %5d\n", iPDFXrefCount);
Printf(" PDFWhitespace = %5d\n", iPDFWhitespaceCount);
Printf(" PDFUnknown = %5d\n", iPDFUnknownCount);
}
// Main
FindAllKeywords();
if (iKeywordCount == 0)
{
Printf("Keywords not found, not a PDF file!\n");
return;
}
local int aiMerge1KeywordType[iKeywordCount];
local int64 aiMerge1KeywordStart[iKeywordCount];
local int aiMerge1KeywordSize[iKeywordCount];
local int aiMerge2KeywordType[iKeywordCount];
local int64 aiMerge2KeywordStart[iKeywordCount];
local int aiMerge2KeywordSize[iKeywordCount];
local int aiMerge3KeywordType[iKeywordCount];
local int64 aiMerge3KeywordStart[iKeywordCount];
local int aiMerge3KeywordSize[iKeywordCount];
MergeAndFilterAllKeywords();
local int aiStructureType[iKeywordCount * 2 + 1];
local int64 aiStructureStart[iKeywordCount * 2 + 1];
local int aiStructureSize[iKeywordCount * 2 + 1];
local int aiStructureExtraParameter1[iKeywordCount * 2 + 1];
local int aiStructureExtraParameter2[iKeywordCount * 2 + 1];
local int aiStructureExtraParameter3[iKeywordCount * 2 + 1];
local int aiStructureExtraParameter4[iKeywordCount * 2 + 1];
local int aiStructureExtraParameter5[iKeywordCount * 2 + 1];
local int aiStructureExtraParameter6[iKeywordCount * 2 + 1];
PrepareStructures();
CreatePDFStructures();
PrintPDFCounters();
| 1 | 0.888448 | 1 | 0.888448 | game-dev | MEDIA | 0.451526 | game-dev | 0.943039 | 1 | 0.943039 |
rust-adventure/asteroids | 9,918 | src/meteors.rs | use std::f32::consts::TAU;
use crate::{
assets::ImageAssets,
kenney_assets::KenneySpriteSheetAsset,
movement::{LinearMovement, Spin, WrappingMovement},
ui::pause::Pausable,
GameState,
};
use bevy::prelude::*;
use bevy_hanabi::prelude::*;
use bevy_xpbd_2d::prelude::*;
use rand::prelude::*;
pub struct MeteorPlugin;
impl Plugin for MeteorPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, register_meteor_effect)
.add_systems(
PostUpdate,
sandbox_meteor_destroyed_event_handler
.run_if(resource_equals(
Pausable::NotPaused,
))
.run_if(in_state(GameState::Playing)),
)
.add_event::<MeteorDestroyed>();
}
}
fn register_meteor_effect(
mut commands: Commands,
mut effects: ResMut<Assets<EffectAsset>>,
) {
let spawner = Spawner::once(100.0.into(), false);
let writer = ExprWriter::new();
let age = writer.lit(0.).expr();
let init_age =
SetAttributeModifier::new(Attribute::AGE, age);
let lifetime = writer.lit(1.5).expr();
let init_lifetime = SetAttributeModifier::new(
Attribute::LIFETIME,
lifetime,
);
let drag = writer.lit(2.).expr();
let update_drag = LinearDragModifier::new(drag);
let color = writer.prop("spawn_color").expr();
let init_color =
SetAttributeModifier::new(Attribute::COLOR, color);
let init_pos = SetPositionCircleModifier {
center: writer.lit(Vec3::Y).expr(),
axis: writer.lit(Vec3::Z).expr(),
radius: writer.lit(TAU).expr(),
dimension: ShapeDimension::Surface,
};
let init_vel = SetVelocityCircleModifier {
center: writer.lit(Vec3::ZERO).expr(),
axis: writer.lit(Vec3::Z).expr(),
speed: (writer.lit(200.)
* writer.rand(ScalarType::Float))
.expr(),
};
let effect = effects.add(
EffectAsset::new(32768, spawner, writer.finish())
.with_name("explosion")
.with_property(
"spawn_color",
0xFFFFFFFFu32.into(),
)
.init(init_pos)
.init(init_vel)
.init(init_age)
.init(init_lifetime)
.init(init_color)
.update(update_drag)
.render(SetSizeModifier {
size: Vec2::splat(3.).into(),
screen_space_size: true,
}),
);
commands
.spawn((
ParticleEffectBundle::new(effect)
.with_spawner(spawner),
EffectProperties::default(),
))
.insert(Name::new("effect:meteor_explosion"));
}
#[derive(Bundle)]
pub struct MeteorBundle {
meteor_type: MeteorType,
meteor: Meteor,
collider: Collider,
sprite_bundle: SpriteBundle,
texture_atlas: TextureAtlas,
linear_movement: LinearMovement,
spin: Spin,
wrapping: WrappingMovement,
}
#[derive(Debug, Component, Clone, Copy)]
pub enum MeteorType {
Big,
Medium,
Small,
}
#[derive(Component)]
pub struct Meteor;
const METEOR_BASE_SPEED_BIG: f32 = 1.;
const METEOR_BASE_SPEED_MEDIUM: f32 = 1.2;
const METEOR_BASE_SPEED_SMALL: f32 = 1.4;
impl MeteorBundle {
pub fn big(
transform: Transform,
space_sheet: &KenneySpriteSheetAsset,
) -> MeteorBundle {
let mut rng = rand::thread_rng();
let x = rng.gen::<f32>() * METEOR_BASE_SPEED_BIG;
let y = rng.gen::<f32>() * METEOR_BASE_SPEED_BIG;
let rotation = rng.gen::<f32>() * TAU;
MeteorBundle {
meteor_type: MeteorType::Big,
meteor: Meteor,
collider: Collider::circle(42.),
sprite_bundle: SpriteBundle {
transform,
texture: space_sheet.sheet.clone(),
..default()
},
texture_atlas: TextureAtlas {
index: 163,
layout: space_sheet
.texture_atlas_layout
.clone(),
},
linear_movement: LinearMovement {
movement_factor: Vec2::new(
x as f32, y as f32,
),
movement_direction: Quat::from_rotation_z(
rotation,
),
},
spin: Spin(1.3),
wrapping: WrappingMovement,
}
}
pub fn medium(
transform: Transform,
space_sheet: &KenneySpriteSheetAsset,
) -> MeteorBundle {
let mut rng = rand::thread_rng();
let x = rng.gen::<f32>() * METEOR_BASE_SPEED_MEDIUM;
let y = rng.gen::<f32>() * METEOR_BASE_SPEED_MEDIUM;
let rotation = rng.gen::<f32>() * TAU;
MeteorBundle {
meteor_type: MeteorType::Medium,
meteor: Meteor,
collider: Collider::circle(21.),
sprite_bundle: SpriteBundle {
transform,
texture: space_sheet.sheet.clone(),
..default()
},
texture_atlas: TextureAtlas {
index: 167,
layout: space_sheet
.texture_atlas_layout
.clone(),
},
linear_movement: LinearMovement {
movement_factor: Vec2::new(
x as f32, y as f32,
),
movement_direction: Quat::from_rotation_z(
rotation,
),
},
spin: Spin(1.6),
wrapping: WrappingMovement,
}
}
pub fn small(
transform: Transform,
space_sheet: &KenneySpriteSheetAsset,
) -> MeteorBundle {
let mut rng = rand::thread_rng();
let x = rng.gen::<f32>() * METEOR_BASE_SPEED_SMALL;
let y = rng.gen::<f32>() * METEOR_BASE_SPEED_SMALL;
let rotation = rng.gen::<f32>() * TAU;
MeteorBundle {
meteor_type: MeteorType::Small,
meteor: Meteor,
collider: Collider::circle(14.),
sprite_bundle: SpriteBundle {
transform,
texture: space_sheet.sheet.clone(),
..default()
},
texture_atlas: TextureAtlas {
index: 169,
layout: space_sheet
.texture_atlas_layout
.clone(),
},
linear_movement: LinearMovement {
movement_factor: Vec2::new(
x as f32, y as f32,
),
movement_direction: Quat::from_rotation_z(
rotation,
),
},
spin: Spin(2.),
wrapping: WrappingMovement,
}
}
}
#[derive(Debug, Event)]
pub struct MeteorDestroyed {
pub destroyed_at: Transform,
pub destroyed_type: MeteorType,
}
fn sandbox_meteor_destroyed_event_handler(
mut commands: Commands,
images: Res<ImageAssets>,
mut events: EventReader<MeteorDestroyed>,
// meteors: Query<Entity, With<MeteorType>>,
sheets: Res<Assets<KenneySpriteSheetAsset>>,
mut effect: Query<(
&mut EffectProperties,
&mut EffectSpawner,
&mut Transform,
)>,
) {
let Some(space_sheet) = sheets.get(&images.space_sheet)
else {
warn!("sandbox_meteor_destroyed_event_handler requires meteor sprites to be loaded");
return;
};
let mut rng = rand::thread_rng();
// Note: On first frame where the effect spawns,
// EffectSpawner is spawned during PostUpdate,
// so will not be available yet. Ignore for a
// frame if so.
let Ok((
mut properties,
mut spawner,
mut effect_transform,
)) = effect.get_single_mut()
else {
warn!("effect not ready yet, returning");
return;
};
for MeteorDestroyed {
destroyed_at,
destroyed_type,
} in &mut events.read()
{
effect_transform.translation =
destroyed_at.translation;
let color = Color::lch(
1.,
1.,
rand::random::<f32>() * 360.,
);
properties.set(
"spawn_color",
color.as_linear_rgba_u32().into(),
);
// Spawn the particles
spawner.reset();
match destroyed_type {
MeteorType::Big => {
// become two medium
for _ in 0..2 {
let x: i32 = rng.gen_range(-5..5);
let y: i32 = rng.gen_range(-5..5);
commands.spawn(MeteorBundle::medium(
Transform::from_xyz(
destroyed_at.translation.x
+ x as f32,
destroyed_at.translation.y
+ y as f32,
1.,
),
space_sheet,
));
}
}
MeteorType::Medium => {
// become two smol
for _ in 0..2 {
let x: i32 = rng.gen_range(-5..5);
let y: i32 = rng.gen_range(-5..5);
commands.spawn(MeteorBundle::small(
Transform::from_xyz(
destroyed_at.translation.x
+ x as f32,
destroyed_at.translation.y
+ y as f32,
1.,
),
space_sheet,
));
}
}
MeteorType::Small => {
// small meteors don't propogate
// more meteors
}
}
}
}
| 1 | 0.767284 | 1 | 0.767284 | game-dev | MEDIA | 0.887092 | game-dev | 0.972414 | 1 | 0.972414 |
leap71/LEAP71_RoverWheel | 13,983 | RoverWheel/RoverWheel.cs | //
// SPDX-License-Identifier: Apache-2.0
//
// The LEAP 71 ShapeKernel is an open source geometry engine
// specifically for use in Computational Engineering Models (CEM).
//
// For more information, please visit https://leap71.com/shapekernel
//
// This project is developed and maintained by LEAP 71 - © 2023 by LEAP 71
// https://leap71.com
//
// Computational Engineering will profoundly change our physical world in the
// years ahead. Thank you for being part of the journey.
//
// We have developed this library to be used widely, for both commercial and
// non-commercial projects alike. Therefore, have released it under a permissive
// open-source license.
//
// The LEAP 71 ShapeKernel is based on the PicoGK compact computational geometry
// framework. See https://picogk.org for more information.
//
// LEAP 71 licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, THE SOFTWARE IS
// PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Numerics;
using PicoGK;
namespace Leap71
{
using ShapeKernel;
namespace Rover
{
/// <summary>
/// Abstract class from which different rover wheel classes can be derived.
/// </summary>
public abstract class RoverWheel
{
public static float m_fHubRadius;
public static float m_fOuterRadius;
public static float m_fRefWidth;
protected BaseLens m_oWheel;
protected ITreadPattern m_xTreadPattern;
protected WheelTread m_oTread;
protected static List<Vector3> m_aFullUpperHeightPoints = new ();
protected static List<Vector3> m_aFullLowerHeightPoints = new ();
protected static Frames m_aUpperHeightFrames;
protected static Frames m_aLowerHeightFrames;
protected static Frames m_aInnerRadiusFrames;
protected static Frames m_aOuterRadiusFrames;
/// <summary>
/// Constructs the final wheel by combining elements, layers and the outer tread.
/// </summary>
public abstract Voxels voxConstruct();
/// <summary>
/// Returns the specified wheel layer as a voxelfield.
/// The layer is defined as a wheel layer struct.
/// </summary>
public static Voxels voxGetLayer(WheelLayer sLayer)
{
return voxGetLayer(sLayer.m_fStartLengthRatio, sLayer.m_fEndLengthRatio);
}
/// <summary>
/// Returns the specified wheel layer as a voxelfield.
/// The layer is defined via its start and end radius ratio within the wheel.
/// </summary>
protected static Voxels voxGetLayer(float fStartLengthRatio, float fEndLengthRatio)
{
float fRefInnerRadius = m_fHubRadius + fStartLengthRatio * (m_fOuterRadius - m_fHubRadius);
float fRefOuterRadius = m_fHubRadius + fEndLengthRatio * (m_fOuterRadius - m_fHubRadius);
BasePipe oLayer = new BasePipe(new LocalFrame(), m_fRefWidth, fRefInnerRadius, fRefOuterRadius);
oLayer.SetLengthSteps(100);
oLayer.SetRadialSteps(100);
oLayer.SetPolarSteps(100);
oLayer.SetTransformation(vecGetWheelLayerTrafo);
//oLayer.SetTransformation(vecGetDummyTrafo);
Voxels voxLayer = oLayer.voxConstruct();
Sh.PreviewVoxels(voxLayer, Cp.clrRandom((int)(fStartLengthRatio * 100)), 0.6f);
return voxLayer;
}
/// <summary>
/// Provides the coordinate transformation that translate from a simple cylindrical space to the curved wheel space.
/// </summary>
public static Vector3 vecGetWheelLayerTrafo(Vector3 vecPt)
{
float fRadius = VecOperations.fGetRadius(vecPt);
float fPhi = VecOperations.fGetPhi(vecPt);
float fHeightRatio = vecPt.Z / m_fRefWidth;
float fLengthRatio = (fRadius - m_fHubRadius) / (m_fOuterRadius - m_fHubRadius);
Vector3 vecNewPt = vecGetInnerPt(fHeightRatio, fLengthRatio);
vecNewPt = VecOperations.vecRotateAroundZ(vecNewPt, fPhi);
return vecNewPt;
}
/// <summary>
/// Provides a dummy coordinate transformation that (when applied to the wheel) showcases the simple cylindrical design space.
/// It does not deform the design space, it just shifts it along the z-axis to be compatible with the actual wheel trafo.
/// </summary>
public static Vector3 vecGetDummyTrafo(Vector3 vecPt)
{
return vecPt - 0.5f * m_fRefWidth * Vector3.UnitZ;
}
/// <summary>
/// Helper function to visualize a 2D slice of the wheel coordinate space.
/// </summary>
protected void ShowPlaneGrid()
{
uint nSamples = 100;
for (float fLengthRatio = 0; fLengthRatio <= 1f; fLengthRatio += 0.1f)
{
List<Vector3> aPoints = new List<Vector3>();
for (int i = 0; i < nSamples; i++)
{
float fHeightRatio = 1f / (float)(nSamples - 1) * i;
Vector3 vecPt = vecGetInnerPt(fHeightRatio, fLengthRatio);
aPoints.Add(vecPt);
}
Sh.PreviewLine(aPoints, Cp.clrRock);
}
for (float fHeightRatio = 0; fHeightRatio <= 1f; fHeightRatio += 0.1f)
{
List<Vector3> aPoints = new List<Vector3>();
for (int i = 0; i < nSamples; i++)
{
float fLengthRatio = 1f / (float)(nSamples - 1) * i;
Vector3 vecPt = vecGetInnerPt(fHeightRatio, fLengthRatio);
aPoints.Add(vecPt);
}
Sh.PreviewLine(aPoints, Cp.clrRock);
}
}
/// <summary>
/// Helper function to navigate within wheel coordinate space and
/// address (conformal) points within the wheel's bounding shape.
/// </summary>
static Vector3 vecGetInnerPt(float fHeightRatio, float fLengthRatio)
{
Vector3 vecUpper = m_aUpperHeightFrames.vecGetSpineAlongLength(fLengthRatio);
Vector3 vecLower = m_aLowerHeightFrames.vecGetSpineAlongLength(fLengthRatio);
Vector3 vecOuter = m_aOuterRadiusFrames.vecGetSpineAlongLength(fHeightRatio);
Vector3 vecInner = m_aInnerRadiusFrames.vecGetSpineAlongLength(fHeightRatio);
Vector3 vecInnerRef = m_aInnerRadiusFrames.vecGetSpineAlongLength(0) + fHeightRatio * (m_aInnerRadiusFrames.vecGetSpineAlongLength(1) - m_aInnerRadiusFrames.vecGetSpineAlongLength(0));
Vector3 vecOuterRef = m_aOuterRadiusFrames.vecGetSpineAlongLength(0) + fHeightRatio * (m_aOuterRadiusFrames.vecGetSpineAlongLength(1) - m_aOuterRadiusFrames.vecGetSpineAlongLength(0));
Vector3 vecDInner = vecInner - vecInnerRef;
Vector3 vecDOuter = vecOuter - vecOuterRef;
Vector3 vecD = vecDInner + fLengthRatio * (vecDOuter - vecDInner);
Vector3 vecRef = vecLower + fHeightRatio * (vecUpper - vecLower);
Vector3 vecPt = vecRef + vecD;
return vecPt;
}
/// <summary>
/// Splits the upper and lower modulated surface of the wheel into 2D contours.
/// The upper contour runs along the top, radially outwards until the outer tread starts.
/// The outer tread contour covers the most radially outwards portion.
/// The lower contour runs along the bottom, radially outwards untul the outer tread starts.
/// The contour point at which the tread starts and ends is defined as where the local contour switches
/// from being more aligned with the radial direction to being more aligned with the axial direction.
/// </summary>
protected void SetOuterPoints()
{
// prep upper and lower contour
List<Vector3> aUpperWheelContour = new List<Vector3>();
foreach (Vector3 vecPt in m_aFullUpperHeightPoints.GetRange(0, m_aFullUpperHeightPoints.Count - 2))
{
float fNewZ = vecPt.X;
float fNewY = 0f;
float fNewX = vecPt.Z * (m_fOuterRadius - m_fHubRadius) + m_fHubRadius;
Vector3 vecNewPt = new Vector3(fNewX, fNewY, fNewZ);
aUpperWheelContour.Add(vecNewPt);
}
aUpperWheelContour = SplineOperations.aGetReparametrizedSpline(aUpperWheelContour, 1f);
List<Vector3> aLowerWheelContour = new List<Vector3>();
foreach (Vector3 vecPt in m_aFullLowerHeightPoints.GetRange(0, m_aFullLowerHeightPoints.Count - 2))
{
float fNewZ = vecPt.X;
float fNewY = 0f;
float fNewX = vecPt.Z * (m_fOuterRadius - m_fHubRadius) + m_fHubRadius;
Vector3 vecNewPt = new Vector3(fNewX, fNewY, fNewZ);
aLowerWheelContour.Add(vecNewPt);
}
aLowerWheelContour = SplineOperations.aGetReparametrizedSpline(aLowerWheelContour, 1f);
// filter for orientation
Vector3 vecTread = Vector3.UnitZ;
Vector3 vecRim = Vector3.UnitX;
List<Vector3> aOuterRadiusPoints = new List<Vector3>();
List<Vector3> aUpperHeightPoints = new List<Vector3>();
List<Vector3> aLowerHeightPoints = new List<Vector3>();
bool bTread = false;
for (int i = 1; i < aUpperWheelContour.Count - 1; i++)
{
Vector3 vecPt = aUpperWheelContour[i];
Vector3 vecContour = (aUpperWheelContour[i - 1] - aUpperWheelContour[i + 1]).Normalize();
float fRimAlign = MathF.Abs(Vector3.Dot(vecContour, vecRim));
float fTreadAlign = MathF.Abs(Vector3.Dot(vecContour, vecTread));
if (fTreadAlign > fRimAlign)
{
bTread = true;
}
if (bTread == true)
{
aOuterRadiusPoints.Add(vecPt);
}
else
{
aUpperHeightPoints.Add(vecPt);
}
}
int iCounter = 0;
for (int i = aLowerWheelContour.Count - 2; i > 0; i--)
{
Vector3 vecPt = aLowerWheelContour[i];
Vector3 vecContour = (aLowerWheelContour[i + 1] - aLowerWheelContour[i - 1]).Normalize();
float fRimAlign = MathF.Abs(Vector3.Dot(vecContour, vecRim));
float fTreadAlign = MathF.Abs(Vector3.Dot(vecContour, vecTread));
if (iCounter > 20 && fTreadAlign < fRimAlign)
{
bTread = false;
}
if (bTread == true)
{
aOuterRadiusPoints.Add(vecPt);
}
else
{
aLowerHeightPoints.Insert(0, vecPt);
}
iCounter++;
}
aLowerHeightPoints = SplineOperations.aGetReparametrizedSpline(aLowerHeightPoints, 1f);
aUpperHeightPoints = SplineOperations.aGetReparametrizedSpline(aUpperHeightPoints, 1f);
aOuterRadiusPoints = SplineOperations.aGetReparametrizedSpline(aOuterRadiusPoints, 1f);
Sh.PreviewLattice(Sh.latFromPoint(aOuterRadiusPoints[0], 3f), Cp.clrRed);
Sh.PreviewLattice(Sh.latFromPoint(aOuterRadiusPoints[^1], 3f), Cp.clrRed);
Sh.PreviewLattice(Sh.latFromLine(aOuterRadiusPoints, 1f), Cp.clrRed);
Sh.PreviewLattice(Sh.latFromLine(aUpperHeightPoints, 1f), Cp.clrBlack);
Sh.PreviewLattice(Sh.latFromLine(aLowerHeightPoints, 1f), Cp.clrBlack);
m_aOuterRadiusFrames = new Frames(aOuterRadiusPoints, Frames.EFrameType.MIN_ROTATION);
m_aUpperHeightFrames = new Frames(aUpperHeightPoints, Frames.EFrameType.MIN_ROTATION);
m_aLowerHeightFrames = new Frames(aLowerHeightPoints, Frames.EFrameType.MIN_ROTATION);
}
/// <summary>
/// Creates points of the inner, radial contour which is the wheel hub with a constant radius.
/// </summary>
protected void SetInnerRadiusPoints()
{
uint nSamples = 100;
List<Vector3> aInnerRadiusPoints = new List<Vector3>();
for (int i = 0; i < nSamples; i++)
{
float fHeightRatio = 1f / (float)(nSamples - 1) * i;
Vector3 vecPt = m_oWheel.vecGetSurfacePoint(fHeightRatio, 0f, 0f);
aInnerRadiusPoints.Add(vecPt);
}
Sh.PreviewLattice(Sh.latFromPoint(aInnerRadiusPoints[0], 3f), Cp.clrRuby);
Sh.PreviewLattice(Sh.latFromPoint(aInnerRadiusPoints[^1], 3f), Cp.clrRuby);
Sh.PreviewLattice(Sh.latFromLine(aInnerRadiusPoints, 1f), Cp.clrRuby);
m_aInnerRadiusFrames = new Frames(aInnerRadiusPoints, Frames.EFrameType.MIN_ROTATION);
}
/// <summary>
/// Creates the points for modulating the upper surface of the wheel bounding body.
/// </summary>
protected abstract List<Vector3> aGetFullUpperHeightPoints();
/// <summary>
/// Creates the points for modulating the lower surface of the wheel bounding body.
/// In this case, the function just mirrors the upper modulation at the z-plane.
/// </summary>
protected List<Vector3> aGetFullLowerHeightPoints()
{
List<Vector3> aUpperHeightPoints = aGetFullUpperHeightPoints();
List<Vector3> aLowerHeightPoints = new List<Vector3>();
foreach(Vector3 vecUpper in aUpperHeightPoints)
{
Vector3 vecLower = new Vector3(-vecUpper.X, vecUpper.Y, vecUpper.Z);
aLowerHeightPoints.Add(vecLower);
}
return aLowerHeightPoints;
}
/// <summary>
/// Creates a surface modulation from points.
/// </summary>
protected SurfaceModulation oGetWidthModulation(List<Vector3> aPoints)
{
SurfaceModulation oSurfMod = new (new LineModulation(aPoints, LineModulation.ECoord.X, LineModulation.ECoord.Z));
return oSurfMod;
}
}
}
} | 1 | 0.783501 | 1 | 0.783501 | game-dev | MEDIA | 0.782675 | game-dev,graphics-rendering | 0.960043 | 1 | 0.960043 |
klebs6/aloe-rs | 4,476 | aloe-box2d/src/verticalstack.rs | crate::ix!();
//-------------------------------------------[.cpp/Aloe/examples/Assets/Box2DTests/VerticalStack.h]
pub const VERTICAL_STACK_E_COLUMNCOUNT: usize = 5;
pub const VERTICAL_STACK_E_ROWCOUNT: usize = 16;
pub struct VerticalStack {
base: Test,
bullet: *mut b2Body,
bodies: *mut [b2Body; VERTICAL_STACK_E_ROWCOUNT * VERTICAL_STACK_E_COLUMNCOUNT],
indices: [i32; VERTICAL_STACK_E_ROWCOUNT * VERTICAL_STACK_E_COLUMNCOUNT],
}
impl Default for VerticalStack {
fn default() -> Self {
todo!();
/*
{
b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
ground->CreateFixture(&shape, 0.0f);
shape.Set(b2Vec2(20.0f, 0.0f), b2Vec2(20.0f, 20.0f));
ground->CreateFixture(&shape, 0.0f);
}
float32 xs[5] = {0.0f, -10.0f, -5.0f, 5.0f, 10.0f};
for (int32 j = 0; j < VERTICAL_STACK_E_COLUMNCOUNT; ++j)
{
b2PolygonShape shape;
shape.SetAsBox(0.5f, 0.5f);
b2FixtureDef fd;
fd.shape = &shape;
fd.density = 1.0f;
fd.friction = 0.3f;
for (int i = 0; i < VERTICAL_STACK_E_ROWCOUNT; ++i)
{
b2BodyDef bd;
bd.type = b2_dynamicBody;
int32 n = j * VERTICAL_STACK_E_ROWCOUNT + i;
b2Assert(n < VERTICAL_STACK_E_ROWCOUNT * VERTICAL_STACK_E_COLUMNCOUNT);
m_indices[n] = n;
bd.userData = m_indices + n;
float32 x = 0.0f;
//float32 x = RandomFloat(-0.02f, 0.02f);
//float32 x = i % 2 == 0 ? -0.025f : 0.025f;
bd.position.Set(xs[j] + x, 0.752f + 1.54f * i);
b2Body* body = m_world->CreateBody(&bd);
m_bodies[n] = body;
body->CreateFixture(&fd);
}
}
m_bullet = NULL
*/
}
}
impl VerticalStack {
pub fn keyboard(&mut self, key: u8) {
todo!();
/*
switch (key)
{
case ',':
if (m_bullet != NULL)
{
m_world->DestroyBody(m_bullet);
m_bullet = NULL;
}
{
b2CircleShape shape;
shape.m_radius = 0.25f;
b2FixtureDef fd;
fd.shape = &shape;
fd.density = 20.0f;
fd.restitution = 0.05f;
b2BodyDef bd;
bd.type = b2_dynamicBody;
bd.bullet = true;
bd.position.Set(-31.0f, 5.0f);
m_bullet = m_world->CreateBody(&bd);
m_bullet->CreateFixture(&fd);
m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f));
}
break;
}
*/
}
pub fn step(&mut self, settings: *mut Settings) {
todo!();
/*
Test::Step(settings);
m_debugDraw.DrawString(5, m_textLine, "Press: (,) to launch a bullet.");
m_textLine += 15;
//if (m_stepCount == 300)
//{
// if (m_bullet != NULL)
// {
// m_world->DestroyBody(m_bullet);
// m_bullet = NULL;
// }
// {
// b2CircleShape shape;
// shape.m_radius = 0.25f;
// b2FixtureDef fd;
// fd.shape = &shape;
// fd.density = 20.0f;
// fd.restitution = 0.05f;
// b2BodyDef bd;
// bd.type = b2_dynamicBody;
// bd.bullet = true;
// bd.position.Set(-31.0f, 5.0f);
// m_bullet = m_world->CreateBody(&bd);
// m_bullet->CreateFixture(&fd);
// m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f));
// }
//}
*/
}
pub fn create() -> *mut Test {
todo!();
/*
return new VerticalStack;
*/
}
}
| 1 | 0.864047 | 1 | 0.864047 | game-dev | MEDIA | 0.970902 | game-dev | 0.664244 | 1 | 0.664244 |
hiredman/gologic | 3,221 | examples/island.go | //http://brownbuffalo.sourceforge.net/FourIslandsClues.html
package main
import "fmt"
import l "gologic"
type Island struct {
Location,Name,Export,Attraction interface{}
}
type Nation struct {
C1,C2,C3,C4 interface{}
}
func v () l.V {
return l.Fresh()
}
func n (a,b,c,d interface{}) interface{} {
return Nation{a,b,c,d}
}
const (
North_of int = iota
East_of
)
var db l.DB = l.Db()
func north_south_bridge(a,b interface{}) l.Goal {
return l.Or(
db.Deref().Find(a,North_of,b),
db.Deref().Find(b,North_of,a))
}
func west_east_bridge(a,b interface{}) l.Goal {
return l.Or(
db.Deref().Find(a,East_of,b),
db.Deref().Find(b,East_of,a))
}
func disconnected(a,b interface{}) l.Goal {
x,y := l.Fresh2()
return l.And(
north_south_bridge(a,x),
l.Neq(x,b),
west_east_bridge(a,y),
l.Neq(y,b))
}
func north_of(a,b interface{}) l.Goal {
return db.Deref().Find(a,North_of,b)
}
func east_of(a,b interface{}) l.Goal {
return db.Deref().Find(a,East_of,b)
}
func islando (q l.V) l.Goal {
db.Assert("A",North_of,"C")
db.Assert("B",North_of,"D")
db.Assert("D",East_of,"C")
db.Assert("B",East_of,"A")
membero := l.StructMemberoConstructor4(n)
alabaster_island,durian_island,banana_island := l.Fresh3()
pwana_island,quero_island,skern_island,rayou_island := l.Fresh4()
hotel_island,koala_island,jai_island,skating_island := l.Fresh4()
return l.And(
l.Unify(Nation{Island{"A",v(),v(),v()},Island{"B",v(),v(),v()},Island{"C",v(),v(),v()},Island{"D",v(),v(),v()}},q),
// 1
north_of(pwana_island,koala_island),
//2
east_of(quero_island,alabaster_island),
//3
east_of(hotel_island,durian_island),
//4
north_south_bridge(skern_island,jai_island),
//5
west_east_bridge(rayou_island,banana_island),
//6
disconnected(skating_island,jai_island),
//
membero(Island{pwana_island,"Pwana",v(),v()},q),
membero(Island{quero_island,"Quero",v(),v()},q),
membero(Island{rayou_island,"Rayou",v(),v()},q),
membero(Island{skern_island,"Skern",v(),v()},q),
//
membero(Island{alabaster_island,v(),"alabaster",v()},q),
membero(Island{banana_island,v(),"bananas",v()},q),
membero(Island{v(),v(),"coconuts",v()},q),
membero(Island{durian_island,v(),"durian fruit",v()},q),
//
membero(Island{hotel_island,v(),v(),"hotel"},q),
membero(Island{skating_island,v(),v(),"ice skating rink"},q),
membero(Island{jai_island,v(),v(),"jai alai stadium"},q),
membero(Island{koala_island,v(),v(),"koala preserve"},q),
)
}
func main() {
q := l.Fresh()
c := l.Run(q,islando(q))
for n := 0 ; n < 10 ; n++ {
i := <- c
if i != nil {
fmt.Println(i)
} else {
break
}
}
}
| 1 | 0.587146 | 1 | 0.587146 | game-dev | MEDIA | 0.389545 | game-dev | 0.847735 | 1 | 0.847735 |
katalash/DSMapStudio | 1,060 | HKX2/Autogen/hkbRotateCharacterModifier.cs | using SoulsFormats;
using System.Collections.Generic;
using System.Numerics;
namespace HKX2
{
public partial class hkbRotateCharacterModifier : hkbModifier
{
public override uint Signature { get => 2166830607; }
public float m_degreesPerSecond;
public float m_speedMultiplier;
public Vector4 m_axisOfRotation;
public override void Read(PackFileDeserializer des, BinaryReaderEx br)
{
base.Read(des, br);
m_degreesPerSecond = br.ReadSingle();
m_speedMultiplier = br.ReadSingle();
m_axisOfRotation = des.ReadVector4(br);
br.ReadUInt64();
br.ReadUInt64();
}
public override void Write(PackFileSerializer s, BinaryWriterEx bw)
{
base.Write(s, bw);
bw.WriteSingle(m_degreesPerSecond);
bw.WriteSingle(m_speedMultiplier);
s.WriteVector4(bw, m_axisOfRotation);
bw.WriteUInt64(0);
bw.WriteUInt64(0);
}
}
}
| 1 | 0.939021 | 1 | 0.939021 | game-dev | MEDIA | 0.45101 | game-dev | 0.843343 | 1 | 0.843343 |
KeenSoftwareHouse/Miner-Wars-2081 | 4,872 | Sources/MinerWars.GameLib/AppCode/Game/Prefabs/MyPrefabKinematicRotating.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MinerWars.AppCode.Game.Managers.EntityManager.Entities;
using MinerWars.CommonLIB.AppCode.ObjectBuilders.SubObjects;
using MinerWars.AppCode.Physics;
using MinerWars.AppCode.Game.Models;
using MinerWars.AppCode.Game.Utils;
using MinerWars.AppCode.Game.Managers.PhysicsManager.Physics;
using MinerWarsCustomContentImporters;
namespace MinerWars.AppCode.Game.Prefabs
{
class MyPrefabKinematicRotating : MyPrefabBase
{
private List<MyPrefabKinematicRotatingPart> m_parts;
//private bool m_on;
//public bool On
//{
// get { return m_on; }
// set
// {
// m_on = value;
// foreach (MyPrefabKinematicRotatingPart part in m_parts)
// {
// part.On = value;
// }
// }
//}
protected override void EnabledChanged()
{
base.EnabledChanged();
foreach (MyPrefabKinematicRotatingPart part in m_parts)
{
part.On = Enabled;
}
}
public MyPrefabKinematicRotating(MyPrefabContainer owner)
: base(owner)
{
m_parts = new List<MyPrefabKinematicRotatingPart>();
}
public override void Init(string displayName, Microsoft.Xna.Framework.Vector3 relativePosition, Microsoft.Xna.Framework.Matrix localOrientation, MyMwcObjectBuilder_PrefabBase objectBuilder, MyPrefabConfiguration prefabConfig)
{
m_config = prefabConfig;
MyPrefabConfigurationKinematicRotating config = (MyPrefabConfigurationKinematicRotating)prefabConfig;
base.Init(displayName, relativePosition, localOrientation, objectBuilder, prefabConfig);
Physics.RemoveAllElements();
// create the box
MyPhysicsObjects physobj = MyPhysics.physicsSystem.GetPhysicsObjects();
MyRBTriangleMeshElementDesc trianglemeshDesc = physobj.GetRBTriangleMeshElementDesc();
trianglemeshDesc.SetToDefault();
trianglemeshDesc.m_Model = ModelLod0;
trianglemeshDesc.m_RBMaterial = MyMaterialsConstants.GetMaterialProperties(config.MaterialType).PhysicsMaterial; ;
MyRBTriangleMeshElement trEl = (MyRBTriangleMeshElement)physobj.CreateRBElement(trianglemeshDesc);
this.Physics = new MyPhysicsBody(this, 1.0f, RigidBodyFlag.RBF_RBO_STATIC) { MaterialType = config.MaterialType };
this.Physics.Enabled = true;
this.Physics.CollisionLayer = MyConstants.COLLISION_LAYER_PREFAB_KINEMATIC;
this.Physics.AddElement(trEl, true);
MyModel model = MyModels.GetModelOnlyDummies(m_config.ModelLod0Enum);
foreach (var dummyKVP in model.Dummies)
{
if (dummyKVP.Key.StartsWith("Dummy"))
{
MyModelDummy dummy = dummyKVP.Value;
MyModelsEnum rotatingPartModel = MyModels.GetModelEnumByAssetName(dummy.CustomData["LINKEDMODEL"].ToString());
MyPrefabKinematicRotatingPart rotatingPart = new MyPrefabKinematicRotatingPart(this.GetOwner());
rotatingPart.Init(this, rotatingPartModel, config.MaterialType, dummy.Matrix, config.RotatingVelocity, true, config.SoundLooping, config.SoundOpening, config.SoundClosing);
m_parts.Add(rotatingPart);
}
}
AppCode.Physics.MyPhysics.physicsSystem.GetRigidBodyModule().EnableCollisionInLayers(MyConstants.COLLISION_LAYER_PREFAB_KINEMATIC, MyConstants.COLLISION_LAYER_MISSILE, true);
AppCode.Physics.MyPhysics.physicsSystem.GetRigidBodyModule().EnableCollisionInLayers(MyConstants.COLLISION_LAYER_PREFAB_KINEMATIC, MyConstants.COLLISION_LAYER_ALL, true);
AppCode.Physics.MyPhysics.physicsSystem.GetRigidBodyModule().EnableCollisionInLayers(MyConstants.COLLISION_LAYER_PREFAB_KINEMATIC, MyConstants.COLLISION_LAYER_MODEL_DEBRIS, true);
AppCode.Physics.MyPhysics.physicsSystem.GetRigidBodyModule().EnableCollisionInLayers(MyConstants.COLLISION_LAYER_PREFAB_KINEMATIC, MyConstants.COLLISION_LAYER_VOXEL_DEBRIS, true);
AppCode.Physics.MyPhysics.physicsSystem.GetRigidBodyModule().EnableCollisionInLayers(MyConstants.COLLISION_LAYER_PREFAB_KINEMATIC, MyConstants.COLLISION_LAYER_PREFAB_KINEMATIC_PART, false);
NeedsUpdate = false;
EnabledChanged();
//Enabled = true;
}
public void RemovePart(MyPrefabKinematicRotatingPart part)
{
m_parts.Remove(part);
}
}
}
| 1 | 0.516626 | 1 | 0.516626 | game-dev | MEDIA | 0.978704 | game-dev | 0.818562 | 1 | 0.818562 |
dartsim/dart | 4,023 | examples/deprecated_examples/glut_atlas_simbicon/TerminalCondition.cpp | /*
* Copyright (c) 2011-2025, The DART development contributors
* All rights reserved.
*
* The list of contributors can be found at:
* https://github.com/dartsim/dart/blob/main/LICENSE
*
* This file is provided under the following "BSD-style" License:
* 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.
* 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.
*/
#include "TerminalCondition.hpp"
#include "State.hpp"
// Macro for functions not implemented yet
#define NOT_YET(FUNCTION) \
std::cout << #FUNCTION << "Not implemented yet." << std::endl;
using namespace std;
using namespace dart::dynamics;
using namespace dart::constraint;
//==============================================================================
TerminalCondition::TerminalCondition(State* _state) : mState(_state)
{
assert(_state != nullptr);
}
//==============================================================================
TerminalCondition::~TerminalCondition() {}
//==============================================================================
TimerCondition::TimerCondition(State* _state, double _duration)
: TerminalCondition(_state), mDuration(_duration)
{
}
//==============================================================================
TimerCondition::~TimerCondition() {}
//==============================================================================
bool TimerCondition::isSatisfied()
{
if (mState->getElapsedTime() > mDuration)
return true;
else
return false;
}
//==============================================================================
BodyContactCondition::BodyContactCondition(State* _state, BodyNode* _body)
: TerminalCondition(_state), mBodyNode(_body)
{
assert(_state != nullptr);
assert(_body != nullptr);
}
//==============================================================================
BodyContactCondition::~BodyContactCondition() {}
//==============================================================================
bool BodyContactCondition::isSatisfied()
{
SoftBodyNode* soft = dynamic_cast<SoftBodyNode*>(mBodyNode);
if (soft) {
for (std::size_t i = 0; i < soft->getNumPointMasses(); ++i) {
PointMass* pm = soft->getPointMass(i);
if (pm->isColliding())
return true;
}
}
// TODO(JS): Need more elegant condition check method
DART_SUPPRESS_DEPRECATED_BEGIN
if (mBodyNode->isColliding())
DART_SUPPRESS_DEPRECATED_END
{
// dtmsg << "BodyNode [" << mBodyNode->getName() << "] is in contact."
// << std::endl;
return true;
}
else {
// dtmsg << "Waiting for BodyNode [" << mBodyNode->getName()
// << "] is in contact."
// << std::endl;
return false;
}
}
| 1 | 0.888985 | 1 | 0.888985 | game-dev | MEDIA | 0.405288 | game-dev | 0.790485 | 1 | 0.790485 |
CloudburstMC/Nukkit | 4,691 | src/main/java/cn/nukkit/block/BlockObserver.java | package cn.nukkit.block;
import cn.nukkit.Player;
import cn.nukkit.event.redstone.RedstoneUpdateEvent;
import cn.nukkit.item.Item;
import cn.nukkit.item.ItemBlock;
import cn.nukkit.item.ItemTool;
import cn.nukkit.level.Level;
import cn.nukkit.math.BlockFace;
import cn.nukkit.math.Vector3;
import cn.nukkit.utils.Faceable;
public class BlockObserver extends BlockSolidMeta implements Faceable {
/**
* Where the block update happens. Used to check whether this observer should detect it.
*/
private Vector3 updatePos;
public BlockObserver() {
this(0);
}
public BlockObserver(int meta) {
super(meta);
}
@Override
public int getId() {
return OBSERVER;
}
@Override
public String getName() {
return "Observer";
}
@Override
public double getHardness() {
return 3.5;
}
@Override
public double getResistance() {
return 17.5;
}
@Override
public int getToolType() {
return ItemTool.TYPE_PICKAXE;
}
@Override
public Item[] getDrops(Item item) {
if (item.isPickaxe()) {
return new Item[]{
Item.get(Item.OBSERVER, 0, 1)
};
} else {
return new Item[0];
}
}
@Override
public boolean canHarvestWithHand() {
return false;
}
@Override
public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) {
if (player != null) {
if (Math.abs(player.x - this.x) < 2 && Math.abs(player.z - this.z) < 2) {
double y = player.y + player.getEyeHeight();
if (y - this.y > 2) {
this.setDamage(BlockFace.DOWN.getIndex());
} else if (this.y - y > 0) {
this.setDamage(BlockFace.UP.getIndex());
} else {
this.setDamage(player.getHorizontalFacing().getIndex());
}
} else {
this.setDamage(player.getHorizontalFacing().getIndex());
}
}
return this.getLevel().setBlock(this, this, true, true);
}
@Override
public BlockFace getBlockFace() {
return BlockFace.fromIndex(this.getDamage() & 0x07);
}
@Override
public int onUpdate(int type) {
if (type == Level.BLOCK_UPDATE_NORMAL && this.getSideVec(this.getBlockFace()).equals(this.updatePos) && !this.isPowered()) {
// Make sure the block still exists to prevent item duplication
if (this.level.getBlockIdAt((int) this.x, (int) this.y, (int) this.z) != this.getId()) {
return 0;
}
RedstoneUpdateEvent ev = new RedstoneUpdateEvent(this);
this.level.getServer().getPluginManager().callEvent(ev);
if (ev.isCancelled()) {
return 0;
}
this.setPowered(true);
this.level.setBlock(this, this, false, false);
this.level.updateAroundRedstone(this, this.getBlockFace());
level.scheduleUpdate(this, 4);
return Level.BLOCK_UPDATE_NORMAL;
} else if (type == Level.BLOCK_UPDATE_SCHEDULED && this.isPowered()) {
// Make sure the block still exists to prevent item duplication
if (this.level.getBlockIdAt((int) this.x, (int) this.y, (int) this.z) != this.getId()) {
return 0;
}
RedstoneUpdateEvent ev = new RedstoneUpdateEvent(this);
this.level.getServer().getPluginManager().callEvent(ev);
if (ev.isCancelled()) {
return 0;
}
this.setPowered(false);
this.level.setBlock(this, this, false, false);
this.level.updateAroundRedstone(this, this.getBlockFace());
}
return type;
}
@Override
public Item toItem() {
return new ItemBlock(Block.get(Block.OBSERVER));
}
@Override
public boolean isPowerSource() {
return true;
}
@Override
public int getStrongPower(BlockFace side) {
return this.isPowered() && side == this.getBlockFace() ? 15 : 0;
}
@Override
public int getWeakPower(BlockFace face) {
return this.getStrongPower(face);
}
public boolean isPowered() {
return (this.getDamage() & 0x8) == 0x8;
}
public void setPowered(boolean powered) {
this.setDamage((this.getDamage() & 0x7) | (powered ? 0x8 : 0x0));
}
@Override
public Block setUpdatePos(Vector3 pos) {
this.updatePos = pos;
return this;
}
}
| 1 | 0.921648 | 1 | 0.921648 | game-dev | MEDIA | 0.98519 | game-dev | 0.96761 | 1 | 0.96761 |
project-flogo/flogo-web | 1,308 | apps/client/src/flogo/app/resource-views/resources/resource-list.component.ts | import {
Component,
Input,
Output,
EventEmitter,
ChangeDetectionStrategy,
} from '@angular/core';
import { ResourceWithPlugin } from '../../core/resource-with-plugin';
@Component({
selector: 'flogo-apps-resource-list',
template: `
<flogo-apps-resource
class="resource qa-resource"
*ngFor="let resource of resources; trackBy: trackByResourceId"
[resource]="resource"
(resourceSelected)="resourceSelected.emit($event)"
(deleteResource)="deleteResource.emit($event)"
></flogo-apps-resource>
`,
styles: [
`
.resource + .resource {
border-top: none;
}
.resource:not(:first-of-type) {
border-top-right-radius: 0;
border-top-left-radius: 0;
}
.resource:not(:last-of-type) {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
`,
],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ResourceListComponent {
@Input()
public resources: Array<ResourceWithPlugin> = [];
@Output()
public resourceSelected = new EventEmitter<ResourceWithPlugin>();
@Output()
public deleteResource = new EventEmitter<ResourceWithPlugin>();
trackByResourceId(index: number, resource: ResourceWithPlugin) {
return resource ? resource.id : null;
}
}
| 1 | 0.883396 | 1 | 0.883396 | game-dev | MEDIA | 0.599606 | game-dev | 0.935599 | 1 | 0.935599 |
s0bvi/goldsvet-opensource | 41,536 | casino/app/Games/SongCaiTongZiSW/SlotSettings.php | <?php
namespace VanguardLTE\Games\SongCaiTongZiSW
{
class SlotSettings
{
public $playerId = null;
public $splitScreen = null;
public $reelStrip1 = null;
public $reelStrip2 = null;
public $reelStrip3 = null;
public $reelStrip4 = null;
public $reelStrip5 = null;
public $reelStrip6 = null;
public $reelStripBonus1 = null;
public $reelStripBonus2 = null;
public $reelStripBonus3 = null;
public $reelStripBonus4 = null;
public $reelStripBonus5 = null;
public $reelStripBonus6 = null;
public $slotId = '';
public $slotDBId = '';
public $Line = null;
public $scaleMode = null;
public $numFloat = null;
public $gameLine = null;
public $Bet = null;
public $isBonusStart = null;
public $Balance = null;
public $SymbolGame = null;
public $GambleType = null;
public $Jackpots = [];
public $keyController = null;
public $slotViewState = null;
public $hideButtons = null;
public $slotReelsConfig = null;
public $slotFreeCount = null;
public $slotFreeMpl = null;
public $slotWildMpl = null;
public $slotExitUrl = null;
public $slotBonus = null;
public $slotBonusType = null;
public $slotScatterType = null;
public $slotGamble = null;
public $Paytable = [];
public $slotSounds = [];
private $jpgs = null;
private $Bank = null;
private $Percent = null;
private $WinLine = null;
private $WinGamble = null;
private $Bonus = null;
private $shop_id = null;
public $currency = null;
public $user = null;
public $game = null;
public $shop = null;
public $jpgPercentZero = false;
public $count_balance = null;
public function __construct($sid, $playerId)
{
$this->slotId = $sid;
$this->playerId = $playerId;
$user = \VanguardLTE\User::lockForUpdate()->find($this->playerId);
$this->user = $user;
$this->shop_id = $user->shop_id;
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $this->shop_id])->lockForUpdate()->get();
$game = \VanguardLTE\Game::where([
'name' => $this->slotId,
'shop_id' => $this->shop_id
])->lockForUpdate()->first();
$this->shop = \VanguardLTE\Shop::find($this->shop_id);
$this->game = $game;
$this->MaxWin = $this->shop->max_win;
$this->increaseRTP = 1;
$this->CurrentDenom = $this->game->denomination;
$this->scaleMode = 0;
$this->numFloat = 0;
$this->Paytable[0] = [
0,
0,
0,
0,
0,
0
];
$this->Paytable[1] = [
0,
2,
10,
50,
500,
10000
];
$this->Paytable[2] = [
0,
0,
5,
25,
250,
5000
];
$this->Paytable[3] = [
0,
0,
5,
20,
170,
1200
];
$this->Paytable[4] = [
0,
0,
5,
20,
125,
750
];
$this->Paytable[5] = [
0,
0,
2,
10,
50,
350
];
$this->Paytable[6] = [
0,
0,
2,
10,
50,
250
];
$this->Paytable[7] = [
0,
0,
0,
5,
25,
200
];
$this->Paytable[8] = [
0,
0,
0,
5,
25,
200
];
$this->Paytable[9] = [
0,
0,
0,
3,
10,
50
];
$this->Paytable[10] = [
0,
0,
0,
3,
10,
50
];
$this->Paytable[11] = [
0,
0,
1,
5,
10,
100
];
$reel = new GameReel();
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $reelStrip )
{
if( count($reel->reelsStrip[$reelStrip]) )
{
$this->$reelStrip = $reel->reelsStrip[$reelStrip];
}
}
$this->keyController = [
'13' => 'uiButtonSpin,uiButtonSkip',
'49' => 'uiButtonInfo',
'50' => 'uiButtonCollect',
'51' => 'uiButtonExit2',
'52' => 'uiButtonLinesMinus',
'53' => 'uiButtonLinesPlus',
'54' => 'uiButtonBetMinus',
'55' => 'uiButtonBetPlus',
'56' => 'uiButtonGamble',
'57' => 'uiButtonRed',
'48' => 'uiButtonBlack',
'189' => 'uiButtonAuto',
'187' => 'uiButtonSpin'
];
$this->slotReelsConfig = [
[
183,
168,
3
],
[
413,
168,
3
],
[
644,
168,
3
],
[
877,
168,
3
],
[
1115,
168,
3
]
];
$this->slotBonusType = 0;
$this->slotScatterType = 0;
$this->splitScreen = false;
$this->slotBonus = false;
$this->slotGamble = true;
$this->slotFastStop = 1;
$this->slotExitUrl = '/';
$this->slotWildMpl = 2;
$this->GambleType = 1;
$this->slotFreeCount = 15;
$this->slotFreeMpl = 3;
$this->slotViewState = ($game->slotViewState == '' ? 'Normal' : $game->slotViewState);
$this->hideButtons = [];
$this->jpgs = \VanguardLTE\JPG::where('shop_id', $this->shop_id)->lockForUpdate()->get();
$this->Line = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
];
$this->gameLine = [9];
$this->Bet = explode(',', $game->bet);
$this->Balance = $user->balance;
$this->SymbolGame = [
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10',
'11'
];
$this->Bank = $game->get_gamebank();
$this->Percent = $this->shop->percent;
$this->WinGamble = $game->rezerv;
$this->slotDBId = $game->id;
$this->slotCurrency = $user->shop->currency;
$this->count_balance = $user->count_balance;
if( $user->address > 0 && $user->count_balance == 0 )
{
$this->Percent = 0;
$this->jpgPercentZero = true;
}
else if( $user->count_balance == 0 )
{
$this->Percent = 100;
}
if( !isset($this->user->session) || strlen($this->user->session) <= 0 )
{
$this->user->session = serialize([]);
}
$this->gameData = unserialize($this->user->session);
if( count($this->gameData) > 0 )
{
foreach( $this->gameData as $key => $vl )
{
if( $vl['timelife'] <= time() )
{
unset($this->gameData[$key]);
}
}
}
if( !isset($this->game->advanced) || strlen($this->game->advanced) <= 0 )
{
$this->game->advanced = serialize([]);
}
$this->gameDataStatic = unserialize($this->game->advanced);
if( count($this->gameDataStatic) > 0 )
{
foreach( $this->gameDataStatic as $key => $vl )
{
if( $vl['timelife'] <= time() )
{
unset($this->gameDataStatic[$key]);
}
}
}
}
public function is_active()
{
if( $this->game && $this->shop && $this->user && (!$this->game->view || $this->shop->is_blocked || $this->user->is_blocked || $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED) )
{
\VanguardLTE\Session::where('user_id', $this->user->id)->delete();
$this->user->update(['remember_token' => null]);
return false;
}
if( !$this->game->view )
{
return false;
}
if( $this->shop->is_blocked )
{
return false;
}
if( $this->user->is_blocked )
{
return false;
}
if( $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED )
{
return false;
}
return true;
}
public function SetGameData($key, $value)
{
$timeLife = 86400;
$this->gameData[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameData($key)
{
if( isset($this->gameData[$key]) )
{
return $this->gameData[$key]['payload'];
}
else
{
return 0;
}
}
public function FormatFloat($num)
{
$str0 = explode('.', $num);
if( isset($str0[1]) )
{
if( strlen($str0[1]) > 4 )
{
return round($num * 100) / 100;
}
else if( strlen($str0[1]) > 2 )
{
return floor($num * 100) / 100;
}
else
{
return $num;
}
}
else
{
return $num;
}
}
public function SaveGameData()
{
$this->user->session = serialize($this->gameData);
$this->user->save();
}
public function CheckBonusWin()
{
$allRateCnt = 0;
$allRate = 0;
foreach( $this->Paytable as $vl )
{
foreach( $vl as $vl2 )
{
if( $vl2 > 0 )
{
$allRateCnt++;
$allRate += $vl2;
break;
}
}
}
return $allRate / $allRateCnt;
}
public function GetRandomPay()
{
$allRate = [];
foreach( $this->Paytable as $vl )
{
foreach( $vl as $vl2 )
{
if( $vl2 > 0 )
{
$allRate[] = $vl2;
}
}
}
shuffle($allRate);
if( $this->game->stat_in < ($this->game->stat_out + ($allRate[0] * $this->AllBet)) )
{
$allRate[0] = 0;
}
return $allRate[0];
}
public function HasGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return true;
}
else
{
return false;
}
}
public function SaveGameDataStatic()
{
$this->game->advanced = serialize($this->gameDataStatic);
$this->game->save();
$this->game->refresh();
}
public function SetGameDataStatic($key, $value)
{
$timeLife = 86400;
$this->gameDataStatic[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return $this->gameDataStatic[$key]['payload'];
}
else
{
return 0;
}
}
public function HasGameData($key)
{
if( isset($this->gameData[$key]) )
{
return true;
}
else
{
return false;
}
}
public function UpdateJackpots($bet)
{
$bet = $bet * $this->CurrentDenom;
$count_balance = $this->count_balance;
$jsum = [];
$payJack = 0;
for( $i = 0; $i < count($this->jpgs); $i++ )
{
if( $count_balance == 0 || $this->jpgPercentZero )
{
$jsum[$i] = $this->jpgs[$i]->balance;
}
else if( $count_balance < $bet )
{
$jsum[$i] = $count_balance / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance;
}
else
{
$jsum[$i] = $bet / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance;
}
if( $this->jpgs[$i]->get_pay_sum() < $jsum[$i] && $this->jpgs[$i]->get_pay_sum() > 0 )
{
if( $this->jpgs[$i]->user_id && $this->jpgs[$i]->user_id != $this->user->id )
{
}
else
{
$payJack = $this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom;
$jsum[$i] = $jsum[$i] - $this->jpgs[$i]->get_pay_sum();
$this->SetBalance($this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom);
if( $this->jpgs[$i]->get_pay_sum() > 0 )
{
\VanguardLTE\StatGame::create([
'user_id' => $this->playerId,
'balance' => $this->Balance * $this->CurrentDenom,
'bet' => 0,
'win' => $this->jpgs[$i]->get_pay_sum(),
'game' => $this->game->name . ' JPG ' . $this->jpgs[$i]->id,
'in_game' => 0,
'in_jpg' => 0,
'in_profit' => 0,
'shop_id' => $this->shop_id,
'date_time' => \Carbon\Carbon::now()
]);
}
}
$i++;
}
$this->jpgs[$i]->balance = $jsum[$i];
$this->jpgs[$i]->save();
if( $this->jpgs[$i]->balance < $this->jpgs[$i]->get_min('start_balance') )
{
$summ = $this->jpgs[$i]->get_start_balance();
if( $summ > 0 )
{
$this->jpgs[$i]->add_jpg('add', $summ);
}
}
}
if( $payJack > 0 )
{
$payJack = sprintf('%01.2f', $payJack);
$this->Jackpots['jackPay'] = $payJack;
}
}
public function GetBank($slotState = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
$game = $this->game;
$this->Bank = $game->get_gamebank($slotState);
return $this->Bank / $this->CurrentDenom;
}
public function GetPercent()
{
return $this->Percent;
}
public function GetCountBalanceUser()
{
return $this->user->count_balance;
}
public function InternalErrorSilent($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
}
public function InternalError($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
exit( '' );
}
public function SetBank($slotState = '', $sum, $slotEvent = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
if( $this->GetBank($slotState) + $sum < 0 )
{
$this->InternalError('Bank_ ' . $sum . ' CurrentBank_ ' . $this->GetBank($slotState) . ' CurrentState_ ' . $slotState . ' Trigger_ ' . ($this->GetBank($slotState) + $sum));
}
$sum = $sum * $this->CurrentDenom;
$game = $this->game;
$bankBonusSum = 0;
if( $sum > 0 && $slotEvent == 'bet' )
{
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
$this->betProfit = 0;
$prc = $this->GetPercent();
$prc_b = 10;
if( $prc <= $prc_b )
{
$prc_b = 0;
}
$count_balance = $this->count_balance;
$gameBet = $sum / $this->GetPercent() * 100;
if( $count_balance < $gameBet && $count_balance > 0 )
{
$firstBid = $count_balance;
$secondBid = $gameBet - $firstBid;
if( isset($this->betRemains0) )
{
$secondBid = $this->betRemains0;
}
$bankSum = $firstBid / 100 * $this->GetPercent();
$sum = $bankSum + $secondBid;
$bankBonusSum = $firstBid / 100 * $prc_b;
}
else if( $count_balance > 0 )
{
$bankBonusSum = $gameBet / 100 * $prc_b;
}
for( $i = 0; $i < count($this->jpgs); $i++ )
{
if( !$this->jpgPercentZero )
{
if( $count_balance < $gameBet && $count_balance > 0 )
{
$this->toSlotJackBanks += ($count_balance / 100 * $this->jpgs[$i]->percent);
}
else if( $count_balance > 0 )
{
$this->toSlotJackBanks += ($gameBet / 100 * $this->jpgs[$i]->percent);
}
}
}
$this->toGameBanks = $sum;
$this->betProfit = $gameBet - $this->toGameBanks - $this->toSlotJackBanks - $this->toSysJackBanks;
}
if( $sum > 0 )
{
$this->toGameBanks = $sum;
}
if( $bankBonusSum > 0 )
{
$sum -= $bankBonusSum;
$game->set_gamebank($bankBonusSum, 'inc', 'bonus');
}
if( $sum == 0 && $slotEvent == 'bet' && isset($this->betRemains) )
{
$sum = $this->betRemains;
}
$game->set_gamebank($sum, 'inc', $slotState);
$game->save();
return $game;
}
public function SetBalance($sum, $slotEvent = '')
{
if( $this->GetBalance() + $sum < 0 )
{
$this->InternalError('Balance_ ' . $sum);
}
$sum = $sum * $this->CurrentDenom;
if( $sum < 0 && $slotEvent == 'bet' )
{
$user = $this->user;
if( $user->count_balance == 0 )
{
$remains = [];
$this->betRemains = 0;
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$remains[] = $sm - $user->address;
}
for( $i = 0; $i < count($remains); $i++ )
{
if( $this->betRemains < $remains[$i] )
{
$this->betRemains = $remains[$i];
}
}
}
if( $user->count_balance > 0 && $user->count_balance < abs($sum) )
{
$remains0 = [];
$sm = abs($sum);
$tmpSum = $sm - $user->count_balance;
$this->betRemains0 = $tmpSum;
if( $user->address > 0 )
{
$this->betRemains0 = 0;
if( $user->address < $tmpSum && $user->address > 0 )
{
$remains0[] = $tmpSum - $user->address;
}
for( $i = 0; $i < count($remains0); $i++ )
{
if( $this->betRemains0 < $remains0[$i] )
{
$this->betRemains0 = $remains0[$i];
}
}
}
}
$sum0 = abs($sum);
if( $user->count_balance == 0 )
{
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
else if( $user->count_balance > 0 && $user->count_balance < $sum0 )
{
$sm = $sum0 - $user->count_balance;
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
$this->user->count_balance = $this->user->updateCountBalance($sum, $this->count_balance);
$this->user->count_balance = $this->FormatFloat($this->user->count_balance);
}
$this->user->increment('balance', $sum);
$this->user->balance = $this->FormatFloat($this->user->balance);
$this->user->save();
return $this->user;
}
public function GetBalance()
{
$user = $this->user;
$this->Balance = $user->balance / $this->CurrentDenom;
return $this->Balance;
}
public function SaveLogReport($spinSymbols, $bet, $lines, $win, $slotState)
{
$reportName = $this->slotId . ' ' . $slotState;
if( $slotState == 'freespin' )
{
$reportName = $this->slotId . ' FG';
}
else if( $slotState == 'spin' )
{
$reportName = $this->slotId . '';
}
else if( $slotState == 'respin' )
{
$reportName = $this->slotId . ' RS';
}
else if( $slotState == 'slotGamble' )
{
$reportName = $this->slotId . ' DG';
}
$game = $this->game;
if( $slotState == 'bet' )
{
$this->user->update_level('bet', $bet * $lines * $this->CurrentDenom);
}
if( $slotState != 'freespin' )
{
$game->increment('stat_in', $bet * $lines * $this->CurrentDenom);
}
$game->increment('stat_out', $win * $this->CurrentDenom);
$game->tournament_stat($slotState, $this->user->id, $bet * $lines * $this->CurrentDenom, $win * $this->CurrentDenom);
$this->user->update(['last_bid' => \Carbon\Carbon::now()]);
if( !isset($this->betProfit) )
{
$this->betProfit = 0;
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
}
if( !isset($this->toGameBanks) )
{
$this->toGameBanks = 0;
}
$this->game->increment('bids');
$this->game->refresh();
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $game->shop_id])->first();
if( $gamebank )
{
list($slotsBank, $bonusBank, $fishBank, $tableBank, $littleBank) = \VanguardLTE\Lib\Banker::get_all_banks($game->shop_id);
}
else
{
$slotsBank = $game->get_gamebank('', 'slots');
$bonusBank = $game->get_gamebank('bonus', 'bonus');
$fishBank = $game->get_gamebank('', 'fish');
$tableBank = $game->get_gamebank('', 'table_bank');
$littleBank = $game->get_gamebank('', 'little');
}
$totalBank = $slotsBank + $bonusBank + $fishBank + $tableBank + $littleBank;
\VanguardLTE\GameLog::create([
'game_id' => $this->slotDBId,
'user_id' => $this->playerId,
'ip' => $_SERVER['REMOTE_ADDR'],
'str' => $spinSymbols,
'shop_id' => $this->shop_id
]);
\VanguardLTE\StatGame::create([
'user_id' => $this->playerId,
'balance' => $this->Balance * $this->CurrentDenom,
'bet' => $bet * $lines * $this->CurrentDenom,
'win' => $win * $this->CurrentDenom,
'game' => $reportName,
'in_game' => $this->toGameBanks,
'in_jpg' => $this->toSlotJackBanks,
'in_profit' => $this->betProfit,
'denomination' => $this->CurrentDenom,
'shop_id' => $this->shop_id,
'slots_bank' => (double)$slotsBank,
'bonus_bank' => (double)$bonusBank,
'fish_bank' => (double)$fishBank,
'table_bank' => (double)$tableBank,
'little_bank' => (double)$littleBank,
'total_bank' => (double)$totalBank,
'date_time' => \Carbon\Carbon::now()
]);
}
public function GetSpinSettings($garantType = 'spin', $bet, $lines)
{
$curField = 10;
switch( $lines )
{
case 10:
$curField = 10;
break;
case 9:
case 8:
$curField = 9;
break;
case 7:
case 6:
$curField = 7;
break;
case 5:
case 4:
$curField = 5;
break;
case 3:
case 2:
$curField = 3;
break;
case 1:
$curField = 1;
break;
default:
$curField = 10;
break;
}
if( $garantType != 'spin' )
{
$pref = '_bonus';
}
else
{
$pref = '';
}
$this->AllBet = $bet * $lines;
$linesPercentConfigSpin = $this->game->get_lines_percent_config('spin');
$linesPercentConfigBonus = $this->game->get_lines_percent_config('bonus');
$currentPercent = $this->shop->percent;
$currentSpinWinChance = 0;
$currentBonusWinChance = 0;
$percentLevel = '';
foreach( $linesPercentConfigSpin['line' . $curField . $pref] as $k => $v )
{
$l = explode('_', $k);
$l0 = $l[0];
$l1 = $l[1];
if( $l0 <= $currentPercent && $currentPercent <= $l1 )
{
$percentLevel = $k;
break;
}
}
$currentSpinWinChance = $linesPercentConfigSpin['line' . $curField . $pref][$percentLevel];
$currentBonusWinChance = $linesPercentConfigBonus['line' . $curField . $pref][$percentLevel];
$RtpControlCount = 200;
if( !$this->HasGameDataStatic('SpinWinLimit') )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
if( !$this->HasGameDataStatic('RtpControlCount') )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
if( $this->game->stat_in > 0 )
{
$rtpRange = $this->game->stat_out / $this->game->stat_in * 100;
}
else
{
$rtpRange = 0;
}
if( $this->GetGameDataStatic('RtpControlCount') == 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
}
}
else if( $this->GetGameDataStatic('RtpControlCount') < 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
}
if( $this->GetGameDataStatic('RtpControlCount') < (-1 * $RtpControlCount) && $currentPercent - 1 <= $rtpRange && $rtpRange <= ($currentPercent + 2) )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
}
else
{
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
$bonusWin = rand(1, $currentBonusWinChance);
$spinWin = rand(1, $currentSpinWinChance);
$return = [
'none',
0
];
if( $bonusWin == 1 && $this->slotBonus )
{
$this->isBonusStart = true;
$garantType = 'bonus';
$winLimit = $this->GetBank($garantType);
$return = [
'bonus',
$winLimit
];
if( $this->game->stat_in < ($this->CheckBonusWin() * $bet + $this->game->stat_out) || $winLimit < ($this->CheckBonusWin() * $bet) )
{
$return = [
'none',
0
];
}
}
else if( $spinWin == 1 )
{
$winLimit = $this->GetBank($garantType);
$return = [
'win',
$winLimit
];
}
if( $garantType == 'bet' && $this->GetBalance() <= (2 / $this->CurrentDenom) )
{
$randomPush = rand(1, 10);
if( $randomPush == 1 )
{
$winLimit = $this->GetBank('');
$return = [
'win',
$winLimit
];
}
}
return $return;
}
public function GetRandomScatterPos($rp)
{
$rpResult = [];
for( $i = 0; $i < count($rp); $i++ )
{
if( $rp[$i] == 'SCAT' )
{
if( $this->slotReelsConfig[0][2] == 4 )
{
if( isset($rp[$i + 1]) && isset($rp[$i + 2]) && isset($rp[$i + 3]) )
{
array_push($rpResult, $i);
}
if( isset($rp[$i - 1]) && isset($rp[$i + 1]) && isset($rp[$i + 2]) )
{
array_push($rpResult, $i - 1);
}
if( isset($rp[$i - 2]) && isset($rp[$i - 1]) && isset($rp[$i + 1]) )
{
array_push($rpResult, $i - 2);
}
if( isset($rp[$i - 3]) && isset($rp[$i - 2]) && isset($rp[$i - 1]) )
{
array_push($rpResult, $i - 3);
}
}
else
{
if( isset($rp[$i + 1]) && isset($rp[$i + 2]) )
{
array_push($rpResult, $i);
}
if( isset($rp[$i - 1]) && isset($rp[$i + 1]) )
{
array_push($rpResult, $i - 1);
}
if( isset($rp[$i - 2]) && isset($rp[$i - 1]) )
{
array_push($rpResult, $i - 2);
}
}
}
}
shuffle($rpResult);
if( !isset($rpResult[0]) )
{
$rpResult[0] = rand(2, count($rp) - 3);
}
return $rpResult[0];
}
public function GetGambleSettings()
{
$spinWin = rand(1, $this->WinGamble);
return $spinWin;
}
public function GetHistory()
{
$history = \VanguardLTE\GameLog::whereRaw('game_id=? and user_id=? ORDER BY id DESC LIMIT 10', [
$this->slotDBId,
$this->playerId
])->get();
$this->lastEvent = 'NULL';
foreach( $history as $log )
{
$tmpLog = json_decode($log->str);
if( $tmpLog->responseEvent != 'gambleResult' )
{
$this->lastEvent = $log->str;
break;
}
}
if( isset($tmpLog) )
{
return $tmpLog;
}
else
{
return 'NULL';
}
}
public function GetReelStrips($winType)
{
if( $winType != 'bonus' )
{
$prs = [];
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $index => $reelStrip )
{
if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 )
{
$prs[$index + 1] = mt_rand(0, count($this->$reelStrip) - 3);
}
}
}
else
{
$reelsId = [];
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $index => $reelStrip )
{
if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 )
{
$prs[$index + 1] = $this->GetRandomScatterPos($this->$reelStrip);
$reelsId[] = $index + 1;
}
}
$scattersCnt = rand(3, count($reelsId));
shuffle($reelsId);
for( $i = 0; $i < count($reelsId); $i++ )
{
if( $i < $scattersCnt )
{
$prs[$reelsId[$i]] = $this->GetRandomScatterPos($this->{'reelStrip' . $reelsId[$i]});
}
else
{
$prs[$reelsId[$i]] = rand(0, count($this->{'reelStrip' . $reelsId[$i]}) - 3);
}
}
}
$reel = [
'rp' => []
];
foreach( $prs as $index => $value )
{
$key = $this->{'reelStrip' . $index};
$reel['reel' . $index][0] = $key[$value];
$reel['reel' . $index][1] = $key[$value + 1];
$reel['reel' . $index][2] = $key[$value + 2];
$reel['reel' . $index][3] = '';
$reel['rp'][] = $value;
}
return $reel;
}
}
}
| 1 | 0.642768 | 1 | 0.642768 | game-dev | MEDIA | 0.663453 | game-dev | 0.821887 | 1 | 0.821887 |
tateisu/SubwayTooter | 5,625 | app/src/main/java/jp/juggler/subwaytooter/util/BucketList.kt | package jp.juggler.subwaytooter.util
import java.util.AbstractList
import java.util.ArrayList
import java.util.NoSuchElementException
import java.util.RandomAccess
class BucketList<E> constructor(
val bucketCapacity: Int = 1024
) : AbstractList<E>(), MutableIterable<E>, RandomAccess {
companion object {
private val pos_internal = object : ThreadLocal<BucketPos>() {
override fun initialValue(): BucketPos {
return BucketPos()
}
}
}
override var size: Int = 0
override fun isEmpty(): Boolean {
return 0 == size
}
private class Bucket<E>(
capacity: Int,
var totalStart: Int = 0,
var totalEnd: Int = 0
) : ArrayList<E>(capacity)
private val groups = ArrayList<Bucket<E>>()
override fun clear() {
groups.clear()
size = 0
}
private fun updateIndex() {
var n = 0
for (bucket in groups) {
bucket.totalStart = n
n += bucket.size
bucket.totalEnd = n
}
size = n
}
internal class BucketPos(
var groupIndex: Int = 0,
var bucketIndex: Int = 0
) {
internal fun set(groupIndex: Int, bucketIndex: Int): BucketPos {
this.groupIndex = groupIndex
this.bucketIndex = bucketIndex
return this
}
}
// allocated を指定しない場合は BucketPosを生成します
private fun findPos(
totalIndex: Int,
result: BucketPos = pos_internal.get()!!
): BucketPos {
if (totalIndex < 0 || totalIndex >= size) {
throw IndexOutOfBoundsException("findPos: bad index=$totalIndex, size=$size")
}
// binary search
var gs = 0
var ge = groups.size
while (true) {
val gi = (gs + ge) shr 1
val group = groups[gi]
when {
totalIndex < group.totalStart -> ge = gi
totalIndex >= group.totalEnd -> gs = gi + 1
else -> {
return result.set(gi, totalIndex - group.totalStart)
}
}
}
}
override fun get(index: Int): E {
val pos = findPos(index)
return groups[pos.groupIndex][pos.bucketIndex]
}
override fun set(index: Int, element: E): E {
val pos = findPos(index)
return groups[pos.groupIndex].set(pos.bucketIndex, element)
}
// 末尾への追加
override fun addAll(elements: Collection<E>): Boolean {
val cSize = elements.size
if (cSize == 0) return false
// 最後のバケツに収まるなら、最後のバケツの中に追加する
if (groups.isNotEmpty()) {
val bucket = groups[groups.size - 1]
if (bucket.size + cSize <= bucketCapacity) {
bucket.addAll(elements)
bucket.totalEnd += cSize
size += cSize
return true
}
}
// 新しいバケツを作って、そこに追加する
val bucket = Bucket<E>(bucketCapacity)
bucket.addAll(elements)
bucket.totalStart = size
bucket.totalEnd = size + cSize
size += cSize
groups.add(bucket)
return true
}
// 位置を指定して挿入
override fun addAll(index: Int, elements: Collection<E>): Boolean {
// indexが終端なら、終端に追加する
// バケツがカラの場合もここ
if (index >= size) {
return addAll(elements)
}
val cSize = elements.size
if (cSize == 0) return false
val pos = findPos(index)
var bucket = groups[pos.groupIndex]
// 挿入位置がバケツの先頭ではないか、バケツのサイズに問題がないなら
if (pos.bucketIndex > 0 || bucket.size + cSize <= bucketCapacity) {
// バケツの中に挿入する
bucket.addAll(pos.bucketIndex, elements)
} else {
// 新しいバケツを作って、そこに追加する
bucket = Bucket(bucketCapacity)
bucket.addAll(elements)
groups.add(pos.groupIndex, bucket)
}
updateIndex()
return true
}
override fun removeAt(index: Int): E {
val pos = findPos(index)
val bucket = groups[pos.groupIndex]
val data = bucket.removeAt(pos.bucketIndex)
if (bucket.isEmpty()) {
groups.removeAt(pos.groupIndex)
}
updateIndex()
return data
}
inner class MyIterator internal constructor() : MutableIterator<E> {
private val pos: BucketPos // indicates next read point
init {
pos = BucketPos(0, 0)
}
override fun hasNext(): Boolean {
while (true) {
if (pos.groupIndex >= groups.size) {
return false
}
val bucket = groups[pos.groupIndex]
if (pos.bucketIndex >= bucket.size) {
pos.bucketIndex = 0
++pos.groupIndex
continue
}
return true
}
}
override fun next(): E {
while (true) {
if (pos.groupIndex >= groups.size) {
throw NoSuchElementException()
}
val bucket = groups[pos.groupIndex]
if (pos.bucketIndex >= bucket.size) {
pos.bucketIndex = 0
++pos.groupIndex
continue
}
return bucket[pos.bucketIndex++]
}
}
override fun remove() {
throw NotImplementedError()
}
}
override fun iterator(): MutableIterator<E> {
return MyIterator()
}
}
| 1 | 0.753756 | 1 | 0.753756 | game-dev | MEDIA | 0.599051 | game-dev | 0.867639 | 1 | 0.867639 |
Greymerk/minecraft-roguelike | 1,482 | src/main/java/com/greymerk/roguelike/treasure/Inventory.java | package com.greymerk.roguelike.treasure;
import java.util.ArrayList;
import java.util.List;
import com.greymerk.roguelike.util.math.RandHelper;
import net.minecraft.block.entity.LootableContainerBlockEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.random.Random;
public class Inventory {
private LootableContainerBlockEntity chest;
List<Integer> shuffledSlots;
public Inventory(Random rand, LootableContainerBlockEntity chest){
this.chest = chest;
this.shuffledSlots = new ArrayList<Integer>();
for(int i = 0; i < this.getInventorySize(); ++i){
shuffledSlots.add(i);
}
RandHelper.shuffle(shuffledSlots, rand);
}
public boolean setRandomEmptySlot(ItemStack item){
int slot = this.getRandomEmptySlot();
if(slot < 0) return false;
return setInventorySlot(slot, item);
}
private int getRandomEmptySlot(){
for(int slot : this.shuffledSlots){
if(isEmptySlot(slot)) return slot;
}
return -1;
}
public boolean isEmptySlot(int slot){
try{
ItemStack item = chest.getStack(slot);
return item.isEmpty();
} catch(NullPointerException e){
return false;
}
}
public boolean setInventorySlot(int slot, ItemStack item){
try{
chest.setStack(slot, item);
return true;
} catch(NullPointerException e){
return false;
}
}
public int getInventorySize(){
if(chest == null){
return 0;
}
try{
return chest.size();
} catch(NullPointerException e){
return 0;
}
}
}
| 1 | 0.904358 | 1 | 0.904358 | game-dev | MEDIA | 0.942216 | game-dev | 0.940983 | 1 | 0.940983 |
microsoft/vsminecraft | 5,515 | minecraftpkg/MekanismModSample/src/main/java/mekanism/client/gui/GuiSolarEvaporationController.java | package mekanism.client.gui;
import mekanism.api.gas.GasStack;
import mekanism.api.util.UnitDisplayUtils.TemperatureUnit;
import mekanism.client.render.MekanismRenderer;
import mekanism.common.inventory.container.ContainerSolarEvaporationController;
import mekanism.common.tile.TileEntitySolarEvaporationController;
import mekanism.common.util.LangUtils;
import mekanism.common.util.MekanismUtils;
import mekanism.common.util.MekanismUtils.ResourceType;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraftforge.fluids.FluidStack;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiSolarEvaporationController extends GuiMekanism
{
public TileEntitySolarEvaporationController tileEntity;
public GuiSolarEvaporationController(InventoryPlayer inventory, TileEntitySolarEvaporationController tentity)
{
super(tentity, new ContainerSolarEvaporationController(inventory, tentity));
tileEntity = tentity;
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY)
{
int xAxis = (mouseX - (width - xSize) / 2);
int yAxis = (mouseY - (height - ySize) / 2);
fontRendererObj.drawString(MekanismUtils.localize("container.inventory"), 8, (ySize - 96) + 4, 0x404040);
fontRendererObj.drawString(tileEntity.getInventoryName(), (xSize/2)-(fontRendererObj.getStringWidth(tileEntity.getInventoryName())/2), 4, 0x404040);
fontRendererObj.drawString(getStruct(), 50, 21, 0x00CD00);
fontRendererObj.drawString(MekanismUtils.localize("gui.height") + ": " + tileEntity.height, 50, 30, 0x00CD00);
fontRendererObj.drawString(MekanismUtils.localize("gui.mult") + ": " + getTempMult(), 50, 39, 0x00CD00);
fontRendererObj.drawString(MekanismUtils.localize("gui.max") + ": " + getMaxTemp(), 50, 48, 0x00CD00);
if(xAxis >= 7 && xAxis <= 23 && yAxis >= 14 && yAxis <= 72)
{
drawCreativeTabHoveringText(tileEntity.inputTank.getFluid() != null ? LangUtils.localizeFluidStack(tileEntity.inputTank.getFluid()) + ": " + tileEntity.inputTank.getFluidAmount() : MekanismUtils.localize("gui.empty"), xAxis, yAxis);
}
if(xAxis >= 153 && xAxis <= 169 && yAxis >= 14 && yAxis <= 72)
{
drawCreativeTabHoveringText(tileEntity.outputTank.getFluid() != null ? LangUtils.localizeFluidStack(tileEntity.outputTank.getFluid()) + ": " + tileEntity.outputTank.getFluidAmount() : MekanismUtils.localize("gui.empty"), xAxis, yAxis);
}
if(xAxis >= 49 && xAxis <= 127 && yAxis >= 64 && yAxis <= 72)
{
drawCreativeTabHoveringText(getTemp(), xAxis, yAxis);
}
super.drawGuiContainerForegroundLayer(mouseX, mouseY);
}
private String getStruct()
{
if(tileEntity.structured)
{
return MekanismUtils.localize("gui.formed");
}
else {
if(tileEntity.controllerConflict)
{
return MekanismUtils.localize("gui.conflict");
}
else {
return MekanismUtils.localize("gui.incomplete");
}
}
}
private String getTemp()
{
float temp = tileEntity.getTemperature()*200;
return MekanismUtils.getTemperatureDisplay(temp, TemperatureUnit.AMBIENT);
}
private String getMaxTemp()
{
float temp = tileEntity.getMaxTemperature()*200;
return MekanismUtils.getTemperatureDisplay(temp, TemperatureUnit.AMBIENT);
}
private String getTempMult()
{
float temp = (float)Math.round((tileEntity.getTempMultiplier())*10)/10F;
return temp + "x";
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTick, int mouseX, int mouseY)
{
super.drawGuiContainerBackgroundLayer(partialTick, mouseX, mouseY);
mc.renderEngine.bindTexture(MekanismUtils.getResource(ResourceType.GUI, "GuiSolarEvaporationController.png"));
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
int guiWidth = (width - xSize) / 2;
int guiHeight = (height - ySize) / 2;
drawTexturedModalRect(guiWidth, guiHeight, 0, 0, xSize, ySize);
int displayInt;
if(tileEntity.getScaledInputLevel(58) > 0)
{
displayGauge(7, 14, tileEntity.getScaledInputLevel(58), tileEntity.inputTank.getFluid(), null);
}
if(tileEntity.getScaledOutputLevel(58) > 0)
{
displayGauge(153, 14, tileEntity.getScaledOutputLevel(58), tileEntity.outputTank.getFluid(), null);
}
displayInt = tileEntity.getScaledTempLevel(78);
drawTexturedModalRect(guiWidth + 49, guiHeight + 64, 176, 59, displayInt, 8);
}
public void displayGauge(int xPos, int yPos, int scale, FluidStack fluid, GasStack gas)
{
if(fluid == null && gas == null)
{
return;
}
int guiWidth = (width - xSize) / 2;
int guiHeight = (height - ySize) / 2;
int start = 0;
while(true)
{
int renderRemaining;
if(scale > 16)
{
renderRemaining = 16;
scale -= 16;
}
else {
renderRemaining = scale;
scale = 0;
}
mc.renderEngine.bindTexture(MekanismRenderer.getBlocksTexture());
if(fluid != null)
{
drawTexturedModelRectFromIcon(guiWidth + xPos, guiHeight + yPos + 58 - renderRemaining - start, fluid.getFluid().getIcon(), 16, 16 - (16 - renderRemaining));
}
else if(gas != null)
{
drawTexturedModelRectFromIcon(guiWidth + xPos, guiHeight + yPos + 58 - renderRemaining - start, gas.getGas().getIcon(), 16, 16 - (16 - renderRemaining));
}
start+=16;
if(renderRemaining == 0 || scale == 0)
{
break;
}
}
mc.renderEngine.bindTexture(MekanismUtils.getResource(ResourceType.GUI, "GuiSolarEvaporationController.png"));
drawTexturedModalRect(guiWidth + xPos, guiHeight + yPos, 176, 0, 16, 59);
}
}
| 1 | 0.87913 | 1 | 0.87913 | game-dev | MEDIA | 0.81418 | game-dev,graphics-rendering | 0.970475 | 1 | 0.970475 |
REGoth-project/REGoth-bs | 39,759 | src/scripting/daedalus/DaedalusVMForGameWorld.cpp | #include "DaedalusVMForGameWorld.hpp"
#include "DaedalusClassVarResolver.hpp"
#include <RTTI/RTTI_DaedalusVMForGameWorld.hpp>
#include <Scene/BsSceneObject.h>
#include <animation/StateNaming.hpp>
#include <components/Character.hpp>
#include <components/CharacterAI.hpp>
#include <components/CharacterEventQueue.hpp>
#include <components/Freepoint.hpp>
#include <components/GameClock.hpp>
#include <components/GameWorld.hpp>
#include <components/Inventory.hpp>
#include <components/Item.hpp>
#include <components/StoryInformation.hpp>
#include <components/VisualCharacter.hpp>
#include <components/Waynet.hpp>
#include <log/logging.hpp>
#include <scripting/ScriptSymbolQueries.hpp>
// TODO: Refactor, so we don't access deep into the UI code here for dialogues
#include <components/GameplayUI.hpp>
namespace REGoth
{
namespace Scripting
{
DaedalusVMForGameWorld::DaedalusVMForGameWorld(HGameWorld gameWorld,
const bs::Vector<bs::UINT8>& datFileData)
: DaedalusVM(datFileData)
, mWorld(gameWorld)
{
}
void DaedalusVMForGameWorld::initialize()
{
DaedalusVM::initialize();
createAllInformationInstances();
}
void DaedalusVMForGameWorld::fillSymbolStorage()
{
DaedalusVM::fillSymbolStorage();
mHeroSymbol = scriptSymbols().findIndexBySymbolName("HERO");
mSelfSymbol = scriptSymbols().findIndexBySymbolName("SELF");
mOtherSymbol = scriptSymbols().findIndexBySymbolName("OTHER");
mVictimSymbol = scriptSymbols().findIndexBySymbolName("VICTIM");
mItemSymbol = scriptSymbols().findIndexBySymbolName("ITEM");
}
ScriptObjectHandle DaedalusVMForGameWorld::instanciateClass(const bs::String& className,
const bs::String& instanceName,
bs::HSceneObject mappedSceneObject)
{
SymbolInstance& symbol = mScriptSymbols.getSymbol<SymbolInstance>(instanceName);
return instanciateClass(className, symbol, mappedSceneObject);
}
ScriptObjectHandle DaedalusVMForGameWorld::instanciateClass(const bs::String& className,
SymbolIndex instanceSymbolIndex,
bs::HSceneObject mappedSceneObject)
{
SymbolInstance& symbol = mScriptSymbols.getSymbol<SymbolInstance>(instanceSymbolIndex);
return instanciateClass(className, symbol, mappedSceneObject);
}
ScriptObjectHandle DaedalusVMForGameWorld::instanciateClass(const bs::String& className,
SymbolInstance& instance,
bs::HSceneObject mappedSceneObject)
{
// To instanciate a class the following has to happen:
//
// 1. Create a blank object of that class,
// 2. Save `self` and *Current Instance*,
// 3. Assign the new object to `self` and *Current Instance*,
// 4. Run the instance constructor
// 5. Restore `self` and *Current Instance*,
// 6. Assign the newly created object to the instances symbol
//
// *Current Instance* must be set so the class-members are resolved correctly.
// `self` must be set so that the constructor can refer to the object being created
// in function calls.
//
// The last created instance is also assigned to the instance symbol in step 6 so that
// it can be referred to by name inside the scripts. Though, this only makes sense for
// instances where there is usually only one instance active.
//
// Since the constructor *can* call externals which refer to the scene object, we need
// to also map the objects *before* executing the constructor.
ScriptObjectHandle obj = instanciateBlankObjectOfClass(className);
ScriptObject& objData = mScriptObjects.get(obj);
objData.instanceName = instance.name;
if (mappedSceneObject)
{
// Constructor might call an external and refer to the scene object, so map before doing
// anything.
mapping().map(obj, mappedSceneObject);
}
instance.instance = obj;
ScriptObjectHandle oldCurrentInstance = mClassVarResolver->getCurrentInstance();
ScriptObjectHandle oldSelf = getInstance("SELF");
setInstance("SELF", obj);
mClassVarResolver->setCurrentInstance(obj);
executeScriptFunction(instance.constructorAddress);
mClassVarResolver->setCurrentInstance(oldCurrentInstance);
setInstance("SELF", oldSelf);
// debugLogScriptObject(objData);
return obj;
}
void DaedalusVMForGameWorld::runFunctionOnSelf(const bs::String& function, HCharacter self)
{
self->useAsSelf();
executeScriptFunction(function);
}
bool DaedalusVMForGameWorld::runStateLoopFunction(SymbolIndex function, HCharacter self)
{
self->useAsSelf();
mStack.clear();
const auto& functionSym = scriptSymbols().getSymbol<SymbolScriptFunction>(function);
executeScriptFunction(functionSym.address);
if (functionSym.returnType != ReturnType::Void)
{
return popIntValue() != 0;
}
else
{
// Some of these have a return type of `void` to say that they should be looping forever.
// This happens on most sub-states of `ZS_MM_ALLSCHEDULER`, for example.
return false;
}
}
bool DaedalusVMForGameWorld::runInfoConditionFunction(SymbolIndex function, HCharacter self,
HCharacter other)
{
self->useAsSelf();
other->useAsOther();
mStack.clear();
const auto& functionSym = scriptSymbols().getSymbol<SymbolScriptFunction>(function);
executeScriptFunction(functionSym.address);
return popIntValue() != 0;
}
void DaedalusVMForGameWorld::runInfoFunction(SymbolIndex function, HCharacter self,
HCharacter other)
{
self->useAsSelf();
other->useAsOther();
mStack.clear();
const auto& functionSym = scriptSymbols().getSymbol<SymbolScriptFunction>(function);
executeScriptFunction(functionSym.address);
}
void DaedalusVMForGameWorld::runFunctionOnSelf(SymbolIndex function, HCharacter self)
{
self->useAsSelf();
const auto& functionSym = scriptSymbols().getSymbol<SymbolScriptFunction>(function);
executeScriptFunction(functionSym.address);
}
void DaedalusVMForGameWorld::setHero(ScriptObjectHandle hero)
{
setInstance(mHeroSymbol, hero);
}
ScriptObjectHandle DaedalusVMForGameWorld::heroInstance()
{
return getInstance(mHeroSymbol);
}
ScriptObjectHandle DaedalusVMForGameWorld::victimInstance() const
{
return getInstance(mVictimSymbol);
}
HCharacter DaedalusVMForGameWorld::victim() const
{
return getInstanceCharacter(mVictimSymbol);
}
void DaedalusVMForGameWorld::setVictim(ScriptObjectHandle victim)
{
setInstance(mVictimSymbol, victim);
}
ScriptObjectHandle DaedalusVMForGameWorld::itemInstance() const
{
return getInstance(mItemSymbol);
}
HItem DaedalusVMForGameWorld::item() const
{
return getInstanceItem(mItemSymbol);
}
void DaedalusVMForGameWorld::setItem(ScriptObjectHandle item)
{
setInstance(mItemSymbol, item);
}
ScriptObjectHandle DaedalusVMForGameWorld::otherInstance() const
{
return getInstance(mOtherSymbol);
}
HCharacter DaedalusVMForGameWorld::other() const
{
return getInstanceCharacter(mOtherSymbol);
}
void DaedalusVMForGameWorld::setOther(ScriptObjectHandle other)
{
setInstance(mOtherSymbol, other);
}
ScriptObjectHandle DaedalusVMForGameWorld::selfInstance() const
{
return getInstance(mSelfSymbol);
}
HCharacter DaedalusVMForGameWorld::self() const
{
return getInstanceCharacter(mSelfSymbol);
}
void DaedalusVMForGameWorld::setSelf(ScriptObjectHandle self)
{
setInstance(mSelfSymbol, self);
}
void DaedalusVMForGameWorld::setInstance(SymbolIndex instance, ScriptObjectHandle scriptObject)
{
SymbolInstance& symbol = mScriptSymbols.getSymbol<SymbolInstance>(instance);
symbol.instance = scriptObject;
}
void DaedalusVMForGameWorld::setInstance(const bs::String& instance,
ScriptObjectHandle scriptObject)
{
SymbolInstance& symbol = mScriptSymbols.getSymbol<SymbolInstance>(instance);
symbol.instance = scriptObject;
}
ScriptObjectHandle DaedalusVMForGameWorld::getInstance(const bs::String& instance) const
{
const SymbolInstance& symbol = mScriptSymbols.getSymbol<SymbolInstance>(instance);
return symbol.instance;
}
ScriptObjectHandle DaedalusVMForGameWorld::getInstance(SymbolIndex symbolIndex) const
{
const SymbolInstance& symbol = mScriptSymbols.getSymbol<SymbolInstance>(symbolIndex);
return symbol.instance;
}
HCharacter DaedalusVMForGameWorld::getInstanceCharacter(const bs::String& instance) const
{
const SymbolInstance& symbol = mScriptSymbols.getSymbol<SymbolInstance>(instance);
if (!mappingConst().isMappedToSomething(symbol.instance))
{
return {};
}
bs::HSceneObject characterSO = mappingConst().getMappedSceneObject(symbol.instance);
HCharacter character = characterSO->getComponent<Character>();
if (!character)
{
REGOTH_THROW(InvalidParametersException,
"Expected to be passed a Character instance, but the scene object does "
"not have a character-component!");
}
return character;
}
HCharacter DaedalusVMForGameWorld::getInstanceCharacter(SymbolIndex symbolIndex) const
{
const SymbolInstance& symbol = mScriptSymbols.getSymbol<SymbolInstance>(symbolIndex);
if (!mappingConst().isMappedToSomething(symbol.instance))
{
return {};
}
bs::HSceneObject characterSO = mappingConst().getMappedSceneObject(symbol.instance);
HCharacter character = characterSO->getComponent<Character>();
if (!character)
{
REGOTH_THROW(InvalidParametersException,
"Expected to be passed a Character instance, but the scene object does "
"not have a character-component!");
}
return character;
}
HItem DaedalusVMForGameWorld::getInstanceItem(const bs::String& instance) const
{
const SymbolInstance& symbol = mScriptSymbols.getSymbol<SymbolInstance>(instance);
bs::HSceneObject itemSO = mappingConst().getMappedSceneObject(symbol.instance);
HItem item = itemSO->getComponent<Item>();
if (!item)
{
REGOTH_THROW(InvalidParametersException,
"Expected to be passed a Item instance, but the scene object does "
"not have a item-component!");
}
return item;
}
HItem DaedalusVMForGameWorld::getInstanceItem(SymbolIndex symbolIndex) const
{
const SymbolInstance& symbol = mScriptSymbols.getSymbol<SymbolInstance>(symbolIndex);
bs::HSceneObject itemSO = mappingConst().getMappedSceneObject(symbol.instance);
HItem item = itemSO->getComponent<Item>();
if (!item)
{
REGOTH_THROW(InvalidParametersException,
"Expected to be passed a Item instance, but the scene object does "
"not have a item-component!");
}
return item;
}
HCharacter DaedalusVMForGameWorld::popCharacterInstance()
{
ScriptObjectHandle scriptObject = popInstanceScriptObject();
if (scriptObject == SCRIPT_OBJECT_HANDLE_INVALID)
{
return {};
}
bs::HSceneObject characterSO = mapping().getMappedSceneObject(scriptObject);
HCharacter character = characterSO->getComponent<Character>();
if (!character)
{
REGOTH_THROW(InvalidParametersException,
"Expected to find a character instance on the stack, but the scene object does "
"not have a character-component!");
}
return character;
}
HItem DaedalusVMForGameWorld::popItemInstance()
{
ScriptObjectHandle scriptObject = popInstanceScriptObject();
if (scriptObject == SCRIPT_OBJECT_HANDLE_INVALID)
{
return {};
}
bs::HSceneObject itemSO = mapping().getMappedSceneObject(scriptObject);
HItem item = itemSO->getComponent<Item>();
if (!item)
{
REGOTH_THROW(InvalidParametersException,
"Expected to find a item instance on the stack, but the scene object does "
"not have a item-component!");
}
return item;
}
void DaedalusVMForGameWorld::initializeWorld(const bs::String& worldName)
{
// Some scripts already refer to the hero, so make sure that has been set
if (getInstance("HERO") == SCRIPT_OBJECT_HANDLE_INVALID)
{
REGOTH_THROW(InvalidStateException, "Hero-instance must be set to call world init scripts!");
}
// Some G1-Scripts refer to SELF during init while doing debug-output.
// I can only assume they mean the hero.
setInstance("SELF", getInstance("HERO"));
// FIXME: Do STARTUP_* only on first load?
executeScriptFunction("STARTUP_" + worldName);
executeScriptFunction("INIT_" + worldName);
}
void DaedalusVMForGameWorld::registerAllExternals()
{
using This = DaedalusVMForGameWorld;
registerExternal("PRINT", (externalCallback)&This::external_Print);
registerExternal("PRINTDEBUGINSTCH", (externalCallback)&This::external_PrintDebugInstCh);
registerExternal("HLP_RANDOM", (externalCallback)&This::external_HLP_Random);
registerExternal("HLP_GETNPC", (externalCallback)&This::external_HLP_GetNpc);
registerExternal("HLP_ISVALIDNPC", (externalCallback)&This::external_HLP_IsValidNpc);
registerExternal("HLP_ISVALIDITEM", (externalCallback)&This::external_HLP_IsValidItem);
registerExternal("INTTOSTRING", (externalCallback)&This::external_IntToString);
registerExternal("INTTOFLOAT", (externalCallback)&This::external_IntToFloat);
registerExternal("FLOATTOINT", (externalCallback)&This::external_FloatToInt);
registerExternal("NPC_ISPLAYER", (externalCallback)&This::external_NPC_IsPlayer);
registerExternal("WLD_INSERTNPC", (externalCallback)&This::external_WLD_InsertNpc);
registerExternal("CONCATSTRINGS", (externalCallback)&This::external_ConcatStrings);
registerExternal("WLD_INSERTITEM", (externalCallback)&This::external_WLD_InsertItem);
registerExternal("NPC_SETTALENTSKILL", (externalCallback)&This::external_NPC_SetTalentSkill);
registerExternal("EQUIPITEM", (externalCallback)&This::external_NPC_EquipItem);
registerExternal("MDL_SETVISUAL", (externalCallback)&This::external_MDL_SetVisual);
registerExternal("MDL_SETVISUALBODY", (externalCallback)&This::external_MDL_SetVisualBody);
registerExternal("WLD_GETDAY", (externalCallback)&This::external_WLD_GetDay);
registerExternal("WLD_ISTIME", (externalCallback)&This::external_WLD_IsTime);
registerExternal("WLD_SETTIME", (externalCallback)&This::external_WLD_SetTime);
registerExternal("TA_MIN", (externalCallback)&This::external_TA_Min);
registerExternal("NPC_EXCHANGEROUTINE", (externalCallback)&This::external_NPC_ExchangeRoutine);
registerExternal("AI_GOTOWP", (externalCallback)&This::external_AI_GotoWaypoint);
registerExternal("AI_GOTOFP", (externalCallback)&This::external_AI_GotoFreepoint);
registerExternal("AI_GOTONEXTFP", (externalCallback)&This::external_AI_GotoNextFreepoint);
registerExternal("AI_GOTONPC", (externalCallback)&This::external_AI_GotoNpc);
registerExternal("AI_SETWALKMODE", (externalCallback)&This::external_AI_SetWalkMode);
registerExternal("AI_WAIT", (externalCallback)&This::external_AI_Wait);
registerExternal("AI_STARTSTATE", (externalCallback)&This::external_AI_StartState);
registerExternal("AI_PLAYANI", (externalCallback)&This::external_AI_PlayAnimation);
registerExternal("NPC_GETNEARESTWP", (externalCallback)&This::external_Npc_GetNearestWP);
registerExternal("NPC_GETNEXTWP", (externalCallback)&This::external_Npc_GetNextWP);
registerExternal("NPC_GETDISTTOWP", (externalCallback)&This::external_Npc_GetDistToWP);
registerExternal("NPC_GETDISTTONPC", (externalCallback)&This::external_Npc_GetDistToNpc);
registerExternal("NPC_GETDISTTOITEM", (externalCallback)&This::external_Npc_GetDistToItem);
registerExternal("NPC_GETDISTTOPLAYER", (externalCallback)&This::external_Npc_GetDistToPlayer);
registerExternal("NPC_ISNEAR", (externalCallback)&This::external_Npc_IsNear);
registerExternal("NPC_SETTOFISTMODE", (externalCallback)&This::external_Npc_SetToFistMode);
registerExternal("NPC_KNOWSINFO", (externalCallback)&This::external_Npc_KnowsInfo);
registerExternal("NPC_REFUSETALK", (externalCallback)&This::external_Npc_RefuseTalk);
registerExternal("NPC_GETSTATETIME", (externalCallback)&This::external_Npc_GetStateTime);
registerExternal("NPC_GETBODYSTATE", (externalCallback)&This::external_Npc_GetBodyState);
registerExternal("AI_PROCESSINFOS", (externalCallback)&This::external_AI_ProcessInfos);
registerExternal("AI_STOPPROCESSINFOS", (externalCallback)&This::external_AI_StopProcessInfos);
registerExternal("CREATEINVITEMS", (externalCallback)&This::external_NPC_CreateInventoryItems);
registerExternal("CREATEINVITEM", (externalCallback)&This::external_NPC_CreateInventoryItem);
registerExternal("NPC_HASITEMS", (externalCallback)&This::external_Npc_HasItems);
registerExternal("NPC_REMOVEINVITEM", (externalCallback)&This::external_Npc_RemoveInvItem);
registerExternal("NPC_REMOVEINVITEMS", (externalCallback)&This::external_Npc_RemoveInvItems);
registerExternal("AI_TURNTONPC", (externalCallback)&This::external_AI_TurnToNpc);
registerExternal("AI_TURNAWAY", (externalCallback)&This::external_AI_TurnAway);
registerExternal("NPC_GETINVITEMBYSLOT",
(externalCallback)&This::external_Npc_GetInvItemBySlot);
registerExternal("INFOMANAGER_HASFINISHED",
(externalCallback)&This::external_InfoManager_HasFinished);
}
void DaedalusVMForGameWorld::external_Print()
{
REGOTH_LOG(Info, Uncategorized, "[ScriptVMInterface] [Print] " + popStringValue());
}
void DaedalusVMForGameWorld::external_PrintDebugInstCh()
{
bs::String text = popStringValue();
bs::INT32 character = popIntValue();
// Don't need this. Just get the parameters off the stack.
}
void DaedalusVMForGameWorld::external_HLP_Random()
{
mStack.pushInt(rand() % popIntValue());
}
void DaedalusVMForGameWorld::external_HLP_GetNpc()
{
bs::INT32 symbolIndex = popIntValue();
mStack.pushInstance((SymbolIndex)symbolIndex);
}
void DaedalusVMForGameWorld::external_HLP_IsValidNpc()
{
HCharacter character = popCharacterInstance();
if (character.isDestroyed())
{
mStack.pushInt(0);
}
else
{
mStack.pushInt(1);
}
}
void DaedalusVMForGameWorld::external_HLP_IsValidItem()
{
HItem item = popItemInstance();
if (item.isDestroyed())
{
mStack.pushInt(0);
}
else
{
mStack.pushInt(1);
}
}
void DaedalusVMForGameWorld::external_IntToString()
{
mStack.pushString(bs::toString(popIntValue()));
}
void DaedalusVMForGameWorld::external_IntToFloat()
{
mStack.pushFloat((float)popIntValue());
}
void DaedalusVMForGameWorld::external_FloatToInt()
{
mStack.pushInt((bs::INT32)popFloatValue());
}
void DaedalusVMForGameWorld::external_ConcatStrings()
{
bs::String b = popStringValue();
bs::String a = popStringValue();
mStack.pushString(a + b);
}
void DaedalusVMForGameWorld::external_WLD_InsertItem()
{
bs::String spawnpoint = popStringValue();
SymbolIndex instance = popIntValue();
mWorld->insertItem(mScriptSymbols.getSymbolName(instance), spawnpoint);
}
void DaedalusVMForGameWorld::external_WLD_InsertNpc()
{
bs::String waypoint = popStringValue();
SymbolIndex instance = popIntValue();
mWorld->insertCharacter(mScriptSymbols.getSymbolName(instance), waypoint);
}
void DaedalusVMForGameWorld::external_WLD_GetDay()
{
bs::INT32 day = mWorld->gameclock()->getDay();
mStack.pushInt(day);
}
void DaedalusVMForGameWorld::external_WLD_IsTime()
{
bs::INT32 min2 = popIntValue();
bs::INT32 hour2 = popIntValue();
bs::INT32 min1 = popIntValue();
bs::INT32 hour1 = popIntValue();
bool test = mWorld->gameclock()->isTime(hour1, min1, hour2, min2);
mStack.pushInt(test ? 1 : 0);
}
void DaedalusVMForGameWorld::external_WLD_SetTime()
{
bs::INT32 min = popIntValue();
bs::INT32 hour = popIntValue();
mWorld->gameclock()->setTime(hour, min);
}
void DaedalusVMForGameWorld::external_NPC_IsPlayer()
{
HCharacter character = popCharacterInstance();
mStack.pushInt(character->isPlayer() ? 1 : 0);
}
void DaedalusVMForGameWorld::external_NPC_SetTalentSkill()
{
bs::INT32 skill = popIntValue();
bs::INT32 talent = popIntValue();
HCharacter character = popCharacterInstance();
REGOTH_LOG(Warning, Uncategorized, "[External] Using external stub: NPC_SetTalentSkill");
}
void DaedalusVMForGameWorld::external_MDL_SetVisual()
{
bs::String visual = popStringValue();
HCharacter character = popCharacterInstance();
HVisualCharacter characterVisual;
// if (!character->SO()->hasComponent<VisualCharacter>())
// {
// characterVisual = character->SO()->addComponent<VisualCharacter>();
// }
// else
// {
characterVisual = character->SO()->getComponent<VisualCharacter>();
// }
bs::StringUtil::toUpperCase(visual);
characterVisual->setVisual(visual);
}
void DaedalusVMForGameWorld::external_MDL_SetVisualBody()
{
bs::INT32 armorInstance = popIntValue();
bs::INT32 teethTexIndex = popIntValue();
bs::INT32 headTexIndex = popIntValue();
bs::String headMesh = popStringValue();
bs::INT32 bodyTexColor = popIntValue();
bs::INT32 bodyTexIndex = popIntValue();
bs::String bodyMesh = popStringValue();
// If an armor is set here, we need to replace the body mesh from the input parameters with the
// visual settings from inside the armor instance
if (armorInstance != -1)
{
// TODO: Original Gothic adds the Armor straight to the inventory. We just create a
// temporary instance to extract the visual information from it
ScriptObjectHandle armorSObj = getInstance(armorInstance);
if (!armorSObj)
{
armorSObj = instanciateClass("C_ITEM", armorInstance, {});
}
ScriptObject& armor = mScriptObjects.get(armorSObj);
bodyMesh = armor.stringValue("VISUAL_CHANGE");
}
HCharacter character = popCharacterInstance();
HVisualCharacter characterVisual = character->SO()->getComponent<VisualCharacter>();
bs::StringUtil::toUpperCase(bodyMesh);
characterVisual->setBodyMesh(bodyMesh, bodyTexIndex, bodyTexColor);
bs::StringUtil::toUpperCase(headMesh);
characterVisual->setHeadMesh(headMesh, headTexIndex, teethTexIndex);
}
void DaedalusVMForGameWorld::external_AI_GotoWaypoint()
{
bs::String waypoint = popStringValue();
HCharacter self = popCharacterInstance();
bs::StringUtil::toUpperCase(waypoint);
auto eventQueue = self->SO()->getComponent<CharacterEventQueue>();
eventQueue->pushGotoObject(mWorld->findObjectByName(waypoint));
}
void DaedalusVMForGameWorld::external_AI_GotoFreepoint()
{
bs::String freepoint = popStringValue();
HCharacter self = popCharacterInstance();
bs::StringUtil::toUpperCase(freepoint);
auto eventQueue = self->SO()->getComponent<CharacterEventQueue>();
eventQueue->pushGotoObject(mWorld->findObjectByName(freepoint));
}
void DaedalusVMForGameWorld::external_AI_GotoNextFreepoint()
{
bs::String freepointName = popStringValue();
HCharacter self = popCharacterInstance();
bs::StringUtil::toUpperCase(freepointName);
auto eventQueue = self->SO()->getComponent<CharacterEventQueue>();
const auto& at = self->SO()->getTransform().pos();
HFreepoint freepoint =
mWorld->waynet()->findClosestFreepointTo(freepointName, at).secondClosest;
eventQueue->pushGotoObject(freepoint->SO());
}
void DaedalusVMForGameWorld::external_AI_GotoNpc()
{
HCharacter other = popCharacterInstance();
HCharacter self = popCharacterInstance();
auto eventQueue = self->SO()->getComponent<CharacterEventQueue>();
eventQueue->pushGotoObject(other->SO());
}
void DaedalusVMForGameWorld::external_TA_Min()
{
bs::String waypoint = popStringValue();
SymbolIndex action =
popIntValue(); // This does not push onto the function stack for some reason
bs::INT32 stop_m = popIntValue();
bs::INT32 stop_h = popIntValue();
bs::INT32 start_m = popIntValue();
bs::INT32 start_h = popIntValue();
HCharacter self = popCharacterInstance();
bs::StringUtil::toUpperCase(waypoint);
AI::ScriptState::RoutineTask task;
task.hoursStart = start_h;
task.hoursEnd = stop_h;
task.minutesStart = start_m;
task.minutesEnd = stop_m;
task.waypoint = waypoint;
if (action != SYMBOL_INDEX_INVALID)
{
task.scriptFunction = scriptSymbols().getSymbolName(action);
}
auto eventQueue = self->SO()->getComponent<CharacterEventQueue>();
eventQueue->insertRoutineTask(task);
}
void DaedalusVMForGameWorld::external_NPC_ExchangeRoutine()
{
bs::String routineName = popStringValue();
HCharacter self = popCharacterInstance();
auto eventQueue = self->SO()->getComponent<CharacterEventQueue>();
bs::StringUtil::toUpperCase(routineName);
self->setDailyRoutine(routineName);
eventQueue->reinitRoutine();
}
void DaedalusVMForGameWorld::external_AI_SetWalkMode()
{
bs::INT32 walkModeIndex = popIntValue();
HCharacter self = popCharacterInstance();
AI::WalkMode realWalkMode;
switch (walkModeIndex)
{
case 0:
realWalkMode = AI::WalkMode::Run;
break;
case 1:
realWalkMode = AI::WalkMode::Walk;
break;
case 2:
realWalkMode = AI::WalkMode::Sneak;
break;
case 3:
realWalkMode = AI::WalkMode::Water;
break;
case 4:
realWalkMode = AI::WalkMode::Swim;
break;
case 5:
realWalkMode = AI::WalkMode::Dive;
break;
default:
REGOTH_THROW(InvalidParametersException, "Invalid Walk-Mode!");
}
auto eventQueue = self->SO()->getComponent<CharacterEventQueue>();
eventQueue->pushSetWalkMode(realWalkMode);
}
void DaedalusVMForGameWorld::external_AI_Wait()
{
float seconds = popFloatValue();
HCharacter self = popCharacterInstance();
auto eventQueue = self->SO()->getComponent<CharacterEventQueue>();
eventQueue->pushWait(seconds);
}
void DaedalusVMForGameWorld::external_AI_StartState()
{
bs::String waypoint = popStringValue();
bs::INT32 endOldState = popIntValue();
bs::INT32 stateFnIndex = popIntValue();
HCharacter self = popCharacterInstance();
const auto& functionSym = scriptSymbols().getSymbol<SymbolScriptFunction>(stateFnIndex);
auto eventQueue = self->SO()->getComponent<CharacterEventQueue>();
if (endOldState != 0)
{
// End old state gracefully
eventQueue->pushStartScriptState(functionSym.name, waypoint, other(), victim());
}
else
{
// Interrupt old state
eventQueue->pushInterruptAndStartScriptState(functionSym.name, waypoint, other(), victim());
}
}
void DaedalusVMForGameWorld::external_AI_PlayAnimation()
{
bs::String animation = popStringValue();
HCharacter self = popCharacterInstance();
auto eventQueue = self->SO()->getComponent<CharacterEventQueue>();
eventQueue->pushPlayAnimation(animation);
}
void DaedalusVMForGameWorld::external_Npc_GetNearestWP()
{
HCharacter self = popCharacterInstance();
mStack.pushString(self->getNearestWaypoint());
}
void DaedalusVMForGameWorld::external_Npc_GetNextWP()
{
HCharacter self = popCharacterInstance();
mStack.pushString(self->getNextWaypoint());
}
void DaedalusVMForGameWorld::external_Npc_GetDistToWP()
{
bs::String waypoint = popStringValue();
HCharacter self = popCharacterInstance();
float distanceMeters = self->getDistanceToWaypoint(waypoint);
if (distanceMeters < 0)
{
mStack.pushInt(INT32_MAX);
}
else
{
mStack.pushInt(distanceMeters * 100);
}
}
void DaedalusVMForGameWorld::external_Npc_GetDistToNpc()
{
HCharacter other = popCharacterInstance();
HCharacter self = popCharacterInstance();
// This is sometimes used with Npc_DetectNpc() which is supposed to set
// `other`. If that doesn't work we'll end up with an invalid handle here.
if (!other)
{
mStack.pushInt(INT32_MAX);
}
else
{
mStack.pushInt(self->getDistanceToObject(other->SO()) * 100);
}
}
void DaedalusVMForGameWorld::external_Npc_GetDistToItem()
{
HItem item = popItemInstance();
HCharacter self = popCharacterInstance();
mStack.pushInt(self->getDistanceToObject(item->SO()) * 100);
}
void DaedalusVMForGameWorld::external_Npc_GetDistToPlayer()
{
HCharacter self = popCharacterInstance();
// I hope they don't mean the player controlled character but the hero.
// FIXME: Clarify, does this is supposed to check the distance to the hero?
// Might as well fix this if we can easily get the reference to the player
// controlled character here. For normal gameplay using the hero should work though.
mStack.pushInt(self->getDistanceToHero() * 100);
}
void DaedalusVMForGameWorld::external_Npc_IsNear()
{
HCharacter other = popCharacterInstance();
HCharacter self = popCharacterInstance();
bool isNear = self->isNearCharacter(other);
mStack.pushInt(isNear ? 1 : 0);
}
void DaedalusVMForGameWorld::external_Npc_SetToFistMode()
{
HCharacter self = popCharacterInstance();
auto eventQueue = self->SO()->getComponent<CharacterEventQueue>();
eventQueue->pushGoToFistModeImmediate();
}
void DaedalusVMForGameWorld::external_Npc_KnowsInfo()
{
bs::INT32 infoSymbolIndex = popIntValue();
HCharacter self = popCharacterInstance();
const bs::String& infoName = scriptSymbols().getSymbolName(infoSymbolIndex);
auto information = self->SO()->getComponent<StoryInformation>();
if (information->knowsInfo(infoName))
{
mStack.pushInt(1);
}
else
{
mStack.pushInt(0);
}
}
void DaedalusVMForGameWorld::external_Npc_RefuseTalk()
{
HCharacter self = popCharacterInstance();
REGOTH_LOG(Warning, Uncategorized, "[External] Using external stub: NPC_RefuseTalk");
mStack.pushInt(0);
}
void DaedalusVMForGameWorld::external_Npc_GetStateTime()
{
HCharacter self = popCharacterInstance();
auto eventQueue = self->SO()->getComponent<CharacterEventQueue>();
// Scripts expect this value to be rounded down
mStack.pushInt((bs::INT32)eventQueue->getCurrentStateRunningTime());
}
void DaedalusVMForGameWorld::external_Npc_Percenable()
{
HCharacter self = popCharacterInstance();
}
void DaedalusVMForGameWorld::external_Npc_GetBodyState()
{
HCharacter self = popCharacterInstance();
// TODO: Implement this. There is no "stub"-debug log here because the function
// is called so often and it would spam the terminal.
mStack.pushInt(0);
}
void DaedalusVMForGameWorld::external_InfoManager_HasFinished()
{
// REGOTH_LOG(Warning, Uncategorized, "[External] Using external stub:
// InfoManager_HasFinished");
if (gGameplayUI()->isDialogueInProgress())
{
mStack.pushInt(0);
}
else
{
mStack.pushInt(1);
}
}
void DaedalusVMForGameWorld::external_AI_ProcessInfos()
{
HCharacter self = popCharacterInstance();
auto storyInfo = self->SO()->getComponent<StoryInformation>();
storyInfo->startDialogueWith(other());
}
void DaedalusVMForGameWorld::external_AI_StopProcessInfos()
{
HCharacter self = popCharacterInstance();
auto storyInfo = self->SO()->getComponent<StoryInformation>();
storyInfo->stopDialogueWith(other());
}
void DaedalusVMForGameWorld::external_NPC_EquipItem()
{
bs::String instance = popStringValue();
HCharacter character = popCharacterInstance();
character->equipItem(instance);
}
void DaedalusVMForGameWorld::external_NPC_CreateInventoryItems()
{
bs::INT32 num = popIntValue();
bs::INT32 instance = popIntValue();
HCharacter character = popCharacterInstance();
const bs::String& instanceName = scriptSymbols().getSymbolName(instance);
auto inventory = character->SO()->getComponent<Inventory>();
inventory->giveItem(instanceName, num);
}
void DaedalusVMForGameWorld::external_NPC_CreateInventoryItem()
{
bs::INT32 instance = popIntValue();
HCharacter character = popCharacterInstance();
const bs::String& instanceName = scriptSymbols().getSymbolName(instance);
auto inventory = character->SO()->getComponent<Inventory>();
inventory->giveItem(instanceName);
}
void DaedalusVMForGameWorld::external_Npc_HasItems()
{
bs::INT32 instance = popIntValue();
HCharacter character = popCharacterInstance();
const bs::String& instanceName = scriptSymbols().getSymbolName(instance);
auto inventory = character->SO()->getComponent<Inventory>();
if (inventory->hasItem(instanceName))
{
mStack.pushInt(1);
}
else
{
mStack.pushInt(0);
}
}
void DaedalusVMForGameWorld::external_Npc_GetInvItemBySlot()
{
bs::INT32 slotNumber = popIntValue();
bs::INT32 category = popIntValue();
HCharacter character = popCharacterInstance();
REGOTH_LOG(Warning, Uncategorized, "[External] Using external stub: Npc_GetInvItemBySlot");
}
void DaedalusVMForGameWorld::external_Npc_RemoveInvItem()
{
bs::INT32 instance = popIntValue();
HCharacter character = popCharacterInstance();
const bs::String& instanceName = scriptSymbols().getSymbolName(instance);
auto inventory = character->SO()->getComponent<Inventory>();
if (inventory->hasItem(instanceName))
{
inventory->removeItem(instanceName);
}
}
void DaedalusVMForGameWorld::external_Npc_RemoveInvItems()
{
bs::INT32 count = popIntValue();
bs::INT32 instance = popIntValue();
HCharacter character = popCharacterInstance();
const bs::String& instanceName = scriptSymbols().getSymbolName(instance);
auto inventory = character->SO()->getComponent<Inventory>();
if (inventory->hasItem(instanceName))
{
bs::INT32 actualCount = inventory->itemCount(instanceName);
inventory->removeItem(instanceName, bs::Math::min(actualCount, count));
}
}
void DaedalusVMForGameWorld::external_AI_TurnToNpc()
{
HCharacter other = popCharacterInstance();
HCharacter self = popCharacterInstance();
// Check needed, `other` was seen to be invalid in G1 (Oldcamp)
if (other)
{
auto eventQueue = self->SO()->getComponent<CharacterEventQueue>();
eventQueue->pushTurnToObject(other->SO());
}
}
void DaedalusVMForGameWorld::external_AI_TurnAway()
{
HCharacter other = popCharacterInstance();
HCharacter self = popCharacterInstance();
// Check needed, `other` was seen to be invalid in G1 (Oldcamp)
if (other)
{
auto eventQueue = self->SO()->getComponent<CharacterEventQueue>();
eventQueue->pushTurnAwayFromObject(other->SO());
}
}
void DaedalusVMForGameWorld::script_PrintPlus(const bs::String& text)
{
mStack.pushString(text);
executeScriptFunction("PrintPlus");
}
void DaedalusVMForGameWorld::createAllInformationInstances()
{
bs::Vector<SymbolIndex> instanceSymbols =
Queries::findAllInstancesOfClass(scriptSymbols(), "C_INFO");
bs::Vector<ScriptObjectHandle> instances;
for (SymbolIndex s : instanceSymbols)
{
instances.push_back(instanciateClass("C_INFO", s, {}));
}
bs::Vector<bs::UINT32> symbolIndices;
symbolIndices.reserve(instances.size());
for (ScriptObjectHandle h : instances)
{
symbolIndices.push_back(scriptObjects().get(h).intValue("NPC"));
}
for (bs::UINT32 i = 0; i < (bs::UINT32)instances.size(); i++)
{
SymbolIndex npcSymbol = symbolIndices[i];
ScriptObjectHandle infoHandle = instances[i];
mInformationInstancesByNpcs[npcSymbol].push_back(infoHandle);
}
}
const bs::Vector<ScriptObjectHandle>& DaedalusVMForGameWorld::allInfosOfNpc(
const bs::String& instanceName) const
{
SymbolIndex npcInstance = scriptSymbolsConst().findIndexBySymbolName(instanceName);
if (mInformationInstancesByNpcs.empty())
{
REGOTH_THROW(InvalidStateException,
"createAllInformationInstances has not been called or failed!");
}
auto it = mInformationInstancesByNpcs.find(npcInstance);
// Some NPCs don't have anything to say, so they don't appear in this list.
if (it == mInformationInstancesByNpcs.end())
{
// It's okay to return this static empty vector here because the return value is const.
static bs::Vector<ScriptObjectHandle> s_empty = {};
return s_empty;
}
return it->second;
}
REGOTH_DEFINE_RTTI(DaedalusVMForGameWorld)
} // namespace Scripting
} // namespace REGoth
| 1 | 0.738916 | 1 | 0.738916 | game-dev | MEDIA | 0.924304 | game-dev | 0.716803 | 1 | 0.716803 |
go2hx/go2hx | 195,300 | tests/go_easy_jvm.md | # go_easy_jvm
## defer_aggregate
```go
// run
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
const p0exp = "foo"
const p1exp = 10101
const p2exp = 3030303
const p3exp = 505050505
const p4exp = 70707070707
//go:noinline
//go:registerparams
func callee(p0 string, p1 uint64, p2 uint64, p3 uint64, p4 uint64) {
if p0 != p0exp {
panic("bad p0")
}
if p1 != p1exp {
panic("bad p1")
}
if p2 != p2exp {
panic("bad p2")
}
if p3 != p3exp {
panic("bad p3")
}
if p4 != p4exp {
panic("bad p4")
}
defer func(p0 string, p2 uint64) {
if p0 != p0exp {
panic("defer bad p0")
}
if p1 != p1exp {
panic("defer bad p1")
}
if p2 != p2exp {
panic("defer bad p2")
}
}(p0, p2)
}
func main() {
callee(p0exp, p1exp, p2exp, p3exp, p4exp)
}
```
## defer_recover_results
```go
// run
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test that when a function recovers from a panic, it
// returns the correct results to the caller (in particular,
// setting the result registers correctly).
package main
type S struct {
x uint8
y uint16
z uint32
w float64
}
var a0, b0, c0, d0 = 10, "hello", S{1, 2, 3, 4}, [2]int{111, 222}
//go:noinline
//go:registerparams
func F() (a int, b string, _ int, c S, d [2]int) {
a, b, c, d = a0, b0, c0, d0
defer func() { recover() }()
panic("XXX")
return
}
func main() {
a1, b1, zero, c1, d1 := F()
if a1 != a0 || b1 != b0 || c1 != c0 || d1 != d0 || zero != 0 { // unnamed result gets zero value
panic("FAIL")
}
}
```
## method_wrapper
```go
// run
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type S int
type T struct {
a int
S
}
//go:noinline
func (s *S) M(a int, x [2]int, b float64, y [2]float64) (S, int, [2]int, float64, [2]float64) {
return *s, a, x, b, y
}
var s S = 42
var t = &T{S: s}
var fn = (*T).M // force a method wrapper
func main() {
a := 123
x := [2]int{456, 789}
b := 1.2
y := [2]float64{3.4, 5.6}
s1, a1, x1, b1, y1 := fn(t, a, x, b, y)
if a1 != a || x1 != x || b1 != b || y1 != y || s1 != s {
panic("FAIL")
}
}
```
## open_defer_1
```go
// run
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// For #45062, miscompilation of open defer of method invocation
package main
func main() {
var x, y, z int = -1, -2, -3
F(x, y, z)
}
//go:noinline
func F(x, y, z int) {
defer i.M(x, y, z)
defer func() { recover() }()
panic("XXX")
}
type T int
func (t *T) M(x, y, z int) {
if x == -1 && y == -2 && z == -3 {
return
}
println("FAIL: Expected -1, -2, -3, but x, y, z =", x, y, z)
}
var t T = 42
type I interface{ M(x, y, z int) }
var i I = &t
```
## result_regalloc
```go
// run
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Bug: in (*bb).d, the value to be returned was not allocated to
// a register that satisfies its register mask.
package main
type bb struct {
r float64
x []float64
}
//go:noinline
func B(r float64, x []float64) I {
return bb{r, x}
}
func (b bb) d() (int, int) {
if b.r == 0 {
return 0, len(b.x)
}
return len(b.x), len(b.x)
}
type I interface { d() (int, int) }
func D(r I) (int, int) { return r.d() }
//go:noinline
func F() (int, int) {
r := float64(1)
x := []float64{0, 1, 2}
b := B(r, x)
return D(b)
}
func main() {
x, y := F()
if x != 3 || y != 3 {
panic("FAIL")
}
}
```
## store_reg_args
```go
// run
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// When the function Store an Arg and also use it in another place,
// be sure not to generate duplicated OpArgXXXReg values, which confuses
// the register allocator.
package main
//go:noinline
//go:registerparams
func F(x, y float32) {
if x < 0 {
panic("FAIL")
}
g = [4]float32{x, y, x, y}
}
var g [4]float32
func main() {
F(1, 2)
if g[0] != 1 || g[1] != 2 || g[2] != 1 || g[3] != 2 {
panic("FAIL")
}
}
```
## bigmap
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Internally a map holds elements in up to 255 bytes of key+value.
// When key or value or both are too large, it uses pointers to key+value
// instead. Test all the combinations.
package main
func seq(x, y int) [1000]byte {
var r [1000]byte
for i := 0; i < len(r); i++ {
r[i] = byte(x + i*y)
}
return r
}
func cmp(x, y [1000]byte) {
for i := 0; i < len(x); i++ {
if x[i] != y[i] {
panic("BUG mismatch")
}
}
}
func main() {
m := make(map[int][1000]byte)
m[1] = seq(11, 13)
m[2] = seq(2, 9)
m[3] = seq(3, 17)
cmp(m[1], seq(11, 13))
cmp(m[2], seq(2, 9))
cmp(m[3], seq(3, 17))
{
type T [1]byte
type V [1]byte
m := make(map[T]V)
m[T{}] = V{1}
m[T{1}] = V{2}
if x, y := m[T{}][0], m[T{1}][0]; x != 1 || y != 2 {
println(x, y)
panic("bad map")
}
}
{
type T [100]byte
type V [1]byte
m := make(map[T]V)
m[T{}] = V{1}
m[T{1}] = V{2}
if x, y := m[T{}][0], m[T{1}][0]; x != 1 || y != 2 {
println(x, y)
panic("bad map")
}
}
{
type T [1]byte
type V [100]byte
m := make(map[T]V)
m[T{}] = V{1}
m[T{1}] = V{2}
if x, y := m[T{}][0], m[T{1}][0]; x != 1 || y != 2 {
println(x, y)
panic("bad map")
}
}
{
type T [1000]byte
type V [1]byte
m := make(map[T]V)
m[T{}] = V{1}
m[T{1}] = V{2}
if x, y := m[T{}][0], m[T{1}][0]; x != 1 || y != 2 {
println(x, y)
panic("bad map")
}
}
{
type T [1]byte
type V [1000]byte
m := make(map[T]V)
m[T{}] = V{1}
m[T{1}] = V{2}
if x, y := m[T{}][0], m[T{1}][0]; x != 1 || y != 2 {
println(x, y)
panic("bad map")
}
}
{
type T [1000]byte
type V [1000]byte
m := make(map[T]V)
m[T{}] = V{1}
m[T{1}] = V{2}
if x, y := m[T{}][0], m[T{1}][0]; x != 1 || y != 2 {
println(x, y)
panic("bad map")
}
}
{
type T [200]byte
type V [1]byte
m := make(map[T]V)
m[T{}] = V{1}
m[T{1}] = V{2}
if x, y := m[T{}][0], m[T{1}][0]; x != 1 || y != 2 {
println(x, y)
panic("bad map")
}
}
{
type T [1]byte
type V [200]byte
m := make(map[T]V)
m[T{}] = V{1}
m[T{1}] = V{2}
if x, y := m[T{}][0], m[T{1}][0]; x != 1 || y != 2 {
println(x, y)
panic("bad map")
}
}
{
type T [200]byte
type V [200]byte
m := make(map[T]V)
m[T{}] = V{1}
m[T{1}] = V{2}
if x, y := m[T{}][0], m[T{1}][0]; x != 1 || y != 2 {
println(x, y)
panic("bad map")
}
}
}
```
## closure2
```go
// run
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Check that these do not use "by value" capturing,
// because changes are made to the value during the closure.
package main
var never bool
func main() {
{
type X struct {
v int
}
var x X
func() {
x.v++
}()
if x.v != 1 {
panic("x.v != 1")
}
type Y struct {
X
}
var y Y
func() {
y.v = 1
}()
if y.v != 1 {
panic("y.v != 1")
}
}
{
type Z struct {
a [3]byte
}
var z Z
func() {
i := 0
for z.a[1] = 1; i < 10; i++ {
}
}()
if z.a[1] != 1 {
panic("z.a[1] != 1")
}
}
{
w := 0
tmp := 0
f := func() {
if w != 1 {
panic("w != 1")
}
}
func() {
tmp = w // force capture of w, but do not write to it yet
_ = tmp
func() {
func() {
w++ // write in a nested closure
}()
}()
}()
f()
}
{
var g func() int
var i int
for i = range [2]int{} {
if i == 0 {
g = func() int {
return i // test that we capture by ref here, i is mutated on every interaction
}
}
}
if g() != 1 {
panic("g() != 1")
}
}
{
var g func() int
q := 0
for range [2]int{} {
q++
g = func() int {
return q // test that we capture by ref here
// q++ must on a different decldepth than q declaration
}
}
if g() != 2 {
panic("g() != 2")
}
}
{
var g func() int
var a [2]int
q := 0
for a[func() int {
q++
return 0
}()] = range [2]int{} {
g = func() int {
return q // test that we capture by ref here
// q++ must on a different decldepth than q declaration
}
}
if g() != 2 {
panic("g() != 2")
}
}
{
var g func() int
q := 0
q, g = 1, func() int { return q }
if never {
g = func() int { return 2 }
}
if g() != 1 {
panic("g() != 1")
}
}
}
```
## closure4
```go
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Check that calling a nil func causes a proper panic.
package main
func main() {
defer func() {
err := recover()
if err == nil {
panic("panic expected")
}
}()
var f func()
f()
}
```
## convert4
```go
// run
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test conversion from slice to array pointer.
package main
func wantPanic(fn func(), s string) {
defer func() {
err := recover()
if err == nil {
panic("expected panic")
}
if got := err.(error).Error(); got != s {
panic("expected panic " + s + " got " + got)
}
}()
fn()
}
func main() {
s := make([]byte, 8, 10)
for i := range s {
s[i] = byte(i)
}
if p := (*[8]byte)(s); &p[0] != &s[0] {
panic("*[8]byte conversion failed")
}
if [8]byte(s) != *(*[8]byte)(s) {
panic("[8]byte conversion failed")
}
wantPanic(
func() {
_ = (*[9]byte)(s)
},
"runtime error: cannot convert slice with length 8 to array or pointer to array with length 9",
)
wantPanic(
func() {
_ = [9]byte(s)
},
"runtime error: cannot convert slice with length 8 to array or pointer to array with length 9",
)
var n []byte
if p := (*[0]byte)(n); p != nil {
panic("nil slice converted to *[0]byte should be nil")
}
_ = [0]byte(n)
z := make([]byte, 0)
if p := (*[0]byte)(z); p == nil {
panic("empty slice converted to *[0]byte should be non-nil")
}
_ = [0]byte(z)
var p *[]byte
wantPanic(
func() {
_ = [0]byte(*p) // evaluating *p should still panic
},
"runtime error: invalid memory address or nil pointer dereference",
)
// Test with named types
type Slice []int
type Int4 [4]int
type PInt4 *[4]int
ii := make(Slice, 4)
if p := (*Int4)(ii); &p[0] != &ii[0] {
panic("*Int4 conversion failed")
}
if p := PInt4(ii); &p[0] != &ii[0] {
panic("PInt4 conversion failed")
}
}
// test static variable conversion
var (
ss = make([]string, 10)
s5 = (*[5]string)(ss)
s10 = (*[10]string)(ss)
ns []string
ns0 = (*[0]string)(ns)
zs = make([]string, 0)
zs0 = (*[0]string)(zs)
)
func init() {
if &ss[0] != &s5[0] {
panic("s5 conversion failed")
}
if &ss[0] != &s10[0] {
panic("s5 conversion failed")
}
if ns0 != nil {
panic("ns0 should be nil")
}
if zs0 == nil {
panic("zs0 should not be nil")
}
}
```
## ddd
```go
// run
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test variadic functions and calls (dot-dot-dot).
package main
func sum(args ...int) int {
s := 0
for _, v := range args {
s += v
}
return s
}
func sumC(args ...int) int { return func() int { return sum(args...) }() }
var sumD = func(args ...int) int { return sum(args...) }
var sumE = func() func(...int) int { return func(args ...int) int { return sum(args...) } }()
var sumF = func(args ...int) func() int { return func() int { return sum(args...) } }
func sumA(args []int) int {
s := 0
for _, v := range args {
s += v
}
return s
}
func sumB(args []int) int { return sum(args...) }
func sum2(args ...int) int { return 2 * sum(args...) }
func sum3(args ...int) int { return 3 * sumA(args) }
func sum4(args ...int) int { return 4 * sumB(args) }
func intersum(args ...interface{}) int {
s := 0
for _, v := range args {
s += v.(int)
}
return s
}
type T []T
func ln(args ...T) int { return len(args) }
func ln2(args ...T) int { return 2 * ln(args...) }
func (*T) Sum(args ...int) int { return sum(args...) }
type U struct {
*T
}
type I interface {
Sum(...int) int
}
func main() {
if x := sum(1, 2, 3); x != 6 {
println("sum 6", x)
panic("fail")
}
if x := sum(); x != 0 {
println("sum 0", x)
panic("fail")
}
if x := sum(10); x != 10 {
println("sum 10", x)
panic("fail")
}
if x := sum(1, 8); x != 9 {
println("sum 9", x)
panic("fail")
}
if x := sumC(4, 5, 6); x != 15 {
println("sumC 15", x)
panic("fail")
}
if x := sumD(4, 5, 7); x != 16 {
println("sumD 16", x)
panic("fail")
}
if x := sumE(4, 5, 8); x != 17 {
println("sumE 17", x)
panic("fail")
}
if x := sumF(4, 5, 9)(); x != 18 {
println("sumF 18", x)
panic("fail")
}
if x := sum2(1, 2, 3); x != 2*6 {
println("sum 6", x)
panic("fail")
}
if x := sum2(); x != 2*0 {
println("sum 0", x)
panic("fail")
}
if x := sum2(10); x != 2*10 {
println("sum 10", x)
panic("fail")
}
if x := sum2(1, 8); x != 2*9 {
println("sum 9", x)
panic("fail")
}
if x := sum3(1, 2, 3); x != 3*6 {
println("sum 6", x)
panic("fail")
}
if x := sum3(); x != 3*0 {
println("sum 0", x)
panic("fail")
}
if x := sum3(10); x != 3*10 {
println("sum 10", x)
panic("fail")
}
if x := sum3(1, 8); x != 3*9 {
println("sum 9", x)
panic("fail")
}
if x := sum4(1, 2, 3); x != 4*6 {
println("sum 6", x)
panic("fail")
}
if x := sum4(); x != 4*0 {
println("sum 0", x)
panic("fail")
}
if x := sum4(10); x != 4*10 {
println("sum 10", x)
panic("fail")
}
if x := sum4(1, 8); x != 4*9 {
println("sum 9", x)
panic("fail")
}
if x := intersum(1, 2, 3); x != 6 {
println("intersum 6", x)
panic("fail")
}
if x := intersum(); x != 0 {
println("intersum 0", x)
panic("fail")
}
if x := intersum(10); x != 10 {
println("intersum 10", x)
panic("fail")
}
if x := intersum(1, 8); x != 9 {
println("intersum 9", x)
panic("fail")
}
if x := ln(nil, nil, nil); x != 3 {
println("ln 3", x)
panic("fail")
}
if x := ln([]T{}); x != 1 {
println("ln 1", x)
panic("fail")
}
if x := ln2(nil, nil, nil); x != 2*3 {
println("ln2 3", x)
panic("fail")
}
if x := ln2([]T{}); x != 2*1 {
println("ln2 1", x)
panic("fail")
}
if x := ((*T)(nil)).Sum(1, 3, 5, 7); x != 16 {
println("(*T)(nil).Sum", x)
panic("fail")
}
if x := (*T).Sum(nil, 1, 3, 5, 6); x != 15 {
println("(*T).Sum", x)
panic("fail")
}
if x := (&U{}).Sum(1, 3, 5, 5); x != 14 {
println("(&U{}).Sum", x)
panic("fail")
}
var u U
if x := u.Sum(1, 3, 5, 4); x != 13 {
println("u.Sum", x)
panic("fail")
}
if x := (&u).Sum(1, 3, 5, 3); x != 12 {
println("(&u).Sum", x)
panic("fail")
}
var i interface {
Sum(...int) int
} = &u
if x := i.Sum(2, 3, 5, 7); x != 17 {
println("i(=&u).Sum", x)
panic("fail")
}
i = u
if x := i.Sum(2, 3, 5, 6); x != 16 {
println("i(=u).Sum", x)
panic("fail")
}
var s struct {
I
}
s.I = &u
if x := s.Sum(2, 3, 5, 8); x != 18 {
println("s{&u}.Sum", x)
panic("fail")
}
if x := (*U).Sum(&U{}, 1, 3, 5, 2); x != 11 {
println("(*U).Sum", x)
panic("fail")
}
if x := U.Sum(U{}, 1, 3, 5, 1); x != 10 {
println("U.Sum", x)
panic("fail")
}
}
```
## decl
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test correct short declarations and redeclarations.
package main
func f1() int { return 1 }
func f2() (float32, int) { return 1, 2 }
func f3() (float32, int, string) { return 1, 2, "3" }
func x() (s string) {
a, b, s := f3()
_, _ = a, b
return // tests that result var is in scope for redeclaration
}
func main() {
i, f, s := f3()
j, f := f2() // redeclare f
k := f1()
m, g, s := f3()
m, h, s := f3()
{
// new block should be ok.
i, f, s := f3()
j, f := f2() // redeclare f
k := f1()
m, g, s := f3()
m, h, s := f3()
_, _, _, _, _, _, _, _, _ = i, f, s, j, k, m, g, s, h
}
if y := x(); y != "3" {
println("x() failed", y)
panic("fail")
}
_, _, _, _, _, _, _, _, _ = i, f, s, j, k, m, g, s, h
}
```
## defernil
```go
// run
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Check that deferring a nil function causes a proper
// panic when the deferred function is invoked (not
// when the function is deferred).
// See Issue #8047 and #34926.
package main
var x = 0
func main() {
defer func() {
err := recover()
if err == nil {
panic("did not panic")
}
if x != 1 {
panic("FAIL")
}
}()
f()
}
func f() {
var nilf func()
defer nilf()
x = 1
}
```
## escape3
```go
// run
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test the run-time behavior of escape analysis-related optimizations.
package main
func main() {
test1()
}
func test1() {
check1(0)
check1(1)
check1(2)
}
type T1 struct {
X, Y, Z int
}
func f() int {
return 1
}
func check1(pass int) T1 {
v := []T1{{X: f(), Z: f()}}
if v[0].Y != 0 {
panic("nonzero init")
}
v[0].Y = pass
return v[0]
}
```
## bug017
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
var s2 string = "\a\b\f\n\r\t\v"; // \r is miscompiled
_ = s2;
}
/*
main.go.c: In function ‘main_main’:
main.go.c:20: error: missing terminating " character
main.go.c:21: error: missing terminating " character
main.go.c:24: error: ‘def’ undeclared (first use in this function)
main.go.c:24: error: (Each undeclared identifier is reported only once
main.go.c:24: error: for each function it appears in.)
main.go.c:24: error: syntax error before ‘def’
main.go.c:24: error: missing terminating " character
main.go.c:25: warning: excess elements in struct initializer
main.go.c:25: warning: (near initialization for ‘slit’)
main.go.c:36: error: syntax error at end of input
*/
```
## bug021
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
s1 := "hi";
s2 := "ho";
s1 += s2;
}
```
## bug024
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
var i int;
i = '\'';
i = '\\';
var s string;
s = "\"";
_, _ = i, s;
}
/*
bug.go:5: unknown escape sequence: '
bug.go:6: unknown escape sequence: \
bug.go:8: unknown escape sequence: "
*/
```
## bug031
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
prog := "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"+
"xxxxxxxxxx"+
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"+
"xxxxxxxxxxxxxxxxxxxxxx"+
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"+
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"+
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"+
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"+
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"+
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"+
"xxxxxxxxxxxxxxxxxxx"+
"xxxxxx"+
"xxxxxxxxxxxxxxxxxxxx"+
"xxxxxxxx"+
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
;
_ = prog;
}
/* Segmentation fault */
```
## bug045
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type T struct {
i int
}
func main() {
var ta []*T;
ta = new([1]*T)[0:];
ta[0] = nil;
}
/*
bug045.go:13: fatal error: goc: exit 1
*/
```
## bug047
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
type T struct {
s string
f float64
}
var s string = "hello"
var f float64 = 0.2
t := T{s, f}
type M map[int]int
m0 := M{7: 8}
_, _ = t, m0
}
```
## bug052
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
c := 10;
d := 7;
var x [10]int;
i := 0;
/* this works:
q := c/d;
x[i] = q;
*/
// this doesn't:
x[i] = c/d; // BUG segmentation fault
}
```
## bug054
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type Element interface {
}
type Vector struct {
elem []Element;
}
func (v *Vector) At(i int) Element {
return v.elem[i];
}
type TStruct struct {
name string;
fields *Vector;
}
func (s *TStruct) field(i int) *TStruct {
return s.fields.At(i).(*TStruct);
}
func main() {
v := new(Vector);
v.elem = make([]Element, 10);
t := new(TStruct);
t.name = "hi";
v.elem[0] = t;
s := new(TStruct);
s.name = "foo";
s.fields = v;
if s.field(0).name != "hi" {
panic("bad name")
}
}
```
## bug058
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type Box struct {};
var m map[string] *Box;
func main() {
m := make(map[string] *Box);
s := "foo";
var x *Box = nil;
m[s] = x;
}
/*
bug058.go:9: illegal types for operand: INDEX
(MAP[<string>*STRING]*<Box>{})
(<string>*STRING)
*/
```
## bug061
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
var s string;
s = "0000000000000000000000000000000000000000000000000000000000"[0:7];
_ = s;
}
/*
uetli:~/Source/go1/test/bugs gri$ 6g bug061.go
Bus error
*/
```
## bug075
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type T struct { m map[int]int }
func main() {
t := new(T);
t.m = make(map[int]int);
var x int;
var ok bool;
x, ok = t.m[0]; //bug075.go:11: bad shape across assignment - cr=1 cl=2
_, _ = x, ok;
}
```
## bug092
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
var a [1000] int64; // this alone works
var b [10000] int64; // this causes a runtime crash
_, _ = a, b;
}
/*
uetli:~/Source/go1/test/bugs gri$ 6g bug092.go && 6l bug092.6 && 6.out
Illegal instruction
gri: array size matters, possibly related to stack overflow check?
*/
```
## bug097
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type A []int
func main() {
var a [3]A
for i := 0; i < 3; i++ {
a[i] = A{i}
}
if a[0][0] != 0 {
panic("fail a[0][0]")
}
if a[1][0] != 1 {
panic("fail a[1][0]")
}
if a[2][0] != 2 {
panic("fail a[2][0]")
}
}
/*
uetli:~/Source/go1/test/bugs gri$ 6g bug097.go && 6l bug097.6 && 6.out
panic on line 342 PC=0x13c2
0x13c2?zi
main·main(1, 0, 1606416416, ...)
main·main(0x1, 0x7fff5fbff820, 0x0, ...)
SIGTRAP: trace trap
Faulting address: 0x4558
pc: 0x4558
0x4558?zi
sys·Breakpoint(40960, 0, 45128, ...)
sys·Breakpoint(0xa000, 0xb048, 0xa000, ...)
0x156a?zi
sys·panicl(342, 0, 0, ...)
sys·panicl(0x156, 0x300000000, 0xb024, ...)
0x13c2?zi
main·main(1, 0, 1606416416, ...)
main·main(0x1, 0x7fff5fbff820, 0x0, ...)
*/
/* An array composite literal needs to be created freshly every time.
It is a "construction" of an array after all. If I pass the address
of the array to some function, it may store it globally. Same applies
to struct literals.
*/
```
## bug101
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
var a = []int { 1, 2, 3 }
func main() {
if len(a) != 3 { panic("array len") }
// print(a[0], " ", a[1], " ", a[2], "\n")
if a[0] != 1 || a[1] != 2 || a[2] != 3 { panic("array contents") }
}
```
## bug102
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
var b [0]byte
s := string(b[0:]) // out of bounds trap
if s != "" {
panic("bad convert")
}
var b1 = [5]byte{'h', 'e', 'l', 'l', 'o'}
if string(b1[0:]) != "hello" {
panic("bad convert 1")
}
var b2 = make([]byte, 5)
for i := 0; i < 5; i++ {
b2[i] = b1[i]
}
if string(b2) != "hello" {
panic("bad convert 2")
}
}
```
## bug119
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func foo(a []int) int {
return a[0] // this seems to do the wrong thing
}
func main() {
a := &[]int{12}
if x := (*a)[0]; x != 12 {
panic(2)
}
if x := foo(*a); x != 12 {
// fails (x is incorrect)
panic(3)
}
}
/*
uetli:~/Source/go1/test/bugs gri$ 6go bug119
3 70160
panic on line 83 PC=0x14d6
0x14d6?zi
main·main(23659, 0, 1, ...)
main·main(0x5c6b, 0x1, 0x7fff5fbff830, ...)
0x52bb?zi
mainstart(1, 0, 1606416432, ...)
mainstart(0x1, 0x7fff5fbff830, 0x0, ...)
uetli:~/Source/go1/test/bugs gri$
*/
```
## bug148
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type T struct {a, b int};
func println(x, y int) { }
func f(x interface{}) interface{} {
type T struct {a, b int};
if x == nil {
return T{2, 3};
}
t := x.(T);
println(t.a, t.b);
return x;
}
func main() {
inner_T := f(nil);
f(inner_T);
shouldPanic(p1)
}
func p1() {
outer_T := T{5, 7};
f(outer_T);
}
func shouldPanic(f func()) {
defer func() {
if recover() == nil {
panic("function should panic")
}
}()
f()
}
/*
This prints:
2 3
5 7
but it should crash: The type assertion on line 18 should fail
for the 2nd call to f with outer_T.
*/
```
## bug1515
```go
// run
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
const (
joao = "João"
jose = "José"
)
func main() {
s1 := joao
s2 := jose
if (s1 < s2) != (joao < jose) {
panic("unequal")
}
}
```
## bug152
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
s := 0;
for _, v := range []int{1} {
s += v;
}
if s != 1 {
println("BUG: s =", s);
}
}
```
## bug168
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
var g byte = 123
var f *byte = &g
var b = make([]byte, 5)
func main() {
b[0:1][0] = *f
if b[0] != 123 {
println("want 123 got", b[0])
panic("fail")
}
}
```
## bug194
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
var v1 = T1(1)
var v2 = T2{2}
var v3 = T3{0: 3, 1: 4}
var v4 = T4{0: 5, 1: 6}
var v5 = T5{0: 7, 1: 8}
var v6 = T2{f: 9}
var v7 = T4{f: 10}
var v8 = T5{f: 11}
var pf func(T1)
func main() {
if v1 != 1 || v2.f != 2 || v3[0] != 3 || v3[1] != 4 ||
v4[0] != 5 || v4[1] != 6 || v5[0] != 7 || v5[1] != 8 ||
v6.f != 9 || v7[0] != 10 || v8[0] != 11 {
panic("fail")
}
}
type T1 int
type T2 struct {
f int
}
type T3 []int
type T4 [2]int
type T5 map[int]int
const f = 0
```
## bug199
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type S struct {
a []int
}
var s = &S{make([]int, 10)}
func main() {
s.a[f()] = 1 // 6g used to call f twice here
}
var n int
func f() int {
if n++; n > 1 {
println("f twice")
panic("fail")
}
return 0
}
```
## bug202
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func f() {
v := [...]string{"a", "b"};
_ = v;
}
func main() {
f();
}
```
## bug203
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
var s [8]string
func
init() {
s = [...]string{ "now", "is", "the", "time", "to", "fix", "this", "bug"}
}
func
main() {
}
```
## bug204
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
nchar := 0
a := []rune{'日', '本', '語', 0xFFFD}
for _, char := range "日本語\xc0" {
if nchar >= len(a) {
println("BUG")
break
}
if char != a[nchar] {
println("expected", a[nchar], "got", char)
println("BUG")
break
}
nchar++
}
}
```
## bug221
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// function call arg reordering was picking out 1 call that
// didn't need to be in a temporary, but it was picking
// out the first call instead of the last call.
// https://golang.org/issue/370
package main
var gen = 'a'
func f(n int) string {
s := string(gen) + string(n+'A'-1)
gen++
return s
}
func g(x, y string) string {
return x + y
}
func main() {
s := f(1) + f(2)
if s != "aAbB" {
println("BUG: bug221a: ", s)
panic("fail")
}
s = g(f(3), f(4))
if s != "cCdD" {
println("BUG: bug221b: ", s)
panic("fail")
}
s = f(5) + f(6) + f(7) + f(8) + f(9)
if s != "eEfFgGhHiI" {
println("BUG: bug221c: ", s)
panic("fail")
}
}
```
## bug227
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
var (
nf int
x, y, z = f(), f(), f()
m = map[string]string{"a": "A"}
a, aok = m["a"]
b, bok = m["b"]
)
func look(s string) (string, bool) {
x, ok := m[s]
return x, ok
}
func f() int {
nf++
return nf
}
func main() {
if nf != 3 || x != 1 || y != 2 || z != 3 {
println("nf=", nf, " x=", x, " y=", y)
panic("fail")
}
if a != "A" || aok != true || b != "" || bok != false {
println("a=", a, " aok=", aok, " b=", b, " bok=", bok)
panic("fail")
}
}
```
## bug236
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
var gen = 'a'
func f(n int) string {
s := string(gen) + string(n+'A'-1)
gen++
return s
}
func g(x, y string) string { return x + y }
var v1 = f(1) + f(2)
var v2 = g(f(3), f(4))
var v3 = f(5) + f(6) + f(7) + f(8) + f(9)
func main() {
gen = 'a'
if v1 != "aAbB" {
panic("BUG: bug236a")
}
if v2 != "cCdD" {
panic("BUG: bug236b")
}
if v3 != "eEfFgGhHiI" {
panic("BUG: bug236c")
}
switch "aAbB" {
case f(1) + f(2):
default:
panic("BUG: bug236d")
}
switch "cCdD" {
case g(f(3), f(4)):
default:
panic("BUG: bug236e")
}
switch "eEfFgGhHiI" {
case f(5) + f(6) + f(7) + f(8) + f(9):
default:
panic("BUG: bug236f")
}
}
```
## bug244
```go
// run
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
var nf int
var ng int
func f() (int, int, int) {
nf++
return 1, 2, 3
}
func g() int {
ng++
return 4
}
var x, y, z = f()
var m = make(map[int]int)
var v, ok = m[g()]
func main() {
if x != 1 || y != 2 || z != 3 || nf != 1 || v != 0 || ok != false || ng != 1 {
println("x=", x, " y=", y, " z=", z, " nf=", nf, " v=", v, " ok=", ok, " ng=", ng)
panic("fail")
}
}
```
## bug261
```go
// run
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
var n int
func f() int {
n++
return n
}
func main() {
x := []int{0,1,2,3,4,5,6,7,8,9,10}
n = 5
y := x[f():f()]
if len(y) != 1 || y[0] != 6 {
println("BUG bug261", len(y), y[0])
}
}
```
## bug263
```go
// run
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
data := make(map[int]string, 1)
data[0] = "hello, "
data[0] += "world!"
if data[0] != "hello, world!" {
panic("BUG: " + data[0])
}
}
```
## bug266
```go
// run
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func f() int {
defer func() {
recover()
}()
panic("oops")
}
func g() int {
return 12345
}
func main() {
g() // leave 12345 on stack
x := f()
if x != 0 {
panic(x)
}
}
```
## bug272
```go
// run
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// https://golang.org/issue/589
package main
func main() {
n := int64(100)
x := make([]int, n)
x[99] = 234;
z := x[n-1]
if z != 234 {
println("BUG")
}
n |= 1<<32
defer func() {
recover()
}()
z = x[n-1]
println("BUG2")
}
```
## bug286
```go
// run
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test case for issue 849.
package main
type I interface {
f()
}
var callee string
var error_ bool
type T int
func (t *T) f() { callee = "f" }
func (i *T) g() { callee = "g" }
// test1 and test2 are the same except that in the interface J
// the entries are swapped. test2 and test3 are the same except
// that in test3 the interface J is declared outside the function.
//
// Error: test2 calls g instead of f
func test1(x I) {
type J interface {
I
g()
}
x.(J).f()
if callee != "f" {
println("test1 called", callee)
error_ = true
}
}
func test2(x I) {
type J interface {
g()
I
}
x.(J).f()
if callee != "f" {
println("test2 called", callee)
error_ = true
}
}
type J interface {
g()
I
}
func test3(x I) {
x.(J).f()
if callee != "f" {
println("test3 called", callee)
error_ = true
}
}
func main() {
x := new(T)
test1(x)
test2(x)
test3(x)
if error_ {
panic("wrong method called")
}
}
/*
6g bug286.go && 6l bug286.6 && 6.out
test2 called g
panic: wrong method called
panic PC=0x24e040
runtime.panic+0x7c /home/gri/go1/src/pkg/runtime/proc.c:1012
runtime.panic(0x0, 0x24e0a0)
main.main+0xef /home/gri/go1/test/bugs/bug286.go:76
main.main()
mainstart+0xf /home/gri/go1/src/pkg/runtime/amd64/asm.s:60
mainstart()
goexit /home/gri/go1/src/pkg/runtime/proc.c:145
goexit()
*/
```
## bug293
```go
// run
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// https://golang.org/issue/846
package main
func x() (a int, b bool) {
defer func(){
a++
}()
a, b = y()
return
}
func x2() (a int, b bool) {
defer func(){
a++
}()
return y()
}
func y() (int, bool) {
return 4, false
}
func main() {
if a, _ := x(); a != 5 {
println("BUG", a)
}
if a, _ := x2(); a != 5 {
println("BUG", a)
}
}
```
## bug294
```go
// run
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// https://golang.org/issue/800
package main
var log string
type T int
func (t T) a(s string) T {
log += "a(" + s + ")"
return t
}
func (T) b(s string) string {
log += "b"
return s
}
type F func(s string) F
func a(s string) F {
log += "a(" + s + ")"
return F(a)
}
func b(s string) string {
log += "b"
return s
}
type I interface {
a(s string) I
b(s string) string
}
type T1 int
func (t T1) a(s string) I {
log += "a(" + s + ")"
return t
}
func (T1) b(s string) string {
log += "b"
return s
}
var ok = true
func bad() {
if !ok {
println("BUG")
ok = false
}
println(log)
}
func main() {
var t T
if t.a("1").a(t.b("2")); log != "a(1)ba(2)" {
bad()
}
log = ""
if a("3")(b("4"))(b("5")); log != "a(3)ba(4)ba(5)" {
bad()
}
log = ""
var i I = T1(0)
if i.a("6").a(i.b("7")).a(i.b("8")).a(i.b("9")); log != "a(6)ba(7)ba(8)ba(9)" {
bad()
}
}
```
## bug296
```go
// run
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type I interface {
m(a, b, c, d, e, f, g, h byte)
}
type Int8 int8
func (x Int8) m(a, b, c, d, e, f, g, h byte) {
check("Int8", int64(x), 0x01, a, b, c, d, e, f, g, h)
}
type Uint8 uint8
func (x Uint8) m(a, b, c, d, e, f, g, h byte) {
check("Uint8", int64(x), 0x01, a, b, c, d, e, f, g, h)
}
type Int16 int16
func (x Int16) m(a, b, c, d, e, f, g, h byte) {
check("Int16", int64(x), 0x0102, a, b, c, d, e, f, g, h)
}
type Uint16 uint16
func (x Uint16) m(a, b, c, d, e, f, g, h byte) {
check("Uint16", int64(x), 0x0102, a, b, c, d, e, f, g, h)
}
type Int32 int32
func (x Int32) m(a, b, c, d, e, f, g, h byte) {
check("Int32", int64(x), 0x01020304, a, b, c, d, e, f, g, h)
}
type Uint32 uint32
func (x Uint32) m(a, b, c, d, e, f, g, h byte) {
check("Uint32", int64(x), 0x01020304, a, b, c, d, e, f, g, h)
}
type Int64 int64
func (x Int64) m(a, b, c, d, e, f, g, h byte) {
check("Int64", int64(x), 0x0102030405060708, a, b, c, d, e, f, g, h)
}
type Uint64 uint64
func (x Uint64) m(a, b, c, d, e, f, g, h byte) {
check("Uint64", int64(x), 0x0102030405060708, a, b, c, d, e, f, g, h)
}
var test = []I{
Int8(0x01),
Uint8(0x01),
Int16(0x0102),
Uint16(0x0102),
Int32(0x01020304),
Uint32(0x01020304),
Int64(0x0102030405060708),
Uint64(0x0102030405060708),
}
func main() {
for _, t := range test {
t.m(0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17)
}
}
var bug = false
func check(desc string, have, want int64, a, b, c, d, e, f, g, h byte) {
if have != want || a != 0x10 || b != 0x11 || c != 0x12 || d != 0x13 || e != 0x14 || f != 0x15 || g != 0x16 || h != 0x17 {
if !bug {
bug = true
println("BUG")
}
println(desc, "check", have, want, a, b, c, d, e, f, g, h)
}
}
```
## bug311
```go
// run
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
m := make(map[string][1000]byte)
m["hi"] = [1000]byte{1}
v := m["hi"]
for k, vv := range m {
if k != "hi" || string(v[:]) != string(vv[:]) {
panic("bad iter")
}
}
}
```
## bug317
```go
// run
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
x := []uint{0}
x[0] &^= f()
}
func f() uint {
return 1<<31 // doesn't panic with 1<<31 - 1
}
```
## bug333
```go
// run
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 1709
package main
func main() {
type Ts string
var ts Ts
_ = []byte(ts)
}
/*
bug333.go:14: cannot use ts (type Ts) as type string in function argument
*/
```
## bug343
```go
// run
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// issue 1900
package main
func getArgs(data map[string]interface{}, keys ...string) map[string]string {
ret := map[string]string{}
var ok bool
for _, k := range keys {
ret[k], ok = data[k].(string)
if !ok {}
}
return ret
}
func main() {
x := getArgs(map[string]interface{}{"x":"y"}, "x")
if x["x"] != "y" {
println("BUG bug343", x)
}
}
/*
typecheck [1008592b0]
. INDREG a(1) l(15) x(24) tc(2) runtime.ret G0 string
bug343.go:15: internal compiler error: typecheck INDREG
*/
```
## bug352
```go
// run
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
var x [10][0]byte
var y = make([]struct{}, 10)
func main() {
if &x[1] != &x[2] {
println("BUG: bug352 [0]byte")
}
if &y[1] != &y[2] {
println("BUG: bug352 struct{}")
}
}
```
## bug356
```go
// run
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// issue 1808
package main
func main() {
var i uint64
var x int = 12345
if y := x << (i&5); y != 12345<<0 {
println("BUG bug344", y)
return
}
i++
if y := x << (i&5); y != 12345<<1 {
println("BUG bug344a", y)
}
i = 70
if y := x << i; y != 0 {
println("BUG bug344b", y)
}
i = 1<<32
if y := x << i; y != 0 {
println("BUG bug344c", y)
}
}
/*
typecheck [1008592b0]
. INDREG a(1) l(15) x(24) tc(2) runtime.ret G0 string
bug343.go:15: internal compiler error: typecheck INDREG
*/
```
## bug366
```go
// run
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 2206. Incorrect sign extension of div arguments.
package main
func five(x int64) {
if x != 5 {
panic(x)
}
}
func main() {
// 5
five(int64(5 / (5 / 3)))
// 5
five(int64(byte(5) / (byte(5) / byte(3))))
// 5
var a, b byte = 5, 3
five(int64(a / (a / b)))
// integer divide by zero in golang.org sandbox
// 0 on windows/amd64
x := [3]byte{2, 3, 5}
five(int64(x[2] / (x[2] / x[1])))
// integer divide by zero in golang.org sandbox
// crash on windows/amd64
y := x[1:3]
five(int64(y[1] / (y[1] / y[0])))
}
```
## bug372
```go
// run
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 2355
package main
type T struct {}
func (T) m() string { return "T" }
type TT struct {
T
m func() string
}
func ff() string { return "ff" }
func main() {
var tt TT
tt.m = ff
if tt.m() != "ff" {
println(tt.m(), "!= \"ff\"")
}
}
```
## bug375
```go
// run
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 2423
package main
func main() {
var x interface{} = "hello"
switch x {
case "hello":
default:
println("FAIL")
}
}
```
## bug406
```go
// run
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 2821
package main
type matrix struct {
e []int
}
func (a matrix) equal() bool {
for _ = range a.e {
}
for range a.e {
}
return true
}
func main() {
var a matrix
var i interface{}
i = true && a.equal()
_ = i
}
```
## bug409
```go
// run
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Multiple inlined calls to a function that causes
// redundant address loads.
package main
func F(v [2]float64) [2]float64 {
return [2]float64{v[0], v[1]}
}
func main() {
a := F([2]float64{1, 2})
b := F([2]float64{3, 4})
println(a[0], a[1], b[0], b[1])
}
```
## bug428
```go
// run
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test that when the compiler expands append inline it does not
// overwrite a value before it needs it (issue 3369).
package main
func main() {
s := make([]byte, 5, 6)
copy(s, "12346")
s = append(s[:len(s)-1], '5', s[len(s)-1])
if string(s) != "123456" {
panic(s)
}
}
```
## bug442
```go
// run
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Used to crash generating hash and == functions for struct
// with leading _ field. Issue 3607.
package main
type T struct {
_ int
X interface{}
_ string
Y float64
}
func main() {
m := map[T]int{}
m[T{X: 1, Y: 2}] = 1
m[T{X: 2, Y: 3}] = 2
m[T{X: 1, Y: 2}] = 3 // overwrites first entry
if len(m) != 2 {
println("BUG")
}
}
```
## bug453
```go
// run
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 4138: bug in floating-point registers numbering.
// Makes 6g unable to use more than 11 registers.
package main
func formula() float32 {
mA := [1]float32{1.0}
det1 := mA[0]
det2 := mA[0]
det3 := mA[0]
det4 := mA[0]
det5 := mA[0]
det6 := mA[0]
det7 := mA[0]
det8 := mA[0]
det9 := mA[0]
det10 := mA[0]
det11 := mA[0]
det12 := mA[0]
return det1 + det2*det3 +
det4*det5 + det6*det7 +
det8*det9 + det10*det11 +
det12
}
func main() {
x := formula()
if x != 7.0 {
println(x, 7.0)
panic("x != 7.0")
}
}
```
## bug454
```go
// run
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 4173
package main
func main() {
var arr *[10]int
s := 0
for i, _ := range arr {
// used to panic trying to access arr[i]
s += i
}
if s != 45 {
println("BUG")
}
}
```
## bug473
```go
// run
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Used to be miscompiled by gccgo, due to a bug in handling
// initialization ordering.
package main
func F(a ...interface{}) interface{} {
s := 0
for _, v := range a {
s += v.(int)
}
return s
}
var V1 = F(V10, V4, V3, V11)
var V2 = F(V1)
var V3 = F(1)
var V4 = F(2)
var V5 = F(3)
var V6 = F(4)
var V7 = F(5)
var V8 = F(V14, V7, V3, V6, V5)
var V9 = F(V4, F(V12))
var V10 = F(V4, V9)
var V11 = F(6)
var V12 = F(V5, V3, V8)
var V13 = F(7)
var V14 = F(8)
func expect(name string, a interface{}, b int) {
if a.(int) != b {
panic(name)
}
}
func main() {
expect("V1", V1, 38)
expect("V2", V2, 38)
expect("V3", V3, 1)
expect("V4", V4, 2)
expect("V5", V5, 3)
expect("V6", V6, 4)
expect("V7", V7, 5)
expect("V8", V8, 21)
expect("V9", V9, 27)
expect("V10", V10, 29)
expect("V11", V11, 6)
expect("V12", V12, 25)
expect("V13", V13, 7)
expect("V14", V14, 8)
}
```
## bug485
```go
// run
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Gccgo chose the wrong embedded method when the same type appeared
// at different levels and the correct choice was not the first
// appearance of the type in a depth-first search.
package main
type embedded string
func (s embedded) val() string {
return string(s)
}
type A struct {
embedded
}
type B struct {
A
embedded
}
func main() {
b := &B{
A: A{
embedded: "a",
},
embedded: "b",
}
s := b.val()
if s != "b" {
panic(s)
}
}
```
## bug491
```go
// run
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test order of calls to builtin functions.
// Discovered during CL 144530045 review.
package main
func main() {
// append
{
x := make([]int, 0)
f := func() int { x = make([]int, 2); return 2 }
a, b, c := append(x, 1), f(), append(x, 1)
if len(a) != 1 || len(c) != 3 {
bug()
println("append call not ordered:", len(a), b, len(c))
}
}
// cap
{
x := make([]int, 1)
f := func() int { x = make([]int, 3); return 2 }
a, b, c := cap(x), f(), cap(x)
if a != 1 || c != 3 {
bug()
println("cap call not ordered:", a, b, c)
}
}
// complex
{
x := 1.0
f := func() int { x = 3; return 2 }
a, b, c := complex(x, 0), f(), complex(x, 0)
if real(a) != 1 || real(c) != 3 {
bug()
println("complex call not ordered:", a, b, c)
}
}
// copy
{
tmp := make([]int, 100)
x := make([]int, 1)
f := func() int { x = make([]int, 3); return 2 }
a, b, c := copy(tmp, x), f(), copy(tmp, x)
if a != 1 || c != 3 {
bug()
println("copy call not ordered:", a, b, c)
}
}
// imag
{
x := 1i
f := func() int { x = 3i; return 2 }
a, b, c := imag(x), f(), imag(x)
if a != 1 || c != 3 {
bug()
println("imag call not ordered:", a, b, c)
}
}
// len
{
x := make([]int, 1)
f := func() int { x = make([]int, 3); return 2 }
a, b, c := len(x), f(), len(x)
if a != 1 || c != 3 {
bug()
println("len call not ordered:", a, b, c)
}
}
// make
{
x := 1
f := func() int { x = 3; return 2 }
a, b, c := make([]int, x), f(), make([]int, x)
if len(a) != 1 || len(c) != 3 {
bug()
println("make call not ordered:", len(a), b, len(c))
}
}
// real
{
x := 1 + 0i
f := func() int { x = 3; return 2 }
a, b, c := real(x), f(), real(x)
if a != 1 || c != 3 {
bug()
println("real call not ordered:", a, b, c)
}
}
}
var bugged = false
func bug() {
if !bugged {
println("BUG")
bugged = true
}
}
```
## bug497
```go
// run
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Gccgo used to miscompile passing a global variable with a
// zero-sized type to a function.
package main
type T struct {
field s
}
type s struct{}
var X T
func F(_ T, c interface{}) int {
return len(c.(string))
}
func main() {
if v := F(X, "hi"); v != 2 {
panic(v)
}
}
```
## bug501
```go
// run
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Gccgo got a compiler crash compiling the addition of more than five
// strings with mixed constants and variables.
package main
func F(s string) (string, error) {
return s, nil
}
func G(a, b, c string) (string, error) {
return F("a" + a + "b" + b + "c" + c)
}
func main() {
if got, _ := G("x", "y", "z"); got != "axbycz" {
panic(got)
}
}
```
## gcc61258
```go
// run
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// PR61258: gccgo crashed when deleting a zero-sized key from a map.
package main
func main() {
delete(make(map[[0]bool]int), [0]bool{})
}
```
## issue10135
```go
// run
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 10135: append a slice with zero-sized element used
// to always return a slice with the same data pointer as the
// old slice, even if it's nil, so this program used to panic
// with nil pointer dereference because after append, s is a
// slice with nil data pointer but non-zero len and cap.
package main
type empty struct{}
func main() {
var s []empty
s = append(s, empty{})
for _, v := range s {
_ = v
}
}
```
## issue10253
```go
// run
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// issue 10253: cmd/7g: bad codegen, probably regopt related
package main
func main() {
if !eq() {
panic("wrong value")
}
}
var text = "abc"
var s = &str{text}
func eq() bool {
return text[0] == s.text[0]
}
type str struct {
text string
}
```
## issue11369
```go
// run
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test that the half multiply resulting from a division
// by a constant generates correct code.
package main
func main() {
var _ = 7 / "0"[0] // test case from #11369
var _ = 1 / "."[0] // test case from #11358
var x = 0 / "0"[0]
var y = 48 / "0"[0]
var z = 5 * 48 / "0"[0]
if x != 0 {
panic("expected 0")
}
if y != 1 {
panic("expected 1")
}
if z != 5 {
panic("expected 5")
}
}
```
## issue1304
```go
// run
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
var a = 1
func main() {
defer func() {
recover()
if a != 2 {
println("BUG a =", a)
}
}()
a = 2
b := a - a
c := 4
a = c / b
a = 3
}
```
## issue15039
```go
// run
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
const fffd = "\uFFFD"
// runtime.intstring used to convert int64 to rune without checking
// for truncation.
u := uint64(0x10001f4a9)
big := string(u)
if big != fffd {
panic("big != bad")
}
// cmd/compile used to require integer constants to fit into an "int".
const huge = string(1<<100)
if huge != fffd {
panic("huge != bad")
}
}
```
## issue15252
```go
// run
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This test makes sure that we use all 64 bits of an
// index, even on 32 bit machines. It also tests that nacl
// can compile 64 bit indexes loaded from ODOTPTR properly.
package main
type T struct {
i int64
}
func f(t *T) byte {
b := [2]byte{3, 4}
return b[t.i]
}
func main() {
t := &T{0x100000001}
defer func() {
r := recover()
if r == nil {
panic("panic wasn't recoverable")
}
}()
f(t)
panic("index didn't panic")
}
```
## issue15902
```go
// run
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This test makes sure we don't use 4-byte unaligned writes
// to zero memory on architectures that don't support them.
package main
type T struct {
a byte
b [10]byte
}
//go:noinline
func f(t *T) {
// t will be aligned, so &t.b won't be.
t.b = [10]byte{}
}
var t T
func main() {
f(&t)
}
```
## issue15975
```go
// run
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
var fail bool
type Closer interface {
Close()
}
func nilInterfaceDeferCall() {
var x Closer
defer x.Close()
// if it panics when evaluating x.Close, it should not reach here
fail = true
}
func shouldPanic(f func()) {
defer func() {
if recover() == nil {
panic("did not panic")
}
}()
f()
}
func main() {
shouldPanic(nilInterfaceDeferCall)
if fail {
panic("fail")
}
}
```
## issue17039
```go
// run
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type S []S
func main() {
var s S
s = append(s, s) // append a nil value to s
if s[0] != nil {
println("BUG: s[0] != nil")
}
}
```
## issue17752
```go
// run
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func f(m map[string]int) int {
return m["a"]
}
func g(m map[[8]string]int) int {
return m[[8]string{"a", "a", "a", "a", "a", "a", "a", "a"}]
}
func main() {
m := map[[8]string]int{}
g(m)
}
```
## issue18906
```go
// run
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
//go:noinline
func f(x int) {
}
//go:noinline
func val() int8 {
return -1
}
var (
array = [257]int{}
slice = array[1:]
)
func init() {
for i := range array {
array[i] = i - 1
}
}
func main() {
x := val()
y := int(uint8(x))
f(y) // try and force y to be calculated and spilled
if slice[y] != 255 {
panic("incorrect value")
}
}
```
## issue19710
```go
// run
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 19710: mishandled defer delete(...)
package main
func main() {
if n := len(f()); n != 0 {
println("got", n, "want 0")
panic("bad defer delete")
}
}
func f() map[int]bool {
m := map[int]bool{}
for i := 0; i < 3; i++ {
m[i] = true
defer delete(m, i)
}
return m
}
```
## issue20811
```go
// run
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 20811: slice-in-bound check is lowered incorrectly on
// amd64p32.
package main
func main() {
i := g()
_ = "x"[int32(i)]
j := g()
_ = "x"[:int32(j)]
}
//go:noinline
func g() int64 {
return 4398046511104
}
```
## issue21048
```go
// run
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 21048: s390x merged address generation into stores
// to unaligned global variables. This resulted in an illegal
// instruction.
package main
type T struct {
_ [1]byte
a [2]byte // offset: 1
_ [3]byte
b [2]uint16 // offset: 6
_ [2]byte
c [2]uint32 // offset: 12
_ [2]byte
d [2]int16 // offset: 22
_ [2]byte
e [2]int32 // offset: 28
}
var Source, Sink T
func newT() T {
return T{
a: [2]byte{1, 2},
b: [2]uint16{1, 2},
c: [2]uint32{1, 2},
d: [2]int16{1, 2},
e: [2]int32{1, 2},
}
}
//go:noinline
func moves() {
Sink.a = Source.a
Sink.b = Source.b
Sink.c = Source.c
Sink.d = Source.d
Sink.e = Source.e
}
//go:noinline
func loads() *T {
t := newT()
t.a = Source.a
t.b = Source.b
t.c = Source.c
t.d = Source.d
t.e = Source.e
return &t
}
//go:noinline
func stores() {
t := newT()
Sink.a = t.a
Sink.b = t.b
Sink.c = t.c
Sink.d = t.d
Sink.e = t.e
}
func main() {
moves()
loads()
stores()
}
```
## issue21687
```go
// run
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 21687: cmd/compile evaluates x twice in "x op= y", which was
// detectable if evaluating y affects x.
package main
func ptrs() (int, int) {
one := 1
two := 2
x := &one
*x += func() int {
x = &two
return 0
}()
return one, two
}
func slices() (int, int) {
one := []int{1}
two := []int{2}
x := one
x[0] += func() int {
x = two
return 0
}()
return one[0], two[0]
}
func maps() (int, int) {
one := map[int]int{0: 1}
two := map[int]int{0: 2}
x := one
x[0] += func() int {
x = two
return 0
}()
return one[0], two[0]
}
var tests = [...]func() (int, int){
ptrs,
slices,
maps,
}
func main() {
bad := 0
for i, f := range tests {
if a, b := f(); a+b != 3 {
println(i, a, b)
bad++
}
}
if bad != 0 {
panic(bad)
}
}
```
## issue22326
```go
// run
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
var (
_ = d
_ = f("_", c, b)
a = f("a")
b = f("b")
c = f("c")
d = f("d")
)
func f(s string, rest ...int) int {
print(s)
return 0
}
func main() {
println()
}
```
## issue23188
```go
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test order of evaluation of index operations.
package main
func main() {
arr := []int{1, 2}
// The spec says that in an assignment statement the operands
// of all index expressions and pointer indirections on the
// left, and the expressions on the right, are evaluated in
// the usual order. The usual order means function calls and
// channel operations are done first. Then the assignments are
// carried out one at a time. The operands of an index
// expression include both the array and the index. So this
// evaluates as
// tmp1 := arr
// tmp2 := len(arr) - 1
// tmp3 := len(arr)
// arr = arr[:tmp3-1]
// tmp1[tmp2] = 3
arr, arr[len(arr)-1] = arr[:len(arr)-1], 3
if len(arr) != 1 || arr[0] != 1 || arr[:2][1] != 3 {
panic(arr)
}
}
```
## issue23536
```go
// run
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test case where a slice of a user-defined byte type (not uint8 or byte) is
// converted to a string. Same for slice of runes.
package main
type MyByte byte
type MyRune rune
func main() {
var y []MyByte
_ = string(y)
var z []MyRune
_ = string(z)
}
```
## issue23719
```go
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
v1 := [2]int32{-1, 88}
v2 := [2]int32{-1, 99}
if v1 == v2 {
panic("bad comparison")
}
w1 := [2]int16{-1, 88}
w2 := [2]int16{-1, 99}
if w1 == w2 {
panic("bad comparison")
}
x1 := [4]int16{-1, 88, 88, 88}
x2 := [4]int16{-1, 99, 99, 99}
if x1 == x2 {
panic("bad comparison")
}
a1 := [2]int8{-1, 88}
a2 := [2]int8{-1, 99}
if a1 == a2 {
panic("bad comparison")
}
b1 := [4]int8{-1, 88, 88, 88}
b2 := [4]int8{-1, 99, 99, 99}
if b1 == b2 {
panic("bad comparison")
}
c1 := [8]int8{-1, 88, 88, 88, 88, 88, 88, 88}
c2 := [8]int8{-1, 99, 99, 99, 99, 99, 99, 99}
if c1 == c2 {
panic("bad comparison")
}
}
```
## issue23734
```go
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
m := map[interface{}]int{}
k := []int{}
mustPanic(func() {
_ = m[k]
})
mustPanic(func() {
_, _ = m[k]
})
mustPanic(func() {
delete(m, k)
})
}
func mustPanic(f func()) {
defer func() {
r := recover()
if r == nil {
panic("didn't panic")
}
}()
f()
}
```
## issue23814
```go
// run
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Examples from the language spec section on string conversions.
package main
func main() {
// 1
_ = string('a') // "a"
_ = string(-1) // "\ufffd" == "\xef\xbf\xbd"
_ = string(0xf8) // "\u00f8" == "ø" == "\xc3\xb8"
type myString string
_ = myString(0x65e5) // "\u65e5" == "日" == "\xe6\x97\xa5"
// 2
_ = string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø"
_ = string([]byte{}) // ""
_ = string([]byte(nil)) // ""
type bytes []byte
_ = string(bytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø"
type myByte byte
_ = string([]myByte{'w', 'o', 'r', 'l', 'd', '!'}) // "world!"
_ = myString([]myByte{'\xf0', '\x9f', '\x8c', '\x8d'}) // "🌍
// 3
_ = string([]rune{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔"
_ = string([]rune{}) // ""
_ = string([]rune(nil)) // ""
type runes []rune
_ = string(runes{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔"
type myRune rune
_ = string([]myRune{0x266b, 0x266c}) // "\u266b\u266c" == "♫♬"
_ = myString([]myRune{0x1f30e}) // "\U0001f30e" == "🌎
// 4
_ = []byte("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
_ = []byte("") // []byte{}
_ = bytes("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
_ = []myByte("world!") // []myByte{'w', 'o', 'r', 'l', 'd', '!'}
_ = []myByte(myString("🌏")) // []myByte{'\xf0', '\x9f', '\x8c', '\x8f'}
// 5
_ = []rune(myString("白鵬翔")) // []rune{0x767d, 0x9d6c, 0x7fd4}
_ = []rune("") // []rune{}
_ = runes("白鵬翔") // []rune{0x767d, 0x9d6c, 0x7fd4}
_ = []myRune("♫♬") // []myRune{0x266b, 0x266c}
_ = []myRune(myString("🌐")) // []myRune{0x1f310}
}
```
## issue23837
```go
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
//go:noinline
func f(p, q *struct{}) bool {
return *p == *q
}
type T struct {
x struct{}
y int
}
//go:noinline
func g(p, q *T) bool {
return p.x == q.x
}
//go:noinline
func h(p, q func() struct{}) bool {
return p() == q()
}
func fi(p, q *struct{}) bool {
return *p == *q
}
func gi(p, q *T) bool {
return p.x == q.x
}
func hi(p, q func() struct{}) bool {
return p() == q()
}
func main() {
shouldPanic(func() { f(nil, nil) })
shouldPanic(func() { g(nil, nil) })
shouldPanic(func() { h(nil, nil) })
shouldPanic(func() { fi(nil, nil) })
shouldPanic(func() { gi(nil, nil) })
shouldPanic(func() { hi(nil, nil) })
n := 0
inc := func() struct{} {
n++
return struct{}{}
}
h(inc, inc)
if n != 2 {
panic("inc not called")
}
hi(inc, inc)
if n != 4 {
panic("inc not called")
}
}
func shouldPanic(x func()) {
defer func() {
if recover() == nil {
panic("did not panic")
}
}()
x()
}
```
## issue24503
```go
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 24503: Handle == and != of addresses taken of symbols consistently.
package main
func test() string {
type test struct{}
o1 := test{}
o2 := test{}
if &o1 == &o2 {
return "equal"
}
if &o1 != &o2 {
return "unequal"
}
return "failed"
}
func main() {
if test() == "failed" {
panic("expected either 'equal' or 'unequal'")
}
}
```
## issue24937
```go
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
x := []byte{'a'}
switch string(x) {
case func() string { x[0] = 'b'; return "b" }():
panic("FAIL")
}
}
```
## issue26116
```go
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
s := []int{0, 1, 2}
i := 1
for i > 0 && s[i] != 2 {
i++
}
if i != 2 {
panic("loop didn't run")
}
}
```
## issue2615
```go
// run
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 2615: a long chain of else if's causes an overflow
// in the parser stack.
package main
// test returns the index of the lowest set bit in a 256-bit vector.
func test(x [4]uint64) int {
if x[0]&(1<<0) != 0 {
return 0
} else if x[0]&(1<<1) != 0 {
return 1
} else if x[0]&(1<<2) != 0 {
return 2
} else if x[0]&(1<<3) != 0 {
return 3
} else if x[0]&(1<<4) != 0 {
return 4
} else if x[0]&(1<<5) != 0 {
return 5
} else if x[0]&(1<<6) != 0 {
return 6
} else if x[0]&(1<<7) != 0 {
return 7
} else if x[0]&(1<<8) != 0 {
return 8
} else if x[0]&(1<<9) != 0 {
return 9
} else if x[0]&(1<<10) != 0 {
return 10
} else if x[0]&(1<<11) != 0 {
return 11
} else if x[0]&(1<<12) != 0 {
return 12
} else if x[0]&(1<<13) != 0 {
return 13
} else if x[0]&(1<<14) != 0 {
return 14
} else if x[0]&(1<<15) != 0 {
return 15
} else if x[0]&(1<<16) != 0 {
return 16
} else if x[0]&(1<<17) != 0 {
return 17
} else if x[0]&(1<<18) != 0 {
return 18
} else if x[0]&(1<<19) != 0 {
return 19
} else if x[0]&(1<<20) != 0 {
return 20
} else if x[0]&(1<<21) != 0 {
return 21
} else if x[0]&(1<<22) != 0 {
return 22
} else if x[0]&(1<<23) != 0 {
return 23
} else if x[0]&(1<<24) != 0 {
return 24
} else if x[0]&(1<<25) != 0 {
return 25
} else if x[0]&(1<<26) != 0 {
return 26
} else if x[0]&(1<<27) != 0 {
return 27
} else if x[0]&(1<<28) != 0 {
return 28
} else if x[0]&(1<<29) != 0 {
return 29
} else if x[0]&(1<<30) != 0 {
return 30
} else if x[0]&(1<<31) != 0 {
return 31
} else if x[0]&(1<<32) != 0 {
return 32
} else if x[0]&(1<<33) != 0 {
return 33
} else if x[0]&(1<<34) != 0 {
return 34
} else if x[0]&(1<<35) != 0 {
return 35
} else if x[0]&(1<<36) != 0 {
return 36
} else if x[0]&(1<<37) != 0 {
return 37
} else if x[0]&(1<<38) != 0 {
return 38
} else if x[0]&(1<<39) != 0 {
return 39
} else if x[0]&(1<<40) != 0 {
return 40
} else if x[0]&(1<<41) != 0 {
return 41
} else if x[0]&(1<<42) != 0 {
return 42
} else if x[0]&(1<<43) != 0 {
return 43
} else if x[0]&(1<<44) != 0 {
return 44
} else if x[0]&(1<<45) != 0 {
return 45
} else if x[0]&(1<<46) != 0 {
return 46
} else if x[0]&(1<<47) != 0 {
return 47
} else if x[0]&(1<<48) != 0 {
return 48
} else if x[0]&(1<<49) != 0 {
return 49
} else if x[0]&(1<<50) != 0 {
return 50
} else if x[0]&(1<<51) != 0 {
return 51
} else if x[0]&(1<<52) != 0 {
return 52
} else if x[0]&(1<<53) != 0 {
return 53
} else if x[0]&(1<<54) != 0 {
return 54
} else if x[0]&(1<<55) != 0 {
return 55
} else if x[0]&(1<<56) != 0 {
return 56
} else if x[0]&(1<<57) != 0 {
return 57
} else if x[0]&(1<<58) != 0 {
return 58
} else if x[0]&(1<<59) != 0 {
return 59
} else if x[0]&(1<<60) != 0 {
return 60
} else if x[0]&(1<<61) != 0 {
return 61
} else if x[0]&(1<<62) != 0 {
return 62
} else if x[0]&(1<<63) != 0 {
return 63
} else if x[1]&(1<<0) != 0 {
return 64
} else if x[1]&(1<<1) != 0 {
return 65
} else if x[1]&(1<<2) != 0 {
return 66
} else if x[1]&(1<<3) != 0 {
return 67
} else if x[1]&(1<<4) != 0 {
return 68
} else if x[1]&(1<<5) != 0 {
return 69
} else if x[1]&(1<<6) != 0 {
return 70
} else if x[1]&(1<<7) != 0 {
return 71
} else if x[1]&(1<<8) != 0 {
return 72
} else if x[1]&(1<<9) != 0 {
return 73
} else if x[1]&(1<<10) != 0 {
return 74
} else if x[1]&(1<<11) != 0 {
return 75
} else if x[1]&(1<<12) != 0 {
return 76
} else if x[1]&(1<<13) != 0 {
return 77
} else if x[1]&(1<<14) != 0 {
return 78
} else if x[1]&(1<<15) != 0 {
return 79
} else if x[1]&(1<<16) != 0 {
return 80
} else if x[1]&(1<<17) != 0 {
return 81
} else if x[1]&(1<<18) != 0 {
return 82
} else if x[1]&(1<<19) != 0 {
return 83
} else if x[1]&(1<<20) != 0 {
return 84
} else if x[1]&(1<<21) != 0 {
return 85
} else if x[1]&(1<<22) != 0 {
return 86
} else if x[1]&(1<<23) != 0 {
return 87
} else if x[1]&(1<<24) != 0 {
return 88
} else if x[1]&(1<<25) != 0 {
return 89
} else if x[1]&(1<<26) != 0 {
return 90
} else if x[1]&(1<<27) != 0 {
return 91
} else if x[1]&(1<<28) != 0 {
return 92
} else if x[1]&(1<<29) != 0 {
return 93
} else if x[1]&(1<<30) != 0 {
return 94
} else if x[1]&(1<<31) != 0 {
return 95
} else if x[1]&(1<<32) != 0 {
return 96
} else if x[1]&(1<<33) != 0 {
return 97
} else if x[1]&(1<<34) != 0 {
return 98
} else if x[1]&(1<<35) != 0 {
return 99
} else if x[1]&(1<<36) != 0 {
return 100
} else if x[1]&(1<<37) != 0 {
return 101
} else if x[1]&(1<<38) != 0 {
return 102
} else if x[1]&(1<<39) != 0 {
return 103
} else if x[1]&(1<<40) != 0 {
return 104
} else if x[1]&(1<<41) != 0 {
return 105
} else if x[1]&(1<<42) != 0 {
return 106
} else if x[1]&(1<<43) != 0 {
return 107
} else if x[1]&(1<<44) != 0 {
return 108
} else if x[1]&(1<<45) != 0 {
return 109
} else if x[1]&(1<<46) != 0 {
return 110
} else if x[1]&(1<<47) != 0 {
return 111
} else if x[1]&(1<<48) != 0 {
return 112
} else if x[1]&(1<<49) != 0 {
return 113
} else if x[1]&(1<<50) != 0 {
return 114
} else if x[1]&(1<<51) != 0 {
return 115
} else if x[1]&(1<<52) != 0 {
return 116
} else if x[1]&(1<<53) != 0 {
return 117
} else if x[1]&(1<<54) != 0 {
return 118
} else if x[1]&(1<<55) != 0 {
return 119
} else if x[1]&(1<<56) != 0 {
return 120
} else if x[1]&(1<<57) != 0 {
return 121
} else if x[1]&(1<<58) != 0 {
return 122
} else if x[1]&(1<<59) != 0 {
return 123
} else if x[1]&(1<<60) != 0 {
return 124
} else if x[1]&(1<<61) != 0 {
return 125
} else if x[1]&(1<<62) != 0 {
return 126
} else if x[1]&(1<<63) != 0 {
return 127
} else if x[2]&(1<<0) != 0 {
return 128
} else if x[2]&(1<<1) != 0 {
return 129
} else if x[2]&(1<<2) != 0 {
return 130
} else if x[2]&(1<<3) != 0 {
return 131
} else if x[2]&(1<<4) != 0 {
return 132
} else if x[2]&(1<<5) != 0 {
return 133
} else if x[2]&(1<<6) != 0 {
return 134
} else if x[2]&(1<<7) != 0 {
return 135
} else if x[2]&(1<<8) != 0 {
return 136
} else if x[2]&(1<<9) != 0 {
return 137
} else if x[2]&(1<<10) != 0 {
return 138
} else if x[2]&(1<<11) != 0 {
return 139
} else if x[2]&(1<<12) != 0 {
return 140
} else if x[2]&(1<<13) != 0 {
return 141
} else if x[2]&(1<<14) != 0 {
return 142
} else if x[2]&(1<<15) != 0 {
return 143
} else if x[2]&(1<<16) != 0 {
return 144
} else if x[2]&(1<<17) != 0 {
return 145
} else if x[2]&(1<<18) != 0 {
return 146
} else if x[2]&(1<<19) != 0 {
return 147
} else if x[2]&(1<<20) != 0 {
return 148
} else if x[2]&(1<<21) != 0 {
return 149
} else if x[2]&(1<<22) != 0 {
return 150
} else if x[2]&(1<<23) != 0 {
return 151
} else if x[2]&(1<<24) != 0 {
return 152
} else if x[2]&(1<<25) != 0 {
return 153
} else if x[2]&(1<<26) != 0 {
return 154
} else if x[2]&(1<<27) != 0 {
return 155
} else if x[2]&(1<<28) != 0 {
return 156
} else if x[2]&(1<<29) != 0 {
return 157
} else if x[2]&(1<<30) != 0 {
return 158
} else if x[2]&(1<<31) != 0 {
return 159
} else if x[2]&(1<<32) != 0 {
return 160
} else if x[2]&(1<<33) != 0 {
return 161
} else if x[2]&(1<<34) != 0 {
return 162
} else if x[2]&(1<<35) != 0 {
return 163
} else if x[2]&(1<<36) != 0 {
return 164
} else if x[2]&(1<<37) != 0 {
return 165
} else if x[2]&(1<<38) != 0 {
return 166
} else if x[2]&(1<<39) != 0 {
return 167
} else if x[2]&(1<<40) != 0 {
return 168
} else if x[2]&(1<<41) != 0 {
return 169
} else if x[2]&(1<<42) != 0 {
return 170
} else if x[2]&(1<<43) != 0 {
return 171
} else if x[2]&(1<<44) != 0 {
return 172
} else if x[2]&(1<<45) != 0 {
return 173
} else if x[2]&(1<<46) != 0 {
return 174
} else if x[2]&(1<<47) != 0 {
return 175
} else if x[2]&(1<<48) != 0 {
return 176
} else if x[2]&(1<<49) != 0 {
return 177
} else if x[2]&(1<<50) != 0 {
return 178
} else if x[2]&(1<<51) != 0 {
return 179
} else if x[2]&(1<<52) != 0 {
return 180
} else if x[2]&(1<<53) != 0 {
return 181
} else if x[2]&(1<<54) != 0 {
return 182
} else if x[2]&(1<<55) != 0 {
return 183
} else if x[2]&(1<<56) != 0 {
return 184
} else if x[2]&(1<<57) != 0 {
return 185
} else if x[2]&(1<<58) != 0 {
return 186
} else if x[2]&(1<<59) != 0 {
return 187
} else if x[2]&(1<<60) != 0 {
return 188
} else if x[2]&(1<<61) != 0 {
return 189
} else if x[2]&(1<<62) != 0 {
return 190
} else if x[2]&(1<<63) != 0 {
return 191
} else if x[3]&(1<<0) != 0 {
return 192
} else if x[3]&(1<<1) != 0 {
return 193
} else if x[3]&(1<<2) != 0 {
return 194
} else if x[3]&(1<<3) != 0 {
return 195
} else if x[3]&(1<<4) != 0 {
return 196
} else if x[3]&(1<<5) != 0 {
return 197
} else if x[3]&(1<<6) != 0 {
return 198
} else if x[3]&(1<<7) != 0 {
return 199
} else if x[3]&(1<<8) != 0 {
return 200
} else if x[3]&(1<<9) != 0 {
return 201
} else if x[3]&(1<<10) != 0 {
return 202
} else if x[3]&(1<<11) != 0 {
return 203
} else if x[3]&(1<<12) != 0 {
return 204
} else if x[3]&(1<<13) != 0 {
return 205
} else if x[3]&(1<<14) != 0 {
return 206
} else if x[3]&(1<<15) != 0 {
return 207
} else if x[3]&(1<<16) != 0 {
return 208
} else if x[3]&(1<<17) != 0 {
return 209
} else if x[3]&(1<<18) != 0 {
return 210
} else if x[3]&(1<<19) != 0 {
return 211
} else if x[3]&(1<<20) != 0 {
return 212
} else if x[3]&(1<<21) != 0 {
return 213
} else if x[3]&(1<<22) != 0 {
return 214
} else if x[3]&(1<<23) != 0 {
return 215
} else if x[3]&(1<<24) != 0 {
return 216
} else if x[3]&(1<<25) != 0 {
return 217
} else if x[3]&(1<<26) != 0 {
return 218
} else if x[3]&(1<<27) != 0 {
return 219
} else if x[3]&(1<<28) != 0 {
return 220
} else if x[3]&(1<<29) != 0 {
return 221
} else if x[3]&(1<<30) != 0 {
return 222
} else if x[3]&(1<<31) != 0 {
return 223
} else if x[3]&(1<<32) != 0 {
return 224
} else if x[3]&(1<<33) != 0 {
return 225
} else if x[3]&(1<<34) != 0 {
return 226
} else if x[3]&(1<<35) != 0 {
return 227
} else if x[3]&(1<<36) != 0 {
return 228
} else if x[3]&(1<<37) != 0 {
return 229
} else if x[3]&(1<<38) != 0 {
return 230
} else if x[3]&(1<<39) != 0 {
return 231
} else if x[3]&(1<<40) != 0 {
return 232
} else if x[3]&(1<<41) != 0 {
return 233
} else if x[3]&(1<<42) != 0 {
return 234
} else if x[3]&(1<<43) != 0 {
return 235
} else if x[3]&(1<<44) != 0 {
return 236
} else if x[3]&(1<<45) != 0 {
return 237
} else if x[3]&(1<<46) != 0 {
return 238
} else if x[3]&(1<<47) != 0 {
return 239
} else if x[3]&(1<<48) != 0 {
return 240
} else if x[3]&(1<<49) != 0 {
return 241
} else if x[3]&(1<<50) != 0 {
return 242
} else if x[3]&(1<<51) != 0 {
return 243
} else if x[3]&(1<<52) != 0 {
return 244
} else if x[3]&(1<<53) != 0 {
return 245
} else if x[3]&(1<<54) != 0 {
return 246
} else if x[3]&(1<<55) != 0 {
return 247
} else if x[3]&(1<<56) != 0 {
return 248
} else if x[3]&(1<<57) != 0 {
return 249
} else if x[3]&(1<<58) != 0 {
return 250
} else if x[3]&(1<<59) != 0 {
return 251
} else if x[3]&(1<<60) != 0 {
return 252
} else if x[3]&(1<<61) != 0 {
return 253
} else if x[3]&(1<<62) != 0 {
return 254
} else if x[3]&(1<<63) != 0 {
return 255
}
return -1
}
func main() {
const ones = ^uint64(0)
for i := 0; i < 256; i++ {
bits := [4]uint64{ones, ones, ones, ones}
// clear bottom i bits
bits[i/64] ^= 1<<(uint(i)&63) - 1
for j := i/64 - 1; j >= 0; j-- {
bits[j] = 0
}
k := test(bits)
if k != i {
print("test(bits)=", k, " want ", i, "\n")
panic("failed")
}
}
}
```
## issue26153
```go
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 26153. The write to ps was incorrectly
// removed by the dead auto elimination pass.
package main
const hello = "hello world"
func main() {
var s string
mangle(&s)
if s != hello {
panic("write incorrectly elided")
}
}
//go:noinline
func mangle(ps *string) {
if ps == nil {
var s string
ps = &s
}
*ps = hello
}
```
## issue27278
```go
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 27278: dead auto elim deletes an auto and its
// initialization, but it is live because of a nil check.
package main
type T struct {
_ [3]string
T2
}
func (t *T) M() []string {
return t.T2.M()
}
type T2 struct {
T3
}
func (t *T2) M() []string {
return t.T3.M()
}
type T3 struct {
a string
}
func (t *T3) M() []string {
return []string{}
}
func main() {
poison()
f()
}
//go:noinline
func f() {
(&T{}).M()
grow(10000)
}
// grow stack, triggers stack copy
func grow(n int) {
if n == 0 {
return
}
grow(n-1)
}
// put some junk on stack, which cannot be valid address
//go:noinline
func poison() {
x := [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
g = x
}
var g [10]int
```
## issue27289
```go
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Make sure we don't prove that the bounds check failure branch is unreachable.
package main
//go:noinline
func f(a []int) {
_ = a[len(a)-1]
}
func main() {
defer func() {
if err := recover(); err != nil {
return
}
panic("f should panic")
}()
f(nil)
}
```
## issue29013a
```go
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type TestSuite struct {
Tests []int
}
var Suites = []TestSuite{
Dicts,
}
var Dicts = TestSuite{
Tests: []int{0},
}
func main() {
if &Dicts.Tests[0] != &Suites[0].Tests[0] {
panic("bad")
}
}
```
## issue29013b
```go
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type TestSuite struct {
Tests []Test
}
type Test struct {
Want interface{}
}
type Int struct {
i int
}
func NewInt(v int) Int {
return Int{i: v}
}
var Suites = []TestSuite{
Dicts,
}
var Dicts = TestSuite{
Tests: []Test{
{
Want: map[Int]bool{NewInt(1): true},
},
{
Want: map[Int]string{
NewInt(3): "3",
},
},
},
}
func main() {
if Suites[0].Tests[0].Want.(map[Int]bool)[NewInt(3)] {
panic("bad")
}
}
```
## issue29402
```go
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 29402: wrong optimization of comparison of
// constant and shift on MIPS.
package main
//go:noinline
func F(s []int) bool {
half := len(s) / 2
return half >= 0
}
func main() {
b := F([]int{1, 2, 3, 4})
if !b {
panic("FAIL")
}
}
```
## issue32680
```go
// run -gcflags=-d=ssa/check/on
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// As of 2019-06, bug affects/ed amd64 and s390x.
package main
var foo = []byte{105, 57, 172, 152}
func main() {
for i := 0; i < len(foo); i += 4 {
// Requires inlining and non-constant i
// Note the bug/fix also apply to different widths, but was unable to reproduce for those.
println(readLittleEndian32_2(foo[i], foo[i+1], foo[i+2], foo[i+3]))
}
}
func readLittleEndian32_2(a, b, c, d byte) uint32 {
return uint32(a) | (uint32(b) << 8) | (uint32(c) << 16) | (uint32(d) << 24)
}
```
## issue33062
```go
// run
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 33062: gccgo generates incorrect type equality
// functions.
package main
type simpleStruct struct {
int
string
}
type complexStruct struct {
int
simpleStruct
}
func main() {
x := complexStruct{1, simpleStruct{2, "xxx"}}
ix := interface{}(x)
y := complexStruct{1, simpleStruct{2, "yyy"}}
iy := interface{}(y)
if ix != ix {
panic("FAIL")
}
if ix == iy {
panic("FAIL")
}
}
```
## issue34395
```go
// run
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test that a binary with a large data section can load. This failed on wasm.
package main
var test = [100 * 1024 * 1024]byte{42}
func main() {
if test[0] != 42 {
panic("bad")
}
}
```
## issue35576
```go
// run
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Check print/println(f()) is allowed where f() is multi-value.
package main
func f() (int16, float64, string) { return -42, 42.0, "x" }
func main() {
print(f())
println(f())
}
```
## issue38496
```go
// run
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Make sure bounds check elision isn't confused with nil check elision.
package main
func main() {
defer func() {
err := recover()
if err == nil {
panic("failed to check nil ptr")
}
}()
var m [2]*int
_ = *m[1] // need a nil check, but not a bounds check
}
```
## issue39505b
```go
// run
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
ff := []func(){lt_f1, lt_f2, lt_f3, lt_f4, lt_f5, lt_f6, lt_f7, lt_f8, lt_f9,
gt_f1, gt_f2, gt_f3, le_f1, le_f2, le_f3, ge_f1, ge_f2, ge_f3}
for _, f := range ff {
f()
}
}
func lt_f1() {
const c = 1
var a = 0
var v *int = &a
if *v-c < len([]int{}) {
} else {
panic("bad")
}
}
func lt_f2() {
const c = 10
var a = 0
var v *int = &a
if *v+c < len([]int{}) {
panic("bad")
}
}
func lt_f3() {
const c = -10
var a = 0
var v *int = &a
if *v|0xff+c < len([]int{}) {
panic("bad")
}
}
func lt_f4() {
const c = 10
var a = 0
var v *int = &a
if *v|0x0f+c < len([]int{}) {
panic("bad")
}
}
func lt_f5() {
const c int32 = 1
var a int32 = 0
var v *int32 = &a
if *v-c < int32(len([]int32{})) {
} else {
panic("bad")
}
}
func lt_f6() {
const c int32 = 10
var a int32 = 0
var v *int32 = &a
if *v+c < int32(len([]int32{})) {
panic("bad")
}
}
func lt_f7() {
const c int32 = -10
var a int32 = 0
var v *int32 = &a
if *v|0xff+c < int32(len([]int{})) {
panic("bad")
}
}
func lt_f8() {
const c int32 = 10
var a int32 = 0
var v *int32 = &a
if *v|0x0f+c < int32(len([]int{})) {
panic("bad")
}
}
func lt_f9() {
const c int32 = -10
var a int32 = 0
var v *int32 = &a
if *v|0x0a+c < int32(len([]int{})) {
panic("bad")
}
}
func gt_f1() {
const c = 1
var a = 0
var v *int = &a
if len([]int{}) > *v-c {
} else {
panic("bad")
}
}
func gt_f2() {
const c = 10
var a = 0
var v *int = &a
if len([]int{}) > *v|0x0f+c {
panic("bad")
}
}
func gt_f3() {
const c int32 = 10
var a int32 = 0
var v *int32 = &a
if int32(len([]int{})) > *v|0x0f+c {
panic("bad")
}
}
func le_f1() {
const c = -10
var a = 0
var v *int = &a
if *v|0xff+c <= len([]int{}) {
panic("bad")
}
}
func le_f2() {
const c = 0xf
var a = 0
var v *int = &a
if *v|0xf-c <= len([]int{}) {
} else {
panic("bad")
}
}
func le_f3() {
const c int32 = -10
var a int32 = 0
var v *int32 = &a
if *v|0xff+c <= int32(len([]int{})) {
panic("bad")
}
}
func ge_f1() {
const c = -10
var a = 0
var v *int = &a
if len([]int{}) >= *v|0xff+c {
panic("bad")
}
}
func ge_f2() {
const c int32 = 10
var a int32 = 0
var v *int32 = &a
if int32(len([]int{})) >= *v|0x0f+c {
panic("bad")
}
}
func ge_f3() {
const c = -10
var a = 0
var v *int = &a
if len([]int{}) >= *v|0x0a+c {
} else {
panic("bad")
}
}
```
## issue40152
```go
// run
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Gccgo mishandles converting an untyped boolean to an interface type.
package main
func t(args ...interface{}) bool {
x := true
return x == args[0]
}
func main() {
r := t("x" == "x" && "y" == "y")
if !r {
panic(r)
}
}
```
## issue40367
```go
// run
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func case1() {
rates := []int32{1,2,3,4,5,6}
var sink [6]int
j := len(sink)
for star, _ := range rates {
if star+1 < 1 {
panic("")
}
j--
sink[j] = j
}
}
func case2() {
i := 0
var sink [3]int
j := len(sink)
top:
j--
sink[j] = j
if i < 2 {
i++
if i < 1 {
return
}
goto top
}
}
func main() {
case1()
case2()
}
```
## issue4167
```go
// run
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 4167: inlining of a (*T).Method expression taking
// its arguments from a multiple return breaks the compiler.
package main
type pa []int
type p int
func (this *pa) func1() (v *p, c int) {
for _ = range *this {
c++
}
v = (*p)(&c)
return
}
func (this *pa) func2() p {
return (*p).func3(this.func1())
}
func (this *p) func3(f int) p {
return *this
}
func (this *pa) func2dots() p {
return (*p).func3(this.func1())
}
func (this *p) func3dots(f ...int) p {
return *this
}
func main() {
arr := make(pa, 13)
length := arr.func2()
if int(length) != len(arr) {
panic("length != len(arr)")
}
length = arr.func2dots()
if int(length) != len(arr) {
panic("length != len(arr)")
}
}
```
## issue41780
```go
// run
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Checks that conversion of CMP(x,-y) -> CMN(x,y) is only applied in correct context.
package main
type decimal struct {
d [8]byte // digits, big-endian representation
dp int // decimal point
}
var powtab = []int{1, 3, 6, 9, 13, 16, 19, 23, 26}
//go:noinline
func foo(d *decimal) int {
exp := int(d.d[1])
if d.dp < 0 || d.dp == 0 && d.d[0] < '5' {
var n int
if -d.dp >= len(powtab) {
n = 27
} else {
n = powtab[-d.dp] // incorrect CMP -> CMN substitution causes indexing panic.
}
exp += n
}
return exp
}
func main() {
var d decimal
d.d[0] = '1'
if foo(&d) != 1 {
println("FAILURE (though not the one this test was written to catch)")
}
}
```
## issue42876
```go
// run
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
var x = [4]int32{-0x7fffffff, 0x7fffffff, 2, 4}
func main() {
if x[0] > x[1] {
panic("fail 1")
}
if x[2]&x[3] < 0 {
panic("fail 2") // Fails here
}
}
```
## issue4316
```go
// run
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 4316: the stack overflow check in the linker
// is confused when it encounters a split-stack function
// that needs 0 bytes of stack space.
package main
type Peano *Peano
func makePeano(n int) *Peano {
if n == 0 {
return nil
}
p := Peano(makePeano(n - 1))
return &p
}
var countArg Peano
var countResult int
func countPeano() {
if countArg == nil {
countResult = 0
return
}
countArg = *countArg
countPeano()
countResult++
}
var s = "(())"
var pT = 0
func p() {
if pT >= len(s) {
return
}
if s[pT] == '(' {
pT += 1
p()
if pT < len(s) && s[pT] == ')' {
pT += 1
} else {
return
}
p()
}
}
func main() {
countArg = makePeano(4096)
countPeano()
if countResult != 4096 {
println("countResult =", countResult)
panic("countResult != 4096")
}
p()
}
```
## issue43444
```go
// run
package main
var sp = ""
func f(name string, _ ...interface{}) int {
print(sp, name)
sp = " "
return 0
}
var a = f("a", x)
var b = f("b", y)
var c = f("c", z)
var d = func() int {
if false {
_ = z
}
return f("d")
}()
var e = f("e")
var x int
var y int = 42
var z int = func() int { return 42 }()
func main() { println() }
```
## issue4353
```go
// run
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 4353. An optimizer bug in 8g triggers a runtime fault
// instead of an out of bounds panic.
package main
var aib [100000]int
var paib *[100000]int = &aib
var i64 int64 = 100023
func main() {
defer func() { recover() }()
_ = paib[i64]
}
```
## issue43835
```go
// run
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
if f() {
panic("FAIL")
}
if bad, _ := g(); bad {
panic("FAIL")
}
if bad, _ := h(); bad {
panic("FAIL")
}
}
func f() (bad bool) {
defer func() {
recover()
}()
var p *int
bad, _ = true, *p
return
}
func g() (bool, int) {
defer func() {
recover()
}()
var p *int
return true, *p
}
func h() (_ bool, _ int) {
defer func() {
recover()
}()
var p *int
return true, *p
}
```
## issue4396a
```go
// run
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 4396. Arrays of bytes are not required to be
// word aligned. 5g should use MOVB to load the address
// of s.g[0] for its nil check.
//
// This test _may_ fail on arm, but requires the host to
// trap unaligned loads. This is generally done with
//
// echo "4" > /proc/cpu/alignment
package main
var s = struct {
// based on lzw.decoder
a, b, c, d, e uint16
f [4096]uint8
g [4096]uint8
}{}
func main() {
s.g[0] = 1
}
```
## issue4396b
```go
// run
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This test _may_ fail on arm, but requires the host to
// trap unaligned loads. This is generally done with
//
// echo "4" > /proc/cpu/alignment
package main
type T struct {
U uint16
V T2
}
type T2 struct {
pad [4096]byte
A, B byte
}
var s, t = new(T), new(T)
func main() {
var u, v *T2 = &s.V, &t.V
u.B = v.B
}
```
## issue4448
```go
// run
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 4448: 64-bit indices that are statically known
// to be bounded make 5g and 8g generate a dangling branch.
package main
const b26 uint64 = 0x022fdd63cc95386d
var bitPos [64]int
func init() {
for p := uint(0); p < 64; p++ {
bitPos[b26<<p>>58] = int(p)
}
}
func MinPos(w uint64) int {
if w == 0 {
panic("bit: MinPos(0) undefined")
}
return bitPos[((w&-w)*b26)>>58]
}
func main() {
const one = uint64(1)
for i := 0; i < 64; i++ {
if MinPos(1<<uint(i)) != i {
println("i =", i)
panic("MinPos(1<<uint(i)) != i")
}
}
}
```
## issue46304
```go
// run
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This testcase caused a crash when the register ABI was in effect,
// on amd64 (problem with register allocation).
package main
type Op struct {
tag string
_x []string
_q [20]uint64
plist []P
}
type P struct {
tag string
_x [10]uint64
b bool
}
type M int
//go:noinline
func (w *M) walkP(p *P) *P {
np := &P{}
*np = *p
np.tag += "new"
return np
}
func (w *M) walkOp(op *Op) *Op {
if op == nil {
return nil
}
orig := op
cloned := false
clone := func() {
if !cloned {
cloned = true
op = &Op{}
*op = *orig
}
}
pCloned := false
for i := range op.plist {
if s := w.walkP(&op.plist[i]); s != &op.plist[i] {
if !pCloned {
pCloned = true
clone()
op.plist = make([]P, len(orig.plist))
copy(op.plist, orig.plist)
}
op.plist[i] = *s
}
}
return op
}
func main() {
var ww M
w := &ww
p1 := P{tag: "a"}
p1._x[1] = 9
o := Op{tag: "old", plist: []P{p1}}
no := w.walkOp(&o)
if no.plist[0].tag != "anew" {
panic("bad")
}
}
```
## issue47771
```go
// run
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// gofrontend miscompiled some cases of append(s, make(typ, ln)...).
package main
var g int
func main() {
a := []*int{&g, &g, &g, &g}
a = append(a[:0], make([]*int, len(a) - 1)...)
if len(a) != 3 || a[0] != nil || a[1] != nil || a[2] != nil {
panic(a)
}
}
```
## issue48898
```go
// run
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
defer func() {
println(recover().(int))
}()
func() {
func() (_ [2]int) { type _ int; return }()
func() {
defer func() {
defer func() {
recover()
}()
defer panic(3)
panic(2)
}()
defer func() {
recover()
}()
panic(1)
}()
defer func() {}()
}()
var x = 123
func() {
// in the original issue, this defer was not executed (which is incorrect)
defer print(x)
func() {
defer func() {}()
panic(4)
}()
}()
}
```
## issue49100b
```go
// run
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func r(j int) {
loop:
for i, c := range "goclang" {
if i == 2 {
continue loop
}
println(string(c))
}
}
func main() {
loop:
for j := 0; j < 4; j++ {
r(j)
if j == 0 {
break loop
}
}
}
```
## issue49512
```go
// run
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type S struct{
m1Called, m2Called bool
}
func (s *S) M1(int) (int, int) {
s.m1Called = true
return 0, 0
}
func (s *S) M2(int) (int, int) {
s.m2Called = true
return 0, 0
}
type C struct {
calls []func(int) (int, int)
}
func makeC() Funcs {
return &C{}
}
func (c *C) Add(fn func(int) (int, int)) Funcs {
c.calls = append(c.calls, fn)
return c
}
func (c *C) Call() {
for _, fn := range c.calls {
fn(0)
}
}
type Funcs interface {
Add(func(int) (int, int)) Funcs
Call()
}
func main() {
s := &S{}
c := makeC().Add(s.M1).Add(s.M2)
c.Call()
if !s.m1Called || !s.m2Called {
panic("missed method call")
}
}
```
## issue50672
```go
// run
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
var ok = false
func f() func(int, int) int {
ok = true
return func(int, int) int { return 0 }
}
func g() (int, int) {
if !ok {
panic("FAIL")
}
return 0, 0
}
var _ = f()(g())
func main() {
f1()
f2()
f3()
f4()
}
func f1() {
ok := false
f := func() func(int, int) {
ok = true
return func(int, int) {}
}
g := func() (int, int) {
if !ok {
panic("FAIL")
}
return 0, 0
}
f()(g())
}
type S struct{}
func (S) f(int, int) {}
func f2() {
ok := false
f := func() S {
ok = true
return S{}
}
g := func() (int, int) {
if !ok {
panic("FAIL")
}
return 0, 0
}
f().f(g())
}
func f3() {
ok := false
f := func() []func(int, int) {
ok = true
return []func(int, int){func(int, int) {}}
}
g := func() (int, int) {
if !ok {
panic("FAIL")
}
return 0, 0
}
f()[0](g())
}
type G[T any] struct{}
func (G[T]) f(int, int) {}
func f4() {
ok := false
f := func() G[int] {
ok = true
return G[int]{}
}
g := func() (int, int) {
if !ok {
panic("FAIL")
}
return 0, 0
}
f().f(g())
}
```
## issue51101
```go
// run
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 51101: on RISCV64, difference of two pointers
// was marked as pointer and crashes GC.
package main
var a, b int
func main() {
F(&b, &a)
}
//go:noinline
func F(a, b *int) bool {
x := a == b
G(x)
y := a != b
return y
}
//go:noinline
func G(bool) {
grow([1000]int{20})
}
func grow(x [1000]int) {
if x[0] != 0 {
x[0]--
grow(x)
}
}
```
## issue55122
```go
// run
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
for i := 0; i < 10000; i++ {
h(i)
sink = make([]byte, 1024) // generate some garbage
}
}
func h(iter int) {
var x [32]byte
for i := 0; i < 32; i++ {
x[i] = 99
}
g(&x)
if x == ([32]byte{}) {
return
}
for i := 0; i < 32; i++ {
println(x[i])
}
panic(iter)
}
//go:noinline
func g(x interface{}) {
switch e := x.(type) {
case *[32]byte:
var c [32]byte
*e = c
case *[]byte:
*e = nil
}
}
var sink []byte
```
## issue55122b
```go
// run
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
for i := 0; i < 10000; i++ {
h(i)
sink = make([]byte, 1024) // generate some garbage
}
}
func h(iter int) {
var x [32]byte
for i := 0; i < 32; i++ {
x[i] = 99
}
g(&x)
if x == ([32]byte{}) {
return
}
for i := 0; i < 32; i++ {
println(x[i])
}
panic(iter)
}
//go:noinline
func g(x interface{}) {
switch e := x.(type) {
case *[32]byte:
var c [32]byte
*e = c
case *[3]*byte:
var c [3]*byte
*e = c
}
}
var sink []byte
```
## issue5515
```go
// run
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// issue 5515: miscompilation doing inlining in generated method wrapper
package main
type T uint32
func main() {
b := make([]T, 8)
b[0] = 0xdeadbeef
rs := Slice(b)
sort(rs)
}
type Slice []T
func (s Slice) Swap(i, j int) {
tmp := s[i]
s[i] = s[j]
s[j] = tmp
}
type Interface interface {
Swap(i, j int)
}
func sort(data Interface) {
data.Swap(0, 4)
}
```
## issue5704
```go
// run
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 5704: Conversions of empty strings to byte
// or rune slices return empty but non-nil slices.
package main
type (
mystring string
mybytes []byte
myrunes []rune
)
func checkBytes(s []byte, arg string) {
if len(s) != 0 {
panic("len(" + arg + ") != 0")
}
if s == nil {
panic(arg + " == nil")
}
}
func checkRunes(s []rune, arg string) {
if len(s) != 0 {
panic("len(" + arg + ") != 0")
}
if s == nil {
panic(arg + " == nil")
}
}
func main() {
checkBytes([]byte(""), `[]byte("")`)
checkBytes([]byte(mystring("")), `[]byte(mystring(""))`)
checkBytes(mybytes(""), `mybytes("")`)
checkBytes(mybytes(mystring("")), `mybytes(mystring(""))`)
checkRunes([]rune(""), `[]rune("")`)
checkRunes([]rune(mystring("")), `[]rune(mystring(""))`)
checkRunes(myrunes(""), `myrunes("")`)
checkRunes(myrunes(mystring("")), `myrunes(mystring(""))`)
}
```
## issue5753
```go
// run
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// issue 5753: bad typecheck info causes escape analysis to
// not run on method thunks.
package main
type Thing struct{}
func (t *Thing) broken(s string) []string {
foo := [1]string{s}
return foo[:]
}
func main() {
t := &Thing{}
f := t.broken
s := f("foo")
_ = f("bar")
if s[0] != "foo" {
panic(`s[0] != "foo"`)
}
}
```
## issue5793
```go
// run
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 5793: calling 2-arg builtin with multiple-result f() call expression gives
// spurious error.
package main
func complexArgs() (float64, float64) {
return 5, 7
}
func appendArgs() ([]string, string) {
return []string{"foo"}, "bar"
}
func appendMultiArgs() ([]byte, byte, byte) {
return []byte{'a', 'b'}, '1', '2'
}
func main() {
if c := complex(complexArgs()); c != 5+7i {
panic(c)
}
if s := append(appendArgs()); len(s) != 2 || s[0] != "foo" || s[1] != "bar" {
panic(s)
}
if b := append(appendMultiArgs()); len(b) != 4 || b[0] != 'a' || b[1] != 'b' || b[2] != '1' || b[3] != '2' {
panic(b)
}
}
```
## issue5820
```go
// run
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// issue 5820: register clobber when clearfat and 64 bit arithmetic is interleaved.
package main
func main() {
array := make([][]int, 2)
index := uint64(1)
array[index] = nil
if array[1] != nil {
panic("array[1] != nil")
}
}
```
## issue59367
```go
// run
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
var b [8]byte
one := uint8(1)
f16(&one, b[:2])
if b[1] != 1 {
println("2-byte value lost")
}
f32(&one, b[:4])
if b[3] != 1 {
println("4-byte value lost")
}
f64(&one, b[:8])
if b[7] != 1 {
println("8-byte value lost")
}
}
//go:noinline
func f16(p *uint8, b []byte) {
_ = b[1] // bounds check
x := *p // load a byte
y := uint16(x) // zero extend to 16 bits
b[0] = byte(y >> 8) // compute ROLW
b[1] = byte(y)
nop() // spill/restore ROLW
b[0] = byte(y >> 8) // use ROLW
b[1] = byte(y)
}
//go:noinline
func f32(p *uint8, b []byte) {
_ = b[3] // bounds check
x := *p // load a byte
y := uint32(x) // zero extend to 32 bits
b[0] = byte(y >> 24) // compute ROLL
b[1] = byte(y >> 16)
b[2] = byte(y >> 8)
b[3] = byte(y)
nop() // spill/restore ROLL
b[0] = byte(y >> 24) // use ROLL
b[1] = byte(y >> 16)
b[2] = byte(y >> 8)
b[3] = byte(y)
}
//go:noinline
func f64(p *uint8, b []byte) {
_ = b[7] // bounds check
x := *p // load a byte
y := uint64(x) // zero extend to 64 bits
b[0] = byte(y >> 56) // compute ROLQ
b[1] = byte(y >> 48)
b[2] = byte(y >> 40)
b[3] = byte(y >> 32)
b[4] = byte(y >> 24)
b[5] = byte(y >> 16)
b[6] = byte(y >> 8)
b[7] = byte(y)
nop() // spill/restore ROLQ
b[0] = byte(y >> 56) // use ROLQ
b[1] = byte(y >> 48)
b[2] = byte(y >> 40)
b[3] = byte(y >> 32)
b[4] = byte(y >> 24)
b[5] = byte(y >> 16)
b[6] = byte(y >> 8)
b[7] = byte(y)
}
//go:noinline
func nop() {
}
```
## issue59572
```go
// run
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func foo() {
println("foo")
}
func main() {
fn := foo
for _, fn = range list {
fn()
}
}
var list = []func(){
func() {
println("1")
},
func() {
println("2")
},
func() {
println("3")
},
}
```
## issue6269
```go
// run
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// issue 6269: name collision on method names for function local types.
package main
type foo struct{}
func (foo) Error() string {
return "ok"
}
type bar struct{}
func (bar) Error() string {
return "fail"
}
func unused() {
type collision struct {
bar
}
_ = collision{}
}
func main() {
type collision struct {
foo
}
s := error(collision{})
if str := s.Error(); str != "ok" {
println("s.Error() ==", str)
panic(`s.Error() != "ok"`)
}
}
```
## issue8047
```go
// run
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 8047. Stack copier shouldn't crash if there
// is a nil defer.
package main
func stackit(n int) {
if n == 0 {
return
}
stackit(n - 1)
}
func main() {
defer func() {
// catch & ignore panic from nil defer below
err := recover()
if err == nil {
panic("defer of nil func didn't panic")
}
}()
defer ((func())(nil))()
stackit(1000)
}
```
## issue8047b
```go
// run
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 8047. Defer setup during panic shouldn't crash for nil defer.
package main
func main() {
defer func() {
// This recover recovers the panic caused by the nil defer func
// g(). The original panic(1) was already aborted/replaced by this
// new panic, so when this recover is done, the program completes
// normally.
recover()
}()
f()
}
func f() {
var g func()
defer g()
panic(1)
}
```
## issue8325
```go
// run
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 8325: corrupted byte operations during optimization
// pass.
package main
const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
func main() {
var bytes = []byte{10, 20, 30, 40, 50}
for i, b := range bytes {
bytes[i] = alphanum[b%byte(len(alphanum))]
}
for _, b := range bytes {
switch {
case '0' <= b && b <= '9',
'A' <= b && b <= 'Z':
default:
println("found a bad character", string(b))
panic("BUG")
}
}
}
```
## issue8613
```go
// run
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
var out int
var zero int
func main() {
wantPanic("test1", func() {
out = 1 / zero
})
wantPanic("test2", func() {
_ = 1 / zero
})
wantPanic("test3", func() {
v := 0
_ = 1 / v
})
wantPanic("test4", func() { divby(0) })
}
func wantPanic(test string, fn func()) {
defer func() {
if e := recover(); e == nil {
panic(test + ": expected panic")
}
}()
fn()
}
//go:noinline
func divby(v int) {
_ = 1 / v
}
```
## issue8620
```go
// run
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 8620. Used to fail with -race.
package main
func min(a, b int) int {
if a < b {
return a
}
return b
}
func test(s1, s2 []struct{}) {
n := min(len(s1), len(s2))
if copy(s1, s2) != n {
panic("bad copy result")
}
}
func main() {
var b [100]struct{}
test(b[:], b[:])
test(b[1:], b[:])
test(b[:], b[2:])
}
```
## issue8947
```go
// run
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Some uses of zeroed constants in non-assignment
// expressions broke with our more aggressive zeroing
// of assignments (internal compiler errors).
package main
func f1() {
type T [2]int
p := T{0, 1}
switch p {
case T{0, 0}:
panic("wrong1")
case T{0, 1}:
// ok
default:
panic("wrong2")
}
if p == (T{0, 0}) {
panic("wrong3")
} else if p == (T{0, 1}) {
// ok
} else {
panic("wrong4")
}
}
type T struct {
V int
}
var X = T{}.V
func f2() {
var x = T{}.V
if x != 0 {
panic("wrongx")
}
if X != 0 {
panic("wrongX")
}
}
func main() {
f1()
f2()
}
```
## issue9691
```go
// run
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
s := "foo"
b := []byte(s)
m := make(map[string]int)
// Test that map index can be used in range
// and that slicebytetostringtmp is not used in this context.
for m[string(b)] = range s {
}
b[0] = 'b'
if m["foo"] != 2 {
panic("bad")
}
}
```
## func
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test simple functions.
package main
func assertequal(is, shouldbe int, msg string) {
if is != shouldbe {
print("assertion fail", msg, "\n")
panic(1)
}
}
func f1() {
}
func f2(a int) {
}
func f3(a, b int) int {
return a + b
}
func f4(a, b int, c float32) int {
return (a+b)/2 + int(c)
}
func f5(a int) int {
return 5
}
func f6(a int) (r int) {
return 6
}
func f7(a int) (x int, y float32) {
return 7, 7.0
}
func f8(a int) (x int, y float32) {
return 8, 8.0
}
type T struct {
x, y int
}
func (t *T) m10(a int, b float32) int {
return (t.x + a) * (t.y + int(b))
}
func f9(a int) (i int, f float32) {
i = 9
f = 9.0
return
}
func main() {
f1()
f2(1)
r3 := f3(1, 2)
assertequal(r3, 3, "3")
r4 := f4(0, 2, 3.0)
assertequal(r4, 4, "4")
r5 := f5(1)
assertequal(r5, 5, "5")
r6 := f6(1)
assertequal(r6, 6, "6")
r7, s7 := f7(1)
assertequal(r7, 7, "r7")
assertequal(int(s7), 7, "s7")
r8, s8 := f8(1)
assertequal(r8, 8, "r8")
assertequal(int(s8), 8, "s8")
r9, s9 := f9(1)
assertequal(r9, 9, "r9")
assertequal(int(s9), 9, "s9")
var t *T = new(T)
t.x = 1
t.y = 2
r10 := t.m10(1, 3.0)
assertequal(r10, 10, "10")
}
```
## func8
```go
// run
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test evaluation order.
package main
var calledf int
func f() int {
calledf++
return 0
}
func g() int {
return calledf
}
var xy string
//go:noinline
func x() bool {
xy += "x"
return false
}
//go:noinline
func y() string {
xy += "y"
return "abc"
}
func main() {
if f() == g() {
panic("wrong f,g order")
}
if x() == (y() == "abc") {
panic("wrong compare")
}
if xy != "xy" {
panic("wrong x,y order")
}
}
```
## gc1
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// A simple test of the garbage collector.
package main
func main() {
for i := 0; i < 1e5; i++ {
x := new([100]byte)
_ = x
}
}
```
## helloworld
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test that we can do page 1 of the C book.
package main
func main() {
print("hello, world\n")
}
```
## if_
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test if statements in various forms.
package main
func assertequal(is, shouldbe int, msg string) {
if is != shouldbe {
print("assertion fail", msg, "\n")
panic(1)
}
}
func main() {
i5 := 5
i7 := 7
var count int
count = 0
if true {
count = count + 1
}
assertequal(count, 1, "if true")
count = 0
if false {
count = count + 1
}
assertequal(count, 0, "if false")
count = 0
if one := 1; true {
count = count + one
}
assertequal(count, 1, "if true one")
count = 0
if one := 1; false {
count = count + 1
_ = one
}
assertequal(count, 0, "if false one")
count = 0
if i5 < i7 {
count = count + 1
}
assertequal(count, 1, "if cond")
count = 0
if true {
count = count + 1
} else {
count = count - 1
}
assertequal(count, 1, "if else true")
count = 0
if false {
count = count + 1
} else {
count = count - 1
}
assertequal(count, -1, "if else false")
count = 0
if t := 1; false {
count = count + 1
_ = t
t := 7
_ = t
} else {
count = count - t
}
assertequal(count, -1, "if else false var")
count = 0
t := 1
if false {
count = count + 1
t := 7
_ = t
} else {
count = count - t
}
_ = t
assertequal(count, -1, "if else false var outside")
}
```
## indirect
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test various safe uses of indirection.
package main
var m0 map[string]int
var m1 *map[string]int
var m2 *map[string]int = &m0
var m3 map[string]int = map[string]int{"a": 1}
var m4 *map[string]int = &m3
var s0 string
var s1 *string
var s2 *string = &s0
var s3 string = "a"
var s4 *string = &s3
var a0 [10]int
var a1 *[10]int
var a2 *[10]int = &a0
var b0 []int
var b1 *[]int
var b2 *[]int = &b0
var b3 []int = []int{1, 2, 3}
var b4 *[]int = &b3
func crash() {
// these uses of nil pointers
// would crash but should type check
println("crash",
len(a1)+cap(a1))
}
func nocrash() {
// this is spaced funny so that
// the compiler will print a different
// line number for each len call if
// it decides there are type errors.
// it might also help in the traceback.
x :=
len(m0) +
len(m3)
if x != 1 {
println("wrong maplen")
panic("fail")
}
x =
len(s0) +
len(s3)
if x != 1 {
println("wrong stringlen")
panic("fail")
}
x =
len(a0) +
len(a2)
if x != 20 {
println("wrong arraylen")
panic("fail")
}
x =
len(b0) +
len(b3)
if x != 3 {
println("wrong slicelen")
panic("fail")
}
x =
cap(b0) +
cap(b3)
if x != 3 {
println("wrong slicecap")
panic("fail")
}
}
func main() { nocrash() }
```
## initcomma
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test trailing commas. DO NOT gofmt THIS FILE.
package main
var a = []int{1, 2, }
var b = [5]int{1, 2, 3, }
var c = []int{1, }
var d = [...]int{1, 2, 3, }
func main() {
if len(a) != 2 {
println("len a", len(a))
panic("fail")
}
if len(b) != 5 {
println("len b", len(b))
panic("fail")
}
if len(c) != 1 {
println("len d", len(c))
panic("fail")
}
if len(d) != 3 {
println("len c", len(d))
panic("fail")
}
if a[0] != 1 {
println("a[0]", a[0])
panic("fail")
}
if a[1] != 2 {
println("a[1]", a[1])
panic("fail")
}
if b[0] != 1 {
println("b[0]", b[0])
panic("fail")
}
if b[1] != 2 {
println("b[1]", b[1])
panic("fail")
}
if b[2] != 3 {
println("b[2]", b[2])
panic("fail")
}
if b[3] != 0 {
println("b[3]", b[3])
panic("fail")
}
if b[4] != 0 {
println("b[4]", b[4])
panic("fail")
}
if c[0] != 1 {
println("c[0]", c[0])
panic("fail")
}
if d[0] != 1 {
println("d[0]", d[0])
panic("fail")
}
if d[1] != 2 {
println("d[1]", d[1])
panic("fail")
}
if d[2] != 3 {
println("d[2]", d[2])
panic("fail")
}
}
```
## bigdata
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test big vs. small, pointer vs. value interface methods.
package main
type I interface { M() int64 }
type BigPtr struct { a, b, c, d int64 }
func (z *BigPtr) M() int64 { return z.a+z.b+z.c+z.d }
type SmallPtr struct { a int32 }
func (z *SmallPtr) M() int64 { return int64(z.a) }
type IntPtr int32
func (z *IntPtr) M() int64 { return int64(*z) }
var bad bool
func test(name string, i I) {
m := i.M()
if m != 12345 {
println(name, m)
bad = true
}
}
func ptrs() {
var bigptr BigPtr = BigPtr{ 10000, 2000, 300, 45 }
var smallptr SmallPtr = SmallPtr{ 12345 }
var intptr IntPtr = 12345
// test("bigptr", bigptr)
test("&bigptr", &bigptr)
// test("smallptr", smallptr)
test("&smallptr", &smallptr)
// test("intptr", intptr)
test("&intptr", &intptr)
}
type Big struct { a, b, c, d int64 }
func (z Big) M() int64 { return z.a+z.b+z.c+z.d }
type Small struct { a int32 }
func (z Small) M() int64 { return int64(z.a) }
type Int int32
func (z Int) M() int64 { return int64(z) }
func nonptrs() {
var big Big = Big{ 10000, 2000, 300, 45 }
var small Small = Small{ 12345 }
var int Int = 12345
test("big", big)
test("&big", &big)
test("small", small)
test("&small", &small)
test("int", int)
test("&int", &int)
}
func main() {
ptrs()
nonptrs()
if bad {
println("BUG: interface4")
}
}
```
## convert
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test all the different interface conversion runtime functions.
package main
type Stringer interface {
String() string
}
type StringLengther interface {
String() string
Length() int
}
type Empty interface{}
type T string
func (t T) String() string {
return string(t)
}
func (t T) Length() int {
return len(t)
}
type U string
func (u U) String() string {
return string(u)
}
var t = T("hello")
var u = U("goodbye")
var e Empty
var s Stringer = t
var sl StringLengther = t
var i int
var ok bool
func hello(s string) {
if s != "hello" {
println("not hello: ", s)
panic("fail")
}
}
func five(i int) {
if i != 5 {
println("not 5: ", i)
panic("fail")
}
}
func true(ok bool) {
if !ok {
panic("not true")
}
}
func false(ok bool) {
if ok {
panic("not false")
}
}
func main() {
// T2I
s = t
hello(s.String())
// I2T
t = s.(T)
hello(t.String())
// T2E
e = t
// E2T
t = e.(T)
hello(t.String())
// T2I again
sl = t
hello(sl.String())
five(sl.Length())
// I2I static
s = sl
hello(s.String())
// I2I dynamic
sl = s.(StringLengther)
hello(sl.String())
five(sl.Length())
// I2E (and E2T)
e = s
hello(e.(T).String())
// E2I
s = e.(Stringer)
hello(s.String())
// I2T2 true
t, ok = s.(T)
true(ok)
hello(t.String())
// I2T2 false
_, ok = s.(U)
false(ok)
// I2I2 true
sl, ok = s.(StringLengther)
true(ok)
hello(sl.String())
five(sl.Length())
// I2I2 false (and T2I)
s = u
sl, ok = s.(StringLengther)
false(ok)
// E2T2 true
t, ok = e.(T)
true(ok)
hello(t.String())
// E2T2 false
i, ok = e.(int)
false(ok)
// E2I2 true
sl, ok = e.(StringLengther)
true(ok)
hello(sl.String())
five(sl.Length())
// E2I2 false (and T2E)
e = u
sl, ok = e.(StringLengther)
false(ok)
}
```
## fail
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test that interface conversion fails when method is missing.
package main
type I interface {
Foo()
}
func main() {
shouldPanic(p1)
}
func p1() {
var s *S
var i I
var e interface{}
e = s
i = e.(I)
_ = i
}
type S struct{}
func (s *S) _() {}
func shouldPanic(f func()) {
defer func() {
if recover() == nil {
panic("function should panic")
}
}()
f()
}
```
## noeq
```go
// run
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test run-time error detection for interface values containing types
// that cannot be compared for equality.
package main
func main() {
cmp(1)
var (
m map[int]int
s struct{ x []int }
f func()
)
noCmp(m)
noCmp(s)
noCmp(f)
}
func cmp(x interface{}) bool {
return x == x
}
func noCmp(x interface{}) {
shouldPanic(func() { cmp(x) })
}
func shouldPanic(f func()) {
defer func() {
if recover() == nil {
panic("function should panic")
}
}()
f()
}
```
## returntype
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test interface methods with different return types are distinct.
package main
type S struct { a int }
type T struct { b string }
func (s *S) Name() int8 { return 1 }
func (t *T) Name() int64 { return 64 }
type I1 interface { Name() int8 }
type I2 interface { Name() int64 }
func main() {
shouldPanic(p1)
}
func p1() {
var i1 I1
var s *S
i1 = s
print(i1.(I2).Name())
}
func shouldPanic(f func()) {
defer func() {
if recover() == nil {
panic("function should panic")
}
}()
f()
}
```
## iota
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test iota.
package main
func assert(cond bool, msg string) {
if !cond {
print("assertion fail: ", msg, "\n")
panic(1)
}
}
const (
x int = iota
y = iota
z = 1 << iota
f float32 = 2 * iota
g float32 = 4.5 * float32(iota)
)
const (
X = 0
Y
Z
)
const (
A = 1 << iota
B
C
D
E = iota * iota
F
G
)
const (
a = 1
b = iota << a
c = iota << b
d
)
const (
i = (a << iota) + (b * iota)
j
k
l
)
const (
m = iota == 0
n
)
const (
p = float32(iota)
q
r
)
const (
s = string(iota + 'a')
t
)
const (
abit, amask = 1 << iota, 1<<iota - 1
bbit, bmask = 1 << iota, 1<<iota - 1
cbit, cmask = 1 << iota, 1<<iota - 1
)
func main() {
assert(x == 0, "x")
assert(y == 1, "y")
assert(z == 4, "z")
assert(f == 6.0, "f")
assert(g == 18.0, "g")
assert(X == 0, "X")
assert(Y == 0, "Y")
assert(Z == 0, "Z")
assert(A == 1, "A")
assert(B == 2, "B")
assert(C == 4, "C")
assert(D == 8, "D")
assert(E == 16, "E")
assert(F == 25, "F")
assert(a == 1, "a")
assert(b == 2, "b")
assert(c == 8, "c")
assert(d == 12, "d")
assert(i == 1, "i")
assert(j == 4, "j")
assert(k == 8, "k")
assert(l == 14, "l")
assert(m, "m")
assert(!n, "n")
assert(p == 0.0, "p")
assert(q == 1.0, "q")
assert(r == 2.0, "r")
assert(s == "a", "s")
assert(t == "b", "t")
assert(abit == 1, "abit")
assert(amask == 0, "amask")
assert(bbit == 2, "bbit")
assert(bmask == 1, "bmask")
assert(cbit == 4, "cbit")
assert(cmask == 3, "cmask")
}
```
## array_
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test arrays and slices.
package main
func setpd(a []int) {
// print("setpd a=", a, " len=", len(a), " cap=", cap(a), "\n");
for i := 0; i < len(a); i++ {
a[i] = i
}
}
func sumpd(a []int) int {
// print("sumpd a=", a, " len=", len(a), " cap=", cap(a), "\n");
t := 0
for i := 0; i < len(a); i++ {
t += a[i]
}
// print("sumpd t=", t, "\n");
return t
}
func setpf(a *[20]int) {
// print("setpf a=", a, " len=", len(a), " cap=", cap(a), "\n");
for i := 0; i < len(a); i++ {
a[i] = i
}
}
func sumpf(a *[20]int) int {
// print("sumpf a=", a, " len=", len(a), " cap=", cap(a), "\n");
t := 0
for i := 0; i < len(a); i++ {
t += a[i]
}
// print("sumpf t=", t, "\n");
return t
}
func res(t int, lb, hb int) {
sb := (hb - lb) * (hb + lb - 1) / 2
if t != sb {
print("lb=", lb,
"; hb=", hb,
"; t=", t,
"; sb=", sb,
"\n")
panic("res")
}
}
// call ptr dynamic with ptr dynamic
func testpdpd() {
a := make([]int, 10, 100)
if len(a) != 10 && cap(a) != 100 {
print("len and cap from new: ", len(a), " ", cap(a), "\n")
panic("fail")
}
a = a[0:100]
setpd(a)
a = a[0:10]
res(sumpd(a), 0, 10)
a = a[5:25]
res(sumpd(a), 5, 25)
a = a[30:95]
res(sumpd(a), 35, 100)
}
// call ptr fixed with ptr fixed
func testpfpf() {
var a [20]int
setpf(&a)
res(sumpf(&a), 0, 20)
}
// call ptr dynamic with ptr fixed from new
func testpdpf1() {
a := new([40]int)
setpd(a[0:])
res(sumpd(a[0:]), 0, 40)
b := (*a)[5:30]
res(sumpd(b), 5, 30)
}
// call ptr dynamic with ptr fixed from var
func testpdpf2() {
var a [80]int
setpd(a[0:])
res(sumpd(a[0:]), 0, 80)
}
// generate bounds error with ptr dynamic
func testpdfault() {
a := make([]int, 100)
print("good\n")
for i := 0; i < 100; i++ {
a[i] = 0
}
print("should fault\n")
a[100] = 0
print("bad\n")
}
// generate bounds error with ptr fixed
func testfdfault() {
var a [80]int
print("good\n")
for i := 0; i < 80; i++ {
a[i] = 0
}
print("should fault\n")
x := 80
a[x] = 0
print("bad\n")
}
func main() {
testpdpd()
testpfpf()
testpdpf1()
testpdpf2()
// print("testpdfault\n"); testpdfault();
// print("testfdfault\n"); testfdfault();
}
```
## complit
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test composite literals.
package main
type M map[int]int
type S struct{ a,b,c int };
type SS struct{ aa,bb,cc S };
type SA struct{ a,b,c [3]int };
type SC struct{ a,b,c []int };
type SM struct{ a,b,c M };
func
main() {
test("s.a", s.a);
test("s.b", s.b);
test("s.c", s.c);
test("ss.aa.a", ss.aa.a);
test("ss.aa.b", ss.aa.b);
test("ss.aa.c", ss.aa.c);
test("ss.bb.a", ss.bb.a);
test("ss.bb.b", ss.bb.b);
test("ss.bb.c", ss.bb.c);
test("ss.cc.a", ss.cc.a);
test("ss.cc.b", ss.cc.b);
test("ss.cc.c", ss.cc.c);
for i:=0; i<3; i++ {
test("a[i]", a[i]);
test("c[i]", c[i]);
test("m[i]", m[i]);
test("as[i].a", as[i].a);
test("as[i].b", as[i].b);
test("as[i].c", as[i].c);
test("cs[i].a", cs[i].a);
test("cs[i].b", cs[i].b);
test("cs[i].c", cs[i].c);
test("ms[i].a", ms[i].a);
test("ms[i].b", ms[i].b);
test("ms[i].c", ms[i].c);
test("sa.a[i]", sa.a[i]);
test("sa.b[i]", sa.b[i]);
test("sa.c[i]", sa.c[i]);
test("sc.a[i]", sc.a[i]);
test("sc.b[i]", sc.b[i]);
test("sc.c[i]", sc.c[i]);
test("sm.a[i]", sm.a[i]);
test("sm.b[i]", sm.b[i]);
test("sm.c[i]", sm.c[i]);
for j:=0; j<3; j++ {
test("aa[i][j]", aa[i][j]);
test("ac[i][j]", ac[i][j]);
test("am[i][j]", am[i][j]);
test("ca[i][j]", ca[i][j]);
test("cc[i][j]", cc[i][j]);
test("cm[i][j]", cm[i][j]);
test("ma[i][j]", ma[i][j]);
test("mc[i][j]", mc[i][j]);
test("mm[i][j]", mm[i][j]);
}
}
}
var ref = 0;
func
test(xs string, x int) {
if ref >= len(answers) {
println(xs, x);
return;
}
if x != answers[ref] {
println(xs, "is", x, "should be", answers[ref])
}
ref++;
}
var a = [3]int{1001, 1002, 1003}
var s = S{1101, 1102, 1103}
var c = []int{1201, 1202, 1203}
var m = M{0:1301, 1:1302, 2:1303}
var aa = [3][3]int{[3]int{2001,2002,2003}, [3]int{2004,2005,2006}, [3]int{2007,2008,2009}}
var as = [3]S{S{2101,2102,2103},S{2104,2105,2106},S{2107,2108,2109}}
var ac = [3][]int{[]int{2201,2202,2203}, []int{2204,2205,2206}, []int{2207,2208,2209}}
var am = [3]M{M{0:2301,1:2302,2:2303}, M{0:2304,1:2305,2:2306}, M{0:2307,1:2308,2:2309}}
var sa = SA{[3]int{3001,3002,3003},[3]int{3004,3005,3006},[3]int{3007,3008,3009}}
var ss = SS{S{3101,3102,3103},S{3104,3105,3106},S{3107,3108,3109}}
var sc = SC{[]int{3201,3202,3203},[]int{3204,3205,3206},[]int{3207,3208,3209}}
var sm = SM{M{0:3301,1:3302,2:3303}, M{0:3304,1:3305,2:3306}, M{0:3307,1:3308,2:3309}}
var ca = [][3]int{[3]int{4001,4002,4003}, [3]int{4004,4005,4006}, [3]int{4007,4008,4009}}
var cs = []S{S{4101,4102,4103},S{4104,4105,4106},S{4107,4108,4109}}
var cc = [][]int{[]int{4201,4202,4203}, []int{4204,4205,4206}, []int{4207,4208,4209}}
var cm = []M{M{0:4301,1:4302,2:4303}, M{0:4304,1:4305,2:4306}, M{0:4307,1:4308,2:4309}}
var ma = map[int][3]int{0:[3]int{5001,5002,5003}, 1:[3]int{5004,5005,5006}, 2:[3]int{5007,5008,5009}}
var ms = map[int]S{0:S{5101,5102,5103},1:S{5104,5105,5106},2:S{5107,5108,5109}}
var mc = map[int][]int{0:[]int{5201,5202,5203}, 1:[]int{5204,5205,5206}, 2:[]int{5207,5208,5209}}
var mm = map[int]M{0:M{0:5301,1:5302,2:5303}, 1:M{0:5304,1:5305,2:5306}, 2:M{0:5307,1:5308,2:5309}}
var answers = [...]int {
// s
1101, 1102, 1103,
// ss
3101, 3102, 3103,
3104, 3105, 3106,
3107, 3108, 3109,
// [0]
1001, 1201, 1301,
2101, 2102, 2103,
4101, 4102, 4103,
5101, 5102, 5103,
3001, 3004, 3007,
3201, 3204, 3207,
3301, 3304, 3307,
// [0][j]
2001, 2201, 2301, 4001, 4201, 4301, 5001, 5201, 5301,
2002, 2202, 2302, 4002, 4202, 4302, 5002, 5202, 5302,
2003, 2203, 2303, 4003, 4203, 4303, 5003, 5203, 5303,
// [1]
1002, 1202, 1302,
2104, 2105, 2106,
4104, 4105, 4106,
5104, 5105, 5106,
3002, 3005, 3008,
3202, 3205, 3208,
3302, 3305, 3308,
// [1][j]
2004, 2204, 2304, 4004, 4204, 4304, 5004, 5204, 5304,
2005, 2205, 2305, 4005, 4205, 4305, 5005, 5205, 5305,
2006, 2206, 2306, 4006, 4206, 4306, 5006, 5206, 5306,
// [2]
1003, 1203, 1303,
2107, 2108, 2109,
4107, 4108, 4109,
5107, 5108, 5109,
3003, 3006, 3009,
3203, 3206, 3209,
3303, 3306, 3309,
// [2][j]
2007, 2207, 2307, 4007, 4207, 4307, 5007, 5207, 5307,
2008, 2208, 2308, 4008, 4208, 4308, 5008, 5208, 5308,
2009, 2209, 2309, 4009, 4209, 4309, 5009, 5209, 5309,
}
```
## convert
```go
// run
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test, near-exhaustive, of converting numbers between types.
// No complex numbers though.
package main
var i8 int8;
var u8 uint8;
var i16 int16;
var u16 uint16;
var i32 int32;
var u32 uint32;
var i64 int64;
var u64 uint64;
var f32 float32;
var f64 float64;
type big float64
type t struct {
from, to int
val big
}
const (
ti8 = iota+1
tu8
ti16
tu16
ti32
tu32
ti64
tu64
tf32
tf64
)
var x = []t{
/* value good in all types (10) */
{ ti8, ti8, 10 }, { ti8, tu8, 10 }, { ti8, ti16, 10 }, { ti8, tu16, 10 },
{ ti8, ti32, 10 }, { ti8, tu32, 10 }, { ti8, ti64, 10 }, { ti8, tu64, 10 },
{ ti8, tf32, 10 }, { ti8, tf64, 10 },
{ tu8, ti8, 10 }, { tu8, tu8, 10 }, { tu8, ti16, 10 }, { tu8, tu16, 10 },
{ tu8, ti32, 10 }, { tu8, tu32, 10 }, { tu8, ti64, 10 }, { tu8, tu64, 10 },
{ tu8, tf32, 10 }, { tu8, tf64, 10 },
{ ti16, ti8, 10 }, { ti16, tu8, 10 }, { ti16, ti16, 10 }, { ti16, tu16, 10 },
{ ti16, ti32, 10 }, { ti16, tu32, 10 }, { ti16, ti64, 10 }, { ti16, tu64, 10 },
{ ti16, tf32, 10 }, { ti16, tf64, 10 },
{ tu16, ti8, 10 }, { tu16, tu8, 10 }, { tu16, ti16, 10 }, { tu16, tu16, 10 },
{ tu16, ti32, 10 }, { tu16, tu32, 10 }, { tu16, ti64, 10 }, { tu16, tu64, 10 },
{ tu16, tf32, 10 }, { tu16, tf64, 10 },
{ ti32, ti8, 10 }, { ti32, tu8, 10 }, { ti32, ti16, 10 }, { ti32, tu16, 10 },
{ ti32, ti32, 10 }, { ti32, tu32, 10 }, { ti32, ti64, 10 }, { ti32, tu64, 10 },
{ ti32, tf32, 10 }, { ti32, tf64, 10 },
{ tu32, ti8, 10 }, { tu32, tu8, 10 }, { tu32, ti16, 10 }, { tu32, tu16, 10 },
{ tu32, ti32, 10 }, { tu32, tu32, 10 }, { tu32, ti64, 10 }, { tu32, tu64, 10 },
{ tu32, tf32, 10 }, { tu32, tf64, 10 },
{ ti64, ti8, 10 }, { ti64, tu8, 10 }, { ti64, ti16, 10 }, { ti64, tu16, 10 },
{ ti64, ti32, 10 }, { ti64, tu32, 10 }, { ti64, ti64, 10 }, { ti64, tu64, 10 },
{ ti64, tf32, 10 }, { ti64, tf64, 10 },
{ tu64, ti8, 10 }, { tu64, tu8, 10 }, { tu64, ti16, 10 }, { tu64, tu16, 10 },
{ tu64, ti32, 10 }, { tu64, tu32, 10 }, { tu64, ti64, 10 }, { tu64, tu64, 10 },
{ tu64, tf32, 10 }, { tu64, tf64, 10 },
{ tf32, ti8, 10 }, { tf32, tu8, 10 }, { tf32, ti16, 10 }, { tf32, tu16, 10 },
{ tf32, ti32, 10 }, { tf32, tu32, 10 }, { tf32, ti64, 10 }, { tf32, tu64, 10 },
{ tf32, tf32, 10 }, { tf32, tf64, 10 },
{ tf64, ti8, 10 }, { tf64, tu8, 10 }, { tf64, ti16, 10 }, { tf64, tu16, 10 },
{ tf64, ti32, 10 }, { tf64, tu32, 10 }, { tf64, ti64, 10 }, { tf64, tu64, 10 },
{ tf64, tf32, 10 }, { tf64, tf64, 10 },
/* value good in all signed types (-4) */
{ ti8, ti8, -4 }, { ti8, ti16, -4 },
{ ti8, ti32, -4 }, { ti8, ti64, -4 },
{ ti8, tf32, -4 }, { ti8, tf64, -4 },
{ ti16, ti8, -4 }, { ti16, ti16, -4 },
{ ti16, ti32, -4 }, { ti16, ti64, -4 },
{ ti16, tf32, -4 },
{ ti32, ti8, -4 }, { ti32, ti16, -4 },
{ ti32, ti32, -4 }, { ti32, ti64, -4 },
{ ti32, tf32, -4 }, { ti32, tf64, -4 },
{ ti64, ti8, -4 }, { ti64, ti16, -4 },
{ ti64, ti32, -4 }, { ti64, ti64, -4 },
{ ti64, tf32, -4 },
{ tf32, ti8, -4 }, { tf32, ti16, -4 },
{ tf32, ti32, -4 }, { tf32, ti64, -4 },
{ tf32, tf32, -4 },
{ tf64, ti8, -4 }, { tf64, ti16, -4 },
{ tf64, ti32, -4 }, { tf64, ti64, -4 },
{ tf64, tf32, -4 }, { tf64, tf64, -4 },
/* value good in u8 and up (175) */
{ tu8, tu8, 175 }, { tu8, ti16, 175 }, { tu8, tu16, 175 },
{ tu8, ti32, 175 }, { tu8, tu32, 175 }, { tu8, ti64, 175 }, { tu8, tu64, 175 },
{ tu8, tf32, 175 }, { tu8, tf64, 175 },
{ ti16, tu8, 175 }, { ti16, ti16, 175 }, { ti16, tu16, 175 },
{ ti16, ti32, 175 }, { ti16, tu32, 175 }, { ti16, ti64, 175 }, { ti16, tu64, 175 },
{ ti16, tf32, 175 }, { ti16, tf64, 175 },
{ tu16, tu8, 175 }, { tu16, ti16, 175 }, { tu16, tu16, 175 },
{ tu16, ti32, 175 }, { tu16, tu32, 175 }, { tu16, ti64, 175 }, { tu16, tu64, 175 },
{ tu16, tf32, 175 }, { tu16, tf64, 175 },
{ ti32, tu8, 175 }, { ti32, ti16, 175 }, { ti32, tu16, 175 },
{ ti32, ti32, 175 }, { ti32, tu32, 175 }, { ti32, ti64, 175 }, { ti32, tu64, 175 },
{ ti32, tf32, 175 }, { ti32, tf64, 175 },
{ tu32, tu8, 175 }, { tu32, ti16, 175 }, { tu32, tu16, 175 },
{ tu32, ti32, 175 }, { tu32, tu32, 175 }, { tu32, ti64, 175 }, { tu32, tu64, 175 },
{ tu32, tf32, 175 }, { tu32, tf64, 175 },
{ ti64, tu8, 175 }, { ti64, ti16, 175 }, { ti64, tu16, 175 },
{ ti64, ti32, 175 }, { ti64, tu32, 175 }, { ti64, ti64, 175 }, { ti64, tu64, 175 },
{ ti64, tf32, 175 }, { ti64, tf64, 175 },
{ tu64, tu8, 175 }, { tu64, ti16, 175 }, { tu64, tu16, 175 },
{ tu64, ti32, 175 }, { tu64, tu32, 175 }, { tu64, ti64, 175 }, { tu64, tu64, 175 },
{ tu64, tf32, 175 }, { tu64, tf64, 175 },
{ tf32, tu8, 175 }, { tf32, ti16, 175 }, { tf32, tu16, 175 },
{ tf32, ti32, 175 }, { tf32, tu32, 175 }, { tf32, ti64, 175 }, { tf32, tu64, 175 },
{ tf32, tf32, 175 }, { tf32, tf64, 175 },
{ tf64, tu8, 175 }, { tf64, ti16, 175 }, { tf64, tu16, 175 },
{ tf64, ti32, 175 }, { tf64, tu32, 175 }, { tf64, ti64, 175 }, { tf64, tu64, 175 },
{ tf64, tf32, 175 }, { tf64, tf64, 175 },
/* value good in u16 and up (41259) */
{ tu16, tu16, 41259 },
{ tu16, ti32, 41259 }, { tu16, ti64, 41259 }, { tu16, tu64, 41259 },
{ tu16, tf32, 41259 }, { tu16, tf64, 41259 },
{ ti32, tu16, 41259 },
{ ti32, ti32, 41259 }, { ti32, tu32, 41259 }, { ti32, ti64, 41259 }, { ti32, tu64, 41259 },
{ ti32, tf32, 41259 }, { ti32, tf64, 41259 },
{ tu32, tu16, 41259 },
{ tu32, ti32, 41259 }, { tu32, tu32, 41259 }, { tu32, ti64, 41259 }, { tu32, tu64, 41259 },
{ tu32, tf32, 41259 }, { tu32, tf64, 41259 },
{ ti64, tu16, 41259 },
{ ti64, ti32, 41259 }, { ti64, tu32, 41259 }, { ti64, ti64, 41259 }, { ti64, tu64, 41259 },
{ ti64, tf32, 41259 }, { ti64, tf64, 41259 },
{ tu64, tu16, 41259 },
{ tu64, ti32, 41259 }, { tu64, tu32, 41259 }, { tu64, ti64, 41259 }, { tu64, tu64, 41259 },
{ tu64, tf32, 41259 }, { tu64, tf64, 41259 },
{ tf32, tu16, 41259 },
{ tf32, ti32, 41259 }, { tf32, tu32, 41259 }, { tf32, ti64, 41259 }, { tf32, tu64, 41259 },
{ tf32, tf32, 41259 }, { tf32, tf64, 41259 },
{ tf64, tu16, 41259 },
{ tf64, ti32, 41259 }, { tf64, tu32, 41259 }, { tf64, ti64, 41259 }, { tf64, tu64, 41259 },
{ tf64, tf32, 41259 }, { tf64, tf64, 41259 },
/* value good in u32 and up (3758096384) */
{ tu32, tu32, 3758096384 }, { tu32, ti64, 3758096384 }, { tu32, tu64, 3758096384 },
{ tu32, tf32, 3758096384 }, { tu32, tf64, 3758096384 },
{ ti64, tu32, 3758096384 }, { ti64, ti64, 3758096384 }, { ti64, tu64, 3758096384 },
{ ti64, tf32, 3758096384 }, { ti64, tf64, 3758096384 },
{ tu64, tu32, 3758096384 }, { tu64, ti64, 3758096384 }, { tu64, tu64, 3758096384 },
{ tu64, tf32, 3758096384 }, { tu64, tf64, 3758096384 },
{ tf32, tu32, 3758096384 }, { tf32, ti64, 3758096384 }, { tf32, tu64, 3758096384 },
{ tf32, tf32, 3758096384 }, { tf32, tf64, 3758096384 },
{ tf64, tu32, 3758096384 }, { tf64, ti64, 3758096384 }, { tf64, tu64, 3758096384 },
{ tf64, tf32, 3758096384 }, { tf64, tf64, 3758096384 },
/* value good in u64 and up (16717361816799281152) */
{ tu64, tu64, 16717361816799281152 },
{ tu64, tf32, 16717361816799281152 }, { tu64, tf64, 16717361816799281152 },
{ tf32, tu64, 16717361816799281152 },
{ tf32, tf32, 16717361816799281152 }, { tf32, tf64, 16717361816799281152 },
{ tf64, tu64, 16717361816799281152 },
{ tf64, tf32, 16717361816799281152 }, { tf64, tf64, 16717361816799281152 },
}
func main() {
for i:=0; i<len(x); i++ {
v := x[i].val // input value
w := big(0) // output value
f := x[i].from // input type
t := x[i].to // output type
i8 = 0; u8 = 0; i16 = 0; u16 = 0
i32 = 0; u32 = 0; i64 = 0; u64 = 0
f32 = 0; f64 = 0
switch f*100 + t {
default:
println("missing case", i, v, f, t)
w = v
case ti8*100 + ti8:
i8 = int8(v); i8 = int8(i8); w = big(i8)
case ti8*100 + tu8:
i8 = int8(v); u8 = uint8(i8); w = big(u8)
case ti8*100 + ti16:
i8 = int8(v); i16 = int16(i8); w = big(i16)
case ti8*100 + tu16:
i8 = int8(v); u16 = uint16(i8); w = big(u16)
case ti8*100 + ti32:
i8 = int8(v); i32 = int32(i8); w = big(i32)
case ti8*100 + tu32:
i8 = int8(v); u32 = uint32(i8); w = big(u32)
case ti8*100 + ti64:
i8 = int8(v); i64 = int64(i8); w = big(i64)
case ti8*100 + tu64:
i8 = int8(v); u64 = uint64(i8); w = big(u64)
case ti8*100 + tf32:
i8 = int8(v); f32 = float32(i8); w = big(f32)
case ti8*100 + tf64:
i8 = int8(v); f64 = float64(i8); w = big(f64)
case tu8*100 + ti8:
u8 = uint8(v); i8 = int8(u8); w = big(i8)
case tu8*100 + tu8:
u8 = uint8(v); u8 = uint8(u8); w = big(u8)
case tu8*100 + ti16:
u8 = uint8(v); i16 = int16(u8); w = big(i16)
case tu8*100 + tu16:
u8 = uint8(v); u16 = uint16(u8); w = big(u16)
case tu8*100 + ti32:
u8 = uint8(v); i32 = int32(u8); w = big(i32)
case tu8*100 + tu32:
u8 = uint8(v); u32 = uint32(u8); w = big(u32)
case tu8*100 + ti64:
u8 = uint8(v); i64 = int64(u8); w = big(i64)
case tu8*100 + tu64:
u8 = uint8(v); u64 = uint64(u8); w = big(u64)
case tu8*100 + tf32:
u8 = uint8(v); f32 = float32(u8); w = big(f32)
case tu8*100 + tf64:
u8 = uint8(v); f64 = float64(u8); w = big(f64)
case ti16*100 + ti8:
i16 = int16(v); i8 = int8(i16); w = big(i8)
case ti16*100 + tu8:
i16 = int16(v); u8 = uint8(i16); w = big(u8)
case ti16*100 + ti16:
i16 = int16(v); i16 = int16(i16); w = big(i16)
case ti16*100 + tu16:
i16 = int16(v); u16 = uint16(i16); w = big(u16)
case ti16*100 + ti32:
i16 = int16(v); i32 = int32(i16); w = big(i32)
case ti16*100 + tu32:
i16 = int16(v); u32 = uint32(i16); w = big(u32)
case ti16*100 + ti64:
i16 = int16(v); i64 = int64(i16); w = big(i64)
case ti16*100 + tu64:
i16 = int16(v); u64 = uint64(i16); w = big(u64)
case ti16*100 + tf32:
i16 = int16(v); f32 = float32(i16); w = big(f32)
case ti16*100 + tf64:
i16 = int16(v); f64 = float64(i16); w = big(f64)
case tu16*100 + ti8:
u16 = uint16(v); i8 = int8(u16); w = big(i8)
case tu16*100 + tu8:
u16 = uint16(v); u8 = uint8(u16); w = big(u8)
case tu16*100 + ti16:
u16 = uint16(v); i16 = int16(u16); w = big(i16)
case tu16*100 + tu16:
u16 = uint16(v); u16 = uint16(u16); w = big(u16)
case tu16*100 + ti32:
u16 = uint16(v); i32 = int32(u16); w = big(i32)
case tu16*100 + tu32:
u16 = uint16(v); u32 = uint32(u16); w = big(u32)
case tu16*100 + ti64:
u16 = uint16(v); i64 = int64(u16); w = big(i64)
case tu16*100 + tu64:
u16 = uint16(v); u64 = uint64(u16); w = big(u64)
case tu16*100 + tf32:
u16 = uint16(v); f32 = float32(u16); w = big(f32)
case tu16*100 + tf64:
u16 = uint16(v); f64 = float64(u16); w = big(f64)
case ti32*100 + ti8:
i32 = int32(v); i8 = int8(i32); w = big(i8)
case ti32*100 + tu8:
i32 = int32(v); u8 = uint8(i32); w = big(u8)
case ti32*100 + ti16:
i32 = int32(v); i16 = int16(i32); w = big(i16)
case ti32*100 + tu16:
i32 = int32(v); u16 = uint16(i32); w = big(u16)
case ti32*100 + ti32:
i32 = int32(v); i32 = int32(i32); w = big(i32)
case ti32*100 + tu32:
i32 = int32(v); u32 = uint32(i32); w = big(u32)
case ti32*100 + ti64:
i32 = int32(v); i64 = int64(i32); w = big(i64)
case ti32*100 + tu64:
i32 = int32(v); u64 = uint64(i32); w = big(u64)
case ti32*100 + tf32:
i32 = int32(v); f32 = float32(i32); w = big(f32)
case ti32*100 + tf64:
i32 = int32(v); f64 = float64(i32); w = big(f64)
case tu32*100 + ti8:
u32 = uint32(v); i8 = int8(u32); w = big(i8)
case tu32*100 + tu8:
u32 = uint32(v); u8 = uint8(u32); w = big(u8)
case tu32*100 + ti16:
u32 = uint32(v); i16 = int16(u32); w = big(i16)
case tu32*100 + tu16:
u32 = uint32(v); u16 = uint16(u32); w = big(u16)
case tu32*100 + ti32:
u32 = uint32(v); i32 = int32(u32); w = big(i32)
case tu32*100 + tu32:
u32 = uint32(v); u32 = uint32(u32); w = big(u32)
case tu32*100 + ti64:
u32 = uint32(v); i64 = int64(u32); w = big(i64)
case tu32*100 + tu64:
u32 = uint32(v); u64 = uint64(u32); w = big(u64)
case tu32*100 + tf32:
u32 = uint32(v); f32 = float32(u32); w = big(f32)
case tu32*100 + tf64:
u32 = uint32(v); f64 = float64(u32); w = big(f64)
case ti64*100 + ti8:
i64 = int64(v); i8 = int8(i64); w = big(i8)
case ti64*100 + tu8:
i64 = int64(v); u8 = uint8(i64); w = big(u8)
case ti64*100 + ti16:
i64 = int64(v); i16 = int16(i64); w = big(i16)
case ti64*100 + tu16:
i64 = int64(v); u16 = uint16(i64); w = big(u16)
case ti64*100 + ti32:
i64 = int64(v); i32 = int32(i64); w = big(i32)
case ti64*100 + tu32:
i64 = int64(v); u32 = uint32(i64); w = big(u32)
case ti64*100 + ti64:
i64 = int64(v); i64 = int64(i64); w = big(i64)
case ti64*100 + tu64:
i64 = int64(v); u64 = uint64(i64); w = big(u64)
case ti64*100 + tf32:
i64 = int64(v); f32 = float32(i64); w = big(f32)
case ti64*100 + tf64:
i64 = int64(v); f64 = float64(i64); w = big(f64)
case tu64*100 + ti8:
u64 = uint64(v); i8 = int8(u64); w = big(i8)
case tu64*100 + tu8:
u64 = uint64(v); u8 = uint8(u64); w = big(u8)
case tu64*100 + ti16:
u64 = uint64(v); i16 = int16(u64); w = big(i16)
case tu64*100 + tu16:
u64 = uint64(v); u16 = uint16(u64); w = big(u16)
case tu64*100 + ti32:
u64 = uint64(v); i32 = int32(u64); w = big(i32)
case tu64*100 + tu32:
u64 = uint64(v); u32 = uint32(u64); w = big(u32)
case tu64*100 + ti64:
u64 = uint64(v); i64 = int64(u64); w = big(i64)
case tu64*100 + tu64:
u64 = uint64(v); u64 = uint64(u64); w = big(u64)
case tu64*100 + tf32:
u64 = uint64(v); f32 = float32(u64); w = big(f32)
case tu64*100 + tf64:
u64 = uint64(v); f64 = float64(u64); w = big(f64)
case tf32*100 + ti8:
f32 = float32(v); i8 = int8(f32); w = big(i8)
case tf32*100 + tu8:
f32 = float32(v); u8 = uint8(f32); w = big(u8)
case tf32*100 + ti16:
f32 = float32(v); i16 = int16(f32); w = big(i16)
case tf32*100 + tu16:
f32 = float32(v); u16 = uint16(f32); w = big(u16)
case tf32*100 + ti32:
f32 = float32(v); i32 = int32(f32); w = big(i32)
case tf32*100 + tu32:
f32 = float32(v); u32 = uint32(f32); w = big(u32)
case tf32*100 + ti64:
f32 = float32(v); i64 = int64(f32); w = big(i64)
case tf32*100 + tu64:
f32 = float32(v); u64 = uint64(f32); w = big(u64)
case tf32*100 + tf32:
f32 = float32(v); f32 = float32(f32); w = big(f32)
case tf32*100 + tf64:
f32 = float32(v); f64 = float64(f32); w = big(f64)
case tf64*100 + ti8:
f64 = float64(v); i8 = int8(f64); w = big(i8)
case tf64*100 + tu8:
f64 = float64(v); u8 = uint8(f64); w = big(u8)
case tf64*100 + ti16:
f64 = float64(v); i16 = int16(f64); w = big(i16)
case tf64*100 + tu16:
f64 = float64(v); u16 = uint16(f64); w = big(u16)
case tf64*100 + ti32:
f64 = float64(v); i32 = int32(f64); w = big(i32)
case tf64*100 + tu32:
f64 = float64(v); u32 = uint32(f64); w = big(u32)
case tf64*100 + ti64:
f64 = float64(v); i64 = int64(f64); w = big(i64)
case tf64*100 + tu64:
f64 = float64(v); u64 = uint64(f64); w = big(u64)
case tf64*100 + tf32:
f64 = float64(v); f32 = float32(f64); w = big(f32)
case tf64*100 + tf64:
f64 = float64(v); f64 = float64(f64); w = big(f64)
}
if v != w { println(i, v, w, f, t) }
}
}
```
## cplx2
```go
// run
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test arithmetic on complex numbers, including multiplication and division.
package main
const (
R = 5
I = 6i
C1 = R + I // ADD(5,6)
C2 = R - I // SUB(5,-6)
C3 = -(R + I) // ADD(5,6) NEG(-5,-6)
C4 = -(R - I) // SUB(5,-6) NEG(-5,6)
C5 = C1 + R // ADD(10,6)
C6 = C1 + I // ADD(5,12)
Ca = C5 + C6 // ADD(15,18)
Cb = C5 - C6 // SUB(5,-6)
Cc = C5 * C6 // MUL(-22,-150)
Cd = C5 / C6 // DIV(0.721893,-0.532544)
Ce = Cd * C6 // MUL(10,6) sb C5
)
func main() {
var r complex64 = 5 + 0i
if r != R {
println("opcode 1", r, R)
panic("fail")
}
var i complex64 = 6i
if i != I {
println("opcode 2", i, I)
panic("fail")
}
c1 := r + i
if c1 != C1 {
println("opcode x", c1, C1)
panic("fail")
}
c2 := r - i
if c2 != C2 {
println("opcode x", c2, C2)
panic("fail")
}
c3 := -(r + i)
if c3 != C3 {
println("opcode x", c3, C3)
panic("fail")
}
c4 := -(r - i)
if c4 != C4 {
println("opcode x", c4, C4)
panic("fail")
}
c5 := c1 + r
if c5 != C5 {
println("opcode x", c5, C5)
panic("fail")
}
c6 := c1 + i
if c6 != C6 {
println("opcode x", c6, C6)
panic("fail")
}
ca := c5 + c6
if ca != Ca {
println("opcode x", ca, Ca)
panic("fail")
}
cb := c5 - c6
if cb != Cb {
println("opcode x", cb, Cb)
panic("fail")
}
cc := c5 * c6
if cc != Cc {
println("opcode x", cc, Cc)
panic("fail")
}
cd := c5 / c6
if cd != Cd {
println("opcode x", cd, Cd)
panic("fail")
}
ce := cd * c6
if ce != Ce {
println("opcode x", ce, Ce)
panic("fail")
}
r32 := real(complex64(ce))
if r32 != float32(real(Ce)) {
println("real(complex64(ce))", r32, real(Ce))
panic("fail")
}
r64 := real(complex128(ce))
if r64 != real(Ce) {
println("real(complex128(ce))", r64, real(Ce))
panic("fail")
}
}
```
## interbasic
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test embedded fields of structs, including methods.
package main
type I interface {
test1() int
test2() int
test3() int
test4() int
test5() int
test6() int
test7() int
}
/******
******
******/
type SubpSubp struct {
a7 int
a int
}
func (p *SubpSubp) test7() int {
if p.a != p.a7 {
println("SubpSubp", p, p.a7)
panic("fail")
}
return p.a
}
func (p *SubpSubp) testx() { println("SubpSubp", p, p.a7) }
/******
******
******/
type SubpSub struct {
a6 int
SubpSubp
a int
}
func (p *SubpSub) test6() int {
if p.a != p.a6 {
println("SubpSub", p, p.a6)
panic("fail")
}
return p.a
}
func (p *SubpSub) testx() { println("SubpSub", p, p.a6) }
/******
******
******/
type SubSubp struct {
a5 int
a int
}
func (p *SubSubp) test5() int {
if p.a != p.a5 {
println("SubpSub", p, p.a5)
panic("fail")
}
return p.a
}
/******
******
******/
type SubSub struct {
a4 int
a int
}
func (p *SubSub) test4() int {
if p.a != p.a4 {
println("SubpSub", p, p.a4)
panic("fail")
}
return p.a
}
/******
******
******/
type Subp struct {
a3 int
*SubpSubp
SubpSub
a int
}
func (p *Subp) test3() int {
if p.a != p.a3 {
println("SubpSub", p, p.a3)
panic("fail")
}
return p.a
}
/******
******
******/
type Sub struct {
a2 int
*SubSubp
SubSub
a int
}
func (p *Sub) test2() int {
if p.a != p.a2 {
println("SubpSub", p, p.a2)
panic("fail")
}
return p.a
}
/******
******
******/
type S struct {
a1 int
Sub
*Subp
a int
}
func (p *S) test1() int {
if p.a != p.a1 {
println("SubpSub", p, p.a1)
panic("fail")
}
return p.a
}
/******
******
******/
func main() {
var i I
var s *S
// allocate
s = new(S)
s.Subp = new(Subp)
s.Sub.SubSubp = new(SubSubp)
s.Subp.SubpSubp = new(SubpSubp)
// explicit assignment
s.a = 1
s.Sub.a = 2
s.Subp.a = 3
s.Sub.SubSub.a = 4
s.Sub.SubSubp.a = 5
s.Subp.SubpSub.a = 6
s.Subp.SubpSubp.a = 7
// embedded (unique) assignment
s.a1 = 1
s.a2 = 2
s.a3 = 3
s.a4 = 4
s.a5 = 5
s.a6 = 6
s.a7 = 7
// unique calls with explicit &
if s.test1() != 1 {
println("t1", 1)
panic("fail")
}
if (&s.Sub).test2() != 2 {
println("t1", 2)
panic("fail")
}
if s.Subp.test3() != 3 {
println("t1", 3)
panic("fail")
}
if (&s.Sub.SubSub).test4() != 4 {
println("t1", 4)
panic("fail")
}
if s.Sub.SubSubp.test5() != 5 {
println("t1", 5)
panic("fail")
}
if (&s.Subp.SubpSub).test6() != 6 {
println("t1", 6)
panic("fail")
}
if s.Subp.SubpSubp.test7() != 7 {
println("t1", 7)
panic("fail")
}
// automatic &
if s.Sub.test2() != 2 {
println("t2", 2)
panic("fail")
}
if s.Sub.SubSub.test4() != 4 {
println("t2", 4)
panic("fail")
}
if s.Subp.SubpSub.test6() != 6 {
println("t2", 6)
panic("fail")
}
// embedded calls
if s.test1() != s.a1 {
println("t3", 1)
panic("fail")
}
if s.test2() != s.a2 {
println("t3", 2)
panic("fail")
}
if s.test3() != s.a3 {
println("t3", 3)
panic("fail")
}
if s.test4() != s.a4 {
println("t3", 4)
panic("fail")
}
if s.test5() != s.a5 {
println("t3", 5)
panic("fail")
}
if s.test6() != s.a6 {
println("t3", 6)
panic("fail")
}
if s.test7() != s.a7 {
println("t3", 7)
panic("fail")
}
// run it through an interface
i = s
s = i.(*S)
// same as t3
if s.test1() != s.a1 {
println("t4", 1)
panic("fail")
}
if s.test2() != s.a2 {
println("t4", 2)
panic("fail")
}
if s.test3() != s.a3 {
println("t4", 3)
panic("fail")
}
if s.test4() != s.a4 {
println("t4", 4)
panic("fail")
}
if s.test5() != s.a5 {
println("t4", 5)
panic("fail")
}
if s.test6() != s.a6 {
println("t4", 6)
panic("fail")
}
if s.test7() != s.a7 {
println("t4", 7)
panic("fail")
}
// call interface
if i.test1() != s.test1() {
println("t5", 1)
panic("fail")
}
if i.test2() != s.test2() {
println("t5", 2)
panic("fail")
}
if i.test3() != s.test3() {
println("t5", 3)
panic("fail")
}
if i.test4() != s.test4() {
println("t5", 4)
panic("fail")
}
if i.test5() != s.test5() {
println("t5", 5)
panic("fail")
}
if i.test6() != s.test6() {
println("t5", 6)
panic("fail")
}
if i.test7() != s.test7() {
println("t5", 7)
panic("fail")
}
}
```
## intervar
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test interfaces on basic types.
package main
type myint int
type mystring string
type I0 interface{}
func f() {
var ia, ib I0
var i myint
var s mystring
if ia != ib {
panic("1")
}
i = 1
ia = i
ib = i
if ia != ib {
panic("2")
}
if ia == nil {
panic("3")
}
i = 2
ia = i
if ia == ib {
panic("4")
}
ia = nil
if ia == ib {
panic("5")
}
ib = nil
if ia != ib {
panic("6")
}
if ia != nil {
panic("7")
}
s = "abc"
ia = s
ib = nil
if ia == ib {
panic("8")
}
s = "def"
ib = s
if ia == ib {
panic("9")
}
s = "abc"
ib = s
if ia != ib {
panic("a")
}
}
func main() {
var ia [20]I0
var b bool
var s string
var i8 int8
var i16 int16
var i32 int32
var i64 int64
var u8 uint8
var u16 uint16
var u32 uint32
var u64 uint64
f()
ia[0] = "xxx"
ia[1] = 12345
ia[2] = true
s = "now is"
ia[3] = s
b = false
ia[4] = b
i8 = 29
ia[5] = i8
i16 = 994
ia[6] = i16
i32 = 3434
ia[7] = i32
i64 = 1234567
ia[8] = i64
u8 = 12
ia[9] = u8
u16 = 799
ia[10] = u16
u32 = 4455
ia[11] = u32
u64 = 765432
ia[12] = u64
s = ia[0].(string)
if s != "xxx" {
println(0, s)
panic("fail")
}
i32 = int32(ia[1].(int))
if i32 != 12345 {
println(1, i32)
panic("fail")
}
b = ia[2].(bool)
if b != true {
println(2, b)
panic("fail")
}
s = ia[3].(string)
if s != "now is" {
println(3, s)
panic("fail")
}
b = ia[4].(bool)
if b != false {
println(4, b)
panic("fail")
}
i8 = ia[5].(int8)
if i8 != 29 {
println(5, i8)
panic("fail")
}
i16 = ia[6].(int16)
if i16 != 994 {
println(6, i16)
panic("fail")
}
i32 = ia[7].(int32)
if i32 != 3434 {
println(7, i32)
panic("fail")
}
i64 = ia[8].(int64)
if i64 != 1234567 {
println(8, i64)
panic("fail")
}
u8 = ia[9].(uint8)
if u8 != 12 {
println(5, u8)
panic("fail")
}
u16 = ia[10].(uint16)
if u16 != 799 {
println(6, u16)
panic("fail")
}
u32 = ia[11].(uint32)
if u32 != 4455 {
println(7, u32)
panic("fail")
}
u64 = ia[12].(uint64)
if u64 != 765432 {
println(8, u64)
panic("fail")
}
}
```
## range
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test method invocation with pointer receivers and function-valued fields.
package main
type C struct {
a int;
x func(p *C)int;
}
func (this *C) f()int {
return this.a;
}
func
main() {
var v int;
var c *C;
c = new(C);
c.a = 6;
c.x = g;
v = g(c);
if v != 6 { panic(v); }
v = c.x(c);
if v != 6 { panic(v); }
v = c.f();
if v != 6 { panic(v); }
}
func g(p *C)int {
var v int;
v = p.a;
if v != 6 { panic(v); }
return p.a;
}
```
## rob1
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test pointers and the . (selector) operator on structs.
package main
type x2 struct { a,b,c int; d int; };
var g1 x2;
var g2 struct { a,b,c int; d x2; };
func
main() {
var x int;
var s1 *x2;
var s2 *struct { a,b,c int; d x2; };
s1 = &g1;
s2 = &g2;
s1.a = 1;
s1.b = 2;
s1.c = 3;
s1.d = 5;
s2.a = 7;
s2.b = 11;
s2.c = 13;
s2.d.a = 17;
s2.d.b = 19;
s2.d.c = 23;
s2.d.d = 20;
if(s2.d.c != 23) { panic(1); }
if(g2.d.c != 23) { panic(2); }
x = s1.a +
s1.b +
s1.c +
s1.d +
s2.a +
s2.b +
s2.c +
s2.d.a +
s2.d.b +
s2.d.c +
s2.d.d;
if(x != 121) { panic(x); }
}
```
## robfor
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test 'for range' on arrays, slices, and maps.
package main
const size = 16
var a [size]byte
var p []byte
var m map[int]byte
func f(k int) byte {
return byte(k * 10007 % size)
}
func init() {
p = make([]byte, size)
m = make(map[int]byte)
for k := 0; k < size; k++ {
v := f(k)
a[k] = v
p[k] = v
m[k] = v
}
}
func main() {
var i int
/*
* key only
*/
i = 0
for k := range a {
v := a[k]
if v != f(k) {
println("key array range", k, v, a[k])
panic("fail")
}
i++
}
if i != size {
println("key array size", i)
panic("fail")
}
i = 0
for k := range p {
v := p[k]
if v != f(k) {
println("key pointer range", k, v, p[k])
panic("fail")
}
i++
}
if i != size {
println("key pointer size", i)
panic("fail")
}
i = 0
for k := range m {
v := m[k]
if v != f(k) {
println("key map range", k, v, m[k])
panic("fail")
}
i++
}
if i != size {
println("key map size", i)
panic("fail")
}
/*
* key,value
*/
i = 0
for k, v := range a {
if v != f(k) {
println("key:value array range", k, v, a[k])
panic("fail")
}
i++
}
if i != size {
println("key:value array size", i)
panic("fail")
}
i = 0
for k, v := range p {
if v != f(k) {
println("key:value pointer range", k, v, p[k])
panic("fail")
}
i++
}
if i != size {
println("key:value pointer size", i)
panic("fail")
}
i = 0
for k, v := range m {
if v != f(k) {
println("key:value map range", k, v, m[k])
panic("fail")
}
i++
}
if i != size {
println("key:value map size", i)
panic("fail")
}
}
```
## robfunc
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test general operation using a list implementation.
package main
type Item interface {
Print() string
}
type ListItem struct {
item Item
next *ListItem
}
type List struct {
head *ListItem
}
func (list *List) Init() {
list.head = nil
}
func (list *List) Insert(i Item) {
item := new(ListItem)
item.item = i
item.next = list.head
list.head = item
}
func (list *List) Print() string {
r := ""
i := list.head
for i != nil {
r += i.item.Print()
i = i.next
}
return r
}
// Something to put in a list
type Integer struct {
val int
}
func (this *Integer) Init(i int) *Integer {
this.val = i
return this
}
func (this *Integer) Print() string {
return string(this.val + '0')
}
func main() {
list := new(List)
list.Init()
for i := 0; i < 10; i = i + 1 {
integer := new(Integer)
integer.Init(i)
list.Insert(integer)
}
r := list.Print()
if r != "9876543210" {
panic(r)
}
}
```
## shift
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test for loops of many forms.
package main
func assertequal(is, shouldbe int, msg string) {
if is != shouldbe {
print("assertion fail" + msg + "\n");
panic(1);
}
}
func main() {
var i, sum int;
i = 0;
for {
i = i + 1;
if i > 5 {
break;
}
}
assertequal(i, 6, "break");
sum = 0;
for i := 0; i <= 10; i++ {
sum = sum + i;
}
assertequal(sum, 55, "all three");
sum = 0;
for i := 0; i <= 10; {
sum = sum + i;
i++;
}
assertequal(sum, 55, "only two");
sum = 0;
for sum < 100 {
sum = sum + 9;
}
assertequal(sum, 99 + 9, "only one");
sum = 0;
for i := 0; i <= 10; i++ {
if i % 2 == 0 {
continue;
}
sum = sum + i;
}
assertequal(sum, 1+3+5+7+9, "continue");
}
```
## simparray
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test functions of many signatures.
package main
func assertequal(is, shouldbe int, msg string) {
if is != shouldbe {
print("assertion fail" + msg + "\n")
panic(1)
}
}
func f1() {
}
func f2(a int) {
}
func f3(a, b int) int {
return a + b
}
func f4(a, b int, c float64) int {
return (a+b)/2 + int(c)
}
func f5(a int) int {
return 5
}
func f6(a int) (r int) {
return 6
}
func f7(a int) (x int, y float64) {
return 7, 7.0
}
func f8(a int) (x int, y float64) {
return 8, 8.0
}
type T struct {
x, y int
}
func (t *T) m10(a int, b float64) int {
return (t.x + a) * (t.y + int(b))
}
func f9(a int) (in int, fl float64) {
i := 9
f := float64(9)
return i, f
}
func main() {
f1()
f2(1)
r3 := f3(1, 2)
assertequal(r3, 3, "3")
r4 := f4(0, 2, 3.0)
assertequal(r4, 4, "4")
r5 := f5(1)
assertequal(r5, 5, "5")
r6 := f6(1)
assertequal(r6, 6, "6")
var r7 int
var s7 float64
r7, s7 = f7(1)
assertequal(r7, 7, "r7")
assertequal(int(s7), 7, "s7")
var r8 int
var s8 float64
r8, s8 = f8(1)
assertequal(r8, 8, "r8")
assertequal(int(s8), 8, "s8")
var r9 int
var s9 float64
r9, s9 = f9(1)
assertequal(r9, 9, "r9")
assertequal(int(s9), 9, "s9")
var t *T = new(T)
t.x = 1
t.y = 2
r10 := t.m10(1, 3.0)
assertequal(r10, 10, "10")
}
```
## simpswitch
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test simple arithmetic conversion.
package main
type vlong int64
type short int16
func main() {
s1 := vlong(0)
for i := short(0); i < 10; i = i + 1 {
s1 = s1 + vlong(i)
}
if s1 != 45 {
panic(s1)
}
s2 := float64(0)
for i := 0; i < 10; i = i + 1 {
s2 = s2 + float64(i)
}
if s2 != 45 {
panic(s2)
}
}
```
## slicearray
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test simple switch.
package main
func main() {
r := ""
a := 3
for i := 0; i < 10; i = i + 1 {
switch i {
case 5:
r += "five"
case a, 7:
r += "a"
default:
r += string(i + '0')
}
r += "out" + string(i+'0')
}
if r != "0out01out12out2aout34out4fiveout56out6aout78out89out9" {
panic(r)
}
}
```
## sliceslice
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test scoping of variables.
package main
var x,y int;
func
main() {
x = 15;
y = 20;
{
var x int;
x = 25;
y = 25;
_ = x;
}
x = x+y;
if(x != 40) { panic(x); }
}
```
## string_
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test basic operations of slices and arrays.
package main
var bx [10]byte
var by []byte
var fx [10]float64
var fy []float64
var lb, hb int
var t int
func main() {
lb = 0
hb = 10
by = bx[0:]
tstb()
lb = 0
hb = 10
fy = fx[0:]
tstf()
// width 1 (byte)
lb = 0
hb = 10
by = bx[lb:hb]
tstb()
by = bx[lb:10]
tstb()
by = bx[lb:]
tstb()
by = bx[:hb]
tstb()
by = bx[0:hb]
tstb()
by = bx[0:10]
tstb()
by = bx[0:]
tstb()
by = bx[:10]
tstb()
by = bx[:]
tstb()
lb = 2
hb = 10
by = bx[lb:hb]
tstb()
by = bx[lb:10]
tstb()
by = bx[lb:]
tstb()
by = bx[2:hb]
tstb()
by = bx[2:10]
tstb()
by = bx[2:]
tstb()
lb = 0
hb = 8
by = bx[lb:hb]
tstb()
by = bx[lb:8]
tstb()
by = bx[0:hb]
tstb()
by = bx[0:8]
tstb()
by = bx[:8]
tstb()
by = bx[:hb]
tstb()
lb = 2
hb = 8
by = bx[lb:hb]
tstb()
by = bx[lb:8]
tstb()
by = bx[2:hb]
tstb()
by = bx[2:8]
tstb()
// width 8 (float64)
lb = 0
hb = 10
fy = fx[lb:hb]
tstf()
fy = fx[lb:10]
tstf()
fy = fx[lb:]
tstf()
fy = fx[:hb]
tstf()
fy = fx[0:hb]
tstf()
fy = fx[0:10]
tstf()
fy = fx[0:]
tstf()
fy = fx[:10]
tstf()
fy = fx[:]
tstf()
lb = 2
hb = 10
fy = fx[lb:hb]
tstf()
fy = fx[lb:10]
tstf()
fy = fx[lb:]
tstf()
fy = fx[2:hb]
tstf()
fy = fx[2:10]
tstf()
fy = fx[2:]
tstf()
lb = 0
hb = 8
fy = fx[lb:hb]
tstf()
fy = fx[lb:8]
tstf()
fy = fx[:hb]
tstf()
fy = fx[0:hb]
tstf()
fy = fx[0:8]
tstf()
fy = fx[:8]
tstf()
lb = 2
hb = 8
fy = fx[lb:hb]
tstf()
fy = fx[lb:8]
tstf()
fy = fx[2:hb]
tstf()
fy = fx[2:8]
tstf()
}
func tstb() {
t++
if len(by) != hb-lb {
println("t=", t, "lb=", lb, "hb=", hb,
"len=", len(by), "hb-lb=", hb-lb)
panic("fail")
}
if cap(by) != len(bx)-lb {
println("t=", t, "lb=", lb, "hb=", hb,
"cap=", cap(by), "len(bx)-lb=", len(bx)-lb)
panic("fail")
}
for i := lb; i < hb; i++ {
if bx[i] != by[i-lb] {
println("t=", t, "lb=", lb, "hb=", hb,
"bx[", i, "]=", bx[i],
"by[", i-lb, "]=", by[i-lb])
panic("fail")
}
}
by = nil
}
func tstf() {
t++
if len(fy) != hb-lb {
println("t=", t, "lb=", lb, "hb=", hb,
"len=", len(fy), "hb-lb=", hb-lb)
panic("fail")
}
if cap(fy) != len(fx)-lb {
println("t=", t, "lb=", lb, "hb=", hb,
"cap=", cap(fy), "len(fx)-lb=", len(fx)-lb)
panic("fail")
}
for i := lb; i < hb; i++ {
if fx[i] != fy[i-lb] {
println("t=", t, "lb=", lb, "hb=", hb,
"fx[", i, "]=", fx[i],
"fy[", i-lb, "]=", fy[i-lb])
panic("fail")
}
}
fy = nil
}
func init() {
for i := 0; i < len(bx); i++ {
bx[i] = byte(i + 20)
}
by = nil
for i := 0; i < len(fx); i++ {
fx[i] = float64(i + 20)
}
fy = nil
}
```
## literal
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test string operations including printing.
package main
func main() {
var c string
a := `abc`
b := `xyz`
/* print a literal */
print(`abc`)
/* print a variable */
print(b, "-")
/* catenate literals */
print(`abc`+`xyz`, "-")
/* catenate variables */
print(a+b, "-")
/* compare literals */
if `abc` == `xyz` || `abc` != "abc" || `abc` > `xyz` {
panic("compare literals")
}
/* compare variables */
if a == b || a != a || a > b {
panic("compare variables")
}
/* cat */
c = a + b
print(c, "-")
/* catequal */
c = a
c += b
print(c, "-")
/* clumsy evaluation */
c = b
c = a + c
print(c, "-")
/* len */
if len(c) != 6 {
print("len ", len(c))
panic("fail")
}
/* index strings */
for i := 0; i < len(c); i = i + 1 {
if c[i] != (a + b)[i] {
print("index ", i, " ", c[i], " ", (a + b)[i])
panic("fail")
}
}
/* slice strings */
print(c[0:3], c[3:])
print("\n")
/* create string with integer constant */
c = string('x')
if c != "x" {
panic("create int " + c)
}
/* create string with integer variable */
v := 'x'
c = string(v)
if c != "x" {
panic("create int " + c)
}
/* create string with byte array */
var z1 [3]byte
z1[0] = 'a'
z1[1] = 'b'
z1[2] = 'c'
c = string(z1[0:])
if c != "abc" {
panic("create byte array " + c)
}
/* create string with int array */
var z2 [3]rune
z2[0] = 'a'
z2[1] = '\u1234'
z2[2] = 'c'
c = string(z2[0:])
if c != "a\u1234c" {
panic("create int array " + c)
}
/* create string with byte array pointer */
z3 := new([3]byte)
z3[0] = 'a'
z3[1] = 'b'
z3[2] = 'c'
c = string(z3[0:])
if c != "abc" {
panic("create array pointer " + c)
}
}
```
## method
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test struct-valued variables (not pointers).
package main
type x2 struct { a,b,c int; d int; };
var g1 x2;
var g2 struct { a,b,c int; d x2; };
func
main() {
var x int;
var s1 *x2;
var s2 *struct { a,b,c int; d x2; };
var s3 struct { a,b,c int; d x2; };
s1 = &g1;
s2 = &g2;
s1.a = 1;
s1.b = 2;
s1.c = 3;
s1.d = 5;
if(s1.c != 3) { panic(s1.c); }
if(g1.c != 3) { panic(g1.c); }
s2.a = 7;
s2.b = 11;
s2.c = 13;
s2.d.a = 17;
s2.d.b = 19;
s2.d.c = 23;
s2.d.d = 29;
if(s2.d.c != 23) { panic(s2.d.c); }
if(g2.d.c != 23) { panic(g2.d.c); }
x = s1.a +
s1.b +
s1.c +
s1.d +
s2.a +
s2.b +
s2.c +
s2.d.a +
s2.d.b +
s2.d.c +
s2.d.d;
if(x != 130) { panic(x); }
// test an automatic struct
s3.a = 7;
s3.b = 11;
s3.c = 13;
s3.d.a = 17;
s3.d.b = 19;
s3.d.c = 23;
s3.d.d = 29;
if(s3.d.c != 23) { panic(s3.d.c); }
x = s3.a +
s3.b +
s3.c +
s3.d.a +
s3.d.b +
s3.d.c +
s3.d.d;
if(x != 119) { panic(x); }
}
```
## method3
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test literal syntax for basic types.
package main
var nbad int
func assert(cond bool, msg string) {
if !cond {
if nbad == 0 {
print("BUG")
}
nbad++
print(" ", msg)
}
}
func equal(a, b float32) bool {
return a == b
}
func main() {
// bool
var t bool = true
var f bool = false
assert(t == !f, "bool")
// int8
var i00 int8 = 0
var i01 int8 = 1
var i02 int8 = -1
var i03 int8 = 127
var i04 int8 = -127
var i05 int8 = -128
var i06 int8 = +127
assert(i01 == i00+1, "i01")
assert(i02 == -i01, "i02")
assert(i03 == -i04, "i03")
assert(-(i05+1) == i06, "i05")
// int16
var i10 int16 = 0
var i11 int16 = 1
var i12 int16 = -1
var i13 int16 = 32767
var i14 int16 = -32767
var i15 int16 = -32768
var i16 int16 = +32767
assert(i11 == i10+1, "i11")
assert(i12 == -i11, "i12")
assert(i13 == -i14, "i13")
assert(-(i15+1) == i16, "i15")
// int32
var i20 int32 = 0
var i21 int32 = 1
var i22 int32 = -1
var i23 int32 = 2147483647
var i24 int32 = -2147483647
var i25 int32 = -2147483648
var i26 int32 = +2147483647
assert(i21 == i20+1, "i21")
assert(i22 == -i21, "i22")
assert(i23 == -i24, "i23")
assert(-(i25+1) == i26, "i25")
assert(i23 == (1<<31)-1, "i23 size")
// int64
var i30 int64 = 0
var i31 int64 = 1
var i32 int64 = -1
var i33 int64 = 9223372036854775807
var i34 int64 = -9223372036854775807
var i35 int64 = -9223372036854775808
var i36 int64 = +9223372036854775807
assert(i31 == i30+1, "i31")
assert(i32 == -i31, "i32")
assert(i33 == -i34, "i33")
assert(-(i35+1) == i36, "i35")
assert(i33 == (1<<63)-1, "i33 size")
// uint8
var u00 uint8 = 0
var u01 uint8 = 1
var u02 uint8 = 255
var u03 uint8 = +255
assert(u01 == u00+1, "u01")
assert(u02 == u03, "u02")
assert(u03 == (1<<8)-1, "u03 size")
// uint16
var u10 uint16 = 0
var u11 uint16 = 1
var u12 uint16 = 65535
var u13 uint16 = +65535
assert(u11 == u10+1, "u11")
assert(u12 == u13, "u12")
// uint32
var u20 uint32 = 0
var u21 uint32 = 1
var u22 uint32 = 4294967295
var u23 uint32 = +4294967295
assert(u21 == u20+1, "u21")
assert(u22 == u23, "u22")
// uint64
var u30 uint64 = 0
var u31 uint64 = 1
var u32 uint64 = 18446744073709551615
var u33 uint64 = +18446744073709551615
_, _, _, _ = u30, u31, u32, u33
// float
var f00 float32 = 3.14159
var f01 float32 = -3.14159
var f02 float32 = +3.14159
var f03 float32 = 0.0
var f04 float32 = .0
var f05 float32 = 0.
var f06 float32 = -0.0
var f07 float32 = 1e10
var f08 float32 = -1e10
var f09 float32 = 1e-10
var f10 float32 = 1e+10
var f11 float32 = 1.e-10
var f12 float32 = 1.e+10
var f13 float32 = .1e-10
var f14 float32 = .1e+10
var f15 float32 = 1.1e-10
var f16 float32 = 1.1e+10
assert(f01 == -f00, "f01")
assert(f02 == -f01, "f02")
assert(f03 == f04, "f03")
assert(f04 == f05, "f04")
assert(f05 == f06, "f05")
assert(f07 == -f08, "f07")
assert(equal(f09, 1/f10), "f09")
assert(f11 == f09, "f11")
assert(f12 == f10, "f12")
assert(equal(f13, f09/10.0), "f13")
assert(equal(f14, f12/10.0), "f14")
assert(equal(f15, f16/1e20), "f15")
// character
var c0 uint8 = 'a'
var c1 uint8 = 'ä'
var c2 uint8 = '\a'
var c3 uint8 = '\b'
var c4 uint8 = '\f'
var c5 uint8 = '\n'
var c6 uint8 = '\r'
var c7 uint8 = '\t'
var c8 uint8 = '\v'
// var c9 uint8 = '本' // correctly caught as error
var c9 uint16 = '本'
assert(c0 == 0x61, "c0")
assert(c1 == 0xe4, "c1")
assert(c2 == 0x07, "c2")
assert(c3 == 0x08, "c3")
assert(c4 == 0x0c, "c4")
assert(c5 == 0x0a, "c4")
assert(c6 == 0x0d, "c6")
assert(c7 == 0x09, "c7")
assert(c8 == 0x0b, "c8")
assert(c9 == 0x672c, "c9")
var c00 uint8 = '\000'
var c01 uint8 = '\007'
var c02 uint8 = '\177'
var c03 uint8 = '\377'
assert(c00 == 0, "c00")
assert(c01 == 7, "c01")
assert(c02 == 127, "c02")
assert(c03 == 255, "c03")
var cx0 uint8 = '\x00'
var cx1 uint8 = '\x0f'
var cx2 uint8 = '\xff'
assert(cx0 == 0, "cx0")
assert(cx1 == 15, "cx1")
assert(cx2 == 255, "cx2")
var cu0 uint16 = '\u1234'
var cu1 uint32 = '\U00101234'
assert(cu0 == 0x1234, "cu0")
assert(cu1 == 0x101234, "cu1")
// string
var s0 string = ""
var s1 string = "hellô"
assert(s1[0] == 'h', "s1-0")
assert(s1[4] == 0xc3, "s1-4")
assert(s1[5] == 0xb4, "s1-5")
var s2 string = "\a\b\f\n\r\t\v"
_, _ = s0, s2
var s00 string = "\000"
var s01 string = "\007"
var s02 string = "\377"
assert(s00[0] == 0, "s00")
assert(s01[0] == 7, "s01")
assert(s02[0] == 255, "s02")
var x00 string = "\x00"
var x01 string = "\x0f"
var x02 string = "\xff"
assert(x00[0] == 0, "x00")
assert(x01[0] == 15, "x01")
assert(x02[0] == 255, "x02")
// these are all the same string
var sj0 string = "日本語"
var sj1 string = "\u65e5\u672c\u8a9e"
var sj2 string = "\U000065e5\U0000672c\U00008a9e"
var sj3 string = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"
assert(sj0 == sj1, "sj1")
assert(sj0 == sj2, "sj2")
assert(sj0 == sj3, "sj3")
if nbad > 0 {
panic("literal failed")
}
}
```
## method5
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test simple methods of various types, with pointer and
// value receivers.
package main
type S string
type S1 string
type I int
type I1 int
type T struct {
x int
}
type T1 T
func (s S) val() int { return 1 }
func (s *S1) val() int { return 2 }
func (i I) val() int { return 3 }
func (i *I1) val() int { return 4 }
func (t T) val() int { return 7 }
func (t *T1) val() int { return 8 }
type Val interface {
val() int
}
func val(v Val) int { return v.val() }
func main() {
var s S
var ps *S1
var i I
var pi *I1
var pt *T1
var t T
var v Val
if s.val() != 1 {
println("s.val:", s.val())
panic("fail")
}
if S.val(s) != 1 {
println("S.val(s):", S.val(s))
panic("fail")
}
if (*S).val(&s) != 1 {
println("(*S).val(s):", (*S).val(&s))
panic("fail")
}
if ps.val() != 2 {
println("ps.val:", ps.val())
panic("fail")
}
if (*S1).val(ps) != 2 {
println("(*S1).val(ps):", (*S1).val(ps))
panic("fail")
}
if i.val() != 3 {
println("i.val:", i.val())
panic("fail")
}
if I.val(i) != 3 {
println("I.val(i):", I.val(i))
panic("fail")
}
if (*I).val(&i) != 3 {
println("(*I).val(&i):", (*I).val(&i))
panic("fail")
}
if pi.val() != 4 {
println("pi.val:", pi.val())
panic("fail")
}
if (*I1).val(pi) != 4 {
println("(*I1).val(pi):", (*I1).val(pi))
panic("fail")
}
if t.val() != 7 {
println("t.val:", t.val())
panic("fail")
}
if pt.val() != 8 {
println("pt.val:", pt.val())
panic("fail")
}
if (*T1).val(pt) != 8 {
println("(*T1).val(pt):", (*T1).val(pt))
panic("fail")
}
if val(s) != 1 {
println("val(s):", val(s))
panic("fail")
}
if val(ps) != 2 {
println("val(ps):", val(ps))
panic("fail")
}
if val(i) != 3 {
println("val(i):", val(i))
panic("fail")
}
if val(pi) != 4 {
println("val(pi):", val(pi))
panic("fail")
}
if val(t) != 7 {
println("val(t):", val(t))
panic("fail")
}
if val(pt) != 8 {
println("val(pt):", val(pt))
panic("fail")
}
if Val.val(i) != 3 {
println("Val.val(i):", Val.val(i))
panic("fail")
}
v = i
if Val.val(v) != 3 {
println("Val.val(v):", Val.val(v))
panic("fail")
}
var zs struct{ S }
var zps struct{ *S1 }
var zi struct{ I }
var zpi struct{ *I1 }
var zpt struct{ *T1 }
var zt struct{ T }
var zv struct{ Val }
if zs.val() != 1 {
println("zs.val:", zs.val())
panic("fail")
}
if zps.val() != 2 {
println("zps.val:", zps.val())
panic("fail")
}
if zi.val() != 3 {
println("zi.val:", zi.val())
panic("fail")
}
if zpi.val() != 4 {
println("zpi.val:", zpi.val())
panic("fail")
}
if zt.val() != 7 {
println("zt.val:", zt.val())
panic("fail")
}
if zpt.val() != 8 {
println("zpt.val:", zpt.val())
panic("fail")
}
if val(zs) != 1 {
println("val(zs):", val(zs))
panic("fail")
}
if val(zps) != 2 {
println("val(zps):", val(zps))
panic("fail")
}
if val(zi) != 3 {
println("val(zi):", val(zi))
panic("fail")
}
if val(zpi) != 4 {
println("val(zpi):", val(zpi))
panic("fail")
}
if val(zt) != 7 {
println("val(zt):", val(zt))
panic("fail")
}
if val(zpt) != 8 {
println("val(zpt):", val(zpt))
panic("fail")
}
zv.Val = zi
if zv.val() != 3 {
println("zv.val():", zv.val())
panic("fail")
}
if (&zs).val() != 1 {
println("(&zs).val:", (&zs).val())
panic("fail")
}
if (&zps).val() != 2 {
println("(&zps).val:", (&zps).val())
panic("fail")
}
if (&zi).val() != 3 {
println("(&zi).val:", (&zi).val())
panic("fail")
}
if (&zpi).val() != 4 {
println("(&zpi).val:", (&zpi).val())
panic("fail")
}
if (&zt).val() != 7 {
println("(&zt).val:", (&zt).val())
panic("fail")
}
if (&zpt).val() != 8 {
println("(&zpt).val:", (&zpt).val())
panic("fail")
}
if val(&zs) != 1 {
println("val(&zs):", val(&zs))
panic("fail")
}
if val(&zps) != 2 {
println("val(&zps):", val(&zps))
panic("fail")
}
if val(&zi) != 3 {
println("val(&zi):", val(&zi))
panic("fail")
}
if val(&zpi) != 4 {
println("val(&zpi):", val(&zpi))
panic("fail")
}
if val(&zt) != 7 {
println("val(&zt):", val(&zt))
panic("fail")
}
if val(&zpt) != 8 {
println("val(&zpt):", val(&zpt))
panic("fail")
}
zv.Val = &zi
if zv.val() != 3 {
println("zv.val():", zv.val())
panic("fail")
}
promotion()
}
type A struct{ B }
type B struct {
C
*D
}
type C int
func (C) f() {} // value receiver, direct field of A
func (*C) g() {} // pointer receiver
type D int
func (D) h() {} // value receiver, indirect field of A
func (*D) i() {} // pointer receiver
func expectPanic() {
if r := recover(); r == nil {
panic("expected nil dereference")
}
}
func promotion() {
var a A
// Addressable value receiver.
a.f()
a.g()
func() {
defer expectPanic()
a.h() // dynamic error: nil dereference in a.B.D->f()
}()
a.i()
// Non-addressable value receiver.
A(a).f()
// A(a).g() // static error: cannot call pointer method on A literal.B.C
func() {
defer expectPanic()
A(a).h() // dynamic error: nil dereference in A().B.D->f()
}()
A(a).i()
// Pointer receiver.
(&a).f()
(&a).g()
func() {
defer expectPanic()
(&a).h() // dynamic error: nil deref: nil dereference in (&a).B.D->f()
}()
(&a).i()
c := new(C)
c.f() // makes a copy
c.g()
}
```
## method7
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test methods on slices.
package main
type T []int
func (t T) Len() int { return len(t) }
type I interface {
Len() int
}
func main() {
var t T = T{0, 1, 2, 3, 4}
var i I
i = t
if i.Len() != 5 {
println("i.Len", i.Len())
panic("fail")
}
if T.Len(t) != 5 {
println("T.Len", T.Len(t))
panic("fail")
}
if (*T).Len(&t) != 5 {
println("(*T).Len", (*T).Len(&t))
panic("fail")
}
}
```
## nilptr2
```go
// run
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
// Concrete types implementing M method.
// Smaller than a word, word-sized, larger than a word.
// Value and pointer receivers.
type Tinter interface {
M(int, byte) (byte, int)
}
type Tsmallv byte
func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x+int(v) }
type Tsmallp byte
func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x+int(*p) }
type Twordv uintptr
func (v Twordv) M(x int, b byte) (byte, int) { return b, x+int(v) }
type Twordp uintptr
func (p *Twordp) M(x int, b byte) (byte, int) { return b, x+int(*p) }
type Tbigv [2]uintptr
func (v Tbigv) M(x int, b byte) (byte, int) { return b, x+int(v[0])+int(v[1]) }
type Tbigp [2]uintptr
func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x+int(p[0])+int(p[1]) }
// Again, with an unexported method.
type tsmallv byte
func (v tsmallv) m(x int, b byte) (byte, int) { return b, x+int(v) }
type tsmallp byte
func (p *tsmallp) m(x int, b byte) (byte, int) { return b, x+int(*p) }
type twordv uintptr
func (v twordv) m(x int, b byte) (byte, int) { return b, x+int(v) }
type twordp uintptr
func (p *twordp) m(x int, b byte) (byte, int) { return b, x+int(*p) }
type tbigv [2]uintptr
func (v tbigv) m(x int, b byte) (byte, int) { return b, x+int(v[0])+int(v[1]) }
type tbigp [2]uintptr
func (p *tbigp) m(x int, b byte) (byte, int) { return b, x+int(p[0])+int(p[1]) }
type tinter interface {
m(int, byte) (byte, int)
}
// Embedding via pointer.
type T1 struct {
T2
}
type T2 struct {
*T3
}
type T3 struct {
*T4
}
type T4 struct {
}
func (t4 T4) M(x int, b byte) (byte, int) { return b, x+40 }
var failed = false
func CheckI(name string, i Tinter, inc int) {
b, x := i.M(1000, 99)
if b != 99 || x != 1000+inc {
failed = true
print(name, ".M(1000, 99) = ", b, ", ", x, " want 99, ", 1000+inc, "\n")
}
CheckF("(i="+name+")", i.M, inc)
}
func CheckF(name string, f func(int, byte) (byte, int), inc int) {
b, x := f(1000, 99)
if b != 99 || x != 1000+inc {
failed = true
print(name, "(1000, 99) = ", b, ", ", x, " want 99, ", 1000+inc, "\n")
}
}
func checkI(name string, i tinter, inc int) {
b, x := i.m(1000, 99)
if b != 99 || x != 1000+inc {
failed = true
print(name, ".m(1000, 99) = ", b, ", ", x, " want 99, ", 1000+inc, "\n")
}
checkF("(i="+name+")", i.m, inc)
}
func checkF(name string, f func(int, byte) (byte, int), inc int) {
b, x := f(1000, 99)
if b != 99 || x != 1000+inc {
failed = true
print(name, "(1000, 99) = ", b, ", ", x, " want 99, ", 1000+inc, "\n")
}
}
func shouldPanic(f func()) {
defer func() {
if recover() == nil {
panic("not panicking")
}
}()
f()
}
func shouldNotPanic(f func()) {
f()
}
func main() {
sv := Tsmallv(1)
CheckI("sv", sv, 1)
CheckF("sv.M", sv.M, 1)
CheckF("(&sv).M", (&sv).M, 1)
psv := &sv
CheckI("psv", psv, 1)
CheckF("psv.M", psv.M, 1)
CheckF("(*psv).M", (*psv).M, 1)
sp := Tsmallp(2)
CheckI("&sp", &sp, 2)
CheckF("sp.M", sp.M, 2)
CheckF("(&sp).M", (&sp).M, 2)
psp := &sp
CheckI("psp", psp, 2)
CheckF("psp.M", psp.M, 2)
CheckF("(*psp).M", (*psp).M, 2)
wv := Twordv(3)
CheckI("wv", wv, 3)
CheckF("wv.M", wv.M, 3)
CheckF("(&wv).M", (&wv).M, 3)
pwv := &wv
CheckI("pwv", pwv, 3)
CheckF("pwv.M", pwv.M, 3)
CheckF("(*pwv).M", (*pwv).M, 3)
wp := Twordp(4)
CheckI("&wp", &wp, 4)
CheckF("wp.M", wp.M, 4)
CheckF("(&wp).M", (&wp).M, 4)
pwp := &wp
CheckI("pwp", pwp, 4)
CheckF("pwp.M", pwp.M, 4)
CheckF("(*pwp).M", (*pwp).M, 4)
bv := Tbigv([2]uintptr{5, 6})
pbv := &bv
CheckI("bv", bv, 11)
CheckF("bv.M", bv.M, 11)
CheckF("(&bv).M", (&bv).M, 11)
CheckI("pbv", pbv, 11)
CheckF("pbv.M", pbv.M, 11)
CheckF("(*pbv).M", (*pbv).M, 11)
bp := Tbigp([2]uintptr{7,8})
CheckI("&bp", &bp, 15)
CheckF("bp.M", bp.M, 15)
CheckF("(&bp).M", (&bp).M, 15)
pbp := &bp
CheckI("pbp", pbp, 15)
CheckF("pbp.M", pbp.M, 15)
CheckF("(*pbp).M", (*pbp).M, 15)
_sv := tsmallv(1)
checkI("_sv", _sv, 1)
checkF("_sv.m", _sv.m, 1)
checkF("(&_sv).m", (&_sv).m, 1)
_psv := &_sv
checkI("_psv", _psv, 1)
checkF("_psv.m", _psv.m, 1)
checkF("(*_psv).m", (*_psv).m, 1)
_sp := tsmallp(2)
checkI("&_sp", &_sp, 2)
checkF("_sp.m", _sp.m, 2)
checkF("(&_sp).m", (&_sp).m, 2)
_psp := &_sp
checkI("_psp", _psp, 2)
checkF("_psp.m", _psp.m, 2)
checkF("(*_psp).m", (*_psp).m, 2)
_wv := twordv(3)
checkI("_wv", _wv, 3)
checkF("_wv.m", _wv.m, 3)
checkF("(&_wv).m", (&_wv).m, 3)
_pwv := &_wv
checkI("_pwv", _pwv, 3)
checkF("_pwv.m", _pwv.m, 3)
checkF("(*_pwv).m", (*_pwv).m, 3)
_wp := twordp(4)
checkI("&_wp", &_wp, 4)
checkF("_wp.m", _wp.m, 4)
checkF("(&_wp).m", (&_wp).m, 4)
_pwp := &_wp
checkI("_pwp", _pwp, 4)
checkF("_pwp.m", _pwp.m, 4)
checkF("(*_pwp).m", (*_pwp).m, 4)
_bv := tbigv([2]uintptr{5, 6})
_pbv := &_bv
checkI("_bv", _bv, 11)
checkF("_bv.m", _bv.m, 11)
checkF("(&_bv).m", (&_bv).m, 11)
checkI("_pbv", _pbv, 11)
checkF("_pbv.m", _pbv.m, 11)
checkF("(*_pbv).m", (*_pbv).m, 11)
_bp := tbigp([2]uintptr{7,8})
checkI("&_bp", &_bp, 15)
checkF("_bp.m", _bp.m, 15)
checkF("(&_bp).m", (&_bp).m, 15)
_pbp := &_bp
checkI("_pbp", _pbp, 15)
checkF("_pbp.m", _pbp.m, 15)
checkF("(*_pbp).m", (*_pbp).m, 15)
t4 := T4{}
t3 := T3{&t4}
t2 := T2{&t3}
t1 := T1{t2}
CheckI("t4", t4, 40)
CheckI("&t4", &t4, 40)
CheckI("t3", t3, 40)
CheckI("&t3", &t3, 40)
CheckI("t2", t2, 40)
CheckI("&t2", &t2, 40)
CheckI("t1", t1, 40)
CheckI("&t1", &t1, 40)
// x.M panics if x is an interface type and is nil,
// or if x.M expands to (*x).M where x is nil,
// or if x.M expands to x.y.z.w.M where something
// along the evaluation of x.y.z.w is nil.
var f func(int, byte) (byte, int)
shouldPanic(func() { psv = nil; f = psv.M })
shouldPanic(func() { pwv = nil; f = pwv.M })
shouldPanic(func() { pbv = nil; f = pbv.M })
shouldPanic(func() { var i Tinter; f = i.M })
shouldPanic(func() { _psv = nil; f = _psv.m })
shouldPanic(func() { _pwv = nil; f = _pwv.m })
shouldPanic(func() { _pbv = nil; f = _pbv.m })
shouldPanic(func() { var _i tinter; f = _i.m })
shouldPanic(func() { var t1 T1; f = t1.M })
shouldPanic(func() { var t2 T2; f = t2.M })
shouldPanic(func() { var t3 *T3; f = t3.M })
shouldPanic(func() { var t3 T3; f = t3.M })
if f != nil {
panic("something set f")
}
// x.M does not panic if x is a nil pointer and
// M is a method with a pointer receiver.
shouldNotPanic(func() { psp = nil; f = psp.M })
shouldNotPanic(func() { pwp = nil; f = pwp.M })
shouldNotPanic(func() { pbp = nil; f = pbp.M })
shouldNotPanic(func() { _psp = nil; f = _psp.m })
shouldNotPanic(func() { _pwp = nil; f = _pwp.m })
shouldNotPanic(func() { _pbp = nil; f = _pbp.m })
shouldNotPanic(func() { var t4 T4; f = t4.M })
if f == nil {
panic("nothing set f")
}
}
```
## print
```go
// run
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test forms of method expressions T.m where T is
// a literal type.
package main
var got, want string
type I interface {
m()
}
type S struct {
}
func (S) m() { got += " m()" }
func (S) m1(s string) { got += " m1(" + s + ")" }
type T int
func (T) m2() { got += " m2()" }
type Outer struct{ *Inner }
type Inner struct{ s string }
func (i Inner) M() string { return i.s }
func main() {
// method expressions with named receiver types
I.m(S{})
want += " m()"
S.m1(S{}, "a")
want += " m1(a)"
// method expressions with literal receiver types
f := interface{ m1(string) }.m1
f(S{}, "b")
want += " m1(b)"
interface{ m1(string) }.m1(S{}, "c")
want += " m1(c)"
x := S{}
interface{ m1(string) }.m1(x, "d")
want += " m1(d)"
g := struct{ T }.m2
g(struct{ T }{})
want += " m2()"
if got != want {
panic("got" + got + ", want" + want)
}
h := (*Outer).M
got := h(&Outer{&Inner{"hello"}})
want := "hello"
if got != want {
panic("got " + got + ", want " + want)
}
}
```
## printbig
```go
// run
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
ok := true
for _, tt := range tests {
func() {
defer func() {
if err := recover(); err == nil {
println(tt.name, "did not panic")
ok = false
}
}()
tt.fn()
}()
}
if !ok {
println("BUG")
}
}
var intp *int
var slicep *[]byte
var a10p *[10]int
var a10Mp *[1<<20]int
var structp *Struct
var bigstructp *BigStruct
var i int
var m *M
var m1 *M1
var m2 *M2
var V interface{}
func use(x interface{}) {
V = x
}
var tests = []struct{
name string
fn func()
}{
// Edit .+1,/^}/s/^[^ ].+/ {"&", func() { println(&) }},\n {"\&&", func() { println(\&&) }},/g
{"*intp", func() { println(*intp) }},
{"&*intp", func() { println(&*intp) }},
{"*slicep", func() { println(*slicep) }},
{"&*slicep", func() { println(&*slicep) }},
{"(*slicep)[0]", func() { println((*slicep)[0]) }},
{"&(*slicep)[0]", func() { println(&(*slicep)[0]) }},
{"(*slicep)[i]", func() { println((*slicep)[i]) }},
{"&(*slicep)[i]", func() { println(&(*slicep)[i]) }},
{"*a10p", func() { use(*a10p) }},
{"&*a10p", func() { println(&*a10p) }},
{"a10p[0]", func() { println(a10p[0]) }},
{"&a10p[0]", func() { println(&a10p[0]) }},
{"a10p[i]", func() { println(a10p[i]) }},
{"&a10p[i]", func() { println(&a10p[i]) }},
{"*structp", func() { use(*structp) }},
{"&*structp", func() { println(&*structp) }},
{"structp.i", func() { println(structp.i) }},
{"&structp.i", func() { println(&structp.i) }},
{"structp.j", func() { println(structp.j) }},
{"&structp.j", func() { println(&structp.j) }},
{"structp.k", func() { println(structp.k) }},
{"&structp.k", func() { println(&structp.k) }},
{"structp.x[0]", func() { println(structp.x[0]) }},
{"&structp.x[0]", func() { println(&structp.x[0]) }},
{"structp.x[i]", func() { println(structp.x[i]) }},
{"&structp.x[i]", func() { println(&structp.x[i]) }},
{"structp.x[9]", func() { println(structp.x[9]) }},
{"&structp.x[9]", func() { println(&structp.x[9]) }},
{"structp.l", func() { println(structp.l) }},
{"&structp.l", func() { println(&structp.l) }},
{"*bigstructp", func() { use(*bigstructp) }},
{"&*bigstructp", func() { println(&*bigstructp) }},
{"bigstructp.i", func() { println(bigstructp.i) }},
{"&bigstructp.i", func() { println(&bigstructp.i) }},
{"bigstructp.j", func() { println(bigstructp.j) }},
{"&bigstructp.j", func() { println(&bigstructp.j) }},
{"bigstructp.k", func() { println(bigstructp.k) }},
{"&bigstructp.k", func() { println(&bigstructp.k) }},
{"bigstructp.x[0]", func() { println(bigstructp.x[0]) }},
{"&bigstructp.x[0]", func() { println(&bigstructp.x[0]) }},
{"bigstructp.x[i]", func() { println(bigstructp.x[i]) }},
{"&bigstructp.x[i]", func() { println(&bigstructp.x[i]) }},
{"bigstructp.x[9]", func() { println(bigstructp.x[9]) }},
{"&bigstructp.x[9]", func() { println(&bigstructp.x[9]) }},
{"bigstructp.x[100<<20]", func() { println(bigstructp.x[100<<20]) }},
{"&bigstructp.x[100<<20]", func() { println(&bigstructp.x[100<<20]) }},
{"bigstructp.l", func() { println(bigstructp.l) }},
{"&bigstructp.l", func() { println(&bigstructp.l) }},
{"m1.F()", func() { println(m1.F()) }},
{"m1.M.F()", func() { println(m1.M.F()) }},
{"m2.F()", func() { println(m2.F()) }},
{"m2.M.F()", func() { println(m2.M.F()) }},
}
type Struct struct {
i int
j float64
k string
x [10]int
l []byte
}
type BigStruct struct {
i int
j float64
k string
x [128<<20]byte
l []byte
}
type M struct {
}
func (m *M) F() int {return 0}
type M1 struct {
M
}
type M2 struct {
x int
M
}
```
## turing
```go
// run
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test that big numbers work as constants and print can print them.
package main
func main() {
print(-(1<<63), "\n")
print((1<<63)-1, "\n")
}
```
| 1 | 0.554569 | 1 | 0.554569 | game-dev | MEDIA | 0.340997 | game-dev | 0.911789 | 1 | 0.911789 |
FoundationAgents/MetaGPT | 17,640 | metagpt/environment/stanford_town/stanford_town_ext_env.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Desc : The StanfordTown external environment to interate with the web interface
# refs to `generative_agents maze.py`
import math
from pathlib import Path
from typing import Any, Optional
from pydantic import ConfigDict, Field, model_validator
from metagpt.environment.base_env import ExtEnv, mark_as_readable, mark_as_writeable
from metagpt.environment.stanford_town.env_space import (
EnvAction,
EnvActionType,
EnvObsParams,
EnvObsType,
EnvObsValType,
get_action_space,
get_observation_space,
)
from metagpt.utils.common import read_csv_to_list, read_json_file
class StanfordTownExtEnv(ExtEnv):
model_config = ConfigDict(arbitrary_types_allowed=True)
maze_asset_path: Optional[Path] = Field(default=None, description="the path to store maze assets")
maze_width: int = Field(default=140, description="maze map width")
maze_height: int = Field(default=100, description="maze map height")
sq_tile_size: int = Field(default=32, description="the pixel height/width of a tile")
special_constraint: str = Field(
default="", description="a string description of any relevant special constraints " "the world might have"
)
tiles: list[list[dict]] = Field(default=[])
address_tiles: dict[str, set] = Field(default=dict())
collision_maze: list[list] = Field(default=[])
@model_validator(mode="before")
@classmethod
def _init_maze(cls, values):
maze_asset_path = values["maze_asset_path"]
assert maze_asset_path
maze_asset_path = Path(maze_asset_path)
maze_matrix_path = maze_asset_path.joinpath("matrix")
meta_info = read_json_file(maze_matrix_path.joinpath("maze_meta_info.json"))
maze_width = int(meta_info["maze_width"])
maze_height = int(meta_info["maze_height"])
values["maze_width"] = maze_width
values["maze_height"] = maze_height
values["sq_tile_size"] = int(meta_info["sq_tile_size"])
values["special_constraint"] = meta_info["special_constraint"]
# READING IN SPECIAL BLOCKS
# Special blocks are those that are colored in the Tiled map.
# Here is an example row for the arena block file:
# e.g, "25331, Double Studio, Studio, Bedroom 2, Painting"
blocks_folder = maze_matrix_path.joinpath("special_blocks")
_wb = blocks_folder.joinpath("world_blocks.csv")
wb_rows = read_csv_to_list(_wb, header=False)
wb = wb_rows[0][-1]
_sb = blocks_folder.joinpath("sector_blocks.csv")
sb_rows = read_csv_to_list(_sb, header=False)
sb_dict = dict()
for i in sb_rows:
sb_dict[i[0]] = i[-1]
_ab = blocks_folder.joinpath("arena_blocks.csv")
ab_rows = read_csv_to_list(_ab, header=False)
ab_dict = dict()
for i in ab_rows:
ab_dict[i[0]] = i[-1]
_gob = blocks_folder.joinpath("game_object_blocks.csv")
gob_rows = read_csv_to_list(_gob, header=False)
gob_dict = dict()
for i in gob_rows:
gob_dict[i[0]] = i[-1]
_slb = blocks_folder.joinpath("spawning_location_blocks.csv")
slb_rows = read_csv_to_list(_slb, header=False)
slb_dict = dict()
for i in slb_rows:
slb_dict[i[0]] = i[-1]
# [SECTION 3] Reading in the matrices
# This is your typical two dimensional matrices. It's made up of 0s and
# the number that represents the color block from the blocks folder.
maze_folder = maze_matrix_path.joinpath("maze")
_cm = maze_folder.joinpath("collision_maze.csv")
collision_maze_raw = read_csv_to_list(_cm, header=False)[0]
_sm = maze_folder.joinpath("sector_maze.csv")
sector_maze_raw = read_csv_to_list(_sm, header=False)[0]
_am = maze_folder.joinpath("arena_maze.csv")
arena_maze_raw = read_csv_to_list(_am, header=False)[0]
_gom = maze_folder.joinpath("game_object_maze.csv")
game_object_maze_raw = read_csv_to_list(_gom, header=False)[0]
_slm = maze_folder.joinpath("spawning_location_maze.csv")
spawning_location_maze_raw = read_csv_to_list(_slm, header=False)[0]
# Loading the maze. The mazes are taken directly from the json exports of
# Tiled maps. They should be in csv format.
# Importantly, they are "not" in a 2-d matrix format -- they are single
# row matrices with the length of width x height of the maze. So we need
# to convert here.
# example format: [['0', '0', ... '25309', '0',...], ['0',...]...]
# 25309 is the collision bar number right now.
collision_maze = []
sector_maze = []
arena_maze = []
game_object_maze = []
spawning_location_maze = []
for i in range(0, len(collision_maze_raw), maze_width):
tw = maze_width
collision_maze += [collision_maze_raw[i : i + tw]]
sector_maze += [sector_maze_raw[i : i + tw]]
arena_maze += [arena_maze_raw[i : i + tw]]
game_object_maze += [game_object_maze_raw[i : i + tw]]
spawning_location_maze += [spawning_location_maze_raw[i : i + tw]]
values["collision_maze"] = collision_maze
tiles = []
for i in range(maze_height):
row = []
for j in range(maze_width):
tile_details = dict()
tile_details["world"] = wb
tile_details["sector"] = ""
if sector_maze[i][j] in sb_dict:
tile_details["sector"] = sb_dict[sector_maze[i][j]]
tile_details["arena"] = ""
if arena_maze[i][j] in ab_dict:
tile_details["arena"] = ab_dict[arena_maze[i][j]]
tile_details["game_object"] = ""
if game_object_maze[i][j] in gob_dict:
tile_details["game_object"] = gob_dict[game_object_maze[i][j]]
tile_details["spawning_location"] = ""
if spawning_location_maze[i][j] in slb_dict:
tile_details["spawning_location"] = slb_dict[spawning_location_maze[i][j]]
tile_details["collision"] = False
if collision_maze[i][j] != "0":
tile_details["collision"] = True
tile_details["events"] = set()
row += [tile_details]
tiles += [row]
values["tiles"] = tiles
# Each game object occupies an event in the tile. We are setting up the
# default event value here.
for i in range(maze_height):
for j in range(maze_width):
if tiles[i][j]["game_object"]:
object_name = ":".join(
[tiles[i][j]["world"], tiles[i][j]["sector"], tiles[i][j]["arena"], tiles[i][j]["game_object"]]
)
go_event = (object_name, None, None, None)
tiles[i][j]["events"].add(go_event)
# Reverse tile access.
# <address_tiles> -- given a string address, we return a set of all
# tile coordinates belonging to that address (this is opposite of
# tiles that give you the string address given a coordinate). This is
# an optimization component for finding paths for the personas' movement.
# address_tiles['<spawn_loc>bedroom-2-a'] == {(58, 9)}
# address_tiles['double studio:recreation:pool table']
# == {(29, 14), (31, 11), (30, 14), (32, 11), ...},
address_tiles = dict()
for i in range(maze_height):
for j in range(maze_width):
addresses = []
if tiles[i][j]["sector"]:
add = f'{tiles[i][j]["world"]}:'
add += f'{tiles[i][j]["sector"]}'
addresses += [add]
if tiles[i][j]["arena"]:
add = f'{tiles[i][j]["world"]}:'
add += f'{tiles[i][j]["sector"]}:'
add += f'{tiles[i][j]["arena"]}'
addresses += [add]
if tiles[i][j]["game_object"]:
add = f'{tiles[i][j]["world"]}:'
add += f'{tiles[i][j]["sector"]}:'
add += f'{tiles[i][j]["arena"]}:'
add += f'{tiles[i][j]["game_object"]}'
addresses += [add]
if tiles[i][j]["spawning_location"]:
add = f'<spawn_loc>{tiles[i][j]["spawning_location"]}'
addresses += [add]
for add in addresses:
if add in address_tiles:
address_tiles[add].add((j, i))
else:
address_tiles[add] = set([(j, i)])
values["address_tiles"] = address_tiles
values["action_space"] = get_action_space((maze_width, maze_height))
values["observation_space"] = get_observation_space()
return values
def reset(
self,
*,
seed: Optional[int] = None,
options: Optional[dict[str, Any]] = None,
) -> tuple[dict[str, EnvObsValType], dict[str, Any]]:
"""reset env and get the init observation
Return results corresponding to `observation, info`
"""
super().reset(seed=seed, options=options)
obs = self._get_obs()
return obs, {}
def _get_obs(self) -> dict[str, EnvObsValType]:
"""Get observation"""
return {
"collision_maze": self.get_collision_maze(),
"tiles": self.tiles,
"address_tiles": self.get_address_tiles(),
}
def observe(self, obs_params: Optional[EnvObsParams] = None) -> Any:
"""Get partial or full observation from the env"""
obs_type = obs_params.obs_type if obs_params else EnvObsType.NONE
if obs_type == EnvObsType.NONE:
obs = self._get_obs()
elif obs_type == EnvObsType.GET_TITLE:
obs = self.access_tile(tile=obs_params.coord)
elif obs_type == EnvObsType.TILE_PATH:
obs = self.get_tile_path(tile=obs_params.coord, level=obs_params.level)
elif obs_type == EnvObsType.TILE_NBR:
obs = self.get_nearby_tiles(tile=obs_params.coord, vision_r=obs_params.vision_radius)
return obs
def step(self, action: EnvAction) -> tuple[dict[str, EnvObsValType], float, bool, bool, dict[str, Any]]:
"""Execute action and then return observation
Return results corresponding to `observation, reward, terminated, truncated, info`
"""
terminated = False
try:
self._execute_env_action(action)
except Exception:
terminated = True
obs = self._get_obs()
ret = (obs, 1.0, terminated, False, {})
return ret
def _execute_env_action(self, action: EnvAction):
action_type = action.action_type
if action_type == EnvActionType.NONE:
pass
elif action_type == EnvActionType.ADD_TILE_EVENT:
self.add_event_from_tile(curr_event=action.event, tile=action.coord)
elif action_type == EnvActionType.RM_TILE_EVENT:
self.remove_event_from_tile(curr_event=action.event, tile=action.coord)
elif action_type == EnvActionType.TURN_TILE_EVENT_IDLE:
self.turn_event_from_tile_idle(curr_event=action.event, tile=action.coord)
elif action_type == EnvActionType.RM_TITLE_SUB_EVENT:
self.remove_subject_events_from_tile(subject=action.subject, tile=action.coord)
def turn_coordinate_to_tile(self, px_coordinate: tuple[int, int]) -> tuple[int, int]:
"""
Turns a pixel coordinate to a tile coordinate.
"""
x = math.ceil(px_coordinate[0] / self.sq_tile_size)
y = math.ceil(px_coordinate[1] / self.sq_tile_size)
return x, y
@mark_as_readable
def get_collision_maze(self) -> list:
return self.collision_maze
@mark_as_readable
def get_address_tiles(self) -> dict:
return self.address_tiles
@mark_as_readable
def access_tile(self, tile: tuple[int, int]) -> dict:
"""
Returns the tiles details dictionary that is stored in self.tiles of the
designated x, y location.
INPUT
tile: The tile coordinate of our interest in (x, y) form.
OUTPUT
The tile detail dictionary for the designated tile.
EXAMPLE OUTPUT
Given (58, 9),
self.tiles[9][58] = {'world': 'double studio',
'sector': 'double studio', 'arena': 'bedroom 2',
'game_object': 'bed', 'spawning_location': 'bedroom-2-a',
'collision': False,
'events': {('double studio:double studio:bedroom 2:bed',
None, None)}}
"""
x = tile[0]
y = tile[1]
return self.tiles[y][x]
@mark_as_readable
def get_tile_path(self, tile: tuple[int, int], level: str) -> str:
"""
Get the tile string address given its coordinate. You designate the level
by giving it a string level description.
INPUT:
tile: The tile coordinate of our interest in (x, y) form.
level: world, sector, arena, or game object
OUTPUT
The string address for the tile.
EXAMPLE OUTPUT
Given tile=(58, 9), and level=arena,
"double studio:double studio:bedroom 2"
"""
x = tile[0]
y = tile[1]
tile = self.tiles[y][x]
path = f"{tile['world']}"
if level == "world":
return path
else:
path += f":{tile['sector']}"
if level == "sector":
return path
else:
path += f":{tile['arena']}"
if level == "arena":
return path
else:
path += f":{tile['game_object']}"
return path
@mark_as_readable
def get_nearby_tiles(self, tile: tuple[int, int], vision_r: int) -> list[tuple[int, int]]:
"""
Given the current tile and vision_r, return a list of tiles that are
within the radius. Note that this implementation looks at a square
boundary when determining what is within the radius.
i.e., for vision_r, returns x's.
x x x x x
x x x x x
x x P x x
x x x x x
x x x x x
INPUT:
tile: The tile coordinate of our interest in (x, y) form.
vision_r: The radius of the persona's vision.
OUTPUT:
nearby_tiles: a list of tiles that are within the radius.
"""
left_end = 0
if tile[0] - vision_r > left_end:
left_end = tile[0] - vision_r
right_end = self.maze_width - 1
if tile[0] + vision_r + 1 < right_end:
right_end = tile[0] + vision_r + 1
bottom_end = self.maze_height - 1
if tile[1] + vision_r + 1 < bottom_end:
bottom_end = tile[1] + vision_r + 1
top_end = 0
if tile[1] - vision_r > top_end:
top_end = tile[1] - vision_r
nearby_tiles = []
for i in range(left_end, right_end):
for j in range(top_end, bottom_end):
nearby_tiles += [(i, j)]
return nearby_tiles
@mark_as_writeable
def add_event_from_tile(self, curr_event: tuple[str], tile: tuple[int, int]) -> None:
"""
Add an event triple to a tile.
INPUT:
curr_event: Current event triple.
e.g., ('double studio:double studio:bedroom 2:bed', None,
None)
tile: The tile coordinate of our interest in (x, y) form.
OUPUT:
None
"""
self.tiles[tile[1]][tile[0]]["events"].add(curr_event)
@mark_as_writeable
def remove_event_from_tile(self, curr_event: tuple[str], tile: tuple[int, int]) -> None:
"""dswaq
Remove an event triple from a tile.
INPUT:
curr_event: Current event triple.
e.g., ('double studio:double studio:bedroom 2:bed', None,
None)
tile: The tile coordinate of our interest in (x, y) form.
OUPUT:
None
"""
curr_tile_ev_cp = self.tiles[tile[1]][tile[0]]["events"].copy()
for event in curr_tile_ev_cp:
if event == curr_event:
self.tiles[tile[1]][tile[0]]["events"].remove(event)
@mark_as_writeable
def turn_event_from_tile_idle(self, curr_event: tuple[str], tile: tuple[int, int]) -> None:
curr_tile_ev_cp = self.tiles[tile[1]][tile[0]]["events"].copy()
for event in curr_tile_ev_cp:
if event == curr_event:
self.tiles[tile[1]][tile[0]]["events"].remove(event)
new_event = (event[0], None, None, None)
self.tiles[tile[1]][tile[0]]["events"].add(new_event)
@mark_as_writeable
def remove_subject_events_from_tile(self, subject: str, tile: tuple[int, int]) -> None:
"""
Remove an event triple that has the input subject from a tile.
INPUT:
subject: "Isabella Rodriguez"
tile: The tile coordinate of our interest in (x, y) form.
OUPUT:
None
"""
curr_tile_ev_cp = self.tiles[tile[1]][tile[0]]["events"].copy()
for event in curr_tile_ev_cp:
if event[0] == subject:
self.tiles[tile[1]][tile[0]]["events"].remove(event)
| 1 | 0.888107 | 1 | 0.888107 | game-dev | MEDIA | 0.904039 | game-dev | 0.941585 | 1 | 0.941585 |
EnttbotX/ClansX | 2,872 | src/main/java/x/Entt/ClansX/CMDs/PECMD.java | package x.Entt.ClansX.CMDs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import x.Entt.ClansX.CX;
import x.Entt.ClansX.Utils.Econo;
import x.Entt.ClansX.Utils.FileHandler;
import x.Entt.ClansX.Utils.MSG;
public class PECMD implements CommandExecutor, TabCompleter {
private final CX plugin;
private static FileHandler fh;
private final Econo econ;
public PECMD(CX plugin) {
this.plugin = plugin;
this.econ = CX.getEcon();
fh = plugin.getFH();
}
public static void addClanToHistory(OfflinePlayer player, String newClan) {
String key = player.getUniqueId().toString();
List<String> history = fh.getPStats().getStringList(key + ".clanHistory");
if (!history.contains(newClan)) {
history.add(newClan);
fh.getPStats().set(key + ".clanHistory", history);
}
fh.getPStats().set(key + ".currentClan", newClan);
fh.savePStats();
}
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, String[] args) {
if (args.length != 1) {
sender.sendMessage(MSG.color(CX.prefix + "&c&lUSE: &f/cxstats <player>"));
return true;
}
OfflinePlayer target = Bukkit.getOfflinePlayer(args[0]);
String key = target.getUniqueId().toString();
double money = this.econ.getBalance(target);
String currentClan = fh.getPStats().getString(key + ".currentClan", "No clan");
List<String> history = fh.getPStats().getStringList(key + ".clanHistory");
sender.sendMessage(MSG.color("&6======= &aStatistics of &e" + target.getName() + " &6======="));
sender.sendMessage(MSG.color("&eMoney: &a" + money));
sender.sendMessage(MSG.color("&eCurrent Clan: &a" + currentClan));
sender.sendMessage(MSG.color("&eClan History:"));
if (history.isEmpty()) {
sender.sendMessage(MSG.color("&7No history found."));
} else {
for (String clan : history)
sender.sendMessage(MSG.color("&7- " + clan));
}
sender.sendMessage(MSG.color("&6=============================="));
return true;
}
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, String[] args) {
if (args.length == 1) {
String partial = args[0].toLowerCase();
List<String> players = new ArrayList<>();
Bukkit.getOnlinePlayers().forEach(p -> {
if (p.getName().toLowerCase().startsWith(partial))
players.add(p.getName());
});
return players;
}
return Collections.emptyList();
}
}
| 1 | 0.804004 | 1 | 0.804004 | game-dev | MEDIA | 0.885532 | game-dev | 0.946616 | 1 | 0.946616 |
TTTReborn/tttreborn | 3,419 | code/gameevents/base/GameEvent.cs | using System;
using System.Text.Json.Serialization;
using Sandbox;
using TTTReborn.Rounds;
namespace TTTReborn
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class GameEventAttribute : LibraryAttribute
{
public GameEventAttribute(string name) : base($"ttt_gameevent_{name}".ToLower()) { }
}
public class EventAttribute : Sandbox.EventAttribute
{
public EventAttribute(string name) : base($"ttt_gameevent_{name}".ToLower()) { } // we can't get the name from GameEventAttribute by Type due to race conditions. We can't set it later due to sbox event initialization issues.
}
// currently (issues with [Net] reassignments and tons of transmitted objects) it's not valuable to make it BaseNetworkable, Transmit always and get rid of NetworkableGameEvent
// that's why we are using our own networking stuff here on demand
public abstract partial class GameEvent
{
public string Name { get; set; }
public float CreatedAt { get; set; }
public GameEventScoring[] Scoring { get; set; } = Array.Empty<GameEventScoring>();
public GameEvent()
{
GameEventAttribute attribute = Utils.GetAttribute<GameEventAttribute>(GetType());
if (attribute != null)
{
Name = attribute.Name;
}
BaseRound baseRound = Gamemode.Game.Instance.Round;
CreatedAt = baseRound.RoundEndTime - baseRound.StartedAt - baseRound.TimeLeft;
}
public virtual void Run() => Event.Run(Name);
protected virtual void OnRegister()
{
foreach (GameEventScoring gameEventScoring in Scoring)
{
gameEventScoring.Init(this);
}
}
internal void ProcessRegister()
{
if (Host.IsServer)
{
Gamemode.Game.Instance.Round?.GameEvents.Add(this);
OnRegister();
}
}
public static void Register<T>(T gameEvent, params GameEventScoring[] gameEventScorings) where T : GameEvent
{
gameEvent.Scoring = gameEventScorings ?? gameEvent.Scoring;
gameEvent.ProcessRegister();
gameEvent.Run();
}
public string GetTranslationKey(string key = null) => Utils.GetTranslationKey(Name, key);
}
public partial class GameEventScoring
{
public int Score { get; set; } = 0;
public int Karma { get; set; } = 0;
public long PlayerId { get; set; }
[JsonIgnore]
public Player Player
{
get => Utils.GetPlayerById(PlayerId);
}
public bool IsInitialized { get; set; } = false;
public virtual void Init<T>(T gameEvent) where T : GameEvent
{
IsInitialized = true;
}
public virtual void Evaluate()
{
if (Player != null && Player.IsValid)
{
Player.Client.SetInt("score", Player.Client.GetInt("score") + Score);
Player.Client.SetInt("karma", Player.Client.GetInt("karma") + Karma);
}
}
public GameEventScoring(Player player)
{
if (player != null && player.Client != null)
{
PlayerId = player.Client.PlayerId;
}
}
}
}
| 1 | 0.813757 | 1 | 0.813757 | game-dev | MEDIA | 0.814198 | game-dev | 0.65672 | 1 | 0.65672 |
gideros/gideros | 10,793 | external/liquidfun-1.0.0/liquidfun/Box2D/Box2D/Dynamics/b2WorldCallbacks.h | /*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
* Copyright (c) 2013 Google, Inc.
*
* 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_WORLD_CALLBACKS_H
#define B2_WORLD_CALLBACKS_H
#include <Box2D/Common/b2Settings.h>
struct b2Vec2;
struct b2Transform;
class b2Fixture;
class b2Body;
class b2Joint;
class b2Contact;
class b2ParticleSystem;
struct b2ContactResult;
struct b2Manifold;
class b2ParticleGroup;
struct b2ParticleBodyContact;
struct b2ParticleContact;
/// Joints and fixtures are destroyed when their associated
/// body is destroyed. Implement this listener so that you
/// may nullify references to these joints and shapes.
class b2DestructionListener
{
public:
virtual ~b2DestructionListener() {}
/// Called when any joint is about to be destroyed due
/// to the destruction of one of its attached bodies.
virtual void SayGoodbye(b2Joint* joint) = 0;
/// Called when any fixture is about to be destroyed due
/// to the destruction of its parent body.
virtual void SayGoodbye(b2Fixture* fixture) = 0;
/// Called when any particle group is about to be destroyed.
virtual void SayGoodbye(b2ParticleGroup* group)
{
B2_NOT_USED(group);
}
/// Called when a particle is about to be destroyed.
/// The index can be used in conjunction with
/// b2ParticleSystem::GetUserDataBuffer() or
/// b2ParticleSystem::GetParticleHandleFromIndex() to determine which
/// particle has been destroyed.
virtual void SayGoodbye(b2ParticleSystem* particleSystem, int32 index)
{
B2_NOT_USED(particleSystem);
B2_NOT_USED(index);
}
};
/// Implement this class to provide collision filtering. In other words, you can implement
/// this class if you want finer control over contact creation.
class b2ContactFilter
{
public:
virtual ~b2ContactFilter() {}
/// Return true if contact calculations should be performed between these two shapes.
/// @warning for performance reasons this is only called when the AABBs begin to overlap.
virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB);
/// Return true if contact calculations should be performed between a
/// fixture and particle. This is only called if the
/// b2_fixtureContactListenerParticle flag is set on the particle.
virtual bool ShouldCollide(b2Fixture* fixture,
b2ParticleSystem* particleSystem,
int32 particleIndex)
{
B2_NOT_USED(fixture);
B2_NOT_USED(particleIndex);
B2_NOT_USED(particleSystem);
return true;
}
/// Return true if contact calculations should be performed between two
/// particles. This is only called if the
/// b2_particleContactListenerParticle flag is set on the particle.
virtual bool ShouldCollide(b2ParticleSystem* particleSystem,
int32 particleIndexA, int32 particleIndexB)
{
B2_NOT_USED(particleSystem);
B2_NOT_USED(particleIndexA);
B2_NOT_USED(particleIndexB);
return true;
}
};
/// Contact impulses for reporting. Impulses are used instead of forces because
/// sub-step forces may approach infinity for rigid body collisions. These
/// match up one-to-one with the contact points in b2Manifold.
struct b2ContactImpulse
{
float32 normalImpulses[b2_maxManifoldPoints];
float32 tangentImpulses[b2_maxManifoldPoints];
int32 count;
};
/// Implement this class to get contact information. You can use these results for
/// things like sounds and game logic. You can also get contact results by
/// traversing the contact lists after the time step. However, you might miss
/// some contacts because continuous physics leads to sub-stepping.
/// Additionally you may receive multiple callbacks for the same contact in a
/// single time step.
/// You should strive to make your callbacks efficient because there may be
/// many callbacks per time step.
/// @warning You cannot create/destroy Box2D entities inside these callbacks.
class b2ContactListener
{
public:
virtual ~b2ContactListener() {}
/// Called when two fixtures begin to touch.
virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); }
/// Called when two fixtures cease to touch.
virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); }
/// Called when a fixture and particle start touching if the
/// b2_fixtureContactFilterParticle flag is set on the particle.
virtual void BeginContact(b2ParticleSystem* particleSystem,
b2ParticleBodyContact* particleBodyContact)
{
B2_NOT_USED(particleSystem);
B2_NOT_USED(particleBodyContact);
}
/// Called when a fixture and particle stop touching if the
/// b2_fixtureContactFilterParticle flag is set on the particle.
virtual void EndContact(b2Fixture* fixture,
b2ParticleSystem* particleSystem, int32 index)
{
B2_NOT_USED(fixture);
B2_NOT_USED(particleSystem);
B2_NOT_USED(index);
}
/// Called when two particles start touching if
/// b2_particleContactFilterParticle flag is set on either particle.
virtual void BeginContact(b2ParticleSystem* particleSystem,
b2ParticleContact* particleContact)
{
B2_NOT_USED(particleSystem);
B2_NOT_USED(particleContact);
}
/// Called when two particles start touching if
/// b2_particleContactFilterParticle flag is set on either particle.
virtual void EndContact(b2ParticleSystem* particleSystem,
int32 indexA, int32 indexB)
{
B2_NOT_USED(particleSystem);
B2_NOT_USED(indexA);
B2_NOT_USED(indexB);
}
/// This is called after a contact is updated. This allows you to inspect a
/// contact before it goes to the solver. If you are careful, you can modify the
/// contact manifold (e.g. disable contact).
/// A copy of the old manifold is provided so that you can detect changes.
/// Note: this is called only for awake bodies.
/// Note: this is called even when the number of contact points is zero.
/// Note: this is not called for sensors.
/// Note: if you set the number of contact points to zero, you will not
/// get an EndContact callback. However, you may get a BeginContact callback
/// the next step.
virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
{
B2_NOT_USED(contact);
B2_NOT_USED(oldManifold);
}
/// This lets you inspect a contact after the solver is finished. This is useful
/// for inspecting impulses.
/// Note: the contact manifold does not include time of impact impulses, which can be
/// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly
/// in a separate data structure.
/// Note: this is only called for contacts that are touching, solid, and awake.
virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse)
{
B2_NOT_USED(contact);
B2_NOT_USED(impulse);
}
};
/// Callback class for AABB queries.
/// See b2World::Query
class b2QueryCallback
{
public:
virtual ~b2QueryCallback() {}
/// Called for each fixture found in the query AABB.
/// @return false to terminate the query.
virtual bool ReportFixture(b2Fixture* fixture) = 0;
/// Called for each particle found in the query AABB.
/// @return false to terminate the query.
virtual bool ReportParticle(const b2ParticleSystem* particleSystem,
int32 index)
{
B2_NOT_USED(particleSystem);
B2_NOT_USED(index);
return false;
}
/// Cull an entire particle system from b2World::QueryAABB. Ignored for
/// b2ParticleSystem::QueryAABB.
/// @return true if you want to include particleSystem in the AABB query,
/// or false to cull particleSystem from the AABB query.
virtual bool ShouldQueryParticleSystem(
const b2ParticleSystem* particleSystem)
{
B2_NOT_USED(particleSystem);
return true;
}
};
/// Callback class for ray casts.
/// See b2World::RayCast
class b2RayCastCallback
{
public:
virtual ~b2RayCastCallback() {}
/// Called for each fixture found in the query. You control how the ray cast
/// proceeds by returning a float:
/// return -1: ignore this fixture and continue
/// return 0: terminate the ray cast
/// return fraction: clip the ray to this point
/// return 1: don't clip the ray and continue
/// @param fixture the fixture hit by the ray
/// @param point the point of initial intersection
/// @param normal the normal vector at the point of intersection
/// @return -1 to filter, 0 to terminate, fraction to clip the ray for
/// closest hit, 1 to continue
virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point,
const b2Vec2& normal, float32 fraction) = 0;
/// Called for each particle found in the query. You control how the ray
/// cast proceeds by returning a float:
/// return <=0: ignore the remaining particles in this particle system
/// return fraction: ignore particles that are 'fraction' percent farther
/// along the line from 'point1' to 'point2'. Note that 'point1' and
/// 'point2' are parameters to b2World::RayCast.
/// @param particleSystem the particle system containing the particle
/// @param index the index of the particle in particleSystem
/// @param point the point of intersection bt the ray and the particle
/// @param normal the normal vector at the point of intersection
/// @param fraction percent (0.0~1.0) from 'point0' to 'point1' along the
/// ray. Note that 'point1' and 'point2' are parameters to
/// b2World::RayCast.
/// @return <=0 to ignore rest of particle system, fraction to ignore
/// particles that are farther away.
virtual float32 ReportParticle(const b2ParticleSystem* particleSystem,
int32 index, const b2Vec2& point,
const b2Vec2& normal, float32 fraction)
{
B2_NOT_USED(particleSystem);
B2_NOT_USED(index);
B2_NOT_USED(&point);
B2_NOT_USED(&normal);
B2_NOT_USED(fraction);
return 0;
}
/// Cull an entire particle system from b2World::RayCast. Ignored in
/// b2ParticleSystem::RayCast.
/// @return true if you want to include particleSystem in the RayCast, or
/// false to cull particleSystem from the RayCast.
virtual bool ShouldQueryParticleSystem(
const b2ParticleSystem* particleSystem)
{
B2_NOT_USED(particleSystem);
return true;
}
};
#endif
| 1 | 0.944148 | 1 | 0.944148 | game-dev | MEDIA | 0.935127 | game-dev | 0.860357 | 1 | 0.860357 |
pixijs-userland/pixi-haxe | 4,338 | samples/src/dragonbones/Main.hx | package dragonbones;
import pixi.interaction.InteractionEvent;
import pixi.plugins.dragonbones.pixi.PixiArmatureDisplay;
import pixi.plugins.dragonbones.pixi.PixiFactory;
import pixi.loaders.Loader;
import pixi.core.Application;
class Main extends Application {
var _loader:Loader;
var _displayIndex:Int;
var _replaceDisplays:Array<String>;
var _factory:PixiFactory;
var _armatureDisplay1:PixiArmatureDisplay;
var _armatureDisplay2:PixiArmatureDisplay;
public function new() {
super({backgroundColor: 0x003366});
_init();
}
function _init() {
super.start();
_displayIndex = 0;
_replaceDisplays = [
"display0002", "display0003", "display0004", "display0005",
"display0006", "display0007", "display0008", "display0009",
"display0010", "meshA", "meshB", "mesh"
];
_factory = PixiFactory.factory;
var baseURL = "assets/dragonbones/";
_loader = new Loader();
_loader.baseUrl = baseURL;
_loader.add("dragonBonesData", "DragonBoy/DragonBoy.json");
_loader.add("textureDataA", "DragonBoy/DragonBoy_texture_1.json");
_loader.add("textureA", "DragonBoy/DragonBoy_texture_1.png");
_loader.add("dragonBonesData1", "ReplaceSlotDisplay/ReplaceSlotDisplay.json");
_loader.add("textureDataA1", "ReplaceSlotDisplay/texture.json");
_loader.add("textureA1", "ReplaceSlotDisplay/texture.png");
_loader.add("textureRP", "ReplaceSlotDisplay/textureReplace.png");
_loader.load(_onLoaded);
}
function _onLoaded() {
_factory.parseDragonBonesData(_loader.resources["dragonBonesData"].data);
_factory.parseTextureAtlasData(_loader.resources["textureDataA"].data, _loader.resources["textureA"].texture);
_armatureDisplay1 = _factory.buildArmatureDisplay("DragonBoy");
_armatureDisplay1.animation.play("walk");
_armatureDisplay1.x = renderer.width * 0.5;
_armatureDisplay1.y = renderer.height * 0.5 + 100;
_factory.parseDragonBonesData(_loader.resources["dragonBonesData1"].data);
_factory.parseTextureAtlasData(_loader.resources["textureDataA1"].data, _loader.resources["textureA1"].texture);
_armatureDisplay2 = _factory.buildArmatureDisplay("MyArmature");
_armatureDisplay2.animation.timeScale = 0.1;
_armatureDisplay2.animation.play();
_armatureDisplay2.x = renderer.width * 0.5;
_armatureDisplay2.y = renderer.height * 0.5;
stage.interactive = true;
stage.on("touchstart", _touchHandler, this);
stage.on("mousedown", _touchHandler, this);
stage.addChild(_armatureDisplay2);
stage.addChild(_armatureDisplay1);
}
function _touchHandler(event:InteractionEvent) {
_replaceDisplay();
}
function _replaceDisplay() {
_displayIndex = (_displayIndex + 1) % _replaceDisplays.length;
var replaceDisplayName = _replaceDisplays[_displayIndex];
if (replaceDisplayName.indexOf("mesh") >= 0) {
switch (replaceDisplayName) {
case "meshA":
// Normal to mesh.
_factory.replaceSlotDisplay(
"ReplaceSlotDisplay",
"MyMesh",
"meshA",
"weapon_1004_1",
_armatureDisplay2.armature.getSlot("weapon")
);
// Replace mesh texture.
_factory.replaceSlotDisplay(
"ReplaceSlotDisplay",
"MyDisplay",
"ball",
"display0002",
_armatureDisplay2.armature.getSlot("mesh")
);
case "meshB":
// Normal to mesh.
_factory.replaceSlotDisplay(
"ReplaceSlotDisplay",
"MyMesh",
"meshB",
"weapon_1004_1",
_armatureDisplay2.armature.getSlot("weapon")
);
// Replace mesh texture.
_factory.replaceSlotDisplay(
"ReplaceSlotDisplay",
"MyDisplay",
"ball",
"display0003",
_armatureDisplay2.armature.getSlot("mesh")
);
case "mesh":
// Back to normal.
_factory.replaceSlotDisplay(
"ReplaceSlotDisplay",
"MyMesh",
"mesh",
"weapon_1004_1",
_armatureDisplay2.armature.getSlot("weapon")
);
// Replace mesh texture.
_factory.replaceSlotDisplay(
"ReplaceSlotDisplay",
"MyDisplay",
"ball",
"display0005",
_armatureDisplay2.armature.getSlot("mesh")
);
}
}
else { // Replace normal display.
_factory.replaceSlotDisplay(
"ReplaceSlotDisplay",
"MyDisplay",
"ball",
replaceDisplayName,
_armatureDisplay2.armature.getSlot("ball")
);
}
}
static function main() {
new Main();
}
} | 1 | 0.725521 | 1 | 0.725521 | game-dev | MEDIA | 0.731554 | game-dev,graphics-rendering | 0.913338 | 1 | 0.913338 |
goonstation/goonstation | 9,822 | code/modules/materials/Mat_Mining.dm | /// Pick(1 tile), hammer(line across), drill(line in front), blaster(cone),
/obj/item/mining_head
name = "mining tool head"
desc = "A mining tool head."
icon = 'icons/obj/items/mining.dmi'
icon_state = "powerpick"
drill
name = "drill head"
desc = "A drill head."
icon_state = "drillhead"
hammer
name = "hammer head"
desc = "A hammer head."
icon_state = "hammerhead"
pick
name = "pick head"
desc = "A pick head."
icon_state = "pickhead"
blaster
name = "blaster head"
desc = "A blaster head."
icon_state = "blasterhead"
/obj/item/mining_mod
name = "mining mod"
desc = "A mod for mining tools."
icon = 'icons/obj/items/mining.dmi'
icon_state = "mod_none"
conc
name = "Concussive Mining Mod"
desc = "A mod for mining tools. Increases AOE."
icon_state = "mod_conc"
/obj/item/mining_tools
name = "mining tool"
desc = "A simple mining tool."
icon = 'icons/obj/items/mining.dmi'
inhand_image_icon = 'icons/mob/inhand/hand_tools.dmi'
icon_state = "powerpick"
item_state = "ppick"
var/blasting = 0 //Small Aoe damage around normal hit tiles.
var/powered = 0 //Undecided.
var/power = 5 //Damage to asteroid tiles.
var/hit_sound = 'sound/items/mining_drill.ogg'
flags = EXTRADELAY | TABLEPASS | CONDUCT
c_flags = ONBELT
New()
..()
BLOCK_SETUP(BLOCK_ROD)
afterattack(atom/target as mob|obj|turf|area, mob/user as mob, var/reach)
if(user == target || (!isturf(target.loc) && !isturf(target)))
return
playsound(src.loc, hit_sound, 20, 1)
if(blasting)
playsound(src.loc, 'sound/items/mining_conc.ogg', 20, 1)
return use(user, target)
onMaterialChanged()
..()
if(istype(src.material))
src.power = max(20, (src.material.getProperty("hard") - 3) * 66)
if(blasting)
src.power *= 0.9
return
proc/use(var/mob/user, var/atom/target)
return
buildTooltipContent()
. = ..()
. += "<br>"
. += "<div><img src='[resource("images/tooltips/mining.png")]' alt='' class='icon' /><span>Mining Power: [power]</span></div>"
lastTooltipContent = .
/obj/item/mining_tools/pick
name = "Mining Pick"
desc = "A mining pick. Affects only a single tile but has very high power."
icon_state = "pickaxe"
item_state = "pick"
hit_sound = 'sound/items/mining_pick.ogg'
onMaterialChanged()
..()
if(istype(src.material))
src.power = 0
src.power += max(10, (src.material.getProperty("density") - 3) * 33)
src.power += max(10, (src.material.getProperty("hard") - 3) * 33)
src.power *= 2.5
if(blasting)
src.power *= 0.9
src.power = round(src.power)
return
use(var/mob/user, var/atom/target)
var/attackDir = get_dir(user, target)
if(attackDir == NORTHEAST || attackDir == NORTHWEST || attackDir == SOUTHEAST || attackDir == SOUTHWEST)
attackDir = (prob(50) ? turn(attackDir, 45) : turn(attackDir, -45))
var/turf/start = get_step(user,attackDir)
var/obj/effect/melee/pick/DA = new/obj/effect/melee/pick(start)
SPAWN(2 SECONDS)
qdel(DA)
var/list/extra_dmg = list()
if(blasting)
extra_dmg |= range(1,start)
for(var/turf/T in extra_dmg)
if(istype(T,/turf/simulated/wall/auto/asteroid))
var/obj/effect/melee/conc/conc = new/obj/effect/melee/conc(T)
SPAWN(1 SECOND) qdel(conc)
T:change_health(-(round(power/7)))
if(istype(start,/turf/simulated/wall/auto/asteroid))
var/turf/simulated/wall/auto/asteroid/A = start
A.change_health(-power)
return
/obj/item/mining_tools/blaster
name = "Mining Blaster"
desc = "A mining blaster. Affects a wide area but has a little bit less power."
icon_state = "blaster"
item_state = "drill"
hit_sound = 'sound/items/mining_blaster.ogg'
onMaterialChanged()
..()
if(istype(src.material))
src.power = max(20, (src.material.getProperty("electrical") - 4) * 80)
src.power *= 0.8
if(blasting)
src.power *= 0.9
src.power = round(src.power)
return
use(var/mob/user, var/atom/target)
var/attackDir = get_dir(user, target)
if(attackDir == NORTHEAST || attackDir == NORTHWEST || attackDir == SOUTHEAST || attackDir == SOUTHWEST)
attackDir = (prob(50) ? turn(attackDir, 45) : turn(attackDir, -45))
var/turf/start = get_step(user,attackDir)
var/turf/TC = get_step(start,attackDir)
var/turf/TA = get_step(TC,turn(attackDir, 90))
var/turf/TB = get_step(TC,turn(attackDir, -90))
animate(start,color="#FFFF00", time=1)
animate(color="#AA0000", time=2)
animate(color="#FFFFFF", time=4)
animate(TC,color="#FFFF00", time=1)
animate(color="#AA0000", time=2)
animate(color="#FFFFFF", time=4)
animate(TA,color="#FFFF00", time=1)
animate(color="#AA0000", time=2)
animate(color="#FFFFFF", time=4)
animate(TB,color="#FFFF00", time=1)
animate(color="#AA0000", time=2)
animate(color="#FFFFFF", time=4)
var/obj/effect/melee/blasterline/EA = new/obj/effect/melee/blasterline(user.loc)
var/obj/effect/melee/blasterline/EB = new/obj/effect/melee/blasterline(start)
EA.set_dir(attackDir)
EB.set_dir(turn(attackDir, 180))
animate(EA,alpha=0, time=5)
animate(EB,alpha=0, time=5)
SPAWN(0.6 SECONDS)
qdel(EA)
qdel(EB)
var/list/extra_dmg = list()
if(blasting)
extra_dmg |= range(1,start)
extra_dmg |= range(1,TA)
extra_dmg |= range(1,TB)
extra_dmg |= range(1,TC)
for(var/turf/T in extra_dmg)
if(istype(T,/turf/simulated/wall/auto/asteroid))
var/obj/effect/melee/conc/conc = new/obj/effect/melee/conc(T)
SPAWN(1 SECOND) qdel(conc)
T:change_health(-(round(power/7)))
if(istype(start,/turf/simulated/wall/auto/asteroid))
var/turf/simulated/wall/auto/asteroid/A = start
A.change_health(-power)
if(istype(TC,/turf/simulated/wall/auto/asteroid))
var/turf/simulated/wall/auto/asteroid/B = TC
B.change_health(-power)
if(istype(TA,/turf/simulated/wall/auto/asteroid))
var/turf/simulated/wall/auto/asteroid/C = TA
C.change_health(-power)
if(istype(TB,/turf/simulated/wall/auto/asteroid))
var/turf/simulated/wall/auto/asteroid/D = TB
D.change_health(-power)
return
/obj/item/mining_tools/hammer
name = "Mining Hammer"
desc = "A mining hammer. Affects a wide area."
icon_state = "powerhammer"
item_state = "hammer"
hit_sound = 'sound/items/mining_hammer.ogg'
force = 5
onMaterialChanged()
..()
if(istype(src.material))
src.power = max(20, (src.material.getProperty("density") - 3) * 66)
if(blasting)
src.power *= 0.9
src.power = round(src.power)
return
use(var/mob/user, var/atom/target)
var/attackDir = get_dir(user, target)
if(attackDir == NORTHEAST || attackDir == NORTHWEST || attackDir == SOUTHEAST || attackDir == SOUTHWEST)
attackDir = (prob(50) ? turn(attackDir, 45) : turn(attackDir, -45))
var/turf/start = get_step(user,attackDir)
var/turf/middle = get_step(start,turn(attackDir, 90))
var/turf/end = get_step(start,turn(attackDir, -90))
var/obj/effect/melee/hammer/DA = new/obj/effect/melee/hammer(start)
var/obj/effect/melee/hammer/DB = new/obj/effect/melee/hammer(middle)
var/obj/effect/melee/hammer/DC = new/obj/effect/melee/hammer(end)
SPAWN(2 SECONDS)
qdel(DA)
qdel(DB)
qdel(DC)
var/list/extra_dmg = list()
if(blasting)
extra_dmg |= range(1,start)
extra_dmg |= range(1,middle)
extra_dmg |= range(1,end)
for(var/turf/T in extra_dmg)
if(istype(T,/turf/simulated/wall/auto/asteroid))
var/obj/effect/melee/conc/conc = new/obj/effect/melee/conc(T)
SPAWN(1 SECOND) qdel(conc)
T:change_health(-(round(power/7)))
if(istype(start,/turf/simulated/wall/auto/asteroid))
var/turf/simulated/wall/auto/asteroid/A = start
A.change_health(-power)
if(istype(middle,/turf/simulated/wall/auto/asteroid))
var/turf/simulated/wall/auto/asteroid/B = middle
B.change_health(-power)
if(istype(end,/turf/simulated/wall/auto/asteroid))
var/turf/simulated/wall/auto/asteroid/C = end
C.change_health(-power)
return
/obj/item/mining_tools/drill
name = "Mining Drill"
desc = "A mining drill. Has a long range."
icon_state = "lasdrill-old"
item_state = "drill"
hit_sound = 'sound/items/mining_drill.ogg'
onMaterialChanged()
..()
if(istype(src.material))
src.power = max(20, (src.material.getProperty("hard") - 3) * 66)
if(blasting)
src.power *= 0.9
src.power = round(src.power)
return
use(var/mob/user, var/atom/target)
var/attackDir = get_dir(user, target)
if(attackDir == NORTHEAST || attackDir == NORTHWEST || attackDir == SOUTHEAST || attackDir == SOUTHWEST)
attackDir = (prob(50) ? turn(attackDir, 45) : turn(attackDir, -45))
var/turf/start = get_step(user,attackDir)
var/turf/middle = get_step(start,attackDir)
var/turf/end = get_step(middle,attackDir)
var/anim_x = 0
var/anim_y = 0
switch(attackDir)
if(NORTH)
anim_x = 0
anim_y = 64
if(EAST)
anim_x = 64
anim_y = 0
if(SOUTH)
anim_x = 0
anim_y = -64
if(WEST)
anim_x = -64
anim_y = 0
var/obj/effect/melee/drill/D = new/obj/effect/melee/drill(start)
D.set_dir(attackDir)
animate(D, pixel_x = anim_x, pixel_y = anim_y, time = 5, easing = QUAD_EASING)
SPAWN(2 SECONDS) qdel(D)
var/list/extra_dmg = list()
if(blasting)
extra_dmg |= range(1,start)
extra_dmg |= range(1,middle)
extra_dmg |= range(1,end)
for(var/turf/T in extra_dmg)
if(istype(T,/turf/simulated/wall/auto/asteroid))
var/obj/effect/melee/conc/conc = new/obj/effect/melee/conc(T)
SPAWN(1 SECOND) qdel(conc)
T:change_health(-(round(power/7)))
if(istype(start,/turf/simulated/wall/auto/asteroid))
var/turf/simulated/wall/auto/asteroid/A = start
A.change_health(-power)
if(istype(middle,/turf/simulated/wall/auto/asteroid))
var/turf/simulated/wall/auto/asteroid/B = middle
B.change_health(-power)
if(istype(end,/turf/simulated/wall/auto/asteroid))
var/turf/simulated/wall/auto/asteroid/C = end
C.change_health(-power)
return
| 1 | 0.961125 | 1 | 0.961125 | game-dev | MEDIA | 0.99493 | game-dev | 0.986705 | 1 | 0.986705 |
SammySemicolon/Malum-Mod | 1,919 | src/main/java/com/sammy/malum/common/item/curiosities/curios/sets/rotten/CurioStarvedBelt.java | package com.sammy.malum.common.item.curiosities.curios.sets.rotten;
import com.sammy.malum.common.effect.gluttony.*;
import com.sammy.malum.common.item.*;
import com.sammy.malum.common.item.curiosities.curios.*;
import com.sammy.malum.common.item.food.*;
import com.sammy.malum.core.helpers.*;
import com.sammy.malum.core.systems.events.*;
import com.sammy.malum.registry.common.*;
import net.minecraft.network.chat.*;
import net.minecraft.server.level.*;
import net.minecraft.sounds.*;
import net.minecraft.util.*;
import net.minecraft.world.entity.*;
import team.lodestar.lodestone.helpers.*;
import java.util.function.*;
public class CurioStarvedBelt extends MalumCurioItem implements IMalumEventResponder {
public CurioStarvedBelt(Properties builder) {
super(builder, MalumTrinketType.ROTTEN);
}
@Override
public void addExtraTooltipLines(Consumer<Component> consumer) {
consumer.accept(ComponentHelper.positiveCurioEffect("spirits_gluttony"));
}
@Override
public void spiritCollectionEvent(CollectSpiritEvent event, LivingEntity collector, double arcaneResonance) {
if (collector.level() instanceof ServerLevel serverLevel) {
int duration = Mth.floor(600 * arcaneResonance);
int limit = Mth.floor(arcaneResonance * 5);
GluttonyEffect.applyGluttony(collector, b -> b
.setInitialDuration(duration)
.setAmplifierGain(1)
.setAmplifierLimit(limit));
var random = serverLevel.random;
SoundHelper.playSound(collector, MalumSoundEvents.HUNGRY_BELT_FEEDS.get(), 0.7f, RandomHelper.randomBetween(random, 1.5f, 2f));
SoundHelper.playSound(collector, SoundEvents.GENERIC_EAT, 0.7f, RandomHelper.randomBetween(random, 0.8f, 1.2f));
ConcentratedGluttonyItem.createGluttonyVFX(serverLevel, collector, 0.5f);
}
}
} | 1 | 0.7344 | 1 | 0.7344 | game-dev | MEDIA | 0.655635 | game-dev | 0.559821 | 1 | 0.559821 |
SchildiChat/schildichat-android-next | 1,183 | libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/room/powerlevels/RoomPowerLevelsValuesMapper.kt | /*
* Copyright 2024 New Vector Ltd.
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
* Please see LICENSE files in the repository root for full details.
*/
package io.element.android.libraries.matrix.impl.room.powerlevels
import io.element.android.libraries.matrix.api.room.RoomMember
import io.element.android.libraries.matrix.api.room.powerlevels.RoomPowerLevelsValues
import org.matrix.rustcomponents.sdk.PowerLevel
import org.matrix.rustcomponents.sdk.RoomPowerLevelsValues as RustRoomPowerLevelsValues
object RoomPowerLevelsValuesMapper {
fun map(values: RustRoomPowerLevelsValues): RoomPowerLevelsValues {
return RoomPowerLevelsValues(
ban = values.ban,
invite = values.invite,
kick = values.kick,
sendEvents = values.eventsDefault,
redactEvents = values.redact,
roomName = values.roomName,
roomAvatar = values.roomAvatar,
roomTopic = values.roomTopic,
)
}
}
fun PowerLevel.into(): Long = when (this) {
PowerLevel.Infinite -> RoomMember.Role.Owner(isCreator = true).powerLevel
is PowerLevel.Value -> this.value
}
| 1 | 0.823876 | 1 | 0.823876 | game-dev | MEDIA | 0.778832 | game-dev | 0.821271 | 1 | 0.821271 |
magefree/mage | 3,231 | Mage.Sets/src/mage/cards/e/EssenceReliquary.java | package mage.cards.e;
import mage.abilities.Ability;
import mage.abilities.common.ActivateIfConditionActivatedAbility;
import mage.abilities.condition.common.MyTurnCondition;
import mage.abilities.costs.common.TapSourceCost;
import mage.abilities.effects.OneShotEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.cards.Cards;
import mage.cards.CardsImpl;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.SubType;
import mage.constants.Zone;
import mage.filter.common.FilterControlledPermanent;
import mage.filter.predicate.mageobject.AnotherPredicate;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.players.Player;
import mage.target.common.TargetControlledPermanent;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* @author Susucr
*/
public final class EssenceReliquary extends CardImpl {
private static final FilterControlledPermanent filter = new FilterControlledPermanent("another target permanent you control");
static {
filter.add(AnotherPredicate.instance);
}
public EssenceReliquary(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, "{2}{W}");
// {T}: Return another target permanent you control and all Auras you control attached to it to their owner's hand. Activate only during your turn.
Ability ability = new ActivateIfConditionActivatedAbility(
new EssenceReliquaryTargetEffect(),
new TapSourceCost(), MyTurnCondition.instance
);
ability.addTarget(new TargetControlledPermanent(filter));
this.addAbility(ability);
}
private EssenceReliquary(final EssenceReliquary card) {
super(card);
}
@Override
public EssenceReliquary copy() {
return new EssenceReliquary(this);
}
}
class EssenceReliquaryTargetEffect extends OneShotEffect {
EssenceReliquaryTargetEffect() {
super(Outcome.ReturnToHand);
this.staticText = "Return another target permanent you control and all Auras you control attached to it to their owner's hand";
}
private EssenceReliquaryTargetEffect(final EssenceReliquaryTargetEffect effect) {
super(effect);
}
@Override
public EssenceReliquaryTargetEffect copy() {
return new EssenceReliquaryTargetEffect(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;
}
Cards cards = new CardsImpl(permanent);
cards.addAll(permanent.getAttachments()
.stream()
.map(game::getPermanent)
.filter(Objects::nonNull)
.filter(p -> p.isControlledBy(source.getControllerId()))
.filter(p -> p.hasSubtype(SubType.AURA, game))
.map(Permanent::getId)
.collect(Collectors.toList()));
return player.moveCards(cards, Zone.HAND, source, game);
}
}
| 1 | 0.981896 | 1 | 0.981896 | game-dev | MEDIA | 0.979973 | game-dev | 0.995642 | 1 | 0.995642 |
flutter/engine | 2,004 | impeller/display_list/aiks_playground.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/display_list/aiks_playground.h"
#include <memory>
#include "impeller/display_list/aiks_context.h"
#include "impeller/display_list/dl_dispatcher.h"
#include "impeller/typographer/backends/skia/typographer_context_skia.h"
#include "impeller/typographer/typographer_context.h"
#include "include/core/SkRect.h"
namespace impeller {
AiksPlayground::AiksPlayground()
: typographer_context_(TypographerContextSkia::Make()) {}
AiksPlayground::~AiksPlayground() = default;
void AiksPlayground::SetTypographerContext(
std::shared_ptr<TypographerContext> typographer_context) {
typographer_context_ = std::move(typographer_context);
}
void AiksPlayground::TearDown() {
PlaygroundTest::TearDown();
}
bool AiksPlayground::ImGuiBegin(const char* name,
bool* p_open,
ImGuiWindowFlags flags) {
ImGui::Begin(name, p_open, flags);
return true;
}
bool AiksPlayground::OpenPlaygroundHere(
const sk_sp<flutter::DisplayList>& list) {
return OpenPlaygroundHere([list]() { return list; });
}
bool AiksPlayground::OpenPlaygroundHere(
const AiksDlPlaygroundCallback& callback) {
AiksContext renderer(GetContext(), typographer_context_);
if (!renderer.IsValid()) {
return false;
}
return Playground::OpenPlaygroundHere(
[&renderer, &callback](RenderTarget& render_target) -> bool {
return RenderToOnscreen(
renderer.GetContentContext(), //
render_target, //
callback(), //
SkIRect::MakeWH(render_target.GetRenderTargetSize().width,
render_target.GetRenderTargetSize().height), //
/*reset_host_buffer=*/true //
);
});
}
} // namespace impeller
| 1 | 0.911541 | 1 | 0.911541 | game-dev | MEDIA | 0.381332 | game-dev | 0.897395 | 1 | 0.897395 |
Baystation12/Baystation12 | 12,150 | code/game/objects/items/weapons/ecigs.dm | /obj/item/clothing/mask/smokable/ecig
name = "electronic cigarette"
desc = "Device with modern approach to smoking."
icon = 'icons/obj/ecig.dmi'
active = 0
var/obj/item/cell/cigcell
var/cartridge_type = /obj/item/reagent_containers/ecig_cartridge/med_nicotine
var/obj/item/reagent_containers/ecig_cartridge/ec_cartridge
var/cell_type = /obj/item/cell/device/standard
w_class = ITEM_SIZE_TINY
slot_flags = SLOT_EARS | SLOT_MASK
attack_verb = list("attacked", "poked", "battered")
body_parts_covered = 0
var/brightness_on = 1
chem_volume = 0 //ecig has no storage on its own but has reagent container created by parent obj
var/icon_off
var/icon_empty
var/power_usage = 450 //value for simple ecig, enough for about 1 cartridge, in JOULES!
var/ecig_colors = list(null, COLOR_DARK_GRAY, COLOR_RED_GRAY, COLOR_BLUE_GRAY, COLOR_GREEN_GRAY, COLOR_PURPLE_GRAY)
var/idle = 0
var/idle_treshold = 30
/obj/item/clothing/mask/smokable/ecig/New()
..()
if(ispath(cell_type))
cigcell = new cell_type
ec_cartridge = new cartridge_type(src)
/obj/item/clothing/mask/smokable/ecig/get_cell()
return cigcell
/obj/item/clothing/mask/smokable/ecig/simple
name = "cheap electronic cigarette"
desc = "A cheap Lucky 1337 electronic cigarette, styled like a traditional cigarette."
icon_state = "ccigoff"
icon_off = "ccigoff"
icon_empty = "ccigoff"
icon_on = "ccigon"
/obj/item/clothing/mask/smokable/ecig/simple/examine(mob/user)
. = ..()
if(ec_cartridge)
to_chat(user,SPAN_NOTICE("There are [round(ec_cartridge.reagents.total_volume, 1)] units of liquid remaining."))
else
to_chat(user,SPAN_NOTICE("There's no cartridge connected."))
/obj/item/clothing/mask/smokable/ecig/util
name = "electronic cigarette"
desc = "A popular utilitarian model of electronic cigarette, the ONI-55. Comes in a variety of colors."
icon_state = "ecigoff1"
icon_off = "ecigoff1"
icon_empty = "ecigoff1"
icon_on = "ecigon"
cell_type = /obj/item/cell/device/high //enough for four cartridges
/obj/item/clothing/mask/smokable/ecig/util/New()
..()
color = pick(ecig_colors)
/obj/item/clothing/mask/smokable/ecig/util/examine(mob/user)
. = ..()
if(ec_cartridge)
to_chat(user,SPAN_NOTICE("There are [round(ec_cartridge.reagents.total_volume, 1)] units of liquid remaining."))
else
to_chat(user,SPAN_NOTICE("There's no cartridge connected."))
if(cigcell)
to_chat(user,SPAN_NOTICE("The power meter shows that there's about [round(cigcell.percent(), 25)]% power remaining."))
else
to_chat(user,SPAN_NOTICE("There's no cartridge connected."))
/obj/item/clothing/mask/smokable/ecig/deluxe
name = "deluxe electronic cigarette"
desc = "A premium model eGavana MK3 electronic cigarette, shaped like a cigar."
icon_state = "pcigoff1"
icon_off = "pcigoff1"
icon_empty = "pcigoff2"
icon_on = "pcigon"
cell_type = /obj/item/cell/device/high //enough for four catridges
/obj/item/clothing/mask/smokable/ecig/deluxe/examine(mob/user)
. = ..()
if(ec_cartridge)
to_chat(user,SPAN_NOTICE("There are [round(ec_cartridge.reagents.total_volume, 1)] units of liquid remaining."))
else
to_chat(user,SPAN_NOTICE("There's no cartridge connected."))
if(cigcell)
to_chat(user,SPAN_NOTICE("The power meter shows that there's about [round(cigcell.percent(), 1)]% power remaining."))
else
to_chat(user,SPAN_NOTICE("There's no cartridge connected."))
/obj/item/clothing/mask/smokable/ecig/proc/Deactivate()
active = 0
STOP_PROCESSING(SSobj, src)
update_icon()
/obj/item/clothing/mask/smokable/ecig/Process()
if(!cigcell)
Deactivate()
return
if(!ec_cartridge)
Deactivate()
return
if(idle >= idle_treshold) //idle too long -> automatic shut down
idle = 0
visible_message(SPAN_NOTICE("\The [src] powers down automatically."), null, 2)
Deactivate()
return
idle ++
if(ishuman(loc))
var/mob/living/carbon/human/C = loc
if (!active || !ec_cartridge || !ec_cartridge.reagents.total_volume)//no cartridge
if(!ec_cartridge.reagents.total_volume)
to_chat(C, SPAN_NOTICE("There's no liquid left in \the [src], so you shut it down."))
Deactivate()
return
if (src == C.wear_mask && C.check_has_mouth()) //transfer, but only when not disabled
idle = 0
//here we'll reduce battery by usage, and check powerlevel - you only use batery while smoking
if(!cigcell.checked_use(power_usage * CELLRATE)) //if this passes, there's not enough power in the battery
Deactivate()
to_chat(C,SPAN_NOTICE("\The [src]'s power meter flashes a low battery warning and shuts down."))
return
ec_cartridge.reagents.trans_to_mob(C, REM, CHEM_INGEST, 0.4) // Most of it is not inhaled... balance reasons.
/obj/item/clothing/mask/smokable/ecig/on_update_icon()
if (active)
item_state = icon_on
icon_state = icon_on
set_light(brightness_on)
else if (ec_cartridge)
set_light(0)
item_state = icon_off
icon_state = icon_off
else
icon_state = icon_empty
item_state = icon_empty
set_light(0)
if(ismob(loc))
var/mob/living/M = loc
M.update_inv_wear_mask(0)
M.update_inv_l_hand(0)
M.update_inv_r_hand(1)
/obj/item/clothing/mask/smokable/ecig/use_tool(obj/item/I, mob/living/user, list/click_params)
if(istype(I, /obj/item/reagent_containers/ecig_cartridge))
if (ec_cartridge)//can't add second one
to_chat(user, "[SPAN_WARNING("A cartridge has already been installed.")] ")
return TRUE
if (user.unEquip(I, src))//fits in new one
ec_cartridge = I
update_icon()
to_chat(user, "[SPAN_NOTICE("You insert \the [I] into \the [src].")] ")
return TRUE
if (isScrewdriver(I))
if(cigcell) //if contains powercell
cigcell.update_icon()
cigcell.dropInto(loc)
cigcell = null
to_chat(user, SPAN_NOTICE("You remove \the [cigcell] from \the [src]."))
else //does not contains cell
to_chat(user, SPAN_NOTICE("There's no battery in \the [src]."))
return TRUE
if(istype(I, /obj/item/cell/device))
if(!cigcell && user.unEquip(I))
I.forceMove(src)
cigcell = I
to_chat(user, SPAN_NOTICE("You install \the [cigcell] into \the [src]."))
update_icon()
else
to_chat(user, SPAN_NOTICE("\The [src] already has a battery installed."))
return TRUE
return ..()
/obj/item/clothing/mask/smokable/ecig/attack_self(mob/user as mob)
if (active)
Deactivate()
to_chat(user, "[SPAN_NOTICE("You turn off \the [src].")] ")
else
if(cigcell)
if (!ec_cartridge)
to_chat(user, "[SPAN_NOTICE("You can't use \the [src] with no cartridge installed!")] ")
return
else if(!ec_cartridge.reagents.total_volume)
to_chat(user, "[SPAN_NOTICE("You can't use \the [src] with no liquid left!")] ")
return
else if(!cigcell.check_charge(power_usage * CELLRATE))
to_chat(user, "[SPAN_NOTICE("\The [src]'s power meter flashes a low battery warning and refuses to operate.")] ")
return
active=1
START_PROCESSING(SSobj, src)
to_chat(user, "[SPAN_NOTICE("You turn on \the [src].")] ")
update_icon()
else
to_chat(user, SPAN_WARNING("\The [src] does not have a battery installed."))
/obj/item/clothing/mask/smokable/ecig/attack_hand(mob/user as mob)//eject cartridge
if(user.get_inactive_hand() == src)//if being hold
if (ec_cartridge)
active=0
user.put_in_hands(ec_cartridge)
to_chat(user, "[SPAN_NOTICE("You remove \the [ec_cartridge] from \the [src].")] ")
ec_cartridge = null
update_icon()
else
..()
/obj/item/reagent_containers/ecig_cartridge
name = "tobacco flavour cartridge"
desc = "A small metal cartridge, used with electronic cigarettes, which contains an atomizing coil and a solution to be atomized."
w_class = ITEM_SIZE_TINY
icon = 'icons/obj/ecig.dmi'
icon_state = "ecartridge"
matter = list(MATERIAL_ALUMINIUM = 50, MATERIAL_GLASS = 10)
volume = 20
atom_flags = ATOM_FLAG_NO_TEMP_CHANGE | ATOM_FLAG_OPEN_CONTAINER
/obj/item/reagent_containers/ecig_cartridge/examine(mob/user)//to see how much left
. = ..()
to_chat(user, "The cartridge has [reagents.total_volume] units of liquid remaining.")
//flavours
/obj/item/reagent_containers/ecig_cartridge/blank
name = "ecigarette cartridge"
desc = "A small metal cartridge which contains an atomizing coil."
/obj/item/reagent_containers/ecig_cartridge/blanknico
name = "flavorless nicotine cartridge"
desc = "A small metal cartridge which contains an atomizing coil and a solution to be atomized. The label says you can add whatever flavoring agents you want."
/obj/item/reagent_containers/ecig_cartridge/blanknico/New()
..()
reagents.add_reagent(/datum/reagent/tobacco/liquid, 5)
reagents.add_reagent(/datum/reagent/water, 10)
/obj/item/reagent_containers/ecig_cartridge/med_nicotine
name = "tobacco flavour cartridge"
desc = "A small metal cartridge which contains an atomizing coil and a solution to be atomized. The label says its tobacco flavored."
/obj/item/reagent_containers/ecig_cartridge/med_nicotine/New()
..()
reagents.add_reagent(/datum/reagent/tobacco, 5)
reagents.add_reagent(/datum/reagent/water, 15)
/obj/item/reagent_containers/ecig_cartridge/high_nicotine
name = "high nicotine tobacco flavour cartridge"
desc = "A small metal cartridge which contains an atomizing coil and a solution to be atomized. The label says its tobacco flavored, with extra nicotine."
/obj/item/reagent_containers/ecig_cartridge/high_nicotine/New()
..()
reagents.add_reagent(/datum/reagent/tobacco, 10)
reagents.add_reagent(/datum/reagent/water, 10)
/obj/item/reagent_containers/ecig_cartridge/orange
name = "orange flavour cartridge"
desc = "A small metal cartridge which contains an atomizing coil and a solution to be atomized. The label says its orange flavored."
/obj/item/reagent_containers/ecig_cartridge/orange/New()
..()
reagents.add_reagent(/datum/reagent/tobacco/liquid, 5)
reagents.add_reagent(/datum/reagent/water, 10)
reagents.add_reagent(/datum/reagent/drink/juice/orange, 5)
/obj/item/reagent_containers/ecig_cartridge/mint
name = "mint flavour cartridge"
desc = "A small metal cartridge which contains an atomizing coil and a solution to be atomized. The label says its mint flavored."
/obj/item/reagent_containers/ecig_cartridge/mint/New()
..()
reagents.add_reagent(/datum/reagent/tobacco/liquid, 5)
reagents.add_reagent(/datum/reagent/water, 10)
reagents.add_reagent(/datum/reagent/menthol, 5)
/obj/item/reagent_containers/ecig_cartridge/watermelon
name = "watermelon flavour cartridge"
desc = "A small metal cartridge which contains an atomizing coil and a solution to be atomized. The label says its watermelon flavored."
/obj/item/reagent_containers/ecig_cartridge/watermelon/New()
..()
reagents.add_reagent(/datum/reagent/tobacco/liquid, 5)
reagents.add_reagent(/datum/reagent/water, 10)
reagents.add_reagent(/datum/reagent/drink/juice/watermelon, 5)
/obj/item/reagent_containers/ecig_cartridge/grape
name = "grape flavour cartridge"
desc = "A small metal cartridge which contains an atomizing coil and a solution to be atomized. The label says its grape flavored."
/obj/item/reagent_containers/ecig_cartridge/grape/New()
..()
reagents.add_reagent(/datum/reagent/tobacco/liquid, 5)
reagents.add_reagent(/datum/reagent/water, 10)
reagents.add_reagent(/datum/reagent/drink/juice/grape, 5)
/obj/item/reagent_containers/ecig_cartridge/lemonlime
name = "lemon-lime flavour cartridge"
desc = "A small metal cartridge which contains an atomizing coil and a solution to be atomized. The label says its lemon-lime flavored."
/obj/item/reagent_containers/ecig_cartridge/lemonlime/New()
..()
reagents.add_reagent(/datum/reagent/tobacco/liquid, 5)
reagents.add_reagent(/datum/reagent/water, 10)
reagents.add_reagent(/datum/reagent/drink/lemon_lime, 5)
/obj/item/reagent_containers/ecig_cartridge/coffee
name = "coffee flavour cartridge"
desc = "A small metal cartridge which contains an atomizing coil and a solution to be atomized. The label says its coffee flavored."
/obj/item/reagent_containers/ecig_cartridge/coffee/New()
..()
reagents.add_reagent(/datum/reagent/tobacco/liquid, 5)
reagents.add_reagent(/datum/reagent/water, 10)
reagents.add_reagent(/datum/reagent/drink/coffee, 5)
/obj/item/clothing/mask/smokable/ecig/smoke(amount)
..(amount * 0.1)
| 1 | 0.903602 | 1 | 0.903602 | game-dev | MEDIA | 0.94565 | game-dev | 0.918103 | 1 | 0.918103 |
agens-no/iMessageStickerUnity | 13,465 | Assets/Stickers/Editor/Xcode/PBX/Utils.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace Agens.StickersEditor.UnityEditor.iOS.Xcode.PBX
{
internal class GUIDToCommentMap
{
private Dictionary<string, string> m_Dict = new Dictionary<string, string>();
public string this[string guid]
{
get {
if (m_Dict.ContainsKey(guid))
return m_Dict[guid];
return null;
}
}
public void Add(string guid, string comment)
{
if (m_Dict.ContainsKey(guid))
return;
m_Dict.Add(guid, comment);
}
public void Remove(string guid)
{
m_Dict.Remove(guid);
}
public string Write(string guid)
{
string comment = this[guid];
if (comment == null)
return guid;
return String.Format("{0} /* {1} */", guid, comment);
}
public void WriteStringBuilder(StringBuilder sb, string guid)
{
string comment = this[guid];
if (comment == null)
sb.Append(guid);
else
{
// {0} /* {1} */
sb.Append(guid).Append(" /* ").Append(comment).Append(" */");
}
}
}
internal class PBXGUID
{
internal delegate string GuidGenerator();
// We allow changing Guid generator to make testing of PBXProject possible
private static GuidGenerator guidGenerator = DefaultGuidGenerator;
internal static string DefaultGuidGenerator()
{
return Guid.NewGuid().ToString("N").Substring(8).ToUpper();
}
internal static void SetGuidGenerator(GuidGenerator generator)
{
guidGenerator = generator;
}
// Generates a GUID.
public static string Generate()
{
return guidGenerator();
}
}
internal class PBXRegex
{
public static string GuidRegexString = "[A-Fa-f0-9]{24}";
}
internal class PBXStream
{
static bool DontNeedQuotes(string src)
{
// using a regex instead of explicit matching slows down common cases by 40%
if (src.Length == 0)
return false;
bool hasSlash = false;
for (int i = 0; i < src.Length; ++i)
{
char c = src[i];
if (Char.IsLetterOrDigit(c) || c == '.' || c == '*' || c == '_')
continue;
if (c == '/')
{
hasSlash = true;
continue;
}
return false;
}
if (hasSlash)
{
if (src.Contains("//") || src.Contains("/*") || src.Contains("*/"))
return false;
}
return true;
}
// Quotes the given string if it contains special characters. Note: if the string already
// contains quotes, then they are escaped and the entire string quoted again
public static string QuoteStringIfNeeded(string src)
{
if (DontNeedQuotes(src))
return src;
return "\"" + src.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n") + "\"";
}
// If the given string is quoted, removes the quotes and unescapes any quotes within the string
public static string UnquoteString(string src)
{
if (!src.StartsWith("\"") || !src.EndsWith("\""))
return src;
return src.Substring(1, src.Length - 2).Replace("\\\\", "\u569f").Replace("\\\"", "\"")
.Replace("\\n", "\n").Replace("\u569f", "\\"); // U+569f is a rarely used Chinese character
}
}
internal enum PBXFileType
{
NotBuildable,
Framework,
Source,
Resource,
CopyFile
}
internal class FileTypeUtils
{
internal class FileTypeDesc
{
public FileTypeDesc(string typeName, PBXFileType type)
{
this.name = typeName;
this.type = type;
this.isExplicit = false;
}
public FileTypeDesc(string typeName, PBXFileType type, bool isExplicit)
{
this.name = typeName;
this.type = type;
this.isExplicit = isExplicit;
}
public string name;
public PBXFileType type;
public bool isExplicit;
}
private static readonly Dictionary<string, FileTypeDesc> types =
new Dictionary<string, FileTypeDesc>
{
{ ".a", new FileTypeDesc("archive.ar", PBXFileType.Framework) },
{ ".app", new FileTypeDesc("wrapper.application", PBXFileType.NotBuildable, true) },
{ ".appex", new FileTypeDesc("wrapper.app-extension", PBXFileType.CopyFile) },
{ ".bin", new FileTypeDesc("archive.macbinary", PBXFileType.Resource) },
{ ".s", new FileTypeDesc("sourcecode.asm", PBXFileType.Source) },
{ ".c", new FileTypeDesc("sourcecode.c.c", PBXFileType.Source) },
{ ".cc", new FileTypeDesc("sourcecode.cpp.cpp", PBXFileType.Source) },
{ ".cpp", new FileTypeDesc("sourcecode.cpp.cpp", PBXFileType.Source) },
{ ".swift", new FileTypeDesc("sourcecode.swift", PBXFileType.Source) },
{ ".dll", new FileTypeDesc("file", PBXFileType.NotBuildable) },
{ ".framework", new FileTypeDesc("wrapper.framework", PBXFileType.Framework) },
{ ".h", new FileTypeDesc("sourcecode.c.h", PBXFileType.NotBuildable) },
{ ".pch", new FileTypeDesc("sourcecode.c.h", PBXFileType.NotBuildable) },
{ ".icns", new FileTypeDesc("image.icns", PBXFileType.Resource) },
{ ".xcassets", new FileTypeDesc("folder.assetcatalog", PBXFileType.Resource) },
{ ".inc", new FileTypeDesc("sourcecode.inc", PBXFileType.NotBuildable) },
{ ".m", new FileTypeDesc("sourcecode.c.objc", PBXFileType.Source) },
{ ".mm", new FileTypeDesc("sourcecode.cpp.objcpp", PBXFileType.Source ) },
{ ".nib", new FileTypeDesc("wrapper.nib", PBXFileType.Resource) },
{ ".plist", new FileTypeDesc("text.plist.xml", PBXFileType.Resource) },
{ ".png", new FileTypeDesc("image.png", PBXFileType.Resource) },
{ ".rtf", new FileTypeDesc("text.rtf", PBXFileType.Resource) },
{ ".tiff", new FileTypeDesc("image.tiff", PBXFileType.Resource) },
{ ".txt", new FileTypeDesc("text", PBXFileType.Resource) },
{ ".json", new FileTypeDesc("text.json", PBXFileType.Resource) },
{ ".xcodeproj", new FileTypeDesc("wrapper.pb-project", PBXFileType.NotBuildable) },
{ ".xib", new FileTypeDesc("file.xib", PBXFileType.Resource) },
{ ".strings", new FileTypeDesc("text.plist.strings", PBXFileType.Resource) },
{ ".storyboard",new FileTypeDesc("file.storyboard", PBXFileType.Resource) },
{ ".bundle", new FileTypeDesc("wrapper.plug-in", PBXFileType.Resource) },
{ ".dylib", new FileTypeDesc("compiled.mach-o.dylib", PBXFileType.Framework) },
{ ".tbd", new FileTypeDesc("sourcecode.text-based-dylib-definition", PBXFileType.Framework) }
};
public static bool IsKnownExtension(string ext)
{
return types.ContainsKey(ext);
}
internal static bool IsFileTypeExplicit(string ext)
{
if (types.ContainsKey(ext))
return types[ext].isExplicit;
return false;
}
public static PBXFileType GetFileType(string ext, bool isFolderRef)
{
if (isFolderRef)
return PBXFileType.Resource;
if (!types.ContainsKey(ext))
return PBXFileType.Resource;
return types[ext].type;
}
public static string GetTypeName(string ext)
{
if (types.ContainsKey(ext))
return types[ext].name;
// Xcode actually checks the file contents to determine the file type.
// Text files have "text" type and all other files have "file" type.
// Since we can't reasonably determine whether the file in question is
// a text file, we just take the safe route and return "file" type.
return "file";
}
public static bool IsBuildableFile(string ext)
{
if (!types.ContainsKey(ext))
return true;
if (types[ext].type != PBXFileType.NotBuildable)
return true;
return false;
}
public static bool IsBuildable(string ext, bool isFolderReference)
{
if (isFolderReference)
return true;
return IsBuildableFile(ext);
}
private static readonly Dictionary<PBXSourceTree, string> sourceTree = new Dictionary<PBXSourceTree, string>
{
{ PBXSourceTree.Absolute, "<absolute>" },
{ PBXSourceTree.Group, "<group>" },
{ PBXSourceTree.Build, "BUILT_PRODUCTS_DIR" },
{ PBXSourceTree.Developer, "DEVELOPER_DIR" },
{ PBXSourceTree.Sdk, "SDKROOT" },
{ PBXSourceTree.Source, "SOURCE_ROOT" },
};
private static readonly Dictionary<string, PBXSourceTree> stringToSourceTreeMap = new Dictionary<string, PBXSourceTree>
{
{ "<absolute>", PBXSourceTree.Absolute },
{ "<group>", PBXSourceTree.Group },
{ "BUILT_PRODUCTS_DIR", PBXSourceTree.Build },
{ "DEVELOPER_DIR", PBXSourceTree.Developer },
{ "SDKROOT", PBXSourceTree.Sdk },
{ "SOURCE_ROOT", PBXSourceTree.Source },
};
internal static string SourceTreeDesc(PBXSourceTree tree)
{
return sourceTree[tree];
}
// returns PBXSourceTree.Source on error
internal static PBXSourceTree ParseSourceTree(string tree)
{
if (stringToSourceTreeMap.ContainsKey(tree))
return stringToSourceTreeMap[tree];
return PBXSourceTree.Source;
}
internal static List<PBXSourceTree> AllAbsoluteSourceTrees()
{
return new List<PBXSourceTree>{PBXSourceTree.Absolute, PBXSourceTree.Build, PBXSourceTree.Group,
PBXSourceTree.Developer, PBXSourceTree.Sdk, PBXSourceTree.Source};
}
}
internal class Utils
{
/// Replaces '\' with '/'. We need to apply this function to all paths that come from the user
/// of the API because we store paths to pbxproj and on windows we may get path with '\' slashes
/// instead of '/' slashes
public static string FixSlashesInPath(string path)
{
if (path == null)
return null;
return path.Replace('\\', '/');
}
public static void CombinePaths(string path1, PBXSourceTree tree1, string path2, PBXSourceTree tree2,
out string resPath, out PBXSourceTree resTree)
{
if (tree2 == PBXSourceTree.Group)
{
resPath = CombinePaths(path1, path2);
resTree = tree1;
return;
}
resPath = path2;
resTree = tree2;
}
public static string CombinePaths(string path1, string path2)
{
if (path2.StartsWith("/"))
return path2;
if (path1.EndsWith("/"))
return path1 + path2;
if (path1 == "")
return path2;
if (path2 == "")
return path1;
return path1 + "/" + path2;
}
public static string GetDirectoryFromPath(string path)
{
int pos = path.LastIndexOf('/');
if (pos == -1)
return "";
else
return path.Substring(0, pos);
}
public static string GetFilenameFromPath(string path)
{
int pos = path.LastIndexOf('/');
if (pos == -1)
return path;
else
return path.Substring(pos + 1);
}
public static string[] SplitPath(string path)
{
if (string.IsNullOrEmpty(path))
return new string[]{};
return path.Split(new[]{'/'}, StringSplitOptions.RemoveEmptyEntries);
}
}
} // UnityEditor.iOS.Xcode
| 1 | 0.710448 | 1 | 0.710448 | game-dev | MEDIA | 0.369916 | game-dev | 0.747016 | 1 | 0.747016 |
dimitri-br/runity | 1,648 | src/data.rs | use crate::{gameobject::GameObjectChanges, Debug, GameObject, Time};
use std::sync::Mutex;
use lazy_static::lazy_static;
/// # DataStruct
///
/// This struct stores all the data we need to run our game.
///
/// It contains structs that point to timing and debugging information.
#[repr(C)]
pub struct DataStruct{
pub time: Time,
pub debug: Debug,
}
// A local store of all data present in unity (that we can interact with)
//
// We then get, and send any state changes to the unity engine. We prefer
// rust changes over unity changes, as rust is more likely to be the source
// of truth.
pub struct LocalData{
gameobjects: Vec<GameObject>, // All gameobjects in the scene
changes: Vec<GameObjectChanges>, // All changes to gameobjects - to be sent to unity
data: Option<DataStruct>, // A reference to all data in the game like time and debug information
}
lazy_static!{
pub static ref LOCAL_DATA: Mutex<LocalData> = Mutex::new(LocalData{
gameobjects: Vec::new(),
changes: Vec::new(),
data: None,
});
}
// Safe extern wrappers to set the data
#[no_mangle]
pub extern "C" fn set_data(data: DataStruct){
let mut local_data = LOCAL_DATA.lock().unwrap();
local_data.data = Some(data);
}
// Data is a one-way street - we only get data from unity
// However, for changes, we need to send them back to unity
// Send changes to unity - return a reference to the changes
#[no_mangle]
pub extern "C" fn send_changes() -> Vec<GameObjectChanges>{
let mut local_data = LOCAL_DATA.lock().unwrap();
let changes = local_data.changes.clone();
local_data.changes.clear();
changes
} | 1 | 0.70264 | 1 | 0.70264 | game-dev | MEDIA | 0.858794 | game-dev | 0.665406 | 1 | 0.665406 |
mattmatterson111/IS12-Warfare-Two | 3,060 | code/game/objects/items/weapons/material/shards.dm | // Glass shards
/obj/item/material/shard
name = "shard"
icon = 'icons/obj/shards.dmi'
desc = "Made of nothing. How does this even exist?" // set based on material, if this desc is visible it's a bug (shards default to being made of glass)
icon_state = "large"
randpixel = 8
sharp = 1
edge = 1
w_class = ITEM_SIZE_SMALL
force_divisor = 0.2 // 6 with hardness 30 (glass)
thrown_force_divisor = 0.4 // 4 with weight 15 (glass)
item_state = "shard-glass"
attack_verb = list("stabbed", "slashed", "sliced", "cut")
default_material = "glass"
unbreakable = 1 //It's already broken.
drops_debris = 0
/obj/item/material/shard/set_material(var/new_material)
..(new_material)
if(!istype(material))
return
icon_state = "[material.shard_icon][pick("large", "medium", "small")]"
update_icon()
if(material.shard_type)
SetName("[material.display_name] [material.shard_type]")
desc = "A small piece of [material.display_name]. It looks sharp, you wouldn't want to step on it barefoot. Could probably be used as ... a throwing weapon?"
switch(material.shard_type)
if(SHARD_SPLINTER, SHARD_SHRAPNEL)
gender = PLURAL
else
gender = NEUTER
else
qdel(src)
/obj/item/material/shard/update_icon()
if(material)
color = material.icon_colour
// 1-(1-x)^2, so that glass shards with 0.3 opacity end up somewhat visible at 0.51 opacity
alpha = 255 * (1 - (1 - material.opacity)*(1 - material.opacity))
else
color = "#ffffff"
alpha = 255
/obj/item/material/shard/attackby(obj/item/W as obj, mob/user as mob)
if(isWelder(W) && material.shard_can_repair)
var/obj/item/weldingtool/WT = W
if(WT.remove_fuel(0, user))
material.place_sheet(loc)
qdel(src)
return
return ..()
/obj/item/material/shard/Crossed(AM as mob|obj)
..()
if(isliving(AM))
var/mob/M = AM
if(M.buckled) //wheelchairs, office chairs, rollerbeds
return
playsound(src.loc, 'sound/effects/glass_step.ogg', 50, 1) // not sure how to handle metal shards with sounds
if(ishuman(M))
var/mob/living/carbon/human/H = M
if(H.species.siemens_coefficient<0.5 || (H.species.species_flags & (SPECIES_FLAG_NO_EMBED|SPECIES_FLAG_NO_MINOR_CUT))) //Thick skin.
return
if( H.shoes || ( H.wear_suit && (H.wear_suit.body_parts_covered & FEET) ) )
return
to_chat(M, "<span class='danger'>You step on \the [src]!</span>")
var/list/check = list(BP_L_FOOT, BP_R_FOOT)
while(check.len)
var/picked = pick(check)
var/obj/item/organ/external/affecting = H.get_organ(picked)
if(affecting)
if(affecting.robotic >= ORGAN_ROBOT)
return
affecting.take_damage(5, 0)
H.updatehealth()
if(affecting.can_feel_pain())
H.Weaken(3)
return
check -= picked
return
// Preset types - left here for the code that uses them
/obj/item/material/shrapnel
name = "shrapnel"
default_material = DEFAULT_WALL_MATERIAL
w_class = ITEM_SIZE_TINY //it's real small
/obj/item/material/shard/shrapnel/New(loc)
..(loc, DEFAULT_WALL_MATERIAL)
/obj/item/material/shard/phoron/New(loc)
..(loc, "phglass")
| 1 | 0.963696 | 1 | 0.963696 | game-dev | MEDIA | 0.996602 | game-dev | 0.977491 | 1 | 0.977491 |
simbody/simbody | 15,006 | examples/ExampleTwoBoxCollide.cpp | /* -------------------------------------------------------------------------- *
* Simbody(tm) Example: Contact Playground *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2010-13 Stanford University and the Authors. *
* Authors: Kevin He, Michael Sherman *
* Contributors: *
* *
* 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. *
* -------------------------------------------------------------------------- */
/* Kevin He at Roblox created this example starting with
ExampleContactPlayground. It basically demonstrates why an Elastic Foundation
(EF) contact model is not a good way to handle coarsely-meshed simple objects,
like a box. EF uses the centroid of each face to generate an area-weighted
force, which can be a good physical representation with a dense mesh but
since the vertices and edges don't participate there is a lot of visible
penetration for a coarse mesh like the ones here.
*/
#include "Simbody.h"
#include <cstdio>
#include <exception>
#include <algorithm>
#include <iostream>
#include <fstream>
using std::cout; using std::endl;
using namespace SimTK;
Array_<State> saveEm;
static const Real TimeScale = 1;
static const Real FrameRate = 30;
static const Real ReportInterval = TimeScale/FrameRate;
// These are the item numbers for the entries on the Run menu.
static const int RunMenuId = 3, HelpMenuId = 7;
static const int GoItem = 1, ReplayItem=2, QuitItem=3;
// This is a periodic event handler that interrupts the simulation on a regular
// basis to poll the InputSilo for user input. If there has been some, process it.
// This one does nothing but look for the Run->Quit selection.
class UserInputHandler : public PeriodicEventHandler {
public:
UserInputHandler(Visualizer::InputSilo& silo, Real interval)
: PeriodicEventHandler(interval), m_silo(silo) {}
virtual void handleEvent(State& state, Real accuracy,
bool& shouldTerminate) const override
{
int menuId, item;
if (m_silo.takeMenuPick(menuId, item) && menuId==RunMenuId && item==QuitItem)
shouldTerminate = true;
}
private:
Visualizer::InputSilo& m_silo;
};
static void makeCube(Real h, PolygonalMesh& cube);
static void makeTetrahedron(Real r, PolygonalMesh& tet);
static void makePyramid(Real baseSideLength, PolygonalMesh& pyramid);
static void makeOctahedron(Real radius, PolygonalMesh& pyramid);
int main() {
try
{ // Create the system.
MultibodySystem system;
SimbodyMatterSubsystem matter(system);
GeneralForceSubsystem forces(system);
Force::Gravity gravity(forces, matter, UnitVec3(2,-10,0), 1);
ContactTrackerSubsystem tracker(system);
CompliantContactSubsystem contactForces(system, tracker);
contactForces.setTrackDissipatedEnergy(true);
contactForces.setTransitionVelocity(1e-3);
Vec3 halfSize(3,4,5);
Vec3 halfSize2(200, 4, 200);
ContactGeometry::TriangleMesh box(PolygonalMesh::createBrickMesh(halfSize));
ContactGeometry::TriangleMesh box2(PolygonalMesh::createBrickMesh(halfSize2, 20));
DecorativeMesh showBox(box.createPolygonalMesh());
DecorativeMesh showBox2(box2.createPolygonalMesh());
const Real boxMass = halfSize[0] * halfSize[1] * halfSize[2] * 8;
const Real boxMass2 = halfSize2[0] * halfSize2[1] * halfSize2[2] * 8;
Body::Rigid boxBody(MassProperties(boxMass, Vec3(0),
boxMass * UnitInertia::brick(halfSize)));
Body::Rigid boxBody2(MassProperties(boxMass2, Vec3(0),
boxMass2 * UnitInertia::brick(halfSize2)));
boxBody.addDecoration(Transform(),
showBox.setColor(Red).setOpacity(1));
boxBody.addDecoration(Transform(),
showBox.setColor(Gray).setRepresentation(DecorativeGeometry::DrawWireframe));
boxBody2.addDecoration(Transform(),
showBox2.setColor(Cyan).setOpacity(.6));
boxBody2.addDecoration(Transform(),
showBox2.setColor(Gray).setRepresentation(DecorativeGeometry::DrawWireframe));
// boxBody.addDecoration(Transform(),
// DecorativeSphere(1).setColor(Gray).setOpacity(.1).setResolution(10));
const Real fFac = 0.3; // to turn off friction
const Real fDis = 0.1; // to turn off dissipation
const Real fVis = 0.01; // to turn off viscous friction
const Real fK = 1e+8; // pascals
boxBody.addContactSurface(Transform(),
ContactSurface(box,
ContactMaterial(fK, fDis, fFac, fFac, fVis),
.5 /*thickness*/)
);
boxBody2.addContactSurface(Transform(),
ContactSurface(box2,
ContactMaterial(fK, fDis, fFac, fFac, fVis),
.5 /*thickness*/)
);
MobilizedBody::Free boxMBody(matter.Ground(), Transform(Vec3(0)), boxBody, Transform(Vec3(0)));
MobilizedBody::Weld boxMBody2(matter.Ground(), Transform(Vec3(0)), boxBody2, Transform(Vec3(0)));
Visualizer viz(system);
// viz.addDecorationGenerator(new ForceArrowGenerator(system,contactForces));
viz.setMode(Visualizer::RealTime);
viz.setDesiredBufferLengthInSec(1);
viz.setDesiredFrameRate(FrameRate);
viz.setGroundHeight(0);
viz.setShowShadows(true);
Visualizer::InputSilo* silo = new Visualizer::InputSilo();
viz.addInputListener(silo);
Array_<std::pair<String,int> > runMenuItems;
runMenuItems.push_back(std::make_pair("Go", GoItem));
runMenuItems.push_back(std::make_pair("Replay", ReplayItem));
runMenuItems.push_back(std::make_pair("Quit", QuitItem));
viz.addMenu("Run", RunMenuId, runMenuItems);
Array_<std::pair<String,int> > helpMenuItems;
helpMenuItems.push_back(std::make_pair("TBD - Sorry!", 1));
viz.addMenu("Help", HelpMenuId, helpMenuItems);
// system.addEventReporter(new MyReporter(system,contactForces,ReportInterval));
system.addEventReporter(new Visualizer::Reporter(viz, ReportInterval));
// Check for a Run->Quit menu pick every 1/4 second.
system.addEventHandler(new UserInputHandler(*silo, .25));
// Initialize the system and state.
system.realizeTopology();
State state = system.getDefaultState();
//ball.setQToFitTransform(state, Transform(Rotation(Pi/2,XAxis),
// Vec3(0,-1.8,0)));
boxMBody.setQToFitTransform(state, Transform(Vec3(0, 10, 0)));
boxMBody2.setQToFitTransform(state, Transform(Vec3(0, 0, 0)));
viz.report(state);
cout << "\nChoose 'Go' from Run menu to simulate:\n";
int menuId, item;
do { silo->waitForMenuPick(menuId, item);
if (menuId != RunMenuId || item != GoItem)
cout << "\aDude ... follow instructions!\n";
} while (menuId != RunMenuId || item != GoItem);
//ball.setOneU(state, 2, -20);
// ball.setOneU(state, 0, .05); // to break symmetry
CPodesIntegrator integ(system,CPodes::BDF,CPodes::Newton);
integ.setAccuracy(1e-3); // minimum for CPodes
TimeStepper ts(system, integ);
ts.initialize(state);
double cpuStart = cpuTime();
double realStart = realTime();
ts.stepTo(100.0);
const double timeInSec = realTime() - realStart;
const int evals = integ.getNumRealizations();
cout << "Done -- took " << integ.getNumStepsTaken() << " steps in " <<
timeInSec << "s elapsed for " << ts.getTime() << "s sim (avg step="
<< (1000*ts.getTime())/integ.getNumStepsTaken() << "ms) "
<< (1000*ts.getTime())/evals << "ms/eval\n";
cout << " CPU time was " << cpuTime() - cpuStart << "s\n";
printf("Using Integrator %s at accuracy %g:\n",
integ.getMethodName(), integ.getAccuracyInUse());
printf("# STEPS/ATTEMPTS = %d/%d\n", integ.getNumStepsTaken(), integ.getNumStepsAttempted());
printf("# ERR TEST FAILS = %d\n", integ.getNumErrorTestFailures());
printf("# REALIZE/PROJECT = %d/%d\n", integ.getNumRealizations(), integ.getNumProjections());
viz.dumpStats(std::cout);
// Add as slider to control playback speed.
viz.addSlider("Speed", 1, 0, 4, 1);
viz.setMode(Visualizer::PassThrough);
silo->clear(); // forget earlier input
double speed = 1; // will change if slider moves
while(true) {
cout << "Choose Run/Replay to see that again ...\n";
int menuId, item;
silo->waitForMenuPick(menuId, item);
if (menuId != RunMenuId) {
cout << "\aUse the Run menu!\n";
continue;
}
if (item == QuitItem)
break;
if (item != ReplayItem) {
cout << "\aHuh? Try again.\n";
continue;
}
for (double i=0; i < (int)saveEm.size(); i += speed ) {
int slider; Real newValue;
if (silo->takeSliderMove(slider,newValue)) {
speed = newValue;
}
viz.report(saveEm[(int)i]);
}
}
} catch (const std::exception& e) {
std::printf("EXCEPTION THROWN: %s\n", e.what());
exit(1);
} catch (...) {
std::printf("UNKNOWN EXCEPTION THROWN\n");
exit(1);
}
return 0;
}
// Create a triangle mesh in the shape of a pyramid, with the
// square base in the x-z plane centered at 0,0,0 of given side length s.
// The base is split into two triangles. The apex will be at (0,s,0).
static void makePyramid(Real s, PolygonalMesh& pyramidMesh) {
const Real h = s/2;
Array_<Vec3> vertices;
vertices.push_back(Vec3(-h, 0, -h)); // base
vertices.push_back(Vec3( h, 0, -h));
vertices.push_back(Vec3( h, 0, h));
vertices.push_back(Vec3(-h, 0, h));
vertices.push_back(Vec3( 0, s, 0)); // apex
Array_<int> faceIndices;
int faces[6][3] = {{0, 1, 2}, {0, 2, 3}, {1, 0, 4},
{2, 1, 4}, {3, 2, 4}, {0, 3, 4}};
for (int i = 0; i < 6; i++)
for (int j = 0; j < 3; j++)
faceIndices.push_back(faces[i][j]);
for (unsigned i=0; i < vertices.size(); ++i)
pyramidMesh.addVertex(vertices[i]);
for (unsigned i=0; i < faceIndices.size(); i += 3) {
const Array_<int> verts(&faceIndices[i], &faceIndices[i]+3);
pyramidMesh.addFace(verts);
}
}
// Create a triangle mesh in the shape of a tetrahedron with the
// points in the corners of a cube inscribed in a sphere of radius r.
static void makeTetrahedron(Real r, PolygonalMesh& tet) {
const Real h = r/std::sqrt(Real(3)); // half-dim of cube
Array_<Vec3> vertices;
vertices.push_back(Vec3( h, h, h));
vertices.push_back(Vec3(-h,-h, h));
vertices.push_back(Vec3(-h, h, -h));
vertices.push_back(Vec3( h,-h, -h));
Array_<int> faceIndices;
int faces[4][3] = {{0, 2, 1}, {1, 3, 0}, {0, 3, 2}, {2, 3, 1}};
for (int i = 0; i < 4; i++)
for (int j = 0; j < 3; j++)
faceIndices.push_back(faces[i][j]);
for (unsigned i=0; i < vertices.size(); ++i)
tet.addVertex(vertices[i]);
for (unsigned i=0; i < faceIndices.size(); i += 3) {
const Array_<int> verts(&faceIndices[i], &faceIndices[i]+3);
tet.addFace(verts);
}
}
static void makeOctahedralMesh(const Vec3& r, Array_<Vec3>& vertices,
Array_<int>& faceIndices) {
vertices.push_back(Vec3( r[0], 0, 0)); //0
vertices.push_back(Vec3(-r[0], 0, 0)); //1
vertices.push_back(Vec3( 0, r[1], 0)); //2
vertices.push_back(Vec3( 0, -r[1], 0)); //3
vertices.push_back(Vec3( 0, 0, r[2])); //4
vertices.push_back(Vec3( 0, 0, -r[2])); //5
int faces[8][3] = {{0, 2, 4}, {4, 2, 1}, {1, 2, 5}, {5, 2, 0},
{4, 3, 0}, {1, 3, 4}, {5, 3, 1}, {0, 3, 5}};
for (int i = 0; i < 8; i++)
for (int j = 0; j < 3; j++)
faceIndices.push_back(faces[i][j]);
}
// Create a triangle mesh in the shape of an octahedron (like two
// pyramids stacked base-to-base, with the square base in the x-z plane
// centered at 0,0,0 of given "radius" r.
// The apexes will be at (0,+/-r,0).
static void makeOctahedron(Real r, PolygonalMesh& mesh) {
Array_<Vec3> vertices;
Array_<int> faceIndices;
makeOctahedralMesh(Vec3(r), vertices, faceIndices);
for (unsigned i=0; i < vertices.size(); ++i)
mesh.addVertex(vertices[i]);
for (unsigned i=0; i < faceIndices.size(); i += 3) {
const Array_<int> verts(&faceIndices[i], &faceIndices[i]+3);
mesh.addFace(verts);
}
}
static void makeCube(Real h, PolygonalMesh& cube) {
Array_<Vec3> vertices;
vertices.push_back(Vec3( h, h, h));
vertices.push_back(Vec3( h, h, -h));
vertices.push_back(Vec3( h,-h, h));
vertices.push_back(Vec3( h,-h, -h));
vertices.push_back(Vec3(-h, h, h));
vertices.push_back(Vec3(-h, h, -h));
vertices.push_back(Vec3(-h,-h, h));
vertices.push_back(Vec3(-h,-h, -h));
Array_<int> faceIndices;
int faces[6][4] = {{0,2,3,1},{1,5,4,0},{0,4,6,2},
{2,6,7,3},{3,7,5,1},{4,5,7,6}};
for (int i = 0; i < 6; i++)
for (int j = 0; j < 4; j++)
faceIndices.push_back(faces[i][j]);
for (unsigned i=0; i < vertices.size(); ++i)
cube.addVertex(vertices[i]);
for (unsigned i=0; i < faceIndices.size(); i += 4) {
const Array_<int> verts(&faceIndices[i], &faceIndices[i]+4);
cube.addFace(verts);
}
}
| 1 | 0.907902 | 1 | 0.907902 | game-dev | MEDIA | 0.355767 | game-dev | 0.928055 | 1 | 0.928055 |
dotnet/Silk.NET | 5,268 | src/Vulkan/Silk.NET.Vulkan/Video/Structs/StdVideoH264PpsFlags.gen.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Text;
using Silk.NET.Core;
using Silk.NET.Core.Native;
using Silk.NET.Core.Attributes;
using Silk.NET.Core.Contexts;
using Silk.NET.Core.Loader;
#pragma warning disable 1591
namespace Silk.NET.Vulkan.Video
{
[NativeName("Name", "StdVideoH264PpsFlags")]
public unsafe partial struct StdVideoH264PpsFlags
{
public StdVideoH264PpsFlags
(
uint? transform8x8ModeFlag = null,
uint? redundantPicCntPresentFlag = null,
uint? constrainedIntraPredFlag = null,
uint? deblockingFilterControlPresentFlag = null,
uint? weightedPredFlag = null,
uint? bottomFieldPicOrderInFramePresentFlag = null,
uint? entropyCodingModeFlag = null,
uint? picScalingMatrixPresentFlag = null
) : this()
{
if (transform8x8ModeFlag is not null)
{
Transform8x8ModeFlag = transform8x8ModeFlag.Value;
}
if (redundantPicCntPresentFlag is not null)
{
RedundantPicCntPresentFlag = redundantPicCntPresentFlag.Value;
}
if (constrainedIntraPredFlag is not null)
{
ConstrainedIntraPredFlag = constrainedIntraPredFlag.Value;
}
if (deblockingFilterControlPresentFlag is not null)
{
DeblockingFilterControlPresentFlag = deblockingFilterControlPresentFlag.Value;
}
if (weightedPredFlag is not null)
{
WeightedPredFlag = weightedPredFlag.Value;
}
if (bottomFieldPicOrderInFramePresentFlag is not null)
{
BottomFieldPicOrderInFramePresentFlag = bottomFieldPicOrderInFramePresentFlag.Value;
}
if (entropyCodingModeFlag is not null)
{
EntropyCodingModeFlag = entropyCodingModeFlag.Value;
}
if (picScalingMatrixPresentFlag is not null)
{
PicScalingMatrixPresentFlag = picScalingMatrixPresentFlag.Value;
}
}
private uint _bitfield1;
public uint Transform8x8ModeFlag
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (uint)(_bitfield1 & 0x1u);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => _bitfield1 = (uint)((uint)(_bitfield1 & ~0x1u) | (uint)((uint)(value) & 0x1u));
}
public uint RedundantPicCntPresentFlag
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (uint)((_bitfield1 >> 1) & 0x1u);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 1)) | (uint)(((uint)(value) & 0x1u) << 1));
}
public uint ConstrainedIntraPredFlag
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (uint)((_bitfield1 >> 2) & 0x1u);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 2)) | (uint)(((uint)(value) & 0x1u) << 2));
}
public uint DeblockingFilterControlPresentFlag
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (uint)((_bitfield1 >> 3) & 0x1u);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 3)) | (uint)(((uint)(value) & 0x1u) << 3));
}
public uint WeightedPredFlag
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (uint)((_bitfield1 >> 4) & 0x1u);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 4)) | (uint)(((uint)(value) & 0x1u) << 4));
}
public uint BottomFieldPicOrderInFramePresentFlag
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (uint)((_bitfield1 >> 5) & 0x1u);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 5)) | (uint)(((uint)(value) & 0x1u) << 5));
}
public uint EntropyCodingModeFlag
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (uint)((_bitfield1 >> 6) & 0x1u);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 6)) | (uint)(((uint)(value) & 0x1u) << 6));
}
public uint PicScalingMatrixPresentFlag
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (uint)((_bitfield1 >> 7) & 0x1u);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 7)) | (uint)(((uint)(value) & 0x1u) << 7));
}
}
}
| 1 | 0.833584 | 1 | 0.833584 | game-dev | MEDIA | 0.349424 | game-dev | 0.598628 | 1 | 0.598628 |
exmex/UnityMoba | 15,927 | Assets/StreamingAssets/lua/Logic/M065/PreviewHero/PreviewHeroAPI.lua | --Maintenance By WYL
local json = require "cjson"
require "Logic.UICommon.Static.UITools"
require "Logic.UTGData.UTGData"
class("PreviewHeroAPI")
----------------------------------------------------
function PreviewHeroAPI:Awake(this)
self.this = this
-------------------------------------
PreviewHeroAPI.Instance=self;
-----------------引用--------------------
self.CategoryAllbutton =self.this.transform:FindChild("Left/Middle/Mask/ScrollRect/ServerMenu/CategoryAll").gameObject
self.Category0button =self.this.transform:FindChild("Left/Middle/Mask/ScrollRect/ServerMenu/Category0").gameObject
self.Category1button =self.this.transform:FindChild("Left/Middle/Mask/ScrollRect/ServerMenu/Category1").gameObject
self.Category2button =self.this.transform:FindChild("Left/Middle/Mask/ScrollRect/ServerMenu/Category2").gameObject
self.Category3button =self.this.transform:FindChild("Left/Middle/Mask/ScrollRect/ServerMenu/Category3").gameObject
self.Category4button =self.this.transform:FindChild("Left/Middle/Mask/ScrollRect/ServerMenu/Category4").gameObject
self.Category5button =self.this.transform:FindChild("Left/Middle/Mask/ScrollRect/ServerMenu/Category5").gameObject
-------------按职业区分表-----------
self.class0Table={}
self.class1Table={}
self.class2Table={}
self.class3Table={}
self.class4Table={}
self.class5Table={}
self.selectedTable={}
--上方资源条
self.NormalResourcePanel = GameManager.CreatePanel("NormalResource")
end
function PreviewHeroAPI:ResetPanel()
local topAPI = self.NormalResourcePanel.gameObject:GetComponent("NTGLuaScript").self
topAPI:GoToPosition("PreviewHeroPanel")
topAPI:ShowControl(3)
topAPI:InitTop(self,self.OnReturnButtonClick,nil,nil,"姬神列表")
topAPI:InitResource(0)
topAPI:HideSom("Button")
UTGDataOperator.Instance:SetResourceList(topAPI)
end
----------------------------------------------------
function PreviewHeroAPI:Start()
--临时添加等待
if WaitingPanelAPI ~= nil and WaitingPanelAPI.Instance ~= nil then
WaitingPanelAPI.Instance:DestroySelf()
end
--UnityEngine.Resources.UnloadUnusedAssets();
self:ResetPanel()
self.Content = UITools.GetLuaScript( self.this.transform:FindChild("Right/Middle/Mask/ScrollRect/Content") ,
"Logic.UICommon.UIItems")
self:ValidLimitFreeRoleListRequest()
end
function PreviewHeroAPI:SetParam()
--------------------------全部英雄-------------------------
local sortTable={}
for k,v in pairs(UTGData.Instance().RolesData) do
table.insert(sortTable,v)
end
table.sort(sortTable,function(a,b) return tonumber(a.Id)<tonumber(b.Id) end )--按Id排序
--------------------------拥有及体验英雄-------------------------
local deckTable={} --拥有
local experienceTable={} --体验
for k,v in pairs(UTGData.Instance().RolesDeck) do --Debugger.LogError("拥有英雄")
if(v.IsOwn==true)then
table.insert(deckTable,v)
elseif(UTGData.Instance():GetLeftTime(v.ExperienceTime)>0 )then
table.insert(experienceTable,v)
end
end
--------------------------限免英雄-------------------------
local freeTable={}
for k,v in pairs(self.LimitFreeData) do
table.insert(freeTable,v)
end
--------------------------Sort-------------------------
--s meaning Sroted
local sTable1Own={}; --拥有(包括限免)
local sTable1IIExp={}; --体验
local sTable2NoOwn={}; --没有
for i,v1 in pairs(sortTable) do
local flag=false;
local ID=v1.Id;
for j,v2 in pairs(deckTable) do
if(ID==v2.RoleId)then
table.insert(sTable1Own,v1);
flag=true
end
end
if(flag==false)then
local isIn=false;
for k3,v3 in pairs(experienceTable) do
if(ID==v3.RoleId)then
table.insert(sTable1IIExp,v1);
isIn=true
break
end
end
if(isIn==false)then
table.insert(sTable2NoOwn,v1);
end
end
end
----Debugger.LogError("Sorted : sTable1Own:" .. #sTable1Own);
----Debugger.LogError("Sorted:table1NoOwn:" .. #sTable2NoOwn);
local sTable3Free={} --没有&&限免
local sTable4NoOwn={} --没有&&不是限免
for i,v1 in pairs(sTable2NoOwn) do
local flag=false;
local ID=v1.Id;
for j,v2 in pairs(freeTable) do
if(ID==v2)then
table.insert(sTable3Free,v1);
flag=true
end
end
if(flag==false)then
table.insert(sTable4NoOwn,v1);
end
end
----Debugger.LogError("Sorted : sTable3Free:" .. #sTable3Free);
----Debugger.LogError("Sorted:sTable4NoOwn:" .. #sTable4NoOwn);
------------------------------将Sorted数据存进一个table--------------------------------
local sTableAll={};
for i,v in pairs(sTable1Own) do
table.insert(sTableAll,v);
end
for i,v in pairs(sTable3Free) do
table.insert(sTableAll,v);
end
for i,v in pairs(sTable1IIExp) do --体验
table.insert(sTableAll,v);
end
for i,v in pairs(sTable4NoOwn) do
table.insert(sTableAll,v);
end
-----------------------------------对排好序的表进行深拷贝------------------------------
--local tableCopy=self:CopyTab(sTableAll);
self.tableCopy=UITools.CopyTab(sTableAll);
-----------------------------将所需要的属性添加进tableCopy-----------------------------
for i,v1 in pairs(self.tableCopy) do
--已经拥有所需数据:职业,名字
local ID=v1.Id;
v1.Deck=false;--是否拥有
for j,v in pairs(deckTable) do
if(ID==v.RoleId)then
v1.Deck=true;
end
end
v1.Free=false;--是否限免
for j,v in pairs(freeTable) do
if(ID==v)then
v1.Free=true;
end
end
v1.Exper=false;--是否体验
for j,v in pairs(experienceTable) do
if(ID==v.RoleId)then
v1.Exper=true;
end
end
v1.ProficiencyQuality=0;--熟练度等级
for j,v in pairs(deckTable) do
if(ID==v.RoleId)then
for k,v2 in pairs(UTGData.Instance().RoleProficiencysData) do
if(v.ProficiencyId==v2.Id )then
v1.ProficiencyQuality=v2.Quality;
end
end
end
end
v1.Portrait="";--皮肤
------------------------先把默认皮肤赋值给拷贝表的Portrait----------------------
for k,v2 in pairs(UTGData.Instance().SkinsData) do --在表中找出对应的Portrait
if(v1.Skin==v2.Id )then
v1.Portrait=v2.Portrait;
v1.CurrentSkin=v2.Id
end
end
---------------------再赋值上次使用过的皮肤,有的话就覆盖默认了-----------------
for j,v in pairs(deckTable) do --在Deck表中找到对应的Skin
if(ID==v.RoleId)then
for k,v2 in pairs(UTGData.Instance().SkinsData) do --在表中找出对应的Portrait
if(v.Skin==v2.Id )then
v1.Portrait=v2.Portrait;
v1.CurrentSkin=v2.Id
end
end
end
end
end
--[[
for i,v in pairs(self.tableCopy) do
--Debugger.LogError("Id :" .. v.Id);
--Debugger.LogError("名字 :" .. v.Name);
--Debugger.LogError("职业 :" .. v.Class);
--Debugger.LogError("是否拥有:" .. tostring(v.Deck));
--Debugger.LogError("是否限免:" .. tostring(v.Free));
--Debugger.LogError("熟练度: " .. v.ProficiencyQuality);
--Debugger.LogError("当前皮肤:" .. v.Portrait);
end
--]]
-------------------------------------按职业区分-----------------------------------------
self.class0Table={}
self.class1Table={}
self.class2Table={}
self.class3Table={}
self.class4Table={}
self.class5Table={}
for i,v in pairs(self.tableCopy) do
if(v.Class==0)then
table.insert(self.class0Table,v);
elseif(v.Class==1)then
table.insert(self.class1Table,v);
elseif(v.Class==2)then
table.insert(self.class2Table,v);
elseif(v.Class==3)then
table.insert(self.class3Table,v);
elseif(v.Class==4)then
table.insert(self.class4Table,v);
elseif(v.Class==5)then
table.insert(self.class5Table,v);
end
end
-----------------------------委托事件-----------------------------
local listener = NTGEventTriggerProxy.Get(self.CategoryAllbutton)
listener.onPointerClick = listener.onPointerClick + NTGEventTriggerProxy.PointerEventDelegateSelf( self.OnCategoryAllButtonClick,self)
listener = NTGEventTriggerProxy.Get(self.Category0button)
listener.onPointerClick = listener.onPointerClick + NTGEventTriggerProxy.PointerEventDelegateSelf( self.OnCategory0ButtonClick,self)
listener = NTGEventTriggerProxy.Get(self.Category1button)
listener.onPointerClick = listener.onPointerClick + NTGEventTriggerProxy.PointerEventDelegateSelf( self.OnCategory1ButtonClick,self)
listener = NTGEventTriggerProxy.Get(self.Category2button)
listener.onPointerClick = listener.onPointerClick + NTGEventTriggerProxy.PointerEventDelegateSelf( self.OnCategory2ButtonClick,self)
listener = NTGEventTriggerProxy.Get(self.Category3button)
listener.onPointerClick = listener.onPointerClick + NTGEventTriggerProxy.PointerEventDelegateSelf( self.OnCategory3ButtonClick,self)
listener = NTGEventTriggerProxy.Get(self.Category4button)
listener.onPointerClick = listener.onPointerClick + NTGEventTriggerProxy.PointerEventDelegateSelf( self.OnCategory4ButtonClick,self)
listener = NTGEventTriggerProxy.Get(self.Category5button)
listener.onPointerClick = listener.onPointerClick + NTGEventTriggerProxy.PointerEventDelegateSelf( self.OnCategory5ButtonClick,self)
-------------------------------------
self:OnCategoryAllButtonClick()--执行一次点击事件,默认显示全部Item
end
-------------------------Start结束--------------------------
-------------------------委托方法---------------------------
function PreviewHeroAPI:OnReturnButtonClick()
if(UTGMainPanelAPI~=nil)then
UTGMainPanelAPI.Instance:ShowSelf()
end
Object.Destroy(self.this.gameObject)
end
function PreviewHeroAPI:OnCategoryAllButtonClick()
self.selectedTable=self.tableCopy
self.Content:ResetItemsSimple(#self.tableCopy)
self:Evaluation(self.tableCopy);
end
function PreviewHeroAPI:OnCategory0ButtonClick()
self.selectedTable=self.class0Table
self.Content:ResetItemsSimple(#self.class0Table)
self:Evaluation(self.class0Table);
end
function PreviewHeroAPI:OnCategory1ButtonClick()
self.selectedTable=self.class1Table
self.Content:ResetItemsSimple(#self.class1Table)
self:Evaluation(self.class1Table);
end
function PreviewHeroAPI:OnCategory2ButtonClick()
self.selectedTable=self.class2Table
self.Content:ResetItemsSimple(#self.class2Table)
self:Evaluation(self.class2Table);
end
function PreviewHeroAPI:OnCategory3ButtonClick()
self.selectedTable=self.class3Table
self.Content:ResetItemsSimple(#self.class3Table)
self:Evaluation(self.class3Table);
end
function PreviewHeroAPI:OnCategory4ButtonClick()
self.selectedTable=self.class4Table
self.Content:ResetItemsSimple(#self.class4Table)
self:Evaluation(self.class4Table);
end
function PreviewHeroAPI:OnCategory5ButtonClick()
self.selectedTable=self.class5Table
self.Content:ResetItemsSimple(#self.class5Table)
self:Evaluation(self.class5Table);
end
------------------------为Item赋值----------------------------
function PreviewHeroAPI:Evaluation(temp)
for i=1, #self.Content.itemList,1 do
--赋值
self.Content.itemList[i].transform:FindChild("IconMask/Icon"):GetComponent("UnityEngine.UI.Image").sprite=UITools.GetSprite("portrait",temp[i].Portrait);
self.Content.itemList[i].transform:FindChild("Name"):GetComponent("UnityEngine.UI.Text").text=temp[i].Name;
self.Content.itemList[i].transform:FindChild("Free").gameObject:SetActive(temp[i].Free);
if(temp[i].Free==false and temp[i].Exper==true)then
self.Content.itemList[i].transform:FindChild("Exper").gameObject:SetActive(true);
else
self.Content.itemList[i].transform:FindChild("Exper").gameObject:SetActive(false);
end
if(temp[i].ProficiencyQuality==0)then
--self.Content.itemList[i].transform:FindChild("Proficiency"):GetComponent("UnityEngine.UI.Image").color=Color.New(0.25,0.25,0.25,1)
else
self.Content.itemList[i].transform:FindChild("Proficiency"):GetComponent("UnityEngine.UI.Image").color=Color.white;
self.Content.itemList[i].transform:FindChild("Proficiency"):GetComponent("UnityEngine.UI.Image").sprite
= UITools.GetSprite("icon", "Ishuliandu-" .. temp[i].ProficiencyQuality );
self.Content.itemList[i].transform:FindChild("Proficiency"):GetComponent("UnityEngine.UI.Image"):SetNativeSize()
end
if(temp[i].Deck or temp[i].Free or temp[i].Exper)then
self.Content.itemList[i].transform:FindChild("IconMask/Icon"):GetComponent("UnityEngine.UI.Image").color=Color.white
else
self.Content.itemList[i].transform:FindChild("IconMask/Icon"):GetComponent("UnityEngine.UI.Image").color=Color.New(0.25,0.25,0.25,1)
end
if(temp[i].Deck)then
self.Content.itemList[i].transform:FindChild("Proficiency"):GetComponent("UnityEngine.UI.Image").color=Color.white
else
self.Content.itemList[i].transform:FindChild("Proficiency"):GetComponent("UnityEngine.UI.Image").color=Color.New(0.25,0.25,0.25,1)
end
--按钮委托
local callback = function()
----Debugger.LogError(temp[i].Id);
----Debugger.LogError(temp[i].Class);
--创建预览详情Panel
GameManager.CreatePanel("Waiting")
local tableCurrentSkin={}
for k,v in pairs(self.selectedTable) do
table.insert(tableCurrentSkin,UTGData.Instance().SkinsData[tostring(v.CurrentSkin)])
end
self:GoToOtherPanel("HeroInfo",temp[i].Id,self.selectedTable,temp[i].CurrentSkin,tableCurrentSkin)
--调用XXXAPI.Instance:XXX()方法
end
UITools.GetLuaScript(self.Content.itemList[i],"Logic.UICommon.UIClick"):RegisterClickDelegate(self,callback)
end
end
function PreviewHeroAPI:GoToOtherPanel(name,id,selectedTable,skinId,skinList)
coroutine.start( PreviewHeroAPI.GoToOtherPanelCoroutine,self,name,id,selectedTable,skinId,skinList)
end
function PreviewHeroAPI:GoToOtherPanelCoroutine(name,id,selectedTable,skinId,skinList)
local async = GameManager.CreatePanelAsync(name)
while async.Done == false do
coroutine.wait(0.05)
end
HeroInfoAPI.Instance:Init(id,selectedTable)
print("44444444444444")
HeroInfoAPI.Instance:InitCenterBySkinId(skinId,skinList)
end
----------------------------------------------------
function PreviewHeroAPI:OnDestroy()
------------------------------------
PreviewHeroAPI.Instance=nil;
------------------------------------
self.this = nil
self = nil
end
---------------------------------获取当前可用的限免英雄-----------------------------
function PreviewHeroAPI:ValidLimitFreeRoleListRequest() --RequestValidLimitFreeRoleList
local request = NetRequest.New()
request.Content = JObject.New(
JProperty.New("Type","RequestValidLimitFreeRoleList")
)
request.Handler = TGNetService.NetEventHanlderSelf( self.ValidLimitFreeRoleListResponseHandler,self)
TGNetService.GetInstance():SendRequest(request)
end
----------------------------------------------------------------------
function PreviewHeroAPI:ValidLimitFreeRoleListResponseHandler(e)
if e.Type == "RequestValidLimitFreeRoleList" then
local data = json.decode(e.Content:ToString())
if(data.Result==0)then
elseif(data.Result==1)then
self.LimitFreeData=data.List
UTGDataTemporary.Instance().LimitedData = data.List
self:SetParam()
end
return true;
else
return false;
end
end | 1 | 0.927578 | 1 | 0.927578 | game-dev | MEDIA | 0.552209 | game-dev | 0.956185 | 1 | 0.956185 |
pontos2024/PCSX2_ARM64 | 16,013 | app/src/main/cpp/3rdparty/SDL3/src/events/SDL_touch.c | /*
Simple DirectMedia Layer
Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL_internal.h"
// General touch handling code for SDL
#include "SDL_events_c.h"
#include "../video/SDL_sysvideo.h"
static int SDL_num_touch = 0;
static SDL_Touch **SDL_touchDevices = NULL;
// for mapping touch events to mice
static bool finger_touching = false;
static SDL_FingerID track_fingerid;
static SDL_TouchID track_touchid;
// Public functions
bool SDL_InitTouch(void)
{
return true;
}
bool SDL_TouchDevicesAvailable(void)
{
return SDL_num_touch > 0;
}
SDL_TouchID *SDL_GetTouchDevices(int *count)
{
if (count) {
*count = 0;
}
const int total = SDL_num_touch;
SDL_TouchID *result = (SDL_TouchID *) SDL_malloc(sizeof (SDL_TouchID) * (total + 1));
if (result) {
for (int i = 0; i < total; i++) {
result[i] = SDL_touchDevices[i]->id;
}
result[total] = 0;
if (count) {
*count = SDL_num_touch;
}
}
return result;
}
static int SDL_GetTouchIndex(SDL_TouchID id)
{
int index;
SDL_Touch *touch;
for (index = 0; index < SDL_num_touch; ++index) {
touch = SDL_touchDevices[index];
if (touch->id == id) {
return index;
}
}
return -1;
}
SDL_Touch *SDL_GetTouch(SDL_TouchID id)
{
int index = SDL_GetTouchIndex(id);
if (index < 0 || index >= SDL_num_touch) {
if ((id == SDL_MOUSE_TOUCHID) || (id == SDL_PEN_TOUCHID)) {
// this is a virtual touch device, but for some reason they aren't added to the system. Just ignore it.
} else if ( SDL_GetVideoDevice()->ResetTouch) {
SDL_SetError("Unknown touch id %d, resetting", (int)id);
SDL_GetVideoDevice()->ResetTouch(SDL_GetVideoDevice());
} else {
SDL_SetError("Unknown touch device id %d, cannot reset", (int)id);
}
return NULL;
}
return SDL_touchDevices[index];
}
const char *SDL_GetTouchDeviceName(SDL_TouchID id)
{
SDL_Touch *touch = SDL_GetTouch(id);
if (!touch) {
return NULL;
}
return SDL_GetPersistentString(touch->name);
}
SDL_TouchDeviceType SDL_GetTouchDeviceType(SDL_TouchID id)
{
SDL_Touch *touch = SDL_GetTouch(id);
return touch ? touch->type : SDL_TOUCH_DEVICE_INVALID;
}
static int SDL_GetFingerIndex(const SDL_Touch *touch, SDL_FingerID fingerid)
{
int index;
for (index = 0; index < touch->num_fingers; ++index) {
if (touch->fingers[index]->id == fingerid) {
return index;
}
}
return -1;
}
static SDL_Finger *SDL_GetFinger(const SDL_Touch *touch, SDL_FingerID id)
{
int index = SDL_GetFingerIndex(touch, id);
if (index < 0 || index >= touch->num_fingers) {
return NULL;
}
return touch->fingers[index];
}
SDL_Finger **SDL_GetTouchFingers(SDL_TouchID touchID, int *count)
{
SDL_Finger **fingers;
SDL_Finger *finger_data;
if (count) {
*count = 0;
}
SDL_Touch *touch = SDL_GetTouch(touchID);
if (!touch) {
return NULL;
}
// Create a snapshot of the current finger state
fingers = (SDL_Finger **)SDL_malloc((touch->num_fingers + 1) * sizeof(*fingers) + touch->num_fingers * sizeof(**fingers));
if (!fingers) {
return NULL;
}
finger_data = (SDL_Finger *)(fingers + (touch->num_fingers + 1));
for (int i = 0; i < touch->num_fingers; ++i) {
fingers[i] = &finger_data[i];
SDL_copyp(fingers[i], touch->fingers[i]);
}
fingers[touch->num_fingers] = NULL;
if (count) {
*count = touch->num_fingers;
}
return fingers;
}
int SDL_AddTouch(SDL_TouchID touchID, SDL_TouchDeviceType type, const char *name)
{
SDL_Touch **touchDevices;
int index;
SDL_assert(touchID != 0);
index = SDL_GetTouchIndex(touchID);
if (index >= 0) {
return index;
}
// Add the touch to the list of touch
touchDevices = (SDL_Touch **)SDL_realloc(SDL_touchDevices,
(SDL_num_touch + 1) * sizeof(*touchDevices));
if (!touchDevices) {
return -1;
}
SDL_touchDevices = touchDevices;
index = SDL_num_touch;
SDL_touchDevices[index] = (SDL_Touch *)SDL_malloc(sizeof(*SDL_touchDevices[index]));
if (!SDL_touchDevices[index]) {
return -1;
}
// Added touch to list
++SDL_num_touch;
// we're setting the touch properties
SDL_touchDevices[index]->id = touchID;
SDL_touchDevices[index]->type = type;
SDL_touchDevices[index]->num_fingers = 0;
SDL_touchDevices[index]->max_fingers = 0;
SDL_touchDevices[index]->fingers = NULL;
SDL_touchDevices[index]->name = SDL_strdup(name ? name : "");
return index;
}
// Set or update the name of a touch.
void SDL_SetTouchName(SDL_TouchID id, const char *name)
{
SDL_Touch *touch = SDL_GetTouch(id);
if (touch) {
SDL_free(touch->name);
touch->name = SDL_strdup(name ? name : "");
}
}
static bool SDL_AddFinger(SDL_Touch *touch, SDL_FingerID fingerid, float x, float y, float pressure)
{
SDL_Finger *finger;
SDL_assert(fingerid != 0);
if (touch->num_fingers == touch->max_fingers) {
SDL_Finger **new_fingers;
new_fingers = (SDL_Finger **)SDL_realloc(touch->fingers, (touch->max_fingers + 1) * sizeof(*touch->fingers));
if (!new_fingers) {
return false;
}
touch->fingers = new_fingers;
touch->fingers[touch->max_fingers] = (SDL_Finger *)SDL_malloc(sizeof(*finger));
if (!touch->fingers[touch->max_fingers]) {
return false;
}
touch->max_fingers++;
}
finger = touch->fingers[touch->num_fingers++];
finger->id = fingerid;
finger->x = x;
finger->y = y;
finger->pressure = pressure;
return true;
}
static void SDL_DelFinger(SDL_Touch *touch, SDL_FingerID fingerid)
{
int index = SDL_GetFingerIndex(touch, fingerid);
if (index < 0) {
return;
}
--touch->num_fingers;
if (index < (touch->num_fingers)) {
// Move the deleted finger to just past the end of the active fingers array and shift the active fingers by one.
// This ensures that the descriptor for the now-deleted finger is located at `touch->fingers[touch->num_fingers]`
// and is ready for use in SDL_AddFinger.
SDL_Finger *deleted_finger = touch->fingers[index];
SDL_memmove(&touch->fingers[index], &touch->fingers[index + 1], (touch->num_fingers - index) * sizeof(touch->fingers[index]));
touch->fingers[touch->num_fingers] = deleted_finger;
}
}
void SDL_SendTouch(Uint64 timestamp, SDL_TouchID id, SDL_FingerID fingerid, SDL_Window *window, SDL_EventType type, float x, float y, float pressure)
{
SDL_Finger *finger;
bool down = (type == SDL_EVENT_FINGER_DOWN);
SDL_Touch *touch = SDL_GetTouch(id);
if (!touch) {
return;
}
SDL_Mouse *mouse = SDL_GetMouse();
// SDL_HINT_TOUCH_MOUSE_EVENTS: controlling whether touch events should generate synthetic mouse events
// SDL_HINT_VITA_TOUCH_MOUSE_DEVICE: controlling which touchpad should generate synthetic mouse events, PSVita-only
{
// FIXME: maybe we should only restrict to a few SDL_TouchDeviceType
if ((id != SDL_MOUSE_TOUCHID) && (id != SDL_PEN_TOUCHID)) {
#ifdef SDL_PLATFORM_VITA
if (mouse->touch_mouse_events && ((mouse->vita_touch_mouse_device == id) || (mouse->vita_touch_mouse_device == 3))) {
#else
if (mouse->touch_mouse_events) {
#endif
if (window) {
if (down) {
if (finger_touching == false) {
float pos_x = (x * (float)window->w);
float pos_y = (y * (float)window->h);
if (pos_x < 0) {
pos_x = 0;
}
if (pos_x > (float)(window->w - 1)) {
pos_x = (float)(window->w - 1);
}
if (pos_y < 0.0f) {
pos_y = 0.0f;
}
if (pos_y > (float)(window->h - 1)) {
pos_y = (float)(window->h - 1);
}
SDL_SendMouseMotion(timestamp, window, SDL_TOUCH_MOUSEID, false, pos_x, pos_y);
SDL_SendMouseButton(timestamp, window, SDL_TOUCH_MOUSEID, SDL_BUTTON_LEFT, true);
}
} else {
if (finger_touching == true && track_touchid == id && track_fingerid == fingerid) {
SDL_SendMouseButton(timestamp, window, SDL_TOUCH_MOUSEID, SDL_BUTTON_LEFT, false);
}
}
}
if (down) {
if (finger_touching == false) {
finger_touching = true;
track_touchid = id;
track_fingerid = fingerid;
}
} else {
if (finger_touching == true && track_touchid == id && track_fingerid == fingerid) {
finger_touching = false;
}
}
}
}
}
// SDL_HINT_MOUSE_TOUCH_EVENTS: if not set, discard synthetic touch events coming from platform layer
if (!mouse->mouse_touch_events && (id == SDL_MOUSE_TOUCHID)) {
return;
} else if (!mouse->pen_touch_events && (id == SDL_PEN_TOUCHID)) {
return;
}
finger = SDL_GetFinger(touch, fingerid);
if (down) {
if (finger) {
/* This finger is already down.
Assume the finger-up for the previous touch was lost, and send it. */
SDL_SendTouch(timestamp, id, fingerid, window, SDL_EVENT_FINGER_CANCELED, x, y, pressure);
}
if (!SDL_AddFinger(touch, fingerid, x, y, pressure)) {
return;
}
if (SDL_EventEnabled(type)) {
SDL_Event event;
event.type = type;
event.common.timestamp = timestamp;
event.tfinger.touchID = id;
event.tfinger.fingerID = fingerid;
event.tfinger.x = x;
event.tfinger.y = y;
event.tfinger.dx = 0;
event.tfinger.dy = 0;
event.tfinger.pressure = pressure;
event.tfinger.windowID = window ? SDL_GetWindowID(window) : 0;
SDL_PushEvent(&event);
}
} else {
if (!finger) {
// This finger is already up
return;
}
if (SDL_EventEnabled(type)) {
SDL_Event event;
event.type = type;
event.common.timestamp = timestamp;
event.tfinger.touchID = id;
event.tfinger.fingerID = fingerid;
// I don't trust the coordinates passed on fingerUp
event.tfinger.x = finger->x;
event.tfinger.y = finger->y;
event.tfinger.dx = 0;
event.tfinger.dy = 0;
event.tfinger.pressure = pressure;
event.tfinger.windowID = window ? SDL_GetWindowID(window) : 0;
SDL_PushEvent(&event);
}
SDL_DelFinger(touch, fingerid);
}
}
void SDL_SendTouchMotion(Uint64 timestamp, SDL_TouchID id, SDL_FingerID fingerid, SDL_Window *window,
float x, float y, float pressure)
{
SDL_Touch *touch;
SDL_Finger *finger;
float xrel, yrel, prel;
touch = SDL_GetTouch(id);
if (!touch) {
return;
}
SDL_Mouse *mouse = SDL_GetMouse();
// SDL_HINT_TOUCH_MOUSE_EVENTS: controlling whether touch events should generate synthetic mouse events
{
if ((id != SDL_MOUSE_TOUCHID) && (id != SDL_PEN_TOUCHID)) {
if (mouse->touch_mouse_events) {
if (window) {
if (finger_touching == true && track_touchid == id && track_fingerid == fingerid) {
float pos_x = (x * (float)window->w);
float pos_y = (y * (float)window->h);
if (pos_x < 0.0f) {
pos_x = 0.0f;
}
if (pos_x > (float)(window->w - 1)) {
pos_x = (float)(window->w - 1);
}
if (pos_y < 0.0f) {
pos_y = 0.0f;
}
if (pos_y > (float)(window->h - 1)) {
pos_y = (float)(window->h - 1);
}
SDL_SendMouseMotion(timestamp, window, SDL_TOUCH_MOUSEID, false, pos_x, pos_y);
}
}
}
}
}
// SDL_HINT_MOUSE_TOUCH_EVENTS: if not set, discard synthetic touch events coming from platform layer
if (mouse->mouse_touch_events == 0) {
if (id == SDL_MOUSE_TOUCHID) {
return;
}
}
finger = SDL_GetFinger(touch, fingerid);
if (!finger) {
SDL_SendTouch(timestamp, id, fingerid, window, SDL_EVENT_FINGER_DOWN, x, y, pressure);
return;
}
xrel = x - finger->x;
yrel = y - finger->y;
prel = pressure - finger->pressure;
// Drop events that don't change state
if (xrel == 0.0f && yrel == 0.0f && prel == 0.0f) {
#if 0
printf("Touch event didn't change state - dropped!\n");
#endif
return;
}
// Update internal touch coordinates
finger->x = x;
finger->y = y;
finger->pressure = pressure;
// Post the event, if desired
if (SDL_EventEnabled(SDL_EVENT_FINGER_MOTION)) {
SDL_Event event;
event.type = SDL_EVENT_FINGER_MOTION;
event.common.timestamp = timestamp;
event.tfinger.touchID = id;
event.tfinger.fingerID = fingerid;
event.tfinger.x = x;
event.tfinger.y = y;
event.tfinger.dx = xrel;
event.tfinger.dy = yrel;
event.tfinger.pressure = pressure;
event.tfinger.windowID = window ? SDL_GetWindowID(window) : 0;
SDL_PushEvent(&event);
}
}
void SDL_DelTouch(SDL_TouchID id)
{
int i, index;
SDL_Touch *touch;
if (SDL_num_touch == 0) {
// We've already cleaned up, we won't find this device
return;
}
index = SDL_GetTouchIndex(id);
touch = SDL_GetTouch(id);
if (!touch) {
return;
}
for (i = 0; i < touch->max_fingers; ++i) {
SDL_free(touch->fingers[i]);
}
SDL_free(touch->fingers);
SDL_free(touch->name);
SDL_free(touch);
SDL_num_touch--;
SDL_touchDevices[index] = SDL_touchDevices[SDL_num_touch];
}
void SDL_QuitTouch(void)
{
int i;
for (i = SDL_num_touch; i--;) {
SDL_DelTouch(SDL_touchDevices[i]->id);
}
SDL_assert(SDL_num_touch == 0);
SDL_free(SDL_touchDevices);
SDL_touchDevices = NULL;
}
| 1 | 0.704086 | 1 | 0.704086 | game-dev | MEDIA | 0.839007 | game-dev | 0.683037 | 1 | 0.683037 |
NBlood/NBlood | 110,708 | source/duke3d/src/m32exec.cpp | //-------------------------------------------------------------------------
/*
Copyright (C) 2010 EDuke32 developers and contributors
This file is part of EDuke32.
EDuke32 is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
//-------------------------------------------------------------------------
// This object is shared by the editors of *all* Build games!
#include "compat.h"
#include "m32script.h"
#include "m32def.h"
#include "sounds_mapster32.h"
#include "osd.h"
#include "keys.h"
#include "common.h"
#include "colmatch.h"
// from macros.h
#define rnd(X) ((krand()>>8)>=(255-(X)))
vmstate_t vm;
vmstate_t vm_default =
{
-1, // g_i
0, // g_st
NULL, // g_sp
0, // flags
0, // miscflags
};
int32_t g_errorLineNum, g_tw;
uint8_t aEventEnabled[MAXEVENTS];
uint32_t m32_drawlinepat=0xffffffff;
int32_t m32_script_expertmode = 0;
instype *insptr;
static instype *x_sortingstateptr;
//#include "m32structures.cpp"
#ifdef DEBUGGINGAIDS
void X_Disasm(ofstype beg, int32_t size)
{
instype *p;
if (!apScript) return;
if (beg<0 || beg+size>g_scriptSize) return;
initprintf("beg=%d, size=%d: ", beg, size);
for (p=apScript+beg; p<apScript+beg+size; p++)
{
if (*p>>12 && (*p&0xFFF)<CON_END)
initprintf("%s ", keyw[*p&0xFFF]);
else
initprintf("%d ", *p);
}
initprintf("\n");
}
#endif
void VM_ScriptInfo(void)
{
if (apScript)
{
instype *p;
if (insptr)
for (p=max(insptr-20,apScript); p<min(insptr+20, apScript+g_scriptSize); p++)
{
if (p==insptr) initprintf("<<");
if (*p>>12 && (*p&0xFFF)<CON_END)
initprintf("\n%5d: L%5d: %s ",(int32_t)(p-apScript),(int32_t)(*p>>12),keyw[*p&0xFFF]);
else initprintf(" %d",*p);
if (p==insptr) initprintf(">>");
}
initprintf(" \n");
if (vm.spriteNum >= 0)
initprintf("current sprite: %d\n",vm.spriteNum);
if (g_tw>=0 && g_tw<CON_END)
initprintf("g_errorLineNum: %d, g_tw: %s\n",g_errorLineNum,keyw[g_tw]);
else
initprintf("g_errorLineNum: %d, g_tw: %d\n",g_errorLineNum,g_tw);
}
}
void M32_PostScriptExec(void)
{
if (vm.miscflags&VMFLAG_MISC_UPDATEHL)
{
update_highlight();
vm.miscflags &= ~VMFLAG_MISC_UPDATEHL;
}
if (vm.miscflags&VMFLAG_MISC_UPDATEHLSECT)
{
update_highlightsector();
if (!in3dmode())
ovh_whiteoutgrab(1);
vm.miscflags &= ~VMFLAG_MISC_UPDATEHLSECT;
}
}
void VM_OnEvent(int32_t iEventID, int32_t spriteNum)
{
if (iEventID < 0 || iEventID >= MAXEVENTS)
{
M32_PRINTERROR("Invalid event ID");
return;
}
if (aEventOffsets[iEventID] < 0 || !aEventEnabled[iEventID])
{
//Bsprintf(g_szBuf,"No event found for %d",iEventID);
//AddLog(g_szBuf);
return;
}
{
instype *const oinsptr=insptr;
vmstate_t vm_backup;
void *const olocalvars = aGameArrays[M32_LOCAL_ARRAY_ID].vals;
#ifdef M32_LOCALS_VARARRAY
int32_t localvars[aEventNumLocals[iEventID]];
#else
int32_t localvars[M32_LOCALS_FIXEDNUM];
#endif
// Initialize 'state'-local variables to 0.
if (aEventNumLocals[iEventID] > 0)
Bmemset(localvars, 0, aEventNumLocals[iEventID]*sizeof(int32_t));
Bmemcpy(&vm_backup, &vm, sizeof(vmstate_t));
vm.spriteNum = spriteNum; // current sprite ID
if (vm.spriteNum >= 0)
vm.pSprite = &sprite[vm.spriteNum];
vm.g_st = 1+iEventID;
vm.flags = 0;
insptr = apScript + aEventOffsets[iEventID];
aGameArrays[M32_LOCAL_ARRAY_ID].vals = localvars;
VM_Execute(0);
aGameArrays[M32_LOCAL_ARRAY_ID].vals = olocalvars;
if (vm.flags&VMFLAG_ERROR)
{
aEventEnabled[iEventID] = 0;
message("ERROR executing %s. Event disabled.", label+(iEventID*MAXLABELLEN));
}
M32_PostScriptExec();
// restore old values...
Bmemcpy(&vm, &vm_backup, sizeof(vmstate_t));
insptr = oinsptr;
//AddLog("End of Execution");
}
}
static int32_t G_GetAngleDelta(int32_t a,int32_t na)
{
a &= 2047;
na &= 2047;
if (klabs(a-na) < 1024)
{
// OSD_Printf("G_GetAngleDelta() returning %d\n",na-a);
return na-a;
}
if (na > 1024) na -= 2048;
if (a > 1024) a -= 2048;
// OSD_Printf("G_GetAngleDelta() returning %d\n",na-a);
return na-a;
}
static inline void __fastcall VM_DoConditional(int32_t condition)
{
if (condition)
{
// skip 'else' pointer.. and...
insptr+=2;
VM_Execute(1);
return;
}
insptr++;
insptr += *insptr;
if (((*insptr)&0xFFF) == CON_ELSE)
{
// else...
// skip 'else' and...
insptr+=2;
VM_Execute(1);
}
}
static int X_DoSortDefault(const void *lv, const void *rv)
{
return *(int32_t const *)rv - *(int32_t const *)lv;
}
static int X_DoSort(const void *lv, const void *rv)
{
m32_sortvar1 = *(int32_t const *)lv;
m32_sortvar2 = *(int32_t const *)rv;
insptr = x_sortingstateptr;
VM_Execute(0);
return g_iReturnVar;
}
// in interactive execution, allow the current sprite index to be the aimed-at sprite (in 3d mode)
#define X_ERROR_INVALIDCI() \
if ((vm.spriteNum < 0 || vm.spriteNum >= MAXSPRITES) && \
(vm.g_st != 0 || searchstat != 3 || (vm.spriteNum = searchwall, vm.pSprite = &sprite[vm.spriteNum], 0))) \
{ \
M32_ERROR("Current sprite index invalid!"); \
continue; \
}
#define X_ERROR_INVALIDSPRI(dasprite) \
if (dasprite < 0 || dasprite >= MAXSPRITES) \
{ \
M32_ERROR("Invalid sprite index %d!", dasprite); \
continue; \
}
#define X_ERROR_INVALIDSECT(dasect) \
if (dasect < 0 || dasect >= numsectors) \
{ \
M32_ERROR("Invalid sector index %d!", dasect); \
continue; \
}
#define X_ERROR_INVALIDSP() \
if (!vm.pSprite && (vm.g_st != 0 || searchstat != 3 || (vm.pSprite = &sprite[searchwall], 0))) \
{ \
M32_ERROR("Current sprite invalid!"); \
continue; \
}
#define X_ERROR_INVALIDQUOTE(q, array) \
if (q < 0 || q >= MAXQUOTES) \
{ \
M32_ERROR("Invalid quote number %d!", q); \
continue; \
} \
else if (array[q] == NULL) \
{ \
M32_ERROR("Null quote %d!", q); \
continue; \
}
static char *GetMaybeInlineQuote(int32_t quotei)
{
char *quotetext;
if (quotei==-1)
{
quotetext = (char *)insptr;
while (*insptr++) /* skip the string */;
}
else
{
quotei = Gv_GetVar(quotei);
do { X_ERROR_INVALIDQUOTE(quotei, apStrings) } while (0);
if (vm.flags&VMFLAG_ERROR)
return NULL;
quotetext = apStrings[quotei];
}
return quotetext;
}
static int CheckArray(int aidx)
{
if (!(aidx >= 0 && aidx < g_gameArrayCount))
M32_ERROR("Invalid array %d!", aidx);
return (vm.flags&VMFLAG_ERROR);
}
int32_t VM_Execute(int32_t once)
{
int32_t tw = *insptr;
// jump directly into the loop, saving us from the checks during the first iteration
goto skip_check;
while (!once)
{
if (vm.flags)
return 1;
tw = *insptr;
skip_check:
// Bsprintf(g_szBuf,"Parsing: %d",*insptr);
// AddLog(g_szBuf);
g_errorLineNum = tw>>12;
g_tw = (tw &= 0xFFF);
switch (tw)
{
// *** basic commands
case CON_NULLOP:
insptr++;
continue;
case CON_STATE:
{
instype *const tempscrptr = insptr+2;
const int32_t stateidx = *(insptr+1), o_g_st = vm.g_st, oret=vm.flags&VMFLAG_RETURN;
void *const olocalvars = aGameArrays[M32_LOCAL_ARRAY_ID].vals;
#ifdef M32_LOCALS_VARARRAY
int32_t localvars[statesinfo[stateidx].numlocals];
#else
int32_t localvars[M32_LOCALS_FIXEDNUM];
#endif
// needed since any read access before initialization would cause undefined behaviour
if (statesinfo[stateidx].numlocals > 0)
Bmemset(localvars, 0, statesinfo[stateidx].numlocals*sizeof(int32_t));
insptr = apScript + statesinfo[stateidx].ofs;
vm.g_st = 1+MAXEVENTS+stateidx;
aGameArrays[M32_LOCAL_ARRAY_ID].vals = localvars;
VM_Execute(0);
aGameArrays[M32_LOCAL_ARRAY_ID].vals = olocalvars;
vm.g_st = o_g_st;
vm.flags &= ~VMFLAG_RETURN;
vm.flags |= oret;
insptr = tempscrptr;
}
continue;
case CON_RETURN:
vm.flags |= VMFLAG_RETURN;
return 1;
case CON_BREAK:
vm.flags |= VMFLAG_BREAK;
// XXX: may not be cleared subsequently?
fallthrough__;
case CON_ENDS:
return 1;
case CON_ELSE:
insptr++;
insptr += *insptr;
continue;
case CON_ENDSWITCH:
vm.flags &= ~VMFLAG_BREAK;
fallthrough__;
case CON_ENDEVENT:
insptr++;
return 1;
case CON_SWITCH:
insptr++; // p-code
{
// command format:
// variable ID to check
// script offset to 'end'
// count of case statements
// script offset to default case (null if none)
// For each case: value, ptr to code
//AddLog("Processing Switch...");
int32_t lValue=Gv_GetVar(*insptr++), lEnd=*insptr++, lCases=*insptr++;
instype *lpDefault=insptr++, *lpCases=insptr, *lCodeInsPtr;
int32_t bMatched=0, lCheckCase;
int32_t left,right;
insptr += lCases*2;
lCodeInsPtr = insptr;
//Bsprintf(g_szBuf,"lEnd= %d *lpDefault=%d",lEnd,*lpDefault); AddLog(g_szBuf);
//Bsprintf(g_szBuf,"Checking %d cases for %d",lCases, lValue); AddLog(g_szBuf);
left = 0;
right = lCases-1;
while (!bMatched)
{
//Bsprintf(g_szBuf,"Checking #%d Value= %d",lCheckCase, lpCases[lCheckCase*2]); AddLog(g_szBuf);
lCheckCase=(left+right)/2;
// initprintf("(%2d..%2d..%2d) [%2d..%2d..%2d]==%2d\n",left,lCheckCase,right,lpCases[left*2],lpCases[lCheckCase*2],lpCases[right*2],lValue);
if (lpCases[lCheckCase*2] > lValue)
right = lCheckCase-1;
else if (lpCases[lCheckCase*2] < lValue)
left = lCheckCase+1;
else if (lpCases[lCheckCase*2] == lValue)
{
//AddLog("Found Case Match");
//Bsprintf(g_szBuf,"insptr=%d. lCheckCase=%d, offset=%d, &script[0]=%d", (int32_t)insptr,(int32_t)lCheckCase,lpCases[lCheckCase*2+1],(int32_t)&script[0]); AddLog(g_szBuf);
// fake a 2-d Array
insptr = lCodeInsPtr + lpCases[lCheckCase*2+1];
//Bsprintf(g_szBuf,"insptr=%d. ", (int32_t)insptr); AddLog(g_szBuf);
VM_Execute(0);
//AddLog("Done Executing Case");
bMatched=1;
}
if (right-left < 0)
break;
}
if (!bMatched)
{
if (*lpDefault >= 0)
{
//AddLog("No Matching Case: Using Default");
insptr = lCodeInsPtr + *lpDefault;
VM_Execute(0);
}
// else
// {
// //AddLog("No Matching Case: No Default to use");
// }
}
insptr = (instype *)(lCodeInsPtr + lEnd);
vm.flags &= ~VMFLAG_BREAK;
//Bsprintf(g_szBuf,"insptr=%d. ", (int32_t)insptr); AddLog(g_szBuf);
//AddLog("Done Processing Switch");
continue;
}
case CON_GETCURRADDRESS:
insptr++;
{
int32_t j=*insptr++;
Gv_SetVar(j, insptr-apScript);
}
continue;
case CON_JUMP:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
if (j<0 || j>=(g_scriptPtr-apScript))
{
M32_ERROR("script index out of bounds (%d)", j);
continue;
}
insptr = (instype *)(j+apScript);
}
continue;
case CON_RIGHTBRACE:
insptr++;
return 1;
case CON_LEFTBRACE:
insptr++;
VM_Execute(0);
continue;
// *** arrays
case CON_SETARRAY:
insptr++;
{
const int32_t j=*insptr++;
const int32_t index = Gv_GetVar(*insptr++);
const int32_t value = Gv_GetVar(*insptr++);
CheckArray(j);
if (aGameArrays[j].dwFlags & GAMEARRAY_READONLY)
M32_ERROR("Tried to set on read-only array `%s'", aGameArrays[j].szLabel);
if (!(index >= 0 && index < aGameArrays[j].size))
M32_ERROR("Array index %d out of bounds", index);
if (vm.flags&VMFLAG_ERROR)
continue;
// NOTE: Other array types not implemented, since they're read-only.
((int32_t *)aGameArrays[j].vals)[index] = value;
continue;
}
case CON_GETARRAYSIZE:
insptr++;
{
const int32_t j=*insptr++;
if (CheckArray(j))
continue;
Gv_SetVar(*insptr++, Gv_GetArraySize(j));
}
continue;
case CON_RESIZEARRAY:
insptr++;
{
const int32_t j=*insptr++;
const int32_t asize = Gv_GetVar(*insptr++);
CheckArray(j);
if (aGameArrays[j].dwFlags & GAMEARRAY_READONLY)
M32_ERROR("Tried to resize read-only array `%s'", aGameArrays[j].szLabel);
if (!(asize >= 1 && asize <= 65536))
M32_ERROR("Invalid array size %d (must be between 1 and 65536)", asize);
if (vm.flags&VMFLAG_ERROR)
continue;
// OSD_Printf(OSDTEXT_GREEN "CON_RESIZEARRAY: resizing array %s from %d to %d\n", aGameArrays[j].szLabel, aGameArrays[j].size, asize);
aGameArrays[j].vals = Xrealloc(aGameArrays[j].vals, sizeof(int32_t) * asize);
aGameArrays[j].size = asize;
continue;
}
case CON_COPY:
insptr++;
{
const int32_t si=*insptr++;
int32_t sidx = Gv_GetVar(*insptr++);
const int32_t di=*insptr++;
int32_t didx = Gv_GetVar(*insptr++);
int32_t numelts = Gv_GetVar(*insptr++);
CheckArray(si);
CheckArray(di);
if (aGameArrays[di].dwFlags & GAMEARRAY_READONLY)
M32_ERROR("Array %d is read-only!", di);
if (vm.flags&VMFLAG_ERROR)
continue;
const int32_t ssiz = Gv_GetArraySize(si);
const int32_t dsiz = Gv_GetArraySize(di);
if ((uint32_t)sidx >= (uint32_t)ssiz)
M32_ERROR("Invalid source index %d", sidx);
if ((uint32_t)didx >= (uint32_t)dsiz)
M32_ERROR("Invalid destination index %d", didx);
if (vm.flags&VMFLAG_ERROR)
continue;
if (numelts > ssiz-sidx)
numelts = ssiz-sidx;
if (numelts > dsiz-didx)
numelts = dsiz-didx;
const gamearray_t *const sar = &aGameArrays[si];
gamearray_t *const dar = &aGameArrays[di];
switch (sar->dwFlags & GAMEARRAY_TYPE_MASK)
{
case 0:
case GAMEARRAY_INT32:
if (sar->dwFlags & GAMEARRAY_STRIDE2)
{
for (; numelts>0; numelts--, sidx += 2)
((int32_t *)dar->vals)[didx++] = ((int32_t *)sar->vals)[sidx];
}
else
{
Bmemcpy((int32_t *)dar->vals + didx, (int32_t *)sar->vals + sidx,
numelts * sizeof(int32_t));
}
break;
case GAMEARRAY_INT16:
for (; numelts>0; numelts--)
((int32_t *)dar->vals)[didx++] = ((int16_t *)sar->vals)[sidx++];
break;
case GAMEARRAY_UINT8:
for (; numelts>0; numelts--)
((int32_t *)dar->vals)[didx++] = ((uint8_t *)sar->vals)[sidx++];
break;
}
continue;
}
// *** var & varvar ops
case CON_RANDVAR:
insptr++;
Gv_SetVar(*insptr, mulscale16(krand(), *(insptr+1)+1));
insptr += 2;
continue;
case CON_DISPLAYRANDVAR:
insptr++;
Gv_SetVar(*insptr, mulscale15(system_15bit_rand(), *(insptr+1)+1));
insptr += 2;
continue;
case CON_SETVAR:
insptr++;
Gv_SetVar(*insptr, *(insptr+1));
insptr += 2;
continue;
case CON_SETVARVAR:
insptr++;
{
int32_t j=*insptr++;
Gv_SetVar(j, Gv_GetVar(*insptr++));
}
continue;
case CON_MULVAR:
insptr++;
Gv_SetVar(*insptr, Gv_GetVar(*insptr) * *(insptr+1));
insptr += 2;
continue;
case CON_DIVVAR:
insptr++;
if (*(insptr+1) == 0)
{
M32_ERROR("Divide by zero.");
insptr += 2;
continue;
}
Gv_SetVar(*insptr, Gv_GetVar(*insptr) / *(insptr+1));
insptr += 2;
continue;
case CON_MODVAR:
insptr++;
if (*(insptr+1) == 0)
{
M32_ERROR("Mod by zero.");
insptr += 2;
continue;
}
Gv_SetVar(*insptr,Gv_GetVar(*insptr)%*(insptr+1));
insptr += 2;
continue;
case CON_ANDVAR:
insptr++;
Gv_SetVar(*insptr,Gv_GetVar(*insptr) & *(insptr+1));
insptr += 2;
continue;
case CON_ORVAR:
insptr++;
Gv_SetVar(*insptr,Gv_GetVar(*insptr) | *(insptr+1));
insptr += 2;
continue;
case CON_XORVAR:
insptr++;
Gv_SetVar(*insptr,Gv_GetVar(*insptr) ^ *(insptr+1));
insptr += 2;
continue;
case CON_RANDVARVAR:
insptr++;
{
int32_t j=*insptr++;
Gv_SetVar(j,mulscale16(krand(), Gv_GetVar(*insptr++)+1));
}
continue;
case CON_DISPLAYRANDVARVAR:
insptr++;
{
int32_t j=*insptr++;
Gv_SetVar(j,mulscale15(system_15bit_rand(), Gv_GetVar(*insptr++)+1));
}
continue;
case CON_MULVARVAR:
insptr++;
{
int32_t j=*insptr++;
Gv_SetVar(j, Gv_GetVar(j)*Gv_GetVar(*insptr++));
}
continue;
case CON_DIVVARVAR:
insptr++;
{
int32_t j=*insptr++;
int32_t l2=Gv_GetVar(*insptr++);
if (l2==0)
{
M32_ERROR("Divide by zero.");
continue;
}
Gv_SetVar(j, Gv_GetVar(j)/l2);
continue;
}
case CON_MODVARVAR:
insptr++;
{
int32_t j=*insptr++;
int32_t l2=Gv_GetVar(*insptr++);
if (l2==0)
{
M32_ERROR("Mod by zero.");
continue;
}
Gv_SetVar(j, Gv_GetVar(j) % l2);
continue;
}
case CON_ANDVARVAR:
insptr++;
{
int32_t j=*insptr++;
Gv_SetVar(j, Gv_GetVar(j) & Gv_GetVar(*insptr++));
}
continue;
case CON_XORVARVAR:
insptr++;
{
int32_t j=*insptr++;
Gv_SetVar(j, Gv_GetVar(j) ^ Gv_GetVar(*insptr++));
}
continue;
case CON_ORVARVAR:
insptr++;
{
int32_t j=*insptr++;
Gv_SetVar(j, Gv_GetVar(j) | Gv_GetVar(*insptr++));
}
continue;
case CON_SUBVAR:
insptr++;
Gv_SetVar(*insptr, Gv_GetVar(*insptr) - *(insptr+1));
insptr += 2;
continue;
case CON_SUBVARVAR:
insptr++;
{
int32_t j=*insptr++;
Gv_SetVar(j, Gv_GetVar(j) - Gv_GetVar(*insptr++));
}
continue;
case CON_ADDVAR:
insptr++;
Gv_SetVar(*insptr, Gv_GetVar(*insptr) + *(insptr+1));
insptr += 2;
continue;
case CON_ADDVARVAR:
insptr++;
{
int32_t j=*insptr++;
Gv_SetVar(j, Gv_GetVar(j) + Gv_GetVar(*insptr++));
}
continue;
case CON_SHIFTVARL:
insptr++;
Gv_SetVar(*insptr, Gv_GetVar(*insptr) << *(insptr+1));
insptr += 2;
continue;
case CON_SHIFTVARVARL:
insptr++;
{
int32_t j=*insptr++;
Gv_SetVar(j, Gv_GetVar(j) << Gv_GetVar(*insptr++));
}
continue;
case CON_SHIFTVARR:
insptr++;
Gv_SetVar(*insptr, Gv_GetVar(*insptr) >> *(insptr+1));
insptr += 2;
continue;
case CON_SHIFTVARVARR:
insptr++;
{
int32_t j=*insptr++;
Gv_SetVar(j, Gv_GetVar(j) >> Gv_GetVar(*insptr++));
}
continue;
case CON_SIN:
insptr++;
Gv_SetVar(*insptr, sintable[Gv_GetVar(*(insptr+1))&2047]);
insptr += 2;
continue;
case CON_COS:
insptr++;
Gv_SetVar(*insptr, sintable[(Gv_GetVar(*(insptr+1))+512)&2047]);
insptr += 2;
continue;
case CON_DISPLAYRAND:
insptr++;
Gv_SetVar(*insptr++, system_15bit_rand());
continue;
// *** other math
case CON_FTOI:
insptr++;
{
union { int32_t ival; float fval; };
ival=Gv_GetVar(*insptr);
int32_t const scale=*(insptr+1);
// rounding must absolutely be!
//OSD_Printf("ftoi: bits:%8x, scale=%d, fval=%f, (int32_t)(fval*scale)=%d\n", bits, scale, fval, (int32_t)(fval*scale));
Gv_SetVar(*insptr, (int32_t)Blrintf(fval * scale));
}
insptr += 2;
continue;
case CON_ITOF:
insptr++;
{
union { int32_t ival; float fval; };
ival=Gv_GetVar(*insptr);
int32_t const scale=*(insptr+1);
fval = (float)ival/(float)scale;
Gv_SetVar(*insptr, ival);
}
insptr += 2;
continue;
case CON_CLAMP:
insptr++;
{
int32_t var=*insptr++, min=Gv_GetVar(*insptr++), max=Gv_GetVar(*insptr++);
int32_t val=Gv_GetVar(var);
if (val<min) Gv_SetVar(var, min);
else if (val>max) Gv_SetVar(var, max);
}
continue;
case CON_INV:
Gv_SetVar(*(insptr+1), -Gv_GetVar(*(insptr+1)));
insptr += 2;
continue;
case CON_SQRT:
insptr++;
{
// syntax sqrt <invar> <outvar>
int32_t lInVarID=*insptr++, lOutVarID=*insptr++;
Gv_SetVar(lOutVarID, ksqrt((uint32_t)Gv_GetVar(lInVarID)));
continue;
}
case CON_LDIST:
case CON_DIST:
insptr++;
{
int32_t distvar = *insptr++, xvar = Gv_GetVar(*insptr++), yvar = Gv_GetVar(*insptr++);
if (xvar < 0 || xvar >= MAXSPRITES || sprite[xvar].statnum==MAXSTATUS)
{
M32_ERROR("invalid sprite %d", xvar);
}
if (yvar < 0 || yvar >= MAXSPRITES || sprite[yvar].statnum==MAXSTATUS)
{
M32_ERROR("invalid sprite %d", yvar);
}
if (vm.flags&VMFLAG_ERROR) continue;
if (tw==CON_DIST)
Gv_SetVar(distvar, dist(&sprite[xvar],&sprite[yvar]));
else
Gv_SetVar(distvar, ldist(&sprite[xvar],&sprite[yvar]));
continue;
}
case CON_GETANGLE:
insptr++;
{
int32_t angvar = *insptr++;
int32_t xvar = Gv_GetVar(*insptr++);
int32_t yvar = Gv_GetVar(*insptr++);
Gv_SetVar(angvar, getangle(xvar,yvar));
continue;
}
case CON_GETINCANGLE:
insptr++;
{
int32_t angvar = *insptr++;
int32_t xvar = Gv_GetVar(*insptr++);
int32_t yvar = Gv_GetVar(*insptr++);
Gv_SetVar(angvar, G_GetAngleDelta(xvar,yvar));
continue;
}
case CON_A2XY:
case CON_AH2XYZ:
insptr++;
{
int32_t ang=Gv_GetVar(*insptr++), horiz=(tw==CON_A2XY)?100:Gv_GetVar(*insptr++);
int32_t xvar=*insptr++, yvar=*insptr++;
int32_t x = sintable[(ang+512)&2047];
int32_t y = sintable[ang&2047];
if (tw==CON_AH2XYZ)
{
int32_t zvar=*insptr++, z=0;
horiz -= 100;
if (horiz)
{
int32_t veclen = ksqrt(200*200 + horiz*horiz);
int32_t dacos = divscale14(200, veclen);
x = mulscale14(x, dacos);
y = mulscale14(y, dacos);
z = divscale14(-horiz, veclen);
}
Gv_SetVar(zvar, z);
}
Gv_SetVar(xvar, x);
Gv_SetVar(yvar, y);
continue;
}
case CON_MULSCALE:
insptr++;
{
int32_t var1 = *insptr++, var2 = Gv_GetVar(*insptr++);
int32_t var3 = Gv_GetVar(*insptr++), var4 = Gv_GetVar(*insptr++);
Gv_SetVar(var1, mulscale(var2, var3, var4));
continue;
}
case CON_DIVSCALE:
insptr++;
{
int32_t var1 = *insptr++, var2 = Gv_GetVar(*insptr++);
int32_t var3 = Gv_GetVar(*insptr++), var4 = Gv_GetVar(*insptr++);
Gv_SetVar(var1, divscale(var2, var3, var4));
continue;
}
case CON_SCALEVAR:
insptr++;
{
int32_t var1 = *insptr++, var2 = Gv_GetVar(*insptr++);
int32_t var3 = Gv_GetVar(*insptr++), var4 = Gv_GetVar(*insptr++);
Gv_SetVar(var1, scale(var2, var3, var4));
continue;
}
// *** if & while
case CON_IFVARVARAND:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
j &= Gv_GetVar(*insptr++);
insptr--;
VM_DoConditional(j);
}
continue;
case CON_IFVARVAROR:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
j |= Gv_GetVar(*insptr++);
insptr--;
VM_DoConditional(j);
}
continue;
case CON_IFVARVARXOR:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
j ^= Gv_GetVar(*insptr++);
insptr--;
VM_DoConditional(j);
}
continue;
case CON_IFVARVAREITHER:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
int32_t l = Gv_GetVar(*insptr++);
insptr--;
VM_DoConditional(j || l);
}
continue;
case CON_IFVARVARBOTH:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
int32_t l = Gv_GetVar(*insptr++);
insptr--;
VM_DoConditional(j && l);
}
continue;
case CON_IFVARVARN:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
j = (j != Gv_GetVar(*insptr++));
insptr--;
VM_DoConditional(j);
}
continue;
case CON_IFVARVARE:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
j = (j == Gv_GetVar(*insptr++));
insptr--;
VM_DoConditional(j);
}
continue;
case CON_IFVARVARG:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
j = (j > Gv_GetVar(*insptr++));
insptr--;
VM_DoConditional(j);
}
continue;
case CON_IFVARVARGE:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
j = (j >= Gv_GetVar(*insptr++));
insptr--;
VM_DoConditional(j);
}
continue;
case CON_IFVARVARL:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
j = (j < Gv_GetVar(*insptr++));
insptr--;
VM_DoConditional(j);
}
continue;
case CON_IFVARVARLE:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
j = (j <= Gv_GetVar(*insptr++));
insptr--;
VM_DoConditional(j);
}
continue;
case CON_IFVARVARA:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
j = ((uint32_t)j > (uint32_t)Gv_GetVar(*insptr++));
insptr--;
VM_DoConditional(j);
}
continue;
case CON_IFVARVARAE:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
j = ((uint32_t)j >= (uint32_t)Gv_GetVar(*insptr++));
insptr--;
VM_DoConditional(j);
}
continue;
case CON_IFVARVARB:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
j = ((uint32_t)j < (uint32_t)Gv_GetVar(*insptr++));
insptr--;
VM_DoConditional(j);
}
continue;
case CON_IFVARVARBE:
insptr++;
{
int32_t j = Gv_GetVar(*insptr++);
j = ((uint32_t)j <= (uint32_t)Gv_GetVar(*insptr++));
insptr--;
VM_DoConditional(j);
}
continue;
case CON_IFVARE:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
VM_DoConditional(j == *insptr);
}
continue;
case CON_IFVARN:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
VM_DoConditional(j != *insptr);
}
continue;
case CON_WHILEVARE:
{
instype *savedinsptr=insptr+2;
int32_t j;
do
{
insptr=savedinsptr;
j = (Gv_GetVar(*(insptr-1)) == *insptr);
VM_DoConditional(j);
}
while (j && !vm.flags);
vm.flags &= ~VMFLAG_BREAK;
continue;
}
case CON_WHILEVARN:
{
instype *savedinsptr=insptr+2;
int32_t j;
do
{
insptr=savedinsptr;
j = (Gv_GetVar(*(insptr-1)) != *insptr);
VM_DoConditional(j);
}
while (j && !vm.flags);
vm.flags &= ~VMFLAG_BREAK;
continue;
}
case CON_WHILEVARL:
{
instype *savedinsptr=insptr+2;
int32_t j;
do
{
insptr=savedinsptr;
j = (Gv_GetVar(*(insptr-1)) < *insptr);
VM_DoConditional(j);
}
while (j && !vm.flags);
vm.flags &= ~VMFLAG_BREAK;
continue;
}
case CON_WHILEVARVARE:
{
int32_t j;
instype *savedinsptr=insptr+2;
do
{
insptr=savedinsptr;
j = Gv_GetVar(*(insptr-1));
j = (j == Gv_GetVar(*insptr++));
insptr--;
VM_DoConditional(j);
}
while (j && !vm.flags);
vm.flags &= ~VMFLAG_BREAK;
continue;
}
case CON_WHILEVARVARN:
{
int32_t j;
instype *savedinsptr=insptr+2;
do
{
insptr=savedinsptr;
j = Gv_GetVar(*(insptr-1));
j = (j != Gv_GetVar(*insptr++));
insptr--;
VM_DoConditional(j);
}
while (j && !vm.flags);
vm.flags &= ~VMFLAG_BREAK;
continue;
}
case CON_WHILEVARVARL:
{
int32_t j;
instype *savedinsptr=insptr+2;
do
{
insptr=savedinsptr;
j = Gv_GetVar(*(insptr-1));
j = (j < Gv_GetVar(*insptr++));
insptr--;
VM_DoConditional(j);
}
while (j && !vm.flags);
vm.flags &= ~VMFLAG_BREAK;
continue;
}
case CON_COLLECTSECTORS:
insptr++;
{
const int32_t aridx=*insptr++, startsectnum=Gv_GetVar(*insptr++);
const int32_t numsectsVar=*insptr++, state=*insptr++;
if (CheckArray(aridx))
continue;
gamearray_t *const gar = &aGameArrays[aridx];
Bassert((gar->dwFlags & (GAMEARRAY_READONLY|GAMEARRAY_VARSIZE)) == 0);
const int32_t o_g_st=vm.g_st, arsize = gar->size;
instype *const end=insptr;
int16_t sectcnt, numsects=0;
// XXX: relies on -fno-strict-aliasing
int16_t *const sectlist = (int16_t *)gar->vals; // actually an int32_t array
int32_t *const sectlist32 = (int32_t *)sectlist;
int32_t j, startwall, endwall, ns;
static uint8_t sectbitmap[bitmap_size(MAXSECTORS)];
X_ERROR_INVALIDSECT(startsectnum);
if (arsize < numsectors)
{
M32_ERROR("Array size must be at least numsectors (=%d) for collecting!",
numsectors);
continue;
}
// collect!
bfirst_search_init(sectlist, sectbitmap, &numsects, MAXSECTORS, startsectnum);
for (sectcnt=0; sectcnt<numsects; sectcnt++)
for (WALLS_OF_SECTOR(sectlist[sectcnt], j))
if ((ns=wall[j].nextsector) >= 0 && wall[j].nextsector<numsectors)
{
if (bitmap_test(sectbitmap, ns))
continue;
vm.g_st = 1+MAXEVENTS+state;
insptr = apScript + statesinfo[state].ofs;
g_iReturnVar = ns;
VM_Execute(0);
if (g_iReturnVar)
bfirst_search_try(sectlist, sectbitmap, &numsects, wall[j].nextsector);
}
// short->int sector list
for (j=numsects-1; j>=0; j--)
sectlist32[j] = sectlist[j];
Gv_SetVar(numsectsVar, numsects);
g_iReturnVar = 0;
// restore some VM state
vm.g_st = o_g_st;
insptr = end;
}
continue;
case CON_SORT:
insptr++;
{
const int32_t aridx=*insptr++, count=Gv_GetVar(*insptr++), state=*insptr++;
const int32_t o_g_st = vm.g_st;
instype *const end = insptr;
if (CheckArray(aridx))
continue;
if (count <= 0)
continue;
gamearray_t *const gar = &aGameArrays[aridx];
Bassert((gar->dwFlags & (GAMEARRAY_READONLY|GAMEARRAY_VARSIZE)) == 0);
if (count > gar->size)
{
M32_ERROR("Count of elements to sort (%d) exceeds array size (%d)!",
count, gar->size);
continue;
}
if (state < 0)
{
qsort(gar->vals, count, sizeof(int32_t), X_DoSortDefault);
}
else
{
x_sortingstateptr = apScript + statesinfo[state].ofs;
vm.g_st = 1+MAXEVENTS+state;
qsort(gar->vals, count, sizeof(int32_t), X_DoSort);
vm.g_st = o_g_st;
insptr = end;
}
}
continue;
case CON_FOR: // special-purpose iteration
insptr++;
{
const int32_t var = *insptr++, how = *insptr++;
const int32_t parm2 = how<=ITER_DRAWNSPRITES ? 0 : Gv_GetVar(*insptr++);
instype *const end = insptr + *insptr, *const beg = ++insptr;
const int32_t vm_i_bak = vm.spriteNum;
auto const vm_sp_bak = vm.pUSprite;
if (vm.flags&VMFLAG_ERROR)
continue;
switch (how)
{
case ITER_ALLSPRITES:
for (bssize_t jj=0; jj<MAXSPRITES && !vm.flags; jj++)
{
if (sprite[jj].statnum == MAXSTATUS)
continue;
Gv_SetVar(var, jj);
vm.spriteNum = jj;
vm.pSprite = &sprite[jj];
insptr = beg;
VM_Execute(1);
}
break;
case ITER_ALLSECTORS:
for (bssize_t jj=0; jj<numsectors && !vm.flags; jj++)
{
Gv_SetVar(var, jj);
insptr = beg;
VM_Execute(1);
}
break;
case ITER_ALLWALLS:
for (bssize_t jj=0; jj<numwalls && !vm.flags; jj++)
{
Gv_SetVar(var, jj);
insptr = beg;
VM_Execute(1);
}
break;
case ITER_ACTIVELIGHTS:
#ifdef POLYMER
for (bssize_t jj=0; jj<PR_MAXLIGHTS; jj++)
{
if (!prlights[jj].flags.active)
continue;
Gv_SetVar(var, jj);
insptr = beg;
VM_Execute(1);
}
#else
M32_ERROR("Polymer not compiled in, iteration over lights forbidden.");
#endif
break;
case ITER_SELSPRITES:
for (bssize_t ii=0; ii<highlightcnt && !vm.flags; ii++)
{
int jj = highlight[ii];
if (jj&0xc000)
{
jj &= (MAXSPRITES-1);
Gv_SetVar(var, jj);
vm.spriteNum = jj;
vm.pSprite = &sprite[jj];
insptr = beg;
VM_Execute(1);
}
}
break;
case ITER_SELSECTORS:
for (bssize_t ii=0; ii<highlightsectorcnt && !vm.flags; ii++)
{
int jj=highlightsector[ii];
Gv_SetVar(var, jj);
insptr = beg;
VM_Execute(1);
}
break;
case ITER_SELWALLS:
for (bssize_t ii=0; ii<highlightcnt && !vm.flags; ii++)
{
int jj=highlight[ii];
if (jj&0xc000)
continue;
Gv_SetVar(var, jj);
insptr = beg;
VM_Execute(1);
}
break;
case ITER_DRAWNSPRITES:
{
uspritetype lastSpriteBackup;
auto const lastSpritePtr = (uspritetype *)&sprite[MAXSPRITES-1];
// Back up sprite MAXSPRITES-1.
Bmemcpy(&lastSpriteBackup, lastSpritePtr, sizeof(uspritetype));
EDUKE32_STATIC_ASSERT(sizeof(uspritetype) == sizeof(tspritetype)); // see TSPRITE_SIZE
for (bssize_t ii=0; ii<spritesortcnt && !vm.flags; ii++)
{
vm.pUSprite = lastSpritePtr;
Bmemcpy(lastSpritePtr, &tsprite[ii], sizeof(tspritetype));
Gv_SetVar(var, ii);
insptr = beg;
VM_Execute(1);
// Copy over potentially altered tsprite.
Bmemcpy(&tsprite[ii], lastSpritePtr, sizeof(tspritetype));
}
// Restore sprite MAXSPRITES-1.
Bmemcpy(lastSpritePtr, &lastSpriteBackup, sizeof(uspritetype));
break;
}
case ITER_SPRITESOFSECTOR:
if (parm2 < 0 || parm2 >= MAXSECTORS)
goto badindex;
for (bssize_t jj=headspritesect[parm2]; jj>=0 && !vm.flags; jj=nextspritesect[jj])
{
Gv_SetVar(var, jj);
vm.spriteNum = jj;
vm.pSprite = &sprite[jj];
insptr = beg;
VM_Execute(1);
}
break;
case ITER_WALLSOFSECTOR:
if (parm2 < 0 || parm2 >= MAXSECTORS)
goto badindex;
for (bssize_t jj=sector[parm2].wallptr, endwall=jj+sector[parm2].wallnum-1;
jj<=endwall && !vm.flags; jj++)
{
Gv_SetVar(var, jj);
insptr = beg;
VM_Execute(1);
}
break;
case ITER_LOOPOFWALL:
if (parm2 < 0 || parm2 >= numwalls)
goto badindex;
{
int jj = parm2;
do
{
Gv_SetVar(var, jj);
insptr = beg;
VM_Execute(1);
jj = wall[jj].point2;
}
while (jj != parm2 && !vm.flags);
}
break;
case ITER_RANGE:
for (bssize_t jj=0; jj<parm2 && !vm.flags; jj++)
{
Gv_SetVar(var, jj);
insptr = beg;
VM_Execute(1);
}
break;
default:
M32_ERROR("Unknown iteration type %d!", how);
continue;
badindex:
OSD_Printf("%sLine %d, %s %s: index %d out of range!\n", osd->draw.highlight,
g_errorLineNum,keyw[g_tw], iter_tokens[how].token, parm2);
vm.flags |= VMFLAG_ERROR;
continue;
}
vm.spriteNum = vm_i_bak;
vm.pUSprite = vm_sp_bak;
vm.flags &= ~VMFLAG_BREAK;
insptr = end;
}
continue;
case CON_IFVARAND:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
VM_DoConditional(j & *insptr);
}
continue;
case CON_IFVAROR:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
VM_DoConditional(j | *insptr);
}
continue;
case CON_IFVARXOR:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
VM_DoConditional(j ^ *insptr);
}
continue;
case CON_IFVAREITHER:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
VM_DoConditional(j || *insptr);
}
continue;
case CON_IFVARBOTH:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
VM_DoConditional(j && *insptr);
}
continue;
case CON_IFVARG:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
VM_DoConditional(j > *insptr);
}
continue;
case CON_IFVARGE:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
VM_DoConditional(j >= *insptr);
}
continue;
case CON_IFVARL:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
VM_DoConditional(j < *insptr);
}
continue;
case CON_IFVARLE:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
VM_DoConditional(j <= *insptr);
}
continue;
case CON_IFVARA:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
VM_DoConditional((uint32_t)j > (uint32_t)*insptr);
}
continue;
case CON_IFVARAE:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
VM_DoConditional((uint32_t)j >= (uint32_t)*insptr);
}
continue;
case CON_IFVARB:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
VM_DoConditional((uint32_t)j < (uint32_t)*insptr);
}
continue;
case CON_IFVARBE:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
VM_DoConditional((uint32_t)j <= (uint32_t)*insptr);
}
continue;
case CON_IFRND:
VM_DoConditional(rnd(Gv_GetVar(*(++insptr))));
continue;
case CON_IFHITKEY:
case CON_IFHOLDKEY:
case CON_RESETKEY:
case CON_SETKEY:
insptr++;
{
int32_t key=Gv_GetVar(*insptr);
if (key<0 || key >= (int32_t)ARRAY_SIZE(keystatus))
{
M32_ERROR("Invalid key %d!", key);
continue;
}
if (tw == CON_IFHITKEY || tw == CON_IFHOLDKEY)
VM_DoConditional(keystatus[key]);
else
insptr++;
if (tw != CON_IFHOLDKEY)
{
if (!(key==0 || key==KEYSC_ESC || key==KEYSC_TILDE || key==KEYSC_gENTER ||
key==KEYSC_LALT || key==KEYSC_RALT || key==KEYSC_LCTRL || key==KEYSC_RCTRL ||
key==KEYSC_LSHIFT || key==KEYSC_RSHIFT))
keystatus[key] = (tw==CON_SETKEY);
}
}
continue;
case CON_IFEITHERALT:
VM_DoConditional(keystatus[KEYSC_LALT]||keystatus[KEYSC_RALT]);
continue;
case CON_IFEITHERCTRL:
VM_DoConditional(keystatus[KEYSC_LCTRL]||keystatus[KEYSC_RCTRL]);
continue;
case CON_IFEITHERSHIFT:
VM_DoConditional(keystatus[KEYSC_LSHIFT]||keystatus[KEYSC_RSHIFT]);
continue;
// vvv CURSPR
case CON_IFSPRITEPAL:
insptr++;
X_ERROR_INVALIDSP();
VM_DoConditional(vm.pSprite->pal == Gv_GetVar(*insptr));
continue;
case CON_IFHIGHLIGHTED:
insptr++;
{
int32_t id=*insptr++, index=Gv_GetVar(*insptr);
if (index<0 || (id==M32_SPRITE_VAR_ID && index>=MAXSPRITES) || (id==M32_WALL_VAR_ID && index>=numwalls))
{
M32_ERROR("%s index %d out of range!", id==M32_SPRITE_VAR_ID?"Sprite":"Wall", index);
continue;
}
if (id==M32_SPRITE_VAR_ID)
VM_DoConditional(bitmap_test(show2dsprite, index));
else
VM_DoConditional(bitmap_test(show2dwall, index));
}
continue;
case CON_IFANGDIFFL:
insptr++;
{
int32_t j;
X_ERROR_INVALIDSP();
j = klabs(G_GetAngleDelta(ang, vm.pSprite->ang));
VM_DoConditional(j <= Gv_GetVar(*insptr));
}
continue;
case CON_IFAWAYFROMWALL:
{
int16_t s1;
int32_t j = 0;
X_ERROR_INVALIDSP();
s1 = vm.pSprite->sectnum;
updatesector(vm.pSprite->x+108,vm.pSprite->y+108,&s1);
if (s1 == vm.pSprite->sectnum)
{
updatesector(vm.pSprite->x-108,vm.pSprite->y-108,&s1);
if (s1 == vm.pSprite->sectnum)
{
updatesector(vm.pSprite->x+108,vm.pSprite->y-108,&s1);
if (s1 == vm.pSprite->sectnum)
{
updatesector(vm.pSprite->x-108,vm.pSprite->y+108,&s1);
if (s1 == vm.pSprite->sectnum)
j = 1;
}
}
}
VM_DoConditional(j);
}
continue;
case CON_IFCANSEE:
{
int32_t j;
X_ERROR_INVALIDSP();
j = cansee(vm.pSprite->x,vm.pSprite->y,vm.pSprite->z/*-((krand()&41)<<8)*/,vm.pSprite->sectnum,
pos.x, pos.y, pos.z /*-((krand()&41)<<8)*/, cursectnum);
VM_DoConditional(j);
}
continue;
case CON_IFONWATER:
X_ERROR_INVALIDSP();
VM_DoConditional(sector[vm.pSprite->sectnum].lotag == 1 && klabs(vm.pSprite->z-sector[vm.pSprite->sectnum].floorz) < (32<<8));
continue;
case CON_IFINWATER:
X_ERROR_INVALIDSP();
VM_DoConditional(sector[vm.pSprite->sectnum].lotag == 2);
continue;
case CON_IFACTOR:
insptr++;
X_ERROR_INVALIDSP();
VM_DoConditional(vm.pSprite->picnum == Gv_GetVar(*insptr));
continue;
case CON_IFINSIDE:
insptr++;
{
int32_t x=Gv_GetVar(*insptr++), y=Gv_GetVar(*insptr++), sectnum=Gv_GetVar(*insptr++), res;
res = inside(x, y, sectnum);
if (res == -1)
{
M32_ERROR("Sector index %d out of range!", sectnum);
continue;
}
insptr--;
VM_DoConditional(res);
}
continue;
case CON_IFOUTSIDE:
X_ERROR_INVALIDSP();
VM_DoConditional(sector[vm.pSprite->sectnum].ceilingstat&1);
continue;
case CON_IFPDISTL:
insptr++;
{
X_ERROR_INVALIDSP();
VM_DoConditional(dist(&pos, vm.pSprite) < Gv_GetVar(*insptr));
}
continue;
case CON_IFPDISTG:
insptr++;
{
X_ERROR_INVALIDSP();
VM_DoConditional(dist(&pos, vm.pSprite) > Gv_GetVar(*insptr));
}
continue;
// ^^^
// *** BUILD functions
case CON_INSERTSPRITE:
insptr++;
{
int32_t dasectnum = Gv_GetVar(*insptr++), ret;
X_ERROR_INVALIDSECT(dasectnum);
if (Numsprites >= MAXSPRITES)
{
M32_ERROR("Maximum number of sprites reached.");
continue;
}
ret = insertsprite(dasectnum, 0);
vm.spriteNum = ret;
vm.pSprite = &sprite[ret];
}
continue;
case CON_DUPSPRITE:
case CON_TDUPSPRITE:
insptr++;
{
int32_t ospritenum = Gv_GetVar(*insptr++), nspritenum;
if (ospritenum<0 || ospritenum>=MAXSPRITES || sprite[ospritenum].statnum==MAXSTATUS)
{
M32_ERROR("Tried to duplicate nonexistent sprite %d", ospritenum);
}
if ((tw==CON_DUPSPRITE && Numsprites >= MAXSPRITES) ||
(tw==CON_DUPSPRITE && spritesortcnt >= maxspritesonscreen))
{
M32_ERROR("Maximum number of sprites reached.");
}
if (vm.flags&VMFLAG_ERROR)
continue;
if (tw==CON_DUPSPRITE)
{
nspritenum = insertsprite(sprite[ospritenum].sectnum, sprite[ospritenum].statnum);
if (nspritenum < 0)
{
M32_ERROR("Internal error.");
continue;
}
Bmemcpy(&sprite[nspritenum], &sprite[ospritenum], sizeof(spritetype));
vm.spriteNum = nspritenum;
vm.pSprite = &sprite[nspritenum];
}
else
{
tspriteptr_t tsp = renderAddTSpriteFromSprite(ospritenum);
vm.spriteNum = -1;
EDUKE32_STATIC_ASSERT(sizeof(uspritetype) == sizeof(tspritetype)); // see TSPRITE_SIZE
vm.pUSprite = (uspriteptr_t)tsp;
}
}
continue;
case CON_DELETESPRITE:
insptr++;
{
int32_t daspritenum = Gv_GetVar(*insptr++), ret;
X_ERROR_INVALIDSPRI(daspritenum);
ret = deletesprite(daspritenum);
g_iReturnVar = ret;
}
continue;
case CON_GETSPRITELINKTYPE:
insptr++;
{
int32_t spritenum=Gv_GetVar(*insptr++), resvar = *insptr++;
X_ERROR_INVALIDSPRI(spritenum);
Gv_SetVar(resvar, taglab_linktags(1, spritenum));
}
continue;
case CON_LASTWALL:
insptr++;
{
int32_t dapoint = Gv_GetVar(*insptr++), resvar=*insptr++;
if (dapoint<0 || dapoint>=numwalls)
{
M32_ERROR("Invalid wall %d", dapoint);
continue;
}
Gv_SetVar(resvar, lastwall(dapoint));
}
continue;
case CON_GETZRANGE:
insptr++;
{
vec3_t vect;
vect.x = Gv_GetVar(*insptr++);
vect.y = Gv_GetVar(*insptr++);
vect.z = Gv_GetVar(*insptr++);
{
int32_t sectnum=Gv_GetVar(*insptr++);
int32_t ceilzvar=*insptr++, ceilhitvar=*insptr++, florzvar=*insptr++, florhitvar=*insptr++;
int32_t walldist=Gv_GetVar(*insptr++), clipmask=Gv_GetVar(*insptr++);
int32_t ceilz, ceilhit, florz, florhit;
X_ERROR_INVALIDSECT(sectnum);
getzrange(&vect, sectnum, &ceilz, &ceilhit, &florz, &florhit, walldist, clipmask);
Gv_SetVar(ceilzvar, ceilz);
Gv_SetVar(ceilhitvar, ceilhit);
Gv_SetVar(florzvar, florz);
Gv_SetVar(florhitvar, florhit);
}
continue;
}
case CON_CALCHYPOTENUSE:
insptr++;
{
int32_t retvar=*insptr++;
int64_t dax=Gv_GetVar(*insptr++), day=Gv_GetVar(*insptr++);
int64_t hypsq = dax*dax + day*day;
if (hypsq > (int64_t)INT32_MAX)
Gv_SetVar(retvar, (int32_t)sqrt((double)hypsq));
else
Gv_SetVar(retvar, ksqrt((uint32_t)hypsq));
continue;
}
case CON_LINEINTERSECT:
case CON_RAYINTERSECT:
insptr++;
{
int32_t x1=Gv_GetVar(*insptr++), y1=Gv_GetVar(*insptr++), z1=Gv_GetVar(*insptr++);
int32_t x2=Gv_GetVar(*insptr++), y2=Gv_GetVar(*insptr++), z2=Gv_GetVar(*insptr++);
int32_t x3=Gv_GetVar(*insptr++), y3=Gv_GetVar(*insptr++), x4=Gv_GetVar(*insptr++), y4=Gv_GetVar(*insptr++);
int32_t intxvar=*insptr++, intyvar=*insptr++, intzvar=*insptr++, retvar=*insptr++;
int32_t intx, inty, intz, ret;
if (tw==CON_LINEINTERSECT)
ret = lintersect(x1, y1, z1, x2, y2, z2, x3, y3, x4, y4, &intx, &inty, &intz);
else
ret = rayintersect(x1, y1, z1, x2, y2, z2, x3, y3, x4, y4, &intx, &inty, &intz);
Gv_SetVar(retvar, ret);
if (ret)
{
Gv_SetVar(intxvar, intx);
Gv_SetVar(intyvar, inty);
Gv_SetVar(intzvar, intz);
}
continue;
}
case CON_CLIPMOVE:
insptr++;
{
vec3_t vect;
int32_t retvar=*insptr++, xvar=*insptr++, yvar=*insptr++, z=Gv_GetVar(*insptr++), sectnumvar=*insptr++;
int32_t xvect=Gv_GetVar(*insptr++), yvect=Gv_GetVar(*insptr++);
int32_t walldist=Gv_GetVar(*insptr++), floordist=Gv_GetVar(*insptr++), ceildist=Gv_GetVar(*insptr++);
int32_t clipmask=Gv_GetVar(*insptr++);
int16_t sectnum;
vect.x = Gv_GetVar(xvar);
vect.y = Gv_GetVar(yvar);
vect.z = z;
sectnum = Gv_GetVar(sectnumvar);
X_ERROR_INVALIDSECT(sectnum);
Gv_SetVar(retvar, clipmove(&vect, §num, xvect, yvect, walldist, floordist, ceildist, clipmask));
Gv_SetVar(sectnumvar, sectnum);
Gv_SetVar(xvar, vect.x);
Gv_SetVar(yvar, vect.y);
continue;
}
case CON_HITSCAN:
insptr++;
{
vec3_t vect;
hitdata_t hit;
vect.x = Gv_GetVar(*insptr++);
vect.y = Gv_GetVar(*insptr++);
vect.z = Gv_GetVar(*insptr++);
{
int32_t sectnum=Gv_GetVar(*insptr++);
int32_t vx=Gv_GetVar(*insptr++), vy=Gv_GetVar(*insptr++), vz=Gv_GetVar(*insptr++);
int32_t hitsectvar=*insptr++, hitwallvar=*insptr++, hitspritevar=*insptr++;
int32_t hitxvar=*insptr++, hityvar=*insptr++, hitzvar=*insptr++, cliptype=Gv_GetVar(*insptr++);
X_ERROR_INVALIDSECT(sectnum);
hitscan((const vec3_t *)&vect, sectnum, vx, vy, vz, &hit, cliptype);
Gv_SetVar(hitsectvar, hit.sect);
Gv_SetVar(hitwallvar, hit.wall);
Gv_SetVar(hitspritevar, hit.sprite);
Gv_SetVar(hitxvar, hit.x);
Gv_SetVar(hityvar, hit.y);
Gv_SetVar(hitzvar, hit.z);
}
continue;
}
case CON_CANSEE:
insptr++;
{
int32_t x1=Gv_GetVar(*insptr++), y1=Gv_GetVar(*insptr++), z1=Gv_GetVar(*insptr++);
int32_t sect1=Gv_GetVar(*insptr++);
int32_t x2=Gv_GetVar(*insptr++), y2=Gv_GetVar(*insptr++), z2=Gv_GetVar(*insptr++);
int32_t sect2=Gv_GetVar(*insptr++), rvar=*insptr++;
X_ERROR_INVALIDSECT(sect1);
X_ERROR_INVALIDSECT(sect2);
Gv_SetVar(rvar, cansee(x1,y1,z1,sect1,x2,y2,z2,sect2));
continue;
}
case CON_ROTATEPOINT:
insptr++;
{
vec2_t pivot = { Gv_GetVar(*insptr), Gv_GetVar(*(insptr+1)) };
vec2_t p = { Gv_GetVar(*(insptr+2)), Gv_GetVar(*(insptr+3)) };
insptr += 4;
int32_t daang=Gv_GetVar(*insptr++);
int32_t x2var=*insptr++, y2var=*insptr++;
vec2_t p2;
rotatepoint(pivot,p,daang,&p2);
Gv_SetVar(x2var, p2.x);
Gv_SetVar(y2var, p2.y);
continue;
}
case CON_NEARTAG:
insptr++;
{
// neartag(int32_t x, int32_t y, int32_t z, short sectnum, short ang, //Starting position & angle
// short *neartagsector, //Returns near sector if sector[].tag != 0
// short *neartagwall, //Returns near wall if wall[].tag != 0
// short *neartagsprite, //Returns near sprite if sprite[].tag != 0
// int32_t *neartaghitdist, //Returns actual distance to object (scale: 1024=largest grid size)
// int32_t neartagrange, //Choose maximum distance to scan (scale: 1024=largest grid size)
// char tagsearch) //1-lotag only, 2-hitag only, 3-lotag&hitag
int32_t x=Gv_GetVar(*insptr++), y=Gv_GetVar(*insptr++), z=Gv_GetVar(*insptr++);
int32_t sectnum=Gv_GetVar(*insptr++), ang=Gv_GetVar(*insptr++);
int32_t neartagsectorvar=*insptr++, neartagwallvar=*insptr++, neartagspritevar=*insptr++, neartaghitdistvar=*insptr++;
int32_t neartagrange=Gv_GetVar(*insptr++), tagsearch=Gv_GetVar(*insptr++);
int16_t neartagsector, neartagwall, neartagsprite;
int32_t neartaghitdist;
X_ERROR_INVALIDSECT(sectnum);
neartag(x, y, z, sectnum, ang, &neartagsector, &neartagwall, &neartagsprite,
&neartaghitdist, neartagrange, tagsearch, NULL);
Gv_SetVar(neartagsectorvar, neartagsector);
Gv_SetVar(neartagwallvar, neartagwall);
Gv_SetVar(neartagspritevar, neartagsprite);
Gv_SetVar(neartaghitdistvar, neartaghitdist);
continue;
}
case CON_BSETSPRITE: // was CON_SETSPRITE
insptr++;
{
int32_t spritenum = Gv_GetVar(*insptr++);
vec3_t davector;
davector.x = Gv_GetVar(*insptr++);
davector.y = Gv_GetVar(*insptr++);
davector.z = Gv_GetVar(*insptr++);
X_ERROR_INVALIDSPRI(spritenum);
setsprite(spritenum, &davector);
continue;
}
case CON_GETFLORZOFSLOPE:
case CON_GETCEILZOFSLOPE:
insptr++;
{
int32_t sectnum = Gv_GetVar(*insptr++), x = Gv_GetVar(*insptr++), y = Gv_GetVar(*insptr++);
int32_t var=*insptr++;
X_ERROR_INVALIDSECT(sectnum);
if (tw == CON_GETFLORZOFSLOPE)
Gv_SetVar(var, getflorzofslope(sectnum,x,y));
else
Gv_SetVar(var, getceilzofslope(sectnum,x,y));
continue;
}
case CON_ALIGNFLORSLOPE:
case CON_ALIGNCEILSLOPE:
insptr++;
{
int32_t sectnum = Gv_GetVar(*insptr++), x = Gv_GetVar(*insptr++), y = Gv_GetVar(*insptr++);
int32_t z=Gv_GetVar(*insptr++);
X_ERROR_INVALIDSECT(sectnum);
if (tw == CON_ALIGNFLORSLOPE)
alignflorslope(sectnum, x,y,z);
else
alignceilslope(sectnum, x,y,z);
continue;
}
// CURSPR
case CON_SETFIRSTWALL:
insptr++;
{
int32_t sect=Gv_GetVar(*insptr++), wal=Gv_GetVar(*insptr++);
X_ERROR_INVALIDSECT(sect);
setfirstwall(sect, wal);
}
continue;
case CON_UPDATECURSECTNUM:
insptr++;
updatesectorz(pos.x, pos.y, pos.z, &cursectnum);
continue;
case CON_UPDATESECTOR:
case CON_UPDATESECTORZ:
case CON_UPDATESECTORNEIGHBOR:
case CON_UPDATESECTORNEIGHBORZ:
insptr++;
{
int32_t x=Gv_GetVar(*insptr++), y=Gv_GetVar(*insptr++);
int32_t z=(tw==CON_UPDATESECTORZ || tw==CON_UPDATESECTORNEIGHBORZ)?Gv_GetVar(*insptr++):0;
int32_t var=*insptr++;
int16_t w;
X_ERROR_INVALIDCI();
w=sprite[vm.spriteNum].sectnum;
switch (tw)
{
case CON_UPDATESECTORNEIGHBORZ:
updatesectorneighborz(x,y,z,&w,getsectordist({x, y}, w));
break;
case CON_UPDATESECTORZ:
updatesectorz(x,y,z,&w);
break;
case CON_UPDATESECTORNEIGHBOR:
updatesectorneighbor(x,y,&w,getsectordist({x, y}, w));
break;
default:
updatesector(x,y,&w);
break;
}
Gv_SetVar(var, w);
continue;
}
case CON_HEADSPRITESTAT:
insptr++;
{
int32_t i=*insptr++;
int32_t j=Gv_GetVar(*insptr++);
if (j < 0 || j > MAXSTATUS)
{
M32_ERROR("invalid status list %d", j);
continue;
}
Gv_SetVar(i,headspritestat[j]);
continue;
}
case CON_PREVSPRITESTAT:
insptr++;
{
int32_t i=*insptr++;
int32_t j=Gv_GetVar(*insptr++);
X_ERROR_INVALIDSPRI(j);
Gv_SetVar(i,prevspritestat[j]);
continue;
}
case CON_NEXTSPRITESTAT:
insptr++;
{
int32_t i=*insptr++;
int32_t j=Gv_GetVar(*insptr++);
X_ERROR_INVALIDSPRI(j);
Gv_SetVar(i,nextspritestat[j]);
continue;
}
case CON_HEADSPRITESECT:
insptr++;
{
int32_t i=*insptr++;
int32_t j=Gv_GetVar(*insptr++);
X_ERROR_INVALIDSECT(j);
Gv_SetVar(i,headspritesect[j]);
continue;
}
case CON_PREVSPRITESECT:
insptr++;
{
int32_t i=*insptr++;
int32_t j=Gv_GetVar(*insptr++);
X_ERROR_INVALIDSPRI(j);
Gv_SetVar(i,prevspritesect[j]);
continue;
}
case CON_NEXTSPRITESECT:
insptr++;
{
int32_t i=*insptr++;
int32_t j=Gv_GetVar(*insptr++);
X_ERROR_INVALIDSPRI(j);
Gv_SetVar(i,nextspritesect[j]);
continue;
}
case CON_CANSEESPR:
insptr++;
{
int32_t lVar1 = Gv_GetVar(*insptr++), lVar2 = Gv_GetVar(*insptr++), res;
if (lVar1<0 || lVar1>=MAXSPRITES || sprite[lVar1].statnum==MAXSTATUS)
{
M32_ERROR("Invalid sprite %d", lVar1);
}
if (lVar2<0 || lVar2>=MAXSPRITES || sprite[lVar2].statnum==MAXSTATUS)
{
M32_ERROR("Invalid sprite %d", lVar2);
}
if (vm.flags&VMFLAG_ERROR) res=0;
else res=cansee(sprite[lVar1].x,sprite[lVar1].y,sprite[lVar1].z,sprite[lVar1].sectnum,
sprite[lVar2].x,sprite[lVar2].y,sprite[lVar2].z,sprite[lVar2].sectnum);
Gv_SetVar(*insptr++, res);
continue;
}
case CON_CHANGESPRITESTAT:
case CON_CHANGESPRITESECT:
insptr++;
{
int32_t i = Gv_GetVar(*insptr++);
int32_t j = Gv_GetVar(*insptr++);
X_ERROR_INVALIDSPRI(i);
if (j<0 || j >= (tw==CON_CHANGESPRITESTAT?MAXSTATUS:numsectors))
{
M32_ERROR("Invalid %s: %d", tw==CON_CHANGESPRITESTAT?"statnum":"sector", j);
continue;
}
if (tw == CON_CHANGESPRITESTAT)
{
if (sprite[i].statnum == j) continue;
changespritestat(i,j);
}
else
{
if (sprite[i].sectnum == j) continue;
changespritesect(i,j);
}
continue;
}
case CON_DRAGPOINT:
insptr++;
{
int32_t wallnum = Gv_GetVar(*insptr++), newx = Gv_GetVar(*insptr++), newy = Gv_GetVar(*insptr++);
if (wallnum<0 || wallnum>=numwalls)
{
M32_ERROR("Invalid wall %d", wallnum);
continue;
}
dragpoint(wallnum,newx,newy,0);
continue;
}
case CON_SECTOROFWALL:
insptr++;
{
int32_t j = *insptr++;
Gv_SetVar(j, sectorofwall(Gv_GetVar(*insptr++)));
}
continue;
case CON_FIXREPEATS:
insptr++;
fixrepeats(Gv_GetVar(*insptr++));
continue;
case CON_GETCLOSESTCOL:
insptr++;
{
int32_t r = Gv_GetVar(*insptr++), g = Gv_GetVar(*insptr++), b = Gv_GetVar(*insptr++);
Gv_SetVar(*insptr++, paletteGetClosestColor(r, g, b));
continue;
}
// *** stuff
case CON_XFLIPHIGHLIGHTEDSECTORS:
case CON_XMIRRORHIGHLIGHTEDSECTORS:
insptr++;
editorFlipHighlightedSectors(1, tw == CON_XMIRRORHIGHLIGHTEDSECTORS);
continue;
case CON_YFLIPHIGHLIGHTEDSECTORS:
case CON_YMIRRORHIGHLIGHTEDSECTORS:
insptr++;
editorFlipHighlightedSectors(0, tw == CON_YMIRRORHIGHLIGHTEDSECTORS);
continue;
case CON_UPDATEHIGHLIGHT:
insptr++;
update_highlight();
continue;
case CON_UPDATEHIGHLIGHTSECTOR:
insptr++;
update_highlightsector();
continue;
case CON_SETHIGHLIGHT:
insptr++;
{
int32_t what=Gv_GetVar(*insptr++), index=Gv_GetVar(*insptr++), doset = Gv_GetVar(*insptr++);
if (highlightsectorcnt >= 0)
{
M32_ERROR("sector highlight active or pending, cannot highlight sprites/walls");
continue;
}
if (what&16384)
{
index &= ~16384;
if (index < 0 || index>=MAXSPRITES || sprite[index].statnum==MAXSTATUS)
{
M32_ERROR("Invalid sprite index %d", index);
continue;
}
if (doset)
bitmap_set(show2dsprite, index);
else
bitmap_clear(show2dsprite, index);
}
else
{
if (index < 0 || index>=numwalls)
{
M32_ERROR("Invalid wall index %d", index);
continue;
}
if (doset)
bitmap_set(show2dwall, index);
else
bitmap_clear(show2dwall, index);
}
vm.miscflags |= VMFLAG_MISC_UPDATEHL;
continue;
}
case CON_SETHIGHLIGHTSECTOR:
insptr++;
{
int32_t index=Gv_GetVar(*insptr++), doset = Gv_GetVar(*insptr++);
if (highlightcnt >= 0)
{
M32_ERROR("sprite/wall highlight active or pending, cannot highlight sectors");
continue;
}
X_ERROR_INVALIDSECT(index);
if (doset)
bitmap_set(hlsectorbitmap, index);
else
bitmap_clear(hlsectorbitmap, index);
vm.miscflags |= VMFLAG_MISC_UPDATEHLSECT;
continue;
}
case CON_GETTIMEDATE:
insptr++;
{
int32_t v1=*insptr++,v2=*insptr++,v3=*insptr++,v4=*insptr++,v5=*insptr++,v6=*insptr++,v7=*insptr++,v8=*insptr++;
time_t rawtime;
struct tm *ti;
time(&rawtime);
ti = localtime(&rawtime);
// initprintf("Time&date: %s\n",asctime (ti));
Gv_SetVar(v1, ti->tm_sec);
Gv_SetVar(v2, ti->tm_min);
Gv_SetVar(v3, ti->tm_hour);
Gv_SetVar(v4, ti->tm_mday);
Gv_SetVar(v5, ti->tm_mon);
Gv_SetVar(v6, ti->tm_year+1900);
Gv_SetVar(v7, ti->tm_wday);
Gv_SetVar(v8, ti->tm_yday);
continue;
}
case CON_ADDLOG:
{
insptr++;
OSD_Printf("L=%d\n", g_errorLineNum);
continue;
}
case CON_ADDLOGVAR:
insptr++;
{
char buf[80] = "", buf2[80] = "";
int32_t code = (int32_t)*insptr, val = Gv_GetVar(code);
int32_t negate=code&M32_FLAG_NEGATE;
if (code & (0xFFFFFFFF-(MAXGAMEVARS-1)))
{
if ((code&M32_VARTYPE_MASK)==M32_FLAG_ARRAY || (code&M32_VARTYPE_MASK)==M32_FLAG_STRUCT)
{
if (code&M32_FLAG_CONSTANT)
Bsprintf(buf2, "%d", (code>>16)&0xffff);
else
{
char *label = aGameVars[(code>>16)&(MAXGAMEVARS-1)].szLabel;
Bsprintf(buf2, "%s", label?label:"???");
}
}
else if ((code&M32_VARTYPE_MASK)==M32_FLAG_LOCAL)
Bsprintf(buf2, "%d", code&(MAXGAMEVARS-1));
if ((code&0x0000FFFC) == M32_FLAG_CONSTANT) // addlogvar for a constant.. why not? :P
{
switch (code&3)
{
case 0: Bsprintf(buf, "(immediate constant)"); break;
case 1: Bsprintf(buf, "(indirect constant)"); break;
case 2: Bsprintf(buf, "(label constant)"); break;
default: Bsprintf(buf, "(??? constant)"); break;
}
}
else
{
switch (code&M32_VARTYPE_MASK)
{
case M32_FLAG_ARRAY:
Bsnprintf(buf, sizeof(buf), "%s[%s]", aGameArrays[code&(MAXGAMEARRAYS-1)].szLabel
? aGameArrays[code&(MAXGAMEARRAYS-1)].szLabel : "???", buf2);
break;
case M32_FLAG_STRUCT:
{
int32_t memberid=(code>>2)&63, lightp = (memberid >= LIGHT_X);
const char *pp1[4] = {"sprite","sector","wall","tsprite"};
memberlabel_t const *pp2[4] = {SpriteLabels, SectorLabels, WallLabels, SpriteLabels};
if (lightp)
{
pp1[3] = "light";
pp2[3] = LightLabels;
memberid -= LIGHT_X;
}
Bsnprintf(buf, sizeof(buf), "%s[%s].%s", pp1[code&3], buf2, pp2[code&3][memberid].name);
}
break;
case M32_FLAG_VAR:
Bstrcpy(buf, "???");
break;
case M32_FLAG_LOCAL:
Bsnprintf(buf, sizeof(buf), ".local[%s]", buf2);
break;
}
}
}
else
{
if (aGameVars[code].dwFlags & GAMEVAR_PERBLOCK)
{
Bsprintf(buf2, "(%s", vm.g_st==0? "top-level) " : vm.g_st<=MAXEVENTS? "event" : "state");
if (vm.g_st >= 1+MAXEVENTS && vm.g_st <1+MAXEVENTS+g_stateCount)
Bsprintf(buf, " `%s') ", statesinfo[vm.g_st-1-MAXEVENTS].name);
else if (vm.g_st > 0)
Bsprintf(buf, " %d) ", vm.g_st-1);
Bstrcat(buf2, buf);
}
Bsnprintf(buf, sizeof(buf), "%s%s", buf2, aGameVars[code].szLabel ? aGameVars[code].szLabel : "???");
}
OSD_Printf("L%d: %s%s=%d\n", g_errorLineNum, negate?"-":"", buf, val);
insptr++;
continue;
}
case CON_DEBUG:
insptr++;
LOG_F(INFO, "%d",*insptr++);
continue;
// *** strings
case CON_REDEFINEQUOTE:
insptr++;
{
int32_t q = *insptr++, i = *insptr++;
X_ERROR_INVALIDQUOTE(q, apStrings);
X_ERROR_INVALIDQUOTE(i, apXStrings);
Bstrcpy(apStrings[q],apXStrings[i]);
continue;
}
case CON_GETNUMBER16: /* deprecated */
case CON_GETNUMBER256: /* deprecated */
case CON_GETNUMBERFROMUSER:
insptr++;
{
int32_t var=*insptr++, quote=*insptr++;
const char *quotetext = GetMaybeInlineQuote(quote);
if (vm.flags&VMFLAG_ERROR)
continue;
{
int32_t max=Gv_GetVar(*insptr++);
int32_t sign = (tw==CON_GETNUMBERFROMUSER) ? Gv_GetVar(*insptr++) : (max<=0);
char buf[64]; // buffers in getnumber* are 80 bytes long
Bstrncpyz(buf, quotetext, sizeof(buf));
if (max==0)
max = INT32_MAX;
else
max = klabs(max);
//OSD_Printf("max:%d, sign:%d\n", max, sign);
if (tw==CON_GETNUMBERFROMUSER)
{
Gv_SetVar(var, in3dmode() ?
getnumber256(quotetext, Gv_GetVar(var), max, sign) :
getnumber16(quotetext, Gv_GetVar(var), max, sign));
}
else if (tw==CON_GETNUMBER16)
Gv_SetVar(var, getnumber16(quotetext, Gv_GetVar(var), max, sign));
else
Gv_SetVar(var, getnumber256(quotetext, Gv_GetVar(var), max, sign));
}
}
continue;
case CON_PRINT:
case CON_QUOTE:
case CON_ERRORINS:
case CON_PRINTMESSAGE16:
case CON_PRINTMESSAGE256:
case CON_PRINTEXT256:
case CON_PRINTEXT16:
case CON_DRAWLABEL:
insptr++;
{
int32_t i=*insptr++;
const char *quotetext = GetMaybeInlineQuote(i);
if (vm.flags&VMFLAG_ERROR)
continue;
{
int32_t x=(tw>=CON_PRINTMESSAGE256)?Gv_GetVar(*insptr++):0;
int32_t y=(tw>=CON_PRINTMESSAGE256)?Gv_GetVar(*insptr++):0;
int32_t col=(tw>=CON_PRINTEXT256)?Gv_GetVar(*insptr++):0;
int32_t backcol=(tw>=CON_PRINTEXT256)?Gv_GetVar(*insptr++):0;
int32_t fontsize=(tw>=CON_PRINTEXT256)?Gv_GetVar(*insptr++):0;
if (tw==CON_PRINT || tw==CON_ERRORINS)
{
OSD_Printf("%s\n", quotetext);
if (tw==CON_ERRORINS)
vm.flags |= VMFLAG_ERROR;
}
else if (tw==CON_QUOTE)
{
message("%s", quotetext);
}
else if (tw==CON_PRINTMESSAGE16)
{
if (!in3dmode())
printmessage16("%s", quotetext);
}
else if (tw==CON_PRINTMESSAGE256)
{
if (in3dmode())
printmessage256(x, y, quotetext);
}
else if (tw==CON_PRINTEXT256)
{
//if (in3dmode())
{
if (col>=256)
col=0;
else if (col < 0 && col >= -255)
col = editorcolors[-col];
if (backcol<0 || backcol>=256)
backcol=-1;
printext256(x, y, col, backcol, quotetext, fontsize);
}
}
else if (tw==CON_PRINTEXT16)
{
if (!in3dmode())
printext16(x, y, col>=0?editorcolors[col&255]:((-col)&255), backcol<0 ? -1 : editorcolors[backcol&255],
quotetext, fontsize);
}
else if (tw==CON_DRAWLABEL)
{
if (!in3dmode())
{
drawsmallabel(quotetext,
editorcolors[backcol&255], // col
fontsize < 0 ? -1 : editorcolors[fontsize&255], editorcolors[fontsize&255] - 3, // backcol
x, y, col); // x y z
}
}
}
}
continue;
case CON_QSTRLEN:
insptr++;
{
int32_t i=*insptr++, quote=*insptr++;
const char *quotetext = GetMaybeInlineQuote(quote);
if (vm.flags&VMFLAG_ERROR)
continue;
Gv_SetVar(i, Bstrlen(quotetext));
continue;
}
case CON_QSUBSTR:
insptr++;
{
int32_t q1 = Gv_GetVar(*insptr++);
int32_t q2 = *insptr++;
const char *q2text = GetMaybeInlineQuote(q2);
if (vm.flags&VMFLAG_ERROR)
continue;
X_ERROR_INVALIDQUOTE(q1, apStrings);
{
int32_t st = Gv_GetVar(*insptr++);
int32_t ln = Gv_GetVar(*insptr++);
char *s1 = apStrings[q1];
const char *s2 = q2text;
while (*s2 && st--) s2++;
while ((*s1 = *s2) && ln--)
{
s1++;
s2++;
}
*s1=0;
}
continue;
}
case CON_QSTRNCAT:
case CON_QSTRCAT:
case CON_QSTRCPY:
/// case CON_QGETSYSSTR:
insptr++;
{
int32_t i = Gv_GetVar(*insptr++);
int32_t j = *insptr++;
const char *quotetext = GetMaybeInlineQuote(j);
if (vm.flags&VMFLAG_ERROR)
continue;
X_ERROR_INVALIDQUOTE(i, apStrings);
switch (tw)
{
case CON_QSTRCAT:
Bstrncat(apStrings[i], quotetext, (MAXQUOTELEN-1)-Bstrlen(apStrings[i]));
break;
case CON_QSTRNCAT:
Bstrncat(apStrings[i], quotetext, Gv_GetVar(*insptr++));
break;
case CON_QSTRCPY:
Bstrcpy(apStrings[i], quotetext);
break;
}
continue;
}
case CON_QSPRINTF:
insptr++;
{
int32_t dq=Gv_GetVar(*insptr++), sq=*insptr++;
const char *sourcetext = GetMaybeInlineQuote(sq);
if (vm.flags&VMFLAG_ERROR)
continue;
X_ERROR_INVALIDQUOTE(dq, apStrings);
{
int32_t arg[32], numvals=0, i=0, j=0, k=0;
int32_t len = Bstrlen(sourcetext);
char tmpbuf[MAXQUOTELEN<<1];
while (*insptr != -1 && numvals < 32)
arg[numvals++] = Gv_GetVar(*insptr++);
insptr++; // skip the NOP
i = 0;
do
{
while (k < len && j < MAXQUOTELEN && sourcetext[k] != '%')
tmpbuf[j++] = sourcetext[k++];
if (sourcetext[k] == '%')
{
k++;
if (i>=numvals) goto dodefault;
switch (sourcetext[k])
{
case 'l':
if (sourcetext[k+1] != 'd')
{
// write the % and l
tmpbuf[j++] = sourcetext[k-1];
tmpbuf[j++] = sourcetext[k++];
break;
}
k++;
fallthrough__;
case 'd':
{
char buf[16];
int32_t ii = 0;
Bsprintf(buf, "%d", arg[i++]);
ii = Bstrlen(buf);
Bmemcpy(&tmpbuf[j], buf, ii);
j += ii;
k++;
}
break;
case 'f':
{
char buf[64];
int32_t ii = 0;
union { int32_t ival; float fval; };
ival = arg[i++];
Bsprintf(buf, "%f", fval);
ii = Bstrlen(buf);
Bmemcpy(&tmpbuf[j], buf, ii);
j += ii;
k++;
}
break;
case 's':
{
if (arg[i]>=0 && arg[i]<MAXQUOTES && apStrings[arg[i]])
{
int32_t ii = Bstrlen(apStrings[arg[i]]);
Bmemcpy(&tmpbuf[j], apStrings[arg[i]], ii);
j += ii;
}
k++;
}
break;
dodefault:
default:
tmpbuf[j++] = sourcetext[k-1];
break;
}
}
}
while (k < len && j < MAXQUOTELEN);
tmpbuf[j] = '\0';
Bmemcpy(apStrings[dq], tmpbuf, MAXQUOTELEN);
apStrings[dq][MAXQUOTELEN-1] = '\0';
continue;
}
}
// *** findnear*
// CURSPR vvv
case CON_FINDNEARSPRITE:
case CON_FINDNEARSPRITE3D:
case CON_FINDNEARSPRITEVAR:
case CON_FINDNEARSPRITE3DVAR:
insptr++;
{
// syntax findnearactor(var) <type> <maxdist(var)> <getvar>
// gets the sprite ID of the nearest actor within max dist
// that is of <type> into <getvar>
// -1 for none found
// <type> <maxdist(varid)> <varid>
int32_t lType=*insptr++;
int32_t lMaxDist = (tw==CON_FINDNEARSPRITE || tw==CON_FINDNEARSPRITE3D)?
*insptr++ : Gv_GetVar(*insptr++);
int32_t lVarID=*insptr++;
int32_t lFound=-1, j, k = MAXSTATUS-1;
X_ERROR_INVALIDCI();
do
{
j=headspritestat[k]; // all sprites
if (tw==CON_FINDNEARSPRITE3D || tw==CON_FINDNEARSPRITE3DVAR)
{
while (j>=0)
{
if (sprite[j].picnum == lType && j != vm.spriteNum && dist(&sprite[vm.spriteNum], &sprite[j]) < lMaxDist)
{
lFound=j;
j = MAXSPRITES;
break;
}
j = nextspritestat[j];
}
if (j == MAXSPRITES)
break;
continue;
}
while (j>=0)
{
if (sprite[j].picnum == lType && j != vm.spriteNum && ldist(&sprite[vm.spriteNum], &sprite[j]) < lMaxDist)
{
lFound=j;
j = MAXSPRITES;
break;
}
j = nextspritestat[j];
}
if (j == MAXSPRITES)
break;
}
while (k--);
Gv_SetVar(lVarID, lFound);
continue;
}
case CON_FINDNEARSPRITEZVAR:
case CON_FINDNEARSPRITEZ:
insptr++;
{
// syntax findnearactor(var) <type> <maxdist(var)> <getvar>
// gets the sprite ID of the nearest actor within max dist
// that is of <type> into <getvar>
// -1 for none found
// <type> <maxdist(varid)> <varid>
int32_t lType=*insptr++;
int32_t lMaxDist = (tw==CON_FINDNEARSPRITEZVAR) ? Gv_GetVar(*insptr++) : *insptr++;
int32_t lMaxZDist = (tw==CON_FINDNEARSPRITEZVAR) ? Gv_GetVar(*insptr++) : *insptr++;
int32_t lVarID=*insptr++;
int32_t lFound=-1, lTemp, lTemp2, j, k=MAXSTATUS-1;
X_ERROR_INVALIDCI();
do
{
j=headspritestat[k]; // all sprites
if (j == -1) continue;
do
{
if (sprite[j].picnum == lType && j != vm.spriteNum)
{
lTemp=ldist(&sprite[vm.spriteNum], &sprite[j]);
if (lTemp < lMaxDist)
{
lTemp2=klabs(sprite[vm.spriteNum].z-sprite[j].z);
if (lTemp2 < lMaxZDist)
{
lFound=j;
j = MAXSPRITES;
break;
}
}
}
j = nextspritestat[j];
}
while (j>=0);
if (j == MAXSPRITES)
break;
}
while (k--);
Gv_SetVar(lVarID, lFound);
continue;
}
// ^^^
case CON_GETTICKS:
insptr++;
{
int32_t j=*insptr++;
Gv_SetVar(j, timerGetTicks());
}
continue;
case CON_SETASPECT:
insptr++;
{
int32_t daxrange = Gv_GetVar(*insptr++), dayxaspect = Gv_GetVar(*insptr++);
if (daxrange < (1<<12)) daxrange = (1<<12);
if (daxrange > (1<<20)) daxrange = (1<<20);
if (dayxaspect < (1<<12)) dayxaspect = (1<<12);
if (dayxaspect > (1<<20)) dayxaspect = (1<<20);
renderSetAspect(daxrange, dayxaspect);
continue;
}
// vvv CURSPR
case CON_SETI:
{
int32_t newcurspritei;
insptr++;
newcurspritei = Gv_GetVar(*insptr++);
X_ERROR_INVALIDSPRI(newcurspritei);
vm.spriteNum = newcurspritei;
vm.pSprite = &sprite[vm.spriteNum];
continue;
}
case CON_SIZEAT:
insptr += 3;
X_ERROR_INVALIDSP();
vm.pSprite->xrepeat = (uint8_t) Gv_GetVar(*(insptr-2));
vm.pSprite->yrepeat = (uint8_t) Gv_GetVar(*(insptr-1));
#ifdef USE_STRUCT_TRACKERS
if (vm.spriteNum != -1) spritechanged[vm.spriteNum]++;
#endif
continue;
case CON_CSTAT:
insptr += 2;
X_ERROR_INVALIDSP();
vm.pSprite->cstat = (int16_t) *(insptr-1);
#ifdef USE_STRUCT_TRACKERS
if (vm.spriteNum != -1) spritechanged[vm.spriteNum]++;
#endif
continue;
case CON_CSTATOR:
insptr += 2;
X_ERROR_INVALIDSP();
vm.pSprite->cstat |= (int16_t) Gv_GetVar(*(insptr-1));
#ifdef USE_STRUCT_TRACKERS
if (vm.spriteNum != -1) spritechanged[vm.spriteNum]++;
#endif
continue;
case CON_CLIPDIST:
insptr += 2;
X_ERROR_INVALIDSP();
vm.pSprite->clipdist = (uint8_t) Gv_GetVar(*(insptr-1));
#ifdef USE_STRUCT_TRACKERS
if (vm.spriteNum != -1) spritechanged[vm.spriteNum]++;
#endif
continue;
case CON_SPRITEPAL:
insptr += 2;
X_ERROR_INVALIDSP();
vm.pSprite->pal = Gv_GetVar(*(insptr-1));
#ifdef USE_STRUCT_TRACKERS
if (vm.spriteNum != -1) spritechanged[vm.spriteNum]++;
#endif
continue;
case CON_CACTOR:
insptr += 2;
X_ERROR_INVALIDSP();
vm.pSprite->picnum = Gv_GetVar(*(insptr-1));
#ifdef USE_STRUCT_TRACKERS
if (vm.spriteNum != -1) spritechanged[vm.spriteNum]++;
#endif
continue;
case CON_SPGETLOTAG:
insptr++;
X_ERROR_INVALIDSP();
Gv_SetVar(M32_LOTAG_VAR_ID, vm.pSprite->lotag);
continue;
case CON_SPGETHITAG:
insptr++;
X_ERROR_INVALIDSP();
Gv_SetVar(M32_HITAG_VAR_ID, vm.pSprite->hitag);
continue;
case CON_SECTGETLOTAG:
insptr++;
X_ERROR_INVALIDSP();
Gv_SetVar(M32_LOTAG_VAR_ID, sector[vm.pSprite->sectnum].lotag);
continue;
case CON_SECTGETHITAG:
insptr++;
X_ERROR_INVALIDSP();
Gv_SetVar(M32_HITAG_VAR_ID, sector[vm.pSprite->sectnum].hitag);
continue;
case CON_GETTEXTUREFLOOR:
insptr++;
X_ERROR_INVALIDSP();
Gv_SetVar(M32_TEXTURE_VAR_ID, sector[vm.pSprite->sectnum].floorpicnum);
continue;
case CON_GETTEXTURECEILING:
insptr++;
X_ERROR_INVALIDSP();
Gv_SetVar(M32_TEXTURE_VAR_ID, sector[vm.pSprite->sectnum].ceilingpicnum);
continue;
// ^^^
case CON_DRAWLINE16:
case CON_DRAWLINE16B:
case CON_DRAWLINE16Z:
insptr++;
{
int32_t x1=Gv_GetVar(*insptr++), y1=Gv_GetVar(*insptr++);
int32_t z1=tw==CON_DRAWLINE16Z?Gv_GetVar(*insptr++):0;
int32_t x2=Gv_GetVar(*insptr++), y2=Gv_GetVar(*insptr++);
int32_t z2=tw==CON_DRAWLINE16Z?Gv_GetVar(*insptr++):0;
int32_t col=Gv_GetVar(*insptr++), odrawlinepat=drawlinepat;
int32_t xofs=0, yofs=0;
if (tw==CON_DRAWLINE16B || tw==CON_DRAWLINE16Z)
{
editorGet2dScreenCoordinates(&x1,&y1, x1-pos.x,y1-pos.y, zoom);
editorGet2dScreenCoordinates(&x2,&y2, x2-pos.x,y2-pos.y, zoom);
if (tw==CON_DRAWLINE16Z && m32_sideview)
{
y1 += getscreenvdisp(z1-pos.z,zoom);
y2 += getscreenvdisp(z2-pos.z,zoom);
}
xofs = halfxdim16;
yofs = midydim16;
}
drawlinepat = m32_drawlinepat;
editorDraw2dLine(xofs+x1,yofs+y1, xofs+x2,yofs+y2, col>=0?editorcolors[col&255]:((-col)&255));
drawlinepat = odrawlinepat;
continue;
}
case CON_DRAWLINE256:
insptr++;
{
int32_t x1=Gv_GetVar(*insptr++), y1=Gv_GetVar(*insptr++);
int32_t x2=Gv_GetVar(*insptr++), y2=Gv_GetVar(*insptr++);
int32_t col=Gv_GetVar(*insptr++);
renderDrawLine(x1, y1, x2, y2, col);
continue;
}
case CON_DRAWCIRCLE16:
case CON_DRAWCIRCLE16B:
case CON_DRAWCIRCLE16Z:
insptr++;
{
int32_t x1=Gv_GetVar(*insptr++), y1=Gv_GetVar(*insptr++);
int32_t z1 = tw==CON_DRAWCIRCLE16Z ? Gv_GetVar(*insptr++) : 0;
int32_t r=Gv_GetVar(*insptr++);
int32_t col=Gv_GetVar(*insptr++), odrawlinepat=drawlinepat;
int32_t xofs=0, yofs=0, eccen=16384;
if (tw==CON_DRAWCIRCLE16B || tw==CON_DRAWCIRCLE16Z)
{
editorGet2dScreenCoordinates(&x1,&y1, x1-pos.x,y1-pos.y, zoom);
if (m32_sideview)
y1 += getscreenvdisp(z1-pos.z, zoom);
r = mulscale14(r,zoom);
eccen = scalescreeny(eccen);
xofs = halfxdim16;
yofs = midydim16;
}
drawlinepat = m32_drawlinepat;
editorDraw2dCircle(xofs+x1, yofs+y1, r, eccen, col>=0?editorcolors[col&255]:((-col)&255));
drawlinepat = odrawlinepat;
continue;
}
case CON_ROTATESPRITEA:
case CON_ROTATESPRITE16:
case CON_ROTATESPRITE:
insptr++;
{
int32_t x=Gv_GetVar(*insptr++), y=Gv_GetVar(*insptr++), z=Gv_GetVar(*insptr++);
int32_t a=Gv_GetVar(*insptr++), tilenum=Gv_GetVar(*insptr++), shade=Gv_GetVar(*insptr++);
int32_t pal=Gv_GetVar(*insptr++), orientation=Gv_GetVar(*insptr++);
int32_t alpha = (tw == CON_ROTATESPRITEA) ? Gv_GetVar(*insptr++) : 0;
int32_t x1=Gv_GetVar(*insptr++), y1=Gv_GetVar(*insptr++);
int32_t x2=Gv_GetVar(*insptr++), y2=Gv_GetVar(*insptr++);
if (tw != CON_ROTATESPRITE16 && !(orientation&ROTATESPRITE_FULL16))
{
x<<=16;
y<<=16;
}
orientation &= (ROTATESPRITE_MAX-1);
rotatesprite_(x,y,z,a,tilenum,shade,pal,2|orientation,alpha,0,x1,y1,x2,y2);
continue;
}
case CON_SETGAMEPALETTE:
insptr++;
SetGamePalette(Gv_GetVar(*insptr++));
continue;
// *** sounds
case CON_IFSOUND:
insptr++;
{
int32_t j=Gv_GetVar(*insptr);
if (S_InvalidSound(j))
{
M32_ERROR("Invalid sound %d", j);
insptr++;
continue;
}
VM_DoConditional(S_CheckSoundPlaying(vm.spriteNum,j));
}
continue;
case CON_IFNOSOUNDS:
VM_DoConditional(S_SoundsPlaying(vm.spriteNum) < 0);
continue;
case CON_IFIN3DMODE:
VM_DoConditional(in3dmode());
continue;
case CON_IFIN2D3DMODE:
VM_DoConditional(m32_is2d3dmode());
continue;
// ifaimingsprite and -wall also work in 2d mode, but you must "and" with 16383 yourself
case CON_IFAIMINGSPRITE:
VM_DoConditional(AIMING_AT_SPRITE || (!in3dmode() && pointhighlight>=16384));
continue;
case CON_IFAIMINGWALL:
VM_DoConditional(AIMING_AT_WALL_OR_MASK || (!in3dmode() && linehighlight>=0));
continue;
case CON_IFAIMINGSECTOR:
VM_DoConditional(AIMING_AT_CEILING_OR_FLOOR);
continue;
case CON_IFINTERACTIVE:
VM_DoConditional(vm.miscflags&VMFLAG_MISC_INTERACTIVE);
continue;
case CON_GETSOUNDFLAGS:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++), var=*insptr++;
if (S_InvalidSound(j))
{
M32_ERROR("Invalid sound %d", j);
insptr++;
continue;
}
Gv_SetVar(var, S_SoundFlags(j));
}
continue;
case CON_SOUNDVAR:
case CON_STOPSOUNDVAR:
case CON_SOUNDONCEVAR:
case CON_GLOBALSOUNDVAR:
insptr++;
{
int32_t j=Gv_GetVar(*insptr++);
if (S_InvalidSound(j))
{
M32_ERROR("Invalid sound %d", j);
continue;
}
switch (tw)
{
case CON_SOUNDONCEVAR:
if (!S_CheckSoundPlaying(vm.spriteNum,j))
A_PlaySound((int16_t)j,vm.spriteNum);
break;
case CON_GLOBALSOUNDVAR:
A_PlaySound((int16_t)j,-1);
break;
case CON_STOPSOUNDVAR:
if (S_CheckSoundPlaying(vm.spriteNum,j))
S_StopSound((int16_t)j);
break;
case CON_SOUNDVAR:
A_PlaySound((int16_t)j,vm.spriteNum);
break;
}
}
continue;
case CON_STOPALLSOUNDS:
insptr++;
S_StopAllSounds();
continue;
default:
VM_ScriptInfo();
OSD_Printf("\nAn error has occurred in the Mapster32 virtual machine.\n\n"
"Please e-mail the file mapster32.log along with every M32 file\n"
"you're using and instructions how to reproduce this error to\n"
"development@voidpoint.com.\n\n"
"Thank you!\n");
vm.flags |= VMFLAG_ERROR;
Bfflush(NULL);
return 1;
}
}
return 0;
}
| 1 | 0.953956 | 1 | 0.953956 | game-dev | MEDIA | 0.428293 | game-dev | 0.92727 | 1 | 0.92727 |
tapharmonic/Learning-AV-Foundation | 2,531 | Chapter 2/VoiceMemo_Starter/VoiceMemo/THMeterTable.m | //
// MIT License
//
// Copyright (c) 2014 Bob McCune http://bobmccune.com/
// Copyright (c) 2014 TapHarmonic, LLC http://tapharmonic.com/
//
// 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.
//
// This code is based on Apple's MeterTable.cpp code used by the avTouch and SpeakHere
// sample projects. It creates an internal table storing the precomputed db -> linear
// values.
#import "THMeterTable.h"
#define MIN_DB -60.0f
#define TABLE_SIZE 300
@implementation THMeterTable {
float _scaleFactor;
NSMutableArray *_meterTable;
}
- (id)init {
self = [super init];
if (self) {
float dbResolution = MIN_DB / (TABLE_SIZE - 1);
_meterTable = [NSMutableArray arrayWithCapacity:TABLE_SIZE];
_scaleFactor = 1.0f / dbResolution;
float minAmp = dbToAmp(MIN_DB);
float ampRange = 1.0 - minAmp;
float invAmpRange = 1.0 / ampRange;
for (int i = 0; i < TABLE_SIZE; i++) {
float decibels = i * dbResolution;
float amp = dbToAmp(decibels);
float adjAmp = (amp - minAmp) * invAmpRange;
_meterTable[i] = @(adjAmp);
}
}
return self;
}
float dbToAmp(float dB) {
return powf(10.0f, 0.05f * dB);
}
- (float)valueForPower:(float)power {
if (power < MIN_DB) {
return 0.0f;
} else if (power >= 0.0f) {
return 1.0f;
} else {
int index = (int) (power * _scaleFactor);
return [_meterTable[index] floatValue];
}
}
@end
| 1 | 0.766028 | 1 | 0.766028 | game-dev | MEDIA | 0.300013 | game-dev | 0.884997 | 1 | 0.884997 |
bladecoder/blade-ink-java | 7,430 | src/main/java/com/bladecoder/ink/runtime/Path.java | package com.bladecoder.ink.runtime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Path {
private static final String PARENT_ID = "^";
private final List<Component> components;
private boolean isRelative = false;
private String componentsString;
public Path() {
components = new ArrayList<>();
}
public Path(Component head, Path tail) {
this();
components.add(head);
components.addAll(tail.components);
}
public Path(Collection<Component> components) {
this(components, false);
}
public Path(Collection<Component> components, boolean relative) {
this();
this.components.addAll(components);
this.isRelative = relative;
}
public Path(String componentsString) {
this();
setComponentsString(componentsString);
}
public Component getComponent(int index) {
return components.get(index);
}
public boolean isRelative() {
return isRelative;
}
private void setRelative(boolean value) {
isRelative = value;
}
public Component getHead() {
if (!components.isEmpty()) {
return components.get(0);
} else {
return null;
}
}
public Path getTail() {
if (components.size() >= 2) {
List<Component> tailComps = components.subList(1, components.size());
return new Path(tailComps);
} else {
return Path.getSelf();
}
}
public int getLength() {
return components.size();
}
public Component getLastComponent() {
int lastComponentIdx = components.size() - 1;
if (lastComponentIdx >= 0) return components.get(lastComponentIdx);
else return null;
}
public boolean containsNamedComponent() {
for (Component comp : components) {
if (!comp.isIndex()) {
return true;
}
}
return false;
}
public static Path getSelf() {
Path path = new Path();
path.setRelative(true);
return path;
}
public Path pathByAppendingPath(Path pathToAppend) {
Path p = new Path();
int upwardMoves = 0;
for (int i = 0; i < pathToAppend.components.size(); ++i) {
if (pathToAppend.components.get(i).isParent()) {
upwardMoves++;
} else {
break;
}
}
for (int i = 0; i < this.components.size() - upwardMoves; ++i) {
p.components.add(this.components.get(i));
}
for (int i = upwardMoves; i < pathToAppend.components.size(); ++i) {
p.components.add(pathToAppend.components.get(i));
}
return p;
}
public String getComponentsString() {
if (componentsString == null) {
StringBuilder sb = new StringBuilder();
if (components.size() > 0) {
sb.append(components.get(0));
for (int i = 1; i < components.size(); i++) {
sb.append('.');
sb.append(components.get(i));
}
}
componentsString = sb.toString();
if (isRelative) componentsString = "." + componentsString;
}
return componentsString;
}
private void setComponentsString(String value) {
components.clear();
componentsString = value;
// Empty path, empty components
// (path is to root, like "/" in file system)
if (componentsString == null || componentsString.isEmpty()) return;
// When components start with ".", it indicates a relative path, e.g.
// .^.^.hello.5
// is equivalent to file system style path:
// ../../hello/5
if (componentsString.charAt(0) == '.') {
setRelative(true);
componentsString = componentsString.substring(1);
} else {
setRelative(false);
}
String[] componentStrings = componentsString.split("\\.");
for (String str : componentStrings) {
int index = 0;
try {
index = Integer.parseInt(str);
components.add(new Component(index));
} catch (NumberFormatException e) {
components.add(new Component(str));
}
}
}
@Override
public String toString() {
return getComponentsString();
}
@Override
public boolean equals(Object obj) {
return equals(obj instanceof Path ? (Path) obj : (Path) null);
}
public boolean equals(Path otherPath) {
if (otherPath == null) return false;
if (otherPath.components.size() != this.components.size()) return false;
if (otherPath.isRelative() != this.isRelative()) return false;
// return
// otherPath.components.SequenceEqual(this.components);
for (int i = 0; i < otherPath.components.size(); i++) {
if (!otherPath.components.get(i).equals(components.get(i))) return false;
}
return true;
}
@Override
public int hashCode() {
return toString().hashCode();
}
public Path pathByAppendingComponent(Component c) {
Path p = new Path();
p.components.addAll(components);
p.components.add(c);
return p;
}
// Immutable Component
public static class Component {
private int index;
private String name;
public Component(int index) {
// Debug.Assert(index >= 0);
this.setIndex(index);
this.setName(null);
}
public Component(String name) {
// Debug.Assert(name != null && name.Length > 0);
this.setName(name);
this.setIndex(-1);
}
public int getIndex() {
return index;
}
public void setIndex(int value) {
index = value;
}
public String getName() {
return name;
}
public void setName(String value) {
name = value;
}
public boolean isIndex() {
return getIndex() >= 0;
}
public boolean isParent() {
return Path.PARENT_ID.equals(getName());
}
public static Component toParent() {
return new Component(PARENT_ID);
}
@Override
public String toString() {
if (isIndex()) {
return Integer.toString(getIndex());
} else {
return getName();
}
}
@Override
public boolean equals(Object obj) {
return equals(obj instanceof Component ? (Component) obj : (Component) null);
}
public boolean equals(Component otherComp) {
if (otherComp != null && otherComp.isIndex() == this.isIndex()) {
if (isIndex()) {
return getIndex() == otherComp.getIndex();
} else {
return getName().equals(otherComp.getName());
}
}
return false;
}
@Override
public int hashCode() {
if (isIndex()) return getIndex();
else return getName().hashCode();
}
}
}
| 1 | 0.854808 | 1 | 0.854808 | game-dev | MEDIA | 0.456669 | game-dev | 0.972259 | 1 | 0.972259 |
KittyPBoxx/pokeemerald-net-demo | 253,003 | pokeemerald/src/battle_dome.c | #include "global.h"
#include "battle_dome.h"
#include "battle.h"
#include "battle_main.h"
#include "battle_setup.h"
#include "battle_tower.h"
#include "frontier_util.h"
#include "battle_message.h"
#include "event_data.h"
#include "overworld.h"
#include "util.h"
#include "malloc.h"
#include "string_util.h"
#include "random.h"
#include "task.h"
#include "main.h"
#include "gpu_regs.h"
#include "text.h"
#include "bg.h"
#include "window.h"
#include "strings.h"
#include "palette.h"
#include "decompress.h"
#include "party_menu.h"
#include "menu.h"
#include "sound.h"
#include "pokemon_icon.h"
#include "data.h"
#include "international_string_util.h"
#include "trainer_pokemon_sprites.h"
#include "scanline_effect.h"
#include "script_pokemon_util.h"
#include "graphics.h"
#include "constants/battle_dome.h"
#include "constants/frontier_util.h"
#include "constants/moves.h"
#include "constants/trainers.h"
#include "constants/abilities.h"
#include "constants/songs.h"
#include "constants/battle_frontier.h"
#include "constants/rgb.h"
#define TAG_BUTTONS 0
// Enough space to hold 2 match info cards worth of trainers and their parties
#define NUM_INFOCARD_SPRITES ((FRONTIER_PARTY_SIZE + 1) * 4)
#define NUM_INFOCARD_TRAINERS 2
// An 'Info Card' is a trainer or match information page that can be viewed on the Tourney Tree
struct TourneyTreeInfoCard
{
u8 spriteIds[NUM_INFOCARD_SPRITES];
u8 pos;
u8 tournamentIds[NUM_INFOCARD_TRAINERS];
};
struct TourneyTreeLineSection
{
u8 x;
u8 y;
u16 tile;
};
#define DOME_TRAINERS gSaveBlock2Ptr->frontier.domeTrainers
#define DOME_MONS gSaveBlock2Ptr->frontier.domeMonIds
#define tState data[0]
// Task data for Task_ShowTourneyTree
#define tNotInteractive data[1]
#define tIsPrevTourneyTree data[4]
// Task data for Task_ShowTourneyInfoCard
#define tTournamentId data[1]
#define tMode data[2]
#define tPrevTaskId data[3]
enum {
EFFECTIVENESS_MODE_GOOD,
EFFECTIVENESS_MODE_BAD,
EFFECTIVENESS_MODE_AI_VS_AI,
};
// Window IDs for the tourney tree
enum {
TOURNEYWIN_NAMES_LEFT,
TOURNEYWIN_NAMES_RIGHT,
TOURNEYWIN_TITLE,
};
// Window IDs for the trainer (WIN_TRAINER_*) and match (WIN_MATCH_*) info cards.
// All 9 have a duplicate window at WIN + NUM_INFO_CARD_WINDOWS used by the alternate info card
enum {
WIN_TRAINER_NAME,
WIN_TRAINER_MON1_NAME,
WIN_TRAINER_MON2_NAME, // Used implicitly
WIN_TRAINER_MON3_NAME, // Used implicitly
WIN_TRAINER_FLAVOR_TEXT = WIN_TRAINER_MON1_NAME + FRONTIER_PARTY_SIZE, // Trainer's potential, battle style, and stat texts
WIN_MATCH_NUMBER,
WIN_MATCH_TRAINER_NAME_LEFT,
WIN_MATCH_TRAINER_NAME_RIGHT,
WIN_MATCH_WIN_TEXT,
NUM_INFO_CARD_WINDOWS
};
static u8 GetDomeTrainerMonIvs(u16);
static void SwapDomeTrainers(int, int, u16 *);
static void CalcDomeMonStats(u16, int, int, u8, u8, int *);
static void CreateDomeOpponentMons(u16);
static int SelectOpponentMons_Good(u16, bool8);
static int SelectOpponentMons_Bad(u16, bool8);
static int GetTypeEffectivenessPoints(int, int, int);
static int SelectOpponentMonsFromParty(int *, bool8);
static void Task_ShowTourneyInfoCard(u8);
static void Task_HandleInfoCardInput(u8);
static u8 Task_GetInfoCardInput(u8);
static void SetFacilityTrainerAndMonPtrs(void);
static int TrainerIdToTournamentId(u16);
static u16 TrainerIdOfPlayerOpponent(void);
static void Task_ShowTourneyTree(u8);
static void Task_HandleStaticTourneyTreeInput(u8);
static void CB2_TourneyTree(void);
static void VblankCb_TourneyInfoCard(void);
static void DisplayMatchInfoOnCard(u8, u8);
static void DisplayTrainerInfoOnCard(u8, u8);
static int BufferDomeWinString(u8, u8 *);
static u8 GetDomeBrainTrainerPicId(void);
static u8 GetDomeBrainTrainerClass(void);
static void CopyDomeBrainTrainerName(u8 *);
static void CopyDomeTrainerName(u8 *, u16);
static void HblankCb_TourneyTree(void);
static void VblankCb_TourneyTree(void);
static u8 UpdateTourneyTreeCursor(u8);
static void DecideRoundWinners(u8);
static u8 GetOpposingNPCTournamentIdByRound(u8, u8);
static void DrawTourneyAdvancementLine(u8, u8);
static void SpriteCB_HorizontalScrollArrow(struct Sprite *);
static void SpriteCB_VerticalScrollArrow(struct Sprite *);
static void InitDomeChallenge(void);
static void GetDomeData(void);
static void SetDomeData(void);
static void BufferDomeRoundText(void);
static void BufferDomeOpponentName(void);
static void InitDomeOpponentParty(void);
static void ShowDomeOpponentInfo(void);
static void ShowDomeTourneyTree(void);
static void ShowPreviousDomeTourneyTree(void);
static void SetDomeOpponentId(void);
static void SetDomeOpponentGraphicsId(void);
static void ShowNonInteractiveDomeTourneyTree(void);
static void ResolveDomeRoundWinners(void);
static void SaveDomeChallenge(void);
static void IncrementDomeStreaks(void);
static void ResetSketchedMoves(void);
static void RestoreDomePlayerPartyHeldItems(void);
static void ReduceDomePlayerPartyToSelectedMons(void);
static void GetPlayerSeededBeforeOpponent(void);
static void BufferLastDomeWinnerName(void);
static void InitRandomTourneyTreeResults(void);
static void InitDomeTrainers(void);
EWRAM_DATA u32 gPlayerPartyLostHP = 0; // never read
static EWRAM_DATA u32 sPlayerPartyMaxHP = 0; // never read
static EWRAM_DATA struct TourneyTreeInfoCard *sInfoCard = {0};
static EWRAM_DATA u8 *sTilemapBuffer = NULL;
// Each move has an array of points for different move characteristics which contribute to a tourney trainers listed battle style (see sBattleStyleThresholds)
// All move points are either 1 or 0, so theyre essentially flags saying whether or not the move has that characteristic
static const u8 sBattleStyleMovePoints[MOVES_COUNT][NUM_MOVE_POINT_TYPES] =
{
[MOVE_NONE] = {0},
[MOVE_POUND] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_KARATE_CHOP] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_DOUBLE_SLAP] = {[MOVE_POINTS_DMG] = 1},
[MOVE_COMET_PUNCH] = {[MOVE_POINTS_DMG] = 1},
[MOVE_MEGA_PUNCH] = {[MOVE_POINTS_DMG] = 1},
[MOVE_PAY_DAY] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_FIRE_PUNCH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_ICE_PUNCH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_THUNDER_PUNCH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SCRATCH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_VICE_GRIP] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_GUILLOTINE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_RAZOR_WIND] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_SWORDS_DANCE] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_STAT_RAISE] = 1, [MOVE_POINTS_POPULAR] = 1},
[MOVE_CUT] = {[MOVE_POINTS_DMG] = 1},
[MOVE_GUST] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_WING_ATTACK] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_WHIRLWIND] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_FLY] = {[MOVE_POINTS_DMG] = 1},
[MOVE_BIND] = {[MOVE_POINTS_STATUS] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SLAM] = {[MOVE_POINTS_DMG] = 1},
[MOVE_VINE_WHIP] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_STOMP] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_DOUBLE_KICK] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_MEGA_KICK] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_JUMP_KICK] = {[MOVE_POINTS_DMG] = 1},
[MOVE_ROLLING_KICK] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SAND_ATTACK] = {[MOVE_POINTS_STAT_LOWER] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_HEADBUTT] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_HORN_ATTACK] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_FURY_ATTACK] = {[MOVE_POINTS_DMG] = 1},
[MOVE_HORN_DRILL] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_TACKLE] = {[MOVE_POINTS_DMG] = 1},
[MOVE_BODY_SLAM] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_WRAP] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_TAKE_DOWN] = {[MOVE_POINTS_DMG] = 1},
[MOVE_THRASH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_DOUBLE_EDGE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_TAIL_WHIP] = {[MOVE_POINTS_STAT_LOWER] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_POISON_STING] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_TWINEEDLE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_PIN_MISSILE] = {[MOVE_POINTS_DMG] = 1},
[MOVE_LEER] = {[MOVE_POINTS_STAT_LOWER] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_BITE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_GROWL] = {[MOVE_POINTS_STAT_LOWER] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_ROAR] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_SING] = {[MOVE_POINTS_STATUS] = 1},
[MOVE_SUPERSONIC] = {[MOVE_POINTS_STATUS] = 1},
[MOVE_SONIC_BOOM] = {[MOVE_POINTS_DMG] = 1},
[MOVE_DISABLE] = {[MOVE_POINTS_STATUS] = 1},
[MOVE_ACID] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_EMBER] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_FLAMETHROWER] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_POPULAR] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_MIST] = {0},
[MOVE_WATER_GUN] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_HYDRO_PUMP] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_SURF] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_POPULAR] = 1, [MOVE_POINTS_STRONG] = 1},
[MOVE_ICE_BEAM] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_POPULAR] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_BLIZZARD] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_LOW_PP] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_PSYBEAM] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_BUBBLE_BEAM] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_AURORA_BEAM] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_HYPER_BEAM] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_POPULAR] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_PECK] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_DRILL_PECK] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_SUBMISSION] = {[MOVE_POINTS_DMG] = 1},
[MOVE_LOW_KICK] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_COUNTER] = {[MOVE_POINTS_DEF] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LUCK] = 1},
[MOVE_SEISMIC_TOSS] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_STRENGTH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_ABSORB] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_MEGA_DRAIN] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_LEECH_SEED] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_STATUS] = 1},
[MOVE_GROWTH] = {[MOVE_POINTS_STAT_RAISE] = 1},
[MOVE_RAZOR_LEAF] = {[MOVE_POINTS_DMG] = 1},
[MOVE_SOLAR_BEAM] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_POPULAR] = 1, [MOVE_POINTS_STRONG] = 1},
[MOVE_POISON_POWDER] = {[MOVE_POINTS_STATUS] = 1},
[MOVE_STUN_SPORE] = {[MOVE_POINTS_STATUS] = 1},
[MOVE_SLEEP_POWDER] = {[MOVE_POINTS_STATUS] = 1},
[MOVE_PETAL_DANCE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_STRING_SHOT] = {[MOVE_POINTS_STAT_LOWER] = 1},
[MOVE_DRAGON_RAGE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_FIRE_SPIN] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_THUNDER_SHOCK] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_THUNDERBOLT] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_POPULAR] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_THUNDER_WAVE] = {[MOVE_POINTS_STATUS] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_THUNDER] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_ROCK_THROW] = {[MOVE_POINTS_DMG] = 1},
[MOVE_EARTHQUAKE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_POPULAR] = 1, [MOVE_POINTS_STRONG] = 1},
[MOVE_FISSURE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_LUCK] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_DIG] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_TOXIC] = {[MOVE_POINTS_STATUS] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_CONFUSION] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_PSYCHIC] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_POPULAR] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_HYPNOSIS] = {[MOVE_POINTS_COMBO] = 1},
[MOVE_MEDITATE] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_STAT_RAISE] = 1},
[MOVE_AGILITY] = {[MOVE_POINTS_STAT_RAISE] = 1},
[MOVE_QUICK_ATTACK] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_RAGE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_TELEPORT] = {0},
[MOVE_NIGHT_SHADE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_MIMIC] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_SCREECH] = {[MOVE_POINTS_STAT_LOWER] = 1},
[MOVE_DOUBLE_TEAM] = {[MOVE_POINTS_STAT_RAISE] = 1, [MOVE_POINTS_DEF] = 1},
[MOVE_RECOVER] = {0},
[MOVE_HARDEN] = {[MOVE_POINTS_STAT_RAISE] = 1, [MOVE_POINTS_DEF] = 1},
[MOVE_MINIMIZE] = {[MOVE_POINTS_STAT_RAISE] = 1, [MOVE_POINTS_DEF] = 1},
[MOVE_SMOKESCREEN] = {[MOVE_POINTS_STAT_LOWER] = 1, [MOVE_POINTS_DEF] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_CONFUSE_RAY] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_WITHDRAW] = {[MOVE_POINTS_STAT_RAISE] = 1, [MOVE_POINTS_DEF] = 1},
[MOVE_DEFENSE_CURL] = {[MOVE_POINTS_STAT_RAISE] = 1, [MOVE_POINTS_DEF] = 1},
[MOVE_BARRIER] = {[MOVE_POINTS_DEF] = 1},
[MOVE_LIGHT_SCREEN] = {[MOVE_POINTS_DEF] = 1},
[MOVE_HAZE] = {0},
[MOVE_REFLECT] = {[MOVE_POINTS_DEF] = 1},
[MOVE_FOCUS_ENERGY] = {[MOVE_POINTS_COMBO] = 1},
[MOVE_BIDE] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_METRONOME] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_LUCK] = 1},
[MOVE_MIRROR_MOVE] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_LUCK] = 1},
[MOVE_SELF_DESTRUCT] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_EGG_BOMB] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1},
[MOVE_LICK] = {[MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SMOG] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SLUDGE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_BONE_CLUB] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_FIRE_BLAST] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_WATERFALL] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_CLAMP] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SWIFT] = {[MOVE_POINTS_DMG] = 1},
[MOVE_SKULL_BASH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_STRONG] = 1},
[MOVE_SPIKE_CANNON] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_CONSTRICT] = {[MOVE_POINTS_STATUS] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_AMNESIA] = {[MOVE_POINTS_STAT_RAISE] = 1, [MOVE_POINTS_DEF] = 1},
[MOVE_KINESIS] = {[MOVE_POINTS_STAT_LOWER] = 1},
[MOVE_SOFT_BOILED] = {[MOVE_POINTS_HEAL] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_HI_JUMP_KICK] = {[MOVE_POINTS_DMG] = 1},
[MOVE_GLARE] = {[MOVE_POINTS_STAT_LOWER] = 1},
[MOVE_DREAM_EATER] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_RARE] = 1, [MOVE_POINTS_HEAL] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_STRONG] = 1},
[MOVE_POISON_GAS] = {[MOVE_POINTS_STATUS] = 1},
[MOVE_BARRAGE] = {[MOVE_POINTS_DMG] = 1},
[MOVE_LEECH_LIFE] = {[MOVE_POINTS_HEAL] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_LOVELY_KISS] = {[MOVE_POINTS_STATUS] = 1},
[MOVE_SKY_ATTACK] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_TRANSFORM] = {[MOVE_POINTS_RARE] = 1},
[MOVE_BUBBLE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_DIZZY_PUNCH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SPORE] = {[MOVE_POINTS_STATUS] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_FLASH] = {0},
[MOVE_PSYWAVE] = {[MOVE_POINTS_DMG] = 1},
[MOVE_SPLASH] = {[MOVE_POINTS_RARE] = 1},
[MOVE_ACID_ARMOR] = {[MOVE_POINTS_STAT_RAISE] = 1, [MOVE_POINTS_DEF] = 1},
[MOVE_CRABHAMMER] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_STRONG] = 1},
[MOVE_EXPLOSION] = {[MOVE_POINTS_RISKY] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_POPULAR] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_FURY_SWIPES] = {[MOVE_POINTS_DMG] = 1},
[MOVE_BONEMERANG] = {[MOVE_POINTS_DMG] = 1},
[MOVE_REST] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_HEAL] = 1},
[MOVE_ROCK_SLIDE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_HYPER_FANG] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SHARPEN] = {[MOVE_POINTS_STAT_RAISE] = 1, [MOVE_POINTS_DEF] = 1},
[MOVE_CONVERSION] = {[MOVE_POINTS_DEF] = 1},
[MOVE_TRI_ATTACK] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SUPER_FANG] = {[MOVE_POINTS_DMG] = 1},
[MOVE_SLASH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_SUBSTITUTE] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_DEF] = 1},
[MOVE_STRUGGLE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LOW_PP] = 1}, // Odd that this is assigned qualities
[MOVE_SKETCH] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_LUCK] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_TRIPLE_KICK] = {[MOVE_POINTS_DMG] = 1},
[MOVE_THIEF] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SPIDER_WEB] = {[MOVE_POINTS_STAT_LOWER] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_MIND_READER] = {[MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_NIGHTMARE] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_STATUS] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_FLAME_WHEEL] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SNORE] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_CURSE] = {[MOVE_POINTS_STATUS] = 1},
[MOVE_FLAIL] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_CONVERSION_2] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_AEROBLAST] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_COTTON_SPORE] = {[MOVE_POINTS_STAT_LOWER] = 1},
[MOVE_REVERSAL] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_SPITE] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_RISKY] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_POWDER_SNOW] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_PROTECT] = {[MOVE_POINTS_DEF] = 1, [MOVE_POINTS_POPULAR] = 1},
[MOVE_MACH_PUNCH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_SCARY_FACE] = {0},
[MOVE_FAINT_ATTACK] = {[MOVE_POINTS_DMG] = 1},
[MOVE_SWEET_KISS] = {0},
[MOVE_BELLY_DRUM] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_STAT_RAISE] = 1},
[MOVE_SLUDGE_BOMB] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_MUD_SLAP] = {[MOVE_POINTS_STAT_LOWER] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_OCTAZOOKA] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SPIKES] = {[MOVE_POINTS_COMBO] = 1},
[MOVE_ZAP_CANNON] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_LUCK] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_FORESIGHT] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_DESTINY_BOND] = {[MOVE_POINTS_RISKY] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_PERISH_SONG] = {[MOVE_POINTS_RISKY] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_ICY_WIND] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_DETECT] = {[MOVE_POINTS_DEF] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_BONE_RUSH] = {[MOVE_POINTS_DMG] = 1},
[MOVE_LOCK_ON] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_OUTRAGE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SANDSTORM] = {0},
[MOVE_GIGA_DRAIN] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_ENDURE] = {[MOVE_POINTS_DEF] = 1},
[MOVE_CHARM] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_ROLLOUT] = {[MOVE_POINTS_DMG] = 1},
[MOVE_FALSE_SWIPE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_SWAGGER] = {[MOVE_POINTS_EFFECT] = 1},
[MOVE_MILK_DRINK] = {[MOVE_POINTS_HEAL] = 1},
[MOVE_SPARK] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_FURY_CUTTER] = {[MOVE_POINTS_DMG] = 1},
[MOVE_STEEL_WING] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_MEAN_LOOK] = {[MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_ATTRACT] = {[MOVE_POINTS_STATUS] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_SLEEP_TALK] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_LUCK] = 1},
[MOVE_HEAL_BELL] = {[MOVE_POINTS_LOW_PP] = 1},
[MOVE_RETURN] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_PRESENT] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_LUCK] = 1},
[MOVE_FRUSTRATION] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_SAFEGUARD] = {[MOVE_POINTS_DEF] = 1},
[MOVE_PAIN_SPLIT] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_SACRED_FIRE] = {[MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_MAGNITUDE] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_DYNAMIC_PUNCH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_LUCK] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_MEGAHORN] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_STRONG] = 1},
[MOVE_DRAGON_BREATH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_BATON_PASS] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_RARE] = 1},
[MOVE_ENCORE] = {[MOVE_POINTS_STATUS] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_PURSUIT] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_RAPID_SPIN] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_SWEET_SCENT] = {[MOVE_POINTS_STAT_LOWER] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_IRON_TAIL] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_METAL_CLAW] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_VITAL_THROW] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_MORNING_SUN] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_HEAL] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_SYNTHESIS] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_HEAL] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_MOONLIGHT] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_HEAL] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_HIDDEN_POWER] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_CROSS_CHOP] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_TWISTER] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_RAIN_DANCE] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_SUNNY_DAY] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_CRUNCH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_MIRROR_COAT] = {[MOVE_POINTS_DEF] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_PSYCH_UP] = {[MOVE_POINTS_STAT_RAISE] = 1},
[MOVE_EXTREME_SPEED] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_ANCIENT_POWER] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LOW_PP] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SHADOW_BALL] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_FUTURE_SIGHT] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_DMG] = 1},
[MOVE_ROCK_SMASH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_WHIRLPOOL] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_BEAT_UP] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_FAKE_OUT] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_UPROAR] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_STOCKPILE] = {[MOVE_POINTS_COMBO] = 1},
[MOVE_SPIT_UP] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_STRONG] = 1},
[MOVE_SWALLOW] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_HEAL] = 1},
[MOVE_HEAT_WAVE] = {[MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_HAIL] = {0},
[MOVE_TORMENT] = {[MOVE_POINTS_STATUS] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_FLATTER] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_WILL_O_WISP] = {[MOVE_POINTS_STATUS] = 1},
[MOVE_MEMENTO] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_FACADE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_FOCUS_PUNCH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_STRONG] = 1},
[MOVE_SMELLING_SALT] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_FOLLOW_ME] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_NATURE_POWER] = {[MOVE_POINTS_DMG] = 1},
[MOVE_CHARGE] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_TAUNT] = {[MOVE_POINTS_STATUS] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_HELPING_HAND] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_TRICK] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_ROLE_PLAY] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_WISH] = {[MOVE_POINTS_HEAL] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_ASSIST] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LUCK] = 1},
[MOVE_INGRAIN] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_HEAL] = 1, [MOVE_POINTS_DEF] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_SUPERPOWER] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_MAGIC_COAT] = {[MOVE_POINTS_DEF] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LUCK] = 1},
[MOVE_RECYCLE] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_REVENGE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LUCK] = 1},
[MOVE_BRICK_BREAK] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_YAWN] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_STATUS] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_KNOCK_OFF] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_ENDEAVOR] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_ERUPTION] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_SKILL_SWAP] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_IMPRISON] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LUCK] = 1},
[MOVE_REFRESH] = {[MOVE_POINTS_HEAL] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_GRUDGE] = {[MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_SNATCH] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LUCK] = 1},
[MOVE_SECRET_POWER] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_DIVE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_ARM_THRUST] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_CAMOUFLAGE] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_TAIL_GLOW] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_LUSTER_PURGE] = {[MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LOW_PP] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_MIST_BALL] = {[MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LOW_PP] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_FEATHER_DANCE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_TEETER_DANCE] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_BLAZE_KICK] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_MUD_SPORT] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_ICE_BALL] = {[MOVE_POINTS_DMG] = 1},
[MOVE_NEEDLE_ARM] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SLACK_OFF] = {[MOVE_POINTS_HEAL] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_HYPER_VOICE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_STRONG] = 1},
[MOVE_POISON_FANG] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_CRUSH_CLAW] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_BLAST_BURN] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_HYDRO_CANNON] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_METEOR_MASH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_ASTONISH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_WEATHER_BALL] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_AROMATHERAPY] = {[MOVE_POINTS_LOW_PP] = 1},
[MOVE_FAKE_TEARS] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_AIR_CUTTER] = {[MOVE_POINTS_DMG] = 1},
[MOVE_OVERHEAT] = {[MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_ODOR_SLEUTH] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_ROCK_TOMB] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SILVER_WIND] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LOW_PP] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_METAL_SOUND] = {0},
[MOVE_GRASS_WHISTLE] = {0},
[MOVE_TICKLE] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_COSMIC_POWER] = {0},
[MOVE_WATER_SPOUT] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_SIGNAL_BEAM] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SHADOW_PUNCH] = {[MOVE_POINTS_DMG] = 1},
[MOVE_EXTRASENSORY] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SKY_UPPERCUT] = {[MOVE_POINTS_DMG] = 1},
[MOVE_SAND_TOMB] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_SHEER_COLD] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_LUCK] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_MUDDY_WATER] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_BULLET_SEED] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_AERIAL_ACE] = {[MOVE_POINTS_DMG] = 1},
[MOVE_ICICLE_SPEAR] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_IRON_DEFENSE] = {[MOVE_POINTS_DEF] = 1},
[MOVE_BLOCK] = {[MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_HOWL] = {0},
[MOVE_DRAGON_CLAW] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_FRENZY_PLANT] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_BULK_UP] = {[MOVE_POINTS_COMBO] = 1},
[MOVE_BOUNCE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_LOW_PP] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_MUD_SHOT] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_POISON_TAIL] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_COVET] = {[MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_VOLT_TACKLE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1},
[MOVE_MAGICAL_LEAF] = {[MOVE_POINTS_DMG] = 1},
[MOVE_WATER_SPORT] = {[MOVE_POINTS_ACCURATE] = 1},
[MOVE_CALM_MIND] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_STAT_RAISE] = 1},
[MOVE_LEAF_BLADE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1},
[MOVE_DRAGON_DANCE] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_STAT_RAISE] = 1},
[MOVE_ROCK_BLAST] = {[MOVE_POINTS_DMG] = 1},
[MOVE_SHOCK_WAVE] = {[MOVE_POINTS_DMG] = 1},
[MOVE_WATER_PULSE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_EFFECT] = 1},
[MOVE_DOOM_DESIRE] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1},
[MOVE_PSYCHO_BOOST] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_LOW_PP] = 1, [MOVE_POINTS_EFFECT] = 1},
};
// This array is searched in-order to determine what battle style a tourney trainer uses.
// If the sum of the points for the party's moves meets/exceeds all the point totals of an element, then they use that battle style
static const u8 sBattleStyleThresholds[NUM_BATTLE_STYLES - 1][NUM_MOVE_POINT_TYPES] =
{
[DOME_BATTLE_STYLE_RISKY] = {[MOVE_POINTS_RISKY] = 1},
[DOME_BATTLE_STYLE_STALL] = {[MOVE_POINTS_HEAL] = 2, [MOVE_POINTS_STATUS] = 1, [MOVE_POINTS_DEF] = 2},
[DOME_BATTLE_STYLE_VARIED] = {[MOVE_POINTS_COMBO] = 1, [MOVE_POINTS_STAT_RAISE] = 1, [MOVE_POINTS_STAT_LOWER] = 1, [MOVE_POINTS_HEAL] = 1, [MOVE_POINTS_STATUS] = 1, [MOVE_POINTS_DEF] = 1},
[DOME_BATTLE_STYLE_COMBO_HIGH] = {[MOVE_POINTS_COMBO] = 3},
[DOME_BATTLE_STYLE_RARE_MOVES] = {[MOVE_POINTS_RARE] = 2},
[DOME_BATTLE_STYLE_RARE_MOVE] = {[MOVE_POINTS_RARE] = 1},
[DOME_BATTLE_STYLE_HP] = {[MOVE_POINTS_HEAL] = 3},
[DOME_BATTLE_STYLE_STORE_POWER] = {[MOVE_POINTS_STAT_RAISE] = 1, [MOVE_POINTS_HEAL] = 1},
[DOME_BATTLE_STYLE_ENFEEBLE_LOW] = {[MOVE_POINTS_STAT_LOWER] = 1, [MOVE_POINTS_STATUS] = 1},
[DOME_BATTLE_STYLE_LUCK] = {[MOVE_POINTS_LUCK] = 2},
[DOME_BATTLE_STYLE_REGAL] = {[MOVE_POINTS_STAT_RAISE] = 1, [MOVE_POINTS_HEAL] = 1, [MOVE_POINTS_DEF] = 1, [MOVE_POINTS_POPULAR] = 1, [MOVE_POINTS_STRONG] = 1},
[DOME_BATTLE_STYLE_LOW_PP] = {[MOVE_POINTS_LOW_PP] = 3},
[DOME_BATTLE_STYLE_STATUS_ATK] = {[MOVE_POINTS_STAT_RAISE] = 1, [MOVE_POINTS_STATUS] = 1},
[DOME_BATTLE_STYLE_ENDURE] = {[MOVE_POINTS_HEAL] = 2, [MOVE_POINTS_DEF] = 2},
[DOME_BATTLE_STYLE_STATUS] = {[MOVE_POINTS_STATUS] = 2},
[DOME_BATTLE_STYLE_STRAIGHTFORWARD] = {[MOVE_POINTS_ACCURATE] = 3, [MOVE_POINTS_STRONG] = 3},
[DOME_BATTLE_STYLE_AGGRESSIVE] = {[MOVE_POINTS_STRONG] = 4},
[DOME_BATTLE_STYLE_DEF] = {[MOVE_POINTS_DEF] = 3},
[DOME_BATTLE_STYLE_ENFEEBLE_HIGH] = {[MOVE_POINTS_STAT_LOWER] = 2, [MOVE_POINTS_STATUS] = 2}, // BUG: This battle style is unobtainable; DOME_BATTLE_STYLE_ENFEEBLE_LOW will always succeed before it
[DOME_BATTLE_STYLE_POPULAR_POWER] = {[MOVE_POINTS_POWERFUL] = 3, [MOVE_POINTS_POPULAR] = 3},
[DOME_BATTLE_STYLE_COMBO_LOW] = {[MOVE_POINTS_COMBO] = 2},
[DOME_BATTLE_STYLE_ACCURATE] = {[MOVE_POINTS_HEAL] = 1, [MOVE_POINTS_ACCURATE] = 3},
[DOME_BATTLE_STYLE_POWERFUL] = {[MOVE_POINTS_POWERFUL] = 4},
[DOME_BATTLE_STYLE_ATK_OVER_DEF] = {[MOVE_POINTS_DMG] = 7},
[DOME_BATTLE_STYLE_DEF_OVER_ATK] = {[MOVE_POINTS_DEF] = 4}, // BUG: This battle style is unobtainable; DOME_BATTLE_STYLE_DEF will always succeed before it
[DOME_BATTLE_STYLE_POPULAR_STRONG] = {[MOVE_POINTS_POPULAR] = 2, [MOVE_POINTS_STRONG] = 4},
[DOME_BATTLE_STYLE_EFFECTS] = {[MOVE_POINTS_EFFECT] = 4},
[DOME_BATTLE_STYLE_BALANCED] = {0}, // If no other thresholds are met, this battle style is used
[DOME_BATTLE_STYLE_UNUSED1] = {0}, // Here below is unreachable
[DOME_BATTLE_STYLE_UNUSED2] = {0},
[DOME_BATTLE_STYLE_UNUSED3] = {0},
//[DOME_BATTLE_STYLE_UNUSED4] = {0}, // Excluded here, presumably was meant to be a style just for Dome Ace Tucker
};
static const u8 sUnusedArray[] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0,
0, 0, 3, 0, 0, 0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 2,
0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0,
0, 2, 253, 0, 0, 0, 0, 0, 253, 0, 0, 0, 0, 0, 253, 0,
0, 0, 0, 0, 253, 0, 0, 0, 0, 0, 253, 254, 0, 0, 0, 0,
0, 254, 0, 0, 0, 0, 0, 254, 0, 0, 0, 0, 0, 254, 0, 0,
0, 0, 0, 254, 0, 0, 0, 0, 0,
};
// 1st array is for cursor position (sprite id): cursor can be on a trainer info button, a match info button, or the exit/cancel button
// 2nd array is for round count. For some reason this array contains an inaccessible Round 5 which is identical to Round 4
// 3rd array is movement direction (see the MOVE_DIR_* constants in UpdateTourneyTreeCursor)
// The values are sprite IDs for the cursor position to move to, with 0xFF being an invalid move
static const u8 sTourneyTreeCursorMovementMap[DOME_TOURNAMENT_TRAINERS_COUNT + DOME_TOURNAMENT_MATCHES_COUNT + 1][DOME_ROUNDS_COUNT + 1][4]=
{
[0] = {{ 7, 1, 8, 16}, { 7, 1, 8, 16}, { 7, 1, 8, 16}, { 7, 1, 8, 16}, { 7, 1, 8, 16}},
[1] = {{ 0, 2, 9, 16}, { 0, 2, 9, 16}, { 0, 2, 9, 16}, { 0, 2, 9, 16}, { 0, 2, 9, 16}},
[2] = {{ 1, 3, 10, 17}, { 1, 3, 10, 17}, { 1, 3, 10, 17}, { 1, 3, 10, 17}, { 1, 3, 10, 17}},
[3] = {{ 2, 4, 11, 17}, { 2, 4, 11, 17}, { 2, 4, 11, 17}, { 2, 4, 11, 17}, { 2, 4, 11, 17}},
[4] = {{ 3, 5, 12, 18}, { 3, 5, 12, 18}, { 3, 5, 12, 18}, { 3, 5, 12, 18}, { 3, 5, 12, 18}},
[5] = {{ 4, 6, 13, 18}, { 4, 6, 13, 18}, { 4, 6, 13, 18}, { 4, 6, 13, 18}, { 4, 6, 13, 18}},
[6] = {{ 5, 7, 14, 19}, { 5, 7, 14, 19}, { 5, 7, 14, 19}, { 5, 7, 14, 19}, { 5, 7, 14, 19}},
[7] = {{ 6, 0, 15, 19}, { 6, 0, 15, 19}, { 6, 0, 15, 19}, { 6, 0, 15, 19}, { 6, 0, 15, 19}},
[8] = {{ 31, 9, 20, 31}, { 31, 9, 20, 31}, { 31, 9, 20, 31}, { 31, 9, 20, 31}, { 31, 9, 20, 31}},
[9] = {{ 8, 10, 20, 1}, { 8, 10, 20, 1}, { 8, 10, 20, 1}, { 8, 10, 20, 1}, { 8, 10, 20, 1}},
[10] = {{ 9, 11, 21, 2}, { 9, 11, 21, 2}, { 9, 11, 21, 2}, { 9, 11, 21, 2}, { 9, 11, 21, 2}},
[11] = {{ 10, 12, 21, 3}, { 10, 12, 21, 3}, { 10, 12, 21, 3}, { 10, 12, 21, 3}, { 10, 12, 21, 3}},
[12] = {{ 11, 13, 22, 4}, { 11, 13, 22, 4}, { 11, 13, 22, 4}, { 11, 13, 22, 4}, { 11, 13, 22, 4}},
[13] = {{ 12, 14, 22, 5}, { 12, 14, 22, 5}, { 12, 14, 22, 5}, { 12, 14, 22, 5}, { 12, 14, 22, 5}},
[14] = {{ 13, 15, 23, 6}, { 13, 15, 23, 6}, { 13, 15, 23, 6}, { 13, 15, 23, 6}, { 13, 15, 23, 6}},
[15] = {{ 14, 31, 23, 7}, { 14, 31, 23, 7}, { 14, 31, 23, 7}, { 14, 31, 23, 7}, { 14, 31, 23, 7}},
[16] = {{ 19, 17, 0, 20}, { 19, 17, 0, 24}, { 19, 17, 0, 24}, { 19, 17, 0, 24}, { 19, 17, 0, 24}},
[17] = {{ 16, 18, 2, 21}, { 16, 18, 2, 24}, { 16, 18, 2, 24}, { 16, 18, 2, 24}, { 16, 18, 2, 24}},
[18] = {{ 17, 19, 4, 22}, { 17, 19, 4, 25}, { 17, 19, 4, 25}, { 17, 19, 4, 25}, { 17, 19, 4, 25}},
[19] = {{ 18, 16, 6, 23}, { 18, 16, 6, 25}, { 18, 16, 6, 25}, { 18, 16, 6, 25}, { 18, 16, 6, 25}},
[20] = {{ 23, 21, 16, 8}, { 23, 21, 26, 8}, { 23, 21, 26, 8}, { 23, 21, 26, 8}, { 23, 21, 26, 8}},
[21] = {{ 20, 22, 17, 10}, { 20, 22, 26, 10}, { 20, 22, 26, 10}, { 20, 22, 26, 10}, { 20, 22, 26, 10}},
[22] = {{ 21, 23, 18, 12}, { 21, 23, 27, 12}, { 21, 23, 27, 12}, { 21, 23, 27, 12}, { 21, 23, 27, 12}},
[23] = {{ 22, 20, 19, 14}, { 22, 20, 27, 14}, { 22, 20, 27, 14}, { 22, 20, 27, 14}, { 22, 20, 27, 14}},
[24] = {{0xFF, 0xFF, 0xFF, 0xFF}, { 25, 25, 16, 26}, { 25, 25, 16, 28}, { 25, 25, 16, 28}, { 25, 25, 16, 28}},
[25] = {{0xFF, 0xFF, 0xFF, 0xFF}, { 24, 24, 18, 27}, { 24, 24, 18, 28}, { 24, 24, 18, 28}, { 24, 24, 18, 28}},
[26] = {{0xFF, 0xFF, 0xFF, 0xFF}, { 27, 27, 24, 20}, { 27, 27, 29, 20}, { 27, 27, 29, 20}, { 27, 27, 29, 20}},
[27] = {{0xFF, 0xFF, 0xFF, 0xFF}, { 26, 26, 25, 22}, { 26, 26, 29, 22}, { 26, 26, 29, 22}, { 26, 26, 29, 22}},
[28] = {{0xFF, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 24, 29}, {0xFF, 0xFF, 24, 30}, {0xFF, 0xFF, 24, 30}},
[29] = {{0xFF, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 28, 26}, {0xFF, 0xFF, 30, 26}, {0xFF, 0xFF, 30, 26}},
[30] = {{0xFF, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 28, 29}, {0xFF, 0xFF, 28, 29}},
[31] = {{ 15, 8, 8, 0}, { 15, 8, 8, 0}, { 15, 8, 8, 0}, { 15, 8, 8, 0}, { 15, 8, 8, 0}}, // TOURNEY_TREE_CLOSE_BUTTON
};
static const struct BgTemplate sTourneyTreeBgTemplates[4] =
{
{
.bg = 0,
.charBaseIndex = 0,
.mapBaseIndex = 28,
.screenSize = 0,
.paletteMode = 0,
.priority = 0,
.baseTile = 0
},
{
.bg = 1,
.charBaseIndex = 1,
.mapBaseIndex = 29,
.screenSize = 0,
.paletteMode = 0,
.priority = 1,
.baseTile = 0
},
{
.bg = 2,
.charBaseIndex = 2,
.mapBaseIndex = 30,
.screenSize = 0,
.paletteMode = 0,
.priority = 2,
.baseTile = 0
},
{
.bg = 3,
.charBaseIndex = 2,
.mapBaseIndex = 31,
.screenSize = 0,
.paletteMode = 0,
.priority = 2,
.baseTile = 0
},
};
static const struct BgTemplate sInfoCardBgTemplates[4] =
{
{
.bg = 0,
.charBaseIndex = 0,
.mapBaseIndex = 20,
.screenSize = 3,
.paletteMode = 0,
.priority = 0,
.baseTile = 0
},
{
.bg = 1,
.charBaseIndex = 1,
.mapBaseIndex = 24,
.screenSize = 3,
.paletteMode = 0,
.priority = 0,
.baseTile = 0
},
{
.bg = 2,
.charBaseIndex = 2,
.mapBaseIndex = 28,
.screenSize = 3,
.paletteMode = 0,
.priority = 1,
.baseTile = 0
},
{
.bg = 3,
.charBaseIndex = 2,
.mapBaseIndex = 7,
.screenSize = 0,
.paletteMode = 0,
.priority = 1,
.baseTile = 0
},
};
static const struct WindowTemplate sTourneyTreeWindowTemplates[] =
{
[TOURNEYWIN_NAMES_LEFT] = {
.bg = 0,
.tilemapLeft = 0,
.tilemapTop = 3,
.width = 8,
.height = 16,
.paletteNum = 15,
.baseBlock = 16,
},
[TOURNEYWIN_NAMES_RIGHT] = {
.bg = 0,
.tilemapLeft = 22,
.tilemapTop = 3,
.width = 8,
.height = 16,
.paletteNum = 15,
.baseBlock = 144,
},
[TOURNEYWIN_TITLE] = {
.bg = 0,
.tilemapLeft = 8,
.tilemapTop = 1,
.width = 14,
.height = 2,
.paletteNum = 15,
.baseBlock = 272,
},
DUMMY_WIN_TEMPLATE,
};
static const struct WindowTemplate sInfoCardWindowTemplates[] =
{
[WIN_TRAINER_NAME] = {
.bg = 0,
.tilemapLeft = 2,
.tilemapTop = 2,
.width = 26,
.height = 2,
.paletteNum = 15,
.baseBlock = 1,
},
[WIN_TRAINER_MON1_NAME] = {
.bg = 0,
.tilemapLeft = 16,
.tilemapTop = 5,
.width = 8,
.height = 2,
.paletteNum = 15,
.baseBlock = 53,
},
[WIN_TRAINER_MON2_NAME] = {
.bg = 0,
.tilemapLeft = 19,
.tilemapTop = 7,
.width = 9,
.height = 3,
.paletteNum = 15,
.baseBlock = 69,
},
[WIN_TRAINER_MON3_NAME] = {
.bg = 0,
.tilemapLeft = 16,
.tilemapTop = 10,
.width = 8,
.height = 2,
.paletteNum = 15,
.baseBlock = 96,
},
[WIN_TRAINER_FLAVOR_TEXT] = {
.bg = 0,
.tilemapLeft = 2,
.tilemapTop = 12,
.width = 26,
.height = 7,
.paletteNum = 15,
.baseBlock = 112,
},
[WIN_MATCH_NUMBER] = {
.bg = 0,
.tilemapLeft = 5,
.tilemapTop = 2,
.width = 23,
.height = 2,
.paletteNum = 15,
.baseBlock = 294,
},
[WIN_MATCH_TRAINER_NAME_LEFT] = {
.bg = 0,
.tilemapLeft = 2,
.tilemapTop = 5,
.width = 8,
.height = 2,
.paletteNum = 15,
.baseBlock = 340,
},
[WIN_MATCH_TRAINER_NAME_RIGHT] = {
.bg = 0,
.tilemapLeft = 20,
.tilemapTop = 5,
.width = 8,
.height = 2,
.paletteNum = 15,
.baseBlock = 356,
},
[WIN_MATCH_WIN_TEXT] = {
.bg = 0,
.tilemapLeft = 2,
.tilemapTop = 16,
.width = 26,
.height = 2,
.paletteNum = 15,
.baseBlock = 372,
},
// Duplicate windows used by the alternate info card
// Same as above but on bg 1 instead of bg 0
[WIN_TRAINER_NAME + NUM_INFO_CARD_WINDOWS] = {
.bg = 1,
.tilemapLeft = 2,
.tilemapTop = 2,
.width = 26,
.height = 2,
.paletteNum = 15,
.baseBlock = 1,
},
[WIN_TRAINER_MON1_NAME + NUM_INFO_CARD_WINDOWS] = {
.bg = 1,
.tilemapLeft = 16,
.tilemapTop = 5,
.width = 8,
.height = 2,
.paletteNum = 15,
.baseBlock = 53,
},
[WIN_TRAINER_MON2_NAME + NUM_INFO_CARD_WINDOWS] = {
.bg = 1,
.tilemapLeft = 19,
.tilemapTop = 7,
.width = 9,
.height = 3,
.paletteNum = 15,
.baseBlock = 69,
},
[WIN_TRAINER_MON3_NAME + NUM_INFO_CARD_WINDOWS] = {
.bg = 1,
.tilemapLeft = 16,
.tilemapTop = 10,
.width = 8,
.height = 2,
.paletteNum = 15,
.baseBlock = 96,
},
[WIN_TRAINER_FLAVOR_TEXT + NUM_INFO_CARD_WINDOWS] = {
.bg = 1,
.tilemapLeft = 2,
.tilemapTop = 12,
.width = 26,
.height = 7,
.paletteNum = 15,
.baseBlock = 112,
},
[WIN_MATCH_NUMBER + NUM_INFO_CARD_WINDOWS] = {
.bg = 1,
.tilemapLeft = 5,
.tilemapTop = 2,
.width = 23,
.height = 2,
.paletteNum = 15,
.baseBlock = 294,
},
[WIN_MATCH_TRAINER_NAME_LEFT + NUM_INFO_CARD_WINDOWS] = {
.bg = 1,
.tilemapLeft = 2,
.tilemapTop = 5,
.width = 8,
.height = 2,
.paletteNum = 15,
.baseBlock = 340,
},
[WIN_MATCH_TRAINER_NAME_RIGHT + NUM_INFO_CARD_WINDOWS] = {
.bg = 1,
.tilemapLeft = 20,
.tilemapTop = 5,
.width = 8,
.height = 2,
.paletteNum = 15,
.baseBlock = 356,
},
[WIN_MATCH_WIN_TEXT + NUM_INFO_CARD_WINDOWS] = {
.bg = 1,
.tilemapLeft = 2,
.tilemapTop = 16,
.width = 26,
.height = 2,
.paletteNum = 15,
.baseBlock = 372,
},
#ifdef UBFIX
DUMMY_WIN_TEMPLATE,
#endif
};
static const struct ScanlineEffectParams sTourneyTreeScanlineEffectParams =
{
.dmaDest = ®_BG3CNT,
.dmaControl = SCANLINE_EFFECT_DMACNT_16BIT,
.initState = 1,
};
static const struct CompressedSpriteSheet sTourneyTreeButtonsSpriteSheet[] =
{
{.data = gDomeTourneyTreeButtons_Gfx, .size = 0x0600, .tag = TAG_BUTTONS},
{},
};
// Unused
static const struct CompressedSpritePalette sTourneyTreeButtonsSpritePal[] =
{
{.data = gDomeTourneyTreeButtons_Pal, .tag = TAG_BUTTONS},
{},
};
static const struct OamData sOamData_TourneyTreePokeball =
{
.y = 0,
.affineMode = ST_OAM_AFFINE_OFF,
.objMode = ST_OAM_OBJ_NORMAL,
.mosaic = FALSE,
.bpp = ST_OAM_4BPP,
.shape = SPRITE_SHAPE(16x16),
.x = 0,
.matrixNum = 0,
.size = SPRITE_SIZE(16x16),
.tileNum = 0,
.priority = 0,
.paletteNum = 0,
.affineParam = 0,
};
// For Exit/Cancel buttons
static const struct OamData sOamData_TourneyTreeCloseButton =
{
.y = 0,
.affineMode = ST_OAM_AFFINE_OFF,
.objMode = ST_OAM_OBJ_NORMAL,
.mosaic = FALSE,
.bpp = ST_OAM_4BPP,
.shape = SPRITE_SHAPE(32x16),
.x = 0,
.matrixNum = 0,
.size = SPRITE_SIZE(32x16),
.tileNum = 0,
.priority = 0,
.paletteNum = 1,
.affineParam = 0,
};
static const struct OamData sOamData_VerticalScrollArrow =
{
.y = 0,
.affineMode = ST_OAM_AFFINE_OFF,
.objMode = ST_OAM_OBJ_NORMAL,
.mosaic = FALSE,
.bpp = ST_OAM_4BPP,
.shape = SPRITE_SHAPE(16x8),
.x = 0,
.matrixNum = 0,
.size = SPRITE_SIZE(16x8),
.tileNum = 0,
.priority = 0,
.paletteNum = 2,
.affineParam = 0,
};
static const struct OamData sOamData_HorizontalScrollArrow =
{
.y = 0,
.affineMode = ST_OAM_AFFINE_OFF,
.objMode = ST_OAM_OBJ_NORMAL,
.mosaic = FALSE,
.bpp = ST_OAM_4BPP,
.shape = SPRITE_SHAPE(8x16),
.x = 0,
.matrixNum = 0,
.size = SPRITE_SIZE(8x16),
.tileNum = 0,
.priority = 0,
.paletteNum = 2,
.affineParam = 0,
};
static const union AnimCmd sSpriteAnim_TourneyTreePokeballNormal[] =
{
ANIMCMD_FRAME(20, 1),
ANIMCMD_END,
};
static const union AnimCmd sSpriteAnim_TourneyTreePokeballSelected[] =
{
ANIMCMD_FRAME(24, 1),
ANIMCMD_END,
};
static const union AnimCmd * const sSpriteAnimTable_TourneyTreePokeball[] =
{
sSpriteAnim_TourneyTreePokeballNormal,
sSpriteAnim_TourneyTreePokeballSelected,
};
// Sprite template for the pokeballs on the tourney tree that act as buttons to view a trainer/match info card
static const struct SpriteTemplate sTourneyTreePokeballSpriteTemplate =
{
.tileTag = TAG_BUTTONS,
.paletteTag = TAG_NONE,
.oam = &sOamData_TourneyTreePokeball,
.anims = sSpriteAnimTable_TourneyTreePokeball,
.images = NULL,
.affineAnims = gDummySpriteAffineAnimTable,
.callback = SpriteCallbackDummy
};
static const union AnimCmd sSpriteAnim_TourneyTreeCancelButtonNormal[] =
{
ANIMCMD_FRAME(8, 1),
ANIMCMD_END,
};
static const union AnimCmd sSpriteAnim_TourneyTreeCancelButtonSelected[] =
{
ANIMCMD_FRAME(0, 1),
ANIMCMD_END,
};
static const union AnimCmd * const sSpriteAnimTable_TourneyTreeCancelButton[] =
{
sSpriteAnim_TourneyTreeCancelButtonNormal,
sSpriteAnim_TourneyTreeCancelButtonSelected,
};
static const struct SpriteTemplate sCancelButtonSpriteTemplate =
{
.tileTag = TAG_BUTTONS,
.paletteTag = TAG_NONE,
.oam = &sOamData_TourneyTreeCloseButton,
.anims = sSpriteAnimTable_TourneyTreeCancelButton,
.images = NULL,
.affineAnims = gDummySpriteAffineAnimTable,
.callback = SpriteCallbackDummy
};
static const union AnimCmd sSpriteAnim_TourneyTreeExitButtonNormal[] =
{
ANIMCMD_FRAME(40, 1),
ANIMCMD_END,
};
static const union AnimCmd sSpriteAnim_TourneyTreeExitButtonSelected[] =
{
ANIMCMD_FRAME(32, 1),
ANIMCMD_END,
};
static const union AnimCmd * const sSpriteAnimTable_TourneyTreeExitButton[] =
{
sSpriteAnim_TourneyTreeExitButtonNormal,
sSpriteAnim_TourneyTreeExitButtonSelected,
};
static const struct SpriteTemplate sExitButtonSpriteTemplate =
{
.tileTag = TAG_BUTTONS,
.paletteTag = TAG_NONE,
.oam = &sOamData_TourneyTreeCloseButton,
.anims = sSpriteAnimTable_TourneyTreeExitButton,
.images = NULL,
.affineAnims = gDummySpriteAffineAnimTable,
.callback = SpriteCallbackDummy
};
static const union AnimCmd sSpriteAnim_UpArrow[] =
{
ANIMCMD_FRAME(18, 1),
ANIMCMD_END,
};
static const union AnimCmd sSpriteAnim_DownArrow[] =
{
ANIMCMD_FRAME(18, 1, .vFlip = TRUE),
ANIMCMD_END,
};
static const union AnimCmd sSpriteAnim_LeftArrow[] =
{
ANIMCMD_FRAME(16, 1, .hFlip = TRUE),
ANIMCMD_END,
};
static const union AnimCmd sSpriteAnim_RightArrow[] =
{
ANIMCMD_FRAME(16, 1),
ANIMCMD_END,
};
static const union AnimCmd * const sSpriteAnimTable_VerticalScrollArrow[] =
{
sSpriteAnim_UpArrow,
sSpriteAnim_DownArrow,
};
static const union AnimCmd * const sSpriteAnimTable_HorizontalScrollArrow[] =
{
sSpriteAnim_LeftArrow,
sSpriteAnim_RightArrow,
};
static const struct SpriteTemplate sHorizontalScrollArrowSpriteTemplate =
{
.tileTag = TAG_BUTTONS,
.paletteTag = TAG_NONE,
.oam = &sOamData_HorizontalScrollArrow,
.anims = sSpriteAnimTable_HorizontalScrollArrow,
.images = NULL,
.affineAnims = gDummySpriteAffineAnimTable,
.callback = SpriteCB_HorizontalScrollArrow
};
static const struct SpriteTemplate sVerticalScrollArrowSpriteTemplate =
{
.tileTag = TAG_BUTTONS,
.paletteTag = TAG_NONE,
.oam = &sOamData_VerticalScrollArrow,
.anims = sSpriteAnimTable_VerticalScrollArrow,
.images = NULL,
.affineAnims = gDummySpriteAffineAnimTable,
.callback = SpriteCB_VerticalScrollArrow
};
// Organized by seed starting position, i.e. seed 0 battles seed 8 first
static const u8 sTourneyTreeTrainerIds[DOME_TOURNAMENT_TRAINERS_COUNT] = {0, 8, 12, 4, 7, 15, 11, 3, 2, 10, 14, 6, 5, 13, 9, 1};
static void (* const sBattleDomeFunctions[])(void) =
{
[BATTLE_DOME_FUNC_INIT] = InitDomeChallenge,
[BATTLE_DOME_FUNC_GET_DATA] = GetDomeData,
[BATTLE_DOME_FUNC_SET_DATA] = SetDomeData,
[BATTLE_DOME_FUNC_GET_ROUND_TEXT] = BufferDomeRoundText,
[BATTLE_DOME_FUNC_GET_OPPONENT_NAME] = BufferDomeOpponentName,
[BATTLE_DOME_FUNC_INIT_OPPONENT_PARTY] = InitDomeOpponentParty,
[BATTLE_DOME_FUNC_SHOW_OPPONENT_INFO] = ShowDomeOpponentInfo,
[BATTLE_DOME_FUNC_SHOW_TOURNEY_TREE] = ShowDomeTourneyTree,
[BATTLE_DOME_FUNC_SHOW_PREV_TOURNEY_TREE] = ShowPreviousDomeTourneyTree,
[BATTLE_DOME_FUNC_SET_OPPONENT_ID] = SetDomeOpponentId,
[BATTLE_DOME_FUNC_SET_OPPONENT_GFX] = SetDomeOpponentGraphicsId,
[BATTLE_DOME_FUNC_SHOW_STATIC_TOURNEY_TREE] = ShowNonInteractiveDomeTourneyTree,
[BATTLE_DOME_FUNC_RESOLVE_WINNERS] = ResolveDomeRoundWinners,
[BATTLE_DOME_FUNC_SAVE] = SaveDomeChallenge,
[BATTLE_DOME_FUNC_INCREMENT_STREAK] = IncrementDomeStreaks,
[BATTLE_DOME_FUNC_SET_TRAINERS] = SetFacilityTrainerAndMonPtrs,
[BATTLE_DOME_FUNC_RESET_SKETCH] = ResetSketchedMoves,
[BATTLE_DOME_FUNC_RESTORE_HELD_ITEMS] = RestoreDomePlayerPartyHeldItems,
[BATTLE_DOME_FUNC_REDUCE_PARTY] = ReduceDomePlayerPartyToSelectedMons,
[BATTLE_DOME_FUNC_COMPARE_SEEDS] = GetPlayerSeededBeforeOpponent,
[BATTLE_DOME_FUNC_GET_WINNER_NAME] = BufferLastDomeWinnerName,
[BATTLE_DOME_FUNC_INIT_RESULTS_TREE] = InitRandomTourneyTreeResults,
[BATTLE_DOME_FUNC_INIT_TRAINERS] = InitDomeTrainers,
};
static const u32 sWinStreakFlags[][2] =
{
{STREAK_DOME_SINGLES_50, STREAK_DOME_SINGLES_OPEN},
{STREAK_DOME_DOUBLES_50, STREAK_DOME_DOUBLES_OPEN},
};
static const u32 sWinStreakMasks[][2] =
{
{~(STREAK_DOME_SINGLES_50), ~(STREAK_DOME_SINGLES_OPEN)},
{~(STREAK_DOME_DOUBLES_50), ~(STREAK_DOME_DOUBLES_OPEN)},
};
// TODO: The below two arrays probably need better names. The one below for example is only true of sIdToOpponentId[i][0]
static const u8 sIdToOpponentId[DOME_TOURNAMENT_TRAINERS_COUNT][DOME_ROUNDS_COUNT] =
{
[0] = { 8, 0, 4, 8},
[1] = { 9, 12, 8, 0},
[2] = {10, 8, 12, 0},
[3] = {11, 4, 0, 8},
[4] = {12, 0, 4, 8},
[5] = {13, 12, 8, 0},
[6] = {14, 8, 12, 0},
[7] = {15, 4, 0, 8},
[8] = { 0, 0, 4, 8},
[9] = { 1, 12, 8, 0},
[10] = { 2, 8, 12, 0},
[11] = { 3, 4, 0, 8},
[12] = { 4, 0, 4, 8},
[13] = { 5, 12, 8, 0},
[14] = { 6, 8, 12, 0},
[15] = { 7, 4, 0, 8},
};
// sTourneyTreeTrainerIds with every other pair swapped
static const u8 sTourneyTreeTrainerOpponentIds[DOME_TOURNAMENT_TRAINERS_COUNT] = { 0, 8, 4, 12, 7, 15, 3, 11, 2, 10, 6, 14, 5, 13, 1, 9 };
// The match number - 1 that a given tournament trainer will participate in for a given round
static const u8 sIdToMatchNumber[DOME_TOURNAMENT_TRAINERS_COUNT][DOME_ROUNDS_COUNT] =
{
{ 0, 8, 12, 14},
{ 0, 8, 12, 14},
{ 1, 8, 12, 14},
{ 1, 8, 12, 14},
{ 2, 9, 12, 14},
{ 2, 9, 12, 14},
{ 3, 9, 12, 14},
{ 3, 9, 12, 14},
{ 4, 10, 13, 14},
{ 4, 10, 13, 14},
{ 5, 10, 13, 14},
{ 5, 10, 13, 14},
{ 6, 11, 13, 14},
{ 6, 11, 13, 14},
{ 7, 11, 13, 14},
{ 7, 11, 13, 14},
};
static const u8 sLastMatchCardNum[DOME_ROUNDS_COUNT] =
{
[DOME_ROUND1] = 23,
[DOME_ROUND2] = 27,
[DOME_SEMIFINAL] = 29,
[DOME_FINAL] = 30
};
static const u8 sTrainerAndRoundToLastMatchCardNum[DOME_TOURNAMENT_TRAINERS_COUNT / 2][DOME_ROUNDS_COUNT] =
{
{16, 24, 28, 30},
{17, 24, 28, 30},
{18, 25, 28, 30},
{19, 25, 28, 30},
{20, 26, 29, 30},
{21, 26, 29, 30},
{22, 27, 29, 30},
{23, 27, 29, 30},
};
static const u8 sTournamentIdToPairedTrainerIds[DOME_TOURNAMENT_TRAINERS_COUNT] = {0, 15, 8, 7, 3, 12, 11, 4, 1, 14, 9, 6, 2, 13, 10, 5};
// The first line of text on a trainers info card. It describes their potential to win, based on their seed in the tournament tree.
// Dome Ace Tucker has their own separate potential text.
static const u8 *const sBattleDomePotentialTexts[DOME_TOURNAMENT_TRAINERS_COUNT + 1] =
{
BattleDome_Text_Potential1, // Highest potential
BattleDome_Text_Potential2,
BattleDome_Text_Potential3,
BattleDome_Text_Potential4,
BattleDome_Text_Potential5,
BattleDome_Text_Potential6,
BattleDome_Text_Potential7,
BattleDome_Text_Potential8,
BattleDome_Text_Potential9,
BattleDome_Text_Potential10,
BattleDome_Text_Potential11,
BattleDome_Text_Potential12,
BattleDome_Text_Potential13,
BattleDome_Text_Potential14,
BattleDome_Text_Potential15,
BattleDome_Text_Potential16, // Lowest potential
BattleDome_Text_PotentialDomeAceTucker,
};
// The second line of text on a trainers info card. It gives information about their battle style (dependent on their party's moves).
static const u8 *const sBattleDomeOpponentStyleTexts[NUM_BATTLE_STYLES] =
{
[DOME_BATTLE_STYLE_RISKY] = BattleDome_Text_StyleRiskDisaster,
[DOME_BATTLE_STYLE_STALL] = BattleDome_Text_StyleEndureLongBattles,
[DOME_BATTLE_STYLE_VARIED] = BattleDome_Text_StyleVariesTactics,
[DOME_BATTLE_STYLE_COMBO_HIGH] = BattleDome_Text_StyleToughWinningPattern,
[DOME_BATTLE_STYLE_RARE_MOVES] = BattleDome_Text_StyleUsesVeryRareMove, // Seems like the text for these two was swapped
[DOME_BATTLE_STYLE_RARE_MOVE] = BattleDome_Text_StyleUsesStartlingMoves, //
[DOME_BATTLE_STYLE_HP] = BattleDome_Text_StyleConstantlyWatchesHP,
[DOME_BATTLE_STYLE_STORE_POWER] = BattleDome_Text_StyleStoresAndLoosesPower,
[DOME_BATTLE_STYLE_ENFEEBLE_LOW] = BattleDome_Text_StyleEnfeeblesFoes,
[DOME_BATTLE_STYLE_LUCK] = BattleDome_Text_StylePrefersLuckTactics,
[DOME_BATTLE_STYLE_REGAL] = BattleDome_Text_StyleRegalAtmosphere,
[DOME_BATTLE_STYLE_LOW_PP] = BattleDome_Text_StylePowerfulLowPPMoves,
[DOME_BATTLE_STYLE_STATUS_ATK] = BattleDome_Text_StyleEnfeebleThenAttack,
[DOME_BATTLE_STYLE_ENDURE] = BattleDome_Text_StyleBattlesWhileEnduring,
[DOME_BATTLE_STYLE_STATUS] = BattleDome_Text_StyleUpsetsFoesEmotionally,
[DOME_BATTLE_STYLE_STRAIGHTFORWARD] = BattleDome_Text_StyleStrongAndStraightforward,
[DOME_BATTLE_STYLE_AGGRESSIVE] = BattleDome_Text_StyleAggressivelyStrongMoves,
[DOME_BATTLE_STYLE_DEF] = BattleDome_Text_StyleCleverlyDodgesAttacks,
[DOME_BATTLE_STYLE_ENFEEBLE_HIGH] = BattleDome_Text_StyleUsesUpsettingMoves,
[DOME_BATTLE_STYLE_POPULAR_POWER] = BattleDome_Text_StyleUsesPopularMoves,
[DOME_BATTLE_STYLE_COMBO_LOW] = BattleDome_Text_StyleHasPowerfulComboMoves,
[DOME_BATTLE_STYLE_ACCURATE] = BattleDome_Text_StyleUsesHighProbabilityMoves,
[DOME_BATTLE_STYLE_POWERFUL] = BattleDome_Text_StyleAggressivelySpectacularMoves,
[DOME_BATTLE_STYLE_ATK_OVER_DEF] = BattleDome_Text_StyleEmphasizesOffenseOverDefense,
[DOME_BATTLE_STYLE_DEF_OVER_ATK] = BattleDome_Text_StyleEmphasizesDefenseOverOffense,
[DOME_BATTLE_STYLE_POPULAR_STRONG] = BattleDome_Text_StyleAttacksQuicklyStrongMoves,
[DOME_BATTLE_STYLE_EFFECTS] = BattleDome_Text_StyleUsesAddedEffectMoves,
[DOME_BATTLE_STYLE_BALANCED] = BattleDome_Text_StyleUsesBalancedMixOfMoves,
[DOME_BATTLE_STYLE_UNUSED1] = BattleDome_Text_StyleSampleMessage1,
[DOME_BATTLE_STYLE_UNUSED2] = BattleDome_Text_StyleSampleMessage2,
[DOME_BATTLE_STYLE_UNUSED3] = BattleDome_Text_StyleSampleMessage3,
[DOME_BATTLE_STYLE_UNUSED4] = BattleDome_Text_StyleSampleMessage4,
};
// The third line of text on a trainers info card. It that gives information about their party's stat spread (based on their Pokémon's effort values and Nature).
static const u8 *const sBattleDomeOpponentStatsTexts[] =
{
BattleDome_Text_EmphasizesHPAndAtk, // DOME_TEXT_TWO_GOOD_STATS and DOME_TEXT_HP start here
BattleDome_Text_EmphasizesHPAndDef,
BattleDome_Text_EmphasizesHPAndSpeed,
BattleDome_Text_EmphasizesHPAndSpAtk,
BattleDome_Text_EmphasizesHPAndSpDef,
BattleDome_Text_EmphasizesAtkAndDef, // DOME_TEXT_ATK starts here
BattleDome_Text_EmphasizesAtkAndSpeed,
BattleDome_Text_EmphasizesAtkAndSpAtk,
BattleDome_Text_EmphasizesAtkAndSpDef,
BattleDome_Text_EmphasizesDefAndSpeed, // DOME_TEXT_DEF starts here
BattleDome_Text_EmphasizesDefAndSpAtk,
BattleDome_Text_EmphasizesDefAndSpDef,
BattleDome_Text_EmphasizesSpeedAndSpAtk, // DOME_TEXT_SPEED starts here
BattleDome_Text_EmphasizesSpeedAndSpDef,
BattleDome_Text_EmphasizesSpAtkAndSpDef, // DOME_TEXT_SPATK starts here
BattleDome_Text_EmphasizesHP, // DOME_TEXT_ONE_GOOD_STAT starts here
BattleDome_Text_EmphasizesAtk,
BattleDome_Text_EmphasizesDef,
BattleDome_Text_EmphasizesSpeed,
BattleDome_Text_EmphasizesSpAtk,
BattleDome_Text_EmphasizesSpDef,
BattleDome_Text_NeglectsHPAndAtk, // DOME_TEXT_TWO_BAD_STATS starts here
BattleDome_Text_NeglectsHPAndDef,
BattleDome_Text_NeglectsHPAndSpeed,
BattleDome_Text_NeglectsHPAndSpAtk,
BattleDome_Text_NeglectsHPAndSpDef,
BattleDome_Text_NeglectsAtkAndDef,
BattleDome_Text_NeglectsAtkAndSpeed,
BattleDome_Text_NeglectsAtkAndSpAtk,
BattleDome_Text_NeglectsAtkAndSpDef,
BattleDome_Text_NeglectsDefAndSpeed,
BattleDome_Text_NeglectsDefAndSpAtk,
BattleDome_Text_NeglectsDefAndSpDef,
BattleDome_Text_NeglectsSpeedAndSpAtk,
BattleDome_Text_NeglectsSpeedAndSpDef,
BattleDome_Text_NeglectsSpAtkAndSpDef,
BattleDome_Text_NeglectsHP, // DOME_TEXT_ONE_BAD_STAT starts here
BattleDome_Text_NeglectsAtk,
BattleDome_Text_NeglectsDef,
BattleDome_Text_NeglectsSpeed,
BattleDome_Text_NeglectsSpAtk,
BattleDome_Text_NeglectsSpDef,
[DOME_TEXT_WELL_BALANCED] = BattleDome_Text_RaisesMonsWellBalanced,
};
static const u8 sInfoTrainerMonX[FRONTIER_PARTY_SIZE] = {104, 136, 104};
static const u8 sInfoTrainerMonY[FRONTIER_PARTY_SIZE] = { 38, 62, 78};
static const u8 sSpeciesNameTextYCoords[] = {0, 4, 0};
// Offsets within sBattleDomeOpponentStatsTexts for stat combinations
// SPDEF has no offset because by then all stat combinations have been reached, so it has no combination texts
static const u8 sStatTextOffsets[NUM_STATS - 1] =
{
DOME_TEXT_HP,
DOME_TEXT_ATK,
DOME_TEXT_DEF,
DOME_TEXT_SPEED,
DOME_TEXT_SPATK
};
static const u8 *const sBattleDomeMatchNumberTexts[DOME_TOURNAMENT_MATCHES_COUNT] =
{
BattleDome_Text_Round1Match1,
BattleDome_Text_Round1Match2,
BattleDome_Text_Round1Match3,
BattleDome_Text_Round1Match4,
BattleDome_Text_Round1Match5,
BattleDome_Text_Round1Match6,
BattleDome_Text_Round1Match7,
BattleDome_Text_Round1Match8,
BattleDome_Text_Round2Match1,
BattleDome_Text_Round2Match2,
BattleDome_Text_Round2Match3,
BattleDome_Text_Round2Match4,
BattleDome_Text_SemifinalMatch1,
BattleDome_Text_SemifinalMatch2,
BattleDome_Text_FinalMatch,
};
static const u8 *const sBattleDomeWinTexts[] =
{
[DOME_TEXT_NO_WINNER_YET] = BattleDome_Text_LetTheBattleBegin,
[DOME_TEXT_WON_USING_MOVE] = BattleDome_Text_TrainerWonUsingMove,
[DOME_TEXT_CHAMP_USING_MOVE] = BattleDome_Text_TrainerBecameChamp,
[DOME_TEXT_WON_ON_FORFEIT] = BattleDome_Text_TrainerWonByDefault,
[DOME_TEXT_CHAMP_ON_FORFEIT] = BattleDome_Text_TrainerWonOutrightByDefault,
[DOME_TEXT_WON_NO_MOVES] = BattleDome_Text_TrainerWonNoMoves,
[DOME_TEXT_CHAMP_NO_MOVES] = BattleDome_Text_TrainerWonOutrightNoMoves,
};
static const u8 sLeftTrainerMonX[FRONTIER_PARTY_SIZE] = { 96, 96, 96};
static const u8 sLeftTrainerMonY[FRONTIER_PARTY_SIZE] = { 56, 80, 104};
static const u8 sRightTrainerMonX[FRONTIER_PARTY_SIZE] = {144, 144, 144};
static const u8 sRightTrainerMonY[FRONTIER_PARTY_SIZE] = { 56, 80, 104};
// Duplicate of sTourneyTreeTrainerIds
static const u8 sTourneyTreeTrainerIds2[DOME_TOURNAMENT_TRAINERS_COUNT] = {0, 8, 12, 4, 7, 15, 11, 3, 2, 10, 14, 6, 5, 13, 9, 1};
// The number of possible trainers that could be competing in a given match
#define NUM_POSSIBLE_MATCH_TRAINERS(round) (DOME_TOURNAMENT_TRAINERS_COUNT / (1 << (DOME_ROUNDS_COUNT - round - 1)))
// The range of tournament trainers to check as possible participants in a given match
// Given by the offset in sCompetitorRangeByMatch[][0], the number of trainers in sCompetitorRangeByMatch[][1], and the round
static const u8 sCompetitorRangeByMatch[DOME_TOURNAMENT_MATCHES_COUNT][3] =
{
{ NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1) * 0, NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1), DOME_ROUND1},
{ NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1) * 1, NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1), DOME_ROUND1},
{ NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1) * 2, NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1), DOME_ROUND1},
{ NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1) * 3, NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1), DOME_ROUND1},
{ NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1) * 4, NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1), DOME_ROUND1},
{ NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1) * 5, NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1), DOME_ROUND1},
{ NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1) * 6, NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1), DOME_ROUND1},
{ NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1) * 7, NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND1), DOME_ROUND1},
{ NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND2) * 0, NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND2), DOME_ROUND2},
{ NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND2) * 1, NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND2), DOME_ROUND2},
{ NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND2) * 2, NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND2), DOME_ROUND2},
{ NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND2) * 3, NUM_POSSIBLE_MATCH_TRAINERS(DOME_ROUND2), DOME_ROUND2},
{ NUM_POSSIBLE_MATCH_TRAINERS(DOME_SEMIFINAL) * 0, NUM_POSSIBLE_MATCH_TRAINERS(DOME_SEMIFINAL), DOME_SEMIFINAL},
{ NUM_POSSIBLE_MATCH_TRAINERS(DOME_SEMIFINAL) * 1, NUM_POSSIBLE_MATCH_TRAINERS(DOME_SEMIFINAL), DOME_SEMIFINAL},
{ NUM_POSSIBLE_MATCH_TRAINERS(DOME_FINAL) * 0, NUM_POSSIBLE_MATCH_TRAINERS(DOME_FINAL), DOME_FINAL},
};
#define NAME_ROW_HEIGHT 16
// 1st value is the windowId, 2nd value is the y coord
static const u8 sTrainerNamePositions[DOME_TOURNAMENT_TRAINERS_COUNT][2] =
{
{ TOURNEYWIN_NAMES_LEFT, 0 * NAME_ROW_HEIGHT},
{ TOURNEYWIN_NAMES_RIGHT, 7 * NAME_ROW_HEIGHT},
{ TOURNEYWIN_NAMES_RIGHT, 0 * NAME_ROW_HEIGHT},
{ TOURNEYWIN_NAMES_LEFT, 7 * NAME_ROW_HEIGHT},
{ TOURNEYWIN_NAMES_LEFT, 3 * NAME_ROW_HEIGHT},
{ TOURNEYWIN_NAMES_RIGHT, 4 * NAME_ROW_HEIGHT},
{ TOURNEYWIN_NAMES_RIGHT, 3 * NAME_ROW_HEIGHT},
{ TOURNEYWIN_NAMES_LEFT, 4 * NAME_ROW_HEIGHT},
{ TOURNEYWIN_NAMES_LEFT, 1 * NAME_ROW_HEIGHT},
{ TOURNEYWIN_NAMES_RIGHT, 6 * NAME_ROW_HEIGHT},
{ TOURNEYWIN_NAMES_RIGHT, 1 * NAME_ROW_HEIGHT},
{ TOURNEYWIN_NAMES_LEFT, 6 * NAME_ROW_HEIGHT},
{ TOURNEYWIN_NAMES_LEFT, 2 * NAME_ROW_HEIGHT},
{ TOURNEYWIN_NAMES_RIGHT, 5 * NAME_ROW_HEIGHT},
{ TOURNEYWIN_NAMES_RIGHT, 2 * NAME_ROW_HEIGHT},
{ TOURNEYWIN_NAMES_LEFT, 5 * NAME_ROW_HEIGHT},
};
// Coords for the pokeballs on the tourney tree that act as buttons to view trainer/match info
static const u8 sTourneyTreePokeballCoords[DOME_TOURNAMENT_TRAINERS_COUNT + DOME_TOURNAMENT_MATCHES_COUNT][2] =
{
{ 68, 33}, // Left side trainers
{ 68, 49},
{ 68, 65},
{ 68, 81},
{ 68, 97},
{ 68, 113},
{ 68, 129},
{ 68, 145},
{172, 33}, // Right side trainers
{172, 49},
{172, 65},
{172, 81},
{172, 97},
{172, 113},
{172, 129},
{172, 145},
{ 87, 41}, // Left side Round 1 matches
{ 87, 73},
{ 87, 105},
{ 87, 137},
{153, 41}, // Right side Round 1 matches
{153, 73},
{153, 105},
{153, 137},
{ 95, 57}, // Left side Round 2 matches
{ 95, 121},
{145, 57}, // Right side Round 2 matches
{145, 121},
{103, 89}, // Left side semifinal match
{137, 89}, // Right side semifinal match
{120, 89}, // Final match
};
// Tile values from tourney_tree.png for the highlighted lines of the tourney tree.
// These tiles will be used to replace the existing, unhighlighted line tiles on the tourney tree tilemap.
#define LINE_PAL (6 << 12)
#define LINE_H (LINE_PAL | 0x21) // Horizontal
#define LINE_CORNER_R (LINE_PAL | 0x23) // Horizontal into a right-side vertical
#define LINE_CORNER_L (LINE_PAL | 0x25) // Horizontal into a left-side vertical
#define LINE_V_R (LINE_PAL | 0x27) // Right-side vertical
#define LINE_V_L (LINE_PAL | 0x29) // Left-side vertical
#define LINE_H_BOTTOM (LINE_PAL | 0x2B) // Horizontal on the bottom of the tree
#define LINE_H_LOGO1 (LINE_PAL | 0x2C) // Horizontal, logo behind
#define LINE_H_LOGO2 (LINE_PAL | 0x2D) // Horizontal, logo behind
#define LINE_H_LOGO3 (LINE_PAL | 0x2E) // Horizontal, logo behind
#define LINE_H_LOGO4 (LINE_PAL | 0x2F) // Horizontal, logo behind
#define LINE_V_R_LOGO1 (LINE_PAL | 0x30) // Right-side vertical, logo behind
#define LINE_V_R_LOGO2 (LINE_PAL | 0x31) // Right-side vertical, logo behind
#define LINE_V_R_LOGO3 (LINE_PAL | 0x32) // Right-side vertical, logo behind
#define LINE_V_R_LOGO4 (LINE_PAL | 0x33) // Right-side vertical, logo behind
#define LINE_V_L_LOGO1 (LINE_PAL | 0x35) // Left-side vertical, logo behind
#define LINE_V_L_LOGO2 (LINE_PAL | 0x36) // Left-side vertical, logo behind
#define LINE_V_L_LOGO3 (LINE_PAL | 0x37) // Left-side vertical, logo behind
#define LINE_V_L_LOGO4 (LINE_PAL | 0x38) // Left-side vertical, logo behind
#define LINE_V_R_HALF_LOGO (LINE_PAL | 0x3B) // Right-side vertical, half lit from the top, logo behind
#define LINE_V_L_HALF_LOGO (LINE_PAL | 0x3C) // Left-side vertical, half lit from the top, logo behind
#define LINE_CORNER_R_HALF (LINE_PAL | 0x43) // Lit horizontal, unlit right-side vertical
#define LINE_CORNER_L_HALF (LINE_PAL | 0x45) // Lit horizontal, unlit left-side vertical
#define LINE_V_R_HALF (LINE_PAL | 0x47) // Right-side vertical, half lit from the top
#define LINE_V_L_HALF (LINE_PAL | 0x49) // Left-side vertical, half lit from the top
// Each of these line sections define the position of the advancement line on the tourney tree for the victor of that round
// The trainers here are numbered by tourney ID (rank/seed) and ordered according to where they start on the tourney tree
#define LINESECTION_ROUND1_TRAINER1(lastTile) \
{.tile = LINE_H, .y = 4, .x = 9}, \
{.tile = LINE_CORNER_R, .y = 4, .x = 10}, \
{.tile = LINE_V_R_HALF, .y = 5, .x = 10}, \
{.tile = lastTile, .y = 5, .x = 11},
#define LINESECTION_ROUND1_TRAINER9(lastTile) \
{.tile = LINE_H, .y = 6, .x = 9}, \
{.tile = LINE_H, .y = 6, .x = 10}, \
{.tile = LINE_V_R, .y = 5, .x = 10}, \
{.tile = lastTile, .y = 5, .x = 11},
#define LINESECTION_ROUND1_TRAINER13(lastTile) \
{.tile = LINE_H, .y = 8, .x = 9}, \
{.tile = LINE_CORNER_R, .y = 8, .x = 10}, \
{.tile = LINE_V_R_HALF, .y = 9, .x = 10}, \
{.tile = lastTile, .y = 9, .x = 11},
#define LINESECTION_ROUND1_TRAINER5(lastTile) \
{.tile = LINE_H, .y = 10, .x = 9}, \
{.tile = LINE_H, .y = 10, .x = 10}, \
{.tile = LINE_V_R, .y = 9, .x = 10}, \
{.tile = lastTile, .y = 9, .x = 11},
#define LINESECTION_ROUND1_TRAINER8(lastTile) \
{.tile = LINE_H, .y = 12, .x = 9}, \
{.tile = LINE_CORNER_R, .y = 12, .x = 10}, \
{.tile = LINE_V_R_HALF, .y = 13, .x = 10}, \
{.tile = lastTile, .y = 13, .x = 11},
#define LINESECTION_ROUND1_TRAINER16(lastTile) \
{.tile = LINE_H, .y = 14, .x = 9}, \
{.tile = LINE_H, .y = 14, .x = 10}, \
{.tile = LINE_V_R, .y = 13, .x = 10}, \
{.tile = lastTile, .y = 13, .x = 11},
#define LINESECTION_ROUND1_TRAINER12(lastTile) \
{.tile = LINE_H, .y = 16, .x = 9}, \
{.tile = LINE_CORNER_R, .y = 16, .x = 10}, \
{.tile = LINE_V_R_HALF, .y = 17, .x = 10}, \
{.tile = lastTile, .y = 17, .x = 11},
#define LINESECTION_ROUND1_TRAINER4(lastTile) \
{.tile = LINE_H_BOTTOM, .y = 18, .x = 9}, \
{.tile = LINE_H_BOTTOM, .y = 18, .x = 10}, \
{.tile = LINE_V_R, .y = 17, .x = 10}, \
{.tile = lastTile, .y = 17, .x = 11},
#define LINESECTION_ROUND1_TRAINER3(lastTile) \
{.tile = LINE_H, .y = 4, .x = 20}, \
{.tile = LINE_CORNER_L, .y = 4, .x = 19}, \
{.tile = LINE_V_L_HALF, .y = 5, .x = 19}, \
{.tile = lastTile, .y = 5, .x = 18},
#define LINESECTION_ROUND1_TRAINER11(lastTile) \
{.tile = LINE_H, .y = 6, .x = 20}, \
{.tile = LINE_H, .y = 6, .x = 19}, \
{.tile = LINE_V_L, .y = 5, .x = 19}, \
{.tile = lastTile, .y = 5, .x = 18},
#define LINESECTION_ROUND1_TRAINER15(lastTile) \
{.tile = LINE_H, .y = 8, .x = 20}, \
{.tile = LINE_CORNER_L, .y = 8, .x = 19}, \
{.tile = LINE_V_L_HALF, .y = 9, .x = 19}, \
{.tile = lastTile, .y = 9, .x = 18},
#define LINESECTION_ROUND1_TRAINER7(lastTile) \
{.tile = LINE_H, .y = 10, .x = 20}, \
{.tile = LINE_H, .y = 10, .x = 19}, \
{.tile = LINE_V_L, .y = 9, .x = 19}, \
{.tile = lastTile, .y = 9, .x = 18},
#define LINESECTION_ROUND1_TRAINER6(lastTile) \
{.tile = LINE_H, .y = 12, .x = 20}, \
{.tile = LINE_CORNER_L, .y = 12, .x = 19}, \
{.tile = LINE_V_L_HALF, .y = 13, .x = 19}, \
{.tile = lastTile, .y = 13, .x = 18},
#define LINESECTION_ROUND1_TRAINER14(lastTile) \
{.tile = LINE_H, .y = 14, .x = 20}, \
{.tile = LINE_H, .y = 14, .x = 19}, \
{.tile = LINE_V_L, .y = 13, .x = 19}, \
{.tile = lastTile, .y = 13, .x = 18},
#define LINESECTION_ROUND1_TRAINER10(lastTile) \
{.tile = LINE_H, .y = 16, .x = 20}, \
{.tile = LINE_CORNER_L, .y = 16, .x = 19}, \
{.tile = LINE_V_L_HALF, .y = 17, .x = 19}, \
{.tile = lastTile, .y = 17, .x = 18},
#define LINESECTION_ROUND1_TRAINER2(lastTile) \
{.tile = LINE_H_BOTTOM, .y = 18, .x = 20}, \
{.tile = LINE_H_BOTTOM, .y = 18, .x = 19}, \
{.tile = LINE_V_L, .y = 17, .x = 19}, \
{.tile = lastTile, .y = 17, .x = 18},
#define LINESECTION_ROUND2_MATCH1(lastTile) \
{.tile = LINE_V_R, .y = 6, .x = 11}, \
{.tile = LINE_V_R_HALF, .y = 7, .x = 11}, \
{.tile = lastTile, .y = 7, .x = 12},
#define LINESECTION_ROUND2_MATCH2(lastTile) \
{.tile = LINE_V_R, .y = 8, .x = 11}, \
{.tile = LINE_V_R, .y = 7, .x = 11}, \
{.tile = lastTile, .y = 7, .x = 12},
#define LINESECTION_ROUND2_MATCH3(lastTile) \
{.tile = LINE_V_R, .y = 14, .x = 11}, \
{.tile = LINE_V_R_HALF, .y = 15, .x = 11}, \
{.tile = lastTile, .y = 15, .x = 12},
#define LINESECTION_ROUND2_MATCH4(lastTile) \
{.tile = LINE_V_R, .y = 16, .x = 11}, \
{.tile = LINE_V_R, .y = 15, .x = 11}, \
{.tile = lastTile, .y = 15, .x = 12},
#define LINESECTION_ROUND2_MATCH5(lastTile) \
{.tile = LINE_V_L, .y = 6, .x = 18}, \
{.tile = LINE_V_L_HALF, .y = 7, .x = 18}, \
{.tile = lastTile, .y = 7, .x = 17},
#define LINESECTION_ROUND2_MATCH6(lastTile) \
{.tile = LINE_V_L, .y = 8, .x = 18}, \
{.tile = LINE_V_L, .y = 7, .x = 18}, \
{.tile = lastTile, .y = 7, .x = 17},
#define LINESECTION_ROUND2_MATCH7(lastTile) \
{.tile = LINE_V_L, .y = 14, .x = 18}, \
{.tile = LINE_V_L_HALF, .y = 15, .x = 18}, \
{.tile = lastTile, .y = 15, .x = 17},
#define LINESECTION_ROUND2_MATCH8(lastTile) \
{.tile = LINE_V_L, .y = 16, .x = 18}, \
{.tile = LINE_V_L, .y = 15, .x = 18}, \
{.tile = lastTile, .y = 15, .x = 17},
#define LINESECTION_SEMIFINAL_TOP_LEFT \
{.tile = LINE_V_R, .y = 8, .x = 12}, \
{.tile = LINE_V_R, .y = 9, .x = 12}, \
{.tile = LINE_V_R, .y = 10, .x = 12}, \
{.tile = LINE_V_R_HALF_LOGO, .y = 11, .x = 12},
#define LINESECTION_SEMIFINAL_BOTTOM_LEFT \
{.tile = LINE_V_R_LOGO4, .y = 14, .x = 12}, \
{.tile = LINE_V_R_LOGO3, .y = 13, .x = 12}, \
{.tile = LINE_V_R_LOGO2, .y = 12, .x = 12}, \
{.tile = LINE_V_R_LOGO1, .y = 11, .x = 12},
#define LINESECTION_SEMIFINAL_TOP_RIGHT \
{.tile = LINE_V_L, .y = 8, .x = 17}, \
{.tile = LINE_V_L, .y = 9, .x = 17}, \
{.tile = LINE_V_L, .y = 10, .x = 17}, \
{.tile = LINE_V_L_HALF_LOGO, .y = 11, .x = 17},
#define LINESECTION_SEMIFINAL_BOTTOM_RIGHT \
{.tile = LINE_V_L_LOGO4, .y = 14, .x = 17}, \
{.tile = LINE_V_L_LOGO3, .y = 13, .x = 17}, \
{.tile = LINE_V_L_LOGO2, .y = 12, .x = 17}, \
{.tile = LINE_V_L_LOGO1, .y = 11, .x = 17},
#define LINESECTION_FINAL_LEFT \
{.tile = LINE_H_LOGO1, .y = 11, .x = 13}, \
{.tile = LINE_H_LOGO2, .y = 11, .x = 14},
#define LINESECTION_FINAL_RIGHT \
{.tile = LINE_H_LOGO4, .y = 11, .x = 16}, \
{.tile = LINE_H_LOGO3, .y = 11, .x = 15},
static const struct TourneyTreeLineSection sLineSectionTrainer1Round1[] =
{
LINESECTION_ROUND1_TRAINER1(LINE_CORNER_R_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer1Round2[] =
{
LINESECTION_ROUND1_TRAINER1(LINE_CORNER_R)
LINESECTION_ROUND2_MATCH1(LINE_CORNER_R_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer1Semifinal[] =
{
LINESECTION_ROUND1_TRAINER1(LINE_CORNER_R)
LINESECTION_ROUND2_MATCH1(LINE_CORNER_R)
LINESECTION_SEMIFINAL_TOP_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer1Final[] =
{
LINESECTION_ROUND1_TRAINER1(LINE_CORNER_R)
LINESECTION_ROUND2_MATCH1(LINE_CORNER_R)
LINESECTION_SEMIFINAL_TOP_LEFT
LINESECTION_FINAL_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer9Round1[] =
{
LINESECTION_ROUND1_TRAINER9(LINE_CORNER_R_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer9Round2[] =
{
LINESECTION_ROUND1_TRAINER9(LINE_CORNER_R)
LINESECTION_ROUND2_MATCH1(LINE_CORNER_R_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer9Semifinal[] =
{
LINESECTION_ROUND1_TRAINER9(LINE_CORNER_R)
LINESECTION_ROUND2_MATCH1(LINE_CORNER_R)
LINESECTION_SEMIFINAL_TOP_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer9Final[] =
{
LINESECTION_ROUND1_TRAINER9(LINE_CORNER_R)
LINESECTION_ROUND2_MATCH1(LINE_CORNER_R)
LINESECTION_SEMIFINAL_TOP_LEFT
LINESECTION_FINAL_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer13Round1[] =
{
LINESECTION_ROUND1_TRAINER13(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer13Round2[] =
{
LINESECTION_ROUND1_TRAINER13(LINE_H)
LINESECTION_ROUND2_MATCH2(LINE_CORNER_R_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer13Semifinal[] =
{
LINESECTION_ROUND1_TRAINER13(LINE_H)
LINESECTION_ROUND2_MATCH2(LINE_CORNER_R)
LINESECTION_SEMIFINAL_TOP_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer13Final[] =
{
LINESECTION_ROUND1_TRAINER13(LINE_H)
LINESECTION_ROUND2_MATCH2(LINE_CORNER_R)
LINESECTION_SEMIFINAL_TOP_LEFT
LINESECTION_FINAL_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer5Round1[] =
{
LINESECTION_ROUND1_TRAINER5(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer5Round2[] =
{
LINESECTION_ROUND1_TRAINER5(LINE_H)
LINESECTION_ROUND2_MATCH2(LINE_CORNER_R_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer5Semifinal[] =
{
LINESECTION_ROUND1_TRAINER5(LINE_H)
LINESECTION_ROUND2_MATCH2(LINE_CORNER_R)
LINESECTION_SEMIFINAL_TOP_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer5Final[] =
{
LINESECTION_ROUND1_TRAINER5(LINE_H)
LINESECTION_ROUND2_MATCH2(LINE_CORNER_R)
LINESECTION_SEMIFINAL_TOP_LEFT
LINESECTION_FINAL_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer8Round1[] =
{
LINESECTION_ROUND1_TRAINER8(LINE_CORNER_R_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer8Round2[] =
{
LINESECTION_ROUND1_TRAINER8(LINE_CORNER_R)
LINESECTION_ROUND2_MATCH3(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer8Semifinal[] =
{
LINESECTION_ROUND1_TRAINER8(LINE_CORNER_R)
LINESECTION_ROUND2_MATCH3(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer8Final[] =
{
LINESECTION_ROUND1_TRAINER8(LINE_CORNER_R)
LINESECTION_ROUND2_MATCH3(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_LEFT
LINESECTION_FINAL_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer16Round1[] =
{
LINESECTION_ROUND1_TRAINER16(LINE_CORNER_R_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer16Round2[] =
{
LINESECTION_ROUND1_TRAINER16(LINE_CORNER_R)
LINESECTION_ROUND2_MATCH3(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer16Semifinal[] =
{
LINESECTION_ROUND1_TRAINER16(LINE_CORNER_R)
LINESECTION_ROUND2_MATCH3(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer16Final[] =
{
LINESECTION_ROUND1_TRAINER16(LINE_CORNER_R)
LINESECTION_ROUND2_MATCH3(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_LEFT
LINESECTION_FINAL_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer12Round1[] =
{
LINESECTION_ROUND1_TRAINER12(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer12Round2[] =
{
LINESECTION_ROUND1_TRAINER12(LINE_H)
LINESECTION_ROUND2_MATCH4(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer12Semifinal[] =
{
LINESECTION_ROUND1_TRAINER12(LINE_H)
LINESECTION_ROUND2_MATCH4(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer12Final[] =
{
LINESECTION_ROUND1_TRAINER12(LINE_H)
LINESECTION_ROUND2_MATCH4(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_LEFT
LINESECTION_FINAL_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer4Round1[] =
{
LINESECTION_ROUND1_TRAINER4(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer4Round2[] =
{
LINESECTION_ROUND1_TRAINER4(LINE_H)
LINESECTION_ROUND2_MATCH4(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer4Semifinal[] =
{
LINESECTION_ROUND1_TRAINER4(LINE_H)
LINESECTION_ROUND2_MATCH4(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer4Final[] =
{
LINESECTION_ROUND1_TRAINER4(LINE_H)
LINESECTION_ROUND2_MATCH4(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_LEFT
LINESECTION_FINAL_LEFT
};
static const struct TourneyTreeLineSection sLineSectionTrainer3Round1[] =
{
LINESECTION_ROUND1_TRAINER3(LINE_CORNER_L_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer3Round2[] =
{
LINESECTION_ROUND1_TRAINER3(LINE_CORNER_L)
LINESECTION_ROUND2_MATCH5(LINE_CORNER_L_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer3Semifinal[] =
{
LINESECTION_ROUND1_TRAINER3(LINE_CORNER_L)
LINESECTION_ROUND2_MATCH5(LINE_CORNER_L)
LINESECTION_SEMIFINAL_TOP_RIGHT
};
static const struct TourneyTreeLineSection sLineSectionTrainer3Final[] =
{
LINESECTION_ROUND1_TRAINER3(LINE_CORNER_L)
LINESECTION_ROUND2_MATCH5(LINE_CORNER_L)
LINESECTION_SEMIFINAL_TOP_RIGHT
LINESECTION_FINAL_RIGHT
};
static const struct TourneyTreeLineSection sLineSectionTrainer11Round1[] =
{
LINESECTION_ROUND1_TRAINER11(LINE_CORNER_L_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer11Round2[] =
{
LINESECTION_ROUND1_TRAINER11(LINE_CORNER_L)
LINESECTION_ROUND2_MATCH5(LINE_CORNER_L_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer11Semifinal[] =
{
LINESECTION_ROUND1_TRAINER11(LINE_CORNER_L)
LINESECTION_ROUND2_MATCH5(LINE_CORNER_L)
LINESECTION_SEMIFINAL_TOP_RIGHT
};
static const struct TourneyTreeLineSection sLineSectionTrainer11Final[] =
{
LINESECTION_ROUND1_TRAINER11(LINE_CORNER_L)
LINESECTION_ROUND2_MATCH5(LINE_CORNER_L)
LINESECTION_SEMIFINAL_TOP_RIGHT
LINESECTION_FINAL_RIGHT
};
static const struct TourneyTreeLineSection sLineSectionTrainer15Round1[] =
{
LINESECTION_ROUND1_TRAINER15(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer15Round2[] =
{
LINESECTION_ROUND1_TRAINER15(LINE_H)
LINESECTION_ROUND2_MATCH6(LINE_CORNER_L_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer15Semifinal[] =
{
LINESECTION_ROUND1_TRAINER15(LINE_H)
LINESECTION_ROUND2_MATCH6(LINE_CORNER_L)
LINESECTION_SEMIFINAL_TOP_RIGHT
};
static const struct TourneyTreeLineSection sLineSectionTrainer15Final[] =
{
LINESECTION_ROUND1_TRAINER15(LINE_H)
LINESECTION_ROUND2_MATCH6(LINE_CORNER_L)
LINESECTION_SEMIFINAL_TOP_RIGHT
LINESECTION_FINAL_RIGHT
};
static const struct TourneyTreeLineSection sLineSectionTrainer7Round1[] =
{
LINESECTION_ROUND1_TRAINER7(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer7Round2[] =
{
LINESECTION_ROUND1_TRAINER7(LINE_H)
LINESECTION_ROUND2_MATCH6(LINE_CORNER_L_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer7Semifinal[] =
{
LINESECTION_ROUND1_TRAINER7(LINE_H)
LINESECTION_ROUND2_MATCH6(LINE_CORNER_L)
LINESECTION_SEMIFINAL_TOP_RIGHT
};
static const struct TourneyTreeLineSection sLineSectionTrainer7Final[] =
{
LINESECTION_ROUND1_TRAINER7(LINE_H)
LINESECTION_ROUND2_MATCH6(LINE_CORNER_L)
LINESECTION_SEMIFINAL_TOP_RIGHT
LINESECTION_FINAL_RIGHT
};
static const struct TourneyTreeLineSection sLineSectionTrainer6Round1[] =
{
LINESECTION_ROUND1_TRAINER6(LINE_CORNER_L_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer6Round2[] =
{
LINESECTION_ROUND1_TRAINER6(LINE_CORNER_L)
LINESECTION_ROUND2_MATCH7(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer6Semifinal[] =
{
LINESECTION_ROUND1_TRAINER6(LINE_CORNER_L)
LINESECTION_ROUND2_MATCH7(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_RIGHT
};
static const struct TourneyTreeLineSection sLineSectionTrainer6Final[] =
{
LINESECTION_ROUND1_TRAINER6(LINE_CORNER_L)
LINESECTION_ROUND2_MATCH7(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_RIGHT
LINESECTION_FINAL_RIGHT
};
static const struct TourneyTreeLineSection sLineSectionTrainer14Round1[] =
{
LINESECTION_ROUND1_TRAINER14(LINE_CORNER_L_HALF)
};
static const struct TourneyTreeLineSection sLineSectionTrainer14Round2[] =
{
LINESECTION_ROUND1_TRAINER14(LINE_CORNER_L)
LINESECTION_ROUND2_MATCH7(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer14Semifinal[] =
{
LINESECTION_ROUND1_TRAINER14(LINE_CORNER_L)
LINESECTION_ROUND2_MATCH7(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_RIGHT
};
static const struct TourneyTreeLineSection sLineSectionTrainer14Final[] =
{
LINESECTION_ROUND1_TRAINER14(LINE_CORNER_L)
LINESECTION_ROUND2_MATCH7(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_RIGHT
LINESECTION_FINAL_RIGHT
};
static const struct TourneyTreeLineSection sLineSectionTrainer10Round1[] =
{
LINESECTION_ROUND1_TRAINER10(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer10Round2[] =
{
LINESECTION_ROUND1_TRAINER10(LINE_H)
LINESECTION_ROUND2_MATCH8(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer10Semifinal[] =
{
LINESECTION_ROUND1_TRAINER10(LINE_H)
LINESECTION_ROUND2_MATCH8(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_RIGHT
};
static const struct TourneyTreeLineSection sLineSectionTrainer10Final[] =
{
LINESECTION_ROUND1_TRAINER10(LINE_H)
LINESECTION_ROUND2_MATCH8(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_RIGHT
LINESECTION_FINAL_RIGHT
};
static const struct TourneyTreeLineSection sLineSectionTrainer2Round1[] =
{
LINESECTION_ROUND1_TRAINER2(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer2Round2[] =
{
LINESECTION_ROUND1_TRAINER2(LINE_H)
LINESECTION_ROUND2_MATCH8(LINE_H)
};
static const struct TourneyTreeLineSection sLineSectionTrainer2Semifinal[] =
{
LINESECTION_ROUND1_TRAINER2(LINE_H)
LINESECTION_ROUND2_MATCH8(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_RIGHT
};
static const struct TourneyTreeLineSection sLineSectionTrainer2Final[] =
{
LINESECTION_ROUND1_TRAINER2(LINE_H)
LINESECTION_ROUND2_MATCH8(LINE_H)
LINESECTION_SEMIFINAL_BOTTOM_RIGHT
LINESECTION_FINAL_RIGHT
};
static const struct TourneyTreeLineSection *const sTourneyTreeLineSections[DOME_TOURNAMENT_TRAINERS_COUNT][DOME_ROUNDS_COUNT] =
{
{sLineSectionTrainer1Round1, sLineSectionTrainer1Round2, sLineSectionTrainer1Semifinal, sLineSectionTrainer1Final},
{sLineSectionTrainer2Round1, sLineSectionTrainer2Round2, sLineSectionTrainer2Semifinal, sLineSectionTrainer2Final},
{sLineSectionTrainer3Round1, sLineSectionTrainer3Round2, sLineSectionTrainer3Semifinal, sLineSectionTrainer3Final},
{sLineSectionTrainer4Round1, sLineSectionTrainer4Round2, sLineSectionTrainer4Semifinal, sLineSectionTrainer4Final},
{sLineSectionTrainer5Round1, sLineSectionTrainer5Round2, sLineSectionTrainer5Semifinal, sLineSectionTrainer5Final},
{sLineSectionTrainer6Round1, sLineSectionTrainer6Round2, sLineSectionTrainer6Semifinal, sLineSectionTrainer6Final},
{sLineSectionTrainer7Round1, sLineSectionTrainer7Round2, sLineSectionTrainer7Semifinal, sLineSectionTrainer7Final},
{sLineSectionTrainer8Round1, sLineSectionTrainer8Round2, sLineSectionTrainer8Semifinal, sLineSectionTrainer8Final},
{sLineSectionTrainer9Round1, sLineSectionTrainer9Round2, sLineSectionTrainer9Semifinal, sLineSectionTrainer9Final},
{sLineSectionTrainer10Round1, sLineSectionTrainer10Round2, sLineSectionTrainer10Semifinal, sLineSectionTrainer10Final},
{sLineSectionTrainer11Round1, sLineSectionTrainer11Round2, sLineSectionTrainer11Semifinal, sLineSectionTrainer11Final},
{sLineSectionTrainer12Round1, sLineSectionTrainer12Round2, sLineSectionTrainer12Semifinal, sLineSectionTrainer12Final},
{sLineSectionTrainer13Round1, sLineSectionTrainer13Round2, sLineSectionTrainer13Semifinal, sLineSectionTrainer13Final},
{sLineSectionTrainer14Round1, sLineSectionTrainer14Round2, sLineSectionTrainer14Semifinal, sLineSectionTrainer14Final},
{sLineSectionTrainer15Round1, sLineSectionTrainer15Round2, sLineSectionTrainer15Semifinal, sLineSectionTrainer15Final},
{sLineSectionTrainer16Round1, sLineSectionTrainer16Round2, sLineSectionTrainer16Semifinal, sLineSectionTrainer16Final},
};
static const u8 sTourneyTreeLineSectionArrayCounts[DOME_TOURNAMENT_TRAINERS_COUNT][DOME_ROUNDS_COUNT] =
{
{ARRAY_COUNT(sLineSectionTrainer1Round1), ARRAY_COUNT(sLineSectionTrainer1Round2), ARRAY_COUNT(sLineSectionTrainer1Semifinal), ARRAY_COUNT(sLineSectionTrainer1Final)},
{ARRAY_COUNT(sLineSectionTrainer2Round1), ARRAY_COUNT(sLineSectionTrainer2Round2), ARRAY_COUNT(sLineSectionTrainer2Semifinal), ARRAY_COUNT(sLineSectionTrainer2Final)},
{ARRAY_COUNT(sLineSectionTrainer3Round1), ARRAY_COUNT(sLineSectionTrainer3Round2), ARRAY_COUNT(sLineSectionTrainer3Semifinal), ARRAY_COUNT(sLineSectionTrainer3Final)},
{ARRAY_COUNT(sLineSectionTrainer4Round1), ARRAY_COUNT(sLineSectionTrainer4Round2), ARRAY_COUNT(sLineSectionTrainer4Semifinal), ARRAY_COUNT(sLineSectionTrainer4Final)},
{ARRAY_COUNT(sLineSectionTrainer5Round1), ARRAY_COUNT(sLineSectionTrainer5Round2), ARRAY_COUNT(sLineSectionTrainer5Semifinal), ARRAY_COUNT(sLineSectionTrainer5Final)},
{ARRAY_COUNT(sLineSectionTrainer6Round1), ARRAY_COUNT(sLineSectionTrainer6Round2), ARRAY_COUNT(sLineSectionTrainer6Semifinal), ARRAY_COUNT(sLineSectionTrainer6Final)},
{ARRAY_COUNT(sLineSectionTrainer7Round1), ARRAY_COUNT(sLineSectionTrainer7Round2), ARRAY_COUNT(sLineSectionTrainer7Semifinal), ARRAY_COUNT(sLineSectionTrainer7Final)},
{ARRAY_COUNT(sLineSectionTrainer8Round1), ARRAY_COUNT(sLineSectionTrainer8Round2), ARRAY_COUNT(sLineSectionTrainer8Semifinal), ARRAY_COUNT(sLineSectionTrainer8Final)},
{ARRAY_COUNT(sLineSectionTrainer9Round1), ARRAY_COUNT(sLineSectionTrainer9Round2), ARRAY_COUNT(sLineSectionTrainer9Semifinal), ARRAY_COUNT(sLineSectionTrainer9Final)},
{ARRAY_COUNT(sLineSectionTrainer10Round1), ARRAY_COUNT(sLineSectionTrainer10Round2), ARRAY_COUNT(sLineSectionTrainer10Semifinal), ARRAY_COUNT(sLineSectionTrainer10Final)},
{ARRAY_COUNT(sLineSectionTrainer11Round1), ARRAY_COUNT(sLineSectionTrainer11Round2), ARRAY_COUNT(sLineSectionTrainer11Semifinal), ARRAY_COUNT(sLineSectionTrainer11Final)},
{ARRAY_COUNT(sLineSectionTrainer12Round1), ARRAY_COUNT(sLineSectionTrainer12Round2), ARRAY_COUNT(sLineSectionTrainer12Semifinal), ARRAY_COUNT(sLineSectionTrainer12Final)},
{ARRAY_COUNT(sLineSectionTrainer13Round1), ARRAY_COUNT(sLineSectionTrainer13Round2), ARRAY_COUNT(sLineSectionTrainer13Semifinal), ARRAY_COUNT(sLineSectionTrainer13Final)},
{ARRAY_COUNT(sLineSectionTrainer14Round1), ARRAY_COUNT(sLineSectionTrainer14Round2), ARRAY_COUNT(sLineSectionTrainer14Semifinal), ARRAY_COUNT(sLineSectionTrainer14Final)},
{ARRAY_COUNT(sLineSectionTrainer15Round1), ARRAY_COUNT(sLineSectionTrainer15Round2), ARRAY_COUNT(sLineSectionTrainer15Semifinal), ARRAY_COUNT(sLineSectionTrainer15Final)},
{ARRAY_COUNT(sLineSectionTrainer16Round1), ARRAY_COUNT(sLineSectionTrainer16Round2), ARRAY_COUNT(sLineSectionTrainer16Semifinal), ARRAY_COUNT(sLineSectionTrainer16Final)},
};
void CallBattleDomeFunction(void)
{
sBattleDomeFunctions[gSpecialVar_0x8004]();
}
static void InitDomeChallenge(void)
{
u32 lvlMode = gSaveBlock2Ptr->frontier.lvlMode;
u32 battleMode = VarGet(VAR_FRONTIER_BATTLE_MODE);
gSaveBlock2Ptr->frontier.challengeStatus = 0;
gSaveBlock2Ptr->frontier.curChallengeBattleNum = 0;
gSaveBlock2Ptr->frontier.challengePaused = FALSE;
gSaveBlock2Ptr->frontier.disableRecordBattle = FALSE;
if (!(gSaveBlock2Ptr->frontier.winStreakActiveFlags & sWinStreakFlags[battleMode][lvlMode]))
gSaveBlock2Ptr->frontier.domeWinStreaks[battleMode][lvlMode] = 0;
SetDynamicWarp(0, gSaveBlock1Ptr->location.mapGroup, gSaveBlock1Ptr->location.mapNum, WARP_ID_NONE);
gTrainerBattleOpponent_A = 0;
}
static void GetDomeData(void)
{
u32 lvlMode = gSaveBlock2Ptr->frontier.lvlMode;
u32 battleMode = VarGet(VAR_FRONTIER_BATTLE_MODE);
switch (gSpecialVar_0x8005)
{
case DOME_DATA_WIN_STREAK:
gSpecialVar_Result = gSaveBlock2Ptr->frontier.domeWinStreaks[battleMode][lvlMode];
break;
case DOME_DATA_WIN_STREAK_ACTIVE:
gSpecialVar_Result = ((gSaveBlock2Ptr->frontier.winStreakActiveFlags & sWinStreakFlags[battleMode][lvlMode]) != 0);
break;
case DOME_DATA_ATTEMPTED_SINGLES_50:
gSpecialVar_Result = gSaveBlock2Ptr->frontier.domeAttemptedSingles50;
break;
case DOME_DATA_ATTEMPTED_SINGLES_OPEN:
gSpecialVar_Result = gSaveBlock2Ptr->frontier.domeAttemptedSinglesOpen;
break;
case DOME_DATA_HAS_WON_SINGLES_50:
gSpecialVar_Result = gSaveBlock2Ptr->frontier.domeHasWonSingles50;
break;
case DOME_DATA_HAS_WON_SINGLES_OPEN:
gSpecialVar_Result = gSaveBlock2Ptr->frontier.domeHasWonSinglesOpen;
break;
case DOME_DATA_ATTEMPTED_CHALLENGE:
if (VarGet(VAR_FRONTIER_BATTLE_MODE) == FRONTIER_MODE_DOUBLES)
{
if (lvlMode != FRONTIER_LVL_50)
gSpecialVar_Result = gSaveBlock2Ptr->frontier.domeAttemptedDoublesOpen;
else
gSpecialVar_Result = gSaveBlock2Ptr->frontier.domeAttemptedDoubles50;
}
else
{
if (lvlMode != FRONTIER_LVL_50)
gSpecialVar_Result = gSaveBlock2Ptr->frontier.domeAttemptedSinglesOpen;
else
gSpecialVar_Result = gSaveBlock2Ptr->frontier.domeAttemptedSingles50;
}
break;
case DOME_DATA_HAS_WON_CHALLENGE:
if (VarGet(VAR_FRONTIER_BATTLE_MODE) == FRONTIER_MODE_DOUBLES)
{
if (lvlMode != FRONTIER_LVL_50)
gSpecialVar_Result = gSaveBlock2Ptr->frontier.domeHasWonDoublesOpen;
else
gSpecialVar_Result = gSaveBlock2Ptr->frontier.domeHasWonDoubles50;
}
else
{
if (lvlMode != FRONTIER_LVL_50)
gSpecialVar_Result = gSaveBlock2Ptr->frontier.domeHasWonSinglesOpen;
else
gSpecialVar_Result = gSaveBlock2Ptr->frontier.domeHasWonSingles50;
}
break;
case DOME_DATA_SELECTED_MONS:
ClearSelectedPartyOrder();
gSelectedOrderFromParty[0] = gSaveBlock2Ptr->frontier.selectedPartyMons[3];
gSelectedOrderFromParty[1] = gSaveBlock2Ptr->frontier.selectedPartyMons[3] >> 8;
break;
case DOME_DATA_PREV_TOURNEY_TYPE:
gSpecialVar_Result = (gSaveBlock2Ptr->frontier.domeLvlMode * 2) - 3 + gSaveBlock2Ptr->frontier.domeBattleMode;
break;
}
}
static void SetDomeData(void)
{
u32 lvlMode = gSaveBlock2Ptr->frontier.lvlMode;
u32 battleMode = VarGet(VAR_FRONTIER_BATTLE_MODE);
switch (gSpecialVar_0x8005)
{
case DOME_DATA_WIN_STREAK:
gSaveBlock2Ptr->frontier.domeWinStreaks[battleMode][lvlMode] = gSpecialVar_0x8006;
break;
case DOME_DATA_WIN_STREAK_ACTIVE:
if (gSpecialVar_0x8006)
gSaveBlock2Ptr->frontier.winStreakActiveFlags |= sWinStreakFlags[battleMode][lvlMode];
else
gSaveBlock2Ptr->frontier.winStreakActiveFlags &= sWinStreakMasks[battleMode][lvlMode];
break;
case DOME_DATA_ATTEMPTED_SINGLES_50:
gSaveBlock2Ptr->frontier.domeAttemptedSingles50 = gSpecialVar_0x8006;
break;
case DOME_DATA_ATTEMPTED_SINGLES_OPEN:
gSaveBlock2Ptr->frontier.domeAttemptedSinglesOpen = gSpecialVar_0x8006;
break;
case DOME_DATA_HAS_WON_SINGLES_50:
gSaveBlock2Ptr->frontier.domeHasWonSingles50 = gSpecialVar_0x8006;
break;
case DOME_DATA_HAS_WON_SINGLES_OPEN:
gSaveBlock2Ptr->frontier.domeHasWonSinglesOpen = gSpecialVar_0x8006;
break;
case DOME_DATA_ATTEMPTED_CHALLENGE:
if (VarGet(VAR_FRONTIER_BATTLE_MODE) == FRONTIER_MODE_DOUBLES)
{
if (lvlMode != FRONTIER_LVL_50)
gSaveBlock2Ptr->frontier.domeAttemptedDoublesOpen = gSpecialVar_0x8006;
else
gSaveBlock2Ptr->frontier.domeAttemptedDoubles50 = gSpecialVar_0x8006;
}
else
{
if (lvlMode != FRONTIER_LVL_50)
gSaveBlock2Ptr->frontier.domeAttemptedSinglesOpen = gSpecialVar_0x8006;
else
gSaveBlock2Ptr->frontier.domeAttemptedSingles50 = gSpecialVar_0x8006;
}
break;
case DOME_DATA_HAS_WON_CHALLENGE:
if (VarGet(VAR_FRONTIER_BATTLE_MODE) == FRONTIER_MODE_DOUBLES)
{
if (lvlMode != FRONTIER_LVL_50)
gSaveBlock2Ptr->frontier.domeHasWonDoublesOpen = gSpecialVar_0x8006;
else
gSaveBlock2Ptr->frontier.domeHasWonDoubles50 = gSpecialVar_0x8006;
}
else
{
if (lvlMode != FRONTIER_LVL_50)
gSaveBlock2Ptr->frontier.domeHasWonSinglesOpen = gSpecialVar_0x8006;
else
gSaveBlock2Ptr->frontier.domeHasWonSingles50 = gSpecialVar_0x8006;
}
break;
case DOME_DATA_SELECTED_MONS:
gSaveBlock2Ptr->frontier.selectedPartyMons[3] = T1_READ_16(gSelectedOrderFromParty);
break;
}
}
static void InitDomeTrainers(void)
{
int i, j, k;
int monLevel;
int species[FRONTIER_PARTY_SIZE];
int monTypesBits, monTypesCount;
int trainerId;
int monId;
u16 *rankingScores;
int *statValues;
u8 ivs = 0;
species[0] = 0;
species[1] = 0;
species[2] = 0;
rankingScores = AllocZeroed(sizeof(u16) * DOME_TOURNAMENT_TRAINERS_COUNT);
statValues = AllocZeroed(sizeof(int) * NUM_STATS);
gSaveBlock2Ptr->frontier.domeLvlMode = gSaveBlock2Ptr->frontier.lvlMode + 1;
gSaveBlock2Ptr->frontier.domeBattleMode = VarGet(VAR_FRONTIER_BATTLE_MODE) + 1;
DOME_TRAINERS[0].trainerId = TRAINER_PLAYER;
DOME_TRAINERS[0].isEliminated = FALSE;
DOME_TRAINERS[0].eliminatedAt = 0;
DOME_TRAINERS[0].forfeited = FALSE;
// Store the data used to display party information on the player's tourney page
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
{
DOME_MONS[0][i] = GetMonData(&gPlayerParty[gSaveBlock2Ptr->frontier.selectedPartyMons[i] - 1], MON_DATA_SPECIES, NULL);
for (j = 0; j < MAX_MON_MOVES; j++)
gSaveBlock2Ptr->frontier.domePlayerPartyData[i].moves[j] = GetMonData(&gPlayerParty[gSaveBlock2Ptr->frontier.selectedPartyMons[i] - 1], MON_DATA_MOVE1 + j, NULL);
for (j = 0; j < NUM_STATS; j++)
gSaveBlock2Ptr->frontier.domePlayerPartyData[i].evs[j] = GetMonData(&gPlayerParty[gSaveBlock2Ptr->frontier.selectedPartyMons[i] - 1], MON_DATA_HP_EV + j, NULL);
gSaveBlock2Ptr->frontier.domePlayerPartyData[i].nature = GetNature(&gPlayerParty[gSaveBlock2Ptr->frontier.selectedPartyMons[i] - 1]);
}
// Populate the tourney roster with random frontier trainers (dependent on streak)
for (i = 1; i < DOME_TOURNAMENT_TRAINERS_COUNT; i++)
{
// Choose trainer. First 5/16 trainers are easier than the rest
if (i > 5)
{
do
{
trainerId = GetRandomScaledFrontierTrainerId(GetCurrentFacilityWinStreak(), 0);
for (j = 1; j < i; j++)
{
if (DOME_TRAINERS[j].trainerId == trainerId)
break;
}
} while (j != i);
DOME_TRAINERS[i].trainerId = trainerId;
}
else
{
do
{
trainerId = GetRandomScaledFrontierTrainerId(GetCurrentFacilityWinStreak() + 1, 0);
for (j = 1; j < i; j++)
{
if (DOME_TRAINERS[j].trainerId == trainerId)
break;
}
} while (j != i);
DOME_TRAINERS[i].trainerId = trainerId;
}
// Choose party
for (j = 0; j < FRONTIER_PARTY_SIZE; j++)
{
do
{
monId = GetRandomFrontierMonFromSet(trainerId);
for (k = 0; k < j; k++)
{
// Make sure the mon is valid.
int alreadySelectedMonId = DOME_MONS[i][k];
if (alreadySelectedMonId == monId
|| species[0] == gFacilityTrainerMons[monId].species
|| species[1] == gFacilityTrainerMons[monId].species
|| gFacilityTrainerMons[alreadySelectedMonId].itemTableId == gFacilityTrainerMons[monId].itemTableId)
break;
}
} while (k != j);
DOME_MONS[i][j] = monId;
species[j] = gFacilityTrainerMons[monId].species;
}
DOME_TRAINERS[i].isEliminated = FALSE;
DOME_TRAINERS[i].eliminatedAt = 0;
DOME_TRAINERS[i].forfeited = FALSE;
}
// rankingScores is used to determine the seed (ranking) of the trainers
// rankingScores[0] is for the player, rankingScores[1-15] are for the opponent trainers
// Calculate player's ranking score
monTypesBits = 0;
rankingScores[0] = 0;
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
{
// trainerId var re-used here as index of selected mons
trainerId = gSaveBlock2Ptr->frontier.selectedPartyMons[i] - 1;
rankingScores[0] += GetMonData(&gPlayerParty[trainerId], MON_DATA_ATK, NULL);
rankingScores[0] += GetMonData(&gPlayerParty[trainerId], MON_DATA_DEF, NULL);
rankingScores[0] += GetMonData(&gPlayerParty[trainerId], MON_DATA_SPATK, NULL);
rankingScores[0] += GetMonData(&gPlayerParty[trainerId], MON_DATA_SPDEF, NULL);
rankingScores[0] += GetMonData(&gPlayerParty[trainerId], MON_DATA_SPEED, NULL);
rankingScores[0] += GetMonData(&gPlayerParty[trainerId], MON_DATA_MAX_HP, NULL);
monTypesBits |= gBitTable[gSpeciesInfo[GetMonData(&gPlayerParty[trainerId], MON_DATA_SPECIES, NULL)].types[0]];
monTypesBits |= gBitTable[gSpeciesInfo[GetMonData(&gPlayerParty[trainerId], MON_DATA_SPECIES, NULL)].types[1]];
}
// Count the number of types in the players party, to factor into the ranking
for (monTypesCount = 0, j = 0; j < 32; j++)
{
if (monTypesBits & 1)
monTypesCount++;
monTypesBits >>= 1;
}
monLevel = SetFacilityPtrsGetLevel();
rankingScores[0] += (monTypesCount * monLevel) / 20;
// Calculate rankingScores for the opponent trainers
for (i = 1; i < DOME_TOURNAMENT_TRAINERS_COUNT; i++)
{
monTypesBits = 0;
rankingScores[i] = 0;
ivs = GetDomeTrainerMonIvs(DOME_TRAINERS[i].trainerId);
for (j = 0; j < FRONTIER_PARTY_SIZE; j++)
{
CalcDomeMonStats(gFacilityTrainerMons[DOME_MONS[i][j]].species,
monLevel, ivs,
gFacilityTrainerMons[DOME_MONS[i][j]].evSpread,
gFacilityTrainerMons[DOME_MONS[i][j]].nature,
statValues);
rankingScores[i] += statValues[STAT_ATK];
rankingScores[i] += statValues[STAT_DEF];
rankingScores[i] += statValues[STAT_SPATK];
rankingScores[i] += statValues[STAT_SPDEF];
rankingScores[i] += statValues[STAT_SPEED];
rankingScores[i] += statValues[STAT_HP];
monTypesBits |= gBitTable[gSpeciesInfo[gFacilityTrainerMons[DOME_MONS[i][j]].species].types[0]];
monTypesBits |= gBitTable[gSpeciesInfo[gFacilityTrainerMons[DOME_MONS[i][j]].species].types[1]];
}
for (monTypesCount = 0, j = 0; j < 32; j++)
{
if (monTypesBits & 1)
monTypesCount++;
monTypesBits >>= 1;
}
rankingScores[i] += (monTypesCount * monLevel) / 20;
}
// Seed tourney trainers according to their ranking
for (i = 0; i < DOME_TOURNAMENT_TRAINERS_COUNT - 1; i++)
{
for (j = i + 1; j < DOME_TOURNAMENT_TRAINERS_COUNT; j++)
{
if (rankingScores[i] < rankingScores[j])
{
SwapDomeTrainers(i, j, rankingScores);
}
else
{
if (rankingScores[i] == rankingScores[j])
{
if (DOME_TRAINERS[j].trainerId == TRAINER_PLAYER)
SwapDomeTrainers(i, j, rankingScores);
else if (DOME_TRAINERS[i].trainerId > DOME_TRAINERS[j].trainerId)
SwapDomeTrainers(i, j, rankingScores);
}
}
}
}
// Add Frontier Brain to the tourney if they should be fought at the end of it
if (GetFrontierBrainStatus() != FRONTIER_BRAIN_NOT_READY)
{
for (i = 0; i < DOME_TOURNAMENT_TRAINERS_COUNT; i++)
{
if (DOME_TRAINERS[i].trainerId == TRAINER_PLAYER)
break;
}
if (sTrainerNamePositions[i][0] != TOURNEYWIN_NAMES_LEFT)
{
j = 0;
DOME_TRAINERS[j].trainerId = TRAINER_FRONTIER_BRAIN;
}
else
{
j = 1;
DOME_TRAINERS[j].trainerId = TRAINER_FRONTIER_BRAIN;
}
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
DOME_MONS[j][i] = GetFrontierBrainMonSpecies(i);
}
Free(rankingScores);
Free(statValues);
}
#define CALC_STAT(base, statIndex) \
{ \
u8 baseStat = gSpeciesInfo[species].base; \
stats[statIndex] = (((2 * baseStat + ivs + evs[statIndex] / 4) * level) / 100) + 5; \
stats[statIndex] = (u8) ModifyStatByNature(nature, stats[statIndex], statIndex); \
}
static void CalcDomeMonStats(u16 species, int level, int ivs, u8 evBits, u8 nature, int *stats)
{
int i, count;
u8 bits;
u16 resultingEvs;
int evs[NUM_STATS];
count = 0, bits = evBits;
for (i = 0; i < NUM_STATS; bits >>= 1, i++)
{
if (bits & 1)
count++;
}
resultingEvs = MAX_TOTAL_EVS / count;
for (i = 0; i < NUM_STATS; bits <<= 1, i++)
{
evs[i] = 0;
if (evBits & bits)
evs[i] = resultingEvs;
}
if (species == SPECIES_SHEDINJA)
{
stats[STAT_HP] = 1;
}
else
{
int n = 2 * gSpeciesInfo[species].baseHP;
stats[STAT_HP] = (((n + ivs + evs[STAT_HP] / 4) * level) / 100) + level + 10;
}
CALC_STAT(baseAttack, STAT_ATK);
CALC_STAT(baseDefense, STAT_DEF);
CALC_STAT(baseSpeed, STAT_SPEED);
CALC_STAT(baseSpAttack, STAT_SPATK);
CALC_STAT(baseSpDefense, STAT_SPDEF);
}
static void SwapDomeTrainers(int id1, int id2, u16 *statsArray)
{
int i;
u16 temp;
SWAP(statsArray[id1], statsArray[id2], temp);
SWAP(DOME_TRAINERS[id1].trainerId, DOME_TRAINERS[id2].trainerId, temp);
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
SWAP(DOME_MONS[id1][i], DOME_MONS[id2][i], temp);
}
static void BufferDomeRoundText(void)
{
StringCopy(gStringVar1, gRoundsStringTable[gSaveBlock2Ptr->frontier.curChallengeBattleNum]);
}
static void BufferDomeOpponentName(void)
{
StringCopy(gStringVar1, gRoundsStringTable[gSaveBlock2Ptr->frontier.curChallengeBattleNum]);
CopyDomeTrainerName(gStringVar2, gTrainerBattleOpponent_A);
}
static void InitDomeOpponentParty(void)
{
gPlayerPartyLostHP = 0;
sPlayerPartyMaxHP = GetMonData(&gPlayerParty[0], MON_DATA_MAX_HP, NULL);
sPlayerPartyMaxHP += GetMonData(&gPlayerParty[1], MON_DATA_MAX_HP, NULL);
CalculatePlayerPartyCount();
CreateDomeOpponentMons(TrainerIdToTournamentId(gTrainerBattleOpponent_A));
}
static void CreateDomeOpponentMon(u8 monPartyId, u16 tournamentTrainerId, u8 tournamentMonId, u32 otId)
{
int i;
u8 friendship = MAX_FRIENDSHIP;
#ifdef BUGFIX
u8 fixedIv = GetDomeTrainerMonIvs(DOME_TRAINERS[tournamentTrainerId].trainerId);
#else
u8 fixedIv = GetDomeTrainerMonIvs(tournamentTrainerId); // BUG: Using the wrong ID. As a result, all Pokemon have ivs of 3.
#endif
u8 level = SetFacilityPtrsGetLevel();
CreateMonWithEVSpreadNatureOTID(&gEnemyParty[monPartyId],
gFacilityTrainerMons[DOME_MONS[tournamentTrainerId][tournamentMonId]].species,
level,
gFacilityTrainerMons[DOME_MONS[tournamentTrainerId][tournamentMonId]].nature,
fixedIv,
gFacilityTrainerMons[DOME_MONS[tournamentTrainerId][tournamentMonId]].evSpread, otId);
friendship = MAX_FRIENDSHIP;
for (i = 0; i < MAX_MON_MOVES; i++)
{
SetMonMoveSlot(&gEnemyParty[monPartyId],
gFacilityTrainerMons[DOME_MONS[tournamentTrainerId][tournamentMonId]].moves[i], i);
if (gFacilityTrainerMons[DOME_MONS[tournamentTrainerId][tournamentMonId]].moves[i] == MOVE_FRUSTRATION)
friendship = 0;
}
SetMonData(&gEnemyParty[monPartyId], MON_DATA_FRIENDSHIP, &friendship);
SetMonData(&gEnemyParty[monPartyId], MON_DATA_HELD_ITEM,
&gBattleFrontierHeldItems[gFacilityTrainerMons[DOME_MONS[tournamentTrainerId][tournamentMonId]].itemTableId]);
}
static void CreateDomeOpponentMons(u16 tournamentTrainerId)
{
u8 monsCount = 0;
u32 otId = 0;
int i, selectedMonBits;
ZeroEnemyPartyMons();
selectedMonBits = GetDomeTrainerSelectedMons(tournamentTrainerId);
otId = Random32();
if (Random() % 10 > 5)
{
// Create mon if it was selected, starting from front
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
{
if (selectedMonBits & 1)
{
CreateDomeOpponentMon(monsCount, tournamentTrainerId, i, otId);
monsCount++;
}
selectedMonBits >>= 1;
}
}
else
{
// Create mon if it was selected, starting from back
for (i = FRONTIER_PARTY_SIZE - 1; i >= 0; i--)
{
if (selectedMonBits & (1 << (FRONTIER_PARTY_SIZE - 1)))
{
CreateDomeOpponentMon(monsCount, tournamentTrainerId, i, otId);
monsCount++;
}
selectedMonBits <<= 1;
}
}
}
// Returns a bitmask representing which 2 of the trainer's 3 pokemon to select.
// The choice is calculated solely depending on the type effectiveness of their
// movesets against the player's pokemon.
// There is a 50% chance of either a "good" or "bad" selection mode being used.
// In the good mode movesets are preferred which are more effective against the
// player, and in the bad mode the opposite is true. If all 3 pokemon tie, the
// other mode will be tried. If they tie again, the pokemon selection is random.
int GetDomeTrainerSelectedMons(u16 tournamentTrainerId)
{
int selectedMonBits;
if (Random() & 1)
{
selectedMonBits = SelectOpponentMons_Good(tournamentTrainerId, FALSE);
if (selectedMonBits == 0)
selectedMonBits = SelectOpponentMons_Bad(tournamentTrainerId, TRUE);
}
else
{
selectedMonBits = SelectOpponentMons_Bad(tournamentTrainerId, FALSE);
if (selectedMonBits == 0)
selectedMonBits = SelectOpponentMons_Good(tournamentTrainerId, TRUE);
}
return selectedMonBits;
}
static int SelectOpponentMons_Good(u16 tournamentTrainerId, bool8 allowRandom)
{
int i, moveId, playerMonId;
int partyMovePoints[FRONTIER_PARTY_SIZE];
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
{
partyMovePoints[i] = 0;
for (moveId = 0; moveId < MAX_MON_MOVES; moveId++)
{
for (playerMonId = 0; playerMonId < FRONTIER_PARTY_SIZE; playerMonId++)
{
if (DOME_TRAINERS[tournamentTrainerId].trainerId == TRAINER_FRONTIER_BRAIN)
{
partyMovePoints[i] += GetTypeEffectivenessPoints(GetFrontierBrainMonMove(i, moveId),
GetMonData(&gPlayerParty[playerMonId], MON_DATA_SPECIES, NULL), EFFECTIVENESS_MODE_GOOD);
}
else
{
partyMovePoints[i] += GetTypeEffectivenessPoints(gFacilityTrainerMons[DOME_MONS[tournamentTrainerId][i]].moves[moveId],
GetMonData(&gPlayerParty[playerMonId], MON_DATA_SPECIES, NULL), EFFECTIVENESS_MODE_GOOD);
}
}
}
}
return SelectOpponentMonsFromParty(partyMovePoints, allowRandom);
}
// Identical to function above, but uses EFFECTIVENESS_MODE_BAD
static int SelectOpponentMons_Bad(u16 tournamentTrainerId, bool8 allowRandom)
{
int i, moveId, playerMonId;
int partyMovePoints[FRONTIER_PARTY_SIZE];
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
{
partyMovePoints[i] = 0;
for (moveId = 0; moveId < MAX_MON_MOVES; moveId++)
{
for (playerMonId = 0; playerMonId < FRONTIER_PARTY_SIZE; playerMonId++)
{
if (DOME_TRAINERS[tournamentTrainerId].trainerId == TRAINER_FRONTIER_BRAIN)
{
partyMovePoints[i] += GetTypeEffectivenessPoints(GetFrontierBrainMonMove(i, moveId),
GetMonData(&gPlayerParty[playerMonId], MON_DATA_SPECIES, NULL), EFFECTIVENESS_MODE_BAD);
}
else
{
partyMovePoints[i] += GetTypeEffectivenessPoints(gFacilityTrainerMons[DOME_MONS[tournamentTrainerId][i]].moves[moveId],
GetMonData(&gPlayerParty[playerMonId], MON_DATA_SPECIES, NULL), EFFECTIVENESS_MODE_BAD);
}
}
}
}
return SelectOpponentMonsFromParty(partyMovePoints, allowRandom);
}
static int SelectOpponentMonsFromParty(int *partyMovePoints, bool8 allowRandom)
{
int i, j;
int selectedMonBits = 0;
int partyPositions[FRONTIER_PARTY_SIZE];
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
partyPositions[i] = i;
// All party mons have equal move score totals, choose randomly
if (partyMovePoints[0] == partyMovePoints[1]
&& partyMovePoints[0] == partyMovePoints[2])
{
if (allowRandom)
{
i = 0;
while (i != DOME_BATTLE_PARTY_SIZE)
{
u32 rand = Random() & FRONTIER_PARTY_SIZE;
if (rand != FRONTIER_PARTY_SIZE && !(selectedMonBits & gBitTable[rand]))
{
selectedMonBits |= gBitTable[rand];
i++;
}
}
}
}
else
{
for (i = 0; i < DOME_BATTLE_PARTY_SIZE; i++)
{
for (j = i + 1; j < FRONTIER_PARTY_SIZE; j++)
{
int temp;
if (partyMovePoints[i] < partyMovePoints[j])
{
SWAP(partyMovePoints[i], partyMovePoints[j],temp)
SWAP(partyPositions[i], partyPositions[j], temp)
}
if (partyMovePoints[i] == partyMovePoints[j] && (Random() & 1))
{
SWAP(partyMovePoints[i], partyMovePoints[j],temp)
SWAP(partyPositions[i], partyPositions[j], temp)
}
}
}
for (i = 0; i < DOME_BATTLE_PARTY_SIZE; i++)
{
selectedMonBits |= gBitTable[partyPositions[i]];
}
}
return selectedMonBits;
}
#define TYPE_x0 0
#define TYPE_x0_25 5
#define TYPE_x0_50 10
#define TYPE_x1 20
#define TYPE_x2 40
#define TYPE_x4 80
static int GetTypeEffectivenessPoints(int move, int targetSpecies, int mode)
{
int defType1, defType2, defAbility, moveType;
int i = 0;
int typePower = TYPE_x1;
if (move == MOVE_NONE || move == MOVE_UNAVAILABLE || gBattleMoves[move].power == 0)
return 0;
defType1 = gSpeciesInfo[targetSpecies].types[0];
defType2 = gSpeciesInfo[targetSpecies].types[1];
defAbility = gSpeciesInfo[targetSpecies].abilities[0];
moveType = gBattleMoves[move].type;
if (defAbility == ABILITY_LEVITATE && moveType == TYPE_GROUND)
{
// They likely meant to return here, as 8 is the number of points normally used in this mode for moves with no effect.
// Because there's no return the value instead gets interpreted by the switch, and the number of points becomes 0.
if (mode == EFFECTIVENESS_MODE_BAD)
{
typePower = 8;
#ifdef BUGFIX
return typePower;
#endif
}
}
else
{
// Calculate a "type power" value to determine the benefit of using this type move against the target.
// This value will then be used to get the number of points to assign to the move.
while (TYPE_EFFECT_ATK_TYPE(i) != TYPE_ENDTABLE)
{
if (TYPE_EFFECT_ATK_TYPE(i) == TYPE_FORESIGHT)
{
i += 3;
continue;
}
if (TYPE_EFFECT_ATK_TYPE(i) == moveType)
{
// BUG: the value of TYPE_x2 does not exist in gTypeEffectiveness, so if defAbility is ABILITY_WONDER_GUARD, the conditional always fails
#ifndef BUGFIX
#define WONDER_GUARD_EFFECTIVENESS TYPE_x2
#else
#define WONDER_GUARD_EFFECTIVENESS TYPE_MUL_SUPER_EFFECTIVE
#endif
if (TYPE_EFFECT_DEF_TYPE(i) == defType1)
if ((defAbility == ABILITY_WONDER_GUARD && TYPE_EFFECT_MULTIPLIER(i) == WONDER_GUARD_EFFECTIVENESS) || defAbility != ABILITY_WONDER_GUARD)
typePower = (typePower * TYPE_EFFECT_MULTIPLIER(i)) / 10;
if (TYPE_EFFECT_DEF_TYPE(i) == defType2 && defType1 != defType2)
if ((defAbility == ABILITY_WONDER_GUARD && TYPE_EFFECT_MULTIPLIER(i) == WONDER_GUARD_EFFECTIVENESS) || defAbility != ABILITY_WONDER_GUARD)
typePower = (typePower * TYPE_EFFECT_MULTIPLIER(i)) / 10;
}
i += 3;
}
}
switch (mode)
{
case EFFECTIVENESS_MODE_GOOD:
// Weights moves that more effective.
switch (typePower)
{
case TYPE_x0:
case TYPE_x0_25:
case TYPE_x0_50:
default:
typePower = 0;
break;
case TYPE_x1:
typePower = 2;
break;
case TYPE_x2:
typePower = 4;
break;
case TYPE_x4:
typePower = 8;
break;
}
break;
case EFFECTIVENESS_MODE_BAD:
// Weights moves that are less effective.
// Odd that there's no limit on this being used, even the Frontier Brain could end up using this.
switch (typePower)
{
case TYPE_x0:
typePower = 8;
break;
case TYPE_x0_25:
typePower = 4;
break;
case TYPE_x0_50:
typePower = 2;
break;
default:
case TYPE_x1:
typePower = 0;
break;
case TYPE_x2:
typePower = -2;
break;
case TYPE_x4:
typePower = -4;
break;
}
break;
case EFFECTIVENESS_MODE_AI_VS_AI:
// Used as part of calculating the winner in a battle between two AIs.
// Weights moves that are more effective much more strongly in both directions.
switch (typePower)
{
case TYPE_x0:
typePower = -16;
break;
case TYPE_x0_25:
typePower = -8;
break;
case TYPE_x0_50:
default:
typePower = 0;
break;
case TYPE_x1:
typePower = 4;
break;
case TYPE_x2:
typePower = 12;
break;
case TYPE_x4:
typePower = 20;
break;
}
break;
}
return typePower;
}
// Duplicate of GetFrontierTrainerFixedIvs
// NOTE: In CreateDomeOpponentMon a tournament trainer ID (0-15) is passed instead, resulting in all IVs of 3
// To fix, see CreateDomeOpponentMon
static u8 GetDomeTrainerMonIvs(u16 trainerId)
{
u8 fixedIv;
if (trainerId <= FRONTIER_TRAINER_JILL) // 0 - 99
fixedIv = 3;
else if (trainerId <= FRONTIER_TRAINER_CHLOE) // 100 - 119
fixedIv = 6;
else if (trainerId <= FRONTIER_TRAINER_SOFIA) // 120 - 139
fixedIv = 9;
else if (trainerId <= FRONTIER_TRAINER_JAZLYN) // 140 - 159
fixedIv = 12;
else if (trainerId <= FRONTIER_TRAINER_ALISON) // 160 - 179
fixedIv = 15;
else if (trainerId <= FRONTIER_TRAINER_LAMAR) // 180 - 199
fixedIv = 18;
else if (trainerId <= FRONTIER_TRAINER_TESS) // 200 - 219
fixedIv = 21;
else // 220+ (- 299)
fixedIv = MAX_PER_STAT_IVS;
return fixedIv;
}
static int TournamentIdOfOpponent(int roundId, int trainerId)
{
int i, j, opponentMax;
// Get trainer's tournament id
for (i = 0; i < DOME_TOURNAMENT_TRAINERS_COUNT; i++)
{
if (DOME_TRAINERS[i].trainerId == trainerId)
break;
}
// Get trainer's opponent's tournament id
if (roundId != DOME_ROUND1)
{
if (roundId == DOME_FINAL)
opponentMax = sIdToOpponentId[i][roundId] + 8;
else
opponentMax = sIdToOpponentId[i][roundId] + 4;
// Get first non-eliminated trainer in range of possible opponents
for (j = sIdToOpponentId[i][roundId]; j < opponentMax; j++)
{
if (sTourneyTreeTrainerOpponentIds[j] != i && !DOME_TRAINERS[sTourneyTreeTrainerOpponentIds[j]].isEliminated)
break;
}
if (j != opponentMax)
return sTourneyTreeTrainerOpponentIds[j];
else
return 0xFF; // Already eliminated
}
else
{
if (!DOME_TRAINERS[sIdToOpponentId[i][roundId]].isEliminated)
return sIdToOpponentId[i][roundId];
else
return 0xFF; // Already eliminated
}
}
static void SetDomeOpponentId(void)
{
gTrainerBattleOpponent_A = TrainerIdOfPlayerOpponent();
}
// While not an issue in-game, this will overflow if called after the player's opponent for the current round has been eliminated
static u16 TrainerIdOfPlayerOpponent(void)
{
return DOME_TRAINERS[TournamentIdOfOpponent(gSaveBlock2Ptr->frontier.curChallengeBattleNum, TRAINER_PLAYER)].trainerId;
}
static void SetDomeOpponentGraphicsId(void)
{
SetBattleFacilityTrainerGfxId(gTrainerBattleOpponent_A, 0);
}
static void SaveDomeChallenge(void)
{
gSaveBlock2Ptr->frontier.challengeStatus = gSpecialVar_0x8005;
VarSet(VAR_TEMP_CHALLENGE_STATUS, 0);
gSaveBlock2Ptr->frontier.challengePaused = TRUE;
SaveGameFrontier();
}
static void IncrementDomeStreaks(void)
{
u8 lvlMode = gSaveBlock2Ptr->frontier.lvlMode;
u8 battleMode = VarGet(VAR_FRONTIER_BATTLE_MODE);
if (gSaveBlock2Ptr->frontier.domeWinStreaks[battleMode][lvlMode] < 999)
gSaveBlock2Ptr->frontier.domeWinStreaks[battleMode][lvlMode]++;
if (gSaveBlock2Ptr->frontier.domeTotalChampionships[battleMode][lvlMode] < 999)
gSaveBlock2Ptr->frontier.domeTotalChampionships[battleMode][lvlMode]++;
if (gSaveBlock2Ptr->frontier.domeWinStreaks[battleMode][lvlMode] > gSaveBlock2Ptr->frontier.domeRecordWinStreaks[battleMode][lvlMode])
gSaveBlock2Ptr->frontier.domeRecordWinStreaks[battleMode][lvlMode] = gSaveBlock2Ptr->frontier.domeWinStreaks[battleMode][lvlMode];
}
// For showing the opponent info card of the upcoming trainer
static void ShowDomeOpponentInfo(void)
{
u8 taskId = CreateTask(Task_ShowTourneyInfoCard, 0);
gTasks[taskId].tState = 0;
gTasks[taskId].tTournamentId = TrainerIdToTournamentId(TrainerIdOfPlayerOpponent());
gTasks[taskId].tMode = INFOCARD_NEXT_OPPONENT;
gTasks[taskId].tPrevTaskId = 0;
SetMainCallback2(CB2_TourneyTree);
}
// For showing the opponent info card or the match info card
static void Task_ShowTourneyInfoCard(u8 taskId)
{
int i;
int tournamentId = gTasks[taskId].tTournamentId;
int mode = gTasks[taskId].tMode;
int id = gTasks[taskId].tPrevTaskId;
switch (gTasks[taskId].tState)
{
case 0:
SetHBlankCallback(NULL);
SetVBlankCallback(NULL);
EnableInterrupts(INTR_FLAG_VBLANK);
CpuFill32(0, (void *)VRAM, VRAM_SIZE);
ResetBgsAndClearDma3BusyFlags(0);
InitBgsFromTemplates(0, sInfoCardBgTemplates, ARRAY_COUNT(sInfoCardBgTemplates));
InitWindows(sInfoCardWindowTemplates);
DeactivateAllTextPrinters();
gBattle_BG0_X = 0;
gBattle_BG0_Y = 0;
gBattle_BG1_X = 0;
gBattle_BG1_Y = 0;
gBattle_BG3_X = 0;
gBattle_BG3_Y = 0;
if (mode == INFOCARD_MATCH)
gBattle_BG2_X = 0, gBattle_BG2_Y = 0;
else
gBattle_BG2_X = 0, gBattle_BG2_Y = DISPLAY_HEIGHT;
gTasks[taskId].tState++;
break;
case 1:
SetGpuReg(REG_OFFSET_BLDCNT, 0);
SetGpuReg(REG_OFFSET_BLDALPHA, 0);
SetGpuReg(REG_OFFSET_BLDY, 0);
SetGpuReg(REG_OFFSET_MOSAIC, 0);
SetGpuReg(REG_OFFSET_WIN0H, 0);
SetGpuReg(REG_OFFSET_WIN0V, 0);
SetGpuReg(REG_OFFSET_WIN1H, 0);
SetGpuReg(REG_OFFSET_WIN1V, 0);
SetGpuReg(REG_OFFSET_WININ, 0);
SetGpuReg(REG_OFFSET_WINOUT, WINOUT_WIN01_BG_ALL | WINOUT_WIN01_OBJ | WINOUT_WIN01_CLR);
ResetPaletteFade();
ResetSpriteData();
FreeAllSpritePalettes();
gReservedSpritePaletteCount = 4;
gTasks[taskId].tState++;
break;
case 2:
DecompressAndLoadBgGfxUsingHeap(2, gDomeTourneyInfoCard_Gfx, 0x2000, 0, 0);
DecompressAndLoadBgGfxUsingHeap(2, gDomeTourneyInfoCard_Tilemap, 0x2000, 0, 1);
DecompressAndLoadBgGfxUsingHeap(3, gDomeTourneyInfoCardBg_Tilemap, 0x800, 0, 1);
LoadCompressedSpriteSheet(sTourneyTreeButtonsSpriteSheet);
LoadCompressedPalette(gDomeTourneyTree_Pal, BG_PLTT_OFFSET, BG_PLTT_SIZE);
LoadCompressedPalette(gDomeTourneyTreeButtons_Pal, OBJ_PLTT_OFFSET, OBJ_PLTT_SIZE);
LoadCompressedPalette(gBattleWindowTextPalette, BG_PLTT_ID(15), PLTT_SIZE_4BPP);
if (mode == INFOCARD_MATCH)
LoadCompressedPalette(gDomeTourneyMatchCardBg_Pal, BG_PLTT_ID(5), PLTT_SIZE_4BPP); // Changes the moving info card bg to orange when in match card mode
CpuFill32(0, gPlttBufferFaded, PLTT_SIZE);
ShowBg(0);
ShowBg(1);
ShowBg(2);
ShowBg(3);
gTasks[taskId].tState++;
break;
case 3:
SetVBlankCallback(VblankCb_TourneyInfoCard);
sInfoCard = AllocZeroed(sizeof(*sInfoCard));
for (i = 0; i < NUM_INFOCARD_SPRITES; i++)
sInfoCard->spriteIds[i] = SPRITE_NONE;
LoadMonIconPalettes();
i = CreateTask(Task_HandleInfoCardInput, 0);
gTasks[i].data[0] = 0;
gTasks[i].data[2] = 0;
gTasks[i].data[3] = mode;
gTasks[i].data[4] = id;
if (mode == INFOCARD_MATCH)
{
DisplayMatchInfoOnCard(0, tournamentId);
sInfoCard->pos = 1;
}
else
{
DisplayTrainerInfoOnCard(0, tournamentId);
}
SetGpuReg(REG_OFFSET_DISPCNT, DISPCNT_OBJ_ON | DISPCNT_BG_ALL_ON | DISPCNT_OBJ_1D_MAP);
if (mode != INFOCARD_NEXT_OPPONENT)
{
// Scroll up arrow
id = CreateSprite(&sVerticalScrollArrowSpriteTemplate, 120, 4, 0);
StartSpriteAnim(&gSprites[id], 0);
gSprites[id].data[0] = i;
// Scroll down arrow
id = CreateSprite(&sVerticalScrollArrowSpriteTemplate, 120, 156, 0);
StartSpriteAnim(&gSprites[id], 1);
gSprites[id].data[0] = i;
// Scroll left arrow
id = CreateSprite(&sHorizontalScrollArrowSpriteTemplate, 6, 80, 0);
StartSpriteAnim(&gSprites[id], 0);
gSprites[id].data[0] = i;
gSprites[id].data[1] = 0;
if (mode == INFOCARD_TRAINER)
gSprites[id].invisible = TRUE;
// Scroll right arrow
id = CreateSprite(&sHorizontalScrollArrowSpriteTemplate, 234, 80, 0);
StartSpriteAnim(&gSprites[id], 1);
gSprites[id].data[0] = i;
gSprites[id].data[1] = 1;
}
DestroyTask(taskId);
break;
}
}
// Note: Card scrolling up means the current card goes down and another one appears from top.
// The same is true for scrolling left.
// That means that the sprite needs to move with the moving card in the opposite scrolling direction.
static void SpriteCB_TrainerIconCardScrollUp(struct Sprite *sprite)
{
sprite->y += 4;
if (sprite->data[0] != 0)
{
if (sprite->y >= -32)
sprite->invisible = FALSE;
if (++sprite->data[1] == 40)
sprite->callback = SpriteCallbackDummy;
}
else
{
if (sprite->y >= 192)
{
sInfoCard->spriteIds[sprite->data[2]] = SPRITE_NONE;
FreeAndDestroyTrainerPicSprite(sprite->data[3]);
}
}
}
static void SpriteCB_TrainerIconCardScrollDown(struct Sprite *sprite)
{
sprite->y -= 4;
if (sprite->data[0] != 0)
{
if (sprite->y <= 192)
sprite->invisible = FALSE;
if (++sprite->data[1] == 40)
sprite->callback = SpriteCallbackDummy;
}
else
{
if (sprite->y <= -32)
{
sInfoCard->spriteIds[sprite->data[2]] = SPRITE_NONE;
FreeAndDestroyTrainerPicSprite(sprite->data[3]);
}
}
}
static void SpriteCB_TrainerIconCardScrollLeft(struct Sprite *sprite)
{
sprite->x += 4;
if (sprite->data[0] != 0)
{
if (sprite->x >= -32)
sprite->invisible = FALSE;
if (++sprite->data[1] == 64)
sprite->callback = SpriteCallbackDummy;
}
else
{
if (sprite->x >= DISPLAY_WIDTH + 32)
{
sInfoCard->spriteIds[sprite->data[2]] = SPRITE_NONE;
FreeAndDestroyTrainerPicSprite(sprite->data[3]);
}
}
}
static void SpriteCB_TrainerIconCardScrollRight(struct Sprite *sprite)
{
sprite->x -= 4;
if (sprite->data[0] != 0)
{
if (sprite->x <= DISPLAY_WIDTH + 32)
sprite->invisible = FALSE;
if (++sprite->data[1] == 64)
sprite->callback = SpriteCallbackDummy;
}
else
{
if (sprite->x <= -32)
{
sInfoCard->spriteIds[sprite->data[2]] = SPRITE_NONE;
FreeAndDestroyTrainerPicSprite(sprite->data[3]);
}
}
}
#define sMonIconStill data[3]
static void SpriteCB_MonIconDomeInfo(struct Sprite *sprite)
{
if (!sprite->sMonIconStill)
UpdateMonIconFrame(sprite);
}
static void SpriteCB_MonIconCardScrollUp(struct Sprite *sprite)
{
if (!sprite->sMonIconStill)
UpdateMonIconFrame(sprite);
sprite->y += 4;
if (sprite->data[0] != 0)
{
if (sprite->y >= -16)
sprite->invisible = FALSE;
if (++sprite->data[1] == 40)
sprite->callback = SpriteCB_MonIconDomeInfo;
}
else
{
if (sprite->y >= 176)
{
sInfoCard->spriteIds[sprite->data[2]] = SPRITE_NONE;
FreeAndDestroyMonIconSprite(sprite);
}
}
}
static void SpriteCB_MonIconCardScrollDown(struct Sprite *sprite)
{
if (!sprite->sMonIconStill)
UpdateMonIconFrame(sprite);
sprite->y -= 4;
if (sprite->data[0] != 0)
{
if (sprite->y <= 176)
sprite->invisible = FALSE;
if (++sprite->data[1] == 40)
sprite->callback = SpriteCB_MonIconDomeInfo;
}
else
{
if (sprite->y <= -16)
{
sInfoCard->spriteIds[sprite->data[2]] = SPRITE_NONE;
FreeAndDestroyMonIconSprite(sprite);
}
}
}
static void SpriteCB_MonIconCardScrollLeft(struct Sprite *sprite)
{
if (!sprite->sMonIconStill)
UpdateMonIconFrame(sprite);
sprite->x += 4;
if (sprite->data[0] != 0)
{
if (sprite->x >= -16)
sprite->invisible = FALSE;
if (++sprite->data[1] == 64)
sprite->callback = SpriteCB_MonIconDomeInfo;
}
else
{
if (sprite->x >= DISPLAY_WIDTH + 16)
{
sInfoCard->spriteIds[sprite->data[2]] = SPRITE_NONE;
FreeAndDestroyMonIconSprite(sprite);
}
}
}
static void SpriteCB_MonIconCardScrollRight(struct Sprite *sprite)
{
if (!sprite->sMonIconStill)
UpdateMonIconFrame(sprite);
sprite->x -= 4;
if (sprite->data[0] != 0)
{
if (sprite->x <= DISPLAY_WIDTH + 16)
sprite->invisible = FALSE;
if (++sprite->data[1] == 64)
sprite->callback = SpriteCB_MonIconDomeInfo;
}
else
{
if (sprite->x <= -16)
{
sInfoCard->spriteIds[sprite->data[2]] = SPRITE_NONE;
FreeAndDestroyMonIconSprite(sprite);
}
}
}
static void SpriteCB_HorizontalScrollArrow(struct Sprite *sprite)
{
int taskId1 = sprite->data[0];
int arrId = gTasks[gTasks[taskId1].data[4]].data[1];
int tournmanetTrainerId = sTourneyTreeTrainerIds[arrId];
int roundId = gSaveBlock2Ptr->frontier.curChallengeBattleNum;
if (gTasks[taskId1].data[3] == 1)
{
if (sprite->data[1])
{
if ((DOME_TRAINERS[tournmanetTrainerId].isEliminated
&& sInfoCard->pos - 1 < DOME_TRAINERS[tournmanetTrainerId].eliminatedAt))
{
sprite->invisible = FALSE;
}
else if (!DOME_TRAINERS[tournmanetTrainerId].isEliminated
&& sInfoCard->pos - 1 < roundId)
{
sprite->invisible = FALSE;
}
else
{
if (gTasks[taskId1].data[0] == 2)
sprite->invisible = TRUE;
}
}
else
{
if (sInfoCard->pos != 0)
{
sprite->invisible = FALSE;
}
else
{
if (gTasks[taskId1].data[0] == 2)
sprite->invisible = TRUE;
}
}
}
else
{
if (sprite->data[1])
{
if (sInfoCard->pos > 1)
{
if (gTasks[taskId1].data[0] == 2)
sprite->invisible = TRUE;
}
else
{
sprite->invisible = FALSE;
}
}
else
{
if (sInfoCard->pos != 0)
{
sprite->invisible = FALSE;
}
else
{
if (gTasks[taskId1].data[0] == 2)
sprite->invisible = TRUE;
}
}
}
}
static void SpriteCB_VerticalScrollArrow(struct Sprite *sprite)
{
int taskId1 = sprite->data[0];
if (gTasks[taskId1].data[3] == 1)
{
if (sInfoCard->pos != 0)
{
if (gTasks[taskId1].data[0] == 2)
sprite->invisible = TRUE;
}
else
{
sprite->invisible = FALSE;
}
}
else
{
if (sInfoCard->pos != 1)
{
if (gTasks[taskId1].data[0] == 2)
sprite->invisible = TRUE;
}
else
{
sprite->invisible = FALSE;
}
}
}
// Task states for Task_HandleInfoCardInput
#define STATE_FADE_IN 0
#define STATE_WAIT_FADE 1
#define STATE_GET_INPUT 2
#define STATE_REACT_INPUT 3
#define STATE_MOVE_UP 4
#define STATE_MOVE_DOWN 5
#define STATE_MOVE_LEFT 6
#define STATE_MOVE_RIGHT 7
#define STATE_CLOSE_CARD 8
#define tUsingAlternateSlot data[2] // CARD_ALTERNATE_SLOT
static void Task_HandleInfoCardInput(u8 taskId)
{
int i;
int windowId = 0;
int mode = gTasks[taskId].data[3];
int taskId2 = gTasks[taskId].data[4];
int trainerTourneyId = 0;
int matchNo = 0;
switch (gTasks[taskId].tState)
{
case STATE_FADE_IN:
if (!gPaletteFade.active)
{
BeginNormalPaletteFade(PALETTES_ALL, 0, 0x10, 0, RGB_BLACK);
gTasks[taskId].tState = STATE_WAIT_FADE;
}
break;
case STATE_WAIT_FADE:
if (!gPaletteFade.active)
gTasks[taskId].tState = STATE_GET_INPUT;
break;
case STATE_GET_INPUT:
i = Task_GetInfoCardInput(taskId);
switch (i)
{
case INFOCARD_INPUT_AB:
BeginNormalPaletteFade(PALETTES_ALL, 0, 0, 0x10, RGB_BLACK);
gTasks[taskId].tState = STATE_CLOSE_CARD;
break;
case TRAINERCARD_INPUT_UP ... TRAINERCARD_INPUT_RIGHT:
case MATCHCARD_INPUT_UP ... MATCHCARD_INPUT_RIGHT:
gTasks[taskId].data[5] = i;
if (gTasks[taskId].tUsingAlternateSlot)
windowId = NUM_INFO_CARD_WINDOWS;
else
windowId = 0;
for (i = windowId; i < windowId + NUM_INFO_CARD_WINDOWS; i++)
{
CopyWindowToVram(i, COPYWIN_GFX);
FillWindowPixelBuffer(i, PIXEL_FILL(0));
}
gTasks[taskId].tState = STATE_REACT_INPUT;
break;
case INFOCARD_INPUT_NONE:
break;
}
break;
case STATE_REACT_INPUT:
i = gTasks[taskId].data[5];
switch (i)
{
case TRAINERCARD_INPUT_UP:
case MATCHCARD_INPUT_UP:
if (gTasks[taskId].tUsingAlternateSlot)
{
gBattle_BG0_X = 0;
gBattle_BG0_Y = 0;
gBattle_BG1_X = 0;
gBattle_BG1_Y = DISPLAY_HEIGHT;
}
else
{
gBattle_BG0_X = 0;
gBattle_BG0_Y = DISPLAY_HEIGHT;
gBattle_BG1_X = 0;
gBattle_BG1_Y = 0;
}
if (i == TRAINERCARD_INPUT_UP)
{
if (sInfoCard->pos == 0)
{
gBattle_BG2_X = 0;
gBattle_BG2_Y = DISPLAY_HEIGHT * 2;
trainerTourneyId = sTourneyTreeTrainerIds[gTasks[taskId2].data[1]];
DisplayTrainerInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_UP, trainerTourneyId);
}
else
{
gBattle_BG2_X = DISPLAY_WIDTH + 16;
gBattle_BG2_Y = 0;
trainerTourneyId = sTourneyTreeTrainerIds[gTasks[taskId2].data[1]];
DisplayTrainerInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_UP, trainerTourneyId);
sInfoCard->pos = 0;
}
}
else // i == MATCHCARD_INPUT_UP
{
if (sInfoCard->pos == 0)
{
matchNo = gTasks[taskId2].data[1] - 16;
BufferDomeWinString(matchNo, sInfoCard->tournamentIds);
gBattle_BG2_X = 0;
gBattle_BG2_Y = DISPLAY_HEIGHT * 2;
trainerTourneyId = sInfoCard->tournamentIds[0];
DisplayTrainerInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_UP, trainerTourneyId);
}
else if (sInfoCard->pos == 2)
{
matchNo = gTasks[taskId2].data[1] - 16;
BufferDomeWinString(matchNo, sInfoCard->tournamentIds);
gBattle_BG2_X = 0;
gBattle_BG2_Y = DISPLAY_HEIGHT * 2;
trainerTourneyId = sInfoCard->tournamentIds[1];
DisplayTrainerInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_UP, trainerTourneyId);
}
else
{
gBattle_BG2_X = DISPLAY_WIDTH + 16;
gBattle_BG2_Y = DISPLAY_HEIGHT;
matchNo = gTasks[taskId2].data[1] - 16;
DisplayMatchInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_UP, matchNo);
}
}
for (i = 0; i < NUM_INFOCARD_SPRITES / 2; i++)
{
if (i < 2)
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_TrainerIconCardScrollUp;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot ^ 1;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
gSprites[sInfoCard->spriteIds[i]].data[3] = sInfoCard->spriteIds[i];
}
}
else
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_MonIconCardScrollUp;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot ^ 1;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
}
}
}
for (i = NUM_INFOCARD_SPRITES / 2; i < NUM_INFOCARD_SPRITES; i++)
{
if (i < 10)
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_TrainerIconCardScrollUp;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
gSprites[sInfoCard->spriteIds[i]].data[3] = sInfoCard->spriteIds[i];
}
}
else
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_MonIconCardScrollUp;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
}
}
}
gTasks[taskId].tState = STATE_MOVE_UP;
gTasks[taskId].data[5] = 0;
break;
case TRAINERCARD_INPUT_DOWN:
case MATCHCARD_INPUT_DOWN:
if (gTasks[taskId].tUsingAlternateSlot)
{
gBattle_BG0_X = 0;
gBattle_BG0_Y = 0;
gBattle_BG1_X = 0;
gBattle_BG1_Y = -DISPLAY_HEIGHT;
}
else
{
gBattle_BG0_X = 0;
gBattle_BG0_Y = -DISPLAY_HEIGHT;
gBattle_BG1_X = 0;
gBattle_BG1_Y = 0;
}
if (i == TRAINERCARD_INPUT_DOWN)
{
if (sInfoCard->pos == 0)
{
gBattle_BG2_X = 0;
gBattle_BG2_Y = DISPLAY_HEIGHT;
trainerTourneyId = sTourneyTreeTrainerIds[gTasks[taskId2].data[1]];
DisplayTrainerInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_DOWN, trainerTourneyId);
}
else
{
gBattle_BG2_X = 0;
gBattle_BG2_Y = 0;
trainerTourneyId = sTourneyTreeTrainerIds[gTasks[taskId2].data[1]];
DisplayTrainerInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_DOWN, trainerTourneyId);
sInfoCard->pos = 0;
}
}
else // i == MATCHCARD_INPUT_DOWN
{
if (sInfoCard->pos == 0)
{
matchNo = gTasks[taskId2].data[1] - 16;
BufferDomeWinString(matchNo, sInfoCard->tournamentIds);
gBattle_BG2_X = 0;
gBattle_BG2_Y = DISPLAY_HEIGHT;
trainerTourneyId = sInfoCard->tournamentIds[0];
DisplayTrainerInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_DOWN, trainerTourneyId);
}
else if (sInfoCard->pos == 2)
{
matchNo = gTasks[taskId2].data[1] - 16;
BufferDomeWinString(matchNo, sInfoCard->tournamentIds);
gBattle_BG2_X = 0;
gBattle_BG2_Y = DISPLAY_HEIGHT;
trainerTourneyId = sInfoCard->tournamentIds[1];
DisplayTrainerInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_DOWN, trainerTourneyId);
}
else
{
gBattle_BG2_X = DISPLAY_WIDTH + 16;
gBattle_BG2_Y = 0;
matchNo = gTasks[taskId2].data[1] - 16;
DisplayMatchInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_DOWN, matchNo);
}
}
for (i = 0; i < NUM_INFOCARD_SPRITES / 2; i++)
{
if (i < 2)
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_TrainerIconCardScrollDown;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot ^ 1;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
gSprites[sInfoCard->spriteIds[i]].data[3] = sInfoCard->spriteIds[i];
}
}
else
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_MonIconCardScrollDown;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot ^ 1;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
}
}
}
for (i = NUM_INFOCARD_SPRITES / 2; i < NUM_INFOCARD_SPRITES; i++)
{
if (i < 10)
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_TrainerIconCardScrollDown;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
gSprites[sInfoCard->spriteIds[i]].data[3] = sInfoCard->spriteIds[i];
}
}
else
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_MonIconCardScrollDown;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
}
}
}
gTasks[taskId].tState = STATE_MOVE_DOWN;
gTasks[taskId].data[5] = 0;
break;
case TRAINERCARD_INPUT_LEFT:
if (gTasks[taskId].tUsingAlternateSlot)
{
gBattle_BG0_X = 0;
gBattle_BG0_Y = 0;
gBattle_BG1_X = DISPLAY_WIDTH + 16;
gBattle_BG1_Y = 0;
}
else
{
gBattle_BG0_X = DISPLAY_WIDTH + 16;
gBattle_BG0_Y = 0;
gBattle_BG1_X = 0;
gBattle_BG1_Y = 0;
}
if (sInfoCard->pos == 0)
{
gBattle_BG2_X = DISPLAY_WIDTH + 16;
gBattle_BG2_Y = DISPLAY_HEIGHT;
trainerTourneyId = sTourneyTreeTrainerIds[gTasks[taskId2].data[1]];
DisplayTrainerInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_LEFT, trainerTourneyId);
}
else
{
gBattle_BG2_X = DISPLAY_WIDTH + 16;
gBattle_BG2_Y = 0;
matchNo = sIdToMatchNumber[gTasks[taskId2].data[1]][sInfoCard->pos - 1];
DisplayMatchInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_LEFT, matchNo);
}
for (i = 0; i < NUM_INFOCARD_SPRITES / 2; i++)
{
if (i < 2)
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_TrainerIconCardScrollLeft;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot ^ 1;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
gSprites[sInfoCard->spriteIds[i]].data[3] = sInfoCard->spriteIds[i];
}
}
else
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_MonIconCardScrollLeft;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot ^ 1;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
}
}
}
for (i = NUM_INFOCARD_SPRITES / 2; i < NUM_INFOCARD_SPRITES; i++)
{
if (i < 10)
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_TrainerIconCardScrollLeft;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
gSprites[sInfoCard->spriteIds[i]].data[3] = sInfoCard->spriteIds[i];
}
}
else
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_MonIconCardScrollLeft;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
}
}
}
gTasks[taskId].tState = STATE_MOVE_LEFT;
gTasks[taskId].data[5] = 0;
break;
case MATCHCARD_INPUT_LEFT:
if (gTasks[taskId].tUsingAlternateSlot)
{
gBattle_BG0_X = 0;
gBattle_BG0_Y = 0;
gBattle_BG1_X = DISPLAY_WIDTH + 16;
gBattle_BG1_Y = 0;
}
else
{
gBattle_BG0_X = DISPLAY_WIDTH + 16;
gBattle_BG0_Y = 0;
gBattle_BG1_X = 0;
gBattle_BG1_Y = 0;
}
if (sInfoCard->pos == 0)
{
gBattle_BG2_X = DISPLAY_WIDTH + 16;
gBattle_BG2_Y = DISPLAY_HEIGHT;
trainerTourneyId = sInfoCard->tournamentIds[0];
DisplayTrainerInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_LEFT, trainerTourneyId);
}
else
{
gBattle_BG2_X = 0;
gBattle_BG2_Y = DISPLAY_HEIGHT;
matchNo = gTasks[taskId2].data[1] - 16;
DisplayMatchInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_LEFT, matchNo);
}
for (i = 0; i < NUM_INFOCARD_SPRITES / 2; i++)
{
if (i < 2)
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_TrainerIconCardScrollLeft;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot ^ 1;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
gSprites[sInfoCard->spriteIds[i]].data[3] = sInfoCard->spriteIds[i];
}
}
else
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_MonIconCardScrollLeft;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot ^ 1;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
}
}
}
for (i = NUM_INFOCARD_SPRITES / 2; i < NUM_INFOCARD_SPRITES; i++)
{
if (i < 10)
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_TrainerIconCardScrollLeft;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
gSprites[sInfoCard->spriteIds[i]].data[3] = sInfoCard->spriteIds[i];
}
}
else
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_MonIconCardScrollLeft;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
}
}
}
gTasks[taskId].tState = STATE_MOVE_LEFT;
gTasks[taskId].data[5] = 0;
break;
case TRAINERCARD_INPUT_RIGHT:
if (gTasks[taskId].tUsingAlternateSlot)
{
gBattle_BG0_X = 0;
gBattle_BG0_Y = 0;
gBattle_BG1_X = -(DISPLAY_WIDTH + 16);
gBattle_BG1_Y = 0;
}
else
{
gBattle_BG0_X = -(DISPLAY_WIDTH + 16);
gBattle_BG0_Y = 0;
gBattle_BG1_X = 0;
gBattle_BG1_Y = 0;
}
if (sInfoCard->pos == 1)
{
gBattle_BG2_X = 0;
gBattle_BG2_Y = DISPLAY_HEIGHT;
}
else
{
gBattle_BG2_X = 0;
gBattle_BG2_Y = 0;
}
matchNo = sIdToMatchNumber[gTasks[taskId2].data[1]][sInfoCard->pos - 1];
DisplayMatchInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_RIGHT, matchNo);
for (i = 0; i < NUM_INFOCARD_SPRITES / 2; i++)
{
if (i < 2)
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_TrainerIconCardScrollRight;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot ^ 1;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
gSprites[sInfoCard->spriteIds[i]].data[3] = sInfoCard->spriteIds[i];
}
}
else
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_MonIconCardScrollRight;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot ^ 1;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
}
}
}
for (i = NUM_INFOCARD_SPRITES / 2; i < NUM_INFOCARD_SPRITES; i++)
{
if (i < 10)
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_TrainerIconCardScrollRight;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
gSprites[sInfoCard->spriteIds[i]].data[3] = sInfoCard->spriteIds[i];
}
}
else
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_MonIconCardScrollRight;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
}
}
}
gTasks[taskId].tState = STATE_MOVE_RIGHT;
gTasks[taskId].data[5] = 0;
break;
case MATCHCARD_INPUT_RIGHT:
if (gTasks[taskId].tUsingAlternateSlot)
{
gBattle_BG0_X = 0;
gBattle_BG0_Y = 0;
gBattle_BG1_X = -(DISPLAY_WIDTH + 16);
gBattle_BG1_Y = 0;
}
else
{
gBattle_BG0_X = -(DISPLAY_WIDTH + 16);
gBattle_BG0_Y = 0;
gBattle_BG1_X = 0;
gBattle_BG1_Y = 0;
}
if (sInfoCard->pos == 2)
{
gBattle_BG2_X = DISPLAY_WIDTH + 16;
gBattle_BG2_Y = DISPLAY_HEIGHT;
trainerTourneyId = sInfoCard->tournamentIds[1];
DisplayTrainerInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_RIGHT, trainerTourneyId);
}
else
{
gBattle_BG2_X = 0;
gBattle_BG2_Y = DISPLAY_HEIGHT;
matchNo = gTasks[taskId2].data[1] - 16;
DisplayMatchInfoOnCard(gTasks[taskId].tUsingAlternateSlot | MOVE_CARD_RIGHT, matchNo);
}
for (i = 0; i < NUM_INFOCARD_SPRITES / 2; i++)
{
if (i < 2)
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_TrainerIconCardScrollRight;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot ^ 1;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
gSprites[sInfoCard->spriteIds[i]].data[3] = sInfoCard->spriteIds[i];
}
}
else
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_MonIconCardScrollRight;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot ^ 1;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
}
}
}
for (i = NUM_INFOCARD_SPRITES / 2; i < NUM_INFOCARD_SPRITES; i++)
{
if (i < 10)
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_TrainerIconCardScrollRight;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
gSprites[sInfoCard->spriteIds[i]].data[3] = sInfoCard->spriteIds[i];
}
}
else
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
{
gSprites[sInfoCard->spriteIds[i]].callback = SpriteCB_MonIconCardScrollRight;
gSprites[sInfoCard->spriteIds[i]].data[0] = gTasks[taskId].tUsingAlternateSlot;
gSprites[sInfoCard->spriteIds[i]].data[1] = 0;
gSprites[sInfoCard->spriteIds[i]].data[2] = i;
}
}
}
gTasks[taskId].tState = STATE_MOVE_RIGHT;
gTasks[taskId].data[5] = 0;
break;
}
break;
case STATE_MOVE_UP:
if (++gTasks[taskId].data[5] != 41)
{
gBattle_BG0_Y -= 4;
gBattle_BG1_Y -= 4;
gBattle_BG2_Y -= 4;
}
else
{
gTasks[taskId].tState = STATE_GET_INPUT;
}
break;
case STATE_MOVE_DOWN:
if (++gTasks[taskId].data[5] != 41)
{
gBattle_BG0_Y += 4;
gBattle_BG1_Y += 4;
gBattle_BG2_Y += 4;
}
else
{
gTasks[taskId].tState = STATE_GET_INPUT;
}
break;
case STATE_MOVE_LEFT:
if (++gTasks[taskId].data[5] != 65)
{
gBattle_BG0_X -= 4;
gBattle_BG1_X -= 4;
gBattle_BG2_X -= 4;
}
else
{
gTasks[taskId].tState = STATE_GET_INPUT;
}
break;
case STATE_MOVE_RIGHT:
if (++gTasks[taskId].data[5] != 65)
{
gBattle_BG0_X += 4;
gBattle_BG1_X += 4;
gBattle_BG2_X += 4;
}
else
{
gTasks[taskId].tState = STATE_GET_INPUT;
}
break;
case STATE_CLOSE_CARD:
if (!gPaletteFade.active)
{
for (i = 0; i < NUM_INFOCARD_SPRITES / 2; i++)
{
if (i < 2)
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
FreeAndDestroyTrainerPicSprite(sInfoCard->spriteIds[i]);
}
else
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
FreeAndDestroyMonIconSprite(&gSprites[sInfoCard->spriteIds[i]]);
}
}
for (i = NUM_INFOCARD_SPRITES / 2; i < NUM_INFOCARD_SPRITES; i++)
{
if (i < 10)
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
FreeAndDestroyTrainerPicSprite(sInfoCard->spriteIds[i]);
}
else
{
if (sInfoCard->spriteIds[i] != SPRITE_NONE)
FreeAndDestroyMonIconSprite(&gSprites[sInfoCard->spriteIds[i]]);
}
}
FreeMonIconPalettes();
FREE_AND_SET_NULL(sInfoCard);
FreeAllWindowBuffers();
if (mode == INFOCARD_NEXT_OPPONENT)
{
SetMainCallback2(CB2_ReturnToFieldContinueScriptPlayMapMusic);
}
else
{
i = CreateTask(Task_ShowTourneyTree, 0);
gTasks[i].data[0] = 0;
gTasks[i].tNotInteractive = FALSE;
gTasks[i].data[2] = 3;
gTasks[i].data[3] = gTasks[taskId].data[4];
gTasks[i].tIsPrevTourneyTree = gTasks[taskId2].data[6];
}
DestroyTask(taskId);
}
break;
}
}
// undefine task states for Task_HandleInfoCardInput
#undef STATE_FADE_IN
#undef STATE_WAIT_FADE
#undef STATE_GET_INPUT
#undef STATE_REACT_INPUT
#undef STATE_MOVE_UP
#undef STATE_MOVE_DOWN
#undef STATE_MOVE_LEFT
#undef STATE_MOVE_RIGHT
#undef STATE_CLOSE_CARD
static u8 Task_GetInfoCardInput(u8 taskId)
{
u8 input = INFOCARD_INPUT_NONE;
int taskId2 = gTasks[taskId].data[4];
int position = gTasks[taskId2].data[1];
u8 tourneyId = sTourneyTreeTrainerIds[position];
u16 roundId = gSaveBlock2Ptr->frontier.curChallengeBattleNum;
if (JOY_NEW(A_BUTTON | B_BUTTON))
input = INFOCARD_INPUT_AB;
// Next opponent card cant scroll
if (gTasks[taskId].data[3] == INFOCARD_NEXT_OPPONENT)
return input;
if (gTasks[taskId].data[3] == INFOCARD_TRAINER)
{
// For trainer info cards, pos is 0 when on a trainer info card (not viewing that trainer's match progression)
// Scrolling up/down from a trainer info card goes to other trainer info cards
if (JOY_NEW(DPAD_UP) && sInfoCard->pos == 0)
{
if (position == 0)
position = DOME_TOURNAMENT_TRAINERS_COUNT - 1;
else
position--;
input = TRAINERCARD_INPUT_UP;
}
else if (JOY_NEW(DPAD_DOWN) && sInfoCard->pos == 0)
{
if (position == DOME_TOURNAMENT_TRAINERS_COUNT - 1)
position = 0;
else
position++;
input = TRAINERCARD_INPUT_DOWN;
}
// Scrolling left can only be done after scrolling right
else if (JOY_NEW(DPAD_LEFT) && sInfoCard->pos != 0)
{
sInfoCard->pos--;
input = TRAINERCARD_INPUT_LEFT;
}
// Scrolling right from a trainer info card shows their match progression
else if (JOY_NEW(DPAD_RIGHT))
{
// Can only scroll right from a trainer card until the round they were eliminated
if (DOME_TRAINERS[tourneyId].isEliminated && sInfoCard->pos - 1 < DOME_TRAINERS[tourneyId].eliminatedAt)
{
sInfoCard->pos++;
input = TRAINERCARD_INPUT_RIGHT;
}
// otherwise can scroll as far right as the current round allows
if (!DOME_TRAINERS[tourneyId].isEliminated && sInfoCard->pos - 1 < roundId)
{
sInfoCard->pos++;
input = TRAINERCARD_INPUT_RIGHT;
}
}
if (input == INFOCARD_INPUT_AB)
{
if (sInfoCard->pos != 0)
gTasks[taskId2].data[1] = sTrainerAndRoundToLastMatchCardNum[position / 2][sInfoCard->pos - 1];
else
gTasks[taskId2].data[1] = position;
}
}
else // gTasks[taskId].data[3] == INFOCARD_MATCH
{
// For match info cards, pos is 1 when on the match card, 0 when on the left trainer, and 1 when on the right trainer
// Scrolling up/down from a match info card goes to the next/previous match
if (JOY_NEW(DPAD_UP) && sInfoCard->pos == 1)
{
if (position == DOME_TOURNAMENT_TRAINERS_COUNT)
position = sLastMatchCardNum[roundId];
else
position--;
input = MATCHCARD_INPUT_UP;
}
else if (JOY_NEW(DPAD_DOWN) && sInfoCard->pos == 1)
{
if (position == sLastMatchCardNum[roundId])
position = DOME_TOURNAMENT_TRAINERS_COUNT;
else
position++;
input = MATCHCARD_INPUT_DOWN;
}
// Scrolling left/right from a match info card shows the trainer info card of the competitors for that match
else if (JOY_NEW(DPAD_LEFT) && sInfoCard->pos != 0)
{
input = MATCHCARD_INPUT_LEFT;
sInfoCard->pos--;
}
else if (JOY_NEW(DPAD_RIGHT) && (sInfoCard->pos == 0 || sInfoCard->pos == 1))
{
input = MATCHCARD_INPUT_RIGHT;
sInfoCard->pos++;
}
if (input == INFOCARD_INPUT_AB)
{
if (sInfoCard->pos == 0) // On left trainer info card
gTasks[taskId2].data[1] = sTournamentIdToPairedTrainerIds[sInfoCard->tournamentIds[0]];
else if (sInfoCard->pos == 2) // On right trainer info card
gTasks[taskId2].data[1] = sTournamentIdToPairedTrainerIds[sInfoCard->tournamentIds[1]];
else // On match info card
gTasks[taskId2].data[1] = position;
}
}
if (input != INFOCARD_INPUT_NONE && input != INFOCARD_INPUT_AB)
{
PlaySE(SE_SELECT);
gTasks[taskId2].data[1] = position;
gTasks[taskId].tUsingAlternateSlot ^= 1;
}
return input;
}
#undef tUsingAlternateSlot
// allocatedArray below needs to be large enough to hold stat totals for each mon, or totals of each type of move points
#define ALLOC_ARRAY_SIZE max(NUM_STATS * FRONTIER_PARTY_SIZE, NUM_MOVE_POINT_TYPES)
static void DisplayTrainerInfoOnCard(u8 flags, u8 trainerTourneyId)
{
struct TextPrinterTemplate textPrinter;
int i, j, k;
int trainerId = 0;
u8 nature = 0;
int arrId = 0;
int windowId = WIN_TRAINER_NAME;
int x = 0, y = 0;
u8 palSlot = 0;
s16 *allocatedArray = AllocZeroed(sizeof(s16) * ALLOC_ARRAY_SIZE);
trainerId = DOME_TRAINERS[trainerTourneyId].trainerId;
if (flags & CARD_ALTERNATE_SLOT)
arrId = 2 * (FRONTIER_PARTY_SIZE + 1), windowId = WIN_TRAINER_NAME + NUM_INFO_CARD_WINDOWS, palSlot = 2;
if (flags & MOVE_CARD_RIGHT)
x = DISPLAY_WIDTH + 16;
if (flags & MOVE_CARD_DOWN)
y = DISPLAY_HEIGHT;
if (flags & MOVE_CARD_LEFT)
x = -(DISPLAY_WIDTH + 16);
if (flags & MOVE_CARD_UP)
y = -DISPLAY_HEIGHT;
// Create trainer pic sprite
if (trainerId == TRAINER_PLAYER)
sInfoCard->spriteIds[arrId] = CreateTrainerPicSprite(PlayerGenderToFrontTrainerPicId(gSaveBlock2Ptr->playerGender), TRUE, x + 48, y + 64, palSlot + 12, TAG_NONE);
else if (trainerId == TRAINER_FRONTIER_BRAIN)
sInfoCard->spriteIds[arrId] = CreateTrainerPicSprite(GetDomeBrainTrainerPicId(), TRUE, x + 48, y + 64, palSlot + 12, TAG_NONE);
else
sInfoCard->spriteIds[arrId] = CreateTrainerPicSprite(GetFrontierTrainerFrontSpriteId(trainerId), TRUE, x + 48, y + 64, palSlot + 12, TAG_NONE);
if (flags & MOVE_CARD)
gSprites[sInfoCard->spriteIds[arrId]].invisible = TRUE;
// Create party mon icons
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
{
if (trainerId == TRAINER_PLAYER)
{
sInfoCard->spriteIds[2 + i + arrId] = CreateMonIcon(DOME_MONS[trainerTourneyId][i],
SpriteCB_MonIconDomeInfo,
x | sInfoTrainerMonX[i],
y + sInfoTrainerMonY[i],
0, 0, TRUE);
gSprites[sInfoCard->spriteIds[2 + i + arrId]].oam.priority = 0;
}
else if (trainerId == TRAINER_FRONTIER_BRAIN)
{
sInfoCard->spriteIds[2 + i + arrId] = CreateMonIcon(DOME_MONS[trainerTourneyId][i],
SpriteCB_MonIconDomeInfo,
x | sInfoTrainerMonX[i],
y + sInfoTrainerMonY[i],
0, 0, TRUE);
gSprites[sInfoCard->spriteIds[2 + i + arrId]].oam.priority = 0;
}
else
{
sInfoCard->spriteIds[2 + i + arrId] = CreateMonIcon(gFacilityTrainerMons[DOME_MONS[trainerTourneyId][i]].species,
SpriteCB_MonIconDomeInfo,
x | sInfoTrainerMonX[i],
y + sInfoTrainerMonY[i],
0, 0, TRUE);
gSprites[sInfoCard->spriteIds[2 + i + arrId]].oam.priority = 0;
}
if (flags & MOVE_CARD)
gSprites[sInfoCard->spriteIds[2 + i + arrId]].invisible = TRUE;
}
// Initialize the text printer
textPrinter.fontId = FONT_SHORT;
textPrinter.x = 0;
textPrinter.y = 0;
textPrinter.currentX = textPrinter.x;
textPrinter.currentY = textPrinter.y;
textPrinter.letterSpacing = 2;
textPrinter.lineSpacing = 0;
textPrinter.unk = 0;
textPrinter.fgColor = TEXT_DYNAMIC_COLOR_5;
textPrinter.bgColor = TEXT_COLOR_TRANSPARENT;
textPrinter.shadowColor = TEXT_DYNAMIC_COLOR_4;
// Get class and trainer name
i = 0;
if (trainerId == TRAINER_PLAYER)
j = gFacilityClassToTrainerClass[FACILITY_CLASS_BRENDAN];
else if (trainerId == TRAINER_FRONTIER_BRAIN)
j = GetDomeBrainTrainerClass();
else
j = GetFrontierOpponentClass(trainerId);
for (;gTrainerClassNames[j][i] != EOS; i++)
gStringVar1[i] = gTrainerClassNames[j][i];
gStringVar1[i] = CHAR_SPACE;
gStringVar1[i + 1] = EOS;
if (trainerId == TRAINER_PLAYER)
{
StringAppend(gStringVar1, gSaveBlock2Ptr->playerName);
}
else if (trainerId == TRAINER_FRONTIER_BRAIN)
{
CopyDomeBrainTrainerName(gStringVar2);
StringAppend(gStringVar1, gStringVar2);
}
else
{
CopyDomeTrainerName(gStringVar2, trainerId);
StringAppend(gStringVar1, gStringVar2);
}
// Print class and trainer name
textPrinter.currentX = GetStringCenterAlignXOffsetWithLetterSpacing(textPrinter.fontId, gStringVar1, 0xD0, textPrinter.letterSpacing);
textPrinter.currentChar = gStringVar1;
textPrinter.windowId = windowId;
PutWindowTilemap(windowId);
CopyWindowToVram(windowId, COPYWIN_FULL);
AddTextPrinter(&textPrinter, 0, NULL);
textPrinter.letterSpacing = 0;
// Print names of the party mons
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
{
textPrinter.currentY = sSpeciesNameTextYCoords[i];
if (trainerId == TRAINER_PLAYER)
textPrinter.currentChar = gSpeciesNames[DOME_MONS[trainerTourneyId][i]];
else if (trainerId == TRAINER_FRONTIER_BRAIN)
textPrinter.currentChar = gSpeciesNames[DOME_MONS[trainerTourneyId][i]];
else
textPrinter.currentChar = gSpeciesNames[gFacilityTrainerMons[DOME_MONS[trainerTourneyId][i]].species];
textPrinter.windowId = WIN_TRAINER_MON1_NAME + i + windowId;
if (i == 1)
textPrinter.currentX = 7;
else
textPrinter.currentX = 0;
PutWindowTilemap(WIN_TRAINER_MON1_NAME + i + windowId);
CopyWindowToVram(WIN_TRAINER_MON1_NAME + i + windowId, COPYWIN_FULL);
AddTextPrinter(&textPrinter, 0, NULL);
}
PutWindowTilemap(windowId + WIN_TRAINER_FLAVOR_TEXT);
CopyWindowToVram(windowId + WIN_TRAINER_FLAVOR_TEXT, COPYWIN_FULL);
// Print text about trainers potential in the tourney
if (trainerId == TRAINER_FRONTIER_BRAIN)
textPrinter.currentChar = sBattleDomePotentialTexts[DOME_TOURNAMENT_TRAINERS_COUNT];
else
textPrinter.currentChar = sBattleDomePotentialTexts[trainerTourneyId];
textPrinter.fontId = FONT_NORMAL;
textPrinter.windowId = windowId + WIN_TRAINER_FLAVOR_TEXT;
textPrinter.currentX = 0;
textPrinter.y = 4;
textPrinter.currentY = 4;
AddTextPrinter(&textPrinter, 0, NULL);
// Calculate move scores to determine the trainers battle style
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
{
for (j = 0; j < MAX_MON_MOVES; j++)
{
for (k = 0; k < NUM_MOVE_POINT_TYPES; k++)
{
if (trainerId == TRAINER_FRONTIER_BRAIN)
allocatedArray[k] += sBattleStyleMovePoints[GetFrontierBrainMonMove(i, j)][k];
else if (trainerId == TRAINER_PLAYER)
allocatedArray[k] += sBattleStyleMovePoints[gSaveBlock2Ptr->frontier.domePlayerPartyData[i].moves[j]][k];
else
allocatedArray[k] += sBattleStyleMovePoints[gFacilityTrainerMons[DOME_MONS[trainerTourneyId][i]].moves[j]][k];
}
}
}
// Get the battle style the trainer uses
// Each element of sBattleStyleThresholds is an array of point thresholds for particular move qualities
// If all the point thresholds in the array are satisfied, the player is considered to be using that battle style
for (i = 0; i < ARRAY_COUNT(sBattleStyleThresholds); i++)
{
int thresholdStatCount = 0;
for (k = 0, j = 0; j < NUM_MOVE_POINT_TYPES; j++)
{
if (sBattleStyleThresholds[i][j] != 0)
{
thresholdStatCount++;
if (allocatedArray[j] != 0 && allocatedArray[j] >= sBattleStyleThresholds[i][j])
k++; // number of point thresholds met/exceeded
}
}
if (thresholdStatCount == k)
break; // All thresholds for battle style met/exceeded, player uses this battle style
}
// Print the trainers battle style
textPrinter.currentChar = sBattleDomeOpponentStyleTexts[i];
textPrinter.y = 20;
textPrinter.currentY = 20;
AddTextPrinter(&textPrinter, 0, NULL);
for (i = 0; i < ALLOC_ARRAY_SIZE; i++)
allocatedArray[i] = 0;
// Calculate EV/nature points for the stat portion of battle style
if (trainerId == TRAINER_FRONTIER_BRAIN || trainerId == TRAINER_PLAYER)
{
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
{
// Add the EVs for this mon
for (j = 0; j < NUM_STATS; j++)
{
if (trainerId == TRAINER_FRONTIER_BRAIN)
allocatedArray[j] = GetFrontierBrainMonEvs(i, j);
else
allocatedArray[j] = gSaveBlock2Ptr->frontier.domePlayerPartyData[i].evs[j];
}
// HP doesnt have a nature modifier, so just add it here
allocatedArray[NUM_STATS] += allocatedArray[STAT_HP];
// Add the EVs with the nature modifier for this mon and and track number of negative natures
for (j = 0; j < NUM_NATURE_STATS; j++)
{
if (trainerId == TRAINER_FRONTIER_BRAIN)
nature = GetFrontierBrainMonNature(i);
else
nature = gSaveBlock2Ptr->frontier.domePlayerPartyData[i].nature;
if (gNatureStatTable[nature][j] > 0)
{
allocatedArray[j + NUM_STATS + 1] += (allocatedArray[j + 1] * 110) / 100;
}
else if (gNatureStatTable[nature][j] < 0)
{
allocatedArray[j + NUM_STATS + 1] += (allocatedArray[j + 1] * 90) / 100;
allocatedArray[j + NUM_STATS + NUM_NATURE_STATS + 2]++;
}
else
{
allocatedArray[j + NUM_STATS + 1] += allocatedArray[j + 1];
}
}
}
for (j = 0, i = 0; i < NUM_STATS; i++)
j += allocatedArray[NUM_STATS + i];
for (i = 0; i < NUM_STATS; i++)
allocatedArray[i] = (allocatedArray[NUM_STATS + i] * 100) / j;
}
// Same as above but for regular trainers instead of the frontier brain or player
else
{
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
{
int evBits = gFacilityTrainerMons[DOME_MONS[trainerTourneyId][i]].evSpread;
for (k = 0, j = 0; j < NUM_STATS; j++)
{
allocatedArray[j] = 0;
if (evBits & 1)
k++;
evBits >>= 1;
}
k = MAX_TOTAL_EVS / k;
evBits = gFacilityTrainerMons[DOME_MONS[trainerTourneyId][i]].evSpread;
for (j = 0; j < NUM_STATS; j++)
{
if (evBits & 1)
allocatedArray[j] = k;
evBits >>= 1;
}
allocatedArray[NUM_STATS] += allocatedArray[STAT_HP];
for (j = 0; j < NUM_NATURE_STATS; j++)
{
nature = gFacilityTrainerMons[DOME_MONS[trainerTourneyId][i]].nature;
if (gNatureStatTable[nature][j] > 0)
{
allocatedArray[j + NUM_STATS + 1] += (allocatedArray[j + 1] * 110) / 100;
}
else if (gNatureStatTable[nature][j] < 0)
{
allocatedArray[j + NUM_STATS + 1] += (allocatedArray[j + 1] * 90) / 100;
allocatedArray[j + NUM_STATS + NUM_NATURE_STATS + 2]++;
}
else
{
allocatedArray[j + NUM_STATS + 1] += allocatedArray[j + 1];
}
}
}
for (j = 0, i = 0; i < NUM_STATS; i++)
j += allocatedArray[i + NUM_STATS];
for (i = 0; i < NUM_STATS; i++)
allocatedArray[i] = (allocatedArray[NUM_STATS + i] * 100) / j;
}
// Count the number of good/bad stats for the party
// i is the number of good stats, j is the number of bad stats
for (i = 0, j = 0, k = 0; k < NUM_STATS; k++)
{
// Any stat above 29 EVs is considered good
if (allocatedArray[k] > 29)
{
// If 2 good stats have been found already, choose which to use
if (i == 2)
{
if (allocatedArray[6] < allocatedArray[k])
{
if (allocatedArray[7] < allocatedArray[k])
{
if (allocatedArray[6] < allocatedArray[7])
{
allocatedArray[6] = allocatedArray[7];
allocatedArray[7] = k;
}
else
{
allocatedArray[7] = k;
}
}
else
{
allocatedArray[6] = allocatedArray[7];
allocatedArray[7] = k;
}
}
else
{
if (allocatedArray[7] < allocatedArray[k])
allocatedArray[7] = k;
}
}
else
{
allocatedArray[i + 6] = k;
i++;
}
}
// Any stat with 0 EVs is considered bad
if (allocatedArray[k] == 0)
{
// If 2 bad stats have been found already, choose which to use
if (j == 2)
{
if (allocatedArray[k + 12] >= 2
|| ((allocatedArray[k + 12] == 1 && allocatedArray[12 + allocatedArray[8]] == 0 && allocatedArray[12 + allocatedArray[9]] == 0)
)
)
{
allocatedArray[8] = allocatedArray[9];
allocatedArray[9] = k;
}
else if (allocatedArray[k + 12] == 1 && allocatedArray[12 + allocatedArray[8]] == 0)
{
allocatedArray[8] = allocatedArray[9];
allocatedArray[9] = k;
}
else if (allocatedArray[k + 12] == 1 && allocatedArray[12 + allocatedArray[9]] == 0)
{
allocatedArray[9] = k;
}
}
else
{
allocatedArray[j + 8] = k;
j++;
}
}
}
// Get the string ID to display which stats are good/bad
if (i == 2)
i = sStatTextOffsets[allocatedArray[6]] + (allocatedArray[7] - (allocatedArray[6] + 1)) + DOME_TEXT_TWO_GOOD_STATS;
else if (i == 1)
i = allocatedArray[6] + DOME_TEXT_ONE_GOOD_STAT;
else if (j == 2)
i = sStatTextOffsets[allocatedArray[8]] + (allocatedArray[9] - (allocatedArray[8] + 1)) + DOME_TEXT_TWO_BAD_STATS;
else if (j == 1)
i = allocatedArray[8] + DOME_TEXT_ONE_BAD_STAT;
else
i = DOME_TEXT_WELL_BALANCED;
// Print the stat text
textPrinter.currentChar = sBattleDomeOpponentStatsTexts[i];
textPrinter.y = 36;
textPrinter.currentY = 36;
AddTextPrinter(&textPrinter, 0, NULL);
Free(allocatedArray);
}
static int BufferDomeWinString(u8 matchNum, u8 *tournamentIds)
{
int i;
u8 tournamentId;
int winStringId = 0;
int count = 0;
// Get winners name
for (i = sCompetitorRangeByMatch[matchNum][0]; i < sCompetitorRangeByMatch[matchNum][0] + sCompetitorRangeByMatch[matchNum][1]; i++)
{
tournamentId = sTourneyTreeTrainerIds2[i];
if (!DOME_TRAINERS[tournamentId].isEliminated)
{
tournamentIds[count] = tournamentId;
if (DOME_TRAINERS[tournamentId].trainerId == TRAINER_PLAYER)
StringCopy(gStringVar1, gSaveBlock2Ptr->playerName);
else if (DOME_TRAINERS[tournamentId].trainerId == TRAINER_FRONTIER_BRAIN)
CopyDomeBrainTrainerName(gStringVar1);
else
CopyDomeTrainerName(gStringVar1, DOME_TRAINERS[tournamentId].trainerId);
count++;
}
}
// Neither trainer has been eliminated, battle hasn't occurred yet
if (count == 2)
return DOME_TEXT_NO_WINNER_YET;
for (i = sCompetitorRangeByMatch[matchNum][0]; i < sCompetitorRangeByMatch[matchNum][0] + sCompetitorRangeByMatch[matchNum][1]; i++)
{
tournamentId = sTourneyTreeTrainerIds2[i];
if (DOME_TRAINERS[tournamentId].isEliminated
&& DOME_TRAINERS[tournamentId].eliminatedAt >= sCompetitorRangeByMatch[matchNum][2])
{
tournamentIds[count] = tournamentId;
count++;
if (DOME_TRAINERS[tournamentId].eliminatedAt == sCompetitorRangeByMatch[matchNum][2])
{
// Set initial winStringId offset
StringCopy(gStringVar2, gMoveNames[gSaveBlock2Ptr->frontier.domeWinningMoves[tournamentId]]);
winStringId = DOME_TRAINERS[tournamentId].forfeited * 2; // (DOME_TEXT_WON_USING_MOVE - 1) or (DOME_TEXT_WON_ON_FORFEIT - 1)
if (gSaveBlock2Ptr->frontier.domeWinningMoves[tournamentId] == MOVE_NONE && DOME_TRAINERS[tournamentId].forfeited == FALSE)
winStringId = DOME_TEXT_WON_NO_MOVES - 1;
}
else
{
if (DOME_TRAINERS[tournamentId].trainerId == TRAINER_PLAYER)
StringCopy(gStringVar1, gSaveBlock2Ptr->playerName);
else if (DOME_TRAINERS[tournamentId].trainerId == TRAINER_FRONTIER_BRAIN)
CopyDomeBrainTrainerName(gStringVar1);
else
CopyDomeTrainerName(gStringVar1, DOME_TRAINERS[tournamentId].trainerId);
}
}
if (count == 2)
break;
}
if (matchNum == DOME_TOURNAMENT_MATCHES_COUNT - 1)
return winStringId + 2; // use DOME_TEXT_CHAMP_*
else
return winStringId + 1; // use DOME_TEXT_WON_*
}
static void DisplayMatchInfoOnCard(u8 flags, u8 matchNo)
{
struct TextPrinterTemplate textPrinter;
int tournamentIds[2];
int trainerIds[2];
bool32 lost[2];
int i;
int winStringId = 0;
int arrId = 0;
int windowId = 0;
int x = 0, y = 0;
u8 palSlot = 0;
if (flags & CARD_ALTERNATE_SLOT)
arrId = 2 * (FRONTIER_PARTY_SIZE + 1), windowId = NUM_INFO_CARD_WINDOWS, palSlot = 2;
if (flags & MOVE_CARD_RIGHT)
x = DISPLAY_WIDTH + 16;
if (flags & MOVE_CARD_DOWN)
y = DISPLAY_HEIGHT;
if (flags & MOVE_CARD_LEFT)
x = -(DISPLAY_WIDTH + 16);
if (flags & MOVE_CARD_UP)
y = -DISPLAY_HEIGHT;
// Copy trainers information to handy arrays.
winStringId = BufferDomeWinString(matchNo, sInfoCard->tournamentIds);
for (i = 0; i < NUM_INFOCARD_TRAINERS; i++)
{
tournamentIds[i] = sInfoCard->tournamentIds[i];
trainerIds[i] = DOME_TRAINERS[tournamentIds[i]].trainerId;
if (DOME_TRAINERS[tournamentIds[i]].eliminatedAt <= sCompetitorRangeByMatch[matchNo][2]
&& DOME_TRAINERS[tournamentIds[i]].isEliminated)
lost[i] = TRUE;
else
lost[i] = FALSE;
}
// Draw left trainer sprite.
if (trainerIds[0] == TRAINER_PLAYER)
sInfoCard->spriteIds[arrId] = CreateTrainerPicSprite(PlayerGenderToFrontTrainerPicId(gSaveBlock2Ptr->playerGender), TRUE, x + 48, y + 88, palSlot + 12, TAG_NONE);
else if (trainerIds[0] == TRAINER_FRONTIER_BRAIN)
sInfoCard->spriteIds[arrId] = CreateTrainerPicSprite(GetDomeBrainTrainerPicId(), TRUE, x + 48, y + 88, palSlot + 12, TAG_NONE);
else
sInfoCard->spriteIds[arrId] = CreateTrainerPicSprite(GetFrontierTrainerFrontSpriteId(trainerIds[0]), TRUE, x + 48, y + 88, palSlot + 12, TAG_NONE);
if (flags & MOVE_CARD)
gSprites[sInfoCard->spriteIds[arrId]].invisible = TRUE;
if (lost[0])
gSprites[sInfoCard->spriteIds[arrId]].oam.paletteNum = 3;
// Draw right trainer sprite.
if (trainerIds[1] == TRAINER_PLAYER)
sInfoCard->spriteIds[1 + arrId] = CreateTrainerPicSprite(PlayerGenderToFrontTrainerPicId(gSaveBlock2Ptr->playerGender), TRUE, x + 192, y + 88, palSlot + 13, TAG_NONE);
else if (trainerIds[1] == TRAINER_FRONTIER_BRAIN)
sInfoCard->spriteIds[1 + arrId] = CreateTrainerPicSprite(GetDomeBrainTrainerPicId(), TRUE, x + 192, y + 88, palSlot + 13, TAG_NONE);
else
sInfoCard->spriteIds[1 + arrId] = CreateTrainerPicSprite(GetFrontierTrainerFrontSpriteId(trainerIds[1]), TRUE, x + 192, y + 88, palSlot + 13, TAG_NONE);
if (flags & MOVE_CARD)
gSprites[sInfoCard->spriteIds[1 + arrId]].invisible = TRUE;
if (lost[1])
gSprites[sInfoCard->spriteIds[1 + arrId]].oam.paletteNum = 3;
// Draw left trainer's pokemon icons.
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
{
if (trainerIds[0] == TRAINER_PLAYER)
{
sInfoCard->spriteIds[2 + i + arrId] = CreateMonIcon(DOME_MONS[tournamentIds[0]][i],
SpriteCB_MonIconDomeInfo,
x | sLeftTrainerMonX[i],
y + sLeftTrainerMonY[i],
0, 0, TRUE);
gSprites[sInfoCard->spriteIds[2 + i + arrId]].oam.priority = 0;
}
else if (trainerIds[0] == TRAINER_FRONTIER_BRAIN)
{
sInfoCard->spriteIds[2 + i + arrId] = CreateMonIcon(DOME_MONS[tournamentIds[0]][i],
SpriteCB_MonIconDomeInfo,
x | sLeftTrainerMonX[i],
y + sLeftTrainerMonY[i],
0, 0, TRUE);
gSprites[sInfoCard->spriteIds[2 + i + arrId]].oam.priority = 0;
}
else
{
sInfoCard->spriteIds[2 + i + arrId] = CreateMonIcon(gFacilityTrainerMons[DOME_MONS[tournamentIds[0]][i]].species,
SpriteCB_MonIconDomeInfo,
x | sLeftTrainerMonX[i],
y + sLeftTrainerMonY[i],
0, 0, TRUE);
gSprites[sInfoCard->spriteIds[2 + i + arrId]].oam.priority = 0;
}
if (flags & MOVE_CARD)
gSprites[sInfoCard->spriteIds[2 + i + arrId]].invisible = TRUE;
if (lost[0])
{
gSprites[sInfoCard->spriteIds[2 + i + arrId]].oam.paletteNum = 3;
gSprites[sInfoCard->spriteIds[2 + i + arrId]].sMonIconStill = TRUE;
}
}
// Draw right trainer's pokemon icons.
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
{
if (trainerIds[1] == TRAINER_PLAYER)
{
sInfoCard->spriteIds[5 + i + arrId] = CreateMonIcon(DOME_MONS[tournamentIds[1]][i],
SpriteCB_MonIconDomeInfo,
x | sRightTrainerMonX[i],
y + sRightTrainerMonY[i],
0, 0, TRUE);
gSprites[sInfoCard->spriteIds[5 + i + arrId]].oam.priority = 0;
}
else if (trainerIds[1] == TRAINER_FRONTIER_BRAIN)
{
sInfoCard->spriteIds[5 + i + arrId] = CreateMonIcon(DOME_MONS[tournamentIds[1]][i],
SpriteCB_MonIconDomeInfo,
x | sRightTrainerMonX[i],
y + sRightTrainerMonY[i],
0, 0, TRUE);
gSprites[sInfoCard->spriteIds[5 + i + arrId]].oam.priority = 0;
}
else
{
sInfoCard->spriteIds[5 + i + arrId] = CreateMonIcon(gFacilityTrainerMons[DOME_MONS[tournamentIds[1]][i]].species,
SpriteCB_MonIconDomeInfo,
x | sRightTrainerMonX[i],
y + sRightTrainerMonY[i],
0, 0, TRUE);
gSprites[sInfoCard->spriteIds[5 + i + arrId]].oam.priority = 0;
}
if (flags & MOVE_CARD)
gSprites[sInfoCard->spriteIds[5 + i + arrId]].invisible = TRUE;
if (lost[1])
{
gSprites[sInfoCard->spriteIds[5 + i + arrId]].oam.paletteNum = 3;
gSprites[sInfoCard->spriteIds[5 + i + arrId]].sMonIconStill = TRUE;
}
}
// Print the win string (or 'Let the battle begin!').
textPrinter.x = 0;
textPrinter.y = 2;
textPrinter.currentX = textPrinter.x;
textPrinter.currentY = textPrinter.y;
textPrinter.letterSpacing = 0;
textPrinter.lineSpacing = 0;
textPrinter.unk = 0;
textPrinter.fgColor = TEXT_DYNAMIC_COLOR_5;
textPrinter.bgColor = TEXT_COLOR_TRANSPARENT;
textPrinter.shadowColor = TEXT_DYNAMIC_COLOR_4;
StringExpandPlaceholders(gStringVar4, sBattleDomeWinTexts[winStringId]);
textPrinter.currentChar = gStringVar4;
textPrinter.windowId = windowId + WIN_MATCH_WIN_TEXT;
textPrinter.fontId = FONT_NORMAL;
PutWindowTilemap(windowId + WIN_MATCH_WIN_TEXT);
CopyWindowToVram(windowId + WIN_MATCH_WIN_TEXT, COPYWIN_FULL);
textPrinter.currentX = 0;
textPrinter.currentY = textPrinter.y = 0;
AddTextPrinter(&textPrinter, 0, NULL);
// Print left trainer's name.
if (trainerIds[0] == TRAINER_PLAYER)
StringCopy(gStringVar1, gSaveBlock2Ptr->playerName);
else if (trainerIds[0] == TRAINER_FRONTIER_BRAIN)
CopyDomeBrainTrainerName(gStringVar1);
else
CopyDomeTrainerName(gStringVar1, trainerIds[0]);
textPrinter.fontId = FONT_SHORT;
textPrinter.letterSpacing = 2;
textPrinter.currentChar = gStringVar1;
textPrinter.windowId = windowId + WIN_MATCH_TRAINER_NAME_LEFT;
textPrinter.currentX = GetStringCenterAlignXOffsetWithLetterSpacing(textPrinter.fontId, textPrinter.currentChar, 0x40, textPrinter.letterSpacing);
textPrinter.currentY = textPrinter.y = 2;
PutWindowTilemap(windowId + WIN_MATCH_TRAINER_NAME_LEFT);
CopyWindowToVram(windowId + WIN_MATCH_TRAINER_NAME_LEFT, COPYWIN_FULL);
AddTextPrinter(&textPrinter, 0, NULL);
// Print right trainer's name.
if (trainerIds[1] == TRAINER_PLAYER)
StringCopy(gStringVar1, gSaveBlock2Ptr->playerName);
else if (trainerIds[1] == TRAINER_FRONTIER_BRAIN)
CopyDomeBrainTrainerName(gStringVar1);
else
CopyDomeTrainerName(gStringVar1, trainerIds[1]);
textPrinter.currentChar = gStringVar1;
textPrinter.windowId = windowId + WIN_MATCH_TRAINER_NAME_RIGHT;
textPrinter.currentX = GetStringCenterAlignXOffsetWithLetterSpacing(textPrinter.fontId, textPrinter.currentChar, 0x40, textPrinter.letterSpacing);
textPrinter.currentY = textPrinter.y = 2;
PutWindowTilemap(windowId + WIN_MATCH_TRAINER_NAME_RIGHT);
CopyWindowToVram(windowId + WIN_MATCH_TRAINER_NAME_RIGHT, COPYWIN_FULL);
AddTextPrinter(&textPrinter, 0, NULL);
// Print match number.
textPrinter.letterSpacing = 0;
textPrinter.currentChar = sBattleDomeMatchNumberTexts[matchNo];
textPrinter.windowId = windowId + WIN_MATCH_NUMBER;
textPrinter.currentX = GetStringCenterAlignXOffsetWithLetterSpacing(textPrinter.fontId, textPrinter.currentChar, 0xA0, textPrinter.letterSpacing);
textPrinter.currentY = textPrinter.y = 2;
PutWindowTilemap(windowId + WIN_MATCH_NUMBER);
CopyWindowToVram(windowId + WIN_MATCH_NUMBER, COPYWIN_FULL);
AddTextPrinter(&textPrinter, 0, NULL);
}
static void ShowDomeTourneyTree(void)
{
u8 taskId = CreateTask(Task_ShowTourneyTree, 0);
gTasks[taskId].tState = 0;
gTasks[taskId].tNotInteractive = FALSE;
gTasks[taskId].data[2] = 2;
gTasks[taskId].tIsPrevTourneyTree = FALSE;
SetMainCallback2(CB2_TourneyTree);
}
// To show the results of the last tourney on the computer in the lobby
static void ShowPreviousDomeTourneyTree(void)
{
u8 taskId;
SetFacilityTrainerAndMonPtrs();
gSaveBlock2Ptr->frontier.lvlMode = gSaveBlock2Ptr->frontier.domeLvlMode - 1;
gSaveBlock2Ptr->frontier.curChallengeBattleNum = DOME_FINAL;
taskId = CreateTask(Task_ShowTourneyTree, 0);
gTasks[taskId].tState = 0;
gTasks[taskId].tNotInteractive = FALSE;
gTasks[taskId].data[2] = 2;
gTasks[taskId].tIsPrevTourneyTree = TRUE;
SetMainCallback2(CB2_TourneyTree);
}
// Task states for Task_HandleTourneyTreeInput
#define STATE_FADE_IN 0
#define STATE_WAIT_FADE 1
#define STATE_GET_INPUT 2
#define STATE_SHOW_INFOCARD_TRAINER 3
#define STATE_SHOW_INFOCARD_MATCH 5
#define STATE_CLOSE_TOURNEY_TREE 7
static void Task_HandleTourneyTreeInput(u8 taskId)
{
u8 newTaskId = 0;
int spriteId = gTasks[taskId].data[1];
switch (gTasks[taskId].tState)
{
case STATE_FADE_IN:
if (!gPaletteFade.active)
{
BeginNormalPaletteFade(PALETTES_ALL, 0, 0x10, 0, RGB_BLACK);
gTasks[taskId].tState = STATE_WAIT_FADE;
StartSpriteAnim(&gSprites[spriteId], 1);
}
break;
case STATE_WAIT_FADE:
if (!gPaletteFade.active)
gTasks[taskId].tState = STATE_GET_INPUT;
break;
case STATE_GET_INPUT:
switch (UpdateTourneyTreeCursor(taskId))
{
case TOURNEY_TREE_SELECTED_CLOSE:
default:
BeginNormalPaletteFade(PALETTES_ALL, 0, 0, 0x10, RGB_BLACK);
gTasks[taskId].tState = STATE_CLOSE_TOURNEY_TREE;
break;
case TOURNEY_TREE_NO_SELECTION:
break;
case TOURNEY_TREE_SELECTED_TRAINER:
BeginNormalPaletteFade(PALETTES_ALL, 0, 0, 0x10, RGB_BLACK);
gTasks[taskId].tState = STATE_SHOW_INFOCARD_TRAINER;
break;
case TOURNEY_TREE_SELECTED_MATCH:
BeginNormalPaletteFade(PALETTES_ALL, 0, 0, 0x10, RGB_BLACK);
gTasks[taskId].tState = STATE_SHOW_INFOCARD_MATCH;
break;
}
break;
case STATE_SHOW_INFOCARD_TRAINER:
if (!gPaletteFade.active)
{
FreeAllWindowBuffers();
ScanlineEffect_Stop();
FREE_AND_SET_NULL(sTilemapBuffer);
newTaskId = CreateTask(Task_ShowTourneyInfoCard, 0);
gTasks[newTaskId].tState = 0;
gTasks[newTaskId].tTournamentId = sTourneyTreeTrainerIds[spriteId];
gTasks[newTaskId].tMode = INFOCARD_TRAINER;
gTasks[newTaskId].tPrevTaskId = taskId;
gTasks[taskId].tState = STATE_SHOW_INFOCARD_TRAINER + 1;
sInfoCard->pos = 0;
}
break;
case STATE_SHOW_INFOCARD_TRAINER + 1:
break;
case STATE_SHOW_INFOCARD_MATCH:
if (!gPaletteFade.active)
{
FreeAllWindowBuffers();
ScanlineEffect_Stop();
FREE_AND_SET_NULL(sTilemapBuffer);
newTaskId = CreateTask(Task_ShowTourneyInfoCard, 0);
gTasks[newTaskId].tState = 0;
gTasks[newTaskId].tTournamentId = spriteId - DOME_TOURNAMENT_TRAINERS_COUNT;
gTasks[newTaskId].tMode = INFOCARD_MATCH;
gTasks[newTaskId].tPrevTaskId = taskId;
gTasks[taskId].tState = STATE_SHOW_INFOCARD_MATCH + 1;
}
break;
case STATE_SHOW_INFOCARD_MATCH + 1:
break;
case STATE_CLOSE_TOURNEY_TREE:
if (!gPaletteFade.active)
{
FreeAllWindowBuffers();
ScanlineEffect_Stop();
FREE_AND_SET_NULL(sTilemapBuffer);
SetMainCallback2(CB2_ReturnToFieldContinueScriptPlayMapMusic);
DestroyTask(gTasks[taskId].data[7]);
DestroyTask(taskId);
}
break;
}
}
// undefine task states for Task_HandleTourneyTreeInput
#undef STATE_FADE_IN
#undef STATE_WAIT_FADE
#undef STATE_GET_INPUT
#undef STATE_SHOW_INFOCARD_TRAINER
#undef STATE_SHOW_INFOCARD_MATCH
#undef STATE_CLOSE_TOURNEY_TREE
#define MOVE_DIR_UP 0
#define MOVE_DIR_DOWN 1
#define MOVE_DIR_LEFT 2
#define MOVE_DIR_RIGHT 3
#define MOVE_DIR_NONE 4
// Move the tourney tree cursor
// The 'cursor' is actually just which button sprite is currently doing the 'selected' animation
static u8 UpdateTourneyTreeCursor(u8 taskId)
{
u8 selection = TOURNEY_TREE_NO_SELECTION;
int direction = MOVE_DIR_NONE;
int tourneyTreeCursorSpriteId = gTasks[taskId].data[1];
int roundId = gSaveBlock2Ptr->frontier.curChallengeBattleNum;
if (gMain.newKeys == B_BUTTON || (JOY_NEW(A_BUTTON) && tourneyTreeCursorSpriteId == TOURNEY_TREE_CLOSE_BUTTON))
{
PlaySE(SE_SELECT);
selection = TOURNEY_TREE_SELECTED_CLOSE;
}
else if (JOY_NEW(A_BUTTON))
{
if (tourneyTreeCursorSpriteId < DOME_TOURNAMENT_TRAINERS_COUNT)
{
PlaySE(SE_SELECT);
selection = TOURNEY_TREE_SELECTED_TRAINER;
}
else
{
PlaySE(SE_SELECT);
selection = TOURNEY_TREE_SELECTED_MATCH;
}
}
else
{
if (gMain.newKeys == DPAD_UP && sTourneyTreeCursorMovementMap[tourneyTreeCursorSpriteId][roundId][0] != 0xFF)
direction = MOVE_DIR_UP;
else if (gMain.newKeys == DPAD_DOWN && sTourneyTreeCursorMovementMap[tourneyTreeCursorSpriteId][roundId][1] != 0xFF)
direction = MOVE_DIR_DOWN;
else if (gMain.newKeys == DPAD_LEFT && sTourneyTreeCursorMovementMap[tourneyTreeCursorSpriteId][roundId][2] != 0xFF)
direction = MOVE_DIR_LEFT;
else if (gMain.newKeys == DPAD_RIGHT && sTourneyTreeCursorMovementMap[tourneyTreeCursorSpriteId][roundId][3] != 0xFF)
direction = MOVE_DIR_RIGHT;
}
if (direction != MOVE_DIR_NONE)
{
PlaySE(SE_SELECT);
StartSpriteAnim(&gSprites[tourneyTreeCursorSpriteId], 0); // Do unselected sprite anim
tourneyTreeCursorSpriteId = sTourneyTreeCursorMovementMap[tourneyTreeCursorSpriteId][roundId][direction];
StartSpriteAnim(&gSprites[tourneyTreeCursorSpriteId], 1); // Do selected sprite anim
gTasks[taskId].data[1] = tourneyTreeCursorSpriteId;
}
return selection;
}
#undef MOVE_DIR_UP
#undef MOVE_DIR_DOWN
#undef MOVE_DIR_LEFT
#undef MOVE_DIR_RIGHT
#undef MOVE_DIR_NONE
// Shows the results of the just-completed round for the current tourney
static void ShowNonInteractiveDomeTourneyTree(void)
{
u8 taskId = CreateTask(Task_ShowTourneyTree, 0);
gTasks[taskId].tState = 0;
gTasks[taskId].tNotInteractive = TRUE;
gTasks[taskId].data[2] = 2;
gTasks[taskId].tIsPrevTourneyTree = FALSE;
SetMainCallback2(CB2_TourneyTree);
}
static void ResolveDomeRoundWinners(void)
{
int i;
if (gSpecialVar_0x8005 == DOME_PLAYER_WON_MATCH)
{
DOME_TRAINERS[TrainerIdToTournamentId(gTrainerBattleOpponent_A)].isEliminated = TRUE;
DOME_TRAINERS[TrainerIdToTournamentId(gTrainerBattleOpponent_A)].eliminatedAt = gSaveBlock2Ptr->frontier.curChallengeBattleNum;
gSaveBlock2Ptr->frontier.domeWinningMoves[TrainerIdToTournamentId(gTrainerBattleOpponent_A)] = gBattleResults.lastUsedMovePlayer;
// If the player's match was the final one, no NPC vs NPC matches to decide
if (gSaveBlock2Ptr->frontier.curChallengeBattleNum < DOME_FINAL)
DecideRoundWinners(gSaveBlock2Ptr->frontier.curChallengeBattleNum);
}
else // DOME_PLAYER_LOST_MATCH or DOME_PLAYER_RETIRED
{
DOME_TRAINERS[TrainerIdToTournamentId(TRAINER_PLAYER)].isEliminated = TRUE;
DOME_TRAINERS[TrainerIdToTournamentId(TRAINER_PLAYER)].eliminatedAt = gSaveBlock2Ptr->frontier.curChallengeBattleNum;
gSaveBlock2Ptr->frontier.domeWinningMoves[TrainerIdToTournamentId(TRAINER_PLAYER)] = gBattleResults.lastUsedMoveOpponent;
if (gBattleOutcome == B_OUTCOME_FORFEITED || gSpecialVar_0x8005 == DOME_PLAYER_RETIRED)
DOME_TRAINERS[TrainerIdToTournamentId(TRAINER_PLAYER)].forfeited = TRUE;
// Player lost, decide remaining outcome of tournament
for (i = gSaveBlock2Ptr->frontier.curChallengeBattleNum; i < DOME_ROUNDS_COUNT; i++)
DecideRoundWinners(i);
}
}
// Decides the winning move of an NPC vs NPC match
static u16 GetWinningMove(int winnerTournamentId, int loserTournamentId, u8 roundId)
{
int i, j, k;
int moveScores[MAX_MON_MOVES * FRONTIER_PARTY_SIZE];
u16 moveIds[MAX_MON_MOVES * FRONTIER_PARTY_SIZE];
u16 bestScore = 0;
u16 bestId = 0;
int movePower = 0;
SetFacilityPtrsGetLevel();
// Calc move points of all 4 moves for all 3 pokemon hitting all 3 target mons.
for (i = 0; i < FRONTIER_PARTY_SIZE; i++)
{
for (j = 0; j < MAX_MON_MOVES; j++)
{
// TODO: Clean this up, looks like a different data structure (2D array)
moveScores[i * MAX_MON_MOVES + j] = 0;
if (DOME_TRAINERS[winnerTournamentId].trainerId == TRAINER_FRONTIER_BRAIN)
moveIds[i * MAX_MON_MOVES + j] = GetFrontierBrainMonMove(i, j);
else
moveIds[i * MAX_MON_MOVES + j] = gFacilityTrainerMons[DOME_MONS[winnerTournamentId][i]].moves[j];
movePower = gBattleMoves[moveIds[i * MAX_MON_MOVES + j]].power;
if (movePower == 0)
movePower = 40;
else if (movePower == 1)
movePower = 60;
else if (moveIds[i * MAX_MON_MOVES + j] == MOVE_SELF_DESTRUCT
|| moveIds[i * MAX_MON_MOVES + j] == MOVE_EXPLOSION)
movePower /= 2;
for (k = 0; k < FRONTIER_PARTY_SIZE; k++)
{
u32 var = 0;
u16 targetSpecies = SPECIES_NONE;
u16 targetAbility = ABILITY_NONE;
do
{
var = Random32();
} while (gFacilityTrainerMons[DOME_MONS[loserTournamentId][k]].nature != GetNatureFromPersonality(var));
targetSpecies = gFacilityTrainerMons[DOME_MONS[loserTournamentId][k]].species;
if (var & 1)
targetAbility = gSpeciesInfo[targetSpecies].abilities[1];
else
targetAbility = gSpeciesInfo[targetSpecies].abilities[0];
var = AI_TypeCalc(moveIds[i * MAX_MON_MOVES + j], targetSpecies, targetAbility);
if (var & MOVE_RESULT_NOT_VERY_EFFECTIVE && var & MOVE_RESULT_SUPER_EFFECTIVE)
moveScores[i * MAX_MON_MOVES + j] += movePower;
else if (var & MOVE_RESULT_NO_EFFECT)
moveScores[i * MAX_MON_MOVES + j] += 0;
else if (var & MOVE_RESULT_SUPER_EFFECTIVE)
moveScores[i * MAX_MON_MOVES + j] += movePower * 2;
else if (var & MOVE_RESULT_NOT_VERY_EFFECTIVE)
moveScores[i * MAX_MON_MOVES + j] += movePower / 2;
else
moveScores[i * MAX_MON_MOVES + j] += movePower;
}
if (bestScore < moveScores[i * MAX_MON_MOVES + j])
{
bestId = i * MAX_MON_MOVES + j;
bestScore = moveScores[i * MAX_MON_MOVES + j];
}
else if (bestScore == moveScores[i * MAX_MON_MOVES + j])
{
if (moveIds[bestId] < moveIds[i * MAX_MON_MOVES + j]) // Why not use (Random() & 1) instead of promoting moves with a higher id?
bestId = i * MAX_MON_MOVES + j;
}
}
}
j = bestId;
do
{
for (i = 0; i < roundId - 1; i++)
{
if (gSaveBlock2Ptr->frontier.domeWinningMoves[GetOpposingNPCTournamentIdByRound(winnerTournamentId, i)] == moveIds[j])
break;
}
if (i != roundId - 1)
{
moveScores[j] = 0;
bestScore = 0;
j = 0;
for (k = 0; k < MAX_MON_MOVES * FRONTIER_PARTY_SIZE; k++)
j += moveScores[k];
if (j == 0)
break;
j = 0;
for (k = 0; k < MAX_MON_MOVES * FRONTIER_PARTY_SIZE; k++)
{
if (bestScore < moveScores[k])
{
j = k;
bestScore = moveScores[k];
}
else if (bestScore == moveScores[k] && moveIds[j] < moveIds[k]) // Yes, these conditions are redundant
{
j = k;
bestScore = moveScores[k];
}
}
}
} while (i != roundId - 1);
if (moveScores[j] == 0)
j = bestId;
return moveIds[j];
}
static void Task_ShowTourneyTree(u8 taskId)
{
int i;
struct TextPrinterTemplate textPrinter;
int notInteractive = gTasks[taskId].tNotInteractive;
int r4 = gTasks[taskId].data[2];
switch (gTasks[taskId].tState)
{
case 0:
SetHBlankCallback(NULL);
SetVBlankCallback(NULL);
EnableInterrupts(INTR_FLAG_HBLANK | INTR_FLAG_VBLANK);
CpuFill32(0, (void *)VRAM, VRAM_SIZE);
ResetBgsAndClearDma3BusyFlags(0);
InitBgsFromTemplates(0, sTourneyTreeBgTemplates, ARRAY_COUNT(sTourneyTreeBgTemplates));
InitWindows(sTourneyTreeWindowTemplates);
DeactivateAllTextPrinters();
gBattle_BG0_X = 0;
gBattle_BG0_Y = 0;
gBattle_BG1_X = 0;
gBattle_BG1_Y = 0;
ChangeBgX(2, 0, BG_COORD_SET);
ChangeBgY(2, 0, BG_COORD_SET);
ChangeBgX(3, 0, BG_COORD_SET);
ChangeBgY(3, 0xB00, BG_COORD_SET);
gTasks[taskId].tState++;
break;
case 1:
SetGpuReg(REG_OFFSET_BLDCNT, 0);
SetGpuReg(REG_OFFSET_BLDALPHA, 0);
SetGpuReg(REG_OFFSET_BLDY, 0);
SetGpuReg(REG_OFFSET_MOSAIC, 0);
SetGpuReg(REG_OFFSET_WIN0H, WIN_RANGE(88, 96));
SetGpuReg(REG_OFFSET_WIN0V, WIN_RANGE(0, DISPLAY_HEIGHT - 1));
SetGpuReg(REG_OFFSET_WIN1H, WIN_RANGE(144, 152));
SetGpuReg(REG_OFFSET_WIN1V, WIN_RANGE(0, DISPLAY_HEIGHT - 1));
SetGpuReg(REG_OFFSET_WININ, 0);
SetGpuReg(REG_OFFSET_WINOUT, WINOUT_WIN01_BG_ALL | WINOUT_WIN01_OBJ | WINOUT_WIN01_CLR);
ResetPaletteFade();
ResetSpriteData();
FreeAllSpritePalettes();
gTasks[taskId].tState++;
break;
case 2:
sTilemapBuffer = AllocZeroed(BG_SCREEN_SIZE);
LZDecompressWram(gDomeTourneyTree_Tilemap, sTilemapBuffer);
SetBgTilemapBuffer(1, sTilemapBuffer);
CopyBgTilemapBufferToVram(1);
DecompressAndLoadBgGfxUsingHeap(1, gDomeTourneyTree_Gfx, 0x2000, 0, 0);
DecompressAndLoadBgGfxUsingHeap(2, gDomeTourneyLine_Gfx, 0x2000, 0, 0);
DecompressAndLoadBgGfxUsingHeap(2, gDomeTourneyLineDown_Tilemap, 0x2000, 0, 1);
DecompressAndLoadBgGfxUsingHeap(3, gDomeTourneyLineUp_Tilemap, 0x2000, 0, 1);
LoadCompressedPalette(gDomeTourneyTree_Pal, BG_PLTT_OFFSET, BG_PLTT_SIZE);
LoadCompressedPalette(gDomeTourneyTreeButtons_Pal, OBJ_PLTT_OFFSET, OBJ_PLTT_SIZE);
LoadCompressedPalette(gBattleWindowTextPalette, BG_PLTT_ID(15), PLTT_SIZE_4BPP);
CpuFill32(0, gPlttBufferFaded, PLTT_SIZE);
ShowBg(0);
ShowBg(1);
ShowBg(2);
ShowBg(3);
gTasks[taskId].tState++;
break;
case 3:
LoadCompressedSpriteSheet(sTourneyTreeButtonsSpriteSheet);
if (notInteractive == FALSE)
{
for (i = 0; i < ARRAY_COUNT(sTourneyTreePokeballCoords); i++)
CreateSprite(&sTourneyTreePokeballSpriteTemplate, sTourneyTreePokeballCoords[i][0], sTourneyTreePokeballCoords[i][1], 0);
if (gTasks[taskId].tIsPrevTourneyTree)
CreateSprite(&sExitButtonSpriteTemplate, 218, 12, 0);
else
CreateSprite(&sCancelButtonSpriteTemplate, 218, 12, 0);
}
SetGpuReg(REG_OFFSET_DISPCNT, DISPCNT_BG_ALL_ON | DISPCNT_OBJ_ON | DISPCNT_WIN0_ON | DISPCNT_WIN1_ON | DISPCNT_OBJ_1D_MAP);
gTasks[taskId].tState++;
break;
case 4:
textPrinter.fontId = FONT_SHORT;
textPrinter.currentChar = gText_BattleTourney;
textPrinter.windowId = TOURNEYWIN_TITLE;
textPrinter.x = 0;
textPrinter.y = 0;
textPrinter.letterSpacing = 2;
textPrinter.lineSpacing = 0;
textPrinter.currentX = GetStringCenterAlignXOffsetWithLetterSpacing(textPrinter.fontId, textPrinter.currentChar, 0x70, textPrinter.letterSpacing);
textPrinter.currentY = 1;
textPrinter.unk = 0;
textPrinter.fgColor = TEXT_DYNAMIC_COLOR_5;
textPrinter.bgColor = TEXT_COLOR_TRANSPARENT;
textPrinter.shadowColor = TEXT_DYNAMIC_COLOR_4;
AddTextPrinter(&textPrinter, 0, NULL);
for (i = 0; i < DOME_TOURNAMENT_TRAINERS_COUNT; i++)
{
int roundId, var2;
CopyDomeTrainerName(gDisplayedStringBattle, DOME_TRAINERS[i].trainerId);
if (notInteractive == TRUE)
{
if (DOME_TRAINERS[i].isEliminated)
{
if (DOME_TRAINERS[i].eliminatedAt != DOME_ROUND1)
{
var2 = DOME_TRAINERS[i].eliminatedAt - 1;
DrawTourneyAdvancementLine(i, var2);
}
}
else if (gSaveBlock2Ptr->frontier.curChallengeBattleNum != DOME_ROUND2)
{
DrawTourneyAdvancementLine(i, gSaveBlock2Ptr->frontier.curChallengeBattleNum - 2);
}
}
else if (notInteractive == FALSE)
{
if (DOME_TRAINERS[i].isEliminated)
{
if (DOME_TRAINERS[i].eliminatedAt != DOME_ROUND1)
{
var2 = DOME_TRAINERS[i].eliminatedAt - 1;
DrawTourneyAdvancementLine(i, var2);
}
}
else if (gSaveBlock2Ptr->frontier.curChallengeBattleNum != DOME_ROUND1)
{
if (gTasks[taskId].tIsPrevTourneyTree)
var2 = gSaveBlock2Ptr->frontier.curChallengeBattleNum;
else
var2 = gSaveBlock2Ptr->frontier.curChallengeBattleNum - 1;
DrawTourneyAdvancementLine(i, var2);
}
}
if (gTasks[taskId].tIsPrevTourneyTree)
roundId = gSaveBlock2Ptr->frontier.curChallengeBattleNum;
else
roundId = gSaveBlock2Ptr->frontier.curChallengeBattleNum - 1;
if ( ((notInteractive == TRUE && DOME_TRAINERS[i].eliminatedAt < gSaveBlock2Ptr->frontier.curChallengeBattleNum - 1)
|| (notInteractive == FALSE && DOME_TRAINERS[i].eliminatedAt <= roundId))
&& DOME_TRAINERS[i].isEliminated)
{
if (DOME_TRAINERS[i].trainerId == TRAINER_PLAYER)
{
textPrinter.fgColor = TEXT_COLOR_LIGHT_GRAY;
textPrinter.shadowColor = TEXT_COLOR_RED;
}
else
{
textPrinter.fgColor = TEXT_DYNAMIC_COLOR_2;
textPrinter.shadowColor = TEXT_DYNAMIC_COLOR_4;
}
}
else
{
if (DOME_TRAINERS[i].trainerId == TRAINER_PLAYER)
{
textPrinter.fgColor = TEXT_COLOR_LIGHT_GRAY;
textPrinter.shadowColor = TEXT_COLOR_RED;
}
else
{
textPrinter.fgColor = TEXT_DYNAMIC_COLOR_5;
textPrinter.shadowColor = TEXT_DYNAMIC_COLOR_4;
}
}
if (sTrainerNamePositions[i][0] == TOURNEYWIN_NAMES_LEFT)
textPrinter.currentX = GetStringWidthDifference(textPrinter.fontId, gDisplayedStringBattle, 0x3D, textPrinter.letterSpacing);
else
textPrinter.currentX = 3;
textPrinter.currentChar = gDisplayedStringBattle;
textPrinter.windowId = sTrainerNamePositions[i][0];
textPrinter.currentY = sTrainerNamePositions[i][1];
AddTextPrinter(&textPrinter, 0, NULL);
}
gTasks[taskId].tState++;
break;
case 5:
PutWindowTilemap(TOURNEYWIN_NAMES_LEFT);
PutWindowTilemap(TOURNEYWIN_NAMES_RIGHT);
PutWindowTilemap(TOURNEYWIN_TITLE);
CopyWindowToVram(TOURNEYWIN_NAMES_LEFT, COPYWIN_FULL);
CopyWindowToVram(TOURNEYWIN_NAMES_RIGHT, COPYWIN_FULL);
CopyWindowToVram(TOURNEYWIN_TITLE, COPYWIN_FULL);
SetHBlankCallback(HblankCb_TourneyTree);
SetVBlankCallback(VblankCb_TourneyTree);
if (r4 == 2)
{
if (notInteractive == FALSE)
{
i = CreateTask(Task_HandleTourneyTreeInput, 0);
gTasks[i].data[0] = notInteractive;
gTasks[i].data[1] = notInteractive;
gTasks[i].data[6] = gTasks[taskId].tIsPrevTourneyTree;
}
else
{
i = CreateTask(Task_HandleStaticTourneyTreeInput, 0);
gTasks[i].data[0] = 0;
}
}
else
{
i = gTasks[taskId].data[3];
gTasks[i].tState = 0;
}
ScanlineEffect_Clear();
i = 0;
while (i < 91)
{
gScanlineEffectRegBuffers[0][i] = BGCNT_PRIORITY(2) | BGCNT_SCREENBASE(31) | BGCNT_16COLOR | BGCNT_CHARBASE(2) | BGCNT_TXT256x256;
gScanlineEffectRegBuffers[1][i] = BGCNT_PRIORITY(2) | BGCNT_SCREENBASE(31) | BGCNT_16COLOR | BGCNT_CHARBASE(2) | BGCNT_TXT256x256;
i++;
}
while (i < 160)
{
gScanlineEffectRegBuffers[0][i] = BGCNT_PRIORITY(1) | BGCNT_SCREENBASE(31) | BGCNT_16COLOR | BGCNT_CHARBASE(2) | BGCNT_TXT256x256;
gScanlineEffectRegBuffers[1][i] = BGCNT_PRIORITY(1) | BGCNT_SCREENBASE(31) | BGCNT_16COLOR | BGCNT_CHARBASE(2) | BGCNT_TXT256x256;
i++;
}
ScanlineEffect_SetParams(sTourneyTreeScanlineEffectParams);
DestroyTask(taskId);
break;
}
}
static void DrawTourneyAdvancementLine(u8 tournamentId, u8 roundId)
{
int i;
const struct TourneyTreeLineSection *lineSection = sTourneyTreeLineSections[tournamentId][roundId];
for (i = 0; i < sTourneyTreeLineSectionArrayCounts[tournamentId][roundId]; i++)
CopyToBgTilemapBufferRect_ChangePalette(1, &lineSection[i].tile, lineSection[i].x, lineSection[i].y, 1, 1, 17);
CopyBgTilemapBufferToVram(1);
}
#define STATE_FADE_IN 0
#define STATE_SHOW_RESULTS 1
#define STATE_DELAY 2
#define STATE_WAIT_FOR_INPUT 3
#define STATE_CLOSE_TOURNEY_TREE 4
// The non-interactive tourney tree that's shown when a round is completed
static void Task_HandleStaticTourneyTreeInput(u8 taskId)
{
int i;
struct TextPrinterTemplate textPrinter;
switch (gTasks[taskId].tState)
{
case STATE_FADE_IN:
BeginNormalPaletteFade(PALETTES_ALL, 0, 0x10, 0, RGB_BLACK);
gTasks[taskId].tState = STATE_SHOW_RESULTS;
break;
case STATE_SHOW_RESULTS:
if (!gPaletteFade.active)
{
gTasks[taskId].tState = STATE_DELAY;
gTasks[taskId].data[3] = 64;
textPrinter.fontId = FONT_SHORT;
textPrinter.x = 0;
textPrinter.y = 0;
textPrinter.letterSpacing = 2;
textPrinter.lineSpacing = 0;
textPrinter.unk = 0;
textPrinter.fgColor = TEXT_DYNAMIC_COLOR_2;
textPrinter.bgColor = TEXT_COLOR_TRANSPARENT;
textPrinter.shadowColor = TEXT_DYNAMIC_COLOR_4;
// Update the advancement lines and gray out eliminated trainer names
for (i = 0; i < DOME_TOURNAMENT_TRAINERS_COUNT; i++)
{
CopyDomeTrainerName(gDisplayedStringBattle, DOME_TRAINERS[i].trainerId);
if (DOME_TRAINERS[i].eliminatedAt == gSaveBlock2Ptr->frontier.curChallengeBattleNum - 1
&& DOME_TRAINERS[i].isEliminated)
{
if (sTrainerNamePositions[i][0] == TOURNEYWIN_NAMES_LEFT)
textPrinter.currentX = GetStringWidthDifference(textPrinter.fontId, gDisplayedStringBattle, 0x3D, textPrinter.letterSpacing);
else
textPrinter.currentX = 3;
textPrinter.currentChar = gDisplayedStringBattle;
textPrinter.windowId = sTrainerNamePositions[i][0];
textPrinter.currentY = sTrainerNamePositions[i][1];
AddTextPrinter(&textPrinter, 0, NULL);
}
if (!DOME_TRAINERS[i].isEliminated)
{
int roundId = gSaveBlock2Ptr->frontier.curChallengeBattleNum - 1;
DrawTourneyAdvancementLine(i, roundId);
}
}
}
break;
case STATE_DELAY:
if (--gTasks[taskId].data[3] == 0)
gTasks[taskId].tState = STATE_WAIT_FOR_INPUT;
break;
case STATE_WAIT_FOR_INPUT:
if (JOY_NEW(A_BUTTON | B_BUTTON))
{
BeginNormalPaletteFade(PALETTES_ALL, 0, 0, 0x10, RGB_BLACK);
gTasks[taskId].tState = STATE_CLOSE_TOURNEY_TREE;
}
break;
case STATE_CLOSE_TOURNEY_TREE:
if (!gPaletteFade.active)
{
SetMainCallback2(CB2_ReturnToFieldContinueScriptPlayMapMusic);
DestroyTask(taskId);
}
break;
}
}
#undef STATE_FADE_IN
#undef STATE_SHOW_RESULTS
#undef STATE_DELAY
#undef STATE_WAIT_FOR_INPUT
#undef STATE_CLOSE_TOURNEY_TREE
static void CB2_TourneyTree(void)
{
AnimateSprites();
BuildOamBuffer();
RunTextPrinters();
UpdatePaletteFade();
RunTasks();
}
static void VblankCb_TourneyInfoCard(void)
{
ChangeBgX(3, 0x80, BG_COORD_ADD);
ChangeBgY(3, 0x80, BG_COORD_SUB);
SetGpuReg(REG_OFFSET_BG0HOFS, gBattle_BG0_X);
SetGpuReg(REG_OFFSET_BG0VOFS, gBattle_BG0_Y);
SetGpuReg(REG_OFFSET_BG1HOFS, gBattle_BG1_X);
SetGpuReg(REG_OFFSET_BG1VOFS, gBattle_BG1_Y);
SetGpuReg(REG_OFFSET_BG2HOFS, gBattle_BG2_X);
SetGpuReg(REG_OFFSET_BG2VOFS, gBattle_BG2_Y);
LoadOam();
ProcessSpriteCopyRequests();
TransferPlttBuffer();
}
#define SET_WIN0H_WIN1H(win0H, win1H) \
{ \
*(vu32*)(REG_ADDR_WIN0H) = ((win0H << 16) | (win1H)); \
}
static void HblankCb_TourneyTree(void)
{
u16 vCount = REG_VCOUNT;
if (vCount < 42)
{
REG_WININ = WININ_WIN0_BG_ALL | WININ_WIN0_CLR | WININ_WIN0_OBJ
| WININ_WIN1_BG_ALL | WININ_WIN1_CLR | WININ_WIN1_OBJ;
SET_WIN0H_WIN1H(0, 0);
}
else if (vCount < 50)
{
REG_WININ = WININ_WIN0_BG0 | WININ_WIN0_BG1 | WININ_WIN0_BG3 | WININ_WIN0_OBJ | WININ_WIN0_CLR
| WININ_WIN1_BG0 | WININ_WIN1_BG1 | WININ_WIN1_BG3 | WININ_WIN1_OBJ | WININ_WIN1_CLR;
SET_WIN0H_WIN1H(WIN_RANGE(152, 155), WIN_RANGE(85, 88));
}
else if (vCount < 58)
{
REG_WININ = WININ_WIN0_BG_ALL | WININ_WIN0_CLR | WININ_WIN0_OBJ
| WININ_WIN1_BG_ALL | WININ_WIN1_CLR | WININ_WIN1_OBJ;
SET_WIN0H_WIN1H(0, 0);
}
else if (vCount < 75)
{
REG_WININ = WININ_WIN0_BG0 | WININ_WIN0_BG1 | WININ_WIN0_BG3 | WININ_WIN0_OBJ | WININ_WIN0_CLR
| WININ_WIN1_BG0 | WININ_WIN1_BG1 | WININ_WIN1_BG3 | WININ_WIN1_OBJ | WININ_WIN1_CLR;
SET_WIN0H_WIN1H(WIN_RANGE(144, 152), WIN_RANGE(88, 96));
}
else if (vCount < 82)
{
REG_WININ = WININ_WIN0_BG0 | WININ_WIN0_BG1 | WININ_WIN0_BG3 | WININ_WIN0_OBJ | WININ_WIN0_CLR
| WININ_WIN1_BG0 | WININ_WIN1_BG1 | WININ_WIN1_BG3 | WININ_WIN1_OBJ | WININ_WIN1_CLR;
SET_WIN0H_WIN1H(WIN_RANGE(152, 155), WIN_RANGE(85, 88));
}
else if (vCount < 95)
{
REG_WININ = WININ_WIN0_BG_ALL | WININ_WIN0_CLR | WININ_WIN0_OBJ
| WININ_WIN1_BG_ALL | WININ_WIN1_CLR | WININ_WIN1_OBJ;
SET_WIN0H_WIN1H(0, 0);
}
else if (vCount < 103)
{
REG_WININ = WININ_WIN0_BG0 | WININ_WIN0_BG1 | WININ_WIN0_BG2 | WININ_WIN0_OBJ | WININ_WIN0_CLR
| WININ_WIN1_BG0 | WININ_WIN1_BG1 | WININ_WIN1_BG2 | WININ_WIN1_OBJ | WININ_WIN1_CLR;
SET_WIN0H_WIN1H(WIN_RANGE(152, 155), WIN_RANGE(85, 88));
}
else if (vCount < 119)
{
REG_WININ = WININ_WIN0_BG0 | WININ_WIN0_BG1 | WININ_WIN0_BG2 | WININ_WIN0_OBJ | WININ_WIN0_CLR
| WININ_WIN1_BG0 | WININ_WIN1_BG1 | WININ_WIN1_BG2 | WININ_WIN1_OBJ | WININ_WIN1_CLR;
SET_WIN0H_WIN1H(WIN_RANGE(144, 152), WIN_RANGE(88, 96));
}
else if (vCount < 127)
{
REG_WININ = WININ_WIN0_BG_ALL | WININ_WIN0_CLR | WININ_WIN0_OBJ
| WININ_WIN1_BG_ALL | WININ_WIN1_CLR | WININ_WIN1_OBJ;
SET_WIN0H_WIN1H(0, 0);
}
else if (vCount < 135)
{
REG_WININ = WININ_WIN0_BG0 | WININ_WIN0_BG1 | WININ_WIN0_BG2 | WININ_WIN0_OBJ | WININ_WIN0_CLR
| WININ_WIN1_BG0 | WININ_WIN1_BG1 | WININ_WIN1_BG2 | WININ_WIN1_OBJ | WININ_WIN1_CLR;
SET_WIN0H_WIN1H(WIN_RANGE(152, 155), WIN_RANGE(85, 88));
}
else
{
REG_WININ = WININ_WIN0_BG_ALL | WININ_WIN0_CLR | WININ_WIN0_OBJ
| WININ_WIN1_BG_ALL | WININ_WIN1_CLR | WININ_WIN1_OBJ;
SET_WIN0H_WIN1H(0, 0);
}
}
static void VblankCb_TourneyTree(void)
{
SetGpuReg(REG_OFFSET_BG0HOFS, gBattle_BG0_X);
SetGpuReg(REG_OFFSET_BG0VOFS, gBattle_BG0_Y);
SetGpuReg(REG_OFFSET_BG1HOFS, gBattle_BG1_X);
SetGpuReg(REG_OFFSET_BG1VOFS, gBattle_BG1_Y);
ChangeBgY(2, 0x80, BG_COORD_SUB);
ChangeBgY(3, 0x80, BG_COORD_ADD);
LoadOam();
ProcessSpriteCopyRequests();
TransferPlttBuffer();
ScanlineEffect_InitHBlankDmaTransfer();
}
static void SetFacilityTrainerAndMonPtrs(void)
{
gFacilityTrainerMons = gBattleFrontierMons;
gFacilityTrainers = gBattleFrontierTrainers;
}
static void ResetSketchedMoves(void)
{
int i, moveSlot;
for (i = 0; i < DOME_BATTLE_PARTY_SIZE; i++)
{
int playerMonId = gSaveBlock2Ptr->frontier.selectedPartyMons[gSelectedOrderFromParty[i] - 1] - 1;
int count;
for (moveSlot = 0; moveSlot < MAX_MON_MOVES; moveSlot++)
{
count = 0;
while (count < MAX_MON_MOVES)
{
if (GetMonData(&gSaveBlock1Ptr->playerParty[playerMonId], MON_DATA_MOVE1 + count, NULL) == GetMonData(&gPlayerParty[i], MON_DATA_MOVE1 + moveSlot, NULL))
break;
count++;
}
if (count == MAX_MON_MOVES)
SetMonMoveSlot(&gPlayerParty[i], MOVE_SKETCH, moveSlot);
}
gSaveBlock1Ptr->playerParty[playerMonId] = gPlayerParty[i];
}
}
static void RestoreDomePlayerPartyHeldItems(void)
{
int i;
for (i = 0; i < DOME_BATTLE_PARTY_SIZE; i++)
{
int playerMonId = gSaveBlock2Ptr->frontier.selectedPartyMons[gSelectedOrderFromParty[i] - 1] - 1;
u16 item = GetMonData(&gSaveBlock1Ptr->playerParty[playerMonId], MON_DATA_HELD_ITEM, NULL);
SetMonData(&gPlayerParty[i], MON_DATA_HELD_ITEM, &item);
}
}
static void ReduceDomePlayerPartyToSelectedMons(void)
{
ReducePlayerPartyToSelectedMons();
}
static void GetPlayerSeededBeforeOpponent(void)
{
// A higher tournament ID is a worse seed
if (TrainerIdToTournamentId(gTrainerBattleOpponent_A) > TrainerIdToTournamentId(TRAINER_PLAYER))
gSpecialVar_Result = 1;
else
gSpecialVar_Result = 2;
}
static void BufferLastDomeWinnerName(void)
{
int i;
SetFacilityTrainerAndMonPtrs();
for (i = 0; i < DOME_TOURNAMENT_TRAINERS_COUNT; i++)
{
if (!DOME_TRAINERS[i].isEliminated)
break;
}
CopyDomeTrainerName(gStringVar1, DOME_TRAINERS[i].trainerId);
}
// For showing the previous tourney results before the player has entered a challenge
static void InitRandomTourneyTreeResults(void)
{
int i, j, k;
int monLevel;
int species[FRONTIER_PARTY_SIZE];
int monTypesBits;
int trainerId;
int monId;
int zero1;
int zero2;
u8 lvlMode;
u16 *statSums;
int *statValues;
u8 ivs = 0;
species[0] = 0;
species[1] = 0;
species[2] = 0;
if ((gSaveBlock2Ptr->frontier.domeLvlMode != -gSaveBlock2Ptr->frontier.domeBattleMode) && gSaveBlock2Ptr->frontier.challengeStatus != CHALLENGE_STATUS_SAVING)
return;
statSums = AllocZeroed(sizeof(u16) * DOME_TOURNAMENT_TRAINERS_COUNT);
statValues = AllocZeroed(sizeof(int) * NUM_STATS);
lvlMode = gSaveBlock2Ptr->frontier.lvlMode;
gSaveBlock2Ptr->frontier.lvlMode = FRONTIER_LVL_50;
zero1 = 0;
zero2 = 0;
gSaveBlock2Ptr->frontier.domeLvlMode = zero1 + 1;
gSaveBlock2Ptr->frontier.domeBattleMode = zero2 + 1;
for (i = 0; i < DOME_TOURNAMENT_TRAINERS_COUNT; i++)
{
do
{
if (i < 5)
trainerId = Random() % 10;
else if (i < 15)
trainerId = Random() % 20 + 10;
else
trainerId = Random() % 10 + 30;
for (j = 0; j < i; j++)
{
if (DOME_TRAINERS[j].trainerId == trainerId)
break;
}
} while (j != i);
DOME_TRAINERS[i].trainerId = trainerId;
for (j = 0; j < FRONTIER_PARTY_SIZE; j++)
{
do
{
monId = GetRandomFrontierMonFromSet(trainerId);
for (k = 0; k < j; k++)
{
// Make sure the mon is valid.
int alreadySelectedMonId = DOME_MONS[i][k];
if (alreadySelectedMonId == monId
|| species[0] == gFacilityTrainerMons[monId].species
|| species[1] == gFacilityTrainerMons[monId].species
|| gFacilityTrainerMons[alreadySelectedMonId].itemTableId == gFacilityTrainerMons[monId].itemTableId)
break;
}
} while (k != j);
DOME_MONS[i][j] = monId;
species[j] = gFacilityTrainerMons[monId].species;
}
DOME_TRAINERS[i].isEliminated = FALSE;
DOME_TRAINERS[i].eliminatedAt = 0;
DOME_TRAINERS[i].forfeited = FALSE;
}
monLevel = FRONTIER_MAX_LEVEL_50;
for (i = 0; i < DOME_TOURNAMENT_TRAINERS_COUNT; i++)
{
monTypesBits = 0;
statSums[i] = 0;
ivs = GetDomeTrainerMonIvs(DOME_TRAINERS[i].trainerId);
for (j = 0; j < FRONTIER_PARTY_SIZE; j++)
{
CalcDomeMonStats(gFacilityTrainerMons[DOME_MONS[i][j]].species,
monLevel, ivs,
gFacilityTrainerMons[DOME_MONS[i][j]].evSpread,
gFacilityTrainerMons[DOME_MONS[i][j]].nature,
statValues);
statSums[i] += statValues[STAT_ATK];
statSums[i] += statValues[STAT_DEF];
statSums[i] += statValues[STAT_SPATK];
statSums[i] += statValues[STAT_SPDEF];
statSums[i] += statValues[STAT_SPEED];
statSums[i] += statValues[STAT_HP];
monTypesBits |= gBitTable[gSpeciesInfo[gFacilityTrainerMons[DOME_MONS[i][j]].species].types[0]];
monTypesBits |= gBitTable[gSpeciesInfo[gFacilityTrainerMons[DOME_MONS[i][j]].species].types[1]];
}
// Because GF hates temporary vars, trainerId acts like monTypesCount here.
for (trainerId = 0, j = 0; j < 32; j++)
{
if (monTypesBits & 1)
trainerId++;
monTypesBits >>= 1;
}
statSums[i] += (trainerId * monLevel) / 20;
}
for (i = 0; i < DOME_TOURNAMENT_TRAINERS_COUNT - 1; i++)
{
for (j = i + 1; j < DOME_TOURNAMENT_TRAINERS_COUNT; j++)
{
if (statSums[i] < statSums[j])
{
SwapDomeTrainers(i, j, statSums);
}
else if (statSums[i] == statSums[j])
{
if (DOME_TRAINERS[i].trainerId > DOME_TRAINERS[j].trainerId)
SwapDomeTrainers(i, j, statSums);
}
}
}
Free(statSums);
Free(statValues);
for (i = 0; i < DOME_ROUNDS_COUNT; i++)
DecideRoundWinners(i);
gSaveBlock2Ptr->frontier.lvlMode = lvlMode;
}
static int TrainerIdToTournamentId(u16 trainerId)
{
int i;
for (i = 0; i < DOME_TOURNAMENT_TRAINERS_COUNT; i++)
{
if (DOME_TRAINERS[i].trainerId == trainerId)
break;
}
return i;
}
// The same as the above one, but has global scope.
int TrainerIdToDomeTournamentId(u16 trainerId)
{
int i;
for (i = 0; i < DOME_TOURNAMENT_TRAINERS_COUNT; i++)
{
if (DOME_TRAINERS[i].trainerId == trainerId)
break;
}
return i;
}
static u8 GetOpposingNPCTournamentIdByRound(u8 tournamentId, u8 round)
{
u8 tournamentIds[2];
BufferDomeWinString(sTrainerAndRoundToLastMatchCardNum[sTournamentIdToPairedTrainerIds[tournamentId] / 2][round] - 16, tournamentIds);
if (tournamentId == tournamentIds[0])
return tournamentIds[1];
else
return tournamentIds[0];
}
// Determines which trainers won in the NPC vs NPC battles
static void DecideRoundWinners(u8 roundId)
{
int i;
int moveSlot, monId1, monId2;
int tournamentId1, tournamentId2;
int species;
int points1 = 0, points2 = 0;
for (i = 0; i < DOME_TOURNAMENT_TRAINERS_COUNT; i++)
{
if (DOME_TRAINERS[i].isEliminated || DOME_TRAINERS[i].trainerId == TRAINER_PLAYER)
continue;
tournamentId1 = i;
tournamentId2 = TournamentIdOfOpponent(roundId, DOME_TRAINERS[tournamentId1].trainerId);
// Frontier Brain always wins, check tournamentId1.
if (DOME_TRAINERS[tournamentId1].trainerId == TRAINER_FRONTIER_BRAIN && tournamentId2 != 0xFF)
{
DOME_TRAINERS[tournamentId2].isEliminated = TRUE;
DOME_TRAINERS[tournamentId2].eliminatedAt = roundId;
gSaveBlock2Ptr->frontier.domeWinningMoves[tournamentId2] = GetWinningMove(tournamentId1, tournamentId2, roundId);
}
// Frontier Brain always wins, check tournamentId2.
else if (DOME_TRAINERS[tournamentId2].trainerId == TRAINER_FRONTIER_BRAIN && tournamentId1 != 0xFF)
{
DOME_TRAINERS[tournamentId1].isEliminated = TRUE;
DOME_TRAINERS[tournamentId1].eliminatedAt = roundId;
gSaveBlock2Ptr->frontier.domeWinningMoves[tournamentId1] = GetWinningMove(tournamentId2, tournamentId1, roundId);
}
// Decide which one of two trainers wins!
else if (tournamentId2 != 0xFF)
{
// BUG: points1 and points2 are not cleared at the beginning of the loop resulting in not fair results.
#ifdef BUGFIX
points1 = 0;
points2 = 0;
#endif
// Calculate points for both trainers.
for (monId1 = 0; monId1 < FRONTIER_PARTY_SIZE; monId1++)
{
for (moveSlot = 0; moveSlot < MAX_MON_MOVES; moveSlot++)
{
for (monId2 = 0; monId2 < FRONTIER_PARTY_SIZE; monId2++)
{
points1 += GetTypeEffectivenessPoints(gFacilityTrainerMons[DOME_MONS[tournamentId1][monId1]].moves[moveSlot],
gFacilityTrainerMons[DOME_MONS[tournamentId2][monId2]].species, EFFECTIVENESS_MODE_AI_VS_AI);
}
}
species = gFacilityTrainerMons[DOME_MONS[tournamentId1][monId1]].species;
points1 += ( gSpeciesInfo[species].baseHP
+ gSpeciesInfo[species].baseAttack
+ gSpeciesInfo[species].baseDefense
+ gSpeciesInfo[species].baseSpeed
+ gSpeciesInfo[species].baseSpAttack
+ gSpeciesInfo[species].baseSpDefense) / 10;
}
// Random part of the formula.
points1 += (Random() & 0x1F);
// Favor trainers with higher id;
points1 += tournamentId1;
for (monId1 = 0; monId1 < FRONTIER_PARTY_SIZE; monId1++)
{
for (moveSlot = 0; moveSlot < MAX_MON_MOVES; moveSlot++)
{
for (monId2 = 0; monId2 < FRONTIER_PARTY_SIZE; monId2++)
{
points2 += GetTypeEffectivenessPoints(gFacilityTrainerMons[DOME_MONS[tournamentId2][monId1]].moves[moveSlot],
gFacilityTrainerMons[DOME_MONS[tournamentId1][monId2]].species, EFFECTIVENESS_MODE_AI_VS_AI);
}
}
species = gFacilityTrainerMons[DOME_MONS[tournamentId2][monId1]].species;
points2 += ( gSpeciesInfo[species].baseHP
+ gSpeciesInfo[species].baseAttack
+ gSpeciesInfo[species].baseDefense
+ gSpeciesInfo[species].baseSpeed
+ gSpeciesInfo[species].baseSpAttack
+ gSpeciesInfo[species].baseSpDefense) / 10;
}
// Random part of the formula.
points2 += (Random() & 0x1F);
// Favor trainers with higher id;
points2 += tournamentId2;
if (points1 > points2)
{
DOME_TRAINERS[tournamentId2].isEliminated = TRUE;
DOME_TRAINERS[tournamentId2].eliminatedAt = roundId;
gSaveBlock2Ptr->frontier.domeWinningMoves[tournamentId2] = GetWinningMove(tournamentId1, tournamentId2, roundId);
}
else if (points1 < points2)
{
DOME_TRAINERS[tournamentId1].isEliminated = TRUE;
DOME_TRAINERS[tournamentId1].eliminatedAt = roundId;
gSaveBlock2Ptr->frontier.domeWinningMoves[tournamentId1] = GetWinningMove(tournamentId2, tournamentId1, roundId);
}
// Points are the same, so we favor the one with the higher id.
else if (tournamentId1 > tournamentId2)
{
DOME_TRAINERS[tournamentId2].isEliminated = TRUE;
DOME_TRAINERS[tournamentId2].eliminatedAt = roundId;
gSaveBlock2Ptr->frontier.domeWinningMoves[tournamentId2] = GetWinningMove(tournamentId1, tournamentId2, roundId);
}
else
{
DOME_TRAINERS[tournamentId1].isEliminated = TRUE;
DOME_TRAINERS[tournamentId1].eliminatedAt = roundId;
gSaveBlock2Ptr->frontier.domeWinningMoves[tournamentId1] = GetWinningMove(tournamentId2, tournamentId1, roundId);
}
}
}
}
static void CopyDomeTrainerName(u8 *str, u16 trainerId)
{
int i = 0;
SetFacilityPtrsGetLevel();
if (trainerId == TRAINER_FRONTIER_BRAIN)
{
CopyDomeBrainTrainerName(str);
}
else
{
if (trainerId == TRAINER_PLAYER)
{
for (i = 0; i < PLAYER_NAME_LENGTH; i++)
str[i] = gSaveBlock2Ptr->playerName[i];
}
else if (trainerId < FRONTIER_TRAINERS_COUNT)
{
for (i = 0; i < PLAYER_NAME_LENGTH; i++)
str[i] = gFacilityTrainers[trainerId].trainerName[i];
}
str[i] = EOS;
}
}
static u8 GetDomeBrainTrainerPicId(void)
{
return gTrainers[TRAINER_TUCKER].trainerPic;
}
static u8 GetDomeBrainTrainerClass(void)
{
return gTrainers[TRAINER_TUCKER].trainerClass;
}
static void CopyDomeBrainTrainerName(u8 *str)
{
int i;
for (i = 0; i < PLAYER_NAME_LENGTH; i++)
str[i] = gTrainers[TRAINER_TUCKER].trainerName[i];
str[i] = EOS;
}
| 1 | 0.897792 | 1 | 0.897792 | game-dev | MEDIA | 0.967881 | game-dev | 0.969574 | 1 | 0.969574 |
kbengine/kbengine_cocos2d_js_demo | 21,100 | cocos2d-js-client/frameworks/js-bindings/cocos2d-x/cocos/physics/CCPhysicsBody.cpp | /****************************************************************************
Copyright (c) 2013 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "physics/CCPhysicsBody.h"
#if CC_USE_PHYSICS
#include <climits>
#include <algorithm>
#include <cmath>
#include "chipmunk.h"
#include "2d/CCScene.h"
#include "CCPhysicsShape.h"
#include "CCPhysicsJoint.h"
#include "CCPhysicsWorld.h"
#include "CCPhysicsHelper.h"
static inline void cpBodyUpdateVelocityWithoutGravity(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt)
{
cpBodyUpdateVelocity(body, cpvzero, damping, dt);
}
NS_CC_BEGIN
extern const float PHYSICS_INFINITY;
namespace
{
static const float MASS_DEFAULT = 1.0;
static const float MOMENT_DEFAULT = 200;
}
PhysicsBody::PhysicsBody()
: _node(nullptr)
, _world(nullptr)
, _cpBody(nullptr)
, _dynamic(true)
, _enabled(true)
, _rotationEnabled(true)
, _gravityEnabled(true)
, _massDefault(true)
, _momentDefault(true)
, _mass(MASS_DEFAULT)
, _area(0.0f)
, _density(0.0f)
, _moment(MOMENT_DEFAULT)
, _isDamping(false)
, _linearDamping(0.0f)
, _angularDamping(0.0f)
, _tag(0)
, _positionInitDirty(true)
, _recordedPosition(Vec2::ZERO)
, _rotationOffset(0)
, _recordedRotation(0.0f)
, _recordedAngle(0.0)
{
}
PhysicsBody::~PhysicsBody()
{
for (auto it = _joints.begin(); it != _joints.end(); ++it)
{
PhysicsJoint* joint = *it;
PhysicsBody* other = joint->getBodyA() == this ? joint->getBodyB() : joint->getBodyA();
other->removeJoint(joint);
delete joint;
}
if (_cpBody)
{
cpBodyFree(_cpBody);
}
}
PhysicsBody* PhysicsBody::create()
{
PhysicsBody* body = new (std::nothrow) PhysicsBody();
if (body && body->init())
{
body->autorelease();
return body;
}
CC_SAFE_DELETE(body);
return nullptr;
}
PhysicsBody* PhysicsBody::create(float mass)
{
PhysicsBody* body = new (std::nothrow) PhysicsBody();
if (body)
{
body->_mass = mass;
body->_massDefault = false;
if (body->init())
{
body->autorelease();
return body;
}
}
CC_SAFE_DELETE(body);
return nullptr;
}
PhysicsBody* PhysicsBody::create(float mass, float moment)
{
PhysicsBody* body = new (std::nothrow) PhysicsBody();
if (body)
{
body->_mass = mass;
body->_massDefault = false;
body->_moment = moment;
body->_momentDefault = false;
if (body->init())
{
body->autorelease();
return body;
}
}
CC_SAFE_DELETE(body);
return nullptr;
}
PhysicsBody* PhysicsBody::createCircle(float radius, const PhysicsMaterial& material, const Vec2& offset)
{
PhysicsBody* body = new (std::nothrow) PhysicsBody();
if (body && body->init())
{
body->addShape(PhysicsShapeCircle::create(radius, material, offset));
body->autorelease();
return body;
}
CC_SAFE_DELETE(body);
return nullptr;
}
PhysicsBody* PhysicsBody::createBox(const Size& size, const PhysicsMaterial& material, const Vec2& offset)
{
PhysicsBody* body = new (std::nothrow) PhysicsBody();
if (body && body->init())
{
body->addShape(PhysicsShapeBox::create(size, material, offset));
body->autorelease();
return body;
}
CC_SAFE_DELETE(body);
return nullptr;
}
PhysicsBody* PhysicsBody::createPolygon(const Vec2* points, int count, const PhysicsMaterial& material, const Vec2& offset)
{
PhysicsBody* body = new (std::nothrow) PhysicsBody();
if (body && body->init())
{
body->addShape(PhysicsShapePolygon::create(points, count, material, offset));
body->autorelease();
return body;
}
CC_SAFE_DELETE(body);
return nullptr;
}
PhysicsBody* PhysicsBody::createEdgeSegment(const Vec2& a, const Vec2& b, const PhysicsMaterial& material, float border/* = 1*/)
{
PhysicsBody* body = new (std::nothrow) PhysicsBody();
if (body && body->init())
{
body->addShape(PhysicsShapeEdgeSegment::create(a, b, material, border));
body->setDynamic(false);
body->autorelease();
return body;
}
CC_SAFE_DELETE(body);
return nullptr;
}
PhysicsBody* PhysicsBody::createEdgeBox(const Size& size, const PhysicsMaterial& material, float border/* = 1*/, const Vec2& offset)
{
PhysicsBody* body = new (std::nothrow) PhysicsBody();
if (body && body->init())
{
body->addShape(PhysicsShapeEdgeBox::create(size, material, border, offset));
body->setDynamic(false);
body->autorelease();
return body;
}
CC_SAFE_DELETE(body);
return nullptr;
}
PhysicsBody* PhysicsBody::createEdgePolygon(const Vec2* points, int count, const PhysicsMaterial& material, float border/* = 1*/)
{
PhysicsBody* body = new (std::nothrow) PhysicsBody();
if (body && body->init())
{
body->addShape(PhysicsShapeEdgePolygon::create(points, count, material, border));
body->setDynamic(false);
body->autorelease();
return body;
}
CC_SAFE_DELETE(body);
return nullptr;
}
PhysicsBody* PhysicsBody::createEdgeChain(const Vec2* points, int count, const PhysicsMaterial& material, float border/* = 1*/)
{
PhysicsBody* body = new (std::nothrow) PhysicsBody();
if (body && body->init())
{
body->addShape(PhysicsShapeEdgeChain::create(points, count, material, border));
body->setDynamic(false);
body->autorelease();
return body;
}
CC_SAFE_DELETE(body);
return nullptr;
}
bool PhysicsBody::init()
{
do
{
_cpBody = cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment));
CC_BREAK_IF(_cpBody == nullptr);
return true;
} while (false);
return false;
}
void PhysicsBody::removeJoint(PhysicsJoint* joint)
{
auto it = std::find(_joints.begin(), _joints.end(), joint);
if (it != _joints.end())
{
_joints.erase(it);
}
}
void PhysicsBody::setDynamic(bool dynamic)
{
if (dynamic != _dynamic)
{
_dynamic = dynamic;
if (dynamic)
{
if (_world && _cpBody->CP_PRIVATE(space))
{
cpSpaceConvertBodyToDynamic(_world->_cpSpace, _cpBody, _mass, _moment);
cpSpaceAddBody(_world->_cpSpace, _cpBody);
}
else
{
cpBodySetMass(_cpBody, _mass);
cpBodySetMoment(_cpBody, _moment);
}
}
else
{
if (_world && _cpBody->CP_PRIVATE(space))
{
cpSpaceRemoveBody(_world->_cpSpace, _cpBody);
cpSpaceConvertBodyToStatic(_world->_cpSpace, _cpBody);
}
else
{
cpBodySetMass(_cpBody, PHYSICS_INFINITY);
cpBodySetMoment(_cpBody, PHYSICS_INFINITY);
cpBodySetVel(_cpBody, cpvzero);
cpBodySetAngVel(_cpBody, 0.0);
}
}
}
}
void PhysicsBody::setRotationEnable(bool enable)
{
if (_rotationEnabled != enable)
{
cpBodySetMoment(_cpBody, enable ? _moment : PHYSICS_INFINITY);
_rotationEnabled = enable;
}
}
void PhysicsBody::setGravityEnable(bool enable)
{
_gravityEnabled = enable;
if (enable)
{
_cpBody->velocity_func = cpBodyUpdateVelocity;
}
else
{
_cpBody->velocity_func = cpBodyUpdateVelocityWithoutGravity;
}
}
void PhysicsBody::setPosition(const Vec2& position)
{
_positionInitDirty = false;
_recordedPosition = position;
cpBodySetPos(_cpBody, PhysicsHelper::point2cpv(position + _positionOffset));
}
void PhysicsBody::setRotation(float rotation)
{
_recordedRotation = rotation;
_recordedAngle = - (rotation + _rotationOffset) * (M_PI / 180.0);
cpBodySetAngle(_cpBody, _recordedAngle);
}
void PhysicsBody::setScale(float scaleX, float scaleY)
{
for (auto shape : _shapes)
{
shape->setScale(scaleX, scaleY);
}
}
const Vec2& PhysicsBody::getPosition()
{
if (_positionInitDirty) {
if (_node) {
if (_node->getParent()) {
_latestPosition = _node->getParent()->convertToWorldSpace(_node->getPosition());
} else {
_latestPosition = _node->getPosition();
}
}
} else {
_latestPosition.x = _cpBody->p.x - _positionOffset.x;
_latestPosition.y = _cpBody->p.y - _positionOffset.y;
}
return _latestPosition;
}
float PhysicsBody::getRotation()
{
if (_recordedAngle != cpBodyGetAngle(_cpBody)) {
_recordedAngle = cpBodyGetAngle(_cpBody);
_recordedRotation = - _recordedAngle * 180.0 / M_PI - _rotationOffset;
}
return _recordedRotation;
}
PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape, bool addMassAndMoment/* = true*/)
{
if (shape == nullptr) return nullptr;
// add shape to body
if (_shapes.getIndex(shape) == -1)
{
shape->setBody(this);
// calculate the area, mass, and desity
// area must update before mass, because the density changes depend on it.
if (addMassAndMoment)
{
_area += shape->getArea();
addMass(shape->getMass());
addMoment(shape->getMoment());
}
if (_world && _cpBody->CP_PRIVATE(space))
{
_world->addShape(shape);
}
_shapes.pushBack(shape);
}
return shape;
}
void PhysicsBody::applyForce(const Vect& force)
{
applyForce(force, Vec2::ZERO);
}
void PhysicsBody::applyForce(const Vect& force, const Vec2& offset)
{
if (_dynamic && _mass != PHYSICS_INFINITY)
{
cpBodyApplyForce(_cpBody, PhysicsHelper::point2cpv(force), PhysicsHelper::point2cpv(offset));
}
}
void PhysicsBody::resetForces()
{
cpBodyResetForces(_cpBody);
}
void PhysicsBody::applyImpulse(const Vect& impulse)
{
applyImpulse(impulse, Vec2());
}
void PhysicsBody::applyImpulse(const Vect& impulse, const Vec2& offset)
{
cpBodyApplyImpulse(_cpBody, PhysicsHelper::point2cpv(impulse), PhysicsHelper::point2cpv(offset));
}
void PhysicsBody::applyTorque(float torque)
{
cpBodySetTorque(_cpBody, PhysicsHelper::float2cpfloat(torque));
}
void PhysicsBody::setMass(float mass)
{
if (mass <= 0)
{
return;
}
_mass = mass;
_massDefault = false;
// update density
if (_mass == PHYSICS_INFINITY)
{
_density = PHYSICS_INFINITY;
}
else
{
if (_area > 0)
{
_density = _mass / _area;
}else
{
_density = 0;
}
}
// the static body's mass and moment is always infinity
if (_dynamic)
{
cpBodySetMass(_cpBody, _mass);
}
}
void PhysicsBody::addMass(float mass)
{
if (mass == PHYSICS_INFINITY)
{
_mass = PHYSICS_INFINITY;
_massDefault = false;
_density = PHYSICS_INFINITY;
}
else if (mass == -PHYSICS_INFINITY)
{
return;
}
else
{
if (_massDefault)
{
_mass = 0;
_massDefault = false;
}
if (_mass + mass > 0)
{
_mass += mass;
}else
{
_mass = MASS_DEFAULT;
_massDefault = true;
}
if (_area > 0)
{
_density = _mass / _area;
}
else
{
_density = 0;
}
}
// the static body's mass and moment is always infinity
if (_dynamic)
{
cpBodySetMass(_cpBody, _mass);
}
}
void PhysicsBody::addMoment(float moment)
{
if (moment == PHYSICS_INFINITY)
{
// if moment is PHYSICS_INFINITY, the moment of the body will become PHYSICS_INFINITY
_moment = PHYSICS_INFINITY;
_momentDefault = false;
}
else if (moment == -PHYSICS_INFINITY)
{
return;
}
else
{
// if moment of the body is PHYSICS_INFINITY is has no effect
if (_moment != PHYSICS_INFINITY)
{
if (_momentDefault)
{
_moment = 0;
_momentDefault = false;
}
if (_moment + moment > 0)
{
_moment += moment;
}
else
{
_moment = MOMENT_DEFAULT;
_momentDefault = true;
}
}
}
// the static body's mass and moment is always infinity
if (_rotationEnabled && _dynamic)
{
cpBodySetMoment(_cpBody, PhysicsHelper::float2cpfloat(_moment));
}
}
void PhysicsBody::setVelocity(const Vec2& velocity)
{
if (!_dynamic)
{
CCLOG("physics warning: your can't set velocity for a static body.");
return;
}
cpBodySetVel(_cpBody, PhysicsHelper::point2cpv(velocity));
}
Vec2 PhysicsBody::getVelocity()
{
return PhysicsHelper::cpv2point(cpBodyGetVel(_cpBody));
}
Vec2 PhysicsBody::getVelocityAtLocalPoint(const Vec2& point)
{
return PhysicsHelper::cpv2point(cpBodyGetVelAtLocalPoint(_cpBody, PhysicsHelper::point2cpv(point)));
}
Vec2 PhysicsBody::getVelocityAtWorldPoint(const Vec2& point)
{
return PhysicsHelper::cpv2point(cpBodyGetVelAtWorldPoint(_cpBody, PhysicsHelper::point2cpv(point)));
}
void PhysicsBody::setAngularVelocity(float velocity)
{
if (!_dynamic)
{
CCLOG("physics warning: your can't set angular velocity for a static body.");
return;
}
cpBodySetAngVel(_cpBody, PhysicsHelper::float2cpfloat(velocity));
}
float PhysicsBody::getAngularVelocity()
{
return PhysicsHelper::cpfloat2float(cpBodyGetAngVel(_cpBody));
}
void PhysicsBody::setVelocityLimit(float limit)
{
cpBodySetVelLimit(_cpBody, PhysicsHelper::float2cpfloat(limit));
}
float PhysicsBody::getVelocityLimit()
{
return PhysicsHelper::cpfloat2float(cpBodyGetVelLimit(_cpBody));
}
void PhysicsBody::setAngularVelocityLimit(float limit)
{
cpBodySetAngVelLimit(_cpBody, PhysicsHelper::float2cpfloat(limit));
}
float PhysicsBody::getAngularVelocityLimit()
{
return PhysicsHelper::cpfloat2float(cpBodyGetAngVelLimit(_cpBody));
}
void PhysicsBody::setMoment(float moment)
{
_moment = moment;
_momentDefault = false;
// the static body's mass and moment is always infinity
if (_rotationEnabled && _dynamic)
{
cpBodySetMoment(_cpBody, PhysicsHelper::float2cpfloat(_moment));
}
}
PhysicsShape* PhysicsBody::getShape(int tag) const
{
for (auto& shape : _shapes)
{
if (shape->getTag() == tag)
{
return shape;
}
}
return nullptr;
}
void PhysicsBody::removeShape(int tag, bool reduceMassAndMoment/* = true*/)
{
for (auto& shape : _shapes)
{
if (shape->getTag() == tag)
{
removeShape(shape, reduceMassAndMoment);
return;
}
}
}
void PhysicsBody::removeShape(PhysicsShape* shape, bool reduceMassAndMoment/* = true*/)
{
if (_shapes.getIndex(shape) != -1)
{
// deduce the area, mass and moment
// area must update before mass, because the density changes depend on it.
if (reduceMassAndMoment)
{
_area -= shape->getArea();
addMass(-shape->getMass());
addMoment(-shape->getMoment());
}
//remove
if (_world)
{
_world->removeShape(shape);
}
// set shape->_body = nullptr make the shape->setBody will not trigger the _body->removeShape function call.
shape->_body = nullptr;
shape->setBody(nullptr);
_shapes.eraseObject(shape);
}
}
void PhysicsBody::removeAllShapes(bool reduceMassAndMoment/* = true*/)
{
for (auto& child : _shapes)
{
PhysicsShape* shape = dynamic_cast<PhysicsShape*>(child);
// deduce the area, mass and moment
// area must update before mass, because the density changes depend on it.
if (reduceMassAndMoment)
{
_area -= shape->getArea();
addMass(-shape->getMass());
addMoment(-shape->getMoment());
}
if (_world)
{
_world->removeShape(shape);
}
// set shape->_body = nullptr make the shape->setBody will not trigger the _body->removeShape function call.
shape->_body = nullptr;
shape->setBody(nullptr);
}
_shapes.clear();
}
void PhysicsBody::removeFromWorld()
{
if (_world)
{
_world->removeBody(this);
}
}
void PhysicsBody::setEnable(bool enable)
{
if (_enabled != enable)
{
_enabled = enable;
if (_world)
{
if (enable)
{
_world->addBodyOrDelay(this);
}else
{
_world->removeBodyOrDelay(this);
}
}
}
}
bool PhysicsBody::isResting() const
{
return CP_PRIVATE(_cpBody->node).root != ((cpBody*)0);
}
void PhysicsBody::setResting(bool rest) const
{
if (rest && !isResting())
{
cpBodySleep(_cpBody);
}else if(!rest && isResting())
{
cpBodyActivate(_cpBody);
}
}
void PhysicsBody::update(float delta)
{
if (_node)
{
// damping compute
if (_isDamping && _dynamic && !isResting())
{
_cpBody->v.x *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f);
_cpBody->v.y *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f);
_cpBody->w *= cpfclamp(1.0f - delta * _angularDamping, 0.0f, 1.0f);
}
}
}
void PhysicsBody::setCategoryBitmask(int bitmask)
{
for (auto& shape : _shapes)
{
shape->setCategoryBitmask(bitmask);
}
}
int PhysicsBody::getCategoryBitmask() const
{
if (!_shapes.empty())
{
return _shapes.front()->getCategoryBitmask();
}
else
{
return UINT_MAX;
}
}
void PhysicsBody::setContactTestBitmask(int bitmask)
{
for (auto& shape : _shapes)
{
shape->setContactTestBitmask(bitmask);
}
}
int PhysicsBody::getContactTestBitmask() const
{
if (!_shapes.empty())
{
return _shapes.front()->getContactTestBitmask();
}
else
{
return 0x00000000;
}
}
void PhysicsBody::setCollisionBitmask(int bitmask)
{
for (auto& shape : _shapes)
{
shape->setCollisionBitmask(bitmask);
}
}
int PhysicsBody::getCollisionBitmask() const
{
if (!_shapes.empty())
{
return _shapes.front()->getCollisionBitmask();
}
else
{
return UINT_MAX;
}
}
void PhysicsBody::setGroup(int group)
{
for (auto& shape : _shapes)
{
shape->setGroup(group);
}
}
int PhysicsBody::getGroup() const
{
if (!_shapes.empty())
{
return _shapes.front()->getGroup();
}
else
{
return 0;
}
}
void PhysicsBody::setPositionOffset(const Vec2& position)
{
if (!_positionOffset.equals(position))
{
Vec2 pos = getPosition();
_positionOffset = position;
setPosition(pos);
}
}
void PhysicsBody::setRotationOffset(float rotation)
{
if (std::abs(_rotationOffset - rotation) > 0.5f)
{
float rot = getRotation();
_rotationOffset = rotation;
setRotation(rot);
}
}
Vec2 PhysicsBody::world2Local(const Vec2& point)
{
return PhysicsHelper::cpv2point(cpBodyWorld2Local(_cpBody, PhysicsHelper::point2cpv(point)));
}
Vec2 PhysicsBody::local2World(const Vec2& point)
{
return PhysicsHelper::cpv2point(cpBodyLocal2World(_cpBody, PhysicsHelper::point2cpv(point)));
}
NS_CC_END
#endif // CC_USE_PHYSICS
| 1 | 0.779675 | 1 | 0.779675 | game-dev | MEDIA | 0.971022 | game-dev | 0.642573 | 1 | 0.642573 |
Renardjojo/PetForDesktop | 2,826 | include/Game/Animations.hpp | #pragma once
#include "Engine/StateMachine.hpp"
#include "Engine/SpriteAnimator.hpp"
#include "Engine/SpriteSheet.hpp"
#include "Engine/Vector2.hpp"
#include "Engine/Utilities.hpp"
#include "Game/GameData.hpp"
class AnimationNode : public StateMachine::Node
{
protected:
class Pet& pet;
SpriteAnimator& spriteAnimator;
SpriteSheet& spriteSheets;
int frameRate;
bool loop;
public:
AnimationNode(Pet& inPet, SpriteAnimator& inSpriteAnimator, SpriteSheet& inSpriteSheets, int inFrameRate, bool inLoop = true)
: pet{inPet}, spriteAnimator{inSpriteAnimator}, spriteSheets{inSpriteSheets}, frameRate{inFrameRate},
loop{inLoop}
{
}
void onEnter(GameData& blackBoard) override
{
StateMachine::Node::onEnter(blackBoard);
spriteAnimator.play(blackBoard, spriteSheets, loop, frameRate);
}
void onUpdate(GameData& blackBoard, double dt) override
{
StateMachine::Node::onUpdate(blackBoard, dt);
spriteAnimator.update(blackBoard, dt);
}
void onExit(GameData& blackBoard) override
{
StateMachine::Node::onExit(blackBoard);
}
bool IsAnimationDone()
{
return spriteAnimator.isDone();
}
};
class PetJumpNode : public AnimationNode
{
Vec2 baseDir = {0.f, 0.f};
float vThrust = 0.f;
float hThrust = 0.f;
public:
PetJumpNode(Pet& inPet, SpriteAnimator& inSpriteAnimator, SpriteSheet& inSpriteSheets, int inFrameRate,
Vec2 inBaseDir,
float inVThrust, float inHThrust)
: AnimationNode(inPet, inSpriteAnimator, inSpriteSheets, inFrameRate, false), baseDir{inBaseDir},
vThrust{inVThrust},
hThrust{inHThrust}
{
}
void onUpdate(GameData& blackBoard, double dt) override;
};
class GrabNode : public AnimationNode
{
public:
GrabNode(Pet& inPet, SpriteAnimator& inSpriteAnimator, SpriteSheet& inSpriteSheets, int inFrameRate, bool inLoop)
: AnimationNode(inPet, inSpriteAnimator, inSpriteSheets, inFrameRate, inLoop)
{
}
void onEnter(GameData& blackBoard) override;
void onExit(GameData& blackBoard) override;
};
class MovementDirectionNode : public AnimationNode
{
std::vector<Vec2> directions;
Vec2 baseDir;
bool applyGravity;
public:
MovementDirectionNode(Pet& inPet, SpriteAnimator& inSpriteAnimator, SpriteSheet& inSpriteSheets, int inFrameRate,
std::vector<Vec2> inDir, bool inApplyGravity = true, bool inLoop = true)
: AnimationNode(inPet, inSpriteAnimator, inSpriteSheets, inFrameRate, inLoop), directions{inDir},
applyGravity{inApplyGravity}
{
}
void onEnter(GameData& blackBoard) override;
void onExit(GameData& blackBoard) override;
}; | 1 | 0.746941 | 1 | 0.746941 | game-dev | MEDIA | 0.91953 | game-dev | 0.655097 | 1 | 0.655097 |
kripken/intensityengine | 4,879 | src/thirdparty/bullet/src/BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btSubSimplexConvexCast.h"
#include "BulletCollision/CollisionShapes/btConvexShape.h"
#include "BulletCollision/CollisionShapes/btMinkowskiSumShape.h"
#include "BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h"
#include "btPointCollector.h"
#include "LinearMath/btTransformUtil.h"
btSubsimplexConvexCast::btSubsimplexConvexCast (const btConvexShape* convexA,const btConvexShape* convexB,btSimplexSolverInterface* simplexSolver)
:m_simplexSolver(simplexSolver),
m_convexA(convexA),m_convexB(convexB)
{
}
///Typically the conservative advancement reaches solution in a few iterations, clip it to 32 for degenerate cases.
///See discussion about this here http://continuousphysics.com/Bullet/phpBB2/viewtopic.php?t=565
#ifdef BT_USE_DOUBLE_PRECISION
#define MAX_ITERATIONS 64
#else
#define MAX_ITERATIONS 32
#endif
bool btSubsimplexConvexCast::calcTimeOfImpact(
const btTransform& fromA,
const btTransform& toA,
const btTransform& fromB,
const btTransform& toB,
CastResult& result)
{
m_simplexSolver->reset();
btVector3 linVelA,linVelB;
linVelA = toA.getOrigin()-fromA.getOrigin();
linVelB = toB.getOrigin()-fromB.getOrigin();
btScalar lambda = btScalar(0.);
btTransform interpolatedTransA = fromA;
btTransform interpolatedTransB = fromB;
///take relative motion
btVector3 r = (linVelA-linVelB);
btVector3 v;
btVector3 supVertexA = fromA(m_convexA->localGetSupportingVertex(-r*fromA.getBasis()));
btVector3 supVertexB = fromB(m_convexB->localGetSupportingVertex(r*fromB.getBasis()));
v = supVertexA-supVertexB;
int maxIter = MAX_ITERATIONS;
btVector3 n;
n.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
bool hasResult = false;
btVector3 c;
btScalar lastLambda = lambda;
btScalar dist2 = v.length2();
#ifdef BT_USE_DOUBLE_PRECISION
btScalar epsilon = btScalar(0.0001);
#else
btScalar epsilon = btScalar(0.0001);
#endif //BT_USE_DOUBLE_PRECISION
btVector3 w,p;
btScalar VdotR;
while ( (dist2 > epsilon) && maxIter--)
{
supVertexA = interpolatedTransA(m_convexA->localGetSupportingVertex(-v*interpolatedTransA.getBasis()));
supVertexB = interpolatedTransB(m_convexB->localGetSupportingVertex(v*interpolatedTransB.getBasis()));
w = supVertexA-supVertexB;
btScalar VdotW = v.dot(w);
if (lambda > btScalar(1.0))
{
return false;
}
if ( VdotW > btScalar(0.))
{
VdotR = v.dot(r);
if (VdotR >= -(SIMD_EPSILON*SIMD_EPSILON))
return false;
else
{
lambda = lambda - VdotW / VdotR;
//interpolate to next lambda
// x = s + lambda * r;
interpolatedTransA.getOrigin().setInterpolate3(fromA.getOrigin(),toA.getOrigin(),lambda);
interpolatedTransB.getOrigin().setInterpolate3(fromB.getOrigin(),toB.getOrigin(),lambda);
//m_simplexSolver->reset();
//check next line
w = supVertexA-supVertexB;
lastLambda = lambda;
n = v;
hasResult = true;
}
}
m_simplexSolver->addVertex( w, supVertexA , supVertexB);
if (m_simplexSolver->closest(v))
{
dist2 = v.length2();
hasResult = true;
//todo: check this normal for validity
//n=v;
//printf("V=%f , %f, %f\n",v[0],v[1],v[2]);
//printf("DIST2=%f\n",dist2);
//printf("numverts = %i\n",m_simplexSolver->numVertices());
} else
{
dist2 = btScalar(0.);
}
}
//int numiter = MAX_ITERATIONS - maxIter;
// printf("number of iterations: %d", numiter);
//don't report a time of impact when moving 'away' from the hitnormal
result.m_fraction = lambda;
if (n.length2() >= (SIMD_EPSILON*SIMD_EPSILON))
result.m_normal = n.normalized();
else
result.m_normal = btVector3(btScalar(0.0), btScalar(0.0), btScalar(0.0));
//don't report time of impact for motion away from the contact normal (or causes minor penetration)
if (result.m_normal.dot(r)>=-result.m_allowedPenetration)
return false;
btVector3 hitA,hitB;
m_simplexSolver->compute_points(hitA,hitB);
result.m_hitPoint=hitB;
return true;
}
| 1 | 0.949643 | 1 | 0.949643 | game-dev | MEDIA | 0.969309 | game-dev | 0.992023 | 1 | 0.992023 |
TeamLumi/opendpr | 12,725 | Assets/Wwise/Deployment/Components/AkGameObj.cs | #if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_WIIU || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms.
//////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014 Audiokinetic Inc. / All Rights Reserved
//
//////////////////////////////////////////////////////////////////////
[UnityEngine.AddComponentMenu("Wwise/AkGameObj")]
[UnityEngine.DisallowMultipleComponent]
[UnityEngine.ExecuteInEditMode] //ExecuteInEditMode necessary to maintain proper state of isStaticObject.
[UnityEngine.DefaultExecutionOrder(-25)]
///@brief This component represents a sound object in your scene tracking its position and other game syncs such as Switches, RTPC and environment values. You can add this to any object that will emit sound, and it will be added to any object that an AkAudioListener is attached to. Note that if it is not present, Wwise will add it automatically, with the default values, to any Unity Game Object that is passed to Wwise.
/// \sa
/// - <a href="https://www.audiokinetic.com/library/edge/?source=SDK&id=soundengine__gameobj.html" target="_blank">Integration Details - Game Objects</a> (Note: This is described in the Wwise SDK documentation.)
/// - <a href="https://www.audiokinetic.com/library/edge/?source=SDK&id=soundengine__events.html" target="_blank">Integration Details - Events</a> (Note: This is described in the Wwise SDK documentation.)
/// - <a href="https://www.audiokinetic.com/library/edge/?source=SDK&id=soundengine__listeners.html" target="_blank">Integrating Listeners</a> (Note: This is described in the Wwise SDK documentation.)
/// - <a href="https://www.audiokinetic.com/library/edge/?source=SDK&id=soundengine__switch.html" target="_blank">Integration Details - Switches</a> (Note: This is described in the Wwise SDK documentation.)
/// - <a href="https://www.audiokinetic.com/library/edge/?source=SDK&id=soundengine__states.html" target="_blank">Integration Details - States</a> (Note: This is described in the Wwise SDK documentation.)
/// - <a href="https://www.audiokinetic.com/library/edge/?source=SDK&id=soundengine__environments.html" target="_blank">Integration Details - Environments and Game-defined Auxiliary Sends</a> (Note: This is described in the Wwise SDK documentation.)
public class AkGameObj : UnityEngine.MonoBehaviour
{
[UnityEngine.SerializeField] private AkGameObjListenerList m_listeners = new AkGameObjListenerList();
/// Is this object affected by Environment changes? Set to false if not affected in order to save some useless calls. Default is true.
public bool isEnvironmentAware = true;
/// Maintains and persists the Static setting of the gameobject, which is available only in the editor.
[UnityEngine.SerializeField] private bool isStaticObject = false;
/// Cache the bounds to avoid calls to GetComponent()
private UnityEngine.Collider m_Collider;
private AkGameObjEnvironmentData m_envData;
private AkGameObjPositionData m_posData;
/// When not set to null, the position will be offset relative to the Game Object position by the Position Offset
public AkGameObjPositionOffsetData m_positionOffsetData;
public bool IsUsingDefaultListeners
{
get { return m_listeners.useDefaultListeners; }
}
public System.Collections.Generic.List<AkAudioListener> ListenerList
{
get { return m_listeners.ListenerList; }
}
private bool isRegistered = false;
internal void AddListener(AkAudioListener listener)
{
m_listeners.Add(listener);
}
internal void RemoveListener(AkAudioListener listener)
{
m_listeners.Remove(listener);
}
public AKRESULT Register()
{
if (isRegistered)
return AKRESULT.AK_Success;
isRegistered = true;
return AkSoundEngine.RegisterGameObj(gameObject, gameObject.name);
}
public void SetPosition()
{
var position = GetPosition();
var forward = GetForward();
var up = GetUpward();
if (m_posData != null)
{
if (m_posData.position == position && m_posData.forward == forward && m_posData.up == up)
return;
m_posData.position = position;
m_posData.forward = forward;
m_posData.up = up;
}
AkSoundEngine.SetObjectPosition(gameObject, position, forward, up);
}
private void Awake()
{
#if UNITY_EDITOR
if (!AkSoundEngineController.Instance.IsSoundEngineLoaded || AkUtilities.IsMigrating)
return;
if (!UnityEditor.EditorApplication.isPlaying)
UnityEditor.EditorApplication.update += CheckStaticStatus;
#endif
// If the object was marked as static, don't update its position to save cycles.
if (!isStaticObject)
m_posData = new AkGameObjPositionData();
// Cache the bounds to avoid calls to GetComponent()
m_Collider = GetComponent<UnityEngine.Collider>();
//Register a Game Object in the sound engine, with its name.
if (Register() == AKRESULT.AK_Success)
{
SetPosition();
if (isEnvironmentAware)
{
m_envData = new AkGameObjEnvironmentData();
if (m_Collider)
m_envData.AddAkEnvironment(m_Collider, m_Collider);
m_envData.UpdateAuxSend(gameObject, transform.position);
}
m_listeners.Init(this);
}
}
private void CheckStaticStatus()
{
#if UNITY_EDITOR
if (AkUtilities.IsMigrating)
return;
try
{
if (gameObject != null && isStaticObject != gameObject.isStatic)
{
isStaticObject = gameObject.isStatic;
UnityEditor.EditorUtility.SetDirty(this);
}
}
catch
{
UnityEditor.EditorApplication.update -= CheckStaticStatus;
}
#endif
}
private void OnEnable()
{
#if UNITY_EDITOR
if (AkUtilities.IsMigrating)
return;
#endif
//if enabled is set to false, then the update function wont be called
enabled = !isStaticObject;
}
#if UNITY_EDITOR
private void OnDisable()
{
if (!UnityEditor.EditorApplication.isPlaying &&AkSoundEngine.IsInitialized())
AkSoundEngine.UnregisterGameObj(gameObject);
}
#endif
private void OnDestroy()
{
#if UNITY_EDITOR
if (!AkSoundEngineController.Instance.IsSoundEngineLoaded || AkUtilities.IsMigrating)
return;
if (!UnityEditor.EditorApplication.isPlaying)
UnityEditor.EditorApplication.update -= CheckStaticStatus;
#endif
// We can't do the code in OnDestroy if the gameObj is unregistered, so do it now.
var eventHandlers = gameObject.GetComponents<AkTriggerHandler>();
foreach (var handler in eventHandlers)
{
if (handler.triggerList.Contains(AkTriggerHandler.DESTROY_TRIGGER_ID))
handler.DoDestroy();
}
#if UNITY_EDITOR
if (!UnityEditor.EditorApplication.isPlaying)
return;
#endif
if (AkSoundEngine.IsInitialized())
AkSoundEngine.UnregisterGameObj(gameObject);
}
private void Update()
{
#if UNITY_EDITOR
if (!AkSoundEngineController.Instance.IsSoundEngineLoaded || AkUtilities.IsMigrating ||
!UnityEditor.EditorApplication.isPlaying)
return;
#endif
if (m_envData != null)
m_envData.UpdateAuxSend(gameObject, transform.position);
if (!isStaticObject)
SetPosition();
}
/// Gets the position including the position offset, if applyPositionOffset is enabled. User can also override this method to calculate an arbitrary position.
/// \return The position.
public virtual UnityEngine.Vector3 GetPosition()
{
if (m_positionOffsetData == null)
return transform.position;
var worldOffset = transform.rotation * m_positionOffsetData.positionOffset;
return transform.position + worldOffset;
}
/// Gets the orientation forward vector. User can also override this method to calculate an arbitrary vector.
/// \return The forward vector of orientation.
public virtual UnityEngine.Vector3 GetForward()
{
return transform.forward;
}
/// Gets the orientation upward vector. User can also override this method to calculate an arbitrary vector.
/// \return The upward vector of orientation.
public virtual UnityEngine.Vector3 GetUpward()
{
return transform.up;
}
private void OnTriggerEnter(UnityEngine.Collider other)
{
#if UNITY_EDITOR
if (AkUtilities.IsMigrating || !UnityEditor.EditorApplication.isPlaying)
return;
#endif
if (isEnvironmentAware && m_envData != null)
m_envData.AddAkEnvironment(other, m_Collider);
}
private void OnTriggerExit(UnityEngine.Collider other)
{
#if UNITY_EDITOR
if (AkUtilities.IsMigrating || !UnityEditor.EditorApplication.isPlaying)
return;
#endif
if (isEnvironmentAware && m_envData != null)
m_envData.RemoveAkEnvironment(other, m_Collider);
}
#if UNITY_EDITOR
public void OnDrawGizmosSelected()
{
if (AkUtilities.IsMigrating)
return;
var position = GetPosition();
UnityEngine.Gizmos.DrawIcon(position, "WwiseAudioSpeaker.png", false);
}
#endif
#region WwiseMigration
#pragma warning disable 0414 // private field assigned but not used.
[UnityEngine.HideInInspector]
[UnityEngine.SerializeField]
private AkGameObjPosOffsetData m_posOffsetData;
// Wwise v2016.2 and below supported up to 8 listeners[0-7].
private const int AK_NUM_LISTENERS = 8;
[UnityEngine.HideInInspector]
[UnityEngine.SerializeField]
/// Listener 0 by default.
private int listenerMask = 1;
#pragma warning restore 0414 // private field assigned but not used.
#if UNITY_EDITOR
public void Migrate9()
{
UnityEngine.Debug.Log("WwiseUnity: AkGameObj.Migrate9 for " + gameObject.name);
const int ALL_LISTENER_MASK = (1 << AK_NUM_LISTENERS) - 1;
if ((listenerMask & ALL_LISTENER_MASK) == ALL_LISTENER_MASK)
listenerMask = 1;
}
public void Migrate10()
{
UnityEngine.Debug.Log("WwiseUnity: AkGameObj.Migrate10 for " + gameObject.name);
if (m_posOffsetData != null)
{
m_positionOffsetData = new AkGameObjPositionOffsetData(true);
m_positionOffsetData.positionOffset = m_posOffsetData.positionOffset;
m_posOffsetData = null;
}
}
private class Migration14Data
{
private readonly System.Collections.Generic.List<AkAudioListener>[] listeners =
new System.Collections.Generic.List<AkAudioListener>[AK_NUM_LISTENERS];
public Migration14Data()
{
var fullSceneListenerMask = 0;
// Get all AkAudioListeners in the scene.
var listenerObjects = FindObjectsOfType<AkAudioListener>();
foreach (var listener in listenerObjects)
{
// Add AkGameObj to AkAudioListeners
if (listener.GetComponent<AkGameObj>() == null)
{
var akGameObj = listener.gameObject.AddComponent<AkGameObj>();
if (akGameObj)
{
akGameObj.isEnvironmentAware = false;
UnityEngine.Debug.Log("WwiseUnity: Added AkGameObj to <" + listener.gameObject.name + ">.");
}
else
UnityEngine.Debug.LogError("WwiseUnity: Failed to add AkGameObj to <" + listener.gameObject.name + ">.");
}
var listenerId = listener.listenerId;
if (listenerId >= 0 && listenerId < AK_NUM_LISTENERS)
{
if (listeners[listenerId] == null)
listeners[listenerId] = new System.Collections.Generic.List<AkAudioListener>();
listeners[listenerId].Add(listener);
fullSceneListenerMask |= 1 << listenerId;
}
else
UnityEngine.Debug.LogError("WwiseUnity: Invalid listenerId <" + listenerId + "> found during migration.");
}
if (fullSceneListenerMask == 0)
{
UnityEngine.Debug.LogWarning("WwiseUnity: Listeners were not added via components within this Scene.");
listeners = null;
}
else
{
for (var ii = 0; ii < AK_NUM_LISTENERS; ++ii)
{
if (listeners[ii] != null && listeners[ii].Count > 1)
{
UnityEngine.Debug.LogWarning("WwiseUnity: Multiple listeners <" + listeners[ii].Count +
"> with same listenerId <" + ii + "> found during migration.");
}
}
if (fullSceneListenerMask == 1)
{
UnityEngine.Debug.Log("WwiseUnity: Default listeners will be used for this Scene.");
listeners = null;
}
}
}
public void Migrate(AkGameObj akGameObj)
{
if (listeners != null)
{
for (var ii = 0; ii < AK_NUM_LISTENERS; ++ii)
{
var idMask = 1 << ii;
if ((akGameObj.listenerMask & idMask) != 0 && listeners[ii] != null)
{
foreach (var listener in listeners[ii])
akGameObj.m_listeners.AddToInitialListenerList(listener);
}
}
}
}
}
private static Migration14Data migration14data;
public static void PreMigration14()
{
migration14data = new Migration14Data();
}
public void Migrate14()
{
UnityEngine.Debug.Log("WwiseUnity: AkGameObj.Migrate14 for " + gameObject.name);
if (migration14data != null)
migration14data.Migrate(this);
}
public static void PostMigration14()
{
migration14data = null;
}
#endif
#endregion
}
#endif // #if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_WIIU || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms. | 1 | 0.936366 | 1 | 0.936366 | game-dev | MEDIA | 0.956648 | game-dev | 0.964033 | 1 | 0.964033 |
LinuxCNC/linuxcnc | 9,720 | src/emc/kinematics/kinematics.h | /********************************************************************
* Description: kinematics.h
*
* Derived from a work by Fred Proctor & Will Shackleford
*
* Author:
* License: GPL Version 2
* System: Linux
*
* Copyright (c) 2004 All rights reserved.
*
* Last change:
********************************************************************/
#ifndef KINEMATICS_H
#define KINEMATICS_H
#include "emcpos.h" /* EmcPose */
#include "rtapi_bool.h"
/*
The type of kinematics used.
KINEMATICS_IDENTITY means that the joints and world coordinates are the
same, as for slideway machines (XYZ milling machines). The EMC will allow
changing from joint to world mode and vice versa. Also, the EMC will set
the actual world position to be the actual joint positions (not commanded)
by calling the forward kinematics each trajectory cycle.
KINEMATICS_FORWARD_ONLY means that only the forward kinematics exist.
Since the EMC requires at least the inverse kinematics, this should simply
terminate the EMC.
KINEMATICS_INVERSE_ONLY means that only the inverse kinematics exist.
The forwards won't be called, and the EMC will only allow changing from
joint to world mode at the home position.
KINEMATICS_BOTH means that both the forward and inverse kins are defined.
Like KINEMATICS_IDENTITY, the EMC will allow changing between world and
joint modes. However, the kins are assumed to be somewhat expensive
computationally, and the forwards won't be called at the trajectory rate
to compute actual world coordinates from actual joint values.
*/
typedef enum {
KINEMATICS_IDENTITY = 1,/* forward=inverse, both well-behaved */
KINEMATICS_FORWARD_ONLY,/* forward but no inverse */
KINEMATICS_INVERSE_ONLY,/* inverse but no forward */
KINEMATICS_BOTH /* forward and inverse both */
} KINEMATICS_TYPE;
/* the forward flags are passed to the forward kinematics so that they
can resolve ambiguities in the world coordinates for a given joint set,
e.g., for hexpods, this would be platform-below-base, platform-above-base.
The flags are also passed to the inverse kinematics and are set by them,
which is how they are changed from their initial value. For example, for
hexapods you could do a coordinated move that brings the platform up from
below the base to above the base. The forward flags would be set to
indicate this. */
typedef unsigned long int KINEMATICS_FORWARD_FLAGS;
/* the inverse flags are passed to the inverse kinematics so that they
can resolve ambiguities in the joint angles for a given world coordinate,
e.g., for robots, this would be elbow-up, elbow-down, etc.
The flags are also passed to the forward kinematics and are set by them,
which is how they are changed from their initial value. For example, for
robots you could do a joint move that brings the elbow from a down
configuration to an up configuration. The inverse flags would be set to
indicate this. */
typedef unsigned long int KINEMATICS_INVERSE_FLAGS;
/* the forward kinematics take joint values and determine world coordinates,
given forward kinematics flags to resolve any ambiguities. The inverse
flags are set to indicate their value appropriate to the joint values
passed in. */
extern int kinematicsForward(const double *joint,
struct EmcPose * world,
const KINEMATICS_FORWARD_FLAGS * fflags,
KINEMATICS_INVERSE_FLAGS * iflags);
/* the inverse kinematics take world coordinates and determine joint values,
given the inverse kinematics flags to resolve any ambiguities. The forward
flags are set to indicate their value appropriate to the world coordinates
passed in. */
extern int kinematicsInverse(const struct EmcPose * world,
double *joint,
const KINEMATICS_INVERSE_FLAGS * iflags,
KINEMATICS_FORWARD_FLAGS * fflags);
/* the home kinematics function sets all its arguments to their proper
values at the known home position. When called, these should be set,
when known, to initial values, e.g., from an INI file. If the home
kinematics can accept arbitrary starting points, these initial values
should be used.
*/
extern int kinematicsHome(struct EmcPose * world,
double *joint,
KINEMATICS_FORWARD_FLAGS * fflags,
KINEMATICS_INVERSE_FLAGS * iflags);
extern KINEMATICS_TYPE kinematicsType(void);
/* parameters for use with switchkins.c */
typedef struct kinematics_parms {
char* sparm; // module string parameter passed to kins
char* kinsname; // must agree with module(file) name
char* halprefix; // for hal pin hames
char* required_coordinates;
int max_joints;
int allow_duplicates;
int fwd_iterates_mask; // identify kins types that use iterative
// forward kinematics (typ: genhex)
// bitmask: 0x0 none
// bitmask: 0x1 bit0: switchkins_type==0
// bitmask: 0x2 bit1: switchkins_type==1
// bitmask: 0x4 bit2: switchkins_type==2
int gui_kinstype; // may be reqd for parallel kins with vismach
// to select switchkins_type for gui pins
} kparms;
/* map letters in a coordinates string to joint numbers
** sequentially. Axis indices are 0:x,1:y,...,etc
** Example: coordinates=XYZYAC
** Result: axis_idx_for_jno[0] = 0 ==> X
** axis_idx_for_jno[1] = 1 ==> Y
** axis_idx_for_jno[2] = 2 ==> Z
** axis_idx_for_jno[3] = 1 ==> Y (duplicate allowed)
** axis_idx_for_jno[4] = 1 ==> A
** axis_idx_for_jno[5] = 1 ==> C
*/
extern int map_coordinates_to_jnumbers(const char *coordinates,
const int max_joints,
const int allow_duplicates,
int axis_idx_for_jno[]);
extern int mapped_joints_to_position(const int max_joints,
const double* joints,
EmcPose* pose);
extern int position_to_mapped_joints(const int max_joints,
const EmcPose* pos,
double* joints);
extern int identityKinematicsSetup(const int comp_id,
const char* coordinates,
kparms* ksetup_parms);
extern int identityKinematicsForward(const double *joint,
struct EmcPose * world,
const KINEMATICS_FORWARD_FLAGS * fflags,
KINEMATICS_INVERSE_FLAGS * iflags);
extern int identityKinematicsInverse(const struct EmcPose * world,
double *joint,
const KINEMATICS_INVERSE_FLAGS * iflags,
KINEMATICS_FORWARD_FLAGS * fflags);
extern int kinematicsSwitchable(void);
extern int kinematicsSwitch(int switchkins_type);
//NOTE: switchable kinematics may require Interp::Synch
// before/after invoking kinematicsSwitch()
// A convenient command to synch is: M66 E0 L0
#define KINS_NOT_SWITCHABLE \
extern int kinematicsSwitchable() {return 0;} \
extern int kinematicsSwitch(int switchkins_type) { (void)switchkins_type; return 0;} \
EXPORT_SYMBOL(kinematicsSwitchable); \
EXPORT_SYMBOL(kinematicsSwitch);
// support for template for user-defined switchkins_type==2
extern int userkKinematicsSetup(const int comp_id,
const char* coordinates,
kparms* ksetup_parms);
extern int userkKinematicsForward(const double *joint,
struct EmcPose * world,
const KINEMATICS_FORWARD_FLAGS * fflags,
KINEMATICS_INVERSE_FLAGS * iflags);
extern int userkKinematicsInverse(const struct EmcPose * world,
double *joint,
const KINEMATICS_INVERSE_FLAGS * iflags,
KINEMATICS_FORWARD_FLAGS * fflags);
#endif
//*********************************************************************
// xyzac,xyzbc;
extern int trtKinematicsSetup(const int comp_id,
const char* coordinates,
kparms* ksetup_parms);
extern int xyzacKinematicsForward(const double *joints,
EmcPose * pos,
const KINEMATICS_FORWARD_FLAGS * fflags,
KINEMATICS_INVERSE_FLAGS * iflags);
extern int xyzacKinematicsInverse(const EmcPose * pos,
double *joints,
const KINEMATICS_INVERSE_FLAGS * iflags,
KINEMATICS_FORWARD_FLAGS * fflags);
extern int xyzbcKinematicsForward(const double *joints,
EmcPose * pos,
const KINEMATICS_FORWARD_FLAGS * fflags,
KINEMATICS_INVERSE_FLAGS * iflags);
extern int xyzbcKinematicsInverse(const EmcPose * pos,
double *joints,
const KINEMATICS_INVERSE_FLAGS * iflags,
KINEMATICS_FORWARD_FLAGS * fflags);
//*********************************************************************
| 1 | 0.822143 | 1 | 0.822143 | game-dev | MEDIA | 0.322596 | game-dev | 0.67718 | 1 | 0.67718 |
googlecreativelab/sounds-in-space | 5,384 | Assets/Scripts/UI/SoundRadiusSlider.cs | //-----------------------------------------------------------------------
// <copyright file="SoundRadiusSlider.cs" company="Google">
//
// Copyright 2019 Google Inc. All Rights Reserved.
//
// 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.
//
// </copyright>
//-----------------------------------------------------------------------
using UnityEngine;
namespace SIS {
public interface ISoundRadiusSliderDelegate {
void SoundRadiusSliderValueChanged(SoundRadiusSlider slider, float sliderPercentage, float adjustedRadius);
}
public class SoundRadiusSlider : MonoBehaviour {
public ISoundRadiusSliderDelegate sliderDelegate = null;
public bool isInnerOtherwiseOuterRadius = false;
// public float minDiameter { get; private set; } // Will get set on Awake
// public float maxDiameter { get; private set; } // Will get set on Awake
public float minDiameter { get { return isInnerOtherwiseOuterRadius
? SingletonData.Instance.InnerRadiusMinDiameter
: SingletonData.Instance.OuterRadiusMinDiameter; } } // Will get set on Awake
public float maxDiameter { get { return isInnerOtherwiseOuterRadius
? SingletonData.Instance.InnerRadiusMaxDiameter
: SingletonData.Instance.OuterRadiusMaxDiameter; } } // Will get set on Awake
public float minRadius { get { return minDiameter * 0.5f; } }
public float maxRadius { get { return maxDiameter * 0.5f; } }
protected float minDiameterDelta { get { return 1f - minDiameter; } }
[SerializeField] bool maxGoesToInfinity = false;
protected UnityEngine.UI.Slider radiusSlider;
public float sliderValue { get { return radiusSlider.value; } }
public float diameterValue { get { return DiameterValueFromPercentage(radiusSlider.value); } }
public float radiusValue { get { return DiameterValueFromPercentage(radiusSlider.value) * 0.5f; } }
[SerializeField] UnityEngine.UI.Text radiusText;
[SerializeField] UnityEngine.UI.Text minRadiusText;
[SerializeField] UnityEngine.UI.Text maxRadiusText;
[SerializeField] UnityEngine.UI.Image sliderKnobImage = null;
[SerializeField] UnityEngine.UI.Image sliderFillImage = null;
[SerializeField] UnityEngine.UI.Image sliderBorderImage = null;
bool notifySliderDelegate = true;
private void Awake() {
}
// Start is called before the first frame update
void Start() {
radiusSlider = GetComponentInChildren<UnityEngine.UI.Slider>();
}
public void SetSliderDiameter(float diameter, bool notifyDelegate = true) {
if (radiusSlider == null) { radiusSlider = GetComponentInChildren<UnityEngine.UI.Slider>(); }
notifySliderDelegate = notifyDelegate;
float sliderPercent = PercentageFromDiameterVal(diameter);
radiusSlider.value = sliderPercent;
notifySliderDelegate = true;
}
public void SetSliderRadius(float radius, bool notifyDelegate = true) {
SetSliderDiameter(radius * 2f, notifyDelegate);
}
public void SetColorTint(Color newCol) {
// sliderKnobImage.color = newCol;
sliderFillImage.color = newCol;
sliderBorderImage.color = newCol;
}
protected float PercentageFromDiameterVal(float diam) {
if (maxGoesToInfinity && diam < 0) { return 1.0f; }
float clampedDiameter = Mathf.Max(minDiameter, Mathf.Min(maxDiameter, diam));
return Mathf.Log(clampedDiameter + minDiameterDelta) / Mathf.Log(maxDiameter + minDiameterDelta);
}
protected float DiameterValueFromPercentage(float percent) {
if (maxGoesToInfinity && percent >= 1.0f) { return -1f; }
return Mathf.Pow(maxDiameter + minDiameterDelta, percent) - minDiameterDelta;
}
// -----------------------------------------
#region Slider Callback
// -----------------------------------------
public void SoundDiameterSliderValueChanged(float percentage) {
float adjustedDiameter = DiameterValueFromPercentage(percentage);
if (radiusText != null) {
if (maxGoesToInfinity && adjustedDiameter < 0) {
radiusText.text = "∞m";
} else {
radiusText.text = string.Format("{0:0.0}m", Mathf.Floor(adjustedDiameter * 10f) / 10f);
}
}
// this.soundRadiusChanged(radiusVal, adjustedRadius);
if (sliderDelegate == null || !notifySliderDelegate) {
return;
}
sliderDelegate.SoundRadiusSliderValueChanged(this, percentage, adjustedDiameter * 0.5f);
}
#endregion
}
}
| 1 | 0.930423 | 1 | 0.930423 | game-dev | MEDIA | 0.324187 | game-dev | 0.982448 | 1 | 0.982448 |
maruohon/malilib | 1,775 | src/main/java/malilib/config/category/BaseConfigOptionCategory.java | package malilib.config.category;
import java.util.List;
import malilib.config.option.ConfigOption;
import malilib.util.data.ModInfo;
public class BaseConfigOptionCategory implements ConfigOptionCategory
{
protected final ModInfo modInfo;
protected final String name;
protected final boolean saveToFile;
protected final List<? extends ConfigOption<?>> configs;
public BaseConfigOptionCategory(ModInfo modInfo,
String name,
boolean saveToFile,
List<? extends ConfigOption<?>> configs)
{
this.modInfo = modInfo;
this.name = name;
this.saveToFile = saveToFile;
this.configs = configs;
}
@Override
public ModInfo getModInfo()
{
return this.modInfo;
}
@Override
public String getName()
{
return this.name;
}
@Override
public boolean shouldSaveToFile()
{
return this.saveToFile;
}
@Override
public List<? extends ConfigOption<?>> getConfigOptions()
{
return this.configs;
}
/**
* Creates a normal config category that is shown on the config screen
* and saved to a config file normally.
*/
public static BaseConfigOptionCategory normal(ModInfo modInfo, String name, List<? extends ConfigOption<?>> configs)
{
return new BaseConfigOptionCategory(modInfo, name, true, configs);
}
/**
* Creates a config category that is not saved to a file.
*/
public static BaseConfigOptionCategory nonSaved(ModInfo modInfo, String name, List<? extends ConfigOption<?>> configs)
{
return new BaseConfigOptionCategory(modInfo, name, false, configs);
}
}
| 1 | 0.917021 | 1 | 0.917021 | game-dev | MEDIA | 0.552485 | game-dev | 0.757744 | 1 | 0.757744 |
OrgEleCho/EleCho.WpfSuite | 1,761 | EleCho.WpfSuite.Media/Media/Transition/FadeTransition.cs | using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace EleCho.WpfSuite.Media.Transition
{
/// <summary>
/// Fade transition
/// </summary>
public class FadeTransition : StoryboardContentTransition
{
/// <inheritdoc/>
protected override Freezable CreateInstanceCore() => new FadeTransition();
/// <inheritdoc/>
protected override Storyboard CreateNewContentStoryboard(UIElement container, UIElement newContent, bool forward)
{
DoubleAnimation opacityAnimation = new()
{
EasingFunction = EasingFunction,
Duration = Duration,
From = 0,
To = 1,
};
Storyboard.SetTargetProperty(opacityAnimation, new PropertyPath(nameof(FrameworkElement.Opacity)));
return new Storyboard()
{
Duration = Duration,
Children =
{
opacityAnimation
}
};
}
/// <inheritdoc/>
protected override Storyboard CreateOldContentStoryboard(UIElement container, UIElement oldContent, bool forward)
{
DoubleAnimation opacityAnimation = new()
{
EasingFunction = EasingFunction,
Duration = Duration,
To = 0,
};
Storyboard.SetTargetProperty(opacityAnimation, new PropertyPath(nameof(FrameworkElement.Opacity)));
return new Storyboard()
{
Duration = Duration,
Children =
{
opacityAnimation
}
};
}
}
}
| 1 | 0.606789 | 1 | 0.606789 | game-dev | MEDIA | 0.402481 | game-dev | 0.689874 | 1 | 0.689874 |
bigbluebutton/bigbluebutton | 2,149 | akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/breakout/BreakoutRoomUsersUpdateMsgHdlr.scala | package org.bigbluebutton.core.apps.breakout
import org.bigbluebutton.core.api.BreakoutRoomUsersUpdateInternalMsg
import org.bigbluebutton.core.db.{ BreakoutRoomUserDAO, UserBreakoutRoomDAO }
import org.bigbluebutton.core.domain.MeetingState2x
import org.bigbluebutton.core.models.{ RegisteredUsers, Users2x }
import org.bigbluebutton.core.running.{ MeetingActor, OutMsgRouter }
trait BreakoutRoomUsersUpdateMsgHdlr {
this: MeetingActor =>
val outGW: OutMsgRouter
def handleBreakoutRoomUsersUpdateInternalMsg(msg: BreakoutRoomUsersUpdateInternalMsg, state: MeetingState2x): MeetingState2x = {
val breakoutModel = for {
model <- state.breakout
room <- model.find(msg.breakoutId)
} yield {
val updatedRoom = room.copy(users = msg.users, voiceUsers = msg.voiceUsers)
//Update user lastActivityTime in parent room (to avoid be ejected while is in Breakout room)
for {
breakoutRoomUser <- updatedRoom.users
user <- Users2x.findWithBreakoutRoomId(liveMeeting.users2x, breakoutRoomUser.id)
} yield Users2x.updateLastUserActivity(liveMeeting.users2x, user)
//Update lastBreakout in registeredUsers to avoid lose this info when the user leaves
for {
breakoutRoomUser <- updatedRoom.users
u <- RegisteredUsers.findWithBreakoutRoomId(breakoutRoomUser.id, liveMeeting.registeredUsers)
} yield {
if (room != null && (u.lastBreakoutRoom == null || u.lastBreakoutRoom.id != room.id)) {
RegisteredUsers.updateUserLastBreakoutRoom(liveMeeting.registeredUsers, u, room)
}
}
val usersInRoom = for {
breakoutRoomUser <- updatedRoom.users
u <- RegisteredUsers.findWithBreakoutRoomId(breakoutRoomUser.id, liveMeeting.registeredUsers)
} yield u.id
UserBreakoutRoomDAO.updateLastBreakoutRoom(props.meetingProp.intId, usersInRoom, updatedRoom)
BreakoutRoomUserDAO.updateUserJoined(props.meetingProp.intId, usersInRoom, updatedRoom)
model.update(updatedRoom)
}
breakoutModel match {
case Some(model) => state.update(Some(model))
case None => state
}
}
}
| 1 | 0.542174 | 1 | 0.542174 | game-dev | MEDIA | 0.774738 | game-dev | 0.912247 | 1 | 0.912247 |
rovertronic/Mario-Builder-64 | 2,325 | src/game/behaviors/grand_star.inc.c | // grand_star.inc.c
s32 arc_to_goal_pos(Vec3f a0, Vec3f a1, f32 yVel, f32 gravity) {
f32 dx = a0[0] - a1[0];
f32 dz = a0[2] - a1[2];
f32 planarDist = sqrtf(sqr(dx) + sqr(dz));
o->oMoveAngleYaw = atan2s(dz, dx);
o->oVelY = yVel;
o->oGravity = gravity;
s32 time = -2.0f / o->oGravity * yVel - 1.0f;
o->oForwardVel = planarDist / time;
return time;
}
void grand_star_zero_velocity(void) {
o->oGravity = 0.0f;
o->oVelY = 0.0f;
o->oForwardVel = 0.0f;
}
void bhv_grand_star_loop(void) {
if (o->oAction == 0) {
if (o->oTimer == 0) {
obj_set_angle(o, 0, 0, 0);
o->oAngleVelYaw = 0x400;
cur_obj_play_sound_2(SOUND_GENERAL2_STAR_APPEARS);
}
if (o->oTimer > 70) {
o->oAction++;
}
spawn_sparkle_particles(3, 200, 80, -60);
} else if (o->oAction == 1) {
if (o->oTimer == 0) {
cur_obj_play_sound_2(SOUND_GENERAL_GRAND_STAR);
cutscene_object(CUTSCENE_STAR_SPAWN, o);
o->oGrandStarArcTime = arc_to_goal_pos(gVec3fZero, &o->oPosVec, 80.0f, -2.0f);
}
cur_obj_move_using_fvel_and_gravity();
if (o->oSubAction == 0) {
if (o->oPosY < o->oHomeY) {
o->oPosY = o->oHomeY;
o->oVelY = 60.0f;
o->oForwardVel = 0.0f;
o->oSubAction++;
cur_obj_play_sound_2(SOUND_GENERAL_GRAND_STAR_JUMP);
}
} else if (o->oVelY < 0.0f && o->oPosY < o->oHomeY + 200.0f) {
o->oPosY = o->oHomeY + 200.0f;
grand_star_zero_velocity();
gObjCutsceneDone = TRUE;
set_mario_npc_dialog(MARIO_DIALOG_STOP);
o->oAction++;
o->oInteractStatus = INT_STATUS_NONE;
cur_obj_play_sound_2(SOUND_GENERAL_GRAND_STAR_JUMP);
}
spawn_sparkle_particles(3, 200, 80, -60);
} else {
cur_obj_become_tangible();
if (o->oInteractStatus & INT_STATUS_INTERACTED) {
obj_mark_for_deletion(o);
o->oInteractStatus = INT_STATUS_NONE;
}
}
if (o->oAngleVelYaw > 0x400) {
o->oAngleVelYaw -= 0x100;
}
o->oFaceAngleYaw += o->oAngleVelYaw;
cur_obj_scale(2.0f);
o->oGraphYOffset = 110.0f;
}
| 1 | 0.646696 | 1 | 0.646696 | game-dev | MEDIA | 0.779747 | game-dev | 0.673207 | 1 | 0.673207 |
dalerank/caesaria-game | 17,233 | source/gui/contextmenu.cpp | // This file is part of CaesarIA.
//
// CaesarIA 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.
//
// CaesarIA 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 CaesarIA. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright 2012-2015 Dalerank, dalerankn8@gmail.com
#include "contextmenu.hpp"
#include "contextmenuprivate.hpp"
#include "contextmenuitem.hpp"
#include "core/event.hpp"
#include "core/utils.hpp"
#include "core/time.hpp"
#include "core/position.hpp"
#include "environment.hpp"
namespace gui
{
//! constructor
ContextMenu::ContextMenu( Widget* parent, const Rect& rectangle,
int id, bool getFocus, bool allowFocus)
: Widget( parent, id, rectangle), _d( new Impl )
{
#ifdef _DEBUG
setDebugName( "ContextMenu");
#endif
_d->eventParent = 0;
_d->closeHandling = cmRemove;
_d->pos = rectangle.lefttop();
_d->flags.invalidate = true;
if( getFocus )
setFocus();
setNotClipped(true);
setTextAlignment( align::center, align::upperLeft );
_d->flags.allowFocus = allowFocus;
_d->changeTime = 0;
_d->highlihted.index = -1;
setDefaultStateFont(stNormal, Font::create("FONT_2"));
setDefaultStateFont(stHovered, Font::create("FONT_2_WHITE"));
}
//! destructor
ContextMenu::~ContextMenu() {}
//! set behaviour when menus are closed
void ContextMenu::setCloseHandling(CloseMode onClose) { _d->closeHandling = onClose;}
//! get current behaviour when the menue will be closed
ContextMenu::CloseMode ContextMenu::getCloseHandling() const { return _d->closeHandling;}
//! Returns amount of menu items
unsigned int ContextMenu::itemCount() const { return _d->items.size();}
ContextMenuItem* ContextMenu::addItem( const std::string& path, const std::string& text, int commandId,
bool enabled, bool hasSubMenu,
bool checked, bool autoChecking)
{
StringArray items = utils::split(path, "/");
if (items.empty())
{
return addItem( text, commandId, enabled, hasSubMenu, checked, autoChecking );
}
ContextMenuItem* lastItem = findItem(items.front());
if (lastItem == NULL)
{
lastItem = addItem( items.front(), -1, true, true );
}
items.pop_front();
for (auto& item : items)
{
if (lastItem->submenu() == NULL)
{
lastItem = lastItem->addSubmenu()->addItem(item, -1, true, true);
}
else
{
ContextMenuItem* saveItem = lastItem;
lastItem = lastItem->submenu()->findItem(item);
if (!lastItem)
lastItem = saveItem->submenu()->addItem(item, -1, true, true);
}
}
if( lastItem->submenu() )
{
lastItem = lastItem->submenu()->addItem( text, commandId );
}
return lastItem;
}
//! Adds a menu item.
ContextMenuItem* ContextMenu::addItem( const std::string& text, int commandId,
bool enabled, bool hasSubMenu,
bool checked, bool autoChecking)
{
return insertItem( _d->items.size(), text, commandId, enabled, hasSubMenu, checked, autoChecking);
}
ContextMenuItem* ContextMenu::addItem(const std::string& path, const std::string& text)
{
updateItems();
if(path.empty())
return addItem(text,-1);
else
return addItem(path,text,-1);
}
//! Insert a menu item at specified position.
ContextMenuItem* ContextMenu::insertItem(unsigned int idx, const std::string& text, int commandId, bool enabled,
bool hasSubMenu, bool checked, bool autoChecking)
{
ContextMenuItem& newItem = add<ContextMenuItem>( text );
newItem.setEnabled(enabled);
newItem.setSubElement(true);
newItem.setChecked(checked);
newItem.setAutoChecking(autoChecking);
newItem.setText(text);
newItem.setFlag(ContextMenuItem::drawSubmenuSprite);
newItem.setIsSeparator(text.empty());
newItem.setCommandId(commandId);
newItem.setStateFont(stHovered, _d->states[stHovered].font);
newItem.setStateFont(stNormal, _d->states[stNormal].font);
newItem.sendToBack();
if (hasSubMenu)
{
ContextMenu* subMenu = newItem.addSubmenu(commandId);
subMenu->setVisible( false );
}
if ( idx < _d->items.size() )
{
_d->items.insert(_d->items.begin() + idx, &newItem);
}
else
{
_d->items.push_back( &newItem );
}
return &newItem;
}
ContextMenuItem* ContextMenu::findItem(const std::string& name) const
{
for( const auto& it : _d->items )
{
if ( it->text() == name )
return it;
}
return nullptr;
}
bool ContextMenu::itemExist(const std::string& name) const
{
if (name.empty())
return false;
return findItem(name) != nullptr;
}
void ContextMenu::setDefaultStateFont(ElementState state, Font f)
{
_d->states[state].font = f.fallback(16,false,false,ColorList::pink);
}
//! Adds a separator item to the menu
void ContextMenu::addSeparator() { addItem(0, -1, true, false, false, false); }
//! Returns text of the menu item.
ContextMenuItem* ContextMenu::item( unsigned int idx ) const
{
if( idx >= _d->items.size() )
return NULL;
return _d->items[ idx ];
}
//! Sets text of the menu item.
void ContextMenu::updateItems() { _d->flags.invalidate = true; }
//! Removes a menu item
void ContextMenu::removeItem(unsigned int idx)
{
if (idx >= _d->items.size())
return;
_d->items[idx]->deleteLater();
_d->items.erase( _d->items.begin() + idx );
updateItems();
}
//! Removes all menu items
void ContextMenu::removeAllItems()
{
for (unsigned int i = 0; i < _d->items.size(); ++i)
_d->items[ i ]->deleteLater();
_d->items.clear();
updateItems();
}
//! called if an event happened.
bool ContextMenu::onEvent(const NEvent& event)
{
if( enabled() )
{
switch(event.EventType)
{
case sEventGui:
switch(event.gui.type)
{
case event::gui::widget::focusLost:
if (event.gui.caller == this && !isMyChild(event.gui.element) && _d->flags.allowFocus)
{
// set event parent of submenus
Widget* p = _d->eventParent ? _d->eventParent : parent();
setEventParent(p);
NEvent event;
event.EventType = sEventGui;
event.gui.caller = this;
event.gui.element = 0;
event.gui.type = event::gui::widget::closed;
if ( !p->onEvent(event) )
{
if( (_d->closeHandling & cmHide) > 0 )
{
hide();
}
else if( (_d->closeHandling & cmRemove) > 0 )
{
deleteLater();
}
}
return false;
}
break;
case event::gui::widget::focused:
if (event.gui.caller == this && !_d->flags.allowFocus)
{
return true;
}
break;
default:
break;
}
break;
case sEventMouse:
switch(event.mouse.type)
{
case NEvent::Mouse::mouseLbtnRelease:
{
// menu might be removed if it loses focus in sendClick, so grab a reference
grab();
const unsigned int t = _sendClick( event.mouse.pos() );
if( (t==0 || t==1) && isFocused() )
removeFocus();
drop();
}
return true;
case NEvent::Mouse::btnLeftPressed:
return true;
case NEvent::Mouse::moved:
if( isHovered() )
_isHighlighted( event.mouse.pos(), true);
return true;
default:
break;
}
break;
default:
break;
}
}
return Widget::onEvent(event);
}
//! Sets the visible state of this element.
void ContextMenu::setVisible(bool visible)
{
_setHovered( -1 );
_closeAllSubMenus();
if( visible )
updateItems();
Widget::setVisible( visible );
}
void ContextMenu::_setHovered( int index )
{
_d->highlihted.index = index;
_d->changeTime = DateTime::elapsedTime();
}
//! sends a click Returns:
//! 0 if click went outside of the element,
//! 1 if a valid button was clicked,
//! 2 if a nonclickable element was clicked
unsigned int ContextMenu::_sendClick(const Point& p)
{
unsigned int t = 0;
// get number of open submenu
int openmenu = -1;
int j;
for( j=0; j<(int)_d->items.size(); ++j )
if (_d->items[j]->submenu() && _d->items[j]->submenu()->visible())
{
openmenu = j;
break;
}
// delegate click operation to submenu
if (openmenu != -1)
{
t = _d->items[j]->submenu()->_sendClick( p );
if (t != 0)
return t; // clicked something
}
// check click on myself
if( isPointInside(p) &&
(unsigned int)_d->highlihted.index < _d->items.size())
{
if (!_d->items[_d->highlihted.index]->enabled() ||
_d->items[_d->highlihted.index ]->isSeparator() ||
_d->items[_d->highlihted.index ]->submenu() )
return 2;
selectedItem()->toggleCheck();
NEvent event;
event.EventType = sEventGui;
event.gui.caller = this;
event.gui.element = 0;
event.gui.type = event::gui::menuItemSelected;
if( _d->eventParent )
_d->eventParent->onEvent(event);
else
parent()->onEvent(event);
ContextMenuItem* tItem = selectedItem();
if( tItem )
{
emit tItem->onClicked()();
emit tItem->onAction()(tItem->commandId());
emit tItem->onClickedA()(tItem);
emit _d->onItemActionSignal(tItem->commandId());
}
return 1;
}
return 0;
}
void ContextMenu::setItemVisible( unsigned int index, bool visible )
{
if( index >= _d->items.size() )
return;
ContextMenu* menuPtr = item( index )->submenu();
if( menuPtr )
{
menuPtr->setVisible( visible );
}
}
//! returns true, if an element was highligted
bool ContextMenu::_isHighlighted( const Point& p, bool canOpenSubMenu )
{
if (!enabled())
{
return false;
}
// get number of open submenu
int openmenu = -1;
foreach( it, _d->items )
{
if( (*it)->enabled() && (*it)->submenu() && (*it)->submenu()->visible() )
{
openmenu = std::distance( _d->items.begin(), it );
break;
}
}
// delegate highlight operation to submenu
if (openmenu != -1)
{
if (_d->items[openmenu]->enabled() && _d->items[openmenu]->submenu()->_isHighlighted(p, canOpenSubMenu))
{
_d->highlihted.index = openmenu;
_d->changeTime = DateTime::elapsedTime();
return true;
}
}
for( auto& it : _d->items )
{
it->setHovered( false );
}
// highlight myself
_d->highlihted.last = -1;
foreach( it, _d->items )
{
if ( (*it)->enabled() && (*it)->absoluteRect().isPointInside( p ))
{
_d->highlihted.index = std::distance( _d->items.begin(), it );
_d->changeTime = DateTime::elapsedTime();
// make submenus visible/invisible
if( _d->highlihted.index != _d->highlihted.last )
{
_closeAllSubMenus();
setItemVisible( _d->highlihted.last, false );
ContextMenuItem* rItem = _d->items[ _d->highlihted.index ];
if( rItem->submenu() && canOpenSubMenu && rItem->enabled() )
{
rItem->submenu()->setVisible( true );
setItemVisible( _d->highlihted.index, true );
}
_d->highlihted.last = _d->highlihted.index;
rItem->setHovered( true );
}
return true;
}
}
_d->highlihted.index = openmenu;
return false;
}
void ContextMenu::beforeDraw(gfx::Engine& painter)
{
if (!visible())
return;
Font font = Font::create( "FONT_2_WHITE" );
if (font != _d->lastFont)
{
_d->lastFont = font;
updateItems();
}
if (_d->flags.invalidate)
{
_d->flags.invalidate = false;
_recalculateSize();
}
Widget::beforeDraw(painter);
}
//! draws the element and its children
void ContextMenu::draw(gfx::Engine& painter )
{
if (!visible())
return;
Widget::draw( painter );
}
void ContextMenu::_recalculateSize()
{
Rect rect;
rect._lefttop = relativeRect().lefttop();
Size maxSize( 100, 3 );
unsigned int i;
unsigned int itemSize = _d->items.size();
for (i=0; i< itemSize; ++i)
{
ContextMenuItem* refItem = _d->items[i];
if (refItem->isSeparator() )
{
refItem->setDimmension( Size( 150, 10 ) );
}
else
{
Font font = refItem->font();
if( font.isValid() )
refItem->setDimmension( font.getTextSize( refItem->text() ) + Size( 40, 0 ) );
maxSize.setWidth( std::max<unsigned int>( refItem->dimmension().width(), maxSize.width() ) );
}
refItem->setOffset( maxSize.height() );
maxSize += Size( 0, std::max<int>( refItem->dimmension().height(), 10 ) );
}
maxSize.setHeight( std::max<unsigned int>( maxSize.height()+5, 10 ) );
rect._bottomright = relativeRect().lefttop() + Point( maxSize.width(), maxSize.height() );
setGeometry(rect);
// recalculate submenus
for (i=0; i<_d->items.size(); ++i)
{
ContextMenuItem* refItem = _d->items[i];
Rect rectangle( 0, refItem->offset(), width(), refItem->offset() + refItem->dimmension().height() );
refItem->setGeometry( rectangle );
if( refItem->submenu() )
{
// move submenu
ContextMenu* subMenu = refItem->submenu();
const Size subMenuSize = subMenu->absoluteRect().size();
Rect subRect( maxSize.width()-5, refItem->offset(),
maxSize.width()+subMenuSize.width()-5, refItem->offset() +subMenuSize.height() );
// if it would be drawn beyond the right border, then add it to the left side
Widget * root = ui()->rootWidget();
if( root && ContextMenuItem::alignAuto == refItem->subMenuAlignment() )
{
Rect rectRoot( root->absoluteRect() );
if ( absoluteRect().left() + subRect.right() > rectRoot.right() )
{
subRect.setLeft( -subMenuSize.width() );
subRect.setRight( 0 );
}
}
else
{
switch( refItem->subMenuAlignment() & 0x0f )
{
case ContextMenuItem::alignLeft:
subRect.setLeft( -subMenuSize.width() );
subRect.setRight( 0 );
break;
case ContextMenuItem::alignRigth:
break;
case ContextMenuItem::alignHorizCenter:
subRect.setLeft( ( absoluteRect().width() - subMenuSize.width() ) / 2 );
subRect.setRight( subRect.left() + subMenuSize.width() );
break;
}
switch( refItem->subMenuAlignment() & 0xf0 )
{
case ContextMenuItem::alignTop:
subRect -= Point( 0, subMenuSize.height() / 2 + refItem->dimmension().height() );
break;
case ContextMenuItem::alignBottom:
break;
case ContextMenuItem::alignVertCenter:
subRect -= Point( 0, subMenuSize.height() / 4 );
break;
}
}
subMenu->setGeometry(subRect);
}
}
}
//! Returns the selected item in the menu
int ContextMenu::selected() const
{
return _d->highlihted.index;
}
ContextMenuItem *ContextMenu::selectedItem() const
{
return item( _d->highlihted.index );
}
void ContextMenu::resetToDefaultFonts()
{
for (auto& item : _d->items)
{
item->setStateFont(stHovered, _d->states[stHovered].font);
item->setStateFont(stNormal, _d->states[stNormal].font);
if (item->submenu())
{
item->submenu()->setDefaultStateFont(stHovered, _d->states[stHovered].font);
item->submenu()->setDefaultStateFont(stNormal, _d->states[stNormal].font);
item->submenu()->resetToDefaultFonts();
}
}
}
void ContextMenu::setProperty(const std::string& name, const Variant &value)
{
if (name == "resetToDefaultFonts") { resetToDefaultFonts(); }
Widget::setProperty(name, value);
}
// because sometimes the element has no parent at click time
void ContextMenu::setEventParent( Widget *parent )
{
_d->eventParent = parent;
for( auto& item : _d->items )
if( item->submenu() )
item->submenu()->setEventParent(parent);
}
bool ContextMenu::_hasOpenSubMenu() const
{
for( auto i : _d->items )
if( i->submenu() && i->submenu()->visible() )
return true;
return false;
}
void ContextMenu::moveItem(ContextMenuItem* item, unsigned int index)
{
if (index >= _d->items.size())
return;
for (unsigned int i = 0; i < _d->items.size(); ++i)
{
if (_d->items[i] == item)
{
_d->items.erase(_d->items.begin() + i);
_d->items.insert(_d->items.begin() + index, item);
return;
}
}
updateItems();
}
void ContextMenu::_closeAllSubMenus()
{
for(unsigned int i=0; i<_d->items.size(); ++i)
{
if( _d->items[i]->submenu() && _d->items[i]->visible())
setItemVisible( i, false );
}
//HighLighted = -1;
}
void ContextMenu::setAllowFocus( bool enabled ) { _d->flags.allowFocus = enabled;}
int ContextMenu::hovered() const { return _d->highlihted.index; }
Signal1<int>& ContextMenu::onItemAction() { return _d->onItemActionSignal; }
}//end namespace gui
| 1 | 0.960496 | 1 | 0.960496 | game-dev | MEDIA | 0.541836 | game-dev,desktop-app | 0.979017 | 1 | 0.979017 |
emoose/Arise-SDK | 3,259 | src/SDK/FullscreenMoviePlayerWidget_parameters.h | #pragma once
#include "../SDK.h"
// Name: Arise, Version: 1.0.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function FullscreenMoviePlayerWidget.FullscreenMoviePlayerWidget_C.Construct
struct UFullscreenMoviePlayerWidget_C_Construct_Params
{
};
// Function FullscreenMoviePlayerWidget.FullscreenMoviePlayerWidget_C.Tick
struct UFullscreenMoviePlayerWidget_C_Tick_Params
{
struct FGeometry MyGeometry; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
float InDeltaTime; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function FullscreenMoviePlayerWidget.FullscreenMoviePlayerWidget_C.SetupMovie
struct UFullscreenMoviePlayerWidget_C_SetupMovie_Params
{
class UMaterialInstance* Material; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UManaTexture* Texture; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function FullscreenMoviePlayerWidget.FullscreenMoviePlayerWidget_C.DisplaySubtitle
struct UFullscreenMoviePlayerWidget_C_DisplaySubtitle_Params
{
bool Visibility; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FString GroupID; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor)
struct FString StringID; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor)
};
// Function FullscreenMoviePlayerWidget.FullscreenMoviePlayerWidget_C.SetFadeColor
struct UFullscreenMoviePlayerWidget_C_SetFadeColor_Params
{
struct FLinearColor Color; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
};
// Function FullscreenMoviePlayerWidget.FullscreenMoviePlayerWidget_C.SetFadeOpacity
struct UFullscreenMoviePlayerWidget_C_SetFadeOpacity_Params
{
float Opacity; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function FullscreenMoviePlayerWidget.FullscreenMoviePlayerWidget_C.ExecuteUbergraph_FullscreenMoviePlayerWidget
struct UFullscreenMoviePlayerWidget_C_ExecuteUbergraph_FullscreenMoviePlayerWidget_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 1 | 0.706088 | 1 | 0.706088 | game-dev | MEDIA | 0.719957 | game-dev | 0.702797 | 1 | 0.702797 |
ProjectEQ/projecteqquests | 4,151 | felwitheb/Thwinose_Vilgarn.lua | function event_say(e)
local level = e.other:GetLevel();
local qglobals = eq.get_qglobals(e.other);
if(level >= 15) then
if(e.message:findi("hail")) then
e.self:Say("Come to find out about the Wayfarers Brotherhood, hm? I think I saw you around here long ago. Because you are familiar to me, I will trust you with some [".. eq.say_link("information",false,"information") .. "].");
elseif(e.message:findi("information")) then
e.self:Say("The Wayfarers Brotherhood is pretty particular about who they do business with. You will need to prove yourself to them. You can start gaining their gratitude by helping them. The Wayfarers Brotherhood will ask you to answer some questions when you first meet with them. They tend to call all of their assignments 'adventures.' You'd do well to keep that in mind as they'll be more likely to give you some tasks. There is other information that makes them easier to [" .. eq.say_link("deal with",false,"deal with") .. "] too.");
elseif(e.message:findi("deal with")) then
e.self:Say("There are several camps of Wayfarers Brotherhood explorers around the world. In each camp you'll find a trusted Wayfarers Brotherhood member that has the task of recruiting adventurers that will take on interesting, and potentially lethal, [" .. eq.say_link("work",false,"work") .. "]. Some members will tell you stories, if they think you are worthy of learning such prized information. Others will share their treasures with you, but only if you do work for them.");
elseif(e.message:findi("work")) then
e.self:Say("The Wayfarers Brotherhood believes in giving something for something. For each adventure you take from them, they will add you to their Favor Journal. With the points of Favor that their record keepers have counted for you, you can trade your good Favor for wonderful treasures and goods. Also, the more adventures you do for the Wayfarers Brotherhood, the more your Favor increases. The harder jobs get you more Favor, by the way. As you gain more Favor, the Wayfarers Brotherhood treasure keepers will let you peek at some of their more unique and sought after items. So, it pays to get in good with them, you see! And there's [" .. eq.say_link("more",false,"more") .. "]!");
elseif(e.message:findi("more")) then
e.self:Say("You should also know that there are five magi in the Wayfarers Brotherhood that have found very unique magic stones in the world that they are able to use to transport adventurers to one another. They have placed a magus with one of these stones at each large camp. They call it Farstone Magic. And that's not the only [" .. eq.say_link("interesting ore",false,"interesting ore") .. "] we've seen lately.");
elseif(e.message:findi("interesting ore")) then
e.self:Say("We've found some strange items off the dead in the dungeons. At first we just thought they were simple things -- rocks, pebbles, gems, and the like -- and then we noticed they had very unusual auras about them. Well, one day, Morden Rasp was toying with one -- a shiny green shard -- and he went to scrape it with his dagger. Suddenly, the shard began to reform and fused with his dagger. While the dagger remained as fine as ever, Morden himself felt a surge of strength! So, you will want to watch out for these strange magic pieces in the world. Now, I suggest you go talk to Selephra Giztral, Barstre Songweaver, Vual Stoutest, Teria Grinntli, or Ruanya Windleaf. They handle all of those who are interested in working for the Wayfarers Brotherhood and getting rewards. Remember well what I've told you!");
if(qglobals.Wayfarer == nil) then
e.other:Message(MT.Yellow,"You have completed a step toward becoming a great adventurer. Well done!");
eq.set_global("Wayfarer","1",5,"F");
end
end
else
e.self:Say("You show a great deal of courage in coming here to speak with me at such a young age. I'm afraid you are not yet ready to pursue work with the Wayfarers Brotherhood.Come back when you have more experience and we will talk again.");
end
end
function event_trade(e)
local item_lib = require("items");
item_lib.return_items(e.self, e.other, e.trade)
end
| 1 | 0.679733 | 1 | 0.679733 | game-dev | MEDIA | 0.916284 | game-dev | 0.608139 | 1 | 0.608139 |
OFS/opae-sdk | 5,421 | libraries/libopaecxx/src/properties.cpp | // Copyright(c) 2018-2022, Intel Corporation
//
// 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 Intel Corporation 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.
#include <opae/cxx/core/except.h>
#include <opae/cxx/core/handle.h>
#include <opae/cxx/core/properties.h>
#include <opae/cxx/core/token.h>
#include <opae/utils.h>
namespace opae {
namespace fpga {
namespace types {
const std::vector<properties::ptr_t> properties::none = {};
properties::properties(bool alloc_props)
: props_(nullptr),
type(&props_, fpgaPropertiesGetObjectType, fpgaPropertiesSetObjectType),
num_errors(&props_, fpgaPropertiesGetNumErrors,
fpgaPropertiesSetNumErrors),
segment(&props_, fpgaPropertiesGetSegment, fpgaPropertiesSetSegment),
bus(&props_, fpgaPropertiesGetBus, fpgaPropertiesSetBus),
device(&props_, fpgaPropertiesGetDevice, fpgaPropertiesSetDevice),
function(&props_, fpgaPropertiesGetFunction, fpgaPropertiesSetFunction),
socket_id(&props_, fpgaPropertiesGetSocketID, fpgaPropertiesSetSocketID),
num_slots(&props_, fpgaPropertiesGetNumSlots, fpgaPropertiesSetNumSlots),
bbs_id(&props_, fpgaPropertiesGetBBSID, fpgaPropertiesSetBBSID),
bbs_version(&props_, fpgaPropertiesGetBBSVersion,
fpgaPropertiesSetBBSVersion),
vendor_id(&props_, fpgaPropertiesGetVendorID, fpgaPropertiesSetVendorID),
device_id(&props_, fpgaPropertiesGetDeviceID, fpgaPropertiesSetDeviceID),
subsystem_vendor_id(&props_, fpgaPropertiesGetSubsystemVendorID,
fpgaPropertiesSetSubsystemVendorID),
subsystem_device_id(&props_, fpgaPropertiesGetSubsystemDeviceID,
fpgaPropertiesSetSubsystemDeviceID),
model(&props_, fpgaPropertiesGetModel, fpgaPropertiesSetModel),
local_memory_size(&props_, fpgaPropertiesGetLocalMemorySize,
fpgaPropertiesSetLocalMemorySize),
capabilities(&props_, fpgaPropertiesGetCapabilities,
fpgaPropertiesSetCapabilities),
num_mmio(&props_, fpgaPropertiesGetNumMMIO, fpgaPropertiesSetNumMMIO),
num_interrupts(&props_, fpgaPropertiesGetNumInterrupts,
fpgaPropertiesSetNumInterrupts),
accelerator_state(&props_, fpgaPropertiesGetAcceleratorState,
fpgaPropertiesSetAcceleratorState),
object_id(&props_, fpgaPropertiesGetObjectID, fpgaPropertiesSetObjectID),
parent(&props_, fpgaPropertiesGetParent, fpgaPropertiesSetParent),
interface(&props_, fpgaPropertiesGetInterface,
fpgaPropertiesSetInterface),
guid(&props_) {
if (alloc_props) {
ASSERT_FPGA_OK(fpgaGetProperties(nullptr, &props_));
}
}
properties::ptr_t properties::get() {
properties::ptr_t props(new properties());
return props;
}
properties::ptr_t properties::get(fpga_guid guid_in) {
properties::ptr_t props(new properties());
props->guid = guid_in;
return props;
}
properties::ptr_t properties::get(fpga_objtype objtype) {
properties::ptr_t props(new properties());
props->type = objtype;
return props;
}
properties::ptr_t properties::get(fpga_token tok) {
ptr_t p(new properties(false));
auto res = fpgaGetProperties(tok, &p->props_);
if (res != FPGA_OK) {
p.reset();
}
ASSERT_FPGA_OK(res);
return p;
}
properties::ptr_t properties::get(handle::ptr_t h) {
ptr_t p(new properties(false));
auto res = fpgaGetPropertiesFromHandle(h->c_type(), &p->props_);
if (res != FPGA_OK) {
p.reset();
}
ASSERT_FPGA_OK(res);
return p;
}
properties::ptr_t properties::get(token::ptr_t tok) {
return get(tok->c_type());
}
properties::~properties() {
if (props_ != nullptr) {
auto res = fpgaDestroyProperties(&props_);
if (res != FPGA_OK) {
std::cerr << "Error while calling fpgaDestroyProperties: "
<< fpgaErrStr(res) << "\n";
}
}
}
} // end of namespace types
} // end of namespace fpga
} // end of namespace opae
| 1 | 0.925756 | 1 | 0.925756 | game-dev | MEDIA | 0.450434 | game-dev | 0.589171 | 1 | 0.589171 |
The-Legion-Preservation-Project/LegionCore-7.3.5 | 6,444 | dep/g3dlite/source/Ray.cpp | /**
@file Ray.cpp
@maintainer Morgan McGuire, http://graphics.cs.williams.edu
@created 2002-07-12
@edited 2004-03-19
*/
#include "G3D/platform.h"
#include "G3D/Ray.h"
#include "G3D/Plane.h"
#include "G3D/Sphere.h"
#include "G3D/CollisionDetection.h"
namespace G3D {
void Ray::set(const Vector3& origin, const Vector3& direction) {
m_origin = origin;
m_direction = direction;
debugAssert(direction.isUnit());
m_invDirection = Vector3::one() / direction;
// ray slope
ibyj = m_direction.x * m_invDirection.y;
jbyi = m_direction.y * m_invDirection.x;
jbyk = m_direction.y * m_invDirection.z;
kbyj = m_direction.z * m_invDirection.y;
ibyk = m_direction.x * m_invDirection.z;
kbyi = m_direction.z * m_invDirection.x;
// precomputed terms
c_xy = m_origin.y - jbyi * m_origin.x;
c_xz = m_origin.z - kbyi * m_origin.x;
c_yx = m_origin.x - ibyj * m_origin.y;
c_yz = m_origin.z - kbyj * m_origin.y;
c_zx = m_origin.x - ibyk * m_origin.z;
c_zy = m_origin.y - jbyk * m_origin.z;
//ray slope classification
if (m_direction.x < 0) {
if (m_direction.y < 0) {
if (m_direction.z < 0) {
classification = MMM;
} else if (m_direction.z > 0) {
classification = MMP;
} else { //(m_direction.z >= 0)
classification = MMO;
}
} else { //(m_direction.y >= 0)
if (m_direction.z < 0) {
if (m_direction.y == 0) {
classification = MOM;
} else {
classification = MPM;
}
} else { //(m_direction.z >= 0)
if ((m_direction.y == 0) && (m_direction.z == 0)) {
classification = MOO;
} else if (m_direction.z == 0) {
classification = MPO;
} else if (m_direction.y == 0) {
classification = MOP;
} else {
classification = MPP;
}
}
}
} else { //(m_direction.x >= 0)
if (m_direction.y < 0) {
if (m_direction.z < 0) {
if (m_direction.x == 0) {
classification = OMM;
} else {
classification = PMM;
}
} else { //(m_direction.z >= 0)
if ((m_direction.x == 0) && (m_direction.z == 0)) {
classification = OMO;
} else if (m_direction.z == 0) {
classification = PMO;
} else if (m_direction.x == 0) {
classification = OMP;
} else {
classification = PMP;
}
}
} else { //(m_direction.y >= 0)
if (m_direction.z < 0) {
if ((m_direction.x == 0) && (m_direction.y == 0)) {
classification = OOM;
} else if (m_direction.x == 0) {
classification = OPM;
} else if (m_direction.y == 0) {
classification = POM;
} else {
classification = PPM;
}
} else { //(m_direction.z > 0)
if (m_direction.x == 0) {
if (m_direction.y == 0) {
classification = OOP;
} else if (m_direction.z == 0) {
classification = OPO;
} else {
classification = OPP;
}
} else {
if ((m_direction.y == 0) && (m_direction.z == 0)) {
classification = POO;
} else if (m_direction.y == 0) {
classification = POP;
} else if (m_direction.z == 0) {
classification = PPO;
} else {
classification = PPP;
}
}
}
}
}
}
Ray::Ray(class BinaryInput& b) {
deserialize(b);
}
void Ray::serialize(class BinaryOutput& b) const {
m_origin.serialize(b);
m_direction.serialize(b);
}
void Ray::deserialize(class BinaryInput& b) {
m_origin.deserialize(b);
m_direction.deserialize(b);
set(m_origin, m_direction);
}
Ray Ray::refract(
const Vector3& newOrigin,
const Vector3& normal,
float iInside,
float iOutside) const {
Vector3 D = m_direction.refractionDirection(normal, iInside, iOutside);
return Ray(newOrigin + (m_direction + normal * (float)sign(m_direction.dot(normal))) * 0.001f, D);
}
Ray Ray::reflect(
const Vector3& newOrigin,
const Vector3& normal) const {
Vector3 D = m_direction.reflectionDirection(normal);
return Ray(newOrigin + (D + normal) * 0.001f, D);
}
Vector3 Ray::intersection(const Plane& plane) const {
float d;
Vector3 normal = plane.normal();
plane.getEquation(normal, d);
float rate = m_direction.dot(normal);
if (rate >= 0.0f) {
return Vector3::inf();
} else {
float t = -(d + m_origin.dot(normal)) / rate;
return m_origin + m_direction * t;
}
}
float Ray::intersectionTime(const class Sphere& sphere, bool solid) const {
Vector3 dummy;
return CollisionDetection::collisionTimeForMovingPointFixedSphere(
m_origin, m_direction, sphere, dummy, dummy, solid);
}
float Ray::intersectionTime(const class Plane& plane) const {
Vector3 dummy;
return CollisionDetection::collisionTimeForMovingPointFixedPlane(
m_origin, m_direction, plane, dummy);
}
float Ray::intersectionTime(const class Box& box) const {
Vector3 dummy;
float time = CollisionDetection::collisionTimeForMovingPointFixedBox(
m_origin, m_direction, box, dummy);
if ((time == finf()) && (box.contains(m_origin))) {
return 0.0f;
} else {
return time;
}
}
float Ray::intersectionTime(const class AABox& box) const {
Vector3 dummy;
bool inside;
float time = CollisionDetection::collisionTimeForMovingPointFixedAABox(
m_origin, m_direction, box, dummy, inside);
if ((time == finf()) && inside) {
return 0.0f;
} else {
return time;
}
}
}
| 1 | 0.847129 | 1 | 0.847129 | game-dev | MEDIA | 0.593477 | game-dev,graphics-rendering | 0.987498 | 1 | 0.987498 |
fortressforever/fortressforever | 1,641 | game_shared/ff/ff_projectile_nail.h | /// =============== Fortress Forever ==============
/// ======== A modification for Half-Life 2 =======
///
/// @file ff_projectile_nail.h
/// @author Gavin "Mirvin_Monkey" Bramhill
/// @date December 21, 2004
/// @brief Declarion of the class for nail projectiles
///
/// REVISIONS
/// ---------
/// Dec 21, 2004 Mirv: First created
#ifndef FF_PROJECTILE_NAIL_H
#define FF_PROJECTILE_NAIL_H
#ifdef _WIN32
#pragma once
#endif
#include "ff_projectile_base.h"
#ifdef CLIENT_DLL
#define CFFProjectileNail C_FFProjectileNail
#endif
class NailTrail;
//=============================================================================
// CFFProjectileNail
//=============================================================================
class CFFProjectileNail : public CFFProjectileBase
{
public:
DECLARE_CLASS(CFFProjectileNail, CFFProjectileBase);
public:
bool m_bNailGrenadeNail;
virtual void Precache();
void BubbleThink();
void NailTouch(CBaseEntity *pOther);
//int ShouldTransmit(const CCheckTransmitInfo *pInfo) { return FL_EDICT_DONTSEND; }
static CFFProjectileNail *CreateNail(const CBaseEntity *pSource, const Vector &vecOrigin, const QAngle &angAngles, CBaseEntity *pentOwner, const int iDamage, const int iSpeed, bool bNotClientSide = false);
virtual bool CanClipOwnerEntity() const { return m_bNailGrenadeNail; }
int UpdateTransmitState() { return FL_EDICT_DONTSEND; }
#ifdef CLIENT_DLL
CFFProjectileNail() {}
CFFProjectileNail(const CFFProjectileNail&) {}
#else
DECLARE_DATADESC(); // Since we're adding new thinks etc
virtual void Spawn();
protected:
private:
#endif
};
#endif // FF_PROJECTILE_NAIL_H
| 1 | 0.902919 | 1 | 0.902919 | game-dev | MEDIA | 0.874893 | game-dev | 0.676207 | 1 | 0.676207 |
minty-codes/TutorialClient1.8.8 | 7,892 | net/minecraft/block/BlockWall.java | package net.minecraft.block;
import java.util.List;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.StatCollector;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class BlockWall extends Block
{
public static final PropertyBool UP = PropertyBool.create("up");
public static final PropertyBool NORTH = PropertyBool.create("north");
public static final PropertyBool EAST = PropertyBool.create("east");
public static final PropertyBool SOUTH = PropertyBool.create("south");
public static final PropertyBool WEST = PropertyBool.create("west");
public static final PropertyEnum<BlockWall.EnumType> VARIANT = PropertyEnum.<BlockWall.EnumType>create("variant", BlockWall.EnumType.class);
public BlockWall(Block modelBlock)
{
super(modelBlock.blockMaterial);
this.setDefaultState(this.blockState.getBaseState().withProperty(UP, Boolean.valueOf(false)).withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false)).withProperty(VARIANT, BlockWall.EnumType.NORMAL));
this.setHardness(modelBlock.blockHardness);
this.setResistance(modelBlock.blockResistance / 3.0F);
this.setStepSound(modelBlock.stepSound);
this.setCreativeTab(CreativeTabs.tabBlock);
}
/**
* Gets the localized name of this block. Used for the statistics page.
*/
public String getLocalizedName()
{
return StatCollector.translateToLocal(this.getUnlocalizedName() + "." + BlockWall.EnumType.NORMAL.getUnlocalizedName() + ".name");
}
public boolean isFullCube()
{
return false;
}
public boolean isPassable(IBlockAccess worldIn, BlockPos pos)
{
return false;
}
/**
* Used to determine ambient occlusion and culling when rebuilding chunks for render
*/
public boolean isOpaqueCube()
{
return false;
}
public void setBlockBoundsBasedOnState(IBlockAccess worldIn, BlockPos pos)
{
boolean flag = this.canConnectTo(worldIn, pos.north());
boolean flag1 = this.canConnectTo(worldIn, pos.south());
boolean flag2 = this.canConnectTo(worldIn, pos.west());
boolean flag3 = this.canConnectTo(worldIn, pos.east());
float f = 0.25F;
float f1 = 0.75F;
float f2 = 0.25F;
float f3 = 0.75F;
float f4 = 1.0F;
if (flag)
{
f2 = 0.0F;
}
if (flag1)
{
f3 = 1.0F;
}
if (flag2)
{
f = 0.0F;
}
if (flag3)
{
f1 = 1.0F;
}
if (flag && flag1 && !flag2 && !flag3)
{
f4 = 0.8125F;
f = 0.3125F;
f1 = 0.6875F;
}
else if (!flag && !flag1 && flag2 && flag3)
{
f4 = 0.8125F;
f2 = 0.3125F;
f3 = 0.6875F;
}
this.setBlockBounds(f, 0.0F, f2, f1, f4, f3);
}
public AxisAlignedBB getCollisionBoundingBox(World worldIn, BlockPos pos, IBlockState state)
{
this.setBlockBoundsBasedOnState(worldIn, pos);
this.maxY = 1.5D;
return super.getCollisionBoundingBox(worldIn, pos, state);
}
public boolean canConnectTo(IBlockAccess worldIn, BlockPos pos)
{
Block block = worldIn.getBlockState(pos).getBlock();
return block == Blocks.barrier ? false : (block != this && !(block instanceof BlockFenceGate) ? (block.blockMaterial.isOpaque() && block.isFullCube() ? block.blockMaterial != Material.gourd : false) : true);
}
/**
* returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks)
*/
public void getSubBlocks(Item itemIn, CreativeTabs tab, List<ItemStack> list)
{
for (BlockWall.EnumType blockwall$enumtype : BlockWall.EnumType.values())
{
list.add(new ItemStack(itemIn, 1, blockwall$enumtype.getMetadata()));
}
}
/**
* Gets the metadata of the item this Block can drop. This method is called when the block gets destroyed. It
* returns the metadata of the dropped item based on the old metadata of the block.
*/
public int damageDropped(IBlockState state)
{
return ((BlockWall.EnumType)state.getValue(VARIANT)).getMetadata();
}
public boolean shouldSideBeRendered(IBlockAccess worldIn, BlockPos pos, EnumFacing side)
{
return side == EnumFacing.DOWN ? super.shouldSideBeRendered(worldIn, pos, side) : true;
}
/**
* Convert the given metadata into a BlockState for this Block
*/
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(VARIANT, BlockWall.EnumType.byMetadata(meta));
}
/**
* Convert the BlockState into the correct metadata value
*/
public int getMetaFromState(IBlockState state)
{
return ((BlockWall.EnumType)state.getValue(VARIANT)).getMetadata();
}
/**
* Get the actual Block state of this Block at the given position. This applies properties not visible in the
* metadata, such as fence connections.
*/
public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos)
{
return state.withProperty(UP, Boolean.valueOf(!worldIn.isAirBlock(pos.up()))).withProperty(NORTH, Boolean.valueOf(this.canConnectTo(worldIn, pos.north()))).withProperty(EAST, Boolean.valueOf(this.canConnectTo(worldIn, pos.east()))).withProperty(SOUTH, Boolean.valueOf(this.canConnectTo(worldIn, pos.south()))).withProperty(WEST, Boolean.valueOf(this.canConnectTo(worldIn, pos.west())));
}
protected BlockState createBlockState()
{
return new BlockState(this, new IProperty[] {UP, NORTH, EAST, WEST, SOUTH, VARIANT});
}
public static enum EnumType implements IStringSerializable
{
NORMAL(0, "cobblestone", "normal"),
MOSSY(1, "mossy_cobblestone", "mossy");
private static final BlockWall.EnumType[] META_LOOKUP = new BlockWall.EnumType[values().length];
private final int meta;
private final String name;
private String unlocalizedName;
private EnumType(int meta, String name, String unlocalizedName)
{
this.meta = meta;
this.name = name;
this.unlocalizedName = unlocalizedName;
}
public int getMetadata()
{
return this.meta;
}
public String toString()
{
return this.name;
}
public static BlockWall.EnumType byMetadata(int meta)
{
if (meta < 0 || meta >= META_LOOKUP.length)
{
meta = 0;
}
return META_LOOKUP[meta];
}
public String getName()
{
return this.name;
}
public String getUnlocalizedName()
{
return this.unlocalizedName;
}
static {
for (BlockWall.EnumType blockwall$enumtype : values())
{
META_LOOKUP[blockwall$enumtype.getMetadata()] = blockwall$enumtype;
}
}
}
}
| 1 | 0.792133 | 1 | 0.792133 | game-dev | MEDIA | 0.992971 | game-dev | 0.895004 | 1 | 0.895004 |
pret/pokeplatinum | 8,346 | src/map_header_data.c | #include "map_header_data.h"
#include <nitro.h>
#include <string.h>
#include "constants/heap.h"
#include "field/field_system.h"
#include "overlay006/wild_encounters.h"
#include "heap.h"
#include "map_header.h"
#include "map_object.h"
#include "narc.h"
static void MapHeaderData_LoadEvents(MapHeaderData *data, int headerID);
static void MapHeaderData_ParseEvents(MapHeaderData *data);
static void MapHeaderData_LoadInitScripts(MapHeaderData *data, int headerID);
void MapHeaderData_Init(FieldSystem *fieldSystem, enum HeapID heapID)
{
GF_ASSERT(fieldSystem->mapHeaderData == NULL);
fieldSystem->mapHeaderData = Heap_Alloc(heapID, sizeof(MapHeaderData));
}
void MapHeaderData_Free(FieldSystem *fieldSystem)
{
GF_ASSERT(fieldSystem->mapHeaderData != NULL);
Heap_Free(fieldSystem->mapHeaderData);
}
void MapHeaderData_Load(FieldSystem *fieldSystem, int headerID)
{
GF_ASSERT(fieldSystem->mapHeaderData != NULL);
MapHeaderData_LoadEvents(fieldSystem->mapHeaderData, headerID);
MapHeaderData_ParseEvents(fieldSystem->mapHeaderData);
MapHeaderData_LoadWildEncounters(&fieldSystem->mapHeaderData->wildEncounters, headerID);
MapHeaderData_LoadInitScripts(fieldSystem->mapHeaderData, headerID);
}
static void MapHeaderData_LoadEvents(MapHeaderData *data, int headerID)
{
int eventsID = MapHeader_GetEventsArchiveID(headerID);
GF_ASSERT(NARC_GetMemberSizeByIndexPair(NARC_INDEX_FIELDDATA__EVENTDATA__ZONE_EVENT, eventsID) < sizeof(data->tmpEventsBuf));
NARC_ReadWholeMemberByIndexPair(data->tmpEventsBuf, NARC_INDEX_FIELDDATA__EVENTDATA__ZONE_EVENT, eventsID);
}
void sub_0203A418(FieldSystem *fieldSystem)
{
int numObjectEvents = fieldSystem->mapHeaderData->numObjectEvents;
GF_ASSERT(fieldSystem->mapHeaderData != NULL);
if (numObjectEvents != 0) {
sub_02062068(fieldSystem->mapObjMan, fieldSystem->location->mapId, numObjectEvents, fieldSystem->mapHeaderData->objectEvents);
}
}
const BgEvent *MapHeaderData_GetBgEvents(const FieldSystem *fieldSystem)
{
return fieldSystem->mapHeaderData->bgEvents;
}
int MapHeaderData_GetNumBgEvents(const FieldSystem *fieldSystem)
{
return fieldSystem->mapHeaderData->numBgEvents;
}
const WarpEvent *MapHeaderData_GetWarpEventByIndex(const FieldSystem *fieldSystem, int index)
{
return (index >= fieldSystem->mapHeaderData->numWarpEvents)
? NULL
: &fieldSystem->mapHeaderData->warpEvents[index];
}
int MapHeaderData_GetIndexOfWarpEventAtPos(const FieldSystem *fieldSystem, int x, int z)
{
for (int i = 0; i < fieldSystem->mapHeaderData->numWarpEvents; i++) {
if (fieldSystem->mapHeaderData->warpEvents[i].x == x
&& fieldSystem->mapHeaderData->warpEvents[i].z == z) {
return i;
}
}
return -1;
}
int MapHeaderData_GetNumCoordEvents(const FieldSystem *fieldSystem)
{
return fieldSystem->mapHeaderData->numCoordEvents;
}
const CoordEvent *MapHeaderData_GetCoordEvents(const FieldSystem *fieldSystem)
{
return fieldSystem->mapHeaderData->coordEvents;
}
u32 MapHeaderData_GetNumObjectEvents(const FieldSystem *fieldSystem)
{
return fieldSystem->mapHeaderData->numObjectEvents;
}
const ObjectEvent *MapHeaderData_GetObjectEvents(const FieldSystem *fieldSystem)
{
return fieldSystem->mapHeaderData->objectEvents;
}
BOOL MapHeaderData_SetObjectEventPos(FieldSystem *fieldSystem, int localID, u16 x, u16 z)
{
int i;
ObjectEvent *objectEvent = fieldSystem->mapHeaderData->objectEvents;
u32 numObjectEvents = fieldSystem->mapHeaderData->numObjectEvents;
for (i = 0; i < numObjectEvents; i++) {
if (objectEvent[i].localID == localID) {
objectEvent[i].x = x;
objectEvent[i].z = z;
return TRUE;
}
}
GF_ASSERT(FALSE);
return FALSE;
}
BOOL MapHeaderData_SetObjectEventDir(FieldSystem *fieldSystem, int localID, int dir)
{
int i;
ObjectEvent *objectEvent = fieldSystem->mapHeaderData->objectEvents;
u32 numObjectEvents = fieldSystem->mapHeaderData->numObjectEvents;
for (i = 0; i < numObjectEvents; i++) {
if (objectEvent[i].localID == localID) {
objectEvent[i].dir = dir;
return TRUE;
}
}
GF_ASSERT(FALSE);
return FALSE;
}
BOOL MapHeaderData_SetObjectEventMovementType(FieldSystem *fieldSystem, int localID, int movementType)
{
int i;
ObjectEvent *objectEvent = fieldSystem->mapHeaderData->objectEvents;
u32 numObjectEvents = fieldSystem->mapHeaderData->numObjectEvents;
for (i = 0; i < numObjectEvents; i++) {
if (objectEvent[i].localID == localID) {
objectEvent[i].movementType = movementType;
return TRUE;
}
}
GF_ASSERT(FALSE);
return FALSE;
}
BOOL MapHeaderData_SetWarpEventPos(FieldSystem *fieldSystem, u16 index, u16 x, u16 z)
{
WarpEvent *warpEvent = fieldSystem->mapHeaderData->warpEvents;
warpEvent[index].x = x;
warpEvent[index].z = z;
return TRUE;
}
BOOL MapHeaderData_SetWarpEventDestHeaderID(FieldSystem *fieldSystem, u16 index, u16 destHeaderID)
{
WarpEvent *warpEvents = fieldSystem->mapHeaderData->warpEvents;
warpEvents[index].destHeaderID = destHeaderID;
return TRUE;
}
BOOL MapHeaderData_SetWarpEventDestWarpID(FieldSystem *fieldSystem, u16 index, u16 destWarpID)
{
WarpEvent *warpEvents = fieldSystem->mapHeaderData->warpEvents;
warpEvents[index].destWarpID = destWarpID;
return TRUE;
}
BOOL MapHeaderData_SetBgEventPos(FieldSystem *fieldSystem, u16 index, u16 x, u16 z)
{
BgEvent *bgEvent = MapHeaderData_GetBgEvents(fieldSystem);
bgEvent += index;
bgEvent->x = x;
bgEvent->z = z;
return TRUE;
}
#define CONSUME_EVENTS(T, dataTEvents, dataNumTEvents) \
do { \
(dataNumTEvents) = *(u32 *)events; \
events += sizeof(u32); \
if ((dataNumTEvents) != 0) { \
(dataTEvents) = (const T *)events; \
} else { \
(dataTEvents) = NULL; \
} \
events += sizeof(T) * (dataNumTEvents); \
} while (0)
static void MapHeaderData_ParseEvents(MapHeaderData *data)
{
const u8 *events = (const u8 *)data->tmpEventsBuf;
CONSUME_EVENTS(BgEvent, data->bgEvents, data->numBgEvents);
CONSUME_EVENTS(ObjectEvent, data->objectEvents, data->numObjectEvents);
CONSUME_EVENTS(WarpEvent, data->warpEvents, data->numWarpEvents);
CONSUME_EVENTS(CoordEvent, data->coordEvents, data->numCoordEvents);
}
void MapHeaderData_LoadWildEncounters(WildEncounters *data, int headerID)
{
memset(data, 0, sizeof(WildEncounters));
if (MapHeader_HasWildEncounters(headerID)) {
enum NarcID narcID = (GAME_VERSION == VERSION_DIAMOND || GAME_VERSION == VERSION_PLATINUM)
? NARC_INDEX_FIELDDATA__ENCOUNTDATA__PL_ENC_DATA
: NARC_INDEX_FIELDDATA__ENCOUNTDATA__P_ENC_DATA;
NARC_ReadWholeMemberByIndexPair(data, narcID, MapHeader_GetWildEncountersArchiveID(headerID));
}
}
const WildEncounters *MapHeaderData_GetWildEncounters(const FieldSystem *fieldSystem)
{
return &fieldSystem->mapHeaderData->wildEncounters;
}
static void MapHeaderData_LoadInitScripts(MapHeaderData *data, int headerID)
{
int initScriptsID = MapHeader_GetInitScriptsArchiveID(headerID);
MI_CpuClearFast(data->initScripts, sizeof(data->initScripts));
GF_ASSERT(NARC_GetMemberSizeByIndexPair(NARC_INDEX_FIELDDATA__SCRIPT__SCR_SEQ, initScriptsID) < sizeof(data->initScripts));
NARC_ReadWholeMemberByIndexPair(data->initScripts, NARC_INDEX_FIELDDATA__SCRIPT__SCR_SEQ, initScriptsID);
}
const u8 *MapHeaderData_GetInitScriptBytes(const FieldSystem *fieldSystem)
{
GF_ASSERT(fieldSystem->mapHeaderData != NULL);
return (const u8 *)&fieldSystem->mapHeaderData->initScripts;
}
BOOL MapHeaderData_IsAnyObjectEventAtPos(const FieldSystem *fieldSystem, u16 x, u16 z)
{
const MapHeaderData *data = fieldSystem->mapHeaderData;
for (u32 i = 0; i < data->numObjectEvents; i++) {
if (data->objectEvents[i].x == x && data->objectEvents[i].z == z) {
return FALSE;
}
}
return TRUE;
}
| 1 | 0.776982 | 1 | 0.776982 | game-dev | MEDIA | 0.884886 | game-dev | 0.717688 | 1 | 0.717688 |
lunar-sway/minestuck | 3,982 | src/main/java/com/mraof/minestuck/block/redstone/RedstoneClockBlock.java | package com.mraof.minestuck.block.redstone;
import com.mraof.minestuck.block.BlockUtil;
import com.mraof.minestuck.block.MSDirectionalBlock;
import com.mraof.minestuck.blockentity.MSBlockEntityTypes;
import com.mraof.minestuck.blockentity.redstone.RedstoneClockBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.particles.DustParticleOptions;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.RandomSource;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityTicker;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.phys.BlockHitResult;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* Generates a redstone pulse through its block entity at a modifiable increment. Used as a compact means of creating redstone clocks
*/
@ParametersAreNonnullByDefault
public class RedstoneClockBlock extends MSDirectionalBlock implements EntityBlock
{
public static final BooleanProperty POWERED = BlockStateProperties.POWERED;
public RedstoneClockBlock(Properties properties)
{
super(properties);
registerDefaultState(stateDefinition.any().setValue(POWERED, false));
}
@Override
protected InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hit)
{
if(level.getBlockEntity(pos) instanceof RedstoneClockBlockEntity be) //does not check for creative shock to anticipate use cases in timing puzzle designs
{
if(!player.isCrouching())
{
be.incrementClockSpeed(player);
return InteractionResult.SUCCESS;
} else
{
be.decrementClockSpeed(player);
return InteractionResult.SUCCESS;
}
}
return InteractionResult.PASS;
}
@Override
protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource rand)
{
super.tick(state, level, pos, rand);
if(state.getValue(POWERED))
{
level.setBlock(pos, state.setValue(POWERED, false), Block.UPDATE_ALL_IMMEDIATE);
}
}
@Override
protected boolean isSignalSource(BlockState state)
{
return state.getValue(POWERED);
}
@Override
protected int getSignal(BlockState blockState, BlockGetter level, BlockPos pos, Direction side)
{
return blockState.getValue(POWERED) ? 15 : 0;
}
@Override
public boolean canConnectRedstone(BlockState state, BlockGetter level, BlockPos pos, @Nullable Direction side)
{
return true;
}
@Nullable
@Override
public BlockEntity newBlockEntity(BlockPos pos, BlockState state)
{
return new RedstoneClockBlockEntity(pos, state);
}
@Nullable
@Override
public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, BlockState state, BlockEntityType<T> placedType)
{
return !level.isClientSide ? BlockUtil.checkTypeForTicker(placedType, MSBlockEntityTypes.REDSTONE_CLOCK.get(), RedstoneClockBlockEntity::serverTick) : null;
}
@Override
public void animateTick(BlockState stateIn, Level level, BlockPos pos, RandomSource rand)
{
if(stateIn.getValue(POWERED))
BlockUtil.spawnParticlesAroundSolidBlock(level, pos, () -> DustParticleOptions.REDSTONE);
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder)
{
super.createBlockStateDefinition(builder);
builder.add(POWERED);
}
}
| 1 | 0.836575 | 1 | 0.836575 | game-dev | MEDIA | 0.999514 | game-dev | 0.916981 | 1 | 0.916981 |
DiligentPanda/Scalable-Imitation-Learning-for-LMAPF | 16,621 | light_malib/envs/gr_football/encoders/encoder_enhanced_LessActionMask.py | # Copyright 2022 Digital Brain Laboratory, Yan Song and He jiang
# 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.
"""
Our Feature Encoder code is adapated from wekick and liveinparis in the kaggle football competition.
basic_enhanced_11 outputs 217+107-dimension features and has less action masking,
used as an extended FE for 11v11 full-game scenarios
"""
from typing import OrderedDict
import numpy as np
from light_malib.utils.logger import Logger
from gym.spaces import Box, Discrete
class FeatureEncoder:
def __init__(self, **kwargs):
self.active = -1
self.player_pos_x, self.player_pos_y = 0, 0
self.action_n = 19
self.use_action_gramma = False
self.num_players = kwargs['num_players'] # the total number of players on the pitch
def encode(self, states):
feats = []
for state in states:
feat = self.encode_each(state)
feats.append(feat)
return feats
@property
def global_observation_space(self):
return self.observation_space
@property
def observation_space(self):
return Box(low=-1000, high=1000, shape=[((self.num_players-1)*7+70) + (self.num_players*4-1+20)])
@property
def action_space(self):
return Discrete(19)
def encode_each(self, state):
obs = state.obs
his_actions = state.action_list
player_num = obs["active"]
player_pos_x, player_pos_y = obs["left_team"][player_num]
player_direction = np.array(obs["left_team_direction"][player_num])
player_speed = np.linalg.norm(player_direction)
player_role = obs["left_team_roles"][player_num]
player_role_onehot = self._encode_role_onehot(player_role)
player_tired = obs["left_team_tired_factor"][player_num]
is_dribbling = obs["sticky_actions"][9]
is_sprinting = obs["sticky_actions"][8]
ball_x, ball_y, ball_z = obs["ball"]
ball_x_relative = ball_x - player_pos_x
ball_y_relative = ball_y - player_pos_y
ball_x_speed, ball_y_speed, _ = obs["ball_direction"]
ball_distance = np.linalg.norm([ball_x_relative, ball_y_relative])
ball_speed = np.linalg.norm([ball_x_speed, ball_y_speed])
ball_owned = 0.0
if obs["ball_owned_team"] == -1:
ball_owned = 0.0
else:
ball_owned = 1.0
ball_owned_by_us = 0.0
if obs["ball_owned_team"] == 0:
ball_owned_by_us = 1.0
elif obs["ball_owned_team"] == 1:
ball_owned_by_us = 0.0
else:
ball_owned_by_us = 0.0
ball_which_zone = self._encode_ball_which_zone(ball_x, ball_y)
if ball_distance > 0.03:
ball_far = 1.0
else:
ball_far = 0.0
avail = self.get_available_actions(obs, ball_distance, his_actions)
player_state = np.concatenate( # 19
(
# avail[2:],
obs["left_team"][player_num], # 2
player_direction * 100, # 2
[player_speed * 100], # 1
player_role_onehot, # 10
[ball_far, player_tired, is_dribbling, is_sprinting], # 4
)
)
ball_state = np.concatenate( # 18
(
np.array(obs["ball"]), # 3
np.array(ball_which_zone), # 6
np.array([ball_x_relative, ball_y_relative]), # 2
np.array(obs["ball_direction"]) * 20, # 3
np.array(
[ball_speed * 20, ball_distance, ball_owned, ball_owned_by_us] # 4
),
)
)
obs_left_team = np.delete(obs["left_team"], player_num, axis=0)
obs_left_team_direction = np.delete(
obs["left_team_direction"], player_num, axis=0
)
left_team_relative = obs_left_team
left_team_distance = np.linalg.norm(
left_team_relative - obs["left_team"][player_num], axis=1, keepdims=True
)
left_team_speed = np.linalg.norm(obs_left_team_direction, axis=1, keepdims=True)
left_team_tired = np.delete(
obs["left_team_tired_factor"], player_num, axis=0
).reshape(-1, 1)
left_team_state = np.concatenate( # 7*(num_left_players-1), remove himself
(
left_team_relative * 2, # 2
obs_left_team_direction * 100, # 2
left_team_speed * 100, # 1
left_team_distance * 2, # 1
left_team_tired, # 1
),
axis=1,
)
left_closest_idx = np.argmin(left_team_distance)
left_closest_state = left_team_state[left_closest_idx]
obs_right_team = np.array(obs["right_team"])
obs_right_team_direction = np.array(obs["right_team_direction"])
right_team_distance = np.linalg.norm(
obs_right_team - obs["left_team"][player_num], axis=1, keepdims=True
)
right_team_speed = np.linalg.norm(
obs_right_team_direction, axis=1, keepdims=True
)
right_team_tired = np.array(obs["right_team_tired_factor"]).reshape(-1, 1)
right_team_state = np.concatenate( # 7*num_right_players
(
obs_right_team * 2,
obs_right_team_direction * 100,
right_team_speed * 100,
right_team_distance * 2,
right_team_tired,
),
axis=1,
)
right_closest_idx = np.argmin(right_team_distance)
right_closest_state = right_team_state[right_closest_idx]
steps_left = obs["steps_left"] # steps left till end
half_steps_left = steps_left
if half_steps_left > 1500:
half_steps_left -= 1501 # steps left till halfend
half_steps_left = 1.0 * min(half_steps_left, 300.0) # clip
half_steps_left /= 300.0
score_ratio = obs["score"][0] - obs["score"][1]
score_ratio /= 5.0
score_ratio = min(score_ratio, 1.0)
score_ratio = max(-1.0, score_ratio)
game_mode = np.zeros(7, dtype=np.float32)
game_mode[obs["game_mode"]] = 1
match_state = np.concatenate( # 10
(
np.array([1.0 * steps_left / 3001, half_steps_left, score_ratio]),
game_mode,
)
)
# offside
l_o, r_o = state.get_offside(obs)
offside = np.concatenate((l_o, r_o))
# card
card = np.concatenate(
(
obs["left_team_yellow_card"],
obs["left_team_active"],
obs["right_team_yellow_card"],
obs["right_team_active"],
)
)
# sticky_action
sticky_action = obs["sticky_actions"]
# ball_distance
left_team_distance = np.linalg.norm(
obs_left_team - obs["ball"][:2], axis=1, keepdims=False
)
right_team_distance = np.linalg.norm(
obs_right_team - obs["ball"][:2], axis=1, keepdims=False
)
ball_distance = np.concatenate((left_team_distance, right_team_distance))
state_dict = OrderedDict(
{
"avail": avail, # 19
"ball": ball_state, # 18
"left_closest": left_closest_state, # 7
"left_team": left_team_state, # 7*(num_left_players-1)
"player": player_state, # 19
"right_closest": right_closest_state, # 7
"right_team": right_team_state, # 7*num_right_players
"match_state": match_state, # 10
"offside": offside, # num_player
"card": card, # num_players*2
"sticky_action": sticky_action, # 10
"ball_distance": ball_distance, # num_players-1
}
)
feats = np.hstack(
[np.array(state_dict[k], dtype=np.float32).flatten() for k in (state_dict)]
)
return feats
def _get_avail(self, obs, ball_distance):
avail = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
(
NO_OP,
MOVE,
LONG_PASS,
HIGH_PASS,
SHORT_PASS,
SHOT,
SPRINT,
RELEASE_MOVE,
RELEASE_SPRINT,
SLIDE,
DRIBBLE,
RELEASE_DRIBBLE,
) = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
if obs["ball_owned_team"] == 1: # opponents owning ball
(
avail[LONG_PASS],
avail[HIGH_PASS],
avail[SHORT_PASS],
avail[SHOT],
avail[DRIBBLE],
) = (0, 0, 0, 0, 0)
elif (
obs["ball_owned_team"] == -1
and ball_distance > 0.03
and obs["game_mode"] == 0
): # Ground ball and far from me
(
avail[LONG_PASS],
avail[HIGH_PASS],
avail[SHORT_PASS],
avail[SHOT],
avail[DRIBBLE],
) = (0, 0, 0, 0, 0)
else: # my team owning ball
avail[SLIDE] = 0
# Dealing with sticky actions
sticky_actions = obs["sticky_actions"]
if sticky_actions[8] == 0: # sprinting
avail[RELEASE_SPRINT] = 0
if sticky_actions[9] == 1: # dribbling
avail[SLIDE] = 0
else:
avail[RELEASE_DRIBBLE] = 0
if np.sum(sticky_actions[:8]) == 0:
avail[RELEASE_MOVE] = 0
# if too far, no shot
ball_x, ball_y, _ = obs["ball"]
if ball_x < 0.64 or ball_y < -0.27 or 0.27 < ball_y:
avail[SHOT] = 0
elif (0.64 <= ball_x and ball_x <= 1.0) and (
-0.27 <= ball_y and ball_y <= 0.27
):
avail[HIGH_PASS], avail[LONG_PASS] = 0, 0
if obs["game_mode"] == 2 and ball_x < -0.7: # Our GoalKick
avail = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
avail[LONG_PASS], avail[HIGH_PASS], avail[SHORT_PASS] = 1, 1, 1
return np.array(avail)
elif obs["game_mode"] == 4 and ball_x > 0.9: # Our CornerKick
avail = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
avail[LONG_PASS], avail[HIGH_PASS], avail[SHORT_PASS] = 1, 1, 1
return np.array(avail)
elif obs["game_mode"] == 6 and ball_x > 0.6: # Our PenaltyKick
avail = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
avail[SHOT] = 1
return np.array(avail)
return np.array(avail)
def _get_avail_new(self, obs, ball_distance, action_n):
assert action_n == 19 or action_n == 20 # we dont support full action set
avail = [1] * action_n
(
NO_OP,
LEFT,
TOP_LEFT,
TOP,
TOP_RIGHT,
RIGHT,
BOTTOM_RIGHT,
BOTTOM,
BOTTOM_LEFT,
LONG_PASS,
HIGH_PASS,
SHORT_PASS,
SHOT,
SPRINT,
RELEASE_MOVE,
RELEASE_SPRINT,
SLIDE,
DRIBBLE,
RELEASE_DRIBBLE,
) = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
if action_n == 20:
BUILTIN_AI = 19
if obs["ball_owned_team"] == 1: # opponents owning ball
pass
elif obs["ball_owned_team"] == 0:
# my team owning ball
avail[SLIDE] = 0
# if too far, no shot
ball_x, ball_y, _ = obs["ball"]
if obs["game_mode"] == 6 and ball_x > 0.6: # Our PenaltyKick
# avail = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
avail = [1] + [0] * (action_n - 1)
avail[SHOT] = 1
return np.array(avail)
return np.array(avail)
def _encode_ball_which_zone(self, ball_x, ball_y):
MIDDLE_X, PENALTY_X, END_X = 0.2, 0.64, 1.0
PENALTY_Y, END_Y = 0.27, 0.42
if (-END_X <= ball_x and ball_x < -PENALTY_X) and (
-PENALTY_Y < ball_y and ball_y < PENALTY_Y
):
return [1.0, 0, 0, 0, 0, 0]
elif (-END_X <= ball_x and ball_x < -MIDDLE_X) and (
-END_Y < ball_y and ball_y < END_Y
):
return [0, 1.0, 0, 0, 0, 0]
elif (-MIDDLE_X <= ball_x and ball_x <= MIDDLE_X) and (
-END_Y < ball_y and ball_y < END_Y
):
return [0, 0, 1.0, 0, 0, 0]
elif (PENALTY_X < ball_x and ball_x <= END_X) and (
-PENALTY_Y < ball_y and ball_y < PENALTY_Y
):
return [0, 0, 0, 1.0, 0, 0]
elif (MIDDLE_X < ball_x and ball_x <= END_X) and (
-END_Y < ball_y and ball_y < END_Y
):
return [0, 0, 0, 0, 1.0, 0]
else:
return [0, 0, 0, 0, 0, 1.0]
def _encode_role_onehot(self, role_num):
result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
result[role_num] = 1.0
return np.array(result)
def _get_available_actions_gramma(self, his_actions, action_n):
(
NO_OP,
LEFT,
TOP_LEFT,
TOP,
TOP_RIGHT,
RIGHT,
BOTTOM_RIGHT,
BOTTOM,
BOTTOM_LEFT,
LONG_PASS,
HIGH_PASS,
SHORT_PASS,
SHOT,
SPRINT,
RELEASE_MOVE,
RELEASE_SPRINT,
SLIDE,
DRIBBLE,
RELEASE_DRIBBLE,
) = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
avail = np.zeros(action_n)
avail[13:] = 1
directions = [
LEFT,
TOP_LEFT,
TOP,
TOP_RIGHT,
RIGHT,
BOTTOM_RIGHT,
BOTTOM_LEFT,
BOTTOM,
]
if len(his_actions) == 0:
self.set_on(avail, directions)
else:
last_action = his_actions[-1]
# directions
if last_action in directions:
self.set_on(
avail, self._get_smooth_directions(his_actions) + [RELEASE_MOVE]
)
elif last_action in [LONG_PASS, SHOT, HIGH_PASS, SHORT_PASS, SLIDE]:
self.set_on(avail, directions + [last_action])
# we regard release move as an end of a series of commands
else:
avail = np.ones(action_n)
avail[0] = 0
ret = np.array(avail)
return ret
def get_available_actions(self, obs, ball_distance, his_actions):
# todo further restrict it by automata
avail1 = self._get_avail_new(obs, ball_distance, self.action_n)
if self.use_action_gramma:
avail2 = self._get_available_actions_gramma(his_actions, self.action_n)
avail = np.minimum(avail1, avail2)
if np.sum(avail) == 0:
# logger.warn("no available actions!")
avail = avail1
else:
avail = avail1
return avail
def set_on(self, avail, args):
avail[args] = 1
def set_off(self, avail, args):
avail[args] = 0
def _get_smooth_directions(self, his_actions):
(
NO_OP,
LEFT,
TOP_LEFT,
TOP,
TOP_RIGHT,
RIGHT,
BOTTOM_RIGHT,
BOTTOM,
BOTTOM_LEFT,
LONG_PASS,
HIGH_PASS,
SHORT_PASS,
SHOT,
SPRINT,
RELEASE_MOVE,
RELEASE_SPRINT,
SLIDE,
DRIBBLE,
RELEASE_DRIBBLE,
) = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
last_action = his_actions[-1]
# last2_action=his_actions[-2]
assert last_action >= 1 and last_action <= 8
# thenext direction is allow to be 90 degrees away,totally 5 actions
s = (last_action + 5) % 8
avail_ids = np.arange(s, s + 5) % 8 + 1
return list(avail_ids)
| 1 | 0.752993 | 1 | 0.752993 | game-dev | MEDIA | 0.698061 | game-dev,ml-ai | 0.802153 | 1 | 0.802153 |
KhronosGroup/WebGL | 3,169 | conformance-suites/1.0.2/conformance/ogles/GL/functions/ivec4_empty_inout_ivec4_bigarray_vert.vert |
/*
** Copyright (c) 2012 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are 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 Materials.
**
** THE MATERIALS ARE 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
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
attribute vec4 gtf_Vertex;
uniform mat4 gtf_ModelViewProjectionMatrix;
varying vec4 color;
// Function declarations.
ivec4 function(inout ivec4 par[10]);
bool is_all(const in ivec4 par, const in int value);
bool is_all(const in ivec4 array[10], const in ivec4 value);
void set_all(out ivec4 array[10], const in ivec4 value);
void main (void)
{
ivec4 par[10];
ivec4 ret = ivec4(0, 0, 0, 0);
float gray = 0.0;
// Initialize the entire array to 1.
set_all(par, ivec4(1, 1, 1, 1));
ret = function(par);
// The parameter should be changed by the function and the function should return 1.
if(is_all(par, ivec4(0, 0, 0, 0)) && is_all(ret, 1))
{
gray = 1.0;
}
color = vec4(gray, gray, gray, 1.0);
gl_Position = gtf_ModelViewProjectionMatrix * gtf_Vertex;
}
// Function definitions.
ivec4 function(inout ivec4 par[10])
{
// Return the value of the array.
if(is_all(par, ivec4(1, 1, 1, 1)))
{
// Test parameter qualifier (default is "in").
set_all(par, ivec4(0, 0, 0, 0));
return ivec4(1, 1, 1, 1);
}
else
return ivec4(0, 0, 0, 0);
}
bool is_all(const in ivec4 par, const in int value)
{
bool ret = true;
if(par[0] != value)
ret = false;
if(par[1] != value)
ret = false;
if(par[2] != value)
ret = false;
if(par[3] != value)
ret = false;
return ret;
}
bool is_all(const in ivec4 array[10], const in ivec4 value)
{
bool ret = true;
if(array[0] != value)
ret = false;
if(array[1] != value)
ret = false;
if(array[2] != value)
ret = false;
if(array[3] != value)
ret = false;
if(array[4] != value)
ret = false;
if(array[5] != value)
ret = false;
if(array[6] != value)
ret = false;
if(array[7] != value)
ret = false;
if(array[8] != value)
ret = false;
if(array[9] != value)
ret = false;
return ret;
}
void set_all(out ivec4 array[10], const in ivec4 value)
{
array[0] = value;
array[1] = value;
array[2] = value;
array[3] = value;
array[4] = value;
array[5] = value;
array[6] = value;
array[7] = value;
array[8] = value;
array[9] = value;
}
| 1 | 0.715939 | 1 | 0.715939 | game-dev | MEDIA | 0.539889 | game-dev | 0.882223 | 1 | 0.882223 |
HuasoFoundries/jpgraph | 1,502 | src/graph/RectPatternFactory.php | <?php
/**
* JPGraph v4.0.3
*/
namespace Amenadiel\JpGraph\Graph;
use Amenadiel\JpGraph\Util;
/**
* @class RectPatternFactory
* // Factory class for rectangular pattern
*/
class RectPatternFactory
{
public function __construct()
{
// Empty
}
public function Create($aPattern, $aColor, $aWeight = 1)
{
switch ($aPattern) {
case BAND_RDIAG:
$obj = new RectPatternRDiag($aColor, $aWeight);
break;
case BAND_LDIAG:
$obj = new RectPatternLDiag($aColor, $aWeight);
break;
case BAND_SOLID:
$obj = new RectPatternSolid($aColor, $aWeight);
break;
case BAND_VLINE:
$obj = new RectPatternVert($aColor, $aWeight);
break;
case BAND_HLINE:
$obj = new RectPatternHor($aColor, $aWeight);
break;
case BAND_3DPLANE:
$obj = new RectPattern3DPlane($aColor, $aWeight);
break;
case BAND_HVCROSS:
$obj = new RectPatternCross($aColor, $aWeight);
break;
case BAND_DIAGCROSS:
$obj = new RectPatternDiagCross($aColor, $aWeight);
break;
default:
Util\JpGraphError::RaiseL(16003, $aPattern);
//(" Unknown pattern specification ($aPattern)");
}
return $obj;
}
}
| 1 | 0.787426 | 1 | 0.787426 | game-dev | MEDIA | 0.268175 | game-dev | 0.894004 | 1 | 0.894004 |
SimFlowCFD/RapidCFD-dev | 1,705 | src/sixDoFRigidBodyMotion/Make/files | sixDoFRigidBodyMotion/sixDoFRigidBodyMotion.C
sixDoFRigidBodyMotion/sixDoFRigidBodyMotionIO.C
sixDoFRigidBodyMotion/sixDoFRigidBodyMotionState.C
sixDoFRigidBodyMotion/sixDoFRigidBodyMotionStateIO.C
restraints = sixDoFRigidBodyMotion/restraints
$(restraints)/sixDoFRigidBodyMotionRestraint/sixDoFRigidBodyMotionRestraint.C
$(restraints)/sixDoFRigidBodyMotionRestraint/sixDoFRigidBodyMotionRestraintNew.C
$(restraints)/linearAxialAngularSpring/linearAxialAngularSpring.C
$(restraints)/linearSpring/linearSpring.C
$(restraints)/sphericalAngularSpring/sphericalAngularSpring.C
$(restraints)/tabulatedAxialAngularSpring/tabulatedAxialAngularSpring.C
$(restraints)/linearDamper/linearDamper.C
$(restraints)/sphericalAngularDamper/sphericalAngularDamper.C
constraints = sixDoFRigidBodyMotion/constraints
$(constraints)/sixDoFRigidBodyMotionConstraint/sixDoFRigidBodyMotionConstraint.C
$(constraints)/sixDoFRigidBodyMotionConstraint/sixDoFRigidBodyMotionConstraintNew.C
$(constraints)/axis/sixDoFRigidBodyMotionAxisConstraint.C
$(constraints)/line/sixDoFRigidBodyMotionLineConstraint.C
$(constraints)/orientation/sixDoFRigidBodyMotionOrientationConstraint.C
$(constraints)/plane/sixDoFRigidBodyMotionPlaneConstraint.C
$(constraints)/point/sixDoFRigidBodyMotionPointConstraint.C
pointPatchFields/derived/sixDoFRigidBodyDisplacement/sixDoFRigidBodyDisplacementPointPatchVectorField.C
pointPatchFields/derived/uncoupledSixDoFRigidBodyDisplacement/uncoupledSixDoFRigidBodyDisplacementPointPatchVectorField.C
sixDoFRigidBodyMotionSolver/sixDoFRigidBodyMotionSolver.C
sixDoFRigidBodyMotionSolver/externalPointEdgePoint.C
sixDoFRigidBodyMotionSolver/pointPatchDist.C
LIB = $(FOAM_LIBBIN)/libsixDoFRigidBodyMotion
| 1 | 0.541133 | 1 | 0.541133 | game-dev | MEDIA | 0.811202 | game-dev | 0.60014 | 1 | 0.60014 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.